diff --git a/.gitattributes b/.gitattributes index bd937856fa9dd7d44575fa06fb2ffc0573f3943f..7d2f07abac71e4f1cbaf44fbe4f47972019e255c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -573,3 +573,37 @@ shared/package-files/72/72f5b59eddc1e471739db67ab9fb91f2a93df5d12ce5235771371b60 shared/package-files/73/73e4d5ccbe1a229ce1a36bbc0398ca8c8d92f2450db637461b460c18b5dbc4de/blob filter=lfs diff=lfs merge=lfs -text shared/package-files/73/73fb6a31adbe9e0b4d63cf0981fbfbc7ce53b030751cf47d123c34f9f936d787/blob filter=lfs diff=lfs merge=lfs -text shared/package-files/74/744d1b57418c2f4d5351de3fc3a654b6c9c06ccd74eb16a27b808b822e6b34ca/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/75/759a552a2ef7efc110201509d3693a34f7055169e41fa28891aeb663336ede38/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/75/75e8d14d1843091a6a1952efb4c03b088095d2ade1ea6db7f8105701f306e424/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/75/75f9c2b09cbeb44939fe0ef0bf12aeb0143cd656f75e150627f979909589c6da/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/76/76a1c1c820477c5eab8f7d4c3504be8f2266a444c5e3b7bb050cd18d25b52d98/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/77/771baa4e2d41cbfb53d6e4f1cff3974b97e11bdad3f067eff43afe4b1f201469/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/77/77494c45d9a5437d3d4e1ddaf782ea955ff8dc12777a964f61ca0b08f7d62edf/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/77/7772e1b01ca6bc9bef27435aa768bd090aeb51c6eee183081721a914ca4b02e5/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/77/77a17fc6bf0f558cd4e2a31c9e8bf19ce6f00b928e647c9da5f0478c67f89dc5/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/784965b9a19f5fd63aae3136a143878d8ffce04d5b2815e08aca379dcd9f59c8/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/785c212f079c6f7bdff9b4ee1bda32c651da9e459bbf4de075a403f24191027a/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/786f29b88771e439187dd2e86ad4d255dd185e0c1ea3f8c37d21770fd1df253a/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/78c9747bc2db92f47ee2775ee64ba4cd7c8d6875c04132782201f543c355ad90/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/78cce4f3057535eeba51cfb543a88add149d42729036c36fd07e04065aeac9c6/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/78e0f83db78dcf4ea14887e915a408af08d9d9a351f2542f29a5d222b9284efe/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/78/78eea04a7cf86787b8612187b4b17d96d27ab0ba91d08c17a96274ec7a5fc37e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/7903c2ea80bd412cc0d6701c38f645063a2f77a502cb7b1c5d9ee9d6ef38e4df/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/7950309e6824e0e2df93ddcfdf7222ef6c6f4d125a8a6fb548e852ddb4ce2723/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/7967dcd2f6620ec18ccf458d87780b19c54f2090bd72ea1d32164b8371483666/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/79881ac42d4a6d3b732d50014e2e6866cee437387bb5177bbf47e7d4e336ea35/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/79a56868a10be9477478422598c81e6a7ab62003adffe1ff07674bf655a08bd2/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/79ab3b3a83c989c9d106b98ecf98acb0f6f254535ca75ac54c298f56b55672c1/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/79ac63ae025a874200da2cb0523344e88fe7b984bace79b7dce55fdbe688d5fa/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/79/79e2b33fec758c92063be4422c83fe56ce565389c26c2111defe0815ee2dd254/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7a/7a20c7231ab9446379bf4a8abab27edcc2155734357d4d88e7861c15d9693c01/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7a/7a7c6052968247f06e135e7a59ea2a89823b59fc41215a371f5269af5668f746/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7a/7ad6709bd4713ec24e958368560e08f7ea6bb312967834a9d6f52641d7b4979b/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7b/7b2d3852e9d9a74b13cfd852b138456368a3533ad9711a82e99d2a4454af30a2/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7b/7bccf225b12b5d9679f77ec191715f9d547a985eeed0c6287867b9ad1957b292/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7c/7c0f114b23205230865dbb7c51a67c17cca2566119ff2c9ad0a7c687e03319bb/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7c/7c1459904e57697fddd21e7fa2f52cb9a157eca6609afc58efde3a4614b47517/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/7c/7c3d5a1bd3cf76695ccc50d4a89c7b9ef7e881fb0cf87fa9c91a6750cea7f973/blob filter=lfs diff=lfs merge=lfs -text diff --git a/shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/blob b/shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/blob new file mode 100644 index 0000000000000000000000000000000000000000..08d518b151425f85458727fbf69f6e601f12be86 Binary files /dev/null and b/shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/blob differ diff --git a/shared/package-files/74/74d0eaa56b246fa61ee453baacdbeae21f74fb5f5f0dcbd7f482d0e2a99002c3/blob b/shared/package-files/74/74d0eaa56b246fa61ee453baacdbeae21f74fb5f5f0dcbd7f482d0e2a99002c3/blob new file mode 100644 index 0000000000000000000000000000000000000000..0eed3cd85270097ec1b58d53fa59b874b3d52c49 --- /dev/null +++ b/shared/package-files/74/74d0eaa56b246fa61ee453baacdbeae21f74fb5f5f0dcbd7f482d0e2a99002c3/blob @@ -0,0 +1,2390 @@ +# mypy: ignore-errors + +""" +Utility function to facilitate testing. + +""" +import contextlib +import gc +import operator +import os +import platform +import pprint +import re +import shutil +import sys +import warnings +from functools import wraps +from io import StringIO +from tempfile import mkdtemp, mkstemp +from warnings import WarningMessage + +import torch._numpy as np +from torch._numpy import arange, asarray as asanyarray, empty, float32, intp, ndarray + +__all__ = [ + "assert_equal", + "assert_almost_equal", + "assert_approx_equal", + "assert_array_equal", + "assert_array_less", + "assert_string_equal", + "assert_", + "assert_array_almost_equal", + "build_err_msg", + "decorate_methods", + "print_assert_equal", + "verbose", + "assert_", + "assert_array_almost_equal_nulp", + "assert_raises_regex", + "assert_array_max_ulp", + "assert_warns", + "assert_no_warnings", + "assert_allclose", + "IgnoreException", + "clear_and_catch_warnings", + "temppath", + "tempdir", + "IS_PYPY", + "HAS_REFCOUNT", + "IS_WASM", + "suppress_warnings", + "assert_array_compare", + "assert_no_gc_cycles", + "break_cycles", + "IS_PYSTON", +] + + +verbose = 0 + +IS_WASM = platform.machine() in ["wasm32", "wasm64"] +IS_PYPY = sys.implementation.name == "pypy" +IS_PYSTON = hasattr(sys, "pyston_version_info") +HAS_REFCOUNT = getattr(sys, "getrefcount", None) is not None and not IS_PYSTON + + +def assert_(val, msg=""): + """ + Assert that works in release mode. + Accepts callable msg to allow deferring evaluation until failure. + + The Python built-in ``assert`` does not work when executing code in + optimized mode (the ``-O`` flag) - no byte-code is generated for it. + + For documentation on usage, refer to the Python documentation. + + """ + __tracebackhide__ = True # Hide traceback for py.test + if not val: + try: + smsg = msg() + except TypeError: + smsg = msg + raise AssertionError(smsg) + + +def gisnan(x): + return np.isnan(x) + + +def gisfinite(x): + return np.isfinite(x) + + +def gisinf(x): + return np.isinf(x) + + +def build_err_msg( + arrays, + err_msg, + header="Items are not equal:", + verbose=True, + names=("ACTUAL", "DESIRED"), + precision=8, +): + msg = ["\n" + header] + if err_msg: + if err_msg.find("\n") == -1 and len(err_msg) < 79 - len(header): + msg = [msg[0] + " " + err_msg] + else: + msg.append(err_msg) + if verbose: + for i, a in enumerate(arrays): + if isinstance(a, ndarray): + # precision argument is only needed if the objects are ndarrays + # r_func = partial(array_repr, precision=precision) + r_func = ndarray.__repr__ + else: + r_func = repr + + try: + r = r_func(a) + except Exception as exc: + r = f"[repr failed for <{type(a).__name__}>: {exc}]" + if r.count("\n") > 3: + r = "\n".join(r.splitlines()[:3]) + r += "..." + msg.append(f" {names[i]}: {r}") + return "\n".join(msg) + + +def assert_equal(actual, desired, err_msg="", verbose=True): + """ + Raises an AssertionError if two objects are not equal. + + Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), + check that all elements of these objects are equal. An exception is raised + at the first conflicting values. + + When one of `actual` and `desired` is a scalar and the other is array_like, + the function checks that each element of the array_like object is equal to + the scalar. + + This function handles NaN comparisons as if NaN was a "normal" number. + That is, AssertionError is not raised if both objects have NaNs in the same + positions. This is in contrast to the IEEE standard on NaNs, which says + that NaN compared to anything must return False. + + Parameters + ---------- + actual : array_like + The object to check. + desired : array_like + The expected object. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal. + + Examples + -------- + >>> np.testing.assert_equal([4,5], [4,6]) + Traceback (most recent call last): + ... + AssertionError: + Items are not equal: + item=1 + ACTUAL: 5 + DESIRED: 6 + + The following comparison does not raise an exception. There are NaNs + in the inputs, but they are in the same positions. + + >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan]) + + """ + __tracebackhide__ = True # Hide traceback for py.test + + num_nones = sum([actual is None, desired is None]) + if num_nones == 1: + raise AssertionError(f"Not equal: {actual} != {desired}") + elif num_nones == 2: + return True + # else, carry on + + if isinstance(actual, np.DType) or isinstance(desired, np.DType): + result = actual == desired + if not result: + raise AssertionError(f"Not equal: {actual} != {desired}") + else: + return True + + if isinstance(desired, str) and isinstance(actual, str): + assert actual == desired + return + + if isinstance(desired, dict): + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) + assert_equal(len(actual), len(desired), err_msg, verbose) + for k in desired.keys(): + if k not in actual: + raise AssertionError(repr(k)) + assert_equal(actual[k], desired[k], f"key={k!r}\n{err_msg}", verbose) + return + if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): + assert_equal(len(actual), len(desired), err_msg, verbose) + for k in range(len(desired)): + assert_equal(actual[k], desired[k], f"item={k!r}\n{err_msg}", verbose) + return + + from torch._numpy import imag, iscomplexobj, isscalar, ndarray, real, signbit + + if isinstance(actual, ndarray) or isinstance(desired, ndarray): + return assert_array_equal(actual, desired, err_msg, verbose) + msg = build_err_msg([actual, desired], err_msg, verbose=verbose) + + # Handle complex numbers: separate into real/imag to handle + # nan/inf/negative zero correctly + # XXX: catch ValueError for subclasses of ndarray where iscomplex fail + try: + usecomplex = iscomplexobj(actual) or iscomplexobj(desired) + except (ValueError, TypeError): + usecomplex = False + + if usecomplex: + if iscomplexobj(actual): + actualr = real(actual) + actuali = imag(actual) + else: + actualr = actual + actuali = 0 + if iscomplexobj(desired): + desiredr = real(desired) + desiredi = imag(desired) + else: + desiredr = desired + desiredi = 0 + try: + assert_equal(actualr, desiredr) + assert_equal(actuali, desiredi) + except AssertionError: + raise AssertionError(msg) # noqa: TRY200 + + # isscalar test to check cases such as [np.nan] != np.nan + if isscalar(desired) != isscalar(actual): + raise AssertionError(msg) + + # Inf/nan/negative zero handling + try: + isdesnan = gisnan(desired) + isactnan = gisnan(actual) + if isdesnan and isactnan: + return # both nan, so equal + + # handle signed zero specially for floats + array_actual = np.asarray(actual) + array_desired = np.asarray(desired) + + if desired == 0 and actual == 0: + if not signbit(desired) == signbit(actual): + raise AssertionError(msg) + + except (TypeError, ValueError, NotImplementedError): + pass + + try: + # Explicitly use __eq__ for comparison, gh-2552 + if not (desired == actual): + raise AssertionError(msg) + + except (DeprecationWarning, FutureWarning) as e: + # this handles the case when the two types are not even comparable + if "elementwise == comparison" in e.args[0]: + raise AssertionError(msg) # noqa: TRY200 + else: + raise + + +def print_assert_equal(test_string, actual, desired): + """ + Test if two objects are equal, and print an error message if test fails. + + The test is performed with ``actual == desired``. + + Parameters + ---------- + test_string : str + The message supplied to AssertionError. + actual : object + The object to test for equality against `desired`. + desired : object + The expected result. + + Examples + -------- + >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1]) # doctest: +SKIP + >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2]) # doctest: +SKIP + Traceback (most recent call last): + ... + AssertionError: Test XYZ of func xyz failed + ACTUAL: + [0, 1] + DESIRED: + [0, 2] + + """ + __tracebackhide__ = True # Hide traceback for py.test + import pprint + + if not (actual == desired): + msg = StringIO() + msg.write(test_string) + msg.write(" failed\nACTUAL: \n") + pprint.pprint(actual, msg) + msg.write("DESIRED: \n") + pprint.pprint(desired, msg) + raise AssertionError(msg.getvalue()) + + +def assert_almost_equal(actual, desired, decimal=7, err_msg="", verbose=True): + """ + Raises an AssertionError if two items are not equal up to desired + precision. + + .. note:: It is recommended to use one of `assert_allclose`, + `assert_array_almost_equal_nulp` or `assert_array_max_ulp` + instead of this function for more consistent floating point + comparisons. + + The test verifies that the elements of `actual` and `desired` satisfy. + + ``abs(desired-actual) < float64(1.5 * 10**(-decimal))`` + + That is a looser test than originally documented, but agrees with what the + actual implementation in `assert_array_almost_equal` did up to rounding + vagaries. An exception is raised at conflicting values. For ndarrays this + delegates to assert_array_almost_equal + + Parameters + ---------- + actual : array_like + The object to check. + desired : array_like + The expected object. + decimal : int, optional + Desired precision, default is 7. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Examples + -------- + >>> from torch._numpy.testing import assert_almost_equal + >>> assert_almost_equal(2.3333333333333, 2.33333334) + >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 10 decimals + ACTUAL: 2.3333333333333 + DESIRED: 2.33333334 + + >>> assert_almost_equal(np.array([1.0,2.3333333333333]), + ... np.array([1.0,2.33333334]), decimal=9) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 9 decimals + + Mismatched elements: 1 / 2 (50%) + Max absolute difference: 6.666699636781459e-09 + Max relative difference: 2.8571569790287484e-09 + x: torch.ndarray([1.0000, 2.3333], dtype=float64) + y: torch.ndarray([1.0000, 2.3333], dtype=float64) + + """ + __tracebackhide__ = True # Hide traceback for py.test + from torch._numpy import imag, iscomplexobj, ndarray, real + + # Handle complex numbers: separate into real/imag to handle + # nan/inf/negative zero correctly + # XXX: catch ValueError for subclasses of ndarray where iscomplex fail + try: + usecomplex = iscomplexobj(actual) or iscomplexobj(desired) + except ValueError: + usecomplex = False + + def _build_err_msg(): + header = "Arrays are not almost equal to %d decimals" % decimal + return build_err_msg([actual, desired], err_msg, verbose=verbose, header=header) + + if usecomplex: + if iscomplexobj(actual): + actualr = real(actual) + actuali = imag(actual) + else: + actualr = actual + actuali = 0 + if iscomplexobj(desired): + desiredr = real(desired) + desiredi = imag(desired) + else: + desiredr = desired + desiredi = 0 + try: + assert_almost_equal(actualr, desiredr, decimal=decimal) + assert_almost_equal(actuali, desiredi, decimal=decimal) + except AssertionError: + raise AssertionError(_build_err_msg()) # noqa: TRY200 + + if isinstance(actual, (ndarray, tuple, list)) or isinstance( + desired, (ndarray, tuple, list) + ): + return assert_array_almost_equal(actual, desired, decimal, err_msg) + try: + # If one of desired/actual is not finite, handle it specially here: + # check that both are nan if any is a nan, and test for equality + # otherwise + if not (gisfinite(desired) and gisfinite(actual)): + if gisnan(desired) or gisnan(actual): + if not (gisnan(desired) and gisnan(actual)): + raise AssertionError(_build_err_msg()) + else: + if not desired == actual: + raise AssertionError(_build_err_msg()) + return + except (NotImplementedError, TypeError): + pass + if abs(desired - actual) >= np.float64(1.5 * 10.0 ** (-decimal)): + raise AssertionError(_build_err_msg()) + + +def assert_approx_equal(actual, desired, significant=7, err_msg="", verbose=True): + """ + Raises an AssertionError if two items are not equal up to significant + digits. + + .. note:: It is recommended to use one of `assert_allclose`, + `assert_array_almost_equal_nulp` or `assert_array_max_ulp` + instead of this function for more consistent floating point + comparisons. + + Given two numbers, check that they are approximately equal. + Approximately equal is defined as the number of significant digits + that agree. + + Parameters + ---------- + actual : scalar + The object to check. + desired : scalar + The expected object. + significant : int, optional + Desired precision, default is 7. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Examples + -------- + >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20) # doctest: +SKIP + >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20, # doctest: +SKIP + ... significant=8) + >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20, # doctest: +SKIP + ... significant=8) + Traceback (most recent call last): + ... + AssertionError: + Items are not equal to 8 significant digits: + ACTUAL: 1.234567e-21 + DESIRED: 1.2345672e-21 + + the evaluated condition that raises the exception is + + >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1) + True + + """ + __tracebackhide__ = True # Hide traceback for py.test + import numpy as np + + (actual, desired) = map(float, (actual, desired)) + if desired == actual: + return + # Normalized the numbers to be in range (-10.0,10.0) + # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual)))))) + scale = 0.5 * (np.abs(desired) + np.abs(actual)) + scale = np.power(10, np.floor(np.log10(scale))) + try: + sc_desired = desired / scale + except ZeroDivisionError: + sc_desired = 0.0 + try: + sc_actual = actual / scale + except ZeroDivisionError: + sc_actual = 0.0 + msg = build_err_msg( + [actual, desired], + err_msg, + header="Items are not equal to %d significant digits:" % significant, + verbose=verbose, + ) + try: + # If one of desired/actual is not finite, handle it specially here: + # check that both are nan if any is a nan, and test for equality + # otherwise + if not (gisfinite(desired) and gisfinite(actual)): + if gisnan(desired) or gisnan(actual): + if not (gisnan(desired) and gisnan(actual)): + raise AssertionError(msg) + else: + if not desired == actual: + raise AssertionError(msg) + return + except (TypeError, NotImplementedError): + pass + if np.abs(sc_desired - sc_actual) >= np.power(10.0, -(significant - 1)): + raise AssertionError(msg) + + +def assert_array_compare( + comparison, + x, + y, + err_msg="", + verbose=True, + header="", + precision=6, + equal_nan=True, + equal_inf=True, + *, + strict=False, +): + __tracebackhide__ = True # Hide traceback for py.test + from torch._numpy import all, array, asarray, bool_, inf, isnan, max + + x = asarray(x) + y = asarray(y) + + def array2string(a): + return str(a) + + # original array for output formatting + ox, oy = x, y + + def func_assert_same_pos(x, y, func=isnan, hasval="nan"): + """Handling nan/inf. + + Combine results of running func on x and y, checking that they are True + at the same locations. + + """ + __tracebackhide__ = True # Hide traceback for py.test + x_id = func(x) + y_id = func(y) + # We include work-arounds here to handle three types of slightly + # pathological ndarray subclasses: + # (1) all() on `masked` array scalars can return masked arrays, so we + # use != True + # (2) __eq__ on some ndarray subclasses returns Python booleans + # instead of element-wise comparisons, so we cast to bool_() and + # use isinstance(..., bool) checks + # (3) subclasses with bare-bones __array_function__ implementations may + # not implement np.all(), so favor using the .all() method + # We are not committed to supporting such subclasses, but it's nice to + # support them if possible. + if (x_id == y_id).all().item() is not True: + msg = build_err_msg( + [x, y], + err_msg + "\nx and y %s location mismatch:" % (hasval), + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise AssertionError(msg) + # If there is a scalar, then here we know the array has the same + # flag as it everywhere, so we should return the scalar flag. + if isinstance(x_id, bool) or x_id.ndim == 0: + return bool_(x_id) + elif isinstance(y_id, bool) or y_id.ndim == 0: + return bool_(y_id) + else: + return y_id + + try: + if strict: + cond = x.shape == y.shape and x.dtype == y.dtype + else: + cond = (x.shape == () or y.shape == ()) or x.shape == y.shape + if not cond: + if x.shape != y.shape: + reason = f"\n(shapes {x.shape}, {y.shape} mismatch)" + else: + reason = f"\n(dtypes {x.dtype}, {y.dtype} mismatch)" + msg = build_err_msg( + [x, y], + err_msg + reason, + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise AssertionError(msg) + + flagged = bool_(False) + + if equal_nan: + flagged = func_assert_same_pos(x, y, func=isnan, hasval="nan") + + if equal_inf: + flagged |= func_assert_same_pos( + x, y, func=lambda xy: xy == +inf, hasval="+inf" + ) + flagged |= func_assert_same_pos( + x, y, func=lambda xy: xy == -inf, hasval="-inf" + ) + + if flagged.ndim > 0: + x, y = x[~flagged], y[~flagged] + # Only do the comparison if actual values are left + if x.size == 0: + return + elif flagged: + # no sense doing comparison if everything is flagged. + return + + val = comparison(x, y) + + if isinstance(val, bool): + cond = val + reduced = array([val]) + else: + reduced = val.ravel() + cond = reduced.all() + + # The below comparison is a hack to ensure that fully masked + # results, for which val.ravel().all() returns np.ma.masked, + # do not trigger a failure (np.ma.masked != True evaluates as + # np.ma.masked, which is falsy). + if not cond: + n_mismatch = reduced.size - int(reduced.sum(dtype=intp)) + n_elements = flagged.size if flagged.ndim != 0 else reduced.size + percent_mismatch = 100 * n_mismatch / n_elements + remarks = [ + f"Mismatched elements: {n_mismatch} / {n_elements} ({percent_mismatch:.3g}%)" + ] + + # with errstate(all='ignore'): + # ignore errors for non-numeric types + with contextlib.suppress(TypeError, RuntimeError): + error = abs(x - y) + if np.issubdtype(x.dtype, np.unsignedinteger): + error2 = abs(y - x) + np.minimum(error, error2, out=error) + max_abs_error = max(error) + remarks.append( + "Max absolute difference: " + array2string(max_abs_error.item()) + ) + + # note: this definition of relative error matches that one + # used by assert_allclose (found in np.isclose) + # Filter values where the divisor would be zero + nonzero = bool_(y != 0) + if all(~nonzero): + max_rel_error = array(inf) + else: + max_rel_error = max(error[nonzero] / abs(y[nonzero])) + remarks.append( + "Max relative difference: " + array2string(max_rel_error.item()) + ) + + err_msg += "\n" + "\n".join(remarks) + msg = build_err_msg( + [ox, oy], + err_msg, + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise AssertionError(msg) + except ValueError: + import traceback + + efmt = traceback.format_exc() + header = f"error during assertion:\n\n{efmt}\n\n{header}" + + msg = build_err_msg( + [x, y], + err_msg, + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise ValueError(msg) # noqa: TRY200 + + +def assert_array_equal(x, y, err_msg="", verbose=True, *, strict=False): + """ + Raises an AssertionError if two array_like objects are not equal. + + Given two array_like objects, check that the shape is equal and all + elements of these objects are equal (but see the Notes for the special + handling of a scalar). An exception is raised at shape mismatch or + conflicting values. In contrast to the standard usage in numpy, NaNs + are compared like numbers, no assertion is raised if both objects have + NaNs in the same positions. + + The usual caution for verifying equality with floating point numbers is + advised. + + Parameters + ---------- + x : array_like + The actual object to check. + y : array_like + The desired, expected object. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + strict : bool, optional + If True, raise an AssertionError when either the shape or the data + type of the array_like objects does not match. The special + handling for scalars mentioned in the Notes section is disabled. + + Raises + ------ + AssertionError + If actual and desired objects are not equal. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Notes + ----- + When one of `x` and `y` is a scalar and the other is array_like, the + function checks that each element of the array_like object is equal to + the scalar. This behaviour can be disabled with the `strict` parameter. + + Examples + -------- + The first assert does not raise an exception: + + >>> np.testing.assert_array_equal([1.0,2.33333,np.nan], + ... [np.exp(0),2.33333, np.nan]) + + Use `assert_allclose` or one of the nulp (number of floating point values) + functions for these cases instead: + + >>> np.testing.assert_allclose([1.0,np.pi,np.nan], + ... [1, np.sqrt(np.pi)**2, np.nan], + ... rtol=1e-10, atol=0) + + As mentioned in the Notes section, `assert_array_equal` has special + handling for scalars. Here the test checks that each value in `x` is 3: + + >>> x = np.full((2, 5), fill_value=3) + >>> np.testing.assert_array_equal(x, 3) + + Use `strict` to raise an AssertionError when comparing a scalar with an + array: + + >>> np.testing.assert_array_equal(x, 3, strict=True) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not equal + + (shapes (2, 5), () mismatch) + x: torch.ndarray([[3, 3, 3, 3, 3], + [3, 3, 3, 3, 3]]) + y: torch.ndarray(3) + + The `strict` parameter also ensures that the array data types match: + + >>> x = np.array([2, 2, 2]) + >>> y = np.array([2., 2., 2.], dtype=np.float32) + >>> np.testing.assert_array_equal(x, y, strict=True) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not equal + + (dtypes dtype("int64"), dtype("float32") mismatch) + x: torch.ndarray([2, 2, 2]) + y: torch.ndarray([2., 2., 2.]) + """ + __tracebackhide__ = True # Hide traceback for py.test + assert_array_compare( + operator.__eq__, + x, + y, + err_msg=err_msg, + verbose=verbose, + header="Arrays are not equal", + strict=strict, + ) + + +def assert_array_almost_equal(x, y, decimal=6, err_msg="", verbose=True): + """ + Raises an AssertionError if two objects are not equal up to desired + precision. + + .. note:: It is recommended to use one of `assert_allclose`, + `assert_array_almost_equal_nulp` or `assert_array_max_ulp` + instead of this function for more consistent floating point + comparisons. + + The test verifies identical shapes and that the elements of ``actual`` and + ``desired`` satisfy. + + ``abs(desired-actual) < 1.5 * 10**(-decimal)`` + + That is a looser test than originally documented, but agrees with what the + actual implementation did up to rounding vagaries. An exception is raised + at shape mismatch or conflicting values. In contrast to the standard usage + in numpy, NaNs are compared like numbers, no assertion is raised if both + objects have NaNs in the same positions. + + Parameters + ---------- + x : array_like + The actual object to check. + y : array_like + The desired, expected object. + decimal : int, optional + Desired precision, default is 6. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Examples + -------- + the first assert does not raise an exception + + >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan], + ... [1.0,2.333,np.nan]) + + >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], + ... [1.0,2.33339,np.nan], decimal=5) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 5 decimals + + Mismatched elements: 1 / 3 (33.3%) + Max absolute difference: 5.999999999994898e-05 + Max relative difference: 2.5713661239633743e-05 + x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64) + y: torch.ndarray([1.0000, 2.3334, nan], dtype=float64) + + >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], + ... [1.0,2.33333, 5], decimal=5) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 5 decimals + + x and y nan location mismatch: + x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64) + y: torch.ndarray([1.0000, 2.3333, 5.0000], dtype=float64) + + """ + __tracebackhide__ = True # Hide traceback for py.test + from torch._numpy import any as npany, float_, issubdtype, number, result_type + + def compare(x, y): + try: + if npany(gisinf(x)) or npany(gisinf(y)): + xinfid = gisinf(x) + yinfid = gisinf(y) + if not (xinfid == yinfid).all(): + return False + # if one item, x and y is +- inf + if x.size == y.size == 1: + return x == y + x = x[~xinfid] + y = y[~yinfid] + except (TypeError, NotImplementedError): + pass + + # make sure y is an inexact type to avoid abs(MIN_INT); will cause + # casting of x later. + dtype = result_type(y, 1.0) + y = asanyarray(y, dtype) + z = abs(x - y) + + if not issubdtype(z.dtype, number): + z = z.astype(float_) # handle object arrays + + return z < 1.5 * 10.0 ** (-decimal) + + assert_array_compare( + compare, + x, + y, + err_msg=err_msg, + verbose=verbose, + header=("Arrays are not almost equal to %d decimals" % decimal), + precision=decimal, + ) + + +def assert_array_less(x, y, err_msg="", verbose=True): + """ + Raises an AssertionError if two array_like objects are not ordered by less + than. + + Given two array_like objects, check that the shape is equal and all + elements of the first object are strictly smaller than those of the + second object. An exception is raised at shape mismatch or incorrectly + ordered values. Shape mismatch does not raise if an object has zero + dimension. In contrast to the standard usage in numpy, NaNs are + compared, no assertion is raised if both objects have NaNs in the same + positions. + + + + Parameters + ---------- + x : array_like + The smaller object to check. + y : array_like + The larger object to compare. + err_msg : string + The error message to be printed in case of failure. + verbose : bool + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired objects are not equal. + + See Also + -------- + assert_array_equal: tests objects for equality + assert_array_almost_equal: test objects for equality up to precision + + + + Examples + -------- + >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan]) + >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan]) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not less-ordered + + Mismatched elements: 1 / 3 (33.3%) + Max absolute difference: 1.0 + Max relative difference: 0.5 + x: torch.ndarray([1., 1., nan], dtype=float64) + y: torch.ndarray([1., 2., nan], dtype=float64) + + >>> np.testing.assert_array_less([1.0, 4.0], 3) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not less-ordered + + Mismatched elements: 1 / 2 (50%) + Max absolute difference: 2.0 + Max relative difference: 0.6666666666666666 + x: torch.ndarray([1., 4.], dtype=float64) + y: torch.ndarray(3) + + >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4]) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not less-ordered + + (shapes (3,), (1,) mismatch) + x: torch.ndarray([1., 2., 3.], dtype=float64) + y: torch.ndarray([4]) + + """ + __tracebackhide__ = True # Hide traceback for py.test + assert_array_compare( + operator.__lt__, + x, + y, + err_msg=err_msg, + verbose=verbose, + header="Arrays are not less-ordered", + equal_inf=False, + ) + + +def assert_string_equal(actual, desired): + """ + Test if two strings are equal. + + If the given strings are equal, `assert_string_equal` does nothing. + If they are not equal, an AssertionError is raised, and the diff + between the strings is shown. + + Parameters + ---------- + actual : str + The string to test for equality against the expected string. + desired : str + The expected string. + + Examples + -------- + >>> np.testing.assert_string_equal('abc', 'abc') # doctest: +SKIP + >>> np.testing.assert_string_equal('abc', 'abcd') # doctest: +SKIP + Traceback (most recent call last): + File "", line 1, in + ... + AssertionError: Differences in strings: + - abc+ abcd? + + + """ + # delay import of difflib to reduce startup time + __tracebackhide__ = True # Hide traceback for py.test + import difflib + + if not isinstance(actual, str): + raise AssertionError(repr(type(actual))) + if not isinstance(desired, str): + raise AssertionError(repr(type(desired))) + if desired == actual: + return + + diff = list( + difflib.Differ().compare(actual.splitlines(True), desired.splitlines(True)) + ) + diff_list = [] + while diff: + d1 = diff.pop(0) + if d1.startswith(" "): + continue + if d1.startswith("- "): + l = [d1] + d2 = diff.pop(0) + if d2.startswith("? "): + l.append(d2) + d2 = diff.pop(0) + if not d2.startswith("+ "): + raise AssertionError(repr(d2)) + l.append(d2) + if diff: + d3 = diff.pop(0) + if d3.startswith("? "): + l.append(d3) + else: + diff.insert(0, d3) + if d2[2:] == d1[2:]: + continue + diff_list.extend(l) + continue + raise AssertionError(repr(d1)) + if not diff_list: + return + msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}" + if actual != desired: + raise AssertionError(msg) + + +import unittest + + +class _Dummy(unittest.TestCase): + def nop(self): + pass + + +_d = _Dummy("nop") + + +def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs): + """ + assert_raises_regex(exception_class, expected_regexp, callable, *args, + **kwargs) + assert_raises_regex(exception_class, expected_regexp) + + Fail unless an exception of class exception_class and with message that + matches expected_regexp is thrown by callable when invoked with arguments + args and keyword arguments kwargs. + + Alternatively, can be used as a context manager like `assert_raises`. + + Notes + ----- + .. versionadded:: 1.9.0 + + """ + __tracebackhide__ = True # Hide traceback for py.test + return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs) + + +def decorate_methods(cls, decorator, testmatch=None): + """ + Apply a decorator to all methods in a class matching a regular expression. + + The given decorator is applied to all public methods of `cls` that are + matched by the regular expression `testmatch` + (``testmatch.search(methodname)``). Methods that are private, i.e. start + with an underscore, are ignored. + + Parameters + ---------- + cls : class + Class whose methods to decorate. + decorator : function + Decorator to apply to methods + testmatch : compiled regexp or str, optional + The regular expression. Default value is None, in which case the + nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``) + is used. + If `testmatch` is a string, it is compiled to a regular expression + first. + + """ + if testmatch is None: + testmatch = re.compile(r"(?:^|[\\b_\\.%s-])[Tt]est" % os.sep) + else: + testmatch = re.compile(testmatch) + cls_attr = cls.__dict__ + + # delayed import to reduce startup time + from inspect import isfunction + + methods = [_m for _m in cls_attr.values() if isfunction(_m)] + for function in methods: + try: + if hasattr(function, "compat_func_name"): + funcname = function.compat_func_name + else: + funcname = function.__name__ + except AttributeError: + # not a function + continue + if testmatch.search(funcname) and not funcname.startswith("_"): + setattr(cls, funcname, decorator(function)) + return + + +def _assert_valid_refcount(op): + """ + Check that ufuncs don't mishandle refcount of object `1`. + Used in a few regression tests. + """ + if not HAS_REFCOUNT: + return True + + import gc + + import numpy as np + + b = np.arange(100 * 100).reshape(100, 100) + c = b + i = 1 + + gc.disable() + try: + rc = sys.getrefcount(i) + for j in range(15): + d = op(b, c) + assert_(sys.getrefcount(i) >= rc) + finally: + gc.enable() + del d # for pyflakes + + +def assert_allclose( + actual, + desired, + rtol=1e-7, + atol=0, + equal_nan=True, + err_msg="", + verbose=True, + check_dtype=False, +): + """ + Raises an AssertionError if two objects are not equal up to desired + tolerance. + + Given two array_like objects, check that their shapes and all elements + are equal (but see the Notes for the special handling of a scalar). An + exception is raised if the shapes mismatch or any values conflict. In + contrast to the standard usage in numpy, NaNs are compared like numbers, + no assertion is raised if both objects have NaNs in the same positions. + + The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note + that ``allclose`` has different default values). It compares the difference + between `actual` and `desired` to ``atol + rtol * abs(desired)``. + + .. versionadded:: 1.5.0 + + Parameters + ---------- + actual : array_like + Array obtained. + desired : array_like + Array desired. + rtol : float, optional + Relative tolerance. + atol : float, optional + Absolute tolerance. + equal_nan : bool, optional. + If True, NaNs will compare equal. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_array_almost_equal_nulp, assert_array_max_ulp + + Notes + ----- + When one of `actual` and `desired` is a scalar and the other is + array_like, the function checks that each element of the array_like + object is equal to the scalar. + + Examples + -------- + >>> x = [1e-5, 1e-3, 1e-1] + >>> y = np.arccos(np.cos(x)) + >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0) + + """ + __tracebackhide__ = True # Hide traceback for py.test + + def compare(x, y): + return np.isclose(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan) + + actual, desired = asanyarray(actual), asanyarray(desired) + header = f"Not equal to tolerance rtol={rtol:g}, atol={atol:g}" + + if check_dtype: + assert actual.dtype == desired.dtype + + assert_array_compare( + compare, + actual, + desired, + err_msg=str(err_msg), + verbose=verbose, + header=header, + equal_nan=equal_nan, + ) + + +def assert_array_almost_equal_nulp(x, y, nulp=1): + """ + Compare two arrays relatively to their spacing. + + This is a relatively robust method to compare two arrays whose amplitude + is variable. + + Parameters + ---------- + x, y : array_like + Input arrays. + nulp : int, optional + The maximum number of unit in the last place for tolerance (see Notes). + Default is 1. + + Returns + ------- + None + + Raises + ------ + AssertionError + If the spacing between `x` and `y` for one or more elements is larger + than `nulp`. + + See Also + -------- + assert_array_max_ulp : Check that all items of arrays differ in at most + N Units in the Last Place. + spacing : Return the distance between x and the nearest adjacent number. + + Notes + ----- + An assertion is raised if the following condition is not met:: + + abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y))) + + Examples + -------- + >>> x = np.array([1., 1e-10, 1e-20]) + >>> eps = np.finfo(x.dtype).eps + >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x) # doctest: +SKIP + + >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) # doctest: +SKIP + Traceback (most recent call last): + ... + AssertionError: X and Y are not equal to 1 ULP (max is 2) + + """ + __tracebackhide__ = True # Hide traceback for py.test + import numpy as np + + ax = np.abs(x) + ay = np.abs(y) + ref = nulp * np.spacing(np.where(ax > ay, ax, ay)) + if not np.all(np.abs(x - y) <= ref): + if np.iscomplexobj(x) or np.iscomplexobj(y): + msg = "X and Y are not equal to %d ULP" % nulp + else: + max_nulp = np.max(nulp_diff(x, y)) + msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp) + raise AssertionError(msg) + + +def assert_array_max_ulp(a, b, maxulp=1, dtype=None): + """ + Check that all items of arrays differ in at most N Units in the Last Place. + + Parameters + ---------- + a, b : array_like + Input arrays to be compared. + maxulp : int, optional + The maximum number of units in the last place that elements of `a` and + `b` can differ. Default is 1. + dtype : dtype, optional + Data-type to convert `a` and `b` to if given. Default is None. + + Returns + ------- + ret : ndarray + Array containing number of representable floating point numbers between + items in `a` and `b`. + + Raises + ------ + AssertionError + If one or more elements differ by more than `maxulp`. + + Notes + ----- + For computing the ULP difference, this API does not differentiate between + various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 + is zero). + + See Also + -------- + assert_array_almost_equal_nulp : Compare two arrays relatively to their + spacing. + + Examples + -------- + >>> a = np.linspace(0., 1., 100) + >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a))) # doctest: +SKIP + + """ + __tracebackhide__ = True # Hide traceback for py.test + import numpy as np + + ret = nulp_diff(a, b, dtype) + if not np.all(ret <= maxulp): + raise AssertionError( + f"Arrays are not almost equal up to {maxulp:g} " + f"ULP (max difference is {np.max(ret):g} ULP)" + ) + return ret + + +def nulp_diff(x, y, dtype=None): + """For each item in x and y, return the number of representable floating + points between them. + + Parameters + ---------- + x : array_like + first input array + y : array_like + second input array + dtype : dtype, optional + Data-type to convert `x` and `y` to if given. Default is None. + + Returns + ------- + nulp : array_like + number of representable floating point numbers between each item in x + and y. + + Notes + ----- + For computing the ULP difference, this API does not differentiate between + various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 + is zero). + + Examples + -------- + # By definition, epsilon is the smallest number such as 1 + eps != 1, so + # there should be exactly one ULP between 1 and 1 + eps + >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) # doctest: +SKIP + 1.0 + """ + import numpy as np + + if dtype: + x = np.asarray(x, dtype=dtype) + y = np.asarray(y, dtype=dtype) + else: + x = np.asarray(x) + y = np.asarray(y) + + t = np.common_type(x, y) + if np.iscomplexobj(x) or np.iscomplexobj(y): + raise NotImplementedError("_nulp not implemented for complex array") + + x = np.array([x], dtype=t) + y = np.array([y], dtype=t) + + x[np.isnan(x)] = np.nan + y[np.isnan(y)] = np.nan + + if not x.shape == y.shape: + raise ValueError(f"x and y do not have the same shape: {x.shape} - {y.shape}") + + def _diff(rx, ry, vdt): + diff = np.asarray(rx - ry, dtype=vdt) + return np.abs(diff) + + rx = integer_repr(x) + ry = integer_repr(y) + return _diff(rx, ry, t) + + +def _integer_repr(x, vdt, comp): + # Reinterpret binary representation of the float as sign-magnitude: + # take into account two-complement representation + # See also + # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + rx = x.view(vdt) + if not (rx.size == 1): + rx[rx < 0] = comp - rx[rx < 0] + else: + if rx < 0: + rx = comp - rx + + return rx + + +def integer_repr(x): + """Return the signed-magnitude interpretation of the binary representation + of x.""" + import numpy as np + + if x.dtype == np.float16: + return _integer_repr(x, np.int16, np.int16(-(2**15))) + elif x.dtype == np.float32: + return _integer_repr(x, np.int32, np.int32(-(2**31))) + elif x.dtype == np.float64: + return _integer_repr(x, np.int64, np.int64(-(2**63))) + else: + raise ValueError(f"Unsupported dtype {x.dtype}") + + +@contextlib.contextmanager +def _assert_warns_context(warning_class, name=None): + __tracebackhide__ = True # Hide traceback for py.test + with suppress_warnings() as sup: + l = sup.record(warning_class) + yield + if not len(l) > 0: + name_str = f" when calling {name}" if name is not None else "" + raise AssertionError("No warning raised" + name_str) + + +def assert_warns(warning_class, *args, **kwargs): + """ + Fail unless the given callable throws the specified warning. + + A warning of class warning_class should be thrown by the callable when + invoked with arguments args and keyword arguments kwargs. + If a different type of warning is thrown, it will not be caught. + + If called with all arguments other than the warning class omitted, may be + used as a context manager: + + with assert_warns(SomeWarning): + do_something() + + The ability to be used as a context manager is new in NumPy v1.11.0. + + .. versionadded:: 1.4.0 + + Parameters + ---------- + warning_class : class + The class defining the warning that `func` is expected to throw. + func : callable, optional + Callable to test + *args : Arguments + Arguments for `func`. + **kwargs : Kwargs + Keyword arguments for `func`. + + Returns + ------- + The value returned by `func`. + + Examples + -------- + >>> import warnings + >>> def deprecated_func(num): + ... warnings.warn("Please upgrade", DeprecationWarning) + ... return num*num + >>> with np.testing.assert_warns(DeprecationWarning): + ... assert deprecated_func(4) == 16 + >>> # or passing a func + >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4) + >>> assert ret == 16 + """ + if not args: + return _assert_warns_context(warning_class) + + func = args[0] + args = args[1:] + with _assert_warns_context(warning_class, name=func.__name__): + return func(*args, **kwargs) + + +@contextlib.contextmanager +def _assert_no_warnings_context(name=None): + __tracebackhide__ = True # Hide traceback for py.test + with warnings.catch_warnings(record=True) as l: + warnings.simplefilter("always") + yield + if len(l) > 0: + name_str = f" when calling {name}" if name is not None else "" + raise AssertionError(f"Got warnings{name_str}: {l}") + + +def assert_no_warnings(*args, **kwargs): + """ + Fail if the given callable produces any warnings. + + If called with all arguments omitted, may be used as a context manager: + + with assert_no_warnings(): + do_something() + + The ability to be used as a context manager is new in NumPy v1.11.0. + + .. versionadded:: 1.7.0 + + Parameters + ---------- + func : callable + The callable to test. + \\*args : Arguments + Arguments passed to `func`. + \\*\\*kwargs : Kwargs + Keyword arguments passed to `func`. + + Returns + ------- + The value returned by `func`. + + """ + if not args: + return _assert_no_warnings_context() + + func = args[0] + args = args[1:] + with _assert_no_warnings_context(name=func.__name__): + return func(*args, **kwargs) + + +def _gen_alignment_data(dtype=float32, type="binary", max_size=24): + """ + generator producing data with different alignment and offsets + to test simd vectorization + + Parameters + ---------- + dtype : dtype + data type to produce + type : string + 'unary': create data for unary operations, creates one input + and output array + 'binary': create data for unary operations, creates two input + and output array + max_size : integer + maximum size of data to produce + + Returns + ------- + if type is 'unary' yields one output, one input array and a message + containing information on the data + if type is 'binary' yields one output array, two input array and a message + containing information on the data + + """ + ufmt = "unary offset=(%d, %d), size=%d, dtype=%r, %s" + bfmt = "binary offset=(%d, %d, %d), size=%d, dtype=%r, %s" + for o in range(3): + for s in range(o + 2, max(o + 3, max_size)): + if type == "unary": + + def inp(): + return arange(s, dtype=dtype)[o:] + + out = empty((s,), dtype=dtype)[o:] + yield out, inp(), ufmt % (o, o, s, dtype, "out of place") + d = inp() + yield d, d, ufmt % (o, o, s, dtype, "in place") + yield out[1:], inp()[:-1], ufmt % ( + o + 1, + o, + s - 1, + dtype, + "out of place", + ) + yield out[:-1], inp()[1:], ufmt % ( + o, + o + 1, + s - 1, + dtype, + "out of place", + ) + yield inp()[:-1], inp()[1:], ufmt % (o, o + 1, s - 1, dtype, "aliased") + yield inp()[1:], inp()[:-1], ufmt % (o + 1, o, s - 1, dtype, "aliased") + if type == "binary": + + def inp1(): + return arange(s, dtype=dtype)[o:] + + inp2 = inp1 + out = empty((s,), dtype=dtype)[o:] + yield out, inp1(), inp2(), bfmt % (o, o, o, s, dtype, "out of place") + d = inp1() + yield d, d, inp2(), bfmt % (o, o, o, s, dtype, "in place1") + d = inp2() + yield d, inp1(), d, bfmt % (o, o, o, s, dtype, "in place2") + yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % ( + o + 1, + o, + o, + s - 1, + dtype, + "out of place", + ) + yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % ( + o, + o + 1, + o, + s - 1, + dtype, + "out of place", + ) + yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % ( + o, + o, + o + 1, + s - 1, + dtype, + "out of place", + ) + yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % ( + o + 1, + o, + o, + s - 1, + dtype, + "aliased", + ) + yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % ( + o, + o + 1, + o, + s - 1, + dtype, + "aliased", + ) + yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % ( + o, + o, + o + 1, + s - 1, + dtype, + "aliased", + ) + + +class IgnoreException(Exception): + "Ignoring this exception due to disabled feature" + + +@contextlib.contextmanager +def tempdir(*args, **kwargs): + """Context manager to provide a temporary test folder. + + All arguments are passed as this to the underlying tempfile.mkdtemp + function. + + """ + tmpdir = mkdtemp(*args, **kwargs) + try: + yield tmpdir + finally: + shutil.rmtree(tmpdir) + + +@contextlib.contextmanager +def temppath(*args, **kwargs): + """Context manager for temporary files. + + Context manager that returns the path to a closed temporary file. Its + parameters are the same as for tempfile.mkstemp and are passed directly + to that function. The underlying file is removed when the context is + exited, so it should be closed at that time. + + Windows does not allow a temporary file to be opened if it is already + open, so the underlying file must be closed after opening before it + can be opened again. + + """ + fd, path = mkstemp(*args, **kwargs) + os.close(fd) + try: + yield path + finally: + os.remove(path) + + +class clear_and_catch_warnings(warnings.catch_warnings): + """Context manager that resets warning registry for catching warnings + + Warnings can be slippery, because, whenever a warning is triggered, Python + adds a ``__warningregistry__`` member to the *calling* module. This makes + it impossible to retrigger the warning in this module, whatever you put in + the warnings filters. This context manager accepts a sequence of `modules` + as a keyword argument to its constructor and: + + * stores and removes any ``__warningregistry__`` entries in given `modules` + on entry; + * resets ``__warningregistry__`` to its previous state on exit. + + This makes it possible to trigger any warning afresh inside the context + manager without disturbing the state of warnings outside. + + For compatibility with Python 3.0, please consider all arguments to be + keyword-only. + + Parameters + ---------- + record : bool, optional + Specifies whether warnings should be captured by a custom + implementation of ``warnings.showwarning()`` and be appended to a list + returned by the context manager. Otherwise None is returned by the + context manager. The objects appended to the list are arguments whose + attributes mirror the arguments to ``showwarning()``. + modules : sequence, optional + Sequence of modules for which to reset warnings registry on entry and + restore on exit. To work correctly, all 'ignore' filters should + filter by one of these modules. + + Examples + -------- + >>> import warnings + >>> with np.testing.clear_and_catch_warnings( # doctest: +SKIP + ... modules=[np.core.fromnumeric]): + ... warnings.simplefilter('always') + ... warnings.filterwarnings('ignore', module='np.core.fromnumeric') + ... # do something that raises a warning but ignore those in + ... # np.core.fromnumeric + """ + + class_modules = () + + def __init__(self, record=False, modules=()): + self.modules = set(modules).union(self.class_modules) + self._warnreg_copies = {} + super().__init__(record=record) + + def __enter__(self): + for mod in self.modules: + if hasattr(mod, "__warningregistry__"): + mod_reg = mod.__warningregistry__ + self._warnreg_copies[mod] = mod_reg.copy() + mod_reg.clear() + return super().__enter__() + + def __exit__(self, *exc_info): + super().__exit__(*exc_info) + for mod in self.modules: + if hasattr(mod, "__warningregistry__"): + mod.__warningregistry__.clear() + if mod in self._warnreg_copies: + mod.__warningregistry__.update(self._warnreg_copies[mod]) + + +class suppress_warnings: + """ + Context manager and decorator doing much the same as + ``warnings.catch_warnings``. + + However, it also provides a filter mechanism to work around + https://bugs.python.org/issue4180. + + This bug causes Python before 3.4 to not reliably show warnings again + after they have been ignored once (even within catch_warnings). It + means that no "ignore" filter can be used easily, since following + tests might need to see the warning. Additionally it allows easier + specificity for testing warnings and can be nested. + + Parameters + ---------- + forwarding_rule : str, optional + One of "always", "once", "module", or "location". Analogous to + the usual warnings module filter mode, it is useful to reduce + noise mostly on the outmost level. Unsuppressed and unrecorded + warnings will be forwarded based on this rule. Defaults to "always". + "location" is equivalent to the warnings "default", match by exact + location the warning warning originated from. + + Notes + ----- + Filters added inside the context manager will be discarded again + when leaving it. Upon entering all filters defined outside a + context will be applied automatically. + + When a recording filter is added, matching warnings are stored in the + ``log`` attribute as well as in the list returned by ``record``. + + If filters are added and the ``module`` keyword is given, the + warning registry of this module will additionally be cleared when + applying it, entering the context, or exiting it. This could cause + warnings to appear a second time after leaving the context if they + were configured to be printed once (default) and were already + printed before the context was entered. + + Nesting this context manager will work as expected when the + forwarding rule is "always" (default). Unfiltered and unrecorded + warnings will be passed out and be matched by the outer level. + On the outmost level they will be printed (or caught by another + warnings context). The forwarding rule argument can modify this + behaviour. + + Like ``catch_warnings`` this context manager is not threadsafe. + + Examples + -------- + + With a context manager:: + + with np.testing.suppress_warnings() as sup: + sup.filter(DeprecationWarning, "Some text") + sup.filter(module=np.ma.core) + log = sup.record(FutureWarning, "Does this occur?") + command_giving_warnings() + # The FutureWarning was given once, the filtered warnings were + # ignored. All other warnings abide outside settings (may be + # printed/error) + assert_(len(log) == 1) + assert_(len(sup.log) == 1) # also stored in log attribute + + Or as a decorator:: + + sup = np.testing.suppress_warnings() + sup.filter(module=np.ma.core) # module must match exactly + @sup + def some_function(): + # do something which causes a warning in np.ma.core + pass + """ + + def __init__(self, forwarding_rule="always"): + self._entered = False + + # Suppressions are either instance or defined inside one with block: + self._suppressions = [] + + if forwarding_rule not in {"always", "module", "once", "location"}: + raise ValueError("unsupported forwarding rule.") + self._forwarding_rule = forwarding_rule + + def _clear_registries(self): + if hasattr(warnings, "_filters_mutated"): + # clearing the registry should not be necessary on new pythons, + # instead the filters should be mutated. + warnings._filters_mutated() + return + # Simply clear the registry, this should normally be harmless, + # note that on new pythons it would be invalidated anyway. + for module in self._tmp_modules: + if hasattr(module, "__warningregistry__"): + module.__warningregistry__.clear() + + def _filter(self, category=Warning, message="", module=None, record=False): + if record: + record = [] # The log where to store warnings + else: + record = None + if self._entered: + if module is None: + warnings.filterwarnings("always", category=category, message=message) + else: + module_regex = module.__name__.replace(".", r"\.") + "$" + warnings.filterwarnings( + "always", category=category, message=message, module=module_regex + ) + self._tmp_modules.add(module) + self._clear_registries() + + self._tmp_suppressions.append( + (category, message, re.compile(message, re.I), module, record) + ) + else: + self._suppressions.append( + (category, message, re.compile(message, re.I), module, record) + ) + + return record + + def filter(self, category=Warning, message="", module=None): + """ + Add a new suppressing filter or apply it if the state is entered. + + Parameters + ---------- + category : class, optional + Warning class to filter + message : string, optional + Regular expression matching the warning message. + module : module, optional + Module to filter for. Note that the module (and its file) + must match exactly and cannot be a submodule. This may make + it unreliable for external modules. + + Notes + ----- + When added within a context, filters are only added inside + the context and will be forgotten when the context is exited. + """ + self._filter(category=category, message=message, module=module, record=False) + + def record(self, category=Warning, message="", module=None): + """ + Append a new recording filter or apply it if the state is entered. + + All warnings matching will be appended to the ``log`` attribute. + + Parameters + ---------- + category : class, optional + Warning class to filter + message : string, optional + Regular expression matching the warning message. + module : module, optional + Module to filter for. Note that the module (and its file) + must match exactly and cannot be a submodule. This may make + it unreliable for external modules. + + Returns + ------- + log : list + A list which will be filled with all matched warnings. + + Notes + ----- + When added within a context, filters are only added inside + the context and will be forgotten when the context is exited. + """ + return self._filter( + category=category, message=message, module=module, record=True + ) + + def __enter__(self): + if self._entered: + raise RuntimeError("cannot enter suppress_warnings twice.") + + self._orig_show = warnings.showwarning + self._filters = warnings.filters + warnings.filters = self._filters[:] + + self._entered = True + self._tmp_suppressions = [] + self._tmp_modules = set() + self._forwarded = set() + + self.log = [] # reset global log (no need to keep same list) + + for cat, mess, _, mod, log in self._suppressions: + if log is not None: + del log[:] # clear the log + if mod is None: + warnings.filterwarnings("always", category=cat, message=mess) + else: + module_regex = mod.__name__.replace(".", r"\.") + "$" + warnings.filterwarnings( + "always", category=cat, message=mess, module=module_regex + ) + self._tmp_modules.add(mod) + warnings.showwarning = self._showwarning + self._clear_registries() + + return self + + def __exit__(self, *exc_info): + warnings.showwarning = self._orig_show + warnings.filters = self._filters + self._clear_registries() + self._entered = False + del self._orig_show + del self._filters + + def _showwarning( + self, message, category, filename, lineno, *args, use_warnmsg=None, **kwargs + ): + for cat, _, pattern, mod, rec in (self._suppressions + self._tmp_suppressions)[ + ::-1 + ]: + if issubclass(category, cat) and pattern.match(message.args[0]) is not None: + if mod is None: + # Message and category match, either recorded or ignored + if rec is not None: + msg = WarningMessage( + message, category, filename, lineno, **kwargs + ) + self.log.append(msg) + rec.append(msg) + return + # Use startswith, because warnings strips the c or o from + # .pyc/.pyo files. + elif mod.__file__.startswith(filename): + # The message and module (filename) match + if rec is not None: + msg = WarningMessage( + message, category, filename, lineno, **kwargs + ) + self.log.append(msg) + rec.append(msg) + return + + # There is no filter in place, so pass to the outside handler + # unless we should only pass it once + if self._forwarding_rule == "always": + if use_warnmsg is None: + self._orig_show(message, category, filename, lineno, *args, **kwargs) + else: + self._orig_showmsg(use_warnmsg) + return + + if self._forwarding_rule == "once": + signature = (message.args, category) + elif self._forwarding_rule == "module": + signature = (message.args, category, filename) + elif self._forwarding_rule == "location": + signature = (message.args, category, filename, lineno) + + if signature in self._forwarded: + return + self._forwarded.add(signature) + if use_warnmsg is None: + self._orig_show(message, category, filename, lineno, *args, **kwargs) + else: + self._orig_showmsg(use_warnmsg) + + def __call__(self, func): + """ + Function decorator to apply certain suppressions to a whole + function. + """ + + @wraps(func) + def new_func(*args, **kwargs): + with self: + return func(*args, **kwargs) + + return new_func + + +@contextlib.contextmanager +def _assert_no_gc_cycles_context(name=None): + __tracebackhide__ = True # Hide traceback for py.test + + # not meaningful to test if there is no refcounting + if not HAS_REFCOUNT: + yield + return + + assert_(gc.isenabled()) + gc.disable() + gc_debug = gc.get_debug() + try: + for i in range(100): + if gc.collect() == 0: + break + else: + raise RuntimeError( + "Unable to fully collect garbage - perhaps a __del__ method " + "is creating more reference cycles?" + ) + + gc.set_debug(gc.DEBUG_SAVEALL) + yield + # gc.collect returns the number of unreachable objects in cycles that + # were found -- we are checking that no cycles were created in the context + n_objects_in_cycles = gc.collect() + objects_in_cycles = gc.garbage[:] + finally: + del gc.garbage[:] + gc.set_debug(gc_debug) + gc.enable() + + if n_objects_in_cycles: + name_str = f" when calling {name}" if name is not None else "" + raise AssertionError( + "Reference cycles were found{}: {} objects were collected, " + "of which {} are shown below:{}".format( + name_str, + n_objects_in_cycles, + len(objects_in_cycles), + "".join( + "\n {} object with id={}:\n {}".format( + type(o).__name__, + id(o), + pprint.pformat(o).replace("\n", "\n "), + ) + for o in objects_in_cycles + ), + ) + ) + + +def assert_no_gc_cycles(*args, **kwargs): + """ + Fail if the given callable produces any reference cycles. + + If called with all arguments omitted, may be used as a context manager: + + with assert_no_gc_cycles(): + do_something() + + .. versionadded:: 1.15.0 + + Parameters + ---------- + func : callable + The callable to test. + \\*args : Arguments + Arguments passed to `func`. + \\*\\*kwargs : Kwargs + Keyword arguments passed to `func`. + + Returns + ------- + Nothing. The result is deliberately discarded to ensure that all cycles + are found. + + """ + if not args: + return _assert_no_gc_cycles_context() + + func = args[0] + args = args[1:] + with _assert_no_gc_cycles_context(name=func.__name__): + func(*args, **kwargs) + + +def break_cycles(): + """ + Break reference cycles by calling gc.collect + Objects can call other objects' methods (for instance, another object's + __del__) inside their own __del__. On PyPy, the interpreter only runs + between calls to gc.collect, so multiple calls are needed to completely + release all cycles. + """ + + gc.collect() + if IS_PYPY: + # a few more, just to make sure all the finalizers are called + gc.collect() + gc.collect() + gc.collect() + gc.collect() + + +def requires_memory(free_bytes): + """Decorator to skip a test if not enough memory is available""" + import pytest + + def decorator(func): + @wraps(func) + def wrapper(*a, **kw): + msg = check_free_memory(free_bytes) + if msg is not None: + pytest.skip(msg) + + try: + return func(*a, **kw) + except MemoryError: + # Probably ran out of memory regardless: don't regard as failure + pytest.xfail("MemoryError raised") + + return wrapper + + return decorator + + +def check_free_memory(free_bytes): + """ + Check whether `free_bytes` amount of memory is currently free. + Returns: None if enough memory available, otherwise error message + """ + env_var = "NPY_AVAILABLE_MEM" + env_value = os.environ.get(env_var) + if env_value is not None: + try: + mem_free = _parse_size(env_value) + except ValueError as exc: + raise ValueError( # noqa: TRY200 + f"Invalid environment variable {env_var}: {exc}" + ) + + msg = ( + f"{free_bytes/1e9} GB memory required, but environment variable " + f"NPY_AVAILABLE_MEM={env_value} set" + ) + else: + mem_free = _get_mem_available() + + if mem_free is None: + msg = ( + "Could not determine available memory; set NPY_AVAILABLE_MEM " + "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run " + "the test." + ) + mem_free = -1 + else: + msg = ( + f"{free_bytes/1e9} GB memory required, but {mem_free/1e9} GB available" + ) + + return msg if mem_free < free_bytes else None + + +def _parse_size(size_str): + """Convert memory size strings ('12 GB' etc.) to float""" + suffixes = { + "": 1, + "b": 1, + "k": 1000, + "m": 1000**2, + "g": 1000**3, + "t": 1000**4, + "kb": 1000, + "mb": 1000**2, + "gb": 1000**3, + "tb": 1000**4, + "kib": 1024, + "mib": 1024**2, + "gib": 1024**3, + "tib": 1024**4, + } + + size_re = re.compile( + r"^\s*(\d+|\d+\.\d+)\s*({})\s*$".format("|".join(suffixes.keys())), re.I + ) + + m = size_re.match(size_str.lower()) + if not m or m.group(2) not in suffixes: + raise ValueError(f"value {size_str!r} not a valid size") + return int(float(m.group(1)) * suffixes[m.group(2)]) + + +def _get_mem_available(): + """Return available memory in bytes, or None if unknown.""" + try: + import psutil + + return psutil.virtual_memory().available + except (ImportError, AttributeError): + pass + + if sys.platform.startswith("linux"): + info = {} + with open("/proc/meminfo") as f: + for line in f: + p = line.split() + info[p[0].strip(":").lower()] = int(p[1]) * 1024 + + if "memavailable" in info: + # Linux >= 3.14 + return info["memavailable"] + else: + return info["memfree"] + info["cached"] + + return None + + +def _no_tracing(func): + """ + Decorator to temporarily turn off tracing for the duration of a test. + Needed in tests that check refcounting, otherwise the tracing itself + influences the refcounts + """ + if not hasattr(sys, "gettrace"): + return func + else: + + @wraps(func) + def wrapper(*args, **kwargs): + original_trace = sys.gettrace() + try: + sys.settrace(None) + return func(*args, **kwargs) + finally: + sys.settrace(original_trace) + + return wrapper + + +def _get_glibc_version(): + try: + ver = os.confstr("CS_GNU_LIBC_VERSION").rsplit(" ")[1] + except Exception as inst: + ver = "0.0" + + return ver + + +_glibcver = _get_glibc_version() + + +def _glibc_older_than(x): + return _glibcver != "0.0" and _glibcver < x diff --git a/shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/blob b/shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/blob new file mode 100644 index 0000000000000000000000000000000000000000..e4027b3cf302b8610b87d9ef8b0aac39d5a40ef9 Binary files /dev/null and b/shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/blob differ diff --git a/shared/package-files/74/74d8c4bc58760b7e17328884fd1ee5889bf972bc97533d9647656cc5d9d0763a/blob b/shared/package-files/74/74d8c4bc58760b7e17328884fd1ee5889bf972bc97533d9647656cc5d9d0763a/blob new file mode 100644 index 0000000000000000000000000000000000000000..85aa46327023e1f83537199647d4f85359398703 --- /dev/null +++ b/shared/package-files/74/74d8c4bc58760b7e17328884fd1ee5889bf972bc97533d9647656cc5d9d0763a/blob @@ -0,0 +1,551 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import argparse +from gettext import gettext +import os +import sys +from typing import Any +from typing import Callable +from typing import cast +from typing import final +from typing import List +from typing import Literal +from typing import Mapping +from typing import NoReturn +from typing import Sequence + +import _pytest._io +from _pytest.config.exceptions import UsageError +from _pytest.deprecated import check_ispytest + + +FILE_OR_DIR = "file_or_dir" + + +class NotSet: + def __repr__(self) -> str: + return "" + + +NOT_SET = NotSet() + + +@final +class Parser: + """Parser for command line arguments and ini-file values. + + :ivar extra_info: Dict of generic param -> value to display in case + there's an error processing the command line arguments. + """ + + prog: str | None = None + + def __init__( + self, + usage: str | None = None, + processopt: Callable[[Argument], None] | None = None, + *, + _ispytest: bool = False, + ) -> None: + check_ispytest(_ispytest) + self._anonymous = OptionGroup("Custom options", parser=self, _ispytest=True) + self._groups: list[OptionGroup] = [] + self._processopt = processopt + self._usage = usage + self._inidict: dict[str, tuple[str, str | None, Any]] = {} + self._ininames: list[str] = [] + self.extra_info: dict[str, Any] = {} + + def processoption(self, option: Argument) -> None: + if self._processopt: + if option.dest: + self._processopt(option) + + def getgroup( + self, name: str, description: str = "", after: str | None = None + ) -> OptionGroup: + """Get (or create) a named option Group. + + :param name: Name of the option group. + :param description: Long description for --help output. + :param after: Name of another group, used for ordering --help output. + :returns: The option group. + + The returned group object has an ``addoption`` method with the same + signature as :func:`parser.addoption ` but + will be shown in the respective group in the output of + ``pytest --help``. + """ + for group in self._groups: + if group.name == name: + return group + group = OptionGroup(name, description, parser=self, _ispytest=True) + i = 0 + for i, grp in enumerate(self._groups): + if grp.name == after: + break + self._groups.insert(i + 1, group) + return group + + def addoption(self, *opts: str, **attrs: Any) -> None: + """Register a command line option. + + :param opts: + Option names, can be short or long options. + :param attrs: + Same attributes as the argparse library's :meth:`add_argument() + ` function accepts. + + After command line parsing, options are available on the pytest config + object via ``config.option.NAME`` where ``NAME`` is usually set + by passing a ``dest`` attribute, for example + ``addoption("--long", dest="NAME", ...)``. + """ + self._anonymous.addoption(*opts, **attrs) + + def parse( + self, + args: Sequence[str | os.PathLike[str]], + namespace: argparse.Namespace | None = None, + ) -> argparse.Namespace: + from _pytest._argcomplete import try_argcomplete + + self.optparser = self._getparser() + try_argcomplete(self.optparser) + strargs = [os.fspath(x) for x in args] + return self.optparser.parse_args(strargs, namespace=namespace) + + def _getparser(self) -> MyOptionParser: + from _pytest._argcomplete import filescompleter + + optparser = MyOptionParser(self, self.extra_info, prog=self.prog) + groups = [*self._groups, self._anonymous] + for group in groups: + if group.options: + desc = group.description or group.name + arggroup = optparser.add_argument_group(desc) + for option in group.options: + n = option.names() + a = option.attrs() + arggroup.add_argument(*n, **a) + file_or_dir_arg = optparser.add_argument(FILE_OR_DIR, nargs="*") + # bash like autocompletion for dirs (appending '/') + # Type ignored because typeshed doesn't know about argcomplete. + file_or_dir_arg.completer = filescompleter # type: ignore + return optparser + + def parse_setoption( + self, + args: Sequence[str | os.PathLike[str]], + option: argparse.Namespace, + namespace: argparse.Namespace | None = None, + ) -> list[str]: + parsedoption = self.parse(args, namespace=namespace) + for name, value in parsedoption.__dict__.items(): + setattr(option, name, value) + return cast(List[str], getattr(parsedoption, FILE_OR_DIR)) + + def parse_known_args( + self, + args: Sequence[str | os.PathLike[str]], + namespace: argparse.Namespace | None = None, + ) -> argparse.Namespace: + """Parse the known arguments at this point. + + :returns: An argparse namespace object. + """ + return self.parse_known_and_unknown_args(args, namespace=namespace)[0] + + def parse_known_and_unknown_args( + self, + args: Sequence[str | os.PathLike[str]], + namespace: argparse.Namespace | None = None, + ) -> tuple[argparse.Namespace, list[str]]: + """Parse the known arguments at this point, and also return the + remaining unknown arguments. + + :returns: + A tuple containing an argparse namespace object for the known + arguments, and a list of the unknown arguments. + """ + optparser = self._getparser() + strargs = [os.fspath(x) for x in args] + return optparser.parse_known_args(strargs, namespace=namespace) + + def addini( + self, + name: str, + help: str, + type: Literal["string", "paths", "pathlist", "args", "linelist", "bool"] + | None = None, + default: Any = NOT_SET, + ) -> None: + """Register an ini-file option. + + :param name: + Name of the ini-variable. + :param type: + Type of the variable. Can be: + + * ``string``: a string + * ``bool``: a boolean + * ``args``: a list of strings, separated as in a shell + * ``linelist``: a list of strings, separated by line breaks + * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell + * ``pathlist``: a list of ``py.path``, separated as in a shell + + For ``paths`` and ``pathlist`` types, they are considered relative to the ini-file. + In case the execution is happening without an ini-file defined, + they will be considered relative to the current working directory (for example with ``--override-ini``). + + .. versionadded:: 7.0 + The ``paths`` variable type. + + .. versionadded:: 8.1 + Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of an ini-file. + + Defaults to ``string`` if ``None`` or not passed. + :param default: + Default value if no ini-file option exists but is queried. + + The value of ini-variables can be retrieved via a call to + :py:func:`config.getini(name) `. + """ + assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool") + if default is NOT_SET: + default = get_ini_default_for_type(type) + + self._inidict[name] = (help, type, default) + self._ininames.append(name) + + +def get_ini_default_for_type( + type: Literal["string", "paths", "pathlist", "args", "linelist", "bool"] | None, +) -> Any: + """ + Used by addini to get the default value for a given ini-option type, when + default is not supplied. + """ + if type is None: + return "" + elif type in ("paths", "pathlist", "args", "linelist"): + return [] + elif type == "bool": + return False + else: + return "" + + +class ArgumentError(Exception): + """Raised if an Argument instance is created with invalid or + inconsistent arguments.""" + + def __init__(self, msg: str, option: Argument | str) -> None: + self.msg = msg + self.option_id = str(option) + + def __str__(self) -> str: + if self.option_id: + return f"option {self.option_id}: {self.msg}" + else: + return self.msg + + +class Argument: + """Class that mimics the necessary behaviour of optparse.Option. + + It's currently a least effort implementation and ignoring choices + and integer prefixes. + + https://docs.python.org/3/library/optparse.html#optparse-standard-option-types + """ + + def __init__(self, *names: str, **attrs: Any) -> None: + """Store params in private vars for use in add_argument.""" + self._attrs = attrs + self._short_opts: list[str] = [] + self._long_opts: list[str] = [] + try: + self.type = attrs["type"] + except KeyError: + pass + try: + # Attribute existence is tested in Config._processopt. + self.default = attrs["default"] + except KeyError: + pass + self._set_opt_strings(names) + dest: str | None = attrs.get("dest") + if dest: + self.dest = dest + elif self._long_opts: + self.dest = self._long_opts[0][2:].replace("-", "_") + else: + try: + self.dest = self._short_opts[0][1:] + except IndexError as e: + self.dest = "???" # Needed for the error repr. + raise ArgumentError("need a long or short option", self) from e + + def names(self) -> list[str]: + return self._short_opts + self._long_opts + + def attrs(self) -> Mapping[str, Any]: + # Update any attributes set by processopt. + attrs = "default dest help".split() + attrs.append(self.dest) + for attr in attrs: + try: + self._attrs[attr] = getattr(self, attr) + except AttributeError: + pass + return self._attrs + + def _set_opt_strings(self, opts: Sequence[str]) -> None: + """Directly from optparse. + + Might not be necessary as this is passed to argparse later on. + """ + for opt in opts: + if len(opt) < 2: + raise ArgumentError( + f"invalid option string {opt!r}: " + "must be at least two characters long", + self, + ) + elif len(opt) == 2: + if not (opt[0] == "-" and opt[1] != "-"): + raise ArgumentError( + f"invalid short option string {opt!r}: " + "must be of the form -x, (x any non-dash char)", + self, + ) + self._short_opts.append(opt) + else: + if not (opt[0:2] == "--" and opt[2] != "-"): + raise ArgumentError( + f"invalid long option string {opt!r}: " + "must start with --, followed by non-dash", + self, + ) + self._long_opts.append(opt) + + def __repr__(self) -> str: + args: list[str] = [] + if self._short_opts: + args += ["_short_opts: " + repr(self._short_opts)] + if self._long_opts: + args += ["_long_opts: " + repr(self._long_opts)] + args += ["dest: " + repr(self.dest)] + if hasattr(self, "type"): + args += ["type: " + repr(self.type)] + if hasattr(self, "default"): + args += ["default: " + repr(self.default)] + return "Argument({})".format(", ".join(args)) + + +class OptionGroup: + """A group of options shown in its own section.""" + + def __init__( + self, + name: str, + description: str = "", + parser: Parser | None = None, + *, + _ispytest: bool = False, + ) -> None: + check_ispytest(_ispytest) + self.name = name + self.description = description + self.options: list[Argument] = [] + self.parser = parser + + def addoption(self, *opts: str, **attrs: Any) -> None: + """Add an option to this group. + + If a shortened version of a long option is specified, it will + be suppressed in the help. ``addoption('--twowords', '--two-words')`` + results in help showing ``--two-words`` only, but ``--twowords`` gets + accepted **and** the automatic destination is in ``args.twowords``. + + :param opts: + Option names, can be short or long options. + :param attrs: + Same attributes as the argparse library's :meth:`add_argument() + ` function accepts. + """ + conflict = set(opts).intersection( + name for opt in self.options for name in opt.names() + ) + if conflict: + raise ValueError(f"option names {conflict} already added") + option = Argument(*opts, **attrs) + self._addoption_instance(option, shortupper=False) + + def _addoption(self, *opts: str, **attrs: Any) -> None: + option = Argument(*opts, **attrs) + self._addoption_instance(option, shortupper=True) + + def _addoption_instance(self, option: Argument, shortupper: bool = False) -> None: + if not shortupper: + for opt in option._short_opts: + if opt[0] == "-" and opt[1].islower(): + raise ValueError("lowercase shortoptions reserved") + if self.parser: + self.parser.processoption(option) + self.options.append(option) + + +class MyOptionParser(argparse.ArgumentParser): + def __init__( + self, + parser: Parser, + extra_info: dict[str, Any] | None = None, + prog: str | None = None, + ) -> None: + self._parser = parser + super().__init__( + prog=prog, + usage=parser._usage, + add_help=False, + formatter_class=DropShorterLongHelpFormatter, + allow_abbrev=False, + fromfile_prefix_chars="@", + ) + # extra_info is a dict of (param -> value) to display if there's + # an usage error to provide more contextual information to the user. + self.extra_info = extra_info if extra_info else {} + + def error(self, message: str) -> NoReturn: + """Transform argparse error message into UsageError.""" + msg = f"{self.prog}: error: {message}" + + if hasattr(self._parser, "_config_source_hint"): + msg = f"{msg} ({self._parser._config_source_hint})" + + raise UsageError(self.format_usage() + msg) + + # Type ignored because typeshed has a very complex type in the superclass. + def parse_args( # type: ignore + self, + args: Sequence[str] | None = None, + namespace: argparse.Namespace | None = None, + ) -> argparse.Namespace: + """Allow splitting of positional arguments.""" + parsed, unrecognized = self.parse_known_args(args, namespace) + if unrecognized: + for arg in unrecognized: + if arg and arg[0] == "-": + lines = [ + "unrecognized arguments: {}".format(" ".join(unrecognized)) + ] + for k, v in sorted(self.extra_info.items()): + lines.append(f" {k}: {v}") + self.error("\n".join(lines)) + getattr(parsed, FILE_OR_DIR).extend(unrecognized) + return parsed + + if sys.version_info < (3, 9): # pragma: no cover + # Backport of https://github.com/python/cpython/pull/14316 so we can + # disable long --argument abbreviations without breaking short flags. + def _parse_optional( + self, arg_string: str + ) -> tuple[argparse.Action | None, str, str | None] | None: + if not arg_string: + return None + if arg_string[0] not in self.prefix_chars: + return None + if arg_string in self._option_string_actions: + action = self._option_string_actions[arg_string] + return action, arg_string, None + if len(arg_string) == 1: + return None + if "=" in arg_string: + option_string, explicit_arg = arg_string.split("=", 1) + if option_string in self._option_string_actions: + action = self._option_string_actions[option_string] + return action, option_string, explicit_arg + if self.allow_abbrev or not arg_string.startswith("--"): + option_tuples = self._get_option_tuples(arg_string) + if len(option_tuples) > 1: + msg = gettext( + "ambiguous option: %(option)s could match %(matches)s" + ) + options = ", ".join(option for _, option, _ in option_tuples) + self.error(msg % {"option": arg_string, "matches": options}) + elif len(option_tuples) == 1: + (option_tuple,) = option_tuples + return option_tuple + if self._negative_number_matcher.match(arg_string): + if not self._has_negative_number_optionals: + return None + if " " in arg_string: + return None + return None, arg_string, None + + +class DropShorterLongHelpFormatter(argparse.HelpFormatter): + """Shorten help for long options that differ only in extra hyphens. + + - Collapse **long** options that are the same except for extra hyphens. + - Shortcut if there are only two options and one of them is a short one. + - Cache result on the action object as this is called at least 2 times. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + # Use more accurate terminal width. + if "width" not in kwargs: + kwargs["width"] = _pytest._io.get_terminal_width() + super().__init__(*args, **kwargs) + + def _format_action_invocation(self, action: argparse.Action) -> str: + orgstr = super()._format_action_invocation(action) + if orgstr and orgstr[0] != "-": # only optional arguments + return orgstr + res: str | None = getattr(action, "_formatted_action_invocation", None) + if res: + return res + options = orgstr.split(", ") + if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2): + # a shortcut for '-h, --help' or '--abc', '-a' + action._formatted_action_invocation = orgstr # type: ignore + return orgstr + return_list = [] + short_long: dict[str, str] = {} + for option in options: + if len(option) == 2 or option[2] == " ": + continue + if not option.startswith("--"): + raise ArgumentError( + f'long optional argument without "--": [{option}]', option + ) + xxoption = option[2:] + shortened = xxoption.replace("-", "") + if shortened not in short_long or len(short_long[shortened]) < len( + xxoption + ): + short_long[shortened] = xxoption + # now short_long has been filled out to the longest with dashes + # **and** we keep the right option ordering from add_argument + for option in options: + if len(option) == 2 or option[2] == " ": + return_list.append(option) + if option[2:] == short_long.get(option.replace("-", "")): + return_list.append(option.replace(" ", "=", 1)) + formatted_action_invocation = ", ".join(return_list) + action._formatted_action_invocation = formatted_action_invocation # type: ignore + return formatted_action_invocation + + def _split_lines(self, text, width): + """Wrap lines after splitting on original newlines. + + This allows to have explicit line breaks in the help text. + """ + import textwrap + + lines = [] + for line in text.splitlines(): + lines.extend(textwrap.wrap(line.strip(), width)) + return lines diff --git a/shared/package-files/74/74db386f628321c1b833584f06f0f4f7e561ec20f394f22b16c70e76f2f7a75a/blob b/shared/package-files/74/74db386f628321c1b833584f06f0f4f7e561ec20f394f22b16c70e76f2f7a75a/blob new file mode 100644 index 0000000000000000000000000000000000000000..13a1074b447e2834c045df8757fc264cad077e03 --- /dev/null +++ b/shared/package-files/74/74db386f628321c1b833584f06f0f4f7e561ec20f394f22b16c70e76f2f7a75a/blob @@ -0,0 +1,988 @@ +""" +Auxiliary functions for f2py2e. + +Copyright 1999 -- 2011 Pearu Peterson all rights reserved. +Copyright 2011 -- present NumPy Developers. +Permission to use, modify, and distribute this software is given under the +terms of the NumPy (BSD style) LICENSE. + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +""" +import pprint +import sys +import re +import types +from functools import reduce +from copy import deepcopy + +from . import __version__ +from . import cfuncs + +__all__ = [ + 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle', + 'getargs2', 'getcallprotoargument', 'getcallstatement', + 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode', + 'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon', + 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote', + 'isallocatable', 'isarray', 'isarrayofstrings', + 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray', + 'iscomplex', + 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn', + 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction', + 'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux', + 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict', + 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace', + 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical', + 'islogicalfunction', 'islong_complex', 'islong_double', + 'islong_doublefunction', 'islong_long', 'islong_longfunction', + 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isrequired', + 'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring', + 'isstringarray', 'isstring_or_stringarray', 'isstringfunction', + 'issubroutine', 'get_f2py_modulename', + 'issubroutine_wrap', 'isthreadsafe', 'isunsigned', 'isunsigned_char', + 'isunsigned_chararray', 'isunsigned_long_long', + 'isunsigned_long_longarray', 'isunsigned_short', + 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess', + 'replace', 'show', 'stripcomma', 'throw_error', 'isattr_value', + 'getuseblocks', 'process_f2cmap_dict' +] + + +f2py_version = __version__.version + + +errmess = sys.stderr.write +show = pprint.pprint + +options = {} +debugoptions = [] +wrapfuncs = 1 + + +def outmess(t): + if options.get('verbose', 1): + sys.stdout.write(t) + + +def debugcapi(var): + return 'capi' in debugoptions + + +def _ischaracter(var): + return 'typespec' in var and var['typespec'] == 'character' and \ + not isexternal(var) + + +def _isstring(var): + return 'typespec' in var and var['typespec'] == 'character' and \ + not isexternal(var) + + +def ischaracter_or_characterarray(var): + return _ischaracter(var) and 'charselector' not in var + + +def ischaracter(var): + return ischaracter_or_characterarray(var) and not isarray(var) + + +def ischaracterarray(var): + return ischaracter_or_characterarray(var) and isarray(var) + + +def isstring_or_stringarray(var): + return _ischaracter(var) and 'charselector' in var + + +def isstring(var): + return isstring_or_stringarray(var) and not isarray(var) + + +def isstringarray(var): + return isstring_or_stringarray(var) and isarray(var) + + +def isarrayofstrings(var): # obsolete? + # leaving out '*' for now so that `character*(*) a(m)` and `character + # a(m,*)` are treated differently. Luckily `character**` is illegal. + return isstringarray(var) and var['dimension'][-1] == '(*)' + + +def isarray(var): + return 'dimension' in var and not isexternal(var) + + +def isscalar(var): + return not (isarray(var) or isstring(var) or isexternal(var)) + + +def iscomplex(var): + return isscalar(var) and \ + var.get('typespec') in ['complex', 'double complex'] + + +def islogical(var): + return isscalar(var) and var.get('typespec') == 'logical' + + +def isinteger(var): + return isscalar(var) and var.get('typespec') == 'integer' + + +def isreal(var): + return isscalar(var) and var.get('typespec') == 'real' + + +def get_kind(var): + try: + return var['kindselector']['*'] + except KeyError: + try: + return var['kindselector']['kind'] + except KeyError: + pass + + +def isint1(var): + return var.get('typespec') == 'integer' \ + and get_kind(var) == '1' and not isarray(var) + + +def islong_long(var): + if not isscalar(var): + return 0 + if var.get('typespec') not in ['integer', 'logical']: + return 0 + return get_kind(var) == '8' + + +def isunsigned_char(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-1' + + +def isunsigned_short(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-2' + + +def isunsigned(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-4' + + +def isunsigned_long_long(var): + if not isscalar(var): + return 0 + if var.get('typespec') != 'integer': + return 0 + return get_kind(var) == '-8' + + +def isdouble(var): + if not isscalar(var): + return 0 + if not var.get('typespec') == 'real': + return 0 + return get_kind(var) == '8' + + +def islong_double(var): + if not isscalar(var): + return 0 + if not var.get('typespec') == 'real': + return 0 + return get_kind(var) == '16' + + +def islong_complex(var): + if not iscomplex(var): + return 0 + return get_kind(var) == '32' + + +def iscomplexarray(var): + return isarray(var) and \ + var.get('typespec') in ['complex', 'double complex'] + + +def isint1array(var): + return isarray(var) and var.get('typespec') == 'integer' \ + and get_kind(var) == '1' + + +def isunsigned_chararray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-1' + + +def isunsigned_shortarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-2' + + +def isunsignedarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-4' + + +def isunsigned_long_longarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '-8' + + +def issigned_chararray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '1' + + +def issigned_shortarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '2' + + +def issigned_array(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '4' + + +def issigned_long_longarray(var): + return isarray(var) and var.get('typespec') in ['integer', 'logical']\ + and get_kind(var) == '8' + + +def isallocatable(var): + return 'attrspec' in var and 'allocatable' in var['attrspec'] + + +def ismutable(var): + return not ('dimension' not in var or isstring(var)) + + +def ismoduleroutine(rout): + return 'modulename' in rout + + +def ismodule(rout): + return 'block' in rout and 'module' == rout['block'] + + +def isfunction(rout): + return 'block' in rout and 'function' == rout['block'] + + +def isfunction_wrap(rout): + if isintent_c(rout): + return 0 + return wrapfuncs and isfunction(rout) and (not isexternal(rout)) + + +def issubroutine(rout): + return 'block' in rout and 'subroutine' == rout['block'] + + +def issubroutine_wrap(rout): + if isintent_c(rout): + return 0 + return issubroutine(rout) and hasassumedshape(rout) + +def isattr_value(var): + return 'value' in var.get('attrspec', []) + + +def hasassumedshape(rout): + if rout.get('hasassumedshape'): + return True + for a in rout['args']: + for d in rout['vars'].get(a, {}).get('dimension', []): + if d == ':': + rout['hasassumedshape'] = True + return True + return False + + +def requiresf90wrapper(rout): + return ismoduleroutine(rout) or hasassumedshape(rout) + + +def isroutine(rout): + return isfunction(rout) or issubroutine(rout) + + +def islogicalfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return islogical(rout['vars'][a]) + return 0 + + +def islong_longfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return islong_long(rout['vars'][a]) + return 0 + + +def islong_doublefunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return islong_double(rout['vars'][a]) + return 0 + + +def iscomplexfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return iscomplex(rout['vars'][a]) + return 0 + + +def iscomplexfunction_warn(rout): + if iscomplexfunction(rout): + outmess("""\ + ************************************************************** + Warning: code with a function returning complex value + may not work correctly with your Fortran compiler. + When using GNU gcc/g77 compilers, codes should work + correctly for callbacks with: + f2py -c -DF2PY_CB_RETURNCOMPLEX + **************************************************************\n""") + return 1 + return 0 + + +def isstringfunction(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return isstring(rout['vars'][a]) + return 0 + + +def hasexternals(rout): + return 'externals' in rout and rout['externals'] + + +def isthreadsafe(rout): + return 'f2pyenhancements' in rout and \ + 'threadsafe' in rout['f2pyenhancements'] + + +def hasvariables(rout): + return 'vars' in rout and rout['vars'] + + +def isoptional(var): + return ('attrspec' in var and 'optional' in var['attrspec'] and + 'required' not in var['attrspec']) and isintent_nothide(var) + + +def isexternal(var): + return 'attrspec' in var and 'external' in var['attrspec'] + + +def getdimension(var): + dimpattern = r"\((.*?)\)" + if 'attrspec' in var.keys(): + if any('dimension' in s for s in var['attrspec']): + return [re.findall(dimpattern, v) for v in var['attrspec']][0] + + +def isrequired(var): + return not isoptional(var) and isintent_nothide(var) + + +def isintent_in(var): + if 'intent' not in var: + return 1 + if 'hide' in var['intent']: + return 0 + if 'inplace' in var['intent']: + return 0 + if 'in' in var['intent']: + return 1 + if 'out' in var['intent']: + return 0 + if 'inout' in var['intent']: + return 0 + if 'outin' in var['intent']: + return 0 + return 1 + + +def isintent_inout(var): + return ('intent' in var and ('inout' in var['intent'] or + 'outin' in var['intent']) and 'in' not in var['intent'] and + 'hide' not in var['intent'] and 'inplace' not in var['intent']) + + +def isintent_out(var): + return 'out' in var.get('intent', []) + + +def isintent_hide(var): + return ('intent' in var and ('hide' in var['intent'] or + ('out' in var['intent'] and 'in' not in var['intent'] and + (not l_or(isintent_inout, isintent_inplace)(var))))) + + +def isintent_nothide(var): + return not isintent_hide(var) + + +def isintent_c(var): + return 'c' in var.get('intent', []) + + +def isintent_cache(var): + return 'cache' in var.get('intent', []) + + +def isintent_copy(var): + return 'copy' in var.get('intent', []) + + +def isintent_overwrite(var): + return 'overwrite' in var.get('intent', []) + + +def isintent_callback(var): + return 'callback' in var.get('intent', []) + + +def isintent_inplace(var): + return 'inplace' in var.get('intent', []) + + +def isintent_aux(var): + return 'aux' in var.get('intent', []) + + +def isintent_aligned4(var): + return 'aligned4' in var.get('intent', []) + + +def isintent_aligned8(var): + return 'aligned8' in var.get('intent', []) + + +def isintent_aligned16(var): + return 'aligned16' in var.get('intent', []) + + +isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT', + isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE', + isintent_cache: 'INTENT_CACHE', + isintent_c: 'INTENT_C', isoptional: 'OPTIONAL', + isintent_inplace: 'INTENT_INPLACE', + isintent_aligned4: 'INTENT_ALIGNED4', + isintent_aligned8: 'INTENT_ALIGNED8', + isintent_aligned16: 'INTENT_ALIGNED16', + } + + +def isprivate(var): + return 'attrspec' in var and 'private' in var['attrspec'] + + +def hasinitvalue(var): + return '=' in var + + +def hasinitvalueasstring(var): + if not hasinitvalue(var): + return 0 + return var['='][0] in ['"', "'"] + + +def hasnote(var): + return 'note' in var + + +def hasresultnote(rout): + if not isfunction(rout): + return 0 + if 'result' in rout: + a = rout['result'] + else: + a = rout['name'] + if a in rout['vars']: + return hasnote(rout['vars'][a]) + return 0 + + +def hascommon(rout): + return 'common' in rout + + +def containscommon(rout): + if hascommon(rout): + return 1 + if hasbody(rout): + for b in rout['body']: + if containscommon(b): + return 1 + return 0 + + +def containsmodule(block): + if ismodule(block): + return 1 + if not hasbody(block): + return 0 + for b in block['body']: + if containsmodule(b): + return 1 + return 0 + + +def hasbody(rout): + return 'body' in rout + + +def hascallstatement(rout): + return getcallstatement(rout) is not None + + +def istrue(var): + return 1 + + +def isfalse(var): + return 0 + + +class F2PYError(Exception): + pass + + +class throw_error: + + def __init__(self, mess): + self.mess = mess + + def __call__(self, var): + mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess) + raise F2PYError(mess) + + +def l_and(*f): + l1, l2 = 'lambda v', [] + for i in range(len(f)): + l1 = '%s,f%d=f[%d]' % (l1, i, i) + l2.append('f%d(v)' % (i)) + return eval('%s:%s' % (l1, ' and '.join(l2))) + + +def l_or(*f): + l1, l2 = 'lambda v', [] + for i in range(len(f)): + l1 = '%s,f%d=f[%d]' % (l1, i, i) + l2.append('f%d(v)' % (i)) + return eval('%s:%s' % (l1, ' or '.join(l2))) + + +def l_not(f): + return eval('lambda v,f=f:not f(v)') + + +def isdummyroutine(rout): + try: + return rout['f2pyenhancements']['fortranname'] == '' + except KeyError: + return 0 + + +def getfortranname(rout): + try: + name = rout['f2pyenhancements']['fortranname'] + if name == '': + raise KeyError + if not name: + errmess('Failed to use fortranname from %s\n' % + (rout['f2pyenhancements'])) + raise KeyError + except KeyError: + name = rout['name'] + return name + + +def getmultilineblock(rout, blockname, comment=1, counter=0): + try: + r = rout['f2pyenhancements'].get(blockname) + except KeyError: + return + if not r: + return + if counter > 0 and isinstance(r, str): + return + if isinstance(r, list): + if counter >= len(r): + return + r = r[counter] + if r[:3] == "'''": + if comment: + r = '\t/* start ' + blockname + \ + ' multiline (' + repr(counter) + ') */\n' + r[3:] + else: + r = r[3:] + if r[-3:] == "'''": + if comment: + r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/' + else: + r = r[:-3] + else: + errmess("%s multiline block should end with `'''`: %s\n" + % (blockname, repr(r))) + return r + + +def getcallstatement(rout): + return getmultilineblock(rout, 'callstatement') + + +def getcallprotoargument(rout, cb_map={}): + r = getmultilineblock(rout, 'callprotoargument', comment=0) + if r: + return r + if hascallstatement(rout): + outmess( + 'warning: callstatement is defined without callprotoargument\n') + return + from .capi_maps import getctype + arg_types, arg_types2 = [], [] + if l_and(isstringfunction, l_not(isfunction_wrap))(rout): + arg_types.extend(['char*', 'size_t']) + for n in rout['args']: + var = rout['vars'][n] + if isintent_callback(var): + continue + if n in cb_map: + ctype = cb_map[n] + '_typedef' + else: + ctype = getctype(var) + if l_and(isintent_c, l_or(isscalar, iscomplex))(var): + pass + elif isstring(var): + pass + else: + if not isattr_value(var): + ctype = ctype + '*' + if ((isstring(var) + or isarrayofstrings(var) # obsolete? + or isstringarray(var))): + arg_types2.append('size_t') + arg_types.append(ctype) + + proto_args = ','.join(arg_types + arg_types2) + if not proto_args: + proto_args = 'void' + return proto_args + + +def getusercode(rout): + return getmultilineblock(rout, 'usercode') + + +def getusercode1(rout): + return getmultilineblock(rout, 'usercode', counter=1) + + +def getpymethoddef(rout): + return getmultilineblock(rout, 'pymethoddef') + + +def getargs(rout): + sortargs, args = [], [] + if 'args' in rout: + args = rout['args'] + if 'sortvars' in rout: + for a in rout['sortvars']: + if a in args: + sortargs.append(a) + for a in args: + if a not in sortargs: + sortargs.append(a) + else: + sortargs = rout['args'] + return args, sortargs + + +def getargs2(rout): + sortargs, args = [], rout.get('args', []) + auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a]) + and a not in args] + args = auxvars + args + if 'sortvars' in rout: + for a in rout['sortvars']: + if a in args: + sortargs.append(a) + for a in args: + if a not in sortargs: + sortargs.append(a) + else: + sortargs = auxvars + rout['args'] + return args, sortargs + + +def getrestdoc(rout): + if 'f2pymultilines' not in rout: + return None + k = None + if rout['block'] == 'python module': + k = rout['block'], rout['name'] + return rout['f2pymultilines'].get(k, None) + + +def gentitle(name): + ln = (80 - len(name) - 6) // 2 + return '/*%s %s %s*/' % (ln * '*', name, ln * '*') + + +def flatlist(lst): + if isinstance(lst, list): + return reduce(lambda x, y, f=flatlist: x + f(y), lst, []) + return [lst] + + +def stripcomma(s): + if s and s[-1] == ',': + return s[:-1] + return s + + +def replace(str, d, defaultsep=''): + if isinstance(d, list): + return [replace(str, _m, defaultsep) for _m in d] + if isinstance(str, list): + return [replace(_m, d, defaultsep) for _m in str] + for k in 2 * list(d.keys()): + if k == 'separatorsfor': + continue + if 'separatorsfor' in d and k in d['separatorsfor']: + sep = d['separatorsfor'][k] + else: + sep = defaultsep + if isinstance(d[k], list): + str = str.replace('#%s#' % (k), sep.join(flatlist(d[k]))) + else: + str = str.replace('#%s#' % (k), d[k]) + return str + + +def dictappend(rd, ar): + if isinstance(ar, list): + for a in ar: + rd = dictappend(rd, a) + return rd + for k in ar.keys(): + if k[0] == '_': + continue + if k in rd: + if isinstance(rd[k], str): + rd[k] = [rd[k]] + if isinstance(rd[k], list): + if isinstance(ar[k], list): + rd[k] = rd[k] + ar[k] + else: + rd[k].append(ar[k]) + elif isinstance(rd[k], dict): + if isinstance(ar[k], dict): + if k == 'separatorsfor': + for k1 in ar[k].keys(): + if k1 not in rd[k]: + rd[k][k1] = ar[k][k1] + else: + rd[k] = dictappend(rd[k], ar[k]) + else: + rd[k] = ar[k] + return rd + + +def applyrules(rules, d, var={}): + ret = {} + if isinstance(rules, list): + for r in rules: + rr = applyrules(r, d, var) + ret = dictappend(ret, rr) + if '_break' in rr: + break + return ret + if '_check' in rules and (not rules['_check'](var)): + return ret + if 'need' in rules: + res = applyrules({'needs': rules['need']}, d, var) + if 'needs' in res: + cfuncs.append_needs(res['needs']) + + for k in rules.keys(): + if k == 'separatorsfor': + ret[k] = rules[k] + continue + if isinstance(rules[k], str): + ret[k] = replace(rules[k], d) + elif isinstance(rules[k], list): + ret[k] = [] + for i in rules[k]: + ar = applyrules({k: i}, d, var) + if k in ar: + ret[k].append(ar[k]) + elif k[0] == '_': + continue + elif isinstance(rules[k], dict): + ret[k] = [] + for k1 in rules[k].keys(): + if isinstance(k1, types.FunctionType) and k1(var): + if isinstance(rules[k][k1], list): + for i in rules[k][k1]: + if isinstance(i, dict): + res = applyrules({'supertext': i}, d, var) + if 'supertext' in res: + i = res['supertext'] + else: + i = '' + ret[k].append(replace(i, d)) + else: + i = rules[k][k1] + if isinstance(i, dict): + res = applyrules({'supertext': i}, d) + if 'supertext' in res: + i = res['supertext'] + else: + i = '' + ret[k].append(replace(i, d)) + else: + errmess('applyrules: ignoring rule %s.\n' % repr(rules[k])) + if isinstance(ret[k], list): + if len(ret[k]) == 1: + ret[k] = ret[k][0] + if ret[k] == []: + del ret[k] + return ret + +_f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P[\w_]+)', + re.I).match +_f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P[\w_]*?' + r'__user__[\w_]*)', re.I).match + +def get_f2py_modulename(source): + name = None + with open(source) as f: + for line in f: + m = _f2py_module_name_match(line) + if m: + if _f2py_user_module_name_match(line): # skip *__user__* names + continue + name = m.group('name') + break + return name + +def getuseblocks(pymod): + all_uses = [] + for inner in pymod['body']: + for modblock in inner['body']: + if modblock.get('use'): + all_uses.extend([x for x in modblock.get("use").keys() if "__" not in x]) + return all_uses + +def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose = False): + """ + Update the Fortran-to-C type mapping dictionary with new mappings and + return a list of successfully mapped C types. + + This function integrates a new mapping dictionary into an existing + Fortran-to-C type mapping dictionary. It ensures that all keys are in + lowercase and validates new entries against a given C-to-Python mapping + dictionary. Redefinitions and invalid entries are reported with a warning. + + Parameters + ---------- + f2cmap_all : dict + The existing Fortran-to-C type mapping dictionary that will be updated. + It should be a dictionary of dictionaries where the main keys represent + Fortran types and the nested dictionaries map Fortran type specifiers + to corresponding C types. + + new_map : dict + A dictionary containing new type mappings to be added to `f2cmap_all`. + The structure should be similar to `f2cmap_all`, with keys representing + Fortran types and values being dictionaries of type specifiers and their + C type equivalents. + + c2py_map : dict + A dictionary used for validating the C types in `new_map`. It maps C + types to corresponding Python types and is used to ensure that the C + types specified in `new_map` are valid. + + verbose : boolean + A flag used to provide information about the types mapped + + Returns + ------- + tuple of (dict, list) + The updated Fortran-to-C type mapping dictionary and a list of + successfully mapped C types. + """ + f2cmap_mapped = [] + + new_map_lower = {} + for k, d1 in new_map.items(): + d1_lower = {k1.lower(): v1 for k1, v1 in d1.items()} + new_map_lower[k.lower()] = d1_lower + + for k, d1 in new_map_lower.items(): + if k not in f2cmap_all: + f2cmap_all[k] = {} + + for k1, v1 in d1.items(): + if v1 in c2py_map: + if k1 in f2cmap_all[k]: + outmess( + "\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n" + % (k, k1, f2cmap_all[k][k1], v1) + ) + f2cmap_all[k][k1] = v1 + if verbose: + outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, v1)) + f2cmap_mapped.append(v1) + else: + if verbose: + errmess( + "\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n" + % (k, k1, v1, v1, list(c2py_map.keys())) + ) + + return f2cmap_all, f2cmap_mapped diff --git a/shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/blob b/shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/blob new file mode 100644 index 0000000000000000000000000000000000000000..badf1f7b0b650ee78ab27aa20a0e1afcff49251c --- /dev/null +++ b/shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/blob @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor bartlett_window(int64_t window_length, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & bartlett_window_out(int64_t window_length, at::Tensor & out); +TORCH_API at::Tensor bartlett_window(int64_t window_length, bool periodic, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & bartlett_window_periodic_out(int64_t window_length, bool periodic, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/blob b/shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/blob new file mode 100644 index 0000000000000000000000000000000000000000..505f50f9c6ecc281233df14b4034b75901004acb Binary files /dev/null and b/shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/blob differ diff --git a/shared/package-files/74/74e2d8d3c19397adbd9941224533e5fe224ed877384e632ee23fe65f7851fd38/blob b/shared/package-files/74/74e2d8d3c19397adbd9941224533e5fe224ed877384e632ee23fe65f7851fd38/blob new file mode 100644 index 0000000000000000000000000000000000000000..37874557bb2d137e985714ec722e6e041e6816bd --- /dev/null +++ b/shared/package-files/74/74e2d8d3c19397adbd9941224533e5fe224ed877384e632ee23fe65f7851fd38/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor special_modified_bessel_k1(const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_k1_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_k1_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/74/74ed196010d4867d7f963ce3724114d8b52f26ee4bb73bf988c1c08dc85343f8/blob b/shared/package-files/74/74ed196010d4867d7f963ce3724114d8b52f26ee4bb73bf988c1c08dc85343f8/blob new file mode 100644 index 0000000000000000000000000000000000000000..c70fad137b3f9689203b0686550a57b83cdd5f0d --- /dev/null +++ b/shared/package-files/74/74ed196010d4867d7f963ce3724114d8b52f26ee4bb73bf988c1c08dc85343f8/blob @@ -0,0 +1,14 @@ +*** Tue, 21 Jun 2016 11:30:21 *** +VECM MODEL STATISTICS +sample range: [1973 Q2, 1998 Q4], T = 103 + +Log Likelihood: 7.940801e+02 +Determinant (Cov): 5.929254e-10 + +Covariance: 2.303948e-05 -1.480276e-06 + -1.480276e-06 2.583030e-05 + +Correlation: 1.000000e+00 -6.067946e-02 + -6.067946e-02 1.000000e+00 + + diff --git a/shared/package-files/74/74ed1bf4c7053d42d37e786969414fcb4dfc648f22430a361720ed8f877d3293/blob b/shared/package-files/74/74ed1bf4c7053d42d37e786969414fcb4dfc648f22430a361720ed8f877d3293/blob new file mode 100644 index 0000000000000000000000000000000000000000..e9f19c145c867395ceb622375fe917bb1f736f5e --- /dev/null +++ b/shared/package-files/74/74ed1bf4c7053d42d37e786969414fcb4dfc648f22430a361720ed8f877d3293/blob @@ -0,0 +1,384 @@ +import builtins +import keyword +import re +import time + +from idlelib.config import idleConf +from idlelib.delegator import Delegator + +DEBUG = False + + +def any(name, alternates): + "Return a named group pattern matching list of alternates." + return "(?P<%s>" % name + "|".join(alternates) + ")" + + +def make_pat(): + kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" + match_softkw = ( + r"^[ \t]*" + # at beginning of line + possible indentation + r"(?Pmatch)\b" + + r"(?![ \t]*(?:" + "|".join([ # not followed by ... + r"[:,;=^&|@~)\]}]", # a character which means it can't be a + # pattern-matching statement + r"\b(?:" + r"|".join(keyword.kwlist) + r")\b", # a keyword + ]) + + r"))" + ) + case_default = ( + r"^[ \t]*" + # at beginning of line + possible indentation + r"(?Pcase)" + + r"[ \t]+(?P_\b)" + ) + case_softkw_and_pattern = ( + r"^[ \t]*" + # at beginning of line + possible indentation + r"(?Pcase)\b" + + r"(?![ \t]*(?:" + "|".join([ # not followed by ... + r"_\b", # a lone underscore + r"[:,;=^&|@~)\]}]", # a character which means it can't be a + # pattern-matching case + r"\b(?:" + r"|".join(keyword.kwlist) + r")\b", # a keyword + ]) + + r"))" + ) + builtinlist = [str(name) for name in dir(builtins) + if not name.startswith('_') and + name not in keyword.kwlist] + builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" + comment = any("COMMENT", [r"#[^\n]*"]) + stringprefix = r"(?i:r|u|f|fr|rf|b|br|rb)?" + sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?" + dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?' + sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" + dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' + string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) + prog = re.compile("|".join([ + builtin, comment, string, kw, + match_softkw, case_default, + case_softkw_and_pattern, + any("SYNC", [r"\n"]), + ]), + re.DOTALL | re.MULTILINE) + return prog + + +prog = make_pat() +idprog = re.compile(r"\s+(\w+)") +prog_group_name_to_tag = { + "MATCH_SOFTKW": "KEYWORD", + "CASE_SOFTKW": "KEYWORD", + "CASE_DEFAULT_UNDERSCORE": "KEYWORD", + "CASE_SOFTKW2": "KEYWORD", +} + + +def matched_named_groups(re_match): + "Get only the non-empty named groups from an re.Match object." + return ((k, v) for (k, v) in re_match.groupdict().items() if v) + + +def color_config(text): + """Set color options of Text widget. + + If ColorDelegator is used, this should be called first. + """ + # Called from htest, TextFrame, Editor, and Turtledemo. + # Not automatic because ColorDelegator does not know 'text'. + theme = idleConf.CurrentTheme() + normal_colors = idleConf.GetHighlight(theme, 'normal') + cursor_color = idleConf.GetHighlight(theme, 'cursor')['foreground'] + select_colors = idleConf.GetHighlight(theme, 'hilite') + text.config( + foreground=normal_colors['foreground'], + background=normal_colors['background'], + insertbackground=cursor_color, + selectforeground=select_colors['foreground'], + selectbackground=select_colors['background'], + inactiveselectbackground=select_colors['background'], # new in 8.5 + ) + + +class ColorDelegator(Delegator): + """Delegator for syntax highlighting (text coloring). + + Instance variables: + delegate: Delegator below this one in the stack, meaning the + one this one delegates to. + + Used to track state: + after_id: Identifier for scheduled after event, which is a + timer for colorizing the text. + allow_colorizing: Boolean toggle for applying colorizing. + colorizing: Boolean flag when colorizing is in process. + stop_colorizing: Boolean flag to end an active colorizing + process. + """ + + def __init__(self): + Delegator.__init__(self) + self.init_state() + self.prog = prog + self.idprog = idprog + self.LoadTagDefs() + + def init_state(self): + "Initialize variables that track colorizing state." + self.after_id = None + self.allow_colorizing = True + self.stop_colorizing = False + self.colorizing = False + + def setdelegate(self, delegate): + """Set the delegate for this instance. + + A delegate is an instance of a Delegator class and each + delegate points to the next delegator in the stack. This + allows multiple delegators to be chained together for a + widget. The bottom delegate for a colorizer is a Text + widget. + + If there is a delegate, also start the colorizing process. + """ + if self.delegate is not None: + self.unbind("<>") + Delegator.setdelegate(self, delegate) + if delegate is not None: + self.config_colors() + self.bind("<>", self.toggle_colorize_event) + self.notify_range("1.0", "end") + else: + # No delegate - stop any colorizing. + self.stop_colorizing = True + self.allow_colorizing = False + + def config_colors(self): + "Configure text widget tags with colors from tagdefs." + for tag, cnf in self.tagdefs.items(): + self.tag_configure(tag, **cnf) + self.tag_raise('sel') + + def LoadTagDefs(self): + "Create dictionary of tag names to text colors." + theme = idleConf.CurrentTheme() + self.tagdefs = { + "COMMENT": idleConf.GetHighlight(theme, "comment"), + "KEYWORD": idleConf.GetHighlight(theme, "keyword"), + "BUILTIN": idleConf.GetHighlight(theme, "builtin"), + "STRING": idleConf.GetHighlight(theme, "string"), + "DEFINITION": idleConf.GetHighlight(theme, "definition"), + "SYNC": {'background': None, 'foreground': None}, + "TODO": {'background': None, 'foreground': None}, + "ERROR": idleConf.GetHighlight(theme, "error"), + # "hit" is used by ReplaceDialog to mark matches. It shouldn't be changed by Colorizer, but + # that currently isn't technically possible. This should be moved elsewhere in the future + # when fixing the "hit" tag's visibility, or when the replace dialog is replaced with a + # non-modal alternative. + "hit": idleConf.GetHighlight(theme, "hit"), + } + if DEBUG: print('tagdefs', self.tagdefs) + + def insert(self, index, chars, tags=None): + "Insert chars into widget at index and mark for colorizing." + index = self.index(index) + self.delegate.insert(index, chars, tags) + self.notify_range(index, index + "+%dc" % len(chars)) + + def delete(self, index1, index2=None): + "Delete chars between indexes and mark for colorizing." + index1 = self.index(index1) + self.delegate.delete(index1, index2) + self.notify_range(index1) + + def notify_range(self, index1, index2=None): + "Mark text changes for processing and restart colorizing, if active." + self.tag_add("TODO", index1, index2) + if self.after_id: + if DEBUG: print("colorizing already scheduled") + return + if self.colorizing: + self.stop_colorizing = True + if DEBUG: print("stop colorizing") + if self.allow_colorizing: + if DEBUG: print("schedule colorizing") + self.after_id = self.after(1, self.recolorize) + return + + def close(self): + if self.after_id: + after_id = self.after_id + self.after_id = None + if DEBUG: print("cancel scheduled recolorizer") + self.after_cancel(after_id) + self.allow_colorizing = False + self.stop_colorizing = True + + def toggle_colorize_event(self, event=None): + """Toggle colorizing on and off. + + When toggling off, if colorizing is scheduled or is in + process, it will be cancelled and/or stopped. + + When toggling on, colorizing will be scheduled. + """ + if self.after_id: + after_id = self.after_id + self.after_id = None + if DEBUG: print("cancel scheduled recolorizer") + self.after_cancel(after_id) + if self.allow_colorizing and self.colorizing: + if DEBUG: print("stop colorizing") + self.stop_colorizing = True + self.allow_colorizing = not self.allow_colorizing + if self.allow_colorizing and not self.colorizing: + self.after_id = self.after(1, self.recolorize) + if DEBUG: + print("auto colorizing turned", + "on" if self.allow_colorizing else "off") + return "break" + + def recolorize(self): + """Timer event (every 1ms) to colorize text. + + Colorizing is only attempted when the text widget exists, + when colorizing is toggled on, and when the colorizing + process is not already running. + + After colorizing is complete, some cleanup is done to + make sure that all the text has been colorized. + """ + self.after_id = None + if not self.delegate: + if DEBUG: print("no delegate") + return + if not self.allow_colorizing: + if DEBUG: print("auto colorizing is off") + return + if self.colorizing: + if DEBUG: print("already colorizing") + return + try: + self.stop_colorizing = False + self.colorizing = True + if DEBUG: print("colorizing...") + t0 = time.perf_counter() + self.recolorize_main() + t1 = time.perf_counter() + if DEBUG: print("%.3f seconds" % (t1-t0)) + finally: + self.colorizing = False + if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): + if DEBUG: print("reschedule colorizing") + self.after_id = self.after(1, self.recolorize) + + def recolorize_main(self): + "Evaluate text and apply colorizing tags." + next = "1.0" + while todo_tag_range := self.tag_nextrange("TODO", next): + self.tag_remove("SYNC", todo_tag_range[0], todo_tag_range[1]) + sync_tag_range = self.tag_prevrange("SYNC", todo_tag_range[0]) + head = sync_tag_range[1] if sync_tag_range else "1.0" + + chars = "" + next = head + lines_to_get = 1 + ok = False + while not ok: + mark = next + next = self.index(mark + "+%d lines linestart" % + lines_to_get) + lines_to_get = min(lines_to_get * 2, 100) + ok = "SYNC" in self.tag_names(next + "-1c") + line = self.get(mark, next) + ##print head, "get", mark, next, "->", repr(line) + if not line: + return + for tag in self.tagdefs: + self.tag_remove(tag, mark, next) + chars += line + self._add_tags_in_section(chars, head) + if "SYNC" in self.tag_names(next + "-1c"): + head = next + chars = "" + else: + ok = False + if not ok: + # We're in an inconsistent state, and the call to + # update may tell us to stop. It may also change + # the correct value for "next" (since this is a + # line.col string, not a true mark). So leave a + # crumb telling the next invocation to resume here + # in case update tells us to leave. + self.tag_add("TODO", next) + self.update() + if self.stop_colorizing: + if DEBUG: print("colorizing stopped") + return + + def _add_tag(self, start, end, head, matched_group_name): + """Add a tag to a given range in the text widget. + + This is a utility function, receiving the range as `start` and + `end` positions, each of which is a number of characters + relative to the given `head` index in the text widget. + + The tag to add is determined by `matched_group_name`, which is + the name of a regular expression "named group" as matched by + by the relevant highlighting regexps. + """ + tag = prog_group_name_to_tag.get(matched_group_name, + matched_group_name) + self.tag_add(tag, + f"{head}+{start:d}c", + f"{head}+{end:d}c") + + def _add_tags_in_section(self, chars, head): + """Parse and add highlighting tags to a given part of the text. + + `chars` is a string with the text to parse and to which + highlighting is to be applied. + + `head` is the index in the text widget where the text is found. + """ + for m in self.prog.finditer(chars): + for name, matched_text in matched_named_groups(m): + a, b = m.span(name) + self._add_tag(a, b, head, name) + if matched_text in ("def", "class"): + if m1 := self.idprog.match(chars, b): + a, b = m1.span(1) + self._add_tag(a, b, head, "DEFINITION") + + def removecolors(self): + "Remove all colorizing tags." + for tag in self.tagdefs: + self.tag_remove(tag, "1.0", "end") + + +def _color_delegator(parent): # htest # + from tkinter import Toplevel, Text + from idlelib.idle_test.test_colorizer import source + from idlelib.percolator import Percolator + + top = Toplevel(parent) + top.title("Test ColorDelegator") + x, y = map(int, parent.geometry().split('+')[1:]) + top.geometry("700x550+%d+%d" % (x + 20, y + 175)) + + text = Text(top, background="white") + text.pack(expand=1, fill="both") + text.insert("insert", source) + text.focus_set() + + color_config(text) + p = Percolator(text) + d = ColorDelegator() + p.insertfilter(d) + + +if __name__ == "__main__": + from unittest import main + main('idlelib.idle_test.test_colorizer', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(_color_delegator) diff --git a/shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob b/shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob new file mode 100644 index 0000000000000000000000000000000000000000..47d99ccd671926aa1bdeaf5487f2f2bb1a384c37 --- /dev/null +++ b/shared/package-files/74/74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74f228e0ec0e77185c65426ce5789f97edc5f0c8ac4e864aae98922d988c150d +size 208346 diff --git a/shared/package-files/74/74f50ae63bf42c71641bdc954f8cf4faf960782063c74ef0d05c2be39b62fb76/blob b/shared/package-files/74/74f50ae63bf42c71641bdc954f8cf4faf960782063c74ef0d05c2be39b62fb76/blob new file mode 100644 index 0000000000000000000000000000000000000000..2f0b5bba7d5a68ebdeb3dd6e152c3925dc43b843 --- /dev/null +++ b/shared/package-files/74/74f50ae63bf42c71641bdc954f8cf4faf960782063c74ef0d05c2be39b62fb76/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options={}); +TORCH_API at::Tensor empty_strided(at::IntArrayRef size, at::IntArrayRef stride, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options={}); +TORCH_API at::Tensor empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/74/74f6ebb9d073af2e826b07d157521b6c5ed21c6bd26baa038c625ac842e71732/blob b/shared/package-files/74/74f6ebb9d073af2e826b07d157521b6c5ed21c6bd26baa038c625ac842e71732/blob new file mode 100644 index 0000000000000000000000000000000000000000..6938e6f9a980dcfdd5fb5464d07dc300ccbd8068 --- /dev/null +++ b/shared/package-files/74/74f6ebb9d073af2e826b07d157521b6c5ed21c6bd26baa038c625ac842e71732/blob @@ -0,0 +1,7 @@ +from typing import Optional, Union + +from django.contrib.sites.models import Site +from django.contrib.sites.requests import RequestSite +from django.http.request import HttpRequest + +def get_current_site(request: Optional[HttpRequest]) -> Union[Site, RequestSite]: ... diff --git a/shared/package-files/74/74f937df87bb310c25ef5f9abcdc911016155ae15341c54a7e5b65461ae5469c/blob b/shared/package-files/74/74f937df87bb310c25ef5f9abcdc911016155ae15341c54a7e5b65461ae5469c/blob new file mode 100644 index 0000000000000000000000000000000000000000..f2acf6cbbd653929e826366aec83f443d11c66e7 Binary files /dev/null and b/shared/package-files/74/74f937df87bb310c25ef5f9abcdc911016155ae15341c54a7e5b65461ae5469c/blob differ diff --git a/shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/blob b/shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/blob new file mode 100644 index 0000000000000000000000000000000000000000..13794a49fb9aeec975f9ff6a3a07d9f38355dc88 --- /dev/null +++ b/shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _ctc_loss_backward(const at::Tensor & grad, const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, const at::Tensor & neg_log_likelihood, const at::Tensor & log_alpha, int64_t blank, bool zero_infinity=false); +TORCH_API at::Tensor _ctc_loss_backward(const at::Tensor & grad, const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, const at::Tensor & neg_log_likelihood, const at::Tensor & log_alpha, int64_t blank, bool zero_infinity=false); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/74/74fb5a1e5668b133d0182c5320a46ae4e8f30aa24f575a3a182210b22e5aa05c/blob b/shared/package-files/74/74fb5a1e5668b133d0182c5320a46ae4e8f30aa24f575a3a182210b22e5aa05c/blob new file mode 100644 index 0000000000000000000000000000000000000000..17f14444abd14a03de30f57d3be7254f51a957f9 --- /dev/null +++ b/shared/package-files/74/74fb5a1e5668b133d0182c5320a46ae4e8f30aa24f575a3a182210b22e5aa05c/blob @@ -0,0 +1,379 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +static constexpr int64_t kILP = 4; +static constexpr int64_t kChunkSize = 65536; +static constexpr int64_t kBlockSize = 512; + +// TODO(crcrpar): Add `n>5` for `low prec params & their higher prec copy` +// TensorListMetadata has to be < 4KB - the limit for kernel launch argument +static constexpr int depth_to_max_tensors[5] = {110, 64, 48, 36, 30}; +static constexpr int depth_to_max_blocks[5] = {320, 320, 320, 320, 320}; +static constexpr int depth_to_max_tensors_scalarlist[5] = {96, 64, 48, 36, 30}; +static constexpr int depth_to_max_tensors_scalarlist_of_complex_double[2] = { + 72, + 60}; + +template +__device__ __forceinline__ bool is_aligned(T* p) { + return ((uint64_t)p) % (kILP * sizeof(T)) == 0; +} + +template +__device__ __forceinline__ void load_store( + T* dst, + T* src, + int64_t dst_offset, + int64_t src_offset) { + using LT = at::native::memory::aligned_vector; + ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; +} + +template +struct TensorListMetadata { + const void* addresses[n][depth_to_max_tensors[n - 1]]; + int64_t numel_for_tensor[depth_to_max_tensors[n - 1]]; + unsigned char block_to_tensor[depth_to_max_blocks[n - 1]]; + int block_to_chunk[depth_to_max_blocks[n - 1]]; + int start_tensor_this_launch; +}; + +template +struct TensorListScalarListMetadata { + const void* addresses[n][depth_to_max_tensors_scalarlist[n - 1]]; + int64_t numel_for_tensor[depth_to_max_tensors_scalarlist[n - 1]]; + scalar_vals_t scalar_vals[depth_to_max_tensors_scalarlist[n - 1]]; + unsigned char block_to_tensor[depth_to_max_blocks[n - 1]]; + int block_to_chunk[depth_to_max_blocks[n - 1]]; +}; + +// note(mkozuki): `n` of 1&2 violate the limit of cuda kernel argument size of +// 4kb with `c10::complex` +template <> +struct TensorListScalarListMetadata, 1> { + const void* addresses[1] + [depth_to_max_tensors_scalarlist_of_complex_double[0]]; + int64_t + numel_for_tensor[depth_to_max_tensors_scalarlist_of_complex_double[0]]; + c10::complex + scalar_vals[depth_to_max_tensors_scalarlist_of_complex_double[0]]; + unsigned char block_to_tensor[depth_to_max_blocks[1 - 1]]; + int block_to_chunk[depth_to_max_blocks[1 - 1]]; +}; + +template <> +struct TensorListScalarListMetadata, 2> { + const void* addresses[2] + [depth_to_max_tensors_scalarlist_of_complex_double[1]]; + int64_t + numel_for_tensor[depth_to_max_tensors_scalarlist_of_complex_double[1]]; + c10::complex + scalar_vals[depth_to_max_tensors_scalarlist_of_complex_double[1]]; + unsigned char block_to_tensor[depth_to_max_blocks[2 - 1]]; + int block_to_chunk[depth_to_max_blocks[2 - 1]]; +}; + +// NOTE(crcrpar): This is a conservative resolution to handle `state_steps` +// whose each element is `at::Tensor` of 1 element representing the number of +// `step`s called so far. +template +struct FusedOptimizerTensorListMetadata { + const void* addresses[n][depth_to_max_tensors[n - 1]]; + int64_t numel_for_tensor[depth_to_max_tensors[n - 1]]; + const void* state_steps_addresses[depth_to_max_tensors_scalarlist[n - 1]]; + unsigned char block_to_tensor[depth_to_max_blocks[n - 1]]; + int block_to_chunk[depth_to_max_blocks[n - 1]]; + int start_tensor_this_launch; +}; + +template +C10_LAUNCH_BOUNDS_1(kBlockSize) +__global__ void multi_tensor_apply_kernel( + T tensorListMeta, + U callable, + ArgTypes... args) { + // Hand the chunk information to the user-supplied functor to process however + // it likes. + callable(kChunkSize, tensorListMeta, args...); +} + +} // namespace + +// multi_tensor_apply enables horizontal fusion across lists of tensors. +// For example, whereas you once had a for-loop of a + b = c, where a, b, +// and c are individual tensors in lists as, bs, and cs, you can now with +// fewer kernel launches compute as + bs = cs. +// +// You can also imagine bs to be a scalar list vs a tensor list. +// +// The function below takes in tensor lists, scalars, and a callable and +// chunks up the computation to launch as few kernels as possible by iterating +// through every "chunk" in every tensor (thus the nested for loops). In the +// simplest case, everything gets bundled into just one kernel launch, but +// due to blocksize constraints, we may need to launch multiple kernels. +// Each kernel launch is defined by one tensorListMeta construct, which we +// use to track and reset the necessary metadata for each launch. +template +void multi_tensor_apply( + std::vector>& tensor_lists, + at::ArrayRef scalars, + T callable, + ArgTypes... args) { + TORCH_CHECK( + tensor_lists.size() == depth, + "Number of tensor lists has to match the depth."); + const size_t n_tensors = tensor_lists[0].size(); + using scalar_vals_t = typename T::opmath_t; + TensorListScalarListMetadata tensorListMeta; + + int loc_block_info = 0; + int loc_tensor_info = 0; + for (size_t t = 0; t < n_tensors; t++) { + // short-circuit to avoid adding empty tensors to tensorListMeta + if (tensor_lists[0][t].numel() == 0) { + continue; + } + tensorListMeta.scalar_vals[loc_tensor_info] = scalars[t].to(); + tensorListMeta.numel_for_tensor[loc_tensor_info] = + tensor_lists[0][t].numel(); + for (int d = 0; d < depth; d++) { + tensorListMeta.addresses[d][loc_tensor_info] = + tensor_lists[d][t].const_data_ptr(); + } + loc_tensor_info++; + + // now we enter [chunking territory]. + // we will launch a kernel when EITHER the blocks get filled up OR + // the tensors get filled up. There will always be at least one block + // per tensor since the zero-sized ones will not enter the loop, so + // the nested forloop within represents iterating through the chunks + // of a single tensor. + const auto numel = tensor_lists[0][t].numel(); + const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0); + for (auto chunk = 0; chunk < chunks; chunk++) { + tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1; + tensorListMeta.block_to_chunk[loc_block_info] = chunk; + loc_block_info++; + + // a tensor is not considered full unless all its chunks have been + // processed + const bool tensors_full = + (loc_tensor_info == depth_to_max_tensors_scalarlist[depth - 1] && + chunk == chunks - 1); + const bool blocks_full = + (loc_block_info == depth_to_max_blocks[depth - 1]); + + if (tensors_full || blocks_full) { + multi_tensor_apply_kernel<<< + loc_block_info, + kBlockSize, + 0, + at::cuda::getCurrentCUDAStream()>>>( + tensorListMeta, callable, args...); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + // Reset. + loc_block_info = 0; + // all chunks have already been handled in the kernel + if (chunk == chunks - 1) { + loc_tensor_info = 0; + } else { // blocks were full and tensor chunks remain + tensorListMeta.numel_for_tensor[0] = + tensorListMeta.numel_for_tensor[loc_tensor_info - 1]; + tensorListMeta.scalar_vals[0] = + tensorListMeta.scalar_vals[loc_tensor_info - 1]; + for (int d = 0; d < depth; d++) { + tensorListMeta.addresses[d][0] = + tensorListMeta.addresses[d][loc_tensor_info - 1]; + } + loc_tensor_info = 1; + } + } + } + } + + // note: [finishing what we started] + // if there's remaining work to be done but the tensors/blocks aren't full + // yet we are at the end, submit the kernel to do the work! + if (loc_block_info != 0) { + multi_tensor_apply_kernel<<< + loc_block_info, + kBlockSize, + 0, + at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } +} + +template +void multi_tensor_apply( + std::vector>& tensor_lists, + T callable, + ArgTypes... args) { + TORCH_CHECK( + tensor_lists.size() == depth, + "Number of tensor lists has to match the depth."); + const size_t n_tensors = tensor_lists[0].size(); + TensorListMetadata tensorListMeta; + tensorListMeta.start_tensor_this_launch = 0; + + int loc_block_info = 0; + int loc_tensor_info = 0; + for (size_t t = 0; t < n_tensors; t++) { + // short-circuit to avoid adding empty tensors to tensorListMeta + if (tensor_lists[0][t].numel() == 0) { + continue; + } + tensorListMeta.numel_for_tensor[loc_tensor_info] = + tensor_lists[0][t].numel(); + for (int d = 0; d < depth; d++) { + tensorListMeta.addresses[d][loc_tensor_info] = + tensor_lists[d][t].const_data_ptr(); + } + loc_tensor_info++; + + // see note: [chunking territory]. + const auto numel = tensor_lists[0][t].numel(); + const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0); + for (auto chunk = 0; chunk < chunks; chunk++) { + tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1; + tensorListMeta.block_to_chunk[loc_block_info] = chunk; + loc_block_info++; + + const bool tensors_full = + (loc_tensor_info == depth_to_max_tensors[depth - 1] && + chunk == chunks - 1); + const bool blocks_full = + (loc_block_info == depth_to_max_blocks[depth - 1]); + + if (tensors_full || blocks_full) { + multi_tensor_apply_kernel<<< + loc_block_info, + kBlockSize, + 0, + at::cuda::getCurrentCUDAStream()>>>( + tensorListMeta, callable, args...); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + // Reset. + loc_block_info = 0; + if (chunk == chunks - 1) { + loc_tensor_info = 0; + tensorListMeta.start_tensor_this_launch = t + 1; + } else { + tensorListMeta.numel_for_tensor[0] = + tensorListMeta.numel_for_tensor[loc_tensor_info - 1]; + for (int d = 0; d < depth; d++) { + tensorListMeta.addresses[d][0] = + tensorListMeta.addresses[d][loc_tensor_info - 1]; + } + loc_tensor_info = 1; + tensorListMeta.start_tensor_this_launch = t; + } + } + } + } + + // see note: [finishing what we started] + if (loc_block_info != 0) { + multi_tensor_apply_kernel<<< + loc_block_info, + kBlockSize, + 0, + at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } +} + +template +void multi_tensor_apply_for_fused_optimizer( + std::vector>& tensor_lists, + at::TensorList state_steps, + T callable, + ArgTypes... args) { + TORCH_CHECK( + tensor_lists.size() == depth, + "Number of tensor lists has to match the depth"); + const auto num_tensors = tensor_lists[0].size(); + FusedOptimizerTensorListMetadata tensorListMeta; + + int loc_block_info = 0; + int loc_tensor_info = 0; + for (const auto& tensor_index : c10::irange(num_tensors)) { + // short-circuit to avoid adding empty tensors to tensorListMeta + if (tensor_lists[0][tensor_index].numel() == 0) { + continue; + } + tensorListMeta.state_steps_addresses[loc_tensor_info] = + state_steps[tensor_index].const_data_ptr(); + tensorListMeta.numel_for_tensor[loc_tensor_info] = + tensor_lists[0][tensor_index].numel(); + for (const auto& d : c10::irange(depth)) { + tensorListMeta.addresses[d][loc_tensor_info] = + tensor_lists[d][tensor_index].const_data_ptr(); + } + loc_tensor_info++; + + // see above note: [chunking territory] + const auto numel = tensor_lists[0][tensor_index].numel(); + const auto chunks = numel / kChunkSize + (numel % kChunkSize != 0); + TORCH_CHECK(chunks > -1); + for (const auto& chunk : c10::irange(chunks)) { + tensorListMeta.block_to_tensor[loc_block_info] = loc_tensor_info - 1; + tensorListMeta.block_to_chunk[loc_block_info] = chunk; + loc_block_info++; + + const auto tensor_full = + (loc_tensor_info == depth_to_max_tensors[depth - 1] && + chunk == chunks - 1); + const auto blocks_full = loc_block_info == depth_to_max_blocks[depth - 1]; + + if (tensor_full || blocks_full) { + multi_tensor_apply_kernel<<< + loc_block_info, + kBlockSize, + 0, + at::cuda::getCurrentCUDAStream()>>>( + tensorListMeta, callable, args...); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + // Reset. + loc_block_info = 0; + if (chunk == chunks - 1) { + loc_tensor_info = 0; + } else { + tensorListMeta.numel_for_tensor[0] = + tensorListMeta.numel_for_tensor[loc_tensor_info - 1]; + tensorListMeta.state_steps_addresses[0] = + tensorListMeta.state_steps_addresses[loc_tensor_info - 1]; + for (const auto& d : c10::irange(depth)) { + tensorListMeta.addresses[d][0] = + tensorListMeta.addresses[d][loc_tensor_info - 1]; + } + loc_tensor_info = 1; + } + } + } + } + + // see above note: [finishing what we've started] + if (loc_block_info != 0) { + multi_tensor_apply_kernel<<< + loc_block_info, + kBlockSize, + 0, + at::cuda::getCurrentCUDAStream()>>>(tensorListMeta, callable, args...); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } +} + +} // namespace at::native diff --git a/shared/package-files/74/74fe34d648c99426271d3dc899c19024a79fd139a0c353fad1b920824b84463f/blob b/shared/package-files/74/74fe34d648c99426271d3dc899c19024a79fd139a0c353fad1b920824b84463f/blob new file mode 100644 index 0000000000000000000000000000000000000000..ac1bdf8d3b1d846c6cd02724fa1fd07f0208c40f --- /dev/null +++ b/shared/package-files/74/74fe34d648c99426271d3dc899c19024a79fd139a0c353fad1b920824b84463f/blob @@ -0,0 +1,91 @@ +#pragma once + +#include +#include +#include + +#include + +#include + +#include + +namespace c10 { +struct IValue; +} + +namespace torch { +namespace jit { + +class Pickler; +class InlinedCallStackSerializer { + public: + // Serialize InlinedCallStack as + // SerializedInlinedCallStack = + // [module_info, source range tag, SerializedInlinedCallStack] + // module_info = [ClassType.qualifiedName, instance_name] + // source_range_tag = unique source range id + c10::IValue serialize( + const InlinedCallStackPtr& cs_ptr, + const SourceRangeTagMap& source_range_tags); + + private: + // module_info = [ClassType.qualifiedName, instance_name] + c10::IValue serialize_module_instance_info( + const c10::optional& m); + + // This caches serialized inlined callstack ptr, since many + // InlinedCallStackPtr can refer to the same one. + ska::flat_hash_map + serialized_inlined_callstack_; + // This caches serialized module instance info. + // There might be many nodes that are part of the same + // parent, grandparent etc. module. + ska::flat_hash_map serialized_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoPickler { + public: + CallStackDebugInfoPickler() = default; + + std::vector pickle( + const std::unordered_map& callstack_ptrs, + const SourceRangeTagMap& source_range_tags); + + private: + InlinedCallStackSerializer css_; +}; + +class InlinedCallStackDeserializer { + public: + InlinedCallStackPtr deserialize( + const c10::IValue& iv, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + c10::optional deserialize_module_instance_info( + const c10::IValue& iv, + const std::shared_ptr& cu); + + ska:: + flat_hash_map, InlinedCallStackPtr> + cached_inlined_callstacks_; + ska::flat_hash_map, ModuleInstanceInfo> + cached_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoUnpickler { + public: + ska::flat_hash_map unpickle( + at::DataPtr&& data, + size_t size, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + InlinedCallStackDeserializer csds_; +}; + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/75/750007a61b9a86c49e4ee516cc31667b7c969861748dee48a2d81cd32b8da07e/blob b/shared/package-files/75/750007a61b9a86c49e4ee516cc31667b7c969861748dee48a2d81cd32b8da07e/blob new file mode 100644 index 0000000000000000000000000000000000000000..ecaf86eabb9f71f018ff84639425431ad905566e --- /dev/null +++ b/shared/package-files/75/750007a61b9a86c49e4ee516cc31667b7c969861748dee48a2d81cd32b8da07e/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API void _amp_foreach_non_finite_check_and_unscale_(at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/75/7501011389a364fb724632972ba67e6cc1c9745aa9c21233c431f8c74e2b2989/blob b/shared/package-files/75/7501011389a364fb724632972ba67e6cc1c9745aa9c21233c431f8c74e2b2989/blob new file mode 100644 index 0000000000000000000000000000000000000000..e7bbfbb8c332fee14ae1b4aa07cc4d128e6a3ca7 Binary files /dev/null and b/shared/package-files/75/7501011389a364fb724632972ba67e6cc1c9745aa9c21233c431f8c74e2b2989/blob differ diff --git a/shared/package-files/75/7502587d52e7810228f2ecb45ac4319ea0f5c008b7ac91053b920010dc6ddf94/blob b/shared/package-files/75/7502587d52e7810228f2ecb45ac4319ea0f5c008b7ac91053b920010dc6ddf94/blob new file mode 100644 index 0000000000000000000000000000000000000000..140aec4c15169a946ae9f4d8d133c930e417e804 --- /dev/null +++ b/shared/package-files/75/7502587d52e7810228f2ecb45ac4319ea0f5c008b7ac91053b920010dc6ddf94/blob @@ -0,0 +1,690 @@ +# Encoding file: shiftjis, multi-byte +M +003F 0 40 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +0080000000000000000000850086008700000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000FF61FF62FF63FF64FF65FF66FF67FF68FF69FF6AFF6BFF6CFF6DFF6EFF6F +FF70FF71FF72FF73FF74FF75FF76FF77FF78FF79FF7AFF7BFF7CFF7DFF7EFF7F +FF80FF81FF82FF83FF84FF85FF86FF87FF88FF89FF8AFF8BFF8CFF8DFF8EFF8F +FF90FF91FF92FF93FF94FF95FF96FF97FF98FF99FF9AFF9BFF9CFF9DFF9EFF9F +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +81 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +300030013002FF0CFF0E30FBFF1AFF1BFF1FFF01309B309C00B4FF4000A8FF3E +FFE3FF3F30FD30FE309D309E30034EDD30053006300730FC20152010FF0FFF3C +301C2016FF5C2026202520182019201C201DFF08FF0930143015FF3BFF3DFF5B +FF5D30083009300A300B300C300D300E300F30103011FF0B221200B100D70000 +00F7FF1D2260FF1CFF1E22662267221E22342642264000B0203220332103FFE5 +FF0400A200A3FF05FF03FF06FF0AFF2000A72606260525CB25CF25CE25C725C6 +25A125A025B325B225BD25BC203B301221922190219121933013000000000000 +000000000000000000000000000000002208220B2286228722822283222A2229 +000000000000000000000000000000002227222800AC21D221D4220022030000 +0000000000000000000000000000000000000000222022A52312220222072261 +2252226A226B221A223D221D2235222B222C0000000000000000000000000000 +212B2030266F266D266A2020202100B6000000000000000025EF000000000000 +82 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +000000000000000000000000000000000000000000000000000000000000FF10 +FF11FF12FF13FF14FF15FF16FF17FF18FF190000000000000000000000000000 +FF21FF22FF23FF24FF25FF26FF27FF28FF29FF2AFF2BFF2CFF2DFF2EFF2FFF30 +FF31FF32FF33FF34FF35FF36FF37FF38FF39FF3A000000000000000000000000 +0000FF41FF42FF43FF44FF45FF46FF47FF48FF49FF4AFF4BFF4CFF4DFF4EFF4F +FF50FF51FF52FF53FF54FF55FF56FF57FF58FF59FF5A00000000000000003041 +30423043304430453046304730483049304A304B304C304D304E304F30503051 +30523053305430553056305730583059305A305B305C305D305E305F30603061 +30623063306430653066306730683069306A306B306C306D306E306F30703071 +30723073307430753076307730783079307A307B307C307D307E307F30803081 +30823083308430853086308730883089308A308B308C308D308E308F30903091 +3092309300000000000000000000000000000000000000000000000000000000 +83 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +30A130A230A330A430A530A630A730A830A930AA30AB30AC30AD30AE30AF30B0 +30B130B230B330B430B530B630B730B830B930BA30BB30BC30BD30BE30BF30C0 +30C130C230C330C430C530C630C730C830C930CA30CB30CC30CD30CE30CF30D0 +30D130D230D330D430D530D630D730D830D930DA30DB30DC30DD30DE30DF0000 +30E030E130E230E330E430E530E630E730E830E930EA30EB30EC30ED30EE30EF +30F030F130F230F330F430F530F6000000000000000000000000000000000391 +03920393039403950396039703980399039A039B039C039D039E039F03A003A1 +03A303A403A503A603A703A803A90000000000000000000000000000000003B1 +03B203B303B403B503B603B703B803B903BA03BB03BC03BD03BE03BF03C003C1 +03C303C403C503C603C703C803C9000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +84 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +04100411041204130414041504010416041704180419041A041B041C041D041E +041F0420042104220423042404250426042704280429042A042B042C042D042E +042F000000000000000000000000000000000000000000000000000000000000 +04300431043204330434043504510436043704380439043A043B043C043D0000 +043E043F0440044104420443044404450446044704480449044A044B044C044D +044E044F00000000000000000000000000000000000000000000000000002500 +2502250C251025182514251C252C25242534253C25012503250F2513251B2517 +25232533252B253B254B2520252F25282537253F251D25302525253825420000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +88 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000004E9C +55165A03963F54C0611B632859F690228475831C7A5060AA63E16E2565ED8466 +82A69BF56893572765A162715B9B59D0867B98F47D627DBE9B8E62167C9F88B7 +5B895EB563096697684895C7978D674F4EE54F0A4F4D4F9D504956F2593759D4 +5A015C0960DF610F61706613690570BA754F757079FB7DAD7DEF80C3840E8863 +8B029055907A533B4E954EA557DF80B290C178EF4E0058F16EA290387A328328 +828B9C2F5141537054BD54E156E059FB5F1598F26DEB80E4852D000000000000 +89 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +9662967096A097FB540B53F35B8770CF7FBD8FC296E8536F9D5C7ABA4E117893 +81FC6E26561855046B1D851A9C3B59E553A96D6674DC958F56424E91904B96F2 +834F990C53E155B65B305F71662066F368046C386CF36D29745B76C87A4E9834 +82F1885B8A6092ED6DB275AB76CA99C560A68B018D8A95B2698E53AD51860000 +5712583059445BB45EF6602863A963F46CBF6F14708E7114715971D5733F7E01 +827682D185979060925B9D1B586965BC6C5A752551F9592E59655F805FDC62BC +65FA6A2A6B276BB4738B7FC189569D2C9D0E9EC45CA16C96837B51045C4B61B6 +81C6687672614E594FFA537860696E297A4F97F34E0B53164EEE4F554F3D4FA1 +4F7352A053EF5609590F5AC15BB65BE179D16687679C67B66B4C6CB3706B73C2 +798D79BE7A3C7B8782B182DB8304837783EF83D387668AB256298CA88FE6904E +971E868A4FC45CE862117259753B81E582BD86FE8CC096C5991399D54ECB4F1A +89E356DE584A58CA5EFB5FEB602A6094606261D0621262D06539000000000000 +8A +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +9B41666668B06D777070754C76867D7582A587F9958B968E8C9D51F152BE5916 +54B35BB35D16616869826DAF788D84CB88578A7293A79AB86D6C99A886D957A3 +67FF86CE920E5283568754045ED362E164B9683C68386BBB737278BA7A6B899A +89D28D6B8F0390ED95A3969497695B665CB3697D984D984E639B7B206A2B0000 +6A7F68B69C0D6F5F5272559D607062EC6D3B6E076ED1845B89108F444E149C39 +53F6691B6A3A9784682A515C7AC384B291DC938C565B9D286822830584317CA5 +520882C574E64E7E4F8351A05BD2520A52D852E75DFB559A582A59E65B8C5B98 +5BDB5E725E7960A3611F616361BE63DB656267D1685368FA6B3E6B536C576F22 +6F976F4574B0751876E3770B7AFF7BA17C217DE97F367FF0809D8266839E89B3 +8ACC8CAB908494519593959195A2966597D3992882184E38542B5CB85DCC73A9 +764C773C5CA97FEB8D0B96C19811985498584F014F0E5371559C566857FA5947 +5B095BC45C905E0C5E7E5FCC63EE673A65D765E2671F68CB68C4000000000000 +8B +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +6A5F5E306BC56C176C7D757F79485B637A007D005FBD898F8A188CB48D778ECC +8F1D98E29A0E9B3C4E80507D510059935B9C622F628064EC6B3A72A075917947 +7FA987FB8ABC8B7063AC83CA97A05409540355AB68546A588A70782767759ECD +53745BA2811A865090064E184E454EC74F1153CA54385BAE5F13602565510000 +673D6C426C726CE3707874037A767AAE7B087D1A7CFE7D6665E7725B53BB5C45 +5DE862D262E063196E20865A8A318DDD92F86F0179A69B5A4EA84EAB4EAC4F9B +4FA050D151477AF6517151F653545321537F53EB55AC58835CE15F375F4A602F +6050606D631F65596A4B6CC172C272ED77EF80F881058208854E90F793E197FF +99579A5A4EF051DD5C2D6681696D5C4066F26975738968507C8150C552E45747 +5DFE932665A46B236B3D7434798179BD7B4B7DCA82B983CC887F895F8B398FD1 +91D1541F92804E5D503653E5533A72D7739677E982E68EAF99C699C899D25177 +611A865E55B07A7A50765BD3904796854E326ADB91E75C515C48000000000000 +8C +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +63987A9F6C9397748F617AAA718A96887C8268177E706851936C52F2541B85AB +8A137FA48ECD90E15366888879414FC250BE521151445553572D73EA578B5951 +5F625F8460756176616761A963B2643A656C666F68426E1375667A3D7CFB7D4C +7D997E4B7F6B830E834A86CD8A088A638B668EFD981A9D8F82B88FCE9BE80000 +5287621F64836FC09699684150916B206C7A6F547A747D5088408A2367084EF6 +503950265065517C5238526355A7570F58055ACC5EFA61B261F862F36372691C +6A29727D72AC732E7814786F7D79770C80A9898B8B198CE28ED290639375967A +98559A139E785143539F53B35E7B5F266E1B6E90738473FE7D4382378A008AFA +96504E4E500B53E4547C56FA59D15B645DF15EAB5F276238654567AF6E5672D0 +7CCA88B480A180E183F0864E8A878DE8923796C798679F134E944E924F0D5348 +5449543E5A2F5F8C5FA1609F68A76A8E745A78818A9E8AA48B7791904E5E9BC9 +4EA44F7C4FAF501950165149516C529F52B952FE539A53E35411000000000000 +8D +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +540E5589575157A2597D5B545B5D5B8F5DE55DE75DF75E785E835E9A5EB75F18 +6052614C629762D863A7653B6602664366F4676D6821689769CB6C5F6D2A6D69 +6E2F6E9D75327687786C7A3F7CE07D057D187D5E7DB18015800380AF80B18154 +818F822A8352884C88618B1B8CA28CFC90CA91759271783F92FC95A4964D0000 +980599999AD89D3B525B52AB53F7540858D562F76FE08C6A8F5F9EB9514B523B +544A56FD7A4091779D609ED273446F09817075115FFD60DA9AA872DB8FBC6B64 +98034ECA56F0576458BE5A5A606861C7660F6606683968B16DF775D57D3A826E +9B424E9B4F5053C955065D6F5DE65DEE67FB6C99747378028A50939688DF5750 +5EA7632B50B550AC518D670054C9585E59BB5BB05F69624D63A1683D6B736E08 +707D91C7728078157826796D658E7D3083DC88C18F09969B5264572867507F6A +8CA151B45742962A583A698A80B454B25D0E57FC78959DFA4F5C524A548B643E +6628671467F57A847B567D22932F685C9BAD7B395319518A5237000000000000 +8E +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +5BDF62F664AE64E6672D6BBA85A996D176909BD6634C93069BAB76BF66524E09 +509853C25C7160E864926563685F71E673CA75237B977E8286958B838CDB9178 +991065AC66AB6B8B4ED54ED44F3A4F7F523A53F853F255E356DB58EB59CB59C9 +59FF5B505C4D5E025E2B5FD7601D6307652F5B5C65AF65BD65E8679D6B620000 +6B7B6C0F7345794979C17CF87D197D2B80A2810281F389968A5E8A698A668A8C +8AEE8CC78CDC96CC98FC6B6F4E8B4F3C4F8D51505B575BFA6148630166426B21 +6ECB6CBB723E74BD75D478C1793A800C803381EA84948F9E6C509E7F5F0F8B58 +9D2B7AFA8EF85B8D96EB4E0353F157F759315AC95BA460896E7F6F0675BE8CEA +5B9F85007BE0507267F4829D5C61854A7E1E820E51995C0463688D66659C716E +793E7D1780058B1D8ECA906E86C790AA501F52FA5C3A6753707C7235914C91C8 +932B82E55BC25F3160F94E3B53D65B88624B67316B8A72E973E07A2E816B8DA3 +91529996511253D7546A5BFF63886A397DAC970056DA53CE5468000000000000 +8F +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +5B975C315DDE4FEE610162FE6D3279C079CB7D427E4D7FD281ED821F84908846 +89728B908E748F2F9031914B916C96C6919C4EC04F4F514553415F93620E67D4 +6C416E0B73637E2691CD928353D459195BBF6DD1795D7E2E7C9B587E719F51FA +88538FF04FCA5CFB662577AC7AE3821C99FF51C65FAA65EC696F6B896DF30000 +6E966F6476FE7D145DE190759187980651E6521D6240669166D96E1A5EB67DD2 +7F7266F885AF85F78AF852A953D959735E8F5F90605592E4966450B7511F52DD +5320534753EC54E8554655315617596859BE5A3C5BB55C065C0F5C115C1A5E84 +5E8A5EE05F70627F628462DB638C63776607660C662D6676677E68A26A1F6A35 +6CBC6D886E096E58713C7126716775C77701785D7901796579F07AE07B117CA7 +7D39809683D6848B8549885D88F38A1F8A3C8A548A738C618CDE91A49266937E +9418969C97984E0A4E084E1E4E575197527057CE583458CC5B225E3860C564FE +676167566D4472B675737A6384B88B7291B89320563157F498FE000000000000 +90 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +62ED690D6B9671ED7E548077827289E698DF87558FB15C3B4F384FE14FB55507 +5A205BDD5BE95FC3614E632F65B0664B68EE699B6D786DF1753375B9771F795E +79E67D3381E382AF85AA89AA8A3A8EAB8F9B903291DD97074EBA4EC152035875 +58EC5C0B751A5C3D814E8A0A8FC59663976D7B258ACF9808916256F353A80000 +9017543957825E2563A86C34708A77617C8B7FE088709042915493109318968F +745E9AC45D075D69657067A28DA896DB636E6749691983C5981796C088FE6F84 +647A5BF84E16702C755D662F51C4523652E259D35F8160276210653F6574661F +667468F268166B636E057272751F76DB7CBE805658F088FD897F8AA08A938ACB +901D91929752975965897A0E810696BB5E2D60DC621A65A56614679077F37A4D +7C4D7E3E810A8CAC8D648DE18E5F78A9520762D963A5644262988A2D7A837BC0 +8AAC96EA7D76820C87494ED95148534353605BA35C025C165DDD6226624764B0 +681368346CC96D456D1767D36F5C714E717D65CB7A7F7BAD7DDA000000000000 +91 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +7E4A7FA8817A821B823985A68A6E8CCE8DF59078907792AD929195839BAE524D +55846F387136516879857E5581B37CCE564C58515CA863AA66FE66FD695A72D9 +758F758E790E795679DF7C977D207D4486078A34963B90619F2050E7527553CC +53E2500955AA58EE594F723D5B8B5C64531D60E360F3635C6383633F63BB0000 +64CD65E966F95DE369CD69FD6F1571E54E8975E976F87A937CDF7DCF7D9C8061 +83498358846C84BC85FB88C58D709001906D9397971C9A1250CF5897618E81D3 +85358D0890204FC3507452475373606F6349675F6E2C8DB3901F4FD75C5E8CCA +65CF7D9A53528896517663C35B585B6B5C0A640D6751905C4ED6591A592A6C70 +8A51553E581559A560F0625367C182356955964099C49A284F5358065BFE8010 +5CB15E2F5F856020614B623466FF6CF06EDE80CE817F82D4888B8CB89000902E +968A9EDB9BDB4EE353F059277B2C918D984C9DF96EDD7027535355445B856258 +629E62D36CA26FEF74228A1794386FC18AFE833851E786F853EA000000000000 +92 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +53E94F4690548FB0596A81315DFD7AEA8FBF68DA8C3772F89C486A3D8AB04E39 +53585606576662C563A265E66B4E6DE16E5B70AD77ED7AEF7BAA7DBB803D80C6 +86CB8A95935B56E358C75F3E65AD66966A806BB575378AC7502477E557305F1B +6065667A6C6075F47A1A7F6E81F48718904599B37BC9755C7AF97B5184C40000 +901079E97A9283365AE177404E2D4EF25B995FE062BD663C67F16CE8866B8877 +8A3B914E92F399D06A177026732A82E784578CAF4E01514651CB558B5BF55E16 +5E335E815F145F355F6B5FB461F2631166A2671D6F6E7252753A773A80748139 +817887768ABF8ADC8D858DF3929A957798029CE552C5635776F467156C8873CD +8CC393AE96736D25589C690E69CC8FFD939A75DB901A585A680263B469FB4F43 +6F2C67D88FBB85267DB49354693F6F70576A58F75B2C7D2C722A540A91E39DB4 +4EAD4F4E505C507552438C9E544858245B9A5E1D5E955EAD5EF75F1F608C62B5 +633A63D068AF6C407887798E7A0B7DE082478A028AE68E449013000000000000 +93 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +90B8912D91D89F0E6CE5645864E265756EF476847B1B906993D16EBA54F25FB9 +64A48F4D8FED92445178586B59295C555E976DFB7E8F751C8CBC8EE2985B70B9 +4F1D6BBF6FB1753096FB514E54105835585759AC5C605F926597675C6E21767B +83DF8CED901490FD934D7825783A52AA5EA6571F597460125012515A51AC0000 +51CD520055105854585859575B955CF65D8B60BC6295642D6771684368BC68DF +76D76DD86E6F6D9B706F71C85F5375D879777B497B547B527CD67D7152308463 +856985E48A0E8B048C468E0F9003900F94199676982D9A3095D850CD52D5540C +58025C0E61A7649E6D1E77B37AE580F48404905392855CE09D07533F5F975FB3 +6D9C7279776379BF7BE46BD272EC8AAD68036A6151F87A8169345C4A9CF682EB +5BC59149701E56785C6F60C765666C8C8C5A90419813545166C7920D594890A3 +51854E4D51EA85998B0E7058637A934B696299B47E047577535769608EDF96E3 +6C5D4E8C5C3C5F108FE953028CD1808986795EFF65E54E735165000000000000 +94 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +59825C3F97EE4EFB598A5FCD8A8D6FE179B079625BE78471732B71B15E745FF5 +637B649A71C37C984E435EFC4E4B57DC56A260A96FC37D0D80FD813381BF8FB2 +899786A45DF4628A64AD898767776CE26D3E743678345A467F7582AD99AC4FF3 +5EC362DD63926557676F76C3724C80CC80BA8F29914D500D57F95A9268850000 +6973716472FD8CB758F28CE0966A9019877F79E477E784294F2F5265535A62CD +67CF6CCA767D7B947C95823685848FEB66DD6F2072067E1B83AB99C19EA651FD +7BB178727BB880877B486AE85E61808C75517560516B92626E8C767A91979AEA +4F107F70629C7B4F95A59CE9567A585986E496BC4F345224534A53CD53DB5E06 +642C6591677F6C3E6C4E724872AF73ED75547E41822C85E98CA97BC491C67169 +981298EF633D6669756A76E478D0854386EE532A5351542659835E875F7C60B2 +6249627962AB65906BD46CCC75B276AE789179D87DCB7F7780A588AB8AB98CBB +907F975E98DB6A0B7C3850995C3E5FAE67876BD8743577097F8E000000000000 +95 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +9F3B67CA7A175339758B9AED5F66819D83F180985F3C5FC575627B46903C6867 +59EB5A9B7D10767E8B2C4FF55F6A6A196C376F0274E2796888688A558C795EDF +63CF75C579D282D7932892F2849C86ED9C2D54C15F6C658C6D5C70158CA78CD3 +983B654F74F64E0D4ED857E0592B5A665BCC51A85E035E9C6016627665770000 +65A7666E6D6E72367B268150819A82998B5C8CA08CE68D74961C96444FAE64AB +6B66821E8461856A90E85C01695398A8847A85574F0F526F5FA95E45670D798F +8179890789866DF55F1762556CB84ECF72699B925206543B567458B361A4626E +711A596E7C897CDE7D1B96F06587805E4E194F75517558405E635E735F0A67C4 +4E26853D9589965B7C73980150FB58C1765678A7522577A585117B86504F5909 +72477BC77DE88FBA8FD4904D4FBF52C95A295F0197AD4FDD821792EA57036355 +6B69752B88DC8F147A4252DF58936155620A66AE6BCD7C3F83E950234FF85305 +5446583159495B9D5CF05CEF5D295E9662B16367653E65B9670B000000000000 +96 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +6CD56CE170F978327E2B80DE82B3840C84EC870289128A2A8C4A90A692D298FD +9CF39D6C4E4F4EA1508D5256574A59A85E3D5FD85FD9623F66B4671B67D068D2 +51927D2180AA81A88B008C8C8CBF927E96325420982C531750D5535C58A864B2 +6734726777667A4691E652C36CA16B8658005E4C5954672C7FFB51E176C60000 +646978E89B549EBB57CB59B96627679A6BCE54E969D95E55819C67959BAA67FE +9C52685D4EA64FE353C862B9672B6CAB8FC44FAD7E6D9EBF4E0761626E806F2B +85135473672A9B455DF37B955CAC5BC6871C6E4A84D17A14810859997C8D6C11 +772052D959227121725F77DB97279D61690B5A7F5A1851A5540D547D660E76DF +8FF792989CF459EA725D6EC5514D68C97DBF7DEC97629EBA64786A2183025984 +5B5F6BDB731B76F27DB280178499513267289ED976EE676252FF99055C24623B +7C7E8CB0554F60B67D0B958053014E5F51B6591C723A803691CE5F2577E25384 +5F797D0485AC8A338E8D975667F385AE9453610961086CB9765200000000FF5E +97 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +8AED8F38552F4F51512A52C753CB5BA55E7D60A0618263D6670967DA6E676D8C +733673377531795088D58A98904A909190F596C4878D59154E884F594E0E8A89 +8F3F981050AD5E7C59965BB95EB863DA63FA64C166DC694A69D86D0B6EB67194 +75287AAF7F8A8000844984C989818B218E0A9065967D990A617E62916B320000 +6C836D747FCC7FFC6DC07F8587BA88F8676583B1983C96F76D1B7D61843D916A +4E7153755D506B046FEB85CD862D89A75229540F5C65674E68A87406748375E2 +88CF88E191CC96E296785F8B73877ACB844E63A0756552896D416E9C74097559 +786B7C9296867ADC9F8D4FB6616E65C5865C4E864EAE50DA4E2151CC5BEE6599 +68816DBC731F764277AD7A1C7CE7826F8AD2907C91CF96759818529B7DD1502B +539867976DCB71D0743381E88F2A96A39C579E9F746058416D997D2F985E4EE4 +4F364F8B51B752B15DBA601C73B2793C82D3923496B796F6970A9E979F6266A6 +6B74521752A370C888C25EC9604B61906F2371497C3E7DF4806F000000000000 +98 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +84EE9023932C54429B6F6AD370898CC28DEF973252B45A415ECA5F046717697C +69946D6A6F0F726272FC7BED8001807E874B90CE516D9E937984808B93328AD6 +502D548C8A716B6A8CC4810760D167A09DF24E994E989C108A6B85C185686900 +6E7E789781550000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000005F0C +4E104E154E2A4E314E364E3C4E3F4E424E564E584E824E858C6B4E8A82125F0D +4E8E4E9E4E9F4EA04EA24EB04EB34EB64ECE4ECD4EC44EC64EC24ED74EDE4EED +4EDF4EF74F094F5A4F304F5B4F5D4F574F474F764F884F8F4F984F7B4F694F70 +4F914F6F4F864F9651184FD44FDF4FCE4FD84FDB4FD14FDA4FD04FE44FE5501A +50285014502A502550054F1C4FF650215029502C4FFE4FEF5011500650435047 +6703505550505048505A5056506C50785080509A508550B450B2000000000000 +99 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +50C950CA50B350C250D650DE50E550ED50E350EE50F950F55109510151025116 +51155114511A5121513A5137513C513B513F51405152514C515451627AF85169 +516A516E5180518256D8518C5189518F519151935195519651A451A651A251A9 +51AA51AB51B351B151B251B051B551BD51C551C951DB51E0865551E951ED0000 +51F051F551FE5204520B5214520E5227522A522E52335239524F5244524B524C +525E5254526A527452695273527F527D528D529452925271528852918FA88FA7 +52AC52AD52BC52B552C152CD52D752DE52E352E698ED52E052F352F552F852F9 +530653087538530D5310530F5315531A5323532F533153335338534053465345 +4E175349534D51D6535E5369536E5918537B53775382539653A053A653A553AE +53B053B653C37C1296D953DF66FC71EE53EE53E853ED53FA5401543D5440542C +542D543C542E54365429541D544E548F5475548E545F5471547754705492547B +5480547654845490548654C754A254B854A554AC54C454C854A8000000000000 +9A +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +54AB54C254A454BE54BC54D854E554E6550F551454FD54EE54ED54FA54E25539 +55405563554C552E555C55455556555755385533555D5599558054AF558A559F +557B557E5598559E55AE557C558355A9558755A855DA55C555DF55C455DC55E4 +55D4561455F7561655FE55FD561B55F9564E565071DF56345636563256380000 +566B5664562F566C566A56865680568A56A05694568F56A556AE56B656B456C2 +56BC56C156C356C056C856CE56D156D356D756EE56F9570056FF570457095708 +570B570D57135718571655C7571C572657375738574E573B5740574F576957C0 +57885761577F5789579357A057B357A457AA57B057C357C657D457D257D3580A +57D657E3580B5819581D587258215862584B58706BC05852583D5879588558B9 +589F58AB58BA58DE58BB58B858AE58C558D358D158D758D958D858E558DC58E4 +58DF58EF58FA58F958FB58FC58FD5902590A5910591B68A65925592C592D5932 +5938593E7AD259555950594E595A5958596259605967596C5969000000000000 +9B +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +59785981599D4F5E4FAB59A359B259C659E859DC598D59D959DA5A255A1F5A11 +5A1C5A095A1A5A405A6C5A495A355A365A625A6A5A9A5ABC5ABE5ACB5AC25ABD +5AE35AD75AE65AE95AD65AFA5AFB5B0C5B0B5B165B325AD05B2A5B365B3E5B43 +5B455B405B515B555B5A5B5B5B655B695B705B735B755B7865885B7A5B800000 +5B835BA65BB85BC35BC75BC95BD45BD05BE45BE65BE25BDE5BE55BEB5BF05BF6 +5BF35C055C075C085C0D5C135C205C225C285C385C395C415C465C4E5C535C50 +5C4F5B715C6C5C6E4E625C765C795C8C5C915C94599B5CAB5CBB5CB65CBC5CB7 +5CC55CBE5CC75CD95CE95CFD5CFA5CED5D8C5CEA5D0B5D155D175D5C5D1F5D1B +5D115D145D225D1A5D195D185D4C5D525D4E5D4B5D6C5D735D765D875D845D82 +5DA25D9D5DAC5DAE5DBD5D905DB75DBC5DC95DCD5DD35DD25DD65DDB5DEB5DF2 +5DF55E0B5E1A5E195E115E1B5E365E375E445E435E405E4E5E575E545E5F5E62 +5E645E475E755E765E7A9EBC5E7F5EA05EC15EC25EC85ED05ECF000000000000 +9C +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +5ED65EE35EDD5EDA5EDB5EE25EE15EE85EE95EEC5EF15EF35EF05EF45EF85EFE +5F035F095F5D5F5C5F0B5F115F165F295F2D5F385F415F485F4C5F4E5F2F5F51 +5F565F575F595F615F6D5F735F775F835F825F7F5F8A5F885F915F875F9E5F99 +5F985FA05FA85FAD5FBC5FD65FFB5FE45FF85FF15FDD60B35FFF602160600000 +601960106029600E6031601B6015602B6026600F603A605A6041606A6077605F +604A6046604D6063604360646042606C606B60596081608D60E76083609A6084 +609B60966097609260A7608B60E160B860E060D360B45FF060BD60C660B560D8 +614D6115610660F660F7610060F460FA6103612160FB60F1610D610E6147613E +61286127614A613F613C612C6134613D614261446173617761586159615A616B +6174616F61656171615F615D6153617561996196618761AC6194619A618A6191 +61AB61AE61CC61CA61C961F761C861C361C661BA61CB7F7961CD61E661E361F6 +61FA61F461FF61FD61FC61FE620062086209620D620C6214621B000000000000 +9D +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +621E6221622A622E6230623262336241624E625E6263625B62606268627C6282 +6289627E62926293629662D46283629462D762D162BB62CF62FF62C664D462C8 +62DC62CC62CA62C262C7629B62C9630C62EE62F163276302630862EF62F56350 +633E634D641C634F6396638E638063AB637663A3638F6389639F63B5636B0000 +636963BE63E963C063C663E363C963D263F663C4641664346406641364266436 +651D64176428640F6467646F6476644E652A6495649364A564A9648864BC64DA +64D264C564C764BB64D864C264F164E7820964E064E162AC64E364EF652C64F6 +64F464F264FA650064FD6518651C650565246523652B65346535653765366538 +754B654865566555654D6558655E655D65726578658265838B8A659B659F65AB +65B765C365C665C165C465CC65D265DB65D965E065E165F16772660A660365FB +6773663566366634661C664F664466496641665E665D666466676668665F6662 +667066836688668E668966846698669D66C166B966C966BE66BC000000000000 +9E +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +66C466B866D666DA66E0663F66E666E966F066F566F7670F6716671E67266727 +9738672E673F67366741673867376746675E67606759676367646789677067A9 +677C676A678C678B67A667A1678567B767EF67B467EC67B367E967B867E467DE +67DD67E267EE67B967CE67C667E76A9C681E684668296840684D6832684E0000 +68B3682B685968636877687F689F688F68AD6894689D689B68836AAE68B96874 +68B568A068BA690F688D687E690168CA690868D86922692668E1690C68CD68D4 +68E768D569366912690468D768E3692568F968E068EF6928692A691A69236921 +68C669796977695C6978696B6954697E696E69396974693D695969306961695E +695D6981696A69B269AE69D069BF69C169D369BE69CE5BE869CA69DD69BB69C3 +69A76A2E699169A0699C699569B469DE69E86A026A1B69FF6B0A69F969F269E7 +6A0569B16A1E69ED6A1469EB6A0A6A126AC16A236A136A446A0C6A726A366A78 +6A476A626A596A666A486A386A226A906A8D6AA06A846AA26AA3000000000000 +9F +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +6A9786176ABB6AC36AC26AB86AB36AAC6ADE6AD16ADF6AAA6ADA6AEA6AFB6B05 +86166AFA6B126B169B316B1F6B386B3776DC6B3998EE6B476B436B496B506B59 +6B546B5B6B5F6B616B786B796B7F6B806B846B836B8D6B986B956B9E6BA46BAA +6BAB6BAF6BB26BB16BB36BB76BBC6BC66BCB6BD36BDF6BEC6BEB6BF36BEF0000 +9EBE6C086C136C146C1B6C246C236C5E6C556C626C6A6C826C8D6C9A6C816C9B +6C7E6C686C736C926C906CC46CF16CD36CBD6CD76CC56CDD6CAE6CB16CBE6CBA +6CDB6CEF6CD96CEA6D1F884D6D366D2B6D3D6D386D196D356D336D126D0C6D63 +6D936D646D5A6D796D596D8E6D956FE46D856DF96E156E0A6DB56DC76DE66DB8 +6DC66DEC6DDE6DCC6DE86DD26DC56DFA6DD96DE46DD56DEA6DEE6E2D6E6E6E2E +6E196E726E5F6E3E6E236E6B6E2B6E766E4D6E1F6E436E3A6E4E6E246EFF6E1D +6E386E826EAA6E986EC96EB76ED36EBD6EAF6EC46EB26ED46ED56E8F6EA56EC2 +6E9F6F416F11704C6EEC6EF86EFE6F3F6EF26F316EEF6F326ECC000000000000 +E0 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +6F3E6F136EF76F866F7A6F786F816F806F6F6F5B6FF36F6D6F826F7C6F586F8E +6F916FC26F666FB36FA36FA16FA46FB96FC66FAA6FDF6FD56FEC6FD46FD86FF1 +6FEE6FDB7009700B6FFA70117001700F6FFE701B701A6F74701D7018701F7030 +703E7032705170637099709270AF70F170AC70B870B370AE70DF70CB70DD0000 +70D9710970FD711C711971657155718871667162714C7156716C718F71FB7184 +719571A871AC71D771B971BE71D271C971D471CE71E071EC71E771F571FC71F9 +71FF720D7210721B7228722D722C72307232723B723C723F72407246724B7258 +7274727E7282728172877292729672A272A772B972B272C372C672C472CE72D2 +72E272E072E172F972F7500F7317730A731C7316731D7334732F73297325733E +734E734F9ED87357736A7368737073787375737B737A73C873B373CE73BB73C0 +73E573EE73DE74A27405746F742573F87432743A7455743F745F74597441745C +746974707463746A7476747E748B749E74A774CA74CF74D473F1000000000000 +E1 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +74E074E374E774E974EE74F274F074F174F874F7750475037505750C750E750D +75157513751E7526752C753C7544754D754A7549755B7546755A756975647567 +756B756D75787576758675877574758A758975827594759A759D75A575A375C2 +75B375C375B575BD75B875BC75B175CD75CA75D275D975E375DE75FE75FF0000 +75FC760175F075FA75F275F3760B760D7609761F762776207621762276247634 +7630763B764776487646765C76587661766276687669766A7667766C76707672 +76767678767C768076837688768B768E769676937699769A76B076B476B876B9 +76BA76C276CD76D676D276DE76E176E576E776EA862F76FB7708770777047729 +7724771E77257726771B773777387747775A7768776B775B7765777F777E7779 +778E778B779177A0779E77B077B677B977BF77BC77BD77BB77C777CD77D777DA +77DC77E377EE77FC780C781279267820792A7845788E78747886787C789A788C +78A378B578AA78AF78D178C678CB78D478BE78BC78C578CA78EC000000000000 +E2 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +78E778DA78FD78F47907791279117919792C792B794079607957795F795A7955 +7953797A797F798A799D79A79F4B79AA79AE79B379B979BA79C979D579E779EC +79E179E37A087A0D7A187A197A207A1F79807A317A3B7A3E7A377A437A577A49 +7A617A627A699F9D7A707A797A7D7A887A977A957A987A967AA97AC87AB00000 +7AB67AC57AC47ABF90837AC77ACA7ACD7ACF7AD57AD37AD97ADA7ADD7AE17AE2 +7AE67AED7AF07B027B0F7B0A7B067B337B187B197B1E7B357B287B367B507B7A +7B047B4D7B0B7B4C7B457B757B657B747B677B707B717B6C7B6E7B9D7B987B9F +7B8D7B9C7B9A7B8B7B927B8F7B5D7B997BCB7BC17BCC7BCF7BB47BC67BDD7BE9 +7C117C147BE67BE57C607C007C077C137BF37BF77C177C0D7BF67C237C277C2A +7C1F7C377C2B7C3D7C4C7C437C547C4F7C407C507C587C5F7C647C567C657C6C +7C757C837C907CA47CAD7CA27CAB7CA17CA87CB37CB27CB17CAE7CB97CBD7CC0 +7CC57CC27CD87CD27CDC7CE29B3B7CEF7CF27CF47CF67CFA7D06000000000000 +E3 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +7D027D1C7D157D0A7D457D4B7D2E7D327D3F7D357D467D737D567D4E7D727D68 +7D6E7D4F7D637D937D897D5B7D8F7D7D7D9B7DBA7DAE7DA37DB57DC77DBD7DAB +7E3D7DA27DAF7DDC7DB87D9F7DB07DD87DDD7DE47DDE7DFB7DF27DE17E057E0A +7E237E217E127E317E1F7E097E0B7E227E467E667E3B7E357E397E437E370000 +7E327E3A7E677E5D7E567E5E7E597E5A7E797E6A7E697E7C7E7B7E837DD57E7D +8FAE7E7F7E887E897E8C7E927E907E937E947E967E8E7E9B7E9C7F387F3A7F45 +7F4C7F4D7F4E7F507F517F557F547F587F5F7F607F687F697F677F787F827F86 +7F837F887F877F8C7F947F9E7F9D7F9A7FA37FAF7FB27FB97FAE7FB67FB88B71 +7FC57FC67FCA7FD57FD47FE17FE67FE97FF37FF998DC80068004800B80128018 +8019801C80218028803F803B804A804680528058805A805F8062806880738072 +807080768079807D807F808480868085809B8093809A80AD519080AC80DB80E5 +80D980DD80C480DA80D6810980EF80F1811B81298123812F814B000000000000 +E4 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +968B8146813E8153815180FC8171816E81658166817481838188818A81808182 +81A0819581A481A3815F819381A981B081B581BE81B881BD81C081C281BA81C9 +81CD81D181D981D881C881DA81DF81E081E781FA81FB81FE8201820282058207 +820A820D821082168229822B82388233824082598258825D825A825F82640000 +82628268826A826B822E827182778278827E828D829282AB829F82BB82AC82E1 +82E382DF82D282F482F382FA8393830382FB82F982DE830682DC830982D98335 +83348316833283318340833983508345832F832B831783188385839A83AA839F +83A283968323838E8387838A837C83B58373837583A0838983A883F4841383EB +83CE83FD840383D8840B83C183F7840783E083F2840D8422842083BD84388506 +83FB846D842A843C855A84848477846B84AD846E848284698446842C846F8479 +843584CA846284B984BF849F84D984CD84BB84DA84D084C184C684D684A18521 +84FF84F485178518852C851F8515851484FC8540856385588548000000000000 +E5 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +85418602854B8555858085A485888591858A85A8856D8594859B85EA8587859C +8577857E859085C985BA85CF85B985D085D585DD85E585DC85F9860A8613860B +85FE85FA86068622861A8630863F864D4E558654865F86678671869386A386A9 +86AA868B868C86B686AF86C486C686B086C9882386AB86D486DE86E986EC0000 +86DF86DB86EF8712870687088700870386FB87118709870D86F9870A8734873F +8737873B87258729871A8760875F8778874C874E877487578768876E87598753 +8763876A880587A2879F878287AF87CB87BD87C087D096D687AB87C487B387C7 +87C687BB87EF87F287E0880F880D87FE87F687F7880E87D28811881688158822 +88218831883688398827883B8844884288528859885E8862886B8881887E889E +8875887D88B5887288828897889288AE889988A2888D88A488B088BF88B188C3 +88C488D488D888D988DD88F9890288FC88F488E888F28904890C890A89138943 +891E8925892A892B89418944893B89368938894C891D8960895E000000000000 +E6 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +89668964896D896A896F89748977897E89838988898A8993899889A189A989A6 +89AC89AF89B289BA89BD89BF89C089DA89DC89DD89E789F489F88A038A168A10 +8A0C8A1B8A1D8A258A368A418A5B8A528A468A488A7C8A6D8A6C8A628A858A82 +8A848AA88AA18A918AA58AA68A9A8AA38AC48ACD8AC28ADA8AEB8AF38AE70000 +8AE48AF18B148AE08AE28AF78ADE8ADB8B0C8B078B1A8AE18B168B108B178B20 +8B3397AB8B268B2B8B3E8B288B418B4C8B4F8B4E8B498B568B5B8B5A8B6B8B5F +8B6C8B6F8B748B7D8B808B8C8B8E8B928B938B968B998B9A8C3A8C418C3F8C48 +8C4C8C4E8C508C558C628C6C8C788C7A8C828C898C858C8A8C8D8C8E8C948C7C +8C98621D8CAD8CAA8CBD8CB28CB38CAE8CB68CC88CC18CE48CE38CDA8CFD8CFA +8CFB8D048D058D0A8D078D0F8D0D8D109F4E8D138CCD8D148D168D678D6D8D71 +8D738D818D998DC28DBE8DBA8DCF8DDA8DD68DCC8DDB8DCB8DEA8DEB8DDF8DE3 +8DFC8E088E098DFF8E1D8E1E8E108E1F8E428E358E308E348E4A000000000000 +E7 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +8E478E498E4C8E508E488E598E648E608E2A8E638E558E768E728E7C8E818E87 +8E858E848E8B8E8A8E938E918E948E998EAA8EA18EAC8EB08EC68EB18EBE8EC5 +8EC88ECB8EDB8EE38EFC8EFB8EEB8EFE8F0A8F058F158F128F198F138F1C8F1F +8F1B8F0C8F268F338F3B8F398F458F428F3E8F4C8F498F468F4E8F578F5C0000 +8F628F638F648F9C8F9F8FA38FAD8FAF8FB78FDA8FE58FE28FEA8FEF90878FF4 +90058FF98FFA901190159021900D901E9016900B90279036903590398FF8904F +905090519052900E9049903E90569058905E9068906F907696A890729082907D +90819080908A9089908F90A890AF90B190B590E290E4624890DB910291129119 +91329130914A9156915891639165916991739172918B9189918291A291AB91AF +91AA91B591B491BA91C091C191C991CB91D091D691DF91E191DB91FC91F591F6 +921E91FF9214922C92159211925E925792459249926492489295923F924B9250 +929C92969293929B925A92CF92B992B792E9930F92FA9344932E000000000000 +E8 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +93199322931A9323933A9335933B935C9360937C936E935693B093AC93AD9394 +93B993D693D793E893E593D893C393DD93D093C893E4941A9414941394039407 +94109436942B94359421943A944194529444945B94609462945E946A92299470 +94759477947D945A947C947E9481947F95829587958A95949596959895990000 +95A095A895A795AD95BC95BB95B995BE95CA6FF695C395CD95CC95D595D495D6 +95DC95E195E595E296219628962E962F9642964C964F964B9677965C965E965D +965F96669672966C968D96989695969796AA96A796B196B296B096B496B696B8 +96B996CE96CB96C996CD894D96DC970D96D596F99704970697089713970E9711 +970F971697199724972A97309739973D973E97449746974897429749975C9760 +97649766976852D2976B977197799785977C9781977A9786978B978F9790979C +97A897A697A397B397B497C397C697C897CB97DC97ED9F4F97F27ADF97F697F5 +980F980C9838982498219837983D9846984F984B986B986F9870000000000000 +E9 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +98719874987398AA98AF98B198B698C498C398C698E998EB9903990999129914 +99189921991D991E99249920992C992E993D993E9942994999459950994B9951 +9952994C99559997999899A599AD99AE99BC99DF99DB99DD99D899D199ED99EE +99F199F299FB99F89A019A0F9A0599E29A199A2B9A379A459A429A409A430000 +9A3E9A559A4D9A5B9A579A5F9A629A659A649A699A6B9A6A9AAD9AB09ABC9AC0 +9ACF9AD19AD39AD49ADE9ADF9AE29AE39AE69AEF9AEB9AEE9AF49AF19AF79AFB +9B069B189B1A9B1F9B229B239B259B279B289B299B2A9B2E9B2F9B329B449B43 +9B4F9B4D9B4E9B519B589B749B939B839B919B969B979B9F9BA09BA89BB49BC0 +9BCA9BB99BC69BCF9BD19BD29BE39BE29BE49BD49BE19C3A9BF29BF19BF09C15 +9C149C099C139C0C9C069C089C129C0A9C049C2E9C1B9C259C249C219C309C47 +9C329C469C3E9C5A9C609C679C769C789CE79CEC9CF09D099D089CEB9D039D06 +9D2A9D269DAF9D239D1F9D449D159D129D419D3F9D3E9D469D48000000000000 +EA +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +9D5D9D5E9D649D519D509D599D729D899D879DAB9D6F9D7A9D9A9DA49DA99DB2 +9DC49DC19DBB9DB89DBA9DC69DCF9DC29DD99DD39DF89DE69DED9DEF9DFD9E1A +9E1B9E1E9E759E799E7D9E819E889E8B9E8C9E929E959E919E9D9EA59EA99EB8 +9EAA9EAD97619ECC9ECE9ECF9ED09ED49EDC9EDE9EDD9EE09EE59EE89EEF0000 +9EF49EF69EF79EF99EFB9EFC9EFD9F079F0876B79F159F219F2C9F3E9F4A9F52 +9F549F639F5F9F609F619F669F679F6C9F6A9F779F729F769F959F9C9FA0582F +69C79059746451DC719900000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +0000000000000000000000000000000000000000000000000000000000000000 +R +8160 301C FF5E +8161 2016 2225 +817C 2212 FF0D +8191 00A2 FFE0 +8192 00A3 FFE1 +81CA 00AC FFE2 diff --git a/shared/package-files/75/75038d5b2a5bcdfbf31820ed769dccfcd25ac12709bccd838876f1d64fb0c3b8/blob b/shared/package-files/75/75038d5b2a5bcdfbf31820ed769dccfcd25ac12709bccd838876f1d64fb0c3b8/blob new file mode 100644 index 0000000000000000000000000000000000000000..a8727ed8592533a009b6202be92f438d4152e793 --- /dev/null +++ b/shared/package-files/75/75038d5b2a5bcdfbf31820ed769dccfcd25ac12709bccd838876f1d64fb0c3b8/blob @@ -0,0 +1,188 @@ +""" + pygments.formatters.svg + ~~~~~~~~~~~~~~~~~~~~~~~ + + Formatter for SVG output. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pip._vendor.pygments.formatter import Formatter +from pip._vendor.pygments.token import Comment +from pip._vendor.pygments.util import get_bool_opt, get_int_opt + +__all__ = ['SvgFormatter'] + + +def escape_html(text): + """Escape &, <, > as well as single and double quotes for HTML.""" + return text.replace('&', '&'). \ + replace('<', '<'). \ + replace('>', '>'). \ + replace('"', '"'). \ + replace("'", ''') + + +class2style = {} + +class SvgFormatter(Formatter): + """ + Format tokens as an SVG graphics file. This formatter is still experimental. + Each line of code is a ```` element with explicit ``x`` and ``y`` + coordinates containing ```` elements with the individual token styles. + + By default, this formatter outputs a full SVG document including doctype + declaration and the ```` root element. + + .. versionadded:: 0.9 + + Additional options accepted: + + `nowrap` + Don't wrap the SVG ```` elements in ```` elements and + don't add a XML declaration and a doctype. If true, the `fontfamily` + and `fontsize` options are ignored. Defaults to ``False``. + + `fontfamily` + The value to give the wrapping ```` element's ``font-family`` + attribute, defaults to ``"monospace"``. + + `fontsize` + The value to give the wrapping ```` element's ``font-size`` + attribute, defaults to ``"14px"``. + + `linenos` + If ``True``, add line numbers (default: ``False``). + + `linenostart` + The line number for the first line (default: ``1``). + + `linenostep` + If set to a number n > 1, only every nth line number is printed. + + `linenowidth` + Maximum width devoted to line numbers (default: ``3*ystep``, sufficient + for up to 4-digit line numbers. Increase width for longer code blocks). + + `xoffset` + Starting offset in X direction, defaults to ``0``. + + `yoffset` + Starting offset in Y direction, defaults to the font size if it is given + in pixels, or ``20`` else. (This is necessary since text coordinates + refer to the text baseline, not the top edge.) + + `ystep` + Offset to add to the Y coordinate for each subsequent line. This should + roughly be the text size plus 5. It defaults to that value if the text + size is given in pixels, or ``25`` else. + + `spacehack` + Convert spaces in the source to `` ``, which are non-breaking + spaces. SVG provides the ``xml:space`` attribute to control how + whitespace inside tags is handled, in theory, the ``preserve`` value + could be used to keep all whitespace as-is. However, many current SVG + viewers don't obey that rule, so this option is provided as a workaround + and defaults to ``True``. + """ + name = 'SVG' + aliases = ['svg'] + filenames = ['*.svg'] + + def __init__(self, **options): + Formatter.__init__(self, **options) + self.nowrap = get_bool_opt(options, 'nowrap', False) + self.fontfamily = options.get('fontfamily', 'monospace') + self.fontsize = options.get('fontsize', '14px') + self.xoffset = get_int_opt(options, 'xoffset', 0) + fs = self.fontsize.strip() + if fs.endswith('px'): fs = fs[:-2].strip() + try: + int_fs = int(fs) + except: + int_fs = 20 + self.yoffset = get_int_opt(options, 'yoffset', int_fs) + self.ystep = get_int_opt(options, 'ystep', int_fs + 5) + self.spacehack = get_bool_opt(options, 'spacehack', True) + self.linenos = get_bool_opt(options,'linenos',False) + self.linenostart = get_int_opt(options,'linenostart',1) + self.linenostep = get_int_opt(options,'linenostep',1) + self.linenowidth = get_int_opt(options,'linenowidth', 3*self.ystep) + self._stylecache = {} + + def format_unencoded(self, tokensource, outfile): + """ + Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` + tuples and write it into ``outfile``. + + For our implementation we put all lines in their own 'line group'. + """ + x = self.xoffset + y = self.yoffset + if not self.nowrap: + if self.encoding: + outfile.write('\n' % + self.encoding) + else: + outfile.write('\n') + outfile.write('\n') + outfile.write('\n') + outfile.write('\n' % + (self.fontfamily, self.fontsize)) + + counter = self.linenostart + counter_step = self.linenostep + counter_style = self._get_style(Comment) + line_x = x + + if self.linenos: + if counter % counter_step == 0: + outfile.write('%s' % + (x+self.linenowidth,y,counter_style,counter)) + line_x += self.linenowidth + self.ystep + counter += 1 + + outfile.write('' % (line_x, y)) + for ttype, value in tokensource: + style = self._get_style(ttype) + tspan = style and '' or '' + tspanend = tspan and '' or '' + value = escape_html(value) + if self.spacehack: + value = value.expandtabs().replace(' ', ' ') + parts = value.split('\n') + for part in parts[:-1]: + outfile.write(tspan + part + tspanend) + y += self.ystep + outfile.write('\n') + if self.linenos and counter % counter_step == 0: + outfile.write('%s' % + (x+self.linenowidth,y,counter_style,counter)) + + counter += 1 + outfile.write('' % (line_x,y)) + outfile.write(tspan + parts[-1] + tspanend) + outfile.write('') + + if not self.nowrap: + outfile.write('\n') + + def _get_style(self, tokentype): + if tokentype in self._stylecache: + return self._stylecache[tokentype] + otokentype = tokentype + while not self.style.styles_token(tokentype): + tokentype = tokentype.parent + value = self.style.style_for_token(tokentype) + result = '' + if value['color']: + result = ' fill="#' + value['color'] + '"' + if value['bold']: + result += ' font-weight="bold"' + if value['italic']: + result += ' font-style="italic"' + self._stylecache[otokentype] = result + return result diff --git a/shared/package-files/75/7505076b53c6a49b0d136c7f490171b4e5fe8e8bac12aa65c07d5b76c93a9a71/blob b/shared/package-files/75/7505076b53c6a49b0d136c7f490171b4e5fe8e8bac12aa65c07d5b76c93a9a71/blob new file mode 100644 index 0000000000000000000000000000000000000000..63c5578000dbd4c910295cc0e98a1b819ab6afcd --- /dev/null +++ b/shared/package-files/75/7505076b53c6a49b0d136c7f490171b4e5fe8e8bac12aa65c07d5b76c93a9a71/blob @@ -0,0 +1,4 @@ +# file generated by setuptools_scm +# don't change, don't track in version control +__version__ = version = '0.2.0' +__version_tuple__ = version_tuple = (0, 2, 0) diff --git a/shared/package-files/75/7505f48f7ae32af9c3cce082d4d3c7d4adc28018d428e52968dd27b50b586edf/blob b/shared/package-files/75/7505f48f7ae32af9c3cce082d4d3c7d4adc28018d428e52968dd27b50b586edf/blob new file mode 100644 index 0000000000000000000000000000000000000000..c2635e8d4940c4521f60a8a9d2122e30a80b565c --- /dev/null +++ b/shared/package-files/75/7505f48f7ae32af9c3cce082d4d3c7d4adc28018d428e52968dd27b50b586edf/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _mkldnn_reshape_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef shape); +TORCH_API at::Tensor & _mkldnn_reshape_outf(const at::Tensor & self, at::IntArrayRef shape, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/75/750a5404fadd8bddb13c09751eacd776c431166e124a0e2dd0d01bd9b8fb2314/blob b/shared/package-files/75/750a5404fadd8bddb13c09751eacd776c431166e124a0e2dd0d01bd9b8fb2314/blob new file mode 100644 index 0000000000000000000000000000000000000000..9a6aaa23023cb49ab1c49691ef8dffc03d1403c1 --- /dev/null +++ b/shared/package-files/75/750a5404fadd8bddb13c09751eacd776c431166e124a0e2dd0d01bd9b8fb2314/blob @@ -0,0 +1,590 @@ +# mypy: disable-error-code="type-arg" +from datetime import timedelta +from enum import Enum +from typing import Any, Dict, List, Optional, overload, Tuple, Union + +import torch +from torch import Tensor +from torch._C import ScriptObject +from torch.futures import Future + +# This module is defined in torch/csrc/distributed/c10d/init.cpp + +_DEFAULT_FIRST_BUCKET_BYTES: int +_DEFAULT_NO_TIMEOUT: timedelta +_DEFAULT_PG_TIMEOUT: timedelta +_DEFAULT_PG_NCCL_TIMEOUT: timedelta + +class BuiltinCommHookType(Enum): + ALLREDUCE = ... + FP16_COMPRESS = ... + +def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ... +def _register_builtin_comm_hook( + reducer: Reducer, + comm_hook_type: BuiltinCommHookType, +): ... +def _set_global_rank(rank: int) -> None: ... +def _hash_tensors(tensors: List[Tensor]) -> int: ... + +class GradBucket: + def index(self) -> int: ... + def buffer(self) -> Tensor: ... + def gradients(self) -> List[Tensor]: ... + def is_last(self) -> bool: ... + def set_buffer(self, tensor: Tensor) -> None: ... + def parameters(self) -> List[Tensor]: ... + +class Reducer: + def __init__( + self, + params: List[Tensor], + bucket_indices: List[List[int]], + per_bucket_size_limits: List[int], + process_group: ProcessGroup, + expect_sparse_gradients: List[bool] = ..., + bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp + find_unused_parameters: bool = ..., + gradient_as_bucket_view: bool = ..., + param_to_name_mapping: Dict[int, str] = ..., + first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp + ): ... + def prepare_for_forward(self) -> None: ... + def prepare_for_backward(self, output: List[Tensor]) -> None: ... + def get_backward_stats(self) -> List[int]: ... + def _install_post_backward_futures(self, futures: List[Future]) -> None: ... + def _rebuild_buckets(self) -> bool: ... + def _get_zeros_like_grad_buckets(self) -> List[GradBucket]: ... + def _push_all_rebuilt_params(self) -> None: ... + def _set_forward_pass_work_handle( + self, + work: Work, + use_static_world_size: bool, + ): ... + def _get_local_used_map(self) -> Tensor: ... + def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ... + def _set_static_graph(self) -> None: ... + def _run_comm_hook(self, bucket: GradBucket) -> Future: ... + def set_logger(self, logger: Logger) -> None: ... + def _remove_autograd_hooks(self) -> None: ... + def _check_reducer_finalized(self) -> None: ... + def _set_sparse_metadata(self, global_unique_ids: Dict[str, Tensor]) -> None: ... + def _reset_state(self) -> None: ... + def _update_process_group(self, new_process_group: ProcessGroup) -> None: ... + +class DDPLoggingData: + strs_map: Dict[str, str] + ints_map: Dict[str, int] + +class Logger: + def __init__(self, reducer: Reducer): ... + def set_construction_data_and_log( + self, + module_name: str, + device_ids: List[int], + output_device: int, + broadcast_buffers: bool, + has_sync_bn: bool, + static_graph: bool, + ): ... + def set_runtime_stats_and_log(self) -> None: ... + def set_error_and_log(self, error: str) -> None: ... + def _get_ddp_logging_data(self) -> DDPLoggingData: ... + def _set_comm_hook_name(self, comm_hook: str) -> None: ... + def _set_uneven_input_join(self) -> None: ... + def _set_static_graph(self) -> None: ... + +def get_debug_level(): ... +def set_debug_level(): ... +def set_debug_level_from_env(): ... + +class DebugLevel(Enum): + OFF = ... + INFO = ... + DETAIL = ... + +class ReduceOp: + def __init__(self, op: RedOpType): ... + + SUM: RedOpType = ... + AVG: RedOpType = ... + PRODUCT: RedOpType = ... + MIN: RedOpType = ... + MAX: RedOpType = ... + BAND: RedOpType = ... + BOR: RedOpType = ... + BXOR: RedOpType = ... + PREMUL_SUM: RedOpType = ... + UNUSED: RedOpType = ... + + class RedOpType(Enum): ... + +class BroadcastOptions: + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllreduceOptions: + reduceOp: ReduceOp + timeout: timedelta + +class AllreduceCoalescedOptions(AllreduceOptions): ... + +class ReduceOptions: + reduceOp: ReduceOp + rootRank: int + rootTensor: int + timeout: timedelta + +class AllgatherOptions: + timeout: timedelta + asyncOp: bool + +class GatherOptions: + rootRank: int + timeout: timedelta + +class ScatterOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ReduceScatterOptions: + reduceOp: ReduceOp + timeout: timedelta + asyncOp: bool + +class BarrierOptions: + device_ids: List[int] + device: torch.device + timeout: timedelta + +class AllToAllOptions: + timeout: timedelta + +class Store: + def set(self, key: str, value: str): ... + def get(self, key: str) -> bytes: ... + def add(self, key: str, value: int) -> int: ... + def compare_set( + self, + key: str, + expected_value: str, + desired_value: str, + ) -> bytes: ... + def delete_key(self, key: str) -> bool: ... + def num_keys(self) -> int: ... + def set_timeout(self, timeout: timedelta): ... + @overload + def wait(self, keys: List[str]): ... + @overload + def wait(self, keys: List[str], timeout: timedelta): ... + +class FileStore(Store): + def __init__(self, path: str, numWorkers: int = ...): ... + +class HashStore(Store): + def __init__(self): ... + +class TCPStore(Store): + def __init__( + self, + host_name: str, + port: int, + world_size: Optional[int] = ..., + is_master: bool = ..., + timeout: timedelta = ..., + wait_for_workers: bool = ..., + multi_tenant: bool = ..., + master_listen_fd: Optional[int] = ..., + use_libuv: Optional[bool] = ..., + ): ... + @property + def host(self) -> str: ... + @property + def port(self) -> int: ... + +class PrefixStore(Store): + def __init__(self, prefix: str, store: Store): ... + @property + def underlying_store(self) -> Store: ... + +class _DistributedBackendOptions: + def __init__(self): ... + @property + def store(self) -> Store: ... + @store.setter + def store(self, store: Store) -> None: ... + @property + def group_rank(self) -> int: ... + @group_rank.setter + def group_rank(self, rank: int) -> None: ... + @property + def group_size(self) -> int: ... + @group_size.setter + def group_size(self, size: int) -> None: ... + @property + def timeout(self) -> timedelta: ... + @timeout.setter + def timeout(self, timeout: timedelta) -> None: ... + @property + def group_id(self) -> str: ... + @group_id.setter + def group_id(self, group_id: str) -> None: ... + @property + def global_ranks_in_group(self) -> List[int]: ... + @global_ranks_in_group.setter + def global_ranks_in_group(self, ranks: List[int]) -> None: ... + +class Work: + def is_completed(self) -> bool: ... + def is_success(self) -> bool: ... + def exception(self) -> Any: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def get_future(self) -> Future: ... + def source_rank(self) -> int: ... + def _source_rank(self) -> int: ... + def result(self) -> List[Tensor]: ... + def synchronize(self): ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> Work: ... + +class Backend: + def __init__( + self, + rank: int, + size: int, + ): ... + @property + def supports_splitting(self) -> bool: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def eager_connect_single_device(self, device: Optional[torch.device]) -> None: ... + def _set_sequence_number_for_group(self) -> None: ... + +class ProcessGroup: + class Options: + def __init__(self, backend: str, timeout: timedelta = ...): ... + @property + def backend(self) -> str: ... + @property + def _timeout(self) -> timedelta: ... + @_timeout.setter + def _timeout(self, val: timedelta) -> None: ... + + class BackendType(Enum): + UNDEFINED = ... + GLOO = ... + NCCL = ... + UCC = ... + MPI = ... + CUSTOM = ... + def __init__(self, store: Store, rank: int, size: int, options: Options): ... + def rank(self) -> int: ... + def size(self) -> int: ... + @overload + def broadcast( + self, + tensors: List[Tensor], + opts=..., + ) -> Work: ... + @overload + def broadcast( + self, + tensor: Tensor, + root: int, + ) -> Work: ... + @overload + def allreduce( + self, + tensors: List[Tensor], + opts: AllreduceOptions = ..., + ) -> Work: ... + @overload + def allreduce( + self, + tensors: List[Tensor], + op=..., + ) -> Work: ... + @overload + def allreduce( + self, + tensor: Tensor, + op=..., + ) -> Work: ... + def allreduce_coalesced( + self, + tensors: List[Tensor], + opts=..., + ) -> Work: ... + def reduce_scatter_tensor_coalesced( + self, + outputTensors: List[Tensor], + inputTensors: List[Tensor], + opts: Optional[ReduceScatterOptions] = None, + ) -> Work: ... + @overload + def reduce( + self, + tensors: List[Tensor], + opts=..., + ) -> Work: ... + @overload + def reduce( + self, + tensor: Tensor, + root: int, + op=..., + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: List[List[Tensor]], + input_tensors: List[Tensor], + opts=..., + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: List[Tensor], + input_tensor: Tensor, + ) -> Work: ... + def _allgather_base( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def allgather_coalesced( + self, + output_lists: List[List[Tensor]], + input_list: List[Tensor], + opts=..., + ) -> Work: ... + def allgather_into_tensor_coalesced( + self, + output_lists: List[Tensor], + input_list: List[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: List[List[Tensor]], + input_tensors: List[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: List[Tensor], + input_tensor: Tensor, + root: int, + ) -> Work: ... + @overload + def scatter( + self, + output_tensors: List[Tensor], + input_tensors: List[List[Tensor]], + opts=..., + ) -> Work: ... + @overload + def scatter( + self, + output_tensor: Tensor, + input_tensors: List[Tensor], + root: int, + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: List[Tensor], + input_tensors: List[List[Tensor]], + opts=..., + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: Tensor, + input_tensor: List[Tensor], + ) -> Work: ... + def _reduce_scatter_base( + self, + outputTensor: Tensor, + inputTensor: Tensor, + opts: Optional[ReduceScatterOptions], + ) -> Work: ... + @overload + def alltoall_base( + self, + output_tensor: Tensor, + input_tensor: Tensor, + output_split_sizes: List[int], + input_split_sizes: List[int], + opts=..., + ) -> Work: ... + @overload + def alltoall_base( + self, + output: Tensor, + input: Tensor, + output_split_sizes: List[int], + input_split_sizes: List[int], + ) -> Work: ... + @overload + def alltoall( + self, + output_tensor: List[Tensor], + input_tensor: List[Tensor], + opts=..., + ) -> Work: ... + @overload + def alltoall( + self, + output: List[Tensor], + input: List[Tensor], + ) -> Work: ... + def send( + self, + tensors: List[Tensor], + dstRank: int, + tag: int, + ) -> Work: ... + def recv( + self, + tensors: List[Tensor], + srcRank: int, + tag: int, + ) -> Work: ... + def recv_anysource(self, tensors: List[Tensor], tag: int) -> Work: ... + def barrier(self, opts=...) -> Work: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> ProcessGroup: ... + def _start_coalescing(self, device: torch.device) -> None: ... + def _end_coalescing(self, device: torch.device) -> Work: ... + def _get_backend_name(self) -> str: ... + def _backend_id(self, backend_type: BackendType) -> int: ... + @property + def _device_types(self) -> List[torch.device]: ... + def _get_backend(self, device: torch.device) -> Backend: ... + def _register_backend( + self, + device: torch.device, + backend_type: BackendType, + backend: Optional[Backend], + ) -> None: ... + def _set_group_name(self, name: str) -> None: ... + def name(self) -> str: ... + def _has_hooks(self) -> bool: ... + def _wait_for_pending_works(self) -> None: ... + def _set_sequence_number_for_group(self) -> None: ... + @property + def bound_device_id(self) -> Optional[torch.device]: ... + @bound_device_id.setter + def bound_device_id(self, device: Optional[torch.device]) -> None: ... + @property + def group_name(self) -> str: ... + +class ProcessGroupRoundRobin(ProcessGroup): ... + +def _round_robin_process_groups( + process_groups: List[ProcessGroup], +) -> ProcessGroupRoundRobin: ... + +class ProcessGroupGloo(Backend): + class Device: ... + class Options: ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ): ... + @staticmethod + def create_device(hostname="", interface="") -> Device: ... + @staticmethod + def create_default_device() -> Device: ... + def _set_default_timeout(self, timeout) -> None: ... + +class _ProcessGroupWrapper(Backend): + def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo): ... + wrapped_pg: Backend + +class ProcessGroupNCCL(Backend): + class Options: + def __init__(self, timeout: Optional[timedelta] = None): ... + @property + def backend(self) -> str: ... + @property + def _timeout(self) -> timedelta: ... + @_timeout.setter + def _timeout(self, val: timedelta) -> None: ... + @property + def _is_high_priority_stream(self) -> bool: ... + @_is_high_priority_stream.setter + def _is_high_priority_stream(self, val: bool) -> None: ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ): ... + def _group_start(self) -> None: ... + def _group_end(self) -> None: ... + def _set_default_timeout(self, timeout) -> None: ... + def _shutdown(self) -> None: ... + @property + def uid(self) -> int: ... + +class ProcessGroupUCC(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ): ... + +class ProcessGroupMPI(Backend): + def __init__( + self, + rank: int, + size: int, + pgComm: int, + ): ... + @staticmethod + def create(ranks: List[int]) -> ProcessGroupMPI: ... + +def _compute_bucket_assignment_by_size( + tensors: List[Tensor], + bucket_size_limits: List[int], + expect_sparse_gradient: List[bool] = ..., + tensor_indices: List[int] = ..., +) -> Tuple[List[List[int]], List[int]]: ... +def _broadcast_coalesced( + process_group: ProcessGroup, + tensors: List[Tensor], + buffer_size: int, + src: int, +): ... +def _test_python_store(store: Store): ... +def _verify_params_across_processes( + process_group: ProcessGroup, + params: List[Tensor], + logger: Optional[Logger], +): ... +def _make_nccl_premul_sum(factor: Union[float, List[Tensor]]) -> ReduceOp: ... +def _register_process_group( + group_name: str, + process_group: ProcessGroup, +) -> None: ... +def _resolve_process_group(group_name: str) -> ProcessGroup: ... +def _unregister_all_process_groups() -> None: ... +def _unregister_process_group(group_name: str) -> None: ... diff --git a/shared/package-files/75/750aa994ff806563d944a8a8f0b9938d85a5098cfd5665bebac52bb5a2e977fc/blob b/shared/package-files/75/750aa994ff806563d944a8a8f0b9938d85a5098cfd5665bebac52bb5a2e977fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b5a0f69a69ffc8f23fb5416e82777d2d06f0a00 --- /dev/null +++ b/shared/package-files/75/750aa994ff806563d944a8a8f0b9938d85a5098cfd5665bebac52bb5a2e977fc/blob @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/acero/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" + +namespace arrow { + +using compute::ExecContext; + +namespace acero { + +class OrderByImpl { + public: + virtual ~OrderByImpl() = default; + + virtual void InputReceived(const std::shared_ptr& batch) = 0; + + virtual Result DoFinish() = 0; + + virtual std::string ToString() const = 0; + + static Result> MakeSort( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options); + + static Result> MakeSelectK( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options); +}; + +} // namespace acero +} // namespace arrow diff --git a/shared/package-files/75/750c6b9abcaee83e2a1cacaa7e5c588e87c4a28cfac5707dae39edb908087b84/blob b/shared/package-files/75/750c6b9abcaee83e2a1cacaa7e5c588e87c4a28cfac5707dae39edb908087b84/blob new file mode 100644 index 0000000000000000000000000000000000000000..74d06117cbb4ab262b4855c82e1e3aa2428caaca --- /dev/null +++ b/shared/package-files/75/750c6b9abcaee83e2a1cacaa7e5c588e87c4a28cfac5707dae39edb908087b84/blob @@ -0,0 +1,1113 @@ +from datetime import datetime +import re + +import numpy as np +import pytest + +from pandas._libs import lib +from pandas.errors import UnsupportedFunctionCall + +import pandas as pd +from pandas import ( + DataFrame, + NamedAgg, + Series, +) +import pandas._testing as tm +from pandas.core.indexes.datetimes import date_range + + +@pytest.fixture +def dti(): + return date_range(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="Min") + + +@pytest.fixture +def _test_series(dti): + return Series(np.random.default_rng(2).random(len(dti)), dti) + + +@pytest.fixture +def test_frame(dti, _test_series): + return DataFrame({"A": _test_series, "B": _test_series, "C": np.arange(len(dti))}) + + +def test_str(_test_series): + r = _test_series.resample("h") + assert ( + "DatetimeIndexResampler [freq=, axis=0, closed=left, " + "label=left, convention=start, origin=start_day]" in str(r) + ) + + r = _test_series.resample("h", origin="2000-01-01") + assert ( + "DatetimeIndexResampler [freq=, axis=0, closed=left, " + "label=left, convention=start, origin=2000-01-01 00:00:00]" in str(r) + ) + + +def test_api(_test_series): + r = _test_series.resample("h") + result = r.mean() + assert isinstance(result, Series) + assert len(result) == 217 + + r = _test_series.to_frame().resample("h") + result = r.mean() + assert isinstance(result, DataFrame) + assert len(result) == 217 + + +def test_groupby_resample_api(): + # GH 12448 + # .groupby(...).resample(...) hitting warnings + # when appropriate + df = DataFrame( + { + "date": date_range(start="2016-01-01", periods=4, freq="W"), + "group": [1, 1, 2, 2], + "val": [5, 6, 7, 8], + } + ).set_index("date") + + # replication step + i = ( + date_range("2016-01-03", periods=8).tolist() + + date_range("2016-01-17", periods=8).tolist() + ) + index = pd.MultiIndex.from_arrays([[1] * 8 + [2] * 8, i], names=["group", "date"]) + expected = DataFrame({"val": [5] * 7 + [6] + [7] * 7 + [8]}, index=index) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("group").apply(lambda x: x.resample("1D").ffill())[["val"]] + tm.assert_frame_equal(result, expected) + + +def test_groupby_resample_on_api(): + # GH 15021 + # .groupby(...).resample(on=...) results in an unexpected + # keyword warning. + df = DataFrame( + { + "key": ["A", "B"] * 5, + "dates": date_range("2016-01-01", periods=10), + "values": np.random.default_rng(2).standard_normal(10), + } + ) + + expected = df.set_index("dates").groupby("key").resample("D").mean() + result = df.groupby("key").resample("D", on="dates").mean() + tm.assert_frame_equal(result, expected) + + +def test_resample_group_keys(): + df = DataFrame({"A": 1, "B": 2}, index=date_range("2000", periods=10)) + expected = df.copy() + + # group_keys=False + g = df.resample("5D", group_keys=False) + result = g.apply(lambda x: x) + tm.assert_frame_equal(result, expected) + + # group_keys defaults to False + g = df.resample("5D") + result = g.apply(lambda x: x) + tm.assert_frame_equal(result, expected) + + # group_keys=True + expected.index = pd.MultiIndex.from_arrays( + [ + pd.to_datetime(["2000-01-01", "2000-01-06"]).as_unit("ns").repeat(5), + expected.index, + ] + ) + g = df.resample("5D", group_keys=True) + result = g.apply(lambda x: x) + tm.assert_frame_equal(result, expected) + + +def test_pipe(test_frame, _test_series): + # GH17905 + + # series + r = _test_series.resample("h") + expected = r.max() - r.mean() + result = r.pipe(lambda x: x.max() - x.mean()) + tm.assert_series_equal(result, expected) + + # dataframe + r = test_frame.resample("h") + expected = r.max() - r.mean() + result = r.pipe(lambda x: x.max() - x.mean()) + tm.assert_frame_equal(result, expected) + + +def test_getitem(test_frame): + r = test_frame.resample("h") + tm.assert_index_equal(r._selected_obj.columns, test_frame.columns) + + r = test_frame.resample("h")["B"] + assert r._selected_obj.name == test_frame.columns[1] + + # technically this is allowed + r = test_frame.resample("h")["A", "B"] + tm.assert_index_equal(r._selected_obj.columns, test_frame.columns[[0, 1]]) + + r = test_frame.resample("h")["A", "B"] + tm.assert_index_equal(r._selected_obj.columns, test_frame.columns[[0, 1]]) + + +@pytest.mark.parametrize("key", [["D"], ["A", "D"]]) +def test_select_bad_cols(key, test_frame): + g = test_frame.resample("h") + # 'A' should not be referenced as a bad column... + # will have to rethink regex if you change message! + msg = r"^\"Columns not found: 'D'\"$" + with pytest.raises(KeyError, match=msg): + g[key] + + +def test_attribute_access(test_frame): + r = test_frame.resample("h") + tm.assert_series_equal(r.A.sum(), r["A"].sum()) + + +@pytest.mark.parametrize("attr", ["groups", "ngroups", "indices"]) +def test_api_compat_before_use(attr): + # make sure that we are setting the binner + # on these attributes + rng = date_range("1/1/2012", periods=100, freq="s") + ts = Series(np.arange(len(rng)), index=rng) + rs = ts.resample("30s") + + # before use + getattr(rs, attr) + + # after grouper is initialized is ok + rs.mean() + getattr(rs, attr) + + +def tests_raises_on_nuisance(test_frame, using_infer_string): + df = test_frame + df["D"] = "foo" + r = df.resample("h") + result = r[["A", "B"]].mean() + expected = pd.concat([r.A.mean(), r.B.mean()], axis=1) + tm.assert_frame_equal(result, expected) + + expected = r[["A", "B", "C"]].mean() + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + with pytest.raises(TypeError, match=msg): + r.mean() + result = r.mean(numeric_only=True) + tm.assert_frame_equal(result, expected) + + +def test_downsample_but_actually_upsampling(): + # this is reindex / asfreq + rng = date_range("1/1/2012", periods=100, freq="s") + ts = Series(np.arange(len(rng), dtype="int64"), index=rng) + result = ts.resample("20s").asfreq() + expected = Series( + [0, 20, 40, 60, 80], + index=date_range("2012-01-01 00:00:00", freq="20s", periods=5), + ) + tm.assert_series_equal(result, expected) + + +def test_combined_up_downsampling_of_irregular(): + # since we are really doing an operation like this + # ts2.resample('2s').mean().ffill() + # preserve these semantics + + rng = date_range("1/1/2012", periods=100, freq="s") + ts = Series(np.arange(len(rng)), index=rng) + ts2 = ts.iloc[[0, 1, 2, 3, 5, 7, 11, 15, 16, 25, 30]] + + result = ts2.resample("2s").mean().ffill() + expected = Series( + [ + 0.5, + 2.5, + 5.0, + 7.0, + 7.0, + 11.0, + 11.0, + 15.0, + 16.0, + 16.0, + 16.0, + 16.0, + 25.0, + 25.0, + 25.0, + 30.0, + ], + index=pd.DatetimeIndex( + [ + "2012-01-01 00:00:00", + "2012-01-01 00:00:02", + "2012-01-01 00:00:04", + "2012-01-01 00:00:06", + "2012-01-01 00:00:08", + "2012-01-01 00:00:10", + "2012-01-01 00:00:12", + "2012-01-01 00:00:14", + "2012-01-01 00:00:16", + "2012-01-01 00:00:18", + "2012-01-01 00:00:20", + "2012-01-01 00:00:22", + "2012-01-01 00:00:24", + "2012-01-01 00:00:26", + "2012-01-01 00:00:28", + "2012-01-01 00:00:30", + ], + dtype="datetime64[ns]", + freq="2s", + ), + ) + tm.assert_series_equal(result, expected) + + +def test_transform_series(_test_series): + r = _test_series.resample("20min") + expected = _test_series.groupby(pd.Grouper(freq="20min")).transform("mean") + result = r.transform("mean") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("on", [None, "date"]) +def test_transform_frame(on): + # GH#47079 + index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") + index.name = "date" + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index + ) + expected = df.groupby(pd.Grouper(freq="20min")).transform("mean") + if on == "date": + # Move date to being a column; result will then have a RangeIndex + expected = expected.reset_index(drop=True) + df = df.reset_index() + + r = df.resample("20min", on=on) + result = r.transform("mean") + tm.assert_frame_equal(result, expected) + + +def test_fillna(): + # need to upsample here + rng = date_range("1/1/2012", periods=10, freq="2s") + ts = Series(np.arange(len(rng), dtype="int64"), index=rng) + r = ts.resample("s") + + expected = r.ffill() + msg = "DatetimeIndexResampler.fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = r.fillna(method="ffill") + tm.assert_series_equal(result, expected) + + expected = r.bfill() + with tm.assert_produces_warning(FutureWarning, match=msg): + result = r.fillna(method="bfill") + tm.assert_series_equal(result, expected) + + msg2 = ( + r"Invalid fill method\. Expecting pad \(ffill\), backfill " + r"\(bfill\) or nearest\. Got 0" + ) + with pytest.raises(ValueError, match=msg2): + with tm.assert_produces_warning(FutureWarning, match=msg): + r.fillna(0) + + +@pytest.mark.parametrize( + "func", + [ + lambda x: x.resample("20min", group_keys=False), + lambda x: x.groupby(pd.Grouper(freq="20min"), group_keys=False), + ], + ids=["resample", "groupby"], +) +def test_apply_without_aggregation(func, _test_series): + # both resample and groupby should work w/o aggregation + t = func(_test_series) + result = t.apply(lambda x: x) + tm.assert_series_equal(result, _test_series) + + +def test_apply_without_aggregation2(_test_series): + grouped = _test_series.to_frame(name="foo").resample("20min", group_keys=False) + result = grouped["foo"].apply(lambda x: x) + tm.assert_series_equal(result, _test_series.rename("foo")) + + +def test_agg_consistency(): + # make sure that we are consistent across + # similar aggregations with and w/o selection list + df = DataFrame( + np.random.default_rng(2).standard_normal((1000, 3)), + index=date_range("1/1/2012", freq="s", periods=1000), + columns=["A", "B", "C"], + ) + + r = df.resample("3min") + + msg = r"Column\(s\) \['r1', 'r2'\] do not exist" + with pytest.raises(KeyError, match=msg): + r.agg({"r1": "mean", "r2": "sum"}) + + +def test_agg_consistency_int_str_column_mix(): + # GH#39025 + df = DataFrame( + np.random.default_rng(2).standard_normal((1000, 2)), + index=date_range("1/1/2012", freq="s", periods=1000), + columns=[1, "a"], + ) + + r = df.resample("3min") + + msg = r"Column\(s\) \[2, 'b'\] do not exist" + with pytest.raises(KeyError, match=msg): + r.agg({2: "mean", "b": "sum"}) + + +# TODO(GH#14008): once GH 14008 is fixed, move these tests into +# `Base` test class + + +@pytest.fixture +def index(): + index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") + index.name = "date" + return index + + +@pytest.fixture +def df(index): + frame = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index + ) + return frame + + +@pytest.fixture +def df_col(df): + return df.reset_index() + + +@pytest.fixture +def df_mult(df_col, index): + df_mult = df_col.copy() + df_mult.index = pd.MultiIndex.from_arrays( + [range(10), index], names=["index", "date"] + ) + return df_mult + + +@pytest.fixture +def a_mean(df): + return df.resample("2D")["A"].mean() + + +@pytest.fixture +def a_std(df): + return df.resample("2D")["A"].std() + + +@pytest.fixture +def a_sum(df): + return df.resample("2D")["A"].sum() + + +@pytest.fixture +def b_mean(df): + return df.resample("2D")["B"].mean() + + +@pytest.fixture +def b_std(df): + return df.resample("2D")["B"].std() + + +@pytest.fixture +def b_sum(df): + return df.resample("2D")["B"].sum() + + +@pytest.fixture +def df_resample(df): + return df.resample("2D") + + +@pytest.fixture +def df_col_resample(df_col): + return df_col.resample("2D", on="date") + + +@pytest.fixture +def df_mult_resample(df_mult): + return df_mult.resample("2D", level="date") + + +@pytest.fixture +def df_grouper_resample(df): + return df.groupby(pd.Grouper(freq="2D")) + + +@pytest.fixture( + params=["df_resample", "df_col_resample", "df_mult_resample", "df_grouper_resample"] +) +def cases(request): + return request.getfixturevalue(request.param) + + +def test_agg_mixed_column_aggregation(cases, a_mean, a_std, b_mean, b_std, request): + expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) + expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]]) + msg = "using SeriesGroupBy.[mean|std]" + # "date" is an index and a column, so get included in the agg + if "df_mult" in request.node.callspec.id: + date_mean = cases["date"].mean() + date_std = cases["date"].std() + expected = pd.concat([date_mean, date_std, expected], axis=1) + expected.columns = pd.MultiIndex.from_product( + [["date", "A", "B"], ["mean", "std"]] + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = cases.aggregate([np.mean, np.std]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg", + [ + {"func": {"A": np.mean, "B": np.std}}, + {"A": ("A", np.mean), "B": ("B", np.std)}, + {"A": NamedAgg("A", np.mean), "B": NamedAgg("B", np.std)}, + ], +) +def test_agg_both_mean_std_named_result(cases, a_mean, b_std, agg): + msg = "using SeriesGroupBy.[mean|std]" + expected = pd.concat([a_mean, b_std], axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = cases.aggregate(**agg) + tm.assert_frame_equal(result, expected, check_like=True) + + +def test_agg_both_mean_std_dict_of_list(cases, a_mean, a_std): + expected = pd.concat([a_mean, a_std], axis=1) + expected.columns = pd.MultiIndex.from_tuples([("A", "mean"), ("A", "std")]) + result = cases.aggregate({"A": ["mean", "std"]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg", [{"func": ["mean", "sum"]}, {"mean": "mean", "sum": "sum"}] +) +def test_agg_both_mean_sum(cases, a_mean, a_sum, agg): + expected = pd.concat([a_mean, a_sum], axis=1) + expected.columns = ["mean", "sum"] + result = cases["A"].aggregate(**agg) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg", + [ + {"A": {"mean": "mean", "sum": "sum"}}, + { + "A": {"mean": "mean", "sum": "sum"}, + "B": {"mean2": "mean", "sum2": "sum"}, + }, + ], +) +def test_agg_dict_of_dict_specificationerror(cases, agg): + msg = "nested renamer is not supported" + with pytest.raises(pd.errors.SpecificationError, match=msg): + cases.aggregate(agg) + + +def test_agg_dict_of_lists(cases, a_mean, a_std, b_mean, b_std): + expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) + expected.columns = pd.MultiIndex.from_tuples( + [("A", "mean"), ("A", "std"), ("B", "mean"), ("B", "std")] + ) + result = cases.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]}) + tm.assert_frame_equal(result, expected, check_like=True) + + +@pytest.mark.parametrize( + "agg", + [ + {"func": {"A": np.sum, "B": lambda x: np.std(x, ddof=1)}}, + {"A": ("A", np.sum), "B": ("B", lambda x: np.std(x, ddof=1))}, + {"A": NamedAgg("A", np.sum), "B": NamedAgg("B", lambda x: np.std(x, ddof=1))}, + ], +) +def test_agg_with_lambda(cases, agg): + # passed lambda + msg = "using SeriesGroupBy.sum" + rcustom = cases["B"].apply(lambda x: np.std(x, ddof=1)) + expected = pd.concat([cases["A"].sum(), rcustom], axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = cases.agg(**agg) + tm.assert_frame_equal(result, expected, check_like=True) + + +@pytest.mark.parametrize( + "agg", + [ + {"func": {"result1": np.sum, "result2": np.mean}}, + {"A": ("result1", np.sum), "B": ("result2", np.mean)}, + {"A": NamedAgg("result1", np.sum), "B": NamedAgg("result2", np.mean)}, + ], +) +def test_agg_no_column(cases, agg): + msg = r"Column\(s\) \['result1', 'result2'\] do not exist" + with pytest.raises(KeyError, match=msg): + cases[["A", "B"]].agg(**agg) + + +@pytest.mark.parametrize( + "cols, agg", + [ + [None, {"A": ["sum", "std"], "B": ["mean", "std"]}], + [ + [ + "A", + "B", + ], + {"A": ["sum", "std"], "B": ["mean", "std"]}, + ], + ], +) +def test_agg_specificationerror_nested(cases, cols, agg, a_sum, a_std, b_mean, b_std): + # agg with different hows + # equivalent of using a selection list / or not + expected = pd.concat([a_sum, a_std, b_mean, b_std], axis=1) + expected.columns = pd.MultiIndex.from_tuples( + [("A", "sum"), ("A", "std"), ("B", "mean"), ("B", "std")] + ) + if cols is not None: + obj = cases[cols] + else: + obj = cases + + result = obj.agg(agg) + tm.assert_frame_equal(result, expected, check_like=True) + + +@pytest.mark.parametrize( + "agg", [{"A": ["sum", "std"]}, {"A": ["sum", "std"], "B": ["mean", "std"]}] +) +def test_agg_specificationerror_series(cases, agg): + msg = "nested renamer is not supported" + + # series like aggs + with pytest.raises(pd.errors.SpecificationError, match=msg): + cases["A"].agg(agg) + + +def test_agg_specificationerror_invalid_names(cases): + # errors + # invalid names in the agg specification + msg = r"Column\(s\) \['B'\] do not exist" + with pytest.raises(KeyError, match=msg): + cases[["A"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) + + +@pytest.mark.parametrize( + "func", [["min"], ["mean", "max"], {"A": "sum"}, {"A": "prod", "B": "median"}] +) +def test_multi_agg_axis_1_raises(func): + # GH#46904 + + index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") + index.name = "date" + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index + ).T + warning_msg = "DataFrame.resample with axis=1 is deprecated." + with tm.assert_produces_warning(FutureWarning, match=warning_msg): + res = df.resample("ME", axis=1) + with pytest.raises( + NotImplementedError, match="axis other than 0 is not supported" + ): + res.agg(func) + + +def test_agg_nested_dicts(): + index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") + index.name = "date" + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index + ) + df_col = df.reset_index() + df_mult = df_col.copy() + df_mult.index = pd.MultiIndex.from_arrays( + [range(10), df.index], names=["index", "date"] + ) + r = df.resample("2D") + cases = [ + r, + df_col.resample("2D", on="date"), + df_mult.resample("2D", level="date"), + df.groupby(pd.Grouper(freq="2D")), + ] + + msg = "nested renamer is not supported" + for t in cases: + with pytest.raises(pd.errors.SpecificationError, match=msg): + t.aggregate({"r1": {"A": ["mean", "sum"]}, "r2": {"B": ["mean", "sum"]}}) + + for t in cases: + with pytest.raises(pd.errors.SpecificationError, match=msg): + t[["A", "B"]].agg( + {"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}} + ) + + with pytest.raises(pd.errors.SpecificationError, match=msg): + t.agg({"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}}) + + +def test_try_aggregate_non_existing_column(): + # GH 16766 + data = [ + {"dt": datetime(2017, 6, 1, 0), "x": 1.0, "y": 2.0}, + {"dt": datetime(2017, 6, 1, 1), "x": 2.0, "y": 2.0}, + {"dt": datetime(2017, 6, 1, 2), "x": 3.0, "y": 1.5}, + ] + df = DataFrame(data).set_index("dt") + + # Error as we don't have 'z' column + msg = r"Column\(s\) \['z'\] do not exist" + with pytest.raises(KeyError, match=msg): + df.resample("30min").agg({"x": ["mean"], "y": ["median"], "z": ["sum"]}) + + +def test_agg_list_like_func_with_args(): + # 50624 + df = DataFrame( + {"x": [1, 2, 3]}, index=date_range("2020-01-01", periods=3, freq="D") + ) + + def foo1(x, a=1, c=0): + return x + a + c + + def foo2(x, b=2, c=0): + return x + b + c + + msg = r"foo1\(\) got an unexpected keyword argument 'b'" + with pytest.raises(TypeError, match=msg): + df.resample("D").agg([foo1, foo2], 3, b=3, c=4) + + result = df.resample("D").agg([foo1, foo2], 3, c=4) + expected = DataFrame( + [[8, 8], [9, 9], [10, 10]], + index=date_range("2020-01-01", periods=3, freq="D"), + columns=pd.MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]), + ) + tm.assert_frame_equal(result, expected) + + +def test_selection_api_validation(): + # GH 13500 + index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") + + rng = np.arange(len(index), dtype=np.int64) + df = DataFrame( + {"date": index, "a": rng}, + index=pd.MultiIndex.from_arrays([rng, index], names=["v", "d"]), + ) + df_exp = DataFrame({"a": rng}, index=index) + + # non DatetimeIndex + msg = ( + "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, " + "but got an instance of 'Index'" + ) + with pytest.raises(TypeError, match=msg): + df.resample("2D", level="v") + + msg = "The Grouper cannot specify both a key and a level!" + with pytest.raises(ValueError, match=msg): + df.resample("2D", on="date", level="d") + + msg = "unhashable type: 'list'" + with pytest.raises(TypeError, match=msg): + df.resample("2D", on=["a", "date"]) + + msg = r"\"Level \['a', 'date'\] not found\"" + with pytest.raises(KeyError, match=msg): + df.resample("2D", level=["a", "date"]) + + # upsampling not allowed + msg = ( + "Upsampling from level= or on= selection is not supported, use " + r"\.set_index\(\.\.\.\) to explicitly set index to datetime-like" + ) + with pytest.raises(ValueError, match=msg): + df.resample("2D", level="d").asfreq() + with pytest.raises(ValueError, match=msg): + df.resample("2D", on="date").asfreq() + + exp = df_exp.resample("2D").sum() + exp.index.name = "date" + result = df.resample("2D", on="date").sum() + tm.assert_frame_equal(exp, result) + + exp.index.name = "d" + with pytest.raises(TypeError, match="datetime64 type does not support sum"): + df.resample("2D", level="d").sum() + result = df.resample("2D", level="d").sum(numeric_only=True) + tm.assert_frame_equal(exp, result) + + +@pytest.mark.parametrize( + "col_name", ["t2", "t2x", "t2q", "T_2M", "t2p", "t2m", "t2m1", "T2M"] +) +def test_agg_with_datetime_index_list_agg_func(col_name): + # GH 22660 + # The parametrized column names would get converted to dates by our + # date parser. Some would result in OutOfBoundsError (ValueError) while + # others would result in OverflowError when passed into Timestamp. + # We catch these errors and move on to the correct branch. + df = DataFrame( + list(range(200)), + index=date_range( + start="2017-01-01", freq="15min", periods=200, tz="Europe/Berlin" + ), + columns=[col_name], + ) + result = df.resample("1d").aggregate(["mean"]) + expected = DataFrame( + [47.5, 143.5, 195.5], + index=date_range(start="2017-01-01", freq="D", periods=3, tz="Europe/Berlin"), + columns=pd.MultiIndex(levels=[[col_name], ["mean"]], codes=[[0], [0]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_resample_agg_readonly(): + # GH#31710 cython needs to allow readonly data + index = date_range("2020-01-01", "2020-01-02", freq="1h") + arr = np.zeros_like(index) + arr.setflags(write=False) + + ser = Series(arr, index=index) + rs = ser.resample("1D") + + expected = Series([pd.Timestamp(0), pd.Timestamp(0)], index=index[::24]) + + result = rs.agg("last") + tm.assert_series_equal(result, expected) + + result = rs.agg("first") + tm.assert_series_equal(result, expected) + + result = rs.agg("max") + tm.assert_series_equal(result, expected) + + result = rs.agg("min") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "start,end,freq,data,resample_freq,origin,closed,exp_data,exp_end,exp_periods", + [ + ( + "2000-10-01 23:30:00", + "2000-10-02 00:26:00", + "7min", + [0, 3, 6, 9, 12, 15, 18, 21, 24], + "17min", + "end", + None, + [0, 18, 27, 63], + "20001002 00:26:00", + 4, + ), + ( + "20200101 8:26:35", + "20200101 9:31:58", + "77s", + [1] * 51, + "7min", + "end", + "right", + [1, 6, 5, 6, 5, 6, 5, 6, 5, 6], + "2020-01-01 09:30:45", + 10, + ), + ( + "2000-10-01 23:30:00", + "2000-10-02 00:26:00", + "7min", + [0, 3, 6, 9, 12, 15, 18, 21, 24], + "17min", + "end", + "left", + [0, 18, 27, 39, 24], + "20001002 00:43:00", + 5, + ), + ( + "2000-10-01 23:30:00", + "2000-10-02 00:26:00", + "7min", + [0, 3, 6, 9, 12, 15, 18, 21, 24], + "17min", + "end_day", + None, + [3, 15, 45, 45], + "2000-10-02 00:29:00", + 4, + ), + ], +) +def test_end_and_end_day_origin( + start, + end, + freq, + data, + resample_freq, + origin, + closed, + exp_data, + exp_end, + exp_periods, +): + rng = date_range(start, end, freq=freq) + ts = Series(data, index=rng) + + res = ts.resample(resample_freq, origin=origin, closed=closed).sum() + expected = Series( + exp_data, + index=date_range(end=exp_end, freq=resample_freq, periods=exp_periods), + ) + + tm.assert_series_equal(res, expected) + + +@pytest.mark.parametrize( + # expected_data is a string when op raises a ValueError + "method, numeric_only, expected_data", + [ + ("sum", True, {"num": [25]}), + ("sum", False, {"cat": ["cat_1cat_2"], "num": [25]}), + ("sum", lib.no_default, {"cat": ["cat_1cat_2"], "num": [25]}), + ("prod", True, {"num": [100]}), + ("prod", False, "can't multiply sequence"), + ("prod", lib.no_default, "can't multiply sequence"), + ("min", True, {"num": [5]}), + ("min", False, {"cat": ["cat_1"], "num": [5]}), + ("min", lib.no_default, {"cat": ["cat_1"], "num": [5]}), + ("max", True, {"num": [20]}), + ("max", False, {"cat": ["cat_2"], "num": [20]}), + ("max", lib.no_default, {"cat": ["cat_2"], "num": [20]}), + ("first", True, {"num": [5]}), + ("first", False, {"cat": ["cat_1"], "num": [5]}), + ("first", lib.no_default, {"cat": ["cat_1"], "num": [5]}), + ("last", True, {"num": [20]}), + ("last", False, {"cat": ["cat_2"], "num": [20]}), + ("last", lib.no_default, {"cat": ["cat_2"], "num": [20]}), + ("mean", True, {"num": [12.5]}), + ("mean", False, "Could not convert"), + ("mean", lib.no_default, "Could not convert"), + ("median", True, {"num": [12.5]}), + ("median", False, r"Cannot convert \['cat_1' 'cat_2'\] to numeric"), + ("median", lib.no_default, r"Cannot convert \['cat_1' 'cat_2'\] to numeric"), + ("std", True, {"num": [10.606601717798213]}), + ("std", False, "could not convert string to float"), + ("std", lib.no_default, "could not convert string to float"), + ("var", True, {"num": [112.5]}), + ("var", False, "could not convert string to float"), + ("var", lib.no_default, "could not convert string to float"), + ("sem", True, {"num": [7.5]}), + ("sem", False, "could not convert string to float"), + ("sem", lib.no_default, "could not convert string to float"), + ], +) +def test_frame_downsample_method( + method, numeric_only, expected_data, using_infer_string +): + # GH#46442 test if `numeric_only` behave as expected for DataFrameGroupBy + + index = date_range("2018-01-01", periods=2, freq="D") + expected_index = date_range("2018-12-31", periods=1, freq="YE") + df = DataFrame({"cat": ["cat_1", "cat_2"], "num": [5, 20]}, index=index) + resampled = df.resample("YE") + if numeric_only is lib.no_default: + kwargs = {} + else: + kwargs = {"numeric_only": numeric_only} + + func = getattr(resampled, method) + if isinstance(expected_data, str): + if method in ("var", "mean", "median", "prod"): + klass = TypeError + msg = re.escape(f"agg function failed [how->{method},dtype->") + if using_infer_string: + msg = f"dtype 'str' does not support operation '{method}'" + elif method in ["sum", "std", "sem"] and using_infer_string: + klass = TypeError + msg = f"dtype 'str' does not support operation '{method}'" + else: + klass = ValueError + msg = expected_data + with pytest.raises(klass, match=msg): + _ = func(**kwargs) + else: + result = func(**kwargs) + expected = DataFrame(expected_data, index=expected_index) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "method, numeric_only, expected_data", + [ + ("sum", True, ()), + ("sum", False, ["cat_1cat_2"]), + ("sum", lib.no_default, ["cat_1cat_2"]), + ("prod", True, ()), + ("prod", False, ()), + ("prod", lib.no_default, ()), + ("min", True, ()), + ("min", False, ["cat_1"]), + ("min", lib.no_default, ["cat_1"]), + ("max", True, ()), + ("max", False, ["cat_2"]), + ("max", lib.no_default, ["cat_2"]), + ("first", True, ()), + ("first", False, ["cat_1"]), + ("first", lib.no_default, ["cat_1"]), + ("last", True, ()), + ("last", False, ["cat_2"]), + ("last", lib.no_default, ["cat_2"]), + ], +) +def test_series_downsample_method( + method, numeric_only, expected_data, using_infer_string +): + # GH#46442 test if `numeric_only` behave as expected for SeriesGroupBy + + index = date_range("2018-01-01", periods=2, freq="D") + expected_index = date_range("2018-12-31", periods=1, freq="YE") + df = Series(["cat_1", "cat_2"], index=index) + resampled = df.resample("YE") + kwargs = {} if numeric_only is lib.no_default else {"numeric_only": numeric_only} + + func = getattr(resampled, method) + if numeric_only and numeric_only is not lib.no_default: + msg = rf"Cannot use numeric_only=True with SeriesGroupBy\.{method}" + with pytest.raises(TypeError, match=msg): + func(**kwargs) + elif method == "prod": + msg = re.escape("agg function failed [how->prod,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'prod'" + with pytest.raises(TypeError, match=msg): + func(**kwargs) + + else: + result = func(**kwargs) + expected = Series(expected_data, index=expected_index) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "method, raises", + [ + ("sum", True), + ("prod", True), + ("min", True), + ("max", True), + ("first", False), + ("last", False), + ("median", False), + ("mean", True), + ("std", True), + ("var", True), + ("sem", False), + ("ohlc", False), + ("nunique", False), + ], +) +def test_args_kwargs_depr(method, raises): + index = date_range("20180101", periods=3, freq="h") + df = Series([2, 4, 6], index=index) + resampled = df.resample("30min") + args = () + + func = getattr(resampled, method) + + error_msg = "numpy operations are not valid with resample." + error_msg_type = "too many arguments passed in" + warn_msg = f"Passing additional args to DatetimeIndexResampler.{method}" + + if raises: + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + with pytest.raises(UnsupportedFunctionCall, match=error_msg): + func(*args, 1, 2, 3, 4) + else: + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + with pytest.raises(TypeError, match=error_msg_type): + func(*args, 1, 2, 3, 4) + + +def test_df_axis_param_depr(): + index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") + index.name = "date" + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index + ).T + + # Deprecation error when axis=1 is explicitly passed + warning_msg = "DataFrame.resample with axis=1 is deprecated." + with tm.assert_produces_warning(FutureWarning, match=warning_msg): + df.resample("ME", axis=1) + + # Deprecation error when axis=0 is explicitly passed + df = df.T + warning_msg = ( + "The 'axis' keyword in DataFrame.resample is deprecated and " + "will be removed in a future version." + ) + with tm.assert_produces_warning(FutureWarning, match=warning_msg): + df.resample("ME", axis=0) + + +def test_series_axis_param_depr(_test_series): + warning_msg = ( + "The 'axis' keyword in Series.resample is " + "deprecated and will be removed in a future version." + ) + with tm.assert_produces_warning(FutureWarning, match=warning_msg): + _test_series.resample("h", axis=0) + + +def test_resample_empty(): + # GH#52484 + df = DataFrame( + index=pd.to_datetime( + ["2018-01-01 00:00:00", "2018-01-01 12:00:00", "2018-01-02 00:00:00"] + ) + ) + expected = DataFrame( + index=pd.to_datetime( + [ + "2018-01-01 00:00:00", + "2018-01-01 08:00:00", + "2018-01-01 16:00:00", + "2018-01-02 00:00:00", + ] + ) + ) + result = df.resample("8h").mean() + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/75/750d3bcc9d7ebe5a45a96041bbf734707c53d325dc192bbba3b2f10c2132077b/blob b/shared/package-files/75/750d3bcc9d7ebe5a45a96041bbf734707c53d325dc192bbba3b2f10c2132077b/blob new file mode 100644 index 0000000000000000000000000000000000000000..70ebd3d061b78da4e274dd81dec4492257044097 --- /dev/null +++ b/shared/package-files/75/750d3bcc9d7ebe5a45a96041bbf734707c53d325dc192bbba3b2f10c2132077b/blob @@ -0,0 +1,274 @@ +"""Helper functions for writing to terminals and files.""" + +from __future__ import annotations + +import os +import shutil +import sys +from typing import final +from typing import Literal +from typing import Sequence +from typing import TextIO +from typing import TYPE_CHECKING + +from ..compat import assert_never +from .wcwidth import wcswidth + + +if TYPE_CHECKING: + from pygments.formatter import Formatter + from pygments.lexer import Lexer + + +# This code was initially copied from py 1.8.1, file _io/terminalwriter.py. + + +def get_terminal_width() -> int: + width, _ = shutil.get_terminal_size(fallback=(80, 24)) + + # The Windows get_terminal_size may be bogus, let's sanify a bit. + if width < 40: + width = 80 + + return width + + +def should_do_markup(file: TextIO) -> bool: + if os.environ.get("PY_COLORS") == "1": + return True + if os.environ.get("PY_COLORS") == "0": + return False + if os.environ.get("NO_COLOR"): + return False + if os.environ.get("FORCE_COLOR"): + return True + return ( + hasattr(file, "isatty") and file.isatty() and os.environ.get("TERM") != "dumb" + ) + + +@final +class TerminalWriter: + _esctable = dict( + black=30, + red=31, + green=32, + yellow=33, + blue=34, + purple=35, + cyan=36, + white=37, + Black=40, + Red=41, + Green=42, + Yellow=43, + Blue=44, + Purple=45, + Cyan=46, + White=47, + bold=1, + light=2, + blink=5, + invert=7, + ) + + def __init__(self, file: TextIO | None = None) -> None: + if file is None: + file = sys.stdout + if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32": + try: + import colorama + except ImportError: + pass + else: + file = colorama.AnsiToWin32(file).stream + assert file is not None + self._file = file + self.hasmarkup = should_do_markup(file) + self._current_line = "" + self._terminal_width: int | None = None + self.code_highlight = True + + @property + def fullwidth(self) -> int: + if self._terminal_width is not None: + return self._terminal_width + return get_terminal_width() + + @fullwidth.setter + def fullwidth(self, value: int) -> None: + self._terminal_width = value + + @property + def width_of_current_line(self) -> int: + """Return an estimate of the width so far in the current line.""" + return wcswidth(self._current_line) + + def markup(self, text: str, **markup: bool) -> str: + for name in markup: + if name not in self._esctable: + raise ValueError(f"unknown markup: {name!r}") + if self.hasmarkup: + esc = [self._esctable[name] for name, on in markup.items() if on] + if esc: + text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m" + return text + + def sep( + self, + sepchar: str, + title: str | None = None, + fullwidth: int | None = None, + **markup: bool, + ) -> None: + if fullwidth is None: + fullwidth = self.fullwidth + # The goal is to have the line be as long as possible + # under the condition that len(line) <= fullwidth. + if sys.platform == "win32": + # If we print in the last column on windows we are on a + # new line but there is no way to verify/neutralize this + # (we may not know the exact line width). + # So let's be defensive to avoid empty lines in the output. + fullwidth -= 1 + if title is not None: + # we want 2 + 2*len(fill) + len(title) <= fullwidth + # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth + # 2*len(sepchar)*N <= fullwidth - len(title) - 2 + # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) + N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1) + fill = sepchar * N + line = f"{fill} {title} {fill}" + else: + # we want len(sepchar)*N <= fullwidth + # i.e. N <= fullwidth // len(sepchar) + line = sepchar * (fullwidth // len(sepchar)) + # In some situations there is room for an extra sepchar at the right, + # in particular if we consider that with a sepchar like "_ " the + # trailing space is not important at the end of the line. + if len(line) + len(sepchar.rstrip()) <= fullwidth: + line += sepchar.rstrip() + + self.line(line, **markup) + + def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None: + if msg: + current_line = msg.rsplit("\n", 1)[-1] + if "\n" in msg: + self._current_line = current_line + else: + self._current_line += current_line + + msg = self.markup(msg, **markup) + + try: + self._file.write(msg) + except UnicodeEncodeError: + # Some environments don't support printing general Unicode + # strings, due to misconfiguration or otherwise; in that case, + # print the string escaped to ASCII. + # When the Unicode situation improves we should consider + # letting the error propagate instead of masking it (see #7475 + # for one brief attempt). + msg = msg.encode("unicode-escape").decode("ascii") + self._file.write(msg) + + if flush: + self.flush() + + def line(self, s: str = "", **markup: bool) -> None: + self.write(s, **markup) + self.write("\n") + + def flush(self) -> None: + self._file.flush() + + def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None: + """Write lines of source code possibly highlighted. + + Keeping this private for now because the API is clunky. We should discuss how + to evolve the terminal writer so we can have more precise color support, for example + being able to write part of a line in one color and the rest in another, and so on. + """ + if indents and len(indents) != len(lines): + raise ValueError( + f"indents size ({len(indents)}) should have same size as lines ({len(lines)})" + ) + if not indents: + indents = [""] * len(lines) + source = "\n".join(lines) + new_lines = self._highlight(source).splitlines() + for indent, new_line in zip(indents, new_lines): + self.line(indent + new_line) + + def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer | None: + try: + if lexer == "python": + from pygments.lexers.python import PythonLexer + + return PythonLexer() + elif lexer == "diff": + from pygments.lexers.diff import DiffLexer + + return DiffLexer() + else: + assert_never(lexer) + except ModuleNotFoundError: + return None + + def _get_pygments_formatter(self) -> Formatter | None: + try: + import pygments.util + except ModuleNotFoundError: + return None + + from _pytest.config.exceptions import UsageError + + theme = os.getenv("PYTEST_THEME") + theme_mode = os.getenv("PYTEST_THEME_MODE", "dark") + + try: + from pygments.formatters.terminal import TerminalFormatter + + return TerminalFormatter(bg=theme_mode, style=theme) + + except pygments.util.ClassNotFound as e: + raise UsageError( + f"PYTEST_THEME environment variable has an invalid value: '{theme}'. " + "Hint: See available pygments styles with `pygmentize -L styles`." + ) from e + except pygments.util.OptionError as e: + raise UsageError( + f"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. " + "The allowed values are 'dark' (default) and 'light'." + ) from e + + def _highlight( + self, source: str, lexer: Literal["diff", "python"] = "python" + ) -> str: + """Highlight the given source if we have markup support.""" + if not source or not self.hasmarkup or not self.code_highlight: + return source + + pygments_lexer = self._get_pygments_lexer(lexer) + if pygments_lexer is None: + return source + + pygments_formatter = self._get_pygments_formatter() + if pygments_formatter is None: + return source + + from pygments import highlight + + highlighted: str = highlight(source, pygments_lexer, pygments_formatter) + # pygments terminal formatter may add a newline when there wasn't one. + # We don't want this, remove. + if highlighted[-1] == "\n" and source[-1] != "\n": + highlighted = highlighted[:-1] + + # Some lexers will not set the initial color explicitly + # which may lead to the previous color being propagated to the + # start of the expression, so reset first. + highlighted = "\x1b[0m" + highlighted + + return highlighted diff --git a/shared/package-files/75/750dae72b20664681807a852e202c8cc5283118a5f00135b3f9e254bb1fa0084/blob b/shared/package-files/75/750dae72b20664681807a852e202c8cc5283118a5f00135b3f9e254bb1fa0084/blob new file mode 100644 index 0000000000000000000000000000000000000000..0921dbf5556bd8ef49a1b0468e2a765ed20b486c --- /dev/null +++ b/shared/package-files/75/750dae72b20664681807a852e202c8cc5283118a5f00135b3f9e254bb1fa0084/blob @@ -0,0 +1,747 @@ +""" +C code printer + +The C89CodePrinter & C99CodePrinter converts single SymPy expressions into +single C expressions, using the functions defined in math.h where possible. + +A complete code generator, which uses ccode extensively, can be found in +sympy.utilities.codegen. The codegen module can be used to generate complete +source code files that are compilable without further modifications. + + +""" + +from __future__ import annotations +from typing import Any + +from functools import wraps +from itertools import chain + +from sympy.core import S +from sympy.core.numbers import equal_valued +from sympy.codegen.ast import ( + Assignment, Pointer, Variable, Declaration, Type, + real, complex_, integer, bool_, float32, float64, float80, + complex64, complex128, intc, value_const, pointer_const, + int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped, + none +) +from sympy.printing.codeprinter import CodePrinter, requires +from sympy.printing.precedence import precedence, PRECEDENCE +from sympy.sets.fancysets import Range + +# These are defined in the other file so we can avoid importing sympy.codegen +# from the top-level 'import sympy'. Export them here as well. +from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401 + +# dictionary mapping SymPy function to (argument_conditions, C_function). +# Used in C89CodePrinter._print_Function(self) +known_functions_C89 = { + "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], + "sin": "sin", + "cos": "cos", + "tan": "tan", + "asin": "asin", + "acos": "acos", + "atan": "atan", + "atan2": "atan2", + "exp": "exp", + "log": "log", + "sinh": "sinh", + "cosh": "cosh", + "tanh": "tanh", + "floor": "floor", + "ceiling": "ceil", + "sqrt": "sqrt", # To enable automatic rewrites +} + +known_functions_C99 = dict(known_functions_C89, **{ + 'exp2': 'exp2', + 'expm1': 'expm1', + 'log10': 'log10', + 'log2': 'log2', + 'log1p': 'log1p', + 'Cbrt': 'cbrt', + 'hypot': 'hypot', + 'fma': 'fma', + 'loggamma': 'lgamma', + 'erfc': 'erfc', + 'Max': 'fmax', + 'Min': 'fmin', + "asinh": "asinh", + "acosh": "acosh", + "atanh": "atanh", + "erf": "erf", + "gamma": "tgamma", +}) + +# These are the core reserved words in the C language. Taken from: +# https://en.cppreference.com/w/c/keyword + +reserved_words = [ + 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', + 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int', + 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static', + 'struct', 'entry', # never standardized, we'll leave it here anyway + 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while' +] + +reserved_words_c99 = ['inline', 'restrict'] + +def get_math_macros(): + """ Returns a dictionary with math-related macros from math.h/cmath + + Note that these macros are not strictly required by the C/C++-standard. + For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably + via a compilation flag). + + Returns + ======= + + Dictionary mapping SymPy expressions to strings (macro names) + + """ + from sympy.codegen.cfunctions import log2, Sqrt + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.miscellaneous import sqrt + + return { + S.Exp1: 'M_E', + log2(S.Exp1): 'M_LOG2E', + 1/log(2): 'M_LOG2E', + log(2): 'M_LN2', + log(10): 'M_LN10', + S.Pi: 'M_PI', + S.Pi/2: 'M_PI_2', + S.Pi/4: 'M_PI_4', + 1/S.Pi: 'M_1_PI', + 2/S.Pi: 'M_2_PI', + 2/sqrt(S.Pi): 'M_2_SQRTPI', + 2/Sqrt(S.Pi): 'M_2_SQRTPI', + sqrt(2): 'M_SQRT2', + Sqrt(2): 'M_SQRT2', + 1/sqrt(2): 'M_SQRT1_2', + 1/Sqrt(2): 'M_SQRT1_2' + } + + +def _as_macro_if_defined(meth): + """ Decorator for printer methods + + When a Printer's method is decorated using this decorator the expressions printed + will first be looked for in the attribute ``math_macros``, and if present it will + print the macro name in ``math_macros`` followed by a type suffix for the type + ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80. + + """ + @wraps(meth) + def _meth_wrapper(self, expr, **kwargs): + if expr in self.math_macros: + return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real)) + else: + return meth(self, expr, **kwargs) + + return _meth_wrapper + + +class C89CodePrinter(CodePrinter): + """A printer to convert Python expressions to strings of C code""" + printmethod = "_ccode" + language = "C" + standard = "C89" + reserved_words = set(reserved_words) + + _default_settings: dict[str, Any] = { + 'order': None, + 'full_prec': 'auto', + 'precision': 17, + 'user_functions': {}, + 'human': True, + 'allow_unknown_functions': False, + 'contract': True, + 'dereference': set(), + 'error_on_reserved': False, + 'reserved_word_suffix': '_', + } + + type_aliases = { + real: float64, + complex_: complex128, + integer: intc + } + + type_mappings: dict[Type, Any] = { + real: 'double', + intc: 'int', + float32: 'float', + float64: 'double', + integer: 'int', + bool_: 'bool', + int8: 'int8_t', + int16: 'int16_t', + int32: 'int32_t', + int64: 'int64_t', + uint8: 'int8_t', + uint16: 'int16_t', + uint32: 'int32_t', + uint64: 'int64_t', + } + + type_headers = { + bool_: {'stdbool.h'}, + int8: {'stdint.h'}, + int16: {'stdint.h'}, + int32: {'stdint.h'}, + int64: {'stdint.h'}, + uint8: {'stdint.h'}, + uint16: {'stdint.h'}, + uint32: {'stdint.h'}, + uint64: {'stdint.h'}, + } + + # Macros needed to be defined when using a Type + type_macros: dict[Type, tuple[str, ...]] = {} + + type_func_suffixes = { + float32: 'f', + float64: '', + float80: 'l' + } + + type_literal_suffixes = { + float32: 'F', + float64: '', + float80: 'L' + } + + type_math_macro_suffixes = { + float80: 'l' + } + + math_macros = None + + _ns = '' # namespace, C++ uses 'std::' + # known_functions-dict to copy + _kf: dict[str, Any] = known_functions_C89 + + def __init__(self, settings=None): + settings = settings or {} + if self.math_macros is None: + self.math_macros = settings.pop('math_macros', get_math_macros()) + self.type_aliases = dict(chain(self.type_aliases.items(), + settings.pop('type_aliases', {}).items())) + self.type_mappings = dict(chain(self.type_mappings.items(), + settings.pop('type_mappings', {}).items())) + self.type_headers = dict(chain(self.type_headers.items(), + settings.pop('type_headers', {}).items())) + self.type_macros = dict(chain(self.type_macros.items(), + settings.pop('type_macros', {}).items())) + self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(), + settings.pop('type_func_suffixes', {}).items())) + self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(), + settings.pop('type_literal_suffixes', {}).items())) + self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(), + settings.pop('type_math_macro_suffixes', {}).items())) + super().__init__(settings) + self.known_functions = dict(self._kf, **settings.get('user_functions', {})) + self._dereference = set(settings.get('dereference', [])) + self.headers = set() + self.libraries = set() + self.macros = set() + + def _rate_index_position(self, p): + return p*5 + + def _get_statement(self, codestring): + """ Get code string as a statement - i.e. ending with a semicolon. """ + return codestring if codestring.endswith(';') else codestring + ';' + + def _get_comment(self, text): + return "/* {} */".format(text) + + def _declare_number_const(self, name, value): + type_ = self.type_aliases[real] + var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const}) + decl = Declaration(var) + return self._get_statement(self._print(decl)) + + def _format_code(self, lines): + return self.indent_code(lines) + + def _traverse_matrix_indices(self, mat): + rows, cols = mat.shape + return ((i, j) for i in range(rows) for j in range(cols)) + + @_as_macro_if_defined + def _print_Mul(self, expr, **kwargs): + return super()._print_Mul(expr, **kwargs) + + @_as_macro_if_defined + def _print_Pow(self, expr): + if "Pow" in self.known_functions: + return self._print_Function(expr) + PREC = precedence(expr) + suffix = self._get_func_suffix(real) + if equal_valued(expr.exp, -1): + literal_suffix = self._get_literal_suffix(real) + return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC)) + elif equal_valued(expr.exp, 0.5): + return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base)) + elif expr.exp == S.One/3 and self.standard != 'C89': + return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base)) + else: + return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base), + self._print(expr.exp)) + + def _print_Mod(self, expr): + num, den = expr.args + if num.is_integer and den.is_integer: + PREC = precedence(expr) + snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args] + # % is remainder (same sign as numerator), not modulo (same sign as + # denominator), in C. Hence, % only works as modulo if both numbers + # have the same sign + if (num.is_nonnegative and den.is_nonnegative or + num.is_nonpositive and den.is_nonpositive): + return f"{snum} % {sden}" + return f"(({snum} % {sden}) + {sden}) % {sden}" + # Not guaranteed integer + return self._print_math_func(expr, known='fmod') + + def _print_Rational(self, expr): + p, q = int(expr.p), int(expr.q) + suffix = self._get_literal_suffix(real) + return '%d.0%s/%d.0%s' % (p, suffix, q, suffix) + + def _print_Indexed(self, expr): + # calculate index for 1d array + offset = getattr(expr.base, 'offset', S.Zero) + strides = getattr(expr.base, 'strides', None) + indices = expr.indices + + if strides is None or isinstance(strides, str): + dims = expr.shape + shift = S.One + temp = () + if strides == 'C' or strides is None: + traversal = reversed(range(expr.rank)) + indices = indices[::-1] + elif strides == 'F': + traversal = range(expr.rank) + + for i in traversal: + temp += (shift,) + shift *= dims[i] + strides = temp + flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset + return "%s[%s]" % (self._print(expr.base.label), + self._print(flat_index)) + + def _print_Idx(self, expr): + return self._print(expr.label) + + @_as_macro_if_defined + def _print_NumberSymbol(self, expr): + return super()._print_NumberSymbol(expr) + + def _print_Infinity(self, expr): + return 'HUGE_VAL' + + def _print_NegativeInfinity(self, expr): + return '-HUGE_VAL' + + def _print_Piecewise(self, expr): + if expr.args[-1].cond != True: + # We need the last conditional to be a True, otherwise the resulting + # function may not return a result. + raise ValueError("All Piecewise expressions must contain an " + "(expr, True) statement to be used as a default " + "condition. Without one, the generated " + "expression may not evaluate to anything under " + "some condition.") + lines = [] + if expr.has(Assignment): + for i, (e, c) in enumerate(expr.args): + if i == 0: + lines.append("if (%s) {" % self._print(c)) + elif i == len(expr.args) - 1 and c == True: + lines.append("else {") + else: + lines.append("else if (%s) {" % self._print(c)) + code0 = self._print(e) + lines.append(code0) + lines.append("}") + return "\n".join(lines) + else: + # The piecewise was used in an expression, need to do inline + # operators. This has the downside that inline operators will + # not work for statements that span multiple lines (Matrix or + # Indexed expressions). + ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), + self._print(e)) + for e, c in expr.args[:-1]] + last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) + return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) + + def _print_ITE(self, expr): + from sympy.functions import Piecewise + return self._print(expr.rewrite(Piecewise, deep=False)) + + def _print_MatrixElement(self, expr): + return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], + strict=True), expr.j + expr.i*expr.parent.shape[1]) + + def _print_Symbol(self, expr): + name = super()._print_Symbol(expr) + if expr in self._settings['dereference']: + return '(*{})'.format(name) + else: + return name + + def _print_Relational(self, expr): + lhs_code = self._print(expr.lhs) + rhs_code = self._print(expr.rhs) + op = expr.rel_op + return "{} {} {}".format(lhs_code, op, rhs_code) + + def _print_For(self, expr): + target = self._print(expr.target) + if isinstance(expr.iterable, Range): + start, stop, step = expr.iterable.args + else: + raise NotImplementedError("Only iterable currently supported is Range") + body = self._print(expr.body) + return ('for ({target} = {start}; {target} < {stop}; {target} += ' + '{step}) {{\n{body}\n}}').format(target=target, start=start, + stop=stop, step=step, body=body) + + def _print_sign(self, func): + return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0])) + + def _print_Max(self, expr): + if "Max" in self.known_functions: + return self._print_Function(expr) + def inner_print_max(args): # The more natural abstraction of creating + if len(args) == 1: # and printing smaller Max objects is slow + return self._print(args[0]) # when there are many arguments. + half = len(args) // 2 + return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % { + 'a': inner_print_max(args[:half]), + 'b': inner_print_max(args[half:]) + } + return inner_print_max(expr.args) + + def _print_Min(self, expr): + if "Min" in self.known_functions: + return self._print_Function(expr) + def inner_print_min(args): # The more natural abstraction of creating + if len(args) == 1: # and printing smaller Min objects is slow + return self._print(args[0]) # when there are many arguments. + half = len(args) // 2 + return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % { + 'a': inner_print_min(args[:half]), + 'b': inner_print_min(args[half:]) + } + return inner_print_min(expr.args) + + def indent_code(self, code): + """Accepts a string of code or a list of code lines""" + + if isinstance(code, str): + code_lines = self.indent_code(code.splitlines(True)) + return ''.join(code_lines) + + tab = " " + inc_token = ('{', '(', '{\n', '(\n') + dec_token = ('}', ')') + + code = [line.lstrip(' \t') for line in code] + + increase = [int(any(map(line.endswith, inc_token))) for line in code] + decrease = [int(any(map(line.startswith, dec_token))) for line in code] + + pretty = [] + level = 0 + for n, line in enumerate(code): + if line in ('', '\n'): + pretty.append(line) + continue + level -= decrease[n] + pretty.append("%s%s" % (tab*level, line)) + level += increase[n] + return pretty + + def _get_func_suffix(self, type_): + return self.type_func_suffixes[self.type_aliases.get(type_, type_)] + + def _get_literal_suffix(self, type_): + return self.type_literal_suffixes[self.type_aliases.get(type_, type_)] + + def _get_math_macro_suffix(self, type_): + alias = self.type_aliases.get(type_, type_) + dflt = self.type_math_macro_suffixes.get(alias, '') + return self.type_math_macro_suffixes.get(type_, dflt) + + def _print_Tuple(self, expr): + return '{'+', '.join(self._print(e) for e in expr)+'}' + + _print_List = _print_Tuple + + def _print_Type(self, type_): + self.headers.update(self.type_headers.get(type_, set())) + self.macros.update(self.type_macros.get(type_, set())) + return self._print(self.type_mappings.get(type_, type_.name)) + + def _print_Declaration(self, decl): + from sympy.codegen.cnodes import restrict + var = decl.variable + val = var.value + if var.type == untyped: + raise ValueError("C does not support untyped variables") + + if isinstance(var, Pointer): + result = '{vc}{t} *{pc} {r}{s}'.format( + vc='const ' if value_const in var.attrs else '', + t=self._print(var.type), + pc=' const' if pointer_const in var.attrs else '', + r='restrict ' if restrict in var.attrs else '', + s=self._print(var.symbol) + ) + elif isinstance(var, Variable): + result = '{vc}{t} {s}'.format( + vc='const ' if value_const in var.attrs else '', + t=self._print(var.type), + s=self._print(var.symbol) + ) + else: + raise NotImplementedError("Unknown type of var: %s" % type(var)) + if val != None: # Must be "!= None", cannot be "is not None" + result += ' = %s' % self._print(val) + return result + + def _print_Float(self, flt): + type_ = self.type_aliases.get(real, real) + self.macros.update(self.type_macros.get(type_, set())) + suffix = self._get_literal_suffix(type_) + num = str(flt.evalf(type_.decimal_dig)) + if 'e' not in num and '.' not in num: + num += '.0' + num_parts = num.split('e') + num_parts[0] = num_parts[0].rstrip('0') + if num_parts[0].endswith('.'): + num_parts[0] += '0' + return 'e'.join(num_parts) + suffix + + @requires(headers={'stdbool.h'}) + def _print_BooleanTrue(self, expr): + return 'true' + + @requires(headers={'stdbool.h'}) + def _print_BooleanFalse(self, expr): + return 'false' + + def _print_Element(self, elem): + if elem.strides == None: # Must be "== None", cannot be "is None" + if elem.offset != None: # Must be "!= None", cannot be "is not None" + raise ValueError("Expected strides when offset is given") + idxs = ']['.join((self._print(arg) for arg in elem.indices)) + else: + global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)]) + if elem.offset != None: # Must be "!= None", cannot be "is not None" + global_idx += elem.offset + idxs = self._print(global_idx) + + return "{symb}[{idxs}]".format( + symb=self._print(elem.symbol), + idxs=idxs + ) + + def _print_CodeBlock(self, expr): + """ Elements of code blocks printed as statements. """ + return '\n'.join([self._get_statement(self._print(i)) for i in expr.args]) + + def _print_While(self, expr): + return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs( + apply=lambda arg: self._print(arg))) + + def _print_Scope(self, expr): + return '{\n%s\n}' % self._print_CodeBlock(expr.body) + + @requires(headers={'stdio.h'}) + def _print_Print(self, expr): + return 'printf({fmt}, {pargs})'.format( + fmt=self._print(expr.format_string), + pargs=', '.join((self._print(arg) for arg in expr.print_args)) + ) + + def _print_FunctionPrototype(self, expr): + pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters)) + return "%s %s(%s)" % ( + tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,) + ) + + def _print_FunctionDefinition(self, expr): + return "%s%s" % (self._print_FunctionPrototype(expr), + self._print_Scope(expr)) + + def _print_Return(self, expr): + arg, = expr.args + return 'return %s' % self._print(arg) + + def _print_CommaOperator(self, expr): + return '(%s)' % ', '.join((self._print(arg) for arg in expr.args)) + + def _print_Label(self, expr): + if expr.body == none: + return '%s:' % str(expr.name) + if len(expr.body.args) == 1: + return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body)) + return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body)) + + def _print_goto(self, expr): + return 'goto %s' % expr.label.name + + def _print_PreIncrement(self, expr): + arg, = expr.args + return '++(%s)' % self._print(arg) + + def _print_PostIncrement(self, expr): + arg, = expr.args + return '(%s)++' % self._print(arg) + + def _print_PreDecrement(self, expr): + arg, = expr.args + return '--(%s)' % self._print(arg) + + def _print_PostDecrement(self, expr): + arg, = expr.args + return '(%s)--' % self._print(arg) + + def _print_struct(self, expr): + return "%(keyword)s %(name)s {\n%(lines)s}" % { + "keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join( + [self._print(decl) for decl in expr.declarations] + ['']) + } + + def _print_BreakToken(self, _): + return 'break' + + def _print_ContinueToken(self, _): + return 'continue' + + _print_union = _print_struct + +class C99CodePrinter(C89CodePrinter): + standard = 'C99' + reserved_words = set(reserved_words + reserved_words_c99) + type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), { + complex64: 'float complex', + complex128: 'double complex', + }.items())) + type_headers = dict(chain(C89CodePrinter.type_headers.items(), { + complex64: {'complex.h'}, + complex128: {'complex.h'} + }.items())) + + # known_functions-dict to copy + _kf: dict[str, Any] = known_functions_C99 + + # functions with versions with 'f' and 'l' suffixes: + _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2' + ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan' + ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf' + ' erfc tgamma lgamma ceil floor trunc round nearbyint rint' + ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split() + + def _print_Infinity(self, expr): + return 'INFINITY' + + def _print_NegativeInfinity(self, expr): + return '-INFINITY' + + def _print_NaN(self, expr): + return 'NAN' + + # tgamma was already covered by 'known_functions' dict + + @requires(headers={'math.h'}, libraries={'m'}) + @_as_macro_if_defined + def _print_math_func(self, expr, nest=False, known=None): + if known is None: + known = self.known_functions[expr.__class__.__name__] + if not isinstance(known, str): + for cb, name in known: + if cb(*expr.args): + known = name + break + else: + raise ValueError("No matching printer") + try: + return known(self, *expr.args) + except TypeError: + suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else '' + + if nest: + args = self._print(expr.args[0]) + if len(expr.args) > 1: + paren_pile = '' + for curr_arg in expr.args[1:-1]: + paren_pile += ')' + args += ', {ns}{name}{suffix}({next}'.format( + ns=self._ns, + name=known, + suffix=suffix, + next = self._print(curr_arg) + ) + args += ', %s%s' % ( + self._print(expr.func(expr.args[-1])), + paren_pile + ) + else: + args = ', '.join((self._print(arg) for arg in expr.args)) + return '{ns}{name}{suffix}({args})'.format( + ns=self._ns, + name=known, + suffix=suffix, + args=args + ) + + def _print_Max(self, expr): + return self._print_math_func(expr, nest=True) + + def _print_Min(self, expr): + return self._print_math_func(expr, nest=True) + + def _get_loop_opening_ending(self, indices): + open_lines = [] + close_lines = [] + loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99 + for i in indices: + # C arrays start at 0 and end at dimension-1 + open_lines.append(loopstart % { + 'var': self._print(i.label), + 'start': self._print(i.lower), + 'end': self._print(i.upper + 1)}) + close_lines.append("}") + return open_lines, close_lines + + +for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma' + ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh ' + 'atanh erf erfc loggamma gamma ceiling floor').split(): + setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func) + + +class C11CodePrinter(C99CodePrinter): + + @requires(headers={'stdalign.h'}) + def _print_alignof(self, expr): + arg, = expr.args + return 'alignof(%s)' % self._print(arg) + + +c_code_printers = { + 'c89': C89CodePrinter, + 'c99': C99CodePrinter, + 'c11': C11CodePrinter +} diff --git a/shared/package-files/75/7510eeb3ef2a9159b938104fdf56be45d49a85872b9fd1c66097204dafcb3c12/blob b/shared/package-files/75/7510eeb3ef2a9159b938104fdf56be45d49a85872b9fd1c66097204dafcb3c12/blob new file mode 100644 index 0000000000000000000000000000000000000000..a51c78732ac4a25854737d26ffd43a07a2bf69af --- /dev/null +++ b/shared/package-files/75/7510eeb3ef2a9159b938104fdf56be45d49a85872b9fd1c66097204dafcb3c12/blob @@ -0,0 +1,19 @@ +from typing import Iterable, Optional + +def smart_truncate( + string: str, max_length: int = ..., word_boundary: bool = ..., separator: str = ..., save_order: bool = ... +) -> str: ... +def slugify( + text: str, + entities: bool = ..., + decimal: bool = ..., + hexadecimal: bool = ..., + max_length: int = ..., + word_boundary: bool = ..., + separator: str = ..., + save_order: bool = ..., + stopwords: Iterable[str] = ..., + regex_pattern: Optional[str] = ..., + lowercase: bool = ..., + replacements: Iterable[str] = ..., +) -> str: ... diff --git a/shared/package-files/75/7513950e2f6446f91b49dca77772f4f6da7dfdec7343842a1b7c67371efc25e5/blob b/shared/package-files/75/7513950e2f6446f91b49dca77772f4f6da7dfdec7343842a1b7c67371efc25e5/blob new file mode 100644 index 0000000000000000000000000000000000000000..0671484c9a0780df353b9b783813b6fa7492d38d --- /dev/null +++ b/shared/package-files/75/7513950e2f6446f91b49dca77772f4f6da7dfdec7343842a1b7c67371efc25e5/blob @@ -0,0 +1,9 @@ +""" FFT backend using pypocketfft """ + +from .basic import * +from .realtransforms import * +from .helper import * + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/shared/package-files/75/7513a174b46308686a1fb6c8dffc946cf06beda20a04cd4ab3f8968beec73aad/blob b/shared/package-files/75/7513a174b46308686a1fb6c8dffc946cf06beda20a04cd4ab3f8968beec73aad/blob new file mode 100644 index 0000000000000000000000000000000000000000..ecec9560a850bbef8c3abbffd20ca4cbc14fd781 --- /dev/null +++ b/shared/package-files/75/7513a174b46308686a1fb6c8dffc946cf06beda20a04cd4ab3f8968beec73aad/blob @@ -0,0 +1,15 @@ +import sys +from typing import Optional + +if sys.version_info >= (3, 8): + class CancelledError(BaseException): ... + class TimeoutError(Exception): ... + class InvalidStateError(Exception): ... + class SendfileNotAvailableError(RuntimeError): ... + class IncompleteReadError(EOFError): + expected: Optional[int] + partial: bytes + def __init__(self, partial: bytes, expected: Optional[int]) -> None: ... + class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... diff --git a/shared/package-files/75/7514b45c9d86e1bc0b74146328c929c82a4119882e52205043d8fe3f70423c93/blob b/shared/package-files/75/7514b45c9d86e1bc0b74146328c929c82a4119882e52205043d8fe3f70423c93/blob new file mode 100644 index 0000000000000000000000000000000000000000..7074de7437caf2f773027d057b77391b51b689da Binary files /dev/null and b/shared/package-files/75/7514b45c9d86e1bc0b74146328c929c82a4119882e52205043d8fe3f70423c93/blob differ diff --git a/shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob b/shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc8e74d302373d8da88ac4af4c7bd91a9e7950ef --- /dev/null +++ b/shared/package-files/75/75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75173baf355b7493185b2268dc65617e6e061b18fb10cff224171db108ca7600 +size 15822785 diff --git a/shared/package-files/75/7518c360c036ef0b0fdaebdaec9f8a81dcb952fba4354a7a21f42d8629b35de1/blob b/shared/package-files/75/7518c360c036ef0b0fdaebdaec9f8a81dcb952fba4354a7a21f42d8629b35de1/blob new file mode 100644 index 0000000000000000000000000000000000000000..d97da238b6870f524914553bd83d323dbfa55a16 --- /dev/null +++ b/shared/package-files/75/7518c360c036ef0b0fdaebdaec9f8a81dcb952fba4354a7a21f42d8629b35de1/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor sign(const at::Tensor & self); +TORCH_API at::Tensor & sign_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & sign_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & sign_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/75/75193016ad610ad89daf29e4b2bc84b3c2f8e3667b445c314e3cb0c24d2b6546/blob b/shared/package-files/75/75193016ad610ad89daf29e4b2bc84b3c2f8e3667b445c314e3cb0c24d2b6546/blob new file mode 100644 index 0000000000000000000000000000000000000000..e504a5eaf81ddf258dd7682f86be0f21731d5c2e --- /dev/null +++ b/shared/package-files/75/75193016ad610ad89daf29e4b2bc84b3c2f8e3667b445c314e3cb0c24d2b6546/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor cat(const at::ITensorListRef & tensors, int64_t dim=0); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob b/shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob new file mode 100644 index 0000000000000000000000000000000000000000..ce9c1ced69bda9ef9d6881ee1eefb615f7a93520 --- /dev/null +++ b/shared/package-files/75/751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:751945c08fd2c7ac7b49d0be092622eafa5ac58e60d92f99a59b4f8bdc307c33 +size 1411784 diff --git a/shared/package-files/75/751c6320bf926c5558d2adc88d232b7e00531eb9b52d90e02ceca0541c226197/blob b/shared/package-files/75/751c6320bf926c5558d2adc88d232b7e00531eb9b52d90e02ceca0541c226197/blob new file mode 100644 index 0000000000000000000000000000000000000000..73f58d7740813264d20047ffe918c82e1acc84eb --- /dev/null +++ b/shared/package-files/75/751c6320bf926c5558d2adc88d232b7e00531eb9b52d90e02ceca0541c226197/blob @@ -0,0 +1,177 @@ +"""Rich text and beautiful formatting in the terminal.""" + +import os +from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union + +from ._extension import load_ipython_extension # noqa: F401 + +__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"] + +if TYPE_CHECKING: + from .console import Console + +# Global console used by alternative print +_console: Optional["Console"] = None + +try: + _IMPORT_CWD = os.path.abspath(os.getcwd()) +except FileNotFoundError: + # Can happen if the cwd has been deleted + _IMPORT_CWD = "" + + +def get_console() -> "Console": + """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console, + and hasn't been explicitly given one. + + Returns: + Console: A console instance. + """ + global _console + if _console is None: + from .console import Console + + _console = Console() + + return _console + + +def reconfigure(*args: Any, **kwargs: Any) -> None: + """Reconfigures the global console by replacing it with another. + + Args: + *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`. + **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`. + """ + from pip._vendor.rich.console import Console + + new_console = Console(*args, **kwargs) + _console = get_console() + _console.__dict__ = new_console.__dict__ + + +def print( + *objects: Any, + sep: str = " ", + end: str = "\n", + file: Optional[IO[str]] = None, + flush: bool = False, +) -> None: + r"""Print object(s) supplied via positional arguments. + This function has an identical signature to the built-in print. + For more advanced features, see the :class:`~rich.console.Console` class. + + Args: + sep (str, optional): Separator between printed objects. Defaults to " ". + end (str, optional): Character to write at end of output. Defaults to "\\n". + file (IO[str], optional): File to write to, or None for stdout. Defaults to None. + flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False. + + """ + from .console import Console + + write_console = get_console() if file is None else Console(file=file) + return write_console.print(*objects, sep=sep, end=end) + + +def print_json( + json: Optional[str] = None, + *, + data: Any = None, + indent: Union[None, int, str] = 2, + highlight: bool = True, + skip_keys: bool = False, + ensure_ascii: bool = False, + check_circular: bool = True, + allow_nan: bool = True, + default: Optional[Callable[[Any], Any]] = None, + sort_keys: bool = False, +) -> None: + """Pretty prints JSON. Output will be valid JSON. + + Args: + json (str): A string containing JSON. + data (Any): If json is not supplied, then encode this data. + indent (int, optional): Number of spaces to indent. Defaults to 2. + highlight (bool, optional): Enable highlighting of output: Defaults to True. + skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. + ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. + check_circular (bool, optional): Check for circular references. Defaults to True. + allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. + default (Callable, optional): A callable that converts values that can not be encoded + in to something that can be JSON encoded. Defaults to None. + sort_keys (bool, optional): Sort dictionary keys. Defaults to False. + """ + + get_console().print_json( + json, + data=data, + indent=indent, + highlight=highlight, + skip_keys=skip_keys, + ensure_ascii=ensure_ascii, + check_circular=check_circular, + allow_nan=allow_nan, + default=default, + sort_keys=sort_keys, + ) + + +def inspect( + obj: Any, + *, + console: Optional["Console"] = None, + title: Optional[str] = None, + help: bool = False, + methods: bool = False, + docs: bool = True, + private: bool = False, + dunder: bool = False, + sort: bool = True, + all: bool = False, + value: bool = True, +) -> None: + """Inspect any Python object. + + * inspect() to see summarized info. + * inspect(, methods=True) to see methods. + * inspect(, help=True) to see full (non-abbreviated) help. + * inspect(, private=True) to see private attributes (single underscore). + * inspect(, dunder=True) to see attributes beginning with double underscore. + * inspect(, all=True) to see all attributes. + + Args: + obj (Any): An object to inspect. + title (str, optional): Title to display over inspect result, or None use type. Defaults to None. + help (bool, optional): Show full help text rather than just first paragraph. Defaults to False. + methods (bool, optional): Enable inspection of callables. Defaults to False. + docs (bool, optional): Also render doc strings. Defaults to True. + private (bool, optional): Show private attributes (beginning with underscore). Defaults to False. + dunder (bool, optional): Show attributes starting with double underscore. Defaults to False. + sort (bool, optional): Sort attributes alphabetically. Defaults to True. + all (bool, optional): Show all attributes. Defaults to False. + value (bool, optional): Pretty print value. Defaults to True. + """ + _console = console or get_console() + from pip._vendor.rich._inspect import Inspect + + # Special case for inspect(inspect) + is_inspect = obj is inspect + + _inspect = Inspect( + obj, + title=title, + help=is_inspect or help, + methods=is_inspect or methods, + docs=is_inspect or docs, + private=private, + dunder=dunder, + sort=sort, + all=all, + value=value, + ) + _console.print(_inspect) + + +if __name__ == "__main__": # pragma: no cover + print("Hello, **World**") diff --git a/shared/package-files/75/751d9124f157e3907b0ed61ac19ec07444db9edec14cebd0e486f7095d4abe08/blob b/shared/package-files/75/751d9124f157e3907b0ed61ac19ec07444db9edec14cebd0e486f7095d4abe08/blob new file mode 100644 index 0000000000000000000000000000000000000000..7690439237add63999cbbb0b5179043036d5b9c3 --- /dev/null +++ b/shared/package-files/75/751d9124f157e3907b0ed61ac19ec07444db9edec14cebd0e486f7095d4abe08/blob @@ -0,0 +1,204 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import datetime +import random +import time +from base64 import b64decode, b64encode +from typing import Optional + +import etcd # type: ignore[import] + +# pyre-ignore[21]: Could not find name `Store` in `torch.distributed`. +from torch.distributed import Store + + +# Delay (sleep) for a small random amount to reduce CAS failures. +# This does not affect correctness, but will reduce requests to etcd server. +def cas_delay(): + time.sleep(random.uniform(0, 0.1)) + + +# pyre-fixme[11]: Annotation `Store` is not defined as a type. +class EtcdStore(Store): + """ + Implement a c10 Store interface by piggybacking on the rendezvous etcd instance. + + This is the store object returned by ``EtcdRendezvous``. + """ + + def __init__( + self, + etcd_client, + etcd_store_prefix, + # Default timeout same as in c10d/Store.hpp + timeout: Optional[datetime.timedelta] = None, + ): + super().__init__() # required for pybind trampoline. + + self.client = etcd_client + self.prefix = etcd_store_prefix + + if timeout is not None: + self.set_timeout(timeout) + + if not self.prefix.endswith("/"): + self.prefix += "/" + + def set(self, key, value): + """ + Write a key/value pair into ``EtcdStore``. + + Both key and value may be either Python ``str`` or ``bytes``. + """ + self.client.set(key=self.prefix + self._encode(key), value=self._encode(value)) + + def get(self, key) -> bytes: + """ + Get a value by key, possibly doing a blocking wait. + + If key is not immediately present, will do a blocking wait + for at most ``timeout`` duration or until the key is published. + + + Returns: + value ``(bytes)`` + + Raises: + LookupError - If key still not published after timeout + """ + b64_key = self.prefix + self._encode(key) + kvs = self._try_wait_get([b64_key]) + + if kvs is None: + raise LookupError(f"Key {key} not found in EtcdStore") + + return self._decode(kvs[b64_key]) + + def add(self, key, num: int) -> int: + """ + Atomically increment a value by an integer amount. + + The integer is represented as a string using base 10. If key is not present, + a default value of ``0`` will be assumed. + + Returns: + the new (incremented) value + + + """ + b64_key = self._encode(key) + # c10d Store assumes value is an integer represented as a decimal string + try: + # Assume default value "0", if this key didn't yet: + node = self.client.write( + key=self.prefix + b64_key, + value=self._encode(str(num)), # i.e. 0 + num + prevExist=False, + ) + return int(self._decode(node.value)) + except etcd.EtcdAlreadyExist: + pass + + while True: + # Note: c10d Store does not have a method to delete keys, so we + # can be sure it's still there. + node = self.client.get(key=self.prefix + b64_key) + new_value = self._encode(str(int(self._decode(node.value)) + num)) + try: + node = self.client.test_and_set( + key=node.key, value=new_value, prev_value=node.value + ) + return int(self._decode(node.value)) + except etcd.EtcdCompareFailed: + cas_delay() + + def wait(self, keys, override_timeout: Optional[datetime.timedelta] = None): + """ + Wait until all of the keys are published, or until timeout. + + Raises: + LookupError - if timeout occurs + """ + b64_keys = [self.prefix + self._encode(key) for key in keys] + kvs = self._try_wait_get(b64_keys, override_timeout) + if kvs is None: + raise LookupError("Timeout while waiting for keys in EtcdStore") + # No return value on success + + def check(self, keys) -> bool: + """Check if all of the keys are immediately present (without waiting).""" + b64_keys = [self.prefix + self._encode(key) for key in keys] + kvs = self._try_wait_get( + b64_keys, + override_timeout=datetime.timedelta(microseconds=1), # as if no wait + ) + return kvs is not None + + # + # Encode key/value data in base64, so we can store arbitrary binary data + # in EtcdStore. Input can be `str` or `bytes`. + # In case of `str`, utf-8 encoding is assumed. + # + def _encode(self, value) -> str: + if type(value) == bytes: + return b64encode(value).decode() + elif type(value) == str: + return b64encode(value.encode()).decode() + raise ValueError("Value must be of type str or bytes") + + # + # Decode a base64 string (of type `str` or `bytes`). + # Return type is `bytes`, which is more convenient with the Store interface. + # + def _decode(self, value) -> bytes: + if type(value) == bytes: + return b64decode(value) + elif type(value) == str: + return b64decode(value.encode()) + raise ValueError("Value must be of type str or bytes") + + # + # Get all of the (base64-encoded) etcd keys at once, or wait until all the keys + # are published or timeout occurs. + # This is a helper method for the public interface methods. + # + # On success, a dictionary of {etcd key -> etcd value} is returned. + # On timeout, None is returned. + # + def _try_wait_get(self, b64_keys, override_timeout=None): + timeout = self.timeout if override_timeout is None else override_timeout # type: ignore[attr-defined] + deadline = time.time() + timeout.total_seconds() + + while True: + # Read whole directory (of keys), filter only the ones waited for + all_nodes = self.client.get(key=self.prefix) + req_nodes = { + node.key: node.value for node in all_nodes.children if node.key in b64_keys + } + + if len(req_nodes) == len(b64_keys): + # All keys are available + return req_nodes + + watch_timeout = deadline - time.time() + if watch_timeout <= 0: + return None + + try: + self.client.watch( + key=self.prefix, + recursive=True, + timeout=watch_timeout, + index=all_nodes.etcd_index + 1, + ) + except etcd.EtcdWatchTimedOut: + if time.time() >= deadline: + return None + else: + continue + except etcd.EtcdEventIndexCleared: + continue diff --git a/shared/package-files/75/752297e4e2cef56804b28cb461cfbd7bd8dfcd455b2d42a2797f5a1ced4b692a/blob b/shared/package-files/75/752297e4e2cef56804b28cb461cfbd7bd8dfcd455b2d42a2797f5a1ced4b692a/blob new file mode 100644 index 0000000000000000000000000000000000000000..838366353ccf4b71a66a4cbd78e45d4763baec6f --- /dev/null +++ b/shared/package-files/75/752297e4e2cef56804b28cb461cfbd7bd8dfcd455b2d42a2797f5a1ced4b692a/blob @@ -0,0 +1,98 @@ +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Any + +from formulaic.materializers.types.evaluated_factor import EvaluatedFactor +from formulaic.utils.variables import Variable + +from .scoped_factor import ScopedFactor + + +class ScopedTerm: + """ + A representation of a `Term` where scopes have been applied to the factors. + Recall that "scopes" in this context refer to whether or not the factor + values have been reduced in rank or not. + + Attributes: + factors: The `ScopedFactor` instances. + scale: The global factor associated with the term that should be applied + during column materialization. + """ + + __slots__ = ("factors", "scale") + + def __init__(self, factors: Iterable[ScopedFactor], scale: float = 1): + self.factors = tuple(dict.fromkeys(factors)) + self.scale = scale + + def __hash__(self) -> int: + return hash(tuple(sorted(self.factors))) + + def __eq__(self, other: Any) -> bool: + if isinstance(other, ScopedTerm): + return sorted(self.factors) == sorted(other.factors) + return NotImplemented + + def __repr__(self) -> str: + factor_repr = ( + ":".join(f.__repr__() for f in self.factors) if self.factors else "1" + ) + if self.scale is not None and self.scale != 1: + return f"{self.scale}*{factor_repr}" + return factor_repr + + def copy(self, *, without_values: bool = False) -> ScopedTerm: + """ + Return a copy of this `ScopedTerm` instance, potentially without the + materialized values attached. This is used during the generation of + model specs in order to reduce the size of the serialized specs. + + Args: + without_values: Whether the materialized values should be omitted + from the copy. + """ + factors: Iterable[ScopedFactor] = self.factors + if without_values: + factors = [ + ScopedFactor( + factor=factor.factor.replace(values=None), + reduced=factor.reduced, + ) + for factor in factors + ] + return ScopedTerm(factors, scale=self.scale) + + def rehydrate(self, factor_values: Mapping[str, EvaluatedFactor]) -> ScopedTerm: + """ + Rehydrate the `ScopedTerm` instance with new `EvaluatedFactor` instances + that have been computed for each factor. An exception will be raised if + any required factor is missing from the `factor_values` mapping. This is + used to allow the reuse of serialized `ScopedTerm` structure that have + had their factor values excised using `.copy(without_values=True)`. + + Args: + factor_values: A mapping from factor expressions to `EvaluatedFactor` + instances. This mapping should contain all factors in the term. + """ + return ScopedTerm( + [ + ScopedFactor( + factor=factor_values[factor.factor.expr], + reduced=factor.reduced, + ) + for factor in self.factors + ], + scale=self.scale, + ) + + @property + def variables(self) -> set[Variable]: + return Variable.union( + *( + factor.factor.variables + for factor in self.factors + if factor.factor.variables is not None + ) + ) diff --git a/shared/package-files/75/75235d661a1cf1ae21e74c11b5b3b12f0a668148ae305a5eeb2b532d445ca656/blob b/shared/package-files/75/75235d661a1cf1ae21e74c11b5b3b12f0a668148ae305a5eeb2b532d445ca656/blob new file mode 100644 index 0000000000000000000000000000000000000000..d648c3e02463d5a7ee1dcbe3b22af5cc22fef43d --- /dev/null +++ b/shared/package-files/75/75235d661a1cf1ae21e74c11b5b3b12f0a668148ae305a5eeb2b532d445ca656/blob @@ -0,0 +1,261 @@ +# conceal the implicit import from the code quality tester +from sympy.core.numbers import (oo, pi) +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.special.bessel import besseli +from sympy.functions.special.gamma_functions import gamma +from sympy.integrals.integrals import integrate +from sympy.integrals.transforms import (mellin_transform, + inverse_fourier_transform, inverse_mellin_transform, + laplace_transform, inverse_laplace_transform, fourier_transform) + +LT = laplace_transform +FT = fourier_transform +MT = mellin_transform +IFT = inverse_fourier_transform +ILT = inverse_laplace_transform +IMT = inverse_mellin_transform + +from sympy.abc import x, y +nu, beta, rho = symbols('nu beta rho') + +apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True) +k = Symbol('k', real=True) +negk = Symbol('k', negative=True) + +mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True) +sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True, + finite=True, positive=True) +rate = Symbol('lambda', positive=True) + + +def normal(x, mu, sigma): + return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) + + +def exponential(x, rate): + return rate*exp(-rate*x) +alpha, beta = symbols('alpha beta', positive=True) +betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ + /gamma(alpha)/gamma(beta) +kint = Symbol('k', integer=True, positive=True) +chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2) +chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) +dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1) +d1, d2 = symbols('d1 d2', positive=True) +f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ + /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) +nupos, sigmapos = symbols('nu sigma', positive=True) +rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x* + nupos/sigmapos**2) +mu = Symbol('mu', real=True) +laplace = exp(-abs(x - mu)/bpos)/2/bpos + +u = Symbol('u', polar=True) +tpos = Symbol('t', positive=True) + + +def E(expr): + integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), + (x, 0, oo), (y, -oo, oo), meijerg=True) + integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), + (y, -oo, oo), (x, 0, oo), meijerg=True) + +bench = [ + 'MT(x**nu*Heaviside(x - 1), x, s)', + 'MT(x**nu*Heaviside(1 - x), x, s)', + 'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)', + 'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)', + 'MT((1+x)**(-rho), x, s)', + 'MT(abs(1-x)**(-rho), x, s)', + 'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)', + 'MT((x**a-b**a)/(x-b), x, s)', + 'MT((x**a-bpos**a)/(x-bpos), x, s)', + 'MT(exp(-x), x, s)', + 'MT(exp(-1/x), x, s)', + 'MT(log(x)**4*Heaviside(1-x), x, s)', + 'MT(log(x)**3*Heaviside(x-1), x, s)', + 'MT(log(x + 1), x, s)', + 'MT(log(1/x + 1), x, s)', + 'MT(log(abs(1 - x)), x, s)', + 'MT(log(abs(1 - 1/x)), x, s)', + 'MT(log(x)/(x+1), x, s)', + 'MT(log(x)**2/(x+1), x, s)', + 'MT(log(x)/(x+1)**2, x, s)', + 'MT(erf(sqrt(x)), x, s)', + + 'MT(besselj(a, 2*sqrt(x)), x, s)', + 'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)', + 'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))**2, x, s)', + 'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)', + 'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)', + 'MT(bessely(a, 2*sqrt(x)), x, s)', + 'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)', + 'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)', + 'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)', + 'MT(bessely(a, sqrt(x))**2, x, s)', + + 'MT(besselk(a, 2*sqrt(x)), x, s)', + 'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)', + 'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)', + 'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)', + 'MT(exp(-x/2)*besselk(a, x/2), x, s)', + + # later: ILT, IMT + + 'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)', + 'LT(t**apos, t, s)', + 'LT(Heaviside(t), t, s)', + 'LT(Heaviside(t - apos), t, s)', + 'LT(1 - exp(-apos*t), t, s)', + 'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)', + 'LT(exp(t), t, s)', + 'LT(exp(2*t), t, s)', + 'LT(exp(apos*t), t, s)', + 'LT(log(t/apos), t, s)', + 'LT(erf(t), t, s)', + 'LT(sin(apos*t), t, s)', + 'LT(cos(apos*t), t, s)', + 'LT(exp(-apos*t)*sin(bpos*t), t, s)', + 'LT(exp(-apos*t)*cos(bpos*t), t, s)', + 'LT(besselj(0, t), t, s, noconds=True)', + 'LT(besselj(1, t), t, s, noconds=True)', + + 'FT(Heaviside(1 - abs(2*apos*x)), x, k)', + 'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)', + 'FT(exp(-apos*x)*Heaviside(x), x, k)', + 'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)', + 'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)', + 'IFT(1/(apos + 2*pi*I*x), x, negk)', + 'FT(x*exp(-apos*x)*Heaviside(x), x, k)', + 'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)', + 'FT(exp(-apos*x**2), x, k)', + 'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)', + 'FT(exp(-apos*abs(x)), x, k)', + + 'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', + 'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' + ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', + 'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)', + 'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)', + 'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)', + 'E(1)', + 'E(x*y)', + 'E(x*y**2)', + 'E((x+y+1)**2)', + 'E(x+y+1)', + 'E((x+y-1)**2)', + 'integrate(betadist, (x, 0, oo), meijerg=True)', + 'integrate(x*betadist, (x, 0, oo), meijerg=True)', + 'integrate(x**2*betadist, (x, 0, oo), meijerg=True)', + 'integrate(chi, (x, 0, oo), meijerg=True)', + 'integrate(x*chi, (x, 0, oo), meijerg=True)', + 'integrate(x**2*chi, (x, 0, oo), meijerg=True)', + 'integrate(chisquared, (x, 0, oo), meijerg=True)', + 'integrate(x*chisquared, (x, 0, oo), meijerg=True)', + 'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)', + 'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)', + 'integrate(dagum, (x, 0, oo), meijerg=True)', + 'integrate(x*dagum, (x, 0, oo), meijerg=True)', + 'integrate(x**2*dagum, (x, 0, oo), meijerg=True)', + 'integrate(f, (x, 0, oo), meijerg=True)', + 'integrate(x*f, (x, 0, oo), meijerg=True)', + 'integrate(x**2*f, (x, 0, oo), meijerg=True)', + 'integrate(rice, (x, 0, oo), meijerg=True)', + 'integrate(laplace, (x, -oo, oo), meijerg=True)', + 'integrate(x*laplace, (x, -oo, oo), meijerg=True)', + 'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)', + 'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))', + + 'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)', + 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)', + 'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)', + 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)', + 'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)', + + 'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))', + "gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))", + + 'mellin_transform(E1(x), x, s)', + 'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))', + 'mellin_transform(expint(a, x), x, s)', + 'mellin_transform(Si(x), x, s)', + 'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))', + 'mellin_transform(Ci(sqrt(x)), x, s)', + 'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))', + 'laplace_transform(Ci(x), x, s)', + 'laplace_transform(expint(a, x), x, s)', + 'laplace_transform(expint(1, x), x, s)', + 'laplace_transform(expint(2, x), x, s)', + 'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)', + 'inverse_laplace_transform(log(s + 1)/s, s, x)', + 'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)', + 'laplace_transform(Chi(x), x, s)', + 'laplace_transform(Shi(x), x, s)', + + 'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")', + 'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")', + 'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")', + 'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)', + 'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)', + 'integrate(sin(x)/x, (x, 0, z), meijerg=True)', + 'integrate(sinh(x)/x, (x, 0, z), meijerg=True)', + 'integrate(exp(-x)/x, x, meijerg=True)', + 'integrate(exp(-x)/x**2, x, meijerg=True)', + 'integrate(cos(u)/u, u, meijerg=True)', + 'integrate(cosh(u)/u, u, meijerg=True)', + 'integrate(expint(1, x), x, meijerg=True)', + 'integrate(expint(2, x), x, meijerg=True)', + 'integrate(Si(x), x, meijerg=True)', + 'integrate(Ci(u), u, meijerg=True)', + 'integrate(Shi(x), x, meijerg=True)', + 'integrate(Chi(u), u, meijerg=True)', + 'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)', + 'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)' +] + +from time import time +from sympy.core.cache import clear_cache +import sys + +timings = [] + +if __name__ == '__main__': + for n, string in enumerate(bench): + clear_cache() + _t = time() + exec(string) + _t = time() - _t + timings += [(_t, string)] + sys.stdout.write('.') + sys.stdout.flush() + if n % (len(bench) // 10) == 0: + sys.stdout.write('%s' % (10*n // len(bench))) + print() + + timings.sort(key=lambda x: -x[0]) + + for ti, string in timings: + print('%.2fs %s' % (ti, string)) diff --git a/shared/package-files/75/7523f6f7746da075be73a707f55468cd1afcd73c2a2f6e03062f7063fa2952ec/blob b/shared/package-files/75/7523f6f7746da075be73a707f55468cd1afcd73c2a2f6e03062f7063fa2952ec/blob new file mode 100644 index 0000000000000000000000000000000000000000..291640d2a8d96e3bb2e1cdb865b1bb60b2f43d18 --- /dev/null +++ b/shared/package-files/75/7523f6f7746da075be73a707f55468cd1afcd73c2a2f6e03062f7063fa2952ec/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _cast_Long(const at::Tensor & self, bool non_blocking=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/75240f0a25da63a2c532ae50653cce37807e98e2384f232cf1deabff30686c63/blob b/shared/package-files/75/75240f0a25da63a2c532ae50653cce37807e98e2384f232cf1deabff30686c63/blob new file mode 100644 index 0000000000000000000000000000000000000000..12031eb68e7525b6dca1555b2696ede3c40dac73 --- /dev/null +++ b/shared/package-files/75/75240f0a25da63a2c532ae50653cce37807e98e2384f232cf1deabff30686c63/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API logical_xor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_xor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API logical_xor_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_xor_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API logical_xor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_xor.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/75/7524540714554e1f9d5ccacc47fa10dd9212bb64127e1499962934dcc8dbbb7d/blob b/shared/package-files/75/7524540714554e1f9d5ccacc47fa10dd9212bb64127e1499962934dcc8dbbb7d/blob new file mode 100644 index 0000000000000000000000000000000000000000..7cfa792f744b7e0b4e28a536c0603f142ded6518 --- /dev/null +++ b/shared/package-files/75/7524540714554e1f9d5ccacc47fa10dd9212bb64127e1499962934dcc8dbbb7d/blob @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: MIT + +""" +Classes Without Boilerplate +""" + +from functools import partial +from typing import Callable + +from . import converters, exceptions, filters, setters, validators +from ._cmp import cmp_using +from ._config import get_run_validators, set_run_validators +from ._funcs import asdict, assoc, astuple, evolve, has, resolve_types +from ._make import ( + NOTHING, + Attribute, + Factory, + attrib, + attrs, + fields, + fields_dict, + make_class, + validate, +) +from ._next_gen import define, field, frozen, mutable +from ._version_info import VersionInfo + + +s = attributes = attrs +ib = attr = attrib +dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) + + +class AttrsInstance: + pass + + +__all__ = [ + "Attribute", + "AttrsInstance", + "Factory", + "NOTHING", + "asdict", + "assoc", + "astuple", + "attr", + "attrib", + "attributes", + "attrs", + "cmp_using", + "converters", + "define", + "evolve", + "exceptions", + "field", + "fields", + "fields_dict", + "filters", + "frozen", + "get_run_validators", + "has", + "ib", + "make_class", + "mutable", + "resolve_types", + "s", + "set_run_validators", + "setters", + "validate", + "validators", +] + + +def _make_getattr(mod_name: str) -> Callable: + """ + Create a metadata proxy for packaging information that uses *mod_name* in + its warnings and errors. + """ + + def __getattr__(name: str) -> str: + dunder_to_metadata = { + "__title__": "Name", + "__copyright__": "", + "__version__": "version", + "__version_info__": "version", + "__description__": "summary", + "__uri__": "", + "__url__": "", + "__author__": "", + "__email__": "", + "__license__": "license", + } + if name not in dunder_to_metadata.keys(): + raise AttributeError(f"module {mod_name} has no attribute {name}") + + import sys + import warnings + + if sys.version_info < (3, 8): + from importlib_metadata import metadata + else: + from importlib.metadata import metadata + + if name != "__version_info__": + warnings.warn( + f"Accessing {mod_name}.{name} is deprecated and will be " + "removed in a future release. Use importlib.metadata directly " + "to query for attrs's packaging metadata.", + DeprecationWarning, + stacklevel=2, + ) + + meta = metadata("attrs") + if name == "__license__": + return "MIT" + elif name == "__copyright__": + return "Copyright (c) 2015 Hynek Schlawack" + elif name in ("__uri__", "__url__"): + return meta["Project-URL"].split(" ", 1)[-1] + elif name == "__version_info__": + return VersionInfo._from_version_string(meta["version"]) + elif name == "__author__": + return meta["Author-email"].rsplit(" ", 1)[0] + elif name == "__email__": + return meta["Author-email"].rsplit("<", 1)[1][:-1] + + return meta[dunder_to_metadata[name]] + + return __getattr__ + + +__getattr__ = _make_getattr(__name__) diff --git a/shared/package-files/75/752560d1d1de753f70d503b617502f5a87a5e3f87cc26b984b882e11a2fee4a9/blob b/shared/package-files/75/752560d1d1de753f70d503b617502f5a87a5e3f87cc26b984b882e11a2fee4a9/blob new file mode 100644 index 0000000000000000000000000000000000000000..dbb8d57d91d6640c1282fab3a063567d1f663f88 Binary files /dev/null and b/shared/package-files/75/752560d1d1de753f70d503b617502f5a87a5e3f87cc26b984b882e11a2fee4a9/blob differ diff --git a/shared/package-files/75/752571886a9d351ea06c5e34578276b46850f93e110ef4b21b2a47bd870f0d83/blob b/shared/package-files/75/752571886a9d351ea06c5e34578276b46850f93e110ef4b21b2a47bd870f0d83/blob new file mode 100644 index 0000000000000000000000000000000000000000..91771ceb0466d6b0fee00570426713d02da14872 --- /dev/null +++ b/shared/package-files/75/752571886a9d351ea06c5e34578276b46850f93e110ef4b21b2a47bd870f0d83/blob @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +from sympy.core.relational import Eq +from sympy.core.symbol import Symbol +from sympy.functions.elementary.piecewise import Piecewise +from sympy.printing.preview import preview + +from io import BytesIO + + +def test_preview(): + x = Symbol('x') + obj = BytesIO() + try: + preview(x, output='png', viewer='BytesIO', outputbuffer=obj) + except RuntimeError: + pass # latex not installed on CI server + + +def test_preview_unicode_symbol(): + # issue 9107 + a = Symbol('α') + obj = BytesIO() + try: + preview(a, output='png', viewer='BytesIO', outputbuffer=obj) + except RuntimeError: + pass # latex not installed on CI server + + +def test_preview_latex_construct_in_expr(): + # see PR 9801 + x = Symbol('x') + pw = Piecewise((1, Eq(x, 0)), (0, True)) + obj = BytesIO() + try: + preview(pw, output='png', viewer='BytesIO', outputbuffer=obj) + except RuntimeError: + pass # latex not installed on CI server diff --git a/shared/package-files/75/75292a923cfe979435cef921f0a15ecc2ff9cd1cf0f0137544e28f8d8f78acdc/blob b/shared/package-files/75/75292a923cfe979435cef921f0a15ecc2ff9cd1cf0f0137544e28f8d8f78acdc/blob new file mode 100644 index 0000000000000000000000000000000000000000..f391766ac9e3bd7b324b0d26fa2d995e7d0581aa --- /dev/null +++ b/shared/package-files/75/75292a923cfe979435cef921f0a15ecc2ff9cd1cf0f0137544e28f8d8f78acdc/blob @@ -0,0 +1,5731 @@ +#pragma once + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include + +namespace c10{ +template class List; +template class IListRef; +} +namespace at { +struct Generator; +struct Type; +class DeprecatedTypeProperties; +class Tensor; +} // namespace at +namespace at { +namespace indexing { +struct TensorIndex; +} // namespace indexing +} // namespace at + +namespace torch { namespace autograd { + +struct Node; + +}} // namespace torch::autograd + +namespace at { + +class OptionalTensorRef; +class TensorRef; +class Tensor; +using TensorList = ArrayRef; +using ITensorList = c10::IListRef; + +using Stream = c10::Stream; + +// Tensor is a "generic" object holding a pointer to the underlying TensorImpl object, which +// has an embedded reference count. In this way, Tensor is similar to boost::intrusive_ptr. +// +// For example: +// +// void func(Tensor a) { +// Tensor b = a; +// ... +// } +// +// In this example, when we say Tensor b = a, we are creating a new object that points to the +// same underlying TensorImpl, and bumps its reference count. When b goes out of scope, the +// destructor decrements the reference count by calling release() on the TensorImpl it points to. +// The existing constructors, operator overloads, etc. take care to implement the correct semantics. +// +// Note that Tensor can also be NULL, i.e. it is not associated with any underlying TensorImpl, and +// special care must be taken to handle this. +class TORCH_API Tensor: public TensorBase { + protected: + // Create a Tensor with a +0 reference count. Special care must be + // taken to avoid decrementing this reference count at destruction + // time. Intended to support MaybeOwnedTraits. + explicit Tensor(unsafe_borrow_t, const TensorBase& rhs): TensorBase(unsafe_borrow_t{}, rhs) {} + friend MaybeOwnedTraits; + friend OptionalTensorRef; + friend TensorRef; + + public: + Tensor() = default; + // This constructor should not be used by end users and is an implementation + // detail invoked by autogenerated code. + explicit Tensor( + c10::intrusive_ptr tensor_impl) + : TensorBase(std::move(tensor_impl)) {} + Tensor(const Tensor &tensor) = default; + Tensor(Tensor &&tensor) = default; + + // Implicitly move-constructible from TensorBase, but must be explicit to increase refcount + explicit Tensor(const TensorBase &base): TensorBase(base) {} + /*implicit*/ Tensor(TensorBase &&base): TensorBase(std::move(base)) {} + + // Creates a new wrapper from TensorImpl. Intentionally a free method because + // it should be used with care. Checks necessary invariants + static Tensor wrap_tensor_impl( + c10::intrusive_ptr tensor_impl) { + return TensorBase::wrap_tensor_impl(std::move(tensor_impl)); + } + + Tensor contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const { + return TensorBase::contiguous(memory_format); + } + + Tensor conj() const { + if (!this->is_complex()) { + return *this; + } + + switch (this->layout()) { + case at::kSparse: + case at::kSparseCsr: + case at::kSparseCsc: + case at::kSparseBsr: + case at::kSparseBsc: + return this->conj_physical(); + default: + return this->_conj(); + } + } + + // Aliased by Dimname overloads, so need explicit using + using TensorBase::size; + using TensorBase::sym_size; + using TensorBase::stride; + + /// Should be used if *this can reasonably be expected to be contiguous and + /// performance is important. + /// Compared to contiguous, it saves a reference count + /// increment/decrement if *this is already contiguous, at the cost + /// in all cases of an extra pointer of stack usage, an extra branch + /// to access, and an extra branch at destruction time. + c10::MaybeOwned expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const &; + + // Use .contiguous() instead. Trying to borrow from a prvalue Tensor + // will only lead to trouble and dangling references. + c10::MaybeOwned expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) && = delete; + + // The following overloads are very intruiging. Consider the following + // program: + // + // x[1] = 3; + // + // We would expect that the first entry of x is written to 3. But how can we + // actually achieve this? x[1] evaluates to a tensor... + // + // The answer is, using a ref-qualifier. x[1] is an rvalue, which cannot be + // (profitably) assigned to in the traditional sense, so we overload + // assignment to mean, "Actually, copy 3 into the tensor data." This is done + // with an rvalue-reference ref-qualified overload (the methods with && at the + // end of their type.) + // + // There's one more fly in the ointment: We also want + // + // Tensor x = y; + // + // to work, and we want it NOT to copy. So we need a traditional operator= + // overload. But we MUST specify a mutable lvalue ref-qualifier, to + // disambiguate the traditional overload from the rvalue-reference + // ref-qualified overload. Otherwise, it will be ambiguous, because + // a non ref-qualified method is eligible for all situations. + + // Unfortunately, we have to write these constructors out manually + // to work around an MSVC bug: + // error C2580: 'at::Tensor &at::Tensor::operator =(const at::Tensor &) &': + // multiple versions of a defaulted special member functions are not allowed + // Tensor& operator=(const Tensor&) & = default; + // Tensor& operator=(Tensor&&) & = default; + + // Also MSVC will wrongly issue the following warning with the aforementioned fix + // warning C4522: 'at::Tensor': multiple assignment operators specified + // Let's just skip the warning. + // + // TODO: temporarily disabled + + Tensor& operator=(const TensorBase& x) & { + impl_ = x.getIntrusivePtr(); + return *this; + } + Tensor& operator=(TensorBase&& x) & noexcept { + impl_ = x.unsafeReleaseIntrusivePtr(); + return *this; + } + + Tensor& operator=(const Tensor &x) & { + return operator=(static_cast(x)); + } + Tensor& operator=(Tensor &&x) & noexcept { + return operator=(static_cast(x)); + } + + Tensor& operator=(const Scalar &v) && { + return fill_(v); + } + Tensor& operator=(const Tensor &rhs) && { + return copy_(rhs); + } + Tensor& operator=(Tensor&& rhs) && { + return copy_(rhs); + } + + C10_DEPRECATED_MESSAGE("Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device().") + DeprecatedTypeProperties & type() const { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + dispatchKeyToBackend(legacyExtractDispatchKey(key_set())), + scalar_type()); + } + + Tensor toType(ScalarType t) const { + return to(options().dtype(t), /*non_blocking*/ false, /*copy*/ false); + } + + // TODO: Deprecate me + Tensor toBackend(Backend b) const { + return to(options().device(backendToDeviceType(b)).layout(layout_from_backend(b)), /*non_blocking*/ false, /*copy*/ false); + } + + C10_DEPRECATED_MESSAGE("Tensor.is_variable() is deprecated; everything is a variable now. (If you want to assert that variable has been appropriately handled already, use at::impl::variable_excluded_from_dispatch())") + bool is_variable() const noexcept { + return !at::impl::variable_excluded_from_dispatch(); + } + + template + C10_DEPRECATED_MESSAGE("Tensor.data() is deprecated. Please use Tensor.data_ptr() instead.") + T * data() const { + return data_ptr(); + } + + template + T item() const; + + template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> + C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead") + GenericPackedTensorAccessor packed_accessor() const & { + return generic_packed_accessor(); + } + template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> + C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead") + GenericPackedTensorAccessor packed_accessor() && = delete; + + Tensor operator~() const { + return bitwise_not(); + } + Tensor operator-() const { + return neg(); + } + Tensor& operator+=(const Tensor & other) { + return add_(other); + } + Tensor& operator+=(const Scalar & other) { + return add_(other); + } + Tensor& operator-=(const Tensor & other) { + return sub_(other); + } + Tensor& operator-=(const Scalar & other) { + return sub_(other); + } + Tensor& operator*=(const Tensor & other) { + return mul_(other); + } + Tensor& operator*=(const Scalar & other) { + return mul_(other); + } + Tensor& operator/=(const Tensor & other) { + return div_(other); + } + Tensor& operator/=(const Scalar & other) { + return div_(other); + } + Tensor& operator&=(const Tensor & other) { + return bitwise_and_(other); + } + Tensor& operator|=(const Tensor & other) { + return bitwise_or_(other); + } + Tensor& operator^=(const Tensor & other) { + return bitwise_xor_(other); + } + Tensor operator[](const Scalar & index) const { + if (!index.isIntegral(false)) { + TORCH_CHECK_INDEX(false, "Can only index tensors with integral scalars"); + } + return this->operator[](index.toLong()); + } + Tensor operator[](const Tensor & index) const { + // These properties are checked in the Scalar constructor, but we already + // check them here to provide more useful diagnostics for the user. + if (!index.defined()) { + TORCH_CHECK_INDEX(false, "Can only index with tensors that are defined"); + } + if (index.dim() != 0) { + TORCH_CHECK_INDEX(false, + "Can only index with tensors that are scalars (zero-dim)"); + } + // The Scalar(Tensor) constructor is explicit, so we need to call it. + return this->operator[](index.item()); + } + Tensor operator[](int64_t index) const { + return select(0, index); + } + + Tensor index(ArrayRef indices) const; + Tensor index(std::initializer_list indices) const; + + Tensor & index_put_(ArrayRef indices, Tensor const & rhs); + Tensor & index_put_(ArrayRef indices, const Scalar& v); + Tensor & index_put_(std::initializer_list indices, Tensor const & rhs); + Tensor & index_put_(std::initializer_list indices, const Scalar& v); + + Tensor cpu() const { + return to(options().device(c10::DeviceType::CPU), /*non_blocking*/ false, /*copy*/ false); + } + + // TODO: The Python version also accepts arguments + Tensor cuda() const { + return to(options().device(c10::DeviceType::CUDA), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor hip() const { + return to(options().device(c10::DeviceType::HIP), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor ve() const { + return to(options().device(c10::DeviceType::VE), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor vulkan() const { + return to(options().device(c10::DeviceType::Vulkan), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor metal() const { + return to(options().device(c10::DeviceType::Metal), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor meta() const { + return to(options().device(c10::DeviceType::Meta), /*non_blocking*/ false, /*copy*/ false); + } + + // ~~~~~ Autograd API ~~~~~ + + /// \fn bool is_leaf() const; + /// + /// All Tensors that have `requires_grad()` which is ``false`` will be leaf Tensors by convention. + /// + /// For Tensors that have `requires_grad()` which is ``true``, they will be leaf Tensors if they were + /// created by the user. This means that they are not the result of an operation and so + /// `grad_fn()` is `nullptr`. + /// + /// Only leaf Tensors will have their `grad()` populated during a call to `backward()`. + /// To get `grad()` populated for non-leaf Tensors, you can use `retain_grad()`. + /// + /// Example: + /// @code + /// auto a = torch::rand(10, torch::requires_grad()); + /// std::cout << a.is_leaf() << std::endl; // prints `true` + /// + /// auto b = torch::rand(10, torch::requires_grad()).to(torch::kCUDA); + /// std::cout << b.is_leaf() << std::endl; // prints `false` + /// // b was created by the operation that cast a cpu Tensor into a cuda Tensor + /// + /// auto c = torch::rand(10, torch::requires_grad()) + 2; + /// std::cout << c.is_leaf() << std::endl; // prints `false` + /// // c was created by the addition operation + /// + /// auto d = torch::rand(10).cuda(); + /// std::cout << d.is_leaf() << std::endl; // prints `true` + /// // d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + /// + /// auto e = torch::rand(10).cuda().requires_grad_(); + /// std::cout << e.is_leaf() << std::endl; // prints `true` + /// // e requires gradients and has no operations creating it + /// + /// auto f = torch::rand(10, torch::device(torch::kCUDA).requires_grad(true)); + /// std::cout << f.is_leaf() << std::endl; // prints `true` + /// // f requires grad, has no operation creating it + /// @endcode + + /// \fn void backward(const Tensor & gradient={}, c10::optional retain_graph=c10::nullopt, bool create_graph=false, c10::optional inputs=c10::nullopt) const; + /// + /// Computes the gradient of current tensor with respect to graph leaves. + /// + /// The graph is differentiated using the chain rule. If the tensor is + /// non-scalar (i.e. its data has more than one element) and requires + /// gradient, the function additionally requires specifying ``gradient``. + /// It should be a tensor of matching type and location, that contains + /// the gradient of the differentiated function w.r.t. this Tensor. + /// + /// This function accumulates gradients in the leaves - you might need to + /// zero them before calling it. + /// + /// \param gradient Gradient w.r.t. the + /// tensor. If it is a tensor, it will be automatically converted + /// to a Tensor that does not require grad unless ``create_graph`` is True. + /// None values can be specified for scalar Tensors or ones that + /// don't require grad. If a None value would be acceptable then + /// this argument is optional. + /// \param retain_graph If ``false``, the graph used to compute + /// the grads will be freed. Note that in nearly all cases setting + /// this option to True is not needed and often can be worked around + /// in a much more efficient way. Defaults to the value of + /// ``create_graph``. + /// \param create_graph If ``true``, graph of the derivative will + /// be constructed, allowing to compute higher order derivative + /// products. Defaults to ``false``. + /// \param inputs Inputs w.r.t. which the gradient will be accumulated into + /// ``at::Tensor::grad``. All other Tensors will be ignored. If not + /// provided, the gradient is accumulated into all the leaf Tensors + /// that were used to compute the current tensor. + /// When inputs are provided and a given input is not a leaf, + /// the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients). + /// It is an implementation detail on which the user should not rely. + /// See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details. + void backward(const Tensor & gradient={}, c10::optional retain_graph=c10::nullopt, bool create_graph=false, c10::optional inputs=c10::nullopt) const { + // NB: Adding this wrapper to _backward here because we'd like our + // 'backwards' api to accept the 'inputs' argument optionally. Since code gen + // currently does not support optional of TensorList our approach is to replace + // backward in native_functions.yaml with _backward and call it here instead. + if (inputs.has_value()) { + TORCH_CHECK(inputs.value().size() > 0, "'inputs' argument to backward cannot be empty") + this->_backward(inputs.value(), gradient, retain_graph, create_graph); + } else { + this->_backward({}, gradient, retain_graph, create_graph); + } + } + + /// \fn Tensor detach() const; + /// + /// Returns a new Tensor, detached from the current graph. + /// The result will never require gradient. + + /// \fn Tensor & detach_() const; + /// + /// Detaches the Tensor from the graph that created it, making it a leaf. + /// Views cannot be detached in-place. + + /// \fn void retain_grad() const; + /// + /// Enables this Tensor to have their :attr:`grad` populated during + /// :func:`backward`. This is a no-op for leaf tensors. + + /// \fn bool retains_grad() const; + /// + /// Is ``true`` if this Tensor is non-leaf and its :attr:`grad` is enabled to be + /// populated during :func:`backward`, ``false`` otherwise. + + const Tensor& set_requires_grad(bool requires_grad) const { + TensorBase::set_requires_grad(requires_grad); + return *this; + } + + /// Return a mutable reference to the gradient. This is conventionally + /// used as `t.grad() = x` to set a gradient to a completely new tensor. + /// Note that this function work with a non-const Tensor and is not + /// thread safe. + Tensor& mutable_grad() const { + return impl_->mutable_grad(); + } + + /// This function returns an undefined tensor by default and returns a defined tensor + /// the first time a call to `backward()` computes gradients for this Tensor. + /// The attribute will then contain the gradients computed and future calls + /// to `backward()` will accumulate (add) gradients into it. + const Tensor& grad() const { + const Tensor& maybe_grad = impl_->grad(); + if (!is_leaf() && !retains_grad() && !maybe_grad.defined()) { + TORCH_WARN( + "The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad " + "attribute won't be populated during autograd.backward(). If you indeed want the .grad " + "field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. " + "If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor " + "instead. See github.com/pytorch/pytorch/pull/30531 for more informations."); + } + return maybe_grad; + } + + // The Forward AD API functions below are low level and are not to be used by end + // users who should use the API provided in torch/csrc/autograd.h + + /// This function returns the forward gradient for this Tensor at the given level. + const Tensor& _fw_grad(uint64_t level) const { + return impl_->_fw_grad(level, *this); + } + + /// This function can be used to set the value of the forward grad. + /// Note that the given new_grad might not be used directly if it has different + /// metadata (size/stride/storage offset) compared to this Tensor. In that case, + /// new_grad content will be copied into a new Tensor + void _set_fw_grad(const TensorBase& new_grad, uint64_t level, bool is_inplace_op) const { + impl_->_set_fw_grad(new_grad, *this, level, is_inplace_op); + } + + + // STOP. Thinking of adding a method here, which only makes use + // of other ATen methods? Define it in native_functions.yaml. + + //example + //Tensor * add(Tensor & b); + void __dispatch__backward(at::TensorList inputs, const c10::optional & gradient={}, c10::optional retain_graph=c10::nullopt, bool create_graph=false) const; + void __dispatch_set_data(const at::Tensor & new_data) const; + at::Tensor __dispatch_data() const; + bool __dispatch_is_leaf() const; + int64_t __dispatch_output_nr() const; + int64_t __dispatch__version() const; + at::Tensor & __dispatch_requires_grad_(bool requires_grad=true) const; + void __dispatch_retain_grad() const; + bool __dispatch_retains_grad() const; + at::Tensor _fw_primal(int64_t level) const; + at::Tensor & rename_(c10::optional names) const; + at::Tensor rename(c10::optional names) const; + at::Tensor align_to(at::DimnameList names) const; + at::Tensor align_to(at::DimnameList order, int64_t ellipsis_idx) const; + at::Tensor align_as(const at::Tensor & other) const; + at::Tensor refine_names(at::DimnameList names) const; + at::Tensor abs() const; + at::Tensor & abs_() const; + at::Tensor absolute() const; + at::Tensor & absolute_() const; + at::Tensor angle() const; + at::Tensor sgn() const; + at::Tensor & sgn_() const; + at::Tensor chalf(c10::optional memory_format=c10::nullopt) const; + at::Tensor _conj() const; + at::Tensor __dispatch_conj() const; + at::Tensor _conj_physical() const; + at::Tensor conj_physical() const; + at::Tensor & conj_physical_() const; + at::Tensor resolve_conj() const; + at::Tensor resolve_neg() const; + at::Tensor _neg_view() const; + at::Tensor acos() const; + at::Tensor & acos_() const; + at::Tensor arccos() const; + at::Tensor & arccos_() const; + at::Tensor add(const at::Tensor & other, const at::Scalar & alpha=1) const; + at::Tensor & add_(const at::Tensor & other, const at::Scalar & alpha=1) const; + at::Tensor add(const at::Scalar & other, const at::Scalar & alpha=1) const; + at::Tensor & add_(const at::Scalar & other, const at::Scalar & alpha=1) const; + at::Tensor addmv(const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor & addmv_(const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor addr(const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor & addr_(const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor _is_all_true() const; + at::Tensor _is_any_true() const; + at::Tensor all(int64_t dim, bool keepdim=false) const; + at::Tensor all(at::OptionalIntArrayRef dim, bool keepdim=false) const; + at::Tensor all(at::Dimname dim, bool keepdim=false) const; + bool allclose(const at::Tensor & other, double rtol=1e-05, double atol=1e-08, bool equal_nan=false) const; + at::Tensor any(int64_t dim, bool keepdim=false) const; + at::Tensor any(at::OptionalIntArrayRef dim, bool keepdim=false) const; + at::Tensor any(at::Dimname dim, bool keepdim=false) const; + at::Tensor argmax(c10::optional dim=c10::nullopt, bool keepdim=false) const; + at::Tensor argmin(c10::optional dim=c10::nullopt, bool keepdim=false) const; + at::Tensor acosh() const; + at::Tensor & acosh_() const; + at::Tensor arccosh() const; + at::Tensor & arccosh_() const; + at::Tensor asinh() const; + at::Tensor & asinh_() const; + at::Tensor arcsinh() const; + at::Tensor & arcsinh_() const; + at::Tensor atanh() const; + at::Tensor & atanh_() const; + at::Tensor arctanh() const; + at::Tensor & arctanh_() const; + at::Tensor as_strided(at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) const; + at::Tensor as_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) const; + const at::Tensor & as_strided_(at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) const; + const at::Tensor & as_strided__symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) const; + at::Tensor asin() const; + at::Tensor & asin_() const; + at::Tensor arcsin() const; + at::Tensor & arcsin_() const; + at::Tensor atan() const; + at::Tensor & atan_() const; + at::Tensor arctan() const; + at::Tensor & arctan_() const; + at::Tensor baddbmm(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor & baddbmm_(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor bernoulli(c10::optional generator=c10::nullopt) const; + at::Tensor & bernoulli_(const at::Tensor & p, c10::optional generator=c10::nullopt) const; + at::Tensor & bernoulli_(double p=0.5, c10::optional generator=c10::nullopt) const; + at::Tensor bernoulli(double p, c10::optional generator=c10::nullopt) const; + at::Tensor bincount(const c10::optional & weights={}, int64_t minlength=0) const; + at::Tensor bitwise_not() const; + at::Tensor & bitwise_not_() const; + at::Tensor copysign(const at::Tensor & other) const; + at::Tensor & copysign_(const at::Tensor & other) const; + at::Tensor copysign(const at::Scalar & other) const; + at::Tensor & copysign_(const at::Scalar & other) const; + at::Tensor _lazy_clone() const; + at::Tensor logical_not() const; + at::Tensor & logical_not_() const; + at::Tensor logical_xor(const at::Tensor & other) const; + at::Tensor & logical_xor_(const at::Tensor & other) const; + at::Tensor logical_and(const at::Tensor & other) const; + at::Tensor & logical_and_(const at::Tensor & other) const; + at::Tensor logical_or(const at::Tensor & other) const; + at::Tensor & logical_or_(const at::Tensor & other) const; + at::Tensor bmm(const at::Tensor & mat2) const; + at::Tensor broadcast_to(at::IntArrayRef size) const; + at::Tensor broadcast_to_symint(c10::SymIntArrayRef size) const; + at::Tensor ceil() const; + at::Tensor & ceil_() const; + ::std::vector unsafe_chunk(int64_t chunks, int64_t dim=0) const; + ::std::vector chunk(int64_t chunks, int64_t dim=0) const; + ::std::vector tensor_split(int64_t sections, int64_t dim=0) const; + ::std::vector tensor_split_symint(c10::SymInt sections, int64_t dim=0) const; + ::std::vector tensor_split(at::IntArrayRef indices, int64_t dim=0) const; + ::std::vector tensor_split_symint(c10::SymIntArrayRef indices, int64_t dim=0) const; + ::std::vector tensor_split(const at::Tensor & tensor_indices_or_sections, int64_t dim=0) const; + at::Tensor clamp(const c10::optional & min, const c10::optional & max=c10::nullopt) const; + at::Tensor clamp(const c10::optional & min={}, const c10::optional & max={}) const; + at::Tensor & clamp_(const c10::optional & min, const c10::optional & max=c10::nullopt) const; + at::Tensor & clamp_(const c10::optional & min={}, const c10::optional & max={}) const; + at::Tensor clamp_max(const at::Scalar & max) const; + at::Tensor clamp_max(const at::Tensor & max) const; + at::Tensor & clamp_max_(const at::Scalar & max) const; + at::Tensor & clamp_max_(const at::Tensor & max) const; + at::Tensor clamp_min(const at::Scalar & min) const; + at::Tensor clamp_min(const at::Tensor & min) const; + at::Tensor & clamp_min_(const at::Scalar & min) const; + at::Tensor & clamp_min_(const at::Tensor & min) const; + at::Tensor clip(const c10::optional & min, const c10::optional & max=c10::nullopt) const; + at::Tensor clip(const c10::optional & min={}, const c10::optional & max={}) const; + at::Tensor & clip_(const c10::optional & min, const c10::optional & max=c10::nullopt) const; + at::Tensor & clip_(const c10::optional & min={}, const c10::optional & max={}) const; + at::Tensor __dispatch_contiguous(at::MemoryFormat memory_format=MemoryFormat::Contiguous) const; + at::Tensor & copy_(const at::Tensor & src, bool non_blocking=false) const; + at::Tensor cos() const; + at::Tensor & cos_() const; + at::Tensor cosh() const; + at::Tensor & cosh_() const; + at::Tensor count_nonzero(at::IntArrayRef dim) const; + at::Tensor count_nonzero(c10::optional dim=c10::nullopt) const; + at::Tensor cov(int64_t correction=1, const c10::optional & fweights={}, const c10::optional & aweights={}) const; + at::Tensor corrcoef() const; + ::std::tuple cummax(int64_t dim) const; + ::std::tuple cummax(at::Dimname dim) const; + ::std::tuple cummin(int64_t dim) const; + ::std::tuple cummin(at::Dimname dim) const; + at::Tensor cumprod(int64_t dim, c10::optional dtype=c10::nullopt) const; + at::Tensor & cumprod_(int64_t dim, c10::optional dtype=c10::nullopt) const; + at::Tensor cumprod(at::Dimname dim, c10::optional dtype=c10::nullopt) const; + at::Tensor & cumprod_(at::Dimname dim, c10::optional dtype=c10::nullopt) const; + at::Tensor cumsum(int64_t dim, c10::optional dtype=c10::nullopt) const; + at::Tensor & cumsum_(int64_t dim, c10::optional dtype=c10::nullopt) const; + at::Tensor cumsum(at::Dimname dim, c10::optional dtype=c10::nullopt) const; + at::Tensor & cumsum_(at::Dimname dim, c10::optional dtype=c10::nullopt) const; + at::Tensor diag_embed(int64_t offset=0, int64_t dim1=-2, int64_t dim2=-1) const; + at::Tensor diagflat(int64_t offset=0) const; + at::Tensor diagonal(int64_t offset=0, int64_t dim1=0, int64_t dim2=1) const; + at::Tensor diagonal(at::Dimname outdim, at::Dimname dim1, at::Dimname dim2, int64_t offset=0) const; + at::Tensor & fill_diagonal_(const at::Scalar & fill_value, bool wrap=false) const; + at::Tensor diff(int64_t n=1, int64_t dim=-1, const c10::optional & prepend={}, const c10::optional & append={}) const; + at::Tensor div(const at::Tensor & other) const; + at::Tensor & div_(const at::Tensor & other) const; + at::Tensor div(const at::Tensor & other, c10::optional rounding_mode) const; + at::Tensor & div_(const at::Tensor & other, c10::optional rounding_mode) const; + at::Tensor div(const at::Scalar & other) const; + at::Tensor & div_(const at::Scalar & other) const; + at::Tensor div(const at::Scalar & other, c10::optional rounding_mode) const; + at::Tensor & div_(const at::Scalar & other, c10::optional rounding_mode) const; + at::Tensor divide(const at::Tensor & other) const; + at::Tensor & divide_(const at::Tensor & other) const; + at::Tensor divide(const at::Scalar & other) const; + at::Tensor & divide_(const at::Scalar & other) const; + at::Tensor divide(const at::Tensor & other, c10::optional rounding_mode) const; + at::Tensor & divide_(const at::Tensor & other, c10::optional rounding_mode) const; + at::Tensor divide(const at::Scalar & other, c10::optional rounding_mode) const; + at::Tensor & divide_(const at::Scalar & other, c10::optional rounding_mode) const; + at::Tensor true_divide(const at::Tensor & other) const; + at::Tensor & true_divide_(const at::Tensor & other) const; + at::Tensor true_divide(const at::Scalar & other) const; + at::Tensor & true_divide_(const at::Scalar & other) const; + at::Tensor dot(const at::Tensor & tensor) const; + at::Tensor vdot(const at::Tensor & other) const; + at::Tensor new_empty(at::IntArrayRef size, at::TensorOptions options={}) const; + at::Tensor new_empty(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_empty_symint(c10::SymIntArrayRef size, at::TensorOptions options={}) const; + at::Tensor new_empty_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options={}) const; + at::Tensor new_empty_strided(at::IntArrayRef size, at::IntArrayRef stride, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options={}) const; + at::Tensor new_empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_full(at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}) const; + at::Tensor new_full(at::IntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}) const; + at::Tensor new_full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_zeros(at::IntArrayRef size, at::TensorOptions options={}) const; + at::Tensor new_zeros(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_zeros_symint(c10::SymIntArrayRef size, at::TensorOptions options={}) const; + at::Tensor new_zeros_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_ones(at::IntArrayRef size, at::TensorOptions options={}) const; + at::Tensor new_ones(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + at::Tensor new_ones_symint(c10::SymIntArrayRef size, at::TensorOptions options={}) const; + at::Tensor new_ones_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const; + const at::Tensor & resize_(at::IntArrayRef size, c10::optional memory_format=c10::nullopt) const; + const at::Tensor & resize__symint(c10::SymIntArrayRef size, c10::optional memory_format=c10::nullopt) const; + at::Tensor erf() const; + at::Tensor & erf_() const; + at::Tensor erfc() const; + at::Tensor & erfc_() const; + at::Tensor exp() const; + at::Tensor & exp_() const; + at::Tensor exp2() const; + at::Tensor & exp2_() const; + at::Tensor expm1() const; + at::Tensor & expm1_() const; + at::Tensor expand(at::IntArrayRef size, bool implicit=false) const; + at::Tensor expand_symint(c10::SymIntArrayRef size, bool implicit=false) const; + at::Tensor expand_as(const at::Tensor & other) const; + at::Tensor flatten(int64_t start_dim=0, int64_t end_dim=-1) const; + at::Tensor flatten(int64_t start_dim, int64_t end_dim, at::Dimname out_dim) const; + at::Tensor flatten(at::Dimname start_dim, at::Dimname end_dim, at::Dimname out_dim) const; + at::Tensor flatten(at::DimnameList dims, at::Dimname out_dim) const; + at::Tensor unflatten(int64_t dim, at::IntArrayRef sizes) const; + at::Tensor unflatten_symint(int64_t dim, c10::SymIntArrayRef sizes) const; + at::Tensor unflatten(at::Dimname dim, at::IntArrayRef sizes, at::DimnameList names) const; + at::Tensor unflatten_symint(at::Dimname dim, c10::SymIntArrayRef sizes, at::DimnameList names) const; + at::Tensor & fill_(const at::Scalar & value) const; + at::Tensor & fill_(const at::Tensor & value) const; + at::Tensor floor() const; + at::Tensor & floor_() const; + at::Tensor floor_divide(const at::Tensor & other) const; + at::Tensor & floor_divide_(const at::Tensor & other) const; + at::Tensor floor_divide(const at::Scalar & other) const; + at::Tensor & floor_divide_(const at::Scalar & other) const; + at::Tensor frac() const; + at::Tensor & frac_() const; + at::Tensor gcd(const at::Tensor & other) const; + at::Tensor & gcd_(const at::Tensor & other) const; + at::Tensor lcm(const at::Tensor & other) const; + at::Tensor & lcm_(const at::Tensor & other) const; + at::Tensor index(const c10::List> & indices) const; + at::Tensor & index_copy_(int64_t dim, const at::Tensor & index, const at::Tensor & source) const; + at::Tensor index_copy(int64_t dim, const at::Tensor & index, const at::Tensor & source) const; + at::Tensor & index_copy_(at::Dimname dim, const at::Tensor & index, const at::Tensor & source) const; + at::Tensor index_copy(at::Dimname dim, const at::Tensor & index, const at::Tensor & source) const; + at::Tensor & index_put_(const c10::List> & indices, const at::Tensor & values, bool accumulate=false) const; + at::Tensor index_put(const c10::List> & indices, const at::Tensor & values, bool accumulate=false) const; + at::Tensor isclose(const at::Tensor & other, double rtol=1e-05, double atol=1e-08, bool equal_nan=false) const; + at::Tensor isnan() const; + bool is_distributed() const; + bool __dispatch_is_floating_point() const; + bool __dispatch_is_complex() const; + bool __dispatch_is_conj() const; + bool __dispatch__is_zerotensor() const; + bool __dispatch_is_neg() const; + at::Tensor isreal() const; + bool is_nonzero() const; + bool is_same_size(const at::Tensor & other) const; + bool __dispatch_is_signed() const; + bool __dispatch_is_inference() const; + at::Tensor kron(const at::Tensor & other) const; + ::std::tuple kthvalue(int64_t k, int64_t dim=-1, bool keepdim=false) const; + ::std::tuple kthvalue(int64_t k, at::Dimname dim, bool keepdim=false) const; + at::Tensor nan_to_num(c10::optional nan=c10::nullopt, c10::optional posinf=c10::nullopt, c10::optional neginf=c10::nullopt) const; + at::Tensor & nan_to_num_(c10::optional nan=c10::nullopt, c10::optional posinf=c10::nullopt, c10::optional neginf=c10::nullopt) const; + at::Tensor ldexp(const at::Tensor & other) const; + at::Tensor & ldexp_(const at::Tensor & other) const; + at::Tensor log() const; + at::Tensor & log_() const; + at::Tensor log10() const; + at::Tensor & log10_() const; + at::Tensor log1p() const; + at::Tensor & log1p_() const; + at::Tensor log2() const; + at::Tensor & log2_() const; + at::Tensor logaddexp(const at::Tensor & other) const; + at::Tensor logaddexp2(const at::Tensor & other) const; + at::Tensor xlogy(const at::Tensor & other) const; + at::Tensor xlogy(const at::Scalar & other) const; + at::Tensor & xlogy_(const at::Tensor & other) const; + at::Tensor & xlogy_(const at::Scalar & other) const; + at::Tensor log_softmax(int64_t dim, c10::optional dtype=c10::nullopt) const; + at::Tensor log_softmax(at::Dimname dim, c10::optional dtype=c10::nullopt) const; + at::Tensor logcumsumexp(int64_t dim) const; + at::Tensor logcumsumexp(at::Dimname dim) const; + at::Tensor logsumexp(at::IntArrayRef dim, bool keepdim=false) const; + at::Tensor logsumexp(at::DimnameList dim, bool keepdim=false) const; + at::Tensor matmul(const at::Tensor & other) const; + at::Tensor matrix_power(int64_t n) const; + at::Tensor matrix_exp() const; + ::std::tuple aminmax(c10::optional dim=c10::nullopt, bool keepdim=false) const; + ::std::tuple max(int64_t dim, bool keepdim=false) const; + ::std::tuple max(at::Dimname dim, bool keepdim=false) const; + at::Tensor amax(at::IntArrayRef dim={}, bool keepdim=false) const; + at::Tensor mean(c10::optional dtype=c10::nullopt) const; + at::Tensor mean(at::OptionalIntArrayRef dim, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor mean(at::DimnameList dim, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor nanmean(at::OptionalIntArrayRef dim=c10::nullopt, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor median() const; + ::std::tuple median(int64_t dim, bool keepdim=false) const; + ::std::tuple median(at::Dimname dim, bool keepdim=false) const; + at::Tensor nanmedian() const; + ::std::tuple nanmedian(int64_t dim, bool keepdim=false) const; + ::std::tuple nanmedian(at::Dimname dim, bool keepdim=false) const; + ::std::tuple min(int64_t dim, bool keepdim=false) const; + ::std::tuple min(at::Dimname dim, bool keepdim=false) const; + at::Tensor amin(at::IntArrayRef dim={}, bool keepdim=false) const; + at::Tensor mm(const at::Tensor & mat2) const; + ::std::tuple mode(int64_t dim=-1, bool keepdim=false) const; + ::std::tuple mode(at::Dimname dim, bool keepdim=false) const; + at::Tensor mul(const at::Tensor & other) const; + at::Tensor & mul_(const at::Tensor & other) const; + at::Tensor mul(const at::Scalar & other) const; + at::Tensor & mul_(const at::Scalar & other) const; + at::Tensor multiply(const at::Tensor & other) const; + at::Tensor & multiply_(const at::Tensor & other) const; + at::Tensor multiply(const at::Scalar & other) const; + at::Tensor & multiply_(const at::Scalar & other) const; + at::Tensor mv(const at::Tensor & vec) const; + at::Tensor mvlgamma(int64_t p) const; + at::Tensor & mvlgamma_(int64_t p) const; + at::Tensor narrow_copy(int64_t dim, int64_t start, int64_t length) const; + at::Tensor narrow_copy_symint(int64_t dim, c10::SymInt start, c10::SymInt length) const; + at::Tensor narrow(int64_t dim, int64_t start, int64_t length) const; + at::Tensor narrow_symint(int64_t dim, c10::SymInt start, c10::SymInt length) const; + at::Tensor narrow(int64_t dim, const at::Tensor & start, int64_t length) const; + at::Tensor narrow_symint(int64_t dim, const at::Tensor & start, c10::SymInt length) const; + at::Tensor permute(at::IntArrayRef dims) const; + at::Tensor movedim(at::IntArrayRef source, at::IntArrayRef destination) const; + at::Tensor movedim(int64_t source, int64_t destination) const; + at::Tensor moveaxis(at::IntArrayRef source, at::IntArrayRef destination) const; + at::Tensor moveaxis(int64_t source, int64_t destination) const; + at::Tensor numpy_T() const; + at::Tensor matrix_H() const; + at::Tensor mT() const; + at::Tensor mH() const; + at::Tensor adjoint() const; + bool is_pinned(c10::optional device=c10::nullopt) const; + at::Tensor pin_memory(c10::optional device=c10::nullopt) const; + at::Tensor pinverse(double rcond=1e-15) const; + at::Tensor rad2deg() const; + at::Tensor & rad2deg_() const; + at::Tensor deg2rad() const; + at::Tensor & deg2rad_() const; + at::Tensor ravel() const; + at::Tensor reciprocal() const; + at::Tensor & reciprocal_() const; + at::Tensor neg() const; + at::Tensor & neg_() const; + at::Tensor negative() const; + at::Tensor & negative_() const; + at::Tensor repeat(at::IntArrayRef repeats) const; + at::Tensor repeat_symint(c10::SymIntArrayRef repeats) const; + at::Tensor repeat_interleave(const at::Tensor & repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) const; + at::Tensor repeat_interleave_symint(const at::Tensor & repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) const; + at::Tensor repeat_interleave(int64_t repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) const; + at::Tensor repeat_interleave_symint(c10::SymInt repeats, c10::optional dim=c10::nullopt, c10::optional output_size=c10::nullopt) const; + at::Tensor reshape(at::IntArrayRef shape) const; + at::Tensor reshape_symint(c10::SymIntArrayRef shape) const; + at::Tensor _reshape_alias(at::IntArrayRef size, at::IntArrayRef stride) const; + at::Tensor _reshape_alias_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride) const; + at::Tensor reshape_as(const at::Tensor & other) const; + at::Tensor round() const; + at::Tensor & round_() const; + at::Tensor round(int64_t decimals) const; + at::Tensor & round_(int64_t decimals) const; + at::Tensor relu() const; + at::Tensor & relu_() const; + at::Tensor prelu(const at::Tensor & weight) const; + at::Tensor hardshrink(const at::Scalar & lambd=0.5) const; + at::Tensor hardshrink_backward(const at::Tensor & grad_out, const at::Scalar & lambd) const; + at::Tensor rsqrt() const; + at::Tensor & rsqrt_() const; + at::Tensor select(at::Dimname dim, int64_t index) const; + at::Tensor select(int64_t dim, int64_t index) const; + at::Tensor select_symint(int64_t dim, c10::SymInt index) const; + at::Tensor sigmoid() const; + at::Tensor & sigmoid_() const; + at::Tensor logit(c10::optional eps=c10::nullopt) const; + at::Tensor & logit_(c10::optional eps=c10::nullopt) const; + at::Tensor sin() const; + at::Tensor & sin_() const; + at::Tensor sinc() const; + at::Tensor & sinc_() const; + at::Tensor sinh() const; + at::Tensor & sinh_() const; + at::Tensor detach() const; + at::Tensor & detach_() const; + int64_t size(at::Dimname dim) const; + at::Tensor slice(int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1) const; + at::Tensor slice_symint(int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, c10::SymInt step=1) const; + at::Tensor slice_inverse(const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1) const; + at::Tensor slice_inverse_symint(const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, c10::SymInt step=1) const; + at::Tensor slice_scatter(const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, int64_t step=1) const; + at::Tensor slice_scatter_symint(const at::Tensor & src, int64_t dim=0, c10::optional start=c10::nullopt, c10::optional end=c10::nullopt, c10::SymInt step=1) const; + at::Tensor select_scatter(const at::Tensor & src, int64_t dim, int64_t index) const; + at::Tensor select_scatter_symint(const at::Tensor & src, int64_t dim, c10::SymInt index) const; + at::Tensor diagonal_scatter(const at::Tensor & src, int64_t offset=0, int64_t dim1=0, int64_t dim2=1) const; + at::Tensor as_strided_scatter(const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt) const; + at::Tensor as_strided_scatter_symint(const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt) const; + at::Tensor smm(const at::Tensor & mat2) const; + at::Tensor softmax(int64_t dim, c10::optional dtype=c10::nullopt) const; + at::Tensor softmax(at::Dimname dim, c10::optional dtype=c10::nullopt) const; + ::std::vector unsafe_split(int64_t split_size, int64_t dim=0) const; + ::std::vector unsafe_split_symint(c10::SymInt split_size, int64_t dim=0) const; + ::std::vector split(int64_t split_size, int64_t dim=0) const; + ::std::vector split_symint(c10::SymInt split_size, int64_t dim=0) const; + ::std::vector split(at::IntArrayRef split_size, int64_t dim=0) const; + ::std::vector split_symint(c10::SymIntArrayRef split_size, int64_t dim=0) const; + ::std::vector unsafe_split_with_sizes(at::IntArrayRef split_sizes, int64_t dim=0) const; + ::std::vector unsafe_split_with_sizes_symint(c10::SymIntArrayRef split_sizes, int64_t dim=0) const; + ::std::vector split_with_sizes(at::IntArrayRef split_sizes, int64_t dim=0) const; + ::std::vector split_with_sizes_symint(c10::SymIntArrayRef split_sizes, int64_t dim=0) const; + ::std::vector hsplit(int64_t sections) const; + ::std::vector hsplit(at::IntArrayRef indices) const; + ::std::vector vsplit(int64_t sections) const; + ::std::vector vsplit(at::IntArrayRef indices) const; + ::std::vector dsplit(int64_t sections) const; + ::std::vector dsplit(at::IntArrayRef indices) const; + at::Tensor squeeze() const; + at::Tensor squeeze(int64_t dim) const; + at::Tensor squeeze(at::Dimname dim) const; + at::Tensor squeeze(at::IntArrayRef dim) const; + at::Tensor & squeeze_() const; + at::Tensor & squeeze_(int64_t dim) const; + at::Tensor & squeeze_(at::IntArrayRef dim) const; + at::Tensor & squeeze_(at::Dimname dim) const; + at::Tensor sspaddmm(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor stft(int64_t n_fft, c10::optional hop_length, c10::optional win_length, const c10::optional & window, bool normalized, c10::optional onesided=c10::nullopt, c10::optional return_complex=c10::nullopt) const; + at::Tensor stft(int64_t n_fft, c10::optional hop_length=c10::nullopt, c10::optional win_length=c10::nullopt, const c10::optional & window={}, bool center=true, c10::string_view pad_mode="reflect", bool normalized=false, c10::optional onesided=c10::nullopt, c10::optional return_complex=c10::nullopt) const; + at::Tensor istft(int64_t n_fft, c10::optional hop_length=c10::nullopt, c10::optional win_length=c10::nullopt, const c10::optional & window={}, bool center=true, bool normalized=false, c10::optional onesided=c10::nullopt, c10::optional length=c10::nullopt, bool return_complex=false) const; + int64_t stride(at::Dimname dim) const; + at::Tensor sum(c10::optional dtype=c10::nullopt) const; + at::Tensor sum(at::OptionalIntArrayRef dim, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor sum(at::DimnameList dim, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor nansum(at::OptionalIntArrayRef dim=c10::nullopt, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor sum_to_size(at::IntArrayRef size) const; + at::Tensor sum_to_size_symint(c10::SymIntArrayRef size) const; + at::Tensor sqrt() const; + at::Tensor & sqrt_() const; + at::Tensor square() const; + at::Tensor & square_() const; + at::Tensor std(bool unbiased) const; + at::Tensor std(at::OptionalIntArrayRef dim, bool unbiased, bool keepdim=false) const; + at::Tensor std(at::OptionalIntArrayRef dim=c10::nullopt, const c10::optional & correction=c10::nullopt, bool keepdim=false) const; + at::Tensor std(at::DimnameList dim, bool unbiased, bool keepdim=false) const; + at::Tensor std(at::DimnameList dim, const c10::optional & correction=c10::nullopt, bool keepdim=false) const; + at::Tensor prod(c10::optional dtype=c10::nullopt) const; + at::Tensor prod(int64_t dim, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor prod(at::Dimname dim, bool keepdim=false, c10::optional dtype=c10::nullopt) const; + at::Tensor t() const; + at::Tensor & t_() const; + at::Tensor tan() const; + at::Tensor & tan_() const; + at::Tensor tanh() const; + at::Tensor & tanh_() const; + at::Tensor tile(at::IntArrayRef dims) const; + at::Tensor tile_symint(c10::SymIntArrayRef dims) const; + at::Tensor transpose(int64_t dim0, int64_t dim1) const; + at::Tensor transpose(at::Dimname dim0, at::Dimname dim1) const; + at::Tensor & transpose_(int64_t dim0, int64_t dim1) const; + at::Tensor flip(at::IntArrayRef dims) const; + at::Tensor fliplr() const; + at::Tensor flipud() const; + at::Tensor roll(at::IntArrayRef shifts, at::IntArrayRef dims={}) const; + at::Tensor roll_symint(c10::SymIntArrayRef shifts, at::IntArrayRef dims={}) const; + at::Tensor rot90(int64_t k=1, at::IntArrayRef dims={0,1}) const; + at::Tensor _nested_tensor_size() const; + at::Tensor _nested_tensor_strides() const; + at::Tensor _nested_tensor_storage_offsets() const; + at::Tensor trunc() const; + at::Tensor & trunc_() const; + at::Tensor fix() const; + at::Tensor & fix_() const; + at::Tensor type_as(const at::Tensor & other) const; + at::Tensor unsqueeze(int64_t dim) const; + at::Tensor & unsqueeze_(int64_t dim) const; + at::Tensor var(bool unbiased) const; + at::Tensor var(at::OptionalIntArrayRef dim, bool unbiased, bool keepdim=false) const; + at::Tensor var(at::OptionalIntArrayRef dim=c10::nullopt, const c10::optional & correction=c10::nullopt, bool keepdim=false) const; + at::Tensor var(at::DimnameList dim, bool unbiased, bool keepdim=false) const; + at::Tensor var(at::DimnameList dim, const c10::optional & correction=c10::nullopt, bool keepdim=false) const; + at::Tensor view_as(const at::Tensor & other) const; + at::Tensor where(const at::Tensor & condition, const at::Tensor & other) const; + at::Tensor where(const at::Tensor & condition, const at::Scalar & other) const; + at::Tensor norm(const c10::optional & p, at::ScalarType dtype) const; + at::Tensor norm(const at::Scalar & p=2) const; + at::Tensor norm(const c10::optional & p, at::IntArrayRef dim, bool keepdim, at::ScalarType dtype) const; + at::Tensor norm(const c10::optional & p, at::IntArrayRef dim, bool keepdim=false) const; + at::Tensor norm(const c10::optional & p, at::DimnameList dim, bool keepdim, at::ScalarType dtype) const; + at::Tensor norm(const c10::optional & p, at::DimnameList dim, bool keepdim=false) const; + ::std::tuple frexp() const; + at::Tensor clone(c10::optional memory_format=c10::nullopt) const; + at::Tensor positive() const; + const at::Tensor & resize_as_(const at::Tensor & the_template, c10::optional memory_format=c10::nullopt) const; + const at::Tensor & resize_as_sparse_(const at::Tensor & the_template) const; + at::Tensor & zero_() const; + at::Tensor sub(const at::Tensor & other, const at::Scalar & alpha=1) const; + at::Tensor & sub_(const at::Tensor & other, const at::Scalar & alpha=1) const; + at::Tensor sub(const at::Scalar & other, const at::Scalar & alpha=1) const; + at::Tensor & sub_(const at::Scalar & other, const at::Scalar & alpha=1) const; + at::Tensor subtract(const at::Tensor & other, const at::Scalar & alpha=1) const; + at::Tensor & subtract_(const at::Tensor & other, const at::Scalar & alpha=1) const; + at::Tensor subtract(const at::Scalar & other, const at::Scalar & alpha=1) const; + at::Tensor & subtract_(const at::Scalar & other, const at::Scalar & alpha=1) const; + at::Tensor heaviside(const at::Tensor & values) const; + at::Tensor & heaviside_(const at::Tensor & values) const; + at::Tensor addmm(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor & addmm_(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor _addmm_activation(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta=1, const at::Scalar & alpha=1, bool use_gelu=false) const; + const at::Tensor & sparse_resize_(at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim) const; + const at::Tensor & sparse_resize_and_clear_(at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim) const; + at::Tensor sparse_mask(const at::Tensor & mask) const; + at::Tensor _sparse_mask_projection(const at::Tensor & mask, bool accumulate_matches=false) const; + at::Tensor to_dense(c10::optional dtype=c10::nullopt, c10::optional masked_grad=c10::nullopt) const; + at::Tensor _to_dense(c10::optional dtype=c10::nullopt, c10::optional masked_grad=c10::nullopt) const; + int64_t sparse_dim() const; + int64_t _dimI() const; + int64_t dense_dim() const; + int64_t _dimV() const; + int64_t _nnz() const; + at::Tensor coalesce() const; + bool is_coalesced() const; + at::Tensor _indices() const; + at::Tensor _values() const; + at::Tensor & _coalesced_(bool coalesced) const; + at::Tensor indices() const; + at::Tensor values() const; + at::Tensor crow_indices() const; + at::Tensor col_indices() const; + at::Tensor ccol_indices() const; + at::Tensor row_indices() const; + ::std::vector unbind(int64_t dim=0) const; + ::std::vector unbind(at::Dimname dim) const; + at::Tensor to_sparse(int64_t sparse_dim) const; + at::Tensor _to_sparse(int64_t sparse_dim) const; + at::Tensor to_sparse(c10::optional layout=c10::nullopt, at::OptionalIntArrayRef blocksize=c10::nullopt, c10::optional dense_dim=c10::nullopt) const; + at::Tensor _to_sparse(c10::optional layout=c10::nullopt, at::OptionalIntArrayRef blocksize=c10::nullopt, c10::optional dense_dim=c10::nullopt) const; + at::Tensor to_sparse_csr(c10::optional dense_dim=c10::nullopt) const; + at::Tensor _to_sparse_csr(c10::optional dense_dim=c10::nullopt) const; + at::Tensor to_sparse_csc(c10::optional dense_dim=c10::nullopt) const; + at::Tensor _to_sparse_csc(c10::optional dense_dim=c10::nullopt) const; + at::Tensor to_sparse_bsr(at::IntArrayRef blocksize, c10::optional dense_dim=c10::nullopt) const; + at::Tensor _to_sparse_bsr(at::IntArrayRef blocksize, c10::optional dense_dim=c10::nullopt) const; + at::Tensor to_sparse_bsc(at::IntArrayRef blocksize, c10::optional dense_dim=c10::nullopt) const; + at::Tensor _to_sparse_bsc(at::IntArrayRef blocksize, c10::optional dense_dim=c10::nullopt) const; + at::Tensor to_mkldnn(c10::optional dtype=c10::nullopt) const; + at::Tensor dequantize() const; + double q_scale() const; + int64_t q_zero_point() const; + at::Tensor q_per_channel_scales() const; + at::Tensor q_per_channel_zero_points() const; + int64_t q_per_channel_axis() const; + at::Tensor int_repr() const; + at::QScheme qscheme() const; + at::Tensor _autocast_to_reduced_precision(bool cuda_enabled, bool cpu_enabled, at::ScalarType cuda_dtype, at::ScalarType cpu_dtype) const; + at::Tensor _autocast_to_full_precision(bool cuda_enabled, bool cpu_enabled) const; + at::Tensor to(at::TensorOptions options={}, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt) const; + at::Tensor to(c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, bool non_blocking, bool copy, c10::optional memory_format) const; + at::Tensor to(at::Device device, at::ScalarType dtype, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt) const; + at::Tensor to(at::ScalarType dtype, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt) const; + at::Tensor to(const at::Tensor & other, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt) const; + at::Scalar item() const; + at::Tensor & set_(at::Storage source) const; + at::Tensor & set_(at::Storage source, int64_t storage_offset, at::IntArrayRef size, at::IntArrayRef stride={}) const; + at::Tensor & set__symint(at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride={}) const; + at::Tensor & set_(const at::Tensor & source, int64_t storage_offset, at::IntArrayRef size, at::IntArrayRef stride={}) const; + at::Tensor & set__symint(const at::Tensor & source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride={}) const; + at::Tensor & set_(const at::Tensor & source) const; + at::Tensor & set_() const; + bool is_set_to(const at::Tensor & tensor) const; + at::Tensor & masked_fill_(const at::Tensor & mask, const at::Scalar & value) const; + at::Tensor masked_fill(const at::Tensor & mask, const at::Scalar & value) const; + at::Tensor & masked_fill_(const at::Tensor & mask, const at::Tensor & value) const; + at::Tensor masked_fill(const at::Tensor & mask, const at::Tensor & value) const; + at::Tensor & masked_scatter_(const at::Tensor & mask, const at::Tensor & source) const; + at::Tensor masked_scatter(const at::Tensor & mask, const at::Tensor & source) const; + at::Tensor view(at::IntArrayRef size) const; + at::Tensor view_symint(c10::SymIntArrayRef size) const; + at::Tensor view(at::ScalarType dtype) const; + at::Tensor & put_(const at::Tensor & index, const at::Tensor & source, bool accumulate=false) const; + at::Tensor put(const at::Tensor & index, const at::Tensor & source, bool accumulate=false) const; + at::Tensor & index_add_(int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha=1) const; + at::Tensor index_add(int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha=1) const; + at::Tensor index_add(at::Dimname dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha=1) const; + at::Tensor & index_reduce_(int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true) const; + at::Tensor index_reduce(int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true) const; + at::Tensor & index_fill_(int64_t dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor index_fill(int64_t dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor & index_fill_(int64_t dim, const at::Tensor & index, const at::Tensor & value) const; + at::Tensor index_fill(int64_t dim, const at::Tensor & index, const at::Tensor & value) const; + at::Tensor & index_fill_(at::Dimname dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor & index_fill_(at::Dimname dim, const at::Tensor & index, const at::Tensor & value) const; + at::Tensor index_fill(at::Dimname dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor index_fill(at::Dimname dim, const at::Tensor & index, const at::Tensor & value) const; + at::Tensor scatter(int64_t dim, const at::Tensor & index, const at::Tensor & src) const; + at::Tensor & scatter_(int64_t dim, const at::Tensor & index, const at::Tensor & src) const; + at::Tensor scatter(int64_t dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor & scatter_(int64_t dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor scatter(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce) const; + at::Tensor & scatter_(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce) const; + at::Tensor scatter(int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce) const; + at::Tensor & scatter_(int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce) const; + at::Tensor scatter(at::Dimname dim, const at::Tensor & index, const at::Tensor & src) const; + at::Tensor scatter(at::Dimname dim, const at::Tensor & index, const at::Scalar & value) const; + at::Tensor scatter_add(int64_t dim, const at::Tensor & index, const at::Tensor & src) const; + at::Tensor & scatter_add_(int64_t dim, const at::Tensor & index, const at::Tensor & src) const; + at::Tensor scatter_add(at::Dimname dim, const at::Tensor & index, const at::Tensor & src) const; + at::Tensor scatter_reduce(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self=true) const; + at::Tensor & scatter_reduce_(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self=true) const; + at::Tensor & eq_(const at::Scalar & other) const; + at::Tensor & eq_(const at::Tensor & other) const; + at::Tensor bitwise_and(const at::Scalar & other) const; + at::Tensor bitwise_and(const at::Tensor & other) const; + at::Tensor & bitwise_and_(const at::Scalar & other) const; + at::Tensor & bitwise_and_(const at::Tensor & other) const; + at::Tensor __and__(const at::Scalar & other) const; + at::Tensor __and__(const at::Tensor & other) const; + at::Tensor & __iand__(const at::Scalar & other) const; + at::Tensor & __iand__(const at::Tensor & other) const; + at::Tensor bitwise_or(const at::Scalar & other) const; + at::Tensor bitwise_or(const at::Tensor & other) const; + at::Tensor & bitwise_or_(const at::Scalar & other) const; + at::Tensor & bitwise_or_(const at::Tensor & other) const; + at::Tensor __or__(const at::Scalar & other) const; + at::Tensor __or__(const at::Tensor & other) const; + at::Tensor & __ior__(const at::Scalar & other) const; + at::Tensor & __ior__(const at::Tensor & other) const; + at::Tensor bitwise_xor(const at::Scalar & other) const; + at::Tensor bitwise_xor(const at::Tensor & other) const; + at::Tensor & bitwise_xor_(const at::Scalar & other) const; + at::Tensor & bitwise_xor_(const at::Tensor & other) const; + at::Tensor __xor__(const at::Scalar & other) const; + at::Tensor __xor__(const at::Tensor & other) const; + at::Tensor & __ixor__(const at::Scalar & other) const; + at::Tensor & __ixor__(const at::Tensor & other) const; + at::Tensor __lshift__(const at::Scalar & other) const; + at::Tensor __lshift__(const at::Tensor & other) const; + at::Tensor & __ilshift__(const at::Scalar & other) const; + at::Tensor & __ilshift__(const at::Tensor & other) const; + at::Tensor bitwise_left_shift(const at::Tensor & other) const; + at::Tensor & bitwise_left_shift_(const at::Tensor & other) const; + at::Tensor bitwise_left_shift(const at::Scalar & other) const; + at::Tensor & bitwise_left_shift_(const at::Scalar & other) const; + at::Tensor __rshift__(const at::Scalar & other) const; + at::Tensor __rshift__(const at::Tensor & other) const; + at::Tensor & __irshift__(const at::Scalar & other) const; + at::Tensor & __irshift__(const at::Tensor & other) const; + at::Tensor bitwise_right_shift(const at::Tensor & other) const; + at::Tensor & bitwise_right_shift_(const at::Tensor & other) const; + at::Tensor bitwise_right_shift(const at::Scalar & other) const; + at::Tensor & bitwise_right_shift_(const at::Scalar & other) const; + at::Tensor & tril_(int64_t diagonal=0) const; + at::Tensor & triu_(int64_t diagonal=0) const; + at::Tensor & digamma_() const; + at::Tensor & lerp_(const at::Tensor & end, const at::Scalar & weight) const; + at::Tensor & lerp_(const at::Tensor & end, const at::Tensor & weight) const; + at::Tensor & addbmm_(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor addbmm(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta=1, const at::Scalar & alpha=1) const; + at::Tensor & random_(int64_t from, c10::optional to, c10::optional generator=c10::nullopt) const; + at::Tensor & random_(int64_t to, c10::optional generator=c10::nullopt) const; + at::Tensor & random_(c10::optional generator=c10::nullopt) const; + at::Tensor & uniform_(double from=0, double to=1, c10::optional generator=c10::nullopt) const; + at::Tensor & cauchy_(double median=0, double sigma=1, c10::optional generator=c10::nullopt) const; + at::Tensor & log_normal_(double mean=1, double std=2, c10::optional generator=c10::nullopt) const; + at::Tensor & exponential_(double lambd=1, c10::optional generator=c10::nullopt) const; + at::Tensor & geometric_(double p, c10::optional generator=c10::nullopt) const; + at::Tensor diag(int64_t diagonal=0) const; + at::Tensor cross(const at::Tensor & other, c10::optional dim=c10::nullopt) const; + at::Tensor triu(int64_t diagonal=0) const; + at::Tensor tril(int64_t diagonal=0) const; + at::Tensor trace() const; + at::Tensor ne(const at::Scalar & other) const; + at::Tensor ne(const at::Tensor & other) const; + at::Tensor & ne_(const at::Scalar & other) const; + at::Tensor & ne_(const at::Tensor & other) const; + at::Tensor not_equal(const at::Scalar & other) const; + at::Tensor not_equal(const at::Tensor & other) const; + at::Tensor & not_equal_(const at::Scalar & other) const; + at::Tensor & not_equal_(const at::Tensor & other) const; + at::Tensor eq(const at::Scalar & other) const; + at::Tensor eq(const at::Tensor & other) const; + at::Tensor ge(const at::Scalar & other) const; + at::Tensor ge(const at::Tensor & other) const; + at::Tensor & ge_(const at::Scalar & other) const; + at::Tensor & ge_(const at::Tensor & other) const; + at::Tensor greater_equal(const at::Scalar & other) const; + at::Tensor greater_equal(const at::Tensor & other) const; + at::Tensor & greater_equal_(const at::Scalar & other) const; + at::Tensor & greater_equal_(const at::Tensor & other) const; + at::Tensor le(const at::Scalar & other) const; + at::Tensor le(const at::Tensor & other) const; + at::Tensor & le_(const at::Scalar & other) const; + at::Tensor & le_(const at::Tensor & other) const; + at::Tensor less_equal(const at::Scalar & other) const; + at::Tensor less_equal(const at::Tensor & other) const; + at::Tensor & less_equal_(const at::Scalar & other) const; + at::Tensor & less_equal_(const at::Tensor & other) const; + at::Tensor gt(const at::Scalar & other) const; + at::Tensor gt(const at::Tensor & other) const; + at::Tensor & gt_(const at::Scalar & other) const; + at::Tensor & gt_(const at::Tensor & other) const; + at::Tensor greater(const at::Scalar & other) const; + at::Tensor greater(const at::Tensor & other) const; + at::Tensor & greater_(const at::Scalar & other) const; + at::Tensor & greater_(const at::Tensor & other) const; + at::Tensor lt(const at::Scalar & other) const; + at::Tensor lt(const at::Tensor & other) const; + at::Tensor & lt_(const at::Scalar & other) const; + at::Tensor & lt_(const at::Tensor & other) const; + at::Tensor less(const at::Scalar & other) const; + at::Tensor less(const at::Tensor & other) const; + at::Tensor & less_(const at::Scalar & other) const; + at::Tensor & less_(const at::Tensor & other) const; + at::Tensor take(const at::Tensor & index) const; + at::Tensor take_along_dim(const at::Tensor & indices, c10::optional dim=c10::nullopt) const; + at::Tensor index_select(int64_t dim, const at::Tensor & index) const; + at::Tensor index_select(at::Dimname dim, const at::Tensor & index) const; + at::Tensor masked_select(const at::Tensor & mask) const; + at::Tensor nonzero() const; + at::Tensor nonzero_static(int64_t size, int64_t fill_value=-1) const; + ::std::vector nonzero_numpy() const; + at::Tensor argwhere() const; + at::Tensor gather(int64_t dim, const at::Tensor & index, bool sparse_grad=false) const; + at::Tensor gather(at::Dimname dim, const at::Tensor & index, bool sparse_grad=false) const; + at::Tensor addcmul(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1) const; + at::Tensor & addcmul_(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1) const; + at::Tensor addcdiv(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1) const; + at::Tensor & addcdiv_(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1) const; + ::std::tuple triangular_solve(const at::Tensor & A, bool upper=true, bool transpose=false, bool unitriangular=false) const; + ::std::tuple svd(bool some=true, bool compute_uv=true) const; + at::Tensor swapaxes(int64_t axis0, int64_t axis1) const; + at::Tensor & swapaxes_(int64_t axis0, int64_t axis1) const; + at::Tensor swapdims(int64_t dim0, int64_t dim1) const; + at::Tensor & swapdims_(int64_t dim0, int64_t dim1) const; + at::Tensor cholesky(bool upper=false) const; + at::Tensor cholesky_solve(const at::Tensor & input2, bool upper=false) const; + at::Tensor cholesky_inverse(bool upper=false) const; + ::std::tuple qr(bool some=true) const; + ::std::tuple geqrf() const; + at::Tensor orgqr(const at::Tensor & input2) const; + at::Tensor ormqr(const at::Tensor & input2, const at::Tensor & input3, bool left=true, bool transpose=false) const; + at::Tensor lu_solve(const at::Tensor & LU_data, const at::Tensor & LU_pivots) const; + at::Tensor multinomial(int64_t num_samples, bool replacement=false, c10::optional generator=c10::nullopt) const; + at::Tensor & lgamma_() const; + at::Tensor lgamma() const; + at::Tensor digamma() const; + at::Tensor polygamma(int64_t n) const; + at::Tensor & polygamma_(int64_t n) const; + at::Tensor erfinv() const; + at::Tensor & erfinv_() const; + at::Tensor i0() const; + at::Tensor & i0_() const; + at::Tensor sign() const; + at::Tensor & sign_() const; + at::Tensor signbit() const; + at::Tensor dist(const at::Tensor & other, const at::Scalar & p=2) const; + at::Tensor & atan2_(const at::Tensor & other) const; + at::Tensor atan2(const at::Tensor & other) const; + at::Tensor arctan2(const at::Tensor & other) const; + at::Tensor & arctan2_(const at::Tensor & other) const; + at::Tensor lerp(const at::Tensor & end, const at::Scalar & weight) const; + at::Tensor lerp(const at::Tensor & end, const at::Tensor & weight) const; + at::Tensor histc(int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0) const; + ::std::tuple histogram(const at::Tensor & bins, const c10::optional & weight={}, bool density=false) const; + ::std::tuple histogram(int64_t bins=100, c10::optional> range=c10::nullopt, const c10::optional & weight={}, bool density=false) const; + at::Tensor fmod(const at::Scalar & other) const; + at::Tensor & fmod_(const at::Scalar & other) const; + at::Tensor fmod(const at::Tensor & other) const; + at::Tensor & fmod_(const at::Tensor & other) const; + at::Tensor hypot(const at::Tensor & other) const; + at::Tensor & hypot_(const at::Tensor & other) const; + at::Tensor igamma(const at::Tensor & other) const; + at::Tensor & igamma_(const at::Tensor & other) const; + at::Tensor igammac(const at::Tensor & other) const; + at::Tensor & igammac_(const at::Tensor & other) const; + at::Tensor nextafter(const at::Tensor & other) const; + at::Tensor & nextafter_(const at::Tensor & other) const; + at::Tensor remainder(const at::Scalar & other) const; + at::Tensor & remainder_(const at::Scalar & other) const; + at::Tensor remainder(const at::Tensor & other) const; + at::Tensor & remainder_(const at::Tensor & other) const; + at::Tensor min() const; + at::Tensor fmin(const at::Tensor & other) const; + at::Tensor max() const; + at::Tensor fmax(const at::Tensor & other) const; + at::Tensor maximum(const at::Tensor & other) const; + at::Tensor max(const at::Tensor & other) const; + at::Tensor minimum(const at::Tensor & other) const; + at::Tensor min(const at::Tensor & other) const; + at::Tensor quantile(const at::Tensor & q, c10::optional dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear") const; + at::Tensor quantile(double q, c10::optional dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear") const; + at::Tensor nanquantile(const at::Tensor & q, c10::optional dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear") const; + at::Tensor nanquantile(double q, c10::optional dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear") const; + ::std::tuple sort(int64_t dim=-1, bool descending=false) const; + ::std::tuple sort(c10::optional stable, int64_t dim=-1, bool descending=false) const; + ::std::tuple sort(at::Dimname dim, bool descending=false) const; + ::std::tuple sort(c10::optional stable, at::Dimname dim, bool descending=false) const; + at::Tensor msort() const; + at::Tensor argsort(int64_t dim=-1, bool descending=false) const; + at::Tensor argsort(bool stable, int64_t dim=-1, bool descending=false) const; + at::Tensor argsort(at::Dimname dim, bool descending=false) const; + ::std::tuple topk(int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true) const; + ::std::tuple topk_symint(c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true) const; + at::Tensor all() const; + at::Tensor any() const; + at::Tensor renorm(const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm) const; + at::Tensor & renorm_(const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm) const; + at::Tensor unfold(int64_t dimension, int64_t size, int64_t step) const; + bool equal(const at::Tensor & other) const; + at::Tensor pow(const at::Tensor & exponent) const; + at::Tensor pow(const at::Scalar & exponent) const; + at::Tensor & pow_(const at::Scalar & exponent) const; + at::Tensor & pow_(const at::Tensor & exponent) const; + at::Tensor float_power(const at::Tensor & exponent) const; + at::Tensor float_power(const at::Scalar & exponent) const; + at::Tensor & float_power_(const at::Scalar & exponent) const; + at::Tensor & float_power_(const at::Tensor & exponent) const; + at::Tensor & normal_(double mean=0, double std=1, c10::optional generator=c10::nullopt) const; + at::Tensor alias() const; + at::Tensor isfinite() const; + at::Tensor isinf() const; + void record_stream(at::Stream s) const; + at::Tensor isposinf() const; + at::Tensor isneginf() const; + at::Tensor det() const; + ::std::tuple slogdet() const; + at::Tensor logdet() const; + at::Tensor inverse() const; + at::Tensor inner(const at::Tensor & other) const; + at::Tensor outer(const at::Tensor & vec2) const; + at::Tensor ger(const at::Tensor & vec2) const; + at::Tensor to_padded_tensor(double padding, at::OptionalIntArrayRef output_size=c10::nullopt) const; + at::Tensor to_padded_tensor_symint(double padding, at::OptionalSymIntArrayRef output_size=c10::nullopt) const; + + // Special C++ only overloads for std()-like functions (See gh-40287) + // These are needed because int -> bool conversion takes precedence over int -> IntArrayRef + // So, for example std(0) would select the std(unbiased=False) overload + + Tensor var(int dim) const { + return var(IntArrayRef{dim}); + } + + Tensor std(int dim) const { + return std(IntArrayRef{dim}); + } + + // We changed .dtype() to return a TypeMeta in #12766. Ideally, we want the + // at::kDouble and its friends to be TypeMeta's, but that hasn't happened yet. + // Before that change, we make this method to maintain BC for C++ usage like + // `x.to(y.dtype)`. + // TODO: remove following two after at::kDouble and its friends are TypeMeta's. + inline Tensor to(caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const { + return this->to(/*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy); + } + inline Tensor to(Device device, caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const { + return this->to(device, /*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy); + } + + template + decltype(auto) m(F func, Args&&... params) const { + return func(*this, std::forward(params)...); + } + + /// NOTE: This is similar to the legacy `.data()` function on `Variable`, and is intended + /// to be used from functions that need to access the `Variable`'s equivalent `Tensor` + /// (i.e. `Tensor` that shares the same storage and tensor metadata with the `Variable`). + /// + /// One notable difference with the legacy `.data()` function is that changes to the + /// returned `Tensor`'s tensor metadata (e.g. sizes / strides / storage / storage_offset) + /// will not update the original `Variable`, due to the fact that this function + /// shallow-copies the `Variable`'s underlying TensorImpl. + at::Tensor tensor_data() const { + return TensorBase::tensor_data(); + } + + /// NOTE: `var.variable_data()` in C++ has the same semantics as `tensor.data` + /// in Python, which create a new `Variable` that shares the same storage and + /// tensor metadata with the original `Variable`, but with a completely new + /// autograd history. + /// + /// NOTE: If we change the tensor metadata (e.g. sizes / strides / + /// storage / storage_offset) of a variable created from `var.variable_data()`, those + /// changes will not update the original variable `var`. In `.variable_data()`, we set + /// `allow_tensor_metadata_change_` to false to make such changes explicitly illegal, + /// in order to prevent users from changing metadata of `var.variable_data()` + /// and expecting the original variable `var` to also be updated. + at::Tensor variable_data() const { + return TensorBase::variable_data(); + } + + // Hooks + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + template + using hook_return_void_t = std::enable_if_t>::value, unsigned>; + template + using hook_return_var_t = std::enable_if_t, Tensor>::value, unsigned>; + + /// Registers a backward hook. + /// + /// The hook will be called every time a gradient with respect to the Tensor is computed. + /// The hook should have one of the following signature: + /// ``` + /// hook(Tensor grad) -> Tensor + /// ``` + /// ``` + /// hook(Tensor grad) -> void + /// ``` + /// The hook should not modify its argument, but it can optionally return a new gradient + /// which will be used in place of `grad`. + /// + /// This function returns the index of the hook in the list which can be used to remove hook. + /// + /// Example: + /// @code + /// auto v = torch::tensor({0., 0., 0.}, torch::requires_grad()); + /// auto h = v.register_hook([](torch::Tensor grad){ return grad * 2; }); // double the gradient + /// v.backward(torch::tensor({1., 2., 3.})); + /// // This prints: + /// // ``` + /// // 2 + /// // 4 + /// // 6 + /// // [ CPUFloatType{3} ] + /// // ``` + /// std::cout << v.grad() << std::endl; + /// v.remove_hook(h); // removes the hook + /// @endcode + template + hook_return_void_t register_hook(T&& hook) const; + template + hook_return_var_t register_hook(T&& hook) const; + + // Variable methods + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Tensor data() const { + return TensorBase::data(); + } + + void _backward(TensorList inputs, const c10::optional& gradient, c10::optional keep_graph, bool create_graph) const; + + const Tensor& requires_grad_(bool _requires_grad=true) const { + TensorBase::requires_grad_(_requires_grad); + return *this; + } +}; + +namespace detail { +// Helper creator for Tensor class which doesn't requires the users to pass +// in an intrusive_ptr instead it just converts the argument passed to +// requested intrusive_ptr type. +template +Tensor make_tensor(Args&&... args) { + return Tensor(c10::make_intrusive(std::forward(args)...)); +} + +} // namespace detail + +} // namespace at + + +namespace at { + +// aten::_backward(Tensor self, Tensor[] inputs, Tensor? gradient=None, bool? retain_graph=None, bool create_graph=False) -> () +inline void Tensor::__dispatch__backward(at::TensorList inputs, const c10::optional & gradient, c10::optional retain_graph, bool create_graph) const { + return at::_ops::_backward::call(const_cast(*this), inputs, gradient, retain_graph, create_graph); +} + +// aten::set_data(Tensor(a!) self, Tensor new_data) -> () +inline void Tensor::__dispatch_set_data(const at::Tensor & new_data) const { + return at::_ops::set_data::call(const_cast(*this), new_data); +} + +// aten::data(Tensor self) -> Tensor +inline at::Tensor Tensor::__dispatch_data() const { + return at::_ops::data::call(const_cast(*this)); +} + +// aten::is_leaf(Tensor self) -> bool +inline bool Tensor::__dispatch_is_leaf() const { + return at::_ops::is_leaf::call(const_cast(*this)); +} + +// aten::output_nr(Tensor self) -> int +inline int64_t Tensor::__dispatch_output_nr() const { + return at::_ops::output_nr::call(const_cast(*this)); +} + +// aten::_version(Tensor self) -> int +inline int64_t Tensor::__dispatch__version() const { + return at::_ops::_version::call(const_cast(*this)); +} + +// aten::requires_grad_(Tensor(a!) self, bool requires_grad=True) -> Tensor(a!) +inline at::Tensor & Tensor::__dispatch_requires_grad_(bool requires_grad) const { + return at::_ops::requires_grad_::call(const_cast(*this), requires_grad); +} + +// aten::retain_grad(Tensor(a!) self) -> () +inline void Tensor::__dispatch_retain_grad() const { + return at::_ops::retain_grad::call(const_cast(*this)); +} + +// aten::retains_grad(Tensor self) -> bool +inline bool Tensor::__dispatch_retains_grad() const { + return at::_ops::retains_grad::call(const_cast(*this)); +} + +// aten::_fw_primal(Tensor(a) self, int level) -> Tensor(a) +inline at::Tensor Tensor::_fw_primal(int64_t level) const { + return at::_ops::_fw_primal::call(const_cast(*this), level); +} + +// aten::rename_(Tensor(a!) self, Dimname[]? names) -> Tensor(a!) +inline at::Tensor & Tensor::rename_(c10::optional names) const { + return at::_ops::rename_::call(const_cast(*this), names); +} + +// aten::rename(Tensor(a) self, Dimname[]? names) -> Tensor(a) +inline at::Tensor Tensor::rename(c10::optional names) const { + return at::_ops::rename::call(const_cast(*this), names); +} + +// aten::align_to(Tensor(a) self, Dimname[] names) -> Tensor(a) +inline at::Tensor Tensor::align_to(at::DimnameList names) const { + return at::_ops::align_to::call(const_cast(*this), names); +} + +// aten::align_to.ellipsis_idx(Tensor(a) self, Dimname[] order, int ellipsis_idx) -> Tensor(a) +inline at::Tensor Tensor::align_to(at::DimnameList order, int64_t ellipsis_idx) const { + return at::_ops::align_to_ellipsis_idx::call(const_cast(*this), order, ellipsis_idx); +} + +// aten::align_as(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::align_as(const at::Tensor & other) const { + return at::_ops::align_as::call(const_cast(*this), other); +} + +// aten::refine_names(Tensor(a) self, Dimname[] names) -> Tensor(a) +inline at::Tensor Tensor::refine_names(at::DimnameList names) const { + return at::_ops::refine_names::call(const_cast(*this), names); +} + +// aten::abs(Tensor self) -> Tensor +inline at::Tensor Tensor::abs() const { + return at::_ops::abs::call(const_cast(*this)); +} + +// aten::abs_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::abs_() const { + return at::_ops::abs_::call(const_cast(*this)); +} + +// aten::absolute(Tensor self) -> Tensor +inline at::Tensor Tensor::absolute() const { + return at::_ops::absolute::call(const_cast(*this)); +} + +// aten::absolute_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::absolute_() const { + return at::_ops::absolute_::call(const_cast(*this)); +} + +// aten::angle(Tensor self) -> Tensor +inline at::Tensor Tensor::angle() const { + return at::_ops::angle::call(const_cast(*this)); +} + +// aten::sgn(Tensor self) -> Tensor +inline at::Tensor Tensor::sgn() const { + return at::_ops::sgn::call(const_cast(*this)); +} + +// aten::sgn_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sgn_() const { + return at::_ops::sgn_::call(const_cast(*this)); +} + +// aten::chalf(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor Tensor::chalf(c10::optional memory_format) const { + return at::_ops::chalf::call(const_cast(*this), memory_format); +} + +// aten::_conj(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::_conj() const { + return at::_ops::_conj::call(const_cast(*this)); +} + +// aten::conj(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::__dispatch_conj() const { + return at::_ops::conj::call(const_cast(*this)); +} + +// aten::_conj_physical(Tensor self) -> Tensor +inline at::Tensor Tensor::_conj_physical() const { + return at::_ops::_conj_physical::call(const_cast(*this)); +} + +// aten::conj_physical(Tensor self) -> Tensor +inline at::Tensor Tensor::conj_physical() const { + return at::_ops::conj_physical::call(const_cast(*this)); +} + +// aten::conj_physical_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::conj_physical_() const { + return at::_ops::conj_physical_::call(const_cast(*this)); +} + +// aten::resolve_conj(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::resolve_conj() const { + return at::_ops::resolve_conj::call(const_cast(*this)); +} + +// aten::resolve_neg(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::resolve_neg() const { + return at::_ops::resolve_neg::call(const_cast(*this)); +} + +// aten::_neg_view(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::_neg_view() const { + return at::_ops::_neg_view::call(const_cast(*this)); +} + +// aten::acos(Tensor self) -> Tensor +inline at::Tensor Tensor::acos() const { + return at::_ops::acos::call(const_cast(*this)); +} + +// aten::acos_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::acos_() const { + return at::_ops::acos_::call(const_cast(*this)); +} + +// aten::arccos(Tensor self) -> Tensor +inline at::Tensor Tensor::arccos() const { + return at::_ops::arccos::call(const_cast(*this)); +} + +// aten::arccos_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::arccos_() const { + return at::_ops::arccos_::call(const_cast(*this)); +} + +// aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::add(const at::Tensor & other, const at::Scalar & alpha) const { + return at::_ops::add_Tensor::call(const_cast(*this), other, alpha); +} + +// aten::add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::add_(const at::Tensor & other, const at::Scalar & alpha) const { + return at::_ops::add__Tensor::call(const_cast(*this), other, alpha); +} + +// aten::add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::add(const at::Scalar & other, const at::Scalar & alpha) const { + return at::_ops::add_Scalar::call(const_cast(*this), other, alpha); +} + +// aten::add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::add_(const at::Scalar & other, const at::Scalar & alpha) const { + return at::_ops::add__Scalar::call(const_cast(*this), other, alpha); +} + +// aten::addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::addmv(const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addmv::call(const_cast(*this), mat, vec, beta, alpha); +} + +// aten::addmv_(Tensor(a!) self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::addmv_(const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addmv_::call(const_cast(*this), mat, vec, beta, alpha); +} + +// aten::addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::addr(const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addr::call(const_cast(*this), vec1, vec2, beta, alpha); +} + +// aten::addr_(Tensor(a!) self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::addr_(const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addr_::call(const_cast(*this), vec1, vec2, beta, alpha); +} + +// aten::_is_all_true(Tensor self) -> Tensor +inline at::Tensor Tensor::_is_all_true() const { + return at::_ops::_is_all_true::call(const_cast(*this)); +} + +// aten::_is_any_true(Tensor self) -> Tensor +inline at::Tensor Tensor::_is_any_true() const { + return at::_ops::_is_any_true::call(const_cast(*this)); +} + +// aten::all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::all(int64_t dim, bool keepdim) const { + return at::_ops::all_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::all(at::OptionalIntArrayRef dim, bool keepdim) const { + return at::_ops::all_dims::call(const_cast(*this), dim, keepdim); +} + +// aten::all.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::all(at::Dimname dim, bool keepdim) const { + return at::_ops::all_dimname::call(const_cast(*this), dim, keepdim); +} + +// aten::allclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> bool +inline bool Tensor::allclose(const at::Tensor & other, double rtol, double atol, bool equal_nan) const { + return at::_ops::allclose::call(const_cast(*this), other, rtol, atol, equal_nan); +} + +// aten::any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::any(int64_t dim, bool keepdim) const { + return at::_ops::any_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::any.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::any(at::OptionalIntArrayRef dim, bool keepdim) const { + return at::_ops::any_dims::call(const_cast(*this), dim, keepdim); +} + +// aten::any.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::any(at::Dimname dim, bool keepdim) const { + return at::_ops::any_dimname::call(const_cast(*this), dim, keepdim); +} + +// aten::argmax(Tensor self, int? dim=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::argmax(c10::optional dim, bool keepdim) const { + return at::_ops::argmax::call(const_cast(*this), dim, keepdim); +} + +// aten::argmin(Tensor self, int? dim=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::argmin(c10::optional dim, bool keepdim) const { + return at::_ops::argmin::call(const_cast(*this), dim, keepdim); +} + +// aten::acosh(Tensor self) -> Tensor +inline at::Tensor Tensor::acosh() const { + return at::_ops::acosh::call(const_cast(*this)); +} + +// aten::acosh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::acosh_() const { + return at::_ops::acosh_::call(const_cast(*this)); +} + +// aten::arccosh(Tensor self) -> Tensor +inline at::Tensor Tensor::arccosh() const { + return at::_ops::arccosh::call(const_cast(*this)); +} + +// aten::arccosh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::arccosh_() const { + return at::_ops::arccosh_::call(const_cast(*this)); +} + +// aten::asinh(Tensor self) -> Tensor +inline at::Tensor Tensor::asinh() const { + return at::_ops::asinh::call(const_cast(*this)); +} + +// aten::asinh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::asinh_() const { + return at::_ops::asinh_::call(const_cast(*this)); +} + +// aten::arcsinh(Tensor self) -> Tensor +inline at::Tensor Tensor::arcsinh() const { + return at::_ops::arcsinh::call(const_cast(*this)); +} + +// aten::arcsinh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::arcsinh_() const { + return at::_ops::arcsinh_::call(const_cast(*this)); +} + +// aten::atanh(Tensor self) -> Tensor +inline at::Tensor Tensor::atanh() const { + return at::_ops::atanh::call(const_cast(*this)); +} + +// aten::atanh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::atanh_() const { + return at::_ops::atanh_::call(const_cast(*this)); +} + +// aten::arctanh(Tensor self) -> Tensor +inline at::Tensor Tensor::arctanh() const { + return at::_ops::arctanh::call(const_cast(*this)); +} + +// aten::arctanh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::arctanh_() const { + return at::_ops::arctanh_::call(const_cast(*this)); +} + +// aten::as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a) +inline at::Tensor Tensor::as_strided(at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset) const { + return at::_ops::as_strided::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt); +} + +// aten::as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a) +inline at::Tensor Tensor::as_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset) const { + return at::_ops::as_strided::call(const_cast(*this), size, stride, storage_offset); +} + +// aten::as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!) +inline const at::Tensor & Tensor::as_strided_(at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset) const { + return at::_ops::as_strided_::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt); +} + +// aten::as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!) +inline const at::Tensor & Tensor::as_strided__symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset) const { + return at::_ops::as_strided_::call(const_cast(*this), size, stride, storage_offset); +} + +// aten::asin(Tensor self) -> Tensor +inline at::Tensor Tensor::asin() const { + return at::_ops::asin::call(const_cast(*this)); +} + +// aten::asin_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::asin_() const { + return at::_ops::asin_::call(const_cast(*this)); +} + +// aten::arcsin(Tensor self) -> Tensor +inline at::Tensor Tensor::arcsin() const { + return at::_ops::arcsin::call(const_cast(*this)); +} + +// aten::arcsin_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::arcsin_() const { + return at::_ops::arcsin_::call(const_cast(*this)); +} + +// aten::atan(Tensor self) -> Tensor +inline at::Tensor Tensor::atan() const { + return at::_ops::atan::call(const_cast(*this)); +} + +// aten::atan_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::atan_() const { + return at::_ops::atan_::call(const_cast(*this)); +} + +// aten::arctan(Tensor self) -> Tensor +inline at::Tensor Tensor::arctan() const { + return at::_ops::arctan::call(const_cast(*this)); +} + +// aten::arctan_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::arctan_() const { + return at::_ops::arctan_::call(const_cast(*this)); +} + +// aten::baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::baddbmm(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::baddbmm::call(const_cast(*this), batch1, batch2, beta, alpha); +} + +// aten::baddbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::baddbmm_(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::baddbmm_::call(const_cast(*this), batch1, batch2, beta, alpha); +} + +// aten::bernoulli(Tensor self, *, Generator? generator=None) -> Tensor +inline at::Tensor Tensor::bernoulli(c10::optional generator) const { + return at::_ops::bernoulli::call(const_cast(*this), generator); +} + +// aten::bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::bernoulli_(const at::Tensor & p, c10::optional generator) const { + return at::_ops::bernoulli__Tensor::call(const_cast(*this), p, generator); +} + +// aten::bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::bernoulli_(double p, c10::optional generator) const { + return at::_ops::bernoulli__float::call(const_cast(*this), p, generator); +} + +// aten::bernoulli.p(Tensor self, float p, *, Generator? generator=None) -> Tensor +inline at::Tensor Tensor::bernoulli(double p, c10::optional generator) const { + return at::_ops::bernoulli_p::call(const_cast(*this), p, generator); +} + +// aten::bincount(Tensor self, Tensor? weights=None, int minlength=0) -> Tensor +inline at::Tensor Tensor::bincount(const c10::optional & weights, int64_t minlength) const { + return at::_ops::bincount::call(const_cast(*this), weights, minlength); +} + +// aten::bitwise_not(Tensor self) -> Tensor +inline at::Tensor Tensor::bitwise_not() const { + return at::_ops::bitwise_not::call(const_cast(*this)); +} + +// aten::bitwise_not_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_not_() const { + return at::_ops::bitwise_not_::call(const_cast(*this)); +} + +// aten::copysign.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::copysign(const at::Tensor & other) const { + return at::_ops::copysign_Tensor::call(const_cast(*this), other); +} + +// aten::copysign_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::copysign_(const at::Tensor & other) const { + return at::_ops::copysign__Tensor::call(const_cast(*this), other); +} + +// aten::copysign.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::copysign(const at::Scalar & other) const { + return at::_ops::copysign_Scalar::call(const_cast(*this), other); +} + +// aten::copysign_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::copysign_(const at::Scalar & other) const { + return at::_ops::copysign__Scalar::call(const_cast(*this), other); +} + +// aten::_lazy_clone(Tensor self) -> Tensor +inline at::Tensor Tensor::_lazy_clone() const { + return at::_ops::_lazy_clone::call(const_cast(*this)); +} + +// aten::logical_not(Tensor self) -> Tensor +inline at::Tensor Tensor::logical_not() const { + return at::_ops::logical_not::call(const_cast(*this)); +} + +// aten::logical_not_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::logical_not_() const { + return at::_ops::logical_not_::call(const_cast(*this)); +} + +// aten::logical_xor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::logical_xor(const at::Tensor & other) const { + return at::_ops::logical_xor::call(const_cast(*this), other); +} + +// aten::logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::logical_xor_(const at::Tensor & other) const { + return at::_ops::logical_xor_::call(const_cast(*this), other); +} + +// aten::logical_and(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::logical_and(const at::Tensor & other) const { + return at::_ops::logical_and::call(const_cast(*this), other); +} + +// aten::logical_and_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::logical_and_(const at::Tensor & other) const { + return at::_ops::logical_and_::call(const_cast(*this), other); +} + +// aten::logical_or(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::logical_or(const at::Tensor & other) const { + return at::_ops::logical_or::call(const_cast(*this), other); +} + +// aten::logical_or_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::logical_or_(const at::Tensor & other) const { + return at::_ops::logical_or_::call(const_cast(*this), other); +} + +// aten::bmm(Tensor self, Tensor mat2) -> Tensor +inline at::Tensor Tensor::bmm(const at::Tensor & mat2) const { + return at::_ops::bmm::call(const_cast(*this), mat2); +} + +// aten::broadcast_to(Tensor(a) self, SymInt[] size) -> Tensor(a) +inline at::Tensor Tensor::broadcast_to(at::IntArrayRef size) const { + return at::_ops::broadcast_to::call(const_cast(*this), c10::fromIntArrayRefSlow(size)); +} + +// aten::broadcast_to(Tensor(a) self, SymInt[] size) -> Tensor(a) +inline at::Tensor Tensor::broadcast_to_symint(c10::SymIntArrayRef size) const { + return at::_ops::broadcast_to::call(const_cast(*this), size); +} + +// aten::ceil(Tensor self) -> Tensor +inline at::Tensor Tensor::ceil() const { + return at::_ops::ceil::call(const_cast(*this)); +} + +// aten::ceil_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::ceil_() const { + return at::_ops::ceil_::call(const_cast(*this)); +} + +// aten::unsafe_chunk(Tensor self, int chunks, int dim=0) -> Tensor[] +inline ::std::vector Tensor::unsafe_chunk(int64_t chunks, int64_t dim) const { + return at::_ops::unsafe_chunk::call(const_cast(*this), chunks, dim); +} + +// aten::chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::chunk(int64_t chunks, int64_t dim) const { + return at::_ops::chunk::call(const_cast(*this), chunks, dim); +} + +// aten::tensor_split.sections(Tensor(a -> *) self, SymInt sections, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::tensor_split(int64_t sections, int64_t dim) const { + return at::_ops::tensor_split_sections::call(const_cast(*this), sections, dim); +} + +// aten::tensor_split.sections(Tensor(a -> *) self, SymInt sections, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::tensor_split_symint(c10::SymInt sections, int64_t dim) const { + return at::_ops::tensor_split_sections::call(const_cast(*this), sections, dim); +} + +// aten::tensor_split.indices(Tensor(a -> *) self, SymInt[] indices, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::tensor_split(at::IntArrayRef indices, int64_t dim) const { + return at::_ops::tensor_split_indices::call(const_cast(*this), c10::fromIntArrayRefSlow(indices), dim); +} + +// aten::tensor_split.indices(Tensor(a -> *) self, SymInt[] indices, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::tensor_split_symint(c10::SymIntArrayRef indices, int64_t dim) const { + return at::_ops::tensor_split_indices::call(const_cast(*this), indices, dim); +} + +// aten::tensor_split.tensor_indices_or_sections(Tensor(a -> *) self, Tensor tensor_indices_or_sections, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::tensor_split(const at::Tensor & tensor_indices_or_sections, int64_t dim) const { + return at::_ops::tensor_split_tensor_indices_or_sections::call(const_cast(*this), tensor_indices_or_sections, dim); +} + +// aten::clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor +inline at::Tensor Tensor::clamp(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clamp::call(const_cast(*this), min, max); +} + +// aten::clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor +inline at::Tensor Tensor::clamp(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clamp_Tensor::call(const_cast(*this), min, max); +} + +// aten::clamp_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!) +inline at::Tensor & Tensor::clamp_(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clamp_::call(const_cast(*this), min, max); +} + +// aten::clamp_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!) +inline at::Tensor & Tensor::clamp_(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clamp__Tensor::call(const_cast(*this), min, max); +} + +// aten::clamp_max(Tensor self, Scalar max) -> Tensor +inline at::Tensor Tensor::clamp_max(const at::Scalar & max) const { + return at::_ops::clamp_max::call(const_cast(*this), max); +} + +// aten::clamp_max.Tensor(Tensor self, Tensor max) -> Tensor +inline at::Tensor Tensor::clamp_max(const at::Tensor & max) const { + return at::_ops::clamp_max_Tensor::call(const_cast(*this), max); +} + +// aten::clamp_max_(Tensor(a!) self, Scalar max) -> Tensor(a!) +inline at::Tensor & Tensor::clamp_max_(const at::Scalar & max) const { + return at::_ops::clamp_max_::call(const_cast(*this), max); +} + +// aten::clamp_max_.Tensor(Tensor(a!) self, Tensor max) -> Tensor(a!) +inline at::Tensor & Tensor::clamp_max_(const at::Tensor & max) const { + return at::_ops::clamp_max__Tensor::call(const_cast(*this), max); +} + +// aten::clamp_min(Tensor self, Scalar min) -> Tensor +inline at::Tensor Tensor::clamp_min(const at::Scalar & min) const { + return at::_ops::clamp_min::call(const_cast(*this), min); +} + +// aten::clamp_min.Tensor(Tensor self, Tensor min) -> Tensor +inline at::Tensor Tensor::clamp_min(const at::Tensor & min) const { + return at::_ops::clamp_min_Tensor::call(const_cast(*this), min); +} + +// aten::clamp_min_(Tensor(a!) self, Scalar min) -> Tensor(a!) +inline at::Tensor & Tensor::clamp_min_(const at::Scalar & min) const { + return at::_ops::clamp_min_::call(const_cast(*this), min); +} + +// aten::clamp_min_.Tensor(Tensor(a!) self, Tensor min) -> Tensor(a!) +inline at::Tensor & Tensor::clamp_min_(const at::Tensor & min) const { + return at::_ops::clamp_min__Tensor::call(const_cast(*this), min); +} + +// aten::clip(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor +inline at::Tensor Tensor::clip(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clip::call(const_cast(*this), min, max); +} + +// aten::clip.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor +inline at::Tensor Tensor::clip(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clip_Tensor::call(const_cast(*this), min, max); +} + +// aten::clip_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!) +inline at::Tensor & Tensor::clip_(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clip_::call(const_cast(*this), min, max); +} + +// aten::clip_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!) +inline at::Tensor & Tensor::clip_(const c10::optional & min, const c10::optional & max) const { + return at::_ops::clip__Tensor::call(const_cast(*this), min, max); +} + +// aten::contiguous(Tensor(a) self, *, MemoryFormat memory_format=contiguous_format) -> Tensor(a) +inline at::Tensor Tensor::__dispatch_contiguous(at::MemoryFormat memory_format) const { + return at::_ops::contiguous::call(const_cast(*this), memory_format); +} + +// aten::copy_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!) +inline at::Tensor & Tensor::copy_(const at::Tensor & src, bool non_blocking) const { + return at::_ops::copy_::call(const_cast(*this), src, non_blocking); +} + +// aten::cos(Tensor self) -> Tensor +inline at::Tensor Tensor::cos() const { + return at::_ops::cos::call(const_cast(*this)); +} + +// aten::cos_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::cos_() const { + return at::_ops::cos_::call(const_cast(*this)); +} + +// aten::cosh(Tensor self) -> Tensor +inline at::Tensor Tensor::cosh() const { + return at::_ops::cosh::call(const_cast(*this)); +} + +// aten::cosh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::cosh_() const { + return at::_ops::cosh_::call(const_cast(*this)); +} + +// aten::count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor +inline at::Tensor Tensor::count_nonzero(at::IntArrayRef dim) const { + return at::_ops::count_nonzero_dim_IntList::call(const_cast(*this), dim); +} + +// aten::count_nonzero(Tensor self, int? dim=None) -> Tensor +inline at::Tensor Tensor::count_nonzero(c10::optional dim) const { + return at::_ops::count_nonzero::call(const_cast(*this), dim); +} + +// aten::cov(Tensor self, *, int correction=1, Tensor? fweights=None, Tensor? aweights=None) -> Tensor +inline at::Tensor Tensor::cov(int64_t correction, const c10::optional & fweights, const c10::optional & aweights) const { + return at::_ops::cov::call(const_cast(*this), correction, fweights, aweights); +} + +// aten::corrcoef(Tensor self) -> Tensor +inline at::Tensor Tensor::corrcoef() const { + return at::_ops::corrcoef::call(const_cast(*this)); +} + +// aten::cummax(Tensor self, int dim) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::cummax(int64_t dim) const { + return at::_ops::cummax::call(const_cast(*this), dim); +} + +// aten::cummax.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::cummax(at::Dimname dim) const { + return at::_ops::cummax_dimname::call(const_cast(*this), dim); +} + +// aten::cummin(Tensor self, int dim) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::cummin(int64_t dim) const { + return at::_ops::cummin::call(const_cast(*this), dim); +} + +// aten::cummin.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::cummin(at::Dimname dim) const { + return at::_ops::cummin_dimname::call(const_cast(*this), dim); +} + +// aten::cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::cumprod(int64_t dim, c10::optional dtype) const { + return at::_ops::cumprod::call(const_cast(*this), dim, dtype); +} + +// aten::cumprod_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!) +inline at::Tensor & Tensor::cumprod_(int64_t dim, c10::optional dtype) const { + return at::_ops::cumprod_::call(const_cast(*this), dim, dtype); +} + +// aten::cumprod.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::cumprod(at::Dimname dim, c10::optional dtype) const { + return at::_ops::cumprod_dimname::call(const_cast(*this), dim, dtype); +} + +// aten::cumprod_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!) +inline at::Tensor & Tensor::cumprod_(at::Dimname dim, c10::optional dtype) const { + return at::_ops::cumprod__dimname::call(const_cast(*this), dim, dtype); +} + +// aten::cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::cumsum(int64_t dim, c10::optional dtype) const { + return at::_ops::cumsum::call(const_cast(*this), dim, dtype); +} + +// aten::cumsum_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!) +inline at::Tensor & Tensor::cumsum_(int64_t dim, c10::optional dtype) const { + return at::_ops::cumsum_::call(const_cast(*this), dim, dtype); +} + +// aten::cumsum.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::cumsum(at::Dimname dim, c10::optional dtype) const { + return at::_ops::cumsum_dimname::call(const_cast(*this), dim, dtype); +} + +// aten::cumsum_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!) +inline at::Tensor & Tensor::cumsum_(at::Dimname dim, c10::optional dtype) const { + return at::_ops::cumsum__dimname::call(const_cast(*this), dim, dtype); +} + +// aten::diag_embed(Tensor self, int offset=0, int dim1=-2, int dim2=-1) -> Tensor +inline at::Tensor Tensor::diag_embed(int64_t offset, int64_t dim1, int64_t dim2) const { + return at::_ops::diag_embed::call(const_cast(*this), offset, dim1, dim2); +} + +// aten::diagflat(Tensor self, int offset=0) -> Tensor +inline at::Tensor Tensor::diagflat(int64_t offset) const { + return at::_ops::diagflat::call(const_cast(*this), offset); +} + +// aten::diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a) +inline at::Tensor Tensor::diagonal(int64_t offset, int64_t dim1, int64_t dim2) const { + return at::_ops::diagonal::call(const_cast(*this), offset, dim1, dim2); +} + +// aten::diagonal.Dimname(Tensor(a) self, *, Dimname outdim, Dimname dim1, Dimname dim2, int offset=0) -> Tensor(a) +inline at::Tensor Tensor::diagonal(at::Dimname outdim, at::Dimname dim1, at::Dimname dim2, int64_t offset) const { + return at::_ops::diagonal_Dimname::call(const_cast(*this), outdim, dim1, dim2, offset); +} + +// aten::fill_diagonal_(Tensor(a!) self, Scalar fill_value, bool wrap=False) -> Tensor(a!) +inline at::Tensor & Tensor::fill_diagonal_(const at::Scalar & fill_value, bool wrap) const { + return at::_ops::fill_diagonal_::call(const_cast(*this), fill_value, wrap); +} + +// aten::diff(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None) -> Tensor +inline at::Tensor Tensor::diff(int64_t n, int64_t dim, const c10::optional & prepend, const c10::optional & append) const { + return at::_ops::diff::call(const_cast(*this), n, dim, prepend, append); +} + +// aten::div.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::div(const at::Tensor & other) const { + return at::_ops::div_Tensor::call(const_cast(*this), other); +} + +// aten::div_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::div_(const at::Tensor & other) const { + return at::_ops::div__Tensor::call(const_cast(*this), other); +} + +// aten::div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor +inline at::Tensor Tensor::div(const at::Tensor & other, c10::optional rounding_mode) const { + return at::_ops::div_Tensor_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!) +inline at::Tensor & Tensor::div_(const at::Tensor & other, c10::optional rounding_mode) const { + return at::_ops::div__Tensor_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::div.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::div(const at::Scalar & other) const { + return at::_ops::div_Scalar::call(const_cast(*this), other); +} + +// aten::div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::div_(const at::Scalar & other) const { + return at::_ops::div__Scalar::call(const_cast(*this), other); +} + +// aten::div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor +inline at::Tensor Tensor::div(const at::Scalar & other, c10::optional rounding_mode) const { + return at::_ops::div_Scalar_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!) +inline at::Tensor & Tensor::div_(const at::Scalar & other, c10::optional rounding_mode) const { + return at::_ops::div__Scalar_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::divide.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::divide(const at::Tensor & other) const { + return at::_ops::divide_Tensor::call(const_cast(*this), other); +} + +// aten::divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::divide_(const at::Tensor & other) const { + return at::_ops::divide__Tensor::call(const_cast(*this), other); +} + +// aten::divide.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::divide(const at::Scalar & other) const { + return at::_ops::divide_Scalar::call(const_cast(*this), other); +} + +// aten::divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::divide_(const at::Scalar & other) const { + return at::_ops::divide__Scalar::call(const_cast(*this), other); +} + +// aten::divide.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor +inline at::Tensor Tensor::divide(const at::Tensor & other, c10::optional rounding_mode) const { + return at::_ops::divide_Tensor_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::divide_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!) +inline at::Tensor & Tensor::divide_(const at::Tensor & other, c10::optional rounding_mode) const { + return at::_ops::divide__Tensor_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::divide.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor +inline at::Tensor Tensor::divide(const at::Scalar & other, c10::optional rounding_mode) const { + return at::_ops::divide_Scalar_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::divide_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!) +inline at::Tensor & Tensor::divide_(const at::Scalar & other, c10::optional rounding_mode) const { + return at::_ops::divide__Scalar_mode::call(const_cast(*this), other, rounding_mode); +} + +// aten::true_divide.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::true_divide(const at::Tensor & other) const { + return at::_ops::true_divide_Tensor::call(const_cast(*this), other); +} + +// aten::true_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::true_divide_(const at::Tensor & other) const { + return at::_ops::true_divide__Tensor::call(const_cast(*this), other); +} + +// aten::true_divide.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::true_divide(const at::Scalar & other) const { + return at::_ops::true_divide_Scalar::call(const_cast(*this), other); +} + +// aten::true_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::true_divide_(const at::Scalar & other) const { + return at::_ops::true_divide__Scalar::call(const_cast(*this), other); +} + +// aten::dot(Tensor self, Tensor tensor) -> Tensor +inline at::Tensor Tensor::dot(const at::Tensor & tensor) const { + return at::_ops::dot::call(const_cast(*this), tensor); +} + +// aten::vdot(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::vdot(const at::Tensor & other) const { + return at::_ops::vdot::call(const_cast(*this), other); +} + +// aten::new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty(at::IntArrayRef size, at::TensorOptions options) const { + return at::_ops::new_empty::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_empty::call(const_cast(*this), c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); +} + +// aten::new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty_symint(c10::SymIntArrayRef size, at::TensorOptions options) const { + return at::_ops::new_empty::call(const_cast(*this), size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_empty::call(const_cast(*this), size, dtype, layout, device, pin_memory); +} + +// aten::new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty_strided(at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options) const { + return at::_ops::new_empty_strided::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty_strided(at::IntArrayRef size, at::IntArrayRef stride, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_empty_strided::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), dtype, layout, device, pin_memory); +} + +// aten::new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options) const { + return at::_ops::new_empty_strided::call(const_cast(*this), size, stride, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_empty_strided_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_empty_strided::call(const_cast(*this), size, stride, dtype, layout, device, pin_memory); +} + +// aten::new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_full(at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options) const { + return at::_ops::new_full::call(const_cast(*this), c10::fromIntArrayRefSlow(size), fill_value, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_full(at::IntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_full::call(const_cast(*this), c10::fromIntArrayRefSlow(size), fill_value, dtype, layout, device, pin_memory); +} + +// aten::new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options) const { + return at::_ops::new_full::call(const_cast(*this), size, fill_value, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_full::call(const_cast(*this), size, fill_value, dtype, layout, device, pin_memory); +} + +// aten::new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_zeros(at::IntArrayRef size, at::TensorOptions options) const { + return at::_ops::new_zeros::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_zeros(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_zeros::call(const_cast(*this), c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); +} + +// aten::new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_zeros_symint(c10::SymIntArrayRef size, at::TensorOptions options) const { + return at::_ops::new_zeros::call(const_cast(*this), size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_zeros_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_zeros::call(const_cast(*this), size, dtype, layout, device, pin_memory); +} + +// aten::new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_ones(at::IntArrayRef size, at::TensorOptions options) const { + return at::_ops::new_ones::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_ones(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_ones::call(const_cast(*this), c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); +} + +// aten::new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_ones_symint(c10::SymIntArrayRef size, at::TensorOptions options) const { + return at::_ops::new_ones::call(const_cast(*this), size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} + +// aten::new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor Tensor::new_ones_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) const { + return at::_ops::new_ones::call(const_cast(*this), size, dtype, layout, device, pin_memory); +} + +// aten::resize_(Tensor(a!) self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!) +inline const at::Tensor & Tensor::resize_(at::IntArrayRef size, c10::optional memory_format) const { + return at::_ops::resize_::call(const_cast(*this), c10::fromIntArrayRefSlow(size), memory_format); +} + +// aten::resize_(Tensor(a!) self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!) +inline const at::Tensor & Tensor::resize__symint(c10::SymIntArrayRef size, c10::optional memory_format) const { + return at::_ops::resize_::call(const_cast(*this), size, memory_format); +} + +// aten::erf(Tensor self) -> Tensor +inline at::Tensor Tensor::erf() const { + return at::_ops::erf::call(const_cast(*this)); +} + +// aten::erf_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::erf_() const { + return at::_ops::erf_::call(const_cast(*this)); +} + +// aten::erfc(Tensor self) -> Tensor +inline at::Tensor Tensor::erfc() const { + return at::_ops::erfc::call(const_cast(*this)); +} + +// aten::erfc_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::erfc_() const { + return at::_ops::erfc_::call(const_cast(*this)); +} + +// aten::exp(Tensor self) -> Tensor +inline at::Tensor Tensor::exp() const { + return at::_ops::exp::call(const_cast(*this)); +} + +// aten::exp_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::exp_() const { + return at::_ops::exp_::call(const_cast(*this)); +} + +// aten::exp2(Tensor self) -> Tensor +inline at::Tensor Tensor::exp2() const { + return at::_ops::exp2::call(const_cast(*this)); +} + +// aten::exp2_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::exp2_() const { + return at::_ops::exp2_::call(const_cast(*this)); +} + +// aten::expm1(Tensor self) -> Tensor +inline at::Tensor Tensor::expm1() const { + return at::_ops::expm1::call(const_cast(*this)); +} + +// aten::expm1_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::expm1_() const { + return at::_ops::expm1_::call(const_cast(*this)); +} + +// aten::expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a) +inline at::Tensor Tensor::expand(at::IntArrayRef size, bool implicit) const { + return at::_ops::expand::call(const_cast(*this), c10::fromIntArrayRefSlow(size), implicit); +} + +// aten::expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a) +inline at::Tensor Tensor::expand_symint(c10::SymIntArrayRef size, bool implicit) const { + return at::_ops::expand::call(const_cast(*this), size, implicit); +} + +// aten::expand_as(Tensor(a) self, Tensor other) -> Tensor(a) +inline at::Tensor Tensor::expand_as(const at::Tensor & other) const { + return at::_ops::expand_as::call(const_cast(*this), other); +} + +// aten::flatten.using_ints(Tensor(a) self, int start_dim=0, int end_dim=-1) -> Tensor(a) +inline at::Tensor Tensor::flatten(int64_t start_dim, int64_t end_dim) const { + return at::_ops::flatten_using_ints::call(const_cast(*this), start_dim, end_dim); +} + +// aten::flatten.named_out_dim(Tensor(a) self, int start_dim, int end_dim, Dimname out_dim) -> Tensor(a) +inline at::Tensor Tensor::flatten(int64_t start_dim, int64_t end_dim, at::Dimname out_dim) const { + return at::_ops::flatten_named_out_dim::call(const_cast(*this), start_dim, end_dim, out_dim); +} + +// aten::flatten.using_names(Tensor(a) self, Dimname start_dim, Dimname end_dim, Dimname out_dim) -> Tensor(a) +inline at::Tensor Tensor::flatten(at::Dimname start_dim, at::Dimname end_dim, at::Dimname out_dim) const { + return at::_ops::flatten_using_names::call(const_cast(*this), start_dim, end_dim, out_dim); +} + +// aten::flatten.DimnameList(Tensor(a) self, Dimname[] dims, Dimname out_dim) -> Tensor(a) +inline at::Tensor Tensor::flatten(at::DimnameList dims, at::Dimname out_dim) const { + return at::_ops::flatten_DimnameList::call(const_cast(*this), dims, out_dim); +} + +// aten::unflatten.int(Tensor(a) self, int dim, SymInt[] sizes) -> Tensor(a) +inline at::Tensor Tensor::unflatten(int64_t dim, at::IntArrayRef sizes) const { + return at::_ops::unflatten_int::call(const_cast(*this), dim, c10::fromIntArrayRefSlow(sizes)); +} + +// aten::unflatten.int(Tensor(a) self, int dim, SymInt[] sizes) -> Tensor(a) +inline at::Tensor Tensor::unflatten_symint(int64_t dim, c10::SymIntArrayRef sizes) const { + return at::_ops::unflatten_int::call(const_cast(*this), dim, sizes); +} + +// aten::unflatten.Dimname(Tensor(a) self, Dimname dim, SymInt[] sizes, Dimname[] names) -> Tensor(a) +inline at::Tensor Tensor::unflatten(at::Dimname dim, at::IntArrayRef sizes, at::DimnameList names) const { + return at::_ops::unflatten_Dimname::call(const_cast(*this), dim, c10::fromIntArrayRefSlow(sizes), names); +} + +// aten::unflatten.Dimname(Tensor(a) self, Dimname dim, SymInt[] sizes, Dimname[] names) -> Tensor(a) +inline at::Tensor Tensor::unflatten_symint(at::Dimname dim, c10::SymIntArrayRef sizes, at::DimnameList names) const { + return at::_ops::unflatten_Dimname::call(const_cast(*this), dim, sizes, names); +} + +// aten::fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!) +inline at::Tensor & Tensor::fill_(const at::Scalar & value) const { + return at::_ops::fill__Scalar::call(const_cast(*this), value); +} + +// aten::fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!) +inline at::Tensor & Tensor::fill_(const at::Tensor & value) const { + return at::_ops::fill__Tensor::call(const_cast(*this), value); +} + +// aten::floor(Tensor self) -> Tensor +inline at::Tensor Tensor::floor() const { + return at::_ops::floor::call(const_cast(*this)); +} + +// aten::floor_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::floor_() const { + return at::_ops::floor_::call(const_cast(*this)); +} + +// aten::floor_divide(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::floor_divide(const at::Tensor & other) const { + return at::_ops::floor_divide::call(const_cast(*this), other); +} + +// aten::floor_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::floor_divide_(const at::Tensor & other) const { + return at::_ops::floor_divide__Tensor::call(const_cast(*this), other); +} + +// aten::floor_divide.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::floor_divide(const at::Scalar & other) const { + return at::_ops::floor_divide_Scalar::call(const_cast(*this), other); +} + +// aten::floor_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::floor_divide_(const at::Scalar & other) const { + return at::_ops::floor_divide__Scalar::call(const_cast(*this), other); +} + +// aten::frac(Tensor self) -> Tensor +inline at::Tensor Tensor::frac() const { + return at::_ops::frac::call(const_cast(*this)); +} + +// aten::frac_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::frac_() const { + return at::_ops::frac_::call(const_cast(*this)); +} + +// aten::gcd(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::gcd(const at::Tensor & other) const { + return at::_ops::gcd::call(const_cast(*this), other); +} + +// aten::gcd_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::gcd_(const at::Tensor & other) const { + return at::_ops::gcd_::call(const_cast(*this), other); +} + +// aten::lcm(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::lcm(const at::Tensor & other) const { + return at::_ops::lcm::call(const_cast(*this), other); +} + +// aten::lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::lcm_(const at::Tensor & other) const { + return at::_ops::lcm_::call(const_cast(*this), other); +} + +// aten::index.Tensor(Tensor self, Tensor?[] indices) -> Tensor +inline at::Tensor Tensor::index(const c10::List> & indices) const { + return at::_ops::index_Tensor::call(const_cast(*this), indices); +} + +// aten::index_copy_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!) +inline at::Tensor & Tensor::index_copy_(int64_t dim, const at::Tensor & index, const at::Tensor & source) const { + return at::_ops::index_copy_::call(const_cast(*this), dim, index, source); +} + +// aten::index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor +inline at::Tensor Tensor::index_copy(int64_t dim, const at::Tensor & index, const at::Tensor & source) const { + return at::_ops::index_copy::call(const_cast(*this), dim, index, source); +} + +// aten::index_copy_.dimname(Tensor(a!) self, Dimname dim, Tensor index, Tensor source) -> Tensor(a!) +inline at::Tensor & Tensor::index_copy_(at::Dimname dim, const at::Tensor & index, const at::Tensor & source) const { + return at::_ops::index_copy__dimname::call(const_cast(*this), dim, index, source); +} + +// aten::index_copy.dimname(Tensor self, Dimname dim, Tensor index, Tensor source) -> Tensor +inline at::Tensor Tensor::index_copy(at::Dimname dim, const at::Tensor & index, const at::Tensor & source) const { + return at::_ops::index_copy_dimname::call(const_cast(*this), dim, index, source); +} + +// aten::index_put_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor(a!) +inline at::Tensor & Tensor::index_put_(const c10::List> & indices, const at::Tensor & values, bool accumulate) const { + return at::_ops::index_put_::call(const_cast(*this), indices, values, accumulate); +} + +// aten::index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor +inline at::Tensor Tensor::index_put(const c10::List> & indices, const at::Tensor & values, bool accumulate) const { + return at::_ops::index_put::call(const_cast(*this), indices, values, accumulate); +} + +// aten::isclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> Tensor +inline at::Tensor Tensor::isclose(const at::Tensor & other, double rtol, double atol, bool equal_nan) const { + return at::_ops::isclose::call(const_cast(*this), other, rtol, atol, equal_nan); +} + +// aten::isnan(Tensor self) -> Tensor +inline at::Tensor Tensor::isnan() const { + return at::_ops::isnan::call(const_cast(*this)); +} + +// aten::is_distributed(Tensor self) -> bool +inline bool Tensor::is_distributed() const { + return at::_ops::is_distributed::call(const_cast(*this)); +} + +// aten::is_floating_point(Tensor self) -> bool +inline bool Tensor::__dispatch_is_floating_point() const { + return at::_ops::is_floating_point::call(const_cast(*this)); +} + +// aten::is_complex(Tensor self) -> bool +inline bool Tensor::__dispatch_is_complex() const { + return at::_ops::is_complex::call(const_cast(*this)); +} + +// aten::is_conj(Tensor self) -> bool +inline bool Tensor::__dispatch_is_conj() const { + return at::_ops::is_conj::call(const_cast(*this)); +} + +// aten::_is_zerotensor(Tensor self) -> bool +inline bool Tensor::__dispatch__is_zerotensor() const { + return at::_ops::_is_zerotensor::call(const_cast(*this)); +} + +// aten::is_neg(Tensor self) -> bool +inline bool Tensor::__dispatch_is_neg() const { + return at::_ops::is_neg::call(const_cast(*this)); +} + +// aten::isreal(Tensor self) -> Tensor +inline at::Tensor Tensor::isreal() const { + return at::_ops::isreal::call(const_cast(*this)); +} + +// aten::is_nonzero(Tensor self) -> bool +inline bool Tensor::is_nonzero() const { + return at::_ops::is_nonzero::call(const_cast(*this)); +} + +// aten::is_same_size(Tensor self, Tensor other) -> bool +inline bool Tensor::is_same_size(const at::Tensor & other) const { + return at::_ops::is_same_size::call(const_cast(*this), other); +} + +// aten::is_signed(Tensor self) -> bool +inline bool Tensor::__dispatch_is_signed() const { + return at::_ops::is_signed::call(const_cast(*this)); +} + +// aten::is_inference(Tensor self) -> bool +inline bool Tensor::__dispatch_is_inference() const { + return at::_ops::is_inference::call(const_cast(*this)); +} + +// aten::kron(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::kron(const at::Tensor & other) const { + return at::_ops::kron::call(const_cast(*this), other); +} + +// aten::kthvalue(Tensor self, int k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::kthvalue(int64_t k, int64_t dim, bool keepdim) const { + return at::_ops::kthvalue::call(const_cast(*this), k, dim, keepdim); +} + +// aten::kthvalue.dimname(Tensor self, int k, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::kthvalue(int64_t k, at::Dimname dim, bool keepdim) const { + return at::_ops::kthvalue_dimname::call(const_cast(*this), k, dim, keepdim); +} + +// aten::nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor +inline at::Tensor Tensor::nan_to_num(c10::optional nan, c10::optional posinf, c10::optional neginf) const { + return at::_ops::nan_to_num::call(const_cast(*this), nan, posinf, neginf); +} + +// aten::nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!) +inline at::Tensor & Tensor::nan_to_num_(c10::optional nan, c10::optional posinf, c10::optional neginf) const { + return at::_ops::nan_to_num_::call(const_cast(*this), nan, posinf, neginf); +} + +// aten::ldexp.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::ldexp(const at::Tensor & other) const { + return at::_ops::ldexp_Tensor::call(const_cast(*this), other); +} + +// aten::ldexp_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::ldexp_(const at::Tensor & other) const { + return at::_ops::ldexp_::call(const_cast(*this), other); +} + +// aten::log(Tensor self) -> Tensor +inline at::Tensor Tensor::log() const { + return at::_ops::log::call(const_cast(*this)); +} + +// aten::log_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::log_() const { + return at::_ops::log_::call(const_cast(*this)); +} + +// aten::log10(Tensor self) -> Tensor +inline at::Tensor Tensor::log10() const { + return at::_ops::log10::call(const_cast(*this)); +} + +// aten::log10_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::log10_() const { + return at::_ops::log10_::call(const_cast(*this)); +} + +// aten::log1p(Tensor self) -> Tensor +inline at::Tensor Tensor::log1p() const { + return at::_ops::log1p::call(const_cast(*this)); +} + +// aten::log1p_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::log1p_() const { + return at::_ops::log1p_::call(const_cast(*this)); +} + +// aten::log2(Tensor self) -> Tensor +inline at::Tensor Tensor::log2() const { + return at::_ops::log2::call(const_cast(*this)); +} + +// aten::log2_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::log2_() const { + return at::_ops::log2_::call(const_cast(*this)); +} + +// aten::logaddexp(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::logaddexp(const at::Tensor & other) const { + return at::_ops::logaddexp::call(const_cast(*this), other); +} + +// aten::logaddexp2(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::logaddexp2(const at::Tensor & other) const { + return at::_ops::logaddexp2::call(const_cast(*this), other); +} + +// aten::xlogy.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::xlogy(const at::Tensor & other) const { + return at::_ops::xlogy_Tensor::call(const_cast(*this), other); +} + +// aten::xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::xlogy(const at::Scalar & other) const { + return at::_ops::xlogy_Scalar_Other::call(const_cast(*this), other); +} + +// aten::xlogy_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::xlogy_(const at::Tensor & other) const { + return at::_ops::xlogy__Tensor::call(const_cast(*this), other); +} + +// aten::xlogy_.Scalar_Other(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::xlogy_(const at::Scalar & other) const { + return at::_ops::xlogy__Scalar_Other::call(const_cast(*this), other); +} + +// aten::log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::log_softmax(int64_t dim, c10::optional dtype) const { + return at::_ops::log_softmax_int::call(const_cast(*this), dim, dtype); +} + +// aten::log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::log_softmax(at::Dimname dim, c10::optional dtype) const { + return at::_ops::log_softmax_Dimname::call(const_cast(*this), dim, dtype); +} + +// aten::logcumsumexp(Tensor self, int dim) -> Tensor +inline at::Tensor Tensor::logcumsumexp(int64_t dim) const { + return at::_ops::logcumsumexp::call(const_cast(*this), dim); +} + +// aten::logcumsumexp.dimname(Tensor self, Dimname dim) -> Tensor +inline at::Tensor Tensor::logcumsumexp(at::Dimname dim) const { + return at::_ops::logcumsumexp_dimname::call(const_cast(*this), dim); +} + +// aten::logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::logsumexp(at::IntArrayRef dim, bool keepdim) const { + return at::_ops::logsumexp::call(const_cast(*this), dim, keepdim); +} + +// aten::logsumexp.names(Tensor self, Dimname[1] dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::logsumexp(at::DimnameList dim, bool keepdim) const { + return at::_ops::logsumexp_names::call(const_cast(*this), dim, keepdim); +} + +// aten::matmul(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::matmul(const at::Tensor & other) const { + return at::_ops::matmul::call(const_cast(*this), other); +} + +// aten::matrix_power(Tensor self, int n) -> Tensor +inline at::Tensor Tensor::matrix_power(int64_t n) const { + return at::_ops::matrix_power::call(const_cast(*this), n); +} + +// aten::matrix_exp(Tensor self) -> Tensor +inline at::Tensor Tensor::matrix_exp() const { + return at::_ops::matrix_exp::call(const_cast(*this)); +} + +// aten::aminmax(Tensor self, *, int? dim=None, bool keepdim=False) -> (Tensor min, Tensor max) +inline ::std::tuple Tensor::aminmax(c10::optional dim, bool keepdim) const { + return at::_ops::aminmax::call(const_cast(*this), dim, keepdim); +} + +// aten::max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::max(int64_t dim, bool keepdim) const { + return at::_ops::max_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::max.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::max(at::Dimname dim, bool keepdim) const { + return at::_ops::max_names_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor +inline at::Tensor Tensor::amax(at::IntArrayRef dim, bool keepdim) const { + return at::_ops::amax::call(const_cast(*this), dim, keepdim); +} + +// aten::mean(Tensor self, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::mean(c10::optional dtype) const { + return at::_ops::mean::call(const_cast(*this), dtype); +} + +// aten::mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::mean(at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype) const { + return at::_ops::mean_dim::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::mean.names_dim(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::mean(at::DimnameList dim, bool keepdim, c10::optional dtype) const { + return at::_ops::mean_names_dim::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::nanmean(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::nanmean(at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype) const { + return at::_ops::nanmean::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::median(Tensor self) -> Tensor +inline at::Tensor Tensor::median() const { + return at::_ops::median::call(const_cast(*this)); +} + +// aten::median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::median(int64_t dim, bool keepdim) const { + return at::_ops::median_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::median.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::median(at::Dimname dim, bool keepdim) const { + return at::_ops::median_names_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::nanmedian(Tensor self) -> Tensor +inline at::Tensor Tensor::nanmedian() const { + return at::_ops::nanmedian::call(const_cast(*this)); +} + +// aten::nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::nanmedian(int64_t dim, bool keepdim) const { + return at::_ops::nanmedian_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::nanmedian.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::nanmedian(at::Dimname dim, bool keepdim) const { + return at::_ops::nanmedian_names_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::min(int64_t dim, bool keepdim) const { + return at::_ops::min_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::min(at::Dimname dim, bool keepdim) const { + return at::_ops::min_names_dim::call(const_cast(*this), dim, keepdim); +} + +// aten::amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor +inline at::Tensor Tensor::amin(at::IntArrayRef dim, bool keepdim) const { + return at::_ops::amin::call(const_cast(*this), dim, keepdim); +} + +// aten::mm(Tensor self, Tensor mat2) -> Tensor +inline at::Tensor Tensor::mm(const at::Tensor & mat2) const { + return at::_ops::mm::call(const_cast(*this), mat2); +} + +// aten::mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::mode(int64_t dim, bool keepdim) const { + return at::_ops::mode::call(const_cast(*this), dim, keepdim); +} + +// aten::mode.dimname(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::mode(at::Dimname dim, bool keepdim) const { + return at::_ops::mode_dimname::call(const_cast(*this), dim, keepdim); +} + +// aten::mul.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::mul(const at::Tensor & other) const { + return at::_ops::mul_Tensor::call(const_cast(*this), other); +} + +// aten::mul_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::mul_(const at::Tensor & other) const { + return at::_ops::mul__Tensor::call(const_cast(*this), other); +} + +// aten::mul.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::mul(const at::Scalar & other) const { + return at::_ops::mul_Scalar::call(const_cast(*this), other); +} + +// aten::mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::mul_(const at::Scalar & other) const { + return at::_ops::mul__Scalar::call(const_cast(*this), other); +} + +// aten::multiply.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::multiply(const at::Tensor & other) const { + return at::_ops::multiply_Tensor::call(const_cast(*this), other); +} + +// aten::multiply_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::multiply_(const at::Tensor & other) const { + return at::_ops::multiply__Tensor::call(const_cast(*this), other); +} + +// aten::multiply.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::multiply(const at::Scalar & other) const { + return at::_ops::multiply_Scalar::call(const_cast(*this), other); +} + +// aten::multiply_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::multiply_(const at::Scalar & other) const { + return at::_ops::multiply__Scalar::call(const_cast(*this), other); +} + +// aten::mv(Tensor self, Tensor vec) -> Tensor +inline at::Tensor Tensor::mv(const at::Tensor & vec) const { + return at::_ops::mv::call(const_cast(*this), vec); +} + +// aten::mvlgamma(Tensor self, int p) -> Tensor +inline at::Tensor Tensor::mvlgamma(int64_t p) const { + return at::_ops::mvlgamma::call(const_cast(*this), p); +} + +// aten::mvlgamma_(Tensor(a!) self, int p) -> Tensor(a!) +inline at::Tensor & Tensor::mvlgamma_(int64_t p) const { + return at::_ops::mvlgamma_::call(const_cast(*this), p); +} + +// aten::narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor +inline at::Tensor Tensor::narrow_copy(int64_t dim, int64_t start, int64_t length) const { + return at::_ops::narrow_copy::call(const_cast(*this), dim, start, length); +} + +// aten::narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor +inline at::Tensor Tensor::narrow_copy_symint(int64_t dim, c10::SymInt start, c10::SymInt length) const { + return at::_ops::narrow_copy::call(const_cast(*this), dim, start, length); +} + +// aten::narrow(Tensor(a) self, int dim, SymInt start, SymInt length) -> Tensor(a) +inline at::Tensor Tensor::narrow(int64_t dim, int64_t start, int64_t length) const { + return at::_ops::narrow::call(const_cast(*this), dim, start, length); +} + +// aten::narrow(Tensor(a) self, int dim, SymInt start, SymInt length) -> Tensor(a) +inline at::Tensor Tensor::narrow_symint(int64_t dim, c10::SymInt start, c10::SymInt length) const { + return at::_ops::narrow::call(const_cast(*this), dim, start, length); +} + +// aten::narrow.Tensor(Tensor(a) self, int dim, Tensor start, SymInt length) -> Tensor(a) +inline at::Tensor Tensor::narrow(int64_t dim, const at::Tensor & start, int64_t length) const { + return at::_ops::narrow_Tensor::call(const_cast(*this), dim, start, length); +} + +// aten::narrow.Tensor(Tensor(a) self, int dim, Tensor start, SymInt length) -> Tensor(a) +inline at::Tensor Tensor::narrow_symint(int64_t dim, const at::Tensor & start, c10::SymInt length) const { + return at::_ops::narrow_Tensor::call(const_cast(*this), dim, start, length); +} + +// aten::permute(Tensor(a) self, int[] dims) -> Tensor(a) +inline at::Tensor Tensor::permute(at::IntArrayRef dims) const { + return at::_ops::permute::call(const_cast(*this), dims); +} + +// aten::movedim.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a) +inline at::Tensor Tensor::movedim(at::IntArrayRef source, at::IntArrayRef destination) const { + return at::_ops::movedim_intlist::call(const_cast(*this), source, destination); +} + +// aten::movedim.int(Tensor(a) self, int source, int destination) -> Tensor(a) +inline at::Tensor Tensor::movedim(int64_t source, int64_t destination) const { + return at::_ops::movedim_int::call(const_cast(*this), source, destination); +} + +// aten::moveaxis.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a) +inline at::Tensor Tensor::moveaxis(at::IntArrayRef source, at::IntArrayRef destination) const { + return at::_ops::moveaxis_intlist::call(const_cast(*this), source, destination); +} + +// aten::moveaxis.int(Tensor(a) self, int source, int destination) -> Tensor(a) +inline at::Tensor Tensor::moveaxis(int64_t source, int64_t destination) const { + return at::_ops::moveaxis_int::call(const_cast(*this), source, destination); +} + +// aten::numpy_T(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::numpy_T() const { + return at::_ops::numpy_T::call(const_cast(*this)); +} + +// aten::matrix_H(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::matrix_H() const { + return at::_ops::matrix_H::call(const_cast(*this)); +} + +// aten::mT(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::mT() const { + return at::_ops::mT::call(const_cast(*this)); +} + +// aten::mH(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::mH() const { + return at::_ops::mH::call(const_cast(*this)); +} + +// aten::adjoint(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::adjoint() const { + return at::_ops::adjoint::call(const_cast(*this)); +} + +// aten::is_pinned(Tensor self, Device? device=None) -> bool +inline bool Tensor::is_pinned(c10::optional device) const { + return at::_ops::is_pinned::call(const_cast(*this), device); +} + +// aten::pin_memory(Tensor(a) self, Device? device=None) -> Tensor(a) +inline at::Tensor Tensor::pin_memory(c10::optional device) const { + return at::_ops::pin_memory::call(const_cast(*this), device); +} + +// aten::pinverse(Tensor self, float rcond=1e-15) -> Tensor +inline at::Tensor Tensor::pinverse(double rcond) const { + return at::_ops::pinverse::call(const_cast(*this), rcond); +} + +// aten::rad2deg(Tensor self) -> Tensor +inline at::Tensor Tensor::rad2deg() const { + return at::_ops::rad2deg::call(const_cast(*this)); +} + +// aten::rad2deg_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::rad2deg_() const { + return at::_ops::rad2deg_::call(const_cast(*this)); +} + +// aten::deg2rad(Tensor self) -> Tensor +inline at::Tensor Tensor::deg2rad() const { + return at::_ops::deg2rad::call(const_cast(*this)); +} + +// aten::deg2rad_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::deg2rad_() const { + return at::_ops::deg2rad_::call(const_cast(*this)); +} + +// aten::ravel(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::ravel() const { + return at::_ops::ravel::call(const_cast(*this)); +} + +// aten::reciprocal(Tensor self) -> Tensor +inline at::Tensor Tensor::reciprocal() const { + return at::_ops::reciprocal::call(const_cast(*this)); +} + +// aten::reciprocal_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::reciprocal_() const { + return at::_ops::reciprocal_::call(const_cast(*this)); +} + +// aten::neg(Tensor self) -> Tensor +inline at::Tensor Tensor::neg() const { + return at::_ops::neg::call(const_cast(*this)); +} + +// aten::neg_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::neg_() const { + return at::_ops::neg_::call(const_cast(*this)); +} + +// aten::negative(Tensor self) -> Tensor +inline at::Tensor Tensor::negative() const { + return at::_ops::negative::call(const_cast(*this)); +} + +// aten::negative_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::negative_() const { + return at::_ops::negative_::call(const_cast(*this)); +} + +// aten::repeat(Tensor self, SymInt[] repeats) -> Tensor +inline at::Tensor Tensor::repeat(at::IntArrayRef repeats) const { + return at::_ops::repeat::call(const_cast(*this), c10::fromIntArrayRefSlow(repeats)); +} + +// aten::repeat(Tensor self, SymInt[] repeats) -> Tensor +inline at::Tensor Tensor::repeat_symint(c10::SymIntArrayRef repeats) const { + return at::_ops::repeat::call(const_cast(*this), repeats); +} + +// aten::repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor +inline at::Tensor Tensor::repeat_interleave(const at::Tensor & repeats, c10::optional dim, c10::optional output_size) const { + return at::_ops::repeat_interleave_self_Tensor::call(const_cast(*this), repeats, dim, output_size.has_value() ? c10::make_optional(c10::SymInt(*output_size)) : c10::nullopt); +} + +// aten::repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor +inline at::Tensor Tensor::repeat_interleave_symint(const at::Tensor & repeats, c10::optional dim, c10::optional output_size) const { + return at::_ops::repeat_interleave_self_Tensor::call(const_cast(*this), repeats, dim, output_size); +} + +// aten::repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor +inline at::Tensor Tensor::repeat_interleave(int64_t repeats, c10::optional dim, c10::optional output_size) const { + return at::_ops::repeat_interleave_self_int::call(const_cast(*this), repeats, dim, output_size.has_value() ? c10::make_optional(c10::SymInt(*output_size)) : c10::nullopt); +} + +// aten::repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor +inline at::Tensor Tensor::repeat_interleave_symint(c10::SymInt repeats, c10::optional dim, c10::optional output_size) const { + return at::_ops::repeat_interleave_self_int::call(const_cast(*this), repeats, dim, output_size); +} + +// aten::reshape(Tensor(a) self, SymInt[] shape) -> Tensor(a) +inline at::Tensor Tensor::reshape(at::IntArrayRef shape) const { + return at::_ops::reshape::call(const_cast(*this), c10::fromIntArrayRefSlow(shape)); +} + +// aten::reshape(Tensor(a) self, SymInt[] shape) -> Tensor(a) +inline at::Tensor Tensor::reshape_symint(c10::SymIntArrayRef shape) const { + return at::_ops::reshape::call(const_cast(*this), shape); +} + +// aten::_reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a) +inline at::Tensor Tensor::_reshape_alias(at::IntArrayRef size, at::IntArrayRef stride) const { + return at::_ops::_reshape_alias::call(const_cast(*this), c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride)); +} + +// aten::_reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a) +inline at::Tensor Tensor::_reshape_alias_symint(c10::SymIntArrayRef size, c10::SymIntArrayRef stride) const { + return at::_ops::_reshape_alias::call(const_cast(*this), size, stride); +} + +// aten::reshape_as(Tensor(a) self, Tensor other) -> Tensor(a) +inline at::Tensor Tensor::reshape_as(const at::Tensor & other) const { + return at::_ops::reshape_as::call(const_cast(*this), other); +} + +// aten::round(Tensor self) -> Tensor +inline at::Tensor Tensor::round() const { + return at::_ops::round::call(const_cast(*this)); +} + +// aten::round_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::round_() const { + return at::_ops::round_::call(const_cast(*this)); +} + +// aten::round.decimals(Tensor self, *, int decimals) -> Tensor +inline at::Tensor Tensor::round(int64_t decimals) const { + return at::_ops::round_decimals::call(const_cast(*this), decimals); +} + +// aten::round_.decimals(Tensor(a!) self, *, int decimals) -> Tensor(a!) +inline at::Tensor & Tensor::round_(int64_t decimals) const { + return at::_ops::round__decimals::call(const_cast(*this), decimals); +} + +// aten::relu(Tensor self) -> Tensor +inline at::Tensor Tensor::relu() const { + return at::_ops::relu::call(const_cast(*this)); +} + +// aten::relu_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::relu_() const { + return at::_ops::relu_::call(const_cast(*this)); +} + +// aten::prelu(Tensor self, Tensor weight) -> Tensor +inline at::Tensor Tensor::prelu(const at::Tensor & weight) const { + return at::_ops::prelu::call(const_cast(*this), weight); +} + +// aten::hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor +inline at::Tensor Tensor::hardshrink(const at::Scalar & lambd) const { + return at::_ops::hardshrink::call(const_cast(*this), lambd); +} + +// aten::hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor +inline at::Tensor Tensor::hardshrink_backward(const at::Tensor & grad_out, const at::Scalar & lambd) const { + return at::_ops::hardshrink_backward::call(grad_out, const_cast(*this), lambd); +} + +// aten::rsqrt(Tensor self) -> Tensor +inline at::Tensor Tensor::rsqrt() const { + return at::_ops::rsqrt::call(const_cast(*this)); +} + +// aten::rsqrt_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::rsqrt_() const { + return at::_ops::rsqrt_::call(const_cast(*this)); +} + +// aten::select.Dimname(Tensor(a) self, Dimname dim, int index) -> Tensor(a) +inline at::Tensor Tensor::select(at::Dimname dim, int64_t index) const { + return at::_ops::select_Dimname::call(const_cast(*this), dim, index); +} + +// aten::select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a) +inline at::Tensor Tensor::select(int64_t dim, int64_t index) const { + return at::_ops::select_int::call(const_cast(*this), dim, index); +} + +// aten::select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a) +inline at::Tensor Tensor::select_symint(int64_t dim, c10::SymInt index) const { + return at::_ops::select_int::call(const_cast(*this), dim, index); +} + +// aten::sigmoid(Tensor self) -> Tensor +inline at::Tensor Tensor::sigmoid() const { + return at::_ops::sigmoid::call(const_cast(*this)); +} + +// aten::sigmoid_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sigmoid_() const { + return at::_ops::sigmoid_::call(const_cast(*this)); +} + +// aten::logit(Tensor self, float? eps=None) -> Tensor +inline at::Tensor Tensor::logit(c10::optional eps) const { + return at::_ops::logit::call(const_cast(*this), eps); +} + +// aten::logit_(Tensor(a!) self, float? eps=None) -> Tensor(a!) +inline at::Tensor & Tensor::logit_(c10::optional eps) const { + return at::_ops::logit_::call(const_cast(*this), eps); +} + +// aten::sin(Tensor self) -> Tensor +inline at::Tensor Tensor::sin() const { + return at::_ops::sin::call(const_cast(*this)); +} + +// aten::sin_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sin_() const { + return at::_ops::sin_::call(const_cast(*this)); +} + +// aten::sinc(Tensor self) -> Tensor +inline at::Tensor Tensor::sinc() const { + return at::_ops::sinc::call(const_cast(*this)); +} + +// aten::sinc_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sinc_() const { + return at::_ops::sinc_::call(const_cast(*this)); +} + +// aten::sinh(Tensor self) -> Tensor +inline at::Tensor Tensor::sinh() const { + return at::_ops::sinh::call(const_cast(*this)); +} + +// aten::sinh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sinh_() const { + return at::_ops::sinh_::call(const_cast(*this)); +} + +// aten::detach(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::detach() const { + return at::_ops::detach::call(const_cast(*this)); +} + +// aten::detach_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::detach_() const { + return at::_ops::detach_::call(const_cast(*this)); +} + +// aten::size.Dimname(Tensor self, Dimname dim) -> int +inline int64_t Tensor::size(at::Dimname dim) const { + return at::_ops::size_Dimname::call(const_cast(*this), dim); +} + +// aten::slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) +inline at::Tensor Tensor::slice(int64_t dim, c10::optional start, c10::optional end, int64_t step) const { + return at::_ops::slice_Tensor::call(const_cast(*this), dim, start.has_value() ? c10::make_optional(c10::SymInt(*start)) : c10::nullopt, end.has_value() ? c10::make_optional(c10::SymInt(*end)) : c10::nullopt, step); +} + +// aten::slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) +inline at::Tensor Tensor::slice_symint(int64_t dim, c10::optional start, c10::optional end, c10::SymInt step) const { + return at::_ops::slice_Tensor::call(const_cast(*this), dim, start, end, step); +} + +// aten::slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) +inline at::Tensor Tensor::slice_inverse(const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, int64_t step) const { + return at::_ops::slice_inverse::call(const_cast(*this), src, dim, start.has_value() ? c10::make_optional(c10::SymInt(*start)) : c10::nullopt, end.has_value() ? c10::make_optional(c10::SymInt(*end)) : c10::nullopt, step); +} + +// aten::slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) +inline at::Tensor Tensor::slice_inverse_symint(const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, c10::SymInt step) const { + return at::_ops::slice_inverse::call(const_cast(*this), src, dim, start, end, step); +} + +// aten::slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor +inline at::Tensor Tensor::slice_scatter(const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, int64_t step) const { + return at::_ops::slice_scatter::call(const_cast(*this), src, dim, start.has_value() ? c10::make_optional(c10::SymInt(*start)) : c10::nullopt, end.has_value() ? c10::make_optional(c10::SymInt(*end)) : c10::nullopt, step); +} + +// aten::slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor +inline at::Tensor Tensor::slice_scatter_symint(const at::Tensor & src, int64_t dim, c10::optional start, c10::optional end, c10::SymInt step) const { + return at::_ops::slice_scatter::call(const_cast(*this), src, dim, start, end, step); +} + +// aten::select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor +inline at::Tensor Tensor::select_scatter(const at::Tensor & src, int64_t dim, int64_t index) const { + return at::_ops::select_scatter::call(const_cast(*this), src, dim, index); +} + +// aten::select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor +inline at::Tensor Tensor::select_scatter_symint(const at::Tensor & src, int64_t dim, c10::SymInt index) const { + return at::_ops::select_scatter::call(const_cast(*this), src, dim, index); +} + +// aten::diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor +inline at::Tensor Tensor::diagonal_scatter(const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2) const { + return at::_ops::diagonal_scatter::call(const_cast(*this), src, offset, dim1, dim2); +} + +// aten::as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor +inline at::Tensor Tensor::as_strided_scatter(const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset) const { + return at::_ops::as_strided_scatter::call(const_cast(*this), src, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? c10::make_optional(c10::SymInt(*storage_offset)) : c10::nullopt); +} + +// aten::as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor +inline at::Tensor Tensor::as_strided_scatter_symint(const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset) const { + return at::_ops::as_strided_scatter::call(const_cast(*this), src, size, stride, storage_offset); +} + +// aten::smm(Tensor self, Tensor mat2) -> Tensor +inline at::Tensor Tensor::smm(const at::Tensor & mat2) const { + return at::_ops::smm::call(const_cast(*this), mat2); +} + +// aten::softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::softmax(int64_t dim, c10::optional dtype) const { + return at::_ops::softmax_int::call(const_cast(*this), dim, dtype); +} + +// aten::softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::softmax(at::Dimname dim, c10::optional dtype) const { + return at::_ops::softmax_Dimname::call(const_cast(*this), dim, dtype); +} + +// aten::unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[] +inline ::std::vector Tensor::unsafe_split(int64_t split_size, int64_t dim) const { + return at::_ops::unsafe_split_Tensor::call(const_cast(*this), split_size, dim); +} + +// aten::unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[] +inline ::std::vector Tensor::unsafe_split_symint(c10::SymInt split_size, int64_t dim) const { + return at::_ops::unsafe_split_Tensor::call(const_cast(*this), split_size, dim); +} + +// aten::split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::split(int64_t split_size, int64_t dim) const { + return at::_ops::split_Tensor::call(const_cast(*this), split_size, dim); +} + +// aten::split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::split_symint(c10::SymInt split_size, int64_t dim) const { + return at::_ops::split_Tensor::call(const_cast(*this), split_size, dim); +} + +// aten::split.sizes(Tensor(a -> *) self, SymInt[] split_size, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::split(at::IntArrayRef split_size, int64_t dim) const { + return at::_ops::split_sizes::call(const_cast(*this), c10::fromIntArrayRefSlow(split_size), dim); +} + +// aten::split.sizes(Tensor(a -> *) self, SymInt[] split_size, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::split_symint(c10::SymIntArrayRef split_size, int64_t dim) const { + return at::_ops::split_sizes::call(const_cast(*this), split_size, dim); +} + +// aten::unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[] +inline ::std::vector Tensor::unsafe_split_with_sizes(at::IntArrayRef split_sizes, int64_t dim) const { + return at::_ops::unsafe_split_with_sizes::call(const_cast(*this), c10::fromIntArrayRefSlow(split_sizes), dim); +} + +// aten::unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[] +inline ::std::vector Tensor::unsafe_split_with_sizes_symint(c10::SymIntArrayRef split_sizes, int64_t dim) const { + return at::_ops::unsafe_split_with_sizes::call(const_cast(*this), split_sizes, dim); +} + +// aten::split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::split_with_sizes(at::IntArrayRef split_sizes, int64_t dim) const { + return at::_ops::split_with_sizes::call(const_cast(*this), c10::fromIntArrayRefSlow(split_sizes), dim); +} + +// aten::split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::split_with_sizes_symint(c10::SymIntArrayRef split_sizes, int64_t dim) const { + return at::_ops::split_with_sizes::call(const_cast(*this), split_sizes, dim); +} + +// aten::hsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] +inline ::std::vector Tensor::hsplit(int64_t sections) const { + return at::_ops::hsplit_int::call(const_cast(*this), sections); +} + +// aten::hsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] +inline ::std::vector Tensor::hsplit(at::IntArrayRef indices) const { + return at::_ops::hsplit_array::call(const_cast(*this), indices); +} + +// aten::vsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] +inline ::std::vector Tensor::vsplit(int64_t sections) const { + return at::_ops::vsplit_int::call(const_cast(*this), sections); +} + +// aten::vsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] +inline ::std::vector Tensor::vsplit(at::IntArrayRef indices) const { + return at::_ops::vsplit_array::call(const_cast(*this), indices); +} + +// aten::dsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] +inline ::std::vector Tensor::dsplit(int64_t sections) const { + return at::_ops::dsplit_int::call(const_cast(*this), sections); +} + +// aten::dsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] +inline ::std::vector Tensor::dsplit(at::IntArrayRef indices) const { + return at::_ops::dsplit_array::call(const_cast(*this), indices); +} + +// aten::squeeze(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::squeeze() const { + return at::_ops::squeeze::call(const_cast(*this)); +} + +// aten::squeeze.dim(Tensor(a) self, int dim) -> Tensor(a) +inline at::Tensor Tensor::squeeze(int64_t dim) const { + return at::_ops::squeeze_dim::call(const_cast(*this), dim); +} + +// aten::squeeze.dimname(Tensor(a) self, Dimname dim) -> Tensor(a) +inline at::Tensor Tensor::squeeze(at::Dimname dim) const { + return at::_ops::squeeze_dimname::call(const_cast(*this), dim); +} + +// aten::squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a) +inline at::Tensor Tensor::squeeze(at::IntArrayRef dim) const { + return at::_ops::squeeze_dims::call(const_cast(*this), dim); +} + +// aten::squeeze_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::squeeze_() const { + return at::_ops::squeeze_::call(const_cast(*this)); +} + +// aten::squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!) +inline at::Tensor & Tensor::squeeze_(int64_t dim) const { + return at::_ops::squeeze__dim::call(const_cast(*this), dim); +} + +// aten::squeeze_.dims(Tensor(a!) self, int[] dim) -> Tensor(a!) +inline at::Tensor & Tensor::squeeze_(at::IntArrayRef dim) const { + return at::_ops::squeeze__dims::call(const_cast(*this), dim); +} + +// aten::squeeze_.dimname(Tensor(a!) self, Dimname dim) -> Tensor(a!) +inline at::Tensor & Tensor::squeeze_(at::Dimname dim) const { + return at::_ops::squeeze__dimname::call(const_cast(*this), dim); +} + +// aten::sspaddmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::sspaddmm(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::sspaddmm::call(const_cast(*this), mat1, mat2, beta, alpha); +} + +// aten::stft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool normalized=False, bool? onesided=None, bool? return_complex=None) -> Tensor +inline at::Tensor Tensor::stft(int64_t n_fft, c10::optional hop_length, c10::optional win_length, const c10::optional & window, bool normalized, c10::optional onesided, c10::optional return_complex) const { + return at::_ops::stft::call(const_cast(*this), n_fft, hop_length, win_length, window, normalized, onesided, return_complex); +} + +// aten::stft.center(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, str pad_mode="reflect", bool normalized=False, bool? onesided=None, bool? return_complex=None) -> Tensor +inline at::Tensor Tensor::stft(int64_t n_fft, c10::optional hop_length, c10::optional win_length, const c10::optional & window, bool center, c10::string_view pad_mode, bool normalized, c10::optional onesided, c10::optional return_complex) const { + return at::_ops::stft_center::call(const_cast(*this), n_fft, hop_length, win_length, window, center, pad_mode, normalized, onesided, return_complex); +} + +// aten::istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensor +inline at::Tensor Tensor::istft(int64_t n_fft, c10::optional hop_length, c10::optional win_length, const c10::optional & window, bool center, bool normalized, c10::optional onesided, c10::optional length, bool return_complex) const { + return at::_ops::istft::call(const_cast(*this), n_fft, hop_length, win_length, window, center, normalized, onesided, length, return_complex); +} + +// aten::stride.Dimname(Tensor self, Dimname dim) -> int +inline int64_t Tensor::stride(at::Dimname dim) const { + return at::_ops::stride_Dimname::call(const_cast(*this), dim); +} + +// aten::sum(Tensor self, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::sum(c10::optional dtype) const { + return at::_ops::sum::call(const_cast(*this), dtype); +} + +// aten::sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::sum(at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype) const { + return at::_ops::sum_dim_IntList::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::sum.dim_DimnameList(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::sum(at::DimnameList dim, bool keepdim, c10::optional dtype) const { + return at::_ops::sum_dim_DimnameList::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::nansum(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::nansum(at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype) const { + return at::_ops::nansum::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::sum_to_size(Tensor self, SymInt[] size) -> Tensor +inline at::Tensor Tensor::sum_to_size(at::IntArrayRef size) const { + return at::_ops::sum_to_size::call(const_cast(*this), c10::fromIntArrayRefSlow(size)); +} + +// aten::sum_to_size(Tensor self, SymInt[] size) -> Tensor +inline at::Tensor Tensor::sum_to_size_symint(c10::SymIntArrayRef size) const { + return at::_ops::sum_to_size::call(const_cast(*this), size); +} + +// aten::sqrt(Tensor self) -> Tensor +inline at::Tensor Tensor::sqrt() const { + return at::_ops::sqrt::call(const_cast(*this)); +} + +// aten::sqrt_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sqrt_() const { + return at::_ops::sqrt_::call(const_cast(*this)); +} + +// aten::square(Tensor self) -> Tensor +inline at::Tensor Tensor::square() const { + return at::_ops::square::call(const_cast(*this)); +} + +// aten::square_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::square_() const { + return at::_ops::square_::call(const_cast(*this)); +} + +// aten::std(Tensor self, bool unbiased=True) -> Tensor +inline at::Tensor Tensor::std(bool unbiased) const { + return at::_ops::std::call(const_cast(*this), unbiased); +} + +// aten::std.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::std(at::OptionalIntArrayRef dim, bool unbiased, bool keepdim) const { + return at::_ops::std_dim::call(const_cast(*this), dim, unbiased, keepdim); +} + +// aten::std.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::std(at::OptionalIntArrayRef dim, const c10::optional & correction, bool keepdim) const { + return at::_ops::std_correction::call(const_cast(*this), dim, correction, keepdim); +} + +// aten::std.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::std(at::DimnameList dim, bool unbiased, bool keepdim) const { + return at::_ops::std_names_dim::call(const_cast(*this), dim, unbiased, keepdim); +} + +// aten::std.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::std(at::DimnameList dim, const c10::optional & correction, bool keepdim) const { + return at::_ops::std_correction_names::call(const_cast(*this), dim, correction, keepdim); +} + +// aten::prod(Tensor self, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::prod(c10::optional dtype) const { + return at::_ops::prod::call(const_cast(*this), dtype); +} + +// aten::prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::prod(int64_t dim, bool keepdim, c10::optional dtype) const { + return at::_ops::prod_dim_int::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::prod.dim_Dimname(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::prod(at::Dimname dim, bool keepdim, c10::optional dtype) const { + return at::_ops::prod_dim_Dimname::call(const_cast(*this), dim, keepdim, dtype); +} + +// aten::t(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::t() const { + return at::_ops::t::call(const_cast(*this)); +} + +// aten::t_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::t_() const { + return at::_ops::t_::call(const_cast(*this)); +} + +// aten::tan(Tensor self) -> Tensor +inline at::Tensor Tensor::tan() const { + return at::_ops::tan::call(const_cast(*this)); +} + +// aten::tan_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::tan_() const { + return at::_ops::tan_::call(const_cast(*this)); +} + +// aten::tanh(Tensor self) -> Tensor +inline at::Tensor Tensor::tanh() const { + return at::_ops::tanh::call(const_cast(*this)); +} + +// aten::tanh_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::tanh_() const { + return at::_ops::tanh_::call(const_cast(*this)); +} + +// aten::tile(Tensor self, SymInt[] dims) -> Tensor +inline at::Tensor Tensor::tile(at::IntArrayRef dims) const { + return at::_ops::tile::call(const_cast(*this), c10::fromIntArrayRefSlow(dims)); +} + +// aten::tile(Tensor self, SymInt[] dims) -> Tensor +inline at::Tensor Tensor::tile_symint(c10::SymIntArrayRef dims) const { + return at::_ops::tile::call(const_cast(*this), dims); +} + +// aten::transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a) +inline at::Tensor Tensor::transpose(int64_t dim0, int64_t dim1) const { + return at::_ops::transpose_int::call(const_cast(*this), dim0, dim1); +} + +// aten::transpose.Dimname(Tensor(a) self, Dimname dim0, Dimname dim1) -> Tensor(a) +inline at::Tensor Tensor::transpose(at::Dimname dim0, at::Dimname dim1) const { + return at::_ops::transpose_Dimname::call(const_cast(*this), dim0, dim1); +} + +// aten::transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) +inline at::Tensor & Tensor::transpose_(int64_t dim0, int64_t dim1) const { + return at::_ops::transpose_::call(const_cast(*this), dim0, dim1); +} + +// aten::flip(Tensor self, int[] dims) -> Tensor +inline at::Tensor Tensor::flip(at::IntArrayRef dims) const { + return at::_ops::flip::call(const_cast(*this), dims); +} + +// aten::fliplr(Tensor self) -> Tensor +inline at::Tensor Tensor::fliplr() const { + return at::_ops::fliplr::call(const_cast(*this)); +} + +// aten::flipud(Tensor self) -> Tensor +inline at::Tensor Tensor::flipud() const { + return at::_ops::flipud::call(const_cast(*this)); +} + +// aten::roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor +inline at::Tensor Tensor::roll(at::IntArrayRef shifts, at::IntArrayRef dims) const { + return at::_ops::roll::call(const_cast(*this), c10::fromIntArrayRefSlow(shifts), dims); +} + +// aten::roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor +inline at::Tensor Tensor::roll_symint(c10::SymIntArrayRef shifts, at::IntArrayRef dims) const { + return at::_ops::roll::call(const_cast(*this), shifts, dims); +} + +// aten::rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor +inline at::Tensor Tensor::rot90(int64_t k, at::IntArrayRef dims) const { + return at::_ops::rot90::call(const_cast(*this), k, dims); +} + +// aten::_nested_tensor_size(Tensor self) -> Tensor +inline at::Tensor Tensor::_nested_tensor_size() const { + return at::_ops::_nested_tensor_size::call(const_cast(*this)); +} + +// aten::_nested_tensor_strides(Tensor self) -> Tensor +inline at::Tensor Tensor::_nested_tensor_strides() const { + return at::_ops::_nested_tensor_strides::call(const_cast(*this)); +} + +// aten::_nested_tensor_storage_offsets(Tensor self) -> Tensor +inline at::Tensor Tensor::_nested_tensor_storage_offsets() const { + return at::_ops::_nested_tensor_storage_offsets::call(const_cast(*this)); +} + +// aten::trunc(Tensor self) -> Tensor +inline at::Tensor Tensor::trunc() const { + return at::_ops::trunc::call(const_cast(*this)); +} + +// aten::trunc_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::trunc_() const { + return at::_ops::trunc_::call(const_cast(*this)); +} + +// aten::fix(Tensor self) -> Tensor +inline at::Tensor Tensor::fix() const { + return at::_ops::fix::call(const_cast(*this)); +} + +// aten::fix_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::fix_() const { + return at::_ops::fix_::call(const_cast(*this)); +} + +// aten::type_as(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::type_as(const at::Tensor & other) const { + return at::_ops::type_as::call(const_cast(*this), other); +} + +// aten::unsqueeze(Tensor(a) self, int dim) -> Tensor(a) +inline at::Tensor Tensor::unsqueeze(int64_t dim) const { + return at::_ops::unsqueeze::call(const_cast(*this), dim); +} + +// aten::unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!) +inline at::Tensor & Tensor::unsqueeze_(int64_t dim) const { + return at::_ops::unsqueeze_::call(const_cast(*this), dim); +} + +// aten::var(Tensor self, bool unbiased=True) -> Tensor +inline at::Tensor Tensor::var(bool unbiased) const { + return at::_ops::var::call(const_cast(*this), unbiased); +} + +// aten::var.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::var(at::OptionalIntArrayRef dim, bool unbiased, bool keepdim) const { + return at::_ops::var_dim::call(const_cast(*this), dim, unbiased, keepdim); +} + +// aten::var.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::var(at::OptionalIntArrayRef dim, const c10::optional & correction, bool keepdim) const { + return at::_ops::var_correction::call(const_cast(*this), dim, correction, keepdim); +} + +// aten::var.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::var(at::DimnameList dim, bool unbiased, bool keepdim) const { + return at::_ops::var_names_dim::call(const_cast(*this), dim, unbiased, keepdim); +} + +// aten::var.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::var(at::DimnameList dim, const c10::optional & correction, bool keepdim) const { + return at::_ops::var_correction_names::call(const_cast(*this), dim, correction, keepdim); +} + +// aten::view_as(Tensor(a) self, Tensor other) -> Tensor(a) +inline at::Tensor Tensor::view_as(const at::Tensor & other) const { + return at::_ops::view_as::call(const_cast(*this), other); +} + +// aten::where.self(Tensor condition, Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::where(const at::Tensor & condition, const at::Tensor & other) const { + return at::_ops::where_self::call(condition, const_cast(*this), other); +} + +// aten::where.ScalarOther(Tensor condition, Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::where(const at::Tensor & condition, const at::Scalar & other) const { + return at::_ops::where_ScalarOther::call(condition, const_cast(*this), other); +} + +// aten::norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor +inline at::Tensor Tensor::norm(const c10::optional & p, at::ScalarType dtype) const { + return at::_ops::norm_ScalarOpt_dtype::call(const_cast(*this), p, dtype); +} + +// aten::norm.Scalar(Tensor self, Scalar p=2) -> Tensor +inline at::Tensor Tensor::norm(const at::Scalar & p) const { + return at::_ops::norm_Scalar::call(const_cast(*this), p); +} + +// aten::norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor +inline at::Tensor Tensor::norm(const c10::optional & p, at::IntArrayRef dim, bool keepdim, at::ScalarType dtype) const { + return at::_ops::norm_ScalarOpt_dim_dtype::call(const_cast(*this), p, dim, keepdim, dtype); +} + +// aten::norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::norm(const c10::optional & p, at::IntArrayRef dim, bool keepdim) const { + return at::_ops::norm_ScalarOpt_dim::call(const_cast(*this), p, dim, keepdim); +} + +// aten::norm.names_ScalarOpt_dim_dtype(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor +inline at::Tensor Tensor::norm(const c10::optional & p, at::DimnameList dim, bool keepdim, at::ScalarType dtype) const { + return at::_ops::norm_names_ScalarOpt_dim_dtype::call(const_cast(*this), p, dim, keepdim, dtype); +} + +// aten::norm.names_ScalarOpt_dim(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False) -> Tensor +inline at::Tensor Tensor::norm(const c10::optional & p, at::DimnameList dim, bool keepdim) const { + return at::_ops::norm_names_ScalarOpt_dim::call(const_cast(*this), p, dim, keepdim); +} + +// aten::frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent) +inline ::std::tuple Tensor::frexp() const { + return at::_ops::frexp_Tensor::call(const_cast(*this)); +} + +// aten::clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor Tensor::clone(c10::optional memory_format) const { + return at::_ops::clone::call(const_cast(*this), memory_format); +} + +// aten::positive(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::positive() const { + return at::_ops::positive::call(const_cast(*this)); +} + +// aten::resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!) +inline const at::Tensor & Tensor::resize_as_(const at::Tensor & the_template, c10::optional memory_format) const { + return at::_ops::resize_as_::call(const_cast(*this), the_template, memory_format); +} + +// aten::resize_as_sparse_(Tensor(a!) self, Tensor the_template) -> Tensor(a!) +inline const at::Tensor & Tensor::resize_as_sparse_(const at::Tensor & the_template) const { + return at::_ops::resize_as_sparse_::call(const_cast(*this), the_template); +} + +// aten::zero_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::zero_() const { + return at::_ops::zero_::call(const_cast(*this)); +} + +// aten::sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::sub(const at::Tensor & other, const at::Scalar & alpha) const { + return at::_ops::sub_Tensor::call(const_cast(*this), other, alpha); +} + +// aten::sub_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::sub_(const at::Tensor & other, const at::Scalar & alpha) const { + return at::_ops::sub__Tensor::call(const_cast(*this), other, alpha); +} + +// aten::sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::sub(const at::Scalar & other, const at::Scalar & alpha) const { + return at::_ops::sub_Scalar::call(const_cast(*this), other, alpha); +} + +// aten::sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::sub_(const at::Scalar & other, const at::Scalar & alpha) const { + return at::_ops::sub__Scalar::call(const_cast(*this), other, alpha); +} + +// aten::subtract.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::subtract(const at::Tensor & other, const at::Scalar & alpha) const { + return at::_ops::subtract_Tensor::call(const_cast(*this), other, alpha); +} + +// aten::subtract_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::subtract_(const at::Tensor & other, const at::Scalar & alpha) const { + return at::_ops::subtract__Tensor::call(const_cast(*this), other, alpha); +} + +// aten::subtract.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::subtract(const at::Scalar & other, const at::Scalar & alpha) const { + return at::_ops::subtract_Scalar::call(const_cast(*this), other, alpha); +} + +// aten::subtract_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::subtract_(const at::Scalar & other, const at::Scalar & alpha) const { + return at::_ops::subtract__Scalar::call(const_cast(*this), other, alpha); +} + +// aten::heaviside(Tensor self, Tensor values) -> Tensor +inline at::Tensor Tensor::heaviside(const at::Tensor & values) const { + return at::_ops::heaviside::call(const_cast(*this), values); +} + +// aten::heaviside_(Tensor(a!) self, Tensor values) -> Tensor(a!) +inline at::Tensor & Tensor::heaviside_(const at::Tensor & values) const { + return at::_ops::heaviside_::call(const_cast(*this), values); +} + +// aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::addmm(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addmm::call(const_cast(*this), mat1, mat2, beta, alpha); +} + +// aten::addmm_(Tensor(a!) self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::addmm_(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addmm_::call(const_cast(*this), mat1, mat2, beta, alpha); +} + +// aten::_addmm_activation(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False) -> Tensor +inline at::Tensor Tensor::_addmm_activation(const at::Tensor & mat1, const at::Tensor & mat2, const at::Scalar & beta, const at::Scalar & alpha, bool use_gelu) const { + return at::_ops::_addmm_activation::call(const_cast(*this), mat1, mat2, beta, alpha, use_gelu); +} + +// aten::sparse_resize_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!) +inline const at::Tensor & Tensor::sparse_resize_(at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim) const { + return at::_ops::sparse_resize_::call(const_cast(*this), size, sparse_dim, dense_dim); +} + +// aten::sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!) +inline const at::Tensor & Tensor::sparse_resize_and_clear_(at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim) const { + return at::_ops::sparse_resize_and_clear_::call(const_cast(*this), size, sparse_dim, dense_dim); +} + +// aten::sparse_mask(Tensor self, Tensor mask) -> Tensor +inline at::Tensor Tensor::sparse_mask(const at::Tensor & mask) const { + return at::_ops::sparse_mask::call(const_cast(*this), mask); +} + +// aten::_sparse_mask_projection(Tensor self, Tensor mask, bool accumulate_matches=False) -> Tensor +inline at::Tensor Tensor::_sparse_mask_projection(const at::Tensor & mask, bool accumulate_matches) const { + return at::_ops::_sparse_mask_projection::call(const_cast(*this), mask, accumulate_matches); +} + +// aten::to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor +inline at::Tensor Tensor::to_dense(c10::optional dtype, c10::optional masked_grad) const { + return at::_ops::to_dense::call(const_cast(*this), dtype, masked_grad); +} + +// aten::_to_dense(Tensor self, ScalarType? dtype=None, bool? masked_grad=None) -> Tensor +inline at::Tensor Tensor::_to_dense(c10::optional dtype, c10::optional masked_grad) const { + return at::_ops::_to_dense::call(const_cast(*this), dtype, masked_grad); +} + +// aten::sparse_dim(Tensor self) -> int +inline int64_t Tensor::sparse_dim() const { + return at::_ops::sparse_dim::call(const_cast(*this)); +} + +// aten::_dimI(Tensor self) -> int +inline int64_t Tensor::_dimI() const { + return at::_ops::_dimI::call(const_cast(*this)); +} + +// aten::dense_dim(Tensor self) -> int +inline int64_t Tensor::dense_dim() const { + return at::_ops::dense_dim::call(const_cast(*this)); +} + +// aten::_dimV(Tensor self) -> int +inline int64_t Tensor::_dimV() const { + return at::_ops::_dimV::call(const_cast(*this)); +} + +// aten::_nnz(Tensor self) -> int +inline int64_t Tensor::_nnz() const { + return at::_ops::_nnz::call(const_cast(*this)); +} + +// aten::coalesce(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::coalesce() const { + return at::_ops::coalesce::call(const_cast(*this)); +} + +// aten::is_coalesced(Tensor self) -> bool +inline bool Tensor::is_coalesced() const { + return at::_ops::is_coalesced::call(const_cast(*this)); +} + +// aten::_indices(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::_indices() const { + return at::_ops::_indices::call(const_cast(*this)); +} + +// aten::_values(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::_values() const { + return at::_ops::_values::call(const_cast(*this)); +} + +// aten::_coalesced_(Tensor(a!) self, bool coalesced) -> Tensor(a!) +inline at::Tensor & Tensor::_coalesced_(bool coalesced) const { + return at::_ops::_coalesced_::call(const_cast(*this), coalesced); +} + +// aten::indices(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::indices() const { + return at::_ops::indices::call(const_cast(*this)); +} + +// aten::values(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::values() const { + return at::_ops::values::call(const_cast(*this)); +} + +// aten::crow_indices(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::crow_indices() const { + return at::_ops::crow_indices::call(const_cast(*this)); +} + +// aten::col_indices(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::col_indices() const { + return at::_ops::col_indices::call(const_cast(*this)); +} + +// aten::ccol_indices(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::ccol_indices() const { + return at::_ops::ccol_indices::call(const_cast(*this)); +} + +// aten::row_indices(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::row_indices() const { + return at::_ops::row_indices::call(const_cast(*this)); +} + +// aten::unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[] +inline ::std::vector Tensor::unbind(int64_t dim) const { + return at::_ops::unbind_int::call(const_cast(*this), dim); +} + +// aten::unbind.Dimname(Tensor(a -> *) self, Dimname dim) -> Tensor(a)[] +inline ::std::vector Tensor::unbind(at::Dimname dim) const { + return at::_ops::unbind_Dimname::call(const_cast(*this), dim); +} + +// aten::to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor +inline at::Tensor Tensor::to_sparse(int64_t sparse_dim) const { + return at::_ops::to_sparse_sparse_dim::call(const_cast(*this), sparse_dim); +} + +// aten::_to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor +inline at::Tensor Tensor::_to_sparse(int64_t sparse_dim) const { + return at::_ops::_to_sparse_sparse_dim::call(const_cast(*this), sparse_dim); +} + +// aten::to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::to_sparse(c10::optional layout, at::OptionalIntArrayRef blocksize, c10::optional dense_dim) const { + return at::_ops::to_sparse::call(const_cast(*this), layout, blocksize, dense_dim); +} + +// aten::_to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::_to_sparse(c10::optional layout, at::OptionalIntArrayRef blocksize, c10::optional dense_dim) const { + return at::_ops::_to_sparse::call(const_cast(*this), layout, blocksize, dense_dim); +} + +// aten::to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::to_sparse_csr(c10::optional dense_dim) const { + return at::_ops::to_sparse_csr::call(const_cast(*this), dense_dim); +} + +// aten::_to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::_to_sparse_csr(c10::optional dense_dim) const { + return at::_ops::_to_sparse_csr::call(const_cast(*this), dense_dim); +} + +// aten::to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::to_sparse_csc(c10::optional dense_dim) const { + return at::_ops::to_sparse_csc::call(const_cast(*this), dense_dim); +} + +// aten::_to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::_to_sparse_csc(c10::optional dense_dim) const { + return at::_ops::_to_sparse_csc::call(const_cast(*this), dense_dim); +} + +// aten::to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::to_sparse_bsr(at::IntArrayRef blocksize, c10::optional dense_dim) const { + return at::_ops::to_sparse_bsr::call(const_cast(*this), blocksize, dense_dim); +} + +// aten::_to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::_to_sparse_bsr(at::IntArrayRef blocksize, c10::optional dense_dim) const { + return at::_ops::_to_sparse_bsr::call(const_cast(*this), blocksize, dense_dim); +} + +// aten::to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::to_sparse_bsc(at::IntArrayRef blocksize, c10::optional dense_dim) const { + return at::_ops::to_sparse_bsc::call(const_cast(*this), blocksize, dense_dim); +} + +// aten::_to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor +inline at::Tensor Tensor::_to_sparse_bsc(at::IntArrayRef blocksize, c10::optional dense_dim) const { + return at::_ops::_to_sparse_bsc::call(const_cast(*this), blocksize, dense_dim); +} + +// aten::to_mkldnn(Tensor self, ScalarType? dtype=None) -> Tensor +inline at::Tensor Tensor::to_mkldnn(c10::optional dtype) const { + return at::_ops::to_mkldnn::call(const_cast(*this), dtype); +} + +// aten::dequantize.self(Tensor self) -> Tensor +inline at::Tensor Tensor::dequantize() const { + return at::_ops::dequantize_self::call(const_cast(*this)); +} + +// aten::q_scale(Tensor self) -> float +inline double Tensor::q_scale() const { + return at::_ops::q_scale::call(const_cast(*this)); +} + +// aten::q_zero_point(Tensor self) -> int +inline int64_t Tensor::q_zero_point() const { + return at::_ops::q_zero_point::call(const_cast(*this)); +} + +// aten::q_per_channel_scales(Tensor self) -> Tensor +inline at::Tensor Tensor::q_per_channel_scales() const { + return at::_ops::q_per_channel_scales::call(const_cast(*this)); +} + +// aten::q_per_channel_zero_points(Tensor self) -> Tensor +inline at::Tensor Tensor::q_per_channel_zero_points() const { + return at::_ops::q_per_channel_zero_points::call(const_cast(*this)); +} + +// aten::q_per_channel_axis(Tensor self) -> int +inline int64_t Tensor::q_per_channel_axis() const { + return at::_ops::q_per_channel_axis::call(const_cast(*this)); +} + +// aten::int_repr(Tensor self) -> Tensor +inline at::Tensor Tensor::int_repr() const { + return at::_ops::int_repr::call(const_cast(*this)); +} + +// aten::qscheme(Tensor self) -> QScheme +inline at::QScheme Tensor::qscheme() const { + return at::_ops::qscheme::call(const_cast(*this)); +} + +// aten::_autocast_to_reduced_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) -> Tensor(a) +inline at::Tensor Tensor::_autocast_to_reduced_precision(bool cuda_enabled, bool cpu_enabled, at::ScalarType cuda_dtype, at::ScalarType cpu_dtype) const { + return at::_ops::_autocast_to_reduced_precision::call(const_cast(*this), cuda_enabled, cpu_enabled, cuda_dtype, cpu_dtype); +} + +// aten::_autocast_to_full_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled) -> Tensor(a) +inline at::Tensor Tensor::_autocast_to_full_precision(bool cuda_enabled, bool cpu_enabled) const { + return at::_ops::_autocast_to_full_precision::call(const_cast(*this), cuda_enabled, cpu_enabled); +} + +// aten::to.dtype_layout(Tensor(a) self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) +inline at::Tensor Tensor::to(at::TensorOptions options, bool non_blocking, bool copy, c10::optional memory_format) const { + return at::_ops::to_dtype_layout::call(const_cast(*this), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), non_blocking, copy, c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format)); +} + +// aten::to.dtype_layout(Tensor(a) self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) +inline at::Tensor Tensor::to(c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, bool non_blocking, bool copy, c10::optional memory_format) const { + return at::_ops::to_dtype_layout::call(const_cast(*this), dtype, layout, device, pin_memory, non_blocking, copy, memory_format); +} + +// aten::to.device(Tensor(a) self, Device device, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) +inline at::Tensor Tensor::to(at::Device device, at::ScalarType dtype, bool non_blocking, bool copy, c10::optional memory_format) const { + return at::_ops::to_device::call(const_cast(*this), device, dtype, non_blocking, copy, memory_format); +} + +// aten::to.dtype(Tensor(a) self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) +inline at::Tensor Tensor::to(at::ScalarType dtype, bool non_blocking, bool copy, c10::optional memory_format) const { + return at::_ops::to_dtype::call(const_cast(*this), dtype, non_blocking, copy, memory_format); +} + +// aten::to.other(Tensor(a) self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) +inline at::Tensor Tensor::to(const at::Tensor & other, bool non_blocking, bool copy, c10::optional memory_format) const { + return at::_ops::to_other::call(const_cast(*this), other, non_blocking, copy, memory_format); +} + +// aten::item(Tensor self) -> Scalar +inline at::Scalar Tensor::item() const { + return at::_ops::item::call(const_cast(*this)); +} + +// aten::set_.source_Storage(Tensor(a!) self, Storage source) -> Tensor(a!) +inline at::Tensor & Tensor::set_(at::Storage source) const { + return at::_ops::set__source_Storage::call(const_cast(*this), source); +} + +// aten::set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!) +inline at::Tensor & Tensor::set_(at::Storage source, int64_t storage_offset, at::IntArrayRef size, at::IntArrayRef stride) const { + return at::_ops::set__source_Storage_storage_offset::call(const_cast(*this), source, storage_offset, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride)); +} + +// aten::set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!) +inline at::Tensor & Tensor::set__symint(at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride) const { + return at::_ops::set__source_Storage_storage_offset::call(const_cast(*this), source, storage_offset, size, stride); +} + +// aten::set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!) +inline at::Tensor & Tensor::set_(const at::Tensor & source, int64_t storage_offset, at::IntArrayRef size, at::IntArrayRef stride) const { + return at::_ops::set__source_Tensor_storage_offset::call(const_cast(*this), source, storage_offset, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride)); +} + +// aten::set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!) +inline at::Tensor & Tensor::set__symint(const at::Tensor & source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride) const { + return at::_ops::set__source_Tensor_storage_offset::call(const_cast(*this), source, storage_offset, size, stride); +} + +// aten::set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!) +inline at::Tensor & Tensor::set_(const at::Tensor & source) const { + return at::_ops::set__source_Tensor::call(const_cast(*this), source); +} + +// aten::set_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::set_() const { + return at::_ops::set_::call(const_cast(*this)); +} + +// aten::is_set_to(Tensor self, Tensor tensor) -> bool +inline bool Tensor::is_set_to(const at::Tensor & tensor) const { + return at::_ops::is_set_to::call(const_cast(*this), tensor); +} + +// aten::masked_fill_.Scalar(Tensor(a!) self, Tensor mask, Scalar value) -> Tensor(a!) +inline at::Tensor & Tensor::masked_fill_(const at::Tensor & mask, const at::Scalar & value) const { + return at::_ops::masked_fill__Scalar::call(const_cast(*this), mask, value); +} + +// aten::masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor +inline at::Tensor Tensor::masked_fill(const at::Tensor & mask, const at::Scalar & value) const { + return at::_ops::masked_fill_Scalar::call(const_cast(*this), mask, value); +} + +// aten::masked_fill_.Tensor(Tensor(a!) self, Tensor mask, Tensor value) -> Tensor(a!) +inline at::Tensor & Tensor::masked_fill_(const at::Tensor & mask, const at::Tensor & value) const { + return at::_ops::masked_fill__Tensor::call(const_cast(*this), mask, value); +} + +// aten::masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor +inline at::Tensor Tensor::masked_fill(const at::Tensor & mask, const at::Tensor & value) const { + return at::_ops::masked_fill_Tensor::call(const_cast(*this), mask, value); +} + +// aten::masked_scatter_(Tensor(a!) self, Tensor mask, Tensor source) -> Tensor(a!) +inline at::Tensor & Tensor::masked_scatter_(const at::Tensor & mask, const at::Tensor & source) const { + return at::_ops::masked_scatter_::call(const_cast(*this), mask, source); +} + +// aten::masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor +inline at::Tensor Tensor::masked_scatter(const at::Tensor & mask, const at::Tensor & source) const { + return at::_ops::masked_scatter::call(const_cast(*this), mask, source); +} + +// aten::view(Tensor(a) self, SymInt[] size) -> Tensor(a) +inline at::Tensor Tensor::view(at::IntArrayRef size) const { + return at::_ops::view::call(const_cast(*this), c10::fromIntArrayRefSlow(size)); +} + +// aten::view(Tensor(a) self, SymInt[] size) -> Tensor(a) +inline at::Tensor Tensor::view_symint(c10::SymIntArrayRef size) const { + return at::_ops::view::call(const_cast(*this), size); +} + +// aten::view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a) +inline at::Tensor Tensor::view(at::ScalarType dtype) const { + return at::_ops::view_dtype::call(const_cast(*this), dtype); +} + +// aten::put_(Tensor(a!) self, Tensor index, Tensor source, bool accumulate=False) -> Tensor(a!) +inline at::Tensor & Tensor::put_(const at::Tensor & index, const at::Tensor & source, bool accumulate) const { + return at::_ops::put_::call(const_cast(*this), index, source, accumulate); +} + +// aten::put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor +inline at::Tensor Tensor::put(const at::Tensor & index, const at::Tensor & source, bool accumulate) const { + return at::_ops::put::call(const_cast(*this), index, source, accumulate); +} + +// aten::index_add_(Tensor(a!) self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::index_add_(int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha) const { + return at::_ops::index_add_::call(const_cast(*this), dim, index, source, alpha); +} + +// aten::index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::index_add(int64_t dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha) const { + return at::_ops::index_add::call(const_cast(*this), dim, index, source, alpha); +} + +// aten::index_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::index_add(at::Dimname dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha) const { + return at::_ops::index_add_dimname::call(const_cast(*this), dim, index, source, alpha); +} + +// aten::index_reduce_(Tensor(a!) self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor(a!) +inline at::Tensor & Tensor::index_reduce_(int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self) const { + return at::_ops::index_reduce_::call(const_cast(*this), dim, index, source, reduce, include_self); +} + +// aten::index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor +inline at::Tensor Tensor::index_reduce(int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self) const { + return at::_ops::index_reduce::call(const_cast(*this), dim, index, source, reduce, include_self); +} + +// aten::index_fill_.int_Scalar(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!) +inline at::Tensor & Tensor::index_fill_(int64_t dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::index_fill__int_Scalar::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor +inline at::Tensor Tensor::index_fill(int64_t dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::index_fill_int_Scalar::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill_.int_Tensor(Tensor(a!) self, int dim, Tensor index, Tensor value) -> Tensor(a!) +inline at::Tensor & Tensor::index_fill_(int64_t dim, const at::Tensor & index, const at::Tensor & value) const { + return at::_ops::index_fill__int_Tensor::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor +inline at::Tensor Tensor::index_fill(int64_t dim, const at::Tensor & index, const at::Tensor & value) const { + return at::_ops::index_fill_int_Tensor::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill_.Dimname_Scalar(Tensor(a!) self, Dimname dim, Tensor index, Scalar value) -> Tensor(a!) +inline at::Tensor & Tensor::index_fill_(at::Dimname dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::index_fill__Dimname_Scalar::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill_.Dimname_Tensor(Tensor(a!) self, Dimname dim, Tensor index, Tensor value) -> Tensor(a!) +inline at::Tensor & Tensor::index_fill_(at::Dimname dim, const at::Tensor & index, const at::Tensor & value) const { + return at::_ops::index_fill__Dimname_Tensor::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill.Dimname_Scalar(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor +inline at::Tensor Tensor::index_fill(at::Dimname dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::index_fill_Dimname_Scalar::call(const_cast(*this), dim, index, value); +} + +// aten::index_fill.Dimname_Tensor(Tensor self, Dimname dim, Tensor index, Tensor value) -> Tensor +inline at::Tensor Tensor::index_fill(at::Dimname dim, const at::Tensor & index, const at::Tensor & value) const { + return at::_ops::index_fill_Dimname_Tensor::call(const_cast(*this), dim, index, value); +} + +// aten::scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor +inline at::Tensor Tensor::scatter(int64_t dim, const at::Tensor & index, const at::Tensor & src) const { + return at::_ops::scatter_src::call(const_cast(*this), dim, index, src); +} + +// aten::scatter_.src(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!) +inline at::Tensor & Tensor::scatter_(int64_t dim, const at::Tensor & index, const at::Tensor & src) const { + return at::_ops::scatter__src::call(const_cast(*this), dim, index, src); +} + +// aten::scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor +inline at::Tensor Tensor::scatter(int64_t dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::scatter_value::call(const_cast(*this), dim, index, value); +} + +// aten::scatter_.value(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!) +inline at::Tensor & Tensor::scatter_(int64_t dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::scatter__value::call(const_cast(*this), dim, index, value); +} + +// aten::scatter.reduce(Tensor self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor +inline at::Tensor Tensor::scatter(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce) const { + return at::_ops::scatter_reduce::call(const_cast(*this), dim, index, src, reduce); +} + +// aten::scatter_.reduce(Tensor(a!) self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor(a!) +inline at::Tensor & Tensor::scatter_(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce) const { + return at::_ops::scatter__reduce::call(const_cast(*this), dim, index, src, reduce); +} + +// aten::scatter.value_reduce(Tensor self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor +inline at::Tensor Tensor::scatter(int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce) const { + return at::_ops::scatter_value_reduce::call(const_cast(*this), dim, index, value, reduce); +} + +// aten::scatter_.value_reduce(Tensor(a!) self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor(a!) +inline at::Tensor & Tensor::scatter_(int64_t dim, const at::Tensor & index, const at::Scalar & value, c10::string_view reduce) const { + return at::_ops::scatter__value_reduce::call(const_cast(*this), dim, index, value, reduce); +} + +// aten::scatter.dimname_src(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor +inline at::Tensor Tensor::scatter(at::Dimname dim, const at::Tensor & index, const at::Tensor & src) const { + return at::_ops::scatter_dimname_src::call(const_cast(*this), dim, index, src); +} + +// aten::scatter.dimname_value(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor +inline at::Tensor Tensor::scatter(at::Dimname dim, const at::Tensor & index, const at::Scalar & value) const { + return at::_ops::scatter_dimname_value::call(const_cast(*this), dim, index, value); +} + +// aten::scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor +inline at::Tensor Tensor::scatter_add(int64_t dim, const at::Tensor & index, const at::Tensor & src) const { + return at::_ops::scatter_add::call(const_cast(*this), dim, index, src); +} + +// aten::scatter_add_(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!) +inline at::Tensor & Tensor::scatter_add_(int64_t dim, const at::Tensor & index, const at::Tensor & src) const { + return at::_ops::scatter_add_::call(const_cast(*this), dim, index, src); +} + +// aten::scatter_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor +inline at::Tensor Tensor::scatter_add(at::Dimname dim, const at::Tensor & index, const at::Tensor & src) const { + return at::_ops::scatter_add_dimname::call(const_cast(*this), dim, index, src); +} + +// aten::scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor +inline at::Tensor Tensor::scatter_reduce(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self) const { + return at::_ops::scatter_reduce_two::call(const_cast(*this), dim, index, src, reduce, include_self); +} + +// aten::scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor(a!) +inline at::Tensor & Tensor::scatter_reduce_(int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self) const { + return at::_ops::scatter_reduce__two::call(const_cast(*this), dim, index, src, reduce, include_self); +} + +// aten::eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::eq_(const at::Scalar & other) const { + return at::_ops::eq__Scalar::call(const_cast(*this), other); +} + +// aten::eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::eq_(const at::Tensor & other) const { + return at::_ops::eq__Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_and.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::bitwise_and(const at::Scalar & other) const { + return at::_ops::bitwise_and_Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_and.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::bitwise_and(const at::Tensor & other) const { + return at::_ops::bitwise_and_Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_and_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_and_(const at::Scalar & other) const { + return at::_ops::bitwise_and__Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_and_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_and_(const at::Tensor & other) const { + return at::_ops::bitwise_and__Tensor::call(const_cast(*this), other); +} + +// aten::__and__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::__and__(const at::Scalar & other) const { + return at::_ops::__and___Scalar::call(const_cast(*this), other); +} + +// aten::__and__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::__and__(const at::Tensor & other) const { + return at::_ops::__and___Tensor::call(const_cast(*this), other); +} + +// aten::__iand__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::__iand__(const at::Scalar & other) const { + return at::_ops::__iand___Scalar::call(const_cast(*this), other); +} + +// aten::__iand__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::__iand__(const at::Tensor & other) const { + return at::_ops::__iand___Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_or.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::bitwise_or(const at::Scalar & other) const { + return at::_ops::bitwise_or_Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_or.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::bitwise_or(const at::Tensor & other) const { + return at::_ops::bitwise_or_Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_or_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_or_(const at::Scalar & other) const { + return at::_ops::bitwise_or__Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_or_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_or_(const at::Tensor & other) const { + return at::_ops::bitwise_or__Tensor::call(const_cast(*this), other); +} + +// aten::__or__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::__or__(const at::Scalar & other) const { + return at::_ops::__or___Scalar::call(const_cast(*this), other); +} + +// aten::__or__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::__or__(const at::Tensor & other) const { + return at::_ops::__or___Tensor::call(const_cast(*this), other); +} + +// aten::__ior__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::__ior__(const at::Scalar & other) const { + return at::_ops::__ior___Scalar::call(const_cast(*this), other); +} + +// aten::__ior__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::__ior__(const at::Tensor & other) const { + return at::_ops::__ior___Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::bitwise_xor(const at::Scalar & other) const { + return at::_ops::bitwise_xor_Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::bitwise_xor(const at::Tensor & other) const { + return at::_ops::bitwise_xor_Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_xor_(const at::Scalar & other) const { + return at::_ops::bitwise_xor__Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_xor_(const at::Tensor & other) const { + return at::_ops::bitwise_xor__Tensor::call(const_cast(*this), other); +} + +// aten::__xor__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::__xor__(const at::Scalar & other) const { + return at::_ops::__xor___Scalar::call(const_cast(*this), other); +} + +// aten::__xor__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::__xor__(const at::Tensor & other) const { + return at::_ops::__xor___Tensor::call(const_cast(*this), other); +} + +// aten::__ixor__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::__ixor__(const at::Scalar & other) const { + return at::_ops::__ixor___Scalar::call(const_cast(*this), other); +} + +// aten::__ixor__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::__ixor__(const at::Tensor & other) const { + return at::_ops::__ixor___Tensor::call(const_cast(*this), other); +} + +// aten::__lshift__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::__lshift__(const at::Scalar & other) const { + return at::_ops::__lshift___Scalar::call(const_cast(*this), other); +} + +// aten::__lshift__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::__lshift__(const at::Tensor & other) const { + return at::_ops::__lshift___Tensor::call(const_cast(*this), other); +} + +// aten::__ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::__ilshift__(const at::Scalar & other) const { + return at::_ops::__ilshift___Scalar::call(const_cast(*this), other); +} + +// aten::__ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::__ilshift__(const at::Tensor & other) const { + return at::_ops::__ilshift___Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_left_shift.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::bitwise_left_shift(const at::Tensor & other) const { + return at::_ops::bitwise_left_shift_Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_left_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_left_shift_(const at::Tensor & other) const { + return at::_ops::bitwise_left_shift__Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_left_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::bitwise_left_shift(const at::Scalar & other) const { + return at::_ops::bitwise_left_shift_Tensor_Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_left_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_left_shift_(const at::Scalar & other) const { + return at::_ops::bitwise_left_shift__Tensor_Scalar::call(const_cast(*this), other); +} + +// aten::__rshift__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::__rshift__(const at::Scalar & other) const { + return at::_ops::__rshift___Scalar::call(const_cast(*this), other); +} + +// aten::__rshift__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::__rshift__(const at::Tensor & other) const { + return at::_ops::__rshift___Tensor::call(const_cast(*this), other); +} + +// aten::__irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::__irshift__(const at::Scalar & other) const { + return at::_ops::__irshift___Scalar::call(const_cast(*this), other); +} + +// aten::__irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::__irshift__(const at::Tensor & other) const { + return at::_ops::__irshift___Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_right_shift.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::bitwise_right_shift(const at::Tensor & other) const { + return at::_ops::bitwise_right_shift_Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_right_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_right_shift_(const at::Tensor & other) const { + return at::_ops::bitwise_right_shift__Tensor::call(const_cast(*this), other); +} + +// aten::bitwise_right_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::bitwise_right_shift(const at::Scalar & other) const { + return at::_ops::bitwise_right_shift_Tensor_Scalar::call(const_cast(*this), other); +} + +// aten::bitwise_right_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::bitwise_right_shift_(const at::Scalar & other) const { + return at::_ops::bitwise_right_shift__Tensor_Scalar::call(const_cast(*this), other); +} + +// aten::tril_(Tensor(a!) self, int diagonal=0) -> Tensor(a!) +inline at::Tensor & Tensor::tril_(int64_t diagonal) const { + return at::_ops::tril_::call(const_cast(*this), diagonal); +} + +// aten::triu_(Tensor(a!) self, int diagonal=0) -> Tensor(a!) +inline at::Tensor & Tensor::triu_(int64_t diagonal) const { + return at::_ops::triu_::call(const_cast(*this), diagonal); +} + +// aten::digamma_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::digamma_() const { + return at::_ops::digamma_::call(const_cast(*this)); +} + +// aten::lerp_.Scalar(Tensor(a!) self, Tensor end, Scalar weight) -> Tensor(a!) +inline at::Tensor & Tensor::lerp_(const at::Tensor & end, const at::Scalar & weight) const { + return at::_ops::lerp__Scalar::call(const_cast(*this), end, weight); +} + +// aten::lerp_.Tensor(Tensor(a!) self, Tensor end, Tensor weight) -> Tensor(a!) +inline at::Tensor & Tensor::lerp_(const at::Tensor & end, const at::Tensor & weight) const { + return at::_ops::lerp__Tensor::call(const_cast(*this), end, weight); +} + +// aten::addbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) +inline at::Tensor & Tensor::addbmm_(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addbmm_::call(const_cast(*this), batch1, batch2, beta, alpha); +} + +// aten::addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor +inline at::Tensor Tensor::addbmm(const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha) const { + return at::_ops::addbmm::call(const_cast(*this), batch1, batch2, beta, alpha); +} + +// aten::random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::random_(int64_t from, c10::optional to, c10::optional generator) const { + return at::_ops::random__from::call(const_cast(*this), from, to, generator); +} + +// aten::random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::random_(int64_t to, c10::optional generator) const { + return at::_ops::random__to::call(const_cast(*this), to, generator); +} + +// aten::random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::random_(c10::optional generator) const { + return at::_ops::random_::call(const_cast(*this), generator); +} + +// aten::uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::uniform_(double from, double to, c10::optional generator) const { + return at::_ops::uniform_::call(const_cast(*this), from, to, generator); +} + +// aten::cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::cauchy_(double median, double sigma, c10::optional generator) const { + return at::_ops::cauchy_::call(const_cast(*this), median, sigma, generator); +} + +// aten::log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::log_normal_(double mean, double std, c10::optional generator) const { + return at::_ops::log_normal_::call(const_cast(*this), mean, std, generator); +} + +// aten::exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::exponential_(double lambd, c10::optional generator) const { + return at::_ops::exponential_::call(const_cast(*this), lambd, generator); +} + +// aten::geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::geometric_(double p, c10::optional generator) const { + return at::_ops::geometric_::call(const_cast(*this), p, generator); +} + +// aten::diag(Tensor self, int diagonal=0) -> Tensor +inline at::Tensor Tensor::diag(int64_t diagonal) const { + return at::_ops::diag::call(const_cast(*this), diagonal); +} + +// aten::cross(Tensor self, Tensor other, int? dim=None) -> Tensor +inline at::Tensor Tensor::cross(const at::Tensor & other, c10::optional dim) const { + return at::_ops::cross::call(const_cast(*this), other, dim); +} + +// aten::triu(Tensor self, int diagonal=0) -> Tensor +inline at::Tensor Tensor::triu(int64_t diagonal) const { + return at::_ops::triu::call(const_cast(*this), diagonal); +} + +// aten::tril(Tensor self, int diagonal=0) -> Tensor +inline at::Tensor Tensor::tril(int64_t diagonal) const { + return at::_ops::tril::call(const_cast(*this), diagonal); +} + +// aten::trace(Tensor self) -> Tensor +inline at::Tensor Tensor::trace() const { + return at::_ops::trace::call(const_cast(*this)); +} + +// aten::ne.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::ne(const at::Scalar & other) const { + return at::_ops::ne_Scalar::call(const_cast(*this), other); +} + +// aten::ne.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::ne(const at::Tensor & other) const { + return at::_ops::ne_Tensor::call(const_cast(*this), other); +} + +// aten::ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::ne_(const at::Scalar & other) const { + return at::_ops::ne__Scalar::call(const_cast(*this), other); +} + +// aten::ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::ne_(const at::Tensor & other) const { + return at::_ops::ne__Tensor::call(const_cast(*this), other); +} + +// aten::not_equal.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::not_equal(const at::Scalar & other) const { + return at::_ops::not_equal_Scalar::call(const_cast(*this), other); +} + +// aten::not_equal.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::not_equal(const at::Tensor & other) const { + return at::_ops::not_equal_Tensor::call(const_cast(*this), other); +} + +// aten::not_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::not_equal_(const at::Scalar & other) const { + return at::_ops::not_equal__Scalar::call(const_cast(*this), other); +} + +// aten::not_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::not_equal_(const at::Tensor & other) const { + return at::_ops::not_equal__Tensor::call(const_cast(*this), other); +} + +// aten::eq.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::eq(const at::Scalar & other) const { + return at::_ops::eq_Scalar::call(const_cast(*this), other); +} + +// aten::eq.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::eq(const at::Tensor & other) const { + return at::_ops::eq_Tensor::call(const_cast(*this), other); +} + +// aten::ge.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::ge(const at::Scalar & other) const { + return at::_ops::ge_Scalar::call(const_cast(*this), other); +} + +// aten::ge.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::ge(const at::Tensor & other) const { + return at::_ops::ge_Tensor::call(const_cast(*this), other); +} + +// aten::ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::ge_(const at::Scalar & other) const { + return at::_ops::ge__Scalar::call(const_cast(*this), other); +} + +// aten::ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::ge_(const at::Tensor & other) const { + return at::_ops::ge__Tensor::call(const_cast(*this), other); +} + +// aten::greater_equal.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::greater_equal(const at::Scalar & other) const { + return at::_ops::greater_equal_Scalar::call(const_cast(*this), other); +} + +// aten::greater_equal.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::greater_equal(const at::Tensor & other) const { + return at::_ops::greater_equal_Tensor::call(const_cast(*this), other); +} + +// aten::greater_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::greater_equal_(const at::Scalar & other) const { + return at::_ops::greater_equal__Scalar::call(const_cast(*this), other); +} + +// aten::greater_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::greater_equal_(const at::Tensor & other) const { + return at::_ops::greater_equal__Tensor::call(const_cast(*this), other); +} + +// aten::le.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::le(const at::Scalar & other) const { + return at::_ops::le_Scalar::call(const_cast(*this), other); +} + +// aten::le.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::le(const at::Tensor & other) const { + return at::_ops::le_Tensor::call(const_cast(*this), other); +} + +// aten::le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::le_(const at::Scalar & other) const { + return at::_ops::le__Scalar::call(const_cast(*this), other); +} + +// aten::le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::le_(const at::Tensor & other) const { + return at::_ops::le__Tensor::call(const_cast(*this), other); +} + +// aten::less_equal.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::less_equal(const at::Scalar & other) const { + return at::_ops::less_equal_Scalar::call(const_cast(*this), other); +} + +// aten::less_equal.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::less_equal(const at::Tensor & other) const { + return at::_ops::less_equal_Tensor::call(const_cast(*this), other); +} + +// aten::less_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::less_equal_(const at::Scalar & other) const { + return at::_ops::less_equal__Scalar::call(const_cast(*this), other); +} + +// aten::less_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::less_equal_(const at::Tensor & other) const { + return at::_ops::less_equal__Tensor::call(const_cast(*this), other); +} + +// aten::gt.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::gt(const at::Scalar & other) const { + return at::_ops::gt_Scalar::call(const_cast(*this), other); +} + +// aten::gt.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::gt(const at::Tensor & other) const { + return at::_ops::gt_Tensor::call(const_cast(*this), other); +} + +// aten::gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::gt_(const at::Scalar & other) const { + return at::_ops::gt__Scalar::call(const_cast(*this), other); +} + +// aten::gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::gt_(const at::Tensor & other) const { + return at::_ops::gt__Tensor::call(const_cast(*this), other); +} + +// aten::greater.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::greater(const at::Scalar & other) const { + return at::_ops::greater_Scalar::call(const_cast(*this), other); +} + +// aten::greater.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::greater(const at::Tensor & other) const { + return at::_ops::greater_Tensor::call(const_cast(*this), other); +} + +// aten::greater_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::greater_(const at::Scalar & other) const { + return at::_ops::greater__Scalar::call(const_cast(*this), other); +} + +// aten::greater_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::greater_(const at::Tensor & other) const { + return at::_ops::greater__Tensor::call(const_cast(*this), other); +} + +// aten::lt.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::lt(const at::Scalar & other) const { + return at::_ops::lt_Scalar::call(const_cast(*this), other); +} + +// aten::lt.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::lt(const at::Tensor & other) const { + return at::_ops::lt_Tensor::call(const_cast(*this), other); +} + +// aten::lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::lt_(const at::Scalar & other) const { + return at::_ops::lt__Scalar::call(const_cast(*this), other); +} + +// aten::lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::lt_(const at::Tensor & other) const { + return at::_ops::lt__Tensor::call(const_cast(*this), other); +} + +// aten::less.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::less(const at::Scalar & other) const { + return at::_ops::less_Scalar::call(const_cast(*this), other); +} + +// aten::less.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::less(const at::Tensor & other) const { + return at::_ops::less_Tensor::call(const_cast(*this), other); +} + +// aten::less_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::less_(const at::Scalar & other) const { + return at::_ops::less__Scalar::call(const_cast(*this), other); +} + +// aten::less_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::less_(const at::Tensor & other) const { + return at::_ops::less__Tensor::call(const_cast(*this), other); +} + +// aten::take(Tensor self, Tensor index) -> Tensor +inline at::Tensor Tensor::take(const at::Tensor & index) const { + return at::_ops::take::call(const_cast(*this), index); +} + +// aten::take_along_dim(Tensor self, Tensor indices, int? dim=None) -> Tensor +inline at::Tensor Tensor::take_along_dim(const at::Tensor & indices, c10::optional dim) const { + return at::_ops::take_along_dim::call(const_cast(*this), indices, dim); +} + +// aten::index_select(Tensor self, int dim, Tensor index) -> Tensor +inline at::Tensor Tensor::index_select(int64_t dim, const at::Tensor & index) const { + return at::_ops::index_select::call(const_cast(*this), dim, index); +} + +// aten::index_select.dimname(Tensor self, Dimname dim, Tensor index) -> Tensor +inline at::Tensor Tensor::index_select(at::Dimname dim, const at::Tensor & index) const { + return at::_ops::index_select_dimname::call(const_cast(*this), dim, index); +} + +// aten::masked_select(Tensor self, Tensor mask) -> Tensor +inline at::Tensor Tensor::masked_select(const at::Tensor & mask) const { + return at::_ops::masked_select::call(const_cast(*this), mask); +} + +// aten::nonzero(Tensor self) -> Tensor +inline at::Tensor Tensor::nonzero() const { + return at::_ops::nonzero::call(const_cast(*this)); +} + +// aten::nonzero_static(Tensor self, *, int size, int fill_value=-1) -> Tensor +inline at::Tensor Tensor::nonzero_static(int64_t size, int64_t fill_value) const { + return at::_ops::nonzero_static::call(const_cast(*this), size, fill_value); +} + +// aten::nonzero_numpy(Tensor self) -> Tensor[] +inline ::std::vector Tensor::nonzero_numpy() const { + return at::_ops::nonzero_numpy::call(const_cast(*this)); +} + +// aten::argwhere(Tensor self) -> Tensor +inline at::Tensor Tensor::argwhere() const { + return at::_ops::argwhere::call(const_cast(*this)); +} + +// aten::gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor +inline at::Tensor Tensor::gather(int64_t dim, const at::Tensor & index, bool sparse_grad) const { + return at::_ops::gather::call(const_cast(*this), dim, index, sparse_grad); +} + +// aten::gather.dimname(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False) -> Tensor +inline at::Tensor Tensor::gather(at::Dimname dim, const at::Tensor & index, bool sparse_grad) const { + return at::_ops::gather_dimname::call(const_cast(*this), dim, index, sparse_grad); +} + +// aten::addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor +inline at::Tensor Tensor::addcmul(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value) const { + return at::_ops::addcmul::call(const_cast(*this), tensor1, tensor2, value); +} + +// aten::addcmul_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) +inline at::Tensor & Tensor::addcmul_(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value) const { + return at::_ops::addcmul_::call(const_cast(*this), tensor1, tensor2, value); +} + +// aten::addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor +inline at::Tensor Tensor::addcdiv(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value) const { + return at::_ops::addcdiv::call(const_cast(*this), tensor1, tensor2, value); +} + +// aten::addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) +inline at::Tensor & Tensor::addcdiv_(const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value) const { + return at::_ops::addcdiv_::call(const_cast(*this), tensor1, tensor2, value); +} + +// aten::triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient) +inline ::std::tuple Tensor::triangular_solve(const at::Tensor & A, bool upper, bool transpose, bool unitriangular) const { + return at::_ops::triangular_solve::call(const_cast(*this), A, upper, transpose, unitriangular); +} + +// aten::svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V) +inline ::std::tuple Tensor::svd(bool some, bool compute_uv) const { + return at::_ops::svd::call(const_cast(*this), some, compute_uv); +} + +// aten::swapaxes(Tensor(a) self, int axis0, int axis1) -> Tensor(a) +inline at::Tensor Tensor::swapaxes(int64_t axis0, int64_t axis1) const { + return at::_ops::swapaxes::call(const_cast(*this), axis0, axis1); +} + +// aten::swapaxes_(Tensor(a!) self, int axis0, int axis1) -> Tensor(a!) +inline at::Tensor & Tensor::swapaxes_(int64_t axis0, int64_t axis1) const { + return at::_ops::swapaxes_::call(const_cast(*this), axis0, axis1); +} + +// aten::swapdims(Tensor(a) self, int dim0, int dim1) -> Tensor(a) +inline at::Tensor Tensor::swapdims(int64_t dim0, int64_t dim1) const { + return at::_ops::swapdims::call(const_cast(*this), dim0, dim1); +} + +// aten::swapdims_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) +inline at::Tensor & Tensor::swapdims_(int64_t dim0, int64_t dim1) const { + return at::_ops::swapdims_::call(const_cast(*this), dim0, dim1); +} + +// aten::cholesky(Tensor self, bool upper=False) -> Tensor +inline at::Tensor Tensor::cholesky(bool upper) const { + return at::_ops::cholesky::call(const_cast(*this), upper); +} + +// aten::cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor +inline at::Tensor Tensor::cholesky_solve(const at::Tensor & input2, bool upper) const { + return at::_ops::cholesky_solve::call(const_cast(*this), input2, upper); +} + +// aten::cholesky_inverse(Tensor self, bool upper=False) -> Tensor +inline at::Tensor Tensor::cholesky_inverse(bool upper) const { + return at::_ops::cholesky_inverse::call(const_cast(*this), upper); +} + +// aten::qr(Tensor self, bool some=True) -> (Tensor Q, Tensor R) +inline ::std::tuple Tensor::qr(bool some) const { + return at::_ops::qr::call(const_cast(*this), some); +} + +// aten::geqrf(Tensor self) -> (Tensor a, Tensor tau) +inline ::std::tuple Tensor::geqrf() const { + return at::_ops::geqrf::call(const_cast(*this)); +} + +// aten::orgqr(Tensor self, Tensor input2) -> Tensor +inline at::Tensor Tensor::orgqr(const at::Tensor & input2) const { + return at::_ops::orgqr::call(const_cast(*this), input2); +} + +// aten::ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor +inline at::Tensor Tensor::ormqr(const at::Tensor & input2, const at::Tensor & input3, bool left, bool transpose) const { + return at::_ops::ormqr::call(const_cast(*this), input2, input3, left, transpose); +} + +// aten::lu_solve(Tensor self, Tensor LU_data, Tensor LU_pivots) -> Tensor +inline at::Tensor Tensor::lu_solve(const at::Tensor & LU_data, const at::Tensor & LU_pivots) const { + return at::_ops::lu_solve::call(const_cast(*this), LU_data, LU_pivots); +} + +// aten::multinomial(Tensor self, int num_samples, bool replacement=False, *, Generator? generator=None) -> Tensor +inline at::Tensor Tensor::multinomial(int64_t num_samples, bool replacement, c10::optional generator) const { + return at::_ops::multinomial::call(const_cast(*this), num_samples, replacement, generator); +} + +// aten::lgamma_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::lgamma_() const { + return at::_ops::lgamma_::call(const_cast(*this)); +} + +// aten::lgamma(Tensor self) -> Tensor +inline at::Tensor Tensor::lgamma() const { + return at::_ops::lgamma::call(const_cast(*this)); +} + +// aten::digamma(Tensor self) -> Tensor +inline at::Tensor Tensor::digamma() const { + return at::_ops::digamma::call(const_cast(*this)); +} + +// aten::polygamma(int n, Tensor self) -> Tensor +inline at::Tensor Tensor::polygamma(int64_t n) const { + return at::_ops::polygamma::call(n, const_cast(*this)); +} + +// aten::polygamma_(Tensor(a!) self, int n) -> Tensor(a!) +inline at::Tensor & Tensor::polygamma_(int64_t n) const { + return at::_ops::polygamma_::call(const_cast(*this), n); +} + +// aten::erfinv(Tensor self) -> Tensor +inline at::Tensor Tensor::erfinv() const { + return at::_ops::erfinv::call(const_cast(*this)); +} + +// aten::erfinv_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::erfinv_() const { + return at::_ops::erfinv_::call(const_cast(*this)); +} + +// aten::i0(Tensor self) -> Tensor +inline at::Tensor Tensor::i0() const { + return at::_ops::i0::call(const_cast(*this)); +} + +// aten::i0_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::i0_() const { + return at::_ops::i0_::call(const_cast(*this)); +} + +// aten::sign(Tensor self) -> Tensor +inline at::Tensor Tensor::sign() const { + return at::_ops::sign::call(const_cast(*this)); +} + +// aten::sign_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & Tensor::sign_() const { + return at::_ops::sign_::call(const_cast(*this)); +} + +// aten::signbit(Tensor self) -> Tensor +inline at::Tensor Tensor::signbit() const { + return at::_ops::signbit::call(const_cast(*this)); +} + +// aten::dist(Tensor self, Tensor other, Scalar p=2) -> Tensor +inline at::Tensor Tensor::dist(const at::Tensor & other, const at::Scalar & p) const { + return at::_ops::dist::call(const_cast(*this), other, p); +} + +// aten::atan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::atan2_(const at::Tensor & other) const { + return at::_ops::atan2_::call(const_cast(*this), other); +} + +// aten::atan2(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::atan2(const at::Tensor & other) const { + return at::_ops::atan2::call(const_cast(*this), other); +} + +// aten::arctan2(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::arctan2(const at::Tensor & other) const { + return at::_ops::arctan2::call(const_cast(*this), other); +} + +// aten::arctan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::arctan2_(const at::Tensor & other) const { + return at::_ops::arctan2_::call(const_cast(*this), other); +} + +// aten::lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor +inline at::Tensor Tensor::lerp(const at::Tensor & end, const at::Scalar & weight) const { + return at::_ops::lerp_Scalar::call(const_cast(*this), end, weight); +} + +// aten::lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor +inline at::Tensor Tensor::lerp(const at::Tensor & end, const at::Tensor & weight) const { + return at::_ops::lerp_Tensor::call(const_cast(*this), end, weight); +} + +// aten::histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor +inline at::Tensor Tensor::histc(int64_t bins, const at::Scalar & min, const at::Scalar & max) const { + return at::_ops::histc::call(const_cast(*this), bins, min, max); +} + +// aten::histogram.bins_tensor(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges) +inline ::std::tuple Tensor::histogram(const at::Tensor & bins, const c10::optional & weight, bool density) const { + return at::_ops::histogram_bins_tensor::call(const_cast(*this), bins, weight, density); +} + +// aten::histogram.bin_ct(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges) +inline ::std::tuple Tensor::histogram(int64_t bins, c10::optional> range, const c10::optional & weight, bool density) const { + return at::_ops::histogram_bin_ct::call(const_cast(*this), bins, range, weight, density); +} + +// aten::fmod.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::fmod(const at::Scalar & other) const { + return at::_ops::fmod_Scalar::call(const_cast(*this), other); +} + +// aten::fmod_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::fmod_(const at::Scalar & other) const { + return at::_ops::fmod__Scalar::call(const_cast(*this), other); +} + +// aten::fmod.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::fmod(const at::Tensor & other) const { + return at::_ops::fmod_Tensor::call(const_cast(*this), other); +} + +// aten::fmod_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::fmod_(const at::Tensor & other) const { + return at::_ops::fmod__Tensor::call(const_cast(*this), other); +} + +// aten::hypot(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::hypot(const at::Tensor & other) const { + return at::_ops::hypot::call(const_cast(*this), other); +} + +// aten::hypot_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::hypot_(const at::Tensor & other) const { + return at::_ops::hypot_::call(const_cast(*this), other); +} + +// aten::igamma(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::igamma(const at::Tensor & other) const { + return at::_ops::igamma::call(const_cast(*this), other); +} + +// aten::igamma_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::igamma_(const at::Tensor & other) const { + return at::_ops::igamma_::call(const_cast(*this), other); +} + +// aten::igammac(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::igammac(const at::Tensor & other) const { + return at::_ops::igammac::call(const_cast(*this), other); +} + +// aten::igammac_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::igammac_(const at::Tensor & other) const { + return at::_ops::igammac_::call(const_cast(*this), other); +} + +// aten::nextafter(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::nextafter(const at::Tensor & other) const { + return at::_ops::nextafter::call(const_cast(*this), other); +} + +// aten::nextafter_(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::nextafter_(const at::Tensor & other) const { + return at::_ops::nextafter_::call(const_cast(*this), other); +} + +// aten::remainder.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor Tensor::remainder(const at::Scalar & other) const { + return at::_ops::remainder_Scalar::call(const_cast(*this), other); +} + +// aten::remainder_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) +inline at::Tensor & Tensor::remainder_(const at::Scalar & other) const { + return at::_ops::remainder__Scalar::call(const_cast(*this), other); +} + +// aten::remainder.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::remainder(const at::Tensor & other) const { + return at::_ops::remainder_Tensor::call(const_cast(*this), other); +} + +// aten::remainder_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) +inline at::Tensor & Tensor::remainder_(const at::Tensor & other) const { + return at::_ops::remainder__Tensor::call(const_cast(*this), other); +} + +// aten::min(Tensor self) -> Tensor +inline at::Tensor Tensor::min() const { + return at::_ops::min::call(const_cast(*this)); +} + +// aten::fmin(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::fmin(const at::Tensor & other) const { + return at::_ops::fmin::call(const_cast(*this), other); +} + +// aten::max(Tensor self) -> Tensor +inline at::Tensor Tensor::max() const { + return at::_ops::max::call(const_cast(*this)); +} + +// aten::fmax(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::fmax(const at::Tensor & other) const { + return at::_ops::fmax::call(const_cast(*this), other); +} + +// aten::maximum(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::maximum(const at::Tensor & other) const { + return at::_ops::maximum::call(const_cast(*this), other); +} + +// aten::max.other(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::max(const at::Tensor & other) const { + return at::_ops::max_other::call(const_cast(*this), other); +} + +// aten::minimum(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::minimum(const at::Tensor & other) const { + return at::_ops::minimum::call(const_cast(*this), other); +} + +// aten::min.other(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::min(const at::Tensor & other) const { + return at::_ops::min_other::call(const_cast(*this), other); +} + +// aten::quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor +inline at::Tensor Tensor::quantile(const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation) const { + return at::_ops::quantile::call(const_cast(*this), q, dim, keepdim, interpolation); +} + +// aten::quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor +inline at::Tensor Tensor::quantile(double q, c10::optional dim, bool keepdim, c10::string_view interpolation) const { + return at::_ops::quantile_scalar::call(const_cast(*this), q, dim, keepdim, interpolation); +} + +// aten::nanquantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor +inline at::Tensor Tensor::nanquantile(const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation) const { + return at::_ops::nanquantile::call(const_cast(*this), q, dim, keepdim, interpolation); +} + +// aten::nanquantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor +inline at::Tensor Tensor::nanquantile(double q, c10::optional dim, bool keepdim, c10::string_view interpolation) const { + return at::_ops::nanquantile_scalar::call(const_cast(*this), q, dim, keepdim, interpolation); +} + +// aten::sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::sort(int64_t dim, bool descending) const { + return at::_ops::sort::call(const_cast(*this), dim, descending); +} + +// aten::sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::sort(c10::optional stable, int64_t dim, bool descending) const { + return at::_ops::sort_stable::call(const_cast(*this), stable, dim, descending); +} + +// aten::sort.dimname(Tensor self, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::sort(at::Dimname dim, bool descending) const { + return at::_ops::sort_dimname::call(const_cast(*this), dim, descending); +} + +// aten::sort.dimname_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::sort(c10::optional stable, at::Dimname dim, bool descending) const { + return at::_ops::sort_dimname_stable::call(const_cast(*this), stable, dim, descending); +} + +// aten::msort(Tensor self) -> Tensor +inline at::Tensor Tensor::msort() const { + return at::_ops::msort::call(const_cast(*this)); +} + +// aten::argsort(Tensor self, int dim=-1, bool descending=False) -> Tensor +inline at::Tensor Tensor::argsort(int64_t dim, bool descending) const { + return at::_ops::argsort::call(const_cast(*this), dim, descending); +} + +// aten::argsort.stable(Tensor self, *, bool stable, int dim=-1, bool descending=False) -> Tensor +inline at::Tensor Tensor::argsort(bool stable, int64_t dim, bool descending) const { + return at::_ops::argsort_stable::call(const_cast(*this), stable, dim, descending); +} + +// aten::argsort.dimname(Tensor self, Dimname dim, bool descending=False) -> Tensor +inline at::Tensor Tensor::argsort(at::Dimname dim, bool descending) const { + return at::_ops::argsort_dimname::call(const_cast(*this), dim, descending); +} + +// aten::topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::topk(int64_t k, int64_t dim, bool largest, bool sorted) const { + return at::_ops::topk::call(const_cast(*this), k, dim, largest, sorted); +} + +// aten::topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) +inline ::std::tuple Tensor::topk_symint(c10::SymInt k, int64_t dim, bool largest, bool sorted) const { + return at::_ops::topk::call(const_cast(*this), k, dim, largest, sorted); +} + +// aten::all(Tensor self) -> Tensor +inline at::Tensor Tensor::all() const { + return at::_ops::all::call(const_cast(*this)); +} + +// aten::any(Tensor self) -> Tensor +inline at::Tensor Tensor::any() const { + return at::_ops::any::call(const_cast(*this)); +} + +// aten::renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor +inline at::Tensor Tensor::renorm(const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm) const { + return at::_ops::renorm::call(const_cast(*this), p, dim, maxnorm); +} + +// aten::renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!) +inline at::Tensor & Tensor::renorm_(const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm) const { + return at::_ops::renorm_::call(const_cast(*this), p, dim, maxnorm); +} + +// aten::unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a) +inline at::Tensor Tensor::unfold(int64_t dimension, int64_t size, int64_t step) const { + return at::_ops::unfold::call(const_cast(*this), dimension, size, step); +} + +// aten::equal(Tensor self, Tensor other) -> bool +inline bool Tensor::equal(const at::Tensor & other) const { + return at::_ops::equal::call(const_cast(*this), other); +} + +// aten::pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor +inline at::Tensor Tensor::pow(const at::Tensor & exponent) const { + return at::_ops::pow_Tensor_Tensor::call(const_cast(*this), exponent); +} + +// aten::pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor +inline at::Tensor Tensor::pow(const at::Scalar & exponent) const { + return at::_ops::pow_Tensor_Scalar::call(const_cast(*this), exponent); +} + +// aten::pow_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!) +inline at::Tensor & Tensor::pow_(const at::Scalar & exponent) const { + return at::_ops::pow__Scalar::call(const_cast(*this), exponent); +} + +// aten::pow_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!) +inline at::Tensor & Tensor::pow_(const at::Tensor & exponent) const { + return at::_ops::pow__Tensor::call(const_cast(*this), exponent); +} + +// aten::float_power.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor +inline at::Tensor Tensor::float_power(const at::Tensor & exponent) const { + return at::_ops::float_power_Tensor_Tensor::call(const_cast(*this), exponent); +} + +// aten::float_power.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor +inline at::Tensor Tensor::float_power(const at::Scalar & exponent) const { + return at::_ops::float_power_Tensor_Scalar::call(const_cast(*this), exponent); +} + +// aten::float_power_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!) +inline at::Tensor & Tensor::float_power_(const at::Scalar & exponent) const { + return at::_ops::float_power__Scalar::call(const_cast(*this), exponent); +} + +// aten::float_power_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!) +inline at::Tensor & Tensor::float_power_(const at::Tensor & exponent) const { + return at::_ops::float_power__Tensor::call(const_cast(*this), exponent); +} + +// aten::normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!) +inline at::Tensor & Tensor::normal_(double mean, double std, c10::optional generator) const { + return at::_ops::normal_::call(const_cast(*this), mean, std, generator); +} + +// aten::alias(Tensor(a) self) -> Tensor(a) +inline at::Tensor Tensor::alias() const { + return at::_ops::alias::call(const_cast(*this)); +} + +// aten::isfinite(Tensor self) -> Tensor +inline at::Tensor Tensor::isfinite() const { + return at::_ops::isfinite::call(const_cast(*this)); +} + +// aten::isinf(Tensor self) -> Tensor +inline at::Tensor Tensor::isinf() const { + return at::_ops::isinf::call(const_cast(*this)); +} + +// aten::record_stream(Tensor(a!) self, Stream s) -> () +inline void Tensor::record_stream(at::Stream s) const { + return at::_ops::record_stream::call(const_cast(*this), s); +} + +// aten::isposinf(Tensor self) -> Tensor +inline at::Tensor Tensor::isposinf() const { + return at::_ops::isposinf::call(const_cast(*this)); +} + +// aten::isneginf(Tensor self) -> Tensor +inline at::Tensor Tensor::isneginf() const { + return at::_ops::isneginf::call(const_cast(*this)); +} + +// aten::det(Tensor self) -> Tensor +inline at::Tensor Tensor::det() const { + return at::_ops::det::call(const_cast(*this)); +} + +// aten::slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet) +inline ::std::tuple Tensor::slogdet() const { + return at::_ops::slogdet::call(const_cast(*this)); +} + +// aten::logdet(Tensor self) -> Tensor +inline at::Tensor Tensor::logdet() const { + return at::_ops::logdet::call(const_cast(*this)); +} + +// aten::inverse(Tensor self) -> Tensor +inline at::Tensor Tensor::inverse() const { + return at::_ops::inverse::call(const_cast(*this)); +} + +// aten::inner(Tensor self, Tensor other) -> Tensor +inline at::Tensor Tensor::inner(const at::Tensor & other) const { + return at::_ops::inner::call(const_cast(*this), other); +} + +// aten::outer(Tensor self, Tensor vec2) -> Tensor +inline at::Tensor Tensor::outer(const at::Tensor & vec2) const { + return at::_ops::outer::call(const_cast(*this), vec2); +} + +// aten::ger(Tensor self, Tensor vec2) -> Tensor +inline at::Tensor Tensor::ger(const at::Tensor & vec2) const { + return at::_ops::ger::call(const_cast(*this), vec2); +} + +// aten::to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor +inline at::Tensor Tensor::to_padded_tensor(double padding, at::OptionalIntArrayRef output_size) const { + return at::_ops::to_padded_tensor::call(const_cast(*this), padding, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt); +} + +// aten::to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor +inline at::Tensor Tensor::to_padded_tensor_symint(double padding, at::OptionalSymIntArrayRef output_size) const { + return at::_ops::to_padded_tensor::call(const_cast(*this), padding, output_size); +} +} // namespace at + + +namespace c10 { +template <> +struct MaybeOwnedTraits { + using owned_type = at::Tensor; + using borrow_type = at::Tensor; + + static borrow_type createBorrow(const owned_type& from) { + // NOTE: this can be implemented without the special + // unsafe_borrow_t Tensor constructor as + // + // return borrow_type(c10::intrusive_ptr::reclaim(from.unsafeGetTensorImpl())); + // + // but that hurts inlining due to the nullptr check in the + // Tensor(c10::intrusive_ptr<...>) constructor. We already know + // that from.impl_ isn't null because from is a valid Tensor, so + // we needn't do the check again. (using __builtin_assume can + // avoid this, but wouldn't be portable to MSVC.) + return borrow_type(borrow_type::unsafe_borrow_t{}, from); + } + + static void assignBorrow(borrow_type& lhs, const borrow_type& rhs) { + lhs.unsafeReleaseTensorImpl(); + // See above note: this can be implemented with public API + // similarly to createBorrow(), but that would hurt inlining. + lhs = borrow_type(borrow_type::unsafe_borrow_t{}, rhs); + } + + static void destroyBorrow(borrow_type& toDestroy) { + toDestroy.unsafeReleaseTensorImpl(); // "leak" it, but it was already +0. + } + + static const owned_type& referenceFromBorrow(const borrow_type& borrow) { + return borrow; + } + + static const owned_type* pointerFromBorrow(const borrow_type& borrow) { + return &borrow; + } + + static bool debugBorrowIsValid(const borrow_type& /*borrow*/) { + return true; + } +}; + +template <> +struct ExclusivelyOwnedTraits { + using repr_type = at::Tensor; + using pointer_type = at::Tensor*; + using const_pointer_type = const at::Tensor*; + + static repr_type nullRepr() { + return at::Tensor(); + } + + template + static repr_type createInPlace(Args&&... args) { + return at::Tensor(std::forward(args)...); + } + + static repr_type moveToRepr(at::Tensor&& x) { + return std::move(x); + } + + static void destroyOwned(at::Tensor& x) { + return ExclusivelyOwnedTraits::destroyOwned(x); + } + + static at::Tensor take(at::Tensor& x) { + return std::move(x); + } + + static pointer_type getImpl(repr_type& x) { + return &x; + } + + static const_pointer_type getImpl(const repr_type& x) { + return &x; + } +}; +} // namespace c10 + +namespace at { + +inline c10::MaybeOwned borrow_from_optional_tensor( + const c10::optional& opt) { + return opt.has_value() + ? c10::MaybeOwned::borrowed(*opt) + : c10::MaybeOwned::owned(std::in_place); +} + +inline c10::MaybeOwned Tensor::expect_contiguous(MemoryFormat memory_format) const & { + if (is_contiguous(memory_format)) { + return c10::MaybeOwned::borrowed(*this); + } else { + return c10::MaybeOwned::owned(__dispatch_contiguous(memory_format)); + } +} +} // namespace at diff --git a/shared/package-files/75/7529f3512586bcbd947268aa68f79cf9d6d344c2063d4ed38fbfafa859751314/blob b/shared/package-files/75/7529f3512586bcbd947268aa68f79cf9d6d344c2063d4ed38fbfafa859751314/blob new file mode 100644 index 0000000000000000000000000000000000000000..856fa43aac9941b54af5f74d7ea961bab364cb8f --- /dev/null +++ b/shared/package-files/75/7529f3512586bcbd947268aa68f79cf9d6d344c2063d4ed38fbfafa859751314/blob @@ -0,0 +1,82 @@ + +import torch +import torch.ao.nn.intrinsic +import torch.ao.nn.intrinsic.qat +import torch.ao.nn.quantized as nnq + +__all__ = [ + "BNReLU2d", + "BNReLU3d" +] + +class BNReLU2d(nnq.BatchNorm2d): + r""" + A BNReLU2d module is a fused module of BatchNorm2d and ReLU + + We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm2d`. + + Attributes: + Same as torch.ao.nn.quantized.BatchNorm2d + + """ + _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU2d + + def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None): + super().__init__(num_features, eps=eps, momentum=momentum, device=device, dtype=dtype) + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 4: + raise ValueError("Input shape must be `(N, C, H, W)`!") + return torch.ops.quantized.batch_norm2d_relu( + input, self.weight, self.bias, self.running_mean, + self.running_var, self.eps, self.scale, self.zero_point) + + def _get_name(self): + return 'QuantizedBNReLU2d' + + @classmethod + def from_float(cls, mod): + # TODO: Add qat support for BNReLU2d + return super().from_float(mod) + + @classmethod + def from_reference(cls, bn_relu, output_scale, output_zero_point): + return super().from_reference(bn_relu[0], output_scale, output_zero_point) + +class BNReLU3d(nnq.BatchNorm3d): + r""" + A BNReLU3d module is a fused module of BatchNorm3d and ReLU + + We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm3d`. + + Attributes: + Same as torch.ao.nn.quantized.BatchNorm3d + + """ + _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU3d + + def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None): + super().__init__(num_features, eps=eps, momentum=momentum, device=device, dtype=dtype) + + def forward(self, input): + # Temporarily using len(shape) instead of ndim due to JIT issue + # https://github.com/pytorch/pytorch/issues/23890 + if len(input.shape) != 5: + raise ValueError("Input shape must be `(N, C, D, H, W)`!") + return torch.ops.quantized.batch_norm3d_relu( + input, self.weight, self.bias, self.running_mean, + self.running_var, self.eps, self.scale, self.zero_point) + + def _get_name(self): + return 'QuantizedBNReLU3d' + + @classmethod + def from_float(cls, mod): + # TODO: Add qat support for BNReLU3d + return super().from_float(mod) + + @classmethod + def from_reference(cls, bn_relu, output_scale, output_zero_point): + return super().from_reference(bn_relu[0], output_scale, output_zero_point) diff --git a/shared/package-files/75/752ad8827ddb5678e68114cca31f7830a5881b91aeaf8dce47113f2be51df840/blob b/shared/package-files/75/752ad8827ddb5678e68114cca31f7830a5881b91aeaf8dce47113f2be51df840/blob new file mode 100644 index 0000000000000000000000000000000000000000..e2f0fbc2b4df8b3f699f5294f2870a2d710dfb22 --- /dev/null +++ b/shared/package-files/75/752ad8827ddb5678e68114cca31f7830a5881b91aeaf8dce47113f2be51df840/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor miopen_convolution_relu(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups); +TORCH_API at::Tensor miopen_convolution_relu_symint(const at::Tensor & self, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/75/7531be245e6cf3693e2ebb502ccc7558d65e7f756b6466bfb016ef4d2027938f/blob b/shared/package-files/75/7531be245e6cf3693e2ebb502ccc7558d65e7f756b6466bfb016ef4d2027938f/blob new file mode 100644 index 0000000000000000000000000000000000000000..5ea7e87e7f3238853b048c222fcd8164ebbc6dc4 --- /dev/null +++ b/shared/package-files/75/7531be245e6cf3693e2ebb502ccc7558d65e7f756b6466bfb016ef4d2027938f/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _values_copy { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_values_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_values_copy(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API _values_copy_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_values_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/75/753a445ffcfeac512a9d02375efa71182c3e204d5aa94c59c3a284bf493ce92a/blob b/shared/package-files/75/753a445ffcfeac512a9d02375efa71182c3e204d5aa94c59c3a284bf493ce92a/blob new file mode 100644 index 0000000000000000000000000000000000000000..a411dbb456d2b9da8de739d6184d78a13180034c --- /dev/null +++ b/shared/package-files/75/753a445ffcfeac512a9d02375efa71182c3e204d5aa94c59c3a284bf493ce92a/blob @@ -0,0 +1,25 @@ +import sys +from typing import Optional + +def version() -> str: ... + +if sys.version_info >= (3, 0): + def bootstrap( + *, + root: Optional[str] = ..., + upgrade: bool = ..., + user: bool = ..., + altinstall: bool = ..., + default_pip: bool = ..., + verbosity: int = ..., + ) -> None: ... + +else: + def bootstrap( + root: Optional[str] = ..., + upgrade: bool = ..., + user: bool = ..., + altinstall: bool = ..., + default_pip: bool = ..., + verbosity: int = ..., + ) -> None: ... diff --git a/shared/package-files/75/753cc1ac635caa7e1b4630fbcebef8db8db332c098154a5b11f652912bf64f37/blob b/shared/package-files/75/753cc1ac635caa7e1b4630fbcebef8db8db332c098154a5b11f652912bf64f37/blob new file mode 100644 index 0000000000000000000000000000000000000000..add10f4e555ff2779e50a1cef035a7a733beefc1 --- /dev/null +++ b/shared/package-files/75/753cc1ac635caa7e1b4630fbcebef8db8db332c098154a5b11f652912bf64f37/blob @@ -0,0 +1,307 @@ +""" Python Character Mapping Codec mac_iceland generated from 'MAPPINGS/VENDORS/APPLE/ICELAND.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_table) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_table)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='mac-iceland', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + + +### Decoding Table + +decoding_table = ( + '\x00' # 0x00 -> CONTROL CHARACTER + '\x01' # 0x01 -> CONTROL CHARACTER + '\x02' # 0x02 -> CONTROL CHARACTER + '\x03' # 0x03 -> CONTROL CHARACTER + '\x04' # 0x04 -> CONTROL CHARACTER + '\x05' # 0x05 -> CONTROL CHARACTER + '\x06' # 0x06 -> CONTROL CHARACTER + '\x07' # 0x07 -> CONTROL CHARACTER + '\x08' # 0x08 -> CONTROL CHARACTER + '\t' # 0x09 -> CONTROL CHARACTER + '\n' # 0x0A -> CONTROL CHARACTER + '\x0b' # 0x0B -> CONTROL CHARACTER + '\x0c' # 0x0C -> CONTROL CHARACTER + '\r' # 0x0D -> CONTROL CHARACTER + '\x0e' # 0x0E -> CONTROL CHARACTER + '\x0f' # 0x0F -> CONTROL CHARACTER + '\x10' # 0x10 -> CONTROL CHARACTER + '\x11' # 0x11 -> CONTROL CHARACTER + '\x12' # 0x12 -> CONTROL CHARACTER + '\x13' # 0x13 -> CONTROL CHARACTER + '\x14' # 0x14 -> CONTROL CHARACTER + '\x15' # 0x15 -> CONTROL CHARACTER + '\x16' # 0x16 -> CONTROL CHARACTER + '\x17' # 0x17 -> CONTROL CHARACTER + '\x18' # 0x18 -> CONTROL CHARACTER + '\x19' # 0x19 -> CONTROL CHARACTER + '\x1a' # 0x1A -> CONTROL CHARACTER + '\x1b' # 0x1B -> CONTROL CHARACTER + '\x1c' # 0x1C -> CONTROL CHARACTER + '\x1d' # 0x1D -> CONTROL CHARACTER + '\x1e' # 0x1E -> CONTROL CHARACTER + '\x1f' # 0x1F -> CONTROL CHARACTER + ' ' # 0x20 -> SPACE + '!' # 0x21 -> EXCLAMATION MARK + '"' # 0x22 -> QUOTATION MARK + '#' # 0x23 -> NUMBER SIGN + '$' # 0x24 -> DOLLAR SIGN + '%' # 0x25 -> PERCENT SIGN + '&' # 0x26 -> AMPERSAND + "'" # 0x27 -> APOSTROPHE + '(' # 0x28 -> LEFT PARENTHESIS + ')' # 0x29 -> RIGHT PARENTHESIS + '*' # 0x2A -> ASTERISK + '+' # 0x2B -> PLUS SIGN + ',' # 0x2C -> COMMA + '-' # 0x2D -> HYPHEN-MINUS + '.' # 0x2E -> FULL STOP + '/' # 0x2F -> SOLIDUS + '0' # 0x30 -> DIGIT ZERO + '1' # 0x31 -> DIGIT ONE + '2' # 0x32 -> DIGIT TWO + '3' # 0x33 -> DIGIT THREE + '4' # 0x34 -> DIGIT FOUR + '5' # 0x35 -> DIGIT FIVE + '6' # 0x36 -> DIGIT SIX + '7' # 0x37 -> DIGIT SEVEN + '8' # 0x38 -> DIGIT EIGHT + '9' # 0x39 -> DIGIT NINE + ':' # 0x3A -> COLON + ';' # 0x3B -> SEMICOLON + '<' # 0x3C -> LESS-THAN SIGN + '=' # 0x3D -> EQUALS SIGN + '>' # 0x3E -> GREATER-THAN SIGN + '?' # 0x3F -> QUESTION MARK + '@' # 0x40 -> COMMERCIAL AT + 'A' # 0x41 -> LATIN CAPITAL LETTER A + 'B' # 0x42 -> LATIN CAPITAL LETTER B + 'C' # 0x43 -> LATIN CAPITAL LETTER C + 'D' # 0x44 -> LATIN CAPITAL LETTER D + 'E' # 0x45 -> LATIN CAPITAL LETTER E + 'F' # 0x46 -> LATIN CAPITAL LETTER F + 'G' # 0x47 -> LATIN CAPITAL LETTER G + 'H' # 0x48 -> LATIN CAPITAL LETTER H + 'I' # 0x49 -> LATIN CAPITAL LETTER I + 'J' # 0x4A -> LATIN CAPITAL LETTER J + 'K' # 0x4B -> LATIN CAPITAL LETTER K + 'L' # 0x4C -> LATIN CAPITAL LETTER L + 'M' # 0x4D -> LATIN CAPITAL LETTER M + 'N' # 0x4E -> LATIN CAPITAL LETTER N + 'O' # 0x4F -> LATIN CAPITAL LETTER O + 'P' # 0x50 -> LATIN CAPITAL LETTER P + 'Q' # 0x51 -> LATIN CAPITAL LETTER Q + 'R' # 0x52 -> LATIN CAPITAL LETTER R + 'S' # 0x53 -> LATIN CAPITAL LETTER S + 'T' # 0x54 -> LATIN CAPITAL LETTER T + 'U' # 0x55 -> LATIN CAPITAL LETTER U + 'V' # 0x56 -> LATIN CAPITAL LETTER V + 'W' # 0x57 -> LATIN CAPITAL LETTER W + 'X' # 0x58 -> LATIN CAPITAL LETTER X + 'Y' # 0x59 -> LATIN CAPITAL LETTER Y + 'Z' # 0x5A -> LATIN CAPITAL LETTER Z + '[' # 0x5B -> LEFT SQUARE BRACKET + '\\' # 0x5C -> REVERSE SOLIDUS + ']' # 0x5D -> RIGHT SQUARE BRACKET + '^' # 0x5E -> CIRCUMFLEX ACCENT + '_' # 0x5F -> LOW LINE + '`' # 0x60 -> GRAVE ACCENT + 'a' # 0x61 -> LATIN SMALL LETTER A + 'b' # 0x62 -> LATIN SMALL LETTER B + 'c' # 0x63 -> LATIN SMALL LETTER C + 'd' # 0x64 -> LATIN SMALL LETTER D + 'e' # 0x65 -> LATIN SMALL LETTER E + 'f' # 0x66 -> LATIN SMALL LETTER F + 'g' # 0x67 -> LATIN SMALL LETTER G + 'h' # 0x68 -> LATIN SMALL LETTER H + 'i' # 0x69 -> LATIN SMALL LETTER I + 'j' # 0x6A -> LATIN SMALL LETTER J + 'k' # 0x6B -> LATIN SMALL LETTER K + 'l' # 0x6C -> LATIN SMALL LETTER L + 'm' # 0x6D -> LATIN SMALL LETTER M + 'n' # 0x6E -> LATIN SMALL LETTER N + 'o' # 0x6F -> LATIN SMALL LETTER O + 'p' # 0x70 -> LATIN SMALL LETTER P + 'q' # 0x71 -> LATIN SMALL LETTER Q + 'r' # 0x72 -> LATIN SMALL LETTER R + 's' # 0x73 -> LATIN SMALL LETTER S + 't' # 0x74 -> LATIN SMALL LETTER T + 'u' # 0x75 -> LATIN SMALL LETTER U + 'v' # 0x76 -> LATIN SMALL LETTER V + 'w' # 0x77 -> LATIN SMALL LETTER W + 'x' # 0x78 -> LATIN SMALL LETTER X + 'y' # 0x79 -> LATIN SMALL LETTER Y + 'z' # 0x7A -> LATIN SMALL LETTER Z + '{' # 0x7B -> LEFT CURLY BRACKET + '|' # 0x7C -> VERTICAL LINE + '}' # 0x7D -> RIGHT CURLY BRACKET + '~' # 0x7E -> TILDE + '\x7f' # 0x7F -> CONTROL CHARACTER + '\xc4' # 0x80 -> LATIN CAPITAL LETTER A WITH DIAERESIS + '\xc5' # 0x81 -> LATIN CAPITAL LETTER A WITH RING ABOVE + '\xc7' # 0x82 -> LATIN CAPITAL LETTER C WITH CEDILLA + '\xc9' # 0x83 -> LATIN CAPITAL LETTER E WITH ACUTE + '\xd1' # 0x84 -> LATIN CAPITAL LETTER N WITH TILDE + '\xd6' # 0x85 -> LATIN CAPITAL LETTER O WITH DIAERESIS + '\xdc' # 0x86 -> LATIN CAPITAL LETTER U WITH DIAERESIS + '\xe1' # 0x87 -> LATIN SMALL LETTER A WITH ACUTE + '\xe0' # 0x88 -> LATIN SMALL LETTER A WITH GRAVE + '\xe2' # 0x89 -> LATIN SMALL LETTER A WITH CIRCUMFLEX + '\xe4' # 0x8A -> LATIN SMALL LETTER A WITH DIAERESIS + '\xe3' # 0x8B -> LATIN SMALL LETTER A WITH TILDE + '\xe5' # 0x8C -> LATIN SMALL LETTER A WITH RING ABOVE + '\xe7' # 0x8D -> LATIN SMALL LETTER C WITH CEDILLA + '\xe9' # 0x8E -> LATIN SMALL LETTER E WITH ACUTE + '\xe8' # 0x8F -> LATIN SMALL LETTER E WITH GRAVE + '\xea' # 0x90 -> LATIN SMALL LETTER E WITH CIRCUMFLEX + '\xeb' # 0x91 -> LATIN SMALL LETTER E WITH DIAERESIS + '\xed' # 0x92 -> LATIN SMALL LETTER I WITH ACUTE + '\xec' # 0x93 -> LATIN SMALL LETTER I WITH GRAVE + '\xee' # 0x94 -> LATIN SMALL LETTER I WITH CIRCUMFLEX + '\xef' # 0x95 -> LATIN SMALL LETTER I WITH DIAERESIS + '\xf1' # 0x96 -> LATIN SMALL LETTER N WITH TILDE + '\xf3' # 0x97 -> LATIN SMALL LETTER O WITH ACUTE + '\xf2' # 0x98 -> LATIN SMALL LETTER O WITH GRAVE + '\xf4' # 0x99 -> LATIN SMALL LETTER O WITH CIRCUMFLEX + '\xf6' # 0x9A -> LATIN SMALL LETTER O WITH DIAERESIS + '\xf5' # 0x9B -> LATIN SMALL LETTER O WITH TILDE + '\xfa' # 0x9C -> LATIN SMALL LETTER U WITH ACUTE + '\xf9' # 0x9D -> LATIN SMALL LETTER U WITH GRAVE + '\xfb' # 0x9E -> LATIN SMALL LETTER U WITH CIRCUMFLEX + '\xfc' # 0x9F -> LATIN SMALL LETTER U WITH DIAERESIS + '\xdd' # 0xA0 -> LATIN CAPITAL LETTER Y WITH ACUTE + '\xb0' # 0xA1 -> DEGREE SIGN + '\xa2' # 0xA2 -> CENT SIGN + '\xa3' # 0xA3 -> POUND SIGN + '\xa7' # 0xA4 -> SECTION SIGN + '\u2022' # 0xA5 -> BULLET + '\xb6' # 0xA6 -> PILCROW SIGN + '\xdf' # 0xA7 -> LATIN SMALL LETTER SHARP S + '\xae' # 0xA8 -> REGISTERED SIGN + '\xa9' # 0xA9 -> COPYRIGHT SIGN + '\u2122' # 0xAA -> TRADE MARK SIGN + '\xb4' # 0xAB -> ACUTE ACCENT + '\xa8' # 0xAC -> DIAERESIS + '\u2260' # 0xAD -> NOT EQUAL TO + '\xc6' # 0xAE -> LATIN CAPITAL LETTER AE + '\xd8' # 0xAF -> LATIN CAPITAL LETTER O WITH STROKE + '\u221e' # 0xB0 -> INFINITY + '\xb1' # 0xB1 -> PLUS-MINUS SIGN + '\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO + '\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO + '\xa5' # 0xB4 -> YEN SIGN + '\xb5' # 0xB5 -> MICRO SIGN + '\u2202' # 0xB6 -> PARTIAL DIFFERENTIAL + '\u2211' # 0xB7 -> N-ARY SUMMATION + '\u220f' # 0xB8 -> N-ARY PRODUCT + '\u03c0' # 0xB9 -> GREEK SMALL LETTER PI + '\u222b' # 0xBA -> INTEGRAL + '\xaa' # 0xBB -> FEMININE ORDINAL INDICATOR + '\xba' # 0xBC -> MASCULINE ORDINAL INDICATOR + '\u03a9' # 0xBD -> GREEK CAPITAL LETTER OMEGA + '\xe6' # 0xBE -> LATIN SMALL LETTER AE + '\xf8' # 0xBF -> LATIN SMALL LETTER O WITH STROKE + '\xbf' # 0xC0 -> INVERTED QUESTION MARK + '\xa1' # 0xC1 -> INVERTED EXCLAMATION MARK + '\xac' # 0xC2 -> NOT SIGN + '\u221a' # 0xC3 -> SQUARE ROOT + '\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK + '\u2248' # 0xC5 -> ALMOST EQUAL TO + '\u2206' # 0xC6 -> INCREMENT + '\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS + '\xa0' # 0xCA -> NO-BREAK SPACE + '\xc0' # 0xCB -> LATIN CAPITAL LETTER A WITH GRAVE + '\xc3' # 0xCC -> LATIN CAPITAL LETTER A WITH TILDE + '\xd5' # 0xCD -> LATIN CAPITAL LETTER O WITH TILDE + '\u0152' # 0xCE -> LATIN CAPITAL LIGATURE OE + '\u0153' # 0xCF -> LATIN SMALL LIGATURE OE + '\u2013' # 0xD0 -> EN DASH + '\u2014' # 0xD1 -> EM DASH + '\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK + '\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK + '\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK + '\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK + '\xf7' # 0xD6 -> DIVISION SIGN + '\u25ca' # 0xD7 -> LOZENGE + '\xff' # 0xD8 -> LATIN SMALL LETTER Y WITH DIAERESIS + '\u0178' # 0xD9 -> LATIN CAPITAL LETTER Y WITH DIAERESIS + '\u2044' # 0xDA -> FRACTION SLASH + '\u20ac' # 0xDB -> EURO SIGN + '\xd0' # 0xDC -> LATIN CAPITAL LETTER ETH + '\xf0' # 0xDD -> LATIN SMALL LETTER ETH + '\xde' # 0xDE -> LATIN CAPITAL LETTER THORN + '\xfe' # 0xDF -> LATIN SMALL LETTER THORN + '\xfd' # 0xE0 -> LATIN SMALL LETTER Y WITH ACUTE + '\xb7' # 0xE1 -> MIDDLE DOT + '\u201a' # 0xE2 -> SINGLE LOW-9 QUOTATION MARK + '\u201e' # 0xE3 -> DOUBLE LOW-9 QUOTATION MARK + '\u2030' # 0xE4 -> PER MILLE SIGN + '\xc2' # 0xE5 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX + '\xca' # 0xE6 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX + '\xc1' # 0xE7 -> LATIN CAPITAL LETTER A WITH ACUTE + '\xcb' # 0xE8 -> LATIN CAPITAL LETTER E WITH DIAERESIS + '\xc8' # 0xE9 -> LATIN CAPITAL LETTER E WITH GRAVE + '\xcd' # 0xEA -> LATIN CAPITAL LETTER I WITH ACUTE + '\xce' # 0xEB -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX + '\xcf' # 0xEC -> LATIN CAPITAL LETTER I WITH DIAERESIS + '\xcc' # 0xED -> LATIN CAPITAL LETTER I WITH GRAVE + '\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE + '\xd4' # 0xEF -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX + '\uf8ff' # 0xF0 -> Apple logo + '\xd2' # 0xF1 -> LATIN CAPITAL LETTER O WITH GRAVE + '\xda' # 0xF2 -> LATIN CAPITAL LETTER U WITH ACUTE + '\xdb' # 0xF3 -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX + '\xd9' # 0xF4 -> LATIN CAPITAL LETTER U WITH GRAVE + '\u0131' # 0xF5 -> LATIN SMALL LETTER DOTLESS I + '\u02c6' # 0xF6 -> MODIFIER LETTER CIRCUMFLEX ACCENT + '\u02dc' # 0xF7 -> SMALL TILDE + '\xaf' # 0xF8 -> MACRON + '\u02d8' # 0xF9 -> BREVE + '\u02d9' # 0xFA -> DOT ABOVE + '\u02da' # 0xFB -> RING ABOVE + '\xb8' # 0xFC -> CEDILLA + '\u02dd' # 0xFD -> DOUBLE ACUTE ACCENT + '\u02db' # 0xFE -> OGONEK + '\u02c7' # 0xFF -> CARON +) + +### Encoding table +encoding_table=codecs.charmap_build(decoding_table) diff --git a/shared/package-files/75/753d07f8c2e2eb64977a22a32d02741153eec644e534ec695ad371039b8124fb/blob b/shared/package-files/75/753d07f8c2e2eb64977a22a32d02741153eec644e534ec695ad371039b8124fb/blob new file mode 100644 index 0000000000000000000000000000000000000000..d16aea1eb887caafec2165ef21c9814cb5bbb551 --- /dev/null +++ b/shared/package-files/75/753d07f8c2e2eb64977a22a32d02741153eec644e534ec695ad371039b8124fb/blob @@ -0,0 +1,105 @@ +from __future__ import annotations + +import os +import sys +from typing import Generator + +from _pytest.config import Config +from _pytest.config.argparsing import Parser +from _pytest.nodes import Item +from _pytest.stash import StashKey +import pytest + + +fault_handler_original_stderr_fd_key = StashKey[int]() +fault_handler_stderr_fd_key = StashKey[int]() + + +def pytest_addoption(parser: Parser) -> None: + help = ( + "Dump the traceback of all threads if a test takes " + "more than TIMEOUT seconds to finish" + ) + parser.addini("faulthandler_timeout", help, default=0.0) + + +def pytest_configure(config: Config) -> None: + import faulthandler + + # at teardown we want to restore the original faulthandler fileno + # but faulthandler has no api to return the original fileno + # so here we stash the stderr fileno to be used at teardown + # sys.stderr and sys.__stderr__ may be closed or patched during the session + # so we can't rely on their values being good at that point (#11572). + stderr_fileno = get_stderr_fileno() + if faulthandler.is_enabled(): + config.stash[fault_handler_original_stderr_fd_key] = stderr_fileno + config.stash[fault_handler_stderr_fd_key] = os.dup(stderr_fileno) + faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key]) + + +def pytest_unconfigure(config: Config) -> None: + import faulthandler + + faulthandler.disable() + # Close the dup file installed during pytest_configure. + if fault_handler_stderr_fd_key in config.stash: + os.close(config.stash[fault_handler_stderr_fd_key]) + del config.stash[fault_handler_stderr_fd_key] + # Re-enable the faulthandler if it was originally enabled. + if fault_handler_original_stderr_fd_key in config.stash: + faulthandler.enable(config.stash[fault_handler_original_stderr_fd_key]) + del config.stash[fault_handler_original_stderr_fd_key] + + +def get_stderr_fileno() -> int: + try: + fileno = sys.stderr.fileno() + # The Twisted Logger will return an invalid file descriptor since it is not backed + # by an FD. So, let's also forward this to the same code path as with pytest-xdist. + if fileno == -1: + raise AttributeError() + return fileno + except (AttributeError, ValueError): + # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file. + # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors + # This is potentially dangerous, but the best we can do. + assert sys.__stderr__ is not None + return sys.__stderr__.fileno() + + +def get_timeout_config_value(config: Config) -> float: + return float(config.getini("faulthandler_timeout") or 0.0) + + +@pytest.hookimpl(wrapper=True, trylast=True) +def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]: + timeout = get_timeout_config_value(item.config) + if timeout > 0: + import faulthandler + + stderr = item.config.stash[fault_handler_stderr_fd_key] + faulthandler.dump_traceback_later(timeout, file=stderr) + try: + return (yield) + finally: + faulthandler.cancel_dump_traceback_later() + else: + return (yield) + + +@pytest.hookimpl(tryfirst=True) +def pytest_enter_pdb() -> None: + """Cancel any traceback dumping due to timeout before entering pdb.""" + import faulthandler + + faulthandler.cancel_dump_traceback_later() + + +@pytest.hookimpl(tryfirst=True) +def pytest_exception_interact() -> None: + """Cancel any traceback dumping due to an interactive exception being + raised.""" + import faulthandler + + faulthandler.cancel_dump_traceback_later() diff --git a/shared/package-files/75/753dda518a7e9f6dc0309721b1faae58c9661f545801da9f04728391f70be2d0/blob b/shared/package-files/75/753dda518a7e9f6dc0309721b1faae58c9661f545801da9f04728391f70be2d0/blob new file mode 100644 index 0000000000000000000000000000000000000000..a58f8e3e297ea002161efa8d6146fe64b1daf321 --- /dev/null +++ b/shared/package-files/75/753dda518a7e9f6dc0309721b1faae58c9661f545801da9f04728391f70be2d0/blob @@ -0,0 +1,14 @@ +# Encoding file: iso2022, escape-driven +E +name iso2022 +init {} +final {} +iso8859-1 \x1b(B +jis0201 \x1b(J +gb1988 \x1b(T +jis0208 \x1b$B +jis0208 \x1b$@ +jis0212 \x1b$(D +gb2312 \x1b$A +ksc5601 \x1b$(C +jis0208 \x1b&@\x1b$B diff --git a/shared/package-files/75/7540139585546646e0810e8f5329832a107450aa83a3e2827f4169fc48d6b133/blob b/shared/package-files/75/7540139585546646e0810e8f5329832a107450aa83a3e2827f4169fc48d6b133/blob new file mode 100644 index 0000000000000000000000000000000000000000..eb73b2a795d7c7d4d3efbef3b2abdbbd882e93c6 --- /dev/null +++ b/shared/package-files/75/7540139585546646e0810e8f5329832a107450aa83a3e2827f4169fc48d6b133/blob @@ -0,0 +1,71 @@ +""" + pygments.lexers.pointless + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for Pointless. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, words +from pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ + Punctuation, String, Text + +__all__ = ['PointlessLexer'] + + +class PointlessLexer(RegexLexer): + """ + For Pointless source code. + + .. versionadded:: 2.7 + """ + + name = 'Pointless' + url = 'https://ptls.dev' + aliases = ['pointless'] + filenames = ['*.ptls'] + + ops = words([ + "+", "-", "*", "/", "**", "%", "+=", "-=", "*=", + "/=", "**=", "%=", "|>", "=", "==", "!=", "<", ">", + "<=", ">=", "=>", "$", "++", + ]) + + keywords = words([ + "if", "then", "else", "where", "with", "cond", + "case", "and", "or", "not", "in", "as", "for", + "requires", "throw", "try", "catch", "when", + "yield", "upval", + ], suffix=r'\b') + + tokens = { + 'root': [ + (r'[ \n\r]+', Text), + (r'--.*$', Comment.Single), + (r'"""', String, 'multiString'), + (r'"', String, 'string'), + (r'[\[\](){}:;,.]', Punctuation), + (ops, Operator), + (keywords, Keyword), + (r'\d+|\d*\.\d+', Number), + (r'(true|false)\b', Name.Builtin), + (r'[A-Z][a-zA-Z0-9]*\b', String.Symbol), + (r'output\b', Name.Variable.Magic), + (r'(export|import)\b', Keyword.Namespace), + (r'[a-z][a-zA-Z0-9]*\b', Name.Variable) + ], + 'multiString': [ + (r'\\.', String.Escape), + (r'"""', String, '#pop'), + (r'"', String), + (r'[^\\"]+', String), + ], + 'string': [ + (r'\\.', String.Escape), + (r'"', String, '#pop'), + (r'\n', Error), + (r'[^\\"]+', String), + ], + } diff --git a/shared/package-files/75/75415caa5bfc77d316399d798f213b94ad69cace64389cb703efbbf6e0fec3a4/blob b/shared/package-files/75/75415caa5bfc77d316399d798f213b94ad69cace64389cb703efbbf6e0fec3a4/blob new file mode 100644 index 0000000000000000000000000000000000000000..39751b677ee39d3614b38dd58454ef41143fec97 --- /dev/null +++ b/shared/package-files/75/75415caa5bfc77d316399d798f213b94ad69cace64389cb703efbbf6e0fec3a4/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor zero(const at::Tensor & self); +TORCH_API at::Tensor & zero_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & zero_(at::Tensor & self); +TORCH_API at::Tensor & zero_nested_(at::Tensor & self); +TORCH_API at::Tensor & zero_sparse_(at::Tensor & self); +TORCH_API at::Tensor & zero_sparse_csr_(at::Tensor & self); +TORCH_API at::Tensor & zero_meta_(at::Tensor & self); +TORCH_API at::Tensor & mkldnn_zero_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/7543cbbbc7eb94afaf99fdfe8ab5ffeeebf0cb0e3171cbfa1088b398867cf243/blob b/shared/package-files/75/7543cbbbc7eb94afaf99fdfe8ab5ffeeebf0cb0e3171cbfa1088b398867cf243/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b41d87bb0118de61d5561433dabcb181f872f84 --- /dev/null +++ b/shared/package-files/75/7543cbbbc7eb94afaf99fdfe8ab5ffeeebf0cb0e3171cbfa1088b398867cf243/blob @@ -0,0 +1,1108 @@ +from .functions import defun, defun_wrapped + +@defun +def j0(ctx, x): + """Computes the Bessel function `J_0(x)`. See :func:`~mpmath.besselj`.""" + return ctx.besselj(0, x) + +@defun +def j1(ctx, x): + """Computes the Bessel function `J_1(x)`. See :func:`~mpmath.besselj`.""" + return ctx.besselj(1, x) + +@defun +def besselj(ctx, n, z, derivative=0, **kwargs): + if type(n) is int: + n_isint = True + else: + n = ctx.convert(n) + n_isint = ctx.isint(n) + if n_isint: + n = int(ctx._re(n)) + if n_isint and n < 0: + return (-1)**n * ctx.besselj(-n, z, derivative, **kwargs) + z = ctx.convert(z) + M = ctx.mag(z) + if derivative: + d = ctx.convert(derivative) + # TODO: the integer special-casing shouldn't be necessary. + # However, the hypergeometric series gets inaccurate for large d + # because of inaccurate pole cancellation at a pole far from + # zero (needs to be fixed in hypercomb or hypsum) + if ctx.isint(d) and d >= 0: + d = int(d) + orig = ctx.prec + try: + ctx.prec += 15 + v = ctx.fsum((-1)**k * ctx.binomial(d,k) * ctx.besselj(2*k+n-d,z) + for k in range(d+1)) + finally: + ctx.prec = orig + v *= ctx.mpf(2)**(-d) + else: + def h(n,d): + r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), -0.25, exact=True) + B = [0.5*(n-d+1), 0.5*(n-d+2)] + T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[],B,[(n+1)*0.5,(n+2)*0.5],B+[n+1],r)] + return T + v = ctx.hypercomb(h, [n,d], **kwargs) + else: + # Fast case: J_n(x), n int, appropriate magnitude for fixed-point calculation + if (not derivative) and n_isint and abs(M) < 10 and abs(n) < 20: + try: + return ctx._besselj(n, z) + except NotImplementedError: + pass + if not z: + if not n: + v = ctx.one + n+z + elif ctx.re(n) > 0: + v = n*z + else: + v = ctx.inf + z + n + else: + #v = 0 + orig = ctx.prec + try: + # XXX: workaround for accuracy in low level hypergeometric series + # when alternating, large arguments + ctx.prec += min(3*abs(M), ctx.prec) + w = ctx.fmul(z, 0.5, exact=True) + def h(n): + r = ctx.fneg(ctx.fmul(w, w, prec=max(0,ctx.prec+M)), exact=True) + return [([w], [n], [], [n+1], [], [n+1], r)] + v = ctx.hypercomb(h, [n], **kwargs) + finally: + ctx.prec = orig + v = +v + return v + +@defun +def besseli(ctx, n, z, derivative=0, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + if not z: + if derivative: + raise ValueError + if not n: + # I(0,0) = 1 + return 1+n+z + if ctx.isint(n): + return 0*(n+z) + r = ctx.re(n) + if r == 0: + return ctx.nan*(n+z) + elif r > 0: + return 0*(n+z) + else: + return ctx.inf+(n+z) + M = ctx.mag(z) + if derivative: + d = ctx.convert(derivative) + def h(n,d): + r = ctx.fmul(ctx.fmul(z, z, prec=ctx.prec+M), 0.25, exact=True) + B = [0.5*(n-d+1), 0.5*(n-d+2), n+1] + T = [([2,ctx.pi,z],[d-2*n,0.5,n-d],[n+1],B,[(n+1)*0.5,(n+2)*0.5],B,r)] + return T + v = ctx.hypercomb(h, [n,d], **kwargs) + else: + def h(n): + w = ctx.fmul(z, 0.5, exact=True) + r = ctx.fmul(w, w, prec=max(0,ctx.prec+M)) + return [([w], [n], [], [n+1], [], [n+1], r)] + v = ctx.hypercomb(h, [n], **kwargs) + return v + +@defun_wrapped +def bessely(ctx, n, z, derivative=0, **kwargs): + if not z: + if derivative: + # Not implemented + raise ValueError + if not n: + # ~ log(z/2) + return -ctx.inf + (n+z) + if ctx.im(n): + return ctx.nan * (n+z) + r = ctx.re(n) + q = n+0.5 + if ctx.isint(q): + if n > 0: + return -ctx.inf + (n+z) + else: + return 0 * (n+z) + if r < 0 and int(ctx.floor(q)) % 2: + return ctx.inf + (n+z) + else: + return ctx.ninf + (n+z) + # XXX: use hypercomb + ctx.prec += 10 + m, d = ctx.nint_distance(n) + if d < -ctx.prec: + h = +ctx.eps + ctx.prec *= 2 + n += h + elif d < 0: + ctx.prec -= d + # TODO: avoid cancellation for imaginary arguments + cos, sin = ctx.cospi_sinpi(n) + return (ctx.besselj(n,z,derivative,**kwargs)*cos - \ + ctx.besselj(-n,z,derivative,**kwargs))/sin + +@defun_wrapped +def besselk(ctx, n, z, **kwargs): + if not z: + return ctx.inf + M = ctx.mag(z) + if M < 1: + # Represent as limit definition + def h(n): + r = (z/2)**2 + T1 = [z, 2], [-n, n-1], [n], [], [], [1-n], r + T2 = [z, 2], [n, -n-1], [-n], [], [], [1+n], r + return T1, T2 + # We could use the limit definition always, but it leads + # to very bad cancellation (of exponentially large terms) + # for large real z + # Instead represent in terms of 2F0 + else: + ctx.prec += M + def h(n): + return [([ctx.pi/2, z, ctx.exp(-z)], [0.5,-0.5,1], [], [], \ + [n+0.5, 0.5-n], [], -1/(2*z))] + return ctx.hypercomb(h, [n], **kwargs) + +@defun_wrapped +def hankel1(ctx,n,x,**kwargs): + return ctx.besselj(n,x,**kwargs) + ctx.j*ctx.bessely(n,x,**kwargs) + +@defun_wrapped +def hankel2(ctx,n,x,**kwargs): + return ctx.besselj(n,x,**kwargs) - ctx.j*ctx.bessely(n,x,**kwargs) + +@defun_wrapped +def whitm(ctx,k,m,z,**kwargs): + if z == 0: + # M(k,m,z) = 0^(1/2+m) + if ctx.re(m) > -0.5: + return z + elif ctx.re(m) < -0.5: + return ctx.inf + z + else: + return ctx.nan * z + x = ctx.fmul(-0.5, z, exact=True) + y = 0.5+m + return ctx.exp(x) * z**y * ctx.hyp1f1(y-k, 1+2*m, z, **kwargs) + +@defun_wrapped +def whitw(ctx,k,m,z,**kwargs): + if z == 0: + g = abs(ctx.re(m)) + if g < 0.5: + return z + elif g > 0.5: + return ctx.inf + z + else: + return ctx.nan * z + x = ctx.fmul(-0.5, z, exact=True) + y = 0.5+m + return ctx.exp(x) * z**y * ctx.hyperu(y-k, 1+2*m, z, **kwargs) + +@defun +def hyperu(ctx, a, b, z, **kwargs): + a, atype = ctx._convert_param(a) + b, btype = ctx._convert_param(b) + z = ctx.convert(z) + if not z: + if ctx.re(b) <= 1: + return ctx.gammaprod([1-b],[a-b+1]) + else: + return ctx.inf + z + bb = 1+a-b + bb, bbtype = ctx._convert_param(bb) + try: + orig = ctx.prec + try: + ctx.prec += 10 + v = ctx.hypsum(2, 0, (atype, bbtype), [a, bb], -1/z, maxterms=ctx.prec) + return v / z**a + finally: + ctx.prec = orig + except ctx.NoConvergence: + pass + def h(a,b): + w = ctx.sinpi(b) + T1 = ([ctx.pi,w],[1,-1],[],[a-b+1,b],[a],[b],z) + T2 = ([-ctx.pi,w,z],[1,-1,1-b],[],[a,2-b],[a-b+1],[2-b],z) + return T1, T2 + return ctx.hypercomb(h, [a,b], **kwargs) + +@defun +def struveh(ctx,n,z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/StruveH/26/01/02/ + def h(n): + return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], -(z/2)**2)] + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def struvel(ctx,n,z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/StruveL/26/01/02/ + def h(n): + return [([z/2, 0.5*ctx.sqrt(ctx.pi)], [n+1, -1], [], [n+1.5], [1], [1.5, n+1.5], (z/2)**2)] + return ctx.hypercomb(h, [n], **kwargs) + +def _anger(ctx,which,v,z,**kwargs): + v = ctx._convert_param(v)[0] + z = ctx.convert(z) + def h(v): + b = ctx.mpq_1_2 + u = v*b + m = b*3 + a1,a2,b1,b2 = m-u, m+u, 1-u, 1+u + c, s = ctx.cospi_sinpi(u) + if which == 0: + A, B = [b*z, s], [c] + if which == 1: + A, B = [b*z, -c], [s] + w = ctx.square_exp_arg(z, mult=-0.25) + T1 = A, [1, 1], [], [a1,a2], [1], [a1,a2], w + T2 = B, [1], [], [b1,b2], [1], [b1,b2], w + return T1, T2 + return ctx.hypercomb(h, [v], **kwargs) + +@defun +def angerj(ctx, v, z, **kwargs): + return _anger(ctx, 0, v, z, **kwargs) + +@defun +def webere(ctx, v, z, **kwargs): + return _anger(ctx, 1, v, z, **kwargs) + +@defun +def lommels1(ctx, u, v, z, **kwargs): + u = ctx._convert_param(u)[0] + v = ctx._convert_param(v)[0] + z = ctx.convert(z) + def h(u,v): + b = ctx.mpq_1_2 + w = ctx.square_exp_arg(z, mult=-0.25) + return ([u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], \ + [b*(u-v+3),b*(u+v+3)], w), + return ctx.hypercomb(h, [u,v], **kwargs) + +@defun +def lommels2(ctx, u, v, z, **kwargs): + u = ctx._convert_param(u)[0] + v = ctx._convert_param(v)[0] + z = ctx.convert(z) + # Asymptotic expansion (GR p. 947) -- need to be careful + # not to use for small arguments + # def h(u,v): + # b = ctx.mpq_1_2 + # w = -(z/2)**(-2) + # return ([z], [u-1], [], [], [b*(1-u+v)], [b*(1-u-v)], w), + def h(u,v): + b = ctx.mpq_1_2 + w = ctx.square_exp_arg(z, mult=-0.25) + T1 = [u-v+1, u+v+1, z], [-1, -1, u+1], [], [], [1], [b*(u-v+3),b*(u+v+3)], w + T2 = [2, z], [u+v-1, -v], [v, b*(u+v+1)], [b*(v-u+1)], [], [1-v], w + T3 = [2, z], [u-v-1, v], [-v, b*(u-v+1)], [b*(1-u-v)], [], [1+v], w + #c1 = ctx.cospi((u-v)*b) + #c2 = ctx.cospi((u+v)*b) + #s = ctx.sinpi(v) + #r1 = (u-v+1)*b + #r2 = (u+v+1)*b + #T2 = [c1, s, z, 2], [1, -1, -v, v], [], [-v+1], [], [-v+1], w + #T3 = [-c2, s, z, 2], [1, -1, v, -v], [], [v+1], [], [v+1], w + #T2 = [c1, s, z, 2], [1, -1, -v, v+u-1], [r1, r2], [-v+1], [], [-v+1], w + #T3 = [-c2, s, z, 2], [1, -1, v, -v+u-1], [r1, r2], [v+1], [], [v+1], w + return T1, T2, T3 + return ctx.hypercomb(h, [u,v], **kwargs) + +@defun +def ber(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBer2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos, sin = ctx.cospi_sinpi(-0.75*n) + T1 = [cos, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r + T2 = [sin, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r + return T1, T2 + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def bei(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinBei2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos, sin = ctx.cospi_sinpi(0.75*n) + T1 = [cos, z/2], [1, n+2], [], [n+2], [], [1.5, 0.5*(n+3), 0.5*n+1], r + T2 = [sin, z/2], [1, n], [], [n+1], [], [0.5, 0.5*(n+1), 0.5*n+1], r + return T1, T2 + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def ker(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKer2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos1, sin1 = ctx.cospi_sinpi(0.25*n) + cos2, sin2 = ctx.cospi_sinpi(0.75*n) + T1 = [2, z, 4*cos1], [-n-3, n, 1], [-n], [], [], [0.5, 0.5*(1+n), 0.5*(n+2)], r + T2 = [2, z, -sin1], [-n-3, 2+n, 1], [-n-1], [], [], [1.5, 0.5*(3+n), 0.5*(n+2)], r + T3 = [2, z, 4*cos2], [n-3, -n, 1], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r + T4 = [2, z, -sin2], [n-3, 2-n, 1], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r + return T1, T2, T3, T4 + return ctx.hypercomb(h, [n], **kwargs) + +@defun +def kei(ctx, n, z, **kwargs): + n = ctx.convert(n) + z = ctx.convert(z) + # http://functions.wolfram.com/Bessel-TypeFunctions/KelvinKei2/26/01/02/0001/ + def h(n): + r = -(z/4)**4 + cos1, sin1 = ctx.cospi_sinpi(0.75*n) + cos2, sin2 = ctx.cospi_sinpi(0.25*n) + T1 = [-cos1, 2, z], [1, n-3, 2-n], [n-1], [], [], [1.5, 0.5*(3-n), 1-0.5*n], r + T2 = [-sin1, 2, z], [1, n-1, -n], [n], [], [], [0.5, 0.5*(1-n), 1-0.5*n], r + T3 = [-sin2, 2, z], [1, -n-1, n], [-n], [], [], [0.5, 0.5*(n+1), 0.5*(n+2)], r + T4 = [-cos2, 2, z], [1, -n-3, n+2], [-n-1], [], [], [1.5, 0.5*(n+3), 0.5*(n+2)], r + return T1, T2, T3, T4 + return ctx.hypercomb(h, [n], **kwargs) + +# TODO: do this more generically? +def c_memo(f): + name = f.__name__ + def f_wrapped(ctx): + cache = ctx._misc_const_cache + prec = ctx.prec + p,v = cache.get(name, (-1,0)) + if p >= prec: + return +v + else: + cache[name] = (prec, f(ctx)) + return cache[name][1] + return f_wrapped + +@c_memo +def _airyai_C1(ctx): + return 1 / (ctx.cbrt(9) * ctx.gamma(ctx.mpf(2)/3)) + +@c_memo +def _airyai_C2(ctx): + return -1 / (ctx.cbrt(3) * ctx.gamma(ctx.mpf(1)/3)) + +@c_memo +def _airybi_C1(ctx): + return 1 / (ctx.nthroot(3,6) * ctx.gamma(ctx.mpf(2)/3)) + +@c_memo +def _airybi_C2(ctx): + return ctx.nthroot(3,6) / ctx.gamma(ctx.mpf(1)/3) + +def _airybi_n2_inf(ctx): + prec = ctx.prec + try: + v = ctx.power(3,'2/3')*ctx.gamma('2/3')/(2*ctx.pi) + finally: + ctx.prec = prec + return +v + +# Derivatives at z = 0 +# TODO: could be expressed more elegantly using triple factorials +def _airyderiv_0(ctx, z, n, ntype, which): + if ntype == 'Z': + if n < 0: + return z + r = ctx.mpq_1_3 + prec = ctx.prec + try: + ctx.prec += 10 + v = ctx.gamma((n+1)*r) * ctx.power(3,n*r) / ctx.pi + if which == 0: + v *= ctx.sinpi(2*(n+1)*r) + v /= ctx.power(3,'2/3') + else: + v *= abs(ctx.sinpi(2*(n+1)*r)) + v /= ctx.power(3,'1/6') + finally: + ctx.prec = prec + return +v + z + else: + # singular (does the limit exist?) + raise NotImplementedError + +@defun +def airyai(ctx, z, derivative=0, **kwargs): + z = ctx.convert(z) + if derivative: + n, ntype = ctx._convert_param(derivative) + else: + n = 0 + # Values at infinities + if not ctx.isnormal(z) and z: + if n and ntype == 'Z': + if n == -1: + if z == ctx.inf: + return ctx.mpf(1)/3 + 1/z + if z == ctx.ninf: + return ctx.mpf(-2)/3 + 1/z + if n < -1: + if z == ctx.inf: + return z + if z == ctx.ninf: + return (-1)**n * (-z) + if (not n) and z == ctx.inf or z == ctx.ninf: + return 1/z + # TODO: limits + raise ValueError("essential singularity of Ai(z)") + # Account for exponential scaling + if z: + extraprec = max(0, int(1.5*ctx.mag(z))) + else: + extraprec = 0 + if n: + if n == 1: + def h(): + # http://functions.wolfram.com/03.07.06.0005.01 + if ctx._re(z) > 4: + ctx.prec += extraprec + w = z**1.5; r = -0.75/w; u = -2*w/3 + ctx.prec -= extraprec + C = -ctx.exp(u)/(2*ctx.sqrt(ctx.pi))*ctx.nthroot(z,4) + return ([C],[1],[],[],[(-1,6),(7,6)],[],r), + # http://functions.wolfram.com/03.07.26.0001.01 + else: + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airyai_C1(ctx) * 0.5 + C2 = _airyai_C2(ctx) + T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w + T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + else: + if z == 0: + return _airyderiv_0(ctx, z, n, ntype, 0) + # http://functions.wolfram.com/03.05.20.0004.01 + def h(n): + ctx.prec += extraprec + w = z**3/9 + ctx.prec -= extraprec + q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 + a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 + T1 = [3, z], [n-q23, -n], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 + T2 = [3, z, -z], [n-q43, -n, 1], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + return T1, T2 + v = ctx.hypercomb(h, [n], **kwargs) + if ctx._is_real_type(z) and ctx.isint(n): + v = ctx._re(v) + return v + else: + def h(): + if ctx._re(z) > 4: + # We could use 1F1, but it results in huge cancellation; + # the following expansion is better. + # TODO: asymptotic series for derivatives + ctx.prec += extraprec + w = z**1.5; r = -0.75/w; u = -2*w/3 + ctx.prec -= extraprec + C = ctx.exp(u)/(2*ctx.sqrt(ctx.pi)*ctx.nthroot(z,4)) + return ([C],[1],[],[],[(1,6),(5,6)],[],r), + else: + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airyai_C1(ctx) + C2 = _airyai_C2(ctx) + T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w + T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + +@defun +def airybi(ctx, z, derivative=0, **kwargs): + z = ctx.convert(z) + if derivative: + n, ntype = ctx._convert_param(derivative) + else: + n = 0 + # Values at infinities + if not ctx.isnormal(z) and z: + if n and ntype == 'Z': + if z == ctx.inf: + return z + if z == ctx.ninf: + if n == -1: + return 1/z + if n == -2: + return _airybi_n2_inf(ctx) + if n < -2: + return (-1)**n * (-z) + if not n: + if z == ctx.inf: + return z + if z == ctx.ninf: + return 1/z + # TODO: limits + raise ValueError("essential singularity of Bi(z)") + if z: + extraprec = max(0, int(1.5*ctx.mag(z))) + else: + extraprec = 0 + if n: + if n == 1: + # http://functions.wolfram.com/03.08.26.0001.01 + def h(): + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airybi_C1(ctx)*0.5 + C2 = _airybi_C2(ctx) + T1 = [C1,z],[1,2],[],[],[],[ctx.mpq_5_3],w + T2 = [C2],[1],[],[],[],[ctx.mpq_1_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + else: + if z == 0: + return _airyderiv_0(ctx, z, n, ntype, 1) + def h(n): + ctx.prec += extraprec + w = z**3/9 + ctx.prec -= extraprec + q13,q23,q43 = ctx.mpq_1_3, ctx.mpq_2_3, ctx.mpq_4_3 + q16 = ctx.mpq_1_6 + q56 = ctx.mpq_5_6 + a1=q13; a2=1; b1=(1-n)*q13; b2=(2-n)*q13; b3=1-n*q13 + T1 = [3, z], [n-q16, -n], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + a1=q23; b1=(2-n)*q13; b2=1-n*q13; b3=(4-n)*q13 + T2 = [3, z], [n-q56, 1-n], [a1], [b1,b2,b3], \ + [a1,a2], [b1,b2,b3], w + return T1, T2 + v = ctx.hypercomb(h, [n], **kwargs) + if ctx._is_real_type(z) and ctx.isint(n): + v = ctx._re(v) + return v + else: + def h(): + ctx.prec += extraprec + w = z**3 / 9 + ctx.prec -= extraprec + C1 = _airybi_C1(ctx) + C2 = _airybi_C2(ctx) + T1 = [C1],[1],[],[],[],[ctx.mpq_2_3],w + T2 = [z*C2],[1],[],[],[],[ctx.mpq_4_3],w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + +def _airy_zero(ctx, which, k, derivative, complex=False): + # Asymptotic formulas are given in DLMF section 9.9 + def U(t): return t**(2/3.)*(1-7/(t**2*48)) + def T(t): return t**(2/3.)*(1+5/(t**2*48)) + k = int(k) + if k < 1: + raise ValueError("k cannot be less than 1") + if not derivative in (0,1): + raise ValueError("Derivative should lie between 0 and 1") + if which == 0: + if derivative: + return ctx.findroot(lambda z: ctx.airyai(z,1), + -U(3*ctx.pi*(4*k-3)/8)) + return ctx.findroot(ctx.airyai, -T(3*ctx.pi*(4*k-1)/8)) + if which == 1 and complex == False: + if derivative: + return ctx.findroot(lambda z: ctx.airybi(z,1), + -U(3*ctx.pi*(4*k-1)/8)) + return ctx.findroot(ctx.airybi, -T(3*ctx.pi*(4*k-3)/8)) + if which == 1 and complex == True: + if derivative: + t = 3*ctx.pi*(4*k-3)/8 + 0.75j*ctx.ln2 + s = ctx.expjpi(ctx.mpf(1)/3) * T(t) + return ctx.findroot(lambda z: ctx.airybi(z,1), s) + t = 3*ctx.pi*(4*k-1)/8 + 0.75j*ctx.ln2 + s = ctx.expjpi(ctx.mpf(1)/3) * U(t) + return ctx.findroot(ctx.airybi, s) + +@defun +def airyaizero(ctx, k, derivative=0): + return _airy_zero(ctx, 0, k, derivative, False) + +@defun +def airybizero(ctx, k, derivative=0, complex=False): + return _airy_zero(ctx, 1, k, derivative, complex) + +def _scorer(ctx, z, which, kwargs): + z = ctx.convert(z) + if ctx.isinf(z): + if z == ctx.inf: + if which == 0: return 1/z + if which == 1: return z + if z == ctx.ninf: + return 1/z + raise ValueError("essential singularity") + if z: + extraprec = max(0, int(1.5*ctx.mag(z))) + else: + extraprec = 0 + if kwargs.get('derivative'): + raise NotImplementedError + # Direct asymptotic expansions, to avoid + # exponentially large cancellation + try: + if ctx.mag(z) > 3: + if which == 0 and abs(ctx.arg(z)) < ctx.pi/3 * 0.999: + def h(): + return (([ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) + return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) + if which == 1 and abs(ctx.arg(-z)) < 2*ctx.pi/3 * 0.999: + def h(): + return (([-ctx.pi,z],[-1,-1],[],[],[(1,3),(2,3),1],[],9/z**3),) + return ctx.hypercomb(h, [], maxterms=ctx.prec, force_series=True) + except ctx.NoConvergence: + pass + def h(): + A = ctx.airybi(z, **kwargs)/3 + B = -2*ctx.pi + if which == 1: + A *= 2 + B *= -1 + ctx.prec += extraprec + w = z**3/9 + ctx.prec -= extraprec + T1 = [A], [1], [], [], [], [], 0 + T2 = [B,z], [-1,2], [], [], [1], [ctx.mpq_4_3,ctx.mpq_5_3], w + return T1, T2 + return ctx.hypercomb(h, [], **kwargs) + +@defun +def scorergi(ctx, z, **kwargs): + return _scorer(ctx, z, 0, kwargs) + +@defun +def scorerhi(ctx, z, **kwargs): + return _scorer(ctx, z, 1, kwargs) + +@defun_wrapped +def coulombc(ctx, l, eta, _cache={}): + if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: + return +_cache[l,eta][1] + G3 = ctx.loggamma(2*l+2) + G1 = ctx.loggamma(1+l+ctx.j*eta) + G2 = ctx.loggamma(1+l-ctx.j*eta) + v = 2**l * ctx.exp((-ctx.pi*eta+G1+G2)/2 - G3) + if not (ctx.im(l) or ctx.im(eta)): + v = ctx.re(v) + _cache[l,eta] = (ctx.prec, v) + return v + +@defun_wrapped +def coulombf(ctx, l, eta, z, w=1, chop=True, **kwargs): + # Regular Coulomb wave function + # Note: w can be either 1 or -1; the other may be better in some cases + # TODO: check that chop=True chops when and only when it should + #ctx.prec += 10 + def h(l, eta): + try: + jw = ctx.j*w + jwz = ctx.fmul(jw, z, exact=True) + jwz2 = ctx.fmul(jwz, -2, exact=True) + C = ctx.coulombc(l, eta) + T1 = [C, z, ctx.exp(jwz)], [1, l+1, 1], [], [], [1+l+jw*eta], \ + [2*l+2], jwz2 + except ValueError: + T1 = [0], [-1], [], [], [], [], 0 + return (T1,) + v = ctx.hypercomb(h, [l,eta], **kwargs) + if chop and (not ctx.im(l)) and (not ctx.im(eta)) and (not ctx.im(z)) and \ + (ctx.re(z) >= 0): + v = ctx.re(v) + return v + +@defun_wrapped +def _coulomb_chi(ctx, l, eta, _cache={}): + if (l, eta) in _cache and _cache[l,eta][0] >= ctx.prec: + return _cache[l,eta][1] + def terms(): + l2 = -l-1 + jeta = ctx.j*eta + return [ctx.loggamma(1+l+jeta) * (-0.5j), + ctx.loggamma(1+l-jeta) * (0.5j), + ctx.loggamma(1+l2+jeta) * (0.5j), + ctx.loggamma(1+l2-jeta) * (-0.5j), + -(l+0.5)*ctx.pi] + v = ctx.sum_accurately(terms, 1) + _cache[l,eta] = (ctx.prec, v) + return v + +@defun_wrapped +def coulombg(ctx, l, eta, z, w=1, chop=True, **kwargs): + # Irregular Coulomb wave function + # Note: w can be either 1 or -1; the other may be better in some cases + # TODO: check that chop=True chops when and only when it should + if not ctx._im(l): + l = ctx._re(l) # XXX: for isint + def h(l, eta): + # Force perturbation for integers and half-integers + if ctx.isint(l*2): + T1 = [0], [-1], [], [], [], [], 0 + return (T1,) + l2 = -l-1 + try: + chi = ctx._coulomb_chi(l, eta) + jw = ctx.j*w + s = ctx.sin(chi); c = ctx.cos(chi) + C1 = ctx.coulombc(l,eta) + C2 = ctx.coulombc(l2,eta) + u = ctx.exp(jw*z) + x = -2*jw*z + T1 = [s, C1, z, u, c], [-1, 1, l+1, 1, 1], [], [], \ + [1+l+jw*eta], [2*l+2], x + T2 = [-s, C2, z, u], [-1, 1, l2+1, 1], [], [], \ + [1+l2+jw*eta], [2*l2+2], x + return T1, T2 + except ValueError: + T1 = [0], [-1], [], [], [], [], 0 + return (T1,) + v = ctx.hypercomb(h, [l,eta], **kwargs) + if chop and (not ctx._im(l)) and (not ctx._im(eta)) and (not ctx._im(z)) and \ + (ctx._re(z) >= 0): + v = ctx._re(v) + return v + +def mcmahon(ctx,kind,prime,v,m): + """ + Computes an estimate for the location of the Bessel function zero + j_{v,m}, y_{v,m}, j'_{v,m} or y'_{v,m} using McMahon's asymptotic + expansion (Abramowitz & Stegun 9.5.12-13, DLMF 20.21(vi)). + + Returns (r,err) where r is the estimated location of the root + and err is a positive number estimating the error of the + asymptotic expansion. + """ + u = 4*v**2 + if kind == 1 and not prime: b = (4*m+2*v-1)*ctx.pi/4 + if kind == 2 and not prime: b = (4*m+2*v-3)*ctx.pi/4 + if kind == 1 and prime: b = (4*m+2*v-3)*ctx.pi/4 + if kind == 2 and prime: b = (4*m+2*v-1)*ctx.pi/4 + if not prime: + s1 = b + s2 = -(u-1)/(8*b) + s3 = -4*(u-1)*(7*u-31)/(3*(8*b)**3) + s4 = -32*(u-1)*(83*u**2-982*u+3779)/(15*(8*b)**5) + s5 = -64*(u-1)*(6949*u**3-153855*u**2+1585743*u-6277237)/(105*(8*b)**7) + if prime: + s1 = b + s2 = -(u+3)/(8*b) + s3 = -4*(7*u**2+82*u-9)/(3*(8*b)**3) + s4 = -32*(83*u**3+2075*u**2-3039*u+3537)/(15*(8*b)**5) + s5 = -64*(6949*u**4+296492*u**3-1248002*u**2+7414380*u-5853627)/(105*(8*b)**7) + terms = [s1,s2,s3,s4,s5] + s = s1 + err = 0.0 + for i in range(1,len(terms)): + if abs(terms[i]) < abs(terms[i-1]): + s += terms[i] + else: + err = abs(terms[i]) + if i == len(terms)-1: + err = abs(terms[-1]) + return s, err + +def generalized_bisection(ctx,f,a,b,n): + """ + Given f known to have exactly n simple roots within [a,b], + return a list of n intervals isolating the roots + and having opposite signs at the endpoints. + + TODO: this can be optimized, e.g. by reusing evaluation points. + """ + if n < 1: + raise ValueError("n cannot be less than 1") + N = n+1 + points = [] + signs = [] + while 1: + points = ctx.linspace(a,b,N) + signs = [ctx.sign(f(x)) for x in points] + ok_intervals = [(points[i],points[i+1]) for i in range(N-1) \ + if signs[i]*signs[i+1] == -1] + if len(ok_intervals) == n: + return ok_intervals + N = N*2 + +def find_in_interval(ctx, f, ab): + return ctx.findroot(f, ab, solver='illinois', verify=False) + +def bessel_zero(ctx, kind, prime, v, m, isoltol=0.01, _interval_cache={}): + prec = ctx.prec + workprec = max(prec, ctx.mag(v), ctx.mag(m))+10 + try: + ctx.prec = workprec + v = ctx.mpf(v) + m = int(m) + prime = int(prime) + if v < 0: + raise ValueError("v cannot be negative") + if m < 1: + raise ValueError("m cannot be less than 1") + if not prime in (0,1): + raise ValueError("prime should lie between 0 and 1") + if kind == 1: + if prime: f = lambda x: ctx.besselj(v,x,derivative=1) + else: f = lambda x: ctx.besselj(v,x) + if kind == 2: + if prime: f = lambda x: ctx.bessely(v,x,derivative=1) + else: f = lambda x: ctx.bessely(v,x) + # The first root of J' is very close to 0 for small + # orders, and this needs to be special-cased + if kind == 1 and prime and m == 1: + if v == 0: + return ctx.zero + if v <= 1: + # TODO: use v <= j'_{v,1} < y_{v,1}? + r = 2*ctx.sqrt(v*(1+v)/(v+2)) + return find_in_interval(ctx, f, (r/10, 2*r)) + if (kind,prime,v,m) in _interval_cache: + return find_in_interval(ctx, f, _interval_cache[kind,prime,v,m]) + r, err = mcmahon(ctx, kind, prime, v, m) + if err < isoltol: + return find_in_interval(ctx, f, (r-isoltol, r+isoltol)) + # An x such that 0 < x < r_{v,1} + if kind == 1 and not prime: low = 2.4 + if kind == 1 and prime: low = 1.8 + if kind == 2 and not prime: low = 0.8 + if kind == 2 and prime: low = 2.0 + n = m+1 + while 1: + r1, err = mcmahon(ctx, kind, prime, v, n) + if err < isoltol: + r2, err2 = mcmahon(ctx, kind, prime, v, n+1) + intervals = generalized_bisection(ctx, f, low, 0.5*(r1+r2), n) + for k, ab in enumerate(intervals): + _interval_cache[kind,prime,v,k+1] = ab + return find_in_interval(ctx, f, intervals[m-1]) + else: + n = n*2 + finally: + ctx.prec = prec + +@defun +def besseljzero(ctx, v, m, derivative=0): + r""" + For a real order `\nu \ge 0` and a positive integer `m`, returns + `j_{\nu,m}`, the `m`-th positive zero of the Bessel function of the + first kind `J_{\nu}(z)` (see :func:`~mpmath.besselj`). Alternatively, + with *derivative=1*, gives the first nonnegative simple zero + `j'_{\nu,m}` of `J'_{\nu}(z)`. + + The indexing convention is that used by Abramowitz & Stegun + and the DLMF. Note the special case `j'_{0,1} = 0`, while all other + zeros are positive. In effect, only simple zeros are counted + (all zeros of Bessel functions are simple except possibly `z = 0`) + and `j_{\nu,m}` becomes a monotonic function of both `\nu` + and `m`. + + The zeros are interlaced according to the inequalities + + .. math :: + + j'_{\nu,k} < j_{\nu,k} < j'_{\nu,k+1} + + j_{\nu,1} < j_{\nu+1,2} < j_{\nu,2} < j_{\nu+1,2} < j_{\nu,3} < \cdots + + **Examples** + + Initial zeros of the Bessel functions `J_0(z), J_1(z), J_2(z)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> besseljzero(0,1); besseljzero(0,2); besseljzero(0,3) + 2.404825557695772768621632 + 5.520078110286310649596604 + 8.653727912911012216954199 + >>> besseljzero(1,1); besseljzero(1,2); besseljzero(1,3) + 3.831705970207512315614436 + 7.01558666981561875353705 + 10.17346813506272207718571 + >>> besseljzero(2,1); besseljzero(2,2); besseljzero(2,3) + 5.135622301840682556301402 + 8.417244140399864857783614 + 11.61984117214905942709415 + + Initial zeros of `J'_0(z), J'_1(z), J'_2(z)`:: + + 0.0 + 3.831705970207512315614436 + 7.01558666981561875353705 + >>> besseljzero(1,1,1); besseljzero(1,2,1); besseljzero(1,3,1) + 1.84118378134065930264363 + 5.331442773525032636884016 + 8.536316366346285834358961 + >>> besseljzero(2,1,1); besseljzero(2,2,1); besseljzero(2,3,1) + 3.054236928227140322755932 + 6.706133194158459146634394 + 9.969467823087595793179143 + + Zeros with large index:: + + >>> besseljzero(0,100); besseljzero(0,1000); besseljzero(0,10000) + 313.3742660775278447196902 + 3140.807295225078628895545 + 31415.14114171350798533666 + >>> besseljzero(5,100); besseljzero(5,1000); besseljzero(5,10000) + 321.1893195676003157339222 + 3148.657306813047523500494 + 31422.9947255486291798943 + >>> besseljzero(0,100,1); besseljzero(0,1000,1); besseljzero(0,10000,1) + 311.8018681873704508125112 + 3139.236339643802482833973 + 31413.57032947022399485808 + + Zeros of functions with large order:: + + >>> besseljzero(50,1) + 57.11689916011917411936228 + >>> besseljzero(50,2) + 62.80769876483536093435393 + >>> besseljzero(50,100) + 388.6936600656058834640981 + >>> besseljzero(50,1,1) + 52.99764038731665010944037 + >>> besseljzero(50,2,1) + 60.02631933279942589882363 + >>> besseljzero(50,100,1) + 387.1083151608726181086283 + + Zeros of functions with fractional order:: + + >>> besseljzero(0.5,1); besseljzero(1.5,1); besseljzero(2.25,4) + 3.141592653589793238462643 + 4.493409457909064175307881 + 15.15657692957458622921634 + + Both `J_{\nu}(z)` and `J'_{\nu}(z)` can be expressed as infinite + products over their zeros:: + + >>> v,z = 2, mpf(1) + >>> (z/2)**v/gamma(v+1) * \ + ... nprod(lambda k: 1-(z/besseljzero(v,k))**2, [1,inf]) + ... + 0.1149034849319004804696469 + >>> besselj(v,z) + 0.1149034849319004804696469 + >>> (z/2)**(v-1)/2/gamma(v) * \ + ... nprod(lambda k: 1-(z/besseljzero(v,k,1))**2, [1,inf]) + ... + 0.2102436158811325550203884 + >>> besselj(v,z,1) + 0.2102436158811325550203884 + + """ + return +bessel_zero(ctx, 1, derivative, v, m) + +@defun +def besselyzero(ctx, v, m, derivative=0): + r""" + For a real order `\nu \ge 0` and a positive integer `m`, returns + `y_{\nu,m}`, the `m`-th positive zero of the Bessel function of the + second kind `Y_{\nu}(z)` (see :func:`~mpmath.bessely`). Alternatively, + with *derivative=1*, gives the first positive zero `y'_{\nu,m}` of + `Y'_{\nu}(z)`. + + The zeros are interlaced according to the inequalities + + .. math :: + + y_{\nu,k} < y'_{\nu,k} < y_{\nu,k+1} + + y_{\nu,1} < y_{\nu+1,2} < y_{\nu,2} < y_{\nu+1,2} < y_{\nu,3} < \cdots + + **Examples** + + Initial zeros of the Bessel functions `Y_0(z), Y_1(z), Y_2(z)`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> besselyzero(0,1); besselyzero(0,2); besselyzero(0,3) + 0.8935769662791675215848871 + 3.957678419314857868375677 + 7.086051060301772697623625 + >>> besselyzero(1,1); besselyzero(1,2); besselyzero(1,3) + 2.197141326031017035149034 + 5.429681040794135132772005 + 8.596005868331168926429606 + >>> besselyzero(2,1); besselyzero(2,2); besselyzero(2,3) + 3.384241767149593472701426 + 6.793807513268267538291167 + 10.02347797936003797850539 + + Initial zeros of `Y'_0(z), Y'_1(z), Y'_2(z)`:: + + >>> besselyzero(0,1,1); besselyzero(0,2,1); besselyzero(0,3,1) + 2.197141326031017035149034 + 5.429681040794135132772005 + 8.596005868331168926429606 + >>> besselyzero(1,1,1); besselyzero(1,2,1); besselyzero(1,3,1) + 3.683022856585177699898967 + 6.941499953654175655751944 + 10.12340465543661307978775 + >>> besselyzero(2,1,1); besselyzero(2,2,1); besselyzero(2,3,1) + 5.002582931446063945200176 + 8.350724701413079526349714 + 11.57419546521764654624265 + + Zeros with large index:: + + >>> besselyzero(0,100); besselyzero(0,1000); besselyzero(0,10000) + 311.8034717601871549333419 + 3139.236498918198006794026 + 31413.57034538691205229188 + >>> besselyzero(5,100); besselyzero(5,1000); besselyzero(5,10000) + 319.6183338562782156235062 + 3147.086508524556404473186 + 31421.42392920214673402828 + >>> besselyzero(0,100,1); besselyzero(0,1000,1); besselyzero(0,10000,1) + 313.3726705426359345050449 + 3140.807136030340213610065 + 31415.14112579761578220175 + + Zeros of functions with large order:: + + >>> besselyzero(50,1) + 53.50285882040036394680237 + >>> besselyzero(50,2) + 60.11244442774058114686022 + >>> besselyzero(50,100) + 387.1096509824943957706835 + >>> besselyzero(50,1,1) + 56.96290427516751320063605 + >>> besselyzero(50,2,1) + 62.74888166945933944036623 + >>> besselyzero(50,100,1) + 388.6923300548309258355475 + + Zeros of functions with fractional order:: + + >>> besselyzero(0.5,1); besselyzero(1.5,1); besselyzero(2.25,4) + 1.570796326794896619231322 + 2.798386045783887136720249 + 13.56721208770735123376018 + + """ + return +bessel_zero(ctx, 2, derivative, v, m) diff --git a/shared/package-files/75/75451687b5c0c7492a340e7ab377ccdd94f75ad1153474080152d18b672f5e3b/blob b/shared/package-files/75/75451687b5c0c7492a340e7ab377ccdd94f75ad1153474080152d18b672f5e3b/blob new file mode 100644 index 0000000000000000000000000000000000000000..50530de9e91b79bd05386ab4d3a73756a75fbf9b --- /dev/null +++ b/shared/package-files/75/75451687b5c0c7492a340e7ab377ccdd94f75ad1153474080152d18b672f5e3b/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor prod(const at::Tensor & self, c10::optional dtype=c10::nullopt); +TORCH_API at::Tensor prod(const at::Tensor & self, int64_t dim, bool keepdim=false, c10::optional dtype=c10::nullopt); +TORCH_API at::Tensor & prod_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool keepdim=false, c10::optional dtype=c10::nullopt); +TORCH_API at::Tensor & prod_outf(const at::Tensor & self, int64_t dim, bool keepdim, c10::optional dtype, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/75/75468aa931383117d4ab6ad65576dba2eee4cc3ed9f4f13d2a8f1a5cbcdaf090/blob b/shared/package-files/75/75468aa931383117d4ab6ad65576dba2eee4cc3ed9f4f13d2a8f1a5cbcdaf090/blob new file mode 100644 index 0000000000000000000000000000000000000000..47f237006caeac212840f23a8c2568947523c596 --- /dev/null +++ b/shared/package-files/75/75468aa931383117d4ab6ad65576dba2eee4cc3ed9f4f13d2a8f1a5cbcdaf090/blob @@ -0,0 +1,21 @@ +# Seaborn poster context +figure.figsize: 12.8, 8.8 +axes.labelsize: 17.6 +axes.titlesize: 19.2 +xtick.labelsize: 16 +ytick.labelsize: 16 +legend.fontsize: 16 + +grid.linewidth: 1.6 +lines.linewidth: 2.8 +patch.linewidth: 0.48 +lines.markersize: 11.2 +lines.markeredgewidth: 0 + +xtick.major.width: 1.6 +ytick.major.width: 1.6 +xtick.minor.width: 0.8 +ytick.minor.width: 0.8 + +xtick.major.pad: 11.2 +ytick.major.pad: 11.2 diff --git a/shared/package-files/75/7547c37c87687ca62e7f0c36f6357c9954268255350271b6b84c91129358ed5d/blob b/shared/package-files/75/7547c37c87687ca62e7f0c36f6357c9954268255350271b6b84c91129358ed5d/blob new file mode 100644 index 0000000000000000000000000000000000000000..6f244b4279f1e44e3f76d82ab9336a12b437a375 --- /dev/null +++ b/shared/package-files/75/7547c37c87687ca62e7f0c36f6357c9954268255350271b6b84c91129358ed5d/blob @@ -0,0 +1,153 @@ +import pickle + +from sympy.core.relational import (Eq, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.external import import_module +from sympy.testing.pytest import skip +from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar, Replacer + +matchpy = import_module("matchpy") + +x, y, z = symbols("x y z") + + +def _get_first_match(expr, pattern): + from matchpy import ManyToOneMatcher, Pattern + + matcher = ManyToOneMatcher() + matcher.add(Pattern(pattern)) + return next(iter(matcher.match(expr))) + + +def test_matchpy_connector(): + if matchpy is None: + skip("matchpy not installed") + + from multiset import Multiset + from matchpy import Pattern, Substitution + + w_ = WildDot("w_") + w__ = WildPlus("w__") + w___ = WildStar("w___") + + expr = x + y + pattern = x + w_ + p, subst = _get_first_match(expr, pattern) + assert p == Pattern(pattern) + assert subst == Substitution({'w_': y}) + + expr = x + y + z + pattern = x + w__ + p, subst = _get_first_match(expr, pattern) + assert p == Pattern(pattern) + assert subst == Substitution({'w__': Multiset([y, z])}) + + expr = x + y + z + pattern = x + y + z + w___ + p, subst = _get_first_match(expr, pattern) + assert p == Pattern(pattern) + assert subst == Substitution({'w___': Multiset()}) + + +def test_matchpy_optional(): + if matchpy is None: + skip("matchpy not installed") + + from matchpy import Pattern, Substitution + from matchpy import ManyToOneReplacer, ReplacementRule + + p = WildDot("p", optional=1) + q = WildDot("q", optional=0) + + pattern = p*x + q + + expr1 = 2*x + pa, subst = _get_first_match(expr1, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': 2, 'q': 0}) + + expr2 = x + 3 + pa, subst = _get_first_match(expr2, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': 1, 'q': 3}) + + expr3 = x + pa, subst = _get_first_match(expr3, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': 1, 'q': 0}) + + expr4 = x*y + z + pa, subst = _get_first_match(expr4, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': y, 'q': z}) + + replacer = ManyToOneReplacer() + replacer.add(ReplacementRule(Pattern(pattern), lambda p, q: sin(p)*cos(q))) + assert replacer.replace(expr1) == sin(2)*cos(0) + assert replacer.replace(expr2) == sin(1)*cos(3) + assert replacer.replace(expr3) == sin(1)*cos(0) + assert replacer.replace(expr4) == sin(y)*cos(z) + + +def test_replacer(): + if matchpy is None: + skip("matchpy not installed") + + x1_ = WildDot("x1_") + x2_ = WildDot("x2_") + + a_ = WildDot("a_", optional=S.One) + b_ = WildDot("b_", optional=S.One) + c_ = WildDot("c_", optional=S.Zero) + + replacer = Replacer(common_constraints=[ + matchpy.CustomConstraint(lambda a_: not a_.has(x)), + matchpy.CustomConstraint(lambda b_: not b_.has(x)), + matchpy.CustomConstraint(lambda c_: not c_.has(x)), + ]) + + # Rewrite the equation into implicit form, unless it's already solved: + replacer.add(Eq(x1_, x2_), Eq(x1_ - x2_, 0), conditions_nonfalse=[Ne(x2_, 0), Ne(x1_, 0), Ne(x1_, x), Ne(x2_, x)]) + + # Simple equation solver for real numbers: + replacer.add(Eq(a_*x + b_, 0), Eq(x, -b_/a_)) + disc = b_**2 - 4*a_*c_ + replacer.add( + Eq(a_*x**2 + b_*x + c_, 0), + Eq(x, (-b_ - sqrt(disc))/(2*a_)) | Eq(x, (-b_ + sqrt(disc))/(2*a_)), + conditions_nonfalse=[disc >= 0] + ) + replacer.add( + Eq(a_*x**2 + c_, 0), + Eq(x, sqrt(-c_/a_)) | Eq(x, -sqrt(-c_/a_)), + conditions_nonfalse=[-c_*a_ > 0] + ) + + assert replacer.replace(Eq(3*x, y)) == Eq(x, y/3) + assert replacer.replace(Eq(x**2 + 1, 0)) == Eq(x**2 + 1, 0) + assert replacer.replace(Eq(x**2, 4)) == (Eq(x, 2) | Eq(x, -2)) + assert replacer.replace(Eq(x**2 + 4*y*x + 4*y**2, 0)) == Eq(x, -2*y) + + +def test_matchpy_object_pickle(): + if matchpy is None: + return + + a1 = WildDot("a") + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 + + a1 = WildDot("a", S(1)) + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 + + a1 = WildPlus("a", S(1)) + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 + + a1 = WildStar("a", S(1)) + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 diff --git a/shared/package-files/75/754aa574f3e220d8c28f6e8e9f5c4e17d5e1fb17cae447a429cd33485633992b/blob b/shared/package-files/75/754aa574f3e220d8c28f6e8e9f5c4e17d5e1fb17cae447a429cd33485633992b/blob new file mode 100644 index 0000000000000000000000000000000000000000..5e8ad855dda3d589b9df3ec6d86da5d65220b07c --- /dev/null +++ b/shared/package-files/75/754aa574f3e220d8c28f6e8e9f5c4e17d5e1fb17cae447a429cd33485633992b/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor isposinf(const at::Tensor & self); +TORCH_API at::Tensor & isposinf_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & isposinf_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/75/754af9bf9ddc4794b8d2bef5402015cb4a9474a3313af89a5804f4a6dadc8d34/blob b/shared/package-files/75/754af9bf9ddc4794b8d2bef5402015cb4a9474a3313af89a5804f4a6dadc8d34/blob new file mode 100644 index 0000000000000000000000000000000000000000..fd64c6d0c3069eceb5a347111f1ac77bea8ea942 --- /dev/null +++ b/shared/package-files/75/754af9bf9ddc4794b8d2bef5402015cb4a9474a3313af89a5804f4a6dadc8d34/blob @@ -0,0 +1,309 @@ +""" +Python wrapper for PROPACK +-------------------------- + +PROPACK is a collection of Fortran routines for iterative computation +of partial SVDs of large matrices or linear operators. + +Based on BSD licensed pypropack project: + http://github.com/jakevdp/pypropack + Author: Jake Vanderplas + +PROPACK source is BSD licensed, and available at + http://soi.stanford.edu/~rmunk/PROPACK/ +""" + +__all__ = ['_svdp'] + +import numpy as np + +from scipy.sparse.linalg import aslinearoperator +from scipy.linalg import LinAlgError + +from ._propack import _spropack # type: ignore[attr-defined] +from ._propack import _dpropack # type: ignore[attr-defined] +from ._propack import _cpropack # type: ignore[attr-defined] +from ._propack import _zpropack # type: ignore[attr-defined] + + +_lansvd_dict = { + 'f': _spropack.slansvd, + 'd': _dpropack.dlansvd, + 'F': _cpropack.clansvd, + 'D': _zpropack.zlansvd, +} + + +_lansvd_irl_dict = { + 'f': _spropack.slansvd_irl, + 'd': _dpropack.dlansvd_irl, + 'F': _cpropack.clansvd_irl, + 'D': _zpropack.zlansvd_irl, +} + +_which_converter = { + 'LM': 'L', + 'SM': 'S', +} + + +class _AProd: + """ + Wrapper class for linear operator + + The call signature of the __call__ method matches the callback of + the PROPACK routines. + """ + def __init__(self, A): + try: + self.A = aslinearoperator(A) + except TypeError: + self.A = aslinearoperator(np.asarray(A)) + + def __call__(self, transa, m, n, x, y, sparm, iparm): + if transa == 'n': + y[:] = self.A.matvec(x) + else: + y[:] = self.A.rmatvec(x) + + @property + def shape(self): + return self.A.shape + + @property + def dtype(self): + try: + return self.A.dtype + except AttributeError: + return self.A.matvec(np.zeros(self.A.shape[1])).dtype + + +def _svdp(A, k, which='LM', irl_mode=True, kmax=None, + compute_u=True, compute_v=True, v0=None, full_output=False, tol=0, + delta=None, eta=None, anorm=0, cgs=False, elr=True, + min_relgap=0.002, shifts=None, maxiter=None, rng=None): + """ + Compute the singular value decomposition of a linear operator using PROPACK + + Parameters + ---------- + A : array_like, sparse matrix, or LinearOperator + Operator for which SVD will be computed. If `A` is a LinearOperator + object, it must define both ``matvec`` and ``rmatvec`` methods. + k : int + Number of singular values/vectors to compute + which : {"LM", "SM"} + Which singular triplets to compute: + - 'LM': compute triplets corresponding to the `k` largest singular + values + - 'SM': compute triplets corresponding to the `k` smallest singular + values + `which='SM'` requires `irl_mode=True`. Computes largest singular + values by default. + irl_mode : bool, optional + If `True`, then compute SVD using IRL (implicitly restarted Lanczos) + mode. Default is `True`. + kmax : int, optional + Maximal number of iterations / maximal dimension of the Krylov + subspace. Default is ``10 * k``. + compute_u : bool, optional + If `True` (default) then compute left singular vectors, `u`. + compute_v : bool, optional + If `True` (default) then compute right singular vectors, `v`. + tol : float, optional + The desired relative accuracy for computed singular values. + If not specified, it will be set based on machine precision. + v0 : array_like, optional + Starting vector for iterations: must be of length ``A.shape[0]``. + If not specified, PROPACK will generate a starting vector. + full_output : bool, optional + If `True`, then return sigma_bound. Default is `False`. + delta : float, optional + Level of orthogonality to maintain between Lanczos vectors. + Default is set based on machine precision. + eta : float, optional + Orthogonality cutoff. During reorthogonalization, vectors with + component larger than `eta` along the Lanczos vector will be purged. + Default is set based on machine precision. + anorm : float, optional + Estimate of ``||A||``. Default is ``0``. + cgs : bool, optional + If `True`, reorthogonalization is done using classical Gram-Schmidt. + If `False` (default), it is done using modified Gram-Schmidt. + elr : bool, optional + If `True` (default), then extended local orthogonality is enforced + when obtaining singular vectors. + min_relgap : float, optional + The smallest relative gap allowed between any shift in IRL mode. + Default is ``0.001``. Accessed only if ``irl_mode=True``. + shifts : int, optional + Number of shifts per restart in IRL mode. Default is determined + to satisfy ``k <= min(kmax-shifts, m, n)``. Must be + >= 0, but choosing 0 might lead to performance degradation. + Accessed only if ``irl_mode=True``. + maxiter : int, optional + Maximum number of restarts in IRL mode. Default is ``1000``. + Accessed only if ``irl_mode=True``. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + u : ndarray + The `k` largest (``which="LM"``) or smallest (``which="SM"``) left + singular vectors, ``shape == (A.shape[0], 3)``, returned only if + ``compute_u=True``. + sigma : ndarray + The top `k` singular values, ``shape == (k,)`` + vt : ndarray + The `k` largest (``which="LM"``) or smallest (``which="SM"``) right + singular vectors, ``shape == (3, A.shape[1])``, returned only if + ``compute_v=True``. + sigma_bound : ndarray + the error bounds on the singular values sigma, returned only if + ``full_output=True``. + + """ + if rng is None: + raise ValueError("`rng` must be a normalized numpy.random.Generator instance") + + which = which.upper() + if which not in {'LM', 'SM'}: + raise ValueError("`which` must be either 'LM' or 'SM'") + if not irl_mode and which == 'SM': + raise ValueError("`which`='SM' requires irl_mode=True") + + aprod = _AProd(A) + typ = aprod.dtype.char + + try: + lansvd_irl = _lansvd_irl_dict[typ] + lansvd = _lansvd_dict[typ] + except KeyError: + # work with non-supported types using native system precision + if np.iscomplexobj(np.empty(0, dtype=typ)): + typ = np.dtype(complex).char + else: + typ = np.dtype(float).char + lansvd_irl = _lansvd_irl_dict[typ] + lansvd = _lansvd_dict[typ] + + m, n = aprod.shape + if (k < 1) or (k > min(m, n)): + raise ValueError("k must be positive and not greater than m or n") + + if kmax is None: + kmax = 10*k + if maxiter is None: + maxiter = 1000 + + # guard against unnecessarily large kmax + kmax = min(m + 1, n + 1, kmax) + if kmax < k: + raise ValueError( + "kmax must be greater than or equal to k, " + f"but kmax ({kmax}) < k ({k})") + + # convert python args to fortran args + jobu = 'y' if compute_u else 'n' + jobv = 'y' if compute_v else 'n' + + # these will be the output arrays + u = np.zeros((m, kmax + 1), order='F', dtype=typ) + v = np.zeros((n, kmax), order='F', dtype=typ) + + # Specify the starting vector. if v0 is all zero, PROPACK will generate + # a random starting vector: the random seed cannot be controlled in that + # case, so we'll instead use numpy to generate a random vector + if v0 is None: + u[:, 0] = rng.uniform(size=m) + if np.iscomplexobj(np.empty(0, dtype=typ)): # complex type + u[:, 0] += 1j * rng.uniform(size=m) + else: + try: + u[:, 0] = v0 + except ValueError: + raise ValueError(f"v0 must be of length {m}") + + # process options for the fit + if delta is None: + delta = np.sqrt(np.finfo(typ).eps) + if eta is None: + eta = np.finfo(typ).eps ** 0.75 + + if irl_mode: + doption = np.array((delta, eta, anorm, min_relgap), dtype=typ.lower()) + + # validate or find default shifts + if shifts is None: + shifts = kmax - k + if k > min(kmax - shifts, m, n): + raise ValueError('shifts must satisfy ' + 'k <= min(kmax-shifts, m, n)!') + elif shifts < 0: + raise ValueError('shifts must be >= 0!') + + else: + doption = np.array((delta, eta, anorm), dtype=typ.lower()) + + ioption = np.array((int(bool(cgs)), int(bool(elr))), dtype='i') + + # If computing `u` or `v` (left and right singular vectors, + # respectively), `blocksize` controls how large a fraction of the + # work is done via fast BLAS level 3 operations. A larger blocksize + # may lead to faster computation at the expense of greater memory + # consumption. `blocksize` must be ``>= 1``. Choosing blocksize + # of 16, but docs don't specify; it's almost surely a + # power of 2. + blocksize = 16 + + # Determine lwork & liwork: + # the required lengths are specified in the PROPACK documentation + if compute_u or compute_v: + lwork = m + n + 9*kmax + 5*kmax*kmax + 4 + max( + 3*kmax*kmax + 4*kmax + 4, + blocksize*max(m, n)) + liwork = 8*kmax + else: + lwork = m + n + 9*kmax + 2*kmax*kmax + 4 + max(m + n, 4*kmax + 4) + liwork = 2*kmax + 1 + work = np.empty(lwork, dtype=typ.lower()) + iwork = np.empty(liwork, dtype=np.int32) + + # dummy arguments: these are passed to aprod, and not used in this wrapper + dparm = np.empty(1, dtype=typ.lower()) + iparm = np.empty(1, dtype=np.int32) + + if typ.isupper(): + # PROPACK documentation is unclear on the required length of zwork. + # Use the same length Julia's wrapper uses + # see https://github.com/JuliaSmoothOptimizers/PROPACK.jl/ + zwork = np.empty(m + n + 32*m, dtype=typ) + works = work, zwork, iwork + else: + works = work, iwork + + if irl_mode: + u, sigma, bnd, v, info = lansvd_irl(_which_converter[which], jobu, + jobv, m, n, shifts, k, maxiter, + aprod, u, v, tol, *works, doption, + ioption, dparm, iparm) + else: + u, sigma, bnd, v, info = lansvd(jobu, jobv, m, n, k, aprod, u, v, tol, + *works, doption, ioption, dparm, iparm) + + if info > 0: + raise LinAlgError( + f"An invariant subspace of dimension {info} was found.") + elif info < 0: + raise LinAlgError( + f"k={k} singular triplets did not converge within " + f"kmax={kmax} iterations") + + # info == 0: The K largest (or smallest) singular triplets were computed + # successfully! + + return u[:, :k], sigma, v[:, :k].conj().T, bnd diff --git a/shared/package-files/75/754b92bbc50434879a89fe3fb69bcd4581a38f4fa4fefe68e24a556d64983f88/blob b/shared/package-files/75/754b92bbc50434879a89fe3fb69bcd4581a38f4fa4fefe68e24a556d64983f88/blob new file mode 100644 index 0000000000000000000000000000000000000000..1cf9bcefcfc6e3071c97f0dff3c9fad5f2cbdfa8 --- /dev/null +++ b/shared/package-files/75/754b92bbc50434879a89fe3fb69bcd4581a38f4fa4fefe68e24a556d64983f88/blob @@ -0,0 +1,258 @@ +import inspect +from collections import defaultdict +from typing import Any, Callable, Dict, List, Tuple, Union + +import torch +from torch._dynamo.source import ( + AttrSource, + GetItemSource, + LocalSource, + TensorProperty, + TensorPropertySource, +) +from torch._dynamo.variables.builder import TrackedFake +from torch._export.passes.add_runtime_assertions_for_constraints_pass import InputDim +from torch._guards import Source +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.export import Constraint +from torch.export.graph_signature import CustomObjArgument +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + EqualityConstraint, + ShapeEnv, + StatelessSymbolicContext, +) +from torch.utils._pytree import ( + GetAttrKey, + KeyPath, + MappingKey, + SequenceKey, + tree_map_with_path, +) + + +def key_path_to_source(kp: KeyPath) -> Source: + """ + Given a key path, return the source for the key path. + """ + source: Source = LocalSource("args") + for k in kp: + if isinstance(k, SequenceKey): + source = GetItemSource(source, k.idx) + elif isinstance(k, MappingKey): + source = GetItemSource(source, k.key) + elif isinstance(k, GetAttrKey): + source = AttrSource(source, k.name) + else: + raise ValueError(f"Unknown KeyEntry {k}") + + return source + + +def _is_constant_argument(t): + return t is None or isinstance(t, (int, float, bool, str)) + + +def fakify( + mode: FakeTensorMode, + kp: KeyPath, + t: Any, + t_constraints: Dict[int, Dict[int, Constraint]], + sources: Dict[Tuple[int, int], List[Source]], +): + source = key_path_to_source(kp) + if _is_constant_argument(t) or isinstance(t, torch.ScriptObject): + return t + if not isinstance(t, torch.Tensor): + raise ValueError(f"Unsupported input type {type(t)}") + n_dims = len(t.shape) + symbolic_context = StatelessSymbolicContext( + dynamic_sizes=[DimDynamic.STATIC] * n_dims, + constraint_sizes=[None] * n_dims, + ) + t_id = id(t) + if t_id in t_constraints: + for i, constraint in t_constraints[t_id].items(): + symbolic_context.constraint_sizes[i] = constraint.constraint_range + symbolic_context.dynamic_sizes[i] = DimDynamic.DYNAMIC + src = TensorPropertySource(base=source, prop=TensorProperty.SIZE, idx=i) + sources[(t_id, i)].append(src) + mode.shape_env.source_name_to_debug_name[src.name()] = constraint.debug_name + fake = mode.from_tensor(t, source=source, symbolic_context=symbolic_context) + mode.shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context)) + return fake + + +def make_fake_params_buffers( + fake_mode: FakeTensorMode, + params_buffers: Dict[str, torch.Tensor], +) -> Dict[str, Union[torch.Tensor, torch.nn.Parameter]]: + faked_params_buffers = {} + for key, value in params_buffers.items(): + faked_params_buffers[key] = fake_mode.from_tensor(value, static_shapes=True) + return faked_params_buffers + + +def make_fake_inputs(nn_module, args, kwargs, constraints): + """ + Given an nn module, example inputs, and constraints, return a new fake mode, + fake inputs created in that mode whose dynamic shape dimensions are constrained + by the given ranges, and sources for pairs of dynamic shape dimensions that are + constrained to be equal. + """ + # TODO(avik): refactor Dynamo to avoid duplication of the following code + # between non-strict and strict. + # Specifically, here (non-strict) we do the following pre-tracing steps: + # - Fakify inputs. + # - Process input shape equalities. + # In strict, these steps are spread across multiple files: + # - output_graph.py fakifies inputs. + # - [post-tracing] guards.py processes input shape equalities. + + t_constraints: Dict[int, Dict[int, Constraint]] = defaultdict(dict) + for constraint in constraints: + t_constraints[constraint.t_id][constraint.dim] = constraint + if constraint.shared is not None: + t_constraints[constraint.shared.t_id][constraint.shared.dim] = constraint + + code = nn_module.forward.__code__ + co_fields = { + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + } + + fake_mode = FakeTensorMode( + shape_env=ShapeEnv(tracked_fakes=[], co_fields=co_fields), + allow_non_fake_inputs=True, + ) + if fake_mode.shape_env is None or fake_mode.shape_env.tracked_fakes is None: + raise ValueError( + "Detected fake_mode does not have a shape_env with tracked fakes. " + "If you constructed the module under a FakeTensorMode, " + "please initialize it like: FakeTensorMode(shape_env=ShapeEnv(tracked_fakes=[]))" + ) + + with fake_mode: + original_signature = inspect.signature(nn_module.forward) + sources: Dict[Tuple[int, int], List[Source]] = defaultdict(list) + fake_args, fake_kwargs = tree_map_with_path( + lambda kp, val: fakify(fake_mode, kp, val, t_constraints, sources), + (args, kwargs), + ) + + from sympy import Symbol + + source_pairs: List[Tuple[Source, Source]] = [] + derived_equalities: List[Tuple[Source, Union[Source, Symbol], Callable]] = [] + phantom_symbols: Dict[str, Symbol] = {} + for constraint in constraints: + torch.export.dynamic_shapes._process_equalities( + constraint, + lambda t_id, dim: sources[(t_id, dim)], + fake_mode.shape_env, + source_pairs, + derived_equalities, + phantom_symbols, + ) + + equalities_inputs = EqualityConstraint( + source_pairs=source_pairs, + derived_equalities=derived_equalities, + phantom_symbols=list(phantom_symbols.values()), + warn_only=False, + ) + return fake_mode, fake_args, fake_kwargs, equalities_inputs, original_signature + + +def make_constraints( + fake_mode, + equalities_inputs, + original_signature, + gm, +): + """ + Given a fake mode, sources pairs corresponding to equal dynamic shape dimensions, + and a graph module, produce guards on the fake mode's shape env (raising constraint + violations if any), solve (to suggest simplifications or fixes), and return the + resulting range constraints and equality constraints. + """ + # TODO(avik): refactor Dynamo to avoid duplication of the following code + # between non-strict and strict. + # Specifically, here (non-strict) we do the following post-tracing steps: + # - Produce guards. + # - Solve constraints. + # - Install shape metadata in IR. + # In strict, these steps are spread across multiple files: + # - guards.py produces guards. + # - eval_frame.py solves constraints + # - _trace.py installs shape metadata in IR. + + shape_env = fake_mode.shape_env + placeholders = [tf.fake for tf in shape_env.tracked_fakes] + sources = [tf.source for tf in shape_env.tracked_fakes] + input_contexts = [tf.symbolic_context for tf in shape_env.tracked_fakes] + constraint_violation_error = None + try: + shape_env.produce_guards( + placeholders, + sources, + input_contexts=input_contexts, + equalities_inputs=equalities_inputs, + ignore_static=False, + ) + except ConstraintViolationError as e: + constraint_violation_error = e + + shape_env.frozen = True + dim_constraints = shape_env.dim_constraints + if dim_constraints is None: + # Expected when shape_env.produce_guards throws an early constraint violation error. + # There is nothing to solve for in this case. + # TODO(avik): Maybe record the constraint violation error instead and replay later? + assert constraint_violation_error + raise constraint_violation_error + dim_constraints.solve() + dim_constraints.remove_redundant_dynamic_results() + forced_specializations = dim_constraints.forced_specializations() + msg = dim_constraints.prettify_results( + original_signature, constraint_violation_error, forced_specializations + ) + if constraint_violation_error: + constraint_violation_error.args = (constraint_violation_error.args[0] + msg,) + elif forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + if constraint_violation_error: + raise constraint_violation_error + + range_constraints = {} + input_dims = defaultdict(list) + free_symbols = set() + for node in gm.graph.nodes: + if node.op != "placeholder": + continue + if _is_constant_argument(node.meta["val"]) or isinstance( + node.meta["val"], CustomObjArgument + ): + continue + for i, d in enumerate(node.meta["val"].shape): + if isinstance(d, torch.SymInt): + # Look up the range constraint for the symbol corresponding to this shape dimension + # and store it indexed by the symbolic expression corresponding to it. + # NOTE(avik): Use node._expr instead of node.expr for the lookup here because + # we want the symbol, not its replacement, which could be an expression. Maybe + # there's a better way to do this, e.g., by (re)computing value ranges for expressions? + range_constraints[d.node.expr] = shape_env.var_to_range[d.node._expr] + input_dims[d.node.expr].append(InputDim(input_name=node.name, dim=i)) + free_symbols.update(d.node.expr.free_symbols) + + for symbol in free_symbols: + if symbol not in range_constraints: + # Placeholders can have symbolic shapes that are derived expressions. + # The above code will record direct range constraints for them + # so that we can do runtime assertions. In addition, for serde checks + # we want to record range constraints for their root symbols. + range_constraints[symbol] = shape_env.var_to_range[symbol] + + return range_constraints diff --git a/shared/package-files/75/754cd6751b89340c671985458c3a9407c0cc62d8b76f2d56ce22847c10ce941e/blob b/shared/package-files/75/754cd6751b89340c671985458c3a9407c0cc62d8b76f2d56ce22847c10ce941e/blob new file mode 100644 index 0000000000000000000000000000000000000000..25728ead5f7ea277e6e94c359d5a5603b99eeb38 --- /dev/null +++ b/shared/package-files/75/754cd6751b89340c671985458c3a9407c0cc62d8b76f2d56ce22847c10ce941e/blob @@ -0,0 +1,4 @@ +# +from .rcont import rvs_rcont1, rvs_rcont2 + +__all__ = ["rvs_rcont1", "rvs_rcont2"] diff --git a/shared/package-files/75/754cf01b8affdf215646d0d5272250956771e8fe47bd3bf3f4ef398ffacbfd4e/blob b/shared/package-files/75/754cf01b8affdf215646d0d5272250956771e8fe47bd3bf3f4ef398ffacbfd4e/blob new file mode 100644 index 0000000000000000000000000000000000000000..188e5b4769cc53829bf3e13f85ee2ee51dd1fb55 --- /dev/null +++ b/shared/package-files/75/754cf01b8affdf215646d0d5272250956771e8fe47bd3bf3f4ef398ffacbfd4e/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor _make_dual(const at::Tensor & primal, const at::Tensor & tangent, int64_t level); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/75/754ef6bf3a564228ab0b56dde391521dcc1a6c83cfb95d4b761141e71d2e8e87/blob b/shared/package-files/75/754ef6bf3a564228ab0b56dde391521dcc1a6c83cfb95d4b761141e71d2e8e87/blob new file mode 100644 index 0000000000000000000000000000000000000000..045d8fa28b448ef90dd4b5ad2642c1e4942ca324 --- /dev/null +++ b/shared/package-files/75/754ef6bf3a564228ab0b56dde391521dcc1a6c83cfb95d4b761141e71d2e8e87/blob @@ -0,0 +1,20 @@ +# Encoding file: iso8859-1, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +0080008100820083008400850086008700880089008A008B008C008D008E008F +0090009100920093009400950096009700980099009A009B009C009D009E009F +00A000A100A200A300A400A500A600A700A800A900AA00AB00AC00AD00AE00AF +00B000B100B200B300B400B500B600B700B800B900BA00BB00BC00BD00BE00BF +00C000C100C200C300C400C500C600C700C800C900CA00CB00CC00CD00CE00CF +00D000D100D200D300D400D500D600D700D800D900DA00DB00DC00DD00DE00DF +00E000E100E200E300E400E500E600E700E800E900EA00EB00EC00ED00EE00EF +00F000F100F200F300F400F500F600F700F800F900FA00FB00FC00FD00FE00FF diff --git a/shared/package-files/75/755171caa60845e1cfcaf5abcb1b2cb0555a4f4206238560f504840c9b48bd92/blob b/shared/package-files/75/755171caa60845e1cfcaf5abcb1b2cb0555a4f4206238560f504840c9b48bd92/blob new file mode 100644 index 0000000000000000000000000000000000000000..293a3ca8dfa79ec35921db7d257ab62fc0fe3499 --- /dev/null +++ b/shared/package-files/75/755171caa60845e1cfcaf5abcb1b2cb0555a4f4206238560f504840c9b48bd92/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::embedding_sparse_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq) -> Tensor +inline at::Tensor embedding_sparse_backward(const at::Tensor & grad, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq) { + return at::_ops::embedding_sparse_backward::call(grad, indices, num_weights, padding_idx, scale_grad_by_freq); +} + +} diff --git a/shared/package-files/75/7557a8be036938d7ca3b18b7dae9e5d9a8c95de3c00b1fe9659dee45cd59e21e/blob b/shared/package-files/75/7557a8be036938d7ca3b18b7dae9e5d9a8c95de3c00b1fe9659dee45cd59e21e/blob new file mode 100644 index 0000000000000000000000000000000000000000..c04823c1590f7bdca9df840cfc17c2500b66d64e --- /dev/null +++ b/shared/package-files/75/7557a8be036938d7ca3b18b7dae9e5d9a8c95de3c00b1fe9659dee45cd59e21e/blob @@ -0,0 +1,215 @@ +from distutils import log +import distutils.command.sdist as orig +import os +import sys +import io +import contextlib +from itertools import chain + +from .._importlib import metadata +from .build import _ORIGINAL_SUBCOMMANDS + +_default_revctrl = list + + +def walk_revctrl(dirname=''): + """Find all files under revision control""" + for ep in metadata.entry_points(group='setuptools.file_finders'): + for item in ep.load()(dirname): + yield item + + +class sdist(orig.sdist): + """Smart sdist that finds anything supported by revision control""" + + user_options = [ + ('formats=', None, "formats for source distribution (comma-separated list)"), + ( + 'keep-temp', + 'k', + "keep the distribution tree around after creating " + "archive file(s)", + ), + ( + 'dist-dir=', + 'd', + "directory to put the source distribution archive(s) in " "[default: dist]", + ), + ( + 'owner=', + 'u', + "Owner name used when creating a tar file [default: current user]", + ), + ( + 'group=', + 'g', + "Group name used when creating a tar file [default: current group]", + ), + ] + + negative_opt = {} + + README_EXTENSIONS = ['', '.rst', '.txt', '.md'] + READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS) + + def run(self): + self.run_command('egg_info') + ei_cmd = self.get_finalized_command('egg_info') + self.filelist = ei_cmd.filelist + self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt')) + self.check_readme() + + # Run sub commands + for cmd_name in self.get_sub_commands(): + self.run_command(cmd_name) + + self.make_distribution() + + dist_files = getattr(self.distribution, 'dist_files', []) + for file in self.archive_files: + data = ('sdist', '', file) + if data not in dist_files: + dist_files.append(data) + + def initialize_options(self): + orig.sdist.initialize_options(self) + + self._default_to_gztar() + + def _default_to_gztar(self): + # only needed on Python prior to 3.6. + if sys.version_info >= (3, 6, 0, 'beta', 1): + return + self.formats = ['gztar'] + + def make_distribution(self): + """ + Workaround for #516 + """ + with self._remove_os_link(): + orig.sdist.make_distribution(self) + + @staticmethod + @contextlib.contextmanager + def _remove_os_link(): + """ + In a context, remove and restore os.link if it exists + """ + + class NoValue: + pass + + orig_val = getattr(os, 'link', NoValue) + try: + del os.link + except Exception: + pass + try: + yield + finally: + if orig_val is not NoValue: + setattr(os, 'link', orig_val) + + def add_defaults(self): + super().add_defaults() + self._add_defaults_build_sub_commands() + + def _add_defaults_optional(self): + super()._add_defaults_optional() + if os.path.isfile('pyproject.toml'): + self.filelist.append('pyproject.toml') + + def _add_defaults_python(self): + """getting python files""" + if self.distribution.has_pure_modules(): + build_py = self.get_finalized_command('build_py') + self.filelist.extend(build_py.get_source_files()) + self._add_data_files(self._safe_data_files(build_py)) + + def _add_defaults_build_sub_commands(self): + build = self.get_finalized_command("build") + missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS + # ^-- the original built-in sub-commands are already handled by default. + cmds = (self.get_finalized_command(c) for c in missing_cmds) + files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files")) + self.filelist.extend(chain.from_iterable(files)) + + def _safe_data_files(self, build_py): + """ + Since the ``sdist`` class is also used to compute the MANIFEST + (via :obj:`setuptools.command.egg_info.manifest_maker`), + there might be recursion problems when trying to obtain the list of + data_files and ``include_package_data=True`` (which in turn depends on + the files included in the MANIFEST). + + To avoid that, ``manifest_maker`` should be able to overwrite this + method and avoid recursive attempts to build/analyze the MANIFEST. + """ + return build_py.data_files + + def _add_data_files(self, data_files): + """ + Add data files as found in build_py.data_files. + """ + self.filelist.extend( + os.path.join(src_dir, name) + for _, src_dir, _, filenames in data_files + for name in filenames + ) + + def _add_defaults_data_files(self): + try: + super()._add_defaults_data_files() + except TypeError: + log.warn("data_files contains unexpected objects") + + def check_readme(self): + for f in self.READMES: + if os.path.exists(f): + return + else: + self.warn( + "standard file not found: should have one of " + ', '.join(self.READMES) + ) + + def make_release_tree(self, base_dir, files): + orig.sdist.make_release_tree(self, base_dir, files) + + # Save any egg_info command line options used to create this sdist + dest = os.path.join(base_dir, 'setup.cfg') + if hasattr(os, 'link') and os.path.exists(dest): + # unlink and re-copy, since it might be hard-linked, and + # we don't want to change the source version + os.unlink(dest) + self.copy_file('setup.cfg', dest) + + self.get_finalized_command('egg_info').save_version_info(dest) + + def _manifest_is_not_generated(self): + # check for special comment used in 2.7.1 and higher + if not os.path.isfile(self.manifest): + return False + + with io.open(self.manifest, 'rb') as fp: + first_line = fp.readline() + return first_line != '# file GENERATED by distutils, do NOT edit\n'.encode() + + def read_manifest(self): + """Read the manifest file (named by 'self.manifest') and use it to + fill in 'self.filelist', the list of files to include in the source + distribution. + """ + log.info("reading manifest file '%s'", self.manifest) + manifest = open(self.manifest, 'rb') + for line in manifest: + # The manifest must contain UTF-8. See #303. + try: + line = line.decode('UTF-8') + except UnicodeDecodeError: + log.warn("%r not UTF-8 decodable -- skipping" % line) + continue + # ignore comments and blank lines + line = line.strip() + if line.startswith('#') or not line: + continue + self.filelist.append(line) + manifest.close() diff --git a/shared/package-files/75/7557d42d8f79f67170a65e4d0b1c82a621f235c48d691ec760e83b414db56b9b/blob b/shared/package-files/75/7557d42d8f79f67170a65e4d0b1c82a621f235c48d691ec760e83b414db56b9b/blob new file mode 100644 index 0000000000000000000000000000000000000000..2eb2f71afd54a67b54d7012347e5d1a983fac7be --- /dev/null +++ b/shared/package-files/75/7557d42d8f79f67170a65e4d0b1c82a621f235c48d691ec760e83b414db56b9b/blob @@ -0,0 +1,6 @@ +import warnings +warnings.warn( + "scipy.misc is deprecated and will be removed in 2.0.0", + DeprecationWarning, + stacklevel=2 +) diff --git a/shared/package-files/75/755b5e6cce810a5ad89f7072c84f637fb73962277150883f6ff7323ce5fbaeb6/blob b/shared/package-files/75/755b5e6cce810a5ad89f7072c84f637fb73962277150883f6ff7323ce5fbaeb6/blob new file mode 100644 index 0000000000000000000000000000000000000000..c45aa6d3e1ab081f0e62c0bc7bce566e330abad2 --- /dev/null +++ b/shared/package-files/75/755b5e6cce810a5ad89f7072c84f637fb73962277150883f6ff7323ce5fbaeb6/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor movedim(const at::Tensor & self, at::IntArrayRef source, at::IntArrayRef destination); +TORCH_API at::Tensor movedim(const at::Tensor & self, int64_t source, int64_t destination); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/755c5d8dc5b41cd64154263849d2f00936aef269ae0e79f047980900ba88e091/blob b/shared/package-files/75/755c5d8dc5b41cd64154263849d2f00936aef269ae0e79f047980900ba88e091/blob new file mode 100644 index 0000000000000000000000000000000000000000..3f7d5a090449fd008bc2a70f3d3f26ad18ae683c --- /dev/null +++ b/shared/package-files/75/755c5d8dc5b41cd64154263849d2f00936aef269ae0e79f047980900ba88e091/blob @@ -0,0 +1,32 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor & normal_(at::Tensor & self, double mean=0, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor normal(const at::Tensor & mean, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(at::Tensor & out, const at::Tensor & mean, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_outf(const at::Tensor & mean, double std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal(double mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(at::Tensor & out, double mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_outf(double mean, const at::Tensor & std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal(const at::Tensor & mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(at::Tensor & out, const at::Tensor & mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_outf(const at::Tensor & mean, const at::Tensor & std, c10::optional generator, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/75/755c76e5f5674012f7d1471386185b5b7c1ca47e51bb910cfe15b8e3c41e14f8/blob b/shared/package-files/75/755c76e5f5674012f7d1471386185b5b7c1ca47e51bb910cfe15b8e3c41e14f8/blob new file mode 100644 index 0000000000000000000000000000000000000000..c9d69978afd2dacedb446f606573fa2a434d88ba --- /dev/null +++ b/shared/package-files/75/755c76e5f5674012f7d1471386185b5b7c1ca47e51bb910cfe15b8e3c41e14f8/blob @@ -0,0 +1,27 @@ +from . import ( + AsyncGenerator as AsyncGenerator, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + ByteString as ByteString, + Callable as Callable, + Collection as Collection, + Container as Container, + Coroutine as Coroutine, + Generator as Generator, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Reversible as Reversible, + Sequence as Sequence, + Set as Set, + Sized as Sized, + ValuesView as ValuesView, +) diff --git a/shared/package-files/75/755cd183b44471946cad2f21e834ac3238a3e35f08dbcd4c85ad6d621c0ee6ea/blob b/shared/package-files/75/755cd183b44471946cad2f21e834ac3238a3e35f08dbcd4c85ad6d621c0ee6ea/blob new file mode 100644 index 0000000000000000000000000000000000000000..4a30c316c4a524b3a41a080dd7e82fe597e6f130 --- /dev/null +++ b/shared/package-files/75/755cd183b44471946cad2f21e834ac3238a3e35f08dbcd4c85ad6d621c0ee6ea/blob @@ -0,0 +1,22 @@ +from numba import runtests +from numba.core import config + +if config.ENABLE_CUDASIM: + from .simulator_init import * +else: + from .device_init import * + from .device_init import _auto_device + +from numba.cuda.compiler import (compile, compile_for_current_device, + compile_ptx, compile_ptx_for_current_device) + +# Are we the numba.cuda built in to upstream Numba, or the out-of-tree +# NVIDIA-maintained target? +implementation = "Built-in" + + +def test(*args, **kwargs): + if not is_available(): + raise cuda_error() + + return runtests.main("numba.cuda.tests", *args, **kwargs) diff --git a/shared/package-files/75/755e6d01f8dafe27dd88db89e882f85f68c57c3a36e16d55bf45f640f72a35e0/blob b/shared/package-files/75/755e6d01f8dafe27dd88db89e882f85f68c57c3a36e16d55bf45f640f72a35e0/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc4fd5112070a6db675d1ae354e482ea9e424deb --- /dev/null +++ b/shared/package-files/75/755e6d01f8dafe27dd88db89e882f85f68c57c3a36e16d55bf45f640f72a35e0/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_view_from_buffer_copy { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_view_from_buffer_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_view_from_buffer_copy(Tensor self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets); +}; + +struct TORCH_API _nested_view_from_buffer_copy_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_view_from_buffer_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_view_from_buffer_copy.out(Tensor self, Tensor nested_size, Tensor nested_strides, Tensor offsets, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/75/756102b7eb1b7ef69288af3e620a7902aca3a0de62dba5443ab5ea834d6b9378/blob b/shared/package-files/75/756102b7eb1b7ef69288af3e620a7902aca3a0de62dba5443ab5ea834d6b9378/blob new file mode 100644 index 0000000000000000000000000000000000000000..69d24c38c28959361283624e02f8891fa69b6c5f --- /dev/null +++ b/shared/package-files/75/756102b7eb1b7ef69288af3e620a7902aca3a0de62dba5443ab5ea834d6b9378/blob @@ -0,0 +1,1001 @@ +seed, 0x0 +0, 0x399e5b222b82fa9 +1, 0x41fd08c1f00f3bc5 +2, 0x78b8824162ee4d04 +3, 0x176747919e02739d +4, 0xfaa88f002a8d3596 +5, 0x418eb6f592e6c227 +6, 0xef83020b8344dd45 +7, 0x30a74a1a6eaa064b +8, 0x93d43bf97a490c3 +9, 0xe4ba28b442194cc +10, 0xc829083a168a8656 +11, 0x73f45d50f8e22849 +12, 0xf912db57352824cc +13, 0xf524216927b12ada +14, 0x22b7697473b1dfda +15, 0x311e2a936414b39f +16, 0xb905abfdcc425be6 +17, 0x4b14630d031eac9c +18, 0x1cf0c4ae01222bc8 +19, 0xa6c33efc6e82ef3 +20, 0x43b3576937ba0948 +21, 0x1e483d17cdde108a +22, 0x6722784cac11ac88 +23, 0xee87569a48fc45d7 +24, 0xb821dcbe74d18661 +25, 0xa5d1876ef3da1a81 +26, 0xe4121c2af72a483 +27, 0x2d747e355a52cf43 +28, 0x609059957bd03725 +29, 0xc3327244b49e16c5 +30, 0xb5ae6cb000dde769 +31, 0x774315003209017 +32, 0xa2013397ba8db605 +33, 0x73b228945dbcd957 +34, 0x801af7190375d3c0 +35, 0xae6dca29f24c9c67 +36, 0xd1cc0bcb1ca26249 +37, 0x1defa62a5bd853be +38, 0x67c2f5557fa89462 +39, 0xf1729b58122fab02 +40, 0xb67eb71949ec6c42 +41, 0x5456366ec1f8f7d7 +42, 0x44492b32eb7966f5 +43, 0xa801804159f175f1 +44, 0x5a416f23cac70d84 +45, 0x186f55293302303d +46, 0x7339d5d7b6a43639 +47, 0xfc6df38d6a566121 +48, 0xed2fe018f150b39e +49, 0x508e0b04a781fa1b +50, 0x8bee9d50f32eaf50 +51, 0x9870015d37e63cc +52, 0x93c6b12309c14f2d +53, 0xb571cf798abe93ff +54, 0x85c35a297a88ae6e +55, 0x9b1b79afe497a2ae +56, 0x1ca02e5b95d96b8d +57, 0x5bb695a666c0a94a +58, 0x4e3caf9bbab0b208 +59, 0x44a44be1a89f2dc1 +60, 0x4ff37c33445758d1 +61, 0xd0e02875322f35da +62, 0xfd449a91fb92646b +63, 0xbe0b49096b95db4d +64, 0xffa3647cad13ef5d +65, 0x75c127a61acd10c8 +66, 0xd65f697756f5f98e +67, 0x3ced84be93d94434 +68, 0x4da3095c2fc46d68 +69, 0x67564e2a771ee9ac +70, 0x36944775180644a9 +71, 0xf458db1c177cdb60 +72, 0x5b58406dcd034c8 +73, 0x793301a3fdab2a73 +74, 0x1c2a1a16d6db6128 +75, 0xc2dacd4ddddbe56c +76, 0x2e7d15be2301a111 +77, 0xd4f4a6341b3bcd18 +78, 0x3622996bbe6a9e3b +79, 0xaf29aa9a7d6d47da +80, 0x6d7dbb74a4cd68ae +81, 0xc260a17e0f39f841 +82, 0xdee0170f2af66f0d +83, 0xf84ae780d7b5a06e +84, 0x8326247b73f43c3a +85, 0xd44eef44b4f98b84 +86, 0x3d10aee62ec895e3 +87, 0x4f23fef01bf703b3 +88, 0xf8e50aa57d888df6 +89, 0x7da67411e3bef261 +90, 0x1d00f2769b2f96d7 +91, 0x7ef9a15b7444b84e +92, 0xcfa16436cc2b7e21 +93, 0x29ab8cfac00460ff +94, 0x23613de8608b0e70 +95, 0xb1aa0980625798a8 +96, 0xb9256fd29db7df99 +97, 0xdacf311bf3e7fa18 +98, 0xa013c8f9fada20d8 +99, 0xaf5fd4fe8230fe3e +100, 0xd3d59ca55102bc5c +101, 0x9d08e2aa5242767f +102, 0x40278fe131e83b53 +103, 0x56397d03c7c14c98 +104, 0xe874b77b119359b3 +105, 0x926a1ba4304ab19f +106, 0x1e115d5aa695a91d +107, 0xc6a459df441f2fe3 +108, 0x2ca842bc1b0b3c6a +109, 0x24c804cf8e5eed16 +110, 0x7ca00fc4a4c3ebd3 +111, 0x546af7cecc4a4ba6 +112, 0x8faae1fa18fd6e3 +113, 0x40420b0089641a6a +114, 0x88175a35d9abcb83 +115, 0xf7d746d1b8b1357c +116, 0x7dae771a651be970 +117, 0x2f6485247ee4df84 +118, 0x6883702fab2d8ec5 +119, 0xeb7eea829a67f9a6 +120, 0x60d5880b485562ed +121, 0x7d4ca3d7e41a4e7e +122, 0xbb7fef961ab8de18 +123, 0x3b92452fb810c164 +124, 0x5f4b4755348b338 +125, 0xca45a715a7539806 +126, 0xc33efd9da5399dd +127, 0x593d665a51d4aedd +128, 0x75d6b8636563036b +129, 0x7b57caa55e262082 +130, 0x4ede7427969e0dd5 +131, 0xc3f19b6f78ea00b +132, 0xeea7bab9be2181ea +133, 0x652c45fe9c420c04 +134, 0x14ba9e3d175670ee +135, 0xd2ad156ba6490474 +136, 0x4d65ae41065f614 +137, 0x6ff911c8afa28eb1 +138, 0xedc2b33588f3cb68 +139, 0x437c8bc324666a2f +140, 0x828cee25457a3f0 +141, 0x530c986091f31b9b +142, 0x2f34671e8326ade7 +143, 0x4f686a8f4d77f6da +144, 0xa4c1987083498895 +145, 0xbce5a88b672b0fb1 +146, 0x8476115a9e6a00cc +147, 0x16de18a55dd2c238 +148, 0xdf38cf4c416232bc +149, 0x2cb837924e7559f3 +150, 0xfad4727484e982ed +151, 0x32a55d4b7801e4f +152, 0x8b9ef96804bd10a5 +153, 0xa1fd422c9b5cf2a9 +154, 0xf46ddb122eb7e442 +155, 0x6e3842547afa3b33 +156, 0x863dee1c34afe5c4 +157, 0x6a43a1935b6db171 +158, 0x1060a5c2f8145821 +159, 0xf783ec9ed34c4607 +160, 0x1da4a86bf5f8c0b0 +161, 0x4c7714041ba12af8 +162, 0x580da7010be2f192 +163, 0xad682fe795a7ea7a +164, 0x6687b6cb88a9ed2c +165, 0x3c8d4b175517cd18 +166, 0xe9247c3a524a6b6b +167, 0x337ca9cfaa02658 +168, 0xed95399481c6feec +169, 0x58726a088e606062 +170, 0xfe7588a5b4ee342a +171, 0xee434c7ed146fdee +172, 0xe2ade8b60fdc4ba5 +173, 0xd57e4c155de4eaab +174, 0xdefeae12de1137cb +175, 0xb7a276a241316ac1 +176, 0xeb838b1b1df4ca15 +177, 0x6f78965edea32f6f +178, 0x18bebd264d7a5d53 +179, 0x3641c691d77005ec +180, 0xbe70ed7efea8c24c +181, 0x33047fa8d03ca560 +182, 0x3bed0d2221ff0f87 +183, 0x23083a6ffbcf38a2 +184, 0xc23eb827073d3fa5 +185, 0xc873bb3415e9fb9b +186, 0xa4645179e54147fe +187, 0x2c72fb443f66e207 +188, 0x98084915dd89d8f4 +189, 0x88baa2de12c99037 +190, 0x85c74ab238cb795f +191, 0xe122186469ea3a26 +192, 0x4c3bba99b3249292 +193, 0x85d6845d9a015234 +194, 0x147ddd69c13e6a31 +195, 0x255f4d678c9a570b +196, 0x2d7c0c410bf962b4 +197, 0x58eb7649e0aa16ca +198, 0x9d240bf662fe0783 +199, 0x5f74f6fa32d293cc +200, 0x4928e52f0f79d9b9 +201, 0xe61c2b87146b706d +202, 0xcfcd90d100cf5431 +203, 0xf15ea8138e6aa178 +204, 0x6ab8287024f9a819 +205, 0xed8942593db74e01 +206, 0xefc00e4ec2ae36dd +207, 0xc21429fb9387f334 +208, 0xf9a3389e285a9bce +209, 0xacdee8c43aae49b3 +210, 0xefc382f02ad55c25 +211, 0x1153b50e8d406b72 +212, 0xb00d39ebcc2f89d8 +213, 0xde62f0b9831c8850 +214, 0xc076994662eef6c7 +215, 0x66f08f4752f1e3ef +216, 0x283b90619796249a +217, 0x4e4869bc4227499e +218, 0xb45ad78a49efd7ed +219, 0xffe19aa77abf5f4b +220, 0xfce11a0daf913aef +221, 0x7e4e64450d5cdceb +222, 0xe9621997cfd62762 +223, 0x4d2c9e156868081 +224, 0x4e2d96eb7cc9a08 +225, 0xda74849bba6e3bd3 +226, 0x6f4621da935e7fde +227, 0xb94b914aa0497259 +228, 0xd50d03e8b8db1563 +229, 0x1a45c1ce5dca422e +230, 0xc8d30d33276f843f +231, 0xb57245774e4176b4 +232, 0x8d36342c05abbbb1 +233, 0x3591ad893ecf9e78 +234, 0x62f4717239ee0ac8 +235, 0x9b71148a1a1d4200 +236, 0x65f8e0f56dd94463 +237, 0x453b1fcfd4fac8c2 +238, 0x4c25e48e54a55865 +239, 0xa866baa05112ace2 +240, 0x7741d3c69c6e79c5 +241, 0x7deb375e8f4f7a8a +242, 0xc242087ede42abd8 +243, 0x2fa9d1d488750c4b +244, 0xe8940137a935d3d3 +245, 0x1dab4918ca24b2f2 +246, 0xe2368c782168fe3e +247, 0x6e8b2d1d73695909 +248, 0x70455ebea268b33e +249, 0x656a919202e28da1 +250, 0x5a5a8935647da999 +251, 0x428c6f77e118c13c +252, 0xa87aee2b675bb083 +253, 0x3873a6412b239969 +254, 0x5f72c1e91cb8a2ee +255, 0xa25af80a1beb5679 +256, 0x1af65d27c7b4abc3 +257, 0x133437060670e067 +258, 0xb1990fa39a97d32e +259, 0x724adc89ae10ed17 +260, 0x3f682a3f2363a240 +261, 0x29198f8dbd343499 +262, 0xdfaeeaa42bc51105 +263, 0x5baff3901b9480c2 +264, 0x3f760a67043e77f5 +265, 0x610fa7aa355a43ba +266, 0x394856ac09c4f7a7 +267, 0x1d9229d058aee82e +268, 0x19c674804c41aeec +269, 0x74cf12372012f4aa +270, 0xa5d89b353fa2f6ca +271, 0x697e4f672ac363dd +272, 0xde6f55ba73df5af9 +273, 0x679cf537510bd68f +274, 0x3dc916114ae9ef7e +275, 0xd7e31a66ec2ee7ba +276, 0xc21bebb968728495 +277, 0xc5e0781414e2adfd +278, 0x71147b5412ddd4bd +279, 0x3b864b410625cca9 +280, 0x433d67c0036cdc6 +281, 0x48083afa0ae20b1b +282, 0x2d80beecd64ac4e8 +283, 0x2a753c27c3a3ee3e +284, 0xb2c5e6afd1fe051a +285, 0xea677930cd66c46b +286, 0x4c3960932f92810a +287, 0xf1b367a9e527eaba +288, 0xb7d92a8a9a69a98e +289, 0x9f9ad3210bd6b453 +290, 0x817f2889db2dcbd8 +291, 0x4270a665ac15813c +292, 0x90b85353bd2be4dd +293, 0x10c0460f7b2d68d +294, 0x11cef32b94f947f5 +295, 0x3cf29ed8e7d477e8 +296, 0x793aaa9bd50599ef +297, 0xbac15d1190014aad +298, 0x987944ae80b5cb13 +299, 0x460aa51f8d57c484 +300, 0xc77df0385f97c2d3 +301, 0x92e743b7293a3822 +302, 0xbc3458bcfbcbb8c0 +303, 0xe277bcf3d04b4ed7 +304, 0xa537ae5cf1c9a31c +305, 0x95eb00d30bd8cfb2 +306, 0x6376361c24e4f2dd +307, 0x374477fe87b9ea8e +308, 0x8210f1a9a039902e +309, 0xe7628f7031321f68 +310, 0x8b8e9c0888fc1d3d +311, 0x306be461fdc9e0ed +312, 0x510009372f9b56f5 +313, 0xa6e6fa486b7a027a +314, 0x9d3f002025203b5a +315, 0x7a46e0e81ecbef86 +316, 0x41e280c611d04df0 +317, 0xedcec10418a99e8a +318, 0x5c27b6327e0b9dbd +319, 0xa81ed2035b509f07 +320, 0x3581e855983a4cc4 +321, 0x4744594b25e9809d +322, 0xc737ac7c27fbd0ed +323, 0x1b523a307045433a +324, 0x8b4ce9171076f1d9 +325, 0x2db02d817cd5eec0 +326, 0x24a1f1229af50288 +327, 0x5550c0dcf583ff16 +328, 0x3587baaa122ec422 +329, 0xf9d3dc894229e510 +330, 0xf3100430d5cf8e87 +331, 0xc31af79862f8e2fb +332, 0xd20582063b9f3537 +333, 0xac5e90ac95fcc7ad +334, 0x107c4c704d5109d4 +335, 0xebc8628906dbfd70 +336, 0x215242776da8c531 +337, 0xa98002f1dcf08b51 +338, 0xbc3bdc07f3b09718 +339, 0x238677062495b512 +340, 0x53b4796f2a3c49e8 +341, 0x6424286467e22f0e +342, 0x14d0952a11a71bac +343, 0x2f97098149b82514 +344, 0x3777f2fdc425ad2 +345, 0xa32f2382938876d4 +346, 0xda8a39a021f20ae3 +347, 0x364361ef0a6ac32c +348, 0x4413eede008ff05a +349, 0x8dda8ace851aa327 +350, 0x4303cabbdcecd1ee +351, 0x2e69f06d74aa549f +352, 0x4797079cd4d9275c +353, 0xc7b1890917e98307 +354, 0x34031b0e822a4b4c +355, 0xfc79f76b566303ea +356, 0x77014adbe255a930 +357, 0xab6c43dd162f3be5 +358, 0xa430041f3463f6b9 +359, 0x5c191a32ada3f84a +360, 0xe8674a0781645a31 +361, 0x3a11cb667b8d0916 +362, 0xaedc73e80c39fd8a +363, 0xfde12c1b42328765 +364, 0x97abb7dcccdc1a0b +365, 0x52475c14d2167bc8 +366, 0x540e8811196d5aff +367, 0xa867e4ccdb2b4b77 +368, 0x2be04af61e5bcfb9 +369, 0x81b645102bfc5dfd +370, 0x96a52c9a66c6450f +371, 0x632ec2d136889234 +372, 0x4ed530c0b36a6c25 +373, 0x6f4851225546b75 +374, 0x2c065d6ba46a1144 +375, 0xf8a3613ff416551d +376, 0xb5f0fd60e9c971a9 +377, 0x339011a03bb4be65 +378, 0x9439f72b6995ded6 +379, 0xc1b03f3ef3b2292d +380, 0xad12fd221daab3ae +381, 0xf615b770f2cf996f +382, 0x269d0fdcb764172 +383, 0x67837025e8039256 +384, 0x6402831fc823fafa +385, 0x22854146a4abb964 +386, 0x7b5ad9b5a1bad7a8 +387, 0x67170e7beb6ac935 +388, 0xfc2d1e8e24adfaaa +389, 0x7ded4395345ff40d +390, 0x418981760a80dd07 +391, 0xc03bef38022c1d2 +392, 0x3a11850b26eade29 +393, 0xaa56d02c7175c5f4 +394, 0xd83b7917b9bfbff5 +395, 0x3c1df2f8fa6fced3 +396, 0xf3d6e2999c0bb760 +397, 0xc66d683a59a950e3 +398, 0x8e3972a9d73ffabf +399, 0x97720a0443edffd9 +400, 0xa85f5d2fe198444a +401, 0xfc5f0458e1b0de5e +402, 0xe3973f03df632b87 +403, 0xe151073c84c594b3 +404, 0x68eb4e22e7ff8ecf +405, 0x274f36eaed7cae27 +406, 0x3b87b1eb60896b13 +407, 0xbe0b2f831442d70a +408, 0x2782ed7a48a1b328 +409, 0xb3619d890310f704 +410, 0xb03926b11b55921a +411, 0xdb46fc44aa6a0ce4 +412, 0x4b063e2ef2e9453a +413, 0xe1584f1aeec60fb5 +414, 0x7092bd6a879c5a49 +415, 0xb84e1e7c7d52b0e6 +416, 0x29d09ca48db64dfb +417, 0x8f6c4a402066e905 +418, 0x77390795eabc36b +419, 0xcc2dc2e4141cc69f +420, 0x2727f83beb9e3c7c +421, 0x1b29868619331de0 +422, 0xd38c571e192c246f +423, 0x535327479fe37b6f +424, 0xaff9ce5758617eb3 +425, 0x5658539e9288a4e4 +426, 0x8df91d87126c4c6d +427, 0xe931cf8fdba6e255 +428, 0x815dfdf25fbee9e8 +429, 0x5c61f4c7cba91697 +430, 0xdd5f5512fe2313a1 +431, 0x499dd918a92a53cd +432, 0xa7e969d007c97dfd +433, 0xb8d39c6fc81ac0bb +434, 0x1d646983def5746c +435, 0x44d4b3b17432a60c +436, 0x65664232a14db1e3 +437, 0xda8fae6433e7500b +438, 0xbe51b94ff2a3fe94 +439, 0xe9b1bd9a9098ef9f +440, 0xfe47d54176297ef5 +441, 0xb8ab99bc03bb7135 +442, 0xcfad97f608565b38 +443, 0xf05da71f6760d9c1 +444, 0xef8da40a7c70e7b +445, 0xe0465d58dbd5d138 +446, 0xb54a2d70eb1a938 +447, 0xfdd50c905958f2d8 +448, 0x3c41933c90a57d43 +449, 0x678f6d894c6ad0bb +450, 0x403e8f4582274e8 +451, 0x5cbbe975668df6b0 +452, 0x297e6520a7902f03 +453, 0x8f6dded33cd1efd7 +454, 0x8e903c97be8d783b +455, 0x10bd015577e30f77 +456, 0x3fcd69d1c36eab0c +457, 0xb45989f3ca198d3 +458, 0x507655ce02b491a9 +459, 0xa92cf99bb78602ce +460, 0xebfb82055fbc2f0f +461, 0x3334256279289b7a +462, 0xc19d2a0f740ee0ac +463, 0x8bb070dea3934905 +464, 0xa4ab57d3a8d1b3eb +465, 0xfee1b09bcacf7ff4 +466, 0xccc7fb41ceec41fa +467, 0xd4da49094eb5a74d +468, 0xed5c693770af02ed +469, 0x369dabc9bbfaa8e4 +470, 0x7eab9f360d054199 +471, 0xe36dbebf5ee94076 +472, 0xd30840e499b23d7 +473, 0x8678e6cb545015ff +474, 0x3a47932ca0b336e +475, 0xeb7c742b6e93d6fe +476, 0x1404ea51fe5a62a9 +477, 0xa72cd49db978e288 +478, 0xfd7bada020173dcf +479, 0xc9e74fc7abe50054 +480, 0x93197847bb66808d +481, 0x25fd5f053dce5698 +482, 0xe198a9b18cc21f4 +483, 0x5cc27b1689452d5d +484, 0x8b3657af955a98dc +485, 0xc17f7584f54aa1c0 +486, 0xe821b088246b1427 +487, 0x32b5a9f6b45b6fa0 +488, 0x2aef7c315c2bae0c +489, 0xe1af8129846b705a +490, 0x4123b4c091b34614 +491, 0x6999d61ec341c073 +492, 0x14b9a8fcf86831ea +493, 0xfd4cff6548f46c9f +494, 0x350c3b7e6cc8d7d6 +495, 0x202a5047fecafcd5 +496, 0xa82509fe496bb57d +497, 0x835e4b2608b575fe +498, 0xf3abe3da919f54ec +499, 0x8705a21e2c9b8796 +500, 0xfd02d1427005c314 +501, 0xa38458faa637f49b +502, 0x61622f2360e7622a +503, 0xe89335a773c2963b +504, 0x481264b659b0e0d0 +505, 0x1e82ae94ebf62f15 +506, 0x8ea7812de49209d4 +507, 0xff963d764680584 +508, 0x418a68bef717f4af +509, 0x581f0e7621a8ab91 +510, 0x840337e9a0ec4150 +511, 0x951ef61b344be505 +512, 0xc8b1b899feb61ec2 +513, 0x8b78ca13c56f6ed9 +514, 0x3d2fd793715a946f +515, 0xf1c04fabcd0f4084 +516, 0x92b602614a9a9fcc +517, 0x7991bd7a94a65be7 +518, 0x5dead10b06cad2d7 +519, 0xda7719b33f722f06 +520, 0x9d87a722b7bff71e +521, 0xb038e479071409e9 +522, 0xf4e8bbec48054775 +523, 0x4fec2cd7a28a88ea +524, 0x839e28526aad3e56 +525, 0xd37ec57852a98bf0 +526, 0xdef2cbbe00f3a02d +527, 0x1aecfe01a9e4d801 +528, 0x59018d3c8beaf067 +529, 0x892753e6ac8bf3cd +530, 0xefdd3437023d2d1c +531, 0x447bfbd148c8cb88 +532, 0x282380221bd442b8 +533, 0xfce8658d1347384a +534, 0x60b211a7ec6bfa8 +535, 0xd21729cfcc692974 +536, 0x162087ecd5038a47 +537, 0x2b17000c4bce39d2 +538, 0x3a1f75ff6adcdce0 +539, 0x721a411d312f1a2c +540, 0x9c13b6133f66934d +541, 0xaa975d14978980e5 +542, 0x9403dbd4754203fa +543, 0x588c15762fdd643 +544, 0xdd1290f8d0ada73a +545, 0xd9b77380936103f4 +546, 0xb2e2047a356eb829 +547, 0x7019e5e7f76f7a47 +548, 0x3c29a461f62b001d +549, 0xa07dc6cfab59c116 +550, 0x9b97e278433f8eb +551, 0x6affc714e7236588 +552, 0x36170aeb32911a73 +553, 0x4a665104d364a789 +554, 0x4be01464ec276c9c +555, 0x71bb10271a8b4ecf +556, 0xbf62e1d068bc018 +557, 0xc9ada5db2cbbb413 +558, 0x2bded75e726650e5 +559, 0x33d5a7af2f34385d +560, 0x8179c46661d85657 +561, 0x324ebcfd29267359 +562, 0xac4c9311dc9f9110 +563, 0xc14bb6a52f9f9c0 +564, 0xc430abe15e7fb9db +565, 0xf1cce5c14df91c38 +566, 0x651e3efa2c0750d3 +567, 0x38a33604a8be5c75 +568, 0x7aaf77fe7ff56a49 +569, 0xc0d1cc56bbf27706 +570, 0x887aa47324e156c6 +571, 0x12547c004b085e8d +572, 0xd86a8d6fbbbfd011 +573, 0x57c860188c92d7b4 +574, 0xcd5d3843d361b8ca +575, 0x8f586ef05a9cb3ef +576, 0x174456e1ba6267d5 +577, 0xf5dc302c62fe583c +578, 0xa349442fabcdb71 +579, 0xe5123c1a8b6fd08e +580, 0x80681552aa318593 +581, 0xb295396deaef1e31 +582, 0xabb626e0b900e32b +583, 0xf024db8d3f19c15e +584, 0x1d04bb9548e2fb6c +585, 0xd8ed2b2214936c2b +586, 0x618ca1e430a52bc9 +587, 0xccbca44a6088136b +588, 0xd0481855c8b9ccbe +589, 0x3c92a2fade28bdf7 +590, 0x855e9fefc38c0816 +591, 0x1269bbfe55a7b27c +592, 0x1d6c853d83726d43 +593, 0xc8655511cc7fcafc +594, 0x301503eb125a9b0e +595, 0xb3108e4532016b11 +596, 0xbb7ab6245da9cb3d +597, 0x18004c49116d85eb +598, 0x3480849c20f61129 +599, 0xe28f45157463937b +600, 0x8e85e61060f2ce1 +601, 0x1673da4ec589ba5e +602, 0x74b9a6bd1b194712 +603, 0xed39e147fa8b7601 +604, 0x28ce54019102ca77 +605, 0x42e0347f6d7a2f30 +606, 0xb6a908d1c4814731 +607, 0x16c3435e4e9a126d +608, 0x8880190514c1ad54 +609, 0xfffd86229a6f773c +610, 0x4f2420cdb0aa1a93 +611, 0xf8e1acb4120fc1fa +612, 0x63a8c553ab36a2f2 +613, 0x86b88cf3c0a6a190 +614, 0x44d8b2801622c792 +615, 0xf6eae14e93082ff1 +616, 0xd9ed4f5d1b8fac61 +617, 0x1808ce17f4e1f70 +618, 0x446e83ea336f262f +619, 0xc7c802b04c0917b7 +620, 0x626f45fd64968b73 +621, 0x9ffa540edc9b2c5c +622, 0xa96a1e219e486af8 +623, 0x2bb8963884e887a1 +624, 0xba7f68a5d029e3c4 +625, 0xefc45f44392d9ca0 +626, 0x98d77762503c5eab +627, 0xd89bcf62f2da627c +628, 0xa3cab8347f833151 +629, 0xa095b7595907d5c7 +630, 0x3b3041274286181 +631, 0xb518db8919eb71fa +632, 0x187036c14fdc9a36 +633, 0xd06e28301e696f5d +634, 0xdbc71184e0c56492 +635, 0xfe51e9cae6125bfd +636, 0x3b12d17cd014df24 +637, 0x3b95e4e2c986ac1a +638, 0x29c1cce59fb2dea2 +639, 0x58c05793182a49d6 +640, 0xc016477e330d8c00 +641, 0x79ef335133ada5d +642, 0x168e2cad941203f3 +643, 0xf99d0f219d702ef0 +644, 0x655628068f8f135b +645, 0xdcdea51910ae3f92 +646, 0x8e4505039c567892 +647, 0x91a9ec7e947c89ae +648, 0x8717172530f93949 +649, 0x1c80aba9a440171a +650, 0x9c8f83f6ebe7441e +651, 0x6c05e1efea4aa7f9 +652, 0x10af696b777c01b +653, 0x5892e9d9a92fc309 +654, 0xd2ba7da71e709432 +655, 0x46378c7c3269a466 +656, 0x942c63dfe18e772c +657, 0x6245cf02ef2476f +658, 0x6f265b2759ea2aea +659, 0x5aa757f17d17f4a6 +660, 0x1ad6a3c44fa09be6 +661, 0xe861af14e7015fb8 +662, 0x86be2e7db388c77 +663, 0x5c7bba32b519e9a0 +664, 0x3feb314850c4437b +665, 0x97955add60cfb45b +666, 0xfdb536230a540bdc +667, 0xdac9d7bf6e58512e +668, 0x4894c00e474e8120 +669, 0xa1918a37739da366 +670, 0xa8097f2096532807 +671, 0x592afe50e6c5e643 +672, 0xd69050ee6dcb33dc +673, 0xa6956b262dd3c561 +674, 0x1a55c815555e63f7 +675, 0x2ec7fd37516de2bb +676, 0x8ec251d9c70e76ba +677, 0x9b76e4abafd2689 +678, 0x9ce3f5c751a57df1 +679, 0x915c4818bf287bc7 +680, 0x2293a0d1fe07c735 +681, 0x7627dcd5d5a66d3d +682, 0xb5e4f92cc49c7138 +683, 0x6fc51298731d268c +684, 0xd19800aa95441f87 +685, 0x14f70f31162fa115 +686, 0x41a3da3752936f59 +687, 0xbec0652be95652ee +688, 0x7aa4bdb1020a290f +689, 0x4382d0d9bee899ef +690, 0xe6d988ae4277d6ff +691, 0xe618088ccb2a32d1 +692, 0x411669dfaa899e90 +693, 0x234e2bf4ba76d9f +694, 0xe109fe4cb7828687 +695, 0x1fb96b5022b0b360 +696, 0x6b24ad76c061a716 +697, 0x7e1781d4d7ecee15 +698, 0xf20c2dbe82ba38ba +699, 0xeda8e8ae1d943655 +700, 0xa58d196e2a77eaec +701, 0x44564765a5995a0b +702, 0x11902fe871ecae21 +703, 0x2ea60279900e675d +704, 0x38427227c18a9a96 +705, 0xe0af01490a1b1b48 +706, 0x826f91997e057824 +707, 0x1e57308e6e50451 +708, 0xb42d469bbbfdc350 +709, 0xb9734cff1109c49b +710, 0x98967559bb9d364f +711, 0xd6be360041907c12 +712, 0xa86a1279122a1e21 +713, 0x26f99a8527bfc698 +714, 0xfa8b85758f28f5d6 +715, 0xe3057429940806ae +716, 0x4bee2d7e84f93b2b +717, 0x948350a76ea506f4 +718, 0xa139154488045e74 +719, 0x8893579ba5e78085 +720, 0x5f21c215c6a9e397 +721, 0x456134f3a59641dc +722, 0x92c0273f8e97a9c6 +723, 0xd2936c9c3f0c6936 +724, 0xcfa4221e752c4735 +725, 0x28cd5a7457355dca +726, 0xecdfdde23d90999f +727, 0x60631b2d494d032b +728, 0xf67289df269a827f +729, 0xcbe8011ef0f5b7ef +730, 0x20eea973c70a84f5 +731, 0xbe1fd200398557ce +732, 0xd2279ee030191bba +733, 0xf2bd4291dedaf819 +734, 0xfc6d167dbe8c402 +735, 0x39ac298da5d0044b +736, 0xceac026f5f561ce +737, 0x10a5b0bdd8ad60e6 +738, 0xdeb3c626df6d4bcb +739, 0x3c128962e77ff6ca +740, 0xc786262e9c67a0e5 +741, 0x4332855b3febcdc0 +742, 0x7bda9724d1c0e020 +743, 0x6a8c93399bc4df22 +744, 0xa9b20100ac707396 +745, 0xa11a3458502c4eb5 +746, 0xb185461c60478941 +747, 0x13131d56195b7ff6 +748, 0x8d55875ddbd4aa1c +749, 0xc09b67425f469aa5 +750, 0x39e33786cc7594c4 +751, 0x75e96db8e4b08b93 +752, 0xda01cd12a3275d1e +753, 0x2c49e7822344fab5 +754, 0x9bd5f10612514ca7 +755, 0x1c801a5c828e7332 +756, 0x29797d3f4f6c7b4c +757, 0xac992715e21e4e53 +758, 0xe40e89ee887ddb37 +759, 0x15189a2b265a783b +760, 0xa854159a52af5c5 +761, 0xb9d8a5a81c12bead +762, 0x3240cdc9d59e2a58 +763, 0x1d0b872234cf8e23 +764, 0xc01224cf6ce12cff +765, 0x2601e9f3905c8663 +766, 0xd4ecf9890168d6b4 +767, 0xa45db796d89bfdd5 +768, 0x9f389406dad64ab4 +769, 0xa5a851adce43ffe3 +770, 0xd0962c41c26e5aa9 +771, 0x8a671679e48510a4 +772, 0xc196dc0924a6bfeb +773, 0x3ead661043b549cb +774, 0x51af4ca737d405ac +775, 0xf4425b5c62275fb6 +776, 0x71e69d1f818c10f5 +777, 0xacaf4af2d3c70162 +778, 0x2e1f1d4fd7524244 +779, 0xe54fdd8f388890e8 +780, 0xfda0d33e84eb2b83 +781, 0x53965c5e392b81da +782, 0x5c92288267263097 +783, 0xcac1b431c878c66c +784, 0x36c0e1cf417241c6 +785, 0x5cc4d9cd1a36bf2c +786, 0x32e4257bb5d3e470 +787, 0x4aecff904adb44fb +788, 0x4d91a8e0d1d60cac +789, 0xa3b478388385b038 +790, 0x48d955f24eba70be +791, 0x310e4deb07f24f68 +792, 0x8853e73b1f30a5a +793, 0x278aee45c2a65c5 +794, 0xf6932eedbd62fb0b +795, 0xafb95958c82fafad +796, 0x78e807c18616c16c +797, 0xd7abadda7488ed9f +798, 0x2dd72e2572aa2ae6 +799, 0x6ec3791982c2be09 +800, 0x6865bb314fac478f +801, 0xa14dc0ce09000d1a +802, 0xb8081ad134da10f2 +803, 0xc4ac1534aa825ef5 +804, 0xd83aeb48ae2d538f +805, 0x38052027e3074be4 +806, 0xa9833e06ef136582 +807, 0x4f02d790ec9fd78 +808, 0xec2f60bc711c5bdc +809, 0x9253b0d12268e561 +810, 0xa8ac607fdd62c206 +811, 0x895e28ebc920289f +812, 0xe2fd42b154243ac7 +813, 0xc69cac2f776eee19 +814, 0xf4d4ac11db56d0dc +815, 0xa8d37049b9f39833 +816, 0x75abbf8a196c337c +817, 0xb115bb76750d27b8 +818, 0x39426d187839154 +819, 0xd488423e7f38bf83 +820, 0xbb92e0c76ecb6a62 +821, 0x3055a018ce39f4e3 +822, 0xc93fe0e907729bfb +823, 0x65985d17c5863340 +824, 0x2088ae081b2028e1 +825, 0x6e628de873314057 +826, 0x864377cccf573f0e +827, 0xae03f4c9aa63d132 +828, 0xb1db766d6404c66d +829, 0xdce5a22414a374b +830, 0x622155b777819997 +831, 0x69fe96e620371f3c +832, 0xa9c67dbc326d94fc +833, 0x932a84ae5dd43bab +834, 0xe2301a20f6c48c3f +835, 0x795d2e79c6477300 +836, 0xd8e3e631289521e7 +837, 0xae2684979002dfd6 +838, 0xc9c2392377550f89 +839, 0xa1b0c99d508ef7ec +840, 0x593aef3c5a5272ec +841, 0xe32e511a4b7162cd +842, 0xab3b81655f5a2857 +843, 0x1b535e1a0aaf053e +844, 0x5b33f56c1b6a07e2 +845, 0x782dc8cfcac4ef36 +846, 0xb3d4f256eecfd202 +847, 0xf73a6598f58c4f7e +848, 0xd5722189524870ae +849, 0x707878de6b995fc0 +850, 0xc3eb6ba73e3d7e8a +851, 0xca75c017655b75a7 +852, 0x1b29369ea3541e5f +853, 0x352e98858bdb58a3 +854, 0x1e4412d184b6b27d +855, 0x2d375ba0304b2d17 +856, 0x56c30fce69a5d08e +857, 0x6b8c2b0c06584bda +858, 0xde4dfff228c8c91f +859, 0xb7c9edd574e6287f +860, 0xf6078281c9fca2b2 +861, 0xb9b9a51de02a2f1e +862, 0xa411bef31c0103b0 +863, 0xc5facd8fc5e1d7a3 +864, 0x54e631c05ddf7359 +865, 0x815b42b3fd06c474 +866, 0xc9ac07566fda18ec +867, 0xd84ea62957bd8e15 +868, 0x5575f74b5cfd8803 +869, 0x5779a8d460c2e304 +870, 0xfd6e87e264a85587 +871, 0xa1d674daa320b26d +872, 0x2c3c3ec64b35afc4 +873, 0x393a274ff03e6935 +874, 0x1f40ecbac52c50ea +875, 0xc3de64fa324ffc0c +876, 0x56ae828b7f9deb04 +877, 0xe7c1a77b5c1f2cb3 +878, 0xa4c4aab19ea921cc +879, 0xec164c238825822c +880, 0xa6a3304770c03b03 +881, 0x3a63641d5b1e8123 +882, 0x42677be3a54617ef +883, 0xa2680423e3a200c0 +884, 0x8b17cf75f3f37277 +885, 0xe7ce65a49242be3d +886, 0x7f85934271323e4b +887, 0xcfb0f431f79a4fab +888, 0x392e4041a8505b65 +889, 0xd3e5daf0d8b25ea6 +890, 0x9447eff675d80f53 +891, 0xea27a9d53cfaeea8 +892, 0xe3f2335945a83ba +893, 0x8875a43ce216413b +894, 0xe49941f9eabce33e +895, 0x9357c1296683a5b1 +896, 0xf0f16439e81ee701 +897, 0x3181515295ffd79a +898, 0x9d7150fffd169ed8 +899, 0x2d6a1d281e255a72 +900, 0x81bf1286fb3a92b6 +901, 0x566d3079b499e279 +902, 0xc7939ca8f047341 +903, 0xb1f8050e7c2d59f6 +904, 0x605701045e7be192 +905, 0x51b73360e8e31a1c +906, 0x9f4ad54483ba9fe0 +907, 0xd3085b8fcf69d1c8 +908, 0xc3e7475026dc5f0b +909, 0x5800f8554b157354 +910, 0x37dfdf858cfcd963 +911, 0x3a1fce05ce385072 +912, 0xf495c062645c20c3 +913, 0xdcbeec2c3492c773 +914, 0xc38f427589d1d0b4 +915, 0x681ead60216a8184 +916, 0x4bd569c40cc88c41 +917, 0x49b0d442e130b7a2 +918, 0xee349156b7d1fa3f +919, 0x2bde2d2db055135b +920, 0xc6a460d2fbcb2378 +921, 0xd0f170494ff3dbb +922, 0xb294422492528a23 +923, 0xfc95873c854e7b86 +924, 0x6c9c3ad1797bb19c +925, 0xe0c06f2aab65062d +926, 0x58e32ce0f11e3a81 +927, 0xa745fcd729ff5036 +928, 0x599b249b2fc2cdb2 +929, 0x78f23b5b0dd5b082 +930, 0x6de3e957f549ecfc +931, 0x9d0712fa6d878756 +932, 0x9076e8554e4a413a +933, 0xf3185818c0294de8 +934, 0x5de7cdf4b455b9b6 +935, 0xb15f6908ed703f7d +936, 0x98c654dfedc6818 +937, 0x120502ab0e93ae42 +938, 0x67966a98a58dc120 +939, 0x1caa0fc628989482 +940, 0xd8b2c3cd480a8625 +941, 0x85c70071b3aed671 +942, 0xff385f8473714662 +943, 0xe2868e4bf3773b63 +944, 0x96cf8019b279298e +945, 0x8511cc930bd74800 +946, 0x5312e48fdd55f5ab +947, 0xfcdae564b52df78d +948, 0x9eee48373e652176 +949, 0x953788f6bcbc56b0 +950, 0xd1a3855dbd2f6b37 +951, 0x3ad32acf77f4d1e9 +952, 0x917c7be81b003e30 +953, 0x9ce817da1e2e9dfb +954, 0x2968983db162d44d +955, 0x1e005decef5828ad +956, 0xc38fe59d1aa4f3d5 +957, 0xf357f1710dc02f1d +958, 0x2613912a4c83ec67 +959, 0x832a11470b9a17cb +960, 0x5e85508a611f0dad +961, 0x2781131677f59d56 +962, 0xa82358d7d4b0237f +963, 0xfbf8b3cc030c3af6 +964, 0x68b2f68ac8a55adb +965, 0x3b6fcf353add0ada +966, 0xd1956049bcd15bd5 +967, 0x95b76f31c7f98b6d +968, 0x814b6690df971a84 +969, 0xdcf7959cddd819e4 +970, 0xcf8c72c5d804fc88 +971, 0x56883769c8945a22 +972, 0x1f034652f658cf46 +973, 0x41df1324cda235a1 +974, 0xeccd32524504a054 +975, 0x974e0910a04ec02c +976, 0x72104507b821f6db +977, 0x791f8d089f273044 +978, 0xe0f79a4f567f73c3 +979, 0x52fe5bea3997f024 +980, 0x5f8b9b446494f78 +981, 0xfd9f511947059190 +982, 0x3aea9dac6063bce3 +983, 0xbfdae4dfc24aee60 +984, 0xa82cdbbf0a280318 +985, 0xf460aae18d70aa9d +986, 0x997367cb204a57c4 +987, 0x616e21ab95ba05ef +988, 0x9bfc93bec116769f +989, 0x2b2ee27c37a3fa5b +990, 0xb25c6ed54006ee38 +991, 0xab04d4a5c69e69a5 +992, 0x6d2f6b45f2d8438f +993, 0x4ad2f32afc82f092 +994, 0x513d718908f709c0 +995, 0x5272aadc4fffca51 +996, 0xeb3f87e66156ef5d +997, 0xf8a3d5a46a86ba85 +998, 0xdb4548a86f27abfd +999, 0x57c05f47ff62380d diff --git a/shared/package-files/75/75611c22748976f65aa4d8ddd95be792c5072b28f8fc05525496aca7bbaa141c/blob b/shared/package-files/75/75611c22748976f65aa4d8ddd95be792c5072b28f8fc05525496aca7bbaa141c/blob new file mode 100644 index 0000000000000000000000000000000000000000..69c82a9c6cd17fe27554622fcd61073f360923f8 --- /dev/null +++ b/shared/package-files/75/75611c22748976f65aa4d8ddd95be792c5072b28f8fc05525496aca7bbaa141c/blob @@ -0,0 +1,57 @@ +from _typeshed import SupportsRead +from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Type, Union + +from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder +from .encoder import JSONEncoder as JSONEncoder + +def dumps( + obj: Any, + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any, +) -> str: ... +def dump( + obj: Any, + fp: IO[str], + *, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Optional[Type[JSONEncoder]] = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any, +) -> None: ... +def loads( + s: Union[str, bytes], + *, + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any, +) -> Any: ... +def load( + fp: SupportsRead[Union[str, bytes]], + *, + cls: Optional[Type[JSONDecoder]] = ..., + object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any, +) -> Any: ... diff --git a/shared/package-files/75/75634be5c80dff0a74207d6256b7cd13832709415f1a5f2bfaee9771e84e8e67/blob b/shared/package-files/75/75634be5c80dff0a74207d6256b7cd13832709415f1a5f2bfaee9771e84e8e67/blob new file mode 100644 index 0000000000000000000000000000000000000000..742f900db1aec7ad7cee452e8503ba6822d8c629 --- /dev/null +++ b/shared/package-files/75/75634be5c80dff0a74207d6256b7cd13832709415f1a5f2bfaee9771e84e8e67/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid +inline at::Tensor cudnn_affine_grid_generator(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W) { + return at::_ops::cudnn_affine_grid_generator::call(theta, N, C, H, W); +} + +// aten::cudnn_affine_grid_generator.out(Tensor theta, int N, int C, int H, int W, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_affine_grid_generator_out(at::Tensor & out, const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W) { + return at::_ops::cudnn_affine_grid_generator_out::call(theta, N, C, H, W, out); +} +// aten::cudnn_affine_grid_generator.out(Tensor theta, int N, int C, int H, int W, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_affine_grid_generator_outf(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W, at::Tensor & out) { + return at::_ops::cudnn_affine_grid_generator_out::call(theta, N, C, H, W, out); +} + +} diff --git a/shared/package-files/75/7564256bb869ec0e11a88d9ad2a44d40b58d3c4baeafaf250f77554f292d7415/blob b/shared/package-files/75/7564256bb869ec0e11a88d9ad2a44d40b58d3c4baeafaf250f77554f292d7415/blob new file mode 100644 index 0000000000000000000000000000000000000000..ec1b3b683511a34e6f98b9839d112b87517390d8 --- /dev/null +++ b/shared/package-files/75/7564256bb869ec0e11a88d9ad2a44d40b58d3c4baeafaf250f77554f292d7415/blob @@ -0,0 +1,126 @@ +from sympy.core import (Function, Pow, sympify, Expr) +from sympy.core.relational import Relational +from sympy.core.singleton import S +from sympy.polys import Poly, decompose +from sympy.utilities.misc import func_name +from sympy.functions.elementary.miscellaneous import Min, Max + + +def decompogen(f, symbol): + """ + Computes General functional decomposition of ``f``. + Given an expression ``f``, returns a list ``[f_1, f_2, ..., f_n]``, + where:: + f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) + + Note: This is a General decomposition function. It also decomposes + Polynomials. For only Polynomial decomposition see ``decompose`` in polys. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import decompogen, sqrt, sin, cos + >>> decompogen(sin(cos(x)), x) + [sin(x), cos(x)] + >>> decompogen(sin(x)**2 + sin(x) + 1, x) + [x**2 + x + 1, sin(x)] + >>> decompogen(sqrt(6*x**2 - 5), x) + [sqrt(x), 6*x**2 - 5] + >>> decompogen(sin(sqrt(cos(x**2 + 1))), x) + [sin(x), sqrt(x), cos(x), x**2 + 1] + >>> decompogen(x**4 + 2*x**3 - x - 1, x) + [x**2 - x - 1, x**2 + x] + + """ + f = sympify(f) + if not isinstance(f, Expr) or isinstance(f, Relational): + raise TypeError('expecting Expr but got: `%s`' % func_name(f)) + if symbol not in f.free_symbols: + return [f] + + + # ===== Simple Functions ===== # + if isinstance(f, (Function, Pow)): + if f.is_Pow and f.base == S.Exp1: + arg = f.exp + else: + arg = f.args[0] + if arg == symbol: + return [f] + return [f.subs(arg, symbol)] + decompogen(arg, symbol) + + # ===== Min/Max Functions ===== # + if isinstance(f, (Min, Max)): + args = list(f.args) + d0 = None + for i, a in enumerate(args): + if not a.has_free(symbol): + continue + d = decompogen(a, symbol) + if len(d) == 1: + d = [symbol] + d + if d0 is None: + d0 = d[1:] + elif d[1:] != d0: + # decomposition is not the same for each arg: + # mark as having no decomposition + d = [symbol] + break + args[i] = d[0] + if d[0] == symbol: + return [f] + return [f.func(*args)] + d0 + + # ===== Convert to Polynomial ===== # + fp = Poly(f) + gens = list(filter(lambda x: symbol in x.free_symbols, fp.gens)) + + if len(gens) == 1 and gens[0] != symbol: + f1 = f.subs(gens[0], symbol) + f2 = gens[0] + return [f1] + decompogen(f2, symbol) + + # ===== Polynomial decompose() ====== # + try: + return decompose(f) + except ValueError: + return [f] + + +def compogen(g_s, symbol): + """ + Returns the composition of functions. + Given a list of functions ``g_s``, returns their composition ``f``, + where: + f = g_1 o g_2 o .. o g_n + + Note: This is a General composition function. It also composes Polynomials. + For only Polynomial composition see ``compose`` in polys. + + Examples + ======== + + >>> from sympy.solvers.decompogen import compogen + >>> from sympy.abc import x + >>> from sympy import sqrt, sin, cos + >>> compogen([sin(x), cos(x)], x) + sin(cos(x)) + >>> compogen([x**2 + x + 1, sin(x)], x) + sin(x)**2 + sin(x) + 1 + >>> compogen([sqrt(x), 6*x**2 - 5], x) + sqrt(6*x**2 - 5) + >>> compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x) + sin(sqrt(cos(x**2 + 1))) + >>> compogen([x**2 - x - 1, x**2 + x], x) + -x**2 - x + (x**2 + x)**2 - 1 + """ + if len(g_s) == 1: + return g_s[0] + + foo = g_s[0].subs(symbol, g_s[1]) + + if len(g_s) == 2: + return foo + + return compogen([foo] + g_s[2:], symbol) diff --git a/shared/package-files/75/7568f8f50d28babe24e12182936ece4ab4e48d73e671b1021b1cbee33c1b251e/blob b/shared/package-files/75/7568f8f50d28babe24e12182936ece4ab4e48d73e671b1021b1cbee33c1b251e/blob new file mode 100644 index 0000000000000000000000000000000000000000..c4d546942f8608e8f91b149cc94fa4590dfc7799 --- /dev/null +++ b/shared/package-files/75/7568f8f50d28babe24e12182936ece4ab4e48d73e671b1021b1cbee33c1b251e/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _gather_sparse_backward { + using schema = at::Tensor (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_gather_sparse_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_gather_sparse_backward(Tensor self, int dim, Tensor index, Tensor grad) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & grad); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & grad); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/75/756c2b15e3f0f1e5f6ac185e0178b5015c6bfe0a810fadd564a7d6f3584da107/blob b/shared/package-files/75/756c2b15e3f0f1e5f6ac185e0178b5015c6bfe0a810fadd564a7d6f3584da107/blob new file mode 100644 index 0000000000000000000000000000000000000000..96cabe0ff4aaa5977e16600217fbbdeb08b962ae --- /dev/null +++ b/shared/package-files/75/756c2b15e3f0f1e5f6ac185e0178b5015c6bfe0a810fadd564a7d6f3584da107/blob @@ -0,0 +1,94 @@ +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.external import import_module +from sympy.stats import Binomial, sample, Die, FiniteRV, DiscreteUniform, Bernoulli, BetaBinomial, Hypergeometric, \ + Rademacher +from sympy.testing.pytest import skip, raises + +def test_given_sample(): + X = Die('X', 6) + scipy = import_module('scipy') + if not scipy: + skip('Scipy is not installed. Abort tests') + assert sample(X, X > 5) == 6 + +def test_sample_numpy(): + distribs_numpy = [ + Binomial("B", 5, 0.4), + Hypergeometric("H", 2, 1, 1) + ] + size = 3 + numpy = import_module('numpy') + if not numpy: + skip('Numpy is not installed. Abort tests for _sample_numpy.') + else: + for X in distribs_numpy: + samps = sample(X, size=size, library='numpy') + for sam in samps: + assert sam in X.pspace.domain.set + raises(NotImplementedError, + lambda: sample(Die("D"), library='numpy')) + raises(NotImplementedError, + lambda: Die("D").pspace.sample(library='tensorflow')) + + +def test_sample_scipy(): + distribs_scipy = [ + FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}), + DiscreteUniform("Y", list(range(5))), + Die("D"), + Bernoulli("Be", 0.3), + Binomial("Bi", 5, 0.4), + BetaBinomial("Bb", 2, 1, 1), + Hypergeometric("H", 1, 1, 1), + Rademacher("R") + ] + + size = 3 + scipy = import_module('scipy') + if not scipy: + skip('Scipy not installed. Abort tests for _sample_scipy.') + else: + for X in distribs_scipy: + samps = sample(X, size=size) + samps2 = sample(X, size=(2, 2)) + for sam in samps: + assert sam in X.pspace.domain.set + for i in range(2): + for j in range(2): + assert samps2[i][j] in X.pspace.domain.set + + +def test_sample_pymc(): + distribs_pymc = [ + Bernoulli('B', 0.2), + Binomial('N', 5, 0.4) + ] + size = 3 + pymc = import_module('pymc') + if not pymc: + skip('PyMC is not installed. Abort tests for _sample_pymc.') + else: + for X in distribs_pymc: + samps = sample(X, size=size, library='pymc') + for sam in samps: + assert sam in X.pspace.domain.set + raises(NotImplementedError, + lambda: (sample(Die("D"), library='pymc'))) + + +def test_sample_seed(): + F = FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}) + size = 10 + libraries = ['scipy', 'numpy', 'pymc'] + for lib in libraries: + try: + imported_lib = import_module(lib) + if imported_lib: + s0 = sample(F, size=size, library=lib, seed=0) + s1 = sample(F, size=size, library=lib, seed=0) + s2 = sample(F, size=size, library=lib, seed=1) + assert all(s0 == s1) + assert not all(s1 == s2) + except NotImplementedError: + continue diff --git a/shared/package-files/75/756d25bc26fff3e4e8c82ae038cf96333504d4aa0596b00c0a7dc4eae296cfec/blob b/shared/package-files/75/756d25bc26fff3e4e8c82ae038cf96333504d4aa0596b00c0a7dc4eae296cfec/blob new file mode 100644 index 0000000000000000000000000000000000000000..828870361b20b215c4d575f82dd75c8343cdd44d --- /dev/null +++ b/shared/package-files/75/756d25bc26fff3e4e8c82ae038cf96333504d4aa0596b00c0a7dc4eae296cfec/blob @@ -0,0 +1,35 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void _foreach_addcmul_Scalar_out(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Scalar & value, at::TensorList out); +TORCH_API ::std::vector foreach_tensor_addcmul_scalar_slow(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Scalar & value=1); +TORCH_API void foreach_tensor_addcmul_scalar_slow_(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Scalar & value=1); +TORCH_API ::std::vector foreach_tensor_addcmul_scalar_cuda(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Scalar & value=1); +TORCH_API void foreach_tensor_addcmul_scalar_cuda_(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Scalar & value=1); +TORCH_API void _foreach_addcmul_ScalarList_out(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, at::ArrayRef scalars, at::TensorList out); +TORCH_API ::std::vector foreach_tensor_addcmul_scalarlist_slow(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, at::ArrayRef scalars); +TORCH_API void foreach_tensor_addcmul_scalarlist_slow_(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, at::ArrayRef scalars); +TORCH_API ::std::vector foreach_tensor_addcmul_scalarlist_cuda(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, at::ArrayRef scalars); +TORCH_API void foreach_tensor_addcmul_scalarlist_cuda_(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, at::ArrayRef scalars); +TORCH_API void _foreach_addcmul_Tensor_out(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Tensor & scalars, at::TensorList out); +TORCH_API ::std::vector foreach_tensor_addcmul_tensor_slow(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Tensor & scalars); +TORCH_API void foreach_tensor_addcmul_tensor_slow_(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Tensor & scalars); +TORCH_API ::std::vector foreach_tensor_addcmul_tensor_cuda(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Tensor & scalars); +TORCH_API void foreach_tensor_addcmul_tensor_cuda_(at::TensorList self, at::TensorList tensor1, at::TensorList tensor2, const at::Tensor & scalars); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/756e457b79541cff1d9ac48f0c631b95d1a5d86967111e08f735a1094ea0ffbf/blob b/shared/package-files/75/756e457b79541cff1d9ac48f0c631b95d1a5d86967111e08f735a1094ea0ffbf/blob new file mode 100644 index 0000000000000000000000000000000000000000..607c75a4c2e8828a55a73c85c48c0551d1b72aa2 --- /dev/null +++ b/shared/package-files/75/756e457b79541cff1d9ac48f0c631b95d1a5d86967111e08f735a1094ea0ffbf/blob @@ -0,0 +1,95 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/util/concurrent_map.h" + +#include "parquet/encryption/kms_client.h" +#include "parquet/platform.h" + +namespace parquet::encryption { + +/// This class supports local wrapping mode, master keys will be fetched from the KMS +/// server and used to encrypt other keys (data encryption keys or key encryption keys). +class PARQUET_EXPORT LocalWrapKmsClient : public KmsClient { + public: + static constexpr const char kLocalWrapNoKeyVersion[] = "NO_VERSION"; + + explicit LocalWrapKmsClient(const KmsConnectionConfig& kms_connection_config); + + std::string WrapKey(const ::arrow::util::SecureString& key_bytes, + const std::string& master_key_identifier) override; + + ::arrow::util::SecureString UnwrapKey( + const std::string& wrapped_key, const std::string& master_key_identifier) override; + + protected: + /// Get master key from the remote KMS server. + /// Note: this function might be called by multiple threads + virtual const ::arrow::util::SecureString& GetMasterKeyFromServer( + const std::string& master_key_identifier) = 0; + + private: + /// KMS systems wrap keys by encrypting them by master keys, and attaching additional + /// information (such as the version number of the masker key) to the result of + /// encryption. The master key version is required in key rotation. Currently, the + /// local wrapping mode does not support key rotation (because not all KMS systems allow + /// to fetch a master key by its ID and version number). Still, the local wrapping mode + /// adds a placeholder for the master key version, that will enable support for key + /// rotation in this mode in the future, with appropriate KMS systems. This will also + /// enable backward compatibility, where future readers will be able to extract master + /// key version in the files written by the current code. + /// + /// LocalKeyWrap class writes (and reads) the "key wrap" as a flat json with the + /// following fields: + /// 1. "masterKeyVersion" - a String, with the master key version. In the current + /// version, only one value is allowed - "NO_VERSION". + /// 2. "encryptedKey" - a String, with the key encrypted by the master key + /// (base64-encoded). + class LocalKeyWrap { + public: + static constexpr const char kLocalWrapKeyVersionField[] = "masterKeyVersion"; + static constexpr const char kLocalWrapEncryptedKeyField[] = "encryptedKey"; + + LocalKeyWrap(std::string master_key_version, std::string encrypted_encoded_key); + + static std::string CreateSerialized(const std::string& encrypted_encoded_key); + + static LocalKeyWrap Parse(const std::string& wrapped_key); + + const std::string& master_key_version() const { return master_key_version_; } + + const std::string& encrypted_encoded_key() const { return encrypted_encoded_key_; } + + private: + std::string encrypted_encoded_key_; + std::string master_key_version_; + }; + + const ::arrow::util::SecureString& GetKeyFromServer(const std::string& key_identifier); + + protected: + KmsConnectionConfig kms_connection_config_; + ::arrow::util::ConcurrentMap + master_key_cache_; +}; + +} // namespace parquet::encryption diff --git a/shared/package-files/75/75708fb4b8867d0f41da983fb3f60aedfbd6c145be09b54e3d8527f69685a2c9/blob b/shared/package-files/75/75708fb4b8867d0f41da983fb3f60aedfbd6c145be09b54e3d8527f69685a2c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..cb2a35be907cdca8d6777b708623c50288d6cca7 --- /dev/null +++ b/shared/package-files/75/75708fb4b8867d0f41da983fb3f60aedfbd6c145be09b54e3d8527f69685a2c9/blob @@ -0,0 +1,24 @@ +""" +Tests for Timestamp timezone-related methods +""" +from datetime import datetime + +from pandas._libs.tslibs import timezones + +from pandas import Timestamp + + +class TestTimestampTZOperations: + # ------------------------------------------------------------------ + + def test_timestamp_timetz_equivalent_with_datetime_tz(self, tz_naive_fixture): + # GH21358 + tz = timezones.maybe_get_tz(tz_naive_fixture) + + stamp = Timestamp("2018-06-04 10:20:30", tz=tz) + _datetime = datetime(2018, 6, 4, hour=10, minute=20, second=30, tzinfo=tz) + + result = stamp.timetz() + expected = _datetime.timetz() + + assert result == expected diff --git a/shared/package-files/75/7570ac0189fb699b968b972919463dfcf09cf16f458e05cadd9927a97e90f78a/blob b/shared/package-files/75/7570ac0189fb699b968b972919463dfcf09cf16f458e05cadd9927a97e90f78a/blob new file mode 100644 index 0000000000000000000000000000000000000000..2f5cd2939de25682e63c588b16a18f6ebd0ede0f Binary files /dev/null and b/shared/package-files/75/7570ac0189fb699b968b972919463dfcf09cf16f458e05cadd9927a97e90f78a/blob differ diff --git a/shared/package-files/75/75732a474b99b4da1ffaf3818e50bb4c12527ae498f91c3881e47b4cc2d8ba80/blob b/shared/package-files/75/75732a474b99b4da1ffaf3818e50bb4c12527ae498f91c3881e47b4cc2d8ba80/blob new file mode 100644 index 0000000000000000000000000000000000000000..7f83db3796b41443700d604e4103755b0f9043e4 --- /dev/null +++ b/shared/package-files/75/75732a474b99b4da1ffaf3818e50bb4c12527ae498f91c3881e47b4cc2d8ba80/blob @@ -0,0 +1,481 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +// Caching allocator will execute every registered callback if it unable to find +// block inside of already allocated area. +class C10_CUDA_API FreeMemoryCallback { + public: + virtual ~FreeMemoryCallback() = default; + virtual bool Execute() = 0; +}; + +C10_DECLARE_REGISTRY(FreeCudaMemoryCallbacksRegistry, FreeMemoryCallback); +#define REGISTER_FREE_MEMORY_CALLBACK(name, ...) \ + C10_REGISTER_CLASS(FreeCudaMemoryCallbacksRegistry, name, __VA_ARGS__); +} // namespace c10 + // +// TODO: Turn this into an honest to goodness class. I briefly attempted to do +// this, but it was a bit irritating to figure out how to also correctly +// apply pimpl pattern so I didn't have to leak any internal implementation +// details in the header (CUDACachingAllocator could be made a pimpl, but +// you also need to appropriately define a class which is a subclass +// of Allocator. Not impossible, but required a bit more surgery than +// I wanted to do at the time.) +// +// Why is this using a namespace rather than old-style THCCachingAllocator_ +// prefix? Mostly because it made the HIPify rules easier to write; _ is +// not counted as a word boundary, so you would otherwise have to list each +// of these functions. + +namespace c10::cuda::CUDACachingAllocator { + +extern const size_t kLargeBuffer; + +struct Stat { + int64_t current = 0; + int64_t peak = 0; + int64_t allocated = 0; + int64_t freed = 0; +}; + +enum struct StatType : uint64_t { + AGGREGATE = 0, + SMALL_POOL = 1, + LARGE_POOL = 2, + NUM_TYPES = 3 // remember to update this whenever a new stat type is added +}; + +typedef std::array(StatType::NUM_TYPES)> StatArray; + +// Struct containing memory allocator summary statistics for a device. +struct DeviceStats { + // COUNT: allocations requested by client code + StatArray allocation; + // COUNT: number of allocated segments from cudaMalloc(). + StatArray segment; + // COUNT: number of active memory blocks (allocated or used by stream) + StatArray active; + // COUNT: number of inactive, split memory blocks (unallocated but can't be + // released via cudaFree) + StatArray inactive_split; + + // SUM: bytes allocated by this memory alocator + StatArray allocated_bytes; + // SUM: bytes reserved by this memory allocator (both free and used) + StatArray reserved_bytes; + // SUM: bytes within active memory blocks + StatArray active_bytes; + // SUM: bytes within inactive, split memory blocks + StatArray inactive_split_bytes; + // SUM: bytes requested by client code + StatArray requested_bytes; + + // COUNT: total number of failed calls to CUDA malloc necessitating cache + // flushes. + int64_t num_alloc_retries = 0; + + // COUNT: total number of OOMs (i.e. failed calls to CUDA after cache flush) + int64_t num_ooms = 0; + + // COUNT: total number of oversize blocks allocated from pool + Stat oversize_allocations; + + // COUNT: total number of oversize blocks requiring malloc + Stat oversize_segments; + + // COUNT: total number of synchronize_and_free_events() calls + int64_t num_sync_all_streams = 0; + + // COUNT: total number of CUDA allocation calls. This includes both cuMemMap + // and cudaMalloc. + int64_t num_device_alloc = 0; + + // COUNT: total number of CUDA free calls. This includes both cuMemUnmap + // and cudaFree. + int64_t num_device_free = 0; + + // SIZE: maximum block size that is allowed to be split. + int64_t max_split_size = 0; +}; + +typedef std::shared_ptr (*CreateContextFn)(); + +// Struct containing info of an allocation block (i.e. a fractional part of a +// cudaMalloc).. +struct BlockInfo { + int64_t size = 0; + int64_t requested_size = 0; + int32_t gc_counter = 0; + bool allocated = false; + bool active = false; + std::shared_ptr + context_when_allocated; // per-watcher context +}; + +// Struct containing info of a memory segment (i.e. one contiguous cudaMalloc). +struct SegmentInfo { + c10::DeviceIndex device = 0; + int64_t address = 0; + int64_t total_size = 0; + int64_t requested_size = 0; // unrounded, actually requested size + int64_t allocated_size = 0; + int64_t active_size = 0; + cudaStream_t stream = nullptr; + bool is_large = false; + bool is_expandable = false; + MempoolId_t owner_private_pool_id = {0, 0}; + std::vector blocks; + std::shared_ptr context_when_allocated; +}; + +struct AllocatorState { + virtual ~AllocatorState() = default; +}; + +union trace_time_ { + time_t t_; + approx_time_t approx_t_; +}; + +struct TraceEntry { + enum Action { + ALLOC, // API made to the caching allocator for new memory + FREE_REQUESTED, // API call made to the caching allocator to free memory + FREE_COMPLETED, // The allocator might have to delay a free because + // it is still in use on another stream via record_stream + // This event is generated when a free actually completes. + SEGMENT_ALLOC, // a call to cudaMalloc to get more memory from the OS + SEGMENT_FREE, // a call to cudaFree to return memory to the OS (e.g. to + // defragment or empty_caches) + SEGMENT_MAP, // a call to cuMemMap (used with expandable_segments) + SEGMENT_UNMAP, // unmap part of a segment (used with expandable segments) + SNAPSHOT, // a call to snapshot, used to correlate memory snapshots to trace + // events + OOM // the allocator threw an OutOfMemoryError (addr_ is the amount of free + // bytes reported by cuda) + }; + TraceEntry( + Action action, + c10::DeviceIndex device, + int64_t addr, + size_t size, + cudaStream_t stream, + approx_time_t time, + std::shared_ptr context = nullptr) + : action_(action), + device_(device), + addr_(addr), + context_(std::move(context)), + stream_(stream), + size_(static_cast(size)) { + time_.approx_t_ = time; + } + Action action_; + c10::DeviceIndex device_; + int64_t addr_; // for OOM, this is the amount of free bytes reported by cuda + std::shared_ptr context_; + cudaStream_t stream_{}; + int64_t size_; + trace_time_ time_{}; +}; + +struct AllocatorConfigInfo { + double garbage_collection_threshold; + size_t max_split_size; + size_t pinned_num_register_threads; + bool expandable_segments; + bool release_lock_on_malloc; + bool pinned_use_host_register; + std::string last_allocator_settings; + std::vector roundup_power2_divisions; +}; + +struct SnapshotInfo { + std::vector segments; + std::vector> device_traces; + AllocatorConfigInfo config_metadata; +}; + +// returns the pointers freed in the pool +// and the pointers allocated. Note: a pointer +// may appear in both freed and allocated +struct CheckpointDelta { + std::vector ptrs_freed; + std::vector dataptrs_allocd; +}; + +enum struct RecordContext { + NEVER = 0, + STATE = 1, // only keep stacks for active allocations + ALLOC = 2, // additionally keep stacks for allocations in the trace history + ALL = 3, // additionally record stacks for when something is freed +}; + +// Size pretty-printer +std::string format_size(uint64_t size); + +using OutOfMemoryObserver = std::function; + +using AllocatorTraceTracker = std::function; + +class CUDAAllocator : public Allocator { + public: + virtual void* raw_alloc(size_t nbytes) = 0; + virtual void* raw_alloc_with_stream(size_t nbytes, cudaStream_t stream) = 0; + virtual void raw_delete(void* ptr) = 0; + virtual void init(int device_count) = 0; + virtual bool initialized() = 0; + virtual void setMemoryFraction(double fraction, c10::DeviceIndex device) = 0; + virtual void emptyCache() = 0; + virtual void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) = 0; + virtual void* getBaseAllocation(void* ptr, size_t* size) = 0; + virtual void recordStream(const DataPtr&, CUDAStream stream) = 0; + virtual DeviceStats getDeviceStats(c10::DeviceIndex device) = 0; + virtual void resetAccumulatedStats(c10::DeviceIndex device) = 0; + virtual void resetPeakStats(c10::DeviceIndex device) = 0; + virtual SnapshotInfo snapshot() = 0; + virtual void beginAllocateToPool( + c10::DeviceIndex device, + MempoolId_t mempool_id, + std::function filter) = 0; + virtual void endAllocateToPool( + c10::DeviceIndex device, + MempoolId_t mempool_id) = 0; + virtual void releasePool(c10::DeviceIndex device, MempoolId_t mempool_id) = 0; + // returns true if the allocated blocks are equal to expected live allocations + virtual bool checkPoolLiveAllocations( + c10::DeviceIndex device, + MempoolId_t mempool_id, + const std::unordered_set& expected_live_allocations) { + TORCH_CHECK( + false, + name(), + " does not yet support checkPoolLiveAllocations. " + "If you need it, please file an issue describing your use case."); + } + virtual std::shared_ptr getIpcDevPtr(std::string handle) = 0; + virtual bool isHistoryEnabled() { + TORCH_CHECK( + false, + name(), + " does not yet support recordHistory. " + "If you need it, please file an issue describing your use case."); + } + virtual void recordHistory( + bool enabled, + CreateContextFn context_recorder, + size_t alloc_trace_max_entries, + RecordContext when) = 0; + virtual void attachOutOfMemoryObserver(OutOfMemoryObserver observer) = 0; + + // Attached AllocatorTraceTracker callbacks will be called while the + // per-device allocator lock is held. Any additional locks taken from within + // the callback must be proven to always have the lock order that never + // triggers a deadlock. In particular, Python's GIL may be held when + // calling the allocator so it is unsafe to try to acquire the GIL in this + // callback. + virtual void attachAllocatorTraceTracker(AllocatorTraceTracker tracker) = 0; + + virtual void enablePeerAccess( + c10::DeviceIndex dev, + c10::DeviceIndex dev_to_access) = 0; + + // memory not allocated from cudaMalloc cannot be copied + // across devices using cudaMemcpyAsync if peer to peer access is disabled. + // instead it requires cudaMemcpyAsyncPeer + // with P2P Enabled, all combinations work + // with P2P Disabled: + // cudaMalloc cudaMallocAsync/cuMemMap + // cudaMemcpyAsyncPeer works works + // cudaMemcpyAsync works error + + // This function performs chooses to use the Peer version of + // memcpy if required based on where the allocated put dst/src. + virtual cudaError_t memcpyAsync( + void* dst, + int dstDevice, + const void* src, + int srcDevice, + size_t count, + cudaStream_t stream, + bool p2p_enabled) = 0; + virtual std::shared_ptr getCheckpointState( + c10::DeviceIndex device, + MempoolId_t id) = 0; + virtual CheckpointDelta setCheckpointPoolState( + c10::DeviceIndex device, + std::shared_ptr pps) = 0; + virtual std::string name() = 0; +}; + +// Allocator object, statically initialized +// See BackendInitializer in CUDACachingAllocator.cpp. +// Atomic loads on x86 are just normal loads, +// (atomic stores are different), so reading this value +// is no different than loading a pointer. +C10_CUDA_API extern std::atomic allocator; + +inline CUDAAllocator* get() { + return allocator.load(); +} + +// Called directly by clients. +inline void* raw_alloc(size_t nbytes) { + return get()->raw_alloc(nbytes); +} + +inline void* raw_alloc_with_stream(size_t nbytes, cudaStream_t stream) { + return get()->raw_alloc_with_stream(nbytes, stream); +} + +inline void raw_delete(void* ptr) { + return get()->raw_delete(ptr); +} + +inline void init(int device_count) { + return get()->init(device_count); +} + +inline void setMemoryFraction(double fraction, c10::DeviceIndex device) { + return get()->setMemoryFraction(fraction, device); +} + +inline void emptyCache() { + return get()->emptyCache(); +} + +inline void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) { + return get()->cacheInfo(device, largestBlock); +} + +inline void* getBaseAllocation(void* ptr, size_t* size) { + return get()->getBaseAllocation(ptr, size); +} + +inline void recordStream(const DataPtr& dataPtr, CUDAStream stream) { + return get()->recordStream(dataPtr, stream); +} + +inline DeviceStats getDeviceStats(c10::DeviceIndex device) { + return get()->getDeviceStats(device); +} + +inline void resetAccumulatedStats(c10::DeviceIndex device) { + return get()->resetAccumulatedStats(device); +} + +inline void resetPeakStats(c10::DeviceIndex device) { + return get()->resetPeakStats(device); +} + +inline SnapshotInfo snapshot() { + return get()->snapshot(); +} + +inline std::shared_ptr getCheckpointState( + c10::DeviceIndex device, + MempoolId_t id) { + return get()->getCheckpointState(device, id); +} + +inline CheckpointDelta setCheckpointPoolState( + c10::DeviceIndex device, + std::shared_ptr pps) { + return get()->setCheckpointPoolState(device, std::move(pps)); +} + +// CUDAGraph interactions +inline void beginAllocateToPool( + c10::DeviceIndex device, + MempoolId_t mempool_id, + std::function filter) { + get()->beginAllocateToPool(device, mempool_id, std::move(filter)); +} + +inline void endAllocateToPool(c10::DeviceIndex device, MempoolId_t mempool_id) { + get()->endAllocateToPool(device, mempool_id); +} + +inline void recordHistory( + bool enabled, + CreateContextFn context_recorder, + size_t alloc_trace_max_entries, + RecordContext when) { + return get()->recordHistory( + enabled, context_recorder, alloc_trace_max_entries, when); +} + +inline bool isHistoryEnabled() { + return get()->isHistoryEnabled(); +} + +inline bool checkPoolLiveAllocations( + c10::DeviceIndex device, + MempoolId_t mempool_id, + const std::unordered_set& expected_live_allocations) { + return get()->checkPoolLiveAllocations( + device, mempool_id, expected_live_allocations); +} + +inline void attachOutOfMemoryObserver(OutOfMemoryObserver observer) { + return get()->attachOutOfMemoryObserver(std::move(observer)); +} + +inline void attachAllocatorTraceTracker(AllocatorTraceTracker tracker) { + return get()->attachAllocatorTraceTracker(std::move(tracker)); +} + +inline void releasePool(c10::DeviceIndex device, MempoolId_t mempool_id) { + return get()->releasePool(device, mempool_id); +} +// Not part of CUDA_ALLOCATOR_BACKEND_INTERFACE +inline std::shared_ptr getIpcDevPtr(std::string handle) { + return get()->getIpcDevPtr(std::move(handle)); +} + +inline std::string name() { + return get()->name(); +} + +inline cudaError_t memcpyAsync( + void* dst, + int dstDevice, + const void* src, + int srcDevice, + size_t count, + cudaStream_t stream, + bool p2p_enabled) { + return get()->memcpyAsync( + dst, dstDevice, src, srcDevice, count, stream, p2p_enabled); +} + +inline void enablePeerAccess( + c10::DeviceIndex dev, + c10::DeviceIndex dev_to_access) { + return get()->enablePeerAccess(dev, dev_to_access); +} + +} // namespace c10::cuda::CUDACachingAllocator diff --git a/shared/package-files/75/757338c2147c00fc0cab3d2b8ef15a75eb7139fe290209cfa8c4f0aee7ca48ef/blob b/shared/package-files/75/757338c2147c00fc0cab3d2b8ef15a75eb7139fe290209cfa8c4f0aee7ca48ef/blob new file mode 100644 index 0000000000000000000000000000000000000000..824740792aaf031a0adcc181cb84a666ef539fe4 --- /dev/null +++ b/shared/package-files/75/757338c2147c00fc0cab3d2b8ef15a75eb7139fe290209cfa8c4f0aee7ca48ef/blob @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE + +TORCH_API void PropagateShapesOnGraph(std::shared_ptr& graph); + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE +// From [beg, end) attempt to propagate shapes and +// build up a graph that will compute all remaining symbolic +// shapes in [beg, end) that can be executed before beg + +struct ShapeComputeGraphMapping { + ShapeComputeGraphMapping( + std::shared_ptr partial_eval_shape_graph, + std::unordered_map + enclosing_graph_value_to_shape_graph_input, + std::unordered_map graph_output_to_symbolic_shape_dim) + : partial_eval_shape_graph(std::move(partial_eval_shape_graph)), + enclosing_graph_value_to_shape_graph_input_( + std::move(enclosing_graph_value_to_shape_graph_input)), + graph_output_to_symbolic_shape_dim_( + std::move(graph_output_to_symbolic_shape_dim)){}; + + std::shared_ptr partial_eval_shape_graph; + std::unordered_map + enclosing_graph_value_to_shape_graph_input_; + std::unordered_map graph_output_to_symbolic_shape_dim_; +}; + +TORCH_API c10::optional +PropagateShapesAndBuildLargeShapeComputeGraph( + std::shared_ptr& graph, + Node* beg, + Node* end); + +// don't insert complete tensor shapes in shape compute graphs and instead +// rely on our partial evaluation pipeline to propagate information. +// this is a good proxy for our ability to propagate non-complete shape +// information. +TORCH_API bool setSymbolicShapeAnalysisTestMode(bool value); +TORCH_API bool symbolicShapeAnalysisTestModeEnabled(); + +using SSAInput = std::variant; +TORCH_API c10::optional> +calculateSymbolicShapesOnOp( + const FunctionSchema* schema, + const std::vector& inputs); +} // namespace jit +} // namespace torch diff --git a/shared/package-files/75/7573581dec27e90b0c7d34057d9f4ef89727317d55f2c4e0428a47740fb1eb7a/blob b/shared/package-files/75/7573581dec27e90b0c7d34057d9f4ef89727317d55f2c4e0428a47740fb1eb7a/blob new file mode 100644 index 0000000000000000000000000000000000000000..3614763a3c35bf0e54c0dc47ed564f8c1b499ca1 --- /dev/null +++ b/shared/package-files/75/7573581dec27e90b0c7d34057d9f4ef89727317d55f2c4e0428a47740fb1eb7a/blob @@ -0,0 +1,53 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset de_BE DAYS_OF_WEEK_ABBREV [list \ + "Son"\ + "Mon"\ + "Die"\ + "Mit"\ + "Don"\ + "Fre"\ + "Sam"] + ::msgcat::mcset de_BE DAYS_OF_WEEK_FULL [list \ + "Sonntag"\ + "Montag"\ + "Dienstag"\ + "Mittwoch"\ + "Donnerstag"\ + "Freitag"\ + "Samstag"] + ::msgcat::mcset de_BE MONTHS_ABBREV [list \ + "Jan"\ + "Feb"\ + "M\u00e4r"\ + "Apr"\ + "Mai"\ + "Jun"\ + "Jul"\ + "Aug"\ + "Sep"\ + "Okt"\ + "Nov"\ + "Dez"\ + ""] + ::msgcat::mcset de_BE MONTHS_FULL [list \ + "Januar"\ + "Februar"\ + "M\u00e4rz"\ + "April"\ + "Mai"\ + "Juni"\ + "Juli"\ + "August"\ + "September"\ + "Oktober"\ + "November"\ + "Dezember"\ + ""] + ::msgcat::mcset de_BE AM "vorm" + ::msgcat::mcset de_BE PM "nachm" + ::msgcat::mcset de_BE DATE_FORMAT "%Y-%m-%d" + ::msgcat::mcset de_BE TIME_FORMAT "%T" + ::msgcat::mcset de_BE TIME_FORMAT_12 "%T" + ::msgcat::mcset de_BE DATE_TIME_FORMAT "%a %d %b %Y %T %z" +} diff --git a/shared/package-files/75/75741fcd550c3fd39c07a88abf9ca8d462c4c05077809e3ca61220a3837e78cd/blob b/shared/package-files/75/75741fcd550c3fd39c07a88abf9ca8d462c4c05077809e3ca61220a3837e78cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..b58e867a133f804fbaf0d31099258a11e29058aa --- /dev/null +++ b/shared/package-files/75/75741fcd550c3fd39c07a88abf9ca8d462c4c05077809e3ca61220a3837e78cd/blob @@ -0,0 +1,10 @@ +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + config = Configuration('polynomial', parent_package, top_path) + config.add_subpackage('tests') + config.add_data_files('*.pyi') + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(configuration=configuration) diff --git a/shared/package-files/75/7574ab15cf4a698f3e46f700fba0541eeee1eaacbd4f6ea3819081d952fd88a6/blob b/shared/package-files/75/7574ab15cf4a698f3e46f700fba0541eeee1eaacbd4f6ea3819081d952fd88a6/blob new file mode 100644 index 0000000000000000000000000000000000000000..1f32a3521ba8a58e73ff83abaa71c034799b2941 --- /dev/null +++ b/shared/package-files/75/7574ab15cf4a698f3e46f700fba0541eeee1eaacbd4f6ea3819081d952fd88a6/blob @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch { +namespace lazy { + +struct TorchScriptIrBuilder : IrBuilder { + NodePtr MakeDeviceData( + const std::shared_ptr& data) const override { + return DeviceData::Create(data); + } + // TODO: Scalar node is not currently used by ts_backend. Enable reusing + // Scalar node later if needed. + NodePtr MakeScalar(const at::Scalar& value, const at::ScalarType& type) + const override { + return MakeNode(value, type); + } + NodePtr MakeExpand( + const Value& input0, + const std::vector& size, + const bool& is_scalar_expand) const override { + return ReuseOrMakeNode(input0, size, is_scalar_expand); + } + NodePtr MakeCast( + const Value& input0, + const at::ScalarType& dtype, + const c10::optional& stype = + c10::nullopt) const override { + return ReuseOrMakeNode(input0, dtype, stype); + } + NodePtr MakeTensorList(const OpList& inputs) const override { + return ReuseOrMakeNode(inputs); + } + // Generic needs cleanup + NodePtr MakeGeneric( + const OpKind& op, + const OpList& operands, + const Shape& shape, + const size_t& num_outputs = 1, + const hash_t& hash_seed = + static_cast(0x5a2d296e9)) const override { + return MakeNode(op, operands, shape, num_outputs, hash_seed); + } + + // dynamic ir nodes + // TODO: verify if IR node reusing works for Dynamic shape ops + NodePtr MakeSizeNode(const Value& input, size_t dim) const override { + return MakeNode(input, dim); + } + NodePtr MakeSizeAdd(const Value& a, const Value& b) const override { + return MakeNode(a, b); + } + NodePtr MakeSizeMul(const Value& a, const Value& b) const override { + return MakeNode(a, b); + } + NodePtr MakeSizeDiv(const Value& a, const Value& b) const override { + return MakeNode(a, b); + } +}; + +} // namespace lazy +} // namespace torch diff --git a/shared/package-files/75/75750b90fe67dacc2cba93f52a5709f81f5c319752d9b08b2c2a31738be00f90/blob b/shared/package-files/75/75750b90fe67dacc2cba93f52a5709f81f5c319752d9b08b2c2a31738be00f90/blob new file mode 100644 index 0000000000000000000000000000000000000000..b6327ea0294cb9d1834af9ac0b19a6f522fab99b --- /dev/null +++ b/shared/package-files/75/75750b90fe67dacc2cba93f52a5709f81f5c319752d9b08b2c2a31738be00f90/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API linalg_inv { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_inv") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_inv(Tensor A) -> Tensor") + static at::Tensor call(const at::Tensor & A); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A); +}; + +struct TORCH_API linalg_inv_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_inv") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_inv.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & A, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/75/757719b9c69c012dc287a9eb0c13e1d9edcb6192df67b570aa905405bfaf30fa/blob b/shared/package-files/75/757719b9c69c012dc287a9eb0c13e1d9edcb6192df67b570aa905405bfaf30fa/blob new file mode 100644 index 0000000000000000000000000000000000000000..41a9990b898826c3a5e455f4e91b5b3af6da83e7 --- /dev/null +++ b/shared/package-files/75/757719b9c69c012dc287a9eb0c13e1d9edcb6192df67b570aa905405bfaf30fa/blob @@ -0,0 +1,10 @@ +from matplotlib.tri import Triangulation +from numpy.typing import ArrayLike + +class TriFinder: + def __init__(self, triangulation: Triangulation) -> None: ... + def __call__(self, x: ArrayLike, y: ArrayLike) -> ArrayLike: ... + +class TrapezoidMapTriFinder(TriFinder): + def __init__(self, triangulation: Triangulation) -> None: ... + def __call__(self, x: ArrayLike, y: ArrayLike) -> ArrayLike: ... diff --git a/shared/package-files/75/757848512824db5273b6c7f176bb0d5aae347d039584f2e6316450a1ccbfab73/blob b/shared/package-files/75/757848512824db5273b6c7f176bb0d5aae347d039584f2e6316450a1ccbfab73/blob new file mode 100644 index 0000000000000000000000000000000000000000..fecf93225e76b9a67f4022da81708ffdbff94097 --- /dev/null +++ b/shared/package-files/75/757848512824db5273b6c7f176bb0d5aae347d039584f2e6316450a1ccbfab73/blob @@ -0,0 +1,15 @@ +#pragma once + +#include +#include +#include + +namespace torch { + +std::string format_invalid_args( + PyObject* given_args, + PyObject* given_kwargs, + const std::string& function_name, + const std::vector& options); + +} // namespace torch diff --git a/shared/package-files/75/7579a3868cd7e58cdbec3b2bb5b7454ea0318bd675519349bc6c63faf1ccedc3/blob b/shared/package-files/75/7579a3868cd7e58cdbec3b2bb5b7454ea0318bd675519349bc6c63faf1ccedc3/blob new file mode 100644 index 0000000000000000000000000000000000000000..c95672f99f878f3def660aadec901afbde9adf8b --- /dev/null +++ b/shared/package-files/75/7579a3868cd7e58cdbec3b2bb5b7454ea0318bd675519349bc6c63faf1ccedc3/blob @@ -0,0 +1,208 @@ +"""Tests for sparse distributed modules. """ + +from sympy.polys.distributedmodules import ( + sdm_monomial_mul, sdm_monomial_deg, sdm_monomial_divides, + sdm_add, sdm_LM, sdm_LT, sdm_mul_term, sdm_zero, sdm_deg, + sdm_LC, sdm_from_dict, + sdm_spoly, sdm_ecart, sdm_nf_mora, sdm_groebner, + sdm_from_vector, sdm_to_vector, sdm_monomial_lcm +) + +from sympy.polys.orderings import lex, grlex, InverseOrder +from sympy.polys.domains import QQ + +from sympy.abc import x, y, z + + +def test_sdm_monomial_mul(): + assert sdm_monomial_mul((1, 1, 0), (1, 3)) == (1, 2, 3) + + +def test_sdm_monomial_deg(): + assert sdm_monomial_deg((5, 2, 1)) == 3 + + +def test_sdm_monomial_lcm(): + assert sdm_monomial_lcm((1, 2, 3), (1, 5, 0)) == (1, 5, 3) + + +def test_sdm_monomial_divides(): + assert sdm_monomial_divides((1, 0, 0), (1, 0, 0)) is True + assert sdm_monomial_divides((1, 0, 0), (1, 2, 1)) is True + assert sdm_monomial_divides((5, 1, 1), (5, 2, 1)) is True + + assert sdm_monomial_divides((1, 0, 0), (2, 0, 0)) is False + assert sdm_monomial_divides((1, 1, 0), (1, 0, 0)) is False + assert sdm_monomial_divides((5, 1, 2), (5, 0, 1)) is False + + +def test_sdm_LC(): + assert sdm_LC([((1, 2, 3), QQ(5))], QQ) == QQ(5) + + +def test_sdm_from_dict(): + dic = {(1, 2, 1, 1): QQ(1), (1, 1, 2, 1): QQ(1), (1, 0, 2, 1): QQ(1), + (1, 0, 0, 3): QQ(1), (1, 1, 1, 0): QQ(1)} + assert sdm_from_dict(dic, grlex) == \ + [((1, 2, 1, 1), QQ(1)), ((1, 1, 2, 1), QQ(1)), + ((1, 0, 2, 1), QQ(1)), ((1, 0, 0, 3), QQ(1)), ((1, 1, 1, 0), QQ(1))] + +# TODO test to_dict? + + +def test_sdm_add(): + assert sdm_add([((1, 1, 1), QQ(1))], [((2, 0, 0), QQ(1))], lex, QQ) == \ + [((2, 0, 0), QQ(1)), ((1, 1, 1), QQ(1))] + assert sdm_add([((1, 1, 1), QQ(1))], [((1, 1, 1), QQ(-1))], lex, QQ) == [] + assert sdm_add([((1, 0, 0), QQ(1))], [((1, 0, 0), QQ(2))], lex, QQ) == \ + [((1, 0, 0), QQ(3))] + assert sdm_add([((1, 0, 1), QQ(1))], [((1, 1, 0), QQ(1))], lex, QQ) == \ + [((1, 1, 0), QQ(1)), ((1, 0, 1), QQ(1))] + + +def test_sdm_LM(): + dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(1), (4, 0, 1): QQ(1)} + assert sdm_LM(sdm_from_dict(dic, lex)) == (4, 0, 1) + + +def test_sdm_LT(): + dic = {(1, 2, 3): QQ(1), (4, 0, 0): QQ(2), (4, 0, 1): QQ(3)} + assert sdm_LT(sdm_from_dict(dic, lex)) == ((4, 0, 1), QQ(3)) + + +def test_sdm_mul_term(): + assert sdm_mul_term([((1, 0, 0), QQ(1))], ((0, 0), QQ(0)), lex, QQ) == [] + assert sdm_mul_term([], ((1, 0), QQ(1)), lex, QQ) == [] + assert sdm_mul_term([((1, 0, 0), QQ(1))], ((1, 0), QQ(1)), lex, QQ) == \ + [((1, 1, 0), QQ(1))] + f = [((2, 0, 1), QQ(4)), ((1, 1, 0), QQ(3))] + assert sdm_mul_term(f, ((1, 1), QQ(2)), lex, QQ) == \ + [((2, 1, 2), QQ(8)), ((1, 2, 1), QQ(6))] + + +def test_sdm_zero(): + assert sdm_zero() == [] + + +def test_sdm_deg(): + assert sdm_deg([((1, 2, 3), 1), ((10, 0, 1), 1), ((2, 3, 4), 4)]) == 7 + + +def test_sdm_spoly(): + f = [((2, 1, 1), QQ(1)), ((1, 0, 1), QQ(1))] + g = [((2, 3, 0), QQ(1))] + h = [((1, 2, 3), QQ(1))] + assert sdm_spoly(f, h, lex, QQ) == [] + assert sdm_spoly(f, g, lex, QQ) == [((1, 2, 1), QQ(1))] + + +def test_sdm_ecart(): + assert sdm_ecart([((1, 2, 3), 1), ((1, 0, 1), 1)]) == 0 + assert sdm_ecart([((2, 2, 1), 1), ((1, 5, 1), 1)]) == 3 + + +def test_sdm_nf_mora(): + f = sdm_from_dict({(1, 2, 1, 1): QQ(1), (1, 1, 2, 1): QQ(1), + (1, 0, 2, 1): QQ(1), (1, 0, 0, 3): QQ(1), (1, 1, 1, 0): QQ(1)}, + grlex) + f1 = sdm_from_dict({(1, 1, 1, 0): QQ(1), (1, 0, 2, 0): QQ(1), + (1, 0, 0, 0): QQ(-1)}, grlex) + f2 = sdm_from_dict({(1, 1, 1, 0): QQ(1)}, grlex) + (id0, id1, id2) = [sdm_from_dict({(i, 0, 0, 0): QQ(1)}, grlex) + for i in range(3)] + + assert sdm_nf_mora(f, [f1, f2], grlex, QQ, phantom=(id0, [id1, id2])) == \ + ([((1, 0, 2, 1), QQ(1)), ((1, 0, 0, 3), QQ(1)), ((1, 1, 1, 0), QQ(1)), + ((1, 1, 0, 1), QQ(1))], + [((1, 1, 0, 1), QQ(-1)), ((0, 0, 0, 0), QQ(1))]) + assert sdm_nf_mora(f, [f2, f1], grlex, QQ, phantom=(id0, [id2, id1])) == \ + ([((1, 0, 2, 1), QQ(1)), ((1, 0, 0, 3), QQ(1)), ((1, 1, 1, 0), QQ(1))], + [((2, 1, 0, 1), QQ(-1)), ((2, 0, 1, 1), QQ(-1)), ((0, 0, 0, 0), QQ(1))]) + + f = sdm_from_vector([x*z, y**2 + y*z - z, y], lex, QQ, gens=[x, y, z]) + f1 = sdm_from_vector([x, y, 1], lex, QQ, gens=[x, y, z]) + f2 = sdm_from_vector([x*y, z, z**2], lex, QQ, gens=[x, y, z]) + assert sdm_nf_mora(f, [f1, f2], lex, QQ) == \ + sdm_nf_mora(f, [f2, f1], lex, QQ) == \ + [((1, 0, 1, 1), QQ(1)), ((1, 0, 0, 1), QQ(-1)), ((0, 1, 1, 0), QQ(-1)), + ((0, 1, 0, 1), QQ(1))] + + +def test_conversion(): + f = [x**2 + y**2, 2*z] + g = [((1, 0, 0, 1), QQ(2)), ((0, 2, 0, 0), QQ(1)), ((0, 0, 2, 0), QQ(1))] + assert sdm_to_vector(g, [x, y, z], QQ) == f + assert sdm_from_vector(f, lex, QQ) == g + assert sdm_from_vector( + [x, 1], lex, QQ) == [((1, 0), QQ(1)), ((0, 1), QQ(1))] + assert sdm_to_vector([((1, 1, 0, 0), 1)], [x, y, z], QQ, n=3) == [0, x, 0] + assert sdm_from_vector([0, 0], lex, QQ, gens=[x, y]) == sdm_zero() + + +def test_nontrivial(): + gens = [x, y, z] + + def contains(I, f): + S = [sdm_from_vector([g], lex, QQ, gens=gens) for g in I] + G = sdm_groebner(S, sdm_nf_mora, lex, QQ) + return sdm_nf_mora(sdm_from_vector([f], lex, QQ, gens=gens), + G, lex, QQ) == sdm_zero() + + assert contains([x, y], x) + assert contains([x, y], x + y) + assert not contains([x, y], 1) + assert not contains([x, y], z) + assert contains([x**2 + y, x**2 + x], x - y) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x) + assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z) + assert contains([x, 1 + x + y, 5 - 7*y], 1) + assert contains( + [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], + x**3) + assert not contains( + [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], + x**2 + y**2) + + # compare local order + assert not contains([x*(1 + x + y), y*(1 + z)], x) + assert not contains([x*(1 + x + y), y*(1 + z)], x + y) + + +def test_local(): + igrlex = InverseOrder(grlex) + gens = [x, y, z] + + def contains(I, f): + S = [sdm_from_vector([g], igrlex, QQ, gens=gens) for g in I] + G = sdm_groebner(S, sdm_nf_mora, igrlex, QQ) + return sdm_nf_mora(sdm_from_vector([f], lex, QQ, gens=gens), + G, lex, QQ) == sdm_zero() + assert contains([x, y], x) + assert contains([x, y], x + y) + assert not contains([x, y], 1) + assert not contains([x, y], z) + assert contains([x**2 + y, x**2 + x], x - y) + assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) + assert contains([x*(1 + x + y), y*(1 + z)], x) + assert contains([x*(1 + x + y), y*(1 + z)], x + y) + + +def test_uncovered_line(): + gens = [x, y] + f1 = sdm_zero() + f2 = sdm_from_vector([x, 0], lex, QQ, gens=gens) + f3 = sdm_from_vector([0, y], lex, QQ, gens=gens) + + assert sdm_spoly(f1, f2, lex, QQ) == sdm_zero() + assert sdm_spoly(f3, f2, lex, QQ) == sdm_zero() + + +def test_chain_criterion(): + gens = [x] + f1 = sdm_from_vector([1, x], grlex, QQ, gens=gens) + f2 = sdm_from_vector([0, x - 2], grlex, QQ, gens=gens) + assert len(sdm_groebner([f1, f2], sdm_nf_mora, grlex, QQ)) == 2 diff --git a/shared/package-files/75/757c0807435a8fed138e56a6b0a41cae53514e13c75b79ef047b54b76f2747a0/blob b/shared/package-files/75/757c0807435a8fed138e56a6b0a41cae53514e13c75b79ef047b54b76f2747a0/blob new file mode 100644 index 0000000000000000000000000000000000000000..bf7e3ef769b84074ca54628a65b724fb83688f0a --- /dev/null +++ b/shared/package-files/75/757c0807435a8fed138e56a6b0a41cae53514e13c75b79ef047b54b76f2747a0/blob @@ -0,0 +1,441 @@ +import sys +from typing import Any, Callable, Generic, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, overload + +_F = TypeVar("_F", bound=Callable[..., Any]) +_T = TypeVar("_T") +_TT = TypeVar("_TT", bound=Type[Any]) +_R = TypeVar("_R") + +__all__ = [ + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", +] +__version__: str + +FILTER_DIR: Any + +class _slotted: ... + +class _SentinelObject: + name: Any + def __init__(self, name: Any) -> None: ... + +class _Sentinel: + def __init__(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +sentinel: Any +DEFAULT: Any + +class _Call(Tuple[Any, ...]): + def __new__( + cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ... + ) -> Any: ... + name: Any + parent: Any + from_kall: Any + def __init__( + self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ... + ) -> None: ... + def __eq__(self, other: Any) -> bool: ... + __ne__: Any + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: Any) -> Any: ... + def count(self, *args: Any, **kwargs: Any) -> Any: ... + def index(self, *args: Any, **kwargs: Any) -> Any: ... + def call_list(self) -> Any: ... + +call: _Call + +class _CallList(List[_Call]): + def __contains__(self, value: Any) -> bool: ... + +class _MockIter: + obj: Any + def __init__(self, obj: Any) -> None: ... + def __iter__(self) -> Any: ... + def __next__(self) -> Any: ... + +class Base: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +class NonCallableMock(Base, Any): # type: ignore + def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... + def __init__( + self, + spec: Union[List[str], object, Type[object], None] = ..., + wraps: Optional[Any] = ..., + name: Optional[str] = ..., + spec_set: Union[List[str], object, Type[object], None] = ..., + parent: Optional[NonCallableMock] = ..., + _spec_state: Optional[Any] = ..., + _new_name: str = ..., + _new_parent: Optional[NonCallableMock] = ..., + _spec_as_instance: bool = ..., + _eat_self: Optional[bool] = ..., + unsafe: bool = ..., + **kwargs: Any, + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + if sys.version_info >= (3, 8): + def _calls_repr(self, prefix: str = ...) -> str: ... + def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(self) -> None: ... + def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = ...) -> str: ... + elif sys.version_info >= (3, 5): + def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(_mock_self) -> None: ... + def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ... + if sys.version_info >= (3, 8): + def assert_called(self) -> None: ... + def assert_called_once(self) -> None: ... + elif sys.version_info >= (3, 6): + def assert_called(_mock_self) -> None: ... + def assert_called_once(_mock_self) -> None: ... + if sys.version_info >= (3, 6): + def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ... + elif sys.version_info >= (3, 5): + def reset_mock(self, visited: Any = ...) -> None: ... + if sys.version_info >= (3, 7): + def _extract_mock_name(self) -> str: ... + def _get_call_signature_from_name(self, name: str) -> Any: ... + def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ... + def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... + def configure_mock(self, **kwargs: Any) -> None: ... + return_value: Any + side_effect: Any + called: bool + call_count: int + call_args: Any + call_args_list: _CallList + mock_calls: _CallList + def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... + def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ... + def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... + +class CallableMixin(Base): + side_effect: Any + def __init__( + self, + spec: Optional[Any] = ..., + side_effect: Optional[Any] = ..., + return_value: Any = ..., + wraps: Optional[Any] = ..., + name: Optional[Any] = ..., + spec_set: Optional[Any] = ..., + parent: Optional[Any] = ..., + _spec_state: Optional[Any] = ..., + _new_name: Any = ..., + _new_parent: Optional[Any] = ..., + **kwargs: Any, + ) -> None: ... + def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + +class Mock(CallableMixin, NonCallableMock): ... + +class _patch(Generic[_T]): + attribute_name: Any + getter: Callable[[], Any] + attribute: str + new: _T + new_callable: Any + spec: Any + create: bool + has_local: Any + spec_set: Any + autospec: Any + kwargs: Mapping[str, Any] + additional_patchers: Any + if sys.version_info >= (3, 8): + @overload + def __init__( + self: _patch[Union[MagicMock, AsyncMock]], + getter: Callable[[], Any], + attribute: str, + *, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + # This overload also covers the case, where new==DEFAULT. In this case, self is _patch[Any]. + # Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + else: + @overload + def __init__( + self: _patch[MagicMock], + getter: Callable[[], Any], + attribute: str, + *, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + @overload + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... + def copy(self) -> _patch[_T]: ... + def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + def decorate_class(self, klass: _TT) -> _TT: ... + def decorate_callable(self, func: _F) -> _F: ... + def get_original(self) -> Tuple[Any, bool]: ... + target: Any + temp_original: Any + is_local: bool + def __enter__(self) -> _T: ... + def __exit__(self, *exc_info: Any) -> None: ... + def start(self) -> _T: ... + def stop(self) -> None: ... + +class _patch_dict: + in_dict: Any + values: Any + clear: Any + def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ... + def __call__(self, f: Any) -> Any: ... + def decorate_class(self, klass: Any) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: Any) -> Any: ... + start: Any + stop: Any + +class _patcher: + TEST_PREFIX: str + dict: Type[_patch_dict] + if sys.version_info >= (3, 8): + @overload + def __call__( # type: ignore + self, + target: Any, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[Union[MagicMock, AsyncMock]]: ... + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __call__( + self, + target: Any, + new: _T, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + else: + @overload + def __call__( # type: ignore + self, + target: Any, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[MagicMock]: ... + @overload + def __call__( + self, + target: Any, + new: _T, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + if sys.version_info >= (3, 8): + @overload + def object( # type: ignore + self, + target: Any, + attribute: str, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[Union[MagicMock, AsyncMock]]: ... + @overload + def object( + self, + target: Any, + attribute: str, + new: _T = ..., + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + else: + @overload + def object( # type: ignore + self, + target: Any, + attribute: str, + *, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[MagicMock]: ... + @overload + def object( + self, + target: Any, + attribute: str, + new: _T = ..., + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + def multiple( + self, + target: Any, + spec: Optional[Any] = ..., + create: bool = ..., + spec_set: Optional[Any] = ..., + autospec: Optional[Any] = ..., + new_callable: Optional[Any] = ..., + **kwargs: _T, + ) -> _patch[_T]: ... + def stopall(self) -> None: ... + +patch: _patcher + +class MagicMixin: + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class NonCallableMagicMock(MagicMixin, NonCallableMock): + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + +class MagicMock(MagicMixin, Mock): + def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ... + +if sys.version_info >= (3, 8): + class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... + def assert_awaited(self) -> None: ... + def assert_awaited_once(self) -> None: ... + def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(self, calls: _CallList, any_order: bool = ...) -> None: ... + def assert_not_awaited(self) -> None: ... + def reset_mock(self, *args, **kwargs) -> None: ... + await_count: int + await_args: Optional[_Call] + await_args_list: _CallList + class AsyncMagicMixin(MagicMixin): + def __init__(self, *args: Any, **kw: Any) -> None: ... + class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... + +class MagicProxy: + name: Any + parent: Any + def __init__(self, name: Any, parent: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Optional[Any] = ...) -> Any: ... + +class _ANY: + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +ANY: Any + +def create_autospec( + spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any +) -> Any: ... + +class _SpecState: + spec: Any + ids: Any + spec_set: Any + parent: Any + instance: Any + name: Any + def __init__( + self, + spec: Any, + spec_set: Any = ..., + parent: Optional[Any] = ..., + name: Optional[Any] = ..., + ids: Optional[Any] = ..., + instance: Any = ..., + ) -> None: ... + +def mock_open(mock: Optional[Any] = ..., read_data: Any = ...) -> Any: ... + +PropertyMock = Any + +if sys.version_info >= (3, 7): + def seal(mock: Any) -> None: ... diff --git a/shared/package-files/75/757d547ab3c42c63d5e25cec6a316ad8137327853caed781fe2346ea963d3092/blob b/shared/package-files/75/757d547ab3c42c63d5e25cec6a316ad8137327853caed781fe2346ea963d3092/blob new file mode 100644 index 0000000000000000000000000000000000000000..a15f08555822b803f3b3400e9b0da39ea3247f43 --- /dev/null +++ b/shared/package-files/75/757d547ab3c42c63d5e25cec6a316ad8137327853caed781fe2346ea963d3092/blob @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor eq(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & eq_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & eq_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & eq_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor eq(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & eq_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & eq_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & eq_(at::Tensor & self, const at::Tensor & other); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/75/7580ac059609cc6773fff13034735b0386b49db0a0c4df41f29fb5380ffa8fc7/blob b/shared/package-files/75/7580ac059609cc6773fff13034735b0386b49db0a0c4df41f29fb5380ffa8fc7/blob new file mode 100644 index 0000000000000000000000000000000000000000..b7ec419f0b79876a4d1e51bf319baf120fc3ce64 --- /dev/null +++ b/shared/package-files/75/7580ac059609cc6773fff13034735b0386b49db0a0c4df41f29fb5380ffa8fc7/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor linalg_det(const at::Tensor & A); +TORCH_API at::Tensor & linalg_det_out(at::Tensor & out, const at::Tensor & A); +TORCH_API at::Tensor & linalg_det_outf(const at::Tensor & A, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/75/7584d1b57bcc0d71e22b35c70f64a1d1f704ba4a1bdf0aff19b49ea9a66bacef/blob b/shared/package-files/75/7584d1b57bcc0d71e22b35c70f64a1d1f704ba4a1bdf0aff19b49ea9a66bacef/blob new file mode 100644 index 0000000000000000000000000000000000000000..4ec2397ea96261d7b582d1f699e3897caae88f20 --- /dev/null +++ b/shared/package-files/75/7584d1b57bcc0d71e22b35c70f64a1d1f704ba4a1bdf0aff19b49ea9a66bacef/blob @@ -0,0 +1,14 @@ +import sympy.physics.mechanics as _me +import sympy as _sm +import math as m +import numpy as _np + +x, y = _me.dynamicsymbols('x y') +a11, a12, a21, a22, b1, b2 = _sm.symbols('a11 a12 a21 a22 b1 b2', real=True) +eqn = _sm.Matrix([[0]]) +eqn[0] = a11*x+a12*y-b1 +eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]])) +eqn[eqn.shape[0]-1] = a21*x+a22*y-b2 +eqn_list = [] +for i in eqn: eqn_list.append(i.subs({a11:2, a12:5, a21:3, a22:4, b1:7, b2:6})) +print(_sm.linsolve(eqn_list, x,y)) diff --git a/shared/package-files/75/75882dd66f83674fe776dc4ae418cf070606f0df22f8de5b90dadcd30994eba8/blob b/shared/package-files/75/75882dd66f83674fe776dc4ae418cf070606f0df22f8de5b90dadcd30994eba8/blob new file mode 100644 index 0000000000000000000000000000000000000000..4a06207b6eaf8f24d673c7ec227c3a5643c2d6a3 --- /dev/null +++ b/shared/package-files/75/75882dd66f83674fe776dc4ae418cf070606f0df22f8de5b90dadcd30994eba8/blob @@ -0,0 +1,19 @@ +import torch + +from torch._export.db.case import export_case, SupportLevel + + +@export_case( + example_inputs=(torch.randn(2, 3),), + tags={"python.object-model"}, + support_level=SupportLevel.NOT_SUPPORTED_YET, +) +class OptionalInput(torch.nn.Module): + """ + Tracing through optional input is not supported yet + """ + + def forward(self, x, y=torch.ones(2, 3)): + if y is not None: + return x + y + return x diff --git a/shared/package-files/75/758c26e7c89566c9b4199beb8fbbf53bbc1df5fa3bb106fbc20e33bb0ec1748f/blob b/shared/package-files/75/758c26e7c89566c9b4199beb8fbbf53bbc1df5fa3bb106fbc20e33bb0ec1748f/blob new file mode 100644 index 0000000000000000000000000000000000000000..db4db85c90ae8c33c7554157eaaa3cca5b5a4b14 --- /dev/null +++ b/shared/package-files/75/758c26e7c89566c9b4199beb8fbbf53bbc1df5fa3bb106fbc20e33bb0ec1748f/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor reciprocal(const at::Tensor & self); +TORCH_API at::Tensor & reciprocal_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & reciprocal_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & reciprocal_(at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/75/758f7f1c0f6d887e85158251ab128e245b5c967a7f7c238ceaf49b917c538790/blob b/shared/package-files/75/758f7f1c0f6d887e85158251ab128e245b5c967a7f7c238ceaf49b917c538790/blob new file mode 100644 index 0000000000000000000000000000000000000000..da65f15fad8bd854b6090ac4cb704d6367a1674d --- /dev/null +++ b/shared/package-files/75/758f7f1c0f6d887e85158251ab128e245b5c967a7f7c238ceaf49b917c538790/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor log10(const at::Tensor & self); +TORCH_API at::Tensor & log10_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & log10_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & log10_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/75/758fa52c656bd2b43ea7fcbef313f9a5aa6f084b9206e68590d782f000c437f3/blob b/shared/package-files/75/758fa52c656bd2b43ea7fcbef313f9a5aa6f084b9206e68590d782f000c437f3/blob new file mode 100644 index 0000000000000000000000000000000000000000..a1cfe8d9f21a8c3164274574d8fd4e4d9a8e7809 --- /dev/null +++ b/shared/package-files/75/758fa52c656bd2b43ea7fcbef313f9a5aa6f084b9206e68590d782f000c437f3/blob @@ -0,0 +1,230 @@ +from typing import Any, Optional, Text + +from werkzeug.exceptions import HTTPException + +def parse_converter_args(argstr): ... +def parse_rule(rule): ... + +class RoutingException(Exception): ... + +class RequestRedirect(HTTPException, RoutingException): + code: Any + new_url: Any + def __init__(self, new_url): ... + def get_response(self, environ): ... + +class RequestSlash(RoutingException): ... + +class RequestAliasRedirect(RoutingException): + matched_values: Any + def __init__(self, matched_values): ... + +class BuildError(RoutingException, LookupError): + endpoint: Any + values: Any + method: Any + adapter: Optional[MapAdapter] + def __init__(self, endpoint, values, method, adapter: Optional[MapAdapter] = ...) -> None: ... + @property + def suggested(self) -> Optional[Rule]: ... + def closest_rule(self, adapter: Optional[MapAdapter]) -> Optional[Rule]: ... + +class ValidationError(ValueError): ... + +class RuleFactory: + def get_rules(self, map): ... + +class Subdomain(RuleFactory): + subdomain: Any + rules: Any + def __init__(self, subdomain, rules): ... + def get_rules(self, map): ... + +class Submount(RuleFactory): + path: Any + rules: Any + def __init__(self, path, rules): ... + def get_rules(self, map): ... + +class EndpointPrefix(RuleFactory): + prefix: Any + rules: Any + def __init__(self, prefix, rules): ... + def get_rules(self, map): ... + +class RuleTemplate: + rules: Any + def __init__(self, rules): ... + def __call__(self, *args, **kwargs): ... + +class RuleTemplateFactory(RuleFactory): + rules: Any + context: Any + def __init__(self, rules, context): ... + def get_rules(self, map): ... + +class Rule(RuleFactory): + rule: Any + is_leaf: Any + map: Any + strict_slashes: Any + subdomain: Any + host: Any + defaults: Any + build_only: Any + alias: Any + methods: Any + endpoint: Any + redirect_to: Any + arguments: Any + def __init__( + self, + string, + defaults: Optional[Any] = ..., + subdomain: Optional[Any] = ..., + methods: Optional[Any] = ..., + build_only: bool = ..., + endpoint: Optional[Any] = ..., + strict_slashes: Optional[Any] = ..., + redirect_to: Optional[Any] = ..., + alias: bool = ..., + host: Optional[Any] = ..., + ): ... + def empty(self): ... + def get_empty_kwargs(self): ... + def get_rules(self, map): ... + def refresh(self): ... + def bind(self, map, rebind: bool = ...): ... + def get_converter(self, variable_name, converter_name, args, kwargs): ... + def compile(self): ... + def match(self, path, method: Optional[Any] = ...): ... + def build(self, values, append_unknown: bool = ...): ... + def provides_defaults_for(self, rule): ... + def suitable_for(self, values, method: Optional[Any] = ...): ... + def match_compare_key(self): ... + def build_compare_key(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + +class BaseConverter: + regex: Any + weight: Any + map: Any + def __init__(self, map): ... + def to_python(self, value): ... + def to_url(self, value) -> str: ... + +class UnicodeConverter(BaseConverter): + regex: Any + def __init__(self, map, minlength: int = ..., maxlength: Optional[Any] = ..., length: Optional[Any] = ...): ... + +class AnyConverter(BaseConverter): + regex: Any + def __init__(self, map, *items): ... + +class PathConverter(BaseConverter): + regex: Any + weight: Any + +class NumberConverter(BaseConverter): + weight: Any + fixed_digits: Any + min: Any + max: Any + def __init__(self, map, fixed_digits: int = ..., min: Optional[Any] = ..., max: Optional[Any] = ...): ... + def to_python(self, value): ... + def to_url(self, value) -> str: ... + +class IntegerConverter(NumberConverter): + regex: Any + num_convert: Any + +class FloatConverter(NumberConverter): + regex: Any + num_convert: Any + def __init__(self, map, min: Optional[Any] = ..., max: Optional[Any] = ...): ... + +class UUIDConverter(BaseConverter): + regex: Any + def to_python(self, value): ... + def to_url(self, value) -> str: ... + +DEFAULT_CONVERTERS: Any + +class Map: + default_converters: Any + default_subdomain: Any + charset: Text + encoding_errors: Text + strict_slashes: Any + redirect_defaults: Any + host_matching: Any + converters: Any + sort_parameters: Any + sort_key: Any + def __init__( + self, + rules: Optional[Any] = ..., + default_subdomain: str = ..., + charset: Text = ..., + strict_slashes: bool = ..., + redirect_defaults: bool = ..., + converters: Optional[Any] = ..., + sort_parameters: bool = ..., + sort_key: Optional[Any] = ..., + encoding_errors: Text = ..., + host_matching: bool = ..., + ): ... + def is_endpoint_expecting(self, endpoint, *arguments): ... + def iter_rules(self, endpoint: Optional[Any] = ...): ... + def add(self, rulefactory): ... + def bind( + self, + server_name, + script_name: Optional[Any] = ..., + subdomain: Optional[Any] = ..., + url_scheme: str = ..., + default_method: str = ..., + path_info: Optional[Any] = ..., + query_args: Optional[Any] = ..., + ): ... + def bind_to_environ(self, environ, server_name: Optional[Any] = ..., subdomain: Optional[Any] = ...): ... + def update(self): ... + +class MapAdapter: + map: Any + server_name: Any + script_name: Any + subdomain: Any + url_scheme: Any + path_info: Any + default_method: Any + query_args: Any + def __init__( + self, map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args: Optional[Any] = ... + ): ... + def dispatch( + self, view_func, path_info: Optional[Any] = ..., method: Optional[Any] = ..., catch_http_exceptions: bool = ... + ): ... + def match( + self, + path_info: Optional[Any] = ..., + method: Optional[Any] = ..., + return_rule: bool = ..., + query_args: Optional[Any] = ..., + ): ... + def test(self, path_info: Optional[Any] = ..., method: Optional[Any] = ...): ... + def allowed_methods(self, path_info: Optional[Any] = ...): ... + def get_host(self, domain_part): ... + def get_default_redirect(self, rule, method, values, query_args): ... + def encode_query_args(self, query_args): ... + def make_redirect_url(self, path_info, query_args: Optional[Any] = ..., domain_part: Optional[Any] = ...): ... + def make_alias_redirect_url(self, path, endpoint, values, method, query_args): ... + def build( + self, + endpoint, + values: Optional[Any] = ..., + method: Optional[Any] = ..., + force_external: bool = ..., + append_unknown: bool = ..., + ): ... diff --git a/shared/package-files/75/7592891e016ba2a78ff43fc5d5d193275f60496fbde337c82539832de169e7f9/blob b/shared/package-files/75/7592891e016ba2a78ff43fc5d5d193275f60496fbde337c82539832de169e7f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..9950a9e8c30a4b38f69ca9627e3980e948dfc213 --- /dev/null +++ b/shared/package-files/75/7592891e016ba2a78ff43fc5d5d193275f60496fbde337c82539832de169e7f9/blob @@ -0,0 +1,44 @@ +# Defined in torch/csrc/monitor/python_init.cpp + +import datetime +from enum import Enum +from typing import Callable, Dict, List, Union + +class Aggregation(Enum): + VALUE = ... + MEAN = ... + COUNT = ... + SUM = ... + MAX = ... + MIN = ... + +class Stat: + name: str + count: int + def __init__( + self, + name: str, + aggregations: List[Aggregation], + window_size: int, + max_samples: int = -1, + ) -> None: ... + def add(self, v: float) -> None: ... + def get(self) -> Dict[Aggregation, float]: ... + +class Event: + name: str + timestamp: datetime.datetime + data: Dict[str, Union[int, float, bool, str]] + def __init__( + self, + name: str, + timestamp: datetime.datetime, + data: Dict[str, Union[int, float, bool, str]], + ) -> None: ... + +def log_event(e: Event) -> None: ... + +class EventHandlerHandle: ... + +def register_event_handler(handler: Callable[[Event], None]) -> EventHandlerHandle: ... +def unregister_event_handler(handle: EventHandlerHandle) -> None: ... diff --git a/shared/package-files/75/7593d4ab920a93bce693f9d287dfef77b09a5f903349bdd500da933d0b785f27/blob b/shared/package-files/75/7593d4ab920a93bce693f9d287dfef77b09a5f903349bdd500da933d0b785f27/blob new file mode 100644 index 0000000000000000000000000000000000000000..97bd13a4134d602ab0a0a11e8964768ea0c9e82d --- /dev/null +++ b/shared/package-files/75/7593d4ab920a93bce693f9d287dfef77b09a5f903349bdd500da933d0b785f27/blob @@ -0,0 +1,27 @@ +import numpy as np +from numpy.testing import assert_allclose +from scipy.linalg import toeplitz + +from statsmodels.tools import linalg + + +def test_stationary_solve_1d(): + rs = np.random.RandomState(283821) + b = rs.uniform(size=10) + r = rs.uniform(size=9) + t = np.concatenate((np.r_[1], r)) + tmat = toeplitz(t) + soln = np.linalg.solve(tmat, b) + soln1 = linalg.stationary_solve(r, b) + assert_allclose(soln, soln1, rtol=1e-5, atol=1e-5) + + +def test_stationary_solve_2d(): + rs = np.random.RandomState(283822) + b = rs.uniform(size=(10, 2)) + r = rs.uniform(size=9) + t = np.concatenate((np.r_[1], r)) + tmat = toeplitz(t) + soln = np.linalg.solve(tmat, b) + soln1 = linalg.stationary_solve(r, b) + assert_allclose(soln, soln1, rtol=1e-5, atol=1e-5) diff --git a/shared/package-files/75/7593fe027fea343257c4ccd6b085f57dc4c8a1cdea23e5889b8f014b780024b9/blob b/shared/package-files/75/7593fe027fea343257c4ccd6b085f57dc4c8a1cdea23e5889b8f014b780024b9/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d76b3afde222ba5e5a9b829a218ea6f20f3b56e --- /dev/null +++ b/shared/package-files/75/7593fe027fea343257c4ccd6b085f57dc4c8a1cdea23e5889b8f014b780024b9/blob @@ -0,0 +1,98 @@ +from types import CodeType, FrameType, TracebackType +from typing import IO, Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, SupportsInt, Tuple, Type, TypeVar, Union + +_T = TypeVar("_T") +_TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type +_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] + +GENERATOR_AND_COROUTINE_FLAGS: int = ... + +class BdbQuit(Exception): ... + +class Bdb: + + skip: Optional[Set[str]] + breaks: Dict[str, List[int]] + fncache: Dict[str, str] + frame_returning: Optional[FrameType] + botframe: Optional[FrameType] + quitting: bool + stopframe: Optional[FrameType] + returnframe: Optional[FrameType] + stoplineno: int + def __init__(self, skip: Optional[Iterable[str]] = ...) -> None: ... + def canonic(self, filename: str) -> str: ... + def reset(self) -> None: ... + def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> _TraceDispatch: ... + def dispatch_line(self, frame: FrameType) -> _TraceDispatch: ... + def dispatch_call(self, frame: FrameType, arg: None) -> _TraceDispatch: ... + def dispatch_return(self, frame: FrameType, arg: Any) -> _TraceDispatch: ... + def dispatch_exception(self, frame: FrameType, arg: _ExcInfo) -> _TraceDispatch: ... + def is_skipped_module(self, module_name: str) -> bool: ... + def stop_here(self, frame: FrameType) -> bool: ... + def break_here(self, frame: FrameType) -> bool: ... + def do_clear(self, arg: Any) -> Optional[bool]: ... + def break_anywhere(self, frame: FrameType) -> bool: ... + def user_call(self, frame: FrameType, argument_list: None) -> None: ... + def user_line(self, frame: FrameType) -> None: ... + def user_return(self, frame: FrameType, return_value: Any) -> None: ... + def user_exception(self, frame: FrameType, exc_info: _ExcInfo) -> None: ... + def set_until(self, frame: FrameType, lineno: Optional[int] = ...) -> None: ... + def set_step(self) -> None: ... + def set_next(self, frame: FrameType) -> None: ... + def set_return(self, frame: FrameType) -> None: ... + def set_trace(self, frame: Optional[FrameType] = ...) -> None: ... + def set_continue(self) -> None: ... + def set_quit(self) -> None: ... + def set_break( + self, filename: str, lineno: int, temporary: bool = ..., cond: Optional[str] = ..., funcname: Optional[str] = ... + ) -> None: ... + def clear_break(self, filename: str, lineno: int) -> None: ... + def clear_bpbynumber(self, arg: SupportsInt) -> None: ... + def clear_all_file_breaks(self, filename: str) -> None: ... + def clear_all_breaks(self) -> None: ... + def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... + def get_break(self, filename: str, lineno: int) -> bool: ... + def get_breaks(self, filename: str, lineno: int) -> List[Breakpoint]: ... + def get_file_breaks(self, filename: str) -> List[Breakpoint]: ... + def get_all_breaks(self) -> List[Breakpoint]: ... + def get_stack(self, f: Optional[FrameType], t: Optional[TracebackType]) -> Tuple[List[Tuple[FrameType, int]], int]: ... + def format_stack_entry(self, frame_lineno: int, lprefix: str = ...) -> str: ... + def run( + self, cmd: Union[str, CodeType], globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ... + ) -> None: ... + def runeval(self, expr: str, globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> None: ... + def runctx( + self, cmd: Union[str, CodeType], globals: Optional[Dict[str, Any]], locals: Optional[Mapping[str, Any]] + ) -> None: ... + def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> Optional[_T]: ... + +class Breakpoint: + + next: int = ... + bplist: Dict[Tuple[str, int], List[Breakpoint]] = ... + bpbynumber: List[Optional[Breakpoint]] = ... + + funcname: Optional[str] + func_first_executable_line: Optional[int] + file: str + line: int + temporary: bool + cond: Optional[str] + enabled: bool + ignore: int + hits: int + number: int + def __init__( + self, file: str, line: int, temporary: bool = ..., cond: Optional[str] = ..., funcname: Optional[str] = ... + ) -> None: ... + def deleteMe(self) -> None: ... + def enable(self) -> None: ... + def disable(self) -> None: ... + def bpprint(self, out: Optional[IO[str]] = ...) -> None: ... + def bpformat(self) -> str: ... + def __str__(self) -> str: ... + +def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... +def effective(file: str, line: int, frame: FrameType) -> Union[Tuple[Breakpoint, bool], Tuple[None, None]]: ... +def set_trace() -> None: ... diff --git a/shared/package-files/75/75958aa9f74b46f26f6c0106fdfa1fffc8a410ac636a400332dcb590b0bf97f3/blob b/shared/package-files/75/75958aa9f74b46f26f6c0106fdfa1fffc8a410ac636a400332dcb590b0bf97f3/blob new file mode 100644 index 0000000000000000000000000000000000000000..87d4213a6d42cf090f8db75571244840dd68cd5a --- /dev/null +++ b/shared/package-files/75/75958aa9f74b46f26f6c0106fdfa1fffc8a410ac636a400332dcb590b0bf97f3/blob @@ -0,0 +1,172 @@ +""" +Various richly-typed exceptions, that also help us deal with string formatting +in python where it's easier. + +By putting the formatting in `__str__`, we also avoid paying the cost for +users who silence the exceptions. +""" +from .._utils import set_module + +def _unpack_tuple(tup): + if len(tup) == 1: + return tup[0] + else: + return tup + + +def _display_as_base(cls): + """ + A decorator that makes an exception class look like its base. + + We use this to hide subclasses that are implementation details - the user + should catch the base type, which is what the traceback will show them. + + Classes decorated with this decorator are subject to removal without a + deprecation warning. + """ + assert issubclass(cls, Exception) + cls.__name__ = cls.__base__.__name__ + return cls + + +class UFuncTypeError(TypeError): + """ Base class for all ufunc exceptions """ + def __init__(self, ufunc): + self.ufunc = ufunc + + +@_display_as_base +class _UFuncNoLoopError(UFuncTypeError): + """ Thrown when a ufunc loop cannot be found """ + def __init__(self, ufunc, dtypes): + super().__init__(ufunc) + self.dtypes = tuple(dtypes) + + def __str__(self): + return ( + "ufunc {!r} did not contain a loop with signature matching types " + "{!r} -> {!r}" + ).format( + self.ufunc.__name__, + _unpack_tuple(self.dtypes[:self.ufunc.nin]), + _unpack_tuple(self.dtypes[self.ufunc.nin:]) + ) + + +@_display_as_base +class _UFuncBinaryResolutionError(_UFuncNoLoopError): + """ Thrown when a binary resolution fails """ + def __init__(self, ufunc, dtypes): + super().__init__(ufunc, dtypes) + assert len(self.dtypes) == 2 + + def __str__(self): + return ( + "ufunc {!r} cannot use operands with types {!r} and {!r}" + ).format( + self.ufunc.__name__, *self.dtypes + ) + + +@_display_as_base +class _UFuncCastingError(UFuncTypeError): + def __init__(self, ufunc, casting, from_, to): + super().__init__(ufunc) + self.casting = casting + self.from_ = from_ + self.to = to + + +@_display_as_base +class _UFuncInputCastingError(_UFuncCastingError): + """ Thrown when a ufunc input cannot be casted """ + def __init__(self, ufunc, casting, from_, to, i): + super().__init__(ufunc, casting, from_, to) + self.in_i = i + + def __str__(self): + # only show the number if more than one input exists + i_str = "{} ".format(self.in_i) if self.ufunc.nin != 1 else "" + return ( + "Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting " + "rule {!r}" + ).format( + self.ufunc.__name__, i_str, self.from_, self.to, self.casting + ) + + +@_display_as_base +class _UFuncOutputCastingError(_UFuncCastingError): + """ Thrown when a ufunc output cannot be casted """ + def __init__(self, ufunc, casting, from_, to, i): + super().__init__(ufunc, casting, from_, to) + self.out_i = i + + def __str__(self): + # only show the number if more than one output exists + i_str = "{} ".format(self.out_i) if self.ufunc.nout != 1 else "" + return ( + "Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting " + "rule {!r}" + ).format( + self.ufunc.__name__, i_str, self.from_, self.to, self.casting + ) + + +@_display_as_base +class _ArrayMemoryError(MemoryError): + """ Thrown when an array cannot be allocated""" + def __init__(self, shape, dtype): + self.shape = shape + self.dtype = dtype + + @property + def _total_size(self): + num_bytes = self.dtype.itemsize + for dim in self.shape: + num_bytes *= dim + return num_bytes + + @staticmethod + def _size_to_string(num_bytes): + """ Convert a number of bytes into a binary size string """ + + # https://en.wikipedia.org/wiki/Binary_prefix + LOG2_STEP = 10 + STEP = 1024 + units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'] + + unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP + unit_val = 1 << (unit_i * LOG2_STEP) + n_units = num_bytes / unit_val + del unit_val + + # ensure we pick a unit that is correct after rounding + if round(n_units) == STEP: + unit_i += 1 + n_units /= STEP + + # deal with sizes so large that we don't have units for them + if unit_i >= len(units): + new_unit_i = len(units) - 1 + n_units *= 1 << ((unit_i - new_unit_i) * LOG2_STEP) + unit_i = new_unit_i + + unit_name = units[unit_i] + # format with a sensible number of digits + if unit_i == 0: + # no decimal point on bytes + return '{:.0f} {}'.format(n_units, unit_name) + elif round(n_units) < 1000: + # 3 significant figures, if none are dropped to the left of the . + return '{:#.3g} {}'.format(n_units, unit_name) + else: + # just give all the digits otherwise + return '{:#.0f} {}'.format(n_units, unit_name) + + def __str__(self): + size_str = self._size_to_string(self._total_size) + return ( + "Unable to allocate {} for an array with shape {} and data type {}" + .format(size_str, self.shape, self.dtype) + ) diff --git a/shared/package-files/75/75973ae495e5475979ba505a42b57390bbf4cfc2e0c17065ac11713b14520599/blob b/shared/package-files/75/75973ae495e5475979ba505a42b57390bbf4cfc2e0c17065ac11713b14520599/blob new file mode 100644 index 0000000000000000000000000000000000000000..4c94dc0d51f7e7de9fbd43150b1331282fbabb90 --- /dev/null +++ b/shared/package-files/75/75973ae495e5475979ba505a42b57390bbf4cfc2e0c17065ac11713b14520599/blob @@ -0,0 +1,606 @@ +import datetime as dt +from datetime import datetime + +import dateutil +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + Timestamp, + concat, + date_range, + to_timedelta, +) +import pandas._testing as tm + + +class TestDatetimeConcat: + def test_concat_datetime64_block(self): + rng = date_range("1/1/2000", periods=10) + + df = DataFrame({"time": rng}) + + result = concat([df, df]) + assert (result.iloc[:10]["time"] == rng).all() + assert (result.iloc[10:]["time"] == rng).all() + + def test_concat_datetime_datetime64_frame(self): + # GH#2624 + rows = [] + rows.append([datetime(2010, 1, 1), 1]) + rows.append([datetime(2010, 1, 2), "hi"]) + + df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) + + ind = date_range(start="2000/1/1", freq="D", periods=10) + df1 = DataFrame({"date": ind, "test": range(10)}) + + # it works! + concat([df1, df2_obj]) + + def test_concat_datetime_timezone(self): + # GH 18523 + idx1 = date_range("2011-01-01", periods=3, freq="h", tz="Europe/Paris") + idx2 = date_range(start=idx1[0], end=idx1[-1], freq="h") + df1 = DataFrame({"a": [1, 2, 3]}, index=idx1) + df2 = DataFrame({"b": [1, 2, 3]}, index=idx2) + result = concat([df1, df2], axis=1) + + exp_idx = DatetimeIndex( + [ + "2011-01-01 00:00:00+01:00", + "2011-01-01 01:00:00+01:00", + "2011-01-01 02:00:00+01:00", + ], + dtype="M8[ns, Europe/Paris]", + freq="h", + ) + expected = DataFrame( + [[1, 1], [2, 2], [3, 3]], index=exp_idx, columns=["a", "b"] + ) + + tm.assert_frame_equal(result, expected) + + idx3 = date_range("2011-01-01", periods=3, freq="h", tz="Asia/Tokyo") + df3 = DataFrame({"b": [1, 2, 3]}, index=idx3) + result = concat([df1, df3], axis=1) + + exp_idx = DatetimeIndex( + [ + "2010-12-31 15:00:00+00:00", + "2010-12-31 16:00:00+00:00", + "2010-12-31 17:00:00+00:00", + "2010-12-31 23:00:00+00:00", + "2011-01-01 00:00:00+00:00", + "2011-01-01 01:00:00+00:00", + ] + ).as_unit("ns") + + expected = DataFrame( + [ + [np.nan, 1], + [np.nan, 2], + [np.nan, 3], + [1, np.nan], + [2, np.nan], + [3, np.nan], + ], + index=exp_idx, + columns=["a", "b"], + ) + + tm.assert_frame_equal(result, expected) + + # GH 13783: Concat after resample + result = concat([df1.resample("h").mean(), df2.resample("h").mean()], sort=True) + expected = DataFrame( + {"a": [1, 2, 3] + [np.nan] * 3, "b": [np.nan] * 3 + [1, 2, 3]}, + index=idx1.append(idx1), + ) + tm.assert_frame_equal(result, expected) + + def test_concat_datetimeindex_freq(self): + # GH 3232 + # Monotonic index result + dr = date_range("01-Jan-2013", periods=100, freq="50ms", tz="UTC") + data = list(range(100)) + expected = DataFrame(data, index=dr) + result = concat([expected[:50], expected[50:]]) + tm.assert_frame_equal(result, expected) + + # Non-monotonic index result + result = concat([expected[50:], expected[:50]]) + expected = DataFrame(data[50:] + data[:50], index=dr[50:].append(dr[:50])) + expected.index._data.freq = None + tm.assert_frame_equal(result, expected) + + def test_concat_multiindex_datetime_object_index(self): + # https://github.com/pandas-dev/pandas/issues/11058 + idx = Index( + [dt.date(2013, 1, 1), dt.date(2014, 1, 1), dt.date(2015, 1, 1)], + dtype="object", + ) + + s = Series( + ["a", "b"], + index=MultiIndex.from_arrays( + [ + [1, 2], + idx[:-1], + ], + names=["first", "second"], + ), + ) + s2 = Series( + ["a", "b"], + index=MultiIndex.from_arrays( + [[1, 2], idx[::2]], + names=["first", "second"], + ), + ) + mi = MultiIndex.from_arrays( + [[1, 2, 2], idx], + names=["first", "second"], + ) + assert mi.levels[1].dtype == object + + expected = DataFrame( + [["a", "a"], ["b", np.nan], [np.nan, "b"]], + index=mi, + ) + result = concat([s, s2], axis=1) + tm.assert_frame_equal(result, expected) + + def test_concat_NaT_series(self): + # GH 11693 + # test for merging NaT series with datetime series. + x = Series( + date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="US/Eastern") + ) + y = Series(pd.NaT, index=[0, 1], dtype="datetime64[ns, US/Eastern]") + expected = Series([x[0], x[1], pd.NaT, pd.NaT]) + + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # all NaT with tz + expected = Series(pd.NaT, index=range(4), dtype="datetime64[ns, US/Eastern]") + result = concat([y, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + def test_concat_NaT_series2(self): + # without tz + x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h")) + y = Series(date_range("20151124 10:00", "20151124 11:00", freq="1h")) + y[:] = pd.NaT + expected = Series([x[0], x[1], pd.NaT, pd.NaT]) + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # all NaT without tz + x[:] = pd.NaT + expected = Series(pd.NaT, index=range(4), dtype="datetime64[ns]") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_concat_NaT_dataframes(self, tz): + # GH 12396 + + dti = DatetimeIndex([pd.NaT, pd.NaT], tz=tz) + first = DataFrame({0: dti}) + second = DataFrame( + [[Timestamp("2015/01/01", tz=tz)], [Timestamp("2016/01/01", tz=tz)]], + index=[2, 3], + ) + expected = DataFrame( + [ + pd.NaT, + pd.NaT, + Timestamp("2015/01/01", tz=tz), + Timestamp("2016/01/01", tz=tz), + ] + ) + + result = concat([first, second], axis=0) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz1", [None, "UTC"]) + @pytest.mark.parametrize("tz2", [None, "UTC"]) + @pytest.mark.parametrize("item", [pd.NaT, Timestamp("20150101")]) + def test_concat_NaT_dataframes_all_NaT_axis_0( + self, tz1, tz2, item, using_array_manager + ): + # GH 12396 + + # tz-naive + first = DataFrame([[pd.NaT], [pd.NaT]]).apply(lambda x: x.dt.tz_localize(tz1)) + second = DataFrame([item]).apply(lambda x: x.dt.tz_localize(tz2)) + + result = concat([first, second], axis=0) + expected = DataFrame(Series([pd.NaT, pd.NaT, item], index=[0, 1, 0])) + expected = expected.apply(lambda x: x.dt.tz_localize(tz2)) + if tz1 != tz2: + expected = expected.astype(object) + if item is pd.NaT and not using_array_manager: + # GH#18463 + # TODO: setting nan here is to keep the test passing as we + # make assert_frame_equal stricter, but is nan really the + # ideal behavior here? + if tz1 is not None: + expected.iloc[-1, 0] = np.nan + else: + expected.iloc[:-1, 0] = np.nan + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz1", [None, "UTC"]) + @pytest.mark.parametrize("tz2", [None, "UTC"]) + def test_concat_NaT_dataframes_all_NaT_axis_1(self, tz1, tz2): + # GH 12396 + + first = DataFrame(Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1)) + second = DataFrame(Series([pd.NaT]).dt.tz_localize(tz2), columns=[1]) + expected = DataFrame( + { + 0: Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1), + 1: Series([pd.NaT, pd.NaT]).dt.tz_localize(tz2), + } + ) + result = concat([first, second], axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz1", [None, "UTC"]) + @pytest.mark.parametrize("tz2", [None, "UTC"]) + def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2): + # GH 12396 + + # tz-naive + first = Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1) + second = DataFrame( + [ + [Timestamp("2015/01/01", tz=tz2)], + [Timestamp("2016/01/01", tz=tz2)], + ], + index=[2, 3], + ) + + expected = DataFrame( + [ + pd.NaT, + pd.NaT, + Timestamp("2015/01/01", tz=tz2), + Timestamp("2016/01/01", tz=tz2), + ] + ) + if tz1 != tz2: + expected = expected.astype(object) + + result = concat([first, second]) + tm.assert_frame_equal(result, expected) + + +class TestTimezoneConcat: + def test_concat_tz_series(self): + # gh-11755: tz and no tz + x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="UTC")) + y = Series(date_range("2012-01-01", "2012-01-02")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + def test_concat_tz_series2(self): + # gh-11887: concat tz and object + x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="UTC")) + y = Series(["a", "b"]) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + def test_concat_tz_series3(self, unit, unit2): + # see gh-12217 and gh-12306 + # Concatenating two UTC times + first = DataFrame([[datetime(2016, 1, 1)]], dtype=f"M8[{unit}]") + first[0] = first[0].dt.tz_localize("UTC") + + second = DataFrame([[datetime(2016, 1, 2)]], dtype=f"M8[{unit2}]") + second[0] = second[0].dt.tz_localize("UTC") + + result = concat([first, second]) + exp_unit = tm.get_finest_unit(unit, unit2) + assert result[0].dtype == f"datetime64[{exp_unit}, UTC]" + + def test_concat_tz_series4(self, unit, unit2): + # Concatenating two London times + first = DataFrame([[datetime(2016, 1, 1)]], dtype=f"M8[{unit}]") + first[0] = first[0].dt.tz_localize("Europe/London") + + second = DataFrame([[datetime(2016, 1, 2)]], dtype=f"M8[{unit2}]") + second[0] = second[0].dt.tz_localize("Europe/London") + + result = concat([first, second]) + exp_unit = tm.get_finest_unit(unit, unit2) + assert result[0].dtype == f"datetime64[{exp_unit}, Europe/London]" + + def test_concat_tz_series5(self, unit, unit2): + # Concatenating 2+1 London times + first = DataFrame( + [[datetime(2016, 1, 1)], [datetime(2016, 1, 2)]], dtype=f"M8[{unit}]" + ) + first[0] = first[0].dt.tz_localize("Europe/London") + + second = DataFrame([[datetime(2016, 1, 3)]], dtype=f"M8[{unit2}]") + second[0] = second[0].dt.tz_localize("Europe/London") + + result = concat([first, second]) + exp_unit = tm.get_finest_unit(unit, unit2) + assert result[0].dtype == f"datetime64[{exp_unit}, Europe/London]" + + def test_concat_tz_series6(self, unit, unit2): + # Concatenating 1+2 London times + first = DataFrame([[datetime(2016, 1, 1)]], dtype=f"M8[{unit}]") + first[0] = first[0].dt.tz_localize("Europe/London") + + second = DataFrame( + [[datetime(2016, 1, 2)], [datetime(2016, 1, 3)]], dtype=f"M8[{unit2}]" + ) + second[0] = second[0].dt.tz_localize("Europe/London") + + result = concat([first, second]) + exp_unit = tm.get_finest_unit(unit, unit2) + assert result[0].dtype == f"datetime64[{exp_unit}, Europe/London]" + + def test_concat_tz_series_tzlocal(self): + # see gh-13583 + x = [ + Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()), + Timestamp("2011-02-01", tz=dateutil.tz.tzlocal()), + ] + y = [ + Timestamp("2012-01-01", tz=dateutil.tz.tzlocal()), + Timestamp("2012-02-01", tz=dateutil.tz.tzlocal()), + ] + + result = concat([Series(x), Series(y)], ignore_index=True) + tm.assert_series_equal(result, Series(x + y)) + assert result.dtype == "datetime64[ns, tzlocal()]" + + def test_concat_tz_series_with_datetimelike(self): + # see gh-12620: tz and timedelta + x = [ + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-02-01", tz="US/Eastern"), + ] + y = [pd.Timedelta("1 day"), pd.Timedelta("2 day")] + result = concat([Series(x), Series(y)], ignore_index=True) + tm.assert_series_equal(result, Series(x + y, dtype="object")) + + # tz and period + y = [pd.Period("2011-03", freq="M"), pd.Period("2011-04", freq="M")] + result = concat([Series(x), Series(y)], ignore_index=True) + tm.assert_series_equal(result, Series(x + y, dtype="object")) + + def test_concat_tz_frame(self): + df2 = DataFrame( + { + "A": Timestamp("20130102", tz="US/Eastern"), + "B": Timestamp("20130603", tz="CET"), + }, + index=range(5), + ) + + # concat + df3 = concat([df2.A.to_frame(), df2.B.to_frame()], axis=1) + tm.assert_frame_equal(df2, df3) + + def test_concat_multiple_tzs(self): + # GH#12467 + # combining datetime tz-aware and naive DataFrames + ts1 = Timestamp("2015-01-01", tz=None) + ts2 = Timestamp("2015-01-01", tz="UTC") + ts3 = Timestamp("2015-01-01", tz="EST") + + df1 = DataFrame({"time": [ts1]}) + df2 = DataFrame({"time": [ts2]}) + df3 = DataFrame({"time": [ts3]}) + + results = concat([df1, df2]).reset_index(drop=True) + expected = DataFrame({"time": [ts1, ts2]}, dtype=object) + tm.assert_frame_equal(results, expected) + + results = concat([df1, df3]).reset_index(drop=True) + expected = DataFrame({"time": [ts1, ts3]}, dtype=object) + tm.assert_frame_equal(results, expected) + + results = concat([df2, df3]).reset_index(drop=True) + expected = DataFrame({"time": [ts2, ts3]}) + tm.assert_frame_equal(results, expected) + + def test_concat_multiindex_with_tz(self): + # GH 6606 + df = DataFrame( + { + "dt": DatetimeIndex( + [ + datetime(2014, 1, 1), + datetime(2014, 1, 2), + datetime(2014, 1, 3), + ], + dtype="M8[ns, US/Pacific]", + ), + "b": ["A", "B", "C"], + "c": [1, 2, 3], + "d": [4, 5, 6], + } + ) + df = df.set_index(["dt", "b"]) + + exp_idx1 = DatetimeIndex( + ["2014-01-01", "2014-01-02", "2014-01-03"] * 2, + dtype="M8[ns, US/Pacific]", + name="dt", + ) + exp_idx2 = Index(["A", "B", "C"] * 2, name="b") + exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) + expected = DataFrame( + {"c": [1, 2, 3] * 2, "d": [4, 5, 6] * 2}, index=exp_idx, columns=["c", "d"] + ) + + result = concat([df, df]) + tm.assert_frame_equal(result, expected) + + def test_concat_tz_not_aligned(self): + # GH#22796 + ts = pd.to_datetime([1, 2]).tz_localize("UTC") + a = DataFrame({"A": ts}) + b = DataFrame({"A": ts, "B": ts}) + result = concat([a, b], sort=True, ignore_index=True) + expected = DataFrame( + {"A": list(ts) + list(ts), "B": [pd.NaT, pd.NaT] + list(ts)} + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "t1", + [ + "2015-01-01", + pytest.param( + pd.NaT, + marks=pytest.mark.xfail( + reason="GH23037 incorrect dtype when concatenating" + ), + ), + ], + ) + def test_concat_tz_NaT(self, t1): + # GH#22796 + # Concatenating tz-aware multicolumn DataFrames + ts1 = Timestamp(t1, tz="UTC") + ts2 = Timestamp("2015-01-01", tz="UTC") + ts3 = Timestamp("2015-01-01", tz="UTC") + + df1 = DataFrame([[ts1, ts2]]) + df2 = DataFrame([[ts3]]) + + result = concat([df1, df2]) + expected = DataFrame([[ts1, ts2], [ts3, pd.NaT]], index=[0, 0]) + + tm.assert_frame_equal(result, expected) + + def test_concat_tz_with_empty(self): + # GH 9188 + result = concat( + [DataFrame(date_range("2000", periods=1, tz="UTC")), DataFrame()] + ) + expected = DataFrame(date_range("2000", periods=1, tz="UTC")) + tm.assert_frame_equal(result, expected) + + +class TestPeriodConcat: + def test_concat_period_series(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="D")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="Period[D]") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + def test_concat_period_multiple_freq_series(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="M")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + def test_concat_period_other_series(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="M")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + def test_concat_period_other_series2(self): + # non-period + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(DatetimeIndex(["2015-11-01", "2015-12-01"])) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + def test_concat_period_other_series3(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(["A", "B"]) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + +def test_concat_timedelta64_block(): + rng = to_timedelta(np.arange(10), unit="s") + + df = DataFrame({"time": rng}) + + result = concat([df, df]) + tm.assert_frame_equal(result.iloc[:10], df) + tm.assert_frame_equal(result.iloc[10:], df) + + +def test_concat_multiindex_datetime_nat(): + # GH#44900 + left = DataFrame({"a": 1}, index=MultiIndex.from_tuples([(1, pd.NaT)])) + right = DataFrame( + {"b": 2}, index=MultiIndex.from_tuples([(1, pd.NaT), (2, pd.NaT)]) + ) + result = concat([left, right], axis="columns") + expected = DataFrame( + {"a": [1.0, np.nan], "b": 2}, MultiIndex.from_tuples([(1, pd.NaT), (2, pd.NaT)]) + ) + tm.assert_frame_equal(result, expected) + + +def test_concat_float_datetime64(using_array_manager): + # GH#32934 + df_time = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")}) + df_float = DataFrame({"A": pd.array([1.0], dtype="float64")}) + + expected = DataFrame( + { + "A": [ + pd.array(["2000"], dtype="datetime64[ns]")[0], + pd.array([1.0], dtype="float64")[0], + ] + }, + index=[0, 0], + ) + result = concat([df_time, df_float]) + tm.assert_frame_equal(result, expected) + + expected = DataFrame({"A": pd.array([], dtype="object")}) + result = concat([df_time.iloc[:0], df_float.iloc[:0]]) + tm.assert_frame_equal(result, expected) + + expected = DataFrame({"A": pd.array([1.0], dtype="object")}) + result = concat([df_time.iloc[:0], df_float]) + tm.assert_frame_equal(result, expected) + + if not using_array_manager: + expected = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")}) + msg = "The behavior of DataFrame concatenation with empty or all-NA entries" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = concat([df_time, df_float.iloc[:0]]) + tm.assert_frame_equal(result, expected) + else: + expected = DataFrame({"A": pd.array(["2000"], dtype="datetime64[ns]")}).astype( + {"A": "object"} + ) + result = concat([df_time, df_float.iloc[:0]]) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/75/7598eb7dc59a500f811d4b6eb732ce58f94e48d2d8cc1a9215eba4111e8bfdb0/blob b/shared/package-files/75/7598eb7dc59a500f811d4b6eb732ce58f94e48d2d8cc1a9215eba4111e8bfdb0/blob new file mode 100644 index 0000000000000000000000000000000000000000..10bae5b2b7b476f96ba06f637c549ee4afff4c6d --- /dev/null +++ b/shared/package-files/75/7598eb7dc59a500f811d4b6eb732ce58f94e48d2d8cc1a9215eba4111e8bfdb0/blob @@ -0,0 +1,100 @@ +"""Implementation of :class:`GMPYRationalField` class. """ + + +from sympy.polys.domains.groundtypes import ( + GMPYRational, SymPyRational, + gmpy_numer, gmpy_denom, factorial as gmpy_factorial, +) +from sympy.polys.domains.rationalfield import RationalField +from sympy.polys.polyerrors import CoercionFailed +from sympy.utilities import public + +@public +class GMPYRationalField(RationalField): + """Rational field based on GMPY's ``mpq`` type. + + This will be the implementation of :ref:`QQ` if ``gmpy`` or ``gmpy2`` is + installed. Elements will be of type ``gmpy.mpq``. + """ + + dtype = GMPYRational + zero = dtype(0) + one = dtype(1) + tp = type(one) + alias = 'QQ_gmpy' + + def __init__(self): + pass + + def get_ring(self): + """Returns ring associated with ``self``. """ + from sympy.polys.domains import GMPYIntegerRing + return GMPYIntegerRing() + + def to_sympy(self, a): + """Convert ``a`` to a SymPy object. """ + return SymPyRational(int(gmpy_numer(a)), + int(gmpy_denom(a))) + + def from_sympy(self, a): + """Convert SymPy's Integer to ``dtype``. """ + if a.is_Rational: + return GMPYRational(a.p, a.q) + elif a.is_Float: + from sympy.polys.domains import RR + return GMPYRational(*map(int, RR.to_rational(a))) + else: + raise CoercionFailed("expected ``Rational`` object, got %s" % a) + + def from_ZZ_python(K1, a, K0): + """Convert a Python ``int`` object to ``dtype``. """ + return GMPYRational(a) + + def from_QQ_python(K1, a, K0): + """Convert a Python ``Fraction`` object to ``dtype``. """ + return GMPYRational(a.numerator, a.denominator) + + def from_ZZ_gmpy(K1, a, K0): + """Convert a GMPY ``mpz`` object to ``dtype``. """ + return GMPYRational(a) + + def from_QQ_gmpy(K1, a, K0): + """Convert a GMPY ``mpq`` object to ``dtype``. """ + return a + + def from_GaussianRationalField(K1, a, K0): + """Convert a ``GaussianElement`` object to ``dtype``. """ + if a.y == 0: + return GMPYRational(a.x) + + def from_RealField(K1, a, K0): + """Convert a mpmath ``mpf`` object to ``dtype``. """ + return GMPYRational(*map(int, K0.to_rational(a))) + + def exquo(self, a, b): + """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return GMPYRational(a) / GMPYRational(b) + + def quo(self, a, b): + """Quotient of ``a`` and ``b``, implies ``__truediv__``. """ + return GMPYRational(a) / GMPYRational(b) + + def rem(self, a, b): + """Remainder of ``a`` and ``b``, implies nothing. """ + return self.zero + + def div(self, a, b): + """Division of ``a`` and ``b``, implies ``__truediv__``. """ + return GMPYRational(a) / GMPYRational(b), self.zero + + def numer(self, a): + """Returns numerator of ``a``. """ + return a.numerator + + def denom(self, a): + """Returns denominator of ``a``. """ + return a.denominator + + def factorial(self, a): + """Returns factorial of ``a``. """ + return GMPYRational(gmpy_factorial(int(a))) diff --git a/shared/package-files/75/7599113abfe4c7930b55d88ff674da1e221d417f7fab7df4fbb497ae0577a639/blob b/shared/package-files/75/7599113abfe4c7930b55d88ff674da1e221d417f7fab7df4fbb497ae0577a639/blob new file mode 100644 index 0000000000000000000000000000000000000000..e93200ba385faf037be75654061932ee6e886b7b --- /dev/null +++ b/shared/package-files/75/7599113abfe4c7930b55d88ff674da1e221d417f7fab7df4fbb497ae0577a639/blob @@ -0,0 +1,226 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Real + +from ..utils._param_validation import Interval, StrOptions +from ._stochastic_gradient import BaseSGDClassifier + + +class Perceptron(BaseSGDClassifier): + """Linear perceptron classifier. + + The implementation is a wrapper around :class:`~sklearn.linear_model.SGDClassifier` + by fixing the `loss` and `learning_rate` parameters as:: + + SGDClassifier(loss="perceptron", learning_rate="constant") + + Other available parameters are described below and are forwarded to + :class:`~sklearn.linear_model.SGDClassifier`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + penalty : {'l2','l1','elasticnet'}, default=None + The penalty (aka regularization term) to be used. + + alpha : float, default=0.0001 + Constant that multiplies the regularization term if regularization is + used. + + l1_ratio : float, default=0.15 + The Elastic Net mixing parameter, with `0 <= l1_ratio <= 1`. + `l1_ratio=0` corresponds to L2 penalty, `l1_ratio=1` to L1. + Only used if `penalty='elasticnet'`. + + .. versionadded:: 0.24 + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`partial_fit` method. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). + + .. versionadded:: 0.19 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + + eta0 : float, default=1 + Constant by which the updates are multiplied. + + n_jobs : int, default=None + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance or None, default=0 + Used to shuffle the training data, when ``shuffle`` is set to + ``True``. Pass an int for reproducible output across multiple + function calls. + See :term:`Glossary `. + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to True, it will automatically set aside + a stratified fraction of training data as validation and terminate + training when validation score is not improving by at least `tol` for + `n_iter_no_change` consecutive epochs. + + .. versionadded:: 0.20 + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before early stopping. + + .. versionadded:: 0.20 + + class_weight : dict, {class_label: weight} or "balanced", default=None + Preset for the class_weight fit parameter. + + Weights associated with classes. If not given, all classes + are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + warm_start : bool, default=False + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. See + :term:`the Glossary `. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + The unique classes labels. + + coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \ + (n_classes, n_features) + Weights assigned to the features. + + intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,) + Constants in decision function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + For multiclass fits, it is the maximum over every binary fit. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + See Also + -------- + sklearn.linear_model.SGDClassifier : Linear classifiers + (SVM, logistic regression, etc.) with SGD training. + + Notes + ----- + ``Perceptron`` is a classification algorithm which shares the same + underlying implementation with ``SGDClassifier``. In fact, + ``Perceptron()`` is equivalent to `SGDClassifier(loss="perceptron", + eta0=1, learning_rate="constant", penalty=None)`. + + References + ---------- + https://en.wikipedia.org/wiki/Perceptron and references therein. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.linear_model import Perceptron + >>> X, y = load_digits(return_X_y=True) + >>> clf = Perceptron(tol=1e-3, random_state=0) + >>> clf.fit(X, y) + Perceptron() + >>> clf.score(X, y) + 0.939... + """ + + _parameter_constraints: dict = {**BaseSGDClassifier._parameter_constraints} + _parameter_constraints.pop("loss") + _parameter_constraints.pop("average") + _parameter_constraints.update( + { + "penalty": [StrOptions({"l2", "l1", "elasticnet"}), None], + "alpha": [Interval(Real, 0, None, closed="left")], + "l1_ratio": [Interval(Real, 0, 1, closed="both")], + "eta0": [Interval(Real, 0, None, closed="left")], + } + ) + + def __init__( + self, + *, + penalty=None, + alpha=0.0001, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + eta0=1.0, + n_jobs=None, + random_state=0, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + class_weight=None, + warm_start=False, + ): + super().__init__( + loss="perceptron", + penalty=penalty, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + learning_rate="constant", + eta0=eta0, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + power_t=0.5, + warm_start=warm_start, + class_weight=class_weight, + n_jobs=n_jobs, + ) diff --git a/shared/package-files/75/759a552a2ef7efc110201509d3693a34f7055169e41fa28891aeb663336ede38/blob b/shared/package-files/75/759a552a2ef7efc110201509d3693a34f7055169e41fa28891aeb663336ede38/blob new file mode 100644 index 0000000000000000000000000000000000000000..bad5d9dd3c2db751a05864a094362dad9d26269f --- /dev/null +++ b/shared/package-files/75/759a552a2ef7efc110201509d3693a34f7055169e41fa28891aeb663336ede38/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:759a552a2ef7efc110201509d3693a34f7055169e41fa28891aeb663336ede38 +size 349128 diff --git a/shared/package-files/75/759bba151956b82248b0aed8358df43e7f9760d30bc439372409e1e1d861e4b8/blob b/shared/package-files/75/759bba151956b82248b0aed8358df43e7f9760d30bc439372409e1e1d861e4b8/blob new file mode 100644 index 0000000000000000000000000000000000000000..13025af0120ebc51dc4dac85eb37aa93ae67bd18 Binary files /dev/null and b/shared/package-files/75/759bba151956b82248b0aed8358df43e7f9760d30bc439372409e1e1d861e4b8/blob differ diff --git a/shared/package-files/75/759d6f0d9d14db0ea00c87b07926d4e19ea43e1ca35c8f466058f2bad08a1943/blob b/shared/package-files/75/759d6f0d9d14db0ea00c87b07926d4e19ea43e1ca35c8f466058f2bad08a1943/blob new file mode 100644 index 0000000000000000000000000000000000000000..a73ec00a47273fdbf131d29f0387e84d3b2415cc --- /dev/null +++ b/shared/package-files/75/759d6f0d9d14db0ea00c87b07926d4e19ea43e1ca35c8f466058f2bad08a1943/blob @@ -0,0 +1,224 @@ +dates, cpi, predict, stderr, conf1, conf2 +1950:1, 28.980,,,, +1950:2, 29.150, 29.848,, +1950:3, 29.350, 29.751,, +1950:4, 29.370, 29.925,, +1951:1, 29.540, 29.788,, +1951:2, 29.550, 30.005,, +1951:3, 29.750, 29.872,, +1951:4, 29.840, 30.181,, +1952:1, 29.810, 30.125,, +1952:2, 29.920, 30.154,, +1952:3, 29.980, 30.203,, +1952:4, 30.040, 30.290,, +1953:1, 30.210, 30.306,, +1953:2, 30.220, 30.535,, +1953:3, 30.380, 30.450,, +1953:4, 30.440, 30.721,, +1954:1, 30.480, 30.657,, +1954:2, 30.690, 30.793,, +1954:3, 30.750, 30.955,, +1954:4, 30.940, 31.034,, +1955:1, 30.950, 31.237,, +1955:2, 31.020, 31.194,, +1955:3, 31.120, 31.310,, +1955:4, 31.280, 31.371,, +1956:1, 31.380, 31.588,, +1956:2, 31.580, 31.629,, +1956:3, 31.650, 31.915,, +1956:4, 31.880, 31.882,, +1957:1, 32.280, 32.248,, +1957:2, 32.450, 32.601,, +1957:3, 32.850, 32.794,, +1957:4, 32.900, 33.245,, +1958:1, 33.100, 33.179,, +1958:2, 33.400, 33.502,, +1958:3, 33.700, 33.723,, +1958:4, 34.100, 34.119,, +1959:1, 34.400, 34.481,, +1959:2, 34.900, 34.819,, +1959:3, 35.300, 35.358,, +1959:4, 35.700, 35.737,, +1960:1, 36.300, 36.176,, +1960:2, 36.800, 36.821,, +1960:3, 37.300, 37.301,, +1960:4, 37.900, 37.844,, +1961:1, 38.500, 38.456,, +1961:2, 38.900, 39.082,, +1961:3, 39.400, 39.423,, +1961:4, 39.900, 39.995,, +1962:1, 40.100, 40.436,, +1962:2, 40.600, 40.599,, +1962:3, 40.900, 41.175,, +1962:4, 41.200, 41.354,, +1963:1, 41.500, 41.738,, +1963:2, 41.800, 41.936,, +1963:3, 42.200, 42.311,, +1963:4, 42.700, 42.658,, +1964:1, 43.700, 43.247,, +1964:2, 44.200, 44.354,, +1964:3, 45.600, 44.715,, +1964:4, 46.800, 46.538,, +1965:1, 48.100, 47.464,, +1965:2, 49.300, 49.162,, +1965:3, 51.000, 50.071,, +1965:4, 52.300, 52.276,, +1966:1, 53.000, 53.138,, +1966:2, 54.000, 54.101,, +1966:3, 54.900, 54.875,, +1966:4, 55.800, 55.948,, +1967:1, 56.100, 56.663,, +1967:2, 57.000, 56.919,, +1967:3, 57.900, 57.917,, +1967:4, 58.700, 58.733,, +1968:1, 60.000, 59.585,, +1968:2, 60.800, 60.985,, +1968:3, 61.600, 61.618,, +1968:4, 62.700, 62.545,, +1969:1, 63.900, 63.602,, +1969:2, 65.500, 64.917,, +1969:3, 67.100, 66.596,, +1969:4, 68.500, 68.249,, +1970:1, 70.600, 69.639,, +1970:2, 73.000, 72.023,, +1970:3, 75.200, 74.438,, +1970:4, 78.000, 76.768,, +1971:1, 80.900, 79.775,, +1971:2, 82.600, 82.748,, +1971:3, 84.700, 84.201,, +1971:4, 87.200, 86.591,, +1972:1, 89.100, 88.976,, +1972:2, 91.500, 90.888,, +1972:3, 93.400, 93.401,, +1972:4, 94.400, 95.103,, +1973:1, 95.000, 95.950,, +1973:2, 97.500, 96.342,, +1973:3, 98.100, 99.392,, +1973:4, 97.900, 99.031,, +1974:1, 98.800, 99.216,, +1974:2, 99.800, 99.751,, +1974:3, 100.800, 101.044,, +1974:4, 102.100, 101.727 ,, +1975:1, 103.300, 103.382 ,, +1975:2, 104.100, 104.251 ,, +1975:3, 105.100, 105.233 ,, +1975:4, 105.700, 106.052 ,, +1976:1, 107.000, 106.667 ,, +1976:2, 107.700, 108.081 ,, +1976:3, 108.500, 108.538 ,, +1976:4, 109.900, 109.523 ,, +1977:1, 108.700, 110.907 ,, +1977:2, 109.500, 108.963 ,, +1977:3, 110.200, 110.651 ,, +1977:4, 111.400, 110.524 ,, +1978:1, 112.700, 112.660 ,, +1978:2, 113.800, 113.230 ,, +1978:3, 115.000, 115.051 ,, +1978:4, 116.000, 115.662 ,, +1979:1, 117.200, 117.204 ,, +1979:2, 118.500, 117.975 ,, +1979:3, 119.900, 119.754 ,, +1979:4, 121.200, 120.802 ,, +1980:1, 123.100, 122.467 ,, +1980:2, 124.500, 124.261 ,, +1980:3, 125.400, 125.749 ,, +1980:4, 127.500, 126.429 ,, +1981:1, 128.900, 129.043 ,, +1981:2, 130.500, 129.915 ,, +1981:3, 133.400, 132.075 ,, +1981:4, 134.700, 134.922 ,, +1982:1, 135.100, 136.050 ,, +1982:2, 136.200, 136.239 ,, +1982:3, 137.200, 137.516 ,, +1982:4, 138.300, 138.258 ,, +1983:1, 139.400, 139.559 ,, +1983:2, 140.500, 140.434 ,, +1983:3, 141.700, 141.711 ,, +1983:4, 142.800, 142.753 ,, +1984:1, 143.800, 143.966 ,, +1984:2, 144.500, 144.807 ,, +1984:3, 145.600, 145.519 ,, +1984:4, 146.300, 146.646 ,, +1985:1, 147.200, 147.195 ,, +1985:2, 148.400, 148.223 ,, +1985:3, 149.400, 149.379 ,, +1985:4, 150.500, 150.396 ,, +1986:1, 151.800, 151.507 ,, +1986:2, 152.600, 152.878 ,, +1986:3, 153.500, 153.502 ,, +1986:4, 154.700, 154.540 ,, +1987:1, 156.100, 155.683 ,, +1987:2, 157.000, 157.240 ,, +1987:3, 158.200, 157.903 ,, +1987:4, 159.400, 159.379 ,, +1988:1, 159.900, 160.350 ,, +1988:2, 160.400, 160.856 ,, +1988:3, 161.500, 161.226 ,, +1988:4, 162.000, 162.540 ,, +1989:1, 162.200, 162.682 ,, +1989:2, 163.200, 163.025 ,, +1989:3, 163.900, 164.017 ,, +1989:4, 164.700, 164.677 ,, +1990:1, 165.900, 165.527 ,, +1990:2, 166.700, 166.815 ,, +1990:3, 168.100, 167.488 ,, +1990:4, 169.300, 169.190 ,, +1991:1, 170.900, 170.157 ,, +1991:2, 172.700, 172.157 ,, +1991:3, 173.900, 173.775 ,, +1991:4, 175.600, 175.092 ,, +1992:1, 176.400, 176.843 ,, +1992:2, 177.400, 177.401 ,, +1992:3, 177.600, 178.590 ,, +1992:4, 177.700, 178.310 ,, +1993:1, 179.300, 178.624 ,, +1993:2, 180.000, 180.330 ,, +1993:3, 181.200, 180.791 ,, +1993:4, 182.600, 182.320 ,, +1994:1, 183.200, 183.535 ,, +1994:2, 183.700, 184.132 ,, +1994:3, 184.900, 184.510 ,, +1994:4, 186.300, 185.955 ,, +1995:1, 187.400, 187.256 ,, +1995:2, 189.100, 188.443 ,, +1995:3, 190.800, 190.274 ,, +1995:4, 191.800, 191.988 ,, +1996:1, 193.800, 192.858 ,, +1996:2, 194.700, 195.254 ,, +1996:3, 199.200, 195.589 ,, +1996:4, 199.400, 201.698 ,, +1997:1, 200.700, 199.660 ,, +1997:2, 202.700, 203.065 ,, +1997:3, 201.900, 203.288 ,, +1997:4, 203.574, 203.327 ,, +1998:1, 205.920, 204.543 ,, +1998:2, 207.338, 207.635 ,, +1998:3, 209.133, 208.278 ,, +1998:4, 212.495, 210.909 ,, +1999:1, 213.997, 214.077 ,, +1999:2, 218.610, 215.531 ,, +1999:3, 216.889, 221.137 ,, +1999:4, 212.174, 217.006 ,, +2000:1, 212.671, 212.741 ,, +2000:2, 214.469, 213.240 ,, +2000:3, 216.385, 215.464,,, +2000:4,, 217.291, 0.7691, 215.784, 218.799 +2001:1,, 218.197, 1.2775, 215.693, 220.701 +2001:2,, 219.100, 1.6382, 215.889, 222.311 +2001:3,, 220.002, 2.0322, 216.019, 223.985 +2001:4,, 220.902, 2.3838, 216.230, 225.574 +2002:1,, 221.801, 2.7544, 216.403, 227.200 +2002:2,, 222.699, 3.1082, 216.607, 228.791 +2002:3,, 223.595, 3.4721, 216.790, 230.400 +2002:4,, 224.490, 3.8288, 216.986, 231.994 +2003:1,, 225.384, 4.1908, 217.170, 233.598 +2003:2,, 226.276, 4.5494, 217.360, 235.193 +2003:3,, 227.168, 4.9105, 217.544, 236.793 +2003:4,, 228.059, 5.2698, 217.730, 238.387 +2004:1,, 228.948, 5.6300, 217.914, 239.983 +2004:2,, 229.837, 5.9888, 218.099, 241.574 +2004:3,, 230.724, 6.3475, 218.283, 243.165 +2004:4,, 231.611, 6.7049, 218.470, 244.752 +2005:1,, 232.497, 7.0614, 218.657, 246.337 +2005:2,, 233.382, 7.4165, 218.846, 247.918 +2005:3,, 234.266, 7.7704, 219.037, 249.496 diff --git a/shared/package-files/75/759d77d3a4bc6be4a310327fde118a554c039803cefeb51709db92cbf1722c7b/blob b/shared/package-files/75/759d77d3a4bc6be4a310327fde118a554c039803cefeb51709db92cbf1722c7b/blob new file mode 100644 index 0000000000000000000000000000000000000000..7285a93894418f41d21ab0c8d67a16d157a46ec4 --- /dev/null +++ b/shared/package-files/75/759d77d3a4bc6be4a310327fde118a554c039803cefeb51709db92cbf1722c7b/blob @@ -0,0 +1,44 @@ +This directory contains a collection of programs to demonstrate +the features of the Tk toolkit. The programs are all scripts for +"wish", a windowing shell. If wish has been installed on your path +then you can invoke any of the programs in this directory just +by typing its file name to your command shell under Unix. Otherwise +invoke wish with the file as its first argument, e.g., "wish hello". +The rest of this file contains a brief description of each program. +Files with names ending in ".tcl" are procedure packages used by one +or more of the demo programs; they can't be used as programs by +themselves so they aren't described below. + +hello - Creates a single button; if you click on it, a message + is typed and the application terminates. + +widget - Contains a collection of demonstrations of the widgets + currently available in the Tk library. Most of the .tcl + files are scripts for individual demos available through + the "widget" program. + +ixset - A simple Tk-based wrapper for the "xset" program, which + allows you to interactively query and set various X options + such as mouse acceleration and bell volume. Thanks to + Pierre David for contributing this example. + +rolodex - A mock-up of a simple rolodex application. It has much of + the user interface for such an application but no back-end + database. This program was written in response to Tom + LaStrange's toolkit benchmark challenge. + +tcolor - A color editor. Allows you to edit colors in several + different ways, and will also perform automatic updates + using "send". + +rmt - Allows you to "hook-up" remotely to any Tk application + on the display. Select an application with the menu, + then just type commands: they'll go to that application. + +timer - Displays a seconds timer with start and stop buttons. + Control-c and control-q cause it to exit. + +browse - A simple directory browser. Invoke it with and argument + giving the name of the directory you'd like to browse. + Double-click on files or subdirectories to browse them. + Control-c and control-q cause the program to exit. diff --git a/shared/package-files/75/759db65021b8801d4bec54d088b9fc031540cdb0042150cb6fa2f96446b29ab9/blob b/shared/package-files/75/759db65021b8801d4bec54d088b9fc031540cdb0042150cb6fa2f96446b29ab9/blob new file mode 100644 index 0000000000000000000000000000000000000000..98e1cb04c2e201fecdf1d911af1968c596d519c4 Binary files /dev/null and b/shared/package-files/75/759db65021b8801d4bec54d088b9fc031540cdb0042150cb6fa2f96446b29ab9/blob differ diff --git a/shared/package-files/75/759f16f9f927d00dc8e3509b42ef759af49c814ed22efc5f6230d7dbd1322231/blob b/shared/package-files/75/759f16f9f927d00dc8e3509b42ef759af49c814ed22efc5f6230d7dbd1322231/blob new file mode 100644 index 0000000000000000000000000000000000000000..b680d819e72e48e983405c3bf969d13544eb73a7 --- /dev/null +++ b/shared/package-files/75/759f16f9f927d00dc8e3509b42ef759af49c814ed22efc5f6230d7dbd1322231/blob @@ -0,0 +1,289 @@ +import array + +import numpy as np + +from numba import jit +from numba.tests.support import TestCase, compile_function, MemoryLeakMixin +import unittest + + +@jit(nopython=True) +def len_usecase(buf): + return len(buf) + + +@jit(nopython=True) +def getitem_usecase(buf, i): + return buf[i] + + +@jit(nopython=True) +def getslice_usecase(buf, i, j): + s = buf[i:j] + return s[0] + 2 * s[-1] + + +@jit(nopython=True) +def setitem_usecase(buf, i, v): + buf[i] = v + + +@jit(nopython=True) +def iter_usecase(buf): + res = 0.0 + for i, x in enumerate(buf): + res += x + res *= i + 1 + return res + + +def attrgetter(attr): + code = """def func(x): + return x.%(attr)s +""" % locals() + pyfunc = compile_function("func", code, globals()) + return jit(nopython=True)(pyfunc) + + +contiguous_usecase = attrgetter("contiguous") +c_contiguous_usecase = attrgetter("c_contiguous") +f_contiguous_usecase = attrgetter("f_contiguous") +itemsize_usecase = attrgetter("itemsize") +nbytes_usecase = attrgetter("nbytes") +ndim_usecase = attrgetter("ndim") +readonly_usecase = attrgetter("readonly") +shape_usecase = attrgetter("shape") +strides_usecase = attrgetter("strides") + + +class TestBufferProtocol(MemoryLeakMixin, TestCase): + """ + Test operations on buffer-providing objects. + """ + + def _arrays(self): + n = 10 + for letter, offset in [ + ('b', -3), + ('B', 0), + ('h', -5000), + ('H', 40000), + ('i', -100000), + ('I', 1000000), + ('l', -100000), + ('L', 1000000), + ('q', -2**60), + ('Q', 2**63 + 1), + ('f', 1.5), + ('d', -1.5), + ]: + yield array.array(letter, [i + offset for i in range(n)]) + + def _memoryviews(self): + n = 10 + yield memoryview(bytearray(b"abcdefghi")) + yield memoryview(b"abcdefghi") + # Different item types + for dtype, start, stop in [ + ('int8', -10, 10), + ('uint8', 0, 10), + ('int16', -5000, 1000), + ('uint16', 40000, 50000), + ('int32', -100000, 100000), + ('uint32', 0, 1000000), + ('int64', -2**60, 10), + ('uint64', 0, 2**64 - 10), + ('float32', 1.5, 3.5), + ('float64', 1.5, 3.5), + ('complex64', -8j, 12 + 5j), + ('complex128', -8j, 12 + 5j), + ]: + yield memoryview(np.linspace(start, stop, n).astype(dtype)) + # Different layouts + arr = np.arange(12).reshape((3, 4)) + assert arr.flags.c_contiguous and not arr.flags.f_contiguous + yield memoryview(arr) + arr = arr.T + assert arr.flags.f_contiguous and not arr.flags.c_contiguous + yield memoryview(arr) + arr = arr[::2] + assert not arr.flags.f_contiguous and not arr.flags.c_contiguous + yield memoryview(arr) + + def _readonlies(self): + yield b"xyz" + yield memoryview(b"abcdefghi") + arr = np.arange(5) + arr.setflags(write=False) + yield memoryview(arr) + + def _check_unary(self, jitfunc, *args): + pyfunc = jitfunc.py_func + self.assertPreciseEqual(jitfunc(*args), pyfunc(*args)) + + def check_len(self, obj): + self._check_unary(len_usecase, obj) + + def check_iter(self, obj): + self._check_unary(iter_usecase, obj) + + def check_getitem(self, obj): + # Be careful to index all dimensions, since we don't support + # partial indexing yet. + def yield_indices(obj): + try: + shape = obj.shape + except AttributeError: + shape = len(obj), + for tup in np.ndindex(shape): + # Simple 1d buffer-providing objects usually don't support + # tuple indexing. + if len(tup) == 1: + yield tup[0] + else: + yield tup + + for i in yield_indices(obj): + try: + expected = obj[i] + except (NotImplementedError, TypeError): + if isinstance(obj, memoryview): + # The memoryview object doesn't support all codes yet, + # fall back on the underlying object. + expected = obj.obj[i] + else: + raise + self.assertPreciseEqual(getitem_usecase(obj, i), expected) + + def check_setitem(self, obj): + for i in range(len(obj)): + orig = list(obj) + val = obj[i] // 2 + 1 + setitem_usecase(obj, i, val) + self.assertEqual(obj[i], val) + for j, val in enumerate(orig): + if j != i: + self.assertEqual(obj[j], val) + + def check_getslice(self, obj): + self._check_unary(getslice_usecase, obj, 1, len(obj) - 1) + + def test_len(self): + self.check_len(bytearray(5)) + self.check_len(b"xyz") + for mem in self._memoryviews(): + self.check_len(mem) + for arr in self._arrays(): + self.check_len(arr) + for buf in self._readonlies(): + self.check_getitem(buf) + + def test_getitem(self): + self.check_getitem(bytearray(b"abc")) + self.check_getitem(b"xyz") + for mem in self._memoryviews(): + self.check_getitem(mem) + for arr in self._arrays(): + self.check_getitem(arr) + for buf in self._readonlies(): + self.check_getitem(buf) + + def test_getslice(self): + with self.assertTypingError(): + self.check_getslice(bytearray(b"abcde")) + self.check_getslice(b"xyzuvw") + self.check_getslice(memoryview(b"xyzuvw")) + with self.assertTypingError(): + self.check_getslice(array.array('i', range(10))) + for buf in self._readonlies(): + self.check_getitem(buf) + + def test_setitem(self): + self.check_setitem(bytearray(b"abcdefghi")) + for arr in self._arrays(): + self.check_setitem(arr) + for mem in self._memoryviews(): + self.check_getitem(mem) + # Read-only buffers + for buf in self._readonlies(): + with self.assertTypingError(): + self.check_setitem(buf) + + def test_iter(self): + self.check_iter(bytearray(b"abc")) + self.check_iter(b"xyz") + self.check_iter(memoryview(b"xyz")) + for arr in self._arrays(): + self.check_iter(arr) + for buf in self._readonlies(): + self.check_getitem(buf) + + +class TestMemoryView(MemoryLeakMixin, TestCase): + """ + Test memoryview-specific attributes and operations. + """ + + def _arrays(self): + arr = np.arange(12) + yield arr + arr = arr.reshape((3, 4)) + yield arr + yield arr.T + yield arr[::2] + arr.setflags(write=False) + yield arr + arr = np.zeros(()) + assert arr.ndim == 0 + yield arr + + def test_ndim(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(ndim_usecase(m), arr.ndim) + + def test_shape(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(shape_usecase(m), arr.shape) + + def test_strides(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(strides_usecase(m), arr.strides) + + def test_itemsize(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(itemsize_usecase(m), arr.itemsize) + + def test_nbytes(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(nbytes_usecase(m), arr.size * arr.itemsize) + + def test_readonly(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertIs(readonly_usecase(m), not arr.flags.writeable) + m = memoryview(b"xyz") + self.assertIs(readonly_usecase(m), True) + m = memoryview(bytearray(b"xyz")) + self.assertIs(readonly_usecase(m), False) + + def test_contiguous(self): + m = memoryview(bytearray(b"xyz")) + self.assertIs(contiguous_usecase(m), True) + self.assertIs(c_contiguous_usecase(m), True) + self.assertIs(f_contiguous_usecase(m), True) + for arr in self._arrays(): + m = memoryview(arr) + # Note `arr.flags.contiguous` is wrong (it mimics c_contiguous) + self.assertIs(contiguous_usecase(m), + arr.flags.f_contiguous or arr.flags.c_contiguous) + self.assertIs(c_contiguous_usecase(m), arr.flags.c_contiguous) + self.assertIs(f_contiguous_usecase(m), arr.flags.f_contiguous) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/75/759fdf5a20c9762cfd0c56b7646047d6ee7e7258de5eb398e43622c71c39acfe/blob b/shared/package-files/75/759fdf5a20c9762cfd0c56b7646047d6ee7e7258de5eb398e43622c71c39acfe/blob new file mode 100644 index 0000000000000000000000000000000000000000..1ba4dcea369748622d366df0477e3b7911873593 --- /dev/null +++ b/shared/package-files/75/759fdf5a20c9762cfd0c56b7646047d6ee7e7258de5eb398e43622c71c39acfe/blob @@ -0,0 +1,618 @@ +import numpy as np +import pytest + +from sklearn import config_context +from sklearn.base import clone +from sklearn.datasets import ( + load_breast_cancer, + load_iris, + make_classification, + make_multilabel_classification, +) +from sklearn.dummy import DummyClassifier +from sklearn.ensemble import GradientBoostingClassifier +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import ( + balanced_accuracy_score, + f1_score, + fbeta_score, + make_scorer, +) +from sklearn.metrics._scorer import _CurveScorer +from sklearn.model_selection import ( + FixedThresholdClassifier, + StratifiedShuffleSplit, + TunedThresholdClassifierCV, +) +from sklearn.model_selection._classification_threshold import ( + _fit_and_score_over_thresholds, +) +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils._mocking import CheckingClassifier +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_array_equal, +) + + +def test_fit_and_score_over_thresholds_curve_scorers(): + """Check that `_fit_and_score_over_thresholds` returns thresholds in ascending order + for the different accepted curve scorers.""" + X, y = make_classification(n_samples=100, random_state=0) + train_idx, val_idx = np.arange(50), np.arange(50, 100) + classifier = LogisticRegression() + + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + scores, thresholds = _fit_and_score_over_thresholds( + classifier, + X, + y, + fit_params={}, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + + assert np.all(thresholds[:-1] <= thresholds[1:]) + assert isinstance(scores, np.ndarray) + assert np.logical_and(scores >= 0, scores <= 1).all() + + +def test_fit_and_score_over_thresholds_prefit(): + """Check the behaviour with a prefit classifier.""" + X, y = make_classification(n_samples=100, random_state=0) + + # `train_idx is None` to indicate that the classifier is prefit + train_idx, val_idx = None, np.arange(50, 100) + classifier = DecisionTreeClassifier(random_state=0).fit(X, y) + # make sure that the classifier memorized the full dataset such that + # we get perfect predictions and thus match the expected score + assert classifier.score(X[val_idx], y[val_idx]) == pytest.approx(1.0) + + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=2, + kwargs={}, + ) + scores, thresholds = _fit_and_score_over_thresholds( + classifier, + X, + y, + fit_params={}, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + assert np.all(thresholds[:-1] <= thresholds[1:]) + assert_allclose(scores, [0.5, 1.0]) + + +@config_context(enable_metadata_routing=True) +def test_fit_and_score_over_thresholds_sample_weight(): + """Check that we dispatch the sample-weight to fit and score the classifier.""" + X, y = load_iris(return_X_y=True) + X, y = X[:100], y[:100] # only 2 classes + + # create a dataset and repeat twice the sample of class #0 + X_repeated, y_repeated = np.vstack([X, X[y == 0]]), np.hstack([y, y[y == 0]]) + # create a sample weight vector that is equivalent to the repeated dataset + sample_weight = np.ones_like(y) + sample_weight[:50] *= 2 + + classifier = LogisticRegression() + train_repeated_idx = np.arange(X_repeated.shape[0]) + val_repeated_idx = np.arange(X_repeated.shape[0]) + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + scores_repeated, thresholds_repeated = _fit_and_score_over_thresholds( + classifier, + X_repeated, + y_repeated, + fit_params={}, + train_idx=train_repeated_idx, + val_idx=val_repeated_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + + train_idx, val_idx = np.arange(X.shape[0]), np.arange(X.shape[0]) + scores, thresholds = _fit_and_score_over_thresholds( + classifier.set_fit_request(sample_weight=True), + X, + y, + fit_params={"sample_weight": sample_weight}, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer.set_score_request(sample_weight=True), + score_params={"sample_weight": sample_weight}, + ) + + assert_allclose(thresholds_repeated, thresholds) + assert_allclose(scores_repeated, scores) + + +@pytest.mark.parametrize("fit_params_type", ["list", "array"]) +@config_context(enable_metadata_routing=True) +def test_fit_and_score_over_thresholds_fit_params(fit_params_type): + """Check that we pass `fit_params` to the classifier when calling `fit`.""" + X, y = make_classification(n_samples=100, random_state=0) + fit_params = { + "a": _convert_container(y, fit_params_type), + "b": _convert_container(y, fit_params_type), + } + + classifier = CheckingClassifier(expected_fit_params=["a", "b"], random_state=0) + classifier.set_fit_request(a=True, b=True) + train_idx, val_idx = np.arange(50), np.arange(50, 100) + + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + _fit_and_score_over_thresholds( + classifier, + X, + y, + fit_params=fit_params, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + + +@pytest.mark.parametrize( + "data", + [ + make_classification(n_classes=3, n_clusters_per_class=1, random_state=0), + make_multilabel_classification(random_state=0), + ], +) +def test_tuned_threshold_classifier_no_binary(data): + """Check that we raise an informative error message for non-binary problem.""" + err_msg = "Only binary classification is supported." + with pytest.raises(ValueError, match=err_msg): + TunedThresholdClassifierCV(LogisticRegression()).fit(*data) + + +@pytest.mark.parametrize( + "params, err_type, err_msg", + [ + ( + {"cv": "prefit", "refit": True}, + ValueError, + "When cv='prefit', refit cannot be True.", + ), + ( + {"cv": 10, "refit": False}, + ValueError, + "When cv has several folds, refit cannot be False.", + ), + ( + {"cv": "prefit", "refit": False}, + NotFittedError, + "`estimator` must be fitted.", + ), + ], +) +def test_tuned_threshold_classifier_conflict_cv_refit(params, err_type, err_msg): + """Check that we raise an informative error message when `cv` and `refit` + cannot be used together. + """ + X, y = make_classification(n_samples=100, random_state=0) + with pytest.raises(err_type, match=err_msg): + TunedThresholdClassifierCV(LogisticRegression(), **params).fit(X, y) + + +@pytest.mark.parametrize( + "estimator", + [LogisticRegression(), SVC(), GradientBoostingClassifier(n_estimators=4)], +) +@pytest.mark.parametrize( + "response_method", ["predict_proba", "predict_log_proba", "decision_function"] +) +@pytest.mark.parametrize( + "ThresholdClassifier", [FixedThresholdClassifier, TunedThresholdClassifierCV] +) +def test_threshold_classifier_estimator_response_methods( + ThresholdClassifier, estimator, response_method +): + """Check that `TunedThresholdClassifierCV` exposes the same response methods as the + underlying estimator. + """ + X, y = make_classification(n_samples=100, random_state=0) + + model = ThresholdClassifier(estimator=estimator) + assert hasattr(model, response_method) == hasattr(estimator, response_method) + + model.fit(X, y) + assert hasattr(model, response_method) == hasattr(estimator, response_method) + + if hasattr(model, response_method): + y_pred_cutoff = getattr(model, response_method)(X) + y_pred_underlying_estimator = getattr(model.estimator_, response_method)(X) + + assert_allclose(y_pred_cutoff, y_pred_underlying_estimator) + + +@pytest.mark.parametrize( + "response_method", ["auto", "decision_function", "predict_proba"] +) +def test_tuned_threshold_classifier_without_constraint_value(response_method): + """Check that `TunedThresholdClassifierCV` is optimizing a given objective + metric.""" + X, y = load_breast_cancer(return_X_y=True) + # remove feature to degrade performances + X = X[:, :5] + + # make the problem completely imbalanced such that the balanced accuracy is low + indices_pos = np.flatnonzero(y == 1) + indices_pos = indices_pos[: indices_pos.size // 50] + indices_neg = np.flatnonzero(y == 0) + + X = np.vstack([X[indices_neg], X[indices_pos]]) + y = np.hstack([y[indices_neg], y[indices_pos]]) + + lr = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y) + thresholds = 100 + model = TunedThresholdClassifierCV( + estimator=lr, + scoring="balanced_accuracy", + response_method=response_method, + thresholds=thresholds, + store_cv_results=True, + ) + score_optimized = balanced_accuracy_score(y, model.fit(X, y).predict(X)) + score_baseline = balanced_accuracy_score(y, lr.predict(X)) + assert score_optimized > score_baseline + assert model.cv_results_["thresholds"].shape == (thresholds,) + assert model.cv_results_["scores"].shape == (thresholds,) + + +def test_tuned_threshold_classifier_metric_with_parameter(): + """Check that we can pass a metric with a parameter in addition check that + `f_beta` with `beta=1` is equivalent to `f1` and different from `f_beta` with + `beta=2`. + """ + X, y = load_breast_cancer(return_X_y=True) + lr = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y) + model_fbeta_1 = TunedThresholdClassifierCV( + estimator=lr, scoring=make_scorer(fbeta_score, beta=1) + ).fit(X, y) + model_fbeta_2 = TunedThresholdClassifierCV( + estimator=lr, scoring=make_scorer(fbeta_score, beta=2) + ).fit(X, y) + model_f1 = TunedThresholdClassifierCV( + estimator=lr, scoring=make_scorer(f1_score) + ).fit(X, y) + + assert model_fbeta_1.best_threshold_ == pytest.approx(model_f1.best_threshold_) + assert model_fbeta_1.best_threshold_ != pytest.approx(model_fbeta_2.best_threshold_) + + +@pytest.mark.parametrize( + "response_method", ["auto", "decision_function", "predict_proba"] +) +@pytest.mark.parametrize( + "metric", + [ + make_scorer(balanced_accuracy_score), + make_scorer(f1_score, pos_label="cancer"), + ], +) +def test_tuned_threshold_classifier_with_string_targets(response_method, metric): + """Check that targets represented by str are properly managed. + Also, check with several metrics to be sure that `pos_label` is properly + dispatched. + """ + X, y = load_breast_cancer(return_X_y=True) + # Encode numeric targets by meaningful strings. We purposely designed the class + # names such that the `pos_label` is the first alphabetically sorted class and thus + # encoded as 0. + classes = np.array(["cancer", "healthy"], dtype=object) + y = classes[y] + model = TunedThresholdClassifierCV( + estimator=make_pipeline(StandardScaler(), LogisticRegression()), + scoring=metric, + response_method=response_method, + thresholds=100, + ).fit(X, y) + assert_array_equal(model.classes_, np.sort(classes)) + y_pred = model.predict(X) + assert_array_equal(np.unique(y_pred), np.sort(classes)) + + +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@config_context(enable_metadata_routing=True) +def test_tuned_threshold_classifier_refit(with_sample_weight, global_random_seed): + """Check the behaviour of the `refit` parameter.""" + rng = np.random.RandomState(global_random_seed) + X, y = make_classification(n_samples=100, random_state=0) + if with_sample_weight: + sample_weight = rng.randn(X.shape[0]) + sample_weight = np.abs(sample_weight, out=sample_weight) + else: + sample_weight = None + + # check that `estimator_` if fitted on the full dataset when `refit=True` + estimator = LogisticRegression().set_fit_request(sample_weight=True) + model = TunedThresholdClassifierCV(estimator, refit=True).fit( + X, y, sample_weight=sample_weight + ) + + assert model.estimator_ is not estimator + estimator.fit(X, y, sample_weight=sample_weight) + assert_allclose(model.estimator_.coef_, estimator.coef_) + assert_allclose(model.estimator_.intercept_, estimator.intercept_) + + # check that `estimator_` was not altered when `refit=False` and `cv="prefit"` + estimator = LogisticRegression().set_fit_request(sample_weight=True) + estimator.fit(X, y, sample_weight=sample_weight) + coef = estimator.coef_.copy() + model = TunedThresholdClassifierCV(estimator, cv="prefit", refit=False).fit( + X, y, sample_weight=sample_weight + ) + + assert model.estimator_ is estimator + assert_allclose(model.estimator_.coef_, coef) + + # check that we train `estimator_` on the training split of a given cross-validation + estimator = LogisticRegression().set_fit_request(sample_weight=True) + cv = [ + (np.arange(50), np.arange(50, 100)), + ] # single split + model = TunedThresholdClassifierCV(estimator, cv=cv, refit=False).fit( + X, y, sample_weight=sample_weight + ) + + assert model.estimator_ is not estimator + if with_sample_weight: + sw_train = sample_weight[cv[0][0]] + else: + sw_train = None + estimator.fit(X[cv[0][0]], y[cv[0][0]], sample_weight=sw_train) + assert_allclose(model.estimator_.coef_, estimator.coef_) + + +@pytest.mark.parametrize("fit_params_type", ["list", "array"]) +@config_context(enable_metadata_routing=True) +def test_tuned_threshold_classifier_fit_params(fit_params_type): + """Check that we pass `fit_params` to the classifier when calling `fit`.""" + X, y = make_classification(n_samples=100, random_state=0) + fit_params = { + "a": _convert_container(y, fit_params_type), + "b": _convert_container(y, fit_params_type), + } + + classifier = CheckingClassifier(expected_fit_params=["a", "b"], random_state=0) + classifier.set_fit_request(a=True, b=True) + model = TunedThresholdClassifierCV(classifier) + model.fit(X, y, **fit_params) + + +@config_context(enable_metadata_routing=True) +def test_tuned_threshold_classifier_cv_zeros_sample_weights_equivalence(): + """Check that passing removing some sample from the dataset `X` is + equivalent to passing a `sample_weight` with a factor 0.""" + X, y = load_iris(return_X_y=True) + # Scale the data to avoid any convergence issue + X = StandardScaler().fit_transform(X) + # Only use 2 classes and select samples such that 2-fold cross-validation + # split will lead to an equivalence with a `sample_weight` of 0 + X = np.vstack((X[:40], X[50:90])) + y = np.hstack((y[:40], y[50:90])) + sample_weight = np.zeros_like(y) + sample_weight[::2] = 1 + + estimator = LogisticRegression().set_fit_request(sample_weight=True) + model_without_weights = TunedThresholdClassifierCV(estimator, cv=2) + model_with_weights = clone(model_without_weights) + + model_with_weights.fit(X, y, sample_weight=sample_weight) + model_without_weights.fit(X[::2], y[::2]) + + assert_allclose( + model_with_weights.estimator_.coef_, model_without_weights.estimator_.coef_ + ) + + y_pred_with_weights = model_with_weights.predict_proba(X) + y_pred_without_weights = model_without_weights.predict_proba(X) + assert_allclose(y_pred_with_weights, y_pred_without_weights) + + +def test_tuned_threshold_classifier_thresholds_array(): + """Check that we can pass an array to `thresholds` and it is used as candidate + threshold internally.""" + X, y = make_classification(random_state=0) + estimator = LogisticRegression() + thresholds = np.linspace(0, 1, 11) + tuned_model = TunedThresholdClassifierCV( + estimator, + thresholds=thresholds, + response_method="predict_proba", + store_cv_results=True, + ).fit(X, y) + assert_allclose(tuned_model.cv_results_["thresholds"], thresholds) + + +@pytest.mark.parametrize("store_cv_results", [True, False]) +def test_tuned_threshold_classifier_store_cv_results(store_cv_results): + """Check that if `cv_results_` exists depending on `store_cv_results`.""" + X, y = make_classification(random_state=0) + estimator = LogisticRegression() + tuned_model = TunedThresholdClassifierCV( + estimator, store_cv_results=store_cv_results + ).fit(X, y) + if store_cv_results: + assert hasattr(tuned_model, "cv_results_") + else: + assert not hasattr(tuned_model, "cv_results_") + + +def test_tuned_threshold_classifier_cv_float(): + """Check the behaviour when `cv` is set to a float.""" + X, y = make_classification(random_state=0) + + # case where `refit=False` and cv is a float: the underlying estimator will be fit + # on the training set given by a ShuffleSplit. We check that we get the same model + # coefficients. + test_size = 0.3 + estimator = LogisticRegression() + tuned_model = TunedThresholdClassifierCV( + estimator, cv=test_size, refit=False, random_state=0 + ).fit(X, y) + tuned_model.fit(X, y) + + cv = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=0) + train_idx, val_idx = next(cv.split(X, y)) + cloned_estimator = clone(estimator).fit(X[train_idx], y[train_idx]) + + assert_allclose(tuned_model.estimator_.coef_, cloned_estimator.coef_) + + # case where `refit=True`, then the underlying estimator is fitted on the full + # dataset. + tuned_model.set_params(refit=True).fit(X, y) + cloned_estimator = clone(estimator).fit(X, y) + + assert_allclose(tuned_model.estimator_.coef_, cloned_estimator.coef_) + + +def test_tuned_threshold_classifier_error_constant_predictor(): + """Check that we raise a ValueError if the underlying classifier returns constant + probabilities such that we cannot find any threshold. + """ + X, y = make_classification(random_state=0) + estimator = DummyClassifier(strategy="constant", constant=1) + tuned_model = TunedThresholdClassifierCV(estimator, response_method="predict_proba") + err_msg = "The provided estimator makes constant predictions" + with pytest.raises(ValueError, match=err_msg): + tuned_model.fit(X, y) + + +@pytest.mark.parametrize( + "response_method", ["auto", "predict_proba", "decision_function"] +) +def test_fixed_threshold_classifier_equivalence_default(response_method): + """Check that `FixedThresholdClassifier` has the same behaviour as the vanilla + classifier. + """ + X, y = make_classification(random_state=0) + classifier = LogisticRegression().fit(X, y) + classifier_default_threshold = FixedThresholdClassifier( + estimator=clone(classifier), response_method=response_method + ) + classifier_default_threshold.fit(X, y) + + # emulate the response method that should take into account the `pos_label` + if response_method in ("auto", "predict_proba"): + y_score = classifier_default_threshold.predict_proba(X)[:, 1] + threshold = 0.5 + else: # response_method == "decision_function" + y_score = classifier_default_threshold.decision_function(X) + threshold = 0.0 + + y_pred_lr = (y_score >= threshold).astype(int) + assert_allclose(classifier_default_threshold.predict(X), y_pred_lr) + + +@pytest.mark.parametrize( + "response_method, threshold", [("predict_proba", 0.7), ("decision_function", 2.0)] +) +@pytest.mark.parametrize("pos_label", [0, 1]) +def test_fixed_threshold_classifier(response_method, threshold, pos_label): + """Check that applying `predict` lead to the same prediction as applying the + threshold to the output of the response method. + """ + X, y = make_classification(n_samples=50, random_state=0) + logistic_regression = LogisticRegression().fit(X, y) + model = FixedThresholdClassifier( + estimator=clone(logistic_regression), + threshold=threshold, + response_method=response_method, + pos_label=pos_label, + ).fit(X, y) + + # check that the underlying estimator is the same + assert_allclose(model.estimator_.coef_, logistic_regression.coef_) + + # emulate the response method that should take into account the `pos_label` + if response_method == "predict_proba": + y_score = model.predict_proba(X)[:, pos_label] + else: # response_method == "decision_function" + y_score = model.decision_function(X) + y_score = y_score if pos_label == 1 else -y_score + + # create a mapping from boolean values to class labels + map_to_label = np.array([0, 1]) if pos_label == 1 else np.array([1, 0]) + y_pred_lr = map_to_label[(y_score >= threshold).astype(int)] + assert_allclose(model.predict(X), y_pred_lr) + + for method in ("predict_proba", "predict_log_proba", "decision_function"): + assert_allclose( + getattr(model, method)(X), getattr(logistic_regression, method)(X) + ) + assert_allclose( + getattr(model.estimator_, method)(X), + getattr(logistic_regression, method)(X), + ) + + +@config_context(enable_metadata_routing=True) +def test_fixed_threshold_classifier_metadata_routing(): + """Check that everything works with metadata routing.""" + X, y = make_classification(random_state=0) + sample_weight = np.ones_like(y) + sample_weight[::2] = 2 + classifier = LogisticRegression().set_fit_request(sample_weight=True) + classifier.fit(X, y, sample_weight=sample_weight) + classifier_default_threshold = FixedThresholdClassifier(estimator=clone(classifier)) + classifier_default_threshold.fit(X, y, sample_weight=sample_weight) + assert_allclose(classifier_default_threshold.estimator_.coef_, classifier.coef_) + + +@pytest.mark.parametrize( + "method", ["predict_proba", "decision_function", "predict", "predict_log_proba"] +) +def test_fixed_threshold_classifier_fitted_estimator(method): + """Check that if the underlying estimator is already fitted, no fit is required.""" + X, y = make_classification(random_state=0) + classifier = LogisticRegression().fit(X, y) + fixed_threshold_classifier = FixedThresholdClassifier(estimator=classifier) + # This should not raise an error + getattr(fixed_threshold_classifier, method)(X) + + +def test_fixed_threshold_classifier_classes_(): + """Check that the classes_ attribute is properly set.""" + X, y = make_classification(random_state=0) + with pytest.raises( + AttributeError, match="The underlying estimator is not fitted yet." + ): + FixedThresholdClassifier(estimator=LogisticRegression()).classes_ + + classifier = LogisticRegression().fit(X, y) + fixed_threshold_classifier = FixedThresholdClassifier(estimator=classifier) + assert_array_equal(fixed_threshold_classifier.classes_, classifier.classes_) diff --git a/shared/package-files/75/75a416de44a4a7b89c0a69539fda42be769abb3eb493f7817f8c7551017e5d56/blob b/shared/package-files/75/75a416de44a4a7b89c0a69539fda42be769abb3eb493f7817f8c7551017e5d56/blob new file mode 100644 index 0000000000000000000000000000000000000000..47366f3803e1a76bc1ab27f5390db250071baf31 --- /dev/null +++ b/shared/package-files/75/75a416de44a4a7b89c0a69539fda42be769abb3eb493f7817f8c7551017e5d56/blob @@ -0,0 +1,99 @@ +from numba import cuda +from numba.cuda.testing import unittest, CUDATestCase + +import numpy as np + + +class TestIterators(CUDATestCase): + + def test_enumerate(self): + @cuda.jit + def enumerator(x, error): + count = 0 + + for i, v in enumerate(x): + if count != i: + error[0] = 1 + if v != x[i]: + error[0] = 2 + + count += 1 + + if count != len(x): + error[0] = 3 + + x = np.asarray((10, 9, 8, 7, 6)) + error = np.zeros(1, dtype=np.int32) + + enumerator[1, 1](x, error) + self.assertEqual(error[0], 0) + + def _test_twoarg_function(self, f): + x = np.asarray((10, 9, 8, 7, 6)) + y = np.asarray((1, 2, 3, 4, 5)) + error = np.zeros(1, dtype=np.int32) + + f[1, 1](x, y, error) + self.assertEqual(error[0], 0) + + def test_zip(self): + @cuda.jit + def zipper(x, y, error): + i = 0 + + for xv, yv in zip(x, y): + if xv != x[i]: + error[0] = 1 + if yv != y[i]: + error[0] = 2 + + i += 1 + + if i != len(x): + error[0] = 3 + + self._test_twoarg_function(zipper) + + def test_enumerate_zip(self): + @cuda.jit + def enumerator_zipper(x, y, error): + count = 0 + + for i, (xv, yv) in enumerate(zip(x, y)): + if i != count: + error[0] = 1 + if xv != x[i]: + error[0] = 2 + if yv != y[i]: + error[0] = 3 + + count += 1 + + if count != len(x): + error[0] = 4 + + self._test_twoarg_function(enumerator_zipper) + + def test_zip_enumerate(self): + @cuda.jit + def zipper_enumerator(x, y, error): + count = 0 + + for (i, xv), yv in zip(enumerate(x), y): + if i != count: + error[0] = 1 + if xv != x[i]: + error[0] = 2 + if yv != y[i]: + error[0] = 3 + + count += 1 + + if count != len(x): + error[0] = 4 + + self._test_twoarg_function(zipper_enumerator) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/75/75a5e07029b97b3c75e84a42f37274e1da15e5f1d0d666652cb08480896d4596/blob b/shared/package-files/75/75a5e07029b97b3c75e84a42f37274e1da15e5f1d0d666652cb08480896d4596/blob new file mode 100644 index 0000000000000000000000000000000000000000..c298f74c5643edff67f3284091213d4eccb685ae --- /dev/null +++ b/shared/package-files/75/75a5e07029b97b3c75e84a42f37274e1da15e5f1d0d666652cb08480896d4596/blob @@ -0,0 +1,109 @@ +import logging +from typing import Any, Optional, Text + +from .s3.connection import S3Connection + +Version: Any +UserAgent: Any +config: Any +BUCKET_NAME_RE: Any +TOO_LONG_DNS_NAME_COMP: Any +GENERATION_RE: Any +VERSION_RE: Any +ENDPOINTS_PATH: Any + +def init_logging(): ... + +class NullHandler(logging.Handler): + def emit(self, record): ... + +log: Any +perflog: Any + +def set_file_logger(name, filepath, level: Any = ..., format_string: Optional[Any] = ...): ... +def set_stream_logger(name, level: Any = ..., format_string: Optional[Any] = ...): ... +def connect_sqs(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_s3( + aws_access_key_id: Optional[Text] = ..., aws_secret_access_key: Optional[Text] = ..., **kwargs +) -> S3Connection: ... +def connect_gs(gs_access_key_id: Optional[Any] = ..., gs_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_ec2(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_elb(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_autoscale(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudwatch(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_sdb(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_fps(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_mturk(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudfront(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_vpc(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_rds(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_rds2(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_emr(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_sns(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_iam(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_route53(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudformation(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_euca( + host: Optional[Any] = ..., + aws_access_key_id: Optional[Any] = ..., + aws_secret_access_key: Optional[Any] = ..., + port: int = ..., + path: str = ..., + is_secure: bool = ..., + **kwargs, +): ... +def connect_glacier(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_ec2_endpoint(url, aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_walrus( + host: Optional[Any] = ..., + aws_access_key_id: Optional[Any] = ..., + aws_secret_access_key: Optional[Any] = ..., + port: int = ..., + path: str = ..., + is_secure: bool = ..., + **kwargs, +): ... +def connect_ses(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_sts(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_ia( + ia_access_key_id: Optional[Any] = ..., ia_secret_access_key: Optional[Any] = ..., is_secure: bool = ..., **kwargs +): ... +def connect_dynamodb(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_swf(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudsearch(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudsearch2( + aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., sign_request: bool = ..., **kwargs +): ... +def connect_cloudsearchdomain(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_beanstalk(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_elastictranscoder(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_opsworks(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_redshift(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_support(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudtrail(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_directconnect(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_kinesis(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_logs(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_route53domains(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cognito_identity(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cognito_sync(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_kms(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_awslambda(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_codedeploy(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_configservice(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_cloudhsm(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_ec2containerservice(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def connect_machinelearning(aws_access_key_id: Optional[Any] = ..., aws_secret_access_key: Optional[Any] = ..., **kwargs): ... +def storage_uri( + uri_str, + default_scheme: str = ..., + debug: int = ..., + validate: bool = ..., + bucket_storage_uri_class: Any = ..., + suppress_consec_slashes: bool = ..., + is_latest: bool = ..., +): ... +def storage_uri_for_key(key): ... + +# Explicitly mark this package as incomplete. +def __getattr__(name: str) -> Any: ... diff --git a/shared/package-files/75/75a6da22075c05405d30ce3edf989145297ccc1ae4dd4b79485e59509f20fd13/blob b/shared/package-files/75/75a6da22075c05405d30ce3edf989145297ccc1ae4dd4b79485e59509f20fd13/blob new file mode 100644 index 0000000000000000000000000000000000000000..04c4883c050bad7a89b52e85b58293e3b4e4052d Binary files /dev/null and b/shared/package-files/75/75a6da22075c05405d30ce3edf989145297ccc1ae4dd4b79485e59509f20fd13/blob differ diff --git a/shared/package-files/75/75a70efa1e815a83c89d86235094e8924fa6fa024589c23c8f08fb79efa11584/blob b/shared/package-files/75/75a70efa1e815a83c89d86235094e8924fa6fa024589c23c8f08fb79efa11584/blob new file mode 100644 index 0000000000000000000000000000000000000000..edb93bd66e6c9c107e8c9ab50caa58f5721c29bf --- /dev/null +++ b/shared/package-files/75/75a70efa1e815a83c89d86235094e8924fa6fa024589c23c8f08fb79efa11584/blob @@ -0,0 +1,53 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::__rshift__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor __rshift__(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::__rshift___Scalar::call(self, other); +} + +// aten::__rshift__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor __rshift__(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::__rshift___Tensor::call(self, other); +} + +// aten::__rshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other) { + return at::_ops::__rshift___Scalar_out::call(self, other, out); +} +// aten::__rshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out) { + return at::_ops::__rshift___Scalar_out::call(self, other, out); +} + +// aten::__rshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::__rshift___Tensor_out::call(self, other, out); +} +// aten::__rshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & __rshift___outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::__rshift___Tensor_out::call(self, other, out); +} + +} diff --git a/shared/package-files/75/75a7f74e9e4392757b9725ad19ee67d2357b53423fe87c283293a796009d62fd/blob b/shared/package-files/75/75a7f74e9e4392757b9725ad19ee67d2357b53423fe87c283293a796009d62fd/blob new file mode 100644 index 0000000000000000000000000000000000000000..f706016ca3869e8639bcfcefefacee34d4fc4011 --- /dev/null +++ b/shared/package-files/75/75a7f74e9e4392757b9725ad19ee67d2357b53423fe87c283293a796009d62fd/blob @@ -0,0 +1,6 @@ +from typing import Any + +HOOKS: Any + +def default_hooks(): ... +def dispatch_hook(key, hooks, hook_data, **kwargs): ... diff --git a/shared/package-files/75/75a9bbf13a7f0a8cf26cda82636258806052dd473d16e254013f6807496894eb/blob b/shared/package-files/75/75a9bbf13a7f0a8cf26cda82636258806052dd473d16e254013f6807496894eb/blob new file mode 100644 index 0000000000000000000000000000000000000000..412e5ba4d2cdea7db090dc96412e697909a38d78 --- /dev/null +++ b/shared/package-files/75/75a9bbf13a7f0a8cf26cda82636258806052dd473d16e254013f6807496894eb/blob @@ -0,0 +1,124 @@ +import logging +import tarfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.compression import compr +from fsspec.utils import infer_compression + +typemap = {b"0": "file", b"5": "directory"} + +logger = logging.getLogger("tar") + + +class TarFileSystem(AbstractArchiveFileSystem): + """Compressed Tar archives as a file-system (read-only) + + Supports the following formats: + tar.gz, tar.bz2, tar.xz + """ + + root_marker = "" + protocol = "tar" + cachable = False + + def __init__( + self, + fo="", + index_store=None, + target_options=None, + target_protocol=None, + compression=None, + **kwargs, + ): + super().__init__(**kwargs) + target_options = target_options or {} + + if isinstance(fo, str): + self.of = fsspec.open(fo, protocol=target_protocol, **target_options) + fo = self.of.open() # keep the reference + + # Try to infer compression. + if compression is None: + name = None + + # Try different ways to get hold of the filename. `fo` might either + # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an + # `fsspec.AbstractFileSystem` instance. + try: + # Amended io.BufferedReader or similar. + # This uses a "protocol extension" where original filenames are + # propagated to archive-like filesystems in order to let them + # infer the right compression appropriately. + if hasattr(fo, "original"): + name = fo.original + + # fsspec.LocalFileOpener + elif hasattr(fo, "path"): + name = fo.path + + # io.BufferedReader + elif hasattr(fo, "name"): + name = fo.name + + # fsspec.AbstractFileSystem + elif hasattr(fo, "info"): + name = fo.info()["name"] + + except Exception as ex: + logger.warning( + f"Unable to determine file name, not inferring compression: {ex}" + ) + + if name is not None: + compression = infer_compression(name) + logger.info(f"Inferred compression {compression} from file name {name}") + + if compression is not None: + # TODO: tarfile already implements compression with modes like "'r:gz'", + # but then would seek to offset in the file work? + fo = compr[compression](fo) + + self._fo_ref = fo + self.fo = fo # the whole instance is a context + self.tar = tarfile.TarFile(fileobj=self.fo) + self.dir_cache = None + + self.index_store = index_store + self.index = None + self._index() + + def _index(self): + # TODO: load and set saved index, if exists + out = {} + for ti in self.tar: + info = ti.get_info() + info["type"] = typemap.get(info["type"], "file") + name = ti.get_info()["name"].rstrip("/") + out[name] = (info, ti.offset_data) + + self.index = out + # TODO: save index to self.index_store here, if set + + def _get_dirs(self): + if self.dir_cache is not None: + return + + # This enables ls to get directories as children as well as files + self.dir_cache = { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(self.tar.getnames()) + } + for member in self.tar.getmembers(): + info = member.get_info() + info["name"] = info["name"].rstrip("/") + info["type"] = typemap.get(info["type"], "file") + self.dir_cache[info["name"]] = info + + def _open(self, path, mode="rb", **kwargs): + if mode != "rb": + raise ValueError("Read-only filesystem implementation") + details, offset = self.index[path] + if details["type"] != "file": + raise ValueError("Can only handle regular files") + return self.tar.extractfile(path) diff --git a/shared/package-files/75/75aa686ff901c9e66e51d36e8e78e5154b57ee9045784568f6a8798ea9689207/blob b/shared/package-files/75/75aa686ff901c9e66e51d36e8e78e5154b57ee9045784568f6a8798ea9689207/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d332ad5c40b14dadf4ed342662787c283c7a772 --- /dev/null +++ b/shared/package-files/75/75aa686ff901c9e66e51d36e8e78e5154b57ee9045784568f6a8798ea9689207/blob @@ -0,0 +1,47 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset gv DAYS_OF_WEEK_ABBREV [list \ + "Jed"\ + "Jel"\ + "Jem"\ + "Jerc"\ + "Jerd"\ + "Jeh"\ + "Jes"] + ::msgcat::mcset gv DAYS_OF_WEEK_FULL [list \ + "Jedoonee"\ + "Jelhein"\ + "Jemayrt"\ + "Jercean"\ + "Jerdein"\ + "Jeheiney"\ + "Jesarn"] + ::msgcat::mcset gv MONTHS_ABBREV [list \ + "J-guer"\ + "T-arree"\ + "Mayrnt"\ + "Avrril"\ + "Boaldyn"\ + "M-souree"\ + "J-souree"\ + "Luanistyn"\ + "M-fouyir"\ + "J-fouyir"\ + "M.Houney"\ + "M.Nollick"\ + ""] + ::msgcat::mcset gv MONTHS_FULL [list \ + "Jerrey-geuree"\ + "Toshiaght-arree"\ + "Mayrnt"\ + "Averil"\ + "Boaldyn"\ + "Mean-souree"\ + "Jerrey-souree"\ + "Luanistyn"\ + "Mean-fouyir"\ + "Jerrey-fouyir"\ + "Mee Houney"\ + "Mee ny Nollick"\ + ""] +} diff --git a/shared/package-files/75/75ad3cb4c8c8b08c3c87df9658e8dec0bf6fefaa3ebabdfee35b437adddcfbcf/blob b/shared/package-files/75/75ad3cb4c8c8b08c3c87df9658e8dec0bf6fefaa3ebabdfee35b437adddcfbcf/blob new file mode 100644 index 0000000000000000000000000000000000000000..33e93c189d972b038efebfffcb20851bf7a5a6be --- /dev/null +++ b/shared/package-files/75/75ad3cb4c8c8b08c3c87df9658e8dec0bf6fefaa3ebabdfee35b437adddcfbcf/blob @@ -0,0 +1,24 @@ +# Process this file with autoconf to produce a pkg-config metadata file. + +# Copyright (C) 2004-2012 Free Software Foundation, Inc. + +# Copying and distribution of this file, with or without modification, +# are permitted in any medium without royalty provided the copyright +# notice and this notice are preserved. This file is offered as-is, +# without any warranty. + +# Author: Simon Josefsson + +prefix=/opt/conda +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include + +Name: GnuTLS +Description: Transport Security Layer implementation for the GNU system +URL: https://www.gnutls.org/ +Version: 3.6.15 +Libs: -L${libdir} -lgnutls +Libs.private: -pthread -lgmp -lunistring -latomic +Requires.private: nettle, hogweed, libtasn1, libidn2 +Cflags: -I${includedir} diff --git a/shared/package-files/75/75ad6bd38f9a074b35bf83d1e1dfd32ab79d5e9564651fa496e430d6ad3b57e5/blob b/shared/package-files/75/75ad6bd38f9a074b35bf83d1e1dfd32ab79d5e9564651fa496e430d6ad3b57e5/blob new file mode 100644 index 0000000000000000000000000000000000000000..7719adb1b15800a733af6a056849ed67c02052a4 --- /dev/null +++ b/shared/package-files/75/75ad6bd38f9a074b35bf83d1e1dfd32ab79d5e9564651fa496e430d6ad3b57e5/blob @@ -0,0 +1,33 @@ +from datetime import datetime +from typing import Any, Optional, Union + +from django.template.base import FilterExpression, NodeList, Parser, Token +from django.utils.timezone import FixedOffset + +from django.template import Node + +register: Any + +class datetimeobject(datetime): ... + +def localtime(value: Optional[Union[datetime, str]]) -> Any: ... +def utc(value: Optional[Union[datetime, str]]) -> Any: ... +def do_timezone(value: Optional[Union[datetime, str]], arg: Optional[Union[FixedOffset, str]]) -> Any: ... + +class LocalTimeNode(Node): + nodelist: NodeList = ... + use_tz: bool = ... + def __init__(self, nodelist: NodeList, use_tz: bool) -> None: ... + +class TimezoneNode(Node): + nodelist: NodeList = ... + tz: FilterExpression = ... + def __init__(self, nodelist: NodeList, tz: FilterExpression) -> None: ... + +class GetCurrentTimezoneNode(Node): + variable: str = ... + def __init__(self, variable: str) -> None: ... + +def localtime_tag(parser: Parser, token: Token) -> LocalTimeNode: ... +def timezone_tag(parser: Parser, token: Token) -> TimezoneNode: ... +def get_current_timezone_tag(parser: Parser, token: Token) -> GetCurrentTimezoneNode: ... diff --git a/shared/package-files/75/75aecda0a7141714bbf0820402c63a917ccbfa6382ad5d32ca115641437aa7c9/blob b/shared/package-files/75/75aecda0a7141714bbf0820402c63a917ccbfa6382ad5d32ca115641437aa7c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..2306f5974ba186587dedb1159d64374601f55c86 --- /dev/null +++ b/shared/package-files/75/75aecda0a7141714bbf0820402c63a917ccbfa6382ad5d32ca115641437aa7c9/blob @@ -0,0 +1,188 @@ +from __future__ import annotations + +import datetime as dt +from typing import ( + TYPE_CHECKING, + Any, + cast, +) + +import numpy as np + +from pandas.core.dtypes.dtypes import register_extension_dtype + +from pandas.api.extensions import ( + ExtensionArray, + ExtensionDtype, +) +from pandas.api.types import pandas_dtype + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pandas._typing import ( + Dtype, + PositionalIndexer, + ) + + +@register_extension_dtype +class DateDtype(ExtensionDtype): + @property + def type(self): + return dt.date + + @property + def name(self): + return "DateDtype" + + @classmethod + def construct_from_string(cls, string: str): + if not isinstance(string, str): + raise TypeError( + f"'construct_from_string' expects a string, got {type(string)}" + ) + + if string == cls.__name__: + return cls() + else: + raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'") + + @classmethod + def construct_array_type(cls): + return DateArray + + @property + def na_value(self): + return dt.date.min + + def __repr__(self) -> str: + return self.name + + +class DateArray(ExtensionArray): + def __init__( + self, + dates: ( + dt.date + | Sequence[dt.date] + | tuple[np.ndarray, np.ndarray, np.ndarray] + | np.ndarray + ), + ) -> None: + if isinstance(dates, dt.date): + self._year = np.array([dates.year]) + self._month = np.array([dates.month]) + self._day = np.array([dates.year]) + return + + ldates = len(dates) + if isinstance(dates, list): + # pre-allocate the arrays since we know the size before hand + self._year = np.zeros(ldates, dtype=np.uint16) # 65535 (0, 9999) + self._month = np.zeros(ldates, dtype=np.uint8) # 255 (1, 31) + self._day = np.zeros(ldates, dtype=np.uint8) # 255 (1, 12) + # populate them + for i, (y, m, d) in enumerate( + (date.year, date.month, date.day) for date in dates + ): + self._year[i] = y + self._month[i] = m + self._day[i] = d + + elif isinstance(dates, tuple): + # only support triples + if ldates != 3: + raise ValueError("only triples are valid") + # check if all elements have the same type + if any(not isinstance(x, np.ndarray) for x in dates): + raise TypeError("invalid type") + ly, lm, ld = (len(cast(np.ndarray, d)) for d in dates) + if not ly == lm == ld: + raise ValueError( + f"tuple members must have the same length: {(ly, lm, ld)}" + ) + self._year = dates[0].astype(np.uint16) + self._month = dates[1].astype(np.uint8) + self._day = dates[2].astype(np.uint8) + + elif isinstance(dates, np.ndarray) and dates.dtype == "U10": + self._year = np.zeros(ldates, dtype=np.uint16) # 65535 (0, 9999) + self._month = np.zeros(ldates, dtype=np.uint8) # 255 (1, 31) + self._day = np.zeros(ldates, dtype=np.uint8) # 255 (1, 12) + + # error: "object_" object is not iterable + obj = np.char.split(dates, sep="-") + for (i,), (y, m, d) in np.ndenumerate(obj): # type: ignore[misc] + self._year[i] = int(y) + self._month[i] = int(m) + self._day[i] = int(d) + + else: + raise TypeError(f"{type(dates)} is not supported") + + @property + def dtype(self) -> ExtensionDtype: + return DateDtype() + + def astype(self, dtype, copy=True): + dtype = pandas_dtype(dtype) + + if isinstance(dtype, DateDtype): + data = self.copy() if copy else self + else: + data = self.to_numpy(dtype=dtype, copy=copy, na_value=dt.date.min) + + return data + + @property + def nbytes(self) -> int: + return self._year.nbytes + self._month.nbytes + self._day.nbytes + + def __len__(self) -> int: + return len(self._year) # all 3 arrays are enforced to have the same length + + def __getitem__(self, item: PositionalIndexer): + if isinstance(item, int): + return dt.date(self._year[item], self._month[item], self._day[item]) + else: + raise NotImplementedError("only ints are supported as indexes") + + def __setitem__(self, key: int | slice | np.ndarray, value: Any) -> None: + if not isinstance(key, int): + raise NotImplementedError("only ints are supported as indexes") + + if not isinstance(value, dt.date): + raise TypeError("you can only set datetime.date types") + + self._year[key] = value.year + self._month[key] = value.month + self._day[key] = value.day + + def __repr__(self) -> str: + return f"DateArray{list(zip(self._year, self._month, self._day))}" + + def copy(self) -> DateArray: + return DateArray((self._year.copy(), self._month.copy(), self._day.copy())) + + def isna(self) -> np.ndarray: + return np.logical_and( + np.logical_and( + self._year == dt.date.min.year, self._month == dt.date.min.month + ), + self._day == dt.date.min.day, + ) + + @classmethod + def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy=False): + if isinstance(scalars, dt.date): + raise TypeError + elif isinstance(scalars, DateArray): + if dtype is not None: + return scalars.astype(dtype, copy=copy) + if copy: + return scalars.copy() + return scalars[:] + elif isinstance(scalars, np.ndarray): + scalars = scalars.astype("U10") # 10 chars for yyyy-mm-dd + return DateArray(scalars) diff --git a/shared/package-files/75/75afb8ee0276e8b5214c2d6b5bb8cb74e07e109c7a3be1f1e86cae5d4c75a464/blob b/shared/package-files/75/75afb8ee0276e8b5214c2d6b5bb8cb74e07e109c7a3be1f1e86cae5d4c75a464/blob new file mode 100644 index 0000000000000000000000000000000000000000..80055281236fa9a7c186d00d0363eb947a22755b --- /dev/null +++ b/shared/package-files/75/75afb8ee0276e8b5214c2d6b5bb8cb74e07e109c7a3be1f1e86cae5d4c75a464/blob @@ -0,0 +1,184 @@ +import itertools +from dataclasses import dataclass + +from typing import List, Tuple + +from torch.distributed._tensor.op_schema import OpStrategy, PlacementStrategy +from torch.distributed._tensor.placement_types import ( + _Partial, + DTensorSpec, + Placement, + Replicate, + Shard, +) + +from torch.distributed.device_mesh import DeviceMesh + + +@dataclass +class EinsumDims: + contracting_dims: List[str] + batch_dims: List[str] + lhs_out_only_dims: List[str] + rhs_out_only_dims: List[str] + + @classmethod + def parse_equation(cls, equation: str) -> Tuple[List[str], str]: + # parse einop equation and extract arg specs + """ + Parse the einsum equation str to input dim chars and output dim char + """ + inputs, outputs = equation.split("->") + input_dims, output_dims = inputs.split(","), outputs.split(",") + + # NOTE: only support at most two inputs, and single output + # extend to support more inputs if needed in future + assert len(input_dims) <= 2, "Only support at most two inputs" + assert len(output_dims) == 1, "Only support single output" + output_dim = output_dims[0] + return input_dims, output_dim + + @classmethod + def parse_dims(cls, input_dims: List[str], output_dim: str) -> "EinsumDims": + """ + Parse the dims and extract the contracting, batch, and free dimensions + for the left and right hand sides. + """ + dim_char_set = set() + for input_dim in input_dims: + for input_char in list(input_dim): + dim_char_set.add(input_char) + + # get a determinisitc order of all dim chars + all_dim_chars = sorted(dim_char_set) + + # parse input and output dimensions + lhs_out_only_dims, rhs_out_only_dims = [], [] + batch_dims, contracting_dims = [], [] + + for dim_char in all_dim_chars: + if dim_char not in output_dim: + contracting_dims.append(dim_char) + else: + is_batch_dim = True + for input_dim in input_dims: + is_batch_dim = is_batch_dim and dim_char in input_dim + + if is_batch_dim: + batch_dims.append(dim_char) + else: + assert ( + len(input_dims) == 2 + ), "free dimension only supported for two inputs!" + lhs, rhs = input_dims + if dim_char in lhs: + lhs_out_only_dims.append(dim_char) + elif dim_char in rhs: + rhs_out_only_dims.append(dim_char) + else: + raise RuntimeError("Invalid dimension character") + + return cls( + contracting_dims=contracting_dims, + batch_dims=batch_dims, + lhs_out_only_dims=lhs_out_only_dims, + rhs_out_only_dims=rhs_out_only_dims, + ) + + +def gen_einsum_strategies( + equation: str, + mesh: DeviceMesh, + *, + linearity: bool = False, +) -> OpStrategy: + """ + Generate a strategy list for the ops that follow einsum style notation. + """ + # parse einop equation and extract dims + input_dims, output_dim = EinsumDims.parse_equation(equation) + edims = EinsumDims.parse_dims(input_dims, output_dim) + + all_mesh_dim_strategies = [] + + # generate strategies for each mesh dim + for mesh_dim in range(mesh.ndim): + mesh_dim_strategies = [] + + # placement list stores placements of [output, input1, input2, ...] + # first we always have replicate all for inputs and output + placement_list: List[Placement] = [Replicate()] * (len(input_dims) + 1) + mesh_dim_strategies.append(placement_list) + + if mesh.size(mesh_dim) <= 1: + # only replicate strategy for mesh dim with size 1 + # TODO: see if this is valid for the submesh case + continue + + # split batch dim + for batch_dim in edims.batch_dims: + output_batch_dim = output_dim.index(batch_dim) + placement_list = [Shard(output_batch_dim)] + for input_dim in input_dims: + input_batch_dim = input_dim.index(batch_dim) + placement_list.append(Shard(input_batch_dim)) + + mesh_dim_strategies.append(placement_list) + + # split contracting dim + for contracting_dim in edims.contracting_dims: + placement_list = [_Partial()] + for input_dim in input_dims: + input_contracting_dim = input_dim.index(contracting_dim) + placement_list.append(Shard(input_contracting_dim)) + + mesh_dim_strategies.append(placement_list) + + # split lhs free dim + for lhs_dim in edims.lhs_out_only_dims: + lhs_free_dim = output_dim.index(lhs_dim) + # this means split the lhs input and output + # i.e. S(0), R -> S(0) + lhs_placement_list: List[Placement] = [ + Shard(lhs_free_dim), + Shard(lhs_free_dim), + Replicate(), + ] + mesh_dim_strategies.append(lhs_placement_list) + + # split rhs free dim + for rhs_dim in edims.rhs_out_only_dims: + rhs_free_dim = output_dim.index(rhs_dim) + rhs_placement_list: List[Placement] = [ + Shard(rhs_free_dim), + Replicate(), + Shard(rhs_free_dim), + ] + mesh_dim_strategies.append(rhs_placement_list) + + # linearity strategy + if linearity: + linearity_placement_list: List[Placement] = [_Partial()] + for input_dim in input_dims: + linearity_placement_list.append(_Partial()) + mesh_dim_strategies.append(linearity_placement_list) + + all_mesh_dim_strategies.append(mesh_dim_strategies) + + # generate strategies for entire mesh + strategy_combs = itertools.product(*all_mesh_dim_strategies) + + # TODO: filter out invalid strategies, at this point we generate + # all possible strategies without considering the whether the tensor + # dim could be sharded or not, we would need to filter out invalid + # strategies base on the actual tensor shape + # (i.e. for Shard, tensor dim size must > mesh size) + all_strategies = [] + for strategy_comb in strategy_combs: + spec_list = [] + for specs in zip(*strategy_comb): + spec_list.append(DTensorSpec(mesh, tuple(specs))) + strat = PlacementStrategy(output_specs=spec_list[0], input_specs=spec_list[1:]) + all_strategies.append(strat) + + return OpStrategy(all_strategies) diff --git a/shared/package-files/75/75b68272cdbb77237d827316185e6703f06b567e90f8dae329826957dfdf801b/blob b/shared/package-files/75/75b68272cdbb77237d827316185e6703f06b567e90f8dae329826957dfdf801b/blob new file mode 100644 index 0000000000000000000000000000000000000000..14876000de895a609d5b9f3de39c3c8fc44ef1fc --- /dev/null +++ b/shared/package-files/75/75b68272cdbb77237d827316185e6703f06b567e90f8dae329826957dfdf801b/blob @@ -0,0 +1,488 @@ +""" +An OrderedSet is a custom MutableSet that remembers its order, so that every +entry has an index that can be looked up. + +Based on a recipe originally posted to ActiveState Recipes by Raymond Hettiger, +and released under the MIT license. +""" +import itertools as it +from collections import deque + +try: + # Python 3 + from collections.abc import MutableSet, Sequence +except ImportError: + # Python 2.7 + from collections import MutableSet, Sequence + +SLICE_ALL = slice(None) +__version__ = "3.1" + + +def is_iterable(obj): + """ + Are we being asked to look up a list of things, instead of a single thing? + We check for the `__iter__` attribute so that this can cover types that + don't have to be known by this module, such as NumPy arrays. + + Strings, however, should be considered as atomic values to look up, not + iterables. The same goes for tuples, since they are immutable and therefore + valid entries. + + We don't need to check for the Python 2 `unicode` type, because it doesn't + have an `__iter__` attribute anyway. + """ + return ( + hasattr(obj, "__iter__") + and not isinstance(obj, str) + and not isinstance(obj, tuple) + ) + + +class OrderedSet(MutableSet, Sequence): + """ + An OrderedSet is a custom MutableSet that remembers its order, so that + every entry has an index that can be looked up. + + Example: + >>> OrderedSet([1, 1, 2, 3, 2]) + OrderedSet([1, 2, 3]) + """ + + def __init__(self, iterable=None): + self.items = [] + self.map = {} + if iterable is not None: + self |= iterable + + def __len__(self): + """ + Returns the number of unique elements in the ordered set + + Example: + >>> len(OrderedSet([])) + 0 + >>> len(OrderedSet([1, 2])) + 2 + """ + return len(self.items) + + def __getitem__(self, index): + """ + Get the item at a given index. + + If `index` is a slice, you will get back that slice of items, as a + new OrderedSet. + + If `index` is a list or a similar iterable, you'll get a list of + items corresponding to those indices. This is similar to NumPy's + "fancy indexing". The result is not an OrderedSet because you may ask + for duplicate indices, and the number of elements returned should be + the number of elements asked for. + + Example: + >>> oset = OrderedSet([1, 2, 3]) + >>> oset[1] + 2 + """ + if isinstance(index, slice) and index == SLICE_ALL: + return self.copy() + elif is_iterable(index): + return [self.items[i] for i in index] + elif hasattr(index, "__index__") or isinstance(index, slice): + result = self.items[index] + if isinstance(result, list): + return self.__class__(result) + else: + return result + else: + raise TypeError("Don't know how to index an OrderedSet by %r" % index) + + def copy(self): + """ + Return a shallow copy of this object. + + Example: + >>> this = OrderedSet([1, 2, 3]) + >>> other = this.copy() + >>> this == other + True + >>> this is other + False + """ + return self.__class__(self) + + def __getstate__(self): + if len(self) == 0: + # The state can't be an empty list. + # We need to return a truthy value, or else __setstate__ won't be run. + # + # This could have been done more gracefully by always putting the state + # in a tuple, but this way is backwards- and forwards- compatible with + # previous versions of OrderedSet. + return (None,) + else: + return list(self) + + def __setstate__(self, state): + if state == (None,): + self.__init__([]) + else: + self.__init__(state) + + def __contains__(self, key): + """ + Test if the item is in this ordered set + + Example: + >>> 1 in OrderedSet([1, 3, 2]) + True + >>> 5 in OrderedSet([1, 3, 2]) + False + """ + return key in self.map + + def add(self, key): + """ + Add `key` as an item to this OrderedSet, then return its index. + + If `key` is already in the OrderedSet, return the index it already + had. + + Example: + >>> oset = OrderedSet() + >>> oset.append(3) + 0 + >>> print(oset) + OrderedSet([3]) + """ + if key not in self.map: + self.map[key] = len(self.items) + self.items.append(key) + return self.map[key] + + append = add + + def update(self, sequence): + """ + Update the set with the given iterable sequence, then return the index + of the last element inserted. + + Example: + >>> oset = OrderedSet([1, 2, 3]) + >>> oset.update([3, 1, 5, 1, 4]) + 4 + >>> print(oset) + OrderedSet([1, 2, 3, 5, 4]) + """ + item_index = None + try: + for item in sequence: + item_index = self.add(item) + except TypeError: + raise ValueError( + "Argument needs to be an iterable, got %s" % type(sequence) + ) + return item_index + + def index(self, key): + """ + Get the index of a given entry, raising an IndexError if it's not + present. + + `key` can be an iterable of entries that is not a string, in which case + this returns a list of indices. + + Example: + >>> oset = OrderedSet([1, 2, 3]) + >>> oset.index(2) + 1 + """ + if is_iterable(key): + return [self.index(subkey) for subkey in key] + return self.map[key] + + # Provide some compatibility with pd.Index + get_loc = index + get_indexer = index + + def pop(self): + """ + Remove and return the last element from the set. + + Raises KeyError if the set is empty. + + Example: + >>> oset = OrderedSet([1, 2, 3]) + >>> oset.pop() + 3 + """ + if not self.items: + raise KeyError("Set is empty") + + elem = self.items[-1] + del self.items[-1] + del self.map[elem] + return elem + + def discard(self, key): + """ + Remove an element. Do not raise an exception if absent. + + The MutableSet mixin uses this to implement the .remove() method, which + *does* raise an error when asked to remove a non-existent item. + + Example: + >>> oset = OrderedSet([1, 2, 3]) + >>> oset.discard(2) + >>> print(oset) + OrderedSet([1, 3]) + >>> oset.discard(2) + >>> print(oset) + OrderedSet([1, 3]) + """ + if key in self: + i = self.map[key] + del self.items[i] + del self.map[key] + for k, v in self.map.items(): + if v >= i: + self.map[k] = v - 1 + + def clear(self): + """ + Remove all items from this OrderedSet. + """ + del self.items[:] + self.map.clear() + + def __iter__(self): + """ + Example: + >>> list(iter(OrderedSet([1, 2, 3]))) + [1, 2, 3] + """ + return iter(self.items) + + def __reversed__(self): + """ + Example: + >>> list(reversed(OrderedSet([1, 2, 3]))) + [3, 2, 1] + """ + return reversed(self.items) + + def __repr__(self): + if not self: + return "%s()" % (self.__class__.__name__,) + return "%s(%r)" % (self.__class__.__name__, list(self)) + + def __eq__(self, other): + """ + Returns true if the containers have the same items. If `other` is a + Sequence, then order is checked, otherwise it is ignored. + + Example: + >>> oset = OrderedSet([1, 3, 2]) + >>> oset == [1, 3, 2] + True + >>> oset == [1, 2, 3] + False + >>> oset == [2, 3] + False + >>> oset == OrderedSet([3, 2, 1]) + False + """ + # In Python 2 deque is not a Sequence, so treat it as one for + # consistent behavior with Python 3. + if isinstance(other, (Sequence, deque)): + # Check that this OrderedSet contains the same elements, in the + # same order, as the other object. + return list(self) == list(other) + try: + other_as_set = set(other) + except TypeError: + # If `other` can't be converted into a set, it's not equal. + return False + else: + return set(self) == other_as_set + + def union(self, *sets): + """ + Combines all unique items. + Each items order is defined by its first appearance. + + Example: + >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0]) + >>> print(oset) + OrderedSet([3, 1, 4, 5, 2, 0]) + >>> oset.union([8, 9]) + OrderedSet([3, 1, 4, 5, 2, 0, 8, 9]) + >>> oset | {10} + OrderedSet([3, 1, 4, 5, 2, 0, 10]) + """ + cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet + containers = map(list, it.chain([self], sets)) + items = it.chain.from_iterable(containers) + return cls(items) + + def __and__(self, other): + # the parent implementation of this is backwards + return self.intersection(other) + + def intersection(self, *sets): + """ + Returns elements in common between all sets. Order is defined only + by the first set. + + Example: + >>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3]) + >>> print(oset) + OrderedSet([1, 2, 3]) + >>> oset.intersection([2, 4, 5], [1, 2, 3, 4]) + OrderedSet([2]) + >>> oset.intersection() + OrderedSet([1, 2, 3]) + """ + cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet + if sets: + common = set.intersection(*map(set, sets)) + items = (item for item in self if item in common) + else: + items = self + return cls(items) + + def difference(self, *sets): + """ + Returns all elements that are in this set but not the others. + + Example: + >>> OrderedSet([1, 2, 3]).difference(OrderedSet([2])) + OrderedSet([1, 3]) + >>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3])) + OrderedSet([1]) + >>> OrderedSet([1, 2, 3]) - OrderedSet([2]) + OrderedSet([1, 3]) + >>> OrderedSet([1, 2, 3]).difference() + OrderedSet([1, 2, 3]) + """ + cls = self.__class__ + if sets: + other = set.union(*map(set, sets)) + items = (item for item in self if item not in other) + else: + items = self + return cls(items) + + def issubset(self, other): + """ + Report whether another set contains this set. + + Example: + >>> OrderedSet([1, 2, 3]).issubset({1, 2}) + False + >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4}) + True + >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5}) + False + """ + if len(self) > len(other): # Fast check for obvious cases + return False + return all(item in other for item in self) + + def issuperset(self, other): + """ + Report whether this set contains another set. + + Example: + >>> OrderedSet([1, 2]).issuperset([1, 2, 3]) + False + >>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3}) + True + >>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3}) + False + """ + if len(self) < len(other): # Fast check for obvious cases + return False + return all(item in self for item in other) + + def symmetric_difference(self, other): + """ + Return the symmetric difference of two OrderedSets as a new set. + That is, the new set will contain all elements that are in exactly + one of the sets. + + Their order will be preserved, with elements from `self` preceding + elements from `other`. + + Example: + >>> this = OrderedSet([1, 4, 3, 5, 7]) + >>> other = OrderedSet([9, 7, 1, 3, 2]) + >>> this.symmetric_difference(other) + OrderedSet([4, 5, 9, 2]) + """ + cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet + diff1 = cls(self).difference(other) + diff2 = cls(other).difference(self) + return diff1.union(diff2) + + def _update_items(self, items): + """ + Replace the 'items' list of this OrderedSet with a new one, updating + self.map accordingly. + """ + self.items = items + self.map = {item: idx for (idx, item) in enumerate(items)} + + def difference_update(self, *sets): + """ + Update this OrderedSet to remove items from one or more other sets. + + Example: + >>> this = OrderedSet([1, 2, 3]) + >>> this.difference_update(OrderedSet([2, 4])) + >>> print(this) + OrderedSet([1, 3]) + + >>> this = OrderedSet([1, 2, 3, 4, 5]) + >>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6])) + >>> print(this) + OrderedSet([3, 5]) + """ + items_to_remove = set() + for other in sets: + items_to_remove |= set(other) + self._update_items([item for item in self.items if item not in items_to_remove]) + + def intersection_update(self, other): + """ + Update this OrderedSet to keep only items in another set, preserving + their order in this set. + + Example: + >>> this = OrderedSet([1, 4, 3, 5, 7]) + >>> other = OrderedSet([9, 7, 1, 3, 2]) + >>> this.intersection_update(other) + >>> print(this) + OrderedSet([1, 3, 7]) + """ + other = set(other) + self._update_items([item for item in self.items if item in other]) + + def symmetric_difference_update(self, other): + """ + Update this OrderedSet to remove items from another set, then + add items from the other set that were not present in this set. + + Example: + >>> this = OrderedSet([1, 4, 3, 5, 7]) + >>> other = OrderedSet([9, 7, 1, 3, 2]) + >>> this.symmetric_difference_update(other) + >>> print(this) + OrderedSet([4, 5, 9, 2]) + """ + items_to_add = [item for item in other if item not in self] + items_to_remove = set(other) + self._update_items( + [item for item in self.items if item not in items_to_remove] + items_to_add + ) diff --git a/shared/package-files/75/75b7efbc4ac8938320faa41c24ec1b27751cfc23fcea4cbb845b9380a1b233c4/blob b/shared/package-files/75/75b7efbc4ac8938320faa41c24ec1b27751cfc23fcea4cbb845b9380a1b233c4/blob new file mode 100644 index 0000000000000000000000000000000000000000..4503566e7c63c2687cad90097b64c73fdb9bccec --- /dev/null +++ b/shared/package-files/75/75b7efbc4ac8938320faa41c24ec1b27751cfc23fcea4cbb845b9380a1b233c4/blob @@ -0,0 +1,1431 @@ +""" +View Classes provide node, edge and degree "views" of a graph. + +Views for nodes, edges and degree are provided for all base graph classes. +A view means a read-only object that is quick to create, automatically +updated when the graph changes, and provides basic access like `n in V`, +`for n in V`, `V[n]` and sometimes set operations. + +The views are read-only iterable containers that are updated as the +graph is updated. As with dicts, the graph should not be updated +while iterating through the view. Views can be iterated multiple times. + +Edge and Node views also allow data attribute lookup. +The resulting attribute dict is writable as `G.edges[3, 4]['color']='red'` +Degree views allow lookup of degree values for single nodes. +Weighted degree is supported with the `weight` argument. + +NodeView +======== + + `V = G.nodes` (or `V = G.nodes()`) allows `len(V)`, `n in V`, set + operations e.g. "G.nodes & H.nodes", and `dd = G.nodes[n]`, where + `dd` is the node data dict. Iteration is over the nodes by default. + +NodeDataView +============ + + To iterate over (node, data) pairs, use arguments to `G.nodes()` + to create a DataView e.g. `DV = G.nodes(data='color', default='red')`. + The DataView iterates as `for n, color in DV` and allows + `(n, 'red') in DV`. Using `DV = G.nodes(data=True)`, the DataViews + use the full datadict in writeable form also allowing contain testing as + `(n, {'color': 'red'}) in VD`. DataViews allow set operations when + data attributes are hashable. + +DegreeView +========== + + `V = G.degree` allows iteration over (node, degree) pairs as well + as lookup: `deg=V[n]`. There are many flavors of DegreeView + for In/Out/Directed/Multi. For Directed Graphs, `G.degree` + counts both in and out going edges. `G.out_degree` and + `G.in_degree` count only specific directions. + Weighted degree using edge data attributes is provide via + `V = G.degree(weight='attr_name')` where any string with the + attribute name can be used. `weight=None` is the default. + No set operations are implemented for degrees, use NodeView. + + The argument `nbunch` restricts iteration to nodes in nbunch. + The DegreeView can still lookup any node even if nbunch is specified. + +EdgeView +======== + + `V = G.edges` or `V = G.edges()` allows iteration over edges as well as + `e in V`, set operations and edge data lookup `dd = G.edges[2, 3]`. + Iteration is over 2-tuples `(u, v)` for Graph/DiGraph. For multigraphs + edges 3-tuples `(u, v, key)` are the default but 2-tuples can be obtained + via `V = G.edges(keys=False)`. + + Set operations for directed graphs treat the edges as a set of 2-tuples. + For undirected graphs, 2-tuples are not a unique representation of edges. + So long as the set being compared to contains unique representations + of its edges, the set operations will act as expected. If the other + set contains both `(0, 1)` and `(1, 0)` however, the result of set + operations may contain both representations of the same edge. + +EdgeDataView +============ + + Edge data can be reported using an EdgeDataView typically created + by calling an EdgeView: `DV = G.edges(data='weight', default=1)`. + The EdgeDataView allows iteration over edge tuples, membership checking + but no set operations. + + Iteration depends on `data` and `default` and for multigraph `keys` + If `data is False` (the default) then iterate over 2-tuples `(u, v)`. + If `data is True` iterate over 3-tuples `(u, v, datadict)`. + Otherwise iterate over `(u, v, datadict.get(data, default))`. + For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` + to create 3-tuples and 4-tuples. + + The argument `nbunch` restricts edges to those incident to nodes in nbunch. +""" +from collections.abc import Mapping, Set + +import networkx as nx + +__all__ = [ + "NodeView", + "NodeDataView", + "EdgeView", + "OutEdgeView", + "InEdgeView", + "EdgeDataView", + "OutEdgeDataView", + "InEdgeDataView", + "MultiEdgeView", + "OutMultiEdgeView", + "InMultiEdgeView", + "MultiEdgeDataView", + "OutMultiEdgeDataView", + "InMultiEdgeDataView", + "DegreeView", + "DiDegreeView", + "InDegreeView", + "OutDegreeView", + "MultiDegreeView", + "DiMultiDegreeView", + "InMultiDegreeView", + "OutMultiDegreeView", +] + + +# NodeViews +class NodeView(Mapping, Set): + """A NodeView class to act as G.nodes for a NetworkX Graph + + Set operations act on the nodes without considering data. + Iteration is over nodes. Node data can be looked up like a dict. + Use NodeDataView to iterate over node data or to specify a data + attribute for lookup. NodeDataView is created by calling the NodeView. + + Parameters + ---------- + graph : NetworkX graph-like class + + Examples + -------- + >>> G = nx.path_graph(3) + >>> NV = G.nodes() + >>> 2 in NV + True + >>> for n in NV: + ... print(n) + 0 + 1 + 2 + >>> assert NV & {1, 2, 3} == {1, 2} + + >>> G.add_node(2, color="blue") + >>> NV[2] + {'color': 'blue'} + >>> G.add_node(8, color="red") + >>> NDV = G.nodes(data=True) + >>> (2, NV[2]) in NDV + True + >>> for n, dd in NDV: + ... print((n, dd.get("color", "aqua"))) + (0, 'aqua') + (1, 'aqua') + (2, 'blue') + (8, 'red') + >>> NDV[2] == NV[2] + True + + >>> NVdata = G.nodes(data="color", default="aqua") + >>> (2, NVdata[2]) in NVdata + True + >>> for n, dd in NVdata: + ... print((n, dd)) + (0, 'aqua') + (1, 'aqua') + (2, 'blue') + (8, 'red') + >>> NVdata[2] == NV[2] # NVdata gets 'color', NV gets datadict + False + """ + + __slots__ = ("_nodes",) + + def __getstate__(self): + return {"_nodes": self._nodes} + + def __setstate__(self, state): + self._nodes = state["_nodes"] + + def __init__(self, graph): + self._nodes = graph._node + + # Mapping methods + def __len__(self): + return len(self._nodes) + + def __iter__(self): + return iter(self._nodes) + + def __getitem__(self, n): + if isinstance(n, slice): + raise nx.NetworkXError( + f"{type(self).__name__} does not support slicing, " + f"try list(G.nodes)[{n.start}:{n.stop}:{n.step}]" + ) + return self._nodes[n] + + # Set methods + def __contains__(self, n): + return n in self._nodes + + @classmethod + def _from_iterable(cls, it): + return set(it) + + # DataView method + def __call__(self, data=False, default=None): + if data is False: + return self + return NodeDataView(self._nodes, data, default) + + def data(self, data=True, default=None): + """ + Return a read-only view of node data. + + Parameters + ---------- + data : bool or node data key, default=True + If ``data=True`` (the default), return a `NodeDataView` object that + maps each node to *all* of its attributes. `data` may also be an + arbitrary key, in which case the `NodeDataView` maps each node to + the value for the keyed attribute. In this case, if a node does + not have the `data` attribute, the `default` value is used. + default : object, default=None + The value used when a node does not have a specific attribute. + + Returns + ------- + NodeDataView + The layout of the returned NodeDataView depends on the value of the + `data` parameter. + + Notes + ----- + If ``data=False``, returns a `NodeView` object without data. + + See Also + -------- + NodeDataView + + Examples + -------- + >>> G = nx.Graph() + >>> G.add_nodes_from([ + ... (0, {"color": "red", "weight": 10}), + ... (1, {"color": "blue"}), + ... (2, {"color": "yellow", "weight": 2}) + ... ]) + + Accessing node data with ``data=True`` (the default) returns a + NodeDataView mapping each node to all of its attributes: + + >>> G.nodes.data() + NodeDataView({0: {'color': 'red', 'weight': 10}, 1: {'color': 'blue'}, 2: {'color': 'yellow', 'weight': 2}}) + + If `data` represents a key in the node attribute dict, a NodeDataView mapping + the nodes to the value for that specific key is returned: + + >>> G.nodes.data("color") + NodeDataView({0: 'red', 1: 'blue', 2: 'yellow'}, data='color') + + If a specific key is not found in an attribute dict, the value specified + by `default` is returned: + + >>> G.nodes.data("weight", default=-999) + NodeDataView({0: 10, 1: -999, 2: 2}, data='weight') + + Note that there is no check that the `data` key is in any of the + node attribute dictionaries: + + >>> G.nodes.data("height") + NodeDataView({0: None, 1: None, 2: None}, data='height') + """ + if data is False: + return self + return NodeDataView(self._nodes, data, default) + + def __str__(self): + return str(list(self)) + + def __repr__(self): + return f"{self.__class__.__name__}({tuple(self)})" + + +class NodeDataView(Set): + """A DataView class for nodes of a NetworkX Graph + + The main use for this class is to iterate through node-data pairs. + The data can be the entire data-dictionary for each node, or it + can be a specific attribute (with default) for each node. + Set operations are enabled with NodeDataView, but don't work in + cases where the data is not hashable. Use with caution. + Typically, set operations on nodes use NodeView, not NodeDataView. + That is, they use `G.nodes` instead of `G.nodes(data='foo')`. + + Parameters + ========== + graph : NetworkX graph-like class + data : bool or string (default=False) + default : object (default=None) + """ + + __slots__ = ("_nodes", "_data", "_default") + + def __getstate__(self): + return {"_nodes": self._nodes, "_data": self._data, "_default": self._default} + + def __setstate__(self, state): + self._nodes = state["_nodes"] + self._data = state["_data"] + self._default = state["_default"] + + def __init__(self, nodedict, data=False, default=None): + self._nodes = nodedict + self._data = data + self._default = default + + @classmethod + def _from_iterable(cls, it): + try: + return set(it) + except TypeError as err: + if "unhashable" in str(err): + msg = " : Could be b/c data=True or your values are unhashable" + raise TypeError(str(err) + msg) from err + raise + + def __len__(self): + return len(self._nodes) + + def __iter__(self): + data = self._data + if data is False: + return iter(self._nodes) + if data is True: + return iter(self._nodes.items()) + return ( + (n, dd[data] if data in dd else self._default) + for n, dd in self._nodes.items() + ) + + def __contains__(self, n): + try: + node_in = n in self._nodes + except TypeError: + n, d = n + return n in self._nodes and self[n] == d + if node_in is True: + return node_in + try: + n, d = n + except (TypeError, ValueError): + return False + return n in self._nodes and self[n] == d + + def __getitem__(self, n): + if isinstance(n, slice): + raise nx.NetworkXError( + f"{type(self).__name__} does not support slicing, " + f"try list(G.nodes.data())[{n.start}:{n.stop}:{n.step}]" + ) + ddict = self._nodes[n] + data = self._data + if data is False or data is True: + return ddict + return ddict[data] if data in ddict else self._default + + def __str__(self): + return str(list(self)) + + def __repr__(self): + name = self.__class__.__name__ + if self._data is False: + return f"{name}({tuple(self)})" + if self._data is True: + return f"{name}({dict(self)})" + return f"{name}({dict(self)}, data={self._data!r})" + + +# DegreeViews +class DiDegreeView: + """A View class for degree of nodes in a NetworkX Graph + + The functionality is like dict.items() with (node, degree) pairs. + Additional functionality includes read-only lookup of node degree, + and calling with optional features nbunch (for only a subset of nodes) + and weight (use edge weights to compute degree). + + Parameters + ========== + graph : NetworkX graph-like class + nbunch : node, container of nodes, or None meaning all nodes (default=None) + weight : bool or string (default=None) + + Notes + ----- + DegreeView can still lookup any node even if nbunch is specified. + + Examples + -------- + >>> G = nx.path_graph(3) + >>> DV = G.degree() + >>> assert DV[2] == 1 + >>> assert sum(deg for n, deg in DV) == 4 + + >>> DVweight = G.degree(weight="span") + >>> G.add_edge(1, 2, span=34) + >>> DVweight[2] + 34 + >>> DVweight[0] # default edge weight is 1 + 1 + >>> sum(span for n, span in DVweight) # sum weighted degrees + 70 + + >>> DVnbunch = G.degree(nbunch=(1, 2)) + >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only + """ + + def __init__(self, G, nbunch=None, weight=None): + self._graph = G + self._succ = G._succ if hasattr(G, "_succ") else G._adj + self._pred = G._pred if hasattr(G, "_pred") else G._adj + self._nodes = self._succ if nbunch is None else list(G.nbunch_iter(nbunch)) + self._weight = weight + + def __call__(self, nbunch=None, weight=None): + if nbunch is None: + if weight == self._weight: + return self + return self.__class__(self._graph, None, weight) + try: + if nbunch in self._nodes: + if weight == self._weight: + return self[nbunch] + return self.__class__(self._graph, None, weight)[nbunch] + except TypeError: + pass + return self.__class__(self._graph, nbunch, weight) + + def __getitem__(self, n): + weight = self._weight + succs = self._succ[n] + preds = self._pred[n] + if weight is None: + return len(succs) + len(preds) + return sum(dd.get(weight, 1) for dd in succs.values()) + sum( + dd.get(weight, 1) for dd in preds.values() + ) + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + succs = self._succ[n] + preds = self._pred[n] + yield (n, len(succs) + len(preds)) + else: + for n in self._nodes: + succs = self._succ[n] + preds = self._pred[n] + deg = sum(dd.get(weight, 1) for dd in succs.values()) + sum( + dd.get(weight, 1) for dd in preds.values() + ) + yield (n, deg) + + def __len__(self): + return len(self._nodes) + + def __str__(self): + return str(list(self)) + + def __repr__(self): + return f"{self.__class__.__name__}({dict(self)})" + + +class DegreeView(DiDegreeView): + """A DegreeView class to act as G.degree for a NetworkX Graph + + Typical usage focuses on iteration over `(node, degree)` pairs. + The degree is by default the number of edges incident to the node. + Optional argument `weight` enables weighted degree using the edge + attribute named in the `weight` argument. Reporting and iteration + can also be restricted to a subset of nodes using `nbunch`. + + Additional functionality include node lookup so that `G.degree[n]` + reported the (possibly weighted) degree of node `n`. Calling the + view creates a view with different arguments `nbunch` or `weight`. + + Parameters + ========== + graph : NetworkX graph-like class + nbunch : node, container of nodes, or None meaning all nodes (default=None) + weight : string or None (default=None) + + Notes + ----- + DegreeView can still lookup any node even if nbunch is specified. + + Examples + -------- + >>> G = nx.path_graph(3) + >>> DV = G.degree() + >>> assert DV[2] == 1 + >>> assert G.degree[2] == 1 + >>> assert sum(deg for n, deg in DV) == 4 + + >>> DVweight = G.degree(weight="span") + >>> G.add_edge(1, 2, span=34) + >>> DVweight[2] + 34 + >>> DVweight[0] # default edge weight is 1 + 1 + >>> sum(span for n, span in DVweight) # sum weighted degrees + 70 + + >>> DVnbunch = G.degree(nbunch=(1, 2)) + >>> assert len(list(DVnbunch)) == 2 # iteration over nbunch only + """ + + def __getitem__(self, n): + weight = self._weight + nbrs = self._succ[n] + if weight is None: + return len(nbrs) + (n in nbrs) + return sum(dd.get(weight, 1) for dd in nbrs.values()) + ( + n in nbrs and nbrs[n].get(weight, 1) + ) + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + nbrs = self._succ[n] + yield (n, len(nbrs) + (n in nbrs)) + else: + for n in self._nodes: + nbrs = self._succ[n] + deg = sum(dd.get(weight, 1) for dd in nbrs.values()) + ( + n in nbrs and nbrs[n].get(weight, 1) + ) + yield (n, deg) + + +class OutDegreeView(DiDegreeView): + """A DegreeView class to report out_degree for a DiGraph; See DegreeView""" + + def __getitem__(self, n): + weight = self._weight + nbrs = self._succ[n] + if self._weight is None: + return len(nbrs) + return sum(dd.get(self._weight, 1) for dd in nbrs.values()) + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + succs = self._succ[n] + yield (n, len(succs)) + else: + for n in self._nodes: + succs = self._succ[n] + deg = sum(dd.get(weight, 1) for dd in succs.values()) + yield (n, deg) + + +class InDegreeView(DiDegreeView): + """A DegreeView class to report in_degree for a DiGraph; See DegreeView""" + + def __getitem__(self, n): + weight = self._weight + nbrs = self._pred[n] + if weight is None: + return len(nbrs) + return sum(dd.get(weight, 1) for dd in nbrs.values()) + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + preds = self._pred[n] + yield (n, len(preds)) + else: + for n in self._nodes: + preds = self._pred[n] + deg = sum(dd.get(weight, 1) for dd in preds.values()) + yield (n, deg) + + +class MultiDegreeView(DiDegreeView): + """A DegreeView class for undirected multigraphs; See DegreeView""" + + def __getitem__(self, n): + weight = self._weight + nbrs = self._succ[n] + if weight is None: + return sum(len(keys) for keys in nbrs.values()) + ( + n in nbrs and len(nbrs[n]) + ) + # edge weighted graph - degree is sum of nbr edge weights + deg = sum( + d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() + ) + if n in nbrs: + deg += sum(d.get(weight, 1) for d in nbrs[n].values()) + return deg + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + nbrs = self._succ[n] + deg = sum(len(keys) for keys in nbrs.values()) + ( + n in nbrs and len(nbrs[n]) + ) + yield (n, deg) + else: + for n in self._nodes: + nbrs = self._succ[n] + deg = sum( + d.get(weight, 1) + for key_dict in nbrs.values() + for d in key_dict.values() + ) + if n in nbrs: + deg += sum(d.get(weight, 1) for d in nbrs[n].values()) + yield (n, deg) + + +class DiMultiDegreeView(DiDegreeView): + """A DegreeView class for MultiDiGraph; See DegreeView""" + + def __getitem__(self, n): + weight = self._weight + succs = self._succ[n] + preds = self._pred[n] + if weight is None: + return sum(len(keys) for keys in succs.values()) + sum( + len(keys) for keys in preds.values() + ) + # edge weighted graph - degree is sum of nbr edge weights + deg = sum( + d.get(weight, 1) for key_dict in succs.values() for d in key_dict.values() + ) + sum( + d.get(weight, 1) for key_dict in preds.values() for d in key_dict.values() + ) + return deg + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + succs = self._succ[n] + preds = self._pred[n] + deg = sum(len(keys) for keys in succs.values()) + sum( + len(keys) for keys in preds.values() + ) + yield (n, deg) + else: + for n in self._nodes: + succs = self._succ[n] + preds = self._pred[n] + deg = sum( + d.get(weight, 1) + for key_dict in succs.values() + for d in key_dict.values() + ) + sum( + d.get(weight, 1) + for key_dict in preds.values() + for d in key_dict.values() + ) + yield (n, deg) + + +class InMultiDegreeView(DiDegreeView): + """A DegreeView class for inward degree of MultiDiGraph; See DegreeView""" + + def __getitem__(self, n): + weight = self._weight + nbrs = self._pred[n] + if weight is None: + return sum(len(data) for data in nbrs.values()) + # edge weighted graph - degree is sum of nbr edge weights + return sum( + d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() + ) + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + nbrs = self._pred[n] + deg = sum(len(data) for data in nbrs.values()) + yield (n, deg) + else: + for n in self._nodes: + nbrs = self._pred[n] + deg = sum( + d.get(weight, 1) + for key_dict in nbrs.values() + for d in key_dict.values() + ) + yield (n, deg) + + +class OutMultiDegreeView(DiDegreeView): + """A DegreeView class for outward degree of MultiDiGraph; See DegreeView""" + + def __getitem__(self, n): + weight = self._weight + nbrs = self._succ[n] + if weight is None: + return sum(len(data) for data in nbrs.values()) + # edge weighted graph - degree is sum of nbr edge weights + return sum( + d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() + ) + + def __iter__(self): + weight = self._weight + if weight is None: + for n in self._nodes: + nbrs = self._succ[n] + deg = sum(len(data) for data in nbrs.values()) + yield (n, deg) + else: + for n in self._nodes: + nbrs = self._succ[n] + deg = sum( + d.get(weight, 1) + for key_dict in nbrs.values() + for d in key_dict.values() + ) + yield (n, deg) + + +# EdgeDataViews +class OutEdgeDataView: + """EdgeDataView for outward edges of DiGraph; See EdgeDataView""" + + __slots__ = ( + "_viewer", + "_nbunch", + "_data", + "_default", + "_adjdict", + "_nodes_nbrs", + "_report", + ) + + def __getstate__(self): + return { + "viewer": self._viewer, + "nbunch": self._nbunch, + "data": self._data, + "default": self._default, + } + + def __setstate__(self, state): + self.__init__(**state) + + def __init__(self, viewer, nbunch=None, data=False, default=None): + self._viewer = viewer + adjdict = self._adjdict = viewer._adjdict + if nbunch is None: + self._nodes_nbrs = adjdict.items + else: + # dict retains order of nodes but acts like a set + nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch)) + self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch] + self._nbunch = nbunch + self._data = data + self._default = default + # Set _report based on data and default + if data is True: + self._report = lambda n, nbr, dd: (n, nbr, dd) + elif data is False: + self._report = lambda n, nbr, dd: (n, nbr) + else: # data is attribute name + self._report = ( + lambda n, nbr, dd: (n, nbr, dd[data]) + if data in dd + else (n, nbr, default) + ) + + def __len__(self): + return sum(len(nbrs) for n, nbrs in self._nodes_nbrs()) + + def __iter__(self): + return ( + self._report(n, nbr, dd) + for n, nbrs in self._nodes_nbrs() + for nbr, dd in nbrs.items() + ) + + def __contains__(self, e): + u, v = e[:2] + if self._nbunch is not None and u not in self._nbunch: + return False # this edge doesn't start in nbunch + try: + ddict = self._adjdict[u][v] + except KeyError: + return False + return e == self._report(u, v, ddict) + + def __str__(self): + return str(list(self)) + + def __repr__(self): + return f"{self.__class__.__name__}({list(self)})" + + +class EdgeDataView(OutEdgeDataView): + """A EdgeDataView class for edges of Graph + + This view is primarily used to iterate over the edges reporting + edges as node-tuples with edge data optionally reported. The + argument `nbunch` allows restriction to edges incident to nodes + in that container/singleton. The default (nbunch=None) + reports all edges. The arguments `data` and `default` control + what edge data is reported. The default `data is False` reports + only node-tuples for each edge. If `data is True` the entire edge + data dict is returned. Otherwise `data` is assumed to hold the name + of the edge attribute to report with default `default` if that + edge attribute is not present. + + Parameters + ---------- + nbunch : container of nodes, node or None (default None) + data : False, True or string (default False) + default : default value (default None) + + Examples + -------- + >>> G = nx.path_graph(3) + >>> G.add_edge(1, 2, foo="bar") + >>> list(G.edges(data="foo", default="biz")) + [(0, 1, 'biz'), (1, 2, 'bar')] + >>> assert (0, 1, "biz") in G.edges(data="foo", default="biz") + """ + + __slots__ = () + + def __len__(self): + return sum(1 for e in self) + + def __iter__(self): + seen = {} + for n, nbrs in self._nodes_nbrs(): + for nbr, dd in nbrs.items(): + if nbr not in seen: + yield self._report(n, nbr, dd) + seen[n] = 1 + del seen + + def __contains__(self, e): + u, v = e[:2] + if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch: + return False # this edge doesn't start and it doesn't end in nbunch + try: + ddict = self._adjdict[u][v] + except KeyError: + return False + return e == self._report(u, v, ddict) + + +class InEdgeDataView(OutEdgeDataView): + """An EdgeDataView class for outward edges of DiGraph; See EdgeDataView""" + + __slots__ = () + + def __iter__(self): + return ( + self._report(nbr, n, dd) + for n, nbrs in self._nodes_nbrs() + for nbr, dd in nbrs.items() + ) + + def __contains__(self, e): + u, v = e[:2] + if self._nbunch is not None and v not in self._nbunch: + return False # this edge doesn't end in nbunch + try: + ddict = self._adjdict[v][u] + except KeyError: + return False + return e == self._report(u, v, ddict) + + +class OutMultiEdgeDataView(OutEdgeDataView): + """An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView""" + + __slots__ = ("keys",) + + def __getstate__(self): + return { + "viewer": self._viewer, + "nbunch": self._nbunch, + "keys": self.keys, + "data": self._data, + "default": self._default, + } + + def __setstate__(self, state): + self.__init__(**state) + + def __init__(self, viewer, nbunch=None, data=False, keys=False, default=None): + self._viewer = viewer + adjdict = self._adjdict = viewer._adjdict + self.keys = keys + if nbunch is None: + self._nodes_nbrs = adjdict.items + else: + # dict retains order of nodes but acts like a set + nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch)) + self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch] + self._nbunch = nbunch + self._data = data + self._default = default + # Set _report based on data and default + if data is True: + if keys is True: + self._report = lambda n, nbr, k, dd: (n, nbr, k, dd) + else: + self._report = lambda n, nbr, k, dd: (n, nbr, dd) + elif data is False: + if keys is True: + self._report = lambda n, nbr, k, dd: (n, nbr, k) + else: + self._report = lambda n, nbr, k, dd: (n, nbr) + else: # data is attribute name + if keys is True: + self._report = ( + lambda n, nbr, k, dd: (n, nbr, k, dd[data]) + if data in dd + else (n, nbr, k, default) + ) + else: + self._report = ( + lambda n, nbr, k, dd: (n, nbr, dd[data]) + if data in dd + else (n, nbr, default) + ) + + def __len__(self): + return sum(1 for e in self) + + def __iter__(self): + return ( + self._report(n, nbr, k, dd) + for n, nbrs in self._nodes_nbrs() + for nbr, kd in nbrs.items() + for k, dd in kd.items() + ) + + def __contains__(self, e): + u, v = e[:2] + if self._nbunch is not None and u not in self._nbunch: + return False # this edge doesn't start in nbunch + try: + kdict = self._adjdict[u][v] + except KeyError: + return False + if self.keys is True: + k = e[2] + try: + dd = kdict[k] + except KeyError: + return False + return e == self._report(u, v, k, dd) + return any(e == self._report(u, v, k, dd) for k, dd in kdict.items()) + + +class MultiEdgeDataView(OutMultiEdgeDataView): + """An EdgeDataView class for edges of MultiGraph; See EdgeDataView""" + + __slots__ = () + + def __iter__(self): + seen = {} + for n, nbrs in self._nodes_nbrs(): + for nbr, kd in nbrs.items(): + if nbr not in seen: + for k, dd in kd.items(): + yield self._report(n, nbr, k, dd) + seen[n] = 1 + del seen + + def __contains__(self, e): + u, v = e[:2] + if self._nbunch is not None and u not in self._nbunch and v not in self._nbunch: + return False # this edge doesn't start and doesn't end in nbunch + try: + kdict = self._adjdict[u][v] + except KeyError: + try: + kdict = self._adjdict[v][u] + except KeyError: + return False + if self.keys is True: + k = e[2] + try: + dd = kdict[k] + except KeyError: + return False + return e == self._report(u, v, k, dd) + return any(e == self._report(u, v, k, dd) for k, dd in kdict.items()) + + +class InMultiEdgeDataView(OutMultiEdgeDataView): + """An EdgeDataView for inward edges of MultiDiGraph; See EdgeDataView""" + + __slots__ = () + + def __iter__(self): + return ( + self._report(nbr, n, k, dd) + for n, nbrs in self._nodes_nbrs() + for nbr, kd in nbrs.items() + for k, dd in kd.items() + ) + + def __contains__(self, e): + u, v = e[:2] + if self._nbunch is not None and v not in self._nbunch: + return False # this edge doesn't end in nbunch + try: + kdict = self._adjdict[v][u] + except KeyError: + return False + if self.keys is True: + k = e[2] + dd = kdict[k] + return e == self._report(u, v, k, dd) + return any(e == self._report(u, v, k, dd) for k, dd in kdict.items()) + + +# EdgeViews have set operations and no data reported +class OutEdgeView(Set, Mapping): + """A EdgeView class for outward edges of a DiGraph""" + + __slots__ = ("_adjdict", "_graph", "_nodes_nbrs") + + def __getstate__(self): + return {"_graph": self._graph, "_adjdict": self._adjdict} + + def __setstate__(self, state): + self._graph = state["_graph"] + self._adjdict = state["_adjdict"] + self._nodes_nbrs = self._adjdict.items + + @classmethod + def _from_iterable(cls, it): + return set(it) + + dataview = OutEdgeDataView + + def __init__(self, G): + self._graph = G + self._adjdict = G._succ if hasattr(G, "succ") else G._adj + self._nodes_nbrs = self._adjdict.items + + # Set methods + def __len__(self): + return sum(len(nbrs) for n, nbrs in self._nodes_nbrs()) + + def __iter__(self): + for n, nbrs in self._nodes_nbrs(): + for nbr in nbrs: + yield (n, nbr) + + def __contains__(self, e): + try: + u, v = e + return v in self._adjdict[u] + except KeyError: + return False + + # Mapping Methods + def __getitem__(self, e): + if isinstance(e, slice): + raise nx.NetworkXError( + f"{type(self).__name__} does not support slicing, " + f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]" + ) + u, v = e + return self._adjdict[u][v] + + # EdgeDataView methods + def __call__(self, nbunch=None, data=False, default=None): + if nbunch is None and data is False: + return self + return self.dataview(self, nbunch, data, default) + + def data(self, data=True, default=None, nbunch=None): + """ + Return a read-only view of edge data. + + Parameters + ---------- + data : bool or edge attribute key + If ``data=True``, then the data view maps each edge to a dictionary + containing all of its attributes. If `data` is a key in the edge + dictionary, then the data view maps each edge to its value for + the keyed attribute. In this case, if the edge doesn't have the + attribute, the `default` value is returned. + default : object, default=None + The value used when an edge does not have a specific attribute + nbunch : container of nodes, optional (default=None) + Allows restriction to edges only involving certain nodes. All edges + are considered by default. + + Returns + ------- + dataview + Returns an `EdgeDataView` for undirected Graphs, `OutEdgeDataView` + for DiGraphs, `MultiEdgeDataView` for MultiGraphs and + `OutMultiEdgeDataView` for MultiDiGraphs. + + Notes + ----- + If ``data=False``, returns an `EdgeView` without any edge data. + + See Also + -------- + EdgeDataView + OutEdgeDataView + MultiEdgeDataView + OutMultiEdgeDataView + + Examples + -------- + >>> G = nx.Graph() + >>> G.add_edges_from([ + ... (0, 1, {"dist": 3, "capacity": 20}), + ... (1, 2, {"dist": 4}), + ... (2, 0, {"dist": 5}) + ... ]) + + Accessing edge data with ``data=True`` (the default) returns an + edge data view object listing each edge with all of its attributes: + + >>> G.edges.data() + EdgeDataView([(0, 1, {'dist': 3, 'capacity': 20}), (0, 2, {'dist': 5}), (1, 2, {'dist': 4})]) + + If `data` represents a key in the edge attribute dict, a dataview listing + each edge with its value for that specific key is returned: + + >>> G.edges.data("dist") + EdgeDataView([(0, 1, 3), (0, 2, 5), (1, 2, 4)]) + + `nbunch` can be used to limit the edges: + + >>> G.edges.data("dist", nbunch=[0]) + EdgeDataView([(0, 1, 3), (0, 2, 5)]) + + If a specific key is not found in an edge attribute dict, the value + specified by `default` is used: + + >>> G.edges.data("capacity") + EdgeDataView([(0, 1, 20), (0, 2, None), (1, 2, None)]) + + Note that there is no check that the `data` key is present in any of + the edge attribute dictionaries: + + >>> G.edges.data("speed") + EdgeDataView([(0, 1, None), (0, 2, None), (1, 2, None)]) + """ + if nbunch is None and data is False: + return self + return self.dataview(self, nbunch, data, default) + + # String Methods + def __str__(self): + return str(list(self)) + + def __repr__(self): + return f"{self.__class__.__name__}({list(self)})" + + +class EdgeView(OutEdgeView): + """A EdgeView class for edges of a Graph + + This densely packed View allows iteration over edges, data lookup + like a dict and set operations on edges represented by node-tuples. + In addition, edge data can be controlled by calling this object + possibly creating an EdgeDataView. Typically edges are iterated over + and reported as `(u, v)` node tuples or `(u, v, key)` node/key tuples + for multigraphs. Those edge representations can also be using to + lookup the data dict for any edge. Set operations also are available + where those tuples are the elements of the set. + Calling this object with optional arguments `data`, `default` and `keys` + controls the form of the tuple (see EdgeDataView). Optional argument + `nbunch` allows restriction to edges only involving certain nodes. + + If `data is False` (the default) then iterate over 2-tuples `(u, v)`. + If `data is True` iterate over 3-tuples `(u, v, datadict)`. + Otherwise iterate over `(u, v, datadict.get(data, default))`. + For Multigraphs, if `keys is True`, replace `u, v` with `u, v, key` above. + + Parameters + ========== + graph : NetworkX graph-like class + nbunch : (default= all nodes in graph) only report edges with these nodes + keys : (only for MultiGraph. default=False) report edge key in tuple + data : bool or string (default=False) see above + default : object (default=None) + + Examples + ======== + >>> G = nx.path_graph(4) + >>> EV = G.edges() + >>> (2, 3) in EV + True + >>> for u, v in EV: + ... print((u, v)) + (0, 1) + (1, 2) + (2, 3) + >>> assert EV & {(1, 2), (3, 4)} == {(1, 2)} + + >>> EVdata = G.edges(data="color", default="aqua") + >>> G.add_edge(2, 3, color="blue") + >>> assert (2, 3, "blue") in EVdata + >>> for u, v, c in EVdata: + ... print(f"({u}, {v}) has color: {c}") + (0, 1) has color: aqua + (1, 2) has color: aqua + (2, 3) has color: blue + + >>> EVnbunch = G.edges(nbunch=2) + >>> assert (2, 3) in EVnbunch + >>> assert (0, 1) not in EVnbunch + >>> for u, v in EVnbunch: + ... assert u == 2 or v == 2 + + >>> MG = nx.path_graph(4, create_using=nx.MultiGraph) + >>> EVmulti = MG.edges(keys=True) + >>> (2, 3, 0) in EVmulti + True + >>> (2, 3) in EVmulti # 2-tuples work even when keys is True + True + >>> key = MG.add_edge(2, 3) + >>> for u, v, k in EVmulti: + ... print((u, v, k)) + (0, 1, 0) + (1, 2, 0) + (2, 3, 0) + (2, 3, 1) + """ + + __slots__ = () + + dataview = EdgeDataView + + def __len__(self): + num_nbrs = (len(nbrs) + (n in nbrs) for n, nbrs in self._nodes_nbrs()) + return sum(num_nbrs) // 2 + + def __iter__(self): + seen = {} + for n, nbrs in self._nodes_nbrs(): + for nbr in list(nbrs): + if nbr not in seen: + yield (n, nbr) + seen[n] = 1 + del seen + + def __contains__(self, e): + try: + u, v = e[:2] + return v in self._adjdict[u] or u in self._adjdict[v] + except (KeyError, ValueError): + return False + + +class InEdgeView(OutEdgeView): + """A EdgeView class for inward edges of a DiGraph""" + + __slots__ = () + + def __setstate__(self, state): + self._graph = state["_graph"] + self._adjdict = state["_adjdict"] + self._nodes_nbrs = self._adjdict.items + + dataview = InEdgeDataView + + def __init__(self, G): + self._graph = G + self._adjdict = G._pred if hasattr(G, "pred") else G._adj + self._nodes_nbrs = self._adjdict.items + + def __iter__(self): + for n, nbrs in self._nodes_nbrs(): + for nbr in nbrs: + yield (nbr, n) + + def __contains__(self, e): + try: + u, v = e + return u in self._adjdict[v] + except KeyError: + return False + + def __getitem__(self, e): + if isinstance(e, slice): + raise nx.NetworkXError( + f"{type(self).__name__} does not support slicing, " + f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]" + ) + u, v = e + return self._adjdict[v][u] + + +class OutMultiEdgeView(OutEdgeView): + """A EdgeView class for outward edges of a MultiDiGraph""" + + __slots__ = () + + dataview = OutMultiEdgeDataView + + def __len__(self): + return sum( + len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items() + ) + + def __iter__(self): + for n, nbrs in self._nodes_nbrs(): + for nbr, kdict in nbrs.items(): + for key in kdict: + yield (n, nbr, key) + + def __contains__(self, e): + N = len(e) + if N == 3: + u, v, k = e + elif N == 2: + u, v = e + k = 0 + else: + raise ValueError("MultiEdge must have length 2 or 3") + try: + return k in self._adjdict[u][v] + except KeyError: + return False + + def __getitem__(self, e): + if isinstance(e, slice): + raise nx.NetworkXError( + f"{type(self).__name__} does not support slicing, " + f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]" + ) + u, v, k = e + return self._adjdict[u][v][k] + + def __call__(self, nbunch=None, data=False, keys=False, default=None): + if nbunch is None and data is False and keys is True: + return self + return self.dataview(self, nbunch, data, keys, default) + + def data(self, data=True, keys=False, default=None, nbunch=None): + if nbunch is None and data is False and keys is True: + return self + return self.dataview(self, nbunch, data, keys, default) + + +class MultiEdgeView(OutMultiEdgeView): + """A EdgeView class for edges of a MultiGraph""" + + __slots__ = () + + dataview = MultiEdgeDataView + + def __len__(self): + return sum(1 for e in self) + + def __iter__(self): + seen = {} + for n, nbrs in self._nodes_nbrs(): + for nbr, kd in nbrs.items(): + if nbr not in seen: + for k, dd in kd.items(): + yield (n, nbr, k) + seen[n] = 1 + del seen + + +class InMultiEdgeView(OutMultiEdgeView): + """A EdgeView class for inward edges of a MultiDiGraph""" + + __slots__ = () + + def __setstate__(self, state): + self._graph = state["_graph"] + self._adjdict = state["_adjdict"] + self._nodes_nbrs = self._adjdict.items + + dataview = InMultiEdgeDataView + + def __init__(self, G): + self._graph = G + self._adjdict = G._pred if hasattr(G, "pred") else G._adj + self._nodes_nbrs = self._adjdict.items + + def __iter__(self): + for n, nbrs in self._nodes_nbrs(): + for nbr, kdict in nbrs.items(): + for key in kdict: + yield (nbr, n, key) + + def __contains__(self, e): + N = len(e) + if N == 3: + u, v, k = e + elif N == 2: + u, v = e + k = 0 + else: + raise ValueError("MultiEdge must have length 2 or 3") + try: + return k in self._adjdict[v][u] + except KeyError: + return False + + def __getitem__(self, e): + if isinstance(e, slice): + raise nx.NetworkXError( + f"{type(self).__name__} does not support slicing, " + f"try list(G.in_edges)[{e.start}:{e.stop}:{e.step}]" + ) + u, v, k = e + return self._adjdict[v][u][k] diff --git a/shared/package-files/75/75b8c68841c0041f192ba72de64223e372d29a136e4c8bd3573205c1eb9755e1/blob b/shared/package-files/75/75b8c68841c0041f192ba72de64223e372d29a136e4c8bd3573205c1eb9755e1/blob new file mode 100644 index 0000000000000000000000000000000000000000..f17a0ae75b0416e4d9e37f84cb15a70e32413689 --- /dev/null +++ b/shared/package-files/75/75b8c68841c0041f192ba72de64223e372d29a136e4c8bd3573205c1eb9755e1/blob @@ -0,0 +1,17 @@ +from statsmodels.tsa.holtwinters.model import ( + PY_SMOOTHERS, + SMOOTHERS, + ExponentialSmoothing, + Holt, + SimpleExpSmoothing, +) +from statsmodels.tsa.holtwinters.results import HoltWintersResults + +__all__ = [ + "PY_SMOOTHERS", + "SMOOTHERS", + "ExponentialSmoothing", + "Holt", + "HoltWintersResults", + "SimpleExpSmoothing", +] diff --git a/shared/package-files/75/75b8e0e428594f6dca6bdcfd0c73977ddb52a4fc147dd80c5e78fc34ea25cbec/blob b/shared/package-files/75/75b8e0e428594f6dca6bdcfd0c73977ddb52a4fc147dd80c5e78fc34ea25cbec/blob new file mode 100644 index 0000000000000000000000000000000000000000..994bb7493fd92865e6ab87c277ba5741b44c31a9 --- /dev/null +++ b/shared/package-files/75/75b8e0e428594f6dca6bdcfd0c73977ddb52a4fc147dd80c5e78fc34ea25cbec/blob @@ -0,0 +1,107 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: 2021 Taneli Hukkinen +# Licensed to PSF under a Contributor Agreement. + +from __future__ import annotations + +from datetime import date, datetime, time, timedelta, timezone, tzinfo +from functools import lru_cache +import re +from typing import Any + +from ._types import ParseFloat + +# E.g. +# - 00:32:00.999999 +# - 00:32:00 +_TIME_RE_STR = r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?" + +RE_NUMBER = re.compile( + r""" +0 +(?: + x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex + | + b[01](?:_?[01])* # bin + | + o[0-7](?:_?[0-7])* # oct +) +| +[+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part +(?P + (?:\.[0-9](?:_?[0-9])*)? # optional fractional part + (?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part +) +""", + flags=re.VERBOSE, +) +RE_LOCALTIME = re.compile(_TIME_RE_STR) +RE_DATETIME = re.compile( + rf""" +([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27 +(?: + [Tt ] + {_TIME_RE_STR} + (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset +)? +""", + flags=re.VERBOSE, +) + + +def match_to_datetime(match: re.Match) -> datetime | date: + """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`. + + Raises ValueError if the match does not correspond to a valid date + or datetime. + """ + ( + year_str, + month_str, + day_str, + hour_str, + minute_str, + sec_str, + micros_str, + zulu_time, + offset_sign_str, + offset_hour_str, + offset_minute_str, + ) = match.groups() + year, month, day = int(year_str), int(month_str), int(day_str) + if hour_str is None: + return date(year, month, day) + hour, minute, sec = int(hour_str), int(minute_str), int(sec_str) + micros = int(micros_str.ljust(6, "0")) if micros_str else 0 + if offset_sign_str: + tz: tzinfo | None = cached_tz( + offset_hour_str, offset_minute_str, offset_sign_str + ) + elif zulu_time: + tz = timezone.utc + else: # local date-time + tz = None + return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz) + + +@lru_cache(maxsize=None) +def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone: + sign = 1 if sign_str == "+" else -1 + return timezone( + timedelta( + hours=sign * int(hour_str), + minutes=sign * int(minute_str), + ) + ) + + +def match_to_localtime(match: re.Match) -> time: + hour_str, minute_str, sec_str, micros_str = match.groups() + micros = int(micros_str.ljust(6, "0")) if micros_str else 0 + return time(int(hour_str), int(minute_str), int(sec_str), micros) + + +def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any: + if match.group("floatpart"): + return parse_float(match.group()) + return int(match.group(), 0) diff --git a/shared/package-files/75/75b9a0df9cf01703d289847ee4eb9203bf74b2504472df0de82d639045dc841b/blob b/shared/package-files/75/75b9a0df9cf01703d289847ee4eb9203bf74b2504472df0de82d639045dc841b/blob new file mode 100644 index 0000000000000000000000000000000000000000..73c4d8061c25789c1ec2a5e4d2c2851d4066a90e --- /dev/null +++ b/shared/package-files/75/75b9a0df9cf01703d289847ee4eb9203bf74b2504472df0de82d639045dc841b/blob @@ -0,0 +1,828 @@ +import pytest + +from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG +from pandas.errors import OutOfBoundsDatetime + +from pandas import ( + Period, + Timestamp, + offsets, +) +import pandas._testing as tm + +bday_msg = "Period with BDay freq is deprecated" + + +class TestFreqConversion: + """Test frequency conversion of date objects""" + + @pytest.mark.filterwarnings("ignore:Period with BDay:FutureWarning") + @pytest.mark.parametrize("freq", ["Y", "Q", "M", "W", "B", "D"]) + def test_asfreq_near_zero(self, freq): + # GH#19643, GH#19650 + per = Period("0001-01-01", freq=freq) + tup1 = (per.year, per.hour, per.day) + + prev = per - 1 + assert prev.ordinal == per.ordinal - 1 + tup2 = (prev.year, prev.month, prev.day) + assert tup2 < tup1 + + def test_asfreq_near_zero_weekly(self): + # GH#19834 + per1 = Period("0001-01-01", "D") + 6 + per2 = Period("0001-01-01", "D") - 6 + week1 = per1.asfreq("W") + week2 = per2.asfreq("W") + assert week1 != week2 + assert week1.asfreq("D", "E") >= per1 + assert week2.asfreq("D", "S") <= per2 + + def test_to_timestamp_out_of_bounds(self): + # GH#19643, used to incorrectly give Timestamp in 1754 + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per = Period("0001-01-01", freq="B") + msg = "Out of bounds nanosecond timestamp" + with pytest.raises(OutOfBoundsDatetime, match=msg): + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + per.to_timestamp() + + def test_asfreq_corner(self): + val = Period(freq="Y", year=2007) + result1 = val.asfreq("5min") + result2 = val.asfreq("min") + expected = Period("2007-12-31 23:59", freq="min") + assert result1.ordinal == expected.ordinal + assert result1.freqstr == "5min" + assert result2.ordinal == expected.ordinal + assert result2.freqstr == "min" + + def test_conv_annual(self): + # frequency conversion tests: from Annual Frequency + + ival_A = Period(freq="Y", year=2007) + + ival_AJAN = Period(freq="Y-JAN", year=2007) + ival_AJUN = Period(freq="Y-JUN", year=2007) + ival_ANOV = Period(freq="Y-NOV", year=2007) + + ival_A_to_Q_start = Period(freq="Q", year=2007, quarter=1) + ival_A_to_Q_end = Period(freq="Q", year=2007, quarter=4) + ival_A_to_M_start = Period(freq="M", year=2007, month=1) + ival_A_to_M_end = Period(freq="M", year=2007, month=12) + ival_A_to_W_start = Period(freq="W", year=2007, month=1, day=1) + ival_A_to_W_end = Period(freq="W", year=2007, month=12, day=31) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_A_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_A_to_B_end = Period(freq="B", year=2007, month=12, day=31) + ival_A_to_D_start = Period(freq="D", year=2007, month=1, day=1) + ival_A_to_D_end = Period(freq="D", year=2007, month=12, day=31) + ival_A_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_A_to_H_end = Period(freq="h", year=2007, month=12, day=31, hour=23) + ival_A_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_A_to_T_end = Period( + freq="Min", year=2007, month=12, day=31, hour=23, minute=59 + ) + ival_A_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_A_to_S_end = Period( + freq="s", year=2007, month=12, day=31, hour=23, minute=59, second=59 + ) + + ival_AJAN_to_D_end = Period(freq="D", year=2007, month=1, day=31) + ival_AJAN_to_D_start = Period(freq="D", year=2006, month=2, day=1) + ival_AJUN_to_D_end = Period(freq="D", year=2007, month=6, day=30) + ival_AJUN_to_D_start = Period(freq="D", year=2006, month=7, day=1) + ival_ANOV_to_D_end = Period(freq="D", year=2007, month=11, day=30) + ival_ANOV_to_D_start = Period(freq="D", year=2006, month=12, day=1) + + assert ival_A.asfreq("Q", "s") == ival_A_to_Q_start + assert ival_A.asfreq("Q", "e") == ival_A_to_Q_end + assert ival_A.asfreq("M", "s") == ival_A_to_M_start + assert ival_A.asfreq("M", "E") == ival_A_to_M_end + assert ival_A.asfreq("W", "s") == ival_A_to_W_start + assert ival_A.asfreq("W", "E") == ival_A_to_W_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_A.asfreq("B", "s") == ival_A_to_B_start + assert ival_A.asfreq("B", "E") == ival_A_to_B_end + assert ival_A.asfreq("D", "s") == ival_A_to_D_start + assert ival_A.asfreq("D", "E") == ival_A_to_D_end + msg = "'H' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(FutureWarning, match=msg): + assert ival_A.asfreq("H", "s") == ival_A_to_H_start + assert ival_A.asfreq("H", "E") == ival_A_to_H_end + assert ival_A.asfreq("min", "s") == ival_A_to_T_start + assert ival_A.asfreq("min", "E") == ival_A_to_T_end + msg = "'T' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(FutureWarning, match=msg): + assert ival_A.asfreq("T", "s") == ival_A_to_T_start + assert ival_A.asfreq("T", "E") == ival_A_to_T_end + msg = "'S' is deprecated and will be removed in a future version." + with tm.assert_produces_warning(FutureWarning, match=msg): + assert ival_A.asfreq("S", "S") == ival_A_to_S_start + assert ival_A.asfreq("S", "E") == ival_A_to_S_end + + assert ival_AJAN.asfreq("D", "s") == ival_AJAN_to_D_start + assert ival_AJAN.asfreq("D", "E") == ival_AJAN_to_D_end + + assert ival_AJUN.asfreq("D", "s") == ival_AJUN_to_D_start + assert ival_AJUN.asfreq("D", "E") == ival_AJUN_to_D_end + + assert ival_ANOV.asfreq("D", "s") == ival_ANOV_to_D_start + assert ival_ANOV.asfreq("D", "E") == ival_ANOV_to_D_end + + assert ival_A.asfreq("Y") == ival_A + + def test_conv_quarterly(self): + # frequency conversion tests: from Quarterly Frequency + + ival_Q = Period(freq="Q", year=2007, quarter=1) + ival_Q_end_of_year = Period(freq="Q", year=2007, quarter=4) + + ival_QEJAN = Period(freq="Q-JAN", year=2007, quarter=1) + ival_QEJUN = Period(freq="Q-JUN", year=2007, quarter=1) + + ival_Q_to_A = Period(freq="Y", year=2007) + ival_Q_to_M_start = Period(freq="M", year=2007, month=1) + ival_Q_to_M_end = Period(freq="M", year=2007, month=3) + ival_Q_to_W_start = Period(freq="W", year=2007, month=1, day=1) + ival_Q_to_W_end = Period(freq="W", year=2007, month=3, day=31) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_Q_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_Q_to_B_end = Period(freq="B", year=2007, month=3, day=30) + ival_Q_to_D_start = Period(freq="D", year=2007, month=1, day=1) + ival_Q_to_D_end = Period(freq="D", year=2007, month=3, day=31) + ival_Q_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_Q_to_H_end = Period(freq="h", year=2007, month=3, day=31, hour=23) + ival_Q_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_Q_to_T_end = Period( + freq="Min", year=2007, month=3, day=31, hour=23, minute=59 + ) + ival_Q_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_Q_to_S_end = Period( + freq="s", year=2007, month=3, day=31, hour=23, minute=59, second=59 + ) + + ival_QEJAN_to_D_start = Period(freq="D", year=2006, month=2, day=1) + ival_QEJAN_to_D_end = Period(freq="D", year=2006, month=4, day=30) + + ival_QEJUN_to_D_start = Period(freq="D", year=2006, month=7, day=1) + ival_QEJUN_to_D_end = Period(freq="D", year=2006, month=9, day=30) + + assert ival_Q.asfreq("Y") == ival_Q_to_A + assert ival_Q_end_of_year.asfreq("Y") == ival_Q_to_A + + assert ival_Q.asfreq("M", "s") == ival_Q_to_M_start + assert ival_Q.asfreq("M", "E") == ival_Q_to_M_end + assert ival_Q.asfreq("W", "s") == ival_Q_to_W_start + assert ival_Q.asfreq("W", "E") == ival_Q_to_W_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_Q.asfreq("B", "s") == ival_Q_to_B_start + assert ival_Q.asfreq("B", "E") == ival_Q_to_B_end + assert ival_Q.asfreq("D", "s") == ival_Q_to_D_start + assert ival_Q.asfreq("D", "E") == ival_Q_to_D_end + assert ival_Q.asfreq("h", "s") == ival_Q_to_H_start + assert ival_Q.asfreq("h", "E") == ival_Q_to_H_end + assert ival_Q.asfreq("Min", "s") == ival_Q_to_T_start + assert ival_Q.asfreq("Min", "E") == ival_Q_to_T_end + assert ival_Q.asfreq("s", "s") == ival_Q_to_S_start + assert ival_Q.asfreq("s", "E") == ival_Q_to_S_end + + assert ival_QEJAN.asfreq("D", "s") == ival_QEJAN_to_D_start + assert ival_QEJAN.asfreq("D", "E") == ival_QEJAN_to_D_end + assert ival_QEJUN.asfreq("D", "s") == ival_QEJUN_to_D_start + assert ival_QEJUN.asfreq("D", "E") == ival_QEJUN_to_D_end + + assert ival_Q.asfreq("Q") == ival_Q + + def test_conv_monthly(self): + # frequency conversion tests: from Monthly Frequency + + ival_M = Period(freq="M", year=2007, month=1) + ival_M_end_of_year = Period(freq="M", year=2007, month=12) + ival_M_end_of_quarter = Period(freq="M", year=2007, month=3) + ival_M_to_A = Period(freq="Y", year=2007) + ival_M_to_Q = Period(freq="Q", year=2007, quarter=1) + ival_M_to_W_start = Period(freq="W", year=2007, month=1, day=1) + ival_M_to_W_end = Period(freq="W", year=2007, month=1, day=31) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_M_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_M_to_B_end = Period(freq="B", year=2007, month=1, day=31) + ival_M_to_D_start = Period(freq="D", year=2007, month=1, day=1) + ival_M_to_D_end = Period(freq="D", year=2007, month=1, day=31) + ival_M_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_M_to_H_end = Period(freq="h", year=2007, month=1, day=31, hour=23) + ival_M_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_M_to_T_end = Period( + freq="Min", year=2007, month=1, day=31, hour=23, minute=59 + ) + ival_M_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_M_to_S_end = Period( + freq="s", year=2007, month=1, day=31, hour=23, minute=59, second=59 + ) + + assert ival_M.asfreq("Y") == ival_M_to_A + assert ival_M_end_of_year.asfreq("Y") == ival_M_to_A + assert ival_M.asfreq("Q") == ival_M_to_Q + assert ival_M_end_of_quarter.asfreq("Q") == ival_M_to_Q + + assert ival_M.asfreq("W", "s") == ival_M_to_W_start + assert ival_M.asfreq("W", "E") == ival_M_to_W_end + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_M.asfreq("B", "s") == ival_M_to_B_start + assert ival_M.asfreq("B", "E") == ival_M_to_B_end + assert ival_M.asfreq("D", "s") == ival_M_to_D_start + assert ival_M.asfreq("D", "E") == ival_M_to_D_end + assert ival_M.asfreq("h", "s") == ival_M_to_H_start + assert ival_M.asfreq("h", "E") == ival_M_to_H_end + assert ival_M.asfreq("Min", "s") == ival_M_to_T_start + assert ival_M.asfreq("Min", "E") == ival_M_to_T_end + assert ival_M.asfreq("s", "s") == ival_M_to_S_start + assert ival_M.asfreq("s", "E") == ival_M_to_S_end + + assert ival_M.asfreq("M") == ival_M + + def test_conv_weekly(self): + # frequency conversion tests: from Weekly Frequency + ival_W = Period(freq="W", year=2007, month=1, day=1) + + ival_WSUN = Period(freq="W", year=2007, month=1, day=7) + ival_WSAT = Period(freq="W-SAT", year=2007, month=1, day=6) + ival_WFRI = Period(freq="W-FRI", year=2007, month=1, day=5) + ival_WTHU = Period(freq="W-THU", year=2007, month=1, day=4) + ival_WWED = Period(freq="W-WED", year=2007, month=1, day=3) + ival_WTUE = Period(freq="W-TUE", year=2007, month=1, day=2) + ival_WMON = Period(freq="W-MON", year=2007, month=1, day=1) + + ival_WSUN_to_D_start = Period(freq="D", year=2007, month=1, day=1) + ival_WSUN_to_D_end = Period(freq="D", year=2007, month=1, day=7) + ival_WSAT_to_D_start = Period(freq="D", year=2006, month=12, day=31) + ival_WSAT_to_D_end = Period(freq="D", year=2007, month=1, day=6) + ival_WFRI_to_D_start = Period(freq="D", year=2006, month=12, day=30) + ival_WFRI_to_D_end = Period(freq="D", year=2007, month=1, day=5) + ival_WTHU_to_D_start = Period(freq="D", year=2006, month=12, day=29) + ival_WTHU_to_D_end = Period(freq="D", year=2007, month=1, day=4) + ival_WWED_to_D_start = Period(freq="D", year=2006, month=12, day=28) + ival_WWED_to_D_end = Period(freq="D", year=2007, month=1, day=3) + ival_WTUE_to_D_start = Period(freq="D", year=2006, month=12, day=27) + ival_WTUE_to_D_end = Period(freq="D", year=2007, month=1, day=2) + ival_WMON_to_D_start = Period(freq="D", year=2006, month=12, day=26) + ival_WMON_to_D_end = Period(freq="D", year=2007, month=1, day=1) + + ival_W_end_of_year = Period(freq="W", year=2007, month=12, day=31) + ival_W_end_of_quarter = Period(freq="W", year=2007, month=3, day=31) + ival_W_end_of_month = Period(freq="W", year=2007, month=1, day=31) + ival_W_to_A = Period(freq="Y", year=2007) + ival_W_to_Q = Period(freq="Q", year=2007, quarter=1) + ival_W_to_M = Period(freq="M", year=2007, month=1) + + if Period(freq="D", year=2007, month=12, day=31).weekday == 6: + ival_W_to_A_end_of_year = Period(freq="Y", year=2007) + else: + ival_W_to_A_end_of_year = Period(freq="Y", year=2008) + + if Period(freq="D", year=2007, month=3, day=31).weekday == 6: + ival_W_to_Q_end_of_quarter = Period(freq="Q", year=2007, quarter=1) + else: + ival_W_to_Q_end_of_quarter = Period(freq="Q", year=2007, quarter=2) + + if Period(freq="D", year=2007, month=1, day=31).weekday == 6: + ival_W_to_M_end_of_month = Period(freq="M", year=2007, month=1) + else: + ival_W_to_M_end_of_month = Period(freq="M", year=2007, month=2) + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_W_to_B_start = Period(freq="B", year=2007, month=1, day=1) + ival_W_to_B_end = Period(freq="B", year=2007, month=1, day=5) + ival_W_to_D_start = Period(freq="D", year=2007, month=1, day=1) + ival_W_to_D_end = Period(freq="D", year=2007, month=1, day=7) + ival_W_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_W_to_H_end = Period(freq="h", year=2007, month=1, day=7, hour=23) + ival_W_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_W_to_T_end = Period( + freq="Min", year=2007, month=1, day=7, hour=23, minute=59 + ) + ival_W_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_W_to_S_end = Period( + freq="s", year=2007, month=1, day=7, hour=23, minute=59, second=59 + ) + + assert ival_W.asfreq("Y") == ival_W_to_A + assert ival_W_end_of_year.asfreq("Y") == ival_W_to_A_end_of_year + + assert ival_W.asfreq("Q") == ival_W_to_Q + assert ival_W_end_of_quarter.asfreq("Q") == ival_W_to_Q_end_of_quarter + + assert ival_W.asfreq("M") == ival_W_to_M + assert ival_W_end_of_month.asfreq("M") == ival_W_to_M_end_of_month + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_W.asfreq("B", "s") == ival_W_to_B_start + assert ival_W.asfreq("B", "E") == ival_W_to_B_end + + assert ival_W.asfreq("D", "s") == ival_W_to_D_start + assert ival_W.asfreq("D", "E") == ival_W_to_D_end + + assert ival_WSUN.asfreq("D", "s") == ival_WSUN_to_D_start + assert ival_WSUN.asfreq("D", "E") == ival_WSUN_to_D_end + assert ival_WSAT.asfreq("D", "s") == ival_WSAT_to_D_start + assert ival_WSAT.asfreq("D", "E") == ival_WSAT_to_D_end + assert ival_WFRI.asfreq("D", "s") == ival_WFRI_to_D_start + assert ival_WFRI.asfreq("D", "E") == ival_WFRI_to_D_end + assert ival_WTHU.asfreq("D", "s") == ival_WTHU_to_D_start + assert ival_WTHU.asfreq("D", "E") == ival_WTHU_to_D_end + assert ival_WWED.asfreq("D", "s") == ival_WWED_to_D_start + assert ival_WWED.asfreq("D", "E") == ival_WWED_to_D_end + assert ival_WTUE.asfreq("D", "s") == ival_WTUE_to_D_start + assert ival_WTUE.asfreq("D", "E") == ival_WTUE_to_D_end + assert ival_WMON.asfreq("D", "s") == ival_WMON_to_D_start + assert ival_WMON.asfreq("D", "E") == ival_WMON_to_D_end + + assert ival_W.asfreq("h", "s") == ival_W_to_H_start + assert ival_W.asfreq("h", "E") == ival_W_to_H_end + assert ival_W.asfreq("Min", "s") == ival_W_to_T_start + assert ival_W.asfreq("Min", "E") == ival_W_to_T_end + assert ival_W.asfreq("s", "s") == ival_W_to_S_start + assert ival_W.asfreq("s", "E") == ival_W_to_S_end + + assert ival_W.asfreq("W") == ival_W + + msg = INVALID_FREQ_ERR_MSG + with pytest.raises(ValueError, match=msg): + ival_W.asfreq("WK") + + def test_conv_weekly_legacy(self): + # frequency conversion tests: from Weekly Frequency + msg = INVALID_FREQ_ERR_MSG + with pytest.raises(ValueError, match=msg): + Period(freq="WK", year=2007, month=1, day=1) + + with pytest.raises(ValueError, match=msg): + Period(freq="WK-SAT", year=2007, month=1, day=6) + with pytest.raises(ValueError, match=msg): + Period(freq="WK-FRI", year=2007, month=1, day=5) + with pytest.raises(ValueError, match=msg): + Period(freq="WK-THU", year=2007, month=1, day=4) + with pytest.raises(ValueError, match=msg): + Period(freq="WK-WED", year=2007, month=1, day=3) + with pytest.raises(ValueError, match=msg): + Period(freq="WK-TUE", year=2007, month=1, day=2) + with pytest.raises(ValueError, match=msg): + Period(freq="WK-MON", year=2007, month=1, day=1) + + def test_conv_business(self): + # frequency conversion tests: from Business Frequency" + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_B = Period(freq="B", year=2007, month=1, day=1) + ival_B_end_of_year = Period(freq="B", year=2007, month=12, day=31) + ival_B_end_of_quarter = Period(freq="B", year=2007, month=3, day=30) + ival_B_end_of_month = Period(freq="B", year=2007, month=1, day=31) + ival_B_end_of_week = Period(freq="B", year=2007, month=1, day=5) + + ival_B_to_A = Period(freq="Y", year=2007) + ival_B_to_Q = Period(freq="Q", year=2007, quarter=1) + ival_B_to_M = Period(freq="M", year=2007, month=1) + ival_B_to_W = Period(freq="W", year=2007, month=1, day=7) + ival_B_to_D = Period(freq="D", year=2007, month=1, day=1) + ival_B_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_B_to_H_end = Period(freq="h", year=2007, month=1, day=1, hour=23) + ival_B_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_B_to_T_end = Period( + freq="Min", year=2007, month=1, day=1, hour=23, minute=59 + ) + ival_B_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_B_to_S_end = Period( + freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59 + ) + + assert ival_B.asfreq("Y") == ival_B_to_A + assert ival_B_end_of_year.asfreq("Y") == ival_B_to_A + assert ival_B.asfreq("Q") == ival_B_to_Q + assert ival_B_end_of_quarter.asfreq("Q") == ival_B_to_Q + assert ival_B.asfreq("M") == ival_B_to_M + assert ival_B_end_of_month.asfreq("M") == ival_B_to_M + assert ival_B.asfreq("W") == ival_B_to_W + assert ival_B_end_of_week.asfreq("W") == ival_B_to_W + + assert ival_B.asfreq("D") == ival_B_to_D + + assert ival_B.asfreq("h", "s") == ival_B_to_H_start + assert ival_B.asfreq("h", "E") == ival_B_to_H_end + assert ival_B.asfreq("Min", "s") == ival_B_to_T_start + assert ival_B.asfreq("Min", "E") == ival_B_to_T_end + assert ival_B.asfreq("s", "s") == ival_B_to_S_start + assert ival_B.asfreq("s", "E") == ival_B_to_S_end + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_B.asfreq("B") == ival_B + + def test_conv_daily(self): + # frequency conversion tests: from Business Frequency" + + ival_D = Period(freq="D", year=2007, month=1, day=1) + ival_D_end_of_year = Period(freq="D", year=2007, month=12, day=31) + ival_D_end_of_quarter = Period(freq="D", year=2007, month=3, day=31) + ival_D_end_of_month = Period(freq="D", year=2007, month=1, day=31) + ival_D_end_of_week = Period(freq="D", year=2007, month=1, day=7) + + ival_D_friday = Period(freq="D", year=2007, month=1, day=5) + ival_D_saturday = Period(freq="D", year=2007, month=1, day=6) + ival_D_sunday = Period(freq="D", year=2007, month=1, day=7) + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_B_friday = Period(freq="B", year=2007, month=1, day=5) + ival_B_monday = Period(freq="B", year=2007, month=1, day=8) + + ival_D_to_A = Period(freq="Y", year=2007) + + ival_Deoq_to_AJAN = Period(freq="Y-JAN", year=2008) + ival_Deoq_to_AJUN = Period(freq="Y-JUN", year=2007) + ival_Deoq_to_ADEC = Period(freq="Y-DEC", year=2007) + + ival_D_to_QEJAN = Period(freq="Q-JAN", year=2007, quarter=4) + ival_D_to_QEJUN = Period(freq="Q-JUN", year=2007, quarter=3) + ival_D_to_QEDEC = Period(freq="Q-DEC", year=2007, quarter=1) + + ival_D_to_M = Period(freq="M", year=2007, month=1) + ival_D_to_W = Period(freq="W", year=2007, month=1, day=7) + + ival_D_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_D_to_H_end = Period(freq="h", year=2007, month=1, day=1, hour=23) + ival_D_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_D_to_T_end = Period( + freq="Min", year=2007, month=1, day=1, hour=23, minute=59 + ) + ival_D_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_D_to_S_end = Period( + freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59 + ) + + assert ival_D.asfreq("Y") == ival_D_to_A + + assert ival_D_end_of_quarter.asfreq("Y-JAN") == ival_Deoq_to_AJAN + assert ival_D_end_of_quarter.asfreq("Y-JUN") == ival_Deoq_to_AJUN + assert ival_D_end_of_quarter.asfreq("Y-DEC") == ival_Deoq_to_ADEC + + assert ival_D_end_of_year.asfreq("Y") == ival_D_to_A + assert ival_D_end_of_quarter.asfreq("Q") == ival_D_to_QEDEC + assert ival_D.asfreq("Q-JAN") == ival_D_to_QEJAN + assert ival_D.asfreq("Q-JUN") == ival_D_to_QEJUN + assert ival_D.asfreq("Q-DEC") == ival_D_to_QEDEC + assert ival_D.asfreq("M") == ival_D_to_M + assert ival_D_end_of_month.asfreq("M") == ival_D_to_M + assert ival_D.asfreq("W") == ival_D_to_W + assert ival_D_end_of_week.asfreq("W") == ival_D_to_W + + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_D_friday.asfreq("B") == ival_B_friday + assert ival_D_saturday.asfreq("B", "s") == ival_B_friday + assert ival_D_saturday.asfreq("B", "E") == ival_B_monday + assert ival_D_sunday.asfreq("B", "s") == ival_B_friday + assert ival_D_sunday.asfreq("B", "E") == ival_B_monday + + assert ival_D.asfreq("h", "s") == ival_D_to_H_start + assert ival_D.asfreq("h", "E") == ival_D_to_H_end + assert ival_D.asfreq("Min", "s") == ival_D_to_T_start + assert ival_D.asfreq("Min", "E") == ival_D_to_T_end + assert ival_D.asfreq("s", "s") == ival_D_to_S_start + assert ival_D.asfreq("s", "E") == ival_D_to_S_end + + assert ival_D.asfreq("D") == ival_D + + def test_conv_hourly(self): + # frequency conversion tests: from Hourly Frequency" + + ival_H = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_H_end_of_year = Period(freq="h", year=2007, month=12, day=31, hour=23) + ival_H_end_of_quarter = Period(freq="h", year=2007, month=3, day=31, hour=23) + ival_H_end_of_month = Period(freq="h", year=2007, month=1, day=31, hour=23) + ival_H_end_of_week = Period(freq="h", year=2007, month=1, day=7, hour=23) + ival_H_end_of_day = Period(freq="h", year=2007, month=1, day=1, hour=23) + ival_H_end_of_bus = Period(freq="h", year=2007, month=1, day=1, hour=23) + + ival_H_to_A = Period(freq="Y", year=2007) + ival_H_to_Q = Period(freq="Q", year=2007, quarter=1) + ival_H_to_M = Period(freq="M", year=2007, month=1) + ival_H_to_W = Period(freq="W", year=2007, month=1, day=7) + ival_H_to_D = Period(freq="D", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_H_to_B = Period(freq="B", year=2007, month=1, day=1) + + ival_H_to_T_start = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=0 + ) + ival_H_to_T_end = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=59 + ) + ival_H_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_H_to_S_end = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=59, second=59 + ) + + assert ival_H.asfreq("Y") == ival_H_to_A + assert ival_H_end_of_year.asfreq("Y") == ival_H_to_A + assert ival_H.asfreq("Q") == ival_H_to_Q + assert ival_H_end_of_quarter.asfreq("Q") == ival_H_to_Q + assert ival_H.asfreq("M") == ival_H_to_M + assert ival_H_end_of_month.asfreq("M") == ival_H_to_M + assert ival_H.asfreq("W") == ival_H_to_W + assert ival_H_end_of_week.asfreq("W") == ival_H_to_W + assert ival_H.asfreq("D") == ival_H_to_D + assert ival_H_end_of_day.asfreq("D") == ival_H_to_D + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_H.asfreq("B") == ival_H_to_B + assert ival_H_end_of_bus.asfreq("B") == ival_H_to_B + + assert ival_H.asfreq("Min", "s") == ival_H_to_T_start + assert ival_H.asfreq("Min", "E") == ival_H_to_T_end + assert ival_H.asfreq("s", "s") == ival_H_to_S_start + assert ival_H.asfreq("s", "E") == ival_H_to_S_end + + assert ival_H.asfreq("h") == ival_H + + def test_conv_minutely(self): + # frequency conversion tests: from Minutely Frequency" + + ival_T = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0) + ival_T_end_of_year = Period( + freq="Min", year=2007, month=12, day=31, hour=23, minute=59 + ) + ival_T_end_of_quarter = Period( + freq="Min", year=2007, month=3, day=31, hour=23, minute=59 + ) + ival_T_end_of_month = Period( + freq="Min", year=2007, month=1, day=31, hour=23, minute=59 + ) + ival_T_end_of_week = Period( + freq="Min", year=2007, month=1, day=7, hour=23, minute=59 + ) + ival_T_end_of_day = Period( + freq="Min", year=2007, month=1, day=1, hour=23, minute=59 + ) + ival_T_end_of_bus = Period( + freq="Min", year=2007, month=1, day=1, hour=23, minute=59 + ) + ival_T_end_of_hour = Period( + freq="Min", year=2007, month=1, day=1, hour=0, minute=59 + ) + + ival_T_to_A = Period(freq="Y", year=2007) + ival_T_to_Q = Period(freq="Q", year=2007, quarter=1) + ival_T_to_M = Period(freq="M", year=2007, month=1) + ival_T_to_W = Period(freq="W", year=2007, month=1, day=7) + ival_T_to_D = Period(freq="D", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_T_to_B = Period(freq="B", year=2007, month=1, day=1) + ival_T_to_H = Period(freq="h", year=2007, month=1, day=1, hour=0) + + ival_T_to_S_start = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0 + ) + ival_T_to_S_end = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=59 + ) + + assert ival_T.asfreq("Y") == ival_T_to_A + assert ival_T_end_of_year.asfreq("Y") == ival_T_to_A + assert ival_T.asfreq("Q") == ival_T_to_Q + assert ival_T_end_of_quarter.asfreq("Q") == ival_T_to_Q + assert ival_T.asfreq("M") == ival_T_to_M + assert ival_T_end_of_month.asfreq("M") == ival_T_to_M + assert ival_T.asfreq("W") == ival_T_to_W + assert ival_T_end_of_week.asfreq("W") == ival_T_to_W + assert ival_T.asfreq("D") == ival_T_to_D + assert ival_T_end_of_day.asfreq("D") == ival_T_to_D + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_T.asfreq("B") == ival_T_to_B + assert ival_T_end_of_bus.asfreq("B") == ival_T_to_B + assert ival_T.asfreq("h") == ival_T_to_H + assert ival_T_end_of_hour.asfreq("h") == ival_T_to_H + + assert ival_T.asfreq("s", "s") == ival_T_to_S_start + assert ival_T.asfreq("s", "E") == ival_T_to_S_end + + assert ival_T.asfreq("Min") == ival_T + + def test_conv_secondly(self): + # frequency conversion tests: from Secondly Frequency" + + ival_S = Period(freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0) + ival_S_end_of_year = Period( + freq="s", year=2007, month=12, day=31, hour=23, minute=59, second=59 + ) + ival_S_end_of_quarter = Period( + freq="s", year=2007, month=3, day=31, hour=23, minute=59, second=59 + ) + ival_S_end_of_month = Period( + freq="s", year=2007, month=1, day=31, hour=23, minute=59, second=59 + ) + ival_S_end_of_week = Period( + freq="s", year=2007, month=1, day=7, hour=23, minute=59, second=59 + ) + ival_S_end_of_day = Period( + freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59 + ) + ival_S_end_of_bus = Period( + freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59 + ) + ival_S_end_of_hour = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=59, second=59 + ) + ival_S_end_of_minute = Period( + freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=59 + ) + + ival_S_to_A = Period(freq="Y", year=2007) + ival_S_to_Q = Period(freq="Q", year=2007, quarter=1) + ival_S_to_M = Period(freq="M", year=2007, month=1) + ival_S_to_W = Period(freq="W", year=2007, month=1, day=7) + ival_S_to_D = Period(freq="D", year=2007, month=1, day=1) + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + ival_S_to_B = Period(freq="B", year=2007, month=1, day=1) + ival_S_to_H = Period(freq="h", year=2007, month=1, day=1, hour=0) + ival_S_to_T = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0) + + assert ival_S.asfreq("Y") == ival_S_to_A + assert ival_S_end_of_year.asfreq("Y") == ival_S_to_A + assert ival_S.asfreq("Q") == ival_S_to_Q + assert ival_S_end_of_quarter.asfreq("Q") == ival_S_to_Q + assert ival_S.asfreq("M") == ival_S_to_M + assert ival_S_end_of_month.asfreq("M") == ival_S_to_M + assert ival_S.asfreq("W") == ival_S_to_W + assert ival_S_end_of_week.asfreq("W") == ival_S_to_W + assert ival_S.asfreq("D") == ival_S_to_D + assert ival_S_end_of_day.asfreq("D") == ival_S_to_D + with tm.assert_produces_warning(FutureWarning, match=bday_msg): + assert ival_S.asfreq("B") == ival_S_to_B + assert ival_S_end_of_bus.asfreq("B") == ival_S_to_B + assert ival_S.asfreq("h") == ival_S_to_H + assert ival_S_end_of_hour.asfreq("h") == ival_S_to_H + assert ival_S.asfreq("Min") == ival_S_to_T + assert ival_S_end_of_minute.asfreq("Min") == ival_S_to_T + + assert ival_S.asfreq("s") == ival_S + + def test_conv_microsecond(self): + # GH#31475 Avoid floating point errors dropping the start_time to + # before the beginning of the Period + per = Period("2020-01-30 15:57:27.576166", freq="us") + assert per.ordinal == 1580399847576166 + + start = per.start_time + expected = Timestamp("2020-01-30 15:57:27.576166") + assert start == expected + assert start._value == per.ordinal * 1000 + + per2 = Period("2300-01-01", "us") + msg = "2300-01-01" + with pytest.raises(OutOfBoundsDatetime, match=msg): + per2.start_time + with pytest.raises(OutOfBoundsDatetime, match=msg): + per2.end_time + + def test_asfreq_mult(self): + # normal freq to mult freq + p = Period(freq="Y", year=2007) + # ordinal will not change + for freq in ["3Y", offsets.YearEnd(3)]: + result = p.asfreq(freq) + expected = Period("2007", freq="3Y") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + # ordinal will not change + for freq in ["3Y", offsets.YearEnd(3)]: + result = p.asfreq(freq, how="S") + expected = Period("2007", freq="3Y") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + + # mult freq to normal freq + p = Period(freq="3Y", year=2007) + # ordinal will change because how=E is the default + for freq in ["Y", offsets.YearEnd()]: + result = p.asfreq(freq) + expected = Period("2009", freq="Y") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + # ordinal will not change + for freq in ["Y", offsets.YearEnd()]: + result = p.asfreq(freq, how="s") + expected = Period("2007", freq="Y") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + + p = Period(freq="Y", year=2007) + for freq in ["2M", offsets.MonthEnd(2)]: + result = p.asfreq(freq) + expected = Period("2007-12", freq="2M") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + for freq in ["2M", offsets.MonthEnd(2)]: + result = p.asfreq(freq, how="s") + expected = Period("2007-01", freq="2M") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + + p = Period(freq="3Y", year=2007) + for freq in ["2M", offsets.MonthEnd(2)]: + result = p.asfreq(freq) + expected = Period("2009-12", freq="2M") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + for freq in ["2M", offsets.MonthEnd(2)]: + result = p.asfreq(freq, how="s") + expected = Period("2007-01", freq="2M") + + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + + def test_asfreq_combined(self): + # normal freq to combined freq + p = Period("2007", freq="h") + + # ordinal will not change + expected = Period("2007", freq="25h") + for freq, how in zip(["1D1h", "1h1D"], ["E", "S"]): + result = p.asfreq(freq, how=how) + assert result == expected + assert result.ordinal == expected.ordinal + assert result.freq == expected.freq + + # combined freq to normal freq + p1 = Period(freq="1D1h", year=2007) + p2 = Period(freq="1h1D", year=2007) + + # ordinal will change because how=E is the default + result1 = p1.asfreq("h") + result2 = p2.asfreq("h") + expected = Period("2007-01-02", freq="h") + assert result1 == expected + assert result1.ordinal == expected.ordinal + assert result1.freq == expected.freq + assert result2 == expected + assert result2.ordinal == expected.ordinal + assert result2.freq == expected.freq + + # ordinal will not change + result1 = p1.asfreq("h", how="S") + result2 = p2.asfreq("h", how="S") + expected = Period("2007-01-01", freq="h") + assert result1 == expected + assert result1.ordinal == expected.ordinal + assert result1.freq == expected.freq + assert result2 == expected + assert result2.ordinal == expected.ordinal + assert result2.freq == expected.freq + + def test_asfreq_MS(self): + initial = Period("2013") + + assert initial.asfreq(freq="M", how="S") == Period("2013-01", "M") + + msg = "MS is not supported as period frequency" + with pytest.raises(ValueError, match=msg): + initial.asfreq(freq="MS", how="S") + + with pytest.raises(ValueError, match=msg): + Period("2013-01", "MS") diff --git a/shared/package-files/75/75ba535dc240ad6451fc7879253bb2d862487e08d5a3acd2db4a3999d544187e/blob b/shared/package-files/75/75ba535dc240ad6451fc7879253bb2d862487e08d5a3acd2db4a3999d544187e/blob new file mode 100644 index 0000000000000000000000000000000000000000..85db6c60ad9d2bd1fbfafcf5d84b97d2fe304250 --- /dev/null +++ b/shared/package-files/75/75ba535dc240ad6451fc7879253bb2d862487e08d5a3acd2db4a3999d544187e/blob @@ -0,0 +1,109 @@ +from sympy.core.containers import Tuple +from sympy.core.symbol import symbols +from sympy.matrices.dense import Matrix +from sympy.physics.quantum.trace import Tr +from sympy.testing.pytest import raises, warns_deprecated_sympy + + +def test_trace_new(): + a, b, c, d, Y = symbols('a b c d Y') + A, B, C, D = symbols('A B C D', commutative=False) + + assert Tr(a + b) == a + b + assert Tr(A + B) == Tr(A) + Tr(B) + + #check trace args not implicitly permuted + assert Tr(C*D*A*B).args[0].args == (C, D, A, B) + + # check for mul and adds + assert Tr((a*b) + ( c*d)) == (a*b) + (c*d) + # Tr(scalar*A) = scalar*Tr(A) + assert Tr(a*A) == a*Tr(A) + assert Tr(a*A*B*b) == a*b*Tr(A*B) + + # since A is symbol and not commutative + assert isinstance(Tr(A), Tr) + + #POW + assert Tr(pow(a, b)) == a**b + assert isinstance(Tr(pow(A, a)), Tr) + + #Matrix + M = Matrix([[1, 1], [2, 2]]) + assert Tr(M) == 3 + + ##test indices in different forms + #no index + t = Tr(A) + assert t.args[1] == Tuple() + + #single index + t = Tr(A, 0) + assert t.args[1] == Tuple(0) + + #index in a list + t = Tr(A, [0]) + assert t.args[1] == Tuple(0) + + t = Tr(A, [0, 1, 2]) + assert t.args[1] == Tuple(0, 1, 2) + + #index is tuple + t = Tr(A, (0)) + assert t.args[1] == Tuple(0) + + t = Tr(A, (1, 2)) + assert t.args[1] == Tuple(1, 2) + + #trace indices test + t = Tr((A + B), [2]) + assert t.args[0].args[1] == Tuple(2) and t.args[1].args[1] == Tuple(2) + + t = Tr(a*A, [2, 3]) + assert t.args[1].args[1] == Tuple(2, 3) + + #class with trace method defined + #to simulate numpy objects + class Foo: + def trace(self): + return 1 + assert Tr(Foo()) == 1 + + #argument test + # check for value error, when either/both arguments are not provided + raises(ValueError, lambda: Tr()) + raises(ValueError, lambda: Tr(A, 1, 2)) + + +def test_trace_doit(): + a, b, c, d = symbols('a b c d') + A, B, C, D = symbols('A B C D', commutative=False) + + #TODO: needed while testing reduced density operations, etc. + + +def test_permute(): + A, B, C, D, E, F, G = symbols('A B C D E F G', commutative=False) + t = Tr(A*B*C*D*E*F*G) + + assert t.permute(0).args[0].args == (A, B, C, D, E, F, G) + assert t.permute(2).args[0].args == (F, G, A, B, C, D, E) + assert t.permute(4).args[0].args == (D, E, F, G, A, B, C) + assert t.permute(6).args[0].args == (B, C, D, E, F, G, A) + assert t.permute(8).args[0].args == t.permute(1).args[0].args + + assert t.permute(-1).args[0].args == (B, C, D, E, F, G, A) + assert t.permute(-3).args[0].args == (D, E, F, G, A, B, C) + assert t.permute(-5).args[0].args == (F, G, A, B, C, D, E) + assert t.permute(-8).args[0].args == t.permute(-1).args[0].args + + t = Tr((A + B)*(B*B)*C*D) + assert t.permute(2).args[0].args == (C, D, (A + B), (B**2)) + + t1 = Tr(A*B) + t2 = t1.permute(1) + assert id(t1) != id(t2) and t1 == t2 + +def test_deprecated_core_trace(): + with warns_deprecated_sympy(): + from sympy.core.trace import Tr # noqa:F401 diff --git a/shared/package-files/75/75bdfdbbb57c7a50e0252997621308be79a535ceb1eb6ba01a462b7e7ffdf19d/blob b/shared/package-files/75/75bdfdbbb57c7a50e0252997621308be79a535ceb1eb6ba01a462b7e7ffdf19d/blob new file mode 100644 index 0000000000000000000000000000000000000000..fe9f87b79457fac74f7dee5643a01870dd3fd8e9 --- /dev/null +++ b/shared/package-files/75/75bdfdbbb57c7a50e0252997621308be79a535ceb1eb6ba01a462b7e7ffdf19d/blob @@ -0,0 +1,733 @@ +r"""UUID objects (universally unique identifiers) according to RFC 4122. + +This module provides immutable UUID objects (class UUID) and the functions +uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 +UUIDs as specified in RFC 4122. + +If all you want is a unique ID, you should probably call uuid1() or uuid4(). +Note that uuid1() may compromise privacy since it creates a UUID containing +the computer's network address. uuid4() creates a random UUID. + +Typical usage: + + >>> import uuid + + # make a UUID based on the host ID and current time + >>> uuid.uuid1() # doctest: +SKIP + UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') + + # make a UUID using an MD5 hash of a namespace UUID and a name + >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') + UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') + + # make a random UUID + >>> uuid.uuid4() # doctest: +SKIP + UUID('16fd2706-8baf-433b-82eb-8c7fada847da') + + # make a UUID using a SHA-1 hash of a namespace UUID and a name + >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') + UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') + + # make a UUID from a string of hex digits (braces and hyphens ignored) + >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') + + # convert a UUID to a string of hex digits in standard form + >>> str(x) + '00010203-0405-0607-0809-0a0b0c0d0e0f' + + # get the raw 16 bytes of the UUID + >>> x.bytes + b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' + + # make a UUID from a 16-byte string + >>> uuid.UUID(bytes=x.bytes) + UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') +""" + +import os +import sys + +from enum import Enum + + +__author__ = 'Ka-Ping Yee ' + +# The recognized platforms - known behaviors +if sys.platform in ('win32', 'darwin'): + _AIX = _LINUX = False +else: + import platform + _platform_system = platform.system() + _AIX = _platform_system == 'AIX' + _LINUX = _platform_system == 'Linux' + +_MAC_DELIM = b':' +_MAC_OMITS_LEADING_ZEROES = False +if _AIX: + _MAC_DELIM = b'.' + _MAC_OMITS_LEADING_ZEROES = True + +RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [ + 'reserved for NCS compatibility', 'specified in RFC 4122', + 'reserved for Microsoft compatibility', 'reserved for future definition'] + +int_ = int # The built-in int type +bytes_ = bytes # The built-in bytes type + + +class SafeUUID(Enum): + safe = 0 + unsafe = -1 + unknown = None + + +class UUID: + """Instances of the UUID class represent UUIDs as specified in RFC 4122. + UUID objects are immutable, hashable, and usable as dictionary keys. + Converting a UUID to a string with str() yields something in the form + '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts + five possible forms: a similar string of hexadecimal digits, or a tuple + of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and + 48-bit values respectively) as an argument named 'fields', or a string + of 16 bytes (with all the integer fields in big-endian order) as an + argument named 'bytes', or a string of 16 bytes (with the first three + fields in little-endian order) as an argument named 'bytes_le', or a + single 128-bit integer as an argument named 'int'. + + UUIDs have these read-only attributes: + + bytes the UUID as a 16-byte string (containing the six + integer fields in big-endian byte order) + + bytes_le the UUID as a 16-byte string (with time_low, time_mid, + and time_hi_version in little-endian byte order) + + fields a tuple of the six integer fields of the UUID, + which are also available as six individual attributes + and two derived attributes: + + time_low the first 32 bits of the UUID + time_mid the next 16 bits of the UUID + time_hi_version the next 16 bits of the UUID + clock_seq_hi_variant the next 8 bits of the UUID + clock_seq_low the next 8 bits of the UUID + node the last 48 bits of the UUID + + time the 60-bit timestamp + clock_seq the 14-bit sequence number + + hex the UUID as a 32-character hexadecimal string + + int the UUID as a 128-bit integer + + urn the UUID as a URN as specified in RFC 4122 + + variant the UUID variant (one of the constants RESERVED_NCS, + RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE) + + version the UUID version number (1 through 5, meaningful only + when the variant is RFC_4122) + + is_safe An enum indicating whether the UUID has been generated in + a way that is safe for multiprocessing applications, via + uuid_generate_time_safe(3). + """ + + __slots__ = ('int', 'is_safe', '__weakref__') + + def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, + int=None, version=None, + *, is_safe=SafeUUID.unknown): + r"""Create a UUID from either a string of 32 hexadecimal digits, + a string of 16 bytes as the 'bytes' argument, a string of 16 bytes + in little-endian order as the 'bytes_le' argument, a tuple of six + integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, + 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as + the 'fields' argument, or a single 128-bit integer as the 'int' + argument. When a string of hex digits is given, curly braces, + hyphens, and a URN prefix are all optional. For example, these + expressions all yield the same UUID: + + UUID('{12345678-1234-5678-1234-567812345678}') + UUID('12345678123456781234567812345678') + UUID('urn:uuid:12345678-1234-5678-1234-567812345678') + UUID(bytes='\x12\x34\x56\x78'*4) + UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + + '\x12\x34\x56\x78\x12\x34\x56\x78') + UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) + UUID(int=0x12345678123456781234567812345678) + + Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must + be given. The 'version' argument is optional; if given, the resulting + UUID will have its variant and version set according to RFC 4122, + overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. + + is_safe is an enum exposed as an attribute on the instance. It + indicates whether the UUID has been generated in a way that is safe + for multiprocessing applications, via uuid_generate_time_safe(3). + """ + + if [hex, bytes, bytes_le, fields, int].count(None) != 4: + raise TypeError('one of the hex, bytes, bytes_le, fields, ' + 'or int arguments must be given') + if hex is not None: + hex = hex.replace('urn:', '').replace('uuid:', '') + hex = hex.strip('{}').replace('-', '') + if len(hex) != 32: + raise ValueError('badly formed hexadecimal UUID string') + int = int_(hex, 16) + if bytes_le is not None: + if len(bytes_le) != 16: + raise ValueError('bytes_le is not a 16-char string') + bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] + + bytes_le[8-1:6-1:-1] + bytes_le[8:]) + if bytes is not None: + if len(bytes) != 16: + raise ValueError('bytes is not a 16-char string') + assert isinstance(bytes, bytes_), repr(bytes) + int = int_.from_bytes(bytes, byteorder='big') + if fields is not None: + if len(fields) != 6: + raise ValueError('fields is not a 6-tuple') + (time_low, time_mid, time_hi_version, + clock_seq_hi_variant, clock_seq_low, node) = fields + if not 0 <= time_low < 1<<32: + raise ValueError('field 1 out of range (need a 32-bit value)') + if not 0 <= time_mid < 1<<16: + raise ValueError('field 2 out of range (need a 16-bit value)') + if not 0 <= time_hi_version < 1<<16: + raise ValueError('field 3 out of range (need a 16-bit value)') + if not 0 <= clock_seq_hi_variant < 1<<8: + raise ValueError('field 4 out of range (need an 8-bit value)') + if not 0 <= clock_seq_low < 1<<8: + raise ValueError('field 5 out of range (need an 8-bit value)') + if not 0 <= node < 1<<48: + raise ValueError('field 6 out of range (need a 48-bit value)') + clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low + int = ((time_low << 96) | (time_mid << 80) | + (time_hi_version << 64) | (clock_seq << 48) | node) + if int is not None: + if not 0 <= int < 1<<128: + raise ValueError('int is out of range (need a 128-bit value)') + if version is not None: + if not 1 <= version <= 5: + raise ValueError('illegal version number') + # Set the variant to RFC 4122. + int &= ~(0xc000 << 48) + int |= 0x8000 << 48 + # Set the version number. + int &= ~(0xf000 << 64) + int |= version << 76 + object.__setattr__(self, 'int', int) + object.__setattr__(self, 'is_safe', is_safe) + + def __getstate__(self): + d = {'int': self.int} + if self.is_safe != SafeUUID.unknown: + # is_safe is a SafeUUID instance. Return just its value, so that + # it can be un-pickled in older Python versions without SafeUUID. + d['is_safe'] = self.is_safe.value + return d + + def __setstate__(self, state): + object.__setattr__(self, 'int', state['int']) + # is_safe was added in 3.7; it is also omitted when it is "unknown" + object.__setattr__(self, 'is_safe', + SafeUUID(state['is_safe']) + if 'is_safe' in state else SafeUUID.unknown) + + def __eq__(self, other): + if isinstance(other, UUID): + return self.int == other.int + return NotImplemented + + # Q. What's the value of being able to sort UUIDs? + # A. Use them as keys in a B-Tree or similar mapping. + + def __lt__(self, other): + if isinstance(other, UUID): + return self.int < other.int + return NotImplemented + + def __gt__(self, other): + if isinstance(other, UUID): + return self.int > other.int + return NotImplemented + + def __le__(self, other): + if isinstance(other, UUID): + return self.int <= other.int + return NotImplemented + + def __ge__(self, other): + if isinstance(other, UUID): + return self.int >= other.int + return NotImplemented + + def __hash__(self): + return hash(self.int) + + def __int__(self): + return self.int + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, str(self)) + + def __setattr__(self, name, value): + raise TypeError('UUID objects are immutable') + + def __str__(self): + hex = '%032x' % self.int + return '%s-%s-%s-%s-%s' % ( + hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:]) + + @property + def bytes(self): + return self.int.to_bytes(16, 'big') + + @property + def bytes_le(self): + bytes = self.bytes + return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] + + bytes[8:]) + + @property + def fields(self): + return (self.time_low, self.time_mid, self.time_hi_version, + self.clock_seq_hi_variant, self.clock_seq_low, self.node) + + @property + def time_low(self): + return self.int >> 96 + + @property + def time_mid(self): + return (self.int >> 80) & 0xffff + + @property + def time_hi_version(self): + return (self.int >> 64) & 0xffff + + @property + def clock_seq_hi_variant(self): + return (self.int >> 56) & 0xff + + @property + def clock_seq_low(self): + return (self.int >> 48) & 0xff + + @property + def time(self): + return (((self.time_hi_version & 0x0fff) << 48) | + (self.time_mid << 32) | self.time_low) + + @property + def clock_seq(self): + return (((self.clock_seq_hi_variant & 0x3f) << 8) | + self.clock_seq_low) + + @property + def node(self): + return self.int & 0xffffffffffff + + @property + def hex(self): + return '%032x' % self.int + + @property + def urn(self): + return 'urn:uuid:' + str(self) + + @property + def variant(self): + if not self.int & (0x8000 << 48): + return RESERVED_NCS + elif not self.int & (0x4000 << 48): + return RFC_4122 + elif not self.int & (0x2000 << 48): + return RESERVED_MICROSOFT + else: + return RESERVED_FUTURE + + @property + def version(self): + # The version bits are only meaningful for RFC 4122 UUIDs. + if self.variant == RFC_4122: + return int((self.int >> 76) & 0xf) + + +def _get_command_stdout(command, *args): + import io, os, shutil, subprocess + + try: + path_dirs = os.environ.get('PATH', os.defpath).split(os.pathsep) + path_dirs.extend(['/sbin', '/usr/sbin']) + executable = shutil.which(command, path=os.pathsep.join(path_dirs)) + if executable is None: + return None + # LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output + # on stderr (Note: we don't have an example where the words we search + # for are actually localized, but in theory some system could do so.) + env = dict(os.environ) + env['LC_ALL'] = 'C' + # Empty strings will be quoted by popen so we should just ommit it + if args != ('',): + command = (executable, *args) + else: + command = (executable,) + proc = subprocess.Popen(command, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + env=env) + if not proc: + return None + stdout, stderr = proc.communicate() + return io.BytesIO(stdout) + except (OSError, subprocess.SubprocessError): + return None + + +# For MAC (a.k.a. IEEE 802, or EUI-48) addresses, the second least significant +# bit of the first octet signifies whether the MAC address is universally (0) +# or locally (1) administered. Network cards from hardware manufacturers will +# always be universally administered to guarantee global uniqueness of the MAC +# address, but any particular machine may have other interfaces which are +# locally administered. An example of the latter is the bridge interface to +# the Touch Bar on MacBook Pros. +# +# This bit works out to be the 42nd bit counting from 1 being the least +# significant, or 1<<41. We'll prefer universally administered MAC addresses +# over locally administered ones since the former are globally unique, but +# we'll return the first of the latter found if that's all the machine has. +# +# See https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local + +def _is_universal(mac): + return not (mac & (1 << 41)) + + +def _find_mac_near_keyword(command, args, keywords, get_word_index): + """Searches a command's output for a MAC address near a keyword. + + Each line of words in the output is case-insensitively searched for + any of the given keywords. Upon a match, get_word_index is invoked + to pick a word from the line, given the index of the match. For + example, lambda i: 0 would get the first word on the line, while + lambda i: i - 1 would get the word preceding the keyword. + """ + stdout = _get_command_stdout(command, args) + if stdout is None: + return None + + first_local_mac = None + for line in stdout: + words = line.lower().rstrip().split() + for i in range(len(words)): + if words[i] in keywords: + try: + word = words[get_word_index(i)] + mac = int(word.replace(_MAC_DELIM, b''), 16) + except (ValueError, IndexError): + # Virtual interfaces, such as those provided by + # VPNs, do not have a colon-delimited MAC address + # as expected, but a 16-byte HWAddr separated by + # dashes. These should be ignored in favor of a + # real MAC address + pass + else: + if _is_universal(mac): + return mac + first_local_mac = first_local_mac or mac + return first_local_mac or None + + +def _parse_mac(word): + # Accept 'HH:HH:HH:HH:HH:HH' MAC address (ex: '52:54:00:9d:0e:67'), + # but reject IPv6 address (ex: 'fe80::5054:ff:fe9' or '123:2:3:4:5:6:7:8'). + # + # Virtual interfaces, such as those provided by VPNs, do not have a + # colon-delimited MAC address as expected, but a 16-byte HWAddr separated + # by dashes. These should be ignored in favor of a real MAC address + parts = word.split(_MAC_DELIM) + if len(parts) != 6: + return + if _MAC_OMITS_LEADING_ZEROES: + # (Only) on AIX the macaddr value given is not prefixed by 0, e.g. + # en0 1500 link#2 fa.bc.de.f7.62.4 110854824 0 160133733 0 0 + # not + # en0 1500 link#2 fa.bc.de.f7.62.04 110854824 0 160133733 0 0 + if not all(1 <= len(part) <= 2 for part in parts): + return + hexstr = b''.join(part.rjust(2, b'0') for part in parts) + else: + if not all(len(part) == 2 for part in parts): + return + hexstr = b''.join(parts) + try: + return int(hexstr, 16) + except ValueError: + return + + +def _find_mac_under_heading(command, args, heading): + """Looks for a MAC address under a heading in a command's output. + + The first line of words in the output is searched for the given + heading. Words at the same word index as the heading in subsequent + lines are then examined to see if they look like MAC addresses. + """ + stdout = _get_command_stdout(command, args) + if stdout is None: + return None + + keywords = stdout.readline().rstrip().split() + try: + column_index = keywords.index(heading) + except ValueError: + return None + + first_local_mac = None + for line in stdout: + words = line.rstrip().split() + try: + word = words[column_index] + except IndexError: + continue + + mac = _parse_mac(word) + if mac is None: + continue + if _is_universal(mac): + return mac + if first_local_mac is None: + first_local_mac = mac + + return first_local_mac + + +# The following functions call external programs to 'get' a macaddr value to +# be used as basis for an uuid +def _ifconfig_getnode(): + """Get the hardware address on Unix by running ifconfig.""" + # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes. + keywords = (b'hwaddr', b'ether', b'address:', b'lladdr') + for args in ('', '-a', '-av'): + mac = _find_mac_near_keyword('ifconfig', args, keywords, lambda i: i+1) + if mac: + return mac + return None + +def _ip_getnode(): + """Get the hardware address on Unix by running ip.""" + # This works on Linux with iproute2. + mac = _find_mac_near_keyword('ip', 'link', [b'link/ether'], lambda i: i+1) + if mac: + return mac + return None + +def _arp_getnode(): + """Get the hardware address on Unix by running arp.""" + import os, socket + try: + ip_addr = socket.gethostbyname(socket.gethostname()) + except OSError: + return None + + # Try getting the MAC addr from arp based on our IP address (Solaris). + mac = _find_mac_near_keyword('arp', '-an', [os.fsencode(ip_addr)], lambda i: -1) + if mac: + return mac + + # This works on OpenBSD + mac = _find_mac_near_keyword('arp', '-an', [os.fsencode(ip_addr)], lambda i: i+1) + if mac: + return mac + + # This works on Linux, FreeBSD and NetBSD + mac = _find_mac_near_keyword('arp', '-an', [os.fsencode('(%s)' % ip_addr)], + lambda i: i+2) + # Return None instead of 0. + if mac: + return mac + return None + +def _lanscan_getnode(): + """Get the hardware address on Unix by running lanscan.""" + # This might work on HP-UX. + return _find_mac_near_keyword('lanscan', '-ai', [b'lan0'], lambda i: 0) + +def _netstat_getnode(): + """Get the hardware address on Unix by running netstat.""" + # This works on AIX and might work on Tru64 UNIX. + return _find_mac_under_heading('netstat', '-ian', b'Address') + +def _ipconfig_getnode(): + """[DEPRECATED] Get the hardware address on Windows.""" + # bpo-40501: UuidCreateSequential() is now the only supported approach + return _windll_getnode() + +def _netbios_getnode(): + """[DEPRECATED] Get the hardware address on Windows.""" + # bpo-40501: UuidCreateSequential() is now the only supported approach + return _windll_getnode() + + +# Import optional C extension at toplevel, to help disabling it when testing +try: + import _uuid + _generate_time_safe = getattr(_uuid, "generate_time_safe", None) + _UuidCreate = getattr(_uuid, "UuidCreate", None) + _has_uuid_generate_time_safe = _uuid.has_uuid_generate_time_safe +except ImportError: + _uuid = None + _generate_time_safe = None + _UuidCreate = None + _has_uuid_generate_time_safe = None + + +def _load_system_functions(): + """[DEPRECATED] Platform-specific functions loaded at import time""" + + +def _unix_getnode(): + """Get the hardware address on Unix using the _uuid extension module.""" + if _generate_time_safe: + uuid_time, _ = _generate_time_safe() + return UUID(bytes=uuid_time).node + +def _windll_getnode(): + """Get the hardware address on Windows using the _uuid extension module.""" + if _UuidCreate: + uuid_bytes = _UuidCreate() + return UUID(bytes_le=uuid_bytes).node + +def _random_getnode(): + """Get a random node ID.""" + # RFC 4122, $4.1.6 says "For systems with no IEEE address, a randomly or + # pseudo-randomly generated value may be used; see Section 4.5. The + # multicast bit must be set in such addresses, in order that they will + # never conflict with addresses obtained from network cards." + # + # The "multicast bit" of a MAC address is defined to be "the least + # significant bit of the first octet". This works out to be the 41st bit + # counting from 1 being the least significant bit, or 1<<40. + # + # See https://en.wikipedia.org/wiki/MAC_address#Unicast_vs._multicast + import random + return random.getrandbits(48) | (1 << 40) + + +# _OS_GETTERS, when known, are targeted for a specific OS or platform. +# The order is by 'common practice' on the specified platform. +# Note: 'posix' and 'windows' _OS_GETTERS are prefixed by a dll/dlload() method +# which, when successful, means none of these "external" methods are called. +# _GETTERS is (also) used by test_uuid.py to SkipUnless(), e.g., +# @unittest.skipUnless(_uuid._ifconfig_getnode in _uuid._GETTERS, ...) +if _LINUX: + _OS_GETTERS = [_ip_getnode, _ifconfig_getnode] +elif sys.platform == 'darwin': + _OS_GETTERS = [_ifconfig_getnode, _arp_getnode, _netstat_getnode] +elif sys.platform == 'win32': + # bpo-40201: _windll_getnode will always succeed, so these are not needed + _OS_GETTERS = [] +elif _AIX: + _OS_GETTERS = [_netstat_getnode] +else: + _OS_GETTERS = [_ifconfig_getnode, _ip_getnode, _arp_getnode, + _netstat_getnode, _lanscan_getnode] +if os.name == 'posix': + _GETTERS = [_unix_getnode] + _OS_GETTERS +elif os.name == 'nt': + _GETTERS = [_windll_getnode] + _OS_GETTERS +else: + _GETTERS = _OS_GETTERS + +_node = None + +def getnode(): + """Get the hardware address as a 48-bit positive integer. + + The first time this runs, it may launch a separate program, which could + be quite slow. If all attempts to obtain the hardware address fail, we + choose a random 48-bit number with its eighth bit set to 1 as recommended + in RFC 4122. + """ + global _node + if _node is not None: + return _node + + for getter in _GETTERS + [_random_getnode]: + try: + _node = getter() + except: + continue + if (_node is not None) and (0 <= _node < (1 << 48)): + return _node + assert False, '_random_getnode() returned invalid value: {}'.format(_node) + + +_last_timestamp = None + +def uuid1(node=None, clock_seq=None): + """Generate a UUID from a host ID, sequence number, and the current time. + If 'node' is not given, getnode() is used to obtain the hardware + address. If 'clock_seq' is given, it is used as the sequence number; + otherwise a random 14-bit sequence number is chosen.""" + + # When the system provides a version-1 UUID generator, use it (but don't + # use UuidCreate here because its UUIDs don't conform to RFC 4122). + if _generate_time_safe is not None and node is clock_seq is None: + uuid_time, safely_generated = _generate_time_safe() + try: + is_safe = SafeUUID(safely_generated) + except ValueError: + is_safe = SafeUUID.unknown + return UUID(bytes=uuid_time, is_safe=is_safe) + + global _last_timestamp + import time + nanoseconds = time.time_ns() + # 0x01b21dd213814000 is the number of 100-ns intervals between the + # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. + timestamp = nanoseconds // 100 + 0x01b21dd213814000 + if _last_timestamp is not None and timestamp <= _last_timestamp: + timestamp = _last_timestamp + 1 + _last_timestamp = timestamp + if clock_seq is None: + import random + clock_seq = random.getrandbits(14) # instead of stable storage + time_low = timestamp & 0xffffffff + time_mid = (timestamp >> 32) & 0xffff + time_hi_version = (timestamp >> 48) & 0x0fff + clock_seq_low = clock_seq & 0xff + clock_seq_hi_variant = (clock_seq >> 8) & 0x3f + if node is None: + node = getnode() + return UUID(fields=(time_low, time_mid, time_hi_version, + clock_seq_hi_variant, clock_seq_low, node), version=1) + +def uuid3(namespace, name): + """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" + from hashlib import md5 + digest = md5( + namespace.bytes + bytes(name, "utf-8"), + usedforsecurity=False + ).digest() + return UUID(bytes=digest[:16], version=3) + +def uuid4(): + """Generate a random UUID.""" + return UUID(bytes=os.urandom(16), version=4) + +def uuid5(namespace, name): + """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" + from hashlib import sha1 + hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest() + return UUID(bytes=hash[:16], version=5) + +# The following standard UUIDs are for use with uuid3() or uuid5(). + +NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') +NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8') +NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8') +NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8') diff --git a/shared/package-files/75/75c0f7cc6b1e8e8c67228db88fb665b909442f095818def1b7e9610aed6c15fd/blob b/shared/package-files/75/75c0f7cc6b1e8e8c67228db88fb665b909442f095818def1b7e9610aed6c15fd/blob new file mode 100644 index 0000000000000000000000000000000000000000..58816959f7cd2276274d71436c46d2c36315c631 --- /dev/null +++ b/shared/package-files/75/75c0f7cc6b1e8e8c67228db88fb665b909442f095818def1b7e9610aed6c15fd/blob @@ -0,0 +1,118 @@ +import itertools +from typing import List, Sequence, Union + +from torchgen.api import cpp + +from torchgen.api.types import ArgName, Binding, CType, NamedCType +from torchgen.model import ( + Argument, + FunctionSchema, + Return, + SelfArgument, + TensorOptionsArguments, + Type, +) +from torchgen.utils import assert_never, concatMap + +# This file describes the translation of JIT schema to the dispatcher +# API, the *unboxed* calling convention by which invocations through +# the dispatcher are made. Historically, the dispatcher API matched +# the C++ API, but with the establishment of the boxed API, we've +# made changes to the dispatcher API to so that the unboxed API +# better aligns with the boxed API. The dispatcher API hooks heavily +# into our template based boxing/unboxing machinery, so changes +# to this convention will usually need template updates too. +# +# Prominent characteristics of the dispatcher API: +# +# - dtype, layout, device and pin_memory are represented as separate +# arguments. +# + + +def name(func: FunctionSchema) -> str: + return cpp.name(func) + + +def argumenttype_type( + t: Type, + *, + mutable: bool, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = True, +) -> NamedCType: + # This is a faux amis. If it makes sense in the future to add + # more special cases here, or invert things so cpp.argument_type + # calls this, or just completely inline the function, please do + # it. + return cpp.argumenttype_type( + t, + mutable=mutable, + binds=binds, + symint=symint, + remove_non_owning_ref_types=remove_non_owning_ref_types, + ) + + +def argument_type( + a: Argument, + *, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = True, +) -> NamedCType: + return argumenttype_type( + a.type, + mutable=a.is_write, + binds=binds, + remove_non_owning_ref_types=remove_non_owning_ref_types, + symint=symint, + ) + + +def returns_type(rs: Sequence[Return], *, symint: bool = True) -> CType: + # At present, there is no difference. But there could be! + return cpp.returns_type(rs, symint=symint) + + +def jit_arguments(func: FunctionSchema) -> List[Argument]: + def to_argument( + a: Union[Argument, TensorOptionsArguments, SelfArgument] + ) -> List[Argument]: + if isinstance(a, Argument): + return [a] + elif isinstance(a, SelfArgument): + return [a.argument] + elif isinstance(a, TensorOptionsArguments): + return [a.dtype, a.layout, a.device, a.pin_memory] + else: + assert_never(a) + + return list( + concatMap( + to_argument, + itertools.chain( + func.arguments.positional, func.arguments.kwarg_only, func.arguments.out + ), + ) + ) + + +def argument( + a: Argument, *, remove_non_owning_ref_types: bool = False, symint: bool = True +) -> Binding: + return Binding( + nctype=argument_type( + a, + binds=a.name, + remove_non_owning_ref_types=remove_non_owning_ref_types, + symint=symint, + ), + name=a.name, + argument=a, + ) + + +def arguments(func: FunctionSchema, *, symint: bool = True) -> List[Binding]: + return [argument(a, symint=symint) for a in jit_arguments(func)] diff --git a/shared/package-files/75/75c3e50711eaa4a27a253049b24bf0d821372187daf97b74db48df4ac9702e3b/blob b/shared/package-files/75/75c3e50711eaa4a27a253049b24bf0d821372187daf97b74db48df4ac9702e3b/blob new file mode 100644 index 0000000000000000000000000000000000000000..a96df27b48d7d8dc0b2f26cc25f0dca16ea3b462 --- /dev/null +++ b/shared/package-files/75/75c3e50711eaa4a27a253049b24bf0d821372187daf97b74db48df4ac9702e3b/blob @@ -0,0 +1,225 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Series, + date_range, +) +import pandas._testing as tm + + +class TestDataFrameRound: + def test_round(self): + # GH#2665 + + # Test that rounding an empty DataFrame does nothing + df = DataFrame() + tm.assert_frame_equal(df, df.round()) + + # Here's the test frame we'll be working with + df = DataFrame({"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]}) + + # Default round to integer (i.e. decimals=0) + expected_rounded = DataFrame({"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]}) + tm.assert_frame_equal(df.round(), expected_rounded) + + # Round with an integer + decimals = 2 + expected_rounded = DataFrame( + {"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]} + ) + tm.assert_frame_equal(df.round(decimals), expected_rounded) + + # This should also work with np.round (since np.round dispatches to + # df.round) + tm.assert_frame_equal(np.round(df, decimals), expected_rounded) + + # Round with a list + round_list = [1, 2] + msg = "decimals must be an integer, a dict-like or a Series" + with pytest.raises(TypeError, match=msg): + df.round(round_list) + + # Round with a dictionary + expected_rounded = DataFrame( + {"col1": [1.1, 2.1, 3.1], "col2": [1.23, 2.23, 3.23]} + ) + round_dict = {"col1": 1, "col2": 2} + tm.assert_frame_equal(df.round(round_dict), expected_rounded) + + # Incomplete dict + expected_partially_rounded = DataFrame( + {"col1": [1.123, 2.123, 3.123], "col2": [1.2, 2.2, 3.2]} + ) + partial_round_dict = {"col2": 1} + tm.assert_frame_equal(df.round(partial_round_dict), expected_partially_rounded) + + # Dict with unknown elements + wrong_round_dict = {"col3": 2, "col2": 1} + tm.assert_frame_equal(df.round(wrong_round_dict), expected_partially_rounded) + + # float input to `decimals` + non_int_round_dict = {"col1": 1, "col2": 0.5} + msg = "Values in decimals must be integers" + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_dict) + + # String input + non_int_round_dict = {"col1": 1, "col2": "foo"} + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_dict) + + non_int_round_Series = Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + # List input + non_int_round_dict = {"col1": 1, "col2": [1, 2]} + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_dict) + + non_int_round_Series = Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + # Non integer Series inputs + non_int_round_Series = Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + non_int_round_Series = Series(non_int_round_dict) + with pytest.raises(TypeError, match=msg): + df.round(non_int_round_Series) + + # Negative numbers + negative_round_dict = {"col1": -1, "col2": -2} + big_df = df * 100 + expected_neg_rounded = DataFrame( + {"col1": [110.0, 210, 310], "col2": [100.0, 200, 300]} + ) + tm.assert_frame_equal(big_df.round(negative_round_dict), expected_neg_rounded) + + # nan in Series round + nan_round_Series = Series({"col1": np.nan, "col2": 1}) + + with pytest.raises(TypeError, match=msg): + df.round(nan_round_Series) + + # Make sure this doesn't break existing Series.round + tm.assert_series_equal(df["col1"].round(1), expected_rounded["col1"]) + + # named columns + # GH#11986 + decimals = 2 + expected_rounded = DataFrame( + {"col1": [1.12, 2.12, 3.12], "col2": [1.23, 2.23, 3.23]} + ) + df.columns.name = "cols" + expected_rounded.columns.name = "cols" + tm.assert_frame_equal(df.round(decimals), expected_rounded) + + # interaction of named columns & series + tm.assert_series_equal(df["col1"].round(decimals), expected_rounded["col1"]) + tm.assert_series_equal(df.round(decimals)["col1"], expected_rounded["col1"]) + + def test_round_numpy(self): + # GH#12600 + df = DataFrame([[1.53, 1.36], [0.06, 7.01]]) + out = np.round(df, decimals=0) + expected = DataFrame([[2.0, 1.0], [0.0, 7.0]]) + tm.assert_frame_equal(out, expected) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.round(df, decimals=0, out=df) + + def test_round_numpy_with_nan(self): + # See GH#14197 + df = Series([1.53, np.nan, 0.06]).to_frame() + with tm.assert_produces_warning(None): + result = df.round() + expected = Series([2.0, np.nan, 0.0]).to_frame() + tm.assert_frame_equal(result, expected) + + def test_round_mixed_type(self): + # GH#11885 + df = DataFrame( + { + "col1": [1.1, 2.2, 3.3, 4.4], + "col2": ["1", "a", "c", "f"], + "col3": date_range("20111111", periods=4), + } + ) + round_0 = DataFrame( + { + "col1": [1.0, 2.0, 3.0, 4.0], + "col2": ["1", "a", "c", "f"], + "col3": date_range("20111111", periods=4), + } + ) + tm.assert_frame_equal(df.round(), round_0) + tm.assert_frame_equal(df.round(1), df) + tm.assert_frame_equal(df.round({"col1": 1}), df) + tm.assert_frame_equal(df.round({"col1": 0}), round_0) + tm.assert_frame_equal(df.round({"col1": 0, "col2": 1}), round_0) + tm.assert_frame_equal(df.round({"col3": 1}), df) + + def test_round_with_duplicate_columns(self): + # GH#11611 + + df = DataFrame( + np.random.default_rng(2).random([3, 3]), + columns=["A", "B", "C"], + index=["first", "second", "third"], + ) + + dfs = pd.concat((df, df), axis=1) + rounded = dfs.round() + tm.assert_index_equal(rounded.index, dfs.index) + + decimals = Series([1, 0, 2], index=["A", "B", "A"]) + msg = "Index of decimals must be unique" + with pytest.raises(ValueError, match=msg): + df.round(decimals) + + def test_round_builtin(self): + # GH#11763 + # Here's the test frame we'll be working with + df = DataFrame({"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]}) + + # Default round to integer (i.e. decimals=0) + expected_rounded = DataFrame({"col1": [1.0, 2.0, 3.0], "col2": [1.0, 2.0, 3.0]}) + tm.assert_frame_equal(round(df), expected_rounded) + + def test_round_nonunique_categorical(self): + # See GH#21809 + idx = pd.CategoricalIndex(["low"] * 3 + ["hi"] * 3) + df = DataFrame(np.random.default_rng(2).random((6, 3)), columns=list("abc")) + + expected = df.round(3) + expected.index = idx + + df_categorical = df.copy().set_index(idx) + assert df_categorical.shape == (6, 3) + result = df_categorical.round(3) + assert result.shape == (6, 3) + + tm.assert_frame_equal(result, expected) + + def test_round_interval_category_columns(self): + # GH#30063 + columns = pd.CategoricalIndex(pd.interval_range(0, 2)) + df = DataFrame([[0.66, 1.1], [0.3, 0.25]], columns=columns) + + result = df.round() + expected = DataFrame([[1.0, 1.0], [0.0, 0.0]], columns=columns) + tm.assert_frame_equal(result, expected) + + def test_round_empty_not_input(self): + # GH#51032 + df = DataFrame() + result = df.round() + tm.assert_frame_equal(df, result) + assert df is not result diff --git a/shared/package-files/75/75c49ab527b21d39e556b483a3e9a9167a59e0e482cff9b469396c42a9e72b2f/blob b/shared/package-files/75/75c49ab527b21d39e556b483a3e9a9167a59e0e482cff9b469396c42a9e72b2f/blob new file mode 100644 index 0000000000000000000000000000000000000000..938de0c6ce3a876aeb85b805140adeb8cc04e229 --- /dev/null +++ b/shared/package-files/75/75c49ab527b21d39e556b483a3e9a9167a59e0e482cff9b469396c42a9e72b2f/blob @@ -0,0 +1,31 @@ +error(0.008847086702401418812) D0 D2 +error(0.005000000000000000104) D0 D3 +error(0.02673132695496444056) D0 D4 +error(0.003484238293381347606) D0 D5 +error(0.008059698278266469451) D0 D7 +error(0.01315919076785178159) D0 L0 +error(0.01313348418835214027) D1 D3 +error(0.03195784914476496041) D1 D5 +error(0.006788950350079408363) D1 L0 +error(0.01096448676392545486) D2 +error(0.002352645825370092147) D2 D4 +error(0.03365062765530446587) D2 D6 +error(0.003659515932194268295) D2 D7 +error(0.03470535105664898645) D3 +error(0.005183984117535067604) D3 D5 +error(0.02717618770334534473) D3 D7 +error(0.01079936451741203562) D4 D6 +error(0.01188111856827944735) D4 D7 +error(0.03266899465127193203) D4 L0 +error(0.02390459564455948982) D5 D7 +error(0.02567676778929081985) D5 L0 +error(0.01805572619911460439) D6 +error(0.04527504299860020398) D7 +detector(4, 3, 0) D0 +detector(6, 1, 0) D1 +detector(4, 5, 0) D2 +detector(6, 3, 0) D3 +detector(4, 3, 1) D4 +detector(6, 1, 1) D5 +detector(4, 5, 1) D6 +detector(6, 3, 1) D7 diff --git a/shared/package-files/75/75c5fd90d28b1e2fd75e414704f4be7dc33e3da7982a45fcd239b3c42d2c8a24/blob b/shared/package-files/75/75c5fd90d28b1e2fd75e414704f4be7dc33e3da7982a45fcd239b3c42d2c8a24/blob new file mode 100644 index 0000000000000000000000000000000000000000..12f707b60b4ad0bcadc35a222d9abe0cc5e033fc --- /dev/null +++ b/shared/package-files/75/75c5fd90d28b1e2fd75e414704f4be7dc33e3da7982a45fcd239b3c42d2c8a24/blob @@ -0,0 +1,469 @@ +"""Module with functions operating on IndexedBase, Indexed and Idx objects + + - Check shape conformance + - Determine indices in resulting expression + + etc. + + Methods in this module could be implemented by calling methods on Expr + objects instead. When things stabilize this could be a useful + refactoring. +""" + +from functools import reduce + +from sympy.core.function import Function +from sympy.functions import exp, Piecewise +from sympy.tensor.indexed import Idx, Indexed +from sympy.utilities import sift + +from collections import OrderedDict + +class IndexConformanceException(Exception): + pass + +def _unique_and_repeated(inds): + """ + Returns the unique and repeated indices. Also note, from the examples given below + that the order of indices is maintained as given in the input. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _unique_and_repeated + >>> _unique_and_repeated([2, 3, 1, 3, 0, 4, 0]) + ([2, 1, 4], [3, 0]) + """ + uniq = OrderedDict() + for i in inds: + if i in uniq: + uniq[i] = 0 + else: + uniq[i] = 1 + return sift(uniq, lambda x: uniq[x], binary=True) + +def _remove_repeated(inds): + """ + Removes repeated objects from sequences + + Returns a set of the unique objects and a tuple of all that have been + removed. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _remove_repeated + >>> l1 = [1, 2, 3, 2] + >>> _remove_repeated(l1) + ({1, 3}, (2,)) + + """ + u, r = _unique_and_repeated(inds) + return set(u), tuple(r) + + +def _get_indices_Mul(expr, return_dummies=False): + """Determine the outer indices of a Mul object. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _get_indices_Mul + >>> from sympy.tensor.indexed import IndexedBase, Idx + >>> i, j, k = map(Idx, ['i', 'j', 'k']) + >>> x = IndexedBase('x') + >>> y = IndexedBase('y') + >>> _get_indices_Mul(x[i, k]*y[j, k]) + ({i, j}, {}) + >>> _get_indices_Mul(x[i, k]*y[j, k], return_dummies=True) + ({i, j}, {}, (k,)) + + """ + + inds = list(map(get_indices, expr.args)) + inds, syms = list(zip(*inds)) + + inds = list(map(list, inds)) + inds = list(reduce(lambda x, y: x + y, inds)) + inds, dummies = _remove_repeated(inds) + + symmetry = {} + for s in syms: + for pair in s: + if pair in symmetry: + symmetry[pair] *= s[pair] + else: + symmetry[pair] = s[pair] + + if return_dummies: + return inds, symmetry, dummies + else: + return inds, symmetry + + +def _get_indices_Pow(expr): + """Determine outer indices of a power or an exponential. + + A power is considered a universal function, so that the indices of a Pow is + just the collection of indices present in the expression. This may be + viewed as a bit inconsistent in the special case: + + x[i]**2 = x[i]*x[i] (1) + + The above expression could have been interpreted as the contraction of x[i] + with itself, but we choose instead to interpret it as a function + + lambda y: y**2 + + applied to each element of x (a universal function in numpy terms). In + order to allow an interpretation of (1) as a contraction, we need + contravariant and covariant Idx subclasses. (FIXME: this is not yet + implemented) + + Expressions in the base or exponent are subject to contraction as usual, + but an index that is present in the exponent, will not be considered + contractable with its own base. Note however, that indices in the same + exponent can be contracted with each other. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _get_indices_Pow + >>> from sympy import Pow, exp, IndexedBase, Idx + >>> A = IndexedBase('A') + >>> x = IndexedBase('x') + >>> i, j, k = map(Idx, ['i', 'j', 'k']) + >>> _get_indices_Pow(exp(A[i, j]*x[j])) + ({i}, {}) + >>> _get_indices_Pow(Pow(x[i], x[i])) + ({i}, {}) + >>> _get_indices_Pow(Pow(A[i, j]*x[j], x[i])) + ({i}, {}) + + """ + base, exp = expr.as_base_exp() + binds, bsyms = get_indices(base) + einds, esyms = get_indices(exp) + + inds = binds | einds + + # FIXME: symmetries from power needs to check special cases, else nothing + symmetries = {} + + return inds, symmetries + + +def _get_indices_Add(expr): + """Determine outer indices of an Add object. + + In a sum, each term must have the same set of outer indices. A valid + expression could be + + x(i)*y(j) - x(j)*y(i) + + But we do not allow expressions like: + + x(i)*y(j) - z(j)*z(j) + + FIXME: Add support for Numpy broadcasting + + Examples + ======== + + >>> from sympy.tensor.index_methods import _get_indices_Add + >>> from sympy.tensor.indexed import IndexedBase, Idx + >>> i, j, k = map(Idx, ['i', 'j', 'k']) + >>> x = IndexedBase('x') + >>> y = IndexedBase('y') + >>> _get_indices_Add(x[i] + x[k]*y[i, k]) + ({i}, {}) + + """ + + inds = list(map(get_indices, expr.args)) + inds, syms = list(zip(*inds)) + + # allow broadcast of scalars + non_scalars = [x for x in inds if x != set()] + if not non_scalars: + return set(), {} + + if not all(x == non_scalars[0] for x in non_scalars[1:]): + raise IndexConformanceException("Indices are not consistent: %s" % expr) + if not reduce(lambda x, y: x != y or y, syms): + symmetries = syms[0] + else: + # FIXME: search for symmetries + symmetries = {} + + return non_scalars[0], symmetries + + +def get_indices(expr): + """Determine the outer indices of expression ``expr`` + + By *outer* we mean indices that are not summation indices. Returns a set + and a dict. The set contains outer indices and the dict contains + information about index symmetries. + + Examples + ======== + + >>> from sympy.tensor.index_methods import get_indices + >>> from sympy import symbols + >>> from sympy.tensor import IndexedBase + >>> x, y, A = map(IndexedBase, ['x', 'y', 'A']) + >>> i, j, a, z = symbols('i j a z', integer=True) + + The indices of the total expression is determined, Repeated indices imply a + summation, for instance the trace of a matrix A: + + >>> get_indices(A[i, i]) + (set(), {}) + + In the case of many terms, the terms are required to have identical + outer indices. Else an IndexConformanceException is raised. + + >>> get_indices(x[i] + A[i, j]*y[j]) + ({i}, {}) + + :Exceptions: + + An IndexConformanceException means that the terms ar not compatible, e.g. + + >>> get_indices(x[i] + y[j]) #doctest: +SKIP + (...) + IndexConformanceException: Indices are not consistent: x(i) + y(j) + + .. warning:: + The concept of *outer* indices applies recursively, starting on the deepest + level. This implies that dummies inside parenthesis are assumed to be + summed first, so that the following expression is handled gracefully: + + >>> get_indices((x[i] + A[i, j]*y[j])*x[j]) + ({i, j}, {}) + + This is correct and may appear convenient, but you need to be careful + with this as SymPy will happily .expand() the product, if requested. The + resulting expression would mix the outer ``j`` with the dummies inside + the parenthesis, which makes it a different expression. To be on the + safe side, it is best to avoid such ambiguities by using unique indices + for all contractions that should be held separate. + + """ + # We call ourself recursively to determine indices of sub expressions. + + # break recursion + if isinstance(expr, Indexed): + c = expr.indices + inds, dummies = _remove_repeated(c) + return inds, {} + elif expr is None: + return set(), {} + elif isinstance(expr, Idx): + return {expr}, {} + elif expr.is_Atom: + return set(), {} + + + # recurse via specialized functions + else: + if expr.is_Mul: + return _get_indices_Mul(expr) + elif expr.is_Add: + return _get_indices_Add(expr) + elif expr.is_Pow or isinstance(expr, exp): + return _get_indices_Pow(expr) + + elif isinstance(expr, Piecewise): + # FIXME: No support for Piecewise yet + return set(), {} + elif isinstance(expr, Function): + # Support ufunc like behaviour by returning indices from arguments. + # Functions do not interpret repeated indices across arguments + # as summation + ind0 = set() + for arg in expr.args: + ind, sym = get_indices(arg) + ind0 |= ind + return ind0, sym + + # this test is expensive, so it should be at the end + elif not expr.has(Indexed): + return set(), {} + raise NotImplementedError( + "FIXME: No specialized handling of type %s" % type(expr)) + + +def get_contraction_structure(expr): + """Determine dummy indices of ``expr`` and describe its structure + + By *dummy* we mean indices that are summation indices. + + The structure of the expression is determined and described as follows: + + 1) A conforming summation of Indexed objects is described with a dict where + the keys are summation indices and the corresponding values are sets + containing all terms for which the summation applies. All Add objects + in the SymPy expression tree are described like this. + + 2) For all nodes in the SymPy expression tree that are *not* of type Add, the + following applies: + + If a node discovers contractions in one of its arguments, the node + itself will be stored as a key in the dict. For that key, the + corresponding value is a list of dicts, each of which is the result of a + recursive call to get_contraction_structure(). The list contains only + dicts for the non-trivial deeper contractions, omitting dicts with None + as the one and only key. + + .. Note:: The presence of expressions among the dictionary keys indicates + multiple levels of index contractions. A nested dict displays nested + contractions and may itself contain dicts from a deeper level. In + practical calculations the summation in the deepest nested level must be + calculated first so that the outer expression can access the resulting + indexed object. + + Examples + ======== + + >>> from sympy.tensor.index_methods import get_contraction_structure + >>> from sympy import default_sort_key + >>> from sympy.tensor import IndexedBase, Idx + >>> x, y, A = map(IndexedBase, ['x', 'y', 'A']) + >>> i, j, k, l = map(Idx, ['i', 'j', 'k', 'l']) + >>> get_contraction_structure(x[i]*y[i] + A[j, j]) + {(i,): {x[i]*y[i]}, (j,): {A[j, j]}} + >>> get_contraction_structure(x[i]*y[j]) + {None: {x[i]*y[j]}} + + A multiplication of contracted factors results in nested dicts representing + the internal contractions. + + >>> d = get_contraction_structure(x[i, i]*y[j, j]) + >>> sorted(d.keys(), key=default_sort_key) + [None, x[i, i]*y[j, j]] + + In this case, the product has no contractions: + + >>> d[None] + {x[i, i]*y[j, j]} + + Factors are contracted "first": + + >>> sorted(d[x[i, i]*y[j, j]], key=default_sort_key) + [{(i,): {x[i, i]}}, {(j,): {y[j, j]}}] + + A parenthesized Add object is also returned as a nested dictionary. The + term containing the parenthesis is a Mul with a contraction among the + arguments, so it will be found as a key in the result. It stores the + dictionary resulting from a recursive call on the Add expression. + + >>> d = get_contraction_structure(x[i]*(y[i] + A[i, j]*x[j])) + >>> sorted(d.keys(), key=default_sort_key) + [(A[i, j]*x[j] + y[i])*x[i], (i,)] + >>> d[(i,)] + {(A[i, j]*x[j] + y[i])*x[i]} + >>> d[x[i]*(A[i, j]*x[j] + y[i])] + [{None: {y[i]}, (j,): {A[i, j]*x[j]}}] + + Powers with contractions in either base or exponent will also be found as + keys in the dictionary, mapping to a list of results from recursive calls: + + >>> d = get_contraction_structure(A[j, j]**A[i, i]) + >>> d[None] + {A[j, j]**A[i, i]} + >>> nested_contractions = d[A[j, j]**A[i, i]] + >>> nested_contractions[0] + {(j,): {A[j, j]}} + >>> nested_contractions[1] + {(i,): {A[i, i]}} + + The description of the contraction structure may appear complicated when + represented with a string in the above examples, but it is easy to iterate + over: + + >>> from sympy import Expr + >>> for key in d: + ... if isinstance(key, Expr): + ... continue + ... for term in d[key]: + ... if term in d: + ... # treat deepest contraction first + ... pass + ... # treat outermost contactions here + + """ + + # We call ourself recursively to inspect sub expressions. + + if isinstance(expr, Indexed): + junk, key = _remove_repeated(expr.indices) + return {key or None: {expr}} + elif expr.is_Atom: + return {None: {expr}} + elif expr.is_Mul: + junk, junk, key = _get_indices_Mul(expr, return_dummies=True) + result = {key or None: {expr}} + # recurse on every factor + nested = [] + for fac in expr.args: + facd = get_contraction_structure(fac) + if not (None in facd and len(facd) == 1): + nested.append(facd) + if nested: + result[expr] = nested + return result + elif expr.is_Pow or isinstance(expr, exp): + # recurse in base and exp separately. If either has internal + # contractions we must include ourselves as a key in the returned dict + b, e = expr.as_base_exp() + dbase = get_contraction_structure(b) + dexp = get_contraction_structure(e) + + dicts = [] + for d in dbase, dexp: + if not (None in d and len(d) == 1): + dicts.append(d) + result = {None: {expr}} + if dicts: + result[expr] = dicts + return result + elif expr.is_Add: + # Note: we just collect all terms with identical summation indices, We + # do nothing to identify equivalent terms here, as this would require + # substitutions or pattern matching in expressions of unknown + # complexity. + result = {} + for term in expr.args: + # recurse on every term + d = get_contraction_structure(term) + for key in d: + if key in result: + result[key] |= d[key] + else: + result[key] = d[key] + return result + + elif isinstance(expr, Piecewise): + # FIXME: No support for Piecewise yet + return {None: expr} + elif isinstance(expr, Function): + # Collect non-trivial contraction structures in each argument + # We do not report repeated indices in separate arguments as a + # contraction + deeplist = [] + for arg in expr.args: + deep = get_contraction_structure(arg) + if not (None in deep and len(deep) == 1): + deeplist.append(deep) + d = {None: {expr}} + if deeplist: + d[expr] = deeplist + return d + + # this test is expensive, so it should be at the end + elif not expr.has(Indexed): + return {None: {expr}} + raise NotImplementedError( + "FIXME: No specialized handling of type %s" % type(expr)) diff --git a/shared/package-files/75/75c8ab309e6c9420377888c1f5545c186dd4da1b53b572fc06260e2ef1c27ddb/blob b/shared/package-files/75/75c8ab309e6c9420377888c1f5545c186dd4da1b53b572fc06260e2ef1c27ddb/blob new file mode 100644 index 0000000000000000000000000000000000000000..d8768d8e9251c6e47debeb65dff3ec056d38ee56 --- /dev/null +++ b/shared/package-files/75/75c8ab309e6c9420377888c1f5545c186dd4da1b53b572fc06260e2ef1c27ddb/blob @@ -0,0 +1,232 @@ +""" Testing + +""" + +import os +import zlib + +from io import BytesIO + + +from tempfile import mkstemp +from contextlib import contextmanager + +import numpy as np + +from numpy.testing import assert_, assert_equal +from pytest import raises as assert_raises + +from scipy.io.matlab._streams import (make_stream, + GenericStream, ZlibInputStream, + _read_into, _read_string, BLOCK_SIZE) + + +@contextmanager +def setup_test_file(): + val = b'a\x00string' + fd, fname = mkstemp() + + with os.fdopen(fd, 'wb') as fs: + fs.write(val) + with open(fname, 'rb') as fs: + gs = BytesIO(val) + cs = BytesIO(val) + yield fs, gs, cs + os.unlink(fname) + + +def test_make_stream(): + with setup_test_file() as (fs, gs, cs): + # test stream initialization + assert_(isinstance(make_stream(gs), GenericStream)) + + +def test_tell_seek(): + with setup_test_file() as (fs, gs, cs): + for s in (fs, gs, cs): + st = make_stream(s) + res = st.seek(0) + assert_equal(res, 0) + assert_equal(st.tell(), 0) + res = st.seek(5) + assert_equal(res, 0) + assert_equal(st.tell(), 5) + res = st.seek(2, 1) + assert_equal(res, 0) + assert_equal(st.tell(), 7) + res = st.seek(-2, 2) + assert_equal(res, 0) + assert_equal(st.tell(), 6) + + +def test_read(): + with setup_test_file() as (fs, gs, cs): + for s in (fs, gs, cs): + st = make_stream(s) + st.seek(0) + res = st.read(-1) + assert_equal(res, b'a\x00string') + st.seek(0) + res = st.read(4) + assert_equal(res, b'a\x00st') + # read into + st.seek(0) + res = _read_into(st, 4) + assert_equal(res, b'a\x00st') + res = _read_into(st, 4) + assert_equal(res, b'ring') + assert_raises(OSError, _read_into, st, 2) + # read alloc + st.seek(0) + res = _read_string(st, 4) + assert_equal(res, b'a\x00st') + res = _read_string(st, 4) + assert_equal(res, b'ring') + assert_raises(OSError, _read_string, st, 2) + + +class TestZlibInputStream: + def _get_data(self, size): + data = np.random.randint(0, 256, size).astype(np.uint8).tobytes() + compressed_data = zlib.compress(data) + stream = BytesIO(compressed_data) + return stream, len(compressed_data), data + + def test_read(self): + SIZES = [0, 1, 10, BLOCK_SIZE//2, BLOCK_SIZE-1, + BLOCK_SIZE, BLOCK_SIZE+1, 2*BLOCK_SIZE-1] + + READ_SIZES = [BLOCK_SIZE//2, BLOCK_SIZE-1, + BLOCK_SIZE, BLOCK_SIZE+1] + + def check(size, read_size): + compressed_stream, compressed_data_len, data = self._get_data(size) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + data2 = b'' + so_far = 0 + while True: + block = stream.read(min(read_size, + size - so_far)) + if not block: + break + so_far += len(block) + data2 += block + assert_equal(data, data2) + + for size in SIZES: + for read_size in READ_SIZES: + check(size, read_size) + + def test_read_max_length(self): + size = 1234 + data = np.random.randint(0, 256, size).astype(np.uint8).tobytes() + compressed_data = zlib.compress(data) + compressed_stream = BytesIO(compressed_data + b"abbacaca") + stream = ZlibInputStream(compressed_stream, len(compressed_data)) + + stream.read(len(data)) + assert_equal(compressed_stream.tell(), len(compressed_data)) + + assert_raises(OSError, stream.read, 1) + + def test_read_bad_checksum(self): + data = np.random.randint(0, 256, 10).astype(np.uint8).tobytes() + compressed_data = zlib.compress(data) + + # break checksum + compressed_data = (compressed_data[:-1] + + bytes([(compressed_data[-1] + 1) & 255])) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, len(compressed_data)) + + assert_raises(zlib.error, stream.read, len(data)) + + def test_seek(self): + compressed_stream, compressed_data_len, data = self._get_data(1024) + + stream = ZlibInputStream(compressed_stream, compressed_data_len) + + stream.seek(123) + p = 123 + assert_equal(stream.tell(), p) + d1 = stream.read(11) + assert_equal(d1, data[p:p+11]) + + stream.seek(321, 1) + p = 123+11+321 + assert_equal(stream.tell(), p) + d2 = stream.read(21) + assert_equal(d2, data[p:p+21]) + + stream.seek(641, 0) + p = 641 + assert_equal(stream.tell(), p) + d3 = stream.read(11) + assert_equal(d3, data[p:p+11]) + + assert_raises(OSError, stream.seek, 10, 2) + assert_raises(OSError, stream.seek, -1, 1) + assert_raises(ValueError, stream.seek, 1, 123) + + stream.seek(10000, 1) + assert_raises(OSError, stream.read, 12) + + def test_seek_bad_checksum(self): + data = np.random.randint(0, 256, 10).astype(np.uint8).tobytes() + compressed_data = zlib.compress(data) + + # break checksum + compressed_data = (compressed_data[:-1] + + bytes([(compressed_data[-1] + 1) & 255])) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, len(compressed_data)) + + assert_raises(zlib.error, stream.seek, len(data)) + + def test_all_data_read(self): + compressed_stream, compressed_data_len, data = self._get_data(1024) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + assert_(not stream.all_data_read()) + stream.seek(512) + assert_(not stream.all_data_read()) + stream.seek(1024) + assert_(stream.all_data_read()) + + def test_all_data_read_overlap(self): + COMPRESSION_LEVEL = 6 + + data = np.arange(33707000).astype(np.uint8).tobytes() + compressed_data = zlib.compress(data, COMPRESSION_LEVEL) + compressed_data_len = len(compressed_data) + + # check that part of the checksum overlaps + assert_(compressed_data_len == BLOCK_SIZE + 2) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + assert_(not stream.all_data_read()) + stream.seek(len(data)) + assert_(stream.all_data_read()) + + def test_all_data_read_bad_checksum(self): + COMPRESSION_LEVEL = 6 + + data = np.arange(33707000).astype(np.uint8).tobytes() + compressed_data = zlib.compress(data, COMPRESSION_LEVEL) + compressed_data_len = len(compressed_data) + + # check that part of the checksum overlaps + assert_(compressed_data_len == BLOCK_SIZE + 2) + + # break checksum + compressed_data = (compressed_data[:-1] + + bytes([(compressed_data[-1] + 1) & 255])) + + compressed_stream = BytesIO(compressed_data) + stream = ZlibInputStream(compressed_stream, compressed_data_len) + assert_(not stream.all_data_read()) + stream.seek(len(data)) + + assert_raises(zlib.error, stream.all_data_read) diff --git a/shared/package-files/75/75c99aa1f34f965f596aa93aadaa0c648bff5906e3d080263ede8308e8cadea8/blob b/shared/package-files/75/75c99aa1f34f965f596aa93aadaa0c648bff5906e3d080263ede8308e8cadea8/blob new file mode 100644 index 0000000000000000000000000000000000000000..95609e7045991abb311e7965a2f20700b9914745 --- /dev/null +++ b/shared/package-files/75/75c99aa1f34f965f596aa93aadaa0c648bff5906e3d080263ede8308e8cadea8/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _reshape_alias_copy_out_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::Tensor & out); +TORCH_API at::Tensor _reshape_alias_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/75c9c04a5db21193171986ec050907d56f8a2c1a104d24a811fba3ba63491e33/blob b/shared/package-files/75/75c9c04a5db21193171986ec050907d56f8a2c1a104d24a811fba3ba63491e33/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b787a2163e87c903ce0bd034b424eb1773c644d --- /dev/null +++ b/shared/package-files/75/75c9c04a5db21193171986ec050907d56f8a2c1a104d24a811fba3ba63491e33/blob @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/shared/package-files/75/75ca0533eae2ad1f2a75cd5bbe027248f859be4db74ba364cf7fb62dcdf4a4c9/blob b/shared/package-files/75/75ca0533eae2ad1f2a75cd5bbe027248f859be4db74ba364cf7fb62dcdf4a4c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..2a6cbe07629031687c249f70b51bdfbe2dd84041 --- /dev/null +++ b/shared/package-files/75/75ca0533eae2ad1f2a75cd5bbe027248f859be4db74ba364cf7fb62dcdf4a4c9/blob @@ -0,0 +1,94 @@ +""" +Internal module for console introspection +""" +from __future__ import annotations + +from shutil import get_terminal_size + + +def get_console_size() -> tuple[int | None, int | None]: + """ + Return console size as tuple = (width, height). + + Returns (None,None) in non-interactive session. + """ + from pandas import get_option + + display_width = get_option("display.width") + display_height = get_option("display.max_rows") + + # Consider + # interactive shell terminal, can detect term size + # interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term + # size non-interactive script, should disregard term size + + # in addition + # width,height have default values, but setting to 'None' signals + # should use Auto-Detection, But only in interactive shell-terminal. + # Simple. yeah. + + if in_interactive_session(): + if in_ipython_frontend(): + # sane defaults for interactive non-shell terminal + # match default for width,height in config_init + from pandas._config.config import get_default_val + + terminal_width = get_default_val("display.width") + terminal_height = get_default_val("display.max_rows") + else: + # pure terminal + terminal_width, terminal_height = get_terminal_size() + else: + terminal_width, terminal_height = None, None + + # Note if the User sets width/Height to None (auto-detection) + # and we're in a script (non-inter), this will return (None,None) + # caller needs to deal. + return display_width or terminal_width, display_height or terminal_height + + +# ---------------------------------------------------------------------- +# Detect our environment + + +def in_interactive_session() -> bool: + """ + Check if we're running in an interactive shell. + + Returns + ------- + bool + True if running under python/ipython interactive shell. + """ + from pandas import get_option + + def check_main(): + try: + import __main__ as main + except ModuleNotFoundError: + return get_option("mode.sim_interactive") + return not hasattr(main, "__file__") or get_option("mode.sim_interactive") + + try: + # error: Name '__IPYTHON__' is not defined + return __IPYTHON__ or check_main() # type: ignore[name-defined] + except NameError: + return check_main() + + +def in_ipython_frontend() -> bool: + """ + Check if we're inside an IPython zmq frontend. + + Returns + ------- + bool + """ + try: + # error: Name 'get_ipython' is not defined + ip = get_ipython() # type: ignore[name-defined] + return "zmq" in str(type(ip)).lower() + except NameError: + pass + + return False diff --git a/shared/package-files/75/75cbdd4007f9419b53d55fa8b05a133c725723c423d12af8ae67ca6640e79e7d/blob b/shared/package-files/75/75cbdd4007f9419b53d55fa8b05a133c725723c423d12af8ae67ca6640e79e7d/blob new file mode 100644 index 0000000000000000000000000000000000000000..de7a44bb820090e34bbbf7e80788e93948c801ec --- /dev/null +++ b/shared/package-files/75/75cbdd4007f9419b53d55fa8b05a133c725723c423d12af8ae67ca6640e79e7d/blob @@ -0,0 +1,248 @@ +import copy +from typing import List, Tuple + +import torch +import torch.distributed as dist +from torch._C._distributed_c10d import ( + ProcessGroup, +) +import torch.distributed._shard.sharding_spec as shard_spec +from torch.distributed._shard.sharding_spec._internals import ( + get_split_size, + get_chunked_dim_size, +) +from torch.distributed.nn.functional import ( + all_to_all, + all_to_all_single, +) +from torch.distributed._shard.metadata import ShardMetadata + +from .shard import Shard + + +def get_idx_from_placements(placements, current_rank) -> int: + """ + Return the position of the current rank in the given placements. + + Args: + placements(List[Union[_remote_device, str]]): + Specifies the placement of each shard of the Tensor. The size of + the list represents the number of shards to be created. This could + be a list of + :class:`torch.distributed._remote_device`'s. This list + could also contain a string which represents remote + device as accepted by + :class:`torch.distributed._remote_device` + current_rank (int): number of current device. + + Returns: + A int which contains the position of current device in the placement list. + """ + for idx, placement in enumerate(placements): # type: ignore[attr-defined] + if current_rank == placement.rank(): # type: ignore[union-attr] + return idx + raise RuntimeError('current_rank not in the placement.') + + +def build_reshard_metadata( + st_size: torch.Size, + sharding_spec: shard_spec.ShardingSpec, + world_size: int, +) -> Tuple[List[ShardMetadata], List[int]]: + """ + Based the given sharding spec, we calculate the offset and local shard size. + We then build a ShardMetadata on top of the calculation result. + + Args: + st_size (torch.Size): The size of the sharded tensor. + sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The + specification describing how the tensor is sharded. + world_size (int): number of ranks. + + Returns: + A Tuple of the followings: + A List[`ShardMetadata`] which contains the metadata for the shard, including + offsets, lengths and device placement. + A List[int] which contains the ranks in the order of placement. + """ + shard_dim = int(sharding_spec.dim) # type: ignore[attr-defined] + shards_metadata = [None] * world_size + ranks = [] + offsets = [0] * len(st_size) + split_size = get_split_size(st_size[shard_dim], world_size) + for idx, placement in enumerate(sharding_spec.placements): # type: ignore[attr-defined] + ranks.append(placement.rank()) + sharded_dim_size = get_chunked_dim_size(st_size[shard_dim], split_size, idx) + local_tensor_size = list(st_size) + local_tensor_size[shard_dim] = sharded_dim_size + shards_metadata[placement.rank()] = ShardMetadata( # type: ignore[call-overload] + shard_offsets=copy.deepcopy(offsets), + shard_sizes=local_tensor_size, + placement=placement, + ) + offsets[shard_dim] += sharded_dim_size + return shards_metadata, ranks # type: ignore[return-value] + + +def reshuffle_local_shard( + local_shard: torch.Tensor, + st_size: torch.Size, + sharding_spec: shard_spec.ShardingSpec, + resharding_spec: shard_spec.ShardingSpec, + pg: ProcessGroup, +) -> Tuple[List[Shard], List[ShardMetadata]]: + """ + Reshuffle the local shard directly when the reshard dim is same as the original + sharding dim. Logically we do this in two step: + 1. To collect all shards based on original sharding spec. + 2. Reshard the tensor based on the given resharding spec. + + In reality, we consolidate the two steps into one by sending the local tensor to + the new shard directly based on the resharding spec. + + Args: + local_shard (Tensor): Local tensor stored in the current rank. + st_size (torch.Size): The size of the sharded tensor. + sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The + specification describing how the tensor is sharded originally. + resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The + specification describing how the tensor will be resharded. + pg (ProcessGroup): The process group to aggregate on. + + Returns: + A Tuple of the followings: + A List[`Shard`] which contains the local tensor and its metadata. + A List[`ShardMetadata`] which contains the metadata for the shard, including + offsets, lengths and device placement. + """ + current_rank = dist.get_rank(pg) + world_size = dist.get_world_size(pg) + # Build shards_metadata first. + shards_metadata, ranks = build_reshard_metadata( + st_size, resharding_spec, world_size + ) + # Get input split size for all2all. + reshard_dim = int(resharding_spec.dim) # type: ignore[attr-defined] + split_size = get_split_size(st_size[reshard_dim], world_size) + input_split_sizes = [0] * world_size + idx = get_idx_from_placements(sharding_spec.placements, current_rank) # type: ignore[attr-defined] + new_rank = resharding_spec.placements[idx].rank() # type: ignore[union-attr, attr-defined] + input_split_sizes[new_rank] = local_shard.size(reshard_dim) + # Get output split size for all2all. + output_split_sizes = [0] * world_size + new_idx = ranks.index(current_rank) + sharded_dim_size = get_chunked_dim_size(st_size[reshard_dim], split_size, new_idx) + output_split_sizes[new_rank] = sharded_dim_size + # Get gathered_input for all2all. + local_shard = local_shard.transpose(0, reshard_dim).contiguous() + gathered_input_size = list(local_shard.size()) + gathered_input_size[0] = sharded_dim_size + gathered_input = torch.empty(gathered_input_size, device=local_shard.device, dtype=local_shard.dtype) + # all2all. + local_shard = all_to_all_single( + gathered_input, + local_shard, + input_split_sizes=input_split_sizes, + output_split_sizes=output_split_sizes, + group=pg, + ) + local_tensor = local_shard.transpose(0, reshard_dim).contiguous() + local_shards = [Shard(local_tensor, shards_metadata[current_rank])] + return local_shards, shards_metadata + + +def reshard_local_shard( + local_tensor: torch.Tensor, + st_size: torch.Size, + sharding_spec: shard_spec.ShardingSpec, + resharding_spec: shard_spec.ShardingSpec, + pg: ProcessGroup, +) -> Tuple[List[Shard], List[ShardMetadata]]: + """ + Reshard a sharded tensor given the ``resharding_spec``. When the reshard dim is + different from the original sharding dim, we need to do two steps logically: + 1. To collect all shards based on original sharding spec. + 2. Reshard the tensor based on the given resharding spec. + + In reality, we consolidate the two steps into one by sending each rank the new + shard based on the resharding spec. + + Args: + local_tensor (Tensor): Local tensor stored in the current rank. + st_size (torch.Size): The size of the sharded tensor. + sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The + specification describing how the tensor is sharded originally. + resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The + specification describing how the tensor will be resharded. + pg (ProcessGroup): The process group to aggregate on. + + Returns: + A Tuple of the followings: + A List[`Shard`] which contains the local tensor and its metadata. + A List[`ShardMetadata`] which contains the metadata for the shard, including + offsets, lengths and device placement. + """ + current_rank = dist.get_rank(pg) + world_size = dist.get_world_size(pg) + current_sharding_dim = int(sharding_spec.dim) # type: ignore[attr-defined] + reshard_dim = int(resharding_spec.dim) # type: ignore[attr-defined] + + # Build shards_metadata first. + shards_metadata, ranks = build_reshard_metadata( + st_size, resharding_spec, world_size + ) + + # Compute expected size + input_split_sizes = [] + for metadata in shards_metadata: + input_split_sizes.append(metadata.shard_sizes[reshard_dim]) + rearrange_input = any(ranks[i] > ranks[i + 1] for i in range(len(ranks) - 1)) + + if rearrange_input: + # Need to re-arrange reshard_dim of local_tensor before all2all. + indices: List[int] = [] + for metadata in shards_metadata: + offset_start_idx = metadata.shard_offsets[reshard_dim] + split_size = metadata.shard_sizes[reshard_dim] + indices += range(offset_start_idx, offset_start_idx + split_size) + local_tensor = local_tensor.index_select( + reshard_dim, torch.tensor(indices, device=local_tensor.device) + ) + + # Because reshard_dim != original shard_dim. We need to compute the + # size of tensor from each rank. + output_tensor_list = [torch.tensor(1)] * world_size + split_size = get_split_size(st_size[current_sharding_dim], world_size) + rearrange_output_list = False + indices = [] + for idx, placement in enumerate(sharding_spec.placements): # type: ignore[attr-defined] + sharded_dim_size = get_chunked_dim_size( + st_size[current_sharding_dim], split_size, idx + ) + output_tensor_size = list(st_size) + output_tensor_size[current_sharding_dim] = sharded_dim_size + output_tensor_size[reshard_dim] = input_split_sizes[current_rank] + output_tensor_list[ + placement.rank() + ] = torch.empty( # type: ignore[union-attr, index] + output_tensor_size, device=local_tensor.device, dtype=local_tensor.dtype + ) + indices.append(placement.rank()) # type: ignore[union-attr, index, arg-type] + if idx != placement.rank(): # type: ignore[union-attr] + rearrange_output_list = True + + # Perform autograd enabled all2all. + input_tensor_tuple = torch.split(local_tensor, input_split_sizes, dim=reshard_dim) + input_tensor_list = [tensor.contiguous() for tensor in input_tensor_tuple] + output_tensor_list = all_to_all( + output_tensor_list, + input_tensor_list, + group=pg, + ) + + if rearrange_output_list: + # Need to re-arrange original shard_dim of output_tensor_list. + output_tensor_list = [output_tensor_list[idx] for idx in indices] # type: ignore[call-overload] + local_tensor = torch.cat(output_tensor_list, dim=current_sharding_dim) + local_shards = [Shard(local_tensor, shards_metadata[current_rank])] + return local_shards, shards_metadata diff --git a/shared/package-files/75/75ce3fc4d19c5fa8e3490b74ce2c28a13bce5bad69207450db669290e16a0a6a/blob b/shared/package-files/75/75ce3fc4d19c5fa8e3490b74ce2c28a13bce5bad69207450db669290e16a0a6a/blob new file mode 100644 index 0000000000000000000000000000000000000000..fdb3b7b0f1dfe68cbc82c04ff675a451148cfeee --- /dev/null +++ b/shared/package-files/75/75ce3fc4d19c5fa8e3490b74ce2c28a13bce5bad69207450db669290e16a0a6a/blob @@ -0,0 +1,415 @@ +from contextlib import contextmanager +from io import BytesIO +from unittest import TestCase, mock +import importlib.metadata +import json +import subprocess +import sys +import urllib.request + +import referencing.exceptions + +from jsonschema import FormatChecker, exceptions, protocols, validators + + +class TestDeprecations(TestCase): + def test_version(self): + """ + As of v4.0.0, __version__ is deprecated in favor of importlib.metadata. + """ + + message = "Accessing jsonschema.__version__ is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import __version__ + + self.assertEqual(__version__, importlib.metadata.version("jsonschema")) + self.assertEqual(w.filename, __file__) + + def test_validators_ErrorTree(self): + """ + As of v4.0.0, importing ErrorTree from jsonschema.validators is + deprecated in favor of doing so from jsonschema.exceptions. + """ + + message = "Importing ErrorTree from jsonschema.validators is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema.validators import ErrorTree + + self.assertEqual(ErrorTree, exceptions.ErrorTree) + self.assertEqual(w.filename, __file__) + + def test_import_ErrorTree(self): + """ + As of v4.18.0, importing ErrorTree from the package root is + deprecated in favor of doing so from jsonschema.exceptions. + """ + + message = "Importing ErrorTree directly from the jsonschema package " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import ErrorTree + + self.assertEqual(ErrorTree, exceptions.ErrorTree) + self.assertEqual(w.filename, __file__) + + def test_import_FormatError(self): + """ + As of v4.18.0, importing FormatError from the package root is + deprecated in favor of doing so from jsonschema.exceptions. + """ + + message = "Importing FormatError directly from the jsonschema package " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import FormatError + + self.assertEqual(FormatError, exceptions.FormatError) + self.assertEqual(w.filename, __file__) + + def test_import_Validator(self): + """ + As of v4.19.0, importing Validator from the package root is + deprecated in favor of doing so from jsonschema.protocols. + """ + + message = "Importing Validator directly from the jsonschema package " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import Validator + + self.assertEqual(Validator, protocols.Validator) + self.assertEqual(w.filename, __file__) + + def test_validators_validators(self): + """ + As of v4.0.0, accessing jsonschema.validators.validators is + deprecated. + """ + + message = "Accessing jsonschema.validators.validators is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + value = validators.validators + + self.assertEqual(value, validators._VALIDATORS) + self.assertEqual(w.filename, __file__) + + def test_validators_meta_schemas(self): + """ + As of v4.0.0, accessing jsonschema.validators.meta_schemas is + deprecated. + """ + + message = "Accessing jsonschema.validators.meta_schemas is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + value = validators.meta_schemas + + self.assertEqual(value, validators._META_SCHEMAS) + self.assertEqual(w.filename, __file__) + + def test_RefResolver_in_scope(self): + """ + As of v4.0.0, RefResolver.in_scope is deprecated. + """ + + resolver = validators._RefResolver.from_schema({}) + message = "jsonschema.RefResolver.in_scope is deprecated " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + with resolver.in_scope("foo"): + pass + + self.assertEqual(w.filename, __file__) + + def test_Validator_is_valid_two_arguments(self): + """ + As of v4.0.0, calling is_valid with two arguments (to provide a + different schema) is deprecated. + """ + + validator = validators.Draft7Validator({}) + message = "Passing a schema to Validator.is_valid is deprecated " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + result = validator.is_valid("foo", {"type": "number"}) + + self.assertFalse(result) + self.assertEqual(w.filename, __file__) + + def test_Validator_iter_errors_two_arguments(self): + """ + As of v4.0.0, calling iter_errors with two arguments (to provide a + different schema) is deprecated. + """ + + validator = validators.Draft7Validator({}) + message = "Passing a schema to Validator.iter_errors is deprecated " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + error, = validator.iter_errors("foo", {"type": "number"}) + + self.assertEqual(error.validator, "type") + self.assertEqual(w.filename, __file__) + + def test_Validator_resolver(self): + """ + As of v4.18.0, accessing Validator.resolver is deprecated. + """ + + validator = validators.Draft7Validator({}) + message = "Accessing Draft7Validator.resolver is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + self.assertIsInstance(validator.resolver, validators._RefResolver) + + self.assertEqual(w.filename, __file__) + + def test_RefResolver(self): + """ + As of v4.18.0, RefResolver is fully deprecated. + """ + + message = "jsonschema.RefResolver is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import RefResolver + self.assertEqual(w.filename, __file__) + + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema.validators import RefResolver # noqa: F401, F811 + self.assertEqual(w.filename, __file__) + + def test_RefResolutionError(self): + """ + As of v4.18.0, RefResolutionError is deprecated in favor of directly + catching errors from the referencing library. + """ + + message = "jsonschema.exceptions.RefResolutionError is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import RefResolutionError + + self.assertEqual(RefResolutionError, exceptions._RefResolutionError) + self.assertEqual(w.filename, __file__) + + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema.exceptions import RefResolutionError + + self.assertEqual(RefResolutionError, exceptions._RefResolutionError) + self.assertEqual(w.filename, __file__) + + def test_catching_Unresolvable_directly(self): + """ + This behavior is the intended behavior (i.e. it's not deprecated), but + given we do "tricksy" things in the iterim to wrap exceptions in a + multiple inheritance subclass, we need to be extra sure it works and + stays working. + """ + validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) + + with self.assertRaises(referencing.exceptions.Unresolvable) as e: + validator.validate(12) + + expected = referencing.exceptions.Unresolvable(ref="urn:nothing") + self.assertEqual( + (e.exception, str(e.exception)), + (expected, "Unresolvable: urn:nothing") + ) + + def test_catching_Unresolvable_via_RefResolutionError(self): + """ + Until RefResolutionError is removed, it is still possible to catch + exceptions from reference resolution using it, even though they may + have been raised by referencing. + """ + with self.assertWarns(DeprecationWarning): + from jsonschema import RefResolutionError + + validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) + + with self.assertRaises(referencing.exceptions.Unresolvable) as u: + validator.validate(12) + + with self.assertRaises(RefResolutionError) as e: + validator.validate(12) + + self.assertEqual( + (e.exception, str(e.exception)), + (u.exception, "Unresolvable: urn:nothing") + ) + + def test_WrappedReferencingError_hashability(self): + """ + Ensure the wrapped referencing errors are hashable when possible. + """ + with self.assertWarns(DeprecationWarning): + from jsonschema import RefResolutionError + + validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) + + with self.assertRaises(referencing.exceptions.Unresolvable) as u: + validator.validate(12) + + with self.assertRaises(RefResolutionError) as e: + validator.validate(12) + + self.assertIn(e.exception, {u.exception}) + self.assertIn(u.exception, {e.exception}) + + def test_Validator_subclassing(self): + """ + As of v4.12.0, subclassing a validator class produces an explicit + deprecation warning. + + This was never intended to be public API (and some comments over the + years in issues said so, but obviously that's not a great way to make + sure it's followed). + + A future version will explicitly raise an error. + """ + + message = "Subclassing validator classes is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + class Subclass(validators.Draft202012Validator): + pass + + self.assertEqual(w.filename, __file__) + + with self.assertWarnsRegex(DeprecationWarning, message) as w: + class AnotherSubclass(validators.create(meta_schema={})): + pass + + def test_FormatChecker_cls_checks(self): + """ + As of v4.14.0, FormatChecker.cls_checks is deprecated without + replacement. + """ + + self.addCleanup(FormatChecker.checkers.pop, "boom", None) + + message = "FormatChecker.cls_checks " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + FormatChecker.cls_checks("boom") + + self.assertEqual(w.filename, __file__) + + def test_draftN_format_checker(self): + """ + As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated + in favor of Validator.FORMAT_CHECKER. + """ + + message = "Accessing jsonschema.draft202012_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft202012_format_checker + + self.assertIs( + draft202012_format_checker, + validators.Draft202012Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft201909_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft201909_format_checker + + self.assertIs( + draft201909_format_checker, + validators.Draft201909Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft7_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft7_format_checker + + self.assertIs( + draft7_format_checker, + validators.Draft7Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft6_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft6_format_checker + + self.assertIs( + draft6_format_checker, + validators.Draft6Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft4_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft4_format_checker + + self.assertIs( + draft4_format_checker, + validators.Draft4Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft3_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft3_format_checker + + self.assertIs( + draft3_format_checker, + validators.Draft3Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + with self.assertRaises(ImportError): + from jsonschema import draft1234_format_checker # noqa + + def test_import_cli(self): + """ + As of v4.17.0, importing jsonschema.cli is deprecated. + """ + + message = "The jsonschema CLI is deprecated and will be removed " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + import jsonschema.cli + importlib.reload(jsonschema.cli) + + self.assertEqual(w.filename, importlib.__file__) + + def test_cli(self): + """ + As of v4.17.0, the jsonschema CLI is deprecated. + """ + + process = subprocess.run( + [sys.executable, "-m", "jsonschema"], + capture_output=True, + ) + self.assertIn(b"The jsonschema CLI is deprecated ", process.stderr) + + def test_automatic_remote_retrieval(self): + """ + Automatic retrieval of remote references is deprecated as of v4.18.0. + """ + ref = "http://bar#/$defs/baz" + schema = {"$defs": {"baz": {"type": "integer"}}} + + if "requests" in sys.modules: # pragma: no cover + self.addCleanup( + sys.modules.__setitem__, "requests", sys.modules["requests"], + ) + sys.modules["requests"] = None + + @contextmanager + def fake_urlopen(request): + self.assertIsInstance(request, urllib.request.Request) + self.assertEqual(request.full_url, "http://bar") + + # Ha ha urllib.request.Request "normalizes" header names and + # Request.get_header does not also normalize them... + (header, value), = request.header_items() + self.assertEqual(header.lower(), "user-agent") + self.assertEqual( + value, "python-jsonschema (deprecated $ref resolution)", + ) + yield BytesIO(json.dumps(schema).encode("utf8")) + + validator = validators.Draft202012Validator({"$ref": ref}) + + message = "Automatically retrieving remote references " + patch = mock.patch.object(urllib.request, "urlopen", new=fake_urlopen) + + with patch, self.assertWarnsRegex(DeprecationWarning, message): + self.assertEqual( + (validator.is_valid({}), validator.is_valid(37)), + (False, True), + ) diff --git a/shared/package-files/75/75cfdd35ecb6f641fa28b535993d836a4abbb59de405fcc41b0cce983cf0d45f/blob b/shared/package-files/75/75cfdd35ecb6f641fa28b535993d836a4abbb59de405fcc41b0cce983cf0d45f/blob new file mode 100644 index 0000000000000000000000000000000000000000..52959005b088f0e5116c8b6acdbcc5937bbaacc8 --- /dev/null +++ b/shared/package-files/75/75cfdd35ecb6f641fa28b535993d836a4abbb59de405fcc41b0cce983cf0d45f/blob @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.filters import * # noqa diff --git a/shared/package-files/75/75cff1387ca65fa141aa635923c58e9d287764be9b90a3dbf607f590b1ca4530/blob b/shared/package-files/75/75cff1387ca65fa141aa635923c58e9d287764be9b90a3dbf607f590b1ca4530/blob new file mode 100644 index 0000000000000000000000000000000000000000..52c54f54b2b0936dc48321c610fb04968e7fbe47 Binary files /dev/null and b/shared/package-files/75/75cff1387ca65fa141aa635923c58e9d287764be9b90a3dbf607f590b1ca4530/blob differ diff --git a/shared/package-files/75/75d2795625ee95b3cba1c1ebf919162b6ed6252b95d965d4c7be236722f434e8/blob b/shared/package-files/75/75d2795625ee95b3cba1c1ebf919162b6ed6252b95d965d4c7be236722f434e8/blob new file mode 100644 index 0000000000000000000000000000000000000000..db72bbdff020680dfd833229cac41e9b33e428ee --- /dev/null +++ b/shared/package-files/75/75d2795625ee95b3cba1c1ebf919162b6ed6252b95d965d4c7be236722f434e8/blob @@ -0,0 +1,84 @@ +""" +Helper module for the *bbox_inches* parameter in `.Figure.savefig`. +""" + +from matplotlib.transforms import Bbox, TransformedBbox, Affine2D + + +def adjust_bbox(fig, bbox_inches, fixed_dpi=None): + """ + Temporarily adjust the figure so that only the specified area + (bbox_inches) is saved. + + It modifies fig.bbox, fig.bbox_inches, + fig.transFigure._boxout, and fig.patch. While the figure size + changes, the scale of the original figure is conserved. A + function which restores the original values are returned. + """ + origBbox = fig.bbox + origBboxInches = fig.bbox_inches + _boxout = fig.transFigure._boxout + + old_aspect = [] + locator_list = [] + sentinel = object() + for ax in fig.axes: + locator = ax.get_axes_locator() + if locator is not None: + ax.apply_aspect(locator(ax, None)) + locator_list.append(locator) + current_pos = ax.get_position(original=False).frozen() + ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos) + # override the method that enforces the aspect ratio on the Axes + if 'apply_aspect' in ax.__dict__: + old_aspect.append(ax.apply_aspect) + else: + old_aspect.append(sentinel) + ax.apply_aspect = lambda pos=None: None + + def restore_bbox(): + for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect): + ax.set_axes_locator(loc) + if aspect is sentinel: + # delete our no-op function which un-hides the original method + del ax.apply_aspect + else: + ax.apply_aspect = aspect + + fig.bbox = origBbox + fig.bbox_inches = origBboxInches + fig.transFigure._boxout = _boxout + fig.transFigure.invalidate() + fig.patch.set_bounds(0, 0, 1, 1) + + if fixed_dpi is None: + fixed_dpi = fig.dpi + tr = Affine2D().scale(fixed_dpi) + dpi_scale = fixed_dpi / fig.dpi + + fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size) + x0, y0 = tr.transform(bbox_inches.p0) + w1, h1 = fig.bbox.size * dpi_scale + fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) + fig.transFigure.invalidate() + + fig.bbox = TransformedBbox(fig.bbox_inches, tr) + + fig.patch.set_bounds(x0 / w1, y0 / h1, + fig.bbox.width / w1, fig.bbox.height / h1) + + return restore_bbox + + +def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): + """ + A function that needs to be called when figure dpi changes during the + drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with + the new dpi. + """ + + bbox_inches, restore_bbox = bbox_inches_restore + restore_bbox() + r = adjust_bbox(fig, bbox_inches, fixed_dpi) + + return bbox_inches, r diff --git a/shared/package-files/75/75d3d0534d213518a35d0cd9d4ee4d3f398f0b1518e2f5083491eba1a6cd572d/inten_model.py b/shared/package-files/75/75d3d0534d213518a35d0cd9d4ee4d3f398f0b1518e2f5083491eba1a6cd572d/inten_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a36d99e5ceda4affa3d0636208f51a66dd0a4d6 --- /dev/null +++ b/shared/package-files/75/75d3d0534d213518a35d0cd9d4ee4d3f398f0b1518e2f5083491eba1a6cd572d/inten_model.py @@ -0,0 +1,835 @@ +"""DAG intensity prediction model.""" +import numpy as np +import copy +import torch +import pytorch_lightning as pl +import torch.nn as nn +import torch_scatter as ts +import dgl.nn as dgl_nn +import pygmtools as pygm +import functools + + +import ms_pred.common as common +import ms_pred.iceberg.dag_data as dag_data +import ms_pred.nn_utils as nn_utils +import ms_pred.magma.fragmentation as fragmentation +import ms_pred.magma.run_magma as run_magma + + +class IntenGNN(pl.LightningModule): + def __init__( + self, + hidden_size: int, + gnn_layers: int = 2, + mlp_layers: int = 0, + set_layers: int = 2, + learning_rate: float = 7e-4, + lr_decay_rate: float = 1.0, + weight_decay: float = 0, + dropout: float = 0, + mpnn_type: str = "PNA", + pool_op: str = "avg", + node_feats: int = common.ELEMENT_DIM + common.MAX_H, + pe_embed_k: int = 0, + max_broken: int = fragmentation.FRAGMENT_ENGINE_PARAMS["max_broken_bonds"], + frag_set_layers: int = 0, + loss_fn: str = "cosine", + track_cosine: bool = False, + root_encode: str = "gnn", + inject_early: bool = False, + warmup: int = 1000, + embed_adduct: bool = False, + embed_collision: bool = False, + embed_elem_group: bool = False, + embed_instrument: bool = False, + include_unshifted_mz: bool = False, + binned_targs: bool = True, + encode_forms: bool = False, + add_hs: bool = False, + sk_tau: float = 0.01, + contr_weight: float = 1., + ppm_tol: float = 20, + **kwargs, + ): + super().__init__() + self.save_hyperparameters() + self.hidden_size = hidden_size + self.pe_embed_k = pe_embed_k + self.root_encode = root_encode + self.pool_op = pool_op + self.inject_early = inject_early + self.embed_adduct = embed_adduct + self.embed_collision = embed_collision + self.embed_instrument = embed_instrument + self.embed_elem_group = embed_elem_group + self.include_unshifted_mz = include_unshifted_mz + self.binned_targs = binned_targs + self.encode_forms = encode_forms + self.add_hs = add_hs + self.sk_tau = sk_tau + self.contr_weight = contr_weight + + self.tree_processor = dag_data.TreeProcessor( + root_encode=root_encode, pe_embed_k=pe_embed_k, add_hs=add_hs, embed_elem_group=self.embed_elem_group, + ) + + self.formula_in_dim = 0 + if self.encode_forms: + self.embedder = nn_utils.get_embedder("abs-sines") + self.formula_dim = common.NORM_VEC.shape[0] + + # Calculate formula dim + self.formula_in_dim = self.formula_dim * self.embedder.num_dim + + # Account for diffs + self.formula_in_dim *= 2 + + self.gnn_layers = gnn_layers + self.set_layers = set_layers + self.frag_set_layers = frag_set_layers + self.mpnn_type = mpnn_type + self.mlp_layers = mlp_layers + + self.learning_rate = learning_rate + self.lr_decay_rate = lr_decay_rate + self.warmup = warmup + + self.weight_decay = weight_decay + self.dropout = dropout + + self.max_broken = max_broken + 1 + self.broken_onehot = torch.nn.Parameter(torch.eye(self.max_broken)) + self.broken_onehot.requires_grad = False + self.broken_clamp = max_broken + + edge_feats = fragmentation.MAX_BONDS + + orig_node_feats = node_feats + if self.inject_early: + node_feats = node_feats + self.hidden_size + + adduct_shift = 0 + if self.embed_adduct: + adduct_types = len(set(common.ion2onehot_pos.values())) + onehot_types = torch.eye(adduct_types) + if self.embed_elem_group: + adduct_modes = len(set([j for i in common.ion_pos2extra_multihot.values() for j in i])) + multihot_modes = torch.zeros((adduct_types, adduct_modes)) + for i in range(adduct_types): + for j in common.ion_pos2extra_multihot[i]: + multihot_modes[i, j] = 1 + adduct_embedder = torch.cat((onehot_types, multihot_modes), dim=-1) + self.adduct_embedder = nn.Parameter(adduct_embedder.float()) + self.adduct_embedder.requires_grad = False + adduct_shift = adduct_types + adduct_modes + else: + self.adduct_embedder = nn.Parameter(onehot_types.float()) + self.adduct_embedder.requires_grad = False + adduct_shift = adduct_types + + collision_shift = 0 + if self.embed_collision: + pe_dim = common.COLLISION_PE_DIM + pe_scalar = common.COLLISION_PE_SCALAR + pe_power = 2 * torch.arange(pe_dim // 2) / pe_dim + self.collision_embedder_denominators = nn.Parameter(torch.pow(pe_scalar, pe_power)) + self.collision_embedder_denominators.requires_grad = False + collision_shift = pe_dim + + # Not used: Compute the merged collision embedding as the mean of all energies 0 - 100 eV + # collision_eng_steps = torch.arange(0, 100, 0.01) + # self.collision_embed_merged = nn.Parameter(torch.cat( + # (torch.sin(collision_eng_steps.unsqueeze(1) / self.collision_embedder_denominators.unsqueeze(0)), + # torch.cos(collision_eng_steps.unsqueeze(1) / self.collision_embedder_denominators.unsqueeze(0))), + # dim=1 + # ).mean(dim=0)) + # self.collision_embed_merged.requires_grad = False + + # All-zero for collision == nan + self.collision_embed_merged = nn.Parameter(torch.zeros(pe_dim)) + self.collision_embed_merged.requires_grad = False + + instrument_shift = 0 + if self.embed_instrument: + instrument_types = len(set(common.instrument2onehot_pos.values())) + onehot_types = torch.eye(instrument_types) + self.instrument_embedder = nn.Parameter(onehot_types.float()) + self.instrument_embedder.requires_grad = False + instrument_shift = instrument_types + + # Define network + self.gnn = nn_utils.MoleculeGNN( + hidden_size=self.hidden_size, + num_step_message_passing=self.gnn_layers, + set_transform_layers=self.set_layers, + mpnn_type=self.mpnn_type, + gnn_node_feats=node_feats + adduct_shift + collision_shift + instrument_shift, + gnn_edge_feats=edge_feats, + dropout=self.dropout, + ) + + if self.root_encode == "gnn": + self.root_module = self.gnn + + # if inject early, need separate root and child GNN's + if self.inject_early: + self.root_module = nn_utils.MoleculeGNN( + hidden_size=self.hidden_size, + num_step_message_passing=self.gnn_layers, + set_transform_layers=self.set_layers, + mpnn_type=self.mpnn_type, + gnn_node_feats=node_feats + adduct_shift, + gnn_edge_feats=edge_feats, + dropout=self.dropout, + ) + elif self.root_encode == "fp": + self.root_module = nn_utils.MLPBlocks( + input_size=2048, + hidden_size=self.hidden_size, + output_size=None, + dropout=self.dropout, + num_layers=1, + use_residuals=True, + ) + else: + raise ValueError() + + # MLP layer to take representations from the pooling layer + # And predict a single scalar value at each of them + # I.e., Go from size B x 2h -> B x 1 + self.intermediate_out = nn_utils.MLPBlocks( + input_size=self.hidden_size * 3 + self.max_broken + self.formula_in_dim, + hidden_size=self.hidden_size, + output_size=self.hidden_size, + dropout=self.dropout, + num_layers=self.mlp_layers, + use_residuals=True, + ) + + trans_layer = nn_utils.TransformerEncoderLayer( + self.hidden_size, + nhead=8, + batch_first=True, + norm_first=False, + dim_feedforward=self.hidden_size * 4, + ) + self.trans_layers = nn_utils.get_clones(trans_layer, self.frag_set_layers) + + self.ppm_tol = ppm_tol + self.mass_tol = self.ppm_tol * 1e-6 + self.loss_fn_name = loss_fn + self.track_cosine = track_cosine + self.cos_fn = nn.CosineSimilarity() + if loss_fn == "cosine": + self.loss_fn = self.cos_loss + self.output_activations = [nn.Sigmoid()] + elif loss_fn == "entropy": + self.loss_fn = self.entropy_loss + self.output_activations = [nn.Sigmoid()] + if self.track_cosine: + self._cosine_fn = self.cos_loss + elif loss_fn == "weighted_entropy": + self.loss_fn = functools.partial(self.entropy_loss, weighted=True) + self.output_activations = [nn.Sigmoid()] + else: + raise NotImplementedError() + + self.num_outputs = len(self.output_activations) + self.output_size = fragmentation.FRAGMENT_ENGINE_PARAMS["max_broken_bonds"] * 2 + 1 + if self.include_unshifted_mz: + self.output_map = nn.Linear( + self.hidden_size, self.num_outputs * self.output_size * 2 + # output_size dim for adduct mass shift & output_size dim for no mass shift + ) + else: + self.output_map = nn.Linear( + self.hidden_size, self.num_outputs * self.output_size + ) + + # Define map from output layer to attn + self.isomer_attn_out = copy.deepcopy(self.output_map) + + # Define buckets + buckets = torch.DoubleTensor(np.linspace(0, 1500, 15000)) + self.inten_buckets = nn.Parameter(buckets) + self.inten_buckets.requires_grad = False + + if self.pool_op == "avg": + self.pool = dgl_nn.AvgPooling() + elif self.pool_op == "attn": + self.pool = dgl_nn.GlobalAttentionPooling(nn.Linear(hidden_size, 1)) + else: + raise NotImplementedError() + + self.sigmoid = nn.Sigmoid() + + def cos_loss(self, pred, targ, parent_mass=None, use_hun=False): + """cos_loss. + + Args: + pred: + targ: + """ + if not self.binned_targs: + tol = parent_mass * self.mass_tol + mask = torch.logical_and( + torch.abs(pred[:, :, None, 0] - targ[:, None, :, 0]) < tol[:, None, None], + targ[:, None, :, 0] > 0 + ) + pred_norm = pred[:, :, 1].norm(dim=-1) + targ_norm = targ[:, :, 1].norm(dim=-1) + score = pred[:, :, None, 1] * targ[:, None, :, 1] / (pred_norm[:, None, None] * targ_norm[:, None, None]) + score = torch.where(mask, score, torch.zeros_like(score)) + target_nums = torch.sum(targ[:, :, 1] != 0, dim=-1) + if use_hun: + assign = pygm.hungarian(score, n2=target_nums, backend='pytorch') + else: + _score = torch.where(mask, score, torch.full_like(score, -1e3)) + assign = pygm.sinkhorn(_score, n2=target_nums, tau=self.sk_tau, dummy_row=True, max_iter=20, backend='pytorch') + loss = 1 - torch.sum(assign * score, dim=(1, 2)) + else: + loss = 1 - self.cos_fn(pred, targ) + return {"loss": loss} + + def entropy_loss(self, pred, targ, parent_mass=None, use_hun=False, weighted=False): + """entropy_loss. + + Args: + pred: + targ: + """ + def norm_peaks(prob): + return prob / (prob.sum(dim=-1, keepdim=True) + 1e-22) + def entropy(prob): + assert torch.all(torch.abs(prob.sum(dim=-1) - 1) < 1e-3), prob.sum(dim=-1) + return -torch.sum(prob * torch.log(prob + 1e-22), dim=-1) / 1.3862943611198906 # norm by log(4) + + if not self.binned_targs: + if weighted: + raise NotImplementedError + tol = parent_mass * self.mass_tol + mask = torch.logical_and( + torch.abs(pred[:, :, None, 0] - targ[:, None, :, 0]) < tol[:, None, None], + targ[:, None, :, 0] > 0 + ) + score = pred[:, :, None, 1] * targ[:, None, :, 1] + score = torch.where(mask, score, torch.zeros_like(score)) + target_nums = torch.sum(targ[:, :, 1] != 0, dim=-1) + if use_hun: + assign = pygm.hungarian(score, n2=target_nums, backend='pytorch') + else: + _score = torch.where(mask, score, torch.full_like(score, -1e3)) + assign = pygm.sinkhorn(_score, n2=target_nums, tau=self.sk_tau, dummy_row=True, max_iter=20, backend='pytorch') + pred_norm = norm_peaks(pred[:, :, 1]) + targ_norm = norm_peaks(targ[:, :, 1]) + merged_peaks = torch.cat(( + torch.bmm(assign, targ_norm.unsueeze(-1)).squeeze(-1) + pred_norm, # usually n_pred > n_targ + (1 - assign.sum(dim=1)) * targ_norm, + ), dim=1) + entropy_mix = entropy(merged_peaks) + entropy_pred = entropy(pred_norm) + entropy_targ = entropy(targ_norm) + loss = 2 * entropy_mix - entropy_pred - entropy_targ + + else: + pred_norm = norm_peaks(pred) + targ_norm = norm_peaks(targ) + if weighted: + def reweight_spec(norm_spec): + entropy_spec = entropy(norm_spec) + weight = torch.where(entropy_spec < 3, 0.25 + 0.25 * entropy_spec, torch.ones_like(entropy_spec)) + weighted_spec = norm_spec ** weight.unsqueeze(-1) + weighted_spec = norm_peaks(weighted_spec) + return weighted_spec + pred_norm = reweight_spec(pred_norm) + targ_norm = reweight_spec(targ_norm) + entropy_pred = entropy(pred_norm) + entropy_targ = entropy(targ_norm) + entropy_mix = entropy((pred_norm + targ_norm) / 2) + loss = 2 * entropy_mix - entropy_pred - entropy_targ + return {"loss": loss} + + def predict( + self, + graphs, + root_reprs, + ind_maps, + num_frags, + max_breaks, + adducts=None, + collision_engs=None, + instruments=None, + precursor_mzs=None, + max_add_hs=None, + max_remove_hs=None, + masses=None, + root_forms=None, + frag_forms=None, + ) -> dict: + """predict _summary_ + + Args: + graphs (_type_): _description_ + root_reprs (_type_): _description_ + ind_maps (_type_): _description_ + num_frags (_type_): _description_ + max_breaks (_type_): _description_ + adducts (_type_): _description_ + collision_engs (_type_): _description_ + instruments (_type_): _description_ + precursor_mzs (_type_): _description_ + max_add_hs (_type_, optional): _description_. Defaults to None. + max_remove_hs (_type_, optional): _description_. Defaults to None. + masses (_type_, optional): _description_. Defaults to None. + root_forms (_type_, optional): _description_. Defaults to None. + frag_forms (_type_, optional): _description_. Defaults to None. + binned_out (bool, optional): _description_. Defaults to False. + + Raises: + NotImplementedError: _description_ + + Returns: + dict: _description_ + """ + # B x nodes x num outputs x inten items + out = self.forward( + graphs, + root_reprs, + ind_maps, + num_frags, + adducts=adducts, + collision_engs=collision_engs, + instruments=instruments, + precursor_mzs=precursor_mzs, + broken=max_breaks, + max_add_hs=max_add_hs, + max_remove_hs=max_remove_hs, + masses=masses, + root_forms=root_forms, + frag_forms=frag_forms, + ) + + if self.loss_fn_name not in ["cosine", "entropy", "weighted_entropy"]: + raise NotImplementedError() + + output = out["output"][ + :, + :, + 0, + ] + out_preds_binned = out["output_binned"][:, 0, :] + out_preds = [ + pred[:num_frag, :] + for pred, num_frag in zip(output, num_frags) + ] + + out_dict = { + "spec": out_preds, + "binned_spec": out_preds_binned, + } + return out_dict + + def forward( + self, + graphs, + root_repr, + ind_maps, + num_frags, + broken, + collision_engs, + precursor_mzs, + adducts=None, + instruments=None, + max_add_hs=None, + max_remove_hs=None, + masses=None, + root_forms=None, + frag_forms=None, + ): + """forward _summary_ + + Args: + graphs (_type_): _description_ + root_repr (_type_): _description_ + ind_maps (_type_): _description_ + num_frags (_type_): _description_ + broken (_type_): _description_ + adducts (_type_): _description_ + collision_engs (_type_): _description_ + instruments (_type_): _description_ + precursor_mzs (_type_): _description_ + max_add_hs (_type_, optional): _description_. Defaults to None. + max_remove_hs (_type_, optional): _description_. Defaults to None. + masses (_type_, optional): _description_. Defaults to None. + root_forms (_type_, optional): _description_. Defaults to None. + frag_forms (_type_, optional): _description_. Defaults to None. + + Raises: + NotImplementedError: _description_ + + Returns: + _type_: _description_ + """ + device = num_frags.device + + if not self.include_unshifted_mz: + masses = masses[:, :, :1, :].contiguous() # only keep m/z with adduct shift + + # if root fingerprints: + if self.embed_adduct: + embed_adducts = self.adduct_embedder[adducts.long()] + if self.embed_instrument: + embed_instruments = self.instrument_embedder[instruments.long()] + if self.root_encode == "fp": + root_embeddings = self.root_module(root_repr) + raise NotImplementedError() + elif self.root_encode == "gnn": + with root_repr.local_scope(): + if self.embed_adduct: + embed_adducts_expand = embed_adducts.repeat_interleave( + root_repr.batch_num_nodes(), 0 + ) + ndata = root_repr.ndata["h"] + ndata = torch.cat([ndata, embed_adducts_expand], -1) + root_repr.ndata["h"] = ndata + + if self.embed_collision: + embed_collision = torch.cat( + (torch.sin(collision_engs.unsqueeze(1) / self.collision_embedder_denominators.unsqueeze(0)), + torch.cos(collision_engs.unsqueeze(1) / self.collision_embedder_denominators.unsqueeze(0))), + dim=1 + ) + embed_collision = torch.where( # handle entries without collision energy (== nan) + torch.isnan(embed_collision), self.collision_embed_merged.unsqueeze(0), embed_collision + ) + embed_collision_expand = embed_collision.repeat_interleave( + root_repr.batch_num_nodes(), 0 + ) + ndata = root_repr.ndata["h"] + ndata = torch.cat([ndata, embed_collision_expand], -1) + root_repr.ndata["h"] = ndata + + if self.embed_instrument: + + # TODO: should I account for nan: + # self.instrument_nansub = nn.Parameter(torch.zeros(len(set(common.instrument2onehot_pos.values())))) + # self.instrument_nansub.requires_grad = False + + # embed_instruments = torch.where(torch.isnan(embed_instruments), + # self.instrument_nansub.unsqueeze(0), + # embed_instruments + # ) + embed_instruments_expand = embed_instruments.repeat_interleave( + root_repr.batch_num_nodes(), 0 + ) + + ndata = root_repr.ndata["h"] + ndata = torch.cat([ndata, embed_instruments_expand], -1) + root_repr.ndata["h"] = ndata + root_embeddings = self.root_module(root_repr) + root_embeddings = self.pool(root_repr, root_embeddings) + else: + pass + + # Line up the features to be parallel between fragment avgs and root + # graphs + ext_root = root_embeddings[ind_maps] + # Extend the root further to cover each individual atom + ext_root_atoms = torch.repeat_interleave( + ext_root, graphs.batch_num_nodes(), dim=0 + ) + concat_list = [graphs.ndata["h"]] + + if self.inject_early: + concat_list.append(ext_root_atoms) + + if self.embed_adduct: + adducts_mapped = embed_adducts[ind_maps] + adducts_exp = torch.repeat_interleave( + adducts_mapped, graphs.batch_num_nodes(), dim=0 + ) + concat_list.append(adducts_exp) + + if self.embed_collision: + collision_mapped = embed_collision[ind_maps] + collision_exp = torch.repeat_interleave( + collision_mapped, graphs.batch_num_nodes(), dim=0 + ) + concat_list.append(collision_exp) + + if self.embed_instrument: + instruments_mapped = embed_instruments[ind_maps] + instruments_exp = torch.repeat_interleave( + instruments_mapped, graphs.batch_num_nodes(), dim=0 + ) + concat_list.append(instruments_exp) + + with graphs.local_scope(): + graphs.ndata["h"] = torch.cat(concat_list, -1).float() + + frag_embeddings = self.gnn(graphs) + + # Average embed the full root molecules and fragments + avg_frags = self.pool(graphs, frag_embeddings) + + # expand broken and map it to each fragment + broken_arange = torch.arange(broken.shape[-1]).to(device) + broken_mask = broken_arange[None, :] < num_frags[:, None] + + broken = torch.clamp(broken[broken_mask], max=self.broken_clamp) + broken_onehots = self.broken_onehot[broken.long()] + + ### Build hidden with forms + mlp_cat_list = [ext_root, ext_root - avg_frags, avg_frags, broken_onehots] + + hidden = torch.cat(mlp_cat_list, dim=1) + + # Pack so we can use interpeak attn + padded_hidden = nn_utils.pad_packed_tensor(hidden, num_frags, 0) + + if self.encode_forms: + diffs = root_forms[:, None, :] - frag_forms + form_encodings = self.embedder(frag_forms) + diff_encodings = self.embedder(diffs) + new_hidden = torch.cat( + [padded_hidden, form_encodings, diff_encodings], dim=-1 + ) + padded_hidden = new_hidden + + padded_hidden = self.intermediate_out(padded_hidden) + batch_size, max_frags, hidden_dim = padded_hidden.shape + + # Build up a mask + arange_frags = torch.arange(padded_hidden.shape[1]).to(device) + attn_mask = ~(arange_frags[None, :] < num_frags[:, None]) + + hidden = padded_hidden + for trans_layer in self.trans_layers: + hidden, _ = trans_layer(hidden, src_key_padding_mask=attn_mask) + + # hidden: B x L x h + # attn_mask: B x L + + # Build mask + max_inten_shift = (self.output_size - 1) / 2 + max_break_ar = torch.arange(self.output_size, device=device)[None, None, :].to( + device + ) + max_breaks_ub = max_add_hs + max_inten_shift + max_breaks_lb = -max_remove_hs + max_inten_shift + + ub_mask = max_break_ar <= max_breaks_ub[:, :, None] + lb_mask = max_break_ar >= max_breaks_lb[:, :, None] + + # B x Length x Mass shifts + valid_pos = torch.logical_and(ub_mask, lb_mask) + valid_pos = torch.logical_and(valid_pos, ~attn_mask[:, :, None]) + + if self.include_unshifted_mz: + mz_groups = 2 + else: + mz_groups = 1 + + # B x Length x outputs x 2 x Mass shift + valid_pos = valid_pos[:, :, None, None, :].expand( + batch_size, max_frags, self.num_outputs, mz_groups, self.output_size + ) + # B x L x Output + output = self.output_map(hidden) + attn_weights = self.isomer_attn_out(hidden) + + # B x L x Out x 2 x Mass shifts + output = output.reshape(batch_size, max_frags, self.num_outputs, mz_groups, -1) + attn_weights = attn_weights.reshape(batch_size, max_frags, self.num_outputs, mz_groups, -1) + + # Mask attn weights + attn_weights.masked_fill_(~valid_pos, -99999) # -float("inf")) + + # B x Out x L x 2 x Mass shifts + output = output.transpose(1, 2) + attn_weights = attn_weights.transpose(1, 2) + valid_pos_binned = valid_pos.transpose(1, 2) + + # Calc inverse indices => B x Out x L x 2 x shift + inverse_indices = torch.clamp(torch.bucketize(masses, self.inten_buckets, right=False), max=len(self.inten_buckets) - 1) + inverse_indices = inverse_indices[:, None, :, :].expand(attn_weights.shape) + + # B x Out x (L * 2 * Mass shifts) + attn_weights = attn_weights.reshape(batch_size, self.num_outputs, -1) + output = output.reshape(batch_size, self.num_outputs, -1) + inverse_indices = inverse_indices.reshape(batch_size, self.num_outputs, -1) + valid_pos_binned = valid_pos.reshape(batch_size, self.num_outputs, -1) + + # B x Outs x ( L * 2 * mass shifts ) + pool_weights = ts.scatter_softmax(attn_weights, index=inverse_indices, dim=-1) + weighted_out = pool_weights * output + + # B x Outs x (UNIQUE(L * 2 * mass shifts)) + output_binned = ts.scatter_add( + weighted_out, + index=inverse_indices, + dim=-1, + dim_size=self.inten_buckets.shape[-1], + ) + + # B x L x Outs x (2 * mass shifts) + pool_weights_reshaped = pool_weights.reshape( + batch_size, self.num_outputs, max_frags, -1 + ).transpose(1, 2) + inverse_indices_reshaped = inverse_indices.reshape( + batch_size, self.num_outputs, max_frags, -1 + ).transpose(1, 2) + + # B x Outs x binned + valid_pos_binned = ts.scatter_max( + (valid_pos_binned).long(), + index=inverse_indices, + dim_size=self.inten_buckets.shape[-1], + dim=-1, + )[0].bool() + + # Activate each dim with its respective output activation + # Helpful for hurdle or probabilistic models + new_outputs_binned = [] + for output_ind, act in enumerate(self.output_activations): + new_outputs_binned.append( + act(output_binned[:, output_ind : output_ind + 1, :]) + ) + output_binned = torch.cat(new_outputs_binned, -2) + output_binned.masked_fill_(~valid_pos_binned, 0) + + # Index into output binned using inverse_indices_reshaped + # Revert the binned output back to frags for attribution + # B x Out x (L * 2 * Mass shifts) + inverse_indices_reshaped_temp = inverse_indices_reshaped.transpose( + 1, 2 + ).reshape(batch_size, self.num_outputs, -1) + output_unbinned = torch.take_along_dim( + output_binned, inverse_indices_reshaped_temp, dim=-1 + ) + output_unbinned = output_unbinned.reshape( + batch_size, self.num_outputs, max_frags, -1 + ).transpose(1, 2) + output_unbinned_alpha = output_unbinned * pool_weights_reshaped + + return {"output_binned": output_binned, "output": output_unbinned_alpha} + + def _common_step(self, batch, name="train"): + pred_obj = self.forward( + batch["frag_graphs"], + batch["root_reprs"], + batch["inds"], + batch["num_frags"], + broken=batch["broken_bonds"], + adducts=batch["adducts"], + instruments=batch["instruments"] if self.embed_instrument else None, + collision_engs=batch["collision_engs"], + precursor_mzs=batch["precursor_mzs"], + max_remove_hs=batch["max_remove_hs"], + max_add_hs=batch["max_add_hs"], + masses=batch["masses"], + root_forms=batch["root_form_vecs"], + frag_forms=batch["frag_form_vecs"], + ) + if self.binned_targs: + pred_inten = pred_obj["output_binned"] + pred_inten = pred_inten[:, 0, :] + else: + pred_inten = pred_obj["output"] + pred_inten = pred_inten[:, :, 0, :] + pred_inten = torch.stack((batch["masses"], pred_inten), dim=-1) + pred_inten = pred_inten.reshape(pred_inten.shape[0], -1, 2) # B x (Out * Mass shifts) x 2 + batch_size = len(batch["names"]) + + if name == 'train': + loss_fn = self.loss_fn + decoy_loss_fn = self.entropy_loss + if self.track_cosine: + cosine_fn = self._cosine_fn + else: + loss_fn = functools.partial(self.loss_fn, use_hun=True) # use hungarian in val and test + decoy_loss_fn = functools.partial(self.entropy_loss, use_hun=True) + if self.track_cosine: + cosine_fn = functools.partial(self._cosine_fn, use_hun=True) # use hungarian in val and test + + if 'is_decoy' in batch and 'mol_num' in batch: # data with decoys + true_data_inds = batch["is_decoy"] == 0 + num_true_data = torch.sum(true_data_inds) + + # the real spectrum loss (cosine or entropy) + spec_loss = loss_fn(pred_inten[true_data_inds], batch["inten_targs"][true_data_inds], + parent_mass=batch["precursor_mzs"][true_data_inds] + )['loss'] + + # contrastive ranking loss cosine loss to decoys + decoy_spec_loss = decoy_loss_fn(pred_inten, + batch["inten_targs"][true_data_inds].repeat_interleave(batch['mol_num'], dim=0), + parent_mass=batch["precursor_mzs"] + )['loss'] + split_end = torch.cumsum(batch['mol_num'], dim=0) + split_start = split_end - batch['mol_num'] + decoy_spec_loss = [decoy_spec_loss[s:e] for s, e in zip(split_start, split_end)] + decoy_spec_loss = torch.nn.utils.rnn.pad_sequence(decoy_spec_loss, batch_first=True, padding_value=1) # cos_loss <=1 by definition + decoy_spec_loss_sorted = torch.sort(decoy_spec_loss, dim=-1).values.detach() + ranking_dist = torch.abs(decoy_spec_loss[:, :, None] - decoy_spec_loss_sorted[:, None, :]) + top1_prob = pygm.sinkhorn(-ranking_dist, n1=batch["mol_num"], n2=batch["mol_num"], tau=self.sk_tau, backend='pytorch')[:, 0, 0] + contr_loss = torch.relu(-torch.log(top1_prob + 0.5)) # shift & cut ce loss for probs > 0.5 + + loss = { + "spec_loss": spec_loss, + "contr_loss": contr_loss, + "loss": spec_loss + contr_loss * self.contr_weight, + } + # TODO: track cosine loss if desired + else: + loss = loss_fn(pred_inten, batch["inten_targs"], parent_mass=batch["precursor_mzs"]) + if self.track_cosine: + cosine_loss_val = cosine_fn(pred_inten, batch["inten_targs"], parent_mass=batch["precursor_mzs"])['loss'] + + loss = {k: v.mean() for k, v in loss.items()} + self.log( + f"{name}_loss", loss["loss"].item(), batch_size=batch_size, on_epoch=True + ) + if self.track_cosine: + self.log( + f"{name}_cosine", cosine_loss_val.mean().item(), batch_size=batch_size, on_epoch=True + ) + + for k, v in loss.items(): + if k != "loss": + self.log(f"{name}_aux_{k}", v.item(), batch_size=batch_size) + return loss + + def training_step(self, batch, batch_idx): + """training_step.""" + return self._common_step(batch, name="train") + + def validation_step(self, batch, batch_idx): + """validation_step.""" + return self._common_step(batch, name="val") + + def test_step(self, batch, batch_idx): + """test_step.""" + return self._common_step(batch, name="test") + + def configure_optimizers(self): + """configure_optimizers.""" + optimizer = torch.optim.Adam( + self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay + ) + scheduler = nn_utils.build_lr_scheduler( + optimizer=optimizer, lr_decay_rate=self.lr_decay_rate, warmup=self.warmup + ) + ret = { + "optimizer": optimizer, + "lr_scheduler": { + "scheduler": scheduler, + "frequency": 1, + "interval": "step", + }, + } + return ret + + def lr_scheduler_step(self, scheduler, optimizer_idx, metric=None): # fix lightning API mismatch for torch>=2.0 + scheduler.step() diff --git a/shared/package-files/75/75d47701bf02b9087e5a83bdff9c1a28ab8ffd0d77d20913cdff8e5345c9bf49/blob b/shared/package-files/75/75d47701bf02b9087e5a83bdff9c1a28ab8ffd0d77d20913cdff8e5345c9bf49/blob new file mode 100644 index 0000000000000000000000000000000000000000..300ae51cef6b9044b1060376b19f7278fcf18a94 --- /dev/null +++ b/shared/package-files/75/75d47701bf02b9087e5a83bdff9c1a28ab8ffd0d77d20913cdff8e5345c9bf49/blob @@ -0,0 +1,39 @@ +#pragma once + +// A fixed-size array type usable from both host and +// device code. + +#include +#include + +namespace at { namespace detail { + +template +struct Array { + T data[size_]; + + C10_HOST_DEVICE T operator[](int i) const { + return data[i]; + } + C10_HOST_DEVICE T& operator[](int i) { + return data[i]; + } +#if defined(USE_ROCM) + C10_HOST_DEVICE Array() = default; + C10_HOST_DEVICE Array(const Array&) = default; + C10_HOST_DEVICE Array& operator=(const Array&) = default; +#else + Array() = default; + Array(const Array&) = default; + Array& operator=(const Array&) = default; +#endif + static constexpr int size(){return size_;} + // Fill the array with x. + C10_HOST_DEVICE Array(T x) { + for (int i = 0; i < size_; i++) { + data[i] = x; + } + } +}; + +}} diff --git a/shared/package-files/75/75d8d4cce43482489604bb55c151584c9c9d688756dea01ce01095b1cc63efe4/blob b/shared/package-files/75/75d8d4cce43482489604bb55c151584c9c9d688756dea01ce01095b1cc63efe4/blob new file mode 100644 index 0000000000000000000000000000000000000000..7ab7813d5facd2953e1d661d3b64a2223b38e48b --- /dev/null +++ b/shared/package-files/75/75d8d4cce43482489604bb55c151584c9c9d688756dea01ce01095b1cc63efe4/blob @@ -0,0 +1,37 @@ +"""Unit tests for the :mod:`networkx.algorithms.bipartite.redundancy` module. + +""" + +import pytest + +from networkx import NetworkXError, cycle_graph +from networkx.algorithms.bipartite import complete_bipartite_graph, node_redundancy + + +def test_no_redundant_nodes(): + G = complete_bipartite_graph(2, 2) + + # when nodes is None + rc = node_redundancy(G) + assert all(redundancy == 1 for redundancy in rc.values()) + + # when set of nodes is specified + rc = node_redundancy(G, (2, 3)) + assert rc == {2: 1.0, 3: 1.0} + + +def test_redundant_nodes(): + G = cycle_graph(6) + edge = {0, 3} + G.add_edge(*edge) + redundancy = node_redundancy(G) + for v in edge: + assert redundancy[v] == 2 / 3 + for v in set(G) - edge: + assert redundancy[v] == 1 + + +def test_not_enough_neighbors(): + with pytest.raises(NetworkXError): + G = complete_bipartite_graph(1, 2) + node_redundancy(G) diff --git a/shared/package-files/75/75dc16aff517cecce90bd1f2ba14b7be265e95ad507236f2b5472da735d058e0/blob b/shared/package-files/75/75dc16aff517cecce90bd1f2ba14b7be265e95ad507236f2b5472da735d058e0/blob new file mode 100644 index 0000000000000000000000000000000000000000..299972343f5f39d5b395e3761f67f4a4ecb5ed76 --- /dev/null +++ b/shared/package-files/75/75dc16aff517cecce90bd1f2ba14b7be265e95ad507236f2b5472da735d058e0/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor fft_rfftfreq(int64_t n, double d=1.0, at::TensorOptions options={}); +TORCH_API at::Tensor fft_rfftfreq(int64_t n, double d, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +TORCH_API at::Tensor & fft_rfftfreq_out(at::Tensor & out, int64_t n, double d=1.0); +TORCH_API at::Tensor & fft_rfftfreq_outf(int64_t n, double d, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/75/75e67af2e02ad23a1d11eba626905859759c8885dc0587e9b0ba5ed5fd562cef/blob b/shared/package-files/75/75e67af2e02ad23a1d11eba626905859759c8885dc0587e9b0ba5ed5fd562cef/blob new file mode 100644 index 0000000000000000000000000000000000000000..e5298711ead793683b7054190819a6d58167ef41 --- /dev/null +++ b/shared/package-files/75/75e67af2e02ad23a1d11eba626905859759c8885dc0587e9b0ba5ed5fd562cef/blob @@ -0,0 +1,488 @@ +from abc import abstractmethod, abstractproperty +from typing import List, Optional, Tuple, Union + +from parso.utils import split_lines + + +def search_ancestor(node: 'NodeOrLeaf', *node_types: str) -> 'Optional[BaseNode]': + """ + Recursively looks at the parents of a node and returns the first found node + that matches ``node_types``. Returns ``None`` if no matching node is found. + + This function is deprecated, use :meth:`NodeOrLeaf.search_ancestor` instead. + + :param node: The ancestors of this node will be checked. + :param node_types: type names that are searched for. + """ + n = node.parent + while n is not None: + if n.type in node_types: + return n + n = n.parent + return None + + +class NodeOrLeaf: + """ + The base class for nodes and leaves. + """ + __slots__ = ('parent',) + type: str + ''' + The type is a string that typically matches the types of the grammar file. + ''' + parent: 'Optional[BaseNode]' + ''' + The parent :class:`BaseNode` of this node or leaf. + None if this is the root node. + ''' + + def get_root_node(self): + """ + Returns the root node of a parser tree. The returned node doesn't have + a parent node like all the other nodes/leaves. + """ + scope = self + while scope.parent is not None: + scope = scope.parent + return scope + + def get_next_sibling(self): + """ + Returns the node immediately following this node in this parent's + children list. If this node does not have a next sibling, it is None + """ + parent = self.parent + if parent is None: + return None + + # Can't use index(); we need to test by identity + for i, child in enumerate(parent.children): + if child is self: + try: + return self.parent.children[i + 1] + except IndexError: + return None + + def get_previous_sibling(self): + """ + Returns the node immediately preceding this node in this parent's + children list. If this node does not have a previous sibling, it is + None. + """ + parent = self.parent + if parent is None: + return None + + # Can't use index(); we need to test by identity + for i, child in enumerate(parent.children): + if child is self: + if i == 0: + return None + return self.parent.children[i - 1] + + def get_previous_leaf(self): + """ + Returns the previous leaf in the parser tree. + Returns `None` if this is the first element in the parser tree. + """ + if self.parent is None: + return None + + node = self + while True: + c = node.parent.children + i = c.index(node) + if i == 0: + node = node.parent + if node.parent is None: + return None + else: + node = c[i - 1] + break + + while True: + try: + node = node.children[-1] + except AttributeError: # A Leaf doesn't have children. + return node + + def get_next_leaf(self): + """ + Returns the next leaf in the parser tree. + Returns None if this is the last element in the parser tree. + """ + if self.parent is None: + return None + + node = self + while True: + c = node.parent.children + i = c.index(node) + if i == len(c) - 1: + node = node.parent + if node.parent is None: + return None + else: + node = c[i + 1] + break + + while True: + try: + node = node.children[0] + except AttributeError: # A Leaf doesn't have children. + return node + + @abstractproperty + def start_pos(self) -> Tuple[int, int]: + """ + Returns the starting position of the prefix as a tuple, e.g. `(3, 4)`. + + :return tuple of int: (line, column) + """ + + @abstractproperty + def end_pos(self) -> Tuple[int, int]: + """ + Returns the end position of the prefix as a tuple, e.g. `(3, 4)`. + + :return tuple of int: (line, column) + """ + + @abstractmethod + def get_start_pos_of_prefix(self): + """ + Returns the start_pos of the prefix. This means basically it returns + the end_pos of the last prefix. The `get_start_pos_of_prefix()` of the + prefix `+` in `2 + 1` would be `(1, 1)`, while the start_pos is + `(1, 2)`. + + :return tuple of int: (line, column) + """ + + @abstractmethod + def get_first_leaf(self): + """ + Returns the first leaf of a node or itself if this is a leaf. + """ + + @abstractmethod + def get_last_leaf(self): + """ + Returns the last leaf of a node or itself if this is a leaf. + """ + + @abstractmethod + def get_code(self, include_prefix=True): + """ + Returns the code that was the input for the parser for this node. + + :param include_prefix: Removes the prefix (whitespace and comments) of + e.g. a statement. + """ + + def search_ancestor(self, *node_types: str) -> 'Optional[BaseNode]': + """ + Recursively looks at the parents of this node or leaf and returns the + first found node that matches ``node_types``. Returns ``None`` if no + matching node is found. + + :param node_types: type names that are searched for. + """ + node = self.parent + while node is not None: + if node.type in node_types: + return node + node = node.parent + return None + + def dump(self, *, indent: Optional[Union[int, str]] = 4) -> str: + """ + Returns a formatted dump of the parser tree rooted at this node or leaf. This is + mainly useful for debugging purposes. + + The ``indent`` parameter is interpreted in a similar way as :py:func:`ast.dump`. + If ``indent`` is a non-negative integer or string, then the tree will be + pretty-printed with that indent level. An indent level of 0, negative, or ``""`` + will only insert newlines. ``None`` selects the single line representation. + Using a positive integer indent indents that many spaces per level. If + ``indent`` is a string (such as ``"\\t"``), that string is used to indent each + level. + + :param indent: Indentation style as described above. The default indentation is + 4 spaces, which yields a pretty-printed dump. + + >>> import parso + >>> print(parso.parse("lambda x, y: x + y").dump()) + Module([ + Lambda([ + Keyword('lambda', (1, 0)), + Param([ + Name('x', (1, 7), prefix=' '), + Operator(',', (1, 8)), + ]), + Param([ + Name('y', (1, 10), prefix=' '), + ]), + Operator(':', (1, 11)), + PythonNode('arith_expr', [ + Name('x', (1, 13), prefix=' '), + Operator('+', (1, 15), prefix=' '), + Name('y', (1, 17), prefix=' '), + ]), + ]), + EndMarker('', (1, 18)), + ]) + """ + if indent is None: + newline = False + indent_string = '' + elif isinstance(indent, int): + newline = True + indent_string = ' ' * indent + elif isinstance(indent, str): + newline = True + indent_string = indent + else: + raise TypeError(f"expect 'indent' to be int, str or None, got {indent!r}") + + def _format_dump(node: NodeOrLeaf, indent: str = '', top_level: bool = True) -> str: + result = '' + node_type = type(node).__name__ + if isinstance(node, Leaf): + result += f'{indent}{node_type}(' + if isinstance(node, ErrorLeaf): + result += f'{node.token_type!r}, ' + elif isinstance(node, TypedLeaf): + result += f'{node.type!r}, ' + result += f'{node.value!r}, {node.start_pos!r}' + if node.prefix: + result += f', prefix={node.prefix!r}' + result += ')' + elif isinstance(node, BaseNode): + result += f'{indent}{node_type}(' + if isinstance(node, Node): + result += f'{node.type!r}, ' + result += '[' + if newline: + result += '\n' + for child in node.children: + result += _format_dump(child, indent=indent + indent_string, top_level=False) + result += f'{indent}])' + else: # pragma: no cover + # We shouldn't ever reach here, unless: + # - `NodeOrLeaf` is incorrectly subclassed else where + # - or a node's children list contains invalid nodes or leafs + # Both are unexpected internal errors. + raise TypeError(f'unsupported node encountered: {node!r}') + if not top_level: + if newline: + result += ',\n' + else: + result += ', ' + return result + + return _format_dump(self) + + +class Leaf(NodeOrLeaf): + ''' + Leafs are basically tokens with a better API. Leafs exactly know where they + were defined and what text preceeds them. + ''' + __slots__ = ('value', 'line', 'column', 'prefix') + prefix: str + + def __init__(self, value: str, start_pos: Tuple[int, int], prefix: str = '') -> None: + self.value = value + ''' + :py:func:`str` The value of the current token. + ''' + self.start_pos = start_pos + self.prefix = prefix + ''' + :py:func:`str` Typically a mixture of whitespace and comments. Stuff + that is syntactically irrelevant for the syntax tree. + ''' + self.parent: Optional[BaseNode] = None + ''' + The parent :class:`BaseNode` of this leaf. + ''' + + @property + def start_pos(self) -> Tuple[int, int]: + return self.line, self.column + + @start_pos.setter + def start_pos(self, value: Tuple[int, int]) -> None: + self.line = value[0] + self.column = value[1] + + def get_start_pos_of_prefix(self): + previous_leaf = self.get_previous_leaf() + if previous_leaf is None: + lines = split_lines(self.prefix) + # + 1 is needed because split_lines always returns at least ['']. + return self.line - len(lines) + 1, 0 # It's the first leaf. + return previous_leaf.end_pos + + def get_first_leaf(self): + return self + + def get_last_leaf(self): + return self + + def get_code(self, include_prefix=True): + if include_prefix: + return self.prefix + self.value + else: + return self.value + + @property + def end_pos(self) -> Tuple[int, int]: + lines = split_lines(self.value) + end_pos_line = self.line + len(lines) - 1 + # Check for multiline token + if self.line == end_pos_line: + end_pos_column = self.column + len(lines[-1]) + else: + end_pos_column = len(lines[-1]) + return end_pos_line, end_pos_column + + def __repr__(self): + value = self.value + if not value: + value = self.type + return "<%s: %s>" % (type(self).__name__, value) + + +class TypedLeaf(Leaf): + __slots__ = ('type',) + + def __init__(self, type, value, start_pos, prefix=''): + super().__init__(value, start_pos, prefix) + self.type = type + + +class BaseNode(NodeOrLeaf): + """ + The super class for all nodes. + A node has children, a type and possibly a parent node. + """ + __slots__ = ('children',) + + def __init__(self, children: List[NodeOrLeaf]) -> None: + self.children = children + """ + A list of :class:`NodeOrLeaf` child nodes. + """ + self.parent: Optional[BaseNode] = None + ''' + The parent :class:`BaseNode` of this node. + None if this is the root node. + ''' + for child in children: + child.parent = self + + @property + def start_pos(self) -> Tuple[int, int]: + return self.children[0].start_pos + + def get_start_pos_of_prefix(self): + return self.children[0].get_start_pos_of_prefix() + + @property + def end_pos(self) -> Tuple[int, int]: + return self.children[-1].end_pos + + def _get_code_for_children(self, children, include_prefix): + if include_prefix: + return "".join(c.get_code() for c in children) + else: + first = children[0].get_code(include_prefix=False) + return first + "".join(c.get_code() for c in children[1:]) + + def get_code(self, include_prefix=True): + return self._get_code_for_children(self.children, include_prefix) + + def get_leaf_for_position(self, position, include_prefixes=False): + """ + Get the :py:class:`parso.tree.Leaf` at ``position`` + + :param tuple position: A position tuple, row, column. Rows start from 1 + :param bool include_prefixes: If ``False``, ``None`` will be returned if ``position`` falls + on whitespace or comments before a leaf + :return: :py:class:`parso.tree.Leaf` at ``position``, or ``None`` + """ + def binary_search(lower, upper): + if lower == upper: + element = self.children[lower] + if not include_prefixes and position < element.start_pos: + # We're on a prefix. + return None + # In case we have prefixes, a leaf always matches + try: + return element.get_leaf_for_position(position, include_prefixes) + except AttributeError: + return element + + index = int((lower + upper) / 2) + element = self.children[index] + if position <= element.end_pos: + return binary_search(lower, index) + else: + return binary_search(index + 1, upper) + + if not ((1, 0) <= position <= self.children[-1].end_pos): + raise ValueError('Please provide a position that exists within this node.') + return binary_search(0, len(self.children) - 1) + + def get_first_leaf(self): + return self.children[0].get_first_leaf() + + def get_last_leaf(self): + return self.children[-1].get_last_leaf() + + def __repr__(self): + code = self.get_code().replace('\n', ' ').replace('\r', ' ').strip() + return "<%s: %s@%s,%s>" % \ + (type(self).__name__, code, self.start_pos[0], self.start_pos[1]) + + +class Node(BaseNode): + """Concrete implementation for interior nodes.""" + __slots__ = ('type',) + + def __init__(self, type, children): + super().__init__(children) + self.type = type + + def __repr__(self): + return "%s(%s, %r)" % (self.__class__.__name__, self.type, self.children) + + +class ErrorNode(BaseNode): + """ + A node that contains valid nodes/leaves that we're follow by a token that + was invalid. This basically means that the leaf after this node is where + Python would mark a syntax error. + """ + __slots__ = () + type = 'error_node' + + +class ErrorLeaf(Leaf): + """ + A leaf that is either completely invalid in a language (like `$` in Python) + or is invalid at that position. Like the star in `1 +* 1`. + """ + __slots__ = ('token_type',) + type = 'error_leaf' + + def __init__(self, token_type, value, start_pos, prefix=''): + super().__init__(value, start_pos, prefix) + self.token_type = token_type + + def __repr__(self): + return "<%s: %s:%s, %s>" % \ + (type(self).__name__, self.token_type, repr(self.value), self.start_pos) diff --git a/shared/package-files/75/75e81de9d2da0c4bc458d1e6bd29d4657a2cd5cb08cdaaa347f8c0bad9bc25f2/blob b/shared/package-files/75/75e81de9d2da0c4bc458d1e6bd29d4657a2cd5cb08cdaaa347f8c0bad9bc25f2/blob new file mode 100644 index 0000000000000000000000000000000000000000..1e8103bcf63271a51122dd90fd1ba6f4c722502c --- /dev/null +++ b/shared/package-files/75/75e81de9d2da0c4bc458d1e6bd29d4657a2cd5cb08cdaaa347f8c0bad9bc25f2/blob @@ -0,0 +1,783 @@ +""":mod:`numpy.ma..mrecords` + +Defines the equivalent of :class:`numpy.recarrays` for masked arrays, +where fields can be accessed as attributes. +Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes +and the masking of individual fields. + +.. moduleauthor:: Pierre Gerard-Marchant + +""" +# We should make sure that no field is called '_mask','mask','_fieldmask', +# or whatever restricted keywords. An idea would be to no bother in the +# first place, and then rename the invalid fields with a trailing +# underscore. Maybe we could just overload the parser function ? + +from numpy.ma import ( + MAError, MaskedArray, masked, nomask, masked_array, getdata, + getmaskarray, filled +) +import numpy.ma as ma +import warnings + +import numpy as np +from numpy import ( + bool_, dtype, ndarray, recarray, array as narray +) +from numpy.core.records import ( + fromarrays as recfromarrays, fromrecords as recfromrecords +) + +_byteorderconv = np.core.records._byteorderconv + + +_check_fill_value = ma.core._check_fill_value + + +__all__ = [ + 'MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords', + 'fromtextfile', 'addfield', +] + +reserved_fields = ['_data', '_mask', '_fieldmask', 'dtype'] + + +def _checknames(descr, names=None): + """ + Checks that field names ``descr`` are not reserved keywords. + + If this is the case, a default 'f%i' is substituted. If the argument + `names` is not None, updates the field names to valid names. + + """ + ndescr = len(descr) + default_names = ['f%i' % i for i in range(ndescr)] + if names is None: + new_names = default_names + else: + if isinstance(names, (tuple, list)): + new_names = names + elif isinstance(names, str): + new_names = names.split(',') + else: + raise NameError(f'illegal input names {names!r}') + nnames = len(new_names) + if nnames < ndescr: + new_names += default_names[nnames:] + ndescr = [] + for (n, d, t) in zip(new_names, default_names, descr.descr): + if n in reserved_fields: + if t[0] in reserved_fields: + ndescr.append((d, t[1])) + else: + ndescr.append(t) + else: + ndescr.append((n, t[1])) + return np.dtype(ndescr) + + +def _get_fieldmask(self): + mdescr = [(n, '|b1') for n in self.dtype.names] + fdmask = np.empty(self.shape, dtype=mdescr) + fdmask.flat = tuple([False] * len(mdescr)) + return fdmask + + +class MaskedRecords(MaskedArray): + """ + + Attributes + ---------- + _data : recarray + Underlying data, as a record array. + _mask : boolean array + Mask of the records. A record is masked when all its fields are + masked. + _fieldmask : boolean recarray + Record array of booleans, setting the mask of each individual field + of each record. + _fill_value : record + Filling values for each field. + + """ + + def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None, + formats=None, names=None, titles=None, + byteorder=None, aligned=False, + mask=nomask, hard_mask=False, fill_value=None, keep_mask=True, + copy=False, + **options): + + self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset, + strides=strides, formats=formats, names=names, + titles=titles, byteorder=byteorder, + aligned=aligned,) + + mdtype = ma.make_mask_descr(self.dtype) + if mask is nomask or not np.size(mask): + if not keep_mask: + self._mask = tuple([False] * len(mdtype)) + else: + mask = np.array(mask, copy=copy) + if mask.shape != self.shape: + (nd, nm) = (self.size, mask.size) + if nm == 1: + mask = np.resize(mask, self.shape) + elif nm == nd: + mask = np.reshape(mask, self.shape) + else: + msg = "Mask and data not compatible: data size is %i, " + \ + "mask size is %i." + raise MAError(msg % (nd, nm)) + if not keep_mask: + self.__setmask__(mask) + self._sharedmask = True + else: + if mask.dtype == mdtype: + _mask = mask + else: + _mask = np.array([tuple([m] * len(mdtype)) for m in mask], + dtype=mdtype) + self._mask = _mask + return self + + def __array_finalize__(self, obj): + # Make sure we have a _fieldmask by default + _mask = getattr(obj, '_mask', None) + if _mask is None: + objmask = getattr(obj, '_mask', nomask) + _dtype = ndarray.__getattribute__(self, 'dtype') + if objmask is nomask: + _mask = ma.make_mask_none(self.shape, dtype=_dtype) + else: + mdescr = ma.make_mask_descr(_dtype) + _mask = narray([tuple([m] * len(mdescr)) for m in objmask], + dtype=mdescr).view(recarray) + # Update some of the attributes + _dict = self.__dict__ + _dict.update(_mask=_mask) + self._update_from(obj) + if _dict['_baseclass'] == ndarray: + _dict['_baseclass'] = recarray + return + + @property + def _data(self): + """ + Returns the data as a recarray. + + """ + return ndarray.view(self, recarray) + + @property + def _fieldmask(self): + """ + Alias to mask. + + """ + return self._mask + + def __len__(self): + """ + Returns the length + + """ + # We have more than one record + if self.ndim: + return len(self._data) + # We have only one record: return the nb of fields + return len(self.dtype) + + def __getattribute__(self, attr): + try: + return object.__getattribute__(self, attr) + except AttributeError: + # attr must be a fieldname + pass + fielddict = ndarray.__getattribute__(self, 'dtype').fields + try: + res = fielddict[attr][:2] + except (TypeError, KeyError) as e: + raise AttributeError( + f'record array has no attribute {attr}') from e + # So far, so good + _localdict = ndarray.__getattribute__(self, '__dict__') + _data = ndarray.view(self, _localdict['_baseclass']) + obj = _data.getfield(*res) + if obj.dtype.names is not None: + raise NotImplementedError("MaskedRecords is currently limited to" + "simple records.") + # Get some special attributes + # Reset the object's mask + hasmasked = False + _mask = _localdict.get('_mask', None) + if _mask is not None: + try: + _mask = _mask[attr] + except IndexError: + # Couldn't find a mask: use the default (nomask) + pass + tp_len = len(_mask.dtype) + hasmasked = _mask.view((bool, ((tp_len,) if tp_len else ()))).any() + if (obj.shape or hasmasked): + obj = obj.view(MaskedArray) + obj._baseclass = ndarray + obj._isfield = True + obj._mask = _mask + # Reset the field values + _fill_value = _localdict.get('_fill_value', None) + if _fill_value is not None: + try: + obj._fill_value = _fill_value[attr] + except ValueError: + obj._fill_value = None + else: + obj = obj.item() + return obj + + def __setattr__(self, attr, val): + """ + Sets the attribute attr to the value val. + + """ + # Should we call __setmask__ first ? + if attr in ['mask', 'fieldmask']: + self.__setmask__(val) + return + # Create a shortcut (so that we don't have to call getattr all the time) + _localdict = object.__getattribute__(self, '__dict__') + # Check whether we're creating a new field + newattr = attr not in _localdict + try: + # Is attr a generic attribute ? + ret = object.__setattr__(self, attr, val) + except Exception: + # Not a generic attribute: exit if it's not a valid field + fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} + optinfo = ndarray.__getattribute__(self, '_optinfo') or {} + if not (attr in fielddict or attr in optinfo): + raise + else: + # Get the list of names + fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} + # Check the attribute + if attr not in fielddict: + return ret + if newattr: + # We just added this one or this setattr worked on an + # internal attribute. + try: + object.__delattr__(self, attr) + except Exception: + return ret + # Let's try to set the field + try: + res = fielddict[attr][:2] + except (TypeError, KeyError) as e: + raise AttributeError( + f'record array has no attribute {attr}') from e + + if val is masked: + _fill_value = _localdict['_fill_value'] + if _fill_value is not None: + dval = _localdict['_fill_value'][attr] + else: + dval = val + mval = True + else: + dval = filled(val) + mval = getmaskarray(val) + obj = ndarray.__getattribute__(self, '_data').setfield(dval, *res) + _localdict['_mask'].__setitem__(attr, mval) + return obj + + def __getitem__(self, indx): + """ + Returns all the fields sharing the same fieldname base. + + The fieldname base is either `_data` or `_mask`. + + """ + _localdict = self.__dict__ + _mask = ndarray.__getattribute__(self, '_mask') + _data = ndarray.view(self, _localdict['_baseclass']) + # We want a field + if isinstance(indx, str): + # Make sure _sharedmask is True to propagate back to _fieldmask + # Don't use _set_mask, there are some copies being made that + # break propagation Don't force the mask to nomask, that wreaks + # easy masking + obj = _data[indx].view(MaskedArray) + obj._mask = _mask[indx] + obj._sharedmask = True + fval = _localdict['_fill_value'] + if fval is not None: + obj._fill_value = fval[indx] + # Force to masked if the mask is True + if not obj.ndim and obj._mask: + return masked + return obj + # We want some elements. + # First, the data. + obj = np.array(_data[indx], copy=False).view(mrecarray) + obj._mask = np.array(_mask[indx], copy=False).view(recarray) + return obj + + def __setitem__(self, indx, value): + """ + Sets the given record to value. + + """ + MaskedArray.__setitem__(self, indx, value) + if isinstance(indx, str): + self._mask[indx] = ma.getmaskarray(value) + + def __str__(self): + """ + Calculates the string representation. + + """ + if self.size > 1: + mstr = [f"({','.join([str(i) for i in s])})" + for s in zip(*[getattr(self, f) for f in self.dtype.names])] + return f"[{', '.join(mstr)}]" + else: + mstr = [f"{','.join([str(i) for i in s])}" + for s in zip([getattr(self, f) for f in self.dtype.names])] + return f"({', '.join(mstr)})" + + def __repr__(self): + """ + Calculates the repr representation. + + """ + _names = self.dtype.names + fmt = "%%%is : %%s" % (max([len(n) for n in _names]) + 4,) + reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names] + reprstr.insert(0, 'masked_records(') + reprstr.extend([fmt % (' fill_value', self.fill_value), + ' )']) + return str("\n".join(reprstr)) + + def view(self, dtype=None, type=None): + """ + Returns a view of the mrecarray. + + """ + # OK, basic copy-paste from MaskedArray.view. + if dtype is None: + if type is None: + output = ndarray.view(self) + else: + output = ndarray.view(self, type) + # Here again. + elif type is None: + try: + if issubclass(dtype, ndarray): + output = ndarray.view(self, dtype) + else: + output = ndarray.view(self, dtype) + # OK, there's the change + except TypeError: + dtype = np.dtype(dtype) + # we need to revert to MaskedArray, but keeping the possibility + # of subclasses (eg, TimeSeriesRecords), so we'll force a type + # set to the first parent + if dtype.fields is None: + basetype = self.__class__.__bases__[0] + output = self.__array__().view(dtype, basetype) + output._update_from(self) + else: + output = ndarray.view(self, dtype) + output._fill_value = None + else: + output = ndarray.view(self, dtype, type) + # Update the mask, just like in MaskedArray.view + if (getattr(output, '_mask', nomask) is not nomask): + mdtype = ma.make_mask_descr(output.dtype) + output._mask = self._mask.view(mdtype, ndarray) + output._mask.shape = output.shape + return output + + def harden_mask(self): + """ + Forces the mask to hard. + + """ + self._hardmask = True + + def soften_mask(self): + """ + Forces the mask to soft + + """ + self._hardmask = False + + def copy(self): + """ + Returns a copy of the masked record. + + """ + copied = self._data.copy().view(type(self)) + copied._mask = self._mask.copy() + return copied + + def tolist(self, fill_value=None): + """ + Return the data portion of the array as a list. + + Data items are converted to the nearest compatible Python type. + Masked values are converted to fill_value. If fill_value is None, + the corresponding entries in the output list will be ``None``. + + """ + if fill_value is not None: + return self.filled(fill_value).tolist() + result = narray(self.filled().tolist(), dtype=object) + mask = narray(self._mask.tolist()) + result[mask] = None + return result.tolist() + + def __getstate__(self): + """Return the internal state of the masked array. + + This is for pickling. + + """ + state = (1, + self.shape, + self.dtype, + self.flags.fnc, + self._data.tobytes(), + self._mask.tobytes(), + self._fill_value, + ) + return state + + def __setstate__(self, state): + """ + Restore the internal state of the masked array. + + This is for pickling. ``state`` is typically the output of the + ``__getstate__`` output, and is a 5-tuple: + + - class name + - a tuple giving the shape of the data + - a typecode for the data + - a binary string for the data + - a binary string for the mask. + + """ + (ver, shp, typ, isf, raw, msk, flv) = state + ndarray.__setstate__(self, (shp, typ, isf, raw)) + mdtype = dtype([(k, bool_) for (k, _) in self.dtype.descr]) + self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk)) + self.fill_value = flv + + def __reduce__(self): + """ + Return a 3-tuple for pickling a MaskedArray. + + """ + return (_mrreconstruct, + (self.__class__, self._baseclass, (0,), 'b',), + self.__getstate__()) + + +def _mrreconstruct(subtype, baseclass, baseshape, basetype,): + """ + Build a new MaskedArray from the information stored in a pickle. + + """ + _data = ndarray.__new__(baseclass, baseshape, basetype).view(subtype) + _mask = ndarray.__new__(ndarray, baseshape, 'b1') + return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,) + +mrecarray = MaskedRecords + + +############################################################################### +# Constructors # +############################################################################### + + +def fromarrays(arraylist, dtype=None, shape=None, formats=None, + names=None, titles=None, aligned=False, byteorder=None, + fill_value=None): + """ + Creates a mrecarray from a (flat) list of masked arrays. + + Parameters + ---------- + arraylist : sequence + A list of (masked) arrays. Each element of the sequence is first converted + to a masked array if needed. If a 2D array is passed as argument, it is + processed line by line + dtype : {None, dtype}, optional + Data type descriptor. + shape : {None, integer}, optional + Number of records. If None, shape is defined from the shape of the + first array in the list. + formats : {None, sequence}, optional + Sequence of formats for each individual field. If None, the formats will + be autodetected by inspecting the fields and selecting the highest dtype + possible. + names : {None, sequence}, optional + Sequence of the names of each field. + fill_value : {None, sequence}, optional + Sequence of data to be used as filling values. + + Notes + ----- + Lists of tuples should be preferred over lists of lists for faster processing. + + """ + datalist = [getdata(x) for x in arraylist] + masklist = [np.atleast_1d(getmaskarray(x)) for x in arraylist] + _array = recfromarrays(datalist, + dtype=dtype, shape=shape, formats=formats, + names=names, titles=titles, aligned=aligned, + byteorder=byteorder).view(mrecarray) + _array._mask.flat = list(zip(*masklist)) + if fill_value is not None: + _array.fill_value = fill_value + return _array + + +def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None, + titles=None, aligned=False, byteorder=None, + fill_value=None, mask=nomask): + """ + Creates a MaskedRecords from a list of records. + + Parameters + ---------- + reclist : sequence + A list of records. Each element of the sequence is first converted + to a masked array if needed. If a 2D array is passed as argument, it is + processed line by line + dtype : {None, dtype}, optional + Data type descriptor. + shape : {None,int}, optional + Number of records. If None, ``shape`` is defined from the shape of the + first array in the list. + formats : {None, sequence}, optional + Sequence of formats for each individual field. If None, the formats will + be autodetected by inspecting the fields and selecting the highest dtype + possible. + names : {None, sequence}, optional + Sequence of the names of each field. + fill_value : {None, sequence}, optional + Sequence of data to be used as filling values. + mask : {nomask, sequence}, optional. + External mask to apply on the data. + + Notes + ----- + Lists of tuples should be preferred over lists of lists for faster processing. + + """ + # Grab the initial _fieldmask, if needed: + _mask = getattr(reclist, '_mask', None) + # Get the list of records. + if isinstance(reclist, ndarray): + # Make sure we don't have some hidden mask + if isinstance(reclist, MaskedArray): + reclist = reclist.filled().view(ndarray) + # Grab the initial dtype, just in case + if dtype is None: + dtype = reclist.dtype + reclist = reclist.tolist() + mrec = recfromrecords(reclist, dtype=dtype, shape=shape, formats=formats, + names=names, titles=titles, + aligned=aligned, byteorder=byteorder).view(mrecarray) + # Set the fill_value if needed + if fill_value is not None: + mrec.fill_value = fill_value + # Now, let's deal w/ the mask + if mask is not nomask: + mask = np.array(mask, copy=False) + maskrecordlength = len(mask.dtype) + if maskrecordlength: + mrec._mask.flat = mask + elif mask.ndim == 2: + mrec._mask.flat = [tuple(m) for m in mask] + else: + mrec.__setmask__(mask) + if _mask is not None: + mrec._mask[:] = _mask + return mrec + + +def _guessvartypes(arr): + """ + Tries to guess the dtypes of the str_ ndarray `arr`. + + Guesses by testing element-wise conversion. Returns a list of dtypes. + The array is first converted to ndarray. If the array is 2D, the test + is performed on the first line. An exception is raised if the file is + 3D or more. + + """ + vartypes = [] + arr = np.asarray(arr) + if arr.ndim == 2: + arr = arr[0] + elif arr.ndim > 2: + raise ValueError("The array should be 2D at most!") + # Start the conversion loop. + for f in arr: + try: + int(f) + except (ValueError, TypeError): + try: + float(f) + except (ValueError, TypeError): + try: + complex(f) + except (ValueError, TypeError): + vartypes.append(arr.dtype) + else: + vartypes.append(np.dtype(complex)) + else: + vartypes.append(np.dtype(float)) + else: + vartypes.append(np.dtype(int)) + return vartypes + + +def openfile(fname): + """ + Opens the file handle of file `fname`. + + """ + # A file handle + if hasattr(fname, 'readline'): + return fname + # Try to open the file and guess its type + try: + f = open(fname) + except FileNotFoundError as e: + raise FileNotFoundError(f"No such file: '{fname}'") from e + if f.readline()[:2] != "\\x": + f.seek(0, 0) + return f + f.close() + raise NotImplementedError("Wow, binary file") + + +def fromtextfile(fname, delimiter=None, commentchar='#', missingchar='', + varnames=None, vartypes=None, + *, delimitor=np._NoValue): # backwards compatibility + """ + Creates a mrecarray from data stored in the file `filename`. + + Parameters + ---------- + fname : {file name/handle} + Handle of an opened file. + delimiter : {None, string}, optional + Alphanumeric character used to separate columns in the file. + If None, any (group of) white spacestring(s) will be used. + commentchar : {'#', string}, optional + Alphanumeric character used to mark the start of a comment. + missingchar : {'', string}, optional + String indicating missing data, and used to create the masks. + varnames : {None, sequence}, optional + Sequence of the variable names. If None, a list will be created from + the first non empty line of the file. + vartypes : {None, sequence}, optional + Sequence of the variables dtypes. If None, it will be estimated from + the first non-commented line. + + + Ultra simple: the varnames are in the header, one line""" + if delimitor is not np._NoValue: + if delimiter is not None: + raise TypeError("fromtextfile() got multiple values for argument " + "'delimiter'") + # NumPy 1.22.0, 2021-09-23 + warnings.warn("The 'delimitor' keyword argument of " + "numpy.ma.mrecords.fromtextfile() is deprecated " + "since NumPy 1.22.0, use 'delimiter' instead.", + DeprecationWarning, stacklevel=2) + delimiter = delimitor + + # Try to open the file. + ftext = openfile(fname) + + # Get the first non-empty line as the varnames + while True: + line = ftext.readline() + firstline = line[:line.find(commentchar)].strip() + _varnames = firstline.split(delimiter) + if len(_varnames) > 1: + break + if varnames is None: + varnames = _varnames + + # Get the data. + _variables = masked_array([line.strip().split(delimiter) for line in ftext + if line[0] != commentchar and len(line) > 1]) + (_, nfields) = _variables.shape + ftext.close() + + # Try to guess the dtype. + if vartypes is None: + vartypes = _guessvartypes(_variables[0]) + else: + vartypes = [np.dtype(v) for v in vartypes] + if len(vartypes) != nfields: + msg = "Attempting to %i dtypes for %i fields!" + msg += " Reverting to default." + warnings.warn(msg % (len(vartypes), nfields), stacklevel=2) + vartypes = _guessvartypes(_variables[0]) + + # Construct the descriptor. + mdescr = [(n, f) for (n, f) in zip(varnames, vartypes)] + mfillv = [ma.default_fill_value(f) for f in vartypes] + + # Get the data and the mask. + # We just need a list of masked_arrays. It's easier to create it like that: + _mask = (_variables.T == missingchar) + _datalist = [masked_array(a, mask=m, dtype=t, fill_value=f) + for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)] + + return fromarrays(_datalist, dtype=mdescr) + + +def addfield(mrecord, newfield, newfieldname=None): + """Adds a new field to the masked record array + + Uses `newfield` as data and `newfieldname` as name. If `newfieldname` + is None, the new field name is set to 'fi', where `i` is the number of + existing fields. + + """ + _data = mrecord._data + _mask = mrecord._mask + if newfieldname is None or newfieldname in reserved_fields: + newfieldname = 'f%i' % len(_data.dtype) + newfield = ma.array(newfield) + # Get the new data. + # Create a new empty recarray + newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)]) + newdata = recarray(_data.shape, newdtype) + # Add the existing field + [newdata.setfield(_data.getfield(*f), *f) + for f in _data.dtype.fields.values()] + # Add the new field + newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname]) + newdata = newdata.view(MaskedRecords) + # Get the new mask + # Create a new empty recarray + newmdtype = np.dtype([(n, bool_) for n in newdtype.names]) + newmask = recarray(_data.shape, newmdtype) + # Add the old masks + [newmask.setfield(_mask.getfield(*f), *f) + for f in _mask.dtype.fields.values()] + # Add the mask of the new field + newmask.setfield(getmaskarray(newfield), + *newmask.dtype.fields[newfieldname]) + newdata._mask = newmask + return newdata diff --git a/shared/package-files/75/75e8d14d1843091a6a1952efb4c03b088095d2ade1ea6db7f8105701f306e424/blob b/shared/package-files/75/75e8d14d1843091a6a1952efb4c03b088095d2ade1ea6db7f8105701f306e424/blob new file mode 100644 index 0000000000000000000000000000000000000000..6f62b8c18e8edd2c9ca5e783c5b80cdfa98c4cd6 --- /dev/null +++ b/shared/package-files/75/75e8d14d1843091a6a1952efb4c03b088095d2ade1ea6db7f8105701f306e424/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75e8d14d1843091a6a1952efb4c03b088095d2ade1ea6db7f8105701f306e424 +size 353720 diff --git a/shared/package-files/75/75ec8de90781c22acb9f3efc46bdb82b3863d5f40d5a2b02f94f57461717410f/blob b/shared/package-files/75/75ec8de90781c22acb9f3efc46bdb82b3863d5f40d5a2b02f94f57461717410f/blob new file mode 100644 index 0000000000000000000000000000000000000000..844e2c9de87506b5b6aba4eaa5af2a80123aa473 Binary files /dev/null and b/shared/package-files/75/75ec8de90781c22acb9f3efc46bdb82b3863d5f40d5a2b02f94f57461717410f/blob differ diff --git a/shared/package-files/75/75edd1f0f84d24ee654fda02a91c5ef1edbf484de30691ce9306cda82ae58234/blob b/shared/package-files/75/75edd1f0f84d24ee654fda02a91c5ef1edbf484de30691ce9306cda82ae58234/blob new file mode 100644 index 0000000000000000000000000000000000000000..d8c4e430e53d49a8fe7d237ffe7ba8feae5e452f --- /dev/null +++ b/shared/package-files/75/75edd1f0f84d24ee654fda02a91c5ef1edbf484de30691ce9306cda82ae58234/blob @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include "arrow/compute/exec.h" +#include "arrow/compute/function.h" +#include "arrow/compute/registry.h" +#include "arrow/python/platform.h" +#include "arrow/record_batch.h" +#include "arrow/util/iterator.h" + +#include "arrow/python/common.h" +#include "arrow/python/pyarrow.h" +#include "arrow/python/visibility.h" + +namespace arrow { + +namespace py { + +// TODO: TODO(ARROW-16041): UDF Options are not exposed to the Python +// users. This feature will be included when extending to provide advanced +// options for the users. +struct ARROW_PYTHON_EXPORT UdfOptions { + std::string func_name; + compute::Arity arity; + compute::FunctionDoc func_doc; + std::vector> input_types; + std::shared_ptr output_type; +}; + +/// \brief A context passed as the first argument of UDF functions. +struct ARROW_PYTHON_EXPORT UdfContext { + MemoryPool* pool; + int64_t batch_length; +}; + +using UdfWrapperCallback = std::function; + +/// \brief register a Scalar user-defined-function from Python +Status ARROW_PYTHON_EXPORT RegisterScalarFunction( + PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, + compute::FunctionRegistry* registry = NULLPTR); + +/// \brief register a Table user-defined-function from Python +Status ARROW_PYTHON_EXPORT RegisterTabularFunction( + PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, + compute::FunctionRegistry* registry = NULLPTR); + +/// \brief register a Aggregate user-defined-function from Python +Status ARROW_PYTHON_EXPORT RegisterAggregateFunction( + PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, + compute::FunctionRegistry* registry = NULLPTR); + +/// \brief register a Vector user-defined-function from Python +Status ARROW_PYTHON_EXPORT RegisterVectorFunction( + PyObject* user_function, UdfWrapperCallback wrapper, const UdfOptions& options, + compute::FunctionRegistry* registry = NULLPTR); + +Result> ARROW_PYTHON_EXPORT +CallTabularFunction(const std::string& func_name, const std::vector& args, + compute::FunctionRegistry* registry = NULLPTR); + +} // namespace py + +} // namespace arrow diff --git a/shared/package-files/75/75ee39c1382e9b598d373054455c5b9f2204f535a1141e256a92564f449c55cc/blob b/shared/package-files/75/75ee39c1382e9b598d373054455c5b9f2204f535a1141e256a92564f449c55cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..0144600066ff3b8690ce93f2fa9480d4246417d9 --- /dev/null +++ b/shared/package-files/75/75ee39c1382e9b598d373054455c5b9f2204f535a1141e256a92564f449c55cc/blob @@ -0,0 +1,998 @@ +from __future__ import annotations + +import calendar +import codecs +import collections +import mmap +import os +import re +import time +import zlib + + +# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set +# on page 656 +def encode_text(s): + return codecs.BOM_UTF16_BE + s.encode("utf_16_be") + + +PDFDocEncoding = { + 0x16: "\u0017", + 0x18: "\u02D8", + 0x19: "\u02C7", + 0x1A: "\u02C6", + 0x1B: "\u02D9", + 0x1C: "\u02DD", + 0x1D: "\u02DB", + 0x1E: "\u02DA", + 0x1F: "\u02DC", + 0x80: "\u2022", + 0x81: "\u2020", + 0x82: "\u2021", + 0x83: "\u2026", + 0x84: "\u2014", + 0x85: "\u2013", + 0x86: "\u0192", + 0x87: "\u2044", + 0x88: "\u2039", + 0x89: "\u203A", + 0x8A: "\u2212", + 0x8B: "\u2030", + 0x8C: "\u201E", + 0x8D: "\u201C", + 0x8E: "\u201D", + 0x8F: "\u2018", + 0x90: "\u2019", + 0x91: "\u201A", + 0x92: "\u2122", + 0x93: "\uFB01", + 0x94: "\uFB02", + 0x95: "\u0141", + 0x96: "\u0152", + 0x97: "\u0160", + 0x98: "\u0178", + 0x99: "\u017D", + 0x9A: "\u0131", + 0x9B: "\u0142", + 0x9C: "\u0153", + 0x9D: "\u0161", + 0x9E: "\u017E", + 0xA0: "\u20AC", +} + + +def decode_text(b): + if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: + return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be") + else: + return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b) + + +class PdfFormatError(RuntimeError): + """An error that probably indicates a syntactic or semantic error in the + PDF file structure""" + + pass + + +def check_format_condition(condition, error_message): + if not condition: + raise PdfFormatError(error_message) + + +class IndirectReference( + collections.namedtuple("IndirectReferenceTuple", ["object_id", "generation"]) +): + def __str__(self): + return f"{self.object_id} {self.generation} R" + + def __bytes__(self): + return self.__str__().encode("us-ascii") + + def __eq__(self, other): + return ( + other.__class__ is self.__class__ + and other.object_id == self.object_id + and other.generation == self.generation + ) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash((self.object_id, self.generation)) + + +class IndirectObjectDef(IndirectReference): + def __str__(self): + return f"{self.object_id} {self.generation} obj" + + +class XrefTable: + def __init__(self): + self.existing_entries = {} # object ID => (offset, generation) + self.new_entries = {} # object ID => (offset, generation) + self.deleted_entries = {0: 65536} # object ID => generation + self.reading_finished = False + + def __setitem__(self, key, value): + if self.reading_finished: + self.new_entries[key] = value + else: + self.existing_entries[key] = value + if key in self.deleted_entries: + del self.deleted_entries[key] + + def __getitem__(self, key): + try: + return self.new_entries[key] + except KeyError: + return self.existing_entries[key] + + def __delitem__(self, key): + if key in self.new_entries: + generation = self.new_entries[key][1] + 1 + del self.new_entries[key] + self.deleted_entries[key] = generation + elif key in self.existing_entries: + generation = self.existing_entries[key][1] + 1 + self.deleted_entries[key] = generation + elif key in self.deleted_entries: + generation = self.deleted_entries[key] + else: + msg = ( + "object ID " + str(key) + " cannot be deleted because it doesn't exist" + ) + raise IndexError(msg) + + def __contains__(self, key): + return key in self.existing_entries or key in self.new_entries + + def __len__(self): + return len( + set(self.existing_entries.keys()) + | set(self.new_entries.keys()) + | set(self.deleted_entries.keys()) + ) + + def keys(self): + return ( + set(self.existing_entries.keys()) - set(self.deleted_entries.keys()) + ) | set(self.new_entries.keys()) + + def write(self, f): + keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys())) + deleted_keys = sorted(set(self.deleted_entries.keys())) + startxref = f.tell() + f.write(b"xref\n") + while keys: + # find a contiguous sequence of object IDs + prev = None + for index, key in enumerate(keys): + if prev is None or prev + 1 == key: + prev = key + else: + contiguous_keys = keys[:index] + keys = keys[index:] + break + else: + contiguous_keys = keys + keys = None + f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys))) + for object_id in contiguous_keys: + if object_id in self.new_entries: + f.write(b"%010d %05d n \n" % self.new_entries[object_id]) + else: + this_deleted_object_id = deleted_keys.pop(0) + check_format_condition( + object_id == this_deleted_object_id, + f"expected the next deleted object ID to be {object_id}, " + f"instead found {this_deleted_object_id}", + ) + try: + next_in_linked_list = deleted_keys[0] + except IndexError: + next_in_linked_list = 0 + f.write( + b"%010d %05d f \n" + % (next_in_linked_list, self.deleted_entries[object_id]) + ) + return startxref + + +class PdfName: + def __init__(self, name): + if isinstance(name, PdfName): + self.name = name.name + elif isinstance(name, bytes): + self.name = name + else: + self.name = name.encode("us-ascii") + + def name_as_str(self): + return self.name.decode("us-ascii") + + def __eq__(self, other): + return ( + isinstance(other, PdfName) and other.name == self.name + ) or other == self.name + + def __hash__(self): + return hash(self.name) + + def __repr__(self): + return f"PdfName({repr(self.name)})" + + @classmethod + def from_pdf_stream(cls, data): + return cls(PdfParser.interpret_name(data)) + + allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"} + + def __bytes__(self): + result = bytearray(b"/") + for b in self.name: + if b in self.allowed_chars: + result.append(b) + else: + result.extend(b"#%02X" % b) + return bytes(result) + + +class PdfArray(list): + def __bytes__(self): + return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]" + + +class PdfDict(collections.UserDict): + def __setattr__(self, key, value): + if key == "data": + collections.UserDict.__setattr__(self, key, value) + else: + self[key.encode("us-ascii")] = value + + def __getattr__(self, key): + try: + value = self[key.encode("us-ascii")] + except KeyError as e: + raise AttributeError(key) from e + if isinstance(value, bytes): + value = decode_text(value) + if key.endswith("Date"): + if value.startswith("D:"): + value = value[2:] + + relationship = "Z" + if len(value) > 17: + relationship = value[14] + offset = int(value[15:17]) * 60 + if len(value) > 20: + offset += int(value[18:20]) + + format = "%Y%m%d%H%M%S"[: len(value) - 2] + value = time.strptime(value[: len(format) + 2], format) + if relationship in ["+", "-"]: + offset *= 60 + if relationship == "+": + offset *= -1 + value = time.gmtime(calendar.timegm(value) + offset) + return value + + def __bytes__(self): + out = bytearray(b"<<") + for key, value in self.items(): + if value is None: + continue + value = pdf_repr(value) + out.extend(b"\n") + out.extend(bytes(PdfName(key))) + out.extend(b" ") + out.extend(value) + out.extend(b"\n>>") + return bytes(out) + + +class PdfBinary: + def __init__(self, data): + self.data = data + + def __bytes__(self): + return b"<%s>" % b"".join(b"%02X" % b for b in self.data) + + +class PdfStream: + def __init__(self, dictionary, buf): + self.dictionary = dictionary + self.buf = buf + + def decode(self): + try: + filter = self.dictionary.Filter + except AttributeError: + return self.buf + if filter == b"FlateDecode": + try: + expected_length = self.dictionary.DL + except AttributeError: + expected_length = self.dictionary.Length + return zlib.decompress(self.buf, bufsize=int(expected_length)) + else: + msg = f"stream filter {repr(self.dictionary.Filter)} unknown/unsupported" + raise NotImplementedError(msg) + + +def pdf_repr(x): + if x is True: + return b"true" + elif x is False: + return b"false" + elif x is None: + return b"null" + elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)): + return bytes(x) + elif isinstance(x, (int, float)): + return str(x).encode("us-ascii") + elif isinstance(x, time.struct_time): + return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")" + elif isinstance(x, dict): + return bytes(PdfDict(x)) + elif isinstance(x, list): + return bytes(PdfArray(x)) + elif isinstance(x, str): + return pdf_repr(encode_text(x)) + elif isinstance(x, bytes): + # XXX escape more chars? handle binary garbage + x = x.replace(b"\\", b"\\\\") + x = x.replace(b"(", b"\\(") + x = x.replace(b")", b"\\)") + return b"(" + x + b")" + else: + return bytes(x) + + +class PdfParser: + """Based on + https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf + Supports PDF up to 1.4 + """ + + def __init__(self, filename=None, f=None, buf=None, start_offset=0, mode="rb"): + if buf and f: + msg = "specify buf or f or filename, but not both buf and f" + raise RuntimeError(msg) + self.filename = filename + self.buf = buf + self.f = f + self.start_offset = start_offset + self.should_close_buf = False + self.should_close_file = False + if filename is not None and f is None: + self.f = f = open(filename, mode) + self.should_close_file = True + if f is not None: + self.buf = buf = self.get_buf_from_file(f) + self.should_close_buf = True + if not filename and hasattr(f, "name"): + self.filename = f.name + self.cached_objects = {} + if buf: + self.read_pdf_info() + else: + self.file_size_total = self.file_size_this = 0 + self.root = PdfDict() + self.root_ref = None + self.info = PdfDict() + self.info_ref = None + self.page_tree_root = {} + self.pages = [] + self.orig_pages = [] + self.pages_ref = None + self.last_xref_section_offset = None + self.trailer_dict = {} + self.xref_table = XrefTable() + self.xref_table.reading_finished = True + if f: + self.seek_end() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + return False # do not suppress exceptions + + def start_writing(self): + self.close_buf() + self.seek_end() + + def close_buf(self): + try: + self.buf.close() + except AttributeError: + pass + self.buf = None + + def close(self): + if self.should_close_buf: + self.close_buf() + if self.f is not None and self.should_close_file: + self.f.close() + self.f = None + + def seek_end(self): + self.f.seek(0, os.SEEK_END) + + def write_header(self): + self.f.write(b"%PDF-1.4\n") + + def write_comment(self, s): + self.f.write(f"% {s}\n".encode()) + + def write_catalog(self): + self.del_root() + self.root_ref = self.next_object_id(self.f.tell()) + self.pages_ref = self.next_object_id(0) + self.rewrite_pages() + self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref) + self.write_obj( + self.pages_ref, + Type=PdfName(b"Pages"), + Count=len(self.pages), + Kids=self.pages, + ) + return self.root_ref + + def rewrite_pages(self): + pages_tree_nodes_to_delete = [] + for i, page_ref in enumerate(self.orig_pages): + page_info = self.cached_objects[page_ref] + del self.xref_table[page_ref.object_id] + pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")]) + if page_ref not in self.pages: + # the page has been deleted + continue + # make dict keys into strings for passing to write_page + stringified_page_info = {} + for key, value in page_info.items(): + # key should be a PdfName + stringified_page_info[key.name_as_str()] = value + stringified_page_info["Parent"] = self.pages_ref + new_page_ref = self.write_page(None, **stringified_page_info) + for j, cur_page_ref in enumerate(self.pages): + if cur_page_ref == page_ref: + # replace the page reference with the new one + self.pages[j] = new_page_ref + # delete redundant Pages tree nodes from xref table + for pages_tree_node_ref in pages_tree_nodes_to_delete: + while pages_tree_node_ref: + pages_tree_node = self.cached_objects[pages_tree_node_ref] + if pages_tree_node_ref.object_id in self.xref_table: + del self.xref_table[pages_tree_node_ref.object_id] + pages_tree_node_ref = pages_tree_node.get(b"Parent", None) + self.orig_pages = [] + + def write_xref_and_trailer(self, new_root_ref=None): + if new_root_ref: + self.del_root() + self.root_ref = new_root_ref + if self.info: + self.info_ref = self.write_obj(None, self.info) + start_xref = self.xref_table.write(self.f) + num_entries = len(self.xref_table) + trailer_dict = {b"Root": self.root_ref, b"Size": num_entries} + if self.last_xref_section_offset is not None: + trailer_dict[b"Prev"] = self.last_xref_section_offset + if self.info: + trailer_dict[b"Info"] = self.info_ref + self.last_xref_section_offset = start_xref + self.f.write( + b"trailer\n" + + bytes(PdfDict(trailer_dict)) + + b"\nstartxref\n%d\n%%%%EOF" % start_xref + ) + + def write_page(self, ref, *objs, **dict_obj): + if isinstance(ref, int): + ref = self.pages[ref] + if "Type" not in dict_obj: + dict_obj["Type"] = PdfName(b"Page") + if "Parent" not in dict_obj: + dict_obj["Parent"] = self.pages_ref + return self.write_obj(ref, *objs, **dict_obj) + + def write_obj(self, ref, *objs, **dict_obj): + f = self.f + if ref is None: + ref = self.next_object_id(f.tell()) + else: + self.xref_table[ref.object_id] = (f.tell(), ref.generation) + f.write(bytes(IndirectObjectDef(*ref))) + stream = dict_obj.pop("stream", None) + if stream is not None: + dict_obj["Length"] = len(stream) + if dict_obj: + f.write(pdf_repr(dict_obj)) + for obj in objs: + f.write(pdf_repr(obj)) + if stream is not None: + f.write(b"stream\n") + f.write(stream) + f.write(b"\nendstream\n") + f.write(b"endobj\n") + return ref + + def del_root(self): + if self.root_ref is None: + return + del self.xref_table[self.root_ref.object_id] + del self.xref_table[self.root[b"Pages"].object_id] + + @staticmethod + def get_buf_from_file(f): + if hasattr(f, "getbuffer"): + return f.getbuffer() + elif hasattr(f, "getvalue"): + return f.getvalue() + else: + try: + return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) + except ValueError: # cannot mmap an empty file + return b"" + + def read_pdf_info(self): + self.file_size_total = len(self.buf) + self.file_size_this = self.file_size_total - self.start_offset + self.read_trailer() + self.root_ref = self.trailer_dict[b"Root"] + self.info_ref = self.trailer_dict.get(b"Info", None) + self.root = PdfDict(self.read_indirect(self.root_ref)) + if self.info_ref is None: + self.info = PdfDict() + else: + self.info = PdfDict(self.read_indirect(self.info_ref)) + check_format_condition(b"Type" in self.root, "/Type missing in Root") + check_format_condition( + self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog" + ) + check_format_condition(b"Pages" in self.root, "/Pages missing in Root") + check_format_condition( + isinstance(self.root[b"Pages"], IndirectReference), + "/Pages in Root is not an indirect reference", + ) + self.pages_ref = self.root[b"Pages"] + self.page_tree_root = self.read_indirect(self.pages_ref) + self.pages = self.linearize_page_tree(self.page_tree_root) + # save the original list of page references + # in case the user modifies, adds or deletes some pages + # and we need to rewrite the pages and their list + self.orig_pages = self.pages[:] + + def next_object_id(self, offset=None): + try: + # TODO: support reuse of deleted objects + reference = IndirectReference(max(self.xref_table.keys()) + 1, 0) + except ValueError: + reference = IndirectReference(1, 0) + if offset is not None: + self.xref_table[reference.object_id] = (offset, 0) + return reference + + delimiter = rb"[][()<>{}/%]" + delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]" + whitespace = rb"[\000\011\012\014\015\040]" + whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]" + whitespace_optional = whitespace + b"*" + whitespace_mandatory = whitespace + b"+" + # No "\012" aka "\n" or "\015" aka "\r": + whitespace_optional_no_nl = rb"[\000\011\014\040]*" + newline_only = rb"[\r\n]+" + newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl + re_trailer_end = re.compile( + whitespace_mandatory + + rb"trailer" + + whitespace_optional + + rb"<<(.*>>)" + + newline + + rb"startxref" + + newline + + rb"([0-9]+)" + + newline + + rb"%%EOF" + + whitespace_optional + + rb"$", + re.DOTALL, + ) + re_trailer_prev = re.compile( + whitespace_optional + + rb"trailer" + + whitespace_optional + + rb"<<(.*?>>)" + + newline + + rb"startxref" + + newline + + rb"([0-9]+)" + + newline + + rb"%%EOF" + + whitespace_optional, + re.DOTALL, + ) + + def read_trailer(self): + search_start_offset = len(self.buf) - 16384 + if search_start_offset < self.start_offset: + search_start_offset = self.start_offset + m = self.re_trailer_end.search(self.buf, search_start_offset) + check_format_condition(m, "trailer end not found") + # make sure we found the LAST trailer + last_match = m + while m: + last_match = m + m = self.re_trailer_end.search(self.buf, m.start() + 16) + if not m: + m = last_match + trailer_data = m.group(1) + self.last_xref_section_offset = int(m.group(2)) + self.trailer_dict = self.interpret_trailer(trailer_data) + self.xref_table = XrefTable() + self.read_xref_table(xref_section_offset=self.last_xref_section_offset) + if b"Prev" in self.trailer_dict: + self.read_prev_trailer(self.trailer_dict[b"Prev"]) + + def read_prev_trailer(self, xref_section_offset): + trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset) + m = self.re_trailer_prev.search( + self.buf[trailer_offset : trailer_offset + 16384] + ) + check_format_condition(m, "previous trailer not found") + trailer_data = m.group(1) + check_format_condition( + int(m.group(2)) == xref_section_offset, + "xref section offset in previous trailer doesn't match what was expected", + ) + trailer_dict = self.interpret_trailer(trailer_data) + if b"Prev" in trailer_dict: + self.read_prev_trailer(trailer_dict[b"Prev"]) + + re_whitespace_optional = re.compile(whitespace_optional) + re_name = re.compile( + whitespace_optional + + rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?=" + + delimiter_or_ws + + rb")" + ) + re_dict_start = re.compile(whitespace_optional + rb"<<") + re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional) + + @classmethod + def interpret_trailer(cls, trailer_data): + trailer = {} + offset = 0 + while True: + m = cls.re_name.match(trailer_data, offset) + if not m: + m = cls.re_dict_end.match(trailer_data, offset) + check_format_condition( + m and m.end() == len(trailer_data), + "name not found in trailer, remaining data: " + + repr(trailer_data[offset:]), + ) + break + key = cls.interpret_name(m.group(1)) + value, offset = cls.get_value(trailer_data, m.end()) + trailer[key] = value + check_format_condition( + b"Size" in trailer and isinstance(trailer[b"Size"], int), + "/Size not in trailer or not an integer", + ) + check_format_condition( + b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference), + "/Root not in trailer or not an indirect reference", + ) + return trailer + + re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?") + + @classmethod + def interpret_name(cls, raw, as_text=False): + name = b"" + for m in cls.re_hashes_in_name.finditer(raw): + if m.group(3): + name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii")) + else: + name += m.group(1) + if as_text: + return name.decode("utf-8") + else: + return bytes(name) + + re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")") + re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")") + re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")") + re_int = re.compile( + whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")" + ) + re_real = re.compile( + whitespace_optional + + rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?=" + + delimiter_or_ws + + rb")" + ) + re_array_start = re.compile(whitespace_optional + rb"\[") + re_array_end = re.compile(whitespace_optional + rb"]") + re_string_hex = re.compile( + whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>" + ) + re_string_lit = re.compile(whitespace_optional + rb"\(") + re_indirect_reference = re.compile( + whitespace_optional + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"R(?=" + + delimiter_or_ws + + rb")" + ) + re_indirect_def_start = re.compile( + whitespace_optional + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"obj(?=" + + delimiter_or_ws + + rb")" + ) + re_indirect_def_end = re.compile( + whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")" + ) + re_comment = re.compile( + rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*" + ) + re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n") + re_stream_end = re.compile( + whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")" + ) + + @classmethod + def get_value(cls, data, offset, expect_indirect=None, max_nesting=-1): + if max_nesting == 0: + return None, None + m = cls.re_comment.match(data, offset) + if m: + offset = m.end() + m = cls.re_indirect_def_start.match(data, offset) + if m: + check_format_condition( + int(m.group(1)) > 0, + "indirect object definition: object ID must be greater than 0", + ) + check_format_condition( + int(m.group(2)) >= 0, + "indirect object definition: generation must be non-negative", + ) + check_format_condition( + expect_indirect is None + or expect_indirect + == IndirectReference(int(m.group(1)), int(m.group(2))), + "indirect object definition different than expected", + ) + object, offset = cls.get_value(data, m.end(), max_nesting=max_nesting - 1) + if offset is None: + return object, None + m = cls.re_indirect_def_end.match(data, offset) + check_format_condition(m, "indirect object definition end not found") + return object, m.end() + check_format_condition( + not expect_indirect, "indirect object definition not found" + ) + m = cls.re_indirect_reference.match(data, offset) + if m: + check_format_condition( + int(m.group(1)) > 0, + "indirect object reference: object ID must be greater than 0", + ) + check_format_condition( + int(m.group(2)) >= 0, + "indirect object reference: generation must be non-negative", + ) + return IndirectReference(int(m.group(1)), int(m.group(2))), m.end() + m = cls.re_dict_start.match(data, offset) + if m: + offset = m.end() + result = {} + m = cls.re_dict_end.match(data, offset) + while not m: + key, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1) + if offset is None: + return result, None + value, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1) + result[key] = value + if offset is None: + return result, None + m = cls.re_dict_end.match(data, offset) + offset = m.end() + m = cls.re_stream_start.match(data, offset) + if m: + try: + stream_len = int(result[b"Length"]) + except (TypeError, KeyError, ValueError) as e: + msg = "bad or missing Length in stream dict (%r)" % result.get( + b"Length", None + ) + raise PdfFormatError(msg) from e + stream_data = data[m.end() : m.end() + stream_len] + m = cls.re_stream_end.match(data, m.end() + stream_len) + check_format_condition(m, "stream end not found") + offset = m.end() + result = PdfStream(PdfDict(result), stream_data) + else: + result = PdfDict(result) + return result, offset + m = cls.re_array_start.match(data, offset) + if m: + offset = m.end() + result = [] + m = cls.re_array_end.match(data, offset) + while not m: + value, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1) + result.append(value) + if offset is None: + return result, None + m = cls.re_array_end.match(data, offset) + return result, m.end() + m = cls.re_null.match(data, offset) + if m: + return None, m.end() + m = cls.re_true.match(data, offset) + if m: + return True, m.end() + m = cls.re_false.match(data, offset) + if m: + return False, m.end() + m = cls.re_name.match(data, offset) + if m: + return PdfName(cls.interpret_name(m.group(1))), m.end() + m = cls.re_int.match(data, offset) + if m: + return int(m.group(1)), m.end() + m = cls.re_real.match(data, offset) + if m: + # XXX Decimal instead of float??? + return float(m.group(1)), m.end() + m = cls.re_string_hex.match(data, offset) + if m: + # filter out whitespace + hex_string = bytearray( + b for b in m.group(1) if b in b"0123456789abcdefABCDEF" + ) + if len(hex_string) % 2 == 1: + # append a 0 if the length is not even - yes, at the end + hex_string.append(ord(b"0")) + return bytearray.fromhex(hex_string.decode("us-ascii")), m.end() + m = cls.re_string_lit.match(data, offset) + if m: + return cls.get_literal_string(data, m.end()) + # return None, offset # fallback (only for debugging) + msg = "unrecognized object: " + repr(data[offset : offset + 32]) + raise PdfFormatError(msg) + + re_lit_str_token = re.compile( + rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))" + ) + escaped_chars = { + b"n": b"\n", + b"r": b"\r", + b"t": b"\t", + b"b": b"\b", + b"f": b"\f", + b"(": b"(", + b")": b")", + b"\\": b"\\", + ord(b"n"): b"\n", + ord(b"r"): b"\r", + ord(b"t"): b"\t", + ord(b"b"): b"\b", + ord(b"f"): b"\f", + ord(b"("): b"(", + ord(b")"): b")", + ord(b"\\"): b"\\", + } + + @classmethod + def get_literal_string(cls, data, offset): + nesting_depth = 0 + result = bytearray() + for m in cls.re_lit_str_token.finditer(data, offset): + result.extend(data[offset : m.start()]) + if m.group(1): + result.extend(cls.escaped_chars[m.group(1)[1]]) + elif m.group(2): + result.append(int(m.group(2)[1:], 8)) + elif m.group(3): + pass + elif m.group(5): + result.extend(b"\n") + elif m.group(6): + result.extend(b"(") + nesting_depth += 1 + elif m.group(7): + if nesting_depth == 0: + return bytes(result), m.end() + result.extend(b")") + nesting_depth -= 1 + offset = m.end() + msg = "unfinished literal string" + raise PdfFormatError(msg) + + re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline) + re_xref_subsection_start = re.compile( + whitespace_optional + + rb"([0-9]+)" + + whitespace_mandatory + + rb"([0-9]+)" + + whitespace_optional + + newline_only + ) + re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)") + + def read_xref_table(self, xref_section_offset): + subsection_found = False + m = self.re_xref_section_start.match( + self.buf, xref_section_offset + self.start_offset + ) + check_format_condition(m, "xref section start not found") + offset = m.end() + while True: + m = self.re_xref_subsection_start.match(self.buf, offset) + if not m: + check_format_condition( + subsection_found, "xref subsection start not found" + ) + break + subsection_found = True + offset = m.end() + first_object = int(m.group(1)) + num_objects = int(m.group(2)) + for i in range(first_object, first_object + num_objects): + m = self.re_xref_entry.match(self.buf, offset) + check_format_condition(m, "xref entry not found") + offset = m.end() + is_free = m.group(3) == b"f" + if not is_free: + generation = int(m.group(2)) + new_entry = (int(m.group(1)), generation) + if i not in self.xref_table: + self.xref_table[i] = new_entry + return offset + + def read_indirect(self, ref, max_nesting=-1): + offset, generation = self.xref_table[ref[0]] + check_format_condition( + generation == ref[1], + f"expected to find generation {ref[1]} for object ID {ref[0]} in xref " + f"table, instead found generation {generation} at offset {offset}", + ) + value = self.get_value( + self.buf, + offset + self.start_offset, + expect_indirect=IndirectReference(*ref), + max_nesting=max_nesting, + )[0] + self.cached_objects[ref] = value + return value + + def linearize_page_tree(self, node=None): + if node is None: + node = self.page_tree_root + check_format_condition( + node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages" + ) + pages = [] + for kid in node[b"Kids"]: + kid_object = self.read_indirect(kid) + if kid_object[b"Type"] == b"Page": + pages.append(kid) + else: + pages.extend(self.linearize_page_tree(node=kid_object)) + return pages diff --git a/shared/package-files/75/75ee9e626dc3fd87445b5ac428e2044bf684caf6e3a9133df08ebb97c4061955/blob b/shared/package-files/75/75ee9e626dc3fd87445b5ac428e2044bf684caf6e3a9133df08ebb97c4061955/blob new file mode 100644 index 0000000000000000000000000000000000000000..1da77d2be6b8351ad16ef142f7add51f316e58ef --- /dev/null +++ b/shared/package-files/75/75ee9e626dc3fd87445b5ac428e2044bf684caf6e3a9133df08ebb97c4061955/blob @@ -0,0 +1,238 @@ +""" +SymPy core decorators. + +The purpose of this module is to expose decorators without any other +dependencies, so that they can be easily imported anywhere in sympy/core. +""" + +from functools import wraps +from .sympify import SympifyError, sympify + + +def _sympifyit(arg, retval=None): + """ + decorator to smartly _sympify function arguments + + Explanation + =========== + + @_sympifyit('other', NotImplemented) + def add(self, other): + ... + + In add, other can be thought of as already being a SymPy object. + + If it is not, the code is likely to catch an exception, then other will + be explicitly _sympified, and the whole code restarted. + + if _sympify(arg) fails, NotImplemented will be returned + + See also + ======== + + __sympifyit + """ + def deco(func): + return __sympifyit(func, arg, retval) + + return deco + + +def __sympifyit(func, arg, retval=None): + """Decorator to _sympify `arg` argument for function `func`. + + Do not use directly -- use _sympifyit instead. + """ + + # we support f(a,b) only + if not func.__code__.co_argcount: + raise LookupError("func not found") + # only b is _sympified + assert func.__code__.co_varnames[1] == arg + if retval is None: + @wraps(func) + def __sympifyit_wrapper(a, b): + return func(a, sympify(b, strict=True)) + + else: + @wraps(func) + def __sympifyit_wrapper(a, b): + try: + # If an external class has _op_priority, it knows how to deal + # with SymPy objects. Otherwise, it must be converted. + if not hasattr(b, '_op_priority'): + b = sympify(b, strict=True) + return func(a, b) + except SympifyError: + return retval + + return __sympifyit_wrapper + + +def call_highest_priority(method_name): + """A decorator for binary special methods to handle _op_priority. + + Explanation + =========== + + Binary special methods in Expr and its subclasses use a special attribute + '_op_priority' to determine whose special method will be called to + handle the operation. In general, the object having the highest value of + '_op_priority' will handle the operation. Expr and subclasses that define + custom binary special methods (__mul__, etc.) should decorate those + methods with this decorator to add the priority logic. + + The ``method_name`` argument is the name of the method of the other class + that will be called. Use this decorator in the following manner:: + + # Call other.__rmul__ if other._op_priority > self._op_priority + @call_highest_priority('__rmul__') + def __mul__(self, other): + ... + + # Call other.__mul__ if other._op_priority > self._op_priority + @call_highest_priority('__mul__') + def __rmul__(self, other): + ... + """ + def priority_decorator(func): + @wraps(func) + def binary_op_wrapper(self, other): + if hasattr(other, '_op_priority'): + if other._op_priority > self._op_priority: + f = getattr(other, method_name, None) + if f is not None: + return f(self) + return func(self, other) + return binary_op_wrapper + return priority_decorator + + +def sympify_method_args(cls): + '''Decorator for a class with methods that sympify arguments. + + Explanation + =========== + + The sympify_method_args decorator is to be used with the sympify_return + decorator for automatic sympification of method arguments. This is + intended for the common idiom of writing a class like : + + Examples + ======== + + >>> from sympy import Basic, SympifyError, S + >>> from sympy.core.sympify import _sympify + + >>> class MyTuple(Basic): + ... def __add__(self, other): + ... try: + ... other = _sympify(other) + ... except SympifyError: + ... return NotImplemented + ... if not isinstance(other, MyTuple): + ... return NotImplemented + ... return MyTuple(*(self.args + other.args)) + + >>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4)) + MyTuple(1, 2, 3, 4) + + In the above it is important that we return NotImplemented when other is + not sympifiable and also when the sympified result is not of the expected + type. This allows the MyTuple class to be used cooperatively with other + classes that overload __add__ and want to do something else in combination + with instance of Tuple. + + Using this decorator the above can be written as + + >>> from sympy.core.decorators import sympify_method_args, sympify_return + + >>> @sympify_method_args + ... class MyTuple(Basic): + ... @sympify_return([('other', 'MyTuple')], NotImplemented) + ... def __add__(self, other): + ... return MyTuple(*(self.args + other.args)) + + >>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4)) + MyTuple(1, 2, 3, 4) + + The idea here is that the decorators take care of the boiler-plate code + for making this happen in each method that potentially needs to accept + unsympified arguments. Then the body of e.g. the __add__ method can be + written without needing to worry about calling _sympify or checking the + type of the resulting object. + + The parameters for sympify_return are a list of tuples of the form + (parameter_name, expected_type) and the value to return (e.g. + NotImplemented). The expected_type parameter can be a type e.g. Tuple or a + string 'Tuple'. Using a string is useful for specifying a Type within its + class body (as in the above example). + + Notes: Currently sympify_return only works for methods that take a single + argument (not including self). Specifying an expected_type as a string + only works for the class in which the method is defined. + ''' + # Extract the wrapped methods from each of the wrapper objects created by + # the sympify_return decorator. Doing this here allows us to provide the + # cls argument which is used for forward string referencing. + for attrname, obj in cls.__dict__.items(): + if isinstance(obj, _SympifyWrapper): + setattr(cls, attrname, obj.make_wrapped(cls)) + return cls + + +def sympify_return(*args): + '''Function/method decorator to sympify arguments automatically + + See the docstring of sympify_method_args for explanation. + ''' + # Store a wrapper object for the decorated method + def wrapper(func): + return _SympifyWrapper(func, args) + return wrapper + + +class _SympifyWrapper: + '''Internal class used by sympify_return and sympify_method_args''' + + def __init__(self, func, args): + self.func = func + self.args = args + + def make_wrapped(self, cls): + func = self.func + parameters, retval = self.args + + # XXX: Handle more than one parameter? + [(parameter, expectedcls)] = parameters + + # Handle forward references to the current class using strings + if expectedcls == cls.__name__: + expectedcls = cls + + # Raise RuntimeError since this is a failure at import time and should + # not be recoverable. + nargs = func.__code__.co_argcount + # we support f(a, b) only + if nargs != 2: + raise RuntimeError('sympify_return can only be used with 2 argument functions') + # only b is _sympified + if func.__code__.co_varnames[1] != parameter: + raise RuntimeError('parameter name mismatch "%s" in %s' % + (parameter, func.__name__)) + + @wraps(func) + def _func(self, other): + # XXX: The check for _op_priority here should be removed. It is + # needed to stop mutable matrices from being sympified to + # immutable matrices which breaks things in quantum... + if not hasattr(other, '_op_priority'): + try: + other = sympify(other, strict=True) + except SympifyError: + return retval + if not isinstance(other, expectedcls): + return retval + return func(self, other) + + return _func diff --git a/shared/package-files/75/75ef12387b6d39f395efff2d1b7d9f6abbb9ecd0d671c0f1da0e19d7b378c616/blob b/shared/package-files/75/75ef12387b6d39f395efff2d1b7d9f6abbb9ecd0d671c0f1da0e19d7b378c616/blob new file mode 100644 index 0000000000000000000000000000000000000000..2efbbde5e4ec6be67441a54b7f787f6d2aebe7b1 Binary files /dev/null and b/shared/package-files/75/75ef12387b6d39f395efff2d1b7d9f6abbb9ecd0d671c0f1da0e19d7b378c616/blob differ diff --git a/shared/package-files/75/75ef87d8dc6fe952363fc297c808ab292f0801db4960a7ea3e80e7de631a2323/blob b/shared/package-files/75/75ef87d8dc6fe952363fc297c808ab292f0801db4960a7ea3e80e7de631a2323/blob new file mode 100644 index 0000000000000000000000000000000000000000..8f6dbd0dfd9ecd81bdd79c74a19d7299e179389d --- /dev/null +++ b/shared/package-files/75/75ef87d8dc6fe952363fc297c808ab292f0801db4960a7ea3e80e7de631a2323/blob @@ -0,0 +1,8 @@ + +/* this is a hack to generate libsvm with both sparse and dense + methods in the same binary*/ + +#define _DENSE_REP +#include "svm.cpp" +#undef _DENSE_REP +#include "svm.cpp" diff --git a/shared/package-files/75/75f14876a059a20d72be1c920ea592b87fae6536d19264c431641c0205ddbb23/blob b/shared/package-files/75/75f14876a059a20d72be1c920ea592b87fae6536d19264c431641c0205ddbb23/blob new file mode 100644 index 0000000000000000000000000000000000000000..92f7c65644bfd5ed82499b6aac475bed04448cb5 --- /dev/null +++ b/shared/package-files/75/75f14876a059a20d72be1c920ea592b87fae6536d19264c431641c0205ddbb23/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API dense_dim { + using schema = int64_t (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::dense_dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "dense_dim(Tensor self) -> int") + static int64_t call(const at::Tensor & self); + static int64_t redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/75/75f267ab2132a439de8cf4f0635ddff833534836ac3325a6f4be7c09b4905b2b/blob b/shared/package-files/75/75f267ab2132a439de8cf4f0635ddff833534836ac3325a6f4be7c09b4905b2b/blob new file mode 100644 index 0000000000000000000000000000000000000000..4853f006d737d1f5b0207a57ea7920132dd7c660 --- /dev/null +++ b/shared/package-files/75/75f267ab2132a439de8cf4f0635ddff833534836ac3325a6f4be7c09b4905b2b/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor upsample_linear1d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor upsample_linear1d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor & upsample_linear1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor & upsample_linear1d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales, at::Tensor & out); +TORCH_API at::Tensor & upsample_linear1d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales=c10::nullopt); +TORCH_API at::Tensor & upsample_linear1d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/75/75f2dc17939ab43f348cd464e857554bf02977fa74b867c61d5fc204854f17c5/spectral_gate.py b/shared/package-files/75/75f2dc17939ab43f348cd464e857554bf02977fa74b867c61d5fc204854f17c5/spectral_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..8972b008a76c8029baf27bd7756fbe89f7f42874 --- /dev/null +++ b/shared/package-files/75/75f2dc17939ab43f348cd464e857554bf02977fa74b867c61d5fc204854f17c5/spectral_gate.py @@ -0,0 +1,29 @@ +"""Shared candidate-free spectral measurement features; no mass-location change.""" +import numpy as np +from scipy.special import logsumexp +from mass_gate import design,adjusted_log_weights +from precursor_peak import precursor_peak + +def spectral_features(q): + mz=np.asarray(q['mzs'],dtype=np.float64);intensity=np.asarray(q['intensities'],dtype=np.float64) + mask=intensity>0;mz=mz[mask];intensity=intensity[mask] + intensity=intensity/intensity.max();intensity=intensity/intensity.sum() + values=[];names=[] + for d in [2,3,4,5]: + with np.errstate(over='ignore',invalid='ignore'): + rounded=abs(mz-np.round(mz,d))<=5e-9 + values.extend([float(rounded.mean()),float(intensity@rounded)]) + names.extend(['fragment_fraction_rounded_'+str(d),'fragment_intensity_rounded_'+str(d)]) + peak,relative,count=precursor_peak(q,20.,.002) + with np.errstate(over='ignore',divide='ignore',invalid='ignore'): + discrepancy=float(np.minimum(abs(np.float64(peak)-q['precursor_mz'])/q['precursor_mz']*1e6,1000.)) + values.extend([float(count>0),relative,np.log1p(discrepancy),np.log1p(count)]) + names.extend(['precursor_peak_found','precursor_peak_relative_intensity','log_abs_precursor_peak_discrepancy_ppm','log_precursor_peak_count']) + result=np.asarray(values,dtype=np.float64);assert result.shape==(12,) and np.isfinite(result).all() + return result,names + +def spectral_log_weights(features,spectral,priors,parent,state): + base=adjusted_log_weights(features,priors,parent) + if not np.any(state['delta']):return base + logits=base+design(spectral,state['center'],state['scale'])@state['delta'] + return logits-logsumexp(logits,axis=1,keepdims=True) diff --git a/shared/package-files/75/75f4fbf31cc0554e3973852dddb129e155050b21121e04d58fc44145f764d7ba/README.md b/shared/package-files/75/75f4fbf31cc0554e3973852dddb129e155050b21121e04d58fc44145f764d7ba/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e0da5293ed34f681ac4db0b9b54c5130d3ba3a18 --- /dev/null +++ b/shared/package-files/75/75f4fbf31cc0554e3973852dddb129e155050b21121e04d58fc44145f764d7ba/README.md @@ -0,0 +1 @@ +E056: one fixed conditional continuous-score hybrid. Known-energy proton spectra use the task-trained native simulator on the E014 inverse top20, ranked by calibrated inverse score plus native entropy similarity with coefficient1. Other public conditions use E054:75% E047 radius2 candidate score plus25% E043 radius3 score and one frozen training-fitted precursor term. Every runtime asset is bundled. Run infer.sh INPUT_ROOT OUTPUT_ROOT. Validation Hit@1/5/20: 0.5205105769725668/0.67574244685779/0.7864532400020587; MCES@1 8.248340110144628. Verification uses the E041 actual native-branch replay (also the E048 native branch) only after exact runtime and public-input identity checks, independently replays the changed inverse branch, and passes whole-package arbitrary-input, ordering and immutability probes. This is component-based complete validation, not a new full native GPU replay. The conservative sum of measured E041full time and changed inverse branch time is 1635.8140419833362 seconds. The paired Hit@1 delta versusE048 and molecule-group interval are 0.0023675948324669307 [-0.0012326110892261404, 0.006510171372252855]. Validation does not establish test performance. Training sources, configurations, logs and complete experiment records are in research/. diff --git a/shared/package-files/75/75f55b51dab37e573afd512878f440b5cbbcc18ab8ecbf2437f71e928fd6b6c2/blob b/shared/package-files/75/75f55b51dab37e573afd512878f440b5cbbcc18ab8ecbf2437f71e928fd6b6c2/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c370da3fa693bc313ddf97ffb48b696e5d36cd1 --- /dev/null +++ b/shared/package-files/75/75f55b51dab37e573afd512878f440b5cbbcc18ab8ecbf2437f71e928fd6b6c2/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor bitwise_not(const at::Tensor & self); +TORCH_API at::Tensor & bitwise_not_(at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/75/75f5a537c82b8dfa5655c09cc91e6c59b3baee5bbb4b20213bc61892c8305780/infer.py b/shared/package-files/75/75f5a537c82b8dfa5655c09cc91e6c59b3baee5bbb4b20213bc61892c8305780/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..d921a53babd1a427a1dbb5c3d64b3384075545be --- /dev/null +++ b/shared/package-files/75/75f5a537c82b8dfa5655c09cc91e6c59b3baee5bbb4b20213bc61892c8305780/infer.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Run a portable fixed hybrid on arbitrary conforming public input.""" + +import argparse +import csv +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def digest(path): + h = hashlib.sha256() + with path.open('rb') as f: + for block in iter(lambda: f.read(1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('input_root', type=Path) + p.add_argument('output_root', type=Path) + args = p.parse_args() + root = Path(__file__).resolve().parent + config = json.loads((root / 'model_config.json').read_text()) + manifest = json.loads((root / 'model_manifest.json').read_text()) + if digest(root / 'glacier.ckpt') != manifest['checkpoint']['sha256']: + raise ValueError('GLACIER checkpoint checksum mismatch') + fallback_manifest = json.loads((root / 'fallback' / 'model_manifest.json').read_text()) + if digest(root / 'fallback' / fallback_manifest['checkpoint']['path']) != config['fallback_checkpoint_sha256']: + raise ValueError('fallback checkpoint checksum mismatch') + env = dict(os.environ, PYTHONPATH=str(root / 'vendor'), PYTHONDONTWRITEBYTECODE='1', DGLBACKEND='pytorch', OMP_NUM_THREADS='4', OPENBLAS_NUM_THREADS='1', + PATH=str(Path(sys.executable).parent) + os.pathsep + os.environ.get('PATH', '')) + + def run(script, *arguments): + subprocess.run([sys.executable, str(script), *map(str, arguments)], check=True, env=env) + + args.output_root.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix='massspecgym-infer-') as temporary: + tmp = Path(temporary) + run(root / 'stage_input.py', '--input-root', args.input_root, '--output-root', tmp / 'partition') + glacier_input = tmp / 'partition' / 'glacier' + fallback_input = tmp / 'partition' / 'fallback' + (tmp / 'fallback').mkdir() + if (fallback_input / 'queries.jsonl').stat().st_size: + subprocess.run(['bash', str(root / 'fallback' / 'infer.sh'), + str(fallback_input), str(tmp / 'fallback')], check=True, env=env) + else: + (tmp / 'fallback' / 'rankings.jsonl').touch() + candidates = tmp / 'candidates.tsv' + run(root / 'prepare_glacier_candidates.py', '--input-root', glacier_input, + '--output', candidates, '--eligible-only') + with candidates.open() as f: + has_candidates = next(csv.DictReader(f, delimiter='\t'), None) is not None + if has_candidates: + import torch + gpu_flag = ['--gpu'] if torch.cuda.is_available() else [] + run(root / 'vendor' / 'ms_pred' / 'glacier' / 'predict_smis_joint.py', + '--dataset-labels', candidates, '--checkpoint', root / 'glacier.ckpt', + '--save-dir', tmp / 'predictions', '--out-name', 'preds.hdf5', + '--sparse-out', '--sparse-k', 100, '--batch-size', config['batch_size'], + '--num-cpu-workers', config['workers'], '--feat-cache-size', config['feature_cache_size'], + '--prefetch-factor', 1, *gpu_flag) + run(root / 'score_glacier_predictions.py', '--input-root', glacier_input, + '--pred-file', tmp / 'predictions' / 'preds.hdf5', '--output-root', tmp / 'glacier', + '--distance', config['distance']) + else: + (tmp / 'glacier').mkdir() + (tmp / 'glacier' / 'rankings.jsonl').touch() + run(root / 'merge_glacier_fallback.py', '--input-root', args.input_root, + '--glacier-query-id-file', tmp / 'partition' / 'glacier-query-ids.txt', + '--glacier', tmp / 'glacier' / 'rankings.jsonl', + '--fallback', tmp / 'fallback' / 'rankings.jsonl', '--output-root', args.output_root) + # The adapter also prints this diagnostic to stdout. The model output + # directory itself must contain only the contracted rankings file. + (args.output_root / 'runtime.json').unlink() + + +if __name__ == '__main__': + main() diff --git a/shared/package-files/75/75f7db8e25bf5540107bb883f249c54bf29ea54213b7417ac6ec1fedd696c0ac/blob b/shared/package-files/75/75f7db8e25bf5540107bb883f249c54bf29ea54213b7417ac6ec1fedd696c0ac/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ebf4d3ef490afce48e3e1298412edb05a385cdc --- /dev/null +++ b/shared/package-files/75/75f7db8e25bf5540107bb883f249c54bf29ea54213b7417ac6ec1fedd696c0ac/blob @@ -0,0 +1,347 @@ +import pytest + +import networkx as nx +from networkx.generators.classic import empty_graph +from networkx.utils import edges_equal, nodes_equal + + +class TestRelabel: + def test_convert_node_labels_to_integers(self): + # test that empty graph converts fine for all options + G = empty_graph() + H = nx.convert_node_labels_to_integers(G, 100) + assert list(H.nodes()) == [] + assert list(H.edges()) == [] + + for opt in ["default", "sorted", "increasing degree", "decreasing degree"]: + G = empty_graph() + H = nx.convert_node_labels_to_integers(G, 100, ordering=opt) + assert list(H.nodes()) == [] + assert list(H.edges()) == [] + + G = empty_graph() + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) + H = nx.convert_node_labels_to_integers(G) + degH = (d for n, d in H.degree()) + degG = (d for n, d in G.degree()) + assert sorted(degH) == sorted(degG) + + H = nx.convert_node_labels_to_integers(G, 1000) + degH = (d for n, d in H.degree()) + degG = (d for n, d in G.degree()) + assert sorted(degH) == sorted(degG) + assert nodes_equal(H.nodes(), [1000, 1001, 1002, 1003]) + + H = nx.convert_node_labels_to_integers(G, ordering="increasing degree") + degH = (d for n, d in H.degree()) + degG = (d for n, d in G.degree()) + assert sorted(degH) == sorted(degG) + assert H.degree(0) == 1 + assert H.degree(1) == 2 + assert H.degree(2) == 2 + assert H.degree(3) == 3 + + H = nx.convert_node_labels_to_integers(G, ordering="decreasing degree") + degH = (d for n, d in H.degree()) + degG = (d for n, d in G.degree()) + assert sorted(degH) == sorted(degG) + assert H.degree(0) == 3 + assert H.degree(1) == 2 + assert H.degree(2) == 2 + assert H.degree(3) == 1 + + H = nx.convert_node_labels_to_integers( + G, ordering="increasing degree", label_attribute="label" + ) + degH = (d for n, d in H.degree()) + degG = (d for n, d in G.degree()) + assert sorted(degH) == sorted(degG) + assert H.degree(0) == 1 + assert H.degree(1) == 2 + assert H.degree(2) == 2 + assert H.degree(3) == 3 + + # check mapping + assert H.nodes[3]["label"] == "C" + assert H.nodes[0]["label"] == "D" + assert H.nodes[1]["label"] == "A" or H.nodes[2]["label"] == "A" + assert H.nodes[1]["label"] == "B" or H.nodes[2]["label"] == "B" + + def test_convert_to_integers2(self): + G = empty_graph() + G.add_edges_from([("C", "D"), ("A", "B"), ("A", "C"), ("B", "C")]) + H = nx.convert_node_labels_to_integers(G, ordering="sorted") + degH = (d for n, d in H.degree()) + degG = (d for n, d in G.degree()) + assert sorted(degH) == sorted(degG) + + H = nx.convert_node_labels_to_integers( + G, ordering="sorted", label_attribute="label" + ) + assert H.nodes[0]["label"] == "A" + assert H.nodes[1]["label"] == "B" + assert H.nodes[2]["label"] == "C" + assert H.nodes[3]["label"] == "D" + + def test_convert_to_integers_raise(self): + with pytest.raises(nx.NetworkXError): + G = nx.Graph() + H = nx.convert_node_labels_to_integers(G, ordering="increasing age") + + def test_relabel_nodes_copy(self): + G = nx.empty_graph() + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) + mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"} + H = nx.relabel_nodes(G, mapping) + assert nodes_equal(H.nodes(), ["aardvark", "bear", "cat", "dog"]) + + def test_relabel_nodes_function(self): + G = nx.empty_graph() + G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) + # function mapping no longer encouraged but works + + def mapping(n): + return ord(n) + + H = nx.relabel_nodes(G, mapping) + assert nodes_equal(H.nodes(), [65, 66, 67, 68]) + + def test_relabel_nodes_callable_type(self): + G = nx.path_graph(4) + H = nx.relabel_nodes(G, str) + assert nodes_equal(H.nodes, ["0", "1", "2", "3"]) + + @pytest.mark.parametrize("non_mc", ("0123", ["0", "1", "2", "3"])) + def test_relabel_nodes_non_mapping_or_callable(self, non_mc): + """If `mapping` is neither a Callable or a Mapping, an exception + should be raised.""" + G = nx.path_graph(4) + with pytest.raises(AttributeError): + nx.relabel_nodes(G, non_mc) + + def test_relabel_nodes_graph(self): + G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) + mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"} + H = nx.relabel_nodes(G, mapping) + assert nodes_equal(H.nodes(), ["aardvark", "bear", "cat", "dog"]) + + def test_relabel_nodes_orderedgraph(self): + G = nx.Graph() + G.add_nodes_from([1, 2, 3]) + G.add_edges_from([(1, 3), (2, 3)]) + mapping = {1: "a", 2: "b", 3: "c"} + H = nx.relabel_nodes(G, mapping) + assert list(H.nodes) == ["a", "b", "c"] + + def test_relabel_nodes_digraph(self): + G = nx.DiGraph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) + mapping = {"A": "aardvark", "B": "bear", "C": "cat", "D": "dog"} + H = nx.relabel_nodes(G, mapping, copy=False) + assert nodes_equal(H.nodes(), ["aardvark", "bear", "cat", "dog"]) + + def test_relabel_nodes_multigraph(self): + G = nx.MultiGraph([("a", "b"), ("a", "b")]) + mapping = {"a": "aardvark", "b": "bear"} + G = nx.relabel_nodes(G, mapping, copy=False) + assert nodes_equal(G.nodes(), ["aardvark", "bear"]) + assert edges_equal(G.edges(), [("aardvark", "bear"), ("aardvark", "bear")]) + + def test_relabel_nodes_multidigraph(self): + G = nx.MultiDiGraph([("a", "b"), ("a", "b")]) + mapping = {"a": "aardvark", "b": "bear"} + G = nx.relabel_nodes(G, mapping, copy=False) + assert nodes_equal(G.nodes(), ["aardvark", "bear"]) + assert edges_equal(G.edges(), [("aardvark", "bear"), ("aardvark", "bear")]) + + def test_relabel_isolated_nodes_to_same(self): + G = nx.Graph() + G.add_nodes_from(range(4)) + mapping = {1: 1} + H = nx.relabel_nodes(G, mapping, copy=False) + assert nodes_equal(H.nodes(), list(range(4))) + + def test_relabel_nodes_missing(self): + G = nx.Graph([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]) + mapping = {0: "aardvark"} + # copy=True + H = nx.relabel_nodes(G, mapping, copy=True) + assert nodes_equal(H.nodes, G.nodes) + # copy=False + GG = G.copy() + nx.relabel_nodes(G, mapping, copy=False) + assert nodes_equal(G.nodes, GG.nodes) + + def test_relabel_copy_name(self): + G = nx.Graph() + H = nx.relabel_nodes(G, {}, copy=True) + assert H.graph == G.graph + H = nx.relabel_nodes(G, {}, copy=False) + assert H.graph == G.graph + G.name = "first" + H = nx.relabel_nodes(G, {}, copy=True) + assert H.graph == G.graph + H = nx.relabel_nodes(G, {}, copy=False) + assert H.graph == G.graph + + def test_relabel_toposort(self): + K5 = nx.complete_graph(4) + G = nx.complete_graph(4) + G = nx.relabel_nodes(G, {i: i + 1 for i in range(4)}, copy=False) + assert nx.is_isomorphic(K5, G) + G = nx.complete_graph(4) + G = nx.relabel_nodes(G, {i: i - 1 for i in range(4)}, copy=False) + assert nx.is_isomorphic(K5, G) + + def test_relabel_selfloop(self): + G = nx.DiGraph([(1, 1), (1, 2), (2, 3)]) + G = nx.relabel_nodes(G, {1: "One", 2: "Two", 3: "Three"}, copy=False) + assert nodes_equal(G.nodes(), ["One", "Three", "Two"]) + G = nx.MultiDiGraph([(1, 1), (1, 2), (2, 3)]) + G = nx.relabel_nodes(G, {1: "One", 2: "Two", 3: "Three"}, copy=False) + assert nodes_equal(G.nodes(), ["One", "Three", "Two"]) + G = nx.MultiDiGraph([(1, 1)]) + G = nx.relabel_nodes(G, {1: 0}, copy=False) + assert nodes_equal(G.nodes(), [0]) + + def test_relabel_multidigraph_inout_merge_nodes(self): + for MG in (nx.MultiGraph, nx.MultiDiGraph): + for cc in (True, False): + G = MG([(0, 4), (1, 4), (4, 2), (4, 3)]) + G[0][4][0]["value"] = "a" + G[1][4][0]["value"] = "b" + G[4][2][0]["value"] = "c" + G[4][3][0]["value"] = "d" + G.add_edge(0, 4, key="x", value="e") + G.add_edge(4, 3, key="x", value="f") + mapping = {0: 9, 1: 9, 2: 9, 3: 9} + H = nx.relabel_nodes(G, mapping, copy=cc) + # No ordering on keys enforced + assert {"value": "a"} in H[9][4].values() + assert {"value": "b"} in H[9][4].values() + assert {"value": "c"} in H[4][9].values() + assert len(H[4][9]) == 3 if G.is_directed() else 6 + assert {"value": "d"} in H[4][9].values() + assert {"value": "e"} in H[9][4].values() + assert {"value": "f"} in H[4][9].values() + assert len(H[9][4]) == 3 if G.is_directed() else 6 + + def test_relabel_multigraph_merge_inplace(self): + G = nx.MultiGraph([(0, 1), (0, 2), (0, 3), (0, 1), (0, 2), (0, 3)]) + G[0][1][0]["value"] = "a" + G[0][2][0]["value"] = "b" + G[0][3][0]["value"] = "c" + mapping = {1: 4, 2: 4, 3: 4} + nx.relabel_nodes(G, mapping, copy=False) + # No ordering on keys enforced + assert {"value": "a"} in G[0][4].values() + assert {"value": "b"} in G[0][4].values() + assert {"value": "c"} in G[0][4].values() + + def test_relabel_multidigraph_merge_inplace(self): + G = nx.MultiDiGraph([(0, 1), (0, 2), (0, 3)]) + G[0][1][0]["value"] = "a" + G[0][2][0]["value"] = "b" + G[0][3][0]["value"] = "c" + mapping = {1: 4, 2: 4, 3: 4} + nx.relabel_nodes(G, mapping, copy=False) + # No ordering on keys enforced + assert {"value": "a"} in G[0][4].values() + assert {"value": "b"} in G[0][4].values() + assert {"value": "c"} in G[0][4].values() + + def test_relabel_multidigraph_inout_copy(self): + G = nx.MultiDiGraph([(0, 4), (1, 4), (4, 2), (4, 3)]) + G[0][4][0]["value"] = "a" + G[1][4][0]["value"] = "b" + G[4][2][0]["value"] = "c" + G[4][3][0]["value"] = "d" + G.add_edge(0, 4, key="x", value="e") + G.add_edge(4, 3, key="x", value="f") + mapping = {0: 9, 1: 9, 2: 9, 3: 9} + H = nx.relabel_nodes(G, mapping, copy=True) + # No ordering on keys enforced + assert {"value": "a"} in H[9][4].values() + assert {"value": "b"} in H[9][4].values() + assert {"value": "c"} in H[4][9].values() + assert len(H[4][9]) == 3 + assert {"value": "d"} in H[4][9].values() + assert {"value": "e"} in H[9][4].values() + assert {"value": "f"} in H[4][9].values() + assert len(H[9][4]) == 3 + + def test_relabel_multigraph_merge_copy(self): + G = nx.MultiGraph([(0, 1), (0, 2), (0, 3)]) + G[0][1][0]["value"] = "a" + G[0][2][0]["value"] = "b" + G[0][3][0]["value"] = "c" + mapping = {1: 4, 2: 4, 3: 4} + H = nx.relabel_nodes(G, mapping, copy=True) + assert {"value": "a"} in H[0][4].values() + assert {"value": "b"} in H[0][4].values() + assert {"value": "c"} in H[0][4].values() + + def test_relabel_multidigraph_merge_copy(self): + G = nx.MultiDiGraph([(0, 1), (0, 2), (0, 3)]) + G[0][1][0]["value"] = "a" + G[0][2][0]["value"] = "b" + G[0][3][0]["value"] = "c" + mapping = {1: 4, 2: 4, 3: 4} + H = nx.relabel_nodes(G, mapping, copy=True) + assert {"value": "a"} in H[0][4].values() + assert {"value": "b"} in H[0][4].values() + assert {"value": "c"} in H[0][4].values() + + def test_relabel_multigraph_nonnumeric_key(self): + for MG in (nx.MultiGraph, nx.MultiDiGraph): + for cc in (True, False): + G = nx.MultiGraph() + G.add_edge(0, 1, key="I", value="a") + G.add_edge(0, 2, key="II", value="b") + G.add_edge(0, 3, key="II", value="c") + mapping = {1: 4, 2: 4, 3: 4} + nx.relabel_nodes(G, mapping, copy=False) + assert {"value": "a"} in G[0][4].values() + assert {"value": "b"} in G[0][4].values() + assert {"value": "c"} in G[0][4].values() + assert 0 in G[0][4] + assert "I" in G[0][4] + assert "II" in G[0][4] + + def test_relabel_circular(self): + G = nx.path_graph(3) + mapping = {0: 1, 1: 0} + H = nx.relabel_nodes(G, mapping, copy=True) + with pytest.raises(nx.NetworkXUnfeasible): + H = nx.relabel_nodes(G, mapping, copy=False) + + def test_relabel_preserve_node_order_full_mapping_with_copy_true(self): + G = nx.path_graph(3) + original_order = list(G.nodes()) + mapping = {2: "a", 1: "b", 0: "c"} # dictionary keys out of order on purpose + H = nx.relabel_nodes(G, mapping, copy=True) + new_order = list(H.nodes()) + assert [mapping.get(i, i) for i in original_order] == new_order + + def test_relabel_preserve_node_order_full_mapping_with_copy_false(self): + G = nx.path_graph(3) + original_order = list(G) + mapping = {2: "a", 1: "b", 0: "c"} # dictionary keys out of order on purpose + H = nx.relabel_nodes(G, mapping, copy=False) + new_order = list(H) + assert [mapping.get(i, i) for i in original_order] == new_order + + def test_relabel_preserve_node_order_partial_mapping_with_copy_true(self): + G = nx.path_graph(3) + original_order = list(G) + mapping = {1: "a", 0: "b"} # partial mapping and keys out of order on purpose + H = nx.relabel_nodes(G, mapping, copy=True) + new_order = list(H) + assert [mapping.get(i, i) for i in original_order] == new_order + + def test_relabel_preserve_node_order_partial_mapping_with_copy_false(self): + G = nx.path_graph(3) + original_order = list(G) + mapping = {1: "a", 0: "b"} # partial mapping and keys out of order on purpose + H = nx.relabel_nodes(G, mapping, copy=False) + new_order = list(H) + assert [mapping.get(i, i) for i in original_order] != new_order diff --git a/shared/package-files/75/75f83787d7c261d8036c60ede9eceba96e5081f51b547a947092889d66bec845/blob b/shared/package-files/75/75f83787d7c261d8036c60ede9eceba96e5081f51b547a947092889d66bec845/blob new file mode 100644 index 0000000000000000000000000000000000000000..5755b99c7571bc4decbcd8671141dc65fddee1b1 --- /dev/null +++ b/shared/package-files/75/75f83787d7c261d8036c60ede9eceba96e5081f51b547a947092889d66bec845/blob @@ -0,0 +1,18 @@ + +import torch + + +def is_available(): + return hasattr(torch._C, "_faulty_agent_init") + + +if is_available() and not torch._C._faulty_agent_init(): + raise RuntimeError("Failed to initialize torch.distributed.rpc._testing") + +if is_available(): + # Registers FAULTY_TENSORPIPE RPC backend. + from . import faulty_agent_backend_registry + from torch._C._distributed_rpc_testing import ( + FaultyTensorPipeRpcBackendOptions, + FaultyTensorPipeAgent, + ) diff --git a/shared/package-files/75/75f9c2b09cbeb44939fe0ef0bf12aeb0143cd656f75e150627f979909589c6da/blob b/shared/package-files/75/75f9c2b09cbeb44939fe0ef0bf12aeb0143cd656f75e150627f979909589c6da/blob new file mode 100644 index 0000000000000000000000000000000000000000..c63b122714c7990c5e0759b25fb30bbc3eeac715 --- /dev/null +++ b/shared/package-files/75/75f9c2b09cbeb44939fe0ef0bf12aeb0143cd656f75e150627f979909589c6da/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75f9c2b09cbeb44939fe0ef0bf12aeb0143cd656f75e150627f979909589c6da +size 1038160 diff --git a/shared/package-files/76/760324c2569858ed83d50c12a462857d896eab374de93529f9a2205e8f3e5b5a/blob b/shared/package-files/76/760324c2569858ed83d50c12a462857d896eab374de93529f9a2205e8f3e5b5a/blob new file mode 100644 index 0000000000000000000000000000000000000000..e650e30e333030a0784cdebbeeec68b7acac2995 --- /dev/null +++ b/shared/package-files/76/760324c2569858ed83d50c12a462857d896eab374de93529f9a2205e8f3e5b5a/blob @@ -0,0 +1,256 @@ +""" +Several methods to simplify expressions involving unit objects. +""" +from functools import reduce +from collections.abc import Iterable +from typing import Optional + +from sympy import default_sort_key +from sympy.core.add import Add +from sympy.core.containers import Tuple +from sympy.core.mul import Mul +from sympy.core.power import Pow +from sympy.core.sorting import ordered +from sympy.core.sympify import sympify +from sympy.matrices.common import NonInvertibleMatrixError +from sympy.physics.units.dimensions import Dimension, DimensionSystem +from sympy.physics.units.prefixes import Prefix +from sympy.physics.units.quantities import Quantity +from sympy.physics.units.unitsystem import UnitSystem +from sympy.utilities.iterables import sift + + +def _get_conversion_matrix_for_expr(expr, target_units, unit_system): + from sympy.matrices.dense import Matrix + + dimension_system = unit_system.get_dimension_system() + + expr_dim = Dimension(unit_system.get_dimensional_expr(expr)) + dim_dependencies = dimension_system.get_dimensional_dependencies(expr_dim, mark_dimensionless=True) + target_dims = [Dimension(unit_system.get_dimensional_expr(x)) for x in target_units] + canon_dim_units = [i for x in target_dims for i in dimension_system.get_dimensional_dependencies(x, mark_dimensionless=True)] + canon_expr_units = set(dim_dependencies) + + if not canon_expr_units.issubset(set(canon_dim_units)): + return None + + seen = set() + canon_dim_units = [i for i in canon_dim_units if not (i in seen or seen.add(i))] + + camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units]) + exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units]) + + try: + res_exponents = camat.solve(exprmat) + except NonInvertibleMatrixError: + return None + + return res_exponents + + +def convert_to(expr, target_units, unit_system="SI"): + """ + Convert ``expr`` to the same expression with all of its units and quantities + represented as factors of ``target_units``, whenever the dimension is compatible. + + ``target_units`` may be a single unit/quantity, or a collection of + units/quantities. + + Examples + ======== + + >>> from sympy.physics.units import speed_of_light, meter, gram, second, day + >>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant + >>> from sympy.physics.units import kilometer, centimeter + >>> from sympy.physics.units import gravitational_constant, hbar + >>> from sympy.physics.units import convert_to + >>> convert_to(mile, kilometer) + 25146*kilometer/15625 + >>> convert_to(mile, kilometer).n() + 1.609344*kilometer + >>> convert_to(speed_of_light, meter/second) + 299792458*meter/second + >>> convert_to(day, second) + 86400*second + >>> 3*newton + 3*newton + >>> convert_to(3*newton, kilogram*meter/second**2) + 3*kilogram*meter/second**2 + >>> convert_to(atomic_mass_constant, gram) + 1.660539060e-24*gram + + Conversion to multiple units: + + >>> convert_to(speed_of_light, [meter, second]) + 299792458*meter/second + >>> convert_to(3*newton, [centimeter, gram, second]) + 300000*centimeter*gram/second**2 + + Conversion to Planck units: + + >>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n() + 7.62963087839509e-20*hbar**0.5*speed_of_light**0.5/gravitational_constant**0.5 + + """ + from sympy.physics.units import UnitSystem + unit_system = UnitSystem.get_unit_system(unit_system) + + if not isinstance(target_units, (Iterable, Tuple)): + target_units = [target_units] + + if isinstance(expr, Add): + return Add.fromiter(convert_to(i, target_units, unit_system) + for i in expr.args) + + expr = sympify(expr) + target_units = sympify(target_units) + + if not isinstance(expr, Quantity) and expr.has(Quantity): + expr = expr.replace(lambda x: isinstance(x, Quantity), + lambda x: x.convert_to(target_units, unit_system)) + + def get_total_scale_factor(expr): + if isinstance(expr, Mul): + return reduce(lambda x, y: x * y, + [get_total_scale_factor(i) for i in expr.args]) + elif isinstance(expr, Pow): + return get_total_scale_factor(expr.base) ** expr.exp + elif isinstance(expr, Quantity): + return unit_system.get_quantity_scale_factor(expr) + return expr + + depmat = _get_conversion_matrix_for_expr(expr, target_units, unit_system) + if depmat is None: + return expr + + expr_scale_factor = get_total_scale_factor(expr) + return expr_scale_factor * Mul.fromiter( + (1/get_total_scale_factor(u)*u)**p for u, p in + zip(target_units, depmat)) + + +def quantity_simplify(expr, across_dimensions: bool=False, unit_system=None): + """Return an equivalent expression in which prefixes are replaced + with numerical values and all units of a given dimension are the + unified in a canonical manner by default. `across_dimensions` allows + for units of different dimensions to be simplified together. + + `unit_system` must be specified if `across_dimensions` is True. + + Examples + ======== + + >>> from sympy.physics.units.util import quantity_simplify + >>> from sympy.physics.units.prefixes import kilo + >>> from sympy.physics.units import foot, inch, joule, coulomb + >>> quantity_simplify(kilo*foot*inch) + 250*foot**2/3 + >>> quantity_simplify(foot - 6*inch) + foot/2 + >>> quantity_simplify(5*joule/coulomb, across_dimensions=True, unit_system="SI") + 5*volt + """ + + if expr.is_Atom or not expr.has(Prefix, Quantity): + return expr + + # replace all prefixes with numerical values + p = expr.atoms(Prefix) + expr = expr.xreplace({p: p.scale_factor for p in p}) + + # replace all quantities of given dimension with a canonical + # quantity, chosen from those in the expression + d = sift(expr.atoms(Quantity), lambda i: i.dimension) + for k in d: + if len(d[k]) == 1: + continue + v = list(ordered(d[k])) + ref = v[0]/v[0].scale_factor + expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]}) + + if across_dimensions: + # combine quantities of different dimensions into a single + # quantity that is equivalent to the original expression + + if unit_system is None: + raise ValueError("unit_system must be specified if across_dimensions is True") + + unit_system = UnitSystem.get_unit_system(unit_system) + dimension_system: DimensionSystem = unit_system.get_dimension_system() + dim_expr = unit_system.get_dimensional_expr(expr) + dim_deps = dimension_system.get_dimensional_dependencies(dim_expr, mark_dimensionless=True) + + target_dimension: Optional[Dimension] = None + for ds_dim, ds_dim_deps in dimension_system.dimensional_dependencies.items(): + if ds_dim_deps == dim_deps: + target_dimension = ds_dim + break + + if target_dimension is None: + # if we can't find a target dimension, we can't do anything. unsure how to handle this case. + return expr + + target_unit = unit_system.derived_units.get(target_dimension) + if target_unit: + expr = convert_to(expr, target_unit, unit_system) + + return expr + + +def check_dimensions(expr, unit_system="SI"): + """Return expr if units in addends have the same + base dimensions, else raise a ValueError.""" + # the case of adding a number to a dimensional quantity + # is ignored for the sake of SymPy core routines, so this + # function will raise an error now if such an addend is + # found. + # Also, when doing substitutions, multiplicative constants + # might be introduced, so remove those now + + from sympy.physics.units import UnitSystem + unit_system = UnitSystem.get_unit_system(unit_system) + + def addDict(dict1, dict2): + """Merge dictionaries by adding values of common keys and + removing keys with value of 0.""" + dict3 = {**dict1, **dict2} + for key, value in dict3.items(): + if key in dict1 and key in dict2: + dict3[key] = value + dict1[key] + return {key:val for key, val in dict3.items() if val != 0} + + adds = expr.atoms(Add) + DIM_OF = unit_system.get_dimension_system().get_dimensional_dependencies + for a in adds: + deset = set() + for ai in a.args: + if ai.is_number: + deset.add(()) + continue + dims = [] + skip = False + dimdict = {} + for i in Mul.make_args(ai): + if i.has(Quantity): + i = Dimension(unit_system.get_dimensional_expr(i)) + if i.has(Dimension): + dimdict = addDict(dimdict, DIM_OF(i)) + elif i.free_symbols: + skip = True + break + dims.extend(dimdict.items()) + if not skip: + deset.add(tuple(sorted(dims, key=default_sort_key))) + if len(deset) > 1: + raise ValueError( + "addends have incompatible dimensions: {}".format(deset)) + + # clear multiplicative constants on Dimensions which may be + # left after substitution + reps = {} + for m in expr.atoms(Mul): + if any(isinstance(i, Dimension) for i in m.args): + reps[m] = m.func(*[ + i for i in m.args if not i.is_number]) + + return expr.xreplace(reps) diff --git a/shared/package-files/76/7603a693e07b33109591b1dd673b0b669a50eb514002b572e0c71254bf007f3a/blob b/shared/package-files/76/7603a693e07b33109591b1dd673b0b669a50eb514002b572e0c71254bf007f3a/blob new file mode 100644 index 0000000000000000000000000000000000000000..7c3560aa81890d0dc308219d7f0983d3950f9fd5 --- /dev/null +++ b/shared/package-files/76/7603a693e07b33109591b1dd673b0b669a50eb514002b572e0c71254bf007f3a/blob @@ -0,0 +1,92 @@ +"""Unit tests for the :mod:`networkx.generators.sudoku_graph` module.""" + +import pytest + +import networkx as nx + + +def test_sudoku_negative(): + """Raise an error when generating a Sudoku graph of order -1.""" + pytest.raises(nx.NetworkXError, nx.sudoku_graph, n=-1) + + +@pytest.mark.parametrize("n", [0, 1, 2, 3, 4]) +def test_sudoku_generator(n): + """Generate Sudoku graphs of various sizes and verify their properties.""" + G = nx.sudoku_graph(n) + expected_nodes = n**4 + expected_degree = (n - 1) * (3 * n + 1) + expected_edges = expected_nodes * expected_degree // 2 + assert not G.is_directed() + assert not G.is_multigraph() + assert G.number_of_nodes() == expected_nodes + assert G.number_of_edges() == expected_edges + assert all(d == expected_degree for _, d in G.degree) + + if n == 2: + assert sorted(G.neighbors(6)) == [2, 3, 4, 5, 7, 10, 14] + elif n == 3: + assert sorted(G.neighbors(42)) == [ + 6, + 15, + 24, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 43, + 44, + 51, + 52, + 53, + 60, + 69, + 78, + ] + elif n == 4: + assert sorted(G.neighbors(0)) == [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 32, + 33, + 34, + 35, + 48, + 49, + 50, + 51, + 64, + 80, + 96, + 112, + 128, + 144, + 160, + 176, + 192, + 208, + 224, + 240, + ] diff --git a/shared/package-files/76/7603f459d9cea69876f0577a522aa8c832a17eb72dd07e905aa6c27044ec93a3/blob b/shared/package-files/76/7603f459d9cea69876f0577a522aa8c832a17eb72dd07e905aa6c27044ec93a3/blob new file mode 100644 index 0000000000000000000000000000000000000000..870cc4ef2daabf7ac770415f73940b3edfd2477c --- /dev/null +++ b/shared/package-files/76/7603f459d9cea69876f0577a522aa8c832a17eb72dd07e905aa6c27044ec93a3/blob @@ -0,0 +1,54 @@ +""" +============= +Masked Arrays +============= + +Arrays sometimes contain invalid or missing data. When doing operations +on such arrays, we wish to suppress invalid values, which is the purpose masked +arrays fulfill (an example of typical use is given below). + +For example, examine the following array: + +>>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan]) + +When we try to calculate the mean of the data, the result is undetermined: + +>>> np.mean(x) +nan + +The mean is calculated using roughly ``np.sum(x)/len(x)``, but since +any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter +masked arrays: + +>>> m = np.ma.masked_array(x, np.isnan(x)) +>>> m +masked_array(data = [2.0 1.0 3.0 -- 5.0 2.0 3.0 --], + mask = [False False False True False False False True], + fill_value=1e+20) + +Here, we construct a masked array that suppress all ``NaN`` values. We +may now proceed to calculate the mean of the other values: + +>>> np.mean(m) +2.6666666666666665 + +.. [1] Not-a-Number, a floating point value that is the result of an + invalid operation. + +.. moduleauthor:: Pierre Gerard-Marchant +.. moduleauthor:: Jarrod Millman + +""" +from . import core +from .core import * + +from . import extras +from .extras import * + +__all__ = ['core', 'extras'] +__all__ += core.__all__ +__all__ += extras.__all__ + +from numpy._pytesttester import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/shared/package-files/76/7604be0b44015219333e11d42c52116e76c5388101d34e46c8f604fa2f9cb856/blob b/shared/package-files/76/7604be0b44015219333e11d42c52116e76c5388101d34e46c8f604fa2f9cb856/blob new file mode 100644 index 0000000000000000000000000000000000000000..7b67fd7c813ee493b18720d1daf71324d72330b6 --- /dev/null +++ b/shared/package-files/76/7604be0b44015219333e11d42c52116e76c5388101d34e46c8f604fa2f9cb856/blob @@ -0,0 +1,387 @@ +import inspect + +import numpy as np + +from ..utils import get_arrays_tol + + +TINY = np.finfo(float).tiny + + +def cauchy_geometry(const, grad, curv, xl, xu, delta, debug): + r""" + Maximize approximately the absolute value of a quadratic function subject + to bound constraints in a trust region. + + This function solves approximately + + .. math:: + + \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s + + \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad + \left\{ \begin{array}{l} + l \le s \le u,\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + by maximizing the objective function along the constrained Cauchy + direction. + + Parameters + ---------- + const : float + Constant :math:`c` as shown above. + grad : `numpy.ndarray`, shape (n,) + Gradient :math:`g` as shown above. + curv : callable + Curvature of :math:`H` along any vector. + + ``curv(s) -> float`` + + returns :math:`s^{\mathsf{T}} H s`. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Notes + ----- + This function is described as the first alternative in Section 6.5 of [1]_. + It is assumed that the origin is feasible with respect to the bound + constraints and that `delta` is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(const, float) + assert isinstance(grad, np.ndarray) and grad.ndim == 1 + assert inspect.signature(curv).bind(grad) + assert isinstance(xl, np.ndarray) and xl.shape == grad.shape + assert isinstance(xu, np.ndarray) and xu.shape == grad.shape + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + + # To maximize the absolute value of a quadratic function, we maximize the + # function itself or its negative, and we choose the solution that provides + # the largest function value. + step1, q_val1 = _cauchy_geom(const, grad, curv, xl, xu, delta, debug) + step2, q_val2 = _cauchy_geom( + -const, + -grad, + lambda x: -curv(x), + xl, + xu, + delta, + debug, + ) + step = step1 if abs(q_val1) >= abs(q_val2) else step2 + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def spider_geometry(const, grad, curv, xpt, xl, xu, delta, debug): + r""" + Maximize approximately the absolute value of a quadratic function subject + to bound constraints in a trust region. + + This function solves approximately + + .. math:: + + \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s + + \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad + \left\{ \begin{array}{l} + l \le s \le u,\\ + \lVert s \rVert \le \Delta, + \end{array} \right. + + by maximizing the objective function along given straight lines. + + Parameters + ---------- + const : float + Constant :math:`c` as shown above. + grad : `numpy.ndarray`, shape (n,) + Gradient :math:`g` as shown above. + curv : callable + Curvature of :math:`H` along any vector. + + ``curv(s) -> float`` + + returns :math:`s^{\mathsf{T}} H s`. + xpt : `numpy.ndarray`, shape (n, npt) + Points defining the straight lines. The straight lines considered are + the ones passing through the origin and the points in `xpt`. + xl : `numpy.ndarray`, shape (n,) + Lower bounds :math:`l` as shown above. + xu : `numpy.ndarray`, shape (n,) + Upper bounds :math:`u` as shown above. + delta : float + Trust-region radius :math:`\Delta` as shown above. + debug : bool + Whether to make debugging tests during the execution. + + Returns + ------- + `numpy.ndarray`, shape (n,) + Approximate solution :math:`s`. + + Notes + ----- + This function is described as the second alternative in Section 6.5 of + [1]_. It is assumed that the origin is feasible with respect to the bound + constraints and that `delta` is finite and positive. + + References + ---------- + .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods + and Software*. PhD thesis, Department of Applied Mathematics, The Hong + Kong Polytechnic University, Hong Kong, China, 2022. URL: + https://theses.lib.polyu.edu.hk/handle/200/12294. + """ + if debug: + assert isinstance(const, float) + assert isinstance(grad, np.ndarray) and grad.ndim == 1 + assert inspect.signature(curv).bind(grad) + assert ( + isinstance(xpt, np.ndarray) + and xpt.ndim == 2 + and xpt.shape[0] == grad.size + ) + assert isinstance(xl, np.ndarray) and xl.shape == grad.shape + assert isinstance(xu, np.ndarray) and xu.shape == grad.shape + assert isinstance(delta, float) + assert isinstance(debug, bool) + tol = get_arrays_tol(xl, xu) + assert np.all(xl <= tol) + assert np.all(xu >= -tol) + assert np.isfinite(delta) and delta > 0.0 + xl = np.minimum(xl, 0.0) + xu = np.maximum(xu, 0.0) + + # Iterate through the straight lines. + step = np.zeros_like(grad) + q_val = const + s_norm = np.linalg.norm(xpt, axis=0) + + # Set alpha_xl to the step size for the lower-bound constraint and + # alpha_xu to the step size for the upper-bound constraint. + + # xl.shape = (N,) + # xpt.shape = (N, M) + # i_xl_pos.shape = (M, N) + i_xl_pos = (xl > -np.inf) & (xpt.T > -TINY * xl) + i_xl_neg = (xl > -np.inf) & (xpt.T < TINY * xl) + i_xu_pos = (xu < np.inf) & (xpt.T > TINY * xu) + i_xu_neg = (xu < np.inf) & (xpt.T < -TINY * xu) + + # (M, N) + alpha_xl_pos = np.atleast_2d( + np.broadcast_to(xl, i_xl_pos.shape)[i_xl_pos] / xpt.T[i_xl_pos] + ) + # (M,) + alpha_xl_pos = np.max(alpha_xl_pos, axis=1, initial=-np.inf) + # make sure it's (M,) + alpha_xl_pos = np.broadcast_to(np.atleast_1d(alpha_xl_pos), xpt.shape[1]) + + alpha_xl_neg = np.atleast_2d( + np.broadcast_to(xl, i_xl_neg.shape)[i_xl_neg] / xpt.T[i_xl_neg] + ) + alpha_xl_neg = np.max(alpha_xl_neg, axis=1, initial=np.inf) + alpha_xl_neg = np.broadcast_to(np.atleast_1d(alpha_xl_neg), xpt.shape[1]) + + alpha_xu_neg = np.atleast_2d( + np.broadcast_to(xu, i_xu_neg.shape)[i_xu_neg] / xpt.T[i_xu_neg] + ) + alpha_xu_neg = np.max(alpha_xu_neg, axis=1, initial=-np.inf) + alpha_xu_neg = np.broadcast_to(np.atleast_1d(alpha_xu_neg), xpt.shape[1]) + + alpha_xu_pos = np.atleast_2d( + np.broadcast_to(xu, i_xu_pos.shape)[i_xu_pos] / xpt.T[i_xu_pos] + ) + alpha_xu_pos = np.max(alpha_xu_pos, axis=1, initial=np.inf) + alpha_xu_pos = np.broadcast_to(np.atleast_1d(alpha_xu_pos), xpt.shape[1]) + + for k in range(xpt.shape[1]): + # Set alpha_tr to the step size for the trust-region constraint. + if s_norm[k] > TINY * delta: + alpha_tr = max(delta / s_norm[k], 0.0) + else: + # The current straight line is basically zero. + continue + + alpha_bd_pos = max(min(alpha_xu_pos[k], alpha_xl_neg[k]), 0.0) + alpha_bd_neg = min(max(alpha_xl_pos[k], alpha_xu_neg[k]), 0.0) + + # Set alpha_quad_pos and alpha_quad_neg to the step size to the extrema + # of the quadratic function along the positive and negative directions. + grad_step = grad @ xpt[:, k] + curv_step = curv(xpt[:, k]) + if ( + grad_step >= 0.0 + and curv_step < -TINY * grad_step + or grad_step <= 0.0 + and curv_step > -TINY * grad_step + ): + alpha_quad_pos = max(-grad_step / curv_step, 0.0) + else: + alpha_quad_pos = np.inf + if ( + grad_step >= 0.0 + and curv_step > TINY * grad_step + or grad_step <= 0.0 + and curv_step < TINY * grad_step + ): + alpha_quad_neg = min(-grad_step / curv_step, 0.0) + else: + alpha_quad_neg = -np.inf + + # Select the step that provides the largest value of the objective + # function if it improves the current best. The best positive step is + # either the one that reaches the constraints or the one that reaches + # the extremum of the objective function along the current direction + # (only possible if the resulting step is feasible). We test both, and + # we perform similar calculations along the negative step. + # N.B.: we select the largest possible step among all the ones that + # maximize the objective function. This is to avoid returning the zero + # step in some extreme cases. + alpha_pos = min(alpha_tr, alpha_bd_pos) + alpha_neg = max(-alpha_tr, alpha_bd_neg) + q_val_pos = ( + const + alpha_pos * grad_step + 0.5 * alpha_pos**2.0 * curv_step + ) + q_val_neg = ( + const + alpha_neg * grad_step + 0.5 * alpha_neg**2.0 * curv_step + ) + if alpha_quad_pos < alpha_pos: + q_val_quad_pos = ( + const + + alpha_quad_pos * grad_step + + 0.5 * alpha_quad_pos**2.0 * curv_step + ) + if abs(q_val_quad_pos) > abs(q_val_pos): + alpha_pos = alpha_quad_pos + q_val_pos = q_val_quad_pos + if alpha_quad_neg > alpha_neg: + q_val_quad_neg = ( + const + + alpha_quad_neg * grad_step + + 0.5 * alpha_quad_neg**2.0 * curv_step + ) + if abs(q_val_quad_neg) > abs(q_val_neg): + alpha_neg = alpha_quad_neg + q_val_neg = q_val_quad_neg + if abs(q_val_pos) >= abs(q_val_neg) and abs(q_val_pos) > abs(q_val): + step = np.clip(alpha_pos * xpt[:, k], xl, xu) + q_val = q_val_pos + elif abs(q_val_neg) > abs(q_val_pos) and abs(q_val_neg) > abs(q_val): + step = np.clip(alpha_neg * xpt[:, k], xl, xu) + q_val = q_val_neg + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step + + +def _cauchy_geom(const, grad, curv, xl, xu, delta, debug): + """ + Same as `bound_constrained_cauchy_step` without the absolute value. + """ + # Calculate the initial active set. + fixed_xl = (xl < 0.0) & (grad > 0.0) + fixed_xu = (xu > 0.0) & (grad < 0.0) + + # Calculate the Cauchy step. + cauchy_step = np.zeros_like(grad) + cauchy_step[fixed_xl] = xl[fixed_xl] + cauchy_step[fixed_xu] = xu[fixed_xu] + if np.linalg.norm(cauchy_step) > delta: + working = fixed_xl | fixed_xu + while True: + # Calculate the Cauchy step for the directions in the working set. + g_norm = np.linalg.norm(grad[working]) + delta_reduced = np.sqrt( + delta**2.0 - cauchy_step[~working] @ cauchy_step[~working] + ) + if g_norm > TINY * abs(delta_reduced): + mu = max(delta_reduced / g_norm, 0.0) + else: + break + cauchy_step[working] = mu * grad[working] + + # Update the working set. + fixed_xl = working & (cauchy_step < xl) + fixed_xu = working & (cauchy_step > xu) + if not np.any(fixed_xl) and not np.any(fixed_xu): + # Stop the calculations as the Cauchy step is now feasible. + break + cauchy_step[fixed_xl] = xl[fixed_xl] + cauchy_step[fixed_xu] = xu[fixed_xu] + working = working & ~(fixed_xl | fixed_xu) + + # Calculate the step that maximizes the quadratic along the Cauchy step. + grad_step = grad @ cauchy_step + if grad_step >= 0.0: + # Set alpha_tr to the step size for the trust-region constraint. + s_norm = np.linalg.norm(cauchy_step) + if s_norm > TINY * delta: + alpha_tr = max(delta / s_norm, 0.0) + else: + # The Cauchy step is basically zero. + alpha_tr = 0.0 + + # Set alpha_quad to the step size for the maximization problem. + curv_step = curv(cauchy_step) + if curv_step < -TINY * grad_step: + alpha_quad = max(-grad_step / curv_step, 0.0) + else: + alpha_quad = np.inf + + # Set alpha_bd to the step size for the bound constraints. + i_xl = (xl > -np.inf) & (cauchy_step < TINY * xl) + i_xu = (xu < np.inf) & (cauchy_step > TINY * xu) + alpha_xl = np.min(xl[i_xl] / cauchy_step[i_xl], initial=np.inf) + alpha_xu = np.min(xu[i_xu] / cauchy_step[i_xu], initial=np.inf) + alpha_bd = min(alpha_xl, alpha_xu) + + # Calculate the solution and the corresponding function value. + alpha = min(alpha_tr, alpha_quad, alpha_bd) + step = np.clip(alpha * cauchy_step, xl, xu) + q_val = const + alpha * grad_step + 0.5 * alpha**2.0 * curv_step + else: + # This case is never reached in exact arithmetic. It prevents this + # function to return a step that decreases the objective function. + step = np.zeros_like(grad) + q_val = const + + if debug: + assert np.all(xl <= step) + assert np.all(step <= xu) + assert np.linalg.norm(step) < 1.1 * delta + return step, q_val diff --git a/shared/package-files/76/7607ba19a6c2f7dc2600e7bfee6297f85ed1e75d01808f499a9e02f3356ee6d9/blob b/shared/package-files/76/7607ba19a6c2f7dc2600e7bfee6297f85ed1e75d01808f499a9e02f3356ee6d9/blob new file mode 100644 index 0000000000000000000000000000000000000000..5b3edb18f4056177282f1b4c9de020e493010898 Binary files /dev/null and b/shared/package-files/76/7607ba19a6c2f7dc2600e7bfee6297f85ed1e75d01808f499a9e02f3356ee6d9/blob differ diff --git a/shared/package-files/76/76097716bc4aad836d4453bd9f7853868e4a9e64d488f9704925d0019075e1fa/blob b/shared/package-files/76/76097716bc4aad836d4453bd9f7853868e4a9e64d488f9704925d0019075e1fa/blob new file mode 100644 index 0000000000000000000000000000000000000000..6e3354786a22a11b37a7ce7635167f8a298ffba7 --- /dev/null +++ b/shared/package-files/76/76097716bc4aad836d4453bd9f7853868e4a9e64d488f9704925d0019075e1fa/blob @@ -0,0 +1,32 @@ +"""Test installing editor hooks""" +import sys +from unittest import mock + +from IPython import get_ipython +from IPython.lib import editorhooks + +def test_install_editor(): + called = [] + def fake_popen(*args, **kwargs): + called.append({ + 'args': args, + 'kwargs': kwargs, + }) + return mock.MagicMock(**{'wait.return_value': 0}) + editorhooks.install_editor('foo -l {line} -f {filename}', wait=False) + + with mock.patch('subprocess.Popen', fake_popen): + get_ipython().hooks.editor('the file', 64) + + assert len(called) == 1 + args = called[0]["args"] + kwargs = called[0]["kwargs"] + + assert kwargs == {"shell": True} + + if sys.platform.startswith("win"): + expected = ["foo", "-l", "64", "-f", "the file"] + else: + expected = "foo -l 64 -f 'the file'" + cmd = args[0] + assert cmd == expected diff --git a/shared/package-files/76/7609a4dfe109311de4f98b5ca6c9ba20152a93d2c3b2f7b76ed1681801da0d27/blob b/shared/package-files/76/7609a4dfe109311de4f98b5ca6c9ba20152a93d2c3b2f7b76ed1681801da0d27/blob new file mode 100644 index 0000000000000000000000000000000000000000..e65652573b1b30bc755ab1861d4f7de0359bcedc --- /dev/null +++ b/shared/package-files/76/7609a4dfe109311de4f98b5ca6c9ba20152a93d2c3b2f7b76ed1681801da0d27/blob @@ -0,0 +1,21 @@ +from .quantizer import ( + DerivedQuantizationSpec, + EdgeOrNode, + FixedQParamsQuantizationSpec, + QuantizationAnnotation, + QuantizationSpec, + QuantizationSpecBase, + Quantizer, + SharedQuantizationSpec, +) + +__all__ = [ + "EdgeOrNode", + "Quantizer", + "QuantizationSpecBase", + "QuantizationSpec", + "FixedQParamsQuantizationSpec", + "SharedQuantizationSpec", + "DerivedQuantizationSpec", + "QuantizationAnnotation", +] diff --git a/shared/package-files/76/760a8760ebf8d98d8b4c3d56610c3747cf98fb6132d08478769f00e4b2ca72ae/blob b/shared/package-files/76/760a8760ebf8d98d8b4c3d56610c3747cf98fb6132d08478769f00e4b2ca72ae/blob new file mode 100644 index 0000000000000000000000000000000000000000..dd459726917fe3423ea448b3c61a7feaeecdeefe --- /dev/null +++ b/shared/package-files/76/760a8760ebf8d98d8b4c3d56610c3747cf98fb6132d08478769f00e4b2ca72ae/blob @@ -0,0 +1,121 @@ +from .core import unify, reify # type: ignore[attr-defined] +from .variable import isvar +from .utils import _toposort, freeze +from .unification_tools import groupby, first # type: ignore[import] + + +class Dispatcher: + def __init__(self, name): + self.name = name + self.funcs = {} + self.ordering = [] + + def add(self, signature, func): + self.funcs[freeze(signature)] = func + self.ordering = ordering(self.funcs) + + def __call__(self, *args, **kwargs): + func, s = self.resolve(args) + return func(*args, **kwargs) + + def resolve(self, args): + n = len(args) + for signature in self.ordering: + if len(signature) != n: + continue + s = unify(freeze(args), signature) + if s is not False: + result = self.funcs[signature] + return result, s + raise NotImplementedError("No match found. \nKnown matches: " + + str(self.ordering) + "\nInput: " + str(args)) + + def register(self, *signature): + def _(func): + self.add(signature, func) + return self + return _ + + +class VarDispatcher(Dispatcher): + """ A dispatcher that calls functions with variable names + >>> # xdoctest: +SKIP + >>> d = VarDispatcher('d') + >>> x = var('x') + >>> @d.register('inc', x) + ... def f(x): + ... return x + 1 + >>> @d.register('double', x) + ... def f(x): + ... return x * 2 + >>> d('inc', 10) + 11 + >>> d('double', 10) + 20 + """ + def __call__(self, *args, **kwargs): + func, s = self.resolve(args) + d = {k.token: v for k, v in s.items()} + return func(**d) + + +global_namespace = {} # type: ignore[var-annotated] + + +def match(*signature, **kwargs): + namespace = kwargs.get('namespace', global_namespace) + dispatcher = kwargs.get('Dispatcher', Dispatcher) + + def _(func): + name = func.__name__ + + if name not in namespace: + namespace[name] = dispatcher(name) + d = namespace[name] + + d.add(signature, func) + + return d + return _ + + +def supercedes(a, b): + """ ``a`` is a more specific match than ``b`` """ + if isvar(b) and not isvar(a): + return True + s = unify(a, b) + if s is False: + return False + s = {k: v for k, v in s.items() if not isvar(k) or not isvar(v)} + if reify(a, s) == a: + return True + if reify(b, s) == b: + return False + + +# Taken from multipledispatch +def edge(a, b, tie_breaker=hash): + """ A should be checked before B + Tie broken by tie_breaker, defaults to ``hash`` + """ + if supercedes(a, b): + if supercedes(b, a): + return tie_breaker(a) > tie_breaker(b) + else: + return True + return False + + +# Taken from multipledispatch +def ordering(signatures): + """ A sane ordering of signatures to check, first to last + Topological sort of edges as given by ``edge`` and ``supercedes`` + """ + signatures = list(map(tuple, signatures)) + edges = [(a, b) for a in signatures for b in signatures if edge(a, b)] + edges = groupby(first, edges) + for s in signatures: + if s not in edges: + edges[s] = [] + edges = {k: [b for a, b in v] for k, v in edges.items()} # type: ignore[attr-defined, assignment] + return _toposort(edges) diff --git a/shared/package-files/76/760fb513900461c0c075c7a1bc194b4ffdc04e8f78bdf4b67fc199c01678e9da/blob b/shared/package-files/76/760fb513900461c0c075c7a1bc194b4ffdc04e8f78bdf4b67fc199c01678e9da/blob new file mode 100644 index 0000000000000000000000000000000000000000..5712b119bf0c3999c052dcc8095182402d5e1f3e --- /dev/null +++ b/shared/package-files/76/760fb513900461c0c075c7a1bc194b4ffdc04e8f78bdf4b67fc199c01678e9da/blob @@ -0,0 +1,32 @@ +from collections import namedtuple +from logging import Logger +from typing import Any, Callable, Mapping, Optional, Sequence, Set + +from .utilities import BadRequest as BadRequest + +PROXY_HEADERS: frozenset + +Forwarded = namedtuple("Forwarded", ["by", "for_", "host", "proto"]) + +class MalformedProxyHeader(Exception): + header: str = ... + reason: str = ... + value: str = ... + def __init__(self, header: str, reason: str, value: str) -> None: ... + +def proxy_headers_middleware( + app: Any, + trusted_proxy: Optional[str] = ..., + trusted_proxy_count: int = ..., + trusted_proxy_headers: Optional[Set[str]] = ..., + clear_untrusted: bool = ..., + log_untrusted: bool = ..., + logger: Logger = ..., +) -> Callable[..., Any]: ... +def parse_proxy_headers( + environ: Mapping[str, str], trusted_proxy_count: int, trusted_proxy_headers: Set[str], logger: Logger = ... +) -> Set[str]: ... +def strip_brackets(addr: str) -> str: ... +def clear_untrusted_headers( + environ: Mapping[str, str], untrusted_headers: Sequence[str], log_warning: bool = ..., logger: Logger = ... +) -> None: ... diff --git a/shared/package-files/76/7610d270e5f3f1cf2294743cbfb2cd577eba5aba69647a04ee27f4a049a30bc7/blob b/shared/package-files/76/7610d270e5f3f1cf2294743cbfb2cd577eba5aba69647a04ee27f4a049a30bc7/blob new file mode 100644 index 0000000000000000000000000000000000000000..6460e2f947d10d456354723073542466db00fde1 --- /dev/null +++ b/shared/package-files/76/7610d270e5f3f1cf2294743cbfb2cd577eba5aba69647a04ee27f4a049a30bc7/blob @@ -0,0 +1,316 @@ +r"""Contains definitions of the methods used by the _BaseDataLoaderIter workers. + +These methods are used to collate samples fetched from dataset into Tensor(s). +These **needs** to be in global scope since Py2 doesn't support serializing +static methods. + +`default_collate` and `default_convert` are exposed to users via 'dataloader.py'. +""" + +import collections +import contextlib +import copy +import re +import torch + +from typing import Callable, Dict, Optional, Tuple, Type, Union + +np_str_obj_array_pattern = re.compile(r'[SaUO]') + + +def default_convert(data): + r""" + Convert each NumPy array element into a :class:`torch.Tensor`. + + If the input is a `Sequence`, `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`. + If the input is not an NumPy array, it is left unchanged. + This is used as the default function for collation when both `batch_sampler` and `batch_size` + are NOT defined in :class:`~torch.utils.data.DataLoader`. + + The general input type to output type mapping is similar to that + of :func:`~torch.utils.data.default_collate`. See the description there for more details. + + Args: + data: a single data point to be converted + + Examples: + >>> # xdoctest: +SKIP + >>> # Example with `int` + >>> default_convert(0) + 0 + >>> # Example with NumPy array + >>> default_convert(np.array([0, 1])) + tensor([0, 1]) + >>> # Example with NamedTuple + >>> Point = namedtuple('Point', ['x', 'y']) + >>> default_convert(Point(0, 0)) + Point(x=0, y=0) + >>> default_convert(Point(np.array(0), np.array(0))) + Point(x=tensor(0), y=tensor(0)) + >>> # Example with List + >>> default_convert([np.array([0, 1]), np.array([2, 3])]) + [tensor([0, 1]), tensor([2, 3])] + """ + elem_type = type(data) + if isinstance(data, torch.Tensor): + return data + elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \ + and elem_type.__name__ != 'string_': + # array of string classes and object + if elem_type.__name__ == 'ndarray' \ + and np_str_obj_array_pattern.search(data.dtype.str) is not None: + return data + return torch.as_tensor(data) + elif isinstance(data, collections.abc.Mapping): + try: + if isinstance(data, collections.abc.MutableMapping): + # The mapping type may have extra properties, so we can't just + # use `type(data)(...)` to create the new mapping. + # Create a clone and update it if the mapping type is mutable. + clone = copy.copy(data) + clone.update({key: default_convert(data[key]) for key in data}) + return clone + else: + return elem_type({key: default_convert(data[key]) for key in data}) + except TypeError: + # The mapping type may not support `copy()` / `update(mapping)` + # or `__init__(iterable)`. + return {key: default_convert(data[key]) for key in data} + elif isinstance(data, tuple) and hasattr(data, '_fields'): # namedtuple + return elem_type(*(default_convert(d) for d in data)) + elif isinstance(data, tuple): + return [default_convert(d) for d in data] # Backwards compatibility. + elif isinstance(data, collections.abc.Sequence) and not isinstance(data, (str, bytes)): + try: + if isinstance(data, collections.abc.MutableSequence): + # The sequence type may have extra properties, so we can't just + # use `type(data)(...)` to create the new sequence. + # Create a clone and update it if the sequence type is mutable. + clone = copy.copy(data) # type: ignore[arg-type] + for i, d in enumerate(data): + clone[i] = default_convert(d) + return clone + else: + return elem_type([default_convert(d) for d in data]) + except TypeError: + # The sequence type may not support `copy()` / `__setitem__(index, item)` + # or `__init__(iterable)` (e.g., `range`). + return [default_convert(d) for d in data] + else: + return data + + +default_collate_err_msg_format = ( + "default_collate: batch must contain tensors, numpy arrays, numbers, " + "dicts or lists; found {}") + + +def collate(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + r""" + General collate function that handles collection type of element within each batch. + + The function also opens function registry to deal with specific element types. `default_collate_fn_map` + provides default collate functions for tensors, numpy arrays, numbers and strings. + + Args: + batch: a single batch to be collated + collate_fn_map: Optional dictionary mapping from element type to the corresponding collate function. + If the element type isn't present in this dictionary, + this function will go through each key of the dictionary in the insertion order to + invoke the corresponding collate function if the element type is a subclass of the key. + + Examples: + >>> def collate_tensor_fn(batch, *, collate_fn_map): + >>> # Extend this function to handle batch of tensors + ... return torch.stack(batch, 0) + >>> def custom_collate(batch): + ... collate_map = {torch.Tensor: collate_tensor_fn} + ... return collate(batch, collate_fn_map=collate_map) + >>> # Extend `default_collate` by in-place modifying `default_collate_fn_map` + >>> default_collate_fn_map.update({torch.Tensor: collate_tensor_fn}) + + Note: + Each collate function requires a positional argument for batch and a keyword argument + for the dictionary of collate functions as `collate_fn_map`. + """ + elem = batch[0] + elem_type = type(elem) + + if collate_fn_map is not None: + if elem_type in collate_fn_map: + return collate_fn_map[elem_type](batch, collate_fn_map=collate_fn_map) + + for collate_type in collate_fn_map: + if isinstance(elem, collate_type): + return collate_fn_map[collate_type](batch, collate_fn_map=collate_fn_map) + + if isinstance(elem, collections.abc.Mapping): + try: + if isinstance(elem, collections.abc.MutableMapping): + # The mapping type may have extra properties, so we can't just + # use `type(data)(...)` to create the new mapping. + # Create a clone and update it if the mapping type is mutable. + clone = copy.copy(elem) + clone.update({key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map) for key in elem}) + return clone + else: + return elem_type({key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map) for key in elem}) + except TypeError: + # The mapping type may not support `copy()` / `update(mapping)` + # or `__init__(iterable)`. + return {key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map) for key in elem} + elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple + return elem_type(*(collate(samples, collate_fn_map=collate_fn_map) for samples in zip(*batch))) + elif isinstance(elem, collections.abc.Sequence): + # check to make sure that the elements in batch have consistent size + it = iter(batch) + elem_size = len(next(it)) + if not all(len(elem) == elem_size for elem in it): + raise RuntimeError('each element in list of batch should be of equal size') + transposed = list(zip(*batch)) # It may be accessed twice, so we use a list. + + if isinstance(elem, tuple): + return [collate(samples, collate_fn_map=collate_fn_map) for samples in transposed] # Backwards compatibility. + else: + try: + if isinstance(elem, collections.abc.MutableSequence): + # The sequence type may have extra properties, so we can't just + # use `type(data)(...)` to create the new sequence. + # Create a clone and update it if the sequence type is mutable. + clone = copy.copy(elem) # type: ignore[arg-type] + for i, samples in enumerate(transposed): + clone[i] = collate(samples, collate_fn_map=collate_fn_map) + return clone + else: + return elem_type([collate(samples, collate_fn_map=collate_fn_map) for samples in transposed]) + except TypeError: + # The sequence type may not support `copy()` / `__setitem__(index, item)` + # or `__init__(iterable)` (e.g., `range`). + return [collate(samples, collate_fn_map=collate_fn_map) for samples in transposed] + + raise TypeError(default_collate_err_msg_format.format(elem_type)) + + +def collate_tensor_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + elem = batch[0] + out = None + if elem.is_nested: + raise RuntimeError( + "Batches of nested tensors are not currently supported by the default collate_fn; " + "please provide a custom collate_fn to handle them appropriately." + ) + if elem.layout in {torch.sparse_coo, torch.sparse_csr, torch.sparse_bsr, torch.sparse_csc, torch.sparse_bsc}: + raise RuntimeError( + "Batches of sparse tensors are not currently supported by the default collate_fn; " + "please provide a custom collate_fn to handle them appropriately." + ) + if torch.utils.data.get_worker_info() is not None: + # If we're in a background process, concatenate directly into a + # shared memory tensor to avoid an extra copy + numel = sum(x.numel() for x in batch) + storage = elem._typed_storage()._new_shared(numel, device=elem.device) + out = elem.new(storage).resize_(len(batch), *list(elem.size())) + return torch.stack(batch, 0, out=out) + + +def collate_numpy_array_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + elem = batch[0] + # array of string classes and object + if np_str_obj_array_pattern.search(elem.dtype.str) is not None: + raise TypeError(default_collate_err_msg_format.format(elem.dtype)) + + return collate([torch.as_tensor(b) for b in batch], collate_fn_map=collate_fn_map) + + +def collate_numpy_scalar_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + return torch.as_tensor(batch) + + +def collate_float_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + return torch.tensor(batch, dtype=torch.float64) + + +def collate_int_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + return torch.tensor(batch) + + +def collate_str_fn(batch, *, collate_fn_map: Optional[Dict[Union[Type, Tuple[Type, ...]], Callable]] = None): + return batch + + +default_collate_fn_map: Dict[Union[Type, Tuple[Type, ...]], Callable] = {torch.Tensor: collate_tensor_fn} +with contextlib.suppress(ImportError): + import numpy as np + # For both ndarray and memmap (subclass of ndarray) + default_collate_fn_map[np.ndarray] = collate_numpy_array_fn + # See scalars hierarchy: https://numpy.org/doc/stable/reference/arrays.scalars.html + # Skip string scalars + default_collate_fn_map[(np.bool_, np.number, np.object_)] = collate_numpy_scalar_fn +default_collate_fn_map[float] = collate_float_fn +default_collate_fn_map[int] = collate_int_fn +default_collate_fn_map[str] = collate_str_fn +default_collate_fn_map[bytes] = collate_str_fn + + +def default_collate(batch): + r""" + Take in a batch of data and put the elements within the batch into a tensor with an additional outer dimension - batch size. + + The exact output type can be a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a + Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type. + This is used as the default function for collation when + `batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`. + + Here is the general input type (based on the type of the element within the batch) to output type mapping: + + * :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size) + * NumPy Arrays -> :class:`torch.Tensor` + * `float` -> :class:`torch.Tensor` + * `int` -> :class:`torch.Tensor` + * `str` -> `str` (unchanged) + * `bytes` -> `bytes` (unchanged) + * `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]` + * `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]), + default_collate([V2_1, V2_2, ...]), ...]` + * `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]), + default_collate([V2_1, V2_2, ...]), ...]` + + Args: + batch: a single batch to be collated + + Examples: + >>> # xdoctest: +SKIP + >>> # Example with a batch of `int`s: + >>> default_collate([0, 1, 2, 3]) + tensor([0, 1, 2, 3]) + >>> # Example with a batch of `str`s: + >>> default_collate(['a', 'b', 'c']) + ['a', 'b', 'c'] + >>> # Example with `Map` inside the batch: + >>> default_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}]) + {'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])} + >>> # Example with `NamedTuple` inside the batch: + >>> Point = namedtuple('Point', ['x', 'y']) + >>> default_collate([Point(0, 0), Point(1, 1)]) + Point(x=tensor([0, 1]), y=tensor([0, 1])) + >>> # Example with `Tuple` inside the batch: + >>> default_collate([(0, 1), (2, 3)]) + [tensor([0, 2]), tensor([1, 3])] + >>> # Example with `List` inside the batch: + >>> default_collate([[0, 1], [2, 3]]) + [tensor([0, 2]), tensor([1, 3])] + >>> # Two options to extend `default_collate` to handle specific type + >>> # Option 1: Write custom collate function and invoke `default_collate` + >>> def custom_collate(batch): + ... elem = batch[0] + ... if isinstance(elem, CustomType): # Some custom condition + ... return ... + ... else: # Fall back to `default_collate` + ... return default_collate(batch) + >>> # Option 2: In-place modify `default_collate_fn_map` + >>> def collate_customtype_fn(batch, *, collate_fn_map=None): + ... return ... + >>> default_collate_fn_map.update(CustoType, collate_customtype_fn) + >>> default_collate(batch) # Handle `CustomType` automatically + """ + return collate(batch, collate_fn_map=default_collate_fn_map) diff --git a/shared/package-files/76/76113f8d85e27e7b2b18af58ff56118caca9e66941e507145dfd67404752656c/blob b/shared/package-files/76/76113f8d85e27e7b2b18af58ff56118caca9e66941e507145dfd67404752656c/blob new file mode 100644 index 0000000000000000000000000000000000000000..e4d9177e7ed97fad9f2b9f906a0ca1e482f01f27 --- /dev/null +++ b/shared/package-files/76/76113f8d85e27e7b2b18af58ff56118caca9e66941e507145dfd67404752656c/blob @@ -0,0 +1,13 @@ +prefix=/opt/conda +exec_prefix=${prefix} +includedir=${prefix}/include +libdir=${exec_prefix}/lib + +Name: reproc++ +Description: Cross-platform C99/C++11 process library +URL: https://github.com/DaanDeMeyer/reproc +Version: 14.2.4 +Cflags: -I${includedir} +Libs: -L${libdir} -lreproc++ +Libs.private: -pthread +Requires.private: reproc = 14.2.4 diff --git a/shared/package-files/76/7613b91f8a8a796248a8a6e6b89037d72e89738fc4d3bff4b990b3d94b7b11a8/blob b/shared/package-files/76/7613b91f8a8a796248a8a6e6b89037d72e89738fc4d3bff4b990b3d94b7b11a8/blob new file mode 100644 index 0000000000000000000000000000000000000000..53cf965c2e48af87b4542b9414e4e3767ed85e92 --- /dev/null +++ b/shared/package-files/76/7613b91f8a8a796248a8a6e6b89037d72e89738fc4d3bff4b990b3d94b7b11a8/blob @@ -0,0 +1,38 @@ +from . import functional +from .modules import * # noqa: F403 +from .modules import MaxPool2d + +__all__ = [ + 'BatchNorm2d', + 'BatchNorm3d', + 'Conv1d', + 'Conv2d', + 'Conv3d', + 'ConvTranspose1d', + 'ConvTranspose2d', + 'ConvTranspose3d', + 'DeQuantize', + 'ELU', + 'Embedding', + 'EmbeddingBag', + 'GroupNorm', + 'Hardswish', + 'InstanceNorm1d', + 'InstanceNorm2d', + 'InstanceNorm3d', + 'LayerNorm', + 'LeakyReLU', + 'Linear', + 'LSTM', + 'MultiheadAttention', + 'Quantize', + 'ReLU6', + 'Sigmoid', + 'Softmax', + 'Dropout', + 'PReLU', + # Wrapper modules + 'FloatFunctional', + 'FXFloatFunctional', + 'QFunctional', +] diff --git a/shared/package-files/76/76185d674bdeb95f19260a1bf3b445d9bafc2b2c8a43bfe11efde128dc369eb2/blob b/shared/package-files/76/76185d674bdeb95f19260a1bf3b445d9bafc2b2c8a43bfe11efde128dc369eb2/blob new file mode 100644 index 0000000000000000000000000000000000000000..d2958f75befdb414a595f9d9971228e13d9f371e --- /dev/null +++ b/shared/package-files/76/76185d674bdeb95f19260a1bf3b445d9bafc2b2c8a43bfe11efde128dc369eb2/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor amax(const at::Tensor & self, at::IntArrayRef dim={}, bool keepdim=false); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/76/761cd6c616cdc2c393f6106b3a51bfc73b7b2e89d62292b2fe5e1c864e45c77c/blob b/shared/package-files/76/761cd6c616cdc2c393f6106b3a51bfc73b7b2e89d62292b2fe5e1c864e45c77c/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c1f52f47022ed4c2e77611e06d42b9b2d84df41 --- /dev/null +++ b/shared/package-files/76/761cd6c616cdc2c393f6106b3a51bfc73b7b2e89d62292b2fe5e1c864e45c77c/blob @@ -0,0 +1,212 @@ +import functools + +import torch +from torch._inductor.compile_fx import fake_tensor_prop +from ..._dynamo.utils import counters + +from .. import config +from ..pattern_matcher import ( + _return_true, + CallFunction, + fwd_only, + Ignored, + init_once_fakemode, + KeywordArg, + Match, + PatternMatcherPass, + register_graph_pattern, + register_replacement, + stable_topological_sort, +) + +aten = torch.ops.aten + +# First pass_patterns[0] are applied, then [1], then [2] +pass_patterns = [ + PatternMatcherPass(), + PatternMatcherPass(), + PatternMatcherPass(), +] + +binary_folding_pass = PatternMatcherPass() + + +def freezing_passes(gm: torch.fx.GraphModule, aot_example_inputs): + """ + Passes that are applied to the graph to freeze pass. + """ + + from ..freezing import constant_fold + + lazy_init() + # We need a few rounds of binary folding to get rid of all the + # unnecessary nodes, but may need a good method to chose the rounds number. + # works like: conv+binary+binary. + binary_folding = counters["inductor"]["binary_folding"] + fake_tensor_prop(gm, aot_example_inputs, True) + + torch._inductor.fx_passes.binary_folding.mark_mixed_dtype_allowed_convs(gm) + for _ in range(4): + constant_fold(gm) + # Make sure meta['val'] is properly set for all nodes + fake_tensor_prop(gm, aot_example_inputs, True) + binary_folding_pass.apply(gm.graph) # type: ignore[arg-type] + # If we don't have binary folding, we don't need to run the pass again. + # TODO: remove the need to run fake_tensor_prop on the whole model. + if counters["inductor"]["binary_folding"] == binary_folding: + break + binary_folding = counters["inductor"]["binary_folding"] + + torch._inductor.fx_passes.binary_folding.recover_original_precision_folded_convs(gm) + + constant_fold(gm) + fake_tensor_prop(gm, aot_example_inputs, True) + + for pattern in pass_patterns: + pattern.apply(gm.graph) # type: ignore[arg-type] + + # The CPU weight packing always assume the conv's weight is channels last, + # So make sure the layout_optimization is on when doing it. + if ( + torch._C._has_mkldnn + and config.cpp.weight_prepack + and config.layout_optimization + ): + from .mkldnn_fusion import _eliminate_duplicate_packed_nodes + + _eliminate_duplicate_packed_nodes(gm) + + stable_topological_sort(gm.graph) + gm.recompile() + gm.graph.lint() + + +@init_once_fakemode +def lazy_init(): + if torch._C._has_mkldnn and config.cpp.weight_prepack: + from .mkldnn_fusion import _mkldnn_weight_pack_init + + _mkldnn_weight_pack_init() + + from .binary_folding import binary_folding_init + + addmm_patterns_init() + binary_folding_init() + + +def register_freezing_graph_pattern(pattern, extra_check=_return_true, pass_number=0): + return register_graph_pattern( + pattern, + extra_check=extra_check, + pass_dict=pass_patterns[pass_number], + ) + + +def register_binary_folding_pattern(pattern, extra_check=_return_true): + return register_graph_pattern( + pattern, + extra_check=extra_check, + pass_dict=binary_folding_pass, + ) + + +@functools.lru_cache(None) +def addmm_patterns_init(): + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + else: + device = "cpu" + val = functools.partial(torch.empty, (10, 10), device=device, requires_grad=False) + + def check_concat_weights(match): + weights = [ + match.kwargs["w1"], + match.kwargs["w2"], + ] + if "w3" in match.kwargs: + weights.append(match.kwargs["w3"]) + + return all( + w.op == "get_attr" and w.meta["val"].shape == weights[0].meta["val"].shape + for w in weights + ) + + def matmul_fuse_pattern(inp, w1, w2, w3): + return (inp @ w1, inp @ w2, inp @ w3) + + def matmul_replacement(inp, w1, w2, w3): + cat_t = torch.cat((w1, w2, w3), dim=1) + mm = inp @ cat_t + return mm.chunk(3, dim=1) + + register_replacement( + matmul_fuse_pattern, + matmul_replacement, + [val(), val(), val(), val()], + fwd_only, + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2", "w3"), + ) + + def matmul_fuse_pattern_two(inp, w1, w2): + return (inp @ w1, inp @ w2) + + def matmul_replacement_two(inp, w1, w2): + cat_t = torch.cat((w1, w2), dim=1) + mm = inp @ cat_t + return mm.chunk(2, dim=1) + + register_replacement( + matmul_fuse_pattern_two, + matmul_replacement_two, + [val(), val(), val()], + fwd_only, + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2"), + ) + + def addmm_fuse_pattern_second(inp, w1, w2, w3, b1, b2, b3): + return ( + aten.addmm(b1, inp, w1), + aten.addmm(b2, inp, w2), + aten.addmm(b3, inp, w3), + ) + + def addmm_fuse_replacement_second(inp, w1, w2, w3, b1, b2, b3): + cat_w = torch.cat((w1, w2, w3), dim=1) + cat_b = torch.cat((b1, b2, b3)) + return aten.addmm(cat_b, inp, cat_w).chunk(3, dim=1) + + register_replacement( + addmm_fuse_pattern_second, + addmm_fuse_replacement_second, + [val() for _ in range(7)], + fwd_only, + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2", "w3", "b1", "b2", "b3"), + ) + + +def same_dtype(match): + return match.output_node().args[0].meta["val"].dtype == match.kwargs["dtype"] + + +@register_graph_pattern( + CallFunction( + torch.ops.prims.convert_element_type.default, + Ignored(), + KeywordArg("dtype"), + ), + pass_dict=pass_patterns[0], + extra_check=same_dtype, +) +def unnecessary_dtype_convert(match: Match, **kwargs): + """Remove unnecessary dtype conversion op, probably left as a result of Conv-Bn folding""" + graph = match.graph + node = match.output_node() + node.replace_all_uses_with(node.args[0]) + graph.erase_node(node) diff --git a/shared/package-files/76/7620ce9122a3fe3d31634f243fbf8da10b1e7f1260b0de5c9448aba9795abc66/blob b/shared/package-files/76/7620ce9122a3fe3d31634f243fbf8da10b1e7f1260b0de5c9448aba9795abc66/blob new file mode 100644 index 0000000000000000000000000000000000000000..37a5368b0b82180d00c5835f0a30e5456020137c --- /dev/null +++ b/shared/package-files/76/7620ce9122a3fe3d31634f243fbf8da10b1e7f1260b0de5c9448aba9795abc66/blob @@ -0,0 +1,2668 @@ +"""Provides the `CCompilerOpt` class, used for handling the CPU/hardware +optimization, starting from parsing the command arguments, to managing the +relation between the CPU baseline and dispatch-able features, +also generating the required C headers and ending with compiling +the sources with proper compiler's flags. + +`CCompilerOpt` doesn't provide runtime detection for the CPU features, +instead only focuses on the compiler side, but it creates abstract C headers +that can be used later for the final runtime dispatching process.""" + +import atexit +import inspect +import os +import pprint +import re +import subprocess +import textwrap + +class _Config: + """An abstract class holds all configurable attributes of `CCompilerOpt`, + these class attributes can be used to change the default behavior + of `CCompilerOpt` in order to fit other requirements. + + Attributes + ---------- + conf_nocache : bool + Set True to disable memory and file cache. + Default is False. + + conf_noopt : bool + Set True to forces the optimization to be disabled, + in this case `CCompilerOpt` tends to generate all + expected headers in order to 'not' break the build. + Default is False. + + conf_cache_factors : list + Add extra factors to the primary caching factors. The caching factors + are utilized to determine if there are changes had happened that + requires to discard the cache and re-updating it. The primary factors + are the arguments of `CCompilerOpt` and `CCompiler`'s properties(type, flags, etc). + Default is list of two items, containing the time of last modification + of `ccompiler_opt` and value of attribute "conf_noopt" + + conf_tmp_path : str, + The path of temporary directory. Default is auto-created + temporary directory via ``tempfile.mkdtemp()``. + + conf_check_path : str + The path of testing files. Each added CPU feature must have a + **C** source file contains at least one intrinsic or instruction that + related to this feature, so it can be tested against the compiler. + Default is ``./distutils/checks``. + + conf_target_groups : dict + Extra tokens that can be reached from dispatch-able sources through + the special mark ``@targets``. Default is an empty dictionary. + + **Notes**: + - case-insensitive for tokens and group names + - sign '#' must stick in the begin of group name and only within ``@targets`` + + **Example**: + .. code-block:: console + + $ "@targets #avx_group other_tokens" > group_inside.c + + >>> CCompilerOpt.conf_target_groups["avx_group"] = \\ + "$werror $maxopt avx2 avx512f avx512_skx" + >>> cco = CCompilerOpt(cc_instance) + >>> cco.try_dispatch(["group_inside.c"]) + + conf_c_prefix : str + The prefix of public C definitions. Default is ``"NPY_"``. + + conf_c_prefix_ : str + The prefix of internal C definitions. Default is ``"NPY__"``. + + conf_cc_flags : dict + Nested dictionaries defining several compiler flags + that linked to some major functions, the main key + represent the compiler name and sub-keys represent + flags names. Default is already covers all supported + **C** compilers. + + Sub-keys explained as follows: + + "native": str or None + used by argument option `native`, to detect the current + machine support via the compiler. + "werror": str or None + utilized to treat warning as errors during testing CPU features + against the compiler and also for target's policy `$werror` + via dispatch-able sources. + "maxopt": str or None + utilized for target's policy '$maxopt' and the value should + contains the maximum acceptable optimization by the compiler. + e.g. in gcc `'-O3'` + + **Notes**: + * case-sensitive for compiler names and flags + * use space to separate multiple flags + * any flag will tested against the compiler and it will skipped + if it's not applicable. + + conf_min_features : dict + A dictionary defines the used CPU features for + argument option `'min'`, the key represent the CPU architecture + name e.g. `'x86'`. Default values provide the best effort + on wide range of users platforms. + + **Note**: case-sensitive for architecture names. + + conf_features : dict + Nested dictionaries used for identifying the CPU features. + the primary key is represented as a feature name or group name + that gathers several features. Default values covers all + supported features but without the major options like "flags", + these undefined options handle it by method `conf_features_partial()`. + Default value is covers almost all CPU features for *X86*, *IBM/Power64* + and *ARM 7/8*. + + Sub-keys explained as follows: + + "implies" : str or list, optional, + List of CPU feature names to be implied by it, + the feature name must be defined within `conf_features`. + Default is None. + + "flags": str or list, optional + List of compiler flags. Default is None. + + "detect": str or list, optional + List of CPU feature names that required to be detected + in runtime. By default, its the feature name or features + in "group" if its specified. + + "implies_detect": bool, optional + If True, all "detect" of implied features will be combined. + Default is True. see `feature_detect()`. + + "group": str or list, optional + Same as "implies" but doesn't require the feature name to be + defined within `conf_features`. + + "interest": int, required + a key for sorting CPU features + + "headers": str or list, optional + intrinsics C header file + + "disable": str, optional + force disable feature, the string value should contains the + reason of disabling. + + "autovec": bool or None, optional + True or False to declare that CPU feature can be auto-vectorized + by the compiler. + By default(None), treated as True if the feature contains at + least one applicable flag. see `feature_can_autovec()` + + "extra_checks": str or list, optional + Extra test case names for the CPU feature that need to be tested + against the compiler. + + Each test case must have a C file named ``extra_xxxx.c``, where + ``xxxx`` is the case name in lower case, under 'conf_check_path'. + It should contain at least one intrinsic or function related to the test case. + + If the compiler able to successfully compile the C file then `CCompilerOpt` + will add a C ``#define`` for it into the main dispatch header, e.g. + ``#define {conf_c_prefix}_XXXX`` where ``XXXX`` is the case name in upper case. + + **NOTES**: + * space can be used as separator with options that supports "str or list" + * case-sensitive for all values and feature name must be in upper-case. + * if flags aren't applicable, its will skipped rather than disable the + CPU feature + * the CPU feature will disabled if the compiler fail to compile + the test file + """ + conf_nocache = False + conf_noopt = False + conf_cache_factors = None + conf_tmp_path = None + conf_check_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "checks" + ) + conf_target_groups = {} + conf_c_prefix = 'NPY_' + conf_c_prefix_ = 'NPY__' + conf_cc_flags = dict( + gcc = dict( + # native should always fail on arm and ppc64, + # native usually works only with x86 + native = '-march=native', + opt = '-O3', + werror = '-Werror', + ), + clang = dict( + native = '-march=native', + opt = "-O3", + # One of the following flags needs to be applicable for Clang to + # guarantee the sanity of the testing process, however in certain + # cases `-Werror` gets skipped during the availability test due to + # "unused arguments" warnings. + # see https://github.com/numpy/numpy/issues/19624 + werror = '-Werror=switch -Werror', + ), + icc = dict( + native = '-xHost', + opt = '-O3', + werror = '-Werror', + ), + iccw = dict( + native = '/QxHost', + opt = '/O3', + werror = '/Werror', + ), + msvc = dict( + native = None, + opt = '/O2', + werror = '/WX', + ), + fcc = dict( + native = '-mcpu=a64fx', + opt = None, + werror = None, + ) + ) + conf_min_features = dict( + x86 = "SSE SSE2", + x64 = "SSE SSE2 SSE3", + ppc64 = '', # play it safe + ppc64le = "VSX VSX2", + s390x = '', + armhf = '', # play it safe + aarch64 = "NEON NEON_FP16 NEON_VFPV4 ASIMD" + ) + conf_features = dict( + # X86 + SSE = dict( + interest=1, headers="xmmintrin.h", + # enabling SSE without SSE2 is useless also + # it's non-optional for x86_64 + implies="SSE2" + ), + SSE2 = dict(interest=2, implies="SSE", headers="emmintrin.h"), + SSE3 = dict(interest=3, implies="SSE2", headers="pmmintrin.h"), + SSSE3 = dict(interest=4, implies="SSE3", headers="tmmintrin.h"), + SSE41 = dict(interest=5, implies="SSSE3", headers="smmintrin.h"), + POPCNT = dict(interest=6, implies="SSE41", headers="popcntintrin.h"), + SSE42 = dict(interest=7, implies="POPCNT"), + AVX = dict( + interest=8, implies="SSE42", headers="immintrin.h", + implies_detect=False + ), + XOP = dict(interest=9, implies="AVX", headers="x86intrin.h"), + FMA4 = dict(interest=10, implies="AVX", headers="x86intrin.h"), + F16C = dict(interest=11, implies="AVX"), + FMA3 = dict(interest=12, implies="F16C"), + AVX2 = dict(interest=13, implies="F16C"), + AVX512F = dict( + interest=20, implies="FMA3 AVX2", implies_detect=False, + extra_checks="AVX512F_REDUCE" + ), + AVX512CD = dict(interest=21, implies="AVX512F"), + AVX512_KNL = dict( + interest=40, implies="AVX512CD", group="AVX512ER AVX512PF", + detect="AVX512_KNL", implies_detect=False + ), + AVX512_KNM = dict( + interest=41, implies="AVX512_KNL", + group="AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ", + detect="AVX512_KNM", implies_detect=False + ), + AVX512_SKX = dict( + interest=42, implies="AVX512CD", group="AVX512VL AVX512BW AVX512DQ", + detect="AVX512_SKX", implies_detect=False, + extra_checks="AVX512BW_MASK AVX512DQ_MASK" + ), + AVX512_CLX = dict( + interest=43, implies="AVX512_SKX", group="AVX512VNNI", + detect="AVX512_CLX" + ), + AVX512_CNL = dict( + interest=44, implies="AVX512_SKX", group="AVX512IFMA AVX512VBMI", + detect="AVX512_CNL", implies_detect=False + ), + AVX512_ICL = dict( + interest=45, implies="AVX512_CLX AVX512_CNL", + group="AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ", + detect="AVX512_ICL", implies_detect=False + ), + AVX512_SPR = dict( + interest=46, implies="AVX512_ICL", group="AVX512FP16", + detect="AVX512_SPR", implies_detect=False + ), + # IBM/Power + ## Power7/ISA 2.06 + VSX = dict(interest=1, headers="altivec.h", extra_checks="VSX_ASM"), + ## Power8/ISA 2.07 + VSX2 = dict(interest=2, implies="VSX", implies_detect=False), + ## Power9/ISA 3.00 + VSX3 = dict(interest=3, implies="VSX2", implies_detect=False, + extra_checks="VSX3_HALF_DOUBLE"), + ## Power10/ISA 3.1 + VSX4 = dict(interest=4, implies="VSX3", implies_detect=False, + extra_checks="VSX4_MMA"), + # IBM/Z + ## VX(z13) support + VX = dict(interest=1, headers="vecintrin.h"), + ## Vector-Enhancements Facility + VXE = dict(interest=2, implies="VX", implies_detect=False), + ## Vector-Enhancements Facility 2 + VXE2 = dict(interest=3, implies="VXE", implies_detect=False), + # ARM + NEON = dict(interest=1, headers="arm_neon.h"), + NEON_FP16 = dict(interest=2, implies="NEON"), + ## FMA + NEON_VFPV4 = dict(interest=3, implies="NEON_FP16"), + ## Advanced SIMD + ASIMD = dict(interest=4, implies="NEON_FP16 NEON_VFPV4", implies_detect=False), + ## ARMv8.2 half-precision & vector arithm + ASIMDHP = dict(interest=5, implies="ASIMD"), + ## ARMv8.2 dot product + ASIMDDP = dict(interest=6, implies="ASIMD"), + ## ARMv8.2 Single & half-precision Multiply + ASIMDFHM = dict(interest=7, implies="ASIMDHP"), + ) + def conf_features_partial(self): + """Return a dictionary of supported CPU features by the platform, + and accumulate the rest of undefined options in `conf_features`, + the returned dict has same rules and notes in + class attribute `conf_features`, also its override + any options that been set in 'conf_features'. + """ + if self.cc_noopt: + # optimization is disabled + return {} + + on_x86 = self.cc_on_x86 or self.cc_on_x64 + is_unix = self.cc_is_gcc or self.cc_is_clang or self.cc_is_fcc + + if on_x86 and is_unix: return dict( + SSE = dict(flags="-msse"), + SSE2 = dict(flags="-msse2"), + SSE3 = dict(flags="-msse3"), + SSSE3 = dict(flags="-mssse3"), + SSE41 = dict(flags="-msse4.1"), + POPCNT = dict(flags="-mpopcnt"), + SSE42 = dict(flags="-msse4.2"), + AVX = dict(flags="-mavx"), + F16C = dict(flags="-mf16c"), + XOP = dict(flags="-mxop"), + FMA4 = dict(flags="-mfma4"), + FMA3 = dict(flags="-mfma"), + AVX2 = dict(flags="-mavx2"), + AVX512F = dict(flags="-mavx512f -mno-mmx"), + AVX512CD = dict(flags="-mavx512cd"), + AVX512_KNL = dict(flags="-mavx512er -mavx512pf"), + AVX512_KNM = dict( + flags="-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq" + ), + AVX512_SKX = dict(flags="-mavx512vl -mavx512bw -mavx512dq"), + AVX512_CLX = dict(flags="-mavx512vnni"), + AVX512_CNL = dict(flags="-mavx512ifma -mavx512vbmi"), + AVX512_ICL = dict( + flags="-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq" + ), + AVX512_SPR = dict(flags="-mavx512fp16"), + ) + if on_x86 and self.cc_is_icc: return dict( + SSE = dict(flags="-msse"), + SSE2 = dict(flags="-msse2"), + SSE3 = dict(flags="-msse3"), + SSSE3 = dict(flags="-mssse3"), + SSE41 = dict(flags="-msse4.1"), + POPCNT = {}, + SSE42 = dict(flags="-msse4.2"), + AVX = dict(flags="-mavx"), + F16C = {}, + XOP = dict(disable="Intel Compiler doesn't support it"), + FMA4 = dict(disable="Intel Compiler doesn't support it"), + # Intel Compiler doesn't support AVX2 or FMA3 independently + FMA3 = dict( + implies="F16C AVX2", flags="-march=core-avx2" + ), + AVX2 = dict(implies="FMA3", flags="-march=core-avx2"), + # Intel Compiler doesn't support AVX512F or AVX512CD independently + AVX512F = dict( + implies="AVX2 AVX512CD", flags="-march=common-avx512" + ), + AVX512CD = dict( + implies="AVX2 AVX512F", flags="-march=common-avx512" + ), + AVX512_KNL = dict(flags="-xKNL"), + AVX512_KNM = dict(flags="-xKNM"), + AVX512_SKX = dict(flags="-xSKYLAKE-AVX512"), + AVX512_CLX = dict(flags="-xCASCADELAKE"), + AVX512_CNL = dict(flags="-xCANNONLAKE"), + AVX512_ICL = dict(flags="-xICELAKE-CLIENT"), + AVX512_SPR = dict(disable="Not supported yet") + ) + if on_x86 and self.cc_is_iccw: return dict( + SSE = dict(flags="/arch:SSE"), + SSE2 = dict(flags="/arch:SSE2"), + SSE3 = dict(flags="/arch:SSE3"), + SSSE3 = dict(flags="/arch:SSSE3"), + SSE41 = dict(flags="/arch:SSE4.1"), + POPCNT = {}, + SSE42 = dict(flags="/arch:SSE4.2"), + AVX = dict(flags="/arch:AVX"), + F16C = {}, + XOP = dict(disable="Intel Compiler doesn't support it"), + FMA4 = dict(disable="Intel Compiler doesn't support it"), + # Intel Compiler doesn't support FMA3 or AVX2 independently + FMA3 = dict( + implies="F16C AVX2", flags="/arch:CORE-AVX2" + ), + AVX2 = dict( + implies="FMA3", flags="/arch:CORE-AVX2" + ), + # Intel Compiler doesn't support AVX512F or AVX512CD independently + AVX512F = dict( + implies="AVX2 AVX512CD", flags="/Qx:COMMON-AVX512" + ), + AVX512CD = dict( + implies="AVX2 AVX512F", flags="/Qx:COMMON-AVX512" + ), + AVX512_KNL = dict(flags="/Qx:KNL"), + AVX512_KNM = dict(flags="/Qx:KNM"), + AVX512_SKX = dict(flags="/Qx:SKYLAKE-AVX512"), + AVX512_CLX = dict(flags="/Qx:CASCADELAKE"), + AVX512_CNL = dict(flags="/Qx:CANNONLAKE"), + AVX512_ICL = dict(flags="/Qx:ICELAKE-CLIENT"), + AVX512_SPR = dict(disable="Not supported yet") + ) + if on_x86 and self.cc_is_msvc: return dict( + SSE = dict(flags="/arch:SSE") if self.cc_on_x86 else {}, + SSE2 = dict(flags="/arch:SSE2") if self.cc_on_x86 else {}, + SSE3 = {}, + SSSE3 = {}, + SSE41 = {}, + POPCNT = dict(headers="nmmintrin.h"), + SSE42 = {}, + AVX = dict(flags="/arch:AVX"), + F16C = {}, + XOP = dict(headers="ammintrin.h"), + FMA4 = dict(headers="ammintrin.h"), + # MSVC doesn't support FMA3 or AVX2 independently + FMA3 = dict( + implies="F16C AVX2", flags="/arch:AVX2" + ), + AVX2 = dict( + implies="F16C FMA3", flags="/arch:AVX2" + ), + # MSVC doesn't support AVX512F or AVX512CD independently, + # always generate instructions belong to (VL/VW/DQ) + AVX512F = dict( + implies="AVX2 AVX512CD AVX512_SKX", flags="/arch:AVX512" + ), + AVX512CD = dict( + implies="AVX512F AVX512_SKX", flags="/arch:AVX512" + ), + AVX512_KNL = dict( + disable="MSVC compiler doesn't support it" + ), + AVX512_KNM = dict( + disable="MSVC compiler doesn't support it" + ), + AVX512_SKX = dict(flags="/arch:AVX512"), + AVX512_CLX = {}, + AVX512_CNL = {}, + AVX512_ICL = {}, + AVX512_SPR= dict( + disable="MSVC compiler doesn't support it" + ) + ) + + on_power = self.cc_on_ppc64le or self.cc_on_ppc64 + if on_power: + partial = dict( + VSX = dict( + implies=("VSX2" if self.cc_on_ppc64le else ""), + flags="-mvsx" + ), + VSX2 = dict( + flags="-mcpu=power8", implies_detect=False + ), + VSX3 = dict( + flags="-mcpu=power9 -mtune=power9", implies_detect=False + ), + VSX4 = dict( + flags="-mcpu=power10 -mtune=power10", implies_detect=False + ) + ) + if self.cc_is_clang: + partial["VSX"]["flags"] = "-maltivec -mvsx" + partial["VSX2"]["flags"] = "-mcpu=power8" + partial["VSX3"]["flags"] = "-mcpu=power9" + partial["VSX4"]["flags"] = "-mcpu=power10" + + return partial + + on_zarch = self.cc_on_s390x + if on_zarch: + partial = dict( + VX = dict( + flags="-march=arch11 -mzvector" + ), + VXE = dict( + flags="-march=arch12", implies_detect=False + ), + VXE2 = dict( + flags="-march=arch13", implies_detect=False + ) + ) + + return partial + + + if self.cc_on_aarch64 and is_unix: return dict( + NEON = dict( + implies="NEON_FP16 NEON_VFPV4 ASIMD", autovec=True + ), + NEON_FP16 = dict( + implies="NEON NEON_VFPV4 ASIMD", autovec=True + ), + NEON_VFPV4 = dict( + implies="NEON NEON_FP16 ASIMD", autovec=True + ), + ASIMD = dict( + implies="NEON NEON_FP16 NEON_VFPV4", autovec=True + ), + ASIMDHP = dict( + flags="-march=armv8.2-a+fp16" + ), + ASIMDDP = dict( + flags="-march=armv8.2-a+dotprod" + ), + ASIMDFHM = dict( + flags="-march=armv8.2-a+fp16fml" + ), + ) + if self.cc_on_armhf and is_unix: return dict( + NEON = dict( + flags="-mfpu=neon" + ), + NEON_FP16 = dict( + flags="-mfpu=neon-fp16 -mfp16-format=ieee" + ), + NEON_VFPV4 = dict( + flags="-mfpu=neon-vfpv4", + ), + ASIMD = dict( + flags="-mfpu=neon-fp-armv8 -march=armv8-a+simd", + ), + ASIMDHP = dict( + flags="-march=armv8.2-a+fp16" + ), + ASIMDDP = dict( + flags="-march=armv8.2-a+dotprod", + ), + ASIMDFHM = dict( + flags="-march=armv8.2-a+fp16fml" + ) + ) + # TODO: ARM MSVC + return {} + + def __init__(self): + if self.conf_tmp_path is None: + import shutil + import tempfile + tmp = tempfile.mkdtemp() + def rm_temp(): + try: + shutil.rmtree(tmp) + except OSError: + pass + atexit.register(rm_temp) + self.conf_tmp_path = tmp + + if self.conf_cache_factors is None: + self.conf_cache_factors = [ + os.path.getmtime(__file__), + self.conf_nocache + ] + +class _Distutils: + """A helper class that provides a collection of fundamental methods + implemented in a top of Python and NumPy Distutils. + + The idea behind this class is to gather all methods that it may + need to override in case of reuse 'CCompilerOpt' in environment + different than of what NumPy has. + + Parameters + ---------- + ccompiler : `CCompiler` + The generate instance that returned from `distutils.ccompiler.new_compiler()`. + """ + def __init__(self, ccompiler): + self._ccompiler = ccompiler + + def dist_compile(self, sources, flags, ccompiler=None, **kwargs): + """Wrap CCompiler.compile()""" + assert(isinstance(sources, list)) + assert(isinstance(flags, list)) + flags = kwargs.pop("extra_postargs", []) + flags + if not ccompiler: + ccompiler = self._ccompiler + + return ccompiler.compile(sources, extra_postargs=flags, **kwargs) + + def dist_test(self, source, flags, macros=[]): + """Return True if 'CCompiler.compile()' able to compile + a source file with certain flags. + """ + assert(isinstance(source, str)) + from distutils.errors import CompileError + cc = self._ccompiler; + bk_spawn = getattr(cc, 'spawn', None) + if bk_spawn: + cc_type = getattr(self._ccompiler, "compiler_type", "") + if cc_type in ("msvc",): + setattr(cc, 'spawn', self._dist_test_spawn_paths) + else: + setattr(cc, 'spawn', self._dist_test_spawn) + test = False + try: + self.dist_compile( + [source], flags, macros=macros, output_dir=self.conf_tmp_path + ) + test = True + except CompileError as e: + self.dist_log(str(e), stderr=True) + if bk_spawn: + setattr(cc, 'spawn', bk_spawn) + return test + + def dist_info(self): + """ + Return a tuple containing info about (platform, compiler, extra_args), + required by the abstract class '_CCompiler' for discovering the + platform environment. This is also used as a cache factor in order + to detect any changes happening from outside. + """ + if hasattr(self, "_dist_info"): + return self._dist_info + + cc_type = getattr(self._ccompiler, "compiler_type", '') + if cc_type in ("intelem", "intelemw"): + platform = "x86_64" + elif cc_type in ("intel", "intelw", "intele"): + platform = "x86" + else: + from distutils.util import get_platform + platform = get_platform() + + cc_info = getattr(self._ccompiler, "compiler", getattr(self._ccompiler, "compiler_so", '')) + if not cc_type or cc_type == "unix": + if hasattr(cc_info, "__iter__"): + compiler = cc_info[0] + else: + compiler = str(cc_info) + else: + compiler = cc_type + + if hasattr(cc_info, "__iter__") and len(cc_info) > 1: + extra_args = ' '.join(cc_info[1:]) + else: + extra_args = os.environ.get("CFLAGS", "") + extra_args += os.environ.get("CPPFLAGS", "") + + self._dist_info = (platform, compiler, extra_args) + return self._dist_info + + @staticmethod + def dist_error(*args): + """Raise a compiler error""" + from distutils.errors import CompileError + raise CompileError(_Distutils._dist_str(*args)) + + @staticmethod + def dist_fatal(*args): + """Raise a distutils error""" + from distutils.errors import DistutilsError + raise DistutilsError(_Distutils._dist_str(*args)) + + @staticmethod + def dist_log(*args, stderr=False): + """Print a console message""" + from numpy.distutils import log + out = _Distutils._dist_str(*args) + if stderr: + log.warn(out) + else: + log.info(out) + + @staticmethod + def dist_load_module(name, path): + """Load a module from file, required by the abstract class '_Cache'.""" + from .misc_util import exec_mod_from_location + try: + return exec_mod_from_location(name, path) + except Exception as e: + _Distutils.dist_log(e, stderr=True) + return None + + @staticmethod + def _dist_str(*args): + """Return a string to print by log and errors.""" + def to_str(arg): + if not isinstance(arg, str) and hasattr(arg, '__iter__'): + ret = [] + for a in arg: + ret.append(to_str(a)) + return '('+ ' '.join(ret) + ')' + return str(arg) + + stack = inspect.stack()[2] + start = "CCompilerOpt.%s[%d] : " % (stack.function, stack.lineno) + out = ' '.join([ + to_str(a) + for a in (*args,) + ]) + return start + out + + def _dist_test_spawn_paths(self, cmd, display=None): + """ + Fix msvc SDK ENV path same as distutils do + without it we get c1: fatal error C1356: unable to find mspdbcore.dll + """ + if not hasattr(self._ccompiler, "_paths"): + self._dist_test_spawn(cmd) + return + old_path = os.getenv("path") + try: + os.environ["path"] = self._ccompiler._paths + self._dist_test_spawn(cmd) + finally: + os.environ["path"] = old_path + + _dist_warn_regex = re.compile( + # intel and msvc compilers don't raise + # fatal errors when flags are wrong or unsupported + ".*(" + "warning D9002|" # msvc, it should be work with any language. + "invalid argument for option" # intel + ").*" + ) + @staticmethod + def _dist_test_spawn(cmd, display=None): + try: + o = subprocess.check_output(cmd, stderr=subprocess.STDOUT, + text=True) + if o and re.match(_Distutils._dist_warn_regex, o): + _Distutils.dist_error( + "Flags in command", cmd ,"aren't supported by the compiler" + ", output -> \n%s" % o + ) + except subprocess.CalledProcessError as exc: + o = exc.output + s = exc.returncode + except OSError as e: + o = e + s = 127 + else: + return None + _Distutils.dist_error( + "Command", cmd, "failed with exit status %d output -> \n%s" % ( + s, o + )) + +_share_cache = {} +class _Cache: + """An abstract class handles caching functionality, provides two + levels of caching, in-memory by share instances attributes among + each other and by store attributes into files. + + **Note**: + any attributes that start with ``_`` or ``conf_`` will be ignored. + + Parameters + ---------- + cache_path : str or None + The path of cache file, if None then cache in file will disabled. + + *factors : + The caching factors that need to utilize next to `conf_cache_factors`. + + Attributes + ---------- + cache_private : set + Hold the attributes that need be skipped from "in-memory cache". + + cache_infile : bool + Utilized during initializing this class, to determine if the cache was able + to loaded from the specified cache path in 'cache_path'. + """ + + # skip attributes from cache + _cache_ignore = re.compile("^(_|conf_)") + + def __init__(self, cache_path=None, *factors): + self.cache_me = {} + self.cache_private = set() + self.cache_infile = False + self._cache_path = None + + if self.conf_nocache: + self.dist_log("cache is disabled by `Config`") + return + + self._cache_hash = self.cache_hash(*factors, *self.conf_cache_factors) + self._cache_path = cache_path + if cache_path: + if os.path.exists(cache_path): + self.dist_log("load cache from file ->", cache_path) + cache_mod = self.dist_load_module("cache", cache_path) + if not cache_mod: + self.dist_log( + "unable to load the cache file as a module", + stderr=True + ) + elif not hasattr(cache_mod, "hash") or \ + not hasattr(cache_mod, "data"): + self.dist_log("invalid cache file", stderr=True) + elif self._cache_hash == cache_mod.hash: + self.dist_log("hit the file cache") + for attr, val in cache_mod.data.items(): + setattr(self, attr, val) + self.cache_infile = True + else: + self.dist_log("miss the file cache") + + if not self.cache_infile: + other_cache = _share_cache.get(self._cache_hash) + if other_cache: + self.dist_log("hit the memory cache") + for attr, val in other_cache.__dict__.items(): + if attr in other_cache.cache_private or \ + re.match(self._cache_ignore, attr): + continue + setattr(self, attr, val) + + _share_cache[self._cache_hash] = self + atexit.register(self.cache_flush) + + def __del__(self): + for h, o in _share_cache.items(): + if o == self: + _share_cache.pop(h) + break + + def cache_flush(self): + """ + Force update the cache. + """ + if not self._cache_path: + return + # TODO: don't write if the cache doesn't change + self.dist_log("write cache to path ->", self._cache_path) + cdict = self.__dict__.copy() + for attr in self.__dict__.keys(): + if re.match(self._cache_ignore, attr): + cdict.pop(attr) + + d = os.path.dirname(self._cache_path) + if not os.path.exists(d): + os.makedirs(d) + + repr_dict = pprint.pformat(cdict, compact=True) + with open(self._cache_path, "w") as f: + f.write(textwrap.dedent("""\ + # AUTOGENERATED DON'T EDIT + # Please make changes to the code generator \ + (distutils/ccompiler_opt.py) + hash = {} + data = \\ + """).format(self._cache_hash)) + f.write(repr_dict) + + def cache_hash(self, *factors): + # is there a built-in non-crypto hash? + # sdbm + chash = 0 + for f in factors: + for char in str(f): + chash = ord(char) + (chash << 6) + (chash << 16) - chash + chash &= 0xFFFFFFFF + return chash + + @staticmethod + def me(cb): + """ + A static method that can be treated as a decorator to + dynamically cache certain methods. + """ + def cache_wrap_me(self, *args, **kwargs): + # good for normal args + cache_key = str(( + cb.__name__, *args, *kwargs.keys(), *kwargs.values() + )) + if cache_key in self.cache_me: + return self.cache_me[cache_key] + ccb = cb(self, *args, **kwargs) + self.cache_me[cache_key] = ccb + return ccb + return cache_wrap_me + +class _CCompiler: + """A helper class for `CCompilerOpt` containing all utilities that + related to the fundamental compiler's functions. + + Attributes + ---------- + cc_on_x86 : bool + True when the target architecture is 32-bit x86 + cc_on_x64 : bool + True when the target architecture is 64-bit x86 + cc_on_ppc64 : bool + True when the target architecture is 64-bit big-endian powerpc + cc_on_ppc64le : bool + True when the target architecture is 64-bit litle-endian powerpc + cc_on_s390x : bool + True when the target architecture is IBM/ZARCH on linux + cc_on_armhf : bool + True when the target architecture is 32-bit ARMv7+ + cc_on_aarch64 : bool + True when the target architecture is 64-bit Armv8-a+ + cc_on_noarch : bool + True when the target architecture is unknown or not supported + cc_is_gcc : bool + True if the compiler is GNU or + if the compiler is unknown + cc_is_clang : bool + True if the compiler is Clang + cc_is_icc : bool + True if the compiler is Intel compiler (unix like) + cc_is_iccw : bool + True if the compiler is Intel compiler (msvc like) + cc_is_nocc : bool + True if the compiler isn't supported directly, + Note: that cause a fail-back to gcc + cc_has_debug : bool + True if the compiler has debug flags + cc_has_native : bool + True if the compiler has native flags + cc_noopt : bool + True if the compiler has definition 'DISABLE_OPT*', + or 'cc_on_noarch' is True + cc_march : str + The target architecture name, or "unknown" if + the architecture isn't supported + cc_name : str + The compiler name, or "unknown" if the compiler isn't supported + cc_flags : dict + Dictionary containing the initialized flags of `_Config.conf_cc_flags` + """ + def __init__(self): + if hasattr(self, "cc_is_cached"): + return + # attr regex compiler-expression + detect_arch = ( + ("cc_on_x64", ".*(x|x86_|amd)64.*", ""), + ("cc_on_x86", ".*(win32|x86|i386|i686).*", ""), + ("cc_on_ppc64le", ".*(powerpc|ppc)64(el|le).*|.*powerpc.*", + "defined(__powerpc64__) && " + "defined(__LITTLE_ENDIAN__)"), + ("cc_on_ppc64", ".*(powerpc|ppc).*|.*powerpc.*", + "defined(__powerpc64__) && " + "defined(__BIG_ENDIAN__)"), + ("cc_on_aarch64", ".*(aarch64|arm64).*", ""), + ("cc_on_armhf", ".*arm.*", "defined(__ARM_ARCH_7__) || " + "defined(__ARM_ARCH_7A__)"), + ("cc_on_s390x", ".*s390x.*", ""), + # undefined platform + ("cc_on_noarch", "", ""), + ) + detect_compiler = ( + ("cc_is_gcc", r".*(gcc|gnu\-g).*", ""), + ("cc_is_clang", ".*clang.*", ""), + # intel msvc like + ("cc_is_iccw", ".*(intelw|intelemw|iccw).*", ""), + ("cc_is_icc", ".*(intel|icc).*", ""), # intel unix like + ("cc_is_msvc", ".*msvc.*", ""), + ("cc_is_fcc", ".*fcc.*", ""), + # undefined compiler will be treat it as gcc + ("cc_is_nocc", "", ""), + ) + detect_args = ( + ("cc_has_debug", ".*(O0|Od|ggdb|coverage|debug:full).*", ""), + ("cc_has_native", + ".*(-march=native|-xHost|/QxHost|-mcpu=a64fx).*", ""), + # in case if the class run with -DNPY_DISABLE_OPTIMIZATION + ("cc_noopt", ".*DISABLE_OPT.*", ""), + ) + + dist_info = self.dist_info() + platform, compiler_info, extra_args = dist_info + # set False to all attrs + for section in (detect_arch, detect_compiler, detect_args): + for attr, rgex, cexpr in section: + setattr(self, attr, False) + + for detect, searchin in ((detect_arch, platform), (detect_compiler, compiler_info)): + for attr, rgex, cexpr in detect: + if rgex and not re.match(rgex, searchin, re.IGNORECASE): + continue + if cexpr and not self.cc_test_cexpr(cexpr): + continue + setattr(self, attr, True) + break + + for attr, rgex, cexpr in detect_args: + if rgex and not re.match(rgex, extra_args, re.IGNORECASE): + continue + if cexpr and not self.cc_test_cexpr(cexpr): + continue + setattr(self, attr, True) + + if self.cc_on_noarch: + self.dist_log( + "unable to detect CPU architecture which lead to disable the optimization. " + f"check dist_info:<<\n{dist_info}\n>>", + stderr=True + ) + self.cc_noopt = True + + if self.conf_noopt: + self.dist_log("Optimization is disabled by the Config", stderr=True) + self.cc_noopt = True + + if self.cc_is_nocc: + """ + mingw can be treated as a gcc, and also xlc even if it based on clang, + but still has the same gcc optimization flags. + """ + self.dist_log( + "unable to detect compiler type which leads to treating it as GCC. " + "this is a normal behavior if you're using gcc-like compiler such as MinGW or IBM/XLC." + f"check dist_info:<<\n{dist_info}\n>>", + stderr=True + ) + self.cc_is_gcc = True + + self.cc_march = "unknown" + for arch in ("x86", "x64", "ppc64", "ppc64le", + "armhf", "aarch64", "s390x"): + if getattr(self, "cc_on_" + arch): + self.cc_march = arch + break + + self.cc_name = "unknown" + for name in ("gcc", "clang", "iccw", "icc", "msvc", "fcc"): + if getattr(self, "cc_is_" + name): + self.cc_name = name + break + + self.cc_flags = {} + compiler_flags = self.conf_cc_flags.get(self.cc_name) + if compiler_flags is None: + self.dist_fatal( + "undefined flag for compiler '%s', " + "leave an empty dict instead" % self.cc_name + ) + for name, flags in compiler_flags.items(): + self.cc_flags[name] = nflags = [] + if flags: + assert(isinstance(flags, str)) + flags = flags.split() + for f in flags: + if self.cc_test_flags([f]): + nflags.append(f) + + self.cc_is_cached = True + + @_Cache.me + def cc_test_flags(self, flags): + """ + Returns True if the compiler supports 'flags'. + """ + assert(isinstance(flags, list)) + self.dist_log("testing flags", flags) + test_path = os.path.join(self.conf_check_path, "test_flags.c") + test = self.dist_test(test_path, flags) + if not test: + self.dist_log("testing failed", stderr=True) + return test + + @_Cache.me + def cc_test_cexpr(self, cexpr, flags=[]): + """ + Same as the above but supports compile-time expressions. + """ + self.dist_log("testing compiler expression", cexpr) + test_path = os.path.join(self.conf_tmp_path, "npy_dist_test_cexpr.c") + with open(test_path, "w") as fd: + fd.write(textwrap.dedent(f"""\ + #if !({cexpr}) + #error "unsupported expression" + #endif + int dummy; + """)) + test = self.dist_test(test_path, flags) + if not test: + self.dist_log("testing failed", stderr=True) + return test + + def cc_normalize_flags(self, flags): + """ + Remove the conflicts that caused due gathering implied features flags. + + Parameters + ---------- + 'flags' list, compiler flags + flags should be sorted from the lowest to the highest interest. + + Returns + ------- + list, filtered from any conflicts. + + Examples + -------- + >>> self.cc_normalize_flags(['-march=armv8.2-a+fp16', '-march=armv8.2-a+dotprod']) + ['armv8.2-a+fp16+dotprod'] + + >>> self.cc_normalize_flags( + ['-msse', '-msse2', '-msse3', '-mssse3', '-msse4.1', '-msse4.2', '-mavx', '-march=core-avx2'] + ) + ['-march=core-avx2'] + """ + assert(isinstance(flags, list)) + if self.cc_is_gcc or self.cc_is_clang or self.cc_is_icc: + return self._cc_normalize_unix(flags) + + if self.cc_is_msvc or self.cc_is_iccw: + return self._cc_normalize_win(flags) + return flags + + _cc_normalize_unix_mrgx = re.compile( + # 1- to check the highest of + r"^(-mcpu=|-march=|-x[A-Z0-9\-])" + ) + _cc_normalize_unix_frgx = re.compile( + # 2- to remove any flags starts with + # -march, -mcpu, -x(INTEL) and '-m' without '=' + r"^(?!(-mcpu=|-march=|-x[A-Z0-9\-]|-m[a-z0-9\-\.]*.$))|" + # exclude: + r"(?:-mzvector)" + ) + _cc_normalize_unix_krgx = re.compile( + # 3- keep only the highest of + r"^(-mfpu|-mtune)" + ) + _cc_normalize_arch_ver = re.compile( + r"[0-9.]" + ) + def _cc_normalize_unix(self, flags): + def ver_flags(f): + # arch ver subflag + # -march=armv8.2-a+fp16fml + tokens = f.split('+') + ver = float('0' + ''.join( + re.findall(self._cc_normalize_arch_ver, tokens[0]) + )) + return ver, tokens[0], tokens[1:] + + if len(flags) <= 1: + return flags + # get the highest matched flag + for i, cur_flag in enumerate(reversed(flags)): + if not re.match(self._cc_normalize_unix_mrgx, cur_flag): + continue + lower_flags = flags[:-(i+1)] + upper_flags = flags[-i:] + filtered = list(filter( + self._cc_normalize_unix_frgx.search, lower_flags + )) + # gather subflags + ver, arch, subflags = ver_flags(cur_flag) + if ver > 0 and len(subflags) > 0: + for xflag in lower_flags: + xver, _, xsubflags = ver_flags(xflag) + if ver == xver: + subflags = xsubflags + subflags + cur_flag = arch + '+' + '+'.join(subflags) + + flags = filtered + [cur_flag] + if i > 0: + flags += upper_flags + break + + # to remove overridable flags + final_flags = [] + matched = set() + for f in reversed(flags): + match = re.match(self._cc_normalize_unix_krgx, f) + if not match: + pass + elif match[0] in matched: + continue + else: + matched.add(match[0]) + final_flags.insert(0, f) + return final_flags + + _cc_normalize_win_frgx = re.compile( + r"^(?!(/arch\:|/Qx\:))" + ) + _cc_normalize_win_mrgx = re.compile( + r"^(/arch|/Qx:)" + ) + def _cc_normalize_win(self, flags): + for i, f in enumerate(reversed(flags)): + if not re.match(self._cc_normalize_win_mrgx, f): + continue + i += 1 + return list(filter( + self._cc_normalize_win_frgx.search, flags[:-i] + )) + flags[-i:] + return flags + +class _Feature: + """A helper class for `CCompilerOpt` that managing CPU features. + + Attributes + ---------- + feature_supported : dict + Dictionary containing all CPU features that supported + by the platform, according to the specified values in attribute + `_Config.conf_features` and `_Config.conf_features_partial()` + + feature_min : set + The minimum support of CPU features, according to + the specified values in attribute `_Config.conf_min_features`. + """ + def __init__(self): + if hasattr(self, "feature_is_cached"): + return + self.feature_supported = pfeatures = self.conf_features_partial() + for feature_name in list(pfeatures.keys()): + feature = pfeatures[feature_name] + cfeature = self.conf_features[feature_name] + feature.update({ + k:v for k,v in cfeature.items() if k not in feature + }) + disabled = feature.get("disable") + if disabled is not None: + pfeatures.pop(feature_name) + self.dist_log( + "feature '%s' is disabled," % feature_name, + disabled, stderr=True + ) + continue + # list is used internally for these options + for option in ( + "implies", "group", "detect", "headers", "flags", "extra_checks" + ) : + oval = feature.get(option) + if isinstance(oval, str): + feature[option] = oval.split() + + self.feature_min = set() + min_f = self.conf_min_features.get(self.cc_march, "") + for F in min_f.upper().split(): + if F in self.feature_supported: + self.feature_min.add(F) + + self.feature_is_cached = True + + def feature_names(self, names=None, force_flags=None, macros=[]): + """ + Returns a set of CPU feature names that supported by platform and the **C** compiler. + + Parameters + ---------- + names : sequence or None, optional + Specify certain CPU features to test it against the **C** compiler. + if None(default), it will test all current supported features. + **Note**: feature names must be in upper-case. + + force_flags : list or None, optional + If None(default), default compiler flags for every CPU feature will + be used during the test. + + macros : list of tuples, optional + A list of C macro definitions. + """ + assert( + names is None or ( + not isinstance(names, str) and + hasattr(names, "__iter__") + ) + ) + assert(force_flags is None or isinstance(force_flags, list)) + if names is None: + names = self.feature_supported.keys() + supported_names = set() + for f in names: + if self.feature_is_supported( + f, force_flags=force_flags, macros=macros + ): + supported_names.add(f) + return supported_names + + def feature_is_exist(self, name): + """ + Returns True if a certain feature is exist and covered within + ``_Config.conf_features``. + + Parameters + ---------- + 'name': str + feature name in uppercase. + """ + assert(name.isupper()) + return name in self.conf_features + + def feature_sorted(self, names, reverse=False): + """ + Sort a list of CPU features ordered by the lowest interest. + + Parameters + ---------- + 'names': sequence + sequence of supported feature names in uppercase. + 'reverse': bool, optional + If true, the sorted features is reversed. (highest interest) + + Returns + ------- + list, sorted CPU features + """ + def sort_cb(k): + if isinstance(k, str): + return self.feature_supported[k]["interest"] + # multiple features + rank = max([self.feature_supported[f]["interest"] for f in k]) + # FIXME: that's not a safe way to increase the rank for + # multi targets + rank += len(k) -1 + return rank + return sorted(names, reverse=reverse, key=sort_cb) + + def feature_implies(self, names, keep_origins=False): + """ + Return a set of CPU features that implied by 'names' + + Parameters + ---------- + names : str or sequence of str + CPU feature name(s) in uppercase. + + keep_origins : bool + if False(default) then the returned set will not contain any + features from 'names'. This case happens only when two features + imply each other. + + Examples + -------- + >>> self.feature_implies("SSE3") + {'SSE', 'SSE2'} + >>> self.feature_implies("SSE2") + {'SSE'} + >>> self.feature_implies("SSE2", keep_origins=True) + # 'SSE2' found here since 'SSE' and 'SSE2' imply each other + {'SSE', 'SSE2'} + """ + def get_implies(name, _caller=set()): + implies = set() + d = self.feature_supported[name] + for i in d.get("implies", []): + implies.add(i) + if i in _caller: + # infinity recursive guard since + # features can imply each other + continue + _caller.add(name) + implies = implies.union(get_implies(i, _caller)) + return implies + + if isinstance(names, str): + implies = get_implies(names) + names = [names] + else: + assert(hasattr(names, "__iter__")) + implies = set() + for n in names: + implies = implies.union(get_implies(n)) + if not keep_origins: + implies.difference_update(names) + return implies + + def feature_implies_c(self, names): + """same as feature_implies() but combining 'names'""" + if isinstance(names, str): + names = set((names,)) + else: + names = set(names) + return names.union(self.feature_implies(names)) + + def feature_ahead(self, names): + """ + Return list of features in 'names' after remove any + implied features and keep the origins. + + Parameters + ---------- + 'names': sequence + sequence of CPU feature names in uppercase. + + Returns + ------- + list of CPU features sorted as-is 'names' + + Examples + -------- + >>> self.feature_ahead(["SSE2", "SSE3", "SSE41"]) + ["SSE41"] + # assume AVX2 and FMA3 implies each other and AVX2 + # is the highest interest + >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"]) + ["AVX2"] + # assume AVX2 and FMA3 don't implies each other + >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"]) + ["AVX2", "FMA3"] + """ + assert( + not isinstance(names, str) + and hasattr(names, '__iter__') + ) + implies = self.feature_implies(names, keep_origins=True) + ahead = [n for n in names if n not in implies] + if len(ahead) == 0: + # return the highest interested feature + # if all features imply each other + ahead = self.feature_sorted(names, reverse=True)[:1] + return ahead + + def feature_untied(self, names): + """ + same as 'feature_ahead()' but if both features implied each other + and keep the highest interest. + + Parameters + ---------- + 'names': sequence + sequence of CPU feature names in uppercase. + + Returns + ------- + list of CPU features sorted as-is 'names' + + Examples + -------- + >>> self.feature_untied(["SSE2", "SSE3", "SSE41"]) + ["SSE2", "SSE3", "SSE41"] + # assume AVX2 and FMA3 implies each other + >>> self.feature_untied(["SSE2", "SSE3", "SSE41", "FMA3", "AVX2"]) + ["SSE2", "SSE3", "SSE41", "AVX2"] + """ + assert( + not isinstance(names, str) + and hasattr(names, '__iter__') + ) + final = [] + for n in names: + implies = self.feature_implies(n) + tied = [ + nn for nn in final + if nn in implies and n in self.feature_implies(nn) + ] + if tied: + tied = self.feature_sorted(tied + [n]) + if n not in tied[1:]: + continue + final.remove(tied[:1][0]) + final.append(n) + return final + + def feature_get_til(self, names, keyisfalse): + """ + same as `feature_implies_c()` but stop collecting implied + features when feature's option that provided through + parameter 'keyisfalse' is False, also sorting the returned + features. + """ + def til(tnames): + # sort from highest to lowest interest then cut if "key" is False + tnames = self.feature_implies_c(tnames) + tnames = self.feature_sorted(tnames, reverse=True) + for i, n in enumerate(tnames): + if not self.feature_supported[n].get(keyisfalse, True): + tnames = tnames[:i+1] + break + return tnames + + if isinstance(names, str) or len(names) <= 1: + names = til(names) + # normalize the sort + names.reverse() + return names + + names = self.feature_ahead(names) + names = {t for n in names for t in til(n)} + return self.feature_sorted(names) + + def feature_detect(self, names): + """ + Return a list of CPU features that required to be detected + sorted from the lowest to highest interest. + """ + names = self.feature_get_til(names, "implies_detect") + detect = [] + for n in names: + d = self.feature_supported[n] + detect += d.get("detect", d.get("group", [n])) + return detect + + @_Cache.me + def feature_flags(self, names): + """ + Return a list of CPU features flags sorted from the lowest + to highest interest. + """ + names = self.feature_sorted(self.feature_implies_c(names)) + flags = [] + for n in names: + d = self.feature_supported[n] + f = d.get("flags", []) + if not f or not self.cc_test_flags(f): + continue + flags += f + return self.cc_normalize_flags(flags) + + @_Cache.me + def feature_test(self, name, force_flags=None, macros=[]): + """ + Test a certain CPU feature against the compiler through its own + check file. + + Parameters + ---------- + name : str + Supported CPU feature name. + + force_flags : list or None, optional + If None(default), the returned flags from `feature_flags()` + will be used. + + macros : list of tuples, optional + A list of C macro definitions. + """ + if force_flags is None: + force_flags = self.feature_flags(name) + + self.dist_log( + "testing feature '%s' with flags (%s)" % ( + name, ' '.join(force_flags) + )) + # Each CPU feature must have C source code contains at + # least one intrinsic or instruction related to this feature. + test_path = os.path.join( + self.conf_check_path, "cpu_%s.c" % name.lower() + ) + if not os.path.exists(test_path): + self.dist_fatal("feature test file is not exist", test_path) + + test = self.dist_test( + test_path, force_flags + self.cc_flags["werror"], macros=macros + ) + if not test: + self.dist_log("testing failed", stderr=True) + return test + + @_Cache.me + def feature_is_supported(self, name, force_flags=None, macros=[]): + """ + Check if a certain CPU feature is supported by the platform and compiler. + + Parameters + ---------- + name : str + CPU feature name in uppercase. + + force_flags : list or None, optional + If None(default), default compiler flags for every CPU feature will + be used during test. + + macros : list of tuples, optional + A list of C macro definitions. + """ + assert(name.isupper()) + assert(force_flags is None or isinstance(force_flags, list)) + + supported = name in self.feature_supported + if supported: + for impl in self.feature_implies(name): + if not self.feature_test(impl, force_flags, macros=macros): + return False + if not self.feature_test(name, force_flags, macros=macros): + return False + return supported + + @_Cache.me + def feature_can_autovec(self, name): + """ + check if the feature can be auto-vectorized by the compiler + """ + assert(isinstance(name, str)) + d = self.feature_supported[name] + can = d.get("autovec", None) + if can is None: + valid_flags = [ + self.cc_test_flags([f]) for f in d.get("flags", []) + ] + can = valid_flags and any(valid_flags) + return can + + @_Cache.me + def feature_extra_checks(self, name): + """ + Return a list of supported extra checks after testing them against + the compiler. + + Parameters + ---------- + names : str + CPU feature name in uppercase. + """ + assert isinstance(name, str) + d = self.feature_supported[name] + extra_checks = d.get("extra_checks", []) + if not extra_checks: + return [] + + self.dist_log("Testing extra checks for feature '%s'" % name, extra_checks) + flags = self.feature_flags(name) + available = [] + not_available = [] + for chk in extra_checks: + test_path = os.path.join( + self.conf_check_path, "extra_%s.c" % chk.lower() + ) + if not os.path.exists(test_path): + self.dist_fatal("extra check file does not exist", test_path) + + is_supported = self.dist_test(test_path, flags + self.cc_flags["werror"]) + if is_supported: + available.append(chk) + else: + not_available.append(chk) + + if not_available: + self.dist_log("testing failed for checks", not_available, stderr=True) + return available + + + def feature_c_preprocessor(self, feature_name, tabs=0): + """ + Generate C preprocessor definitions and include headers of a CPU feature. + + Parameters + ---------- + 'feature_name': str + CPU feature name in uppercase. + 'tabs': int + if > 0, align the generated strings to the right depend on number of tabs. + + Returns + ------- + str, generated C preprocessor + + Examples + -------- + >>> self.feature_c_preprocessor("SSE3") + /** SSE3 **/ + #define NPY_HAVE_SSE3 1 + #include + """ + assert(feature_name.isupper()) + feature = self.feature_supported.get(feature_name) + assert(feature is not None) + + prepr = [ + "/** %s **/" % feature_name, + "#define %sHAVE_%s 1" % (self.conf_c_prefix, feature_name) + ] + prepr += [ + "#include <%s>" % h for h in feature.get("headers", []) + ] + + extra_defs = feature.get("group", []) + extra_defs += self.feature_extra_checks(feature_name) + for edef in extra_defs: + # Guard extra definitions in case of duplicate with + # another feature + prepr += [ + "#ifndef %sHAVE_%s" % (self.conf_c_prefix, edef), + "\t#define %sHAVE_%s 1" % (self.conf_c_prefix, edef), + "#endif", + ] + + if tabs > 0: + prepr = [('\t'*tabs) + l for l in prepr] + return '\n'.join(prepr) + +class _Parse: + """A helper class that parsing main arguments of `CCompilerOpt`, + also parsing configuration statements in dispatch-able sources. + + Parameters + ---------- + cpu_baseline : str or None + minimal set of required CPU features or special options. + + cpu_dispatch : str or None + dispatched set of additional CPU features or special options. + + Special options can be: + - **MIN**: Enables the minimum CPU features that utilized via `_Config.conf_min_features` + - **MAX**: Enables all supported CPU features by the Compiler and platform. + - **NATIVE**: Enables all CPU features that supported by the current machine. + - **NONE**: Enables nothing + - **Operand +/-**: remove or add features, useful with options **MAX**, **MIN** and **NATIVE**. + NOTE: operand + is only added for nominal reason. + + NOTES: + - Case-insensitive among all CPU features and special options. + - Comma or space can be used as a separator. + - If the CPU feature is not supported by the user platform or compiler, + it will be skipped rather than raising a fatal error. + - Any specified CPU features to 'cpu_dispatch' will be skipped if its part of CPU baseline features + - 'cpu_baseline' force enables implied features. + + Attributes + ---------- + parse_baseline_names : list + Final CPU baseline's feature names(sorted from low to high) + parse_baseline_flags : list + Compiler flags of baseline features + parse_dispatch_names : list + Final CPU dispatch-able feature names(sorted from low to high) + parse_target_groups : dict + Dictionary containing initialized target groups that configured + through class attribute `conf_target_groups`. + + The key is represent the group name and value is a tuple + contains three items : + - bool, True if group has the 'baseline' option. + - list, list of CPU features. + - list, list of extra compiler flags. + + """ + def __init__(self, cpu_baseline, cpu_dispatch): + self._parse_policies = dict( + # POLICY NAME, (HAVE, NOT HAVE, [DEB]) + KEEP_BASELINE = ( + None, self._parse_policy_not_keepbase, + [] + ), + KEEP_SORT = ( + self._parse_policy_keepsort, + self._parse_policy_not_keepsort, + [] + ), + MAXOPT = ( + self._parse_policy_maxopt, None, + [] + ), + WERROR = ( + self._parse_policy_werror, None, + [] + ), + AUTOVEC = ( + self._parse_policy_autovec, None, + ["MAXOPT"] + ) + ) + if hasattr(self, "parse_is_cached"): + return + + self.parse_baseline_names = [] + self.parse_baseline_flags = [] + self.parse_dispatch_names = [] + self.parse_target_groups = {} + + if self.cc_noopt: + # skip parsing baseline and dispatch args and keep parsing target groups + cpu_baseline = cpu_dispatch = None + + self.dist_log("check requested baseline") + if cpu_baseline is not None: + cpu_baseline = self._parse_arg_features("cpu_baseline", cpu_baseline) + baseline_names = self.feature_names(cpu_baseline) + self.parse_baseline_flags = self.feature_flags(baseline_names) + self.parse_baseline_names = self.feature_sorted( + self.feature_implies_c(baseline_names) + ) + + self.dist_log("check requested dispatch-able features") + if cpu_dispatch is not None: + cpu_dispatch_ = self._parse_arg_features("cpu_dispatch", cpu_dispatch) + cpu_dispatch = { + f for f in cpu_dispatch_ + if f not in self.parse_baseline_names + } + conflict_baseline = cpu_dispatch_.difference(cpu_dispatch) + self.parse_dispatch_names = self.feature_sorted( + self.feature_names(cpu_dispatch) + ) + if len(conflict_baseline) > 0: + self.dist_log( + "skip features", conflict_baseline, "since its part of baseline" + ) + + self.dist_log("initialize targets groups") + for group_name, tokens in self.conf_target_groups.items(): + self.dist_log("parse target group", group_name) + GROUP_NAME = group_name.upper() + if not tokens or not tokens.strip(): + # allow empty groups, useful in case if there's a need + # to disable certain group since '_parse_target_tokens()' + # requires at least one valid target + self.parse_target_groups[GROUP_NAME] = ( + False, [], [] + ) + continue + has_baseline, features, extra_flags = \ + self._parse_target_tokens(tokens) + self.parse_target_groups[GROUP_NAME] = ( + has_baseline, features, extra_flags + ) + + self.parse_is_cached = True + + def parse_targets(self, source): + """ + Fetch and parse configuration statements that required for + defining the targeted CPU features, statements should be declared + in the top of source in between **C** comment and start + with a special mark **@targets**. + + Configuration statements are sort of keywords representing + CPU features names, group of statements and policies, combined + together to determine the required optimization. + + Parameters + ---------- + source : str + the path of **C** source file. + + Returns + ------- + - bool, True if group has the 'baseline' option + - list, list of CPU features + - list, list of extra compiler flags + """ + self.dist_log("looking for '@targets' inside -> ", source) + # get lines between /*@targets and */ + with open(source) as fd: + tokens = "" + max_to_reach = 1000 # good enough, isn't? + start_with = "@targets" + start_pos = -1 + end_with = "*/" + end_pos = -1 + for current_line, line in enumerate(fd): + if current_line == max_to_reach: + self.dist_fatal("reached the max of lines") + break + if start_pos == -1: + start_pos = line.find(start_with) + if start_pos == -1: + continue + start_pos += len(start_with) + tokens += line + end_pos = line.find(end_with) + if end_pos != -1: + end_pos += len(tokens) - len(line) + break + + if start_pos == -1: + self.dist_fatal("expected to find '%s' within a C comment" % start_with) + if end_pos == -1: + self.dist_fatal("expected to end with '%s'" % end_with) + + tokens = tokens[start_pos:end_pos] + return self._parse_target_tokens(tokens) + + _parse_regex_arg = re.compile(r'\s|,|([+-])') + def _parse_arg_features(self, arg_name, req_features): + if not isinstance(req_features, str): + self.dist_fatal("expected a string in '%s'" % arg_name) + + final_features = set() + # space and comma can be used as a separator + tokens = list(filter(None, re.split(self._parse_regex_arg, req_features))) + append = True # append is the default + for tok in tokens: + if tok[0] in ("#", "$"): + self.dist_fatal( + arg_name, "target groups and policies " + "aren't allowed from arguments, " + "only from dispatch-able sources" + ) + if tok == '+': + append = True + continue + if tok == '-': + append = False + continue + + TOK = tok.upper() # we use upper-case internally + features_to = set() + if TOK == "NONE": + pass + elif TOK == "NATIVE": + native = self.cc_flags["native"] + if not native: + self.dist_fatal(arg_name, + "native option isn't supported by the compiler" + ) + features_to = self.feature_names( + force_flags=native, macros=[("DETECT_FEATURES", 1)] + ) + elif TOK == "MAX": + features_to = self.feature_supported.keys() + elif TOK == "MIN": + features_to = self.feature_min + else: + if TOK in self.feature_supported: + features_to.add(TOK) + else: + if not self.feature_is_exist(TOK): + self.dist_fatal(arg_name, + ", '%s' isn't a known feature or option" % tok + ) + if append: + final_features = final_features.union(features_to) + else: + final_features = final_features.difference(features_to) + + append = True # back to default + + return final_features + + _parse_regex_target = re.compile(r'\s|[*,/]|([()])') + def _parse_target_tokens(self, tokens): + assert(isinstance(tokens, str)) + final_targets = [] # to keep it sorted as specified + extra_flags = [] + has_baseline = False + + skipped = set() + policies = set() + multi_target = None + + tokens = list(filter(None, re.split(self._parse_regex_target, tokens))) + if not tokens: + self.dist_fatal("expected one token at least") + + for tok in tokens: + TOK = tok.upper() + ch = tok[0] + if ch in ('+', '-'): + self.dist_fatal( + "+/- are 'not' allowed from target's groups or @targets, " + "only from cpu_baseline and cpu_dispatch parms" + ) + elif ch == '$': + if multi_target is not None: + self.dist_fatal( + "policies aren't allowed inside multi-target '()'" + ", only CPU features" + ) + policies.add(self._parse_token_policy(TOK)) + elif ch == '#': + if multi_target is not None: + self.dist_fatal( + "target groups aren't allowed inside multi-target '()'" + ", only CPU features" + ) + has_baseline, final_targets, extra_flags = \ + self._parse_token_group(TOK, has_baseline, final_targets, extra_flags) + elif ch == '(': + if multi_target is not None: + self.dist_fatal("unclosed multi-target, missing ')'") + multi_target = set() + elif ch == ')': + if multi_target is None: + self.dist_fatal("multi-target opener '(' wasn't found") + targets = self._parse_multi_target(multi_target) + if targets is None: + skipped.add(tuple(multi_target)) + else: + if len(targets) == 1: + targets = targets[0] + if targets and targets not in final_targets: + final_targets.append(targets) + multi_target = None # back to default + else: + if TOK == "BASELINE": + if multi_target is not None: + self.dist_fatal("baseline isn't allowed inside multi-target '()'") + has_baseline = True + continue + + if multi_target is not None: + multi_target.add(TOK) + continue + + if not self.feature_is_exist(TOK): + self.dist_fatal("invalid target name '%s'" % TOK) + + is_enabled = ( + TOK in self.parse_baseline_names or + TOK in self.parse_dispatch_names + ) + if is_enabled: + if TOK not in final_targets: + final_targets.append(TOK) + continue + + skipped.add(TOK) + + if multi_target is not None: + self.dist_fatal("unclosed multi-target, missing ')'") + if skipped: + self.dist_log( + "skip targets", skipped, + "not part of baseline or dispatch-able features" + ) + + final_targets = self.feature_untied(final_targets) + + # add polices dependencies + for p in list(policies): + _, _, deps = self._parse_policies[p] + for d in deps: + if d in policies: + continue + self.dist_log( + "policy '%s' force enables '%s'" % ( + p, d + )) + policies.add(d) + + # release policies filtrations + for p, (have, nhave, _) in self._parse_policies.items(): + func = None + if p in policies: + func = have + self.dist_log("policy '%s' is ON" % p) + else: + func = nhave + if not func: + continue + has_baseline, final_targets, extra_flags = func( + has_baseline, final_targets, extra_flags + ) + + return has_baseline, final_targets, extra_flags + + def _parse_token_policy(self, token): + """validate policy token""" + if len(token) <= 1 or token[-1:] == token[0]: + self.dist_fatal("'$' must stuck in the begin of policy name") + token = token[1:] + if token not in self._parse_policies: + self.dist_fatal( + "'%s' is an invalid policy name, available policies are" % token, + self._parse_policies.keys() + ) + return token + + def _parse_token_group(self, token, has_baseline, final_targets, extra_flags): + """validate group token""" + if len(token) <= 1 or token[-1:] == token[0]: + self.dist_fatal("'#' must stuck in the begin of group name") + + token = token[1:] + ghas_baseline, gtargets, gextra_flags = self.parse_target_groups.get( + token, (False, None, []) + ) + if gtargets is None: + self.dist_fatal( + "'%s' is an invalid target group name, " % token + \ + "available target groups are", + self.parse_target_groups.keys() + ) + if ghas_baseline: + has_baseline = True + # always keep sorting as specified + final_targets += [f for f in gtargets if f not in final_targets] + extra_flags += [f for f in gextra_flags if f not in extra_flags] + return has_baseline, final_targets, extra_flags + + def _parse_multi_target(self, targets): + """validate multi targets that defined between parentheses()""" + # remove any implied features and keep the origins + if not targets: + self.dist_fatal("empty multi-target '()'") + if not all([ + self.feature_is_exist(tar) for tar in targets + ]) : + self.dist_fatal("invalid target name in multi-target", targets) + if not all([ + ( + tar in self.parse_baseline_names or + tar in self.parse_dispatch_names + ) + for tar in targets + ]) : + return None + targets = self.feature_ahead(targets) + if not targets: + return None + # force sort multi targets, so it can be comparable + targets = self.feature_sorted(targets) + targets = tuple(targets) # hashable + return targets + + def _parse_policy_not_keepbase(self, has_baseline, final_targets, extra_flags): + """skip all baseline features""" + skipped = [] + for tar in final_targets[:]: + is_base = False + if isinstance(tar, str): + is_base = tar in self.parse_baseline_names + else: + # multi targets + is_base = all([ + f in self.parse_baseline_names + for f in tar + ]) + if is_base: + skipped.append(tar) + final_targets.remove(tar) + + if skipped: + self.dist_log("skip baseline features", skipped) + + return has_baseline, final_targets, extra_flags + + def _parse_policy_keepsort(self, has_baseline, final_targets, extra_flags): + """leave a notice that $keep_sort is on""" + self.dist_log( + "policy 'keep_sort' is on, dispatch-able targets", final_targets, "\n" + "are 'not' sorted depend on the highest interest but" + "as specified in the dispatch-able source or the extra group" + ) + return has_baseline, final_targets, extra_flags + + def _parse_policy_not_keepsort(self, has_baseline, final_targets, extra_flags): + """sorted depend on the highest interest""" + final_targets = self.feature_sorted(final_targets, reverse=True) + return has_baseline, final_targets, extra_flags + + def _parse_policy_maxopt(self, has_baseline, final_targets, extra_flags): + """append the compiler optimization flags""" + if self.cc_has_debug: + self.dist_log("debug mode is detected, policy 'maxopt' is skipped.") + elif self.cc_noopt: + self.dist_log("optimization is disabled, policy 'maxopt' is skipped.") + else: + flags = self.cc_flags["opt"] + if not flags: + self.dist_log( + "current compiler doesn't support optimization flags, " + "policy 'maxopt' is skipped", stderr=True + ) + else: + extra_flags += flags + return has_baseline, final_targets, extra_flags + + def _parse_policy_werror(self, has_baseline, final_targets, extra_flags): + """force warnings to treated as errors""" + flags = self.cc_flags["werror"] + if not flags: + self.dist_log( + "current compiler doesn't support werror flags, " + "warnings will 'not' treated as errors", stderr=True + ) + else: + self.dist_log("compiler warnings are treated as errors") + extra_flags += flags + return has_baseline, final_targets, extra_flags + + def _parse_policy_autovec(self, has_baseline, final_targets, extra_flags): + """skip features that has no auto-vectorized support by compiler""" + skipped = [] + for tar in final_targets[:]: + if isinstance(tar, str): + can = self.feature_can_autovec(tar) + else: # multiple target + can = all([ + self.feature_can_autovec(t) + for t in tar + ]) + if not can: + final_targets.remove(tar) + skipped.append(tar) + + if skipped: + self.dist_log("skip non auto-vectorized features", skipped) + + return has_baseline, final_targets, extra_flags + +class CCompilerOpt(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse): + """ + A helper class for `CCompiler` aims to provide extra build options + to effectively control of compiler optimizations that are directly + related to CPU features. + """ + def __init__(self, ccompiler, cpu_baseline="min", cpu_dispatch="max", cache_path=None): + _Config.__init__(self) + _Distutils.__init__(self, ccompiler) + _Cache.__init__(self, cache_path, self.dist_info(), cpu_baseline, cpu_dispatch) + _CCompiler.__init__(self) + _Feature.__init__(self) + if not self.cc_noopt and self.cc_has_native: + self.dist_log( + "native flag is specified through environment variables. " + "force cpu-baseline='native'" + ) + cpu_baseline = "native" + _Parse.__init__(self, cpu_baseline, cpu_dispatch) + # keep the requested features untouched, need it later for report + # and trace purposes + self._requested_baseline = cpu_baseline + self._requested_dispatch = cpu_dispatch + # key is the dispatch-able source and value is a tuple + # contains two items (has_baseline[boolean], dispatched-features[list]) + self.sources_status = getattr(self, "sources_status", {}) + # every instance should has a separate one + self.cache_private.add("sources_status") + # set it at the end to make sure the cache writing was done after init + # this class + self.hit_cache = hasattr(self, "hit_cache") + + def is_cached(self): + """ + Returns True if the class loaded from the cache file + """ + return self.cache_infile and self.hit_cache + + def cpu_baseline_flags(self): + """ + Returns a list of final CPU baseline compiler flags + """ + return self.parse_baseline_flags + + def cpu_baseline_names(self): + """ + return a list of final CPU baseline feature names + """ + return self.parse_baseline_names + + def cpu_dispatch_names(self): + """ + return a list of final CPU dispatch feature names + """ + return self.parse_dispatch_names + + def try_dispatch(self, sources, src_dir=None, ccompiler=None, **kwargs): + """ + Compile one or more dispatch-able sources and generates object files, + also generates abstract C config headers and macros that + used later for the final runtime dispatching process. + + The mechanism behind it is to takes each source file that specified + in 'sources' and branching it into several files depend on + special configuration statements that must be declared in the + top of each source which contains targeted CPU features, + then it compiles every branched source with the proper compiler flags. + + Parameters + ---------- + sources : list + Must be a list of dispatch-able sources file paths, + and configuration statements must be declared inside + each file. + + src_dir : str + Path of parent directory for the generated headers and wrapped sources. + If None(default) the files will generated in-place. + + ccompiler : CCompiler + Distutils `CCompiler` instance to be used for compilation. + If None (default), the provided instance during the initialization + will be used instead. + + **kwargs : any + Arguments to pass on to the `CCompiler.compile()` + + Returns + ------- + list : generated object files + + Raises + ------ + CompileError + Raises by `CCompiler.compile()` on compiling failure. + DistutilsError + Some errors during checking the sanity of configuration statements. + + See Also + -------- + parse_targets : + Parsing the configuration statements of dispatch-able sources. + """ + to_compile = {} + baseline_flags = self.cpu_baseline_flags() + include_dirs = kwargs.setdefault("include_dirs", []) + + for src in sources: + output_dir = os.path.dirname(src) + if src_dir: + if not output_dir.startswith(src_dir): + output_dir = os.path.join(src_dir, output_dir) + if output_dir not in include_dirs: + # To allow including the generated config header(*.dispatch.h) + # by the dispatch-able sources + include_dirs.append(output_dir) + + has_baseline, targets, extra_flags = self.parse_targets(src) + nochange = self._generate_config(output_dir, src, targets, has_baseline) + for tar in targets: + tar_src = self._wrap_target(output_dir, src, tar, nochange=nochange) + flags = tuple(extra_flags + self.feature_flags(tar)) + to_compile.setdefault(flags, []).append(tar_src) + + if has_baseline: + flags = tuple(extra_flags + baseline_flags) + to_compile.setdefault(flags, []).append(src) + + self.sources_status[src] = (has_baseline, targets) + + # For these reasons, the sources are compiled in a separate loop: + # - Gathering all sources with the same flags to benefit from + # the parallel compiling as much as possible. + # - To generate all config headers of the dispatchable sources, + # before the compilation in case if there are dependency relationships + # among them. + objects = [] + for flags, srcs in to_compile.items(): + objects += self.dist_compile( + srcs, list(flags), ccompiler=ccompiler, **kwargs + ) + return objects + + def generate_dispatch_header(self, header_path): + """ + Generate the dispatch header which contains the #definitions and headers + for platform-specific instruction-sets for the enabled CPU baseline and + dispatch-able features. + + Its highly recommended to take a look at the generated header + also the generated source files via `try_dispatch()` + in order to get the full picture. + """ + self.dist_log("generate CPU dispatch header: (%s)" % header_path) + + baseline_names = self.cpu_baseline_names() + dispatch_names = self.cpu_dispatch_names() + baseline_len = len(baseline_names) + dispatch_len = len(dispatch_names) + + header_dir = os.path.dirname(header_path) + if not os.path.exists(header_dir): + self.dist_log( + f"dispatch header dir {header_dir} does not exist, creating it", + stderr=True + ) + os.makedirs(header_dir) + + with open(header_path, 'w') as f: + baseline_calls = ' \\\n'.join([ + ( + "\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))" + ) % (self.conf_c_prefix, f) + for f in baseline_names + ]) + dispatch_calls = ' \\\n'.join([ + ( + "\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))" + ) % (self.conf_c_prefix, f) + for f in dispatch_names + ]) + f.write(textwrap.dedent("""\ + /* + * AUTOGENERATED DON'T EDIT + * Please make changes to the code generator (distutils/ccompiler_opt.py) + */ + #define {pfx}WITH_CPU_BASELINE "{baseline_str}" + #define {pfx}WITH_CPU_DISPATCH "{dispatch_str}" + #define {pfx}WITH_CPU_BASELINE_N {baseline_len} + #define {pfx}WITH_CPU_DISPATCH_N {dispatch_len} + #define {pfx}WITH_CPU_EXPAND_(X) X + #define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \\ + {baseline_calls} + #define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \\ + {dispatch_calls} + """).format( + pfx=self.conf_c_prefix, baseline_str=" ".join(baseline_names), + dispatch_str=" ".join(dispatch_names), baseline_len=baseline_len, + dispatch_len=dispatch_len, baseline_calls=baseline_calls, + dispatch_calls=dispatch_calls + )) + baseline_pre = '' + for name in baseline_names: + baseline_pre += self.feature_c_preprocessor(name, tabs=1) + '\n' + + dispatch_pre = '' + for name in dispatch_names: + dispatch_pre += textwrap.dedent("""\ + #ifdef {pfx}CPU_TARGET_{name} + {pre} + #endif /*{pfx}CPU_TARGET_{name}*/ + """).format( + pfx=self.conf_c_prefix_, name=name, pre=self.feature_c_preprocessor( + name, tabs=1 + )) + + f.write(textwrap.dedent("""\ + /******* baseline features *******/ + {baseline_pre} + /******* dispatch features *******/ + {dispatch_pre} + """).format( + pfx=self.conf_c_prefix_, baseline_pre=baseline_pre, + dispatch_pre=dispatch_pre + )) + + def report(self, full=False): + report = [] + platform_rows = [] + baseline_rows = [] + dispatch_rows = [] + report.append(("Platform", platform_rows)) + report.append(("", "")) + report.append(("CPU baseline", baseline_rows)) + report.append(("", "")) + report.append(("CPU dispatch", dispatch_rows)) + + ########## platform ########## + platform_rows.append(("Architecture", ( + "unsupported" if self.cc_on_noarch else self.cc_march) + )) + platform_rows.append(("Compiler", ( + "unix-like" if self.cc_is_nocc else self.cc_name) + )) + ########## baseline ########## + if self.cc_noopt: + baseline_rows.append(("Requested", "optimization disabled")) + else: + baseline_rows.append(("Requested", repr(self._requested_baseline))) + + baseline_names = self.cpu_baseline_names() + baseline_rows.append(( + "Enabled", (' '.join(baseline_names) if baseline_names else "none") + )) + baseline_flags = self.cpu_baseline_flags() + baseline_rows.append(( + "Flags", (' '.join(baseline_flags) if baseline_flags else "none") + )) + extra_checks = [] + for name in baseline_names: + extra_checks += self.feature_extra_checks(name) + baseline_rows.append(( + "Extra checks", (' '.join(extra_checks) if extra_checks else "none") + )) + + ########## dispatch ########## + if self.cc_noopt: + baseline_rows.append(("Requested", "optimization disabled")) + else: + dispatch_rows.append(("Requested", repr(self._requested_dispatch))) + + dispatch_names = self.cpu_dispatch_names() + dispatch_rows.append(( + "Enabled", (' '.join(dispatch_names) if dispatch_names else "none") + )) + ########## Generated ########## + # TODO: + # - collect object names from 'try_dispatch()' + # then get size of each object and printed + # - give more details about the features that not + # generated due compiler support + # - find a better output's design. + # + target_sources = {} + for source, (_, targets) in self.sources_status.items(): + for tar in targets: + target_sources.setdefault(tar, []).append(source) + + if not full or not target_sources: + generated = "" + for tar in self.feature_sorted(target_sources): + sources = target_sources[tar] + name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar) + generated += name + "[%d] " % len(sources) + dispatch_rows.append(("Generated", generated[:-1] if generated else "none")) + else: + dispatch_rows.append(("Generated", '')) + for tar in self.feature_sorted(target_sources): + sources = target_sources[tar] + pretty_name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar) + flags = ' '.join(self.feature_flags(tar)) + implies = ' '.join(self.feature_sorted(self.feature_implies(tar))) + detect = ' '.join(self.feature_detect(tar)) + extra_checks = [] + for name in ((tar,) if isinstance(tar, str) else tar): + extra_checks += self.feature_extra_checks(name) + extra_checks = (' '.join(extra_checks) if extra_checks else "none") + + dispatch_rows.append(('', '')) + dispatch_rows.append((pretty_name, implies)) + dispatch_rows.append(("Flags", flags)) + dispatch_rows.append(("Extra checks", extra_checks)) + dispatch_rows.append(("Detect", detect)) + for src in sources: + dispatch_rows.append(("", src)) + + ############################### + # TODO: add support for 'markdown' format + text = [] + secs_len = [len(secs) for secs, _ in report] + cols_len = [len(col) for _, rows in report for col, _ in rows] + tab = ' ' * 2 + pad = max(max(secs_len), max(cols_len)) + for sec, rows in report: + if not sec: + text.append("") # empty line + continue + sec += ' ' * (pad - len(sec)) + text.append(sec + tab + ': ') + for col, val in rows: + col += ' ' * (pad - len(col)) + text.append(tab + col + ': ' + val) + + return '\n'.join(text) + + def _wrap_target(self, output_dir, dispatch_src, target, nochange=False): + assert(isinstance(target, (str, tuple))) + if isinstance(target, str): + ext_name = target_name = target + else: + # multi-target + ext_name = '.'.join(target) + target_name = '__'.join(target) + + wrap_path = os.path.join(output_dir, os.path.basename(dispatch_src)) + wrap_path = "{0}.{2}{1}".format(*os.path.splitext(wrap_path), ext_name.lower()) + if nochange and os.path.exists(wrap_path): + return wrap_path + + self.dist_log("wrap dispatch-able target -> ", wrap_path) + # sorting for readability + features = self.feature_sorted(self.feature_implies_c(target)) + target_join = "#define %sCPU_TARGET_" % self.conf_c_prefix_ + target_defs = [target_join + f for f in features] + target_defs = '\n'.join(target_defs) + + with open(wrap_path, "w") as fd: + fd.write(textwrap.dedent("""\ + /** + * AUTOGENERATED DON'T EDIT + * Please make changes to the code generator \ + (distutils/ccompiler_opt.py) + */ + #define {pfx}CPU_TARGET_MODE + #define {pfx}CPU_TARGET_CURRENT {target_name} + {target_defs} + #include "{path}" + """).format( + pfx=self.conf_c_prefix_, target_name=target_name, + path=os.path.abspath(dispatch_src), target_defs=target_defs + )) + return wrap_path + + def _generate_config(self, output_dir, dispatch_src, targets, has_baseline=False): + config_path = os.path.basename(dispatch_src) + config_path = os.path.splitext(config_path)[0] + '.h' + config_path = os.path.join(output_dir, config_path) + # check if targets didn't change to avoid recompiling + cache_hash = self.cache_hash(targets, has_baseline) + try: + with open(config_path) as f: + last_hash = f.readline().split("cache_hash:") + if len(last_hash) == 2 and int(last_hash[1]) == cache_hash: + return True + except OSError: + pass + + os.makedirs(os.path.dirname(config_path), exist_ok=True) + + self.dist_log("generate dispatched config -> ", config_path) + dispatch_calls = [] + for tar in targets: + if isinstance(tar, str): + target_name = tar + else: # multi target + target_name = '__'.join([t for t in tar]) + req_detect = self.feature_detect(tar) + req_detect = '&&'.join([ + "CHK(%s)" % f for f in req_detect + ]) + dispatch_calls.append( + "\t%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))" % ( + self.conf_c_prefix_, req_detect, target_name + )) + dispatch_calls = ' \\\n'.join(dispatch_calls) + + if has_baseline: + baseline_calls = ( + "\t%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))" + ) % self.conf_c_prefix_ + else: + baseline_calls = '' + + with open(config_path, "w") as fd: + fd.write(textwrap.dedent("""\ + // cache_hash:{cache_hash} + /** + * AUTOGENERATED DON'T EDIT + * Please make changes to the code generator (distutils/ccompiler_opt.py) + */ + #ifndef {pfx}CPU_DISPATCH_EXPAND_ + #define {pfx}CPU_DISPATCH_EXPAND_(X) X + #endif + #undef {pfx}CPU_DISPATCH_BASELINE_CALL + #undef {pfx}CPU_DISPATCH_CALL + #define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \\ + {baseline_calls} + #define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \\ + {dispatch_calls} + """).format( + pfx=self.conf_c_prefix_, baseline_calls=baseline_calls, + dispatch_calls=dispatch_calls, cache_hash=cache_hash + )) + return False + +def new_ccompiler_opt(compiler, dispatch_hpath, **kwargs): + """ + Create a new instance of 'CCompilerOpt' and generate the dispatch header + which contains the #definitions and headers of platform-specific instruction-sets for + the enabled CPU baseline and dispatch-able features. + + Parameters + ---------- + compiler : CCompiler instance + dispatch_hpath : str + path of the dispatch header + + **kwargs: passed as-is to `CCompilerOpt(...)` + Returns + ------- + new instance of CCompilerOpt + """ + opt = CCompilerOpt(compiler, **kwargs) + if not os.path.exists(dispatch_hpath) or not opt.is_cached(): + opt.generate_dispatch_header(dispatch_hpath) + return opt diff --git a/shared/package-files/76/76213eaadcf2a9e5e1c5fa8c314a9ff0da341701d70e331208e71c5420d930bd/blob b/shared/package-files/76/76213eaadcf2a9e5e1c5fa8c314a9ff0da341701d70e331208e71c5420d930bd/blob new file mode 100644 index 0000000000000000000000000000000000000000..50099eeeefec918f425c4fded9deef951a9b5a58 --- /dev/null +++ b/shared/package-files/76/76213eaadcf2a9e5e1c5fa8c314a9ff0da341701d70e331208e71c5420d930bd/blob @@ -0,0 +1,195 @@ +# Copyright 2022-2024 MetaOPT Team. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Integration with NumPy.""" + +from __future__ import annotations + +import functools +import itertools +import warnings +from typing import Any, Callable +from typing_extensions import TypeAlias # Python 3.10+ + +import numpy as np +from numpy.typing import ArrayLike + +from optree.ops import tree_flatten, tree_unflatten +from optree.typing import PyTreeSpec, PyTreeTypeVar +from optree.utils import safe_zip + + +__all__ = ['ArrayLikeTree', 'ArrayTree', 'tree_ravel'] + + +ArrayLikeTree: TypeAlias = PyTreeTypeVar('ArrayLikeTree', ArrayLike) # type: ignore[valid-type] +ArrayTree: TypeAlias = PyTreeTypeVar('ArrayTree', np.ndarray) # type: ignore[valid-type] + + +def tree_ravel( + tree: ArrayLikeTree, + is_leaf: Callable[[Any], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = '', +) -> tuple[np.ndarray, Callable[[np.ndarray], ArrayTree]]: + r"""Ravel (flatten) a pytree of arrays down to a 1D array. + + >>> tree = { + ... 'layer1': { + ... 'weight': np.arange(0, 6, dtype=np.float32).reshape((2, 3)), + ... 'bias': np.arange(6, 8, dtype=np.float32).reshape((2,)), + ... }, + ... 'layer2': { + ... 'weight': np.arange(8, 10, dtype=np.float32).reshape((1, 2)), + ... 'bias': np.arange(10, 11, dtype=np.float32).reshape((1,)) + ... }, + ... } + >>> tree + {'layer1': {'weight': array([[0., 1., 2.], + [3., 4., 5.]], dtype=float32), + 'bias': array([6., 7.], dtype=float32)}, + 'layer2': {'weight': array([[8., 9.]], dtype=float32), + 'bias': array([10.], dtype=float32)}} + >>> flat, unravel_func = tree_ravel(tree) + >>> flat + array([ 6., 7., 0., 1., 2., 3., 4., 5., 10., 8., 9.], dtype=float32) + >>> unravel_func(flat) + {'layer1': {'weight': array([[0., 1., 2.], + [3., 4., 5.]], dtype=float32), + 'bias': array([6., 7.], dtype=float32)}, + 'layer2': {'weight': array([[8., 9.]], dtype=float32), + 'bias': array([10.], dtype=float32)}} + + Args: + tree (pytree): a pytree of arrays and scalars to ravel. + is_leaf (callable, optional): An optionally specified function that will be called at each + flattening step. It should return a boolean, with :data:`True` stopping the traversal + and the whole subtree being treated as a leaf, and :data:`False` indicating the + flattening should traverse the current object. + none_is_leaf (bool, optional): Whether to treat :data:`None` as a leaf. If :data:`False`, + :data:`None` is a non-leaf node with arity 0. Thus :data:`None` is contained in the + treespec rather than in the leaves list and :data:`None` will be remain in the result + pytree. (default: :data:`False`) + namespace (str, optional): The registry namespace used for custom pytree node types. + (default: :const:`''`, i.e., the global namespace) + + Returns: + A pair ``(array, unravel_func)`` where the first element is a 1D array representing the + flattened and concatenated leaf values, with ``dtype`` determined by promoting the + ``dtype``\s of leaf values, and the second element is a callable for unflattening a 1D array + of the same length back to a pytree of the same structure as the input ``tree``. If the + input pytree is empty (i.e. has no leaves) then as a convention a 1D empty array of the + default dtype is returned in the first component of the output. + """ + leaves, treespec = tree_flatten( + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + flat, unravel_flat = _ravel_leaves(leaves) + return flat, functools.partial(_tree_unravel, treespec, unravel_flat) + + +ravel_pytree = tree_ravel + + +def _tree_unravel( + treespec: PyTreeSpec, + unravel_flat: Callable[[np.ndarray], list[np.ndarray]], + flat: np.ndarray, +) -> ArrayTree: + return tree_unflatten(treespec, unravel_flat(flat)) + + +def _ravel_leaves( + leaves: list[np.ndarray], +) -> tuple[np.ndarray, Callable[[np.ndarray], list[np.ndarray]]]: + if not leaves: + return (np.array([]), _unravel_empty) + + from_dtypes = tuple(np.result_type(leaf) for leaf in leaves) + to_dtype = np.result_type(*leaves) + sizes = tuple(np.size(leaf) for leaf in leaves) + shapes = tuple(np.shape(leaf) for leaf in leaves) + indices = tuple(itertools.accumulate(sizes)) + + if all(dt == to_dtype for dt in from_dtypes): + # Skip any dtype conversion, resulting in a dtype-polymorphic `unravel`. + raveled = np.concatenate([np.ravel(leaf) for leaf in leaves]) + return ( + raveled, + functools.partial(_unravel_leaves_single_dtype, indices, shapes), + ) + + # When there is more than one distinct input dtype, we perform type conversions and produce a + # dtype-specific unravel function. + raveled = np.concatenate([np.ravel(leaf).astype(to_dtype) for leaf in leaves]) + return ( + raveled, + functools.partial(_unravel_leaves, indices, shapes, from_dtypes, to_dtype), + ) + + +def _unravel_empty(flat: np.ndarray) -> list[np.ndarray]: + if np.shape(flat) != (0,): # type: ignore[comparison-overlap] + raise ValueError( + f'The unravel function expected an array of shape {(0,)}, ' + f'got shape {np.shape(flat)}.', + ) + return [] + + +def _unravel_leaves_single_dtype( + indices: tuple[int, ...], + shapes: tuple[tuple[int, ...]], + flat: np.ndarray, +) -> list[np.ndarray]: + if np.shape(flat) != (indices[-1],): # type: ignore[comparison-overlap] + raise ValueError( + f'The unravel function expected an array of shape {(indices[-1],)}, ' + f'got shape {np.shape(flat)}.', + ) + + chunks = np.split(flat, indices[:-1]) + return [chunk.reshape(shape) for chunk, shape in safe_zip(chunks, shapes)] + + +def _unravel_leaves( + indices: tuple[int, ...], + shapes: tuple[tuple[int, ...]], + from_dtypes: tuple[np.dtype, ...], + to_dtype: np.dtype, + flat: np.ndarray, +) -> list[np.ndarray]: + if np.shape(flat) != (indices[-1],): # type: ignore[comparison-overlap] + raise ValueError( + f'The unravel function expected an array of shape {(indices[-1],)}, ' + f'got shape {np.shape(flat)}.', + ) + array_dtype = np.result_type(flat) + if array_dtype != to_dtype: + raise ValueError( + f'The unravel function expected an array of dtype {to_dtype}, ' + f'got dtype {array_dtype}.', + ) + + chunks = np.split(flat, indices[:-1]) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # ignore complex-to-real cast warning + return [ + chunk.reshape(shape).astype(dtype) + for chunk, shape, dtype in safe_zip(chunks, shapes, from_dtypes) + ] diff --git a/shared/package-files/76/762314415f81220ec88c86fafa8d61b30b678eb478a9d014cffb44f20c52f7ac/blob b/shared/package-files/76/762314415f81220ec88c86fafa8d61b30b678eb478a9d014cffb44f20c52f7ac/blob new file mode 100644 index 0000000000000000000000000000000000000000..d9cbe22cde35ff08abb0f1261f2173091490e02f --- /dev/null +++ b/shared/package-files/76/762314415f81220ec88c86fafa8d61b30b678eb478a9d014cffb44f20c52f7ac/blob @@ -0,0 +1,155 @@ +# SPDX-License-Identifier: MIT + + +import functools +import types + +from ._make import _make_ne + + +_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} + + +def cmp_using( + eq=None, + lt=None, + le=None, + gt=None, + ge=None, + require_same_type=True, + class_name="Comparable", +): + """ + Create a class that can be passed into `attrs.field`'s ``eq``, ``order``, + and ``cmp`` arguments to customize field comparison. + + The resulting class will have a full set of ordering methods if at least + one of ``{lt, le, gt, ge}`` and ``eq`` are provided. + + :param Optional[callable] eq: `callable` used to evaluate equality of two + objects. + :param Optional[callable] lt: `callable` used to evaluate whether one + object is less than another object. + :param Optional[callable] le: `callable` used to evaluate whether one + object is less than or equal to another object. + :param Optional[callable] gt: `callable` used to evaluate whether one + object is greater than another object. + :param Optional[callable] ge: `callable` used to evaluate whether one + object is greater than or equal to another object. + + :param bool require_same_type: When `True`, equality and ordering methods + will return `NotImplemented` if objects are not of the same type. + + :param Optional[str] class_name: Name of class. Defaults to 'Comparable'. + + See `comparison` for more details. + + .. versionadded:: 21.1.0 + """ + + body = { + "__slots__": ["value"], + "__init__": _make_init(), + "_requirements": [], + "_is_comparable_to": _is_comparable_to, + } + + # Add operations. + num_order_functions = 0 + has_eq_function = False + + if eq is not None: + has_eq_function = True + body["__eq__"] = _make_operator("eq", eq) + body["__ne__"] = _make_ne() + + if lt is not None: + num_order_functions += 1 + body["__lt__"] = _make_operator("lt", lt) + + if le is not None: + num_order_functions += 1 + body["__le__"] = _make_operator("le", le) + + if gt is not None: + num_order_functions += 1 + body["__gt__"] = _make_operator("gt", gt) + + if ge is not None: + num_order_functions += 1 + body["__ge__"] = _make_operator("ge", ge) + + type_ = types.new_class( + class_name, (object,), {}, lambda ns: ns.update(body) + ) + + # Add same type requirement. + if require_same_type: + type_._requirements.append(_check_same_type) + + # Add total ordering if at least one operation was defined. + if 0 < num_order_functions < 4: + if not has_eq_function: + # functools.total_ordering requires __eq__ to be defined, + # so raise early error here to keep a nice stack. + raise ValueError( + "eq must be define is order to complete ordering from " + "lt, le, gt, ge." + ) + type_ = functools.total_ordering(type_) + + return type_ + + +def _make_init(): + """ + Create __init__ method. + """ + + def __init__(self, value): + """ + Initialize object with *value*. + """ + self.value = value + + return __init__ + + +def _make_operator(name, func): + """ + Create operator method. + """ + + def method(self, other): + if not self._is_comparable_to(other): + return NotImplemented + + result = func(self.value, other.value) + if result is NotImplemented: + return NotImplemented + + return result + + method.__name__ = f"__{name}__" + method.__doc__ = ( + f"Return a {_operation_names[name]} b. Computed by attrs." + ) + + return method + + +def _is_comparable_to(self, other): + """ + Check whether `other` is comparable to `self`. + """ + for func in self._requirements: + if not func(self, other): + return False + return True + + +def _check_same_type(self, other): + """ + Return True if *self* and *other* are of the same type, False otherwise. + """ + return other.value.__class__ is self.value.__class__ diff --git a/shared/package-files/76/762480c696d883c3de1fbe5038413e09110ef29dfd7f80592b6746ca72432887/blob b/shared/package-files/76/762480c696d883c3de1fbe5038413e09110ef29dfd7f80592b6746ca72432887/blob new file mode 100644 index 0000000000000000000000000000000000000000..e032ddd9c673be3bc8790adad3bdae1839127050 --- /dev/null +++ b/shared/package-files/76/762480c696d883c3de1fbe5038413e09110ef29dfd7f80592b6746ca72432887/blob @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.sparse.linalg` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres', + 'lgmres', 'lsmr', 'lsqr', + 'minres', 'qmr', 'tfqmr', 'test' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="sparse.linalg", module="isolve", + private_modules=["_isolve"], all=__all__, + attribute=name) diff --git a/shared/package-files/76/76259af103e3aa567b0612b327158ba9f1473a01375d84567ded3a51bbe05a55/blob b/shared/package-files/76/76259af103e3aa567b0612b327158ba9f1473a01375d84567ded3a51bbe05a55/blob new file mode 100644 index 0000000000000000000000000000000000000000..84a648f432e58a49474fde7837280068be2b68a8 --- /dev/null +++ b/shared/package-files/76/76259af103e3aa567b0612b327158ba9f1473a01375d84567ded3a51bbe05a55/blob @@ -0,0 +1,54 @@ +import sys +from logging import Logger +from types import TracebackType +from typing import Optional, Type, Union + +def logger() -> Logger: ... + +class Timeout(TimeoutError): + def __init__(self, lock_file: str) -> None: ... + def __str__(self) -> str: ... + +class _Acquire_ReturnProxy: + def __init__(self, lock: str) -> None: ... + def __enter__(self) -> str: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], traceback: Optional[TracebackType] + ) -> None: ... + +class BaseFileLock: + def __init__(self, lock_file: str, timeout: Union[float, int, str] = ...) -> None: ... + @property + def lock_file(self) -> str: ... + @property + def timeout(self) -> float: ... + @timeout.setter + def timeout(self, value: Union[int, str, float]) -> None: ... + @property + def is_locked(self) -> bool: ... + def acquire(self, timeout: Optional[float] = ..., poll_intervall: float = ...) -> _Acquire_ReturnProxy: ... + def release(self, force: bool = ...) -> None: ... + def __enter__(self) -> BaseFileLock: ... + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], traceback: Optional[TracebackType] + ) -> None: ... + def __del__(self) -> None: ... + +class WindowsFileLock(BaseFileLock): + def _acquire(self) -> None: ... + def _release(self) -> None: ... + +class UnixFileLock(BaseFileLock): + def _acquire(self) -> None: ... + def _release(self) -> None: ... + +class SoftFileLock(BaseFileLock): + def _acquire(self) -> None: ... + def _release(self) -> None: ... + +if sys.platform == "win32": + FileLock = WindowsFileLock +elif sys.platform == "linux" or sys.platform == "darwin": + FileLock = UnixFileLock +else: + FileLock = SoftFileLock diff --git a/shared/package-files/76/76265bbfbcec3dc2f051f76cae8111c02eabb9aa8d52fccd04fc779d9d9753ad/blob b/shared/package-files/76/76265bbfbcec3dc2f051f76cae8111c02eabb9aa8d52fccd04fc779d9d9753ad/blob new file mode 100644 index 0000000000000000000000000000000000000000..9a9165fbbea7fe6e036e4d5ff742f6d2117aed47 --- /dev/null +++ b/shared/package-files/76/76265bbfbcec3dc2f051f76cae8111c02eabb9aa8d52fccd04fc779d9d9753ad/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +TORCH_API ::std::tuple sort(const at::Tensor & self, int64_t dim=-1, bool descending=false); +TORCH_API ::std::tuple sort_out(const at::Tensor & self, int64_t dim, bool descending, at::Tensor & values, at::Tensor & indices); +struct TORCH_API structured_sort_stable_out : public at::meta::structured_sort_stable { +void impl(const at::Tensor & self, c10::optional stable, int64_t dim, bool descending, const at::Tensor & values, const at::Tensor & indices); +}; +TORCH_API ::std::tuple sort_quantized_cpu_stable(const at::Tensor & self, c10::optional stable, int64_t dim=-1, bool descending=false); +TORCH_API ::std::tuple sort(const at::Tensor & self, at::Dimname dim, bool descending=false); +TORCH_API ::std::tuple sort_out(const at::Tensor & self, at::Dimname dim, bool descending, at::Tensor & values, at::Tensor & indices); +TORCH_API ::std::tuple sort(const at::Tensor & self, c10::optional stable, at::Dimname dim, bool descending=false); +TORCH_API ::std::tuple sort_out(const at::Tensor & self, c10::optional stable, at::Dimname dim, bool descending, at::Tensor & values, at::Tensor & indices); +} // namespace native +} // namespace at diff --git a/shared/package-files/76/76293c8b87c6e8c3e5c558a55b897da4ce68fef04c02c44622d95d784f61bef5/blob b/shared/package-files/76/76293c8b87c6e8c3e5c558a55b897da4ce68fef04c02c44622d95d784f61bef5/blob new file mode 100644 index 0000000000000000000000000000000000000000..7c7dff8cafd94f257a6cc061b7c1b3c8d8d3a10d --- /dev/null +++ b/shared/package-files/76/76293c8b87c6e8c3e5c558a55b897da4ce68fef04c02c44622d95d784f61bef5/blob @@ -0,0 +1,42 @@ +import numpy as np +from numba import from_dtype, cuda +from numba.cuda.testing import skip_on_cudasim, CUDATestCase +import unittest + + +class TestAlignment(CUDATestCase): + def test_record_alignment(self): + rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True) + rec = from_dtype(rec_dtype) + + @cuda.jit((rec[:],)) + def foo(a): + i = cuda.grid(1) + a[i].a = a[i].b + + a_recarray = np.recarray(3, dtype=rec_dtype) + for i in range(a_recarray.size): + a_rec = a_recarray[i] + a_rec.a = 0 + a_rec.b = (i + 1) * 123 + + foo[1, 3](a_recarray) + + self.assertTrue(np.all(a_recarray.a == a_recarray.b)) + + @skip_on_cudasim('Simulator does not check alignment') + def test_record_alignment_error(self): + rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')]) + rec = from_dtype(rec_dtype) + + with self.assertRaises(Exception) as raises: + @cuda.jit((rec[:],)) + def foo(a): + i = cuda.grid(1) + a[i].a = a[i].b + + self.assertTrue('type float64 is not aligned' in str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/76/762a38bbfad8dc653cd48bb70d2f70543628be5b155b78c033f9d94e6daf322f/blob b/shared/package-files/76/762a38bbfad8dc653cd48bb70d2f70543628be5b155b78c033f9d94e6daf322f/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d3496176aca0253e392f4c29fea24aac2912832 --- /dev/null +++ b/shared/package-files/76/762a38bbfad8dc653cd48bb70d2f70543628be5b155b78c033f9d94e6daf322f/blob @@ -0,0 +1,17 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +from types import MethodType + + +def is_hypothesis_test(test): + if isinstance(test, MethodType): + return is_hypothesis_test(test.__func__) + return getattr(test, "is_hypothesis_test", False) diff --git a/shared/package-files/76/762c7331ef418879ef6cbf0ac91f8a63d2cb5fe543d7ea606d65c2e8cc1ce0b0/blob b/shared/package-files/76/762c7331ef418879ef6cbf0ac91f8a63d2cb5fe543d7ea606d65c2e8cc1ce0b0/blob new file mode 100644 index 0000000000000000000000000000000000000000..2645fe9ff41c853fc53c4e2cfdb98273067a6aa2 --- /dev/null +++ b/shared/package-files/76/762c7331ef418879ef6cbf0ac91f8a63d2cb5fe543d7ea606d65c2e8cc1ce0b0/blob @@ -0,0 +1,24 @@ +from typing import Any + +number_re: Any +regex_type: Any +test_callable: Any + +def test_odd(value): ... +def test_even(value): ... +def test_divisibleby(value, num): ... +def test_defined(value): ... +def test_undefined(value): ... +def test_none(value): ... +def test_lower(value): ... +def test_upper(value): ... +def test_string(value): ... +def test_mapping(value): ... +def test_number(value): ... +def test_sequence(value): ... +def test_equalto(value, other): ... +def test_sameas(value, other): ... +def test_iterable(value): ... +def test_escaped(value): ... + +TESTS: Any diff --git a/shared/package-files/76/762cc04a825e9ef8c2c9d6960e8ef6fc542688d3a32e69c265b5198029bc1272/blob b/shared/package-files/76/762cc04a825e9ef8c2c9d6960e8ef6fc542688d3a32e69c265b5198029bc1272/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ec1a1e25a2b3cfe974baebfe32d686435f73e11 --- /dev/null +++ b/shared/package-files/76/762cc04a825e9ef8c2c9d6960e8ef6fc542688d3a32e69c265b5198029bc1272/blob @@ -0,0 +1,14 @@ +import numpy as np + +from pandas._typing import npt + +def array_strptime( + values: npt.NDArray[np.object_], + fmt: str | None, + exact: bool = ..., + errors: str = ..., + utc: bool = ..., + creso: int = ..., # NPY_DATETIMEUNIT +) -> tuple[np.ndarray, np.ndarray]: ... + +# first ndarray is M8[ns], second is object ndarray of tzinfo | None diff --git a/shared/package-files/76/762cd65a662dc566b92dce07bfaf6245a2686b34617a025a0c6598816b49bbe5/blob b/shared/package-files/76/762cd65a662dc566b92dce07bfaf6245a2686b34617a025a0c6598816b49bbe5/blob new file mode 100644 index 0000000000000000000000000000000000000000..993f18a61d74aaa643e9790df70ede618b917223 --- /dev/null +++ b/shared/package-files/76/762cd65a662dc566b92dce07bfaf6245a2686b34617a025a0c6598816b49bbe5/blob @@ -0,0 +1,12 @@ +DAYS: list[str] +MONTH_ALIASES: dict[int, str] +MONTH_NUMBERS: dict[str, int] +MONTHS: list[str] +int_to_weekday: dict[int, str] + +def get_firstbday(year: int, month: int) -> int: ... +def get_lastbday(year: int, month: int) -> int: ... +def get_day_of_year(year: int, month: int, day: int) -> int: ... +def get_iso_calendar(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def get_week_of_year(year: int, month: int, day: int) -> int: ... +def get_days_in_month(year: int, month: int) -> int: ... diff --git a/shared/package-files/76/762de06c2f66b97293a39542ad6e727be7b5f40d66ace97c7bc96f2376fdd380/blob b/shared/package-files/76/762de06c2f66b97293a39542ad6e727be7b5f40d66ace97c7bc96f2376fdd380/blob new file mode 100644 index 0000000000000000000000000000000000000000..94f0d76fa814c6015fd4acefca5b1c1732645c85 --- /dev/null +++ b/shared/package-files/76/762de06c2f66b97293a39542ad6e727be7b5f40d66ace97c7bc96f2376fdd380/blob @@ -0,0 +1,38 @@ +from .backend_bases import RendererBase + +from matplotlib.typing import ColorType + +import numpy as np + +class TexManager: + texcache: str + @classmethod + def get_basefile( + cls, tex: str, fontsize: float, dpi: float | None = ... + ) -> str: ... + @classmethod + def get_font_preamble(cls) -> str: ... + @classmethod + def get_custom_preamble(cls) -> str: ... + @classmethod + def make_tex(cls, tex: str, fontsize: float) -> str: ... + @classmethod + def make_dvi(cls, tex: str, fontsize: float) -> str: ... + @classmethod + def make_png(cls, tex: str, fontsize: float, dpi: float) -> str: ... + @classmethod + def get_grey( + cls, tex: str, fontsize: float | None = ..., dpi: float | None = ... + ) -> np.ndarray: ... + @classmethod + def get_rgba( + cls, + tex: str, + fontsize: float | None = ..., + dpi: float | None = ..., + rgb: ColorType = ..., + ) -> np.ndarray: ... + @classmethod + def get_text_width_height_descent( + cls, tex: str, fontsize, renderer: RendererBase | None = ... + ) -> tuple[int, int, int]: ... diff --git a/shared/package-files/76/762e631dcd15ac8b9bb9f80aa9004e1f57ad591adcdaef6bf6e73f0a893242c7/blob b/shared/package-files/76/762e631dcd15ac8b9bb9f80aa9004e1f57ad591adcdaef6bf6e73f0a893242c7/blob new file mode 100644 index 0000000000000000000000000000000000000000..fee5b0c5dd3c0e4f257b16fcdb171b2e89f7e712 --- /dev/null +++ b/shared/package-files/76/762e631dcd15ac8b9bb9f80aa9004e1f57ad591adcdaef6bf6e73f0a893242c7/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API ::std::tuple linalg_slogdet(const at::Tensor & A); +TORCH_API ::std::tuple linalg_slogdet_out(at::Tensor & sign, at::Tensor & logabsdet, const at::Tensor & A); +TORCH_API ::std::tuple linalg_slogdet_outf(const at::Tensor & A, at::Tensor & sign, at::Tensor & logabsdet); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/76/763092fec9ebecd2814e74000aaecc31c3875abd82f16dd9a27fd57e74b5091d/blob b/shared/package-files/76/763092fec9ebecd2814e74000aaecc31c3875abd82f16dd9a27fd57e74b5091d/blob new file mode 100644 index 0000000000000000000000000000000000000000..c81aaf9978330ecd6a55b045318bd23867b587e5 Binary files /dev/null and b/shared/package-files/76/763092fec9ebecd2814e74000aaecc31c3875abd82f16dd9a27fd57e74b5091d/blob differ diff --git a/shared/package-files/76/7632a2572dd155adb683f041124c251f63332c0274ee9ce9bbd5f85e5638b77e/blob b/shared/package-files/76/7632a2572dd155adb683f041124c251f63332c0274ee9ce9bbd5f85e5638b77e/blob new file mode 100644 index 0000000000000000000000000000000000000000..5279724c29b5f06c058cf7c25ba40f9ebdcee599 --- /dev/null +++ b/shared/package-files/76/7632a2572dd155adb683f041124c251f63332c0274ee9ce9bbd5f85e5638b77e/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logaddexp2_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::logaddexp2_out::call(self, other, out); +} +// aten::logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logaddexp2_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::logaddexp2_out::call(self, other, out); +} + +// aten::logaddexp2(Tensor self, Tensor other) -> Tensor +inline at::Tensor logaddexp2(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::logaddexp2::call(self, other); +} + +} diff --git a/shared/package-files/76/7635a8c3ba61226c771d8452e134b36fcb2d41cfdf9be500bbef054186cced57/blob b/shared/package-files/76/7635a8c3ba61226c771d8452e134b36fcb2d41cfdf9be500bbef054186cced57/blob new file mode 100644 index 0000000000000000000000000000000000000000..a6752cf5eb1bad16c5f902f0feb07c75aa9dd03d --- /dev/null +++ b/shared/package-files/76/7635a8c3ba61226c771d8452e134b36fcb2d41cfdf9be500bbef054186cced57/blob @@ -0,0 +1,93 @@ +# test_lowess_r_output.R +# +# Generate outputs for unit tests +# for lowess function in cylowess.pyx +# +# May 2012 +# + +# test_simple +x_simple = 0:19 +# Standard Normal noise +noise_simple = c(-0.76741118, -0.30754369, + 0.39950921, -0.46352422, -1.67081778, + 0.6595567 , 0.66367639, -2.04388585, + 0.8123281 , 1.45977518, + 1.21428038, 1.29296866, 0.78028477, + -0.2402853 , -0.21721302, + 0.24549405, 0.25987014, -0.90709034, + -1.45688216, -0.31780505) + +y_simple = x_simple + noise_simple + +out_simple = lowess(x_simple, y_simple, delta = 0, iter = 3) + + +# test_iter +x_iter = 0:19 +# Cauchy noise +noise_iter = c(1.86299605, -0.10816866, 1.87761229, + -3.63442237, 0.30249022, + 1.03560416, 0.21163349, 1.14167809, + -0.00368175, -2.08808987, + 0.13065417, -1.8052207 , 0.60404596, + -2.30908204, 1.7081412 , + -0.54633243, -0.93107948, 1.79023999, + 1.05822445, -1.04530564) + +y_iter = x_iter + noise_iter + +out_iter_0 = lowess(x_iter, y_iter, delta = 0, iter = 0) +out_iter_3 = lowess(x_iter, y_iter, delta = 0, iter = 3) + + +# test_frac +x_frac = seq(-2*pi, 2*pi, length = 30) + +# normal noise +noise_frac = c(1.62379338, -1.11849371, 1.60085673, + 0.41996348, 0.70896754, + 0.19271408, 0.04972776, -0.22411356, + 0.18154882, -0.63651971, + 0.64942414, -2.26509826, 0.80018964, + 0.89826857, -0.09136105, + 0.80482898, 1.54504686, -1.23734643, + -1.16572754, 0.28027691, + -0.85191583, 0.20417445, 0.61034806, + 0.68297375, 1.45707167, + 0.45157072, -1.13669622, -0.08552254, + -0.28368514, -0.17326155) + +y_frac = sin(x_frac) + noise_frac + +out_frac_2_3 = lowess(x_frac, y_frac, f = 2/3, delta = 0, iter = 3) +out_frac_1_5 = lowess(x_frac, y_frac, f = 1/5, delta = 0, iter = 3) + + +# test_delta +# Load mcycle motorcycle collision data +library(MASS) +data(mcycle) + +out_delta_0 = lowess(mcycle, f = 0.1, delta = 0.0) +out_delta_Rdef = lowess(mcycle, f = 0.1) +out_delta_1 = lowess(mcycle, f = 0.1, delta = 1.0) + + +# Create data frames of inputs and outputs, write them to CSV to be imported +# by test_lowess.py + +df_test_simple = data.frame(x = x_simple, y = y_simple, out = out_simple$y) +df_test_frac = data.frame(x = x_frac, y = y_frac, + out_2_3 = out_frac_2_3$y, out_1_5 = out_frac_1_5$y) +df_test_iter = data.frame(x = x_iter, y = y_iter, out_0 = out_iter_0$y, + out_3 = out_iter_3$y) +df_test_delta = data.frame(x = mcycle$times, y = mcycle$accel, + out_0 = out_delta_0$y, out_Rdef = out_delta_Rdef$y, + out_1 = out_delta_1$y) + + +write.csv(df_test_simple, "test_lowess_simple.csv", row.names = FALSE) +write.csv(df_test_frac, "test_lowess_frac.csv", row.names = FALSE) +write.csv(df_test_iter, "test_lowess_iter.csv", row.names = FALSE) +write.csv(df_test_delta, "test_lowess_delta.csv", row.names = FALSE) diff --git a/shared/package-files/76/763754ef1090fb9d77565c4510ebcb37ca1a63843250f1c32475a58a58721150/blob b/shared/package-files/76/763754ef1090fb9d77565c4510ebcb37ca1a63843250f1c32475a58a58721150/blob new file mode 100644 index 0000000000000000000000000000000000000000..e938eacad04467068985aacc7134248ab6ec44a6 --- /dev/null +++ b/shared/package-files/76/763754ef1090fb9d77565c4510ebcb37ca1a63843250f1c32475a58a58721150/blob @@ -0,0 +1,204 @@ +import numpy as np +from scipy.sparse import coo_matrix +from scipy._lib._bunch import _make_tuple_bunch + + +CrosstabResult = _make_tuple_bunch( + "CrosstabResult", ["elements", "count"] +) + + +def crosstab(*args, levels=None, sparse=False): + """ + Return table of counts for each possible unique combination in ``*args``. + + When ``len(args) > 1``, the array computed by this function is + often referred to as a *contingency table* [1]_. + + The arguments must be sequences with the same length. The second return + value, `count`, is an integer array with ``len(args)`` dimensions. If + `levels` is None, the shape of `count` is ``(n0, n1, ...)``, where ``nk`` + is the number of unique elements in ``args[k]``. + + Parameters + ---------- + *args : sequences + A sequence of sequences whose unique aligned elements are to be + counted. The sequences in args must all be the same length. + levels : sequence, optional + If `levels` is given, it must be a sequence that is the same length as + `args`. Each element in `levels` is either a sequence or None. If it + is a sequence, it gives the values in the corresponding sequence in + `args` that are to be counted. If any value in the sequences in `args` + does not occur in the corresponding sequence in `levels`, that value + is ignored and not counted in the returned array `count`. The default + value of `levels` for ``args[i]`` is ``np.unique(args[i])`` + sparse : bool, optional + If True, return a sparse matrix. The matrix will be an instance of + the `scipy.sparse.coo_matrix` class. Because SciPy's sparse matrices + must be 2-d, only two input sequences are allowed when `sparse` is + True. Default is False. + + Returns + ------- + res : CrosstabResult + An object containing the following attributes: + + elements : tuple of numpy.ndarrays. + Tuple of length ``len(args)`` containing the arrays of elements + that are counted in `count`. These can be interpreted as the + labels of the corresponding dimensions of `count`. If `levels` was + given, then if ``levels[i]`` is not None, ``elements[i]`` will + hold the values given in ``levels[i]``. + count : numpy.ndarray or scipy.sparse.coo_matrix + Counts of the unique elements in ``zip(*args)``, stored in an + array. Also known as a *contingency table* when ``len(args) > 1``. + + See Also + -------- + numpy.unique + + Notes + ----- + .. versionadded:: 1.7.0 + + References + ---------- + .. [1] "Contingency table", http://en.wikipedia.org/wiki/Contingency_table + + Examples + -------- + >>> from scipy.stats.contingency import crosstab + + Given the lists `a` and `x`, create a contingency table that counts the + frequencies of the corresponding pairs. + + >>> a = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'] + >>> x = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z'] + >>> res = crosstab(a, x) + >>> avals, xvals = res.elements + >>> avals + array(['A', 'B'], dtype='>> xvals + array(['X', 'Y', 'Z'], dtype='>> res.count + array([[2, 3, 0], + [1, 0, 4]]) + + So ``('A', 'X')`` occurs twice, ``('A', 'Y')`` occurs three times, etc. + + Higher dimensional contingency tables can be created. + + >>> p = [0, 0, 0, 0, 1, 1, 1, 0, 0, 1] + >>> res = crosstab(a, x, p) + >>> res.count + array([[[2, 0], + [2, 1], + [0, 0]], + [[1, 0], + [0, 0], + [1, 3]]]) + >>> res.count.shape + (2, 3, 2) + + The values to be counted can be set by using the `levels` argument. + It allows the elements of interest in each input sequence to be + given explicitly instead finding the unique elements of the sequence. + + For example, suppose one of the arguments is an array containing the + answers to a survey question, with integer values 1 to 4. Even if the + value 1 does not occur in the data, we want an entry for it in the table. + + >>> q1 = [2, 3, 3, 2, 4, 4, 2, 3, 4, 4, 4, 3, 3, 3, 4] # 1 does not occur. + >>> q2 = [4, 4, 2, 2, 2, 4, 1, 1, 2, 2, 4, 2, 2, 2, 4] # 3 does not occur. + >>> options = [1, 2, 3, 4] + >>> res = crosstab(q1, q2, levels=(options, options)) + >>> res.count + array([[0, 0, 0, 0], + [1, 1, 0, 1], + [1, 4, 0, 1], + [0, 3, 0, 3]]) + + If `levels` is given, but an element of `levels` is None, the unique values + of the corresponding argument are used. For example, + + >>> res = crosstab(q1, q2, levels=(None, options)) + >>> res.elements + [array([2, 3, 4]), [1, 2, 3, 4]] + >>> res.count + array([[1, 1, 0, 1], + [1, 4, 0, 1], + [0, 3, 0, 3]]) + + If we want to ignore the pairs where 4 occurs in ``q2``, we can + give just the values [1, 2] to `levels`, and the 4 will be ignored: + + >>> res = crosstab(q1, q2, levels=(None, [1, 2])) + >>> res.elements + [array([2, 3, 4]), [1, 2]] + >>> res.count + array([[1, 1], + [1, 4], + [0, 3]]) + + Finally, let's repeat the first example, but return a sparse matrix: + + >>> res = crosstab(a, x, sparse=True) + >>> res.count + + >>> res.count.toarray() + array([[2, 3, 0], + [1, 0, 4]]) + + """ + nargs = len(args) + if nargs == 0: + raise TypeError("At least one input sequence is required.") + + len0 = len(args[0]) + if not all(len(a) == len0 for a in args[1:]): + raise ValueError("All input sequences must have the same length.") + + if sparse and nargs != 2: + raise ValueError("When `sparse` is True, only two input sequences " + "are allowed.") + + if levels is None: + # Call np.unique with return_inverse=True on each argument. + actual_levels, indices = zip(*[np.unique(a, return_inverse=True) + for a in args]) + else: + # `levels` is not None... + if len(levels) != nargs: + raise ValueError('len(levels) must equal the number of input ' + 'sequences') + + args = [np.asarray(arg) for arg in args] + mask = np.zeros((nargs, len0), dtype=np.bool_) + inv = np.zeros((nargs, len0), dtype=np.intp) + actual_levels = [] + for k, (levels_list, arg) in enumerate(zip(levels, args)): + if levels_list is None: + levels_list, inv[k, :] = np.unique(arg, return_inverse=True) + mask[k, :] = True + else: + q = arg == np.asarray(levels_list).reshape(-1, 1) + mask[k, :] = np.any(q, axis=0) + qnz = q.T.nonzero() + inv[k, qnz[0]] = qnz[1] + actual_levels.append(levels_list) + + mask_all = mask.all(axis=0) + indices = tuple(inv[:, mask_all]) + + if sparse: + count = coo_matrix((np.ones(len(indices[0]), dtype=int), + (indices[0], indices[1]))) + count.sum_duplicates() + else: + shape = [len(u) for u in actual_levels] + count = np.zeros(shape, dtype=int) + np.add.at(count, indices, 1) + + return CrosstabResult(actual_levels, count) diff --git a/shared/package-files/76/763990360c781fddf68646bdfe402b51f46b1fe311c4c7d04b949c8416a916a3/blob b/shared/package-files/76/763990360c781fddf68646bdfe402b51f46b1fe311c4c7d04b949c8416a916a3/blob new file mode 100644 index 0000000000000000000000000000000000000000..12c560e697e67c22fe2a3ad16d30ee9f0564d92e --- /dev/null +++ b/shared/package-files/76/763990360c781fddf68646bdfe402b51f46b1fe311c4c7d04b949c8416a916a3/blob @@ -0,0 +1,36 @@ +from typing import Any, Callable, List, Optional, Set, Union + +from django.apps.config import AppConfig +from django.core.checks.messages import CheckMessage + +class Tags: + admin: str = ... + caches: str = ... + compatibility: str = ... + database: str = ... + models: str = ... + security: str = ... + signals: str = ... + templates: str = ... + translation: str = ... + urls: str = ... + +class CheckRegistry: + registered_checks: Set[Callable] = ... + deployment_checks: Set[Callable] = ... + def __init__(self) -> None: ... + def register(self, check: Optional[Union[Callable, str]] = ..., *tags: Any, **kwargs: Any) -> Callable: ... + def run_checks( + self, + app_configs: Optional[List[AppConfig]] = ..., + tags: Optional[List[str]] = ..., + include_deployment_checks: bool = ..., + ) -> Union[List[CheckMessage], List[int], List[str]]: ... + def tag_exists(self, tag: str, include_deployment_checks: bool = ...) -> bool: ... + def tags_available(self, deployment_checks: bool = ...) -> Set[str]: ... + def get_checks(self, include_deployment_checks: bool = ...) -> List[Callable]: ... + +registry: Any +register: Any +run_checks: Any +tag_exists: Any diff --git a/shared/package-files/76/763b1e1c197352a0c9ec951cd89e75393ffb08b9bf2f3d04c95439e68dee7542/blob b/shared/package-files/76/763b1e1c197352a0c9ec951cd89e75393ffb08b9bf2f3d04c95439e68dee7542/blob new file mode 100644 index 0000000000000000000000000000000000000000..18a6fb87b6283bac0e0fd5716dceef4dee6cb15b --- /dev/null +++ b/shared/package-files/76/763b1e1c197352a0c9ec951cd89e75393ffb08b9bf2f3d04c95439e68dee7542/blob @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +def check_pkcs7_padding(data: bytes) -> bool: ... +def check_ansix923_padding(data: bytes) -> bool: ... + +class ObjectIdentifier: + def __init__(self, val: str) -> None: ... + @property + def dotted_string(self) -> str: ... + @property + def _name(self) -> str: ... + +T = typing.TypeVar("T") diff --git a/shared/package-files/76/763dfb1978b7b08fbb1e8cf833824b1073b6c21f9c20437310d883718219aa7f/blob b/shared/package-files/76/763dfb1978b7b08fbb1e8cf833824b1073b6c21f9c20437310d883718219aa7f/blob new file mode 100644 index 0000000000000000000000000000000000000000..a66523ab183923e1c15862268b1b0260ccfb9e14 --- /dev/null +++ b/shared/package-files/76/763dfb1978b7b08fbb1e8cf833824b1073b6c21f9c20437310d883718219aa7f/blob @@ -0,0 +1,46 @@ +#pragma once +#include + +// Forward declarations of core ATen types used in dispatch functions +namespace c10 { + +template +class List; +template +class IListRef; +class Stream; +class Scalar; +class SymInt; +class SymIntList; +struct Storage; +struct TensorOptions; +template +class ArrayRef; +template +class OptionalArrayRef; + +} // namespace c10 + +namespace at { + +class Tensor; +class OptionalTensorRef; +struct Dimname; +struct Generator; +using TensorList = c10::ArrayRef; +using ITensorListRef = c10::IListRef; +using IOptTensorListRef = c10::IListRef; +using DimnameList = c10::ArrayRef; +using IntArrayRef = c10::ArrayRef; +using OptionalIntArrayRef = c10::OptionalArrayRef; +using OptionalSymIntArrayRef = c10::OptionalArrayRef; + +using c10::Stream; +using c10::Storage; +using c10::QScheme; +using c10::Scalar; +using c10::SymInt; +using c10::SymIntList; +using c10::TensorOptions; + +} // namespace at diff --git a/shared/package-files/76/76403fb0002053565bd4f368a6e3accb06cb7852beacb580638578563dfec742/blob b/shared/package-files/76/76403fb0002053565bd4f368a6e3accb06cb7852beacb580638578563dfec742/blob new file mode 100644 index 0000000000000000000000000000000000000000..d8e49ca773dc553cfbc14e526c2c48054e564a12 --- /dev/null +++ b/shared/package-files/76/76403fb0002053565bd4f368a6e3accb06cb7852beacb580638578563dfec742/blob @@ -0,0 +1,31 @@ +from __future__ import annotations + +__all__ = ["Array", "DType", "Device"] +_all_ignore = ["cp"] + +from typing import TYPE_CHECKING + +import cupy as cp +from cupy import ndarray as Array +from cupy.cuda.device import Device + +if TYPE_CHECKING: + # NumPy 1.x on Python 3.10 fails to parse np.dtype[] + DType = cp.dtype[ + cp.intp + | cp.int8 + | cp.int16 + | cp.int32 + | cp.int64 + | cp.uint8 + | cp.uint16 + | cp.uint32 + | cp.uint64 + | cp.float32 + | cp.float64 + | cp.complex64 + | cp.complex128 + | cp.bool_ + ] +else: + DType = cp.dtype diff --git a/shared/package-files/76/7641893cd320832ef1775351575c2cead7882bb65eda54c5be9033ec2c3976b2/blob b/shared/package-files/76/7641893cd320832ef1775351575c2cead7882bb65eda54c5be9033ec2c3976b2/blob new file mode 100644 index 0000000000000000000000000000000000000000..ae727f7595dc9a142147784411a28a8f61fd6d79 --- /dev/null +++ b/shared/package-files/76/7641893cd320832ef1775351575c2cead7882bb65eda54c5be9033ec2c3976b2/blob @@ -0,0 +1,3 @@ +# Re-export symbols +from numba.core.extending import * # noqa: F403, F401 +from numba.core.extending import _Intrinsic # noqa: F401 diff --git a/shared/package-files/76/76464e731b05d50dde939f0fec8a00f1fde5432050a45bc64857b29cd5763a57/blob b/shared/package-files/76/76464e731b05d50dde939f0fec8a00f1fde5432050a45bc64857b29cd5763a57/blob new file mode 100644 index 0000000000000000000000000000000000000000..9ed85126da1412774bc216737b7f4abc3795815c --- /dev/null +++ b/shared/package-files/76/76464e731b05d50dde939f0fec8a00f1fde5432050a45bc64857b29cd5763a57/blob @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/util/delimiting.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace json { + +struct ParseOptions; + +ARROW_EXPORT +std::unique_ptr MakeChunker(const ParseOptions& options); + +} // namespace json +} // namespace arrow diff --git a/shared/package-files/76/764745b5f5c403f54c0748a022b60a83305f64a81810cccdda5ba10d2eb556ed/blob b/shared/package-files/76/764745b5f5c403f54c0748a022b60a83305f64a81810cccdda5ba10d2eb556ed/blob new file mode 100644 index 0000000000000000000000000000000000000000..0149dc3a9f5bca55083e3cdf0a366c9982103050 Binary files /dev/null and b/shared/package-files/76/764745b5f5c403f54c0748a022b60a83305f64a81810cccdda5ba10d2eb556ed/blob differ diff --git a/shared/package-files/76/7648c6d10b2a52809b15f701d48d9da90ffba19a13daceaf7df5a834be4a3008/blob b/shared/package-files/76/7648c6d10b2a52809b15f701d48d9da90ffba19a13daceaf7df5a834be4a3008/blob new file mode 100644 index 0000000000000000000000000000000000000000..aae7957ea55f943ffe6a0c578e93ae4229d6d8cf --- /dev/null +++ b/shared/package-files/76/7648c6d10b2a52809b15f701d48d9da90ffba19a13daceaf7df5a834be4a3008/blob @@ -0,0 +1,257 @@ +""" Public facing layer for slicer. +The little slicer that could. +""" +# TODO: Move Obj and Alias class here. + +from .slicer_internal import AtomicSlicer, Alias, Obj, AliasLookup, Tracked, UnifiedDataHandler +from .slicer_internal import reduced_o, resolve_dim, unify_slice + + +class Slicer: + """ Provides unified slicing to tensor-like objects. """ + + def __init__(self, *args, **kwargs): + """ Wraps objects in args and provides unified numpy-like slicing. + + Currently supports (with arbitrary nesting): + + - lists and tuples + - dictionaries + - numpy arrays + - pandas dataframes and series + - pytorch tensors + + Args: + *args: Unnamed tensor-like objects. + **kwargs: Named tensor-like objects. + + Examples: + + Basic anonymous slicing: + + >>> from slicer import Slicer as S + >>> li = [[1, 2, 3], [4, 5, 6]] + >>> S(li)[:, 0:2].o + [[1, 2], [4, 5]] + >>> di = {'x': [1, 2, 3], 'y': [4, 5, 6]} + >>> S(di)[:, 0:2].o + {'x': [1, 2], 'y': [4, 5]} + + Basic named slicing: + + >>> import pandas as pd + >>> import numpy as np + >>> df = pd.DataFrame({'A': [1, 3], 'B': [2, 4]}) + >>> ar = np.array([[5, 6], [7, 8]]) + >>> sliced = S(first=df, second=ar)[0, :] + >>> sliced.first + A 1 + B 2 + Name: 0, dtype: int64 + >>> sliced.second + array([5, 6]) + + """ + self.__class__._init_slicer(self, *args, **kwargs) + + @classmethod + def from_slicer(cls, *args, **kwargs): + """ Alternative to SUPER SLICE + Args: + *args: + **kwargs: + + Returns: + + """ + slicer_instance = cls.__new__(cls) + cls._init_slicer(slicer_instance, *args, **kwargs) + return slicer_instance + + @classmethod + def _init_slicer(cls, slicer_instance, *args, **kwargs): + # NOTE: Protected attributes. + slicer_instance._max_dim = 0 + + # NOTE: Private attributes. + slicer_instance._anon = [] + slicer_instance._objects = {} + slicer_instance._aliases = {} + slicer_instance._alias_lookup = None + + # Go through unnamed objects / aliases + slicer_instance.__setattr__("o", args) + + # Go through named objects / aliases + for key, value in kwargs.items(): + slicer_instance.__setattr__(key, value) + + # Generate default aliases only if one object and no aliases exist + objects_len = len(slicer_instance._objects) + anon_len = len(slicer_instance._anon) + aliases_len = len(slicer_instance._aliases) + if ((objects_len == 1) ^ (anon_len == 1)) and aliases_len == 0: + obj = None + for _, t in slicer_instance._iter_tracked(): + obj = t + + generated_aliases = UnifiedDataHandler.default_alias(obj.o) + for generated_alias in generated_aliases: + slicer_instance.__setattr__(generated_alias._name, generated_alias) + + def __getitem__(self, item): + index_tup = unify_slice(item, self._max_dim, self._alias_lookup) + new_args = [] + new_kwargs = {} + for name, tracked in self._iter_tracked(include_aliases=True): + if len(tracked.dim) == 0: # No slice on empty dim + new_tracked = tracked + else: + index_slicer = AtomicSlicer(index_tup, max_dim=1) + slicer_index = index_slicer[tracked.dim] + sliced_o = tracked[slicer_index] + sliced_dim = resolve_dim(index_tup, tracked.dim) + + new_tracked = tracked.__class__(sliced_o, sliced_dim) + new_tracked._name = tracked._name + + if name == "o": + new_args.append(new_tracked) + else: + new_kwargs[name] = new_tracked + + return self.__class__.from_slicer(*new_args, **new_kwargs) + + def __getattr__(self, item): + """ Override default getattr to return tracked attribute. + + Args: + item: Name of tracked attribute. + Returns: + Corresponding object. + """ + if item.startswith("_"): + return super(Slicer, self).__getattr__(item) + + if item == "o": + return reduced_o(self._anon) + else: + tracked = self._objects.get(item, None) + if tracked is None: + tracked = self._aliases.get(item, None) + + if tracked is None: + raise AttributeError(f"Attribute '{item}' does not exist.") + + return tracked.o + + def __setattr__(self, key, value): + """ Override default setattr to sync tracking of slicer. + + Args: + key: Name of tracked attribute. + value: Either an Obj, Alias or Python Object. + """ + if key.startswith("_"): + return super(Slicer, self).__setattr__(key, value) + + # Grab previous objects if they exist: + old_obj = self._objects.get(key, None) + old_alias = self._aliases.get(key, None) + + # For existing attributes, honor Alias status and dimension unless specified otherwise + if getattr(self, key, None) is not None and key != "o": + if not isinstance(value, Tracked): + if old_obj: + value = Obj(value, dim=old_obj.dim) + elif old_alias: + value = Alias(value, dim=old_alias.dim) + + if isinstance(value, Alias): + value._name = key + self._aliases[key] = value + + if old_obj: # If object previously existed as an object, clean up all references. + del self._objects[key] + + # Build lookup (for perf) + if self._alias_lookup is None: + self._alias_lookup = AliasLookup(self._aliases) + else: + if old_alias: + self._alias_lookup.delete(old_alias) + self._alias_lookup.update(value) + else: + if key == "o": + tracked = [Obj(x) if not isinstance(x, Obj) else x for x in value] + self._anon = tracked + for t in tracked: + self._update_max_dim(t) + + os = reduced_o(self._anon) + super(Slicer, self).__setattr__(key, os) + else: + if old_alias: # If object previously existed as an alias, clean up all references. + self._alias_lookup.delete(old_alias) + del self._aliases[key] + + value = Obj(value) if not isinstance(value, Obj) else value + value._name = key + self._objects[key] = value + self._update_max_dim(value) + super(Slicer, self).__setattr__(key, value.o) + + def __delattr__(self, item): + """ Override default delattr to remove tracked attribute. + + Args: + item: Name of tracked attribute to delete. + """ + if item.startswith("_"): + return super(Slicer, self).__delattr__(item) + + # Sync private attributes that help track + self._objects.pop(item, None) + self._aliases.pop(item, None) + if item == "o": + self._anon.clear() + + # Recompute max_dim + self._recompute_max_dim() + + # Recompute alias lookup + # NOTE: This doesn't use diff-style deletes, but we don't care (not a perf target). + self._alias_lookup = AliasLookup(self._aliases) + + # TODO: Mutate and check interactively what it does + super(Slicer, self).__delattr__(item) + + def __repr__(self): + """ Override default repr for human readability. + + Returns: + String to display. + """ + orig = self.__dict__ + di = {} + for key, value in orig.items(): + if not key.startswith("_"): + di[key] = value + return f"{self.__class__.__name__}({str(di)})" + + def _update_max_dim(self, tracked): + self._max_dim = max(self._max_dim, max(tracked.dim, default=-1) + 1) + + def _iter_tracked(self, include_aliases=False): + for tracked in self._anon: + yield "o", tracked + for name, tracked in self._objects.items(): + yield name, tracked + if include_aliases: + for name, tracked in self._aliases.items(): + yield name, tracked + + def _recompute_max_dim(self): + self._max_dim = max( + [max(o.dim, default=-1) + 1 for _, o in self._iter_tracked()], default=0 + ) diff --git a/shared/package-files/76/764e8afea91a1e8dbe284c91181fa75de89522a18816dea0306c3e26a931c355/model_manifest.json b/shared/package-files/76/764e8afea91a1e8dbe284c91181fa75de89522a18816dea0306c3e26a931c355/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..e39fa60a2475693c0578e08169f3a3099d6a5efa --- /dev/null +++ b/shared/package-files/76/764e8afea91a1e8dbe284c91181fa75de89522a18816dea0306c3e26a931c355/model_manifest.json @@ -0,0 +1,13 @@ +{ + "schema": "massspecgym-retrieval-model/v1", + "checkpoint": { + "path": ".versions/generation-4tcdv5aw/model.pt", + "sha256": "c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf", + "format": "pytorch" + }, + "model_config": ".versions/generation-4tcdv5aw/model_config.json", + "training_provenance": { + "data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", + "pretrained_assets": [] + } +} diff --git a/shared/package-files/76/765098240cd77491834ec4f4ff52b5b556427a91a84651291a4507304f50f4df/blob b/shared/package-files/76/765098240cd77491834ec4f4ff52b5b556427a91a84651291a4507304f50f4df/blob new file mode 100644 index 0000000000000000000000000000000000000000..42445be87997f44423189e62a1a8343ff9a86de6 --- /dev/null +++ b/shared/package-files/76/765098240cd77491834ec4f4ff52b5b556427a91a84651291a4507304f50f4df/blob @@ -0,0 +1,5333 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +""" +This module transforms data-parallel operations such as Numpy calls into +'Parfor' nodes, which are nested loops that can be parallelized. +It also implements optimizations such as loop fusion, and extends the rest of +compiler analysis and optimizations to support Parfors. +This is similar to ParallelAccelerator package in Julia: +https://github.com/IntelLabs/ParallelAccelerator.jl +'Parallelizing Julia with a Non-invasive DSL', T. Anderson et al., ECOOP'17. +""" +import types as pytypes # avoid confusion with numba.types +import sys, math +import os +import textwrap +import copy +import inspect +import linecache +from functools import reduce +from collections import defaultdict, OrderedDict, namedtuple +from contextlib import contextmanager +import operator +from dataclasses import make_dataclass +import warnings + +from llvmlite import ir as lir +from numba.core.imputils import impl_ret_untracked +import numba.core.ir +from numba.core import types, typing, utils, errors, ir, analysis, postproc, rewrites, typeinfer, config, ir_utils +from numba import prange, pndindex +from numba.np.npdatetime_helpers import datetime_minimum, datetime_maximum +from numba.np.numpy_support import as_dtype, numpy_version +from numba.core.typing.templates import infer_global, AbstractTemplate +from numba.stencils.stencilparfor import StencilPass +from numba.core.extending import register_jitable, lower_builtin + +from numba.core.ir_utils import ( + mk_unique_var, + next_label, + get_np_ufunc_typ, + mk_range_block, + mk_loop_header, + get_name_var_table, + replace_vars, + replace_vars_inner, + visit_vars, + visit_vars_inner, + remove_dead, + copy_propagate, + get_block_copies, + apply_copy_propagate, + dprint_func_ir, + find_topo_order, + get_stmt_writes, + rename_labels, + get_call_table, + simplify, + simplify_CFG, + has_no_side_effect, + canonicalize_array_math, + add_offset_to_labels, + find_callname, + find_build_sequence, + guard, + require, + GuardException, + compile_to_numba_ir, + get_definition, + build_definitions, + replace_arg_nodes, + replace_returns, + is_getitem, + is_setitem, + is_get_setitem, + index_var_of_get_setitem, + set_index_var_of_get_setitem, + find_potential_aliases, + replace_var_names, + transfer_scope, +) + +from numba.core.analysis import (compute_use_defs, compute_live_map, + compute_dead_maps, compute_cfg_from_blocks) +from numba.core.controlflow import CFGraph +from numba.core.typing import npydecl, signature +from numba.core.types.functions import Function +from numba.parfors.array_analysis import (random_int_args, random_1arg_size, + random_2arg_sizelast, random_3arg_sizelast, + random_calls, assert_equiv) +from numba.parfors.ir_utils import mk_alloc +from numba.np import types as npy_types +from numba.core.extending import overload +import copy +import numpy +import numpy as np +from numba.parfors import array_analysis +import numba.cpython.builtins +from numba.stencils import stencilparfor +# circular dependency: import numba.npyufunc.dufunc.DUFunc + +# wrapped pretty print +_termwidth = 80 +_txtwrapper = textwrap.TextWrapper(width=_termwidth, drop_whitespace=False) +def print_wrapped(x): + for l in x.splitlines(): + [print(y) for y in _txtwrapper.wrap(l)] + +sequential_parfor_lowering = False + +# init_prange is a sentinel call that specifies the start of the initialization +# code for the computation in the upcoming prange call +# This lets the prange pass to put the code in the generated parfor's init_block +def init_prange(): + return + +@overload(init_prange) +def init_prange_overload(): + def no_op(): + return + return no_op + +class internal_prange(object): + + def __new__(cls, *args): + return range(*args) + + +def min_parallel_impl(return_type, arg): + # XXX: use prange for 1D arrays since pndindex returns a 1-tuple instead of + # integer. This causes type and fusion issues. + if arg.ndim == 0: + def min_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + if isinstance(arg.dtype, (npy_types.NPDatetime, npy_types.NPTimedelta)): + # NaT is always returned if it is in the array + def min_1(in_arr): + numba.parfors.parfor.init_prange() + min_checker(len(in_arr)) + val = get_type_max_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = datetime_minimum(val, in_arr[i]) + return val + else: + def min_1(in_arr): + numba.parfors.parfor.init_prange() + min_checker(len(in_arr)) + val = get_type_max_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = min(val, in_arr[i]) + return val + else: + def min_1(in_arr): + numba.parfors.parfor.init_prange() + min_checker(len(in_arr)) + val = get_type_max_value(in_arr.dtype) + for i in numba.pndindex(in_arr.shape): + val = min(val, in_arr[i]) + return val + return min_1 + +# ----------------------------------------------------------------------------- + +def get_type_max_value(typ): + if isinstance(typ, types.Float): + return np.inf + if isinstance(typ, types.Integer): + return typ.maxval + raise NotImplementedError("Unsupported type") + +def get_type_min_value(typ): + if isinstance(typ, types.Float): + return -np.inf + if isinstance(typ, types.Integer): + return typ.minval + raise NotImplementedError("Unsupported type") + +@infer_global(get_type_min_value) +@infer_global(get_type_max_value) +class MinValInfer(AbstractTemplate): + def generic(self, args, kws): + assert not kws + assert len(args) == 1 + if isinstance(args[0], (types.DType, types.NumberClass)): + return signature(args[0].dtype, *args) + +@lower_builtin(get_type_min_value, types.NumberClass) +@lower_builtin(get_type_min_value, types.DType) +def lower_get_type_min_value(context, builder, sig, args): + typ = sig.args[0].dtype + + if isinstance(typ, types.Integer): + bw = typ.bitwidth + lty = lir.IntType(bw) + val = typ.minval + res = lir.Constant(lty, val) + elif isinstance(typ, types.Float): + bw = typ.bitwidth + if bw == 32: + lty = lir.FloatType() + elif bw == 64: + lty = lir.DoubleType() + else: + raise NotImplementedError("llvmlite only supports 32 and 64 bit floats") + npty = getattr(np, 'float{}'.format(bw)) + res = lir.Constant(lty, -np.inf) + elif isinstance(typ, (npy_types.NPDatetime, npy_types.NPTimedelta)): + bw = 64 + lty = lir.IntType(bw) + val = types.int64.minval + 1 # minval is NaT, so minval + 1 is the smallest value + res = lir.Constant(lty, val) + return impl_ret_untracked(context, builder, lty, res) + +@lower_builtin(get_type_max_value, types.NumberClass) +@lower_builtin(get_type_max_value, types.DType) +def lower_get_type_max_value(context, builder, sig, args): + typ = sig.args[0].dtype + + if isinstance(typ, types.Integer): + bw = typ.bitwidth + lty = lir.IntType(bw) + val = typ.maxval + res = lir.Constant(lty, val) + elif isinstance(typ, types.Float): + bw = typ.bitwidth + if bw == 32: + lty = lir.FloatType() + elif bw == 64: + lty = lir.DoubleType() + else: + raise NotImplementedError("llvmlite only supports 32 and 64 bit floats") + npty = getattr(np, 'float{}'.format(bw)) + res = lir.Constant(lty, np.inf) + elif isinstance(typ, (npy_types.NPDatetime, npy_types.NPTimedelta)): + bw = 64 + lty = lir.IntType(bw) + val = types.int64.maxval + res = lir.Constant(lty, val) + return impl_ret_untracked(context, builder, lty, res) + +def max_parallel_impl(return_type, arg): + if arg.ndim == 0: + def max_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + if isinstance(arg.dtype, (npy_types.NPDatetime, npy_types.NPTimedelta)): + # NaT is always returned if it is in the array + def max_1(in_arr): + numba.parfors.parfor.init_prange() + max_checker(len(in_arr)) + val = get_type_min_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = datetime_maximum(val, in_arr[i]) + return val + else: + def max_1(in_arr): + numba.parfors.parfor.init_prange() + max_checker(len(in_arr)) + val = get_type_min_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = max(val, in_arr[i]) + return val + else: + def max_1(in_arr): + numba.parfors.parfor.init_prange() + max_checker(len(in_arr)) + val = get_type_min_value(in_arr.dtype) + for i in numba.pndindex(in_arr.shape): + val = max(val, in_arr[i]) + return val + return max_1 + +def argmin_parallel_impl(in_arr): + numba.parfors.parfor.init_prange() + argmin_checker(len(in_arr)) + A = in_arr.ravel() + init_val = get_type_max_value(A.dtype) + ival = typing.builtins.IndexValue(0, init_val) + for i in numba.parfors.parfor.internal_prange(len(A)): + curr_ival = typing.builtins.IndexValue(i, A[i]) + ival = min(ival, curr_ival) + return ival.index + +def argmax_parallel_impl(in_arr): + numba.parfors.parfor.init_prange() + argmax_checker(len(in_arr)) + A = in_arr.ravel() + init_val = get_type_min_value(A.dtype) + ival = typing.builtins.IndexValue(0, init_val) + for i in numba.parfors.parfor.internal_prange(len(A)): + curr_ival = typing.builtins.IndexValue(i, A[i]) + ival = max(ival, curr_ival) + return ival.index + +def dotvv_parallel_impl(a, b): + numba.parfors.parfor.init_prange() + l = a.shape[0] + m = b.shape[0] + # TODO: investigate assert_equiv + #assert_equiv("sizes of l, m do not match", l, m) + s = 0 + for i in numba.parfors.parfor.internal_prange(l): + s += a[i] * b[i] + return s + +def dotvm_parallel_impl(a, b): + numba.parfors.parfor.init_prange() + l = a.shape + m, n = b.shape + # TODO: investigate assert_equiv + #assert_equiv("Sizes of l, m do not match", l, m) + c = np.zeros(n, a.dtype) + # TODO: evaluate dotvm implementation options + #for i in prange(n): + # s = 0 + # for j in range(m): + # s += a[j] * b[j, i] + # c[i] = s + for i in numba.parfors.parfor.internal_prange(m): + c += a[i] * b[i, :] + return c + +def dotmv_parallel_impl(a, b): + numba.parfors.parfor.init_prange() + m, n = a.shape + l = b.shape + # TODO: investigate assert_equiv + #assert_equiv("sizes of n, l do not match", n, l) + c = np.empty(m, a.dtype) + for i in numba.parfors.parfor.internal_prange(m): + s = 0 + for j in range(n): + s += a[i, j] * b[j] + c[i] = s + return c + +def dot_parallel_impl(return_type, atyp, btyp): + # Note that matrix matrix multiply is not translated. + if (isinstance(atyp, types.npytypes.Array) and + isinstance(btyp, types.npytypes.Array)): + if atyp.ndim == btyp.ndim == 1: + return dotvv_parallel_impl + # TODO: evaluate support for dotvm and enable + #elif atyp.ndim == 1 and btyp.ndim == 2: + # return dotvm_parallel_impl + elif atyp.ndim == 2 and btyp.ndim == 1: + return dotmv_parallel_impl + +def sum_parallel_impl(return_type, arg): + zero = return_type(0) + + if arg.ndim == 0: + def sum_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + def sum_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val += in_arr[i] + return val + else: + def sum_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.pndindex(in_arr.shape): + val += in_arr[i] + return val + return sum_1 + +def prod_parallel_impl(return_type, arg): + one = return_type(1) + + if arg.ndim == 0: + def prod_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + def prod_1(in_arr): + numba.parfors.parfor.init_prange() + val = one + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val *= in_arr[i] + return val + else: + def prod_1(in_arr): + numba.parfors.parfor.init_prange() + val = one + for i in numba.pndindex(in_arr.shape): + val *= in_arr[i] + return val + return prod_1 + + +def mean_parallel_impl(return_type, arg): + # can't reuse sum since output type is different + zero = return_type(0) + + if arg.ndim == 0: + def mean_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + def mean_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val += in_arr[i] + return val/len(in_arr) + else: + def mean_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.pndindex(in_arr.shape): + val += in_arr[i] + return val/in_arr.size + return mean_1 + +def var_parallel_impl(return_type, arg): + if arg.ndim == 0: + def var_1(in_arr): + return 0 + elif arg.ndim == 1: + def var_1(in_arr): + # Compute the mean + m = in_arr.mean() + # Compute the sum of square diffs + numba.parfors.parfor.init_prange() + ssd = 0 + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = in_arr[i] - m + ssd += np.real(val * np.conj(val)) + return ssd / len(in_arr) + else: + def var_1(in_arr): + # Compute the mean + m = in_arr.mean() + # Compute the sum of square diffs + numba.parfors.parfor.init_prange() + ssd = 0 + for i in numba.pndindex(in_arr.shape): + val = in_arr[i] - m + ssd += np.real(val * np.conj(val)) + return ssd / in_arr.size + return var_1 + +def std_parallel_impl(return_type, arg): + def std_1(in_arr): + return in_arr.var() ** 0.5 + return std_1 + +def arange_parallel_impl(return_type, *args, dtype=None): + inferred_dtype = as_dtype(return_type.dtype) + + def arange_1(stop): + return np.arange(0, stop, 1, inferred_dtype) + + def arange_1_dtype(stop, dtype): + return np.arange(0, stop, 1, dtype) + + def arange_2(start, stop): + return np.arange(start, stop, 1, inferred_dtype) + + def arange_2_dtype(start, stop, dtype): + return np.arange(start, stop, 1, dtype) + + def arange_3(start, stop, step): + return np.arange(start, stop, step, inferred_dtype) + + def arange_3_dtype(start, stop, step, dtype): + return np.arange(start, stop, step, dtype) + + if any(isinstance(a, types.Complex) for a in args): + def arange_4(start, stop, step, dtype): + numba.parfors.parfor.init_prange() + nitems_c = (stop - start) / step + nitems_r = math.ceil(nitems_c.real) + nitems_i = math.ceil(nitems_c.imag) + nitems = int(max(min(nitems_i, nitems_r), 0)) + arr = np.empty(nitems, dtype) + for i in numba.parfors.parfor.internal_prange(nitems): + arr[i] = start + i * step + return arr + else: + def arange_4(start, stop, step, dtype): + numba.parfors.parfor.init_prange() + nitems_r = math.ceil((stop - start) / step) + nitems = int(max(nitems_r, 0)) + arr = np.empty(nitems, dtype) + val = start + for i in numba.parfors.parfor.internal_prange(nitems): + arr[i] = start + i * step + return arr + + if len(args) == 1: + return arange_1 if dtype is None else arange_1_dtype + elif len(args) == 2: + return arange_2 if dtype is None else arange_2_dtype + elif len(args) == 3: + return arange_3 if dtype is None else arange_3_dtype + elif len(args) == 4: + return arange_4 + else: + raise ValueError("parallel arange with types {}".format(args)) + +def linspace_parallel_impl(return_type, *args): + dtype = as_dtype(return_type.dtype) + + def linspace_2(start, stop): + return np.linspace(start, stop, 50) + + def linspace_3(start, stop, num): + numba.parfors.parfor.init_prange() + arr = np.empty(num, dtype) + div = num - 1 + delta = stop - start + arr[0] = start + for i in numba.parfors.parfor.internal_prange(num): + arr[i] = start + delta * (i / div) + return arr + + if len(args) == 2: + return linspace_2 + elif len(args) == 3: + return linspace_3 + else: + raise ValueError("parallel linspace with types {}".format(args)) + +swap_functions_map = { + ('argmin', 'numpy'): lambda r,a: argmin_parallel_impl, + ('argmax', 'numpy'): lambda r,a: argmax_parallel_impl, + ('min', 'numpy'): min_parallel_impl, + ('max', 'numpy'): max_parallel_impl, + ('amin', 'numpy'): min_parallel_impl, + ('amax', 'numpy'): max_parallel_impl, + ('sum', 'numpy'): sum_parallel_impl, + ('prod', 'numpy'): prod_parallel_impl, + ('mean', 'numpy'): mean_parallel_impl, + ('var', 'numpy'): var_parallel_impl, + ('std', 'numpy'): std_parallel_impl, + ('dot', 'numpy'): dot_parallel_impl, + ('arange', 'numpy'): arange_parallel_impl, + ('linspace', 'numpy'): linspace_parallel_impl, +} + +def fill_parallel_impl(return_type, arr, val): + """Parallel implementation of ndarray.fill. The array on + which to operate is retrieved from get_call_name and + is passed along with the value to fill. + """ + if arr.ndim == 1: + def fill_1(in_arr, val): + numba.parfors.parfor.init_prange() + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + in_arr[i] = val + return None + else: + def fill_1(in_arr, val): + numba.parfors.parfor.init_prange() + for i in numba.pndindex(in_arr.shape): + in_arr[i] = val + return None + return fill_1 + +replace_functions_ndarray = { + 'fill': fill_parallel_impl, +} + +@register_jitable +def max_checker(arr_size): + if arr_size == 0: + raise ValueError(("zero-size array to reduction operation " + "maximum which has no identity")) + +@register_jitable +def min_checker(arr_size): + if arr_size == 0: + raise ValueError(("zero-size array to reduction operation " + "minimum which has no identity")) + +@register_jitable +def argmin_checker(arr_size): + if arr_size == 0: + raise ValueError("attempt to get argmin of an empty sequence") + +@register_jitable +def argmax_checker(arr_size): + if arr_size == 0: + raise ValueError("attempt to get argmax of an empty sequence") + +checker_impl = namedtuple('checker_impl', ['name', 'func']) + +replace_functions_checkers_map = { + ('argmin', 'numpy') : checker_impl('argmin_checker', argmin_checker), + ('argmax', 'numpy') : checker_impl('argmax_checker', argmax_checker), + ('min', 'numpy') : checker_impl('min_checker', min_checker), + ('max', 'numpy') : checker_impl('max_checker', max_checker), + ('amin', 'numpy') : checker_impl('min_checker', min_checker), + ('amax', 'numpy') : checker_impl('max_checker', max_checker), +} + + +class LoopNest(object): + + '''The LoopNest class holds information of a single loop including + the index variable (of a non-negative integer value), and the + range variable, e.g. range(r) is 0 to r-1 with step size 1. + ''' + + def __init__(self, index_variable, start, stop, step): + self.index_variable = index_variable + self.start = start + self.stop = stop + self.step = step + + + def __repr__(self): + return ("LoopNest(index_variable = {}, range = ({}, {}, {}))". + format(self.index_variable, self.start, self.stop, self.step)) + + def list_vars(self): + all_uses = [] + all_uses.append(self.index_variable) + if isinstance(self.start, ir.Var): + all_uses.append(self.start) + if isinstance(self.stop, ir.Var): + all_uses.append(self.stop) + if isinstance(self.step, ir.Var): + all_uses.append(self.step) + return all_uses + +class Parfor(ir.Expr, ir.Stmt): + + id_counter = 0 + + def __init__( + self, + loop_nests, + init_block, + loop_body, + loc, + index_var, + equiv_set, + pattern, + flags, + *, #only specify the options below by keyword + no_sequential_lowering=False, + races=None): + if races is None: + races = set() + super(Parfor, self).__init__( + op='parfor', + loc=loc + ) + + self.id = type(self).id_counter + type(self).id_counter += 1 + #self.input_info = input_info + #self.output_info = output_info + self.loop_nests = loop_nests + self.init_block = init_block + self.loop_body = loop_body + self.index_var = index_var + self.params = None # filled right before parallel lowering + self.equiv_set = equiv_set + # The parallel patterns this parfor was generated from and their options + # for example, a parfor could be from the stencil pattern with + # the neighborhood option + assert len(pattern) > 1 + self.patterns = [pattern] + self.flags = flags + # if True, this parfor shouldn't be lowered sequentially even with the + # sequential lowering option + self.no_sequential_lowering = no_sequential_lowering + self.races = races + self.redvars = [] + self.reddict = {} + # If the lowerer is None then the standard lowerer will be used. + # This can be set to a function to have that function act as the lowerer + # for this parfor. This lowerer field will also prevent parfors from + # being fused unless they have use the same lowerer. + self.lowerer = None + if config.DEBUG_ARRAY_OPT_STATS: + fmt = 'Parallel for-loop #{} is produced from pattern \'{}\' at {}' + print(fmt.format( + self.id, pattern, loc)) + + def __repr__(self): + return "id=" + str(self.id) + repr(self.loop_nests) + \ + repr(self.loop_body) + repr(self.index_var) + + def get_loop_nest_vars(self): + return [x.index_variable for x in self.loop_nests] + + def list_vars(self): + """list variables used (read/written) in this parfor by + traversing the body and combining block uses. + """ + all_uses = [] + for l, b in self.loop_body.items(): + for stmt in b.body: + all_uses += stmt.list_vars() + + for loop in self.loop_nests: + all_uses += loop.list_vars() + + for stmt in self.init_block.body: + all_uses += stmt.list_vars() + + return all_uses + + def get_shape_classes(self, var, typemap=None): + """get the shape classes for a given variable. + If a typemap is specified then use it for type resolution + """ + # We get shape classes from the equivalence set but that + # keeps its own typemap at a time prior to lowering. So + # if something is added during lowering then we can pass + # in a type map to use. We temporarily replace the + # equivalence set typemap, do the work and then restore + # the original on the way out. + if typemap is not None: + save_typemap = self.equiv_set.typemap + self.equiv_set.typemap = typemap + res = self.equiv_set.get_shape_classes(var) + if typemap is not None: + self.equiv_set.typemap = save_typemap + return res + + def dump(self, file=None): + file = file or sys.stdout + print(("begin parfor {}".format(self.id)).center(20, '-'), file=file) + print("index_var = ", self.index_var, file=file) + print("params = ", self.params, file=file) + print("races = ", self.races, file=file) + for loopnest in self.loop_nests: + print(loopnest, file=file) + print("init block:", file=file) + self.init_block.dump(file) + for offset, block in sorted(self.loop_body.items()): + print('label %s:' % (offset,), file=file) + block.dump(file) + print(("end parfor {}".format(self.id)).center(20, '-'), file=file) + + def validate_params(self, typemap): + """ + Check that Parfors params are of valid types. + """ + if self.params is None: + msg = ("Cannot run parameter validation on a Parfor with params " + "not set") + raise ValueError(msg) + for p in self.params: + ty = typemap.get(p) + if ty is None: + msg = ("Cannot validate parameter %s, there is no type " + "information available") + raise ValueError(msg) + if isinstance(ty, types.BaseTuple): + if ty.count > config.PARFOR_MAX_TUPLE_SIZE: + msg = ("Use of a tuple (%s) of length %d in a parallel region " + "exceeds the maximum supported tuple size. Since " + "Generalized Universal Functions back parallel regions " + "and those do not support tuples, tuples passed to " + "parallel regions are unpacked if their size is below " + "a certain threshold, currently configured to be %d. " + "This threshold can be modified using the Numba " + "environment variable NUMBA_PARFOR_MAX_TUPLE_SIZE.") + raise errors.UnsupportedParforsError(msg % + (p, ty.count, config.PARFOR_MAX_TUPLE_SIZE), + self.loc) + + +def _analyze_parfor(parfor, equiv_set, typemap, array_analysis): + """Recursive array analysis for parfor nodes. + """ + func_ir = array_analysis.func_ir + parfor_blocks = wrap_parfor_blocks(parfor) + # Since init_block get label 0 after wrap, we need to save + # the equivset for the real block label 0. + backup_equivset = array_analysis.equiv_sets.get(0, None) + array_analysis.run(parfor_blocks, equiv_set) + unwrap_parfor_blocks(parfor, parfor_blocks) + parfor.equiv_set = array_analysis.equiv_sets[0] + # Restore equivset for block 0 after parfor is unwrapped + if backup_equivset: + array_analysis.equiv_sets[0] = backup_equivset + return [], [] + +array_analysis.array_analysis_extensions[Parfor] = _analyze_parfor + +class ParforDiagnostics(object): + """Holds parfor diagnostic info, this is accumulated throughout the + PreParforPass and ParforPass, also in the closure inlining! + """ + def __init__(self): + # holds ref to the function for which this is providing diagnostics + self.func = None + # holds a map of the replaced functions + self.replaced_fns = dict() + # used to identify "internal" parfor functions + self.internal_name = '__numba_parfor_gufunc' + self.fusion_info = defaultdict(list) + self.nested_fusion_info = defaultdict(list) + self.fusion_reports = [] + self.hoist_info = {} + self.has_setup = False + + def setup(self, func_ir, fusion_enabled): + self.func_ir = func_ir + self.name = self.func_ir.func_id.func_qualname + self.line = self.func_ir.loc + self.fusion_enabled = fusion_enabled + if self.internal_name in self.name: + self.purpose = 'Internal parallel function' + else: + self.purpose = 'Function %s, %s' % (self.name, self.line) + # we store a reference to the parfors prior to fusion etc, the parfors + # do get mangled in the fusion process but in a predetermined manner + # and by holding a reference here the "before" state can be printed + self.initial_parfors = self.get_parfors() + self.has_setup = True + + @property + def has_setup(self): + return self._has_setup + + @has_setup.setter + def has_setup(self, state): + self._has_setup = state + + def count_parfors(self, blocks=None): + return len(self.get_parfors()) + + def _get_nested_parfors(self, parfor, parfors_list): + blocks = wrap_parfor_blocks(parfor) + self._get_parfors(blocks, parfors_list) + unwrap_parfor_blocks(parfor) + + def _get_parfors(self, blocks, parfors_list): + for label, blk in blocks.items(): + for stmt in blk.body: + if isinstance(stmt, Parfor): + parfors_list.append(stmt) + self._get_nested_parfors(stmt, parfors_list) + + def get_parfors(self): + parfors_list = [] + self._get_parfors(self.func_ir.blocks, parfors_list) + return parfors_list + + def hoisted_allocations(self): + allocs = [] + for pf_id, data in self.hoist_info.items(): + stmt = data.get('hoisted', []) + for inst in stmt: + if isinstance(inst.value, ir.Expr): + if inst.value.op == 'call': + call = guard(find_callname, self.func_ir, inst.value) + if call is not None and call == ('empty', 'numpy'): + allocs.append(inst) + return allocs + + def compute_graph_info(self, _a): + """ + compute adjacency list of the fused loops + and find the roots in of the lists + """ + a = copy.deepcopy(_a) + if a == {}: + return [], set() + + vtx = set() + for v in a.values(): + for x in v: + vtx.add(x) + + # find roots + potential_roots = set(a.keys()) + roots = potential_roots - vtx + if roots is None: + roots = set() + + # populate rest of adjacency list + not_roots = set() + for x in range(max(set(a.keys()).union(vtx)) + 1): + val = a.get(x) + if val is not None: + a[x] = val + elif val == []: + not_roots.add(x) # debug only + else: + a[x] = [] + + + # fold adjacency list into an actual list ordered + # by vtx + l = [] + for x in sorted(a.keys()): + l.append(a[x]) + + return l, roots #, not_roots + + def get_stats(self, fadj, nadj, root): + """ + Computes the number of fused and serialized loops + based on a fusion adjacency list `fadj` and a nested + parfors adjacency list `nadj` for the root, `root` + """ + def count_root(fadj, nadj, root, nfused, nserial): + for k in nadj[root]: + nserial += 1 + if nadj[k] == []: + nfused += len(fadj[k]) + else: + nf, ns = count_root(fadj, nadj, k, nfused, nserial) + nfused += nf + nserial = ns + return nfused, nserial + nfused, nserial = count_root(fadj, nadj, root, 0, 0) + return nfused, nserial + + def reachable_nodes(self, adj, root): + """ + returns a list of nodes reachable in an adjacency list from a + specified root + """ + fusers = [] + fusers.extend(adj[root]) + for k in adj[root]: + if adj[k] != []: + fusers.extend(self.reachable_nodes(adj, k)) + return fusers + + def sort_pf_by_line(self, pf_id, parfors_simple): + """ + pd_id - the parfors id + parfors_simple - the simple parfors map + """ + # this sorts parfors by source line number + pf = parfors_simple[pf_id][0] + pattern = pf.patterns[0] + line = max(0, pf.loc.line - 1) # why are these out by 1 ?! + filename = self.func_ir.loc.filename + nadj, nroots = self.compute_graph_info(self.nested_fusion_info) + fadj, froots = self.compute_graph_info(self.fusion_info) + graphs = [nadj, fadj] + + # If the parfor is internal, like internal prange, then the + # default line number is from its location in the numba source + # To get a more accurate line number, this first checks the + # adjacency graph for fused parfors that might not be internal + # and uses the minimum line number from there. If that fails + # (case where there's just a single internal parfor) the IR + # is walked backwards from the parfor location and the first non + # parfor statement line number is used. + if isinstance(pattern, tuple): + if pattern[1] == 'internal': + reported_loc = pattern[2][1] + if reported_loc.filename == filename: + return max(0, reported_loc.line - 1) + else: + # first recurse and check the adjacency list for + # something that is not an in internal parfor + tmp = [] + for adj in graphs: + if adj: # graph may be empty, e.g. no nesting + for k in adj[pf_id]: + tmp.append(self.sort_pf_by_line(k, parfors_simple)) + if tmp: + return max(0, min(tmp) - 1) + # second run through the parfor block to see if there's + # and reference to a line number in the user source + for blk in pf.loop_body.values(): + for stmt in blk.body: + if stmt.loc.filename == filename: + return max(0, stmt.loc.line - 1) + # finally run through the func_ir and look for the + # first non-parfor statement prior to this one and + # grab the line from that + for blk in self.func_ir.blocks.values(): + try: + idx = blk.body.index(pf) + for i in range(idx - 1, 0, -1): + stmt = blk.body[i] + if not isinstance(stmt, Parfor): + line = max(0, stmt.loc.line - 1) + break + except ValueError: + pass + return line + + def get_parfors_simple(self, print_loop_search): + parfors_simple = dict() + + # print in line order, parfors loop id is based on discovery order + for pf in sorted(self.initial_parfors, key=lambda x: x.loc.line): + # use 0 here, the parfors are mutated by the time this routine + # is called, however, fusion appends the patterns so we can just + # pull in the first as a "before fusion" emulation + r_pattern = pf.patterns[0] + pattern = pf.patterns[0] + loc = pf.loc + if isinstance(pattern, tuple): + if pattern[0] == 'prange': + if pattern[1] == 'internal': + replfn = '.'.join(reversed(list(pattern[2][0]))) + loc = pattern[2][1] + r_pattern = '%s %s' % (replfn, '(internal parallel version)') + elif pattern[1] == 'user': + r_pattern = "user defined prange" + elif pattern[1] == 'pndindex': + r_pattern = "internal pndindex" #FIXME: trace this! + else: + assert 0 + fmt = 'Parallel for-loop #%s: is produced from %s:\n %s\n \n' + if print_loop_search: + print_wrapped(fmt % (pf.id, loc, r_pattern)) + parfors_simple[pf.id] = (pf, loc, r_pattern) + return parfors_simple + + def get_all_lines(self, parfors_simple): + # ensure adjacency lists are the same size for both sets of info + # (nests and fusion may not traverse the same space, for + # convenience [] is used as a condition to halt recursion) + fadj, froots = self.compute_graph_info(self.fusion_info) + nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) + + if len(fadj) > len(nadj): + lim = len(fadj) + tmp = nadj + else: + lim = len(nadj) + tmp = fadj + for x in range(len(tmp), lim): + tmp.append([]) + + # This computes the roots of true loop nests (i.e. loops containing + # loops opposed to just a loop that's a root). + nroots = set() + if _nroots: + for r in _nroots: + if nadj[r] != []: + nroots.add(r) + all_roots = froots ^ nroots + + # This computes all the parfors at the top level that are either: + # - roots of loop fusion + # - roots of true loop nests + # it then combines these based on source line number for ease of + # producing output ordered in a manner similar to the code structure + froots_lines = {} + for x in froots: + line = self.sort_pf_by_line(x, parfors_simple) + froots_lines[line] = 'fuse', x, fadj + + nroots_lines = {} + for x in nroots: + line = self.sort_pf_by_line(x, parfors_simple) + nroots_lines[line] = 'nest', x, nadj + + all_lines = froots_lines.copy() + all_lines.update(nroots_lines) + return all_lines + + def source_listing(self, parfors_simple, purpose_str): + filename = self.func_ir.loc.filename + count = self.count_parfors() + func_name = self.func_ir.func_id.func + try: + lines = inspect.getsource(func_name).splitlines() + except OSError: # generated function + lines = None + if lines and parfors_simple: + src_width = max([len(x) for x in lines]) + map_line_to_pf = defaultdict(list) # parfors can alias lines + for k, v in parfors_simple.items(): + # TODO: do a better job of tracking parfors that are not in + # this file but are referred to, e.g. np.arange() + if parfors_simple[k][1].filename == filename: + match_line = self.sort_pf_by_line(k, parfors_simple) + map_line_to_pf[match_line].append(str(k)) + + max_pf_per_line = max([1] + [len(x) for x in map_line_to_pf.values()]) + width = src_width + (1 + max_pf_per_line * (len(str(count)) + 2)) + newlines = [] + newlines.append('\n') + newlines.append('Parallel loop listing for %s' % purpose_str) + newlines.append(width * '-' + '|loop #ID') + fmt = '{0:{1}}| {2}' + # why are these off by 1? + lstart = max(0, self.func_ir.loc.line - 1) + for no, line in enumerate(lines, lstart): + pf_ids = map_line_to_pf.get(no, None) + if pf_ids is not None: + pfstr = '#' + ', '.join(pf_ids) + else: + pfstr = '' + stripped = line.strip('\n') + srclen = len(stripped) + if pf_ids: + l = fmt.format(width * '-', width, pfstr) + else: + l = fmt.format(width * ' ', width, pfstr) + newlines.append(stripped + l[srclen:]) + print('\n'.join(newlines)) + else: + print("No source available") + + def print_unoptimised(self, lines): + # This prints the unoptimised parfors state + sword = '+--' + fac = len(sword) + fadj, froots = self.compute_graph_info(self.fusion_info) + nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) + + if len(fadj) > len(nadj): + lim = len(fadj) + tmp = nadj + else: + lim = len(nadj) + tmp = fadj + for x in range(len(tmp), lim): + tmp.append([]) + + def print_nest(fadj_, nadj_, theroot, reported, region_id): + def print_g(fadj_, nadj_, nroot, depth): + print_wrapped(fac * depth * ' ' + '%s%s %s' % (sword, nroot, '(parallel)')) + for k in nadj_[nroot]: + if nadj_[k] == []: + msg = [] + msg.append(fac * (depth + 1) * ' ' + '%s%s %s' % (sword, k, '(parallel)')) + if fadj_[k] != [] and k not in reported: + fused = self.reachable_nodes(fadj_, k) + for i in fused: + msg.append(fac * (depth + 1) * ' ' + '%s%s %s' % (sword, i, '(parallel)')) + reported.append(k) + print_wrapped('\n'.join(msg)) + else: + print_g(fadj_, nadj_, k, depth + 1) + + if nadj_[theroot] != []: + print_wrapped("Parallel region %s:" % region_id) + print_g(fadj_, nadj_, theroot, 0) + print("\n") + region_id = region_id + 1 + return region_id + + def print_fuse(ty, pf_id, adj, depth, region_id): + msg = [] + print_wrapped("Parallel region %s:" % region_id) + msg.append(fac * depth * ' ' + '%s%s %s' % (sword, pf_id, '(parallel)')) + if adj[pf_id] != []: + fused = sorted(self.reachable_nodes(adj, pf_id)) + for k in fused: + msg.append(fac * depth * ' ' + '%s%s %s' % (sword, k, '(parallel)')) + region_id = region_id + 1 + print_wrapped('\n'.join(msg)) + print("\n") + return region_id + + # Walk the parfors by src line and print optimised structure + region_id = 0 + reported = [] + for line, info in sorted(lines.items()): + opt_ty, pf_id, adj = info + if opt_ty == 'fuse': + if pf_id not in reported: + region_id = print_fuse('f', pf_id, adj, 0, region_id) + elif opt_ty == 'nest': + region_id = print_nest(fadj, nadj, pf_id, reported, region_id) + else: + assert 0 + + def print_optimised(self, lines): + # This prints the optimised output based on the transforms that + # occurred during loop fusion and rewriting of loop nests + sword = '+--' + fac = len(sword) + fadj, froots = self.compute_graph_info(self.fusion_info) + nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) + + if len(fadj) > len(nadj): + lim = len(fadj) + tmp = nadj + else: + lim = len(nadj) + tmp = fadj + for x in range(len(tmp), lim): + tmp.append([]) + + summary = dict() + # region : {fused, serialized} + + def print_nest(fadj_, nadj_, theroot, reported, region_id): + def print_g(fadj_, nadj_, nroot, depth): + for k in nadj_[nroot]: + msg = fac * depth * ' ' + '%s%s %s' % (sword, k, '(serial') + if nadj_[k] == []: + fused = [] + if fadj_[k] != [] and k not in reported: + fused = sorted(self.reachable_nodes(fadj_, k)) + msg += ", fused with loop(s): " + msg += ', '.join([str(x) for x in fused]) + msg += ')' + reported.append(k) + print_wrapped(msg) + summary[region_id]['fused'] += len(fused) + else: + print_wrapped(msg + ')') + print_g(fadj_, nadj_, k, depth + 1) + summary[region_id]['serialized'] += 1 + + if nadj_[theroot] != []: + print_wrapped("Parallel region %s:" % region_id) + print_wrapped('%s%s %s' % (sword, theroot, '(parallel)')) + summary[region_id] = {'root': theroot, 'fused': 0, 'serialized': 0} + print_g(fadj_, nadj_, theroot, 1) + print("\n") + region_id = region_id + 1 + return region_id + + def print_fuse(ty, pf_id, adj, depth, region_id): + print_wrapped("Parallel region %s:" % region_id) + msg = fac * depth * ' ' + '%s%s %s' % (sword, pf_id, '(parallel') + fused = [] + if adj[pf_id] != []: + fused = sorted(self.reachable_nodes(adj, pf_id)) + msg += ", fused with loop(s): " + msg += ', '.join([str(x) for x in fused]) + + summary[region_id] = {'root': pf_id, 'fused': len(fused), 'serialized': 0} + msg += ')' + print_wrapped(msg) + print("\n") + region_id = region_id + 1 + return region_id + + # Walk the parfors by src line and print optimised structure + region_id = 0 + reported = [] + for line, info in sorted(lines.items()): + opt_ty, pf_id, adj = info + if opt_ty == 'fuse': + if pf_id not in reported: + region_id = print_fuse('f', pf_id, adj, 0, region_id) + elif opt_ty == 'nest': + region_id = print_nest(fadj, nadj, pf_id, reported, region_id) + else: + assert 0 + + # print the summary of the fuse/serialize rewrite + if summary: + for k, v in sorted(summary.items()): + msg = ('\n \nParallel region %s (loop #%s) had %s ' + 'loop(s) fused') + root = v['root'] + fused = v['fused'] + serialized = v['serialized'] + if serialized != 0: + msg += (' and %s loop(s) ' + 'serialized as part of the larger ' + 'parallel loop (#%s).') + print_wrapped(msg % (k, root, fused, serialized, root)) + else: + msg += '.' + print_wrapped(msg % (k, root, fused)) + else: + print_wrapped("Parallel structure is already optimal.") + + def allocation_hoist(self): + found = False + print('Allocation hoisting:') + for pf_id, data in self.hoist_info.items(): + stmt = data.get('hoisted', []) + for inst in stmt: + if isinstance(inst.value, ir.Expr): + try: + attr = inst.value.attr + if attr == 'empty': + msg = ("The memory allocation derived from the " + "instruction at %s is hoisted out of the " + "parallel loop labelled #%s (it will be " + "performed before the loop is executed and " + "reused inside the loop):") + loc = inst.loc + print_wrapped(msg % (loc, pf_id)) + try: + path = os.path.relpath(loc.filename) + except ValueError: + path = os.path.abspath(loc.filename) + lines = linecache.getlines(path) + if lines and loc.line: + print_wrapped(" Allocation:: " + lines[0 if loc.line < 2 else loc.line - 1].strip()) + print_wrapped(" - numpy.empty() is used for the allocation.\n") + found = True + except (KeyError, AttributeError): + pass + if not found: + print_wrapped('No allocation hoisting found') + + def instruction_hoist(self): + print("") + print('Instruction hoisting:') + hoist_info_printed = False + if self.hoist_info: + for pf_id, data in self.hoist_info.items(): + hoisted = data.get('hoisted', None) + not_hoisted = data.get('not_hoisted', None) + if not hoisted and not not_hoisted: + print("loop #%s has nothing to hoist." % pf_id) + continue + + print("loop #%s:" % pf_id) + if hoisted: + print(" Has the following hoisted:") + [print(" %s" % y) for y in hoisted] + hoist_info_printed = True + if not_hoisted: + print(" Failed to hoist the following:") + [print(" %s: %s" % (y, x)) for x, y in not_hoisted] + hoist_info_printed = True + if not hoist_info_printed: + print_wrapped('No instruction hoisting found') + print_wrapped(80 * '-') + + def dump(self, level=1): + if not self.has_setup: + raise RuntimeError("self.setup has not been called") + name = self.func_ir.func_id.func_qualname + line = self.func_ir.loc + if self.internal_name in name: + purpose_str = 'Internal parallel functions ' + purpose = 'internal' + else: + purpose_str = ' Function %s, %s ' % (name, line) + purpose = 'user' + + print_loop_search = False + print_source_listing = False + print_fusion_search = False + print_fusion_summary = False + print_loopnest_rewrite = False + print_pre_optimised = False + print_post_optimised = False + print_allocation_hoist = False + print_instruction_hoist = False + print_internal = False + + # each level switches on progressively more output + if level in (1, 2, 3, 4): + print_source_listing = True + print_post_optimised = True + else: + raise ValueError("Report level unknown, should be one of 1, 2, 3, 4") + + if level in (2, 3, 4): + print_pre_optimised = True + + if level in (3, 4): + print_allocation_hoist = True + + if level == 3: + print_fusion_summary = True + print_loopnest_rewrite = True + + if level == 4: + print_fusion_search = True + print_instruction_hoist = True + print_internal = True + + if purpose == 'internal' and not print_internal: + return + + print_wrapped('\n ') + print_wrapped(_termwidth * "=") + print_wrapped((" Parallel Accelerator Optimizing: %s " % purpose_str).center(_termwidth, '=')) + print_wrapped(_termwidth * "=") + print_wrapped("") + +#----------- search section + if print_loop_search: + print_wrapped('Looking for parallel loops'.center(_termwidth, '-')) + parfors_simple = self.get_parfors_simple(print_loop_search) + + count = self.count_parfors() + if print_loop_search: + print_wrapped("\nFound %s parallel loops." % count) + print_wrapped('-' * _termwidth) + +#----------- augmented source section + filename = self.func_ir.loc.filename + try: + # Try to get a relative path + # ipython/jupyter input just returns as filename + path = os.path.relpath(filename) + except ValueError: + # Fallback to absolute path if error occurred in getting the + # relative path. + # This may happen on windows if the drive is different + path = os.path.abspath(filename) + + if print_source_listing: + self.source_listing(parfors_simple, purpose_str) + +#---------- these are used a lot here on in + sword = '+--' + parfors = self.get_parfors() # this is the mutated parfors + parfor_ids = [x.id for x in parfors] + n_parfors = len(parfor_ids) + +#----------- loop fusion section + if print_fusion_search or print_fusion_summary: + if not sequential_parfor_lowering: + print_wrapped(' Fusing loops '.center(_termwidth, '-')) + msg = ("Attempting fusion of parallel loops (combines loops " + "with similar properties)...\n") + print_wrapped(msg) + else: + msg = "Performing sequential lowering of loops...\n" + print_wrapped(msg) + print_wrapped(_termwidth * '-') + # if there are some parfors, print information about them! + if n_parfors > -1: + def dump_graph_indented(a, root_msg, node_msg): + fac = len(sword) + def print_graph(adj, roots): + def print_g(adj, root, depth): + for k in adj[root]: + print_wrapped(fac * depth * ' ' + '%s%s %s' % (sword, k, node_msg)) + if adj[k] != []: + print_g(adj, k, depth + 1) + for r in roots: + print_wrapped('%s%s %s' % (sword, r, root_msg)) + print_g(l, r, 1) + print_wrapped("") + l, roots = self.compute_graph_info(a) + print_graph(l, roots) + + if print_fusion_search: + for report in self.fusion_reports: + l1, l2, msg = report + print_wrapped(" Trying to fuse loops #%s and #%s:" % (l1, l2)) + print_wrapped(" %s" % msg) + + if self.fusion_info != {}: + if print_fusion_summary: + print_wrapped("\n \nFused loop summary:\n") + + dump_graph_indented(self.fusion_info, 'has the following loops fused into it:', '(fused)') + + if print_fusion_summary: + if self.fusion_enabled: + after_fusion = "Following the attempted fusion of parallel for-loops" + else: + after_fusion = "With fusion disabled" + + print_wrapped(('\n{} there are {} parallel for-loop(s) (originating from loops labelled: {}).').format( + after_fusion, n_parfors, ', '.join(['#%s' % x for x in parfor_ids]))) + print_wrapped(_termwidth * '-') + print_wrapped("") + +#----------- loop nest section + if print_loopnest_rewrite: + if self.nested_fusion_info != {}: + print_wrapped((" Optimising loop nests ").center(_termwidth, '-')) + print_wrapped("Attempting loop nest rewrites (optimising for the largest parallel loops)...\n ") + root_msg = 'is a parallel loop' + node_msg = '--> rewritten as a serial loop' + dump_graph_indented(self.nested_fusion_info, root_msg, node_msg) + print_wrapped(_termwidth * '-') + print_wrapped("") + +#---------- compute various properties and orderings in the data for subsequent use + all_lines = self.get_all_lines(parfors_simple) + + if print_pre_optimised: + print(' Before Optimisation '.center(_termwidth,'-')) + self.print_unoptimised(all_lines) + print(_termwidth * '-') + + if print_post_optimised: + print(' After Optimisation '.center(_termwidth,'-')) + self.print_optimised(all_lines) + print(_termwidth * '-') + print_wrapped("") + print_wrapped(_termwidth * '-') + print_wrapped("\n ") + +#----------- LICM section + if print_allocation_hoist or print_instruction_hoist: + print_wrapped('Loop invariant code motion'.center(80, '-')) + + if print_allocation_hoist: + self.allocation_hoist() + + if print_instruction_hoist: + self.instruction_hoist() + + else: # there are no parfors + print_wrapped('Function %s, %s, has no parallel for-loops.'.format(name, line)) + + def __str__(self): + r = "ParforDiagnostics:\n" + r += repr(self.replaced_fns) + return r + + def __repr__(self): + r = "ParforDiagnostics" + return r + + +class PreParforPass(object): + """Preprocessing for the Parfor pass. It mostly inlines parallel + implementations of numpy functions if available. + """ + def __init__(self, func_ir, typemap, calltypes, typingctx, targetctx, + options, swapped=None, replace_functions_map=None): + if swapped is None: + swapped = {} + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + self.typingctx = typingctx + self.targetctx = targetctx + self.options = options + # diagnostics + self.swapped = swapped + if replace_functions_map is None: + replace_functions_map = swap_functions_map + self.replace_functions_map = replace_functions_map + self.stats = { + 'replaced_func': 0, + 'replaced_dtype': 0, + } + + def run(self): + """Run pre-parfor processing pass. + """ + # e.g. convert A.sum() to np.sum(A) for easier match and optimization + canonicalize_array_math(self.func_ir, self.typemap, + self.calltypes, self.typingctx) + if self.options.numpy: + self._replace_parallel_functions(self.func_ir.blocks) + self.func_ir.blocks = simplify_CFG(self.func_ir.blocks) + + def _replace_parallel_functions(self, blocks): + """ + Replace functions with their parallel implementation in + replace_functions_map if available. + The implementation code is inlined to enable more optimization. + """ + swapped = self.swapped + from numba.core.inline_closurecall import inline_closure_call + work_list = list(blocks.items()) + while work_list: + label, block = work_list.pop() + for i, instr in enumerate(block.body): + if isinstance(instr, ir.Assign): + lhs = instr.target + lhs_typ = self.typemap[lhs.name] + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + # Try and inline known calls with their parallel implementations + def replace_func(): + func_def = get_definition(self.func_ir, expr.func) + callname = find_callname(self.func_ir, expr) + repl_func = self.replace_functions_map.get(callname, None) + # Handle method on array type + if (repl_func is None and + len(callname) == 2 and + isinstance(callname[1], ir.Var) and + isinstance(self.typemap[callname[1].name], + types.npytypes.Array)): + repl_func = replace_functions_ndarray.get(callname[0], None) + if repl_func is not None: + # Add the array that the method is on to the arg list. + expr.args.insert(0, callname[1]) + + require(repl_func is not None) + typs = tuple(self.typemap[x.name] for x in expr.args) + kws_typs = {k: self.typemap[x.name] for k, x in expr.kws} + try: + new_func = repl_func(lhs_typ, *typs, **kws_typs) + except Exception: + new_func = None + require(new_func is not None) + # bind arguments to the new_func + typs = utils.pysignature(new_func).bind(*typs, **kws_typs).args + + g = copy.copy(self.func_ir.func_id.func.__globals__) + g['numba'] = numba + g['np'] = numpy + g['math'] = math + # if the function being inlined has a function + # checking the inputs, find it and add it to globals + check = replace_functions_checkers_map.get(callname, + None) + if check is not None: + g[check.name] = check.func + # inline the parallel implementation + new_blocks, _ = inline_closure_call(self.func_ir, g, + block, i, new_func, self.typingctx, self.targetctx, + typs, self.typemap, self.calltypes, work_list) + call_table = get_call_table(new_blocks, topological_ordering=False) + + # find the prange in the new blocks and record it for use in diagnostics + for call in call_table: + for k, v in call.items(): + if v[0] == 'internal_prange': + swapped[k] = [callname, repl_func.__name__, func_def, block.body[i].loc] + break + return True + if guard(replace_func): + self.stats['replaced_func'] += 1 + break + elif (isinstance(expr, ir.Expr) and expr.op == 'getattr' and + expr.attr == 'dtype'): + # Replace getattr call "A.dtype" with numpy.dtype(). + # This helps remove superfluous dependencies from parfor. + typ = self.typemap[expr.value.name] + if isinstance(typ, types.npytypes.Array): + # Convert A.dtype to four statements. + # 1) Get numpy global. + # 2) Create var for known type of array as string + # constant. e.g. 'float64' + # 3) Get dtype function from numpy module. + # 4) Create var for numpy.dtype(var from #2). + + # Create var for numpy module. + dtype = typ.dtype + scope = block.scope + loc = instr.loc + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + self.typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + + # Create var for the inferred type of the array + # e.g., 'float64' + dtype_str = str(dtype) + if dtype_str == 'bool': + dtype_str = 'bool_' + typ_var = ir.Var( + scope, mk_unique_var("$np_typ_var"), loc) + self.typemap[typ_var.name] = types.StringLiteral( + dtype_str) + typ_var_assign = ir.Assign( + ir.Const(dtype_str, loc), typ_var, loc) + + # Get the dtype function from the numpy module. + dtype_attr_var = ir.Var(scope, mk_unique_var("$dtype_attr_var"), loc) + temp = find_template(numpy.dtype) + tfunc = numba.core.types.Function(temp) + tfunc.get_call_type(self.typingctx, (self.typemap[typ_var.name],), {}) + self.typemap[dtype_attr_var.name] = types.functions.Function(temp) + dtype_attr_getattr = ir.Expr.getattr(g_np_var, 'dtype', loc) + dtype_attr_assign = ir.Assign(dtype_attr_getattr, dtype_attr_var, loc) + + # Call numpy.dtype on the statically coded type two steps above. + dtype_var = ir.Var(scope, mk_unique_var("$dtype_var"), loc) + self.typemap[dtype_var.name] = types.npytypes.DType(dtype) + dtype_getattr = ir.Expr.call(dtype_attr_var, [typ_var], (), loc) + dtype_assign = ir.Assign(dtype_getattr, dtype_var, loc) + self.calltypes[dtype_getattr] = signature( + self.typemap[dtype_var.name], self.typemap[typ_var.name]) + + # The original A.dtype rhs is replaced with result of this call. + instr.value = dtype_var + # Add statements to body of the code. + block.body.insert(0, dtype_assign) + block.body.insert(0, dtype_attr_assign) + block.body.insert(0, typ_var_assign) + block.body.insert(0, g_np_assign) + self.stats['replaced_dtype'] += 1 + break + +def find_template(op): + for ft in numba.core.typing.templates.builtin_registry.functions: + if ft.key == op: + return ft + + +class ParforPassStates: + """This class encapsulates all internal states of the ParforPass. + """ + + def __init__(self, func_ir, typemap, calltypes, return_type, typingctx, + targetctx, options, flags, metadata, + diagnostics=ParforDiagnostics()): + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + self.typingctx = typingctx + self.targetctx = targetctx + self.return_type = return_type + self.options = options + self.diagnostics = diagnostics + self.swapped_fns = diagnostics.replaced_fns + self.fusion_info = diagnostics.fusion_info + self.nested_fusion_info = diagnostics.nested_fusion_info + + self.array_analysis = array_analysis.ArrayAnalysis( + self.typingctx, self.func_ir, self.typemap, self.calltypes, + ) + + ir_utils._the_max_label.update(max(func_ir.blocks.keys())) + self.flags = flags + self.metadata = metadata + if "parfors" not in metadata: + metadata["parfors"] = {} + + +class ConvertInplaceBinop: + """Parfor subpass to convert setitem on Arrays + """ + def __init__(self, pass_states): + """ + Parameters + ---------- + pass_states : ParforPassStates + """ + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + # convert expressions like A += ... where A is an array. + topo_order = find_topo_order(blocks) + # variables available in the program so far (used for finding map + # functions in array_expr lowering) + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + if isinstance(instr, ir.Assign): + lhs = instr.target + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'inplace_binop': + loc = expr.loc + target = expr.lhs + value = expr.rhs + target_typ = pass_states.typemap[target.name] + value_typ = pass_states.typemap[value.name] + # Handle A op= ... + if isinstance(target_typ, types.npytypes.Array): + # RHS is an array + if isinstance(value_typ, types.npytypes.Array): + new_instr = self._inplace_binop_to_parfor(equiv_set, + loc, expr.immutable_fn, target, value) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='inplace_binop'), + ) + instr = [new_instr, ir.Assign(target, lhs, loc)] + if isinstance(instr, list): + new_body.extend(instr) + else: + new_body.append(instr) + block.body = new_body + + def _inplace_binop_to_parfor(self, equiv_set, loc, op, target, value): + """generate parfor from setitem node with a boolean or slice array indices. + The value can be either a scalar or an array variable, and if a boolean index + is used for the latter case, the same index must be used for the value too. + """ + pass_states = self.pass_states + scope = target.scope + arr_typ = pass_states.typemap[target.name] + el_typ = arr_typ.dtype + init_block = ir.Block(scope, loc) + value_typ = pass_states.typemap[value.name] + + size_vars = equiv_set.get_shape(target) + + # generate loopnests and size variables from target correlations + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + + # generate body + body_label = next_label() + body_block = ir.Block(scope, loc) + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + # Read value. + value_var = ir.Var(scope, mk_unique_var("$value_var"), loc) + pass_states.typemap[value_var.name] = value_typ.dtype + getitem_call = ir.Expr.getitem(value, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + value_typ.dtype, value_typ, index_var_typ) + body_block.body.append(ir.Assign(getitem_call, value_var, loc)) + + # Read target + target_var = ir.Var(scope, mk_unique_var("$target_var"), loc) + pass_states.typemap[target_var.name] = el_typ + getitem_call = ir.Expr.getitem(target, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + el_typ, arr_typ, index_var_typ) + body_block.body.append(ir.Assign(getitem_call, target_var, loc)) + + # Create temp to hold result. + expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc) + pass_states.typemap[expr_out_var.name] = el_typ + + # Create binop and assign result to temporary. + binop_expr = ir.Expr.binop(op, target_var, value_var, loc) + body_block.body.append(ir.Assign(binop_expr, expr_out_var, loc)) + unified_type = self.pass_states.typingctx.unify_pairs(el_typ, value_typ.dtype) + pass_states.calltypes[binop_expr] = signature( + unified_type, unified_type, unified_type) + + # Write to target + setitem_node = ir.SetItem(target, index_var, expr_out_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, arr_typ, index_var_typ, el_typ) + body_block.body.append(setitem_node) + + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, + ('inplace_binop', ''), pass_states.flags) + parfor.loop_body = {body_label: body_block} + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from inplace_binop") + parfor.dump() + return parfor + + def _type_getitem(self, args): + fnty = operator.getitem + return self.pass_states.typingctx.resolve_function_type(fnty, tuple(args), {}) + + +def get_index_var(x): + return x.index if isinstance(x, ir.SetItem) else x.index_var + + +class ConvertSetItemPass: + """Parfor subpass to convert setitem on Arrays + """ + def __init__(self, pass_states): + """ + Parameters + ---------- + pass_states : ParforPassStates + """ + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + # convert setitem expressions like A[C] = c or A[C] = B[C] to parfor, + # where C is a boolean array. + topo_order = find_topo_order(blocks) + # variables available in the program so far (used for finding map + # functions in array_expr lowering) + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + if isinstance(instr, (ir.StaticSetItem, ir.SetItem)): + loc = instr.loc + target = instr.target + index = get_index_var(instr) + value = instr.value + target_typ = pass_states.typemap[target.name] + index_typ = pass_states.typemap[index.name] + value_typ = pass_states.typemap[value.name] + # Handle A[boolean_array] = + if isinstance(target_typ, types.npytypes.Array): + if (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Boolean) and + target_typ.ndim == index_typ.ndim): + # RHS is a scalar number + if isinstance(value_typ, types.Number): + new_instr = self._setitem_to_parfor(equiv_set, + loc, target, index, value) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='masked_assign_broadcast_scalar'), + ) + instr = new_instr + # RHS is an array + elif isinstance(value_typ, types.npytypes.Array): + val_def = guard(get_definition, pass_states.func_ir, + value.name) + if (isinstance(val_def, ir.Expr) and + val_def.op == 'getitem' and + val_def.index.name == index.name): + new_instr = self._setitem_to_parfor(equiv_set, + loc, target, index, val_def.value) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='masked_assign_array'), + ) + instr = new_instr + else: + # Handle A[:] = x + shape = equiv_set.get_shape(instr) + # Don't converted broadcasted setitems into parfors. + if isinstance(index_typ, types.BaseTuple): + # The sliced dims are those in the index that + # are made of slices. Count the numbers of slices + # in the index tuple. + sliced_dims = len(list(filter( + lambda x: isinstance(x, types.misc.SliceType), + index_typ.types))) + elif isinstance(index_typ, types.misc.SliceType): + # For singular indices there can be a bare slice + # and if so there is one dimension being set. + sliced_dims = 1 + else: + sliced_dims = 0 + + # Only create a parfor for this setitem if we know the + # shape of the output and number of dimensions set is + # equal to the number of dimensions on the right side. + if (shape is not None and + (not isinstance(value_typ, types.npytypes.Array) or + sliced_dims == value_typ.ndim)): + new_instr = self._setitem_to_parfor(equiv_set, + loc, target, index, value, shape=shape) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='slice'), + ) + instr = new_instr + new_body.append(instr) + block.body = new_body + + def _setitem_to_parfor(self, equiv_set, loc, target, index, value, shape=None): + """generate parfor from setitem node with a boolean or slice array indices. + The value can be either a scalar or an array variable, and if a boolean index + is used for the latter case, the same index must be used for the value too. + """ + pass_states = self.pass_states + scope = target.scope + arr_typ = pass_states.typemap[target.name] + el_typ = arr_typ.dtype + index_typ = pass_states.typemap[index.name] + init_block = ir.Block(scope, loc) + + if shape: + # Slice index is being used on the target array, we'll have to create + # a sub-array so that the target dimension matches the given shape. + assert(isinstance(index_typ, types.BaseTuple) or + isinstance(index_typ, types.SliceType)) + # setitem has a custom target shape + size_vars = shape + # create a new target array via getitem + subarr_var = ir.Var(scope, mk_unique_var("$subarr"), loc) + getitem_call = ir.Expr.getitem(target, index, loc) + subarr_typ = typing.arraydecl.get_array_index_type( arr_typ, index_typ).result + pass_states.typemap[subarr_var.name] = subarr_typ + pass_states.calltypes[getitem_call] = self._type_getitem((arr_typ, index_typ)) + init_block.append(ir.Assign(getitem_call, subarr_var, loc)) + target = subarr_var + else: + # Otherwise it is a boolean array that is used as index. + assert(isinstance(index_typ, types.ArrayCompatible)) + size_vars = equiv_set.get_shape(target) + bool_typ = index_typ.dtype + + # generate loopnests and size variables from lhs correlations + loopnests = [] + index_vars = [] + for size_var in size_vars: + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + index_vars.append(index_var) + pass_states.typemap[index_var.name] = types.uintp + loopnests.append(LoopNest(index_var, 0, size_var, 1)) + + # generate body + body_label = next_label() + body_block = ir.Block(scope, loc) + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, + ('setitem', ''), pass_states.flags) + if shape: + # slice subarray + parfor.loop_body = {body_label: body_block} + true_block = body_block + end_label = None + else: + # boolean mask + true_label = next_label() + true_block = ir.Block(scope, loc) + end_label = next_label() + end_block = ir.Block(scope, loc) + parfor.loop_body = {body_label: body_block, + true_label: true_block, + end_label: end_block, + } + mask_var = ir.Var(scope, mk_unique_var("$mask_var"), loc) + pass_states.typemap[mask_var.name] = bool_typ + mask_val = ir.Expr.getitem(index, index_var, loc) + body_block.body.extend([ + ir.Assign(mask_val, mask_var, loc), + ir.Branch(mask_var, true_label, end_label, loc) + ]) + + value_typ = pass_states.typemap[value.name] + if isinstance(value_typ, types.npytypes.Array): + value_var = ir.Var(scope, mk_unique_var("$value_var"), loc) + pass_states.typemap[value_var.name] = value_typ.dtype + getitem_call = ir.Expr.getitem(value, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + value_typ.dtype, value_typ, index_var_typ) + true_block.body.append(ir.Assign(getitem_call, value_var, loc)) + else: + value_var = value + setitem_node = ir.SetItem(target, index_var, value_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, pass_states.typemap[target.name], index_var_typ, el_typ) + true_block.body.append(setitem_node) + if end_label: + true_block.body.append(ir.Jump(end_label, loc)) + + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from setitem") + parfor.dump() + return parfor + + def _type_getitem(self, args): + fnty = operator.getitem + return self.pass_states.typingctx.resolve_function_type(fnty, tuple(args), {}) + + +def _make_index_var(typemap, scope, index_vars, body_block, force_tuple=False): + """ When generating a SetItem call to an array in a parfor, the general + strategy is to generate a tuple if the array is more than 1 dimension. + If it is 1 dimensional then you can use a simple variable. This routine + is also used when converting pndindex to parfor but pndindex requires a + tuple even if the iteration space is 1 dimensional. The pndindex use of + this function will use force_tuple to make the output index a tuple even + if it is one dimensional. + """ + ndims = len(index_vars) + loc = body_block.loc + if ndims > 1 or force_tuple: + tuple_var = ir.Var(scope, mk_unique_var( + "$parfor_index_tuple_var"), loc) + typemap[tuple_var.name] = types.containers.UniTuple( + types.uintp, ndims) + tuple_call = ir.Expr.build_tuple(list(index_vars), loc) + tuple_assign = ir.Assign(tuple_call, tuple_var, loc) + body_block.body.append(tuple_assign) + return tuple_var, types.containers.UniTuple(types.uintp, ndims) + elif ndims == 1: + return index_vars[0], types.uintp + else: + raise errors.UnsupportedRewriteError( + "Parfor does not handle arrays of dimension 0", + loc=loc, + ) + + +def _mk_parfor_loops(typemap, size_vars, scope, loc): + """ + Create loop index variables and build LoopNest objects for a parfor. + """ + loopnests = [] + index_vars = [] + for size_var in size_vars: + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + index_vars.append(index_var) + typemap[index_var.name] = types.uintp + loopnests.append(LoopNest(index_var, 0, size_var, 1)) + return index_vars, loopnests + +class ConvertNumpyPass: + """ + Convert supported Numpy functions, as well as arrayexpr nodes, to + parfor nodes. + """ + def __init__(self, pass_states): + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + topo_order = find_topo_order(blocks) + # variables available in the program so far (used for finding map + # functions in array_expr lowering) + avail_vars = [] + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + if isinstance(instr, ir.Assign): + expr = instr.value + lhs = instr.target + lhs_typ = self.pass_states.typemap[lhs.name] + if self._is_C_or_F_order(lhs_typ): + if guard(self._is_supported_npycall, expr): + new_instr = self._numpy_to_parfor(equiv_set, lhs, expr) + if new_instr is not None: + self.rewritten.append(dict( + old=instr, + new=new_instr, + reason='numpy_allocator', + )) + instr = new_instr + elif isinstance(expr, ir.Expr) and expr.op == 'arrayexpr': + new_instr = self._arrayexpr_to_parfor( + equiv_set, lhs, expr, avail_vars) + self.rewritten.append(dict( + old=instr, + new=new_instr, + reason='arrayexpr', + )) + instr = new_instr + avail_vars.append(lhs.name) + new_body.append(instr) + block.body = new_body + + def _is_C_order(self, arr_name): + if isinstance(arr_name, types.npytypes.Array): + return arr_name.layout == 'C' and arr_name.ndim > 0 + elif arr_name is str: + typ = self.pass_states.typemap[arr_name] + return (isinstance(typ, types.npytypes.Array) and + typ.layout == 'C' and + typ.ndim > 0) + else: + return False + + def _is_C_or_F_order(self, arr_name): + if isinstance(arr_name, types.npytypes.Array): + return (arr_name.layout == 'C' or arr_name.layout == 'F') and arr_name.ndim > 0 + elif arr_name is str: + typ = self.pass_states.typemap[arr_name] + return (isinstance(typ, types.npytypes.Array) and + (typ.layout == 'C' or typ.layout == 'F') and + typ.ndim > 0) + else: + return False + + def _arrayexpr_to_parfor(self, equiv_set, lhs, arrayexpr, avail_vars): + """generate parfor from arrayexpr node, which is essentially a + map with recursive tree. + """ + pass_states = self.pass_states + scope = lhs.scope + loc = lhs.loc + expr = arrayexpr.expr + arr_typ = pass_states.typemap[lhs.name] + el_typ = arr_typ.dtype + + # generate loopnests and size variables from lhs correlations + size_vars = equiv_set.get_shape(lhs) + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + + # generate init block and body + init_block = ir.Block(scope, loc) + init_block.body = mk_alloc( + pass_states.typingctx, + pass_states.typemap, pass_states.calltypes, lhs, + tuple(size_vars), el_typ, scope, loc, + pass_states.typemap[lhs.name]) + body_label = next_label() + body_block = ir.Block(scope, loc) + expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc) + pass_states.typemap[expr_out_var.name] = el_typ + + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + body_block.body.extend( + _arrayexpr_tree_to_ir( + pass_states.func_ir, + pass_states.typingctx, + pass_states.typemap, + pass_states.calltypes, + equiv_set, + init_block, + expr_out_var, + expr, + index_var, + index_vars, + avail_vars)) + + pat = ('array expression {}'.format(repr_arrayexpr(arrayexpr.expr)),) + + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, pat[0], pass_states.flags) + + setitem_node = ir.SetItem(lhs, index_var, expr_out_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, pass_states.typemap[lhs.name], index_var_typ, el_typ) + body_block.body.append(setitem_node) + parfor.loop_body = {body_label: body_block} + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from arrayexpr") + parfor.dump() + return parfor + + def _is_supported_npycall(self, expr): + """check if we support parfor translation for + this Numpy call. + """ + call_name, mod_name = find_callname(self.pass_states.func_ir, expr) + if not (isinstance(mod_name, str) and mod_name.startswith('numpy')): + return False + if call_name in ['zeros', 'ones']: + return True + if mod_name == 'numpy.random' and call_name in random_calls: + return True + # TODO: add more calls + return False + + def _numpy_to_parfor(self, equiv_set, lhs, expr): + call_name, mod_name = find_callname(self.pass_states.func_ir, expr) + args = expr.args + kws = dict(expr.kws) + if call_name in ['zeros', 'ones'] or mod_name == 'numpy.random': + return self._numpy_map_to_parfor(equiv_set, call_name, lhs, args, kws, expr) + # return error if we couldn't handle it (avoid rewrite infinite loop) + raise errors.UnsupportedRewriteError( + f"parfor translation failed for {expr}", loc=expr.loc, + ) + + def _numpy_map_to_parfor(self, equiv_set, call_name, lhs, args, kws, expr): + """generate parfor from Numpy calls that are maps. + """ + pass_states = self.pass_states + scope = lhs.scope + loc = lhs.loc + arr_typ = pass_states.typemap[lhs.name] + el_typ = arr_typ.dtype + + # generate loopnests and size variables from lhs correlations + size_vars = equiv_set.get_shape(lhs) + if size_vars is None: + if config.DEBUG_ARRAY_OPT >= 1: + print("Could not convert numpy map to parfor, unknown size") + return None + + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + + # generate init block and body + init_block = ir.Block(scope, loc) + init_block.body = mk_alloc( + pass_states.typingctx, + pass_states.typemap, pass_states.calltypes, lhs, + tuple(size_vars), el_typ, scope, loc, + pass_states.typemap[lhs.name]) + body_label = next_label() + body_block = ir.Block(scope, loc) + expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc) + pass_states.typemap[expr_out_var.name] = el_typ + + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + if call_name == 'zeros': + value = ir.Const(el_typ(0), loc) + elif call_name == 'ones': + value = ir.Const(el_typ(1), loc) + elif call_name in random_calls: + # remove size arg to reuse the call expr for single value + _remove_size_arg(call_name, expr) + # update expr type + new_arg_typs, new_kw_types = _get_call_arg_types( + expr, pass_states.typemap) + pass_states.calltypes.pop(expr) + pass_states.calltypes[expr] = pass_states.typemap[expr.func.name].get_call_type( + typing.Context(), new_arg_typs, new_kw_types) + value = expr + else: + raise NotImplementedError( + "Map of numpy.{} to parfor is not implemented".format(call_name)) + + value_assign = ir.Assign(value, expr_out_var, loc) + body_block.body.append(value_assign) + + setitem_node = ir.SetItem(lhs, index_var, expr_out_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, pass_states.typemap[lhs.name], index_var_typ, el_typ) + body_block.body.append(setitem_node) + + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, + ('{} function'.format(call_name,), 'NumPy mapping'), + pass_states.flags) + parfor.loop_body = {body_label: body_block} + if config.DEBUG_ARRAY_OPT >= 1: + print("generated parfor for numpy map:") + parfor.dump() + return parfor + + +class ConvertReducePass: + """ + Find reduce() calls and convert them to parfors. + """ + def __init__(self, pass_states): + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + + topo_order = find_topo_order(blocks) + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + parfor = None + if isinstance(instr, ir.Assign): + loc = instr.loc + lhs = instr.target + expr = instr.value + callname = guard(find_callname, pass_states.func_ir, expr) + if (callname == ('reduce', 'builtins') + or callname == ('reduce', '_functools')): + # reduce function with generic function + parfor = guard(self._reduce_to_parfor, equiv_set, lhs, + expr.args, loc) + if parfor: + self.rewritten.append(dict( + new=parfor, + old=instr, + reason='reduce', + )) + instr = parfor + new_body.append(instr) + block.body = new_body + return + + def _reduce_to_parfor(self, equiv_set, lhs, args, loc): + """ + Convert a reduce call to a parfor. + The call arguments should be (call_name, array, init_value). + """ + pass_states = self.pass_states + + scope = lhs.scope + call_name = args[0] + in_arr = args[1] + arr_def = get_definition(pass_states.func_ir, in_arr.name) + + mask_var = None + mask_indices = None + + # Search for array[boolean_mask] + mask_query_result = guard(_find_mask, pass_states.typemap, pass_states.func_ir, arr_def) + if mask_query_result: + in_arr, mask_var, mask_typ, mask_indices = mask_query_result + + init_val = args[2] + size_vars = equiv_set.get_shape(in_arr if mask_indices is None else mask_var) + if size_vars is None: + return None + + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + mask_index = index_vars + if mask_indices: + # the following is never tested + raise AssertionError("unreachable") + index_vars = tuple(x if x else index_vars[0] for x in mask_indices) + acc_var = lhs + + # init block has to init the reduction variable + init_block = ir.Block(scope, loc) + init_block.body.append(ir.Assign(init_val, acc_var, loc)) + + # produce loop body + body_label = next_label() + index_var, loop_body = self._mk_reduction_body(call_name, + scope, loc, index_vars, in_arr, acc_var) + if mask_indices: + # the following is never tested + raise AssertionError("unreachable") + index_var = mask_index[0] + + if mask_var is not None: + true_label = min(loop_body.keys()) + false_label = max(loop_body.keys()) + body_block = ir.Block(scope, loc) + loop_body[body_label] = body_block + mask = ir.Var(scope, mk_unique_var("$mask_val"), loc) + pass_states.typemap[mask.name] = mask_typ + mask_val = ir.Expr.getitem(mask_var, index_var, loc) + body_block.body.extend([ + ir.Assign(mask_val, mask, loc), + ir.Branch(mask, true_label, false_label, loc) + ]) + + parfor = Parfor(loopnests, init_block, loop_body, loc, index_var, + equiv_set, ('{} function'.format(call_name), + 'reduction'), pass_states.flags) + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from reduction") + parfor.dump() + return parfor + + def _mk_reduction_body(self, call_name, scope, loc, + index_vars, in_arr, acc_var): + """ + Produce the body blocks for a reduction function indicated by call_name. + """ + from numba.core.inline_closurecall import check_reduce_func + + pass_states = self.pass_states + reduce_func = get_definition(pass_states.func_ir, call_name) + fcode = check_reduce_func(pass_states.func_ir, reduce_func) + + arr_typ = pass_states.typemap[in_arr.name] + in_typ = arr_typ.dtype + body_block = ir.Block(scope, loc) + index_var, index_var_type = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + tmp_var = ir.Var(scope, mk_unique_var("$val"), loc) + pass_states.typemap[tmp_var.name] = in_typ + getitem_call = ir.Expr.getitem(in_arr, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + in_typ, arr_typ, index_var_type) + body_block.append(ir.Assign(getitem_call, tmp_var, loc)) + + reduce_f_ir = compile_to_numba_ir(fcode, + pass_states.func_ir.func_id.func.__globals__, + pass_states.typingctx, + pass_states.targetctx, + (in_typ, in_typ), + pass_states.typemap, + pass_states.calltypes) + loop_body = reduce_f_ir.blocks + end_label = next_label() + end_block = ir.Block(scope, loc) + loop_body[end_label] = end_block + first_reduce_label = min(reduce_f_ir.blocks.keys()) + first_reduce_block = reduce_f_ir.blocks[first_reduce_label] + body_block.body.extend(first_reduce_block.body) + first_reduce_block.body = body_block.body + replace_arg_nodes(first_reduce_block, [acc_var, tmp_var]) + replace_returns(loop_body, acc_var, end_label) + return index_var, loop_body + + +class ConvertLoopPass: + """Build Parfor nodes from prange loops. + """ + def __init__(self, pass_states): + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + + call_table, _ = get_call_table(blocks) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + loops = cfg.loops() + sized_loops = [(loops[k], len(loops[k].body)) for k in loops.keys()] + moved_blocks = [] + # We go over all loops, smaller loops first (inner first) + for loop, s in sorted(sized_loops, key=lambda tup: tup[1]): + if len(loop.entries) != 1 or len(loop.exits) != 1: + if not config.DISABLE_PERFORMANCE_WARNINGS: + for entry in loop.entries: + for inst in blocks[entry].body: + # if prange or pndindex call + if ( + isinstance(inst, ir.Assign) + and isinstance(inst.value, ir.Expr) + and inst.value.op == "call" + and self._is_parallel_loop( + inst.value.func.name, call_table) + ): + msg = "\nprange or pndindex loop " \ + "will not be executed in " \ + "parallel due to there being more than one " \ + "entry to or exit from the loop (e.g., an " \ + "assertion)." + warnings.warn( + errors.NumbaPerformanceWarning( + msg, inst.loc)) + continue + + entry = list(loop.entries)[0] + for inst in blocks[entry].body: + # if prange or pndindex call + if (isinstance(inst, ir.Assign) + and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and self._is_parallel_loop(inst.value.func.name, call_table)): + # Here we've found a parallel loop, either prange or pndindex. + # We create a parfor from this loop and then overwrite the contents + # of the original loop header block to contain this parfor and then + # a jump to the original loop exit block. Other blocks in the + # original loop are discarded. + body_labels = [ l for l in loop.body if + l in blocks and l != loop.header ] + args = inst.value.args + loop_kind, loop_replacing = self._get_loop_kind(inst.value.func.name, + call_table) + # Get the body of the header of the loops minus the branch terminator + # The general approach is to prepend the header block to the first + # body block and then let dead code removal handle removing unneeded + # statements. Not all statements in the header block are unnecessary. + header_body = blocks[loop.header].body[:-1] + # find loop index variable (pair_first in header block) + loop_index = None + for hbi, stmt in enumerate(header_body): + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'pair_first'): + loop_index = stmt.target.name + li_index = hbi + break + assert(loop_index is not None) + # Remove pair_first from header. + # We have to remove the pair_first by hand since it causes problems + # for some code below if we don't. + header_body = header_body[:li_index] + header_body[li_index+1:] + + # loop_index may be assigned to other vars + # get header copies to find all of them + cps, _ = get_block_copies({0: blocks[loop.header]}, + pass_states.typemap) + cps = cps[0] + loop_index_vars = set(t for t, v in cps if v == loop_index) + loop_index_vars.add(loop_index) + + scope = blocks[entry].scope + loc = inst.loc + equiv_set = pass_states.array_analysis.get_equiv_set(loop.header) + init_block = ir.Block(scope, loc) + init_block.body = self._get_prange_init_block(blocks[entry], + call_table, args) + loop_body = {l: blocks[l] for l in body_labels} + # Add an empty block to the end of loop body + end_label = next_label() + loop_body[end_label] = ir.Block(scope, loc) + + # Detect races in the prange. + # Races are defs in the parfor body that are live at the exit block. + bodydefs = set() + for bl in body_labels: + bodydefs = bodydefs.union(usedefs.defmap[bl]) + exit_lives = set() + for bl in loop.exits: + exit_lives = exit_lives.union(live_map[bl]) + races = bodydefs.intersection(exit_lives) + # It is possible for the result of an ir.Global to be flagged + # as a race if it is defined in this Parfor and then used in + # a subsequent Parfor. push_call_vars() in the Parfor pass + # copies such ir.Global nodes into the Parfors in which they + # are used so no need to treat things of type Module as a race. + races = races.intersection({x for x in races + if not isinstance(pass_states.typemap[x], types.misc.Module)}) + + # replace jumps to header block with the end block + for l in body_labels: + last_inst = loop_body[l].body[-1] + if (isinstance(last_inst, ir.Jump) and + last_inst.target == loop.header): + last_inst.target = end_label + + def find_indexed_arrays(): + """find expressions that involve getitem using the + index variable. Return both the arrays and expressions. + """ + indices = copy.copy(loop_index_vars) + for block in loop_body.values(): + for inst in block.find_insts(ir.Assign): + if (isinstance(inst.value, ir.Var) and + inst.value.name in indices): + indices.add(inst.target.name) + arrs = [] + exprs = [] + for block in loop_body.values(): + for inst in block.body: + lv = set(x.name for x in inst.list_vars()) + if lv & indices: + if lv.issubset(indices): + continue + require(isinstance(inst, ir.Assign)) + expr = inst.value + require(isinstance(expr, ir.Expr) and + expr.op in ['getitem', 'static_getitem']) + arrs.append(expr.value.name) + exprs.append(expr) + return arrs, exprs + + mask_var = None + mask_indices = None + def find_mask_from_size(size_var): + """Find the case where size_var is defined by A[M].shape, + where M is a boolean array. + """ + size_def = get_definition(pass_states.func_ir, size_var) + require(size_def and isinstance(size_def, ir.Expr) and + size_def.op == 'getattr' and size_def.attr == 'shape') + arr_var = size_def.value + live_vars = set.union(*[live_map[l] for l in loop.exits]) + index_arrs, index_exprs = find_indexed_arrays() + require([arr_var.name] == list(index_arrs)) + # input array has to be dead after loop + require(arr_var.name not in live_vars) + # loop for arr's definition, where size = arr.shape + arr_def = get_definition(pass_states.func_ir, size_def.value) + result = _find_mask(pass_states.typemap, pass_states.func_ir, arr_def) + + # The following is never tested. + raise AssertionError("unreachable") + # Found the mask. + # Replace B[i] with A[i], where B = A[M] + for expr in index_exprs: + expr.value = result[0] + return result + + # pndindex and prange are provably positive except when + # user provides negative start to prange() + unsigned_index = True + # TODO: support array mask optimization for prange + # TODO: refactor and simplify array mask optimization + if loop_kind == 'pndindex': + assert(equiv_set.has_shape(args[0])) + # see if input array to pndindex is output of array + # mask like B = A[M] + result = guard(find_mask_from_size, args[0]) + if result: + in_arr, mask_var, mask_typ, mask_indices = result + else: + in_arr = args[0] + assert(isinstance(in_arr, ir.Var)) + in_arr_typ = pass_states.typemap[in_arr.name] + if isinstance(in_arr_typ, types.Integer): + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + pass_states.typemap[index_var.name] = types.uintp + loops = [LoopNest(index_var, 0, in_arr, 1)] + index_vars = [index_var] + else: + size_vars = equiv_set.get_shape(in_arr + if mask_indices is None else mask_var) + index_vars, loops = _mk_parfor_loops( + pass_states.typemap, size_vars, scope, loc, + ) + assert(len(loops) > 0) + orig_index = index_vars + if mask_indices: + # replace mask indices if required; + # integer indices of original array should be used + # instead of parfor indices + index_vars = tuple(x if x else index_vars[0] + for x in mask_indices) + first_body_block = loop_body[min(loop_body.keys())] + body_block = ir.Block(scope, loc) + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block, + force_tuple=False + ) + body = body_block.body + first_body_block.body + first_body_block.body = body + if mask_indices: + orig_index_var = orig_index[0] + else: + orig_index_var = index_var + + # if masked array optimization is being applied, create + # the branch for array selection + if mask_var is not None: + # The following code are not tested + raise AssertionError("unreachable") + body_label = next_label() + # loop_body needs new labels greater than body_label + loop_body = add_offset_to_labels(loop_body, + body_label - min(loop_body.keys()) + 1) + labels = loop_body.keys() + true_label = min(labels) + false_label = max(labels) + body_block = ir.Block(scope, loc) + loop_body[body_label] = body_block + mask = ir.Var(scope, mk_unique_var("$mask_val"), loc) + pass_states.typemap[mask.name] = mask_typ + mask_val = ir.Expr.getitem(mask_var, orig_index_var, loc) + body_block.body.extend([ + ir.Assign(mask_val, mask, loc), + ir.Branch(mask, true_label, false_label, loc) + ]) + else: # prange + start = 0 + step = 1 + size_var = args[0] + if len(args) == 2: + start = args[0] + size_var = args[1] + if len(args) == 3: + start = args[0] + size_var = args[1] + try: + step = pass_states.func_ir.get_definition(args[2]) + except KeyError: + raise errors.UnsupportedRewriteError( + "Only known step size is supported for prange", + loc=inst.loc, + ) + if not isinstance(step, ir.Const): + raise errors.UnsupportedRewriteError( + "Only constant step size is supported for prange", + loc=inst.loc, + ) + step = step.value + if step != 1: + raise errors.UnsupportedRewriteError( + "Only constant step size of 1 is supported for prange", + loc=inst.loc, + ) + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + # assume user-provided start to prange can be negative + # this is the only case parfor can have negative index + if isinstance(start, int) and start >= 0: + index_var_typ = types.uintp + else: + index_var_typ = types.intp + unsigned_index = False + loops = [LoopNest(index_var, start, size_var, step)] + pass_states.typemap[index_var.name] = index_var_typ + + # We can't just drop the header block since there can be things + # in there other than the prange looping infrastructure. + # So we just add the header to the first loop body block (minus the + # branch) and let dead code elimination remove the unnecessary parts. + first_body_label = min(loop_body.keys()) + loop_body[first_body_label].body = header_body + loop_body[first_body_label].body + + index_var_map = {v: index_var for v in loop_index_vars} + replace_vars(loop_body, index_var_map) + if unsigned_index: + # need to replace signed array access indices to enable + # optimizations (see #2846) + self._replace_loop_access_indices( + loop_body, loop_index_vars, index_var) + parfor = Parfor(loops, init_block, loop_body, loc, + orig_index_var if mask_indices else index_var, + equiv_set, + ("prange", loop_kind, loop_replacing), + pass_states.flags, races=races) + + blocks[loop.header].body = [parfor] + # We have to insert the header_body after the parfor because in + # a Numba loop this will be executed one more times before the + # branch and may contain instructions such as variable renamings + # that are relied upon later. + blocks[loop.header].body.extend(header_body) + blocks[loop.header].body.append(ir.Jump(list(loop.exits)[0], loc)) + self.rewritten.append(dict( + old_loop=loop, + new=parfor, + reason='loop', + )) + # remove loop blocks from top level dict + for l in body_labels: + if l != loop.header: + blocks.pop(l) + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from loop") + parfor.dump() + + def _is_parallel_loop(self, func_var, call_table): + # prange can be either getattr (numba.prange) or global (prange) + if func_var not in call_table: + return False + call = call_table[func_var] + return len(call) > 0 and (call[0] == 'prange' or call[0] == prange + or call[0] == 'internal_prange' or call[0] == internal_prange + or call[0] == 'pndindex' or call[0] == pndindex) + + def _get_loop_kind(self, func_var, call_table): + """see if prange is user prange or internal""" + pass_states = self.pass_states + # prange can be either getattr (numba.prange) or global (prange) + assert func_var in call_table + call = call_table[func_var] + assert len(call) > 0 + kind = 'user', '' + if call[0] == 'internal_prange' or call[0] == internal_prange: + try: + kind = 'internal', (pass_states.swapped_fns[func_var][0], pass_states.swapped_fns[func_var][-1]) + except KeyError: + # FIXME: Fix this issue... the code didn't manage to trace the + # swapout for func_var so set the kind as internal so that the + # transform can occur, it's just not tracked + kind = 'internal', ('', '') + elif call[0] == 'pndindex' or call[0] == pndindex: + kind = 'pndindex', '' + return kind + + def _get_prange_init_block(self, entry_block, call_table, prange_args): + """ + If there is init_prange, find the code between init_prange and prange + calls. Remove the code from entry_block and return it. + """ + init_call_ind = -1 + prange_call_ind = -1 + init_body = [] + for i, inst in enumerate(entry_block.body): + # if init_prange call + if (isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and self._is_prange_init(inst.value.func.name, call_table)): + init_call_ind = i + if (isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and self._is_parallel_loop(inst.value.func.name, call_table)): + prange_call_ind = i + if init_call_ind != -1 and prange_call_ind != -1: + # we save instructions that are used to calculate prange call args + # in the entry block. The rest go to parfor init_block + arg_related_vars = {v.name for v in prange_args} + saved_nodes = [] + for i in reversed(range(init_call_ind+1, prange_call_ind)): + inst = entry_block.body[i] + inst_vars = {v.name for v in inst.list_vars()} + if arg_related_vars & inst_vars: + arg_related_vars |= inst_vars + saved_nodes.append(inst) + else: + init_body.append(inst) + + init_body.reverse() + saved_nodes.reverse() + entry_block.body = (entry_block.body[:init_call_ind] + + saved_nodes + entry_block.body[prange_call_ind+1:]) + + return init_body + + def _is_prange_init(self, func_var, call_table): + if func_var not in call_table: + return False + call = call_table[func_var] + return len(call) > 0 and (call[0] == 'init_prange' or call[0] == init_prange) + + def _replace_loop_access_indices(self, loop_body, index_set, new_index): + """ + Replace array access indices in a loop body with a new index. + index_set has all the variables that are equivalent to loop index. + """ + # treat new index like others since replacing it with itself is ok + index_set.add(new_index.name) + + with dummy_return_in_loop_body(loop_body): + labels = find_topo_order(loop_body) + + first_label = labels[0] + added_indices = set() + + # traverse loop body and replace indices in getitem/setitem with + # new_index if possible. + # also, find equivalent indices defined in first block. + for l in labels: + block = loop_body[l] + for stmt in block.body: + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Var)): + # the first block dominates others so we can use copies + # of indices safely + if (l == first_label and stmt.value.name in index_set + and stmt.target.name not in index_set): + index_set.add(stmt.target.name) + added_indices.add(stmt.target.name) + # make sure parallel index is not overwritten + else: + scope = block.scope + + def unver(name): + from numba.core import errors + try: + return scope.get_exact(name).unversioned_name + except errors.NotDefinedError: + return name + + if unver(stmt.target.name) in map(unver, index_set) and unver(stmt.target.name) != unver(stmt.value.name): + raise errors.UnsupportedRewriteError( + "Overwrite of parallel loop index", + loc=stmt.target.loc, + ) + + + + if is_get_setitem(stmt): + index = index_var_of_get_setitem(stmt) + # statics can have none indices + if index is None: + continue + ind_def = guard(get_definition, self.pass_states.func_ir, + index, lhs_only=True) + if (index.name in index_set + or (ind_def is not None + and ind_def.name in index_set)): + set_index_var_of_get_setitem(stmt, new_index) + # corner case where one dimension of a multi-dim access + # should be replaced + guard(self._replace_multi_dim_ind, ind_def, index_set, + new_index) + + if isinstance(stmt, Parfor): + self._replace_loop_access_indices(stmt.loop_body, index_set, new_index) + + # remove added indices for correct recursive parfor handling + index_set -= added_indices + return + + def _replace_multi_dim_ind(self, ind_var, index_set, new_index): + """ + replace individual indices in multi-dimensional access variable, which + is a build_tuple + """ + pass_states = self.pass_states + require(ind_var is not None) + # check for Tuple instead of UniTuple since some dims could be slices + require(isinstance(pass_states.typemap[ind_var.name], + (types.Tuple, types.UniTuple))) + ind_def_node = get_definition(pass_states.func_ir, ind_var) + require(isinstance(ind_def_node, ir.Expr) + and ind_def_node.op == 'build_tuple') + ind_def_node.items = [new_index if v.name in index_set else v + for v in ind_def_node.items] + + +def _find_mask(typemap, func_ir, arr_def): + """check if an array is of B[...M...], where M is a + boolean array, and other indices (if available) are ints. + If found, return B, M, M's type, and a tuple representing mask indices. + Otherwise, raise GuardException. + """ + require(isinstance(arr_def, ir.Expr) and arr_def.op == 'getitem') + value = arr_def.value + index = arr_def.index + value_typ = typemap[value.name] + index_typ = typemap[index.name] + ndim = value_typ.ndim + require(isinstance(value_typ, types.npytypes.Array)) + if (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Boolean) and + ndim == index_typ.ndim): + return value, index, index_typ.dtype, None + elif isinstance(index_typ, types.BaseTuple): + # Handle multi-dimension differently by requiring + # all indices to be constant except the one for mask. + seq, op = find_build_sequence(func_ir, index) + require(op == 'build_tuple' and len(seq) == ndim) + count_consts = 0 + mask_indices = [] + mask_var = None + for ind in seq: + index_typ = typemap[ind.name] + # Handle boolean mask + if (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Boolean)): + mask_var = ind + mask_typ = index_typ.dtype + mask_indices.append(None) + # Handle integer array selector + elif (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Integer)): + mask_var = ind + mask_typ = index_typ.dtype + mask_indices.append(None) + # Handle integer index + elif isinstance(index_typ, types.Integer): + count_consts += 1 + mask_indices.append(ind) + + require(mask_var and count_consts == ndim - 1) + return value, mask_var, mask_typ, mask_indices + raise GuardException + + +class ParforPass(ParforPassStates): + + """ParforPass class is responsible for converting NumPy + calls in Numba intermediate representation to Parfors, which + will lower into either sequential or parallel loops during lowering + stage. + """ + + def _pre_run(self): + # run array analysis, a pre-requisite for parfor translation + self.array_analysis.run(self.func_ir.blocks) + # NOTE: Prepare _the_max_label. See #6102 + ir_utils._the_max_label.update( + ir_utils.find_max_label(self.func_ir.blocks)) + + def run(self): + """run parfor conversion pass: replace Numpy calls + with Parfors when possible and optimize the IR.""" + self._pre_run() + # run stencil translation to parfor + if self.options.stencil: + stencil_pass = StencilPass(self.func_ir, self.typemap, + self.calltypes, self.array_analysis, + self.typingctx, self.targetctx, + self.flags) + stencil_pass.run() + if self.options.setitem: + ConvertSetItemPass(self).run(self.func_ir.blocks) + if self.options.numpy: + ConvertNumpyPass(self).run(self.func_ir.blocks) + if self.options.reduction: + ConvertReducePass(self).run(self.func_ir.blocks) + if self.options.prange: + ConvertLoopPass(self).run(self.func_ir.blocks) + if self.options.inplace_binop: + ConvertInplaceBinop(self).run(self.func_ir.blocks) + + # setup diagnostics now parfors are found + self.diagnostics.setup(self.func_ir, self.options.fusion) + + dprint_func_ir(self.func_ir, "after parfor pass") + + def _find_mask(self, arr_def): + """check if an array is of B[...M...], where M is a + boolean array, and other indices (if available) are ints. + If found, return B, M, M's type, and a tuple representing mask indices. + Otherwise, raise GuardException. + """ + return _find_mask(self.typemap, self.func_ir, arr_def) + + def _mk_parfor_loops(self, size_vars, scope, loc): + """ + Create loop index variables and build LoopNest objects for a parfor. + """ + return _mk_parfor_loops(self.typemap, size_vars, scope, loc) + + +class ParforFusionPass(ParforPassStates): + + """ParforFusionPass class is responsible for fusing parfors + """ + + def run(self): + """run parfor fusion pass""" + + # simplify CFG of parfor body loops since nested parfors with extra + # jumps can be created with prange conversion + n_parfors = simplify_parfor_body_CFG(self.func_ir.blocks) + # simplify before fusion + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + # need two rounds of copy propagation to enable fusion of long sequences + # of parfors like test_fuse_argmin (some PYTHONHASHSEED values since + # apply_copies_parfor depends on set order for creating dummy assigns) + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + + if self.options.fusion and n_parfors >= 2: + self.func_ir._definitions = build_definitions(self.func_ir.blocks) + self.array_analysis.equiv_sets = dict() + self.array_analysis.run(self.func_ir.blocks) + + # Get parfor params to calculate reductions below. + _, parfors = get_parfor_params(self.func_ir.blocks, + self.options.fusion, + self.nested_fusion_info) + + # Find reductions so that fusion can be disallowed if a + # subsequent parfor read a reduction variable. + for p in parfors: + p.redvars, p.reddict = get_parfor_reductions(self.func_ir, + p, + p.params, + self.calltypes) + + # reorder statements to maximize fusion + # push non-parfors down + maximize_fusion(self.func_ir, self.func_ir.blocks, self.typemap, + up_direction=False) + dprint_func_ir(self.func_ir, "after maximize fusion down") + self.fuse_parfors(self.array_analysis, + self.func_ir.blocks, + self.func_ir, + self.typemap) + dprint_func_ir(self.func_ir, "after first fuse") + # push non-parfors up + maximize_fusion(self.func_ir, self.func_ir.blocks, self.typemap) + dprint_func_ir(self.func_ir, "after maximize fusion up") + # try fuse again after maximize + self.fuse_parfors(self.array_analysis, + self.func_ir.blocks, + self.func_ir, + self.typemap) + dprint_func_ir(self.func_ir, "after fusion") + # remove dead code after fusion to remove extra arrays and variables + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + + def fuse_parfors(self, array_analysis, blocks, func_ir, typemap): + for label, block in blocks.items(): + equiv_set = array_analysis.get_equiv_set(label) + fusion_happened = True + while fusion_happened: + fusion_happened = False + new_body = [] + i = 0 + while i < len(block.body) - 1: + stmt = block.body[i] + next_stmt = block.body[i + 1] + if isinstance(stmt, Parfor) and isinstance(next_stmt, Parfor): + # we have to update equiv_set since they have changed due to + # variables being renamed before fusion. + equiv_set = array_analysis.get_equiv_set(label) + stmt.equiv_set = equiv_set + next_stmt.equiv_set = equiv_set + fused_node, fuse_report = try_fuse(equiv_set, stmt, next_stmt, + self.metadata["parfors"], func_ir, typemap) + # accumulate fusion reports + self.diagnostics.fusion_reports.append(fuse_report) + if fused_node is not None: + fusion_happened = True + self.diagnostics.fusion_info[stmt.id].extend([next_stmt.id]) + new_body.append(fused_node) + self.fuse_recursive_parfor(fused_node, equiv_set, func_ir, typemap) + i += 2 + continue + new_body.append(stmt) + if isinstance(stmt, Parfor): + self.fuse_recursive_parfor(stmt, equiv_set, func_ir, typemap) + i += 1 + new_body.append(block.body[-1]) + block.body = new_body + return + + def fuse_recursive_parfor(self, parfor, equiv_set, func_ir, typemap): + blocks = wrap_parfor_blocks(parfor) + maximize_fusion(self.func_ir, blocks, self.typemap) + dprint_func_ir(self.func_ir, "after recursive maximize fusion down", blocks) + arr_analysis = array_analysis.ArrayAnalysis(self.typingctx, self.func_ir, + self.typemap, self.calltypes) + arr_analysis.run(blocks, equiv_set) + self.fuse_parfors(arr_analysis, blocks, func_ir, typemap) + unwrap_parfor_blocks(parfor) + + +class ParforPreLoweringPass(ParforPassStates): + + """ParforPreLoweringPass class is responsible for preparing parfors for lowering. + """ + + def run(self): + """run parfor prelowering pass""" + + # push function call variables inside parfors so gufunc function + # wouldn't need function variables as argument + push_call_vars(self.func_ir.blocks, {}, {}, self.typemap) + dprint_func_ir(self.func_ir, "after push call vars") + # simplify again + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + dprint_func_ir(self.func_ir, "after optimization") + if config.DEBUG_ARRAY_OPT >= 1: + print("variable types: ", sorted(self.typemap.items())) + print("call types: ", self.calltypes) + + if config.DEBUG_ARRAY_OPT >= 3: + for(block_label, block) in self.func_ir.blocks.items(): + new_block = [] + scope = block.scope + for stmt in block.body: + new_block.append(stmt) + if isinstance(stmt, ir.Assign): + loc = stmt.loc + lhs = stmt.target + rhs = stmt.value + lhs_typ = self.typemap[lhs.name] + print("Adding print for assignment to ", lhs.name, lhs_typ, type(lhs_typ)) + if lhs_typ in types.number_domain or isinstance(lhs_typ, types.Literal): + str_var = ir.Var(scope, mk_unique_var("str_var"), loc) + self.typemap[str_var.name] = types.StringLiteral(lhs.name) + lhs_const = ir.Const(lhs.name, loc) + str_assign = ir.Assign(lhs_const, str_var, loc) + new_block.append(str_assign) + str_print = ir.Print([str_var], None, loc) + self.calltypes[str_print] = signature(types.none, self.typemap[str_var.name]) + new_block.append(str_print) + ir_print = ir.Print([lhs], None, loc) + self.calltypes[ir_print] = signature(types.none, lhs_typ) + new_block.append(ir_print) + block.body = new_block + + if self.func_ir.is_generator: + fix_generator_types(self.func_ir.generator_info, self.return_type, + self.typemap) + if sequential_parfor_lowering: + lower_parfor_sequential( + self.typingctx, self.func_ir, self.typemap, self.calltypes, self.metadata) + else: + # prepare for parallel lowering + # add parfor params to parfors here since lowering is destructive + # changing the IR after this is not allowed + parfor_ids, parfors = get_parfor_params(self.func_ir.blocks, + self.options.fusion, + self.nested_fusion_info) + + # Validate reduction in parfors. + for p in parfors: + p.redvars, p.reddict = get_parfor_reductions(self.func_ir, + p, + p.params, + self.calltypes) + + # Validate parameters: + for p in parfors: + p.validate_params(self.typemap) + + if config.DEBUG_ARRAY_OPT_STATS: + name = self.func_ir.func_id.func_qualname + n_parfors = len(parfor_ids) + if n_parfors > 0: + after_fusion = ("After fusion" if self.options.fusion + else "With fusion disabled") + print(('{}, function {} has ' + '{} parallel for-loop(s) #{}.').format( + after_fusion, name, n_parfors, parfor_ids)) + else: + print('Function {} has no Parfor.'.format(name)) + + +def _remove_size_arg(call_name, expr): + "remove size argument from args or kws" + # remove size kwarg + kws = dict(expr.kws) + kws.pop('size', '') + expr.kws = tuple(kws.items()) + + # remove size arg if available + if call_name in random_1arg_size + random_int_args: + # these calls have only a "size" argument or list of ints + # so remove all args + expr.args = [] + + if call_name in random_3arg_sizelast: + # normal, uniform, ... have 3 args, last one is size + if len(expr.args) == 3: + expr.args.pop() + + if call_name in random_2arg_sizelast: + # have 2 args, last one is size + if len(expr.args) == 2: + expr.args.pop() + + if call_name == 'randint': + # has 4 args, 3rd one is size + if len(expr.args) == 3: + expr.args.pop() + if len(expr.args) == 4: + dt_arg = expr.args.pop() + expr.args.pop() # remove size + expr.args.append(dt_arg) + + if call_name == 'triangular': + # has 4 args, last one is size + if len(expr.args) == 4: + expr.args.pop() + + return + + +def _get_call_arg_types(expr, typemap): + new_arg_typs = [] + for arg in expr.args: + new_arg_typs.append(typemap[arg.name]) + + new_kw_types = {} + for name, arg in expr.kws: + new_kw_types[name] = typemap[arg.name] + + return tuple(new_arg_typs), new_kw_types + + +def _arrayexpr_tree_to_ir( + func_ir, + typingctx, + typemap, + calltypes, + equiv_set, + init_block, + expr_out_var, + expr, + parfor_index_tuple_var, + all_parfor_indices, + avail_vars): + """generate IR from array_expr's expr tree recursively. Assign output to + expr_out_var and returns the whole IR as a list of Assign nodes. + """ + el_typ = typemap[expr_out_var.name] + scope = expr_out_var.scope + loc = expr_out_var.loc + out_ir = [] + + if isinstance(expr, tuple): + op, arr_expr_args = expr + arg_vars = [] + for arg in arr_expr_args: + arg_out_var = ir.Var(scope, mk_unique_var("$arg_out_var"), loc) + typemap[arg_out_var.name] = el_typ + out_ir += _arrayexpr_tree_to_ir(func_ir, + typingctx, + typemap, + calltypes, + equiv_set, + init_block, + arg_out_var, + arg, + parfor_index_tuple_var, + all_parfor_indices, + avail_vars) + arg_vars.append(arg_out_var) + if op in npydecl.supported_array_operators: + el_typ1 = typemap[arg_vars[0].name] + if len(arg_vars) == 2: + el_typ2 = typemap[arg_vars[1].name] + func_typ = typingctx.resolve_function_type(op, (el_typ1, + el_typ2), {}) + ir_expr = ir.Expr.binop(op, arg_vars[0], arg_vars[1], loc) + if op == operator.truediv: + func_typ, ir_expr = _gen_np_divide( + arg_vars[0], arg_vars[1], out_ir, typemap, typingctx) + else: + func_typ = typingctx.resolve_function_type(op, (el_typ1,), {}) + ir_expr = ir.Expr.unary(op, arg_vars[0], loc) + calltypes[ir_expr] = func_typ + el_typ = func_typ.return_type + out_ir.append(ir.Assign(ir_expr, expr_out_var, loc)) + for T in array_analysis.MAP_TYPES: + if isinstance(op, T): + # elif isinstance(op, (np.ufunc, DUFunc)): + # function calls are stored in variables which are not removed + # op is typing_key to the variables type + func_var_name = _find_func_var(typemap, op, avail_vars, loc=loc) + func_var = ir.Var(scope, mk_unique_var(func_var_name), loc) + typemap[func_var.name] = typemap[func_var_name] + func_var_def = copy.deepcopy(func_ir.get_definition(func_var_name)) + if isinstance(func_var_def, ir.Expr) and func_var_def.op == 'getattr' and func_var_def.attr == 'sqrt': + g_math_var = ir.Var(scope, mk_unique_var("$math_g_var"), loc) + typemap[g_math_var.name] = types.misc.Module(math) + g_math = ir.Global('math', math, loc) + g_math_assign = ir.Assign(g_math, g_math_var, loc) + func_var_def = ir.Expr.getattr(g_math_var, 'sqrt', loc) + out_ir.append(g_math_assign) +# out_ir.append(func_var_def) + ir_expr = ir.Expr.call(func_var, arg_vars, (), loc) + call_typ = typemap[func_var.name].get_call_type( + typingctx, tuple(typemap[a.name] for a in arg_vars), {}) + calltypes[ir_expr] = call_typ + el_typ = call_typ.return_type + #signature(el_typ, el_typ) + out_ir.append(ir.Assign(func_var_def, func_var, loc)) + out_ir.append(ir.Assign(ir_expr, expr_out_var, loc)) + elif isinstance(expr, ir.Var): + var_typ = typemap[expr.name] + if isinstance(var_typ, types.Array): + el_typ = var_typ.dtype + ir_expr = _gen_arrayexpr_getitem( + equiv_set, + expr, + parfor_index_tuple_var, + all_parfor_indices, + el_typ, + calltypes, + typingctx, + typemap, + init_block, + out_ir) + else: + # assert typemap[expr.name]==el_typ + el_typ = var_typ + ir_expr = expr + out_ir.append(ir.Assign(ir_expr, expr_out_var, loc)) + elif isinstance(expr, ir.Const): + el_typ = typing.Context().resolve_value_type(expr.value) + out_ir.append(ir.Assign(expr, expr_out_var, loc)) + + if len(out_ir) == 0: + raise errors.UnsupportedRewriteError( + f"Don't know how to translate array expression '{expr:r}'", + loc=expr.loc, + ) + typemap.pop(expr_out_var.name, None) + typemap[expr_out_var.name] = el_typ + return out_ir + + +def _gen_np_divide(arg1, arg2, out_ir, typemap, typingctx): + """generate np.divide() instead of / for array_expr to get numpy error model + like inf for division by zero (test_division_by_zero). + """ + scope = arg1.scope + loc = arg1.loc + # g_np_var = Global(numpy) + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + # attr call: div_attr = getattr(g_np_var, divide) + div_attr_call = ir.Expr.getattr(g_np_var, "divide", loc) + attr_var = ir.Var(scope, mk_unique_var("$div_attr"), loc) + func_var_typ = get_np_ufunc_typ(numpy.divide, typingctx) + typemap[attr_var.name] = func_var_typ + attr_assign = ir.Assign(div_attr_call, attr_var, loc) + # divide call: div_attr(arg1, arg2) + div_call = ir.Expr.call(attr_var, [arg1, arg2], (), loc) + func_typ = func_var_typ.get_call_type( + typingctx, [typemap[arg1.name], typemap[arg2.name]], {}) + out_ir.extend([g_np_assign, attr_assign]) + return func_typ, div_call + + +def _gen_arrayexpr_getitem( + equiv_set, + var, + parfor_index_tuple_var, + all_parfor_indices, + el_typ, + calltypes, + typingctx, + typemap, + init_block, + out_ir): + """if there is implicit dimension broadcast, generate proper access variable + for getitem. For example, if indices are (i1,i2,i3) but shape is (c1,0,c3), + generate a tuple with (i1,0,i3) for access. Another example: for (i1,i2,i3) + and (c1,c2) generate (i2,i3). + """ + loc = var.loc + index_var = parfor_index_tuple_var + var_typ = typemap[var.name] + ndims = typemap[var.name].ndim + num_indices = len(all_parfor_indices) + size_vars = equiv_set.get_shape(var) or [] + size_consts = [equiv_set.get_equiv_const(x) for x in size_vars] + # Handle array-scalar + if ndims == 0: + # call np.ravel + ravel_var = ir.Var(var.scope, mk_unique_var("$ravel"), loc) + ravel_typ = types.npytypes.Array(dtype=var_typ.dtype, ndim=1, layout='C') + typemap[ravel_var.name] = ravel_typ + stmts = ir_utils.gen_np_call('ravel', numpy.ravel, ravel_var, [var], typingctx, typemap, calltypes) + init_block.body.extend(stmts) + var = ravel_var + # Const(0) + const_node = ir.Const(0, var.loc) + const_var = ir.Var(var.scope, mk_unique_var("$const_ind_0"), loc) + typemap[const_var.name] = types.uintp + const_assign = ir.Assign(const_node, const_var, loc) + out_ir.append(const_assign) + index_var = const_var + # Handle 1d array + elif ndims == 1: + # Use last index for 1D arrays + index_var = all_parfor_indices[-1] + # Handle known constant size + elif any([x is not None for x in size_consts]): + # Need a tuple as index + ind_offset = num_indices - ndims + tuple_var = ir.Var(var.scope, mk_unique_var( + "$parfor_index_tuple_var_bcast"), loc) + typemap[tuple_var.name] = types.containers.UniTuple(types.uintp, ndims) + # Just in case, const var for size 1 dim access index: $const0 = + # Const(0) + const_node = ir.Const(0, var.loc) + const_var = ir.Var(var.scope, mk_unique_var("$const_ind_0"), loc) + typemap[const_var.name] = types.uintp + const_assign = ir.Assign(const_node, const_var, loc) + out_ir.append(const_assign) + index_vars = [] + for i in reversed(range(ndims)): + size_var = size_vars[i] + size_const = size_consts[i] + if size_const == 1: + index_vars.append(const_var) + else: + index_vars.append(all_parfor_indices[ind_offset + i]) + index_vars = list(reversed(index_vars)) + tuple_call = ir.Expr.build_tuple(index_vars, loc) + tuple_assign = ir.Assign(tuple_call, tuple_var, loc) + out_ir.append(tuple_assign) + index_var = tuple_var + + ir_expr = ir.Expr.getitem(var, index_var, loc) + calltypes[ir_expr] = signature(el_typ, typemap[var.name], + typemap[index_var.name]) + return ir_expr + + +def _find_func_var(typemap, func, avail_vars, loc): + """find variable in typemap which represents the function func. + """ + for v in avail_vars: + t = typemap[v] + # Function types store actual functions in typing_key. + if isinstance(t, Function) and t.typing_key == func: + return v + raise errors.UnsupportedRewriteError("ufunc call variable not found", loc=loc) + + +def lower_parfor_sequential(typingctx, func_ir, typemap, calltypes, metadata): + ir_utils._the_max_label.update(ir_utils.find_max_label(func_ir.blocks)) + parfor_found = False + new_blocks = {} + scope = next(iter(func_ir.blocks.values())).scope + for (block_label, block) in func_ir.blocks.items(): + block_label, parfor_found = _lower_parfor_sequential_block( + block_label, block, new_blocks, typemap, calltypes, parfor_found, + scope=scope) + # old block stays either way + new_blocks[block_label] = block + func_ir.blocks = new_blocks + # rename only if parfor found and replaced (avoid test_flow_control error) + if parfor_found: + func_ir.blocks = rename_labels(func_ir.blocks) + dprint_func_ir(func_ir, "after parfor sequential lowering") + simplify(func_ir, typemap, calltypes, metadata["parfors"]) + dprint_func_ir(func_ir, "after parfor sequential simplify") + + +def _lower_parfor_sequential_block( + block_label, + block, + new_blocks, + typemap, + calltypes, + parfor_found, + scope): + i = _find_first_parfor(block.body) + while i != -1: + parfor_found = True + inst = block.body[i] + loc = inst.init_block.loc + # split block across parfor + prev_block = ir.Block(scope, loc) + prev_block.body = block.body[:i] + block.body = block.body[i + 1:] + # previous block jump to parfor init block + init_label = next_label() + prev_block.body.append(ir.Jump(init_label, loc)) + new_blocks[init_label] = transfer_scope(inst.init_block, scope) + new_blocks[block_label] = prev_block + block_label = next_label() + + ndims = len(inst.loop_nests) + for i in range(ndims): + loopnest = inst.loop_nests[i] + # create range block for loop + range_label = next_label() + header_label = next_label() + range_block = mk_range_block( + typemap, + loopnest.start, + loopnest.stop, + loopnest.step, + calltypes, + scope, + loc) + range_block.body[-1].target = header_label # fix jump target + phi_var = range_block.body[-2].target + new_blocks[range_label] = range_block + header_block = mk_loop_header(typemap, phi_var, calltypes, + scope, loc) + header_block.body[-2].target = loopnest.index_variable + new_blocks[header_label] = header_block + # jump to this new inner loop + if i == 0: + inst.init_block.body.append(ir.Jump(range_label, loc)) + header_block.body[-1].falsebr = block_label + else: + new_blocks[prev_header_label].body[-1].truebr = range_label + header_block.body[-1].falsebr = prev_header_label + prev_header_label = header_label # to set truebr next loop + + # last body block jump to inner most header + body_last_label = max(inst.loop_body.keys()) + inst.loop_body[body_last_label].body.append( + ir.Jump(header_label, loc)) + # inner most header jumps to first body block + body_first_label = min(inst.loop_body.keys()) + header_block.body[-1].truebr = body_first_label + # add parfor body to blocks + for (l, b) in inst.loop_body.items(): + l, parfor_found = _lower_parfor_sequential_block( + l, b, new_blocks, typemap, calltypes, parfor_found, + scope=scope) + new_blocks[l] = transfer_scope(b, scope) + i = _find_first_parfor(block.body) + return block_label, parfor_found + + +def _find_first_parfor(body): + for (i, inst) in enumerate(body): + if isinstance(inst, Parfor) and not inst.no_sequential_lowering: + return i + return -1 + + +def get_parfor_params(blocks, options_fusion, fusion_info): + """find variables used in body of parfors from outside and save them. + computed as live variables at entry of first block. + """ + + # since parfor wrap creates a back-edge to first non-init basic block, + # live_map[first_non_init_block] contains variables defined in parfor body + # that could be undefined before. So we only consider variables that are + # actually defined before the parfor body in the program. + parfor_ids = set() + parfors = [] + pre_defs = set() + _, all_defs = compute_use_defs(blocks) + topo_order = find_topo_order(blocks) + for label in topo_order: + block = blocks[label] + for i, parfor in _find_parfors(block.body): + # find variable defs before the parfor in the same block + dummy_block = ir.Block(block.scope, block.loc) + dummy_block.body = block.body[:i] + before_defs = compute_use_defs({0: dummy_block}).defmap[0] + pre_defs |= before_defs + params = get_parfor_params_inner( + parfor, pre_defs, options_fusion, fusion_info, + ) + parfor.params, parfor.races = _combine_params_races_for_ssa_names( + block.scope, params, parfor.races, + ) + parfor_ids.add(parfor.id) + parfors.append(parfor) + + pre_defs |= all_defs[label] + return parfor_ids, parfors + + +def _combine_params_races_for_ssa_names(scope, params, races): + """Returns `(params|races1, races1)`, where `races1` contains all variables + in `races` are NOT referring to the same unversioned (SSA) variables in + `params`. + """ + def unversion(k): + try: + return scope.get_exact(k).unversioned_name + except ir.NotDefinedError: + # XXX: it's a bug that something references an undefined name + return k + + races1 = set(races) + unver_params = list(map(unversion, params)) + + for rv in races: + if any(unversion(rv) == pv for pv in unver_params): + races1.discard(rv) + else: + break + + return params | races1, races1 + + +def get_parfor_params_inner(parfor, pre_defs, options_fusion, fusion_info): + blocks = wrap_parfor_blocks(parfor) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + parfor_ids, _ = get_parfor_params(blocks, options_fusion, fusion_info) + n_parfors = len(parfor_ids) + if n_parfors > 0: + if config.DEBUG_ARRAY_OPT_STATS: + after_fusion = ("After fusion" if options_fusion + else "With fusion disabled") + print(('{}, parallel for-loop {} has ' + 'nested Parfor(s) #{}.').format( + after_fusion, parfor.id, n_parfors, parfor_ids)) + fusion_info[parfor.id] = list(parfor_ids) + + unwrap_parfor_blocks(parfor) + keylist = sorted(live_map.keys()) + init_block = keylist[0] + first_non_init_block = keylist[1] + + before_defs = usedefs.defmap[init_block] | pre_defs + params = live_map[first_non_init_block] & before_defs + return params + + +def _find_parfors(body): + for i, inst in enumerate(body): + if isinstance(inst, Parfor): + yield i, inst + + +def _is_indirect_index(func_ir, index, nest_indices): + index_def = guard(get_definition, func_ir, index.name) + if isinstance(index_def, ir.Expr) and index_def.op == 'build_tuple': + if [x.name for x in index_def.items] == [x.name for x in nest_indices]: + return True + + return False + + +def get_array_indexed_with_parfor_index_internal(loop_body, + index, + ret_indexed, + ret_not_indexed, + nest_indices, + func_ir): + for blk in loop_body: + for stmt in blk.body: + if isinstance(stmt, (ir.StaticSetItem, ir.SetItem)): + setarray_index = get_index_var(stmt) + if (isinstance(setarray_index, ir.Var) and + (setarray_index.name == index or + _is_indirect_index( + func_ir, + setarray_index, + nest_indices))): + ret_indexed.add(stmt.target.name) + else: + ret_not_indexed.add(stmt.target.name) + elif (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Expr) and + stmt.value.op in ['getitem', 'static_getitem']): + getarray_index = stmt.value.index + getarray_name = stmt.value.value.name + if (isinstance(getarray_index, ir.Var) and + (getarray_index.name == index or + _is_indirect_index( + func_ir, + getarray_index, + nest_indices))): + ret_indexed.add(getarray_name) + else: + ret_not_indexed.add(getarray_name) + elif isinstance(stmt, Parfor): + get_array_indexed_with_parfor_index_internal( + stmt.loop_body.values(), + index, + ret_indexed, + ret_not_indexed, + nest_indices, + func_ir) + + +def get_array_indexed_with_parfor_index(loop_body, + index, + nest_indices, + func_ir): + ret_indexed = set() + ret_not_indexed = set() + get_array_indexed_with_parfor_index_internal( + loop_body, + index, + ret_indexed, + ret_not_indexed, + nest_indices, + func_ir) + return ret_indexed, ret_not_indexed + + +def get_parfor_outputs(parfor, parfor_params): + """get arrays that are written to inside the parfor and need to be passed + as parameters to gufunc. + """ + # FIXME: The following assumes the target of all SetItem are outputs, + # which is wrong! + last_label = max(parfor.loop_body.keys()) + outputs = [] + for blk in parfor.loop_body.values(): + for stmt in blk.body: + if (isinstance(stmt, (ir.StaticSetItem, ir.SetItem)) and + get_index_var(stmt).name == parfor.index_var.name): + outputs.append(stmt.target.name) + # make sure these written arrays are in parfor parameters (live coming in) + outputs = list(set(outputs) & set(parfor_params)) + return sorted(outputs) + + +_RedVarInfo = make_dataclass( + "_RedVarInfo", + ["init_val", "reduce_nodes", "redop"], + frozen=True, +) + + +def get_parfor_reductions(func_ir, parfor, parfor_params, calltypes, reductions=None, + reduce_varnames=None, param_uses=None, param_nodes=None, + var_to_param=None): + """find variables that are updated using their previous values and an array + item accessed with parfor index, e.g. s = s+A[i] + """ + if reductions is None: + reductions = {} + if reduce_varnames is None: + reduce_varnames = [] + + # for each param variable, find what other variables are used to update it + # also, keep the related nodes + if param_uses is None: + param_uses = defaultdict(list) + if param_nodes is None: + param_nodes = defaultdict(list) + if var_to_param is None: + var_to_param = {} + + blocks = wrap_parfor_blocks(parfor) + topo_order = find_topo_order(blocks) + topo_order = topo_order[1:] # ignore init block + unwrap_parfor_blocks(parfor) + + for label in reversed(topo_order): + for stmt in reversed(parfor.loop_body[label].body): + if (isinstance(stmt, ir.Assign) + and (stmt.target.name in parfor_params + or stmt.target.name in var_to_param)): + lhs = stmt.target + rhs = stmt.value + cur_param = lhs if lhs.name in parfor_params else var_to_param[lhs.name] + used_vars = [] + if isinstance(rhs, ir.Var): + used_vars = [rhs.name] + elif isinstance(rhs, ir.Expr): + used_vars = [v.name for v in stmt.value.list_vars()] + param_uses[cur_param].extend(used_vars) + for v in used_vars: + var_to_param[v] = cur_param + # save copy of dependent stmt + stmt_cp = copy.deepcopy(stmt) + if stmt.value in calltypes: + calltypes[stmt_cp.value] = calltypes[stmt.value] + param_nodes[cur_param].append(stmt_cp) + if isinstance(stmt, Parfor): + # recursive parfors can have reductions like test_prange8 + get_parfor_reductions(func_ir, stmt, parfor_params, calltypes, + reductions, reduce_varnames, None, param_nodes, var_to_param) + + for param, used_vars in param_uses.items(): + # a parameter is a reduction variable if its value is used to update it + # check reduce_varnames since recursive parfors might have processed + # param already + param_name = param.name + if param_name in used_vars and param_name not in reduce_varnames: + param_nodes[param].reverse() + reduce_nodes = get_reduce_nodes(param, param_nodes[param], func_ir) + # Certain kinds of ill-formed Python (like potentially undefined + # variables) in combination with SSA can make things look like + # reductions except that they don't have reduction operators. + # If we get to this point but don't find a reduction operator + # then assume it is this situation and just don't treat this + # variable as a reduction. + if reduce_nodes is not None: + reduce_varnames.append(param_name) + check_conflicting_reduction_operators(param, reduce_nodes) + gri_out = guard(get_reduction_init, reduce_nodes) + if gri_out is not None: + init_val, redop = gri_out + else: + init_val = None + redop = None + reductions[param_name] = _RedVarInfo( + init_val=init_val, + reduce_nodes=reduce_nodes, + redop=redop, + ) + + return reduce_varnames, reductions + +def check_conflicting_reduction_operators(param, nodes): + """In prange, a user could theoretically specify conflicting + reduction operators. For example, in one spot it is += and + another spot *=. Here, we raise an exception if multiple + different reduction operators are used in one prange. + """ + first_red_func = None + for node in nodes: + if (isinstance(node, ir.Assign) and + isinstance(node.value, ir.Expr) and + node.value.op=='inplace_binop'): + if first_red_func is None: + first_red_func = node.value.fn + else: + if first_red_func != node.value.fn: + msg = ("Reduction variable %s has multiple conflicting " + "reduction operators." % param.unversioned_name) + raise errors.UnsupportedRewriteError(msg, node.loc) + +def get_reduction_init(nodes): + """ + Get initial value for known reductions. + Currently, only += and *= are supported. + """ + require(len(nodes) >= 1) + # there could be multiple extra assignments after the reduce node + # See: test_reduction_var_reuse + acc_expr = list(filter(lambda x: isinstance(x.value, ir.Expr), nodes))[-1].value + require(isinstance(acc_expr, ir.Expr) and acc_expr.op in ['inplace_binop', 'binop']) + acc_expr_fn = acc_expr.fn + if acc_expr.op == 'binop': + if acc_expr_fn == operator.add: + acc_expr_fn = operator.iadd + elif acc_expr_fn == operator.sub: + acc_expr_fn = operator.isub + elif acc_expr_fn == operator.mul: + acc_expr_fn = operator.imul + elif acc_expr_fn == operator.truediv: + acc_expr_fn = operator.itruediv + if acc_expr_fn == operator.iadd or acc_expr_fn == operator.isub: + return 0, acc_expr_fn + if ( acc_expr_fn == operator.imul + or acc_expr_fn == operator.itruediv ): + return 1, acc_expr_fn + return None, None + +def supported_reduction(x, func_ir): + if x.op == 'inplace_binop' or x.op == 'binop': + if x.fn == operator.ifloordiv or x.fn == operator.floordiv: + raise errors.NumbaValueError(("Parallel floordiv reductions are not supported. " + "If all divisors are integers then a floordiv " + "reduction can in some cases be parallelized as " + "a multiply reduction followed by a floordiv of " + "the resulting product."), x.loc) + supps = [operator.iadd, + operator.isub, + operator.imul, + operator.itruediv, + operator.add, + operator.sub, + operator.mul, + operator.truediv] + return x.fn in supps + if x.op == 'call': + callname = guard(find_callname, func_ir, x) + if callname in [ + ('max', 'builtins'), + ('min', 'builtins'), + ('datetime_minimum', 'numba.np.npdatetime_helpers'), + ('datetime_maximum', 'numba.np.npdatetime_helpers'), + ]: + return True + return False + +def get_reduce_nodes(reduction_node, nodes, func_ir): + """ + Get nodes that combine the reduction variable with a sentinel variable. + Recognizes the first node that combines the reduction variable with another + variable. + """ + reduce_nodes = None + defs = {} + + def cyclic_lookup(var, varonly=True, start=None): + """Lookup definition of ``var``. + Returns ``None`` if variable definition forms a cycle. + """ + lookedup_var = defs.get(var.name, None) + if isinstance(lookedup_var, ir.Var): + if start is None: + start = lookedup_var + elif start == lookedup_var: + # cycle detected + return None + return cyclic_lookup(lookedup_var, start=start) + else: + return var if (varonly or lookedup_var is None) else lookedup_var + + def noncyclic_lookup(*args, **kwargs): + """Similar to cyclic_lookup but raise AssertionError if a cycle is + detected. + """ + res = cyclic_lookup(*args, **kwargs) + if res is None: + raise AssertionError("unexpected cycle in lookup()") + return res + + name = reduction_node.name + unversioned_name = reduction_node.unversioned_name + for i, stmt in enumerate(nodes): + lhs = stmt.target + rhs = stmt.value + defs[lhs.name] = rhs + if isinstance(rhs, ir.Var) and rhs.name in defs: + rhs = cyclic_lookup(rhs) + if isinstance(rhs, ir.Expr): + in_vars = set(noncyclic_lookup(v, True).name + for v in rhs.list_vars()) + if name in in_vars: + # reductions like sum have an assignment afterwards + # e.g. $2 = a + $1; a = $2 + # reductions that are functions calls like max() don't have an + # extra assignment afterwards + + # This code was created when Numba had an IR generation strategy + # where a binop for a reduction would be followed by an + # assignment as follows: + #$c.4.15 = inplace_binop(fn=, ...>, lhs=c.3, rhs=$const20) + #c.4 = $c.4.15 + + # With Python 3.12 changes, Numba may separate that assignment + # to a new basic block. The code below looks and sees if an + # assignment to the reduction var follows the reduction operator + # and if not it searches the rest of the reduction nodes to find + # the assignment that should follow the reduction operator + # and then reorders the reduction nodes so that assignment + # follows the reduction operator. + if (i + 1 < len(nodes) and + ((not isinstance(nodes[i + 1], ir.Assign)) or + nodes[i + 1].target.unversioned_name != unversioned_name)): + foundj = None + # Iterate through the rest of the reduction nodes. + for j, jstmt in enumerate(nodes[i + 1:]): + # If this stmt is an assignment where the right-hand + # side of the assignment is the output of the reduction + # operator. + if isinstance(jstmt, ir.Assign) and jstmt.value == lhs: + # Remember the index of this node. Because of + # nodes[i+1] above, we have to add i + 1 to j below + # to get the index in the original nodes list. + foundj = i + j + 1 + break + if foundj is not None: + # If we found the correct assignment then move it to + # after the reduction operator. + nodes = (nodes[:i + 1] + # nodes up to operator + nodes[foundj:foundj + 1] + # assignment node + nodes[i + 1:foundj] + # between op and assign + nodes[foundj + 1:]) # after assignment node + + if (not (i+1 < len(nodes) and isinstance(nodes[i+1], ir.Assign) + and nodes[i+1].target.unversioned_name == unversioned_name) + and lhs.unversioned_name != unversioned_name): + raise ValueError( + f"Use of reduction variable {unversioned_name!r} other " + "than in a supported reduction function is not " + "permitted." + ) + + if not supported_reduction(rhs, func_ir): + raise ValueError(("Use of reduction variable " + unversioned_name + + " in an unsupported reduction function.")) + args = [(x.name, noncyclic_lookup(x, True)) + for x in get_expr_args(rhs) ] + non_red_args = [ x for (x, y) in args if y.name != name ] + assert len(non_red_args) == 1 + args = [ (x, y) for (x, y) in args if x != y.name ] + replace_dict = dict(args) + replace_dict[non_red_args[0]] = ir.Var(lhs.scope, name+"#init", lhs.loc) + replace_vars_inner(rhs, replace_dict) + reduce_nodes = nodes[i:] + break + return reduce_nodes + +def get_expr_args(expr): + """ + Get arguments of an expression node + """ + if expr.op in ['binop', 'inplace_binop']: + return [expr.lhs, expr.rhs] + if expr.op == 'call': + return [v for v in expr.args] + raise NotImplementedError("get arguments for expression {}".format(expr)) + +def visit_parfor_pattern_vars(parfor, callback, cbdata): + # currently, only stencil pattern has variables + for pattern in parfor.patterns: + if pattern[0] == 'stencil': + left_lengths = pattern[1][0] + for i in range(len(left_lengths)): + if isinstance(left_lengths[i], ir.Var): + left_lengths[i] = visit_vars_inner(left_lengths[i], + callback, cbdata) + right_lengths = pattern[1][1] + for i in range(len(right_lengths)): + if isinstance(right_lengths[i], ir.Var): + right_lengths[i] = visit_vars_inner(right_lengths[i], + callback, cbdata) + +def visit_vars_parfor(parfor, callback, cbdata): + if config.DEBUG_ARRAY_OPT >= 1: + print("visiting parfor vars for:", parfor) + print("cbdata: ", sorted(cbdata.items())) + for l in parfor.loop_nests: + l.index_variable = visit_vars_inner(l.index_variable, callback, cbdata) + if isinstance(l.start, ir.Var): + l.start = visit_vars_inner(l.start, callback, cbdata) + if isinstance(l.stop, ir.Var): + l.stop = visit_vars_inner(l.stop, callback, cbdata) + if isinstance(l.step, ir.Var): + l.step = visit_vars_inner(l.step, callback, cbdata) + visit_vars({-1: parfor.init_block}, callback, cbdata) + visit_parfor_pattern_vars(parfor, callback, cbdata) + visit_vars(parfor.loop_body, callback, cbdata) + return + + +# add call to visit parfor variable +ir_utils.visit_vars_extensions[Parfor] = visit_vars_parfor + + +def parfor_defs(parfor, use_set=None, def_set=None): + """list variables written in this parfor by recursively + calling compute_use_defs() on body and combining block defs. + """ + if use_set is None: + use_set = set() + if def_set is None: + def_set = set() + blocks = wrap_parfor_blocks(parfor) + uses, defs = compute_use_defs(blocks) + cfg = compute_cfg_from_blocks(blocks) + last_label = max(blocks.keys()) + unwrap_parfor_blocks(parfor) + + # Conservatively, only add defs for blocks that are definitely executed + # Go through blocks in order, as if they are statements of the block that + # includes the parfor, and update uses/defs. + + # no need for topo order of ir_utils + topo_order = cfg.topo_order() + # blocks that dominate last block are definitely executed + definitely_executed = cfg.dominators()[last_label] + # except loop bodies that might not execute + for loop in cfg.loops().values(): + definitely_executed -= loop.body + for label in topo_order: + if label in definitely_executed: + # see compute_use_defs() in analysis.py + # variables defined in the block that includes the parfor are not + # uses of that block (are not potentially live in the beginning of + # the block) + use_set.update(uses[label] - def_set) + def_set.update(defs[label]) + else: + use_set.update(uses[label] - def_set) + + # treat loop variables and size variables as use + loop_vars = { + l.start.name for l in parfor.loop_nests if isinstance( + l.start, ir.Var)} + loop_vars |= { + l.stop.name for l in parfor.loop_nests if isinstance( + l.stop, ir.Var)} + loop_vars |= { + l.step.name for l in parfor.loop_nests if isinstance( + l.step, ir.Var)} + use_set.update(loop_vars - def_set) + use_set |= get_parfor_pattern_vars(parfor) + + return analysis._use_defs_result(usemap=use_set, defmap=def_set) + + +analysis.ir_extension_usedefs[Parfor] = parfor_defs + + +def _parfor_use_alloca(parfor, alloca_set): + """ + Reduction variables for parfors and the reduction variables within + nested parfors must be stack allocated. + """ + alloca_set |= set(parfor.redvars) + + blocks = wrap_parfor_blocks(parfor) + alloca_set |= analysis.must_use_alloca(blocks) + + unwrap_parfor_blocks(parfor) + + +analysis.ir_extension_use_alloca[Parfor] = _parfor_use_alloca + + +def parfor_insert_dels(parfor, curr_dead_set): + """insert dels in parfor. input: dead variable set right after parfor. + returns the variables for which del was inserted. + """ + blocks = wrap_parfor_blocks(parfor) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + dead_map = compute_dead_maps(cfg, blocks, live_map, usedefs.defmap) + + # treat loop variables and size variables as live + loop_vars = { + l.start.name for l in parfor.loop_nests if isinstance( + l.start, ir.Var)} + loop_vars |= { + l.stop.name for l in parfor.loop_nests if isinstance( + l.stop, ir.Var)} + loop_vars |= { + l.step.name for l in parfor.loop_nests if isinstance( + l.step, ir.Var)} + loop_vars |= {l.index_variable.name for l in parfor.loop_nests} + # for var_list in parfor.array_analysis.array_size_vars.values(): + # loop_vars |= {v.name for v in var_list if isinstance(v, ir.Var)} + + dead_set = set() + for label in blocks.keys(): + # only kill vars that are actually dead at the parfor's block + dead_map.internal[label] &= curr_dead_set + dead_map.internal[label] -= loop_vars + dead_set |= dead_map.internal[label] + dead_map.escaping[label] &= curr_dead_set + dead_map.escaping[label] -= loop_vars + dead_set |= dead_map.escaping[label] + + # dummy class to replace func_ir. _patch_var_dels only accesses blocks + class DummyFuncIR(object): + + def __init__(self, blocks): + self.blocks = blocks + post_proc = postproc.PostProcessor(DummyFuncIR(blocks)) + post_proc._patch_var_dels(dead_map.internal, dead_map.escaping) + unwrap_parfor_blocks(parfor) + + return dead_set | loop_vars + + +postproc.ir_extension_insert_dels[Parfor] = parfor_insert_dels + + +def maximize_fusion(func_ir, blocks, typemap, up_direction=True): + """ + Reorder statements to maximize parfor fusion. Push all parfors up or down + so they are adjacent. + """ + call_table, _ = get_call_table(blocks) + alias_map, arg_aliases = find_potential_aliases( + blocks, + func_ir.arg_names, + typemap, + func_ir + ) + for block in blocks.values(): + order_changed = True + while order_changed: + order_changed = maximize_fusion_inner( + func_ir, + block, + call_table, + alias_map, + arg_aliases, + up_direction + ) + +def maximize_fusion_inner(func_ir, block, call_table, alias_map, + arg_aliases, up_direction=True): + order_changed = False + i = 0 + # i goes to body[-3] (i+1 to body[-2]) since body[-1] is terminator and + # shouldn't be reordered + while i < len(block.body) - 2: + stmt = block.body[i] + next_stmt = block.body[i+1] + can_reorder = (_can_reorder_stmts(stmt, next_stmt, func_ir, + call_table, alias_map, arg_aliases) + if up_direction else _can_reorder_stmts(next_stmt, stmt, + func_ir, call_table, alias_map, arg_aliases)) + if can_reorder: + block.body[i] = next_stmt + block.body[i+1] = stmt + order_changed = True + i += 1 + return order_changed + +def expand_aliases(the_set, alias_map, arg_aliases): + ret = set() + for i in the_set: + if i in alias_map: + ret = ret.union(alias_map[i]) + if i in arg_aliases: + ret = ret.union(arg_aliases) + ret.add(i) + return ret + +def _can_reorder_stmts(stmt, next_stmt, func_ir, call_table, + alias_map, arg_aliases): + """ + Check dependencies to determine if a parfor can be reordered in the IR block + with a non-parfor statement. + """ + # swap only parfors with non-parfors + # don't reorder calls with side effects (e.g. file close) + # only read-read dependencies are OK + # make sure there is no write-write, write-read dependencies + if (isinstance(stmt, Parfor) + and not isinstance(next_stmt, Parfor) + and not isinstance(next_stmt, ir.Print) + and (not isinstance(next_stmt, ir.Assign) + or has_no_side_effect(next_stmt.value, set(), call_table) + or guard(is_assert_equiv, func_ir, next_stmt.value))): + stmt_accesses = expand_aliases({v.name for v in stmt.list_vars()}, + alias_map, arg_aliases) + stmt_writes = expand_aliases(get_parfor_writes(stmt), + alias_map, arg_aliases) + next_accesses = expand_aliases({v.name for v in next_stmt.list_vars()}, + alias_map, arg_aliases) + next_writes = expand_aliases(get_stmt_writes(next_stmt), + alias_map, arg_aliases) + if len((stmt_writes & next_accesses) + | (next_writes & stmt_accesses)) == 0: + return True + return False + +def is_assert_equiv(func_ir, expr): + func_name, mod_name = find_callname(func_ir, expr) + return func_name == 'assert_equiv' + + +def get_parfor_writes(parfor): + assert isinstance(parfor, Parfor) + writes = set() + blocks = parfor.loop_body.copy() + blocks[-1] = parfor.init_block + for block in blocks.values(): + for stmt in block.body: + writes.update(get_stmt_writes(stmt)) + if isinstance(stmt, Parfor): + writes.update(get_parfor_writes(stmt)) + return writes + +FusionReport = namedtuple('FusionReport', ['first', 'second', 'message']) + +def try_fuse(equiv_set, parfor1, parfor2, metadata, func_ir, typemap): + """try to fuse parfors and return a fused parfor, otherwise return None + """ + dprint("try_fuse: trying to fuse \n", parfor1, "\n", parfor2) + + # default report is None + report = None + + # fusion of parfors with different lowerers is not possible + if parfor1.lowerer != parfor2.lowerer: + dprint("try_fuse: parfors different lowerers") + msg = "- fusion failed: lowerer mismatch" + report = FusionReport(parfor1.id, parfor2.id, msg) + return None, report + + # fusion of parfors with different dimensions not supported yet + if len(parfor1.loop_nests) != len(parfor2.loop_nests): + dprint("try_fuse: parfors number of dimensions mismatch") + msg = "- fusion failed: number of loops mismatched, %s, %s." + fmt = "parallel loop #%s has a nest of %s loops" + l1 = fmt % (parfor1.id, len(parfor1.loop_nests)) + l2 = fmt % (parfor2.id, len(parfor2.loop_nests)) + report = FusionReport(parfor1.id, parfor2.id, msg % (l1, l2)) + return None, report + + ndims = len(parfor1.loop_nests) + # all loops should be equal length + + def is_equiv(x, y): + return x == y or equiv_set.is_equiv(x, y) + + def get_user_varname(v): + """get original variable name by user if possible""" + if not isinstance(v, ir.Var): + return v + v = v.name + if "var_rename_map" in metadata and v in metadata["var_rename_map"]: + user_varname = metadata["var_rename_map"][v] + return user_varname + return v + + for i in range(ndims): + nest1 = parfor1.loop_nests[i] + nest2 = parfor2.loop_nests[i] + if not (is_equiv(nest1.start, nest2.start) and + is_equiv(nest1.stop, nest2.stop) and + is_equiv(nest1.step, nest2.step)): + dprint("try_fuse: parfor dimension correlation mismatch", i) + msg = "- fusion failed: loop dimension mismatched in axis %s. " + msg += "slice(%s, %s, %s) != " % (get_user_varname(nest1.start), + get_user_varname(nest1.stop), get_user_varname(nest1.step)) + msg += "slice(%s, %s, %s)" % (get_user_varname(nest2.start), + get_user_varname(nest2.stop), get_user_varname(nest2.step)) + report = FusionReport(parfor1.id, parfor2.id, msg % i) + return None, report + + func_ir._definitions = build_definitions(func_ir.blocks) + p1_cross_dep, p1_ip, p1_ia, p1_non_ia = has_cross_iter_dep(parfor1, func_ir, typemap) + if not p1_cross_dep: + p2_cross_dep = has_cross_iter_dep(parfor2, func_ir, typemap, p1_ip, p1_ia, p1_non_ia)[0] + else: + p2_cross_dep = True + + if p1_cross_dep or p2_cross_dep: + dprint("try_fuse: parfor cross iteration dependency found") + msg = ("- fusion failed: cross iteration dependency found " + "between loops #%s and #%s") + report = FusionReport(parfor1.id, parfor2.id, + msg % (parfor1.id, parfor2.id)) + return None, report + + + # find parfor1's defs, only body is considered since init_block will run + # first after fusion as well + p1_body_usedefs = compute_use_defs(parfor1.loop_body) + p1_body_defs = set() + for defs in p1_body_usedefs.defmap.values(): + p1_body_defs |= defs + p1_body_defs |= get_parfor_writes(parfor1) + # Add reduction variables from parfor1 to the set of body defs + # so that if parfor2 reads the reduction variable it won't fuse. + p1_body_defs |= set(parfor1.redvars) + + p2_usedefs = compute_use_defs(parfor2.loop_body) + p2_uses = compute_use_defs({0: parfor2.init_block}).usemap[0] + for uses in p2_usedefs.usemap.values(): + p2_uses |= uses + + overlap = p1_body_defs.intersection(p2_uses) + # overlap are those variable defined in first parfor and used in the second + if len(overlap) != 0: + # Get all the arrays + _, p2arraynotindexed = get_array_indexed_with_parfor_index( + parfor2.loop_body.values(), + parfor2.index_var.name, + parfor2.get_loop_nest_vars(), + func_ir) + + unsafe_var = (not isinstance(typemap[x], types.ArrayCompatible) or x in p2arraynotindexed for x in overlap) + + if any(unsafe_var): + dprint("try_fuse: parfor2 depends on parfor1 body") + msg = ("- fusion failed: parallel loop %s has a dependency on the " + "body of parallel loop %s. ") + report = FusionReport(parfor1.id, parfor2.id, + msg % (parfor1.id, parfor2.id)) + return None, report + + return fuse_parfors_inner(parfor1, parfor2) + + +def fuse_parfors_inner(parfor1, parfor2): + # fuse parfor2 into parfor1 + # append parfor2's init block on parfor1's + parfor1.init_block.body.extend(parfor2.init_block.body) + + # append parfor2's first block to parfor1's last block + parfor2_first_label = min(parfor2.loop_body.keys()) + parfor2_first_block = parfor2.loop_body[parfor2_first_label].body + parfor1_first_label = min(parfor1.loop_body.keys()) + parfor1_last_label = max(parfor1.loop_body.keys()) + parfor1.loop_body[parfor1_last_label].body.extend(parfor2_first_block) + + # add parfor2 body blocks to parfor1's except first + parfor1.loop_body.update(parfor2.loop_body) + parfor1.loop_body.pop(parfor2_first_label) + + # replace parfor2 indices with parfor1's + ndims = len(parfor1.loop_nests) + index_dict = {parfor2.index_var.name: parfor1.index_var} + for i in range(ndims): + index_dict[parfor2.loop_nests[i].index_variable.name] = parfor1.loop_nests[ + i].index_variable + replace_vars(parfor1.loop_body, index_dict) + + # re-order labels from min to max + blocks = wrap_parfor_blocks(parfor1, entry_label=parfor1_first_label) + blocks = rename_labels(blocks) + unwrap_parfor_blocks(parfor1, blocks) + + nameset = set(x.name for x in index_dict.values()) + remove_duplicate_definitions(parfor1.loop_body, nameset) + parfor1.patterns.extend(parfor2.patterns) + if config.DEBUG_ARRAY_OPT_STATS: + print('Parallel for-loop #{} is fused into for-loop #{}.'.format( + parfor2.id, parfor1.id)) + + msg = '- fusion succeeded: parallel for-loop #{} is fused into for-loop #{}.' + msg = msg.format(parfor2.id, parfor1.id) + report = FusionReport(parfor1.id, parfor2.id, msg) + + return parfor1, report + + +def remove_duplicate_definitions(blocks, nameset): + """Remove duplicated definition for variables in the given nameset, which + is often a result of parfor fusion. + """ + for label, block in blocks.items(): + body = block.body + new_body = [] + defined = set() + for inst in body: + if isinstance(inst, ir.Assign): + name = inst.target.name + if name in nameset: + if name in defined: + continue + defined.add(name) + new_body.append(inst) + block.body = new_body + return + + +def has_cross_iter_dep( + parfor, + func_ir, + typemap, + index_positions=None, + indexed_arrays=None, + non_indexed_arrays=None): + # We should assume there is cross iteration dependency unless we can + # prove otherwise. Return True if there is a cross-iter dependency + # that should prevent fusion, False if fusion is okay. + # Also returns index_positions, indexed_arrays, and non_indexed_arrays + # who purpose is described below so that subsequent additional + # has_cross_iter_dep calls for other parfors can build on the same + # data structures to make sure that the array accesses generate no + # cross-iter dependencies both within a parfor but also across parfors. + + # TODO: make it more accurate using ud-chains + + # Get the index variable used by this parfor. + # This will hold other variables with equivalent value, e.g., a = index_var + indices = {l.index_variable.name for l in parfor.loop_nests} + # This set will store variables that are (potentially recursively) + # defined in relation to an index variable, e.g., a = index_var + 1. + # A getitem that uses an index variable from this set will be considered + # as potentially having a cross-iter dependency and so won't fuse. + derived_from_indices = set() + # For the first parfor considered for fusion, the latter 3 args will be None + # and initialized to empty. For the second parfor, the structures from the + # previous parfor are passed in so that cross-parfor violations of the + # below comments can prevent fusion. + # + # index_positions keeps track of which index positions have had an index + # variable used for them and which ones haven't for each possible array + # dimensionality. After the first array access is seen, if subsequent + # ones use a parfor index for a different dimension then we conservatively + # say that we can't fuse. For example, if a 2D array is accessed with + # a[parfor_index, 0] then index_positions[2] will be (True, False) and + # if a[0, parfor_index] happens later which is (False, True) then this + # conflicts with the previous value and will prevent fusion. + # + # indexed_arrays records arrays that are accessed with at least one + # parfor index. If such an array is later accessed with indices that + # don't include a parfor index then conservatively assume we can't fuse. + # + # non_indexed_arrays holds arrays that are indexed without a parfor index. + # If an array first accessed without a parfor index is later indexed + # with one then conservatively assume we can't fuse. + if index_positions is None: + index_positions = {} + if indexed_arrays is None: + indexed_arrays = set() + if non_indexed_arrays is None: + non_indexed_arrays = set() + + def add_check_position(new_position, + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays): + """Returns True if there is a reason to prevent fusion based + on the rules described above. + new_position will be a list or tuple of booleans that + says whether the index in that spot is a parfor index + or not. array_accessed is the array on which the access + is occurring.""" + + # Convert list indices to tuple for generality. + if isinstance(new_position, list): + new_position = tuple(new_position) + + # If none of the indices are based on a parfor index. + if True not in new_position: + # See if this array has been accessed before with a + # a parfor index and if so say that we can't fuse. + if array_accessed in indexed_arrays: + return True + else: + # Either array is already in non_indexed arrays or we + # will add it. Either way, this index usage can fuse. + non_indexed_arrays.add(array_accessed) + return False + + # Fallthrough for cases where one of the indices is a parfor index. + # If this array was previously accessed without a parfor index then + # conservatively say we can't fuse. + if array_accessed in non_indexed_arrays: + return True + + indexed_arrays.add(array_accessed) + + npsize = len(new_position) + # See if we have not seen a npsize dimensioned array accessed before. + if npsize not in index_positions: + # If not then add current set of parfor/non-parfor indices and + # indicate it is safe as it is the first usage. + index_positions[npsize] = new_position + return False + + # Here we have a subsequent access to a npsize-dimensioned array. + # Make sure we see the same combination of parfor/non-parfor index + # indices that we've seen before. If not then return True saying + # that we can't fuse. + return index_positions[npsize] != new_position + + def check_index(stmt_index, + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays, + derived_from_indices): + """Looks at the indices of a getitem or setitem to see if there + is a reason that they would prevent fusion. + Returns True if fusion should be prohibited, False otherwise. + """ + if isinstance(stmt_index, ir.Var): + # If the array is 2+ dimensions then the index should be a tuple. + if isinstance(typemap[stmt_index.name], types.BaseTuple): + # Get how the index tuple is constructed. + fbs_res = guard(find_build_sequence, func_ir, stmt_index) + if fbs_res is not None: + ind_seq, _ = fbs_res + # If any indices are derived from an index is used then + # return True to say we can't fuse. + if (all([x.name in indices or + x.name not in derived_from_indices for x in ind_seq])): + # Get position in index tuple where parfor indices used. + new_index_positions = [x.name in indices for x in ind_seq] + # Make sure that we aren't accessing a given array with + # different indices in a different order. + return add_check_position(new_index_positions, + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays) + else: + # index derived from a parfor index used so no fusion + return True + else: + # Don't know how the index tuple is built so + # have to assume fusion can't happen. + return True + else: + # Should be for 1D arrays. + if stmt_index.name in indices: + # Array indexed by a parfor index variable. + # Make sure this 1D access is consistent with prior ones. + return add_check_position((True,), + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays) + elif stmt_index.name in derived_from_indices: + # If we ever index an array with something calculated + # from an index then no fusion. + return True + else: + # Some kind of index that isn't a parfor index or + # one derived from one, e.g., a constant. Make sure + # this is consistent with prior accessed of this array. + return add_check_position((False,), + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays) + else: + # We don't know how to handle non-Var indices so no fusion. + return True + + # All branches above should cover all the cases and each should + # return so we should never get here. + raise errors.InternalError("Some code path in the parfor fusion " + "cross-iteration dependency checker " + "check_index didn't return a result.") + + # Iterate through all the statements in the parfor. + for b in parfor.loop_body.values(): + for stmt in b.body: + # Make sure SetItem accesses are fusion safe. + if isinstance(stmt, (ir.SetItem, ir.StaticSetItem)): + if isinstance(typemap[stmt.target.name], types.npytypes.Array): + # Check index safety with prior array accesses. + if check_index(stmt.index, + stmt.target.name, + index_positions, + indexed_arrays, + non_indexed_arrays, + derived_from_indices): + return True, index_positions, indexed_arrays, non_indexed_arrays + # Fusion safe so go to next statement. + continue + elif isinstance(stmt, ir.Assign): + # If stmt of form a = parfor_index then add "a" to set of + # parfor indices. + if isinstance(stmt.value, ir.Var): + if stmt.value.name in indices: + indices.add(stmt.target.name) + continue + elif isinstance(stmt.value, ir.Expr): + op = stmt.value.op + # Make sure getitem accesses are fusion safe. + if op in ['getitem', 'static_getitem']: + if isinstance(typemap[stmt.value.value.name], types.npytypes.Array): + # Check index safety with prior array accesses. + if check_index(stmt.value.index, + stmt.value.value.name, + index_positions, + indexed_arrays, + non_indexed_arrays, + derived_from_indices): + return True, index_positions, indexed_arrays, non_indexed_arrays + # Fusion safe so go to next statement. + continue + elif op == 'call': + # If there is a call in the parfor body that takes some + # array parameter then we have no way to analyze what + # that call is doing so presume it is unsafe for fusion. + if (any([isinstance(typemap[x.name], types.npytypes.Array) + for x in stmt.value.list_vars()])): + return True, index_positions, indexed_arrays, non_indexed_arrays + + # Get the vars used by this non-setitem/getitem statement. + rhs_vars = [x.name for x in stmt.value.list_vars()] + # If a parfor index is used as part of this statement or + # something previous determined to be derived from a parfor + # index then add the target variable to the set of + # variables that are derived from parfors and so should + # prevent fusion if used as an index. + if (not indices.isdisjoint(rhs_vars) or + not derived_from_indices.isdisjoint(rhs_vars)): + derived_from_indices.add(stmt.target.name) + + return False, index_positions, indexed_arrays, non_indexed_arrays + + +def dprint(*s): + if config.DEBUG_ARRAY_OPT >= 1: + print(*s) + +def get_parfor_pattern_vars(parfor): + """ get the variables used in parfor pattern information + """ + out = set() + # currently, only stencil pattern has variables + for pattern in parfor.patterns: + if pattern[0] == 'stencil': + left_lengths = pattern[1][0] + right_lengths = pattern[1][1] + for v in left_lengths+right_lengths: + if isinstance(v, ir.Var): + out.add(v.name) + return out + +def remove_dead_parfor(parfor, lives, lives_n_aliases, arg_aliases, alias_map, func_ir, typemap): + """ remove dead code inside parfor including get/sets + """ + + with dummy_return_in_loop_body(parfor.loop_body): + labels = find_topo_order(parfor.loop_body) + + # get/setitem replacement should ideally use dataflow to propagate setitem + # saved values, but for simplicity we handle the common case of propagating + # setitems in the first block (which is dominant) if the array is not + # potentially changed in any way + first_label = labels[0] + first_block_saved_values = {} + _update_parfor_get_setitems( + parfor.loop_body[first_label].body, + parfor.index_var, alias_map, + first_block_saved_values, + lives_n_aliases + ) + + # remove saved first block setitems if array potentially changed later + saved_arrs = set(first_block_saved_values.keys()) + for l in labels: + if l == first_label: + continue + for stmt in parfor.loop_body[l].body: + if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'getitem' + and stmt.value.index.name == parfor.index_var.name): + continue + varnames = set(v.name for v in stmt.list_vars()) + rm_arrs = varnames & saved_arrs + for a in rm_arrs: + first_block_saved_values.pop(a, None) + + + # replace getitems with available value + # e.g. A[i] = v; ... s = A[i] -> s = v + for l in labels: + if l == first_label: + continue + block = parfor.loop_body[l] + saved_values = first_block_saved_values.copy() + _update_parfor_get_setitems(block.body, parfor.index_var, alias_map, + saved_values, lives_n_aliases) + + + # after getitem replacement, remove extra setitems + blocks = parfor.loop_body.copy() # shallow copy is enough + last_label = max(blocks.keys()) + return_label, tuple_var = _add_liveness_return_block(blocks, lives_n_aliases, typemap) + # jump to return label + jump = ir.Jump(return_label, ir.Loc("parfors_dummy", -1)) + blocks[last_label].body.append(jump) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + alias_set = set(alias_map.keys()) + + for label, block in blocks.items(): + new_body = [] + in_lives = {v.name for v in block.terminator.list_vars()} + # find live variables at the end of block + for out_blk, _data in cfg.successors(label): + in_lives |= live_map[out_blk] + for stmt in reversed(block.body): + # aliases of lives are also live for setitems + alias_lives = in_lives & alias_set + for v in alias_lives: + in_lives |= alias_map[v] + if (isinstance(stmt, (ir.StaticSetItem, ir.SetItem)) and + get_index_var(stmt).name == parfor.index_var.name and + stmt.target.name not in in_lives and + stmt.target.name not in arg_aliases): + continue + in_lives |= {v.name for v in stmt.list_vars()} + new_body.append(stmt) + new_body.reverse() + block.body = new_body + + typemap.pop(tuple_var.name) # remove dummy tuple type + blocks[last_label].body.pop() # remove jump + + """ + Process parfor body recursively. + Note that this is the only place in this function that uses the + argument lives instead of lives_n_aliases. The former does not + include the aliases of live variables but only the live variable + names themselves. See a comment in this function for how that + is used. + """ + remove_dead_parfor_recursive( + parfor, lives, arg_aliases, alias_map, func_ir, typemap) + + # remove parfor if empty + is_empty = len(parfor.init_block.body) == 0 + for block in parfor.loop_body.values(): + is_empty &= len(block.body) == 0 + if is_empty: + return None + return parfor + +def _update_parfor_get_setitems(block_body, index_var, alias_map, + saved_values, lives): + """ + replace getitems of a previously set array in a block of parfor loop body + """ + for stmt in block_body: + if (isinstance(stmt, (ir.StaticSetItem, ir.SetItem)) and + get_index_var(stmt).name == index_var.name and + stmt.target.name not in lives): + # saved values of aliases of SetItem target array are invalid + for w in alias_map.get(stmt.target.name, []): + saved_values.pop(w, None) + # set saved value after invalidation since alias_map may + # contain the array itself (e.g. pi example) + saved_values[stmt.target.name] = stmt.value + continue + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr): + rhs = stmt.value + if rhs.op == 'getitem' and isinstance(rhs.index, ir.Var): + if rhs.index.name == index_var.name: + # replace getitem if value saved + stmt.value = saved_values.get(rhs.value.name, rhs) + continue + # conservative assumption: array is modified if referenced + # remove all referenced arrays + for v in stmt.list_vars(): + saved_values.pop(v.name, None) + # aliases are potentially modified as well + for w in alias_map.get(v.name, []): + saved_values.pop(w, None) + + return + +ir_utils.remove_dead_extensions[Parfor] = remove_dead_parfor + + +def remove_dead_parfor_recursive(parfor, lives, arg_aliases, alias_map, + func_ir, typemap): + """create a dummy function from parfor and call remove dead recursively + """ + blocks = parfor.loop_body.copy() # shallow copy is enough + first_body_block = min(blocks.keys()) + assert first_body_block > 0 # we are using 0 for init block here + last_label = max(blocks.keys()) + + """ + Previously, this statement used lives_n_aliases. That had the effect of + keeping variables in the init_block alive if they aliased an array that + was later written to. By using just lives to indicate which variables + names are live at exit of the parfor but then using alias_map for the + actual recursive dead code removal, we keep any writes to aliased arrays + alive but also allow aliasing assignments (i.e., a = b) to be eliminated + so long as 'b' is not written to through the variable 'a' later on. + This makes assignment handling of remove_dead_block work properly since + it allows distinguishing between live variables and their aliases. + """ + return_label, tuple_var = _add_liveness_return_block(blocks, lives, typemap) + + # branch back to first body label to simulate loop + scope = blocks[last_label].scope + + branchcond = ir.Var(scope, mk_unique_var("$branchcond"), ir.Loc("parfors_dummy", -1)) + typemap[branchcond.name] = types.boolean + + branch = ir.Branch(branchcond, first_body_block, return_label, ir.Loc("parfors_dummy", -1)) + blocks[last_label].body.append(branch) + + # add dummy jump in init_block for CFG to work + blocks[0] = parfor.init_block + blocks[0].body.append(ir.Jump(first_body_block, ir.Loc("parfors_dummy", -1))) + + # args var including aliases is ok + remove_dead(blocks, arg_aliases, func_ir, typemap, alias_map, arg_aliases) + typemap.pop(tuple_var.name) # remove dummy tuple type + blocks[0].body.pop() # remove dummy jump + blocks[last_label].body.pop() # remove branch + return + +def _add_liveness_return_block(blocks, lives, typemap): + last_label = max(blocks.keys()) + return_label = last_label + 1 + + loc = blocks[last_label].loc + scope = blocks[last_label].scope + blocks[return_label] = ir.Block(scope, loc) + + # add lives in a dummpy return to last block to avoid their removal + tuple_var = ir.Var(scope, mk_unique_var("$tuple_var"), loc) + # dummy type for tuple_var + typemap[tuple_var.name] = types.containers.UniTuple( + types.uintp, 2) + live_vars = [ir.Var(scope, v, loc) for v in lives] + tuple_call = ir.Expr.build_tuple(live_vars, loc) + blocks[return_label].body.append(ir.Assign(tuple_call, tuple_var, loc)) + blocks[return_label].body.append(ir.Return(tuple_var, loc)) + return return_label, tuple_var + + +def find_potential_aliases_parfor(parfor, args, typemap, func_ir, alias_map, arg_aliases): + blocks = wrap_parfor_blocks(parfor) + ir_utils.find_potential_aliases( + blocks, args, typemap, func_ir, alias_map, arg_aliases) + unwrap_parfor_blocks(parfor) + return + +ir_utils.alias_analysis_extensions[Parfor] = find_potential_aliases_parfor + +def simplify_parfor_body_CFG(blocks): + """simplify CFG of body loops in parfors""" + n_parfors = 0 + for block in blocks.values(): + for stmt in block.body: + if isinstance(stmt, Parfor): + n_parfors += 1 + parfor = stmt + # add dummy return to enable CFG creation + # can't use dummy_return_in_loop_body since body changes + last_block = parfor.loop_body[max(parfor.loop_body.keys())] + scope = last_block.scope + loc = ir.Loc("parfors_dummy", -1) + const = ir.Var(scope, mk_unique_var("$const"), loc) + last_block.body.append(ir.Assign(ir.Const(0, loc), const, loc)) + last_block.body.append(ir.Return(const, loc)) + parfor.loop_body = simplify_CFG(parfor.loop_body) + last_block = parfor.loop_body[max(parfor.loop_body.keys())] + last_block.body.pop() + # call on body recursively + simplify_parfor_body_CFG(parfor.loop_body) + return n_parfors + + +def wrap_parfor_blocks(parfor, entry_label = None): + """wrap parfor blocks for analysis/optimization like CFG""" + blocks = parfor.loop_body.copy() # shallow copy is enough + if entry_label is None: + entry_label = min(blocks.keys()) + assert entry_label > 0 # we are using 0 for init block here + + # add dummy jump in init_block for CFG to work + blocks[0] = parfor.init_block + blocks[0].body.append(ir.Jump(entry_label, blocks[0].loc)) + for block in blocks.values(): + if len(block.body) == 0 or (not block.body[-1].is_terminator): + block.body.append(ir.Jump(entry_label, block.loc)) + return blocks + + +def unwrap_parfor_blocks(parfor, blocks=None): + """ + unwrap parfor blocks after analysis/optimization. + Allows changes to the parfor loop. + """ + if blocks is not None: + # make sure init block isn't removed + init_block_label = min(blocks.keys()) + # update loop body blocks + blocks.pop(init_block_label) + parfor.loop_body = blocks + + # make sure dummy jump to loop body isn't altered + first_body_label = min(parfor.loop_body.keys()) + assert isinstance(parfor.init_block.body[-1], ir.Jump) + + # remove dummy jump to loop body + parfor.init_block.body.pop() + + # make sure dummy jump back to loop body isn't altered + for block in parfor.loop_body.values(): + if (isinstance(block.body[-1], ir.Jump) and + block.body[-1].target == first_body_label): + # remove dummy jump back to loop + block.body.pop() + return + + +def get_copies_parfor(parfor, typemap): + """find copies generated/killed by parfor""" + blocks = wrap_parfor_blocks(parfor) + in_copies_parfor, out_copies_parfor = copy_propagate(blocks, typemap) + in_gen_copies, in_extra_kill = get_block_copies(blocks, typemap) + unwrap_parfor_blocks(parfor) + + # parfor's extra kill is kills of its init block, + # and all possible gens and kills of it's body loop. + # body doesn't gen and only kills since it may or may not run + # TODO: save copies that are repeated in parfor + kill_set = in_extra_kill[0] + for label in parfor.loop_body.keys(): + kill_set |= {l for l, r in in_gen_copies[label]} + kill_set |= in_extra_kill[label] + + # gen copies is copies generated by init that are not killed by body + last_label = max(parfor.loop_body.keys()) + gens = out_copies_parfor[last_label] & in_gen_copies[0] + + if config.DEBUG_ARRAY_OPT >= 1: + print("copy propagate parfor gens:", gens, "kill_set", kill_set) + return gens, kill_set + + +ir_utils.copy_propagate_extensions[Parfor] = get_copies_parfor + + +def apply_copies_parfor(parfor, var_dict, name_var_table, + typemap, calltypes, save_copies): + """apply copy propagate recursively in parfor""" + # replace variables in pattern metadata like stencil neighborhood + for i, pattern in enumerate(parfor.patterns): + if pattern[0] == 'stencil': + parfor.patterns[i] = ('stencil', + replace_vars_inner(pattern[1], var_dict)) + + # replace loop boundary variables + for l in parfor.loop_nests: + l.start = replace_vars_inner(l.start, var_dict) + l.stop = replace_vars_inner(l.stop, var_dict) + l.step = replace_vars_inner(l.step, var_dict) + + blocks = wrap_parfor_blocks(parfor) + # add dummy assigns for each copy + assign_list = [] + for lhs_name, rhs in var_dict.items(): + assign_list.append(ir.Assign(rhs, name_var_table[lhs_name], + ir.Loc("dummy", -1))) + blocks[0].body = assign_list + blocks[0].body + in_copies_parfor, out_copies_parfor = copy_propagate(blocks, typemap) + apply_copy_propagate(blocks, in_copies_parfor, name_var_table, typemap, + calltypes, save_copies) + unwrap_parfor_blocks(parfor) + # remove dummy assignments + blocks[0].body = blocks[0].body[len(assign_list):] + return + + +ir_utils.apply_copy_propagate_extensions[Parfor] = apply_copies_parfor + + +def push_call_vars(blocks, saved_globals, saved_getattrs, typemap, nested=False): + """push call variables to right before their call site. + assuming one global/getattr is created for each call site and control flow + doesn't change it. + """ + for block in blocks.values(): + new_body = [] + # global/attr variables that are defined in this block already, + # no need to reassign them + block_defs = set() + # Some definitions are copied right before the call but then we + # need to rename that symbol in that block so that typing won't + # generate an error trying to lock the save var twice. + # In rename_dict, we collect the symbols that must be renamed in + # this block. We collect them then apply the renaming at the end. + rename_dict = {} + for stmt in block.body: + def process_assign(stmt): + if isinstance(stmt, ir.Assign): + rhs = stmt.value + lhs = stmt.target + if (isinstance(rhs, ir.Global)): + saved_globals[lhs.name] = stmt + block_defs.add(lhs.name) + elif isinstance(rhs, ir.Expr) and rhs.op == 'getattr': + if (rhs.value.name in saved_globals + or rhs.value.name in saved_getattrs): + saved_getattrs[lhs.name] = stmt + block_defs.add(lhs.name) + + if not nested and isinstance(stmt, Parfor): + for s in stmt.init_block.body: + process_assign(s) + pblocks = stmt.loop_body.copy() + push_call_vars(pblocks, saved_globals, saved_getattrs, typemap, nested=True) + new_body.append(stmt) + continue + else: + process_assign(stmt) + for v in stmt.list_vars(): + new_body += _get_saved_call_nodes(v.name, saved_globals, + saved_getattrs, block_defs, rename_dict) + new_body.append(stmt) + block.body = new_body + # If there is anything to rename then apply the renaming here. + if len(rename_dict) > 0: + # Fix-up the typing for the renamed vars. + for k, v in rename_dict.items(): + typemap[v] = typemap[k] + # This is only to call replace_var_names which takes a dict. + temp_blocks = {0: block} + replace_var_names(temp_blocks, rename_dict) + + return + + +def _get_saved_call_nodes(fname, saved_globals, saved_getattrs, block_defs, rename_dict): + """ Implement the copying of globals or getattrs for the purposes noted in + push_call_vars. We make a new var and assign to it a copy of the + global or getattr. We remember this new assignment node and add an + entry in the renaming dictionary so that for this block the original + var name is replaced by the new var name we created. + """ + nodes = [] + while (fname not in block_defs and (fname in saved_globals + or fname in saved_getattrs)): + def rename_global_or_getattr(obj, var_base, nodes, block_defs, rename_dict): + assert(isinstance(obj, ir.Assign)) + renamed_var = ir.Var(obj.target.scope, + mk_unique_var(var_base), + obj.target.loc) + renamed_assign = ir.Assign(copy.deepcopy(obj.value), + renamed_var, + obj.loc) + nodes.append(renamed_assign) + block_defs.add(obj.target.name) + rename_dict[obj.target.name] = renamed_assign.target.name + + if fname in saved_globals: + rename_global_or_getattr(saved_globals[fname], "$push_global_to_block", + nodes, block_defs, rename_dict) + fname = '_PA_DONE' + elif fname in saved_getattrs: + rename_global_or_getattr(saved_getattrs[fname], "$push_getattr_to_block", + nodes, block_defs, rename_dict) + fname = saved_getattrs[fname].value.value.name + nodes.reverse() + return nodes + +def repr_arrayexpr(arrayexpr): + """Extract operators from arrayexpr to represent it abstractly as a string. + """ + if isinstance(arrayexpr, tuple): + opr = arrayexpr[0] + # sometimes opr is not string like '+', but is a ufunc object + if not isinstance(opr, str): + if hasattr(opr, '__name__'): + opr = opr.__name__ + else: + opr = '_' # can return dummy since repr is not critical + args = arrayexpr[1] + if len(args) == 1: + return '({}({}))'.format(opr, repr_arrayexpr(args[0])) + else: + opr = ' ' + opr + ' ' + return '({})'.format(opr.join([ repr_arrayexpr(x) for x in args ])) + elif isinstance(arrayexpr, numba.core.ir.Var): + name = arrayexpr.name + if name.startswith('$'): + return '\'%s\' (temporary variable)' % name + else: + return name + elif isinstance(arrayexpr, numba.core.ir.Const): + return repr(arrayexpr.value) + else: + return '_' + +def fix_generator_types(generator_info, return_type, typemap): + """postproc updates generator_info with live variables after transformations + but generator variables have types in return_type that are updated here. + """ + new_state_types = [] + for v in generator_info.state_vars: + new_state_types.append(typemap[v]) + return_type.state_types = tuple(new_state_types) + return + + +def get_parfor_call_table(parfor, call_table=None, reverse_call_table=None): + if call_table is None: + call_table = {} + if reverse_call_table is None: + reverse_call_table = {} + blocks = wrap_parfor_blocks(parfor) + call_table, reverse_call_table = get_call_table(blocks, call_table, + reverse_call_table) + unwrap_parfor_blocks(parfor) + return call_table, reverse_call_table + + +ir_utils.call_table_extensions[Parfor] = get_parfor_call_table + + +def get_parfor_tuple_table(parfor, tuple_table=None): + if tuple_table is None: + tuple_table = {} + blocks = wrap_parfor_blocks(parfor) + tuple_table = ir_utils.get_tuple_table(blocks, tuple_table) + unwrap_parfor_blocks(parfor) + return tuple_table + + +ir_utils.tuple_table_extensions[Parfor] = get_parfor_tuple_table + + +def get_parfor_array_accesses(parfor, accesses=None): + if accesses is None: + accesses = set() + blocks = wrap_parfor_blocks(parfor) + accesses = ir_utils.get_array_accesses(blocks, accesses) + unwrap_parfor_blocks(parfor) + return accesses + + +# parfor handler is same as +ir_utils.array_accesses_extensions[Parfor] = get_parfor_array_accesses + + +def parfor_add_offset_to_labels(parfor, offset): + blocks = wrap_parfor_blocks(parfor) + blocks = add_offset_to_labels(blocks, offset) + blocks[0] = blocks[offset] + blocks.pop(offset) + unwrap_parfor_blocks(parfor, blocks) + return + + +ir_utils.add_offset_to_labels_extensions[Parfor] = parfor_add_offset_to_labels + + +def parfor_find_max_label(parfor): + blocks = wrap_parfor_blocks(parfor) + max_label = ir_utils.find_max_label(blocks) + unwrap_parfor_blocks(parfor) + return max_label + +ir_utils.find_max_label_extensions[Parfor] = parfor_find_max_label + + +def parfor_typeinfer(parfor, typeinferer): + save_blocks = typeinferer.blocks + blocks = wrap_parfor_blocks(parfor) + index_vars = [l.index_variable for l in parfor.loop_nests] + # no need to handle parfor.index_var (tuple of variables), since it will be + # assigned to a tuple from individual indices + first_block = min(blocks.keys()) + loc = blocks[first_block].loc + # XXX + index_assigns = [ir.Assign(ir.Const(1, loc=loc, use_literal_type=False), v, loc) for v in index_vars] + save_first_block_body = blocks[first_block].body + blocks[first_block].body = index_assigns + blocks[first_block].body + typeinferer.blocks = blocks + typeinferer.build_constraint() + typeinferer.blocks = save_blocks + blocks[first_block].body = save_first_block_body + unwrap_parfor_blocks(parfor) + + +typeinfer.typeinfer_extensions[Parfor] = parfor_typeinfer + +def build_parfor_definitions(parfor, definitions=None): + """get variable definition table for parfors""" + if definitions is None: + definitions = defaultdict(list) + + # avoid wrap_parfor_blocks() since build_definitions is called inside + # find_potential_aliases_parfor where the parfor is already wrapped + build_definitions(parfor.loop_body, definitions) + build_definitions({0: parfor.init_block}, definitions) + return definitions + +ir_utils.build_defs_extensions[Parfor] = build_parfor_definitions + +@contextmanager +def dummy_return_in_loop_body(loop_body): + """adds dummy return to last block of parfor loop body for CFG computation + """ + # max is last block since we add it manually for prange + last_label = max(loop_body.keys()) + scope = loop_body[last_label].scope + const = ir.Var(scope, mk_unique_var("$const"), ir.Loc("parfors_dummy", -1)) + loop_body[last_label].body.append( + ir.Return(const, ir.Loc("parfors_dummy", -1))) + yield + # remove dummy return + loop_body[last_label].body.pop() + +@infer_global(reduce) +class ReduceInfer(AbstractTemplate): + def generic(self, args, kws): + assert not kws + if len(args) != 3: + raise errors.NumbaAssertionError("len(args) != 3") + assert isinstance(args[1], types.Array) + return signature(args[1].dtype, *args) + + +def ensure_parallel_support(): + """Check if the platform supports parallel=True and raise if it does not. + """ + if config.IS_32BITS: + msg = ("The 'parallel' target is not currently supported on 32 bit " + "hardware.") + raise errors.UnsupportedParforsError(msg) diff --git a/shared/package-files/76/765f2c8748e9a7e8f8ebab9b55d7bae81cb332b7fd739f594eacc5856386f4d2/blob b/shared/package-files/76/765f2c8748e9a7e8f8ebab9b55d7bae81cb332b7fd739f594eacc5856386f4d2/blob new file mode 100644 index 0000000000000000000000000000000000000000..828685103261d82c6a84010da0260a062d743a2b --- /dev/null +++ b/shared/package-files/76/765f2c8748e9a7e8f8ebab9b55d7bae81cb332b7fd739f594eacc5856386f4d2/blob @@ -0,0 +1,41 @@ +import traceback as tb +from typing import Any, Dict, Tuple + +WRAPPED_EXCEPTION = Tuple[BaseException, tb.StackSummary] + +__all__ = ["CheckpointException"] + + +def _wrap_exception(exc: BaseException) -> WRAPPED_EXCEPTION: + return (exc, tb.extract_tb(exc.__traceback__)) + + +def _is_wrapped_exception(obj: Any) -> bool: + if not isinstance(obj, tuple): + return False + if len(obj) != 2: + return False + return isinstance(obj[0], BaseException) and isinstance(obj[1], tb.StackSummary) + + +class CheckpointException(BaseException): + """Exception raised if failure was detected as part of a checkpoint load or save.""" + + def __init__(self, msg: str, failures: Dict[int, WRAPPED_EXCEPTION]): + super().__init__(msg, failures) + self._failures = failures + + @property + def failures(self) -> Dict[int, WRAPPED_EXCEPTION]: + """Return a dictionary mapping node ranks to their associated exceptions in case of failure.""" + return self._failures + + def __str__(self): + str = f"CheckpointException ranks:{self._failures.keys()}\n" + for rank, exc_pair in self._failures.items(): + exc, trace = exc_pair + str += f"Traceback (most recent call last): (RANK {rank})\n" + if trace is not None: + str += "".join(tb.format_list(trace)) + str += "".join(tb.format_exception_only(type(exc), value=exc)) + return str diff --git a/shared/package-files/76/766bf37b741c6a803f05ee87f33b306a355ab4e3f0b49148171a19144f6a47e0/blob b/shared/package-files/76/766bf37b741c6a803f05ee87f33b306a355ab4e3f0b49148171a19144f6a47e0/blob new file mode 100644 index 0000000000000000000000000000000000000000..416128eab5f53cdc8f45c422bcc140451223bd3f --- /dev/null +++ b/shared/package-files/76/766bf37b741c6a803f05ee87f33b306a355ab4e3f0b49148171a19144f6a47e0/blob @@ -0,0 +1,213 @@ +''' +Static type checking stub file for scipy/spatial/qhull.pyx +''' + + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from typing_extensions import final + +class QhullError(RuntimeError): + ... + +@final +class _Qhull: + # Read-only cython attribute that behaves, more or less, like a property + @property + def ndim(self) -> int: ... + mode_option: bytes + options: bytes + furthest_site: bool + + def __init__( + self, + mode_option: bytes, + points: NDArray[np.float64], + options: None | bytes = ..., + required_options: None | bytes = ..., + furthest_site: bool = ..., + incremental: bool = ..., + interior_point: None | NDArray[np.float64] = ..., + ) -> None: ... + def check_active(self) -> None: ... + def close(self) -> None: ... + def get_points(self) -> NDArray[np.float64]: ... + def add_points( + self, + points: ArrayLike, + interior_point: ArrayLike = ... + ) -> None: ... + def get_paraboloid_shift_scale(self) -> tuple[float, float]: ... + def volume_area(self) -> tuple[float, float]: ... + def triangulate(self) -> None: ... + def get_simplex_facet_array(self) -> tuple[ + NDArray[np.intc], + NDArray[np.intc], + NDArray[np.float64], + NDArray[np.intc], + NDArray[np.intc], + ]: ... + def get_hull_points(self) -> NDArray[np.float64]: ... + def get_hull_facets(self) -> tuple[ + list[list[int]], + NDArray[np.float64], + ]: ... + def get_voronoi_diagram(self) -> tuple[ + NDArray[np.float64], + NDArray[np.intc], + list[list[int]], + list[list[int]], + NDArray[np.intp], + ]: ... + def get_extremes_2d(self) -> NDArray[np.intc]: ... + +def _get_barycentric_transforms( + points: NDArray[np.float64], + simplices: NDArray[np.intc], + eps: float +) -> NDArray[np.float64]: ... + +class _QhullUser: + ndim: int + npoints: int + min_bound: NDArray[np.float64] + max_bound: NDArray[np.float64] + + def __init__(self, qhull: _Qhull, incremental: bool = ...) -> None: ... + def close(self) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def _add_points( + self, + points: ArrayLike, + restart: bool = ..., + interior_point: ArrayLike = ... + ) -> None: ... + +class Delaunay(_QhullUser): + furthest_site: bool + paraboloid_scale: float + paraboloid_shift: float + simplices: NDArray[np.intc] + neighbors: NDArray[np.intc] + equations: NDArray[np.float64] + coplanar: NDArray[np.intc] + good: NDArray[np.intc] + nsimplex: int + vertices: NDArray[np.intc] + + def __init__( + self, + points: ArrayLike, + furthest_site: bool = ..., + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_points( + self, + points: ArrayLike, + restart: bool = ... + ) -> None: ... + @property + def points(self) -> NDArray[np.float64]: ... + @property + def transform(self) -> NDArray[np.float64]: ... + @property + def vertex_to_simplex(self) -> NDArray[np.intc]: ... + @property + def vertex_neighbor_vertices(self) -> tuple[ + NDArray[np.intc], + NDArray[np.intc], + ]: ... + @property + def convex_hull(self) -> NDArray[np.intc]: ... + def find_simplex( + self, + xi: ArrayLike, + bruteforce: bool = ..., + tol: float = ... + ) -> NDArray[np.intc]: ... + def plane_distance(self, xi: ArrayLike) -> NDArray[np.float64]: ... + def lift_points(self, x: ArrayLike) -> NDArray[np.float64]: ... + +def tsearch(tri: Delaunay, xi: ArrayLike) -> NDArray[np.intc]: ... +def _copy_docstr(dst: object, src: object) -> None: ... + +class ConvexHull(_QhullUser): + simplices: NDArray[np.intc] + neighbors: NDArray[np.intc] + equations: NDArray[np.float64] + coplanar: NDArray[np.intc] + good: None | NDArray[np.bool_] + volume: float + area: float + nsimplex: int + + def __init__( + self, + points: ArrayLike, + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_points(self, points: ArrayLike, + restart: bool = ...) -> None: ... + @property + def points(self) -> NDArray[np.float64]: ... + @property + def vertices(self) -> NDArray[np.intc]: ... + +class Voronoi(_QhullUser): + vertices: NDArray[np.float64] + ridge_points: NDArray[np.intc] + ridge_vertices: list[list[int]] + regions: list[list[int]] + point_region: NDArray[np.intp] + furthest_site: bool + + def __init__( + self, + points: ArrayLike, + furthest_site: bool = ..., + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_points( + self, + points: ArrayLike, + restart: bool = ... + ) -> None: ... + @property + def points(self) -> NDArray[np.float64]: ... + @property + def ridge_dict(self) -> dict[tuple[int, int], list[int]]: ... + +class HalfspaceIntersection(_QhullUser): + interior_point: NDArray[np.float64] + dual_facets: list[list[int]] + dual_equations: NDArray[np.float64] + dual_points: NDArray[np.float64] + dual_volume: float + dual_area: float + intersections: NDArray[np.float64] + ndim: int + nineq: int + + def __init__( + self, + halfspaces: ArrayLike, + interior_point: ArrayLike, + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_halfspaces( + self, + halfspaces: ArrayLike, + restart: bool = ... + ) -> None: ... + @property + def halfspaces(self) -> NDArray[np.float64]: ... + @property + def dual_vertices(self) -> NDArray[np.integer]: ... diff --git a/shared/package-files/76/766ca6b23e19a943ec38a82dfdde1e69ab2d1ce4787f5c625c3ba2e272c82255/blob b/shared/package-files/76/766ca6b23e19a943ec38a82dfdde1e69ab2d1ce4787f5c625c3ba2e272c82255/blob new file mode 100644 index 0000000000000000000000000000000000000000..3a56ce711a201163c5ab3d643416c4e6008915b2 --- /dev/null +++ b/shared/package-files/76/766ca6b23e19a943ec38a82dfdde1e69ab2d1ce4787f5c625c3ba2e272c82255/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor cartesian_prod(at::TensorList tensors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/76/766f61ff713546b0b92237b505fd797c0ae8ebe06caaf63f90bdd6a77a5fe7ce/blob b/shared/package-files/76/766f61ff713546b0b92237b505fd797c0ae8ebe06caaf63f90bdd6a77a5fe7ce/blob new file mode 100644 index 0000000000000000000000000000000000000000..97bbe89c41f4fd672f410cd792ee0dc121411940 --- /dev/null +++ b/shared/package-files/76/766f61ff713546b0b92237b505fd797c0ae8ebe06caaf63f90bdd6a77a5fe7ce/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_broadcast_to { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_broadcast_to") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_broadcast_to(Tensor(a) self, int[] size) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef size); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/76/7670685bcbe86d2bd8465ce552d49bd06e29959b752b251189c0b03f0c519bb2/blob b/shared/package-files/76/7670685bcbe86d2bd8465ce552d49bd06e29959b752b251189c0b03f0c519bb2/blob new file mode 100644 index 0000000000000000000000000000000000000000..d763d3dc17662fa1b8158d732ecf9f173a708343 Binary files /dev/null and b/shared/package-files/76/7670685bcbe86d2bd8465ce552d49bd06e29959b752b251189c0b03f0c519bb2/blob differ diff --git a/shared/package-files/76/76786bfeda419d6ee51bfc469672e5cd2b6905e3177df0bb8ed4dda234bb83ec/blob b/shared/package-files/76/76786bfeda419d6ee51bfc469672e5cd2b6905e3177df0bb8ed4dda234bb83ec/blob new file mode 100644 index 0000000000000000000000000000000000000000..aaa2dc745f134c918aa653ac65f14fd2e117765a --- /dev/null +++ b/shared/package-files/76/76786bfeda419d6ee51bfc469672e5cd2b6905e3177df0bb8ed4dda234bb83ec/blob @@ -0,0 +1,477 @@ +""" +Provide math calls that uses intrinsics or libc math functions. +""" + +import math +import operator +import sys +import numpy as np + +import llvmlite.ir +from llvmlite.ir import Constant + +from numba.core.imputils import Registry, impl_ret_untracked +from numba import typeof +from numba.core import types, utils, config, cgutils +from numba.core.extending import overload +from numba.core.typing import signature +from numba.cpython.unsafe.numbers import trailing_zeros + + +registry = Registry('mathimpl') +lower = registry.lower + + +# Helpers, shared with cmathimpl. +_NP_FLT_FINFO = np.finfo(np.dtype('float32')) +FLT_MAX = _NP_FLT_FINFO.max +FLT_MIN = _NP_FLT_FINFO.tiny + +_NP_DBL_FINFO = np.finfo(np.dtype('float64')) +DBL_MAX = _NP_DBL_FINFO.max +DBL_MIN = _NP_DBL_FINFO.tiny + +FLOAT_ABS_MASK = 0x7fffffff +FLOAT_SIGN_MASK = 0x80000000 +DOUBLE_ABS_MASK = 0x7fffffffffffffff +DOUBLE_SIGN_MASK = 0x8000000000000000 + + +def is_nan(builder, val): + """ + Return a condition testing whether *val* is a NaN. + """ + return builder.fcmp_unordered('uno', val, val) + +def is_inf(builder, val): + """ + Return a condition testing whether *val* is an infinite. + """ + pos_inf = Constant(val.type, float("+inf")) + neg_inf = Constant(val.type, float("-inf")) + isposinf = builder.fcmp_ordered('==', val, pos_inf) + isneginf = builder.fcmp_ordered('==', val, neg_inf) + return builder.or_(isposinf, isneginf) + +def is_finite(builder, val): + """ + Return a condition testing whether *val* is a finite. + """ + # is_finite(x) <=> x - x != NaN + val_minus_val = builder.fsub(val, val) + return builder.fcmp_ordered('ord', val_minus_val, val_minus_val) + +def f64_as_int64(builder, val): + """ + Bitcast a double into a 64-bit integer. + """ + assert val.type == llvmlite.ir.DoubleType() + return builder.bitcast(val, llvmlite.ir.IntType(64)) + +def int64_as_f64(builder, val): + """ + Bitcast a 64-bit integer into a double. + """ + assert val.type == llvmlite.ir.IntType(64) + return builder.bitcast(val, llvmlite.ir.DoubleType()) + +def f32_as_int32(builder, val): + """ + Bitcast a float into a 32-bit integer. + """ + assert val.type == llvmlite.ir.FloatType() + return builder.bitcast(val, llvmlite.ir.IntType(32)) + +def int32_as_f32(builder, val): + """ + Bitcast a 32-bit integer into a float. + """ + assert val.type == llvmlite.ir.IntType(32) + return builder.bitcast(val, llvmlite.ir.FloatType()) + +def negate_real(builder, val): + """ + Negate real number *val*, with proper handling of zeros. + """ + # The negative zero forces LLVM to handle signed zeros properly. + return builder.fsub(Constant(val.type, -0.0), val) + +def call_fp_intrinsic(builder, name, args): + """ + Call a LLVM intrinsic floating-point operation. + """ + mod = builder.module + intr = mod.declare_intrinsic(name, [a.type for a in args]) + return builder.call(intr, args) + + +def _unary_int_input_wrapper_impl(wrapped_impl): + """ + Return an implementation factory to convert the single integral input + argument to a float64, then defer to the *wrapped_impl*. + """ + def implementer(context, builder, sig, args): + val, = args + input_type = sig.args[0] + fpval = context.cast(builder, val, input_type, types.float64) + inner_sig = signature(types.float64, types.float64) + res = wrapped_impl(context, builder, inner_sig, (fpval,)) + return context.cast(builder, res, types.float64, sig.return_type) + + return implementer + +def unary_math_int_impl(fn, float_impl): + impl = _unary_int_input_wrapper_impl(float_impl) + lower(fn, types.Integer)(impl) + +def unary_math_intr(fn, intrcode): + """ + Implement the math function *fn* using the LLVM intrinsic *intrcode*. + """ + @lower(fn, types.Float) + def float_impl(context, builder, sig, args): + res = call_fp_intrinsic(builder, intrcode, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + unary_math_int_impl(fn, float_impl) + return float_impl + +def unary_math_extern(fn, f32extern, f64extern, int_restype=False): + """ + Register implementations of Python function *fn* using the + external function named *f32extern* and *f64extern* (for float32 + and float64 inputs, respectively). + If *int_restype* is true, then the function's return value should be + integral, otherwise floating-point. + """ + f_restype = types.int64 if int_restype else None + + def float_impl(context, builder, sig, args): + """ + Implement *fn* for a types.Float input. + """ + [val] = args + mod = builder.module + input_type = sig.args[0] + lty = context.get_value_type(input_type) + func_name = { + types.float32: f32extern, + types.float64: f64extern, + }[input_type] + fnty = llvmlite.ir.FunctionType(lty, [lty]) + fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name) + res = builder.call(fn, (val,)) + res = context.cast(builder, res, input_type, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + lower(fn, types.Float)(float_impl) + + # Implement wrapper for integer inputs + unary_math_int_impl(fn, float_impl) + + return float_impl + + +unary_math_intr(math.fabs, 'llvm.fabs') +exp_impl = unary_math_intr(math.exp, 'llvm.exp') +if sys.version_info >= (3, 11): + exp2_impl = unary_math_intr(math.exp2, 'llvm.exp2') +log_impl = unary_math_intr(math.log, 'llvm.log') +log10_impl = unary_math_intr(math.log10, 'llvm.log10') +log2_impl = unary_math_intr(math.log2, 'llvm.log2') +sin_impl = unary_math_intr(math.sin, 'llvm.sin') +cos_impl = unary_math_intr(math.cos, 'llvm.cos') + +log1p_impl = unary_math_extern(math.log1p, "log1pf", "log1p") +expm1_impl = unary_math_extern(math.expm1, "expm1f", "expm1") +erf_impl = unary_math_extern(math.erf, "erff", "erf") +erfc_impl = unary_math_extern(math.erfc, "erfcf", "erfc") + +tan_impl = unary_math_extern(math.tan, "tanf", "tan") +asin_impl = unary_math_extern(math.asin, "asinf", "asin") +acos_impl = unary_math_extern(math.acos, "acosf", "acos") +atan_impl = unary_math_extern(math.atan, "atanf", "atan") + +asinh_impl = unary_math_extern(math.asinh, "asinhf", "asinh") +acosh_impl = unary_math_extern(math.acosh, "acoshf", "acosh") +atanh_impl = unary_math_extern(math.atanh, "atanhf", "atanh") +sinh_impl = unary_math_extern(math.sinh, "sinhf", "sinh") +cosh_impl = unary_math_extern(math.cosh, "coshf", "cosh") +tanh_impl = unary_math_extern(math.tanh, "tanhf", "tanh") + +log2_impl = unary_math_extern(math.log2, "log2f", "log2") +ceil_impl = unary_math_extern(math.ceil, "ceilf", "ceil", True) +floor_impl = unary_math_extern(math.floor, "floorf", "floor", True) + +gamma_impl = unary_math_extern(math.gamma, "numba_gammaf", "numba_gamma") # work-around +sqrt_impl = unary_math_extern(math.sqrt, "sqrtf", "sqrt") +trunc_impl = unary_math_extern(math.trunc, "truncf", "trunc", True) +lgamma_impl = unary_math_extern(math.lgamma, "lgammaf", "lgamma") + + +@lower(math.isnan, types.Float) +def isnan_float_impl(context, builder, sig, args): + [val] = args + res = is_nan(builder, val) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower(math.isnan, types.Integer) +def isnan_int_impl(context, builder, sig, args): + res = cgutils.false_bit + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.isinf, types.Float) +def isinf_float_impl(context, builder, sig, args): + [val] = args + res = is_inf(builder, val) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower(math.isinf, types.Integer) +def isinf_int_impl(context, builder, sig, args): + res = cgutils.false_bit + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.isfinite, types.Float) +def isfinite_float_impl(context, builder, sig, args): + [val] = args + res = is_finite(builder, val) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.isfinite, types.Integer) +def isfinite_int_impl(context, builder, sig, args): + res = cgutils.true_bit + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.copysign, types.Float, types.Float) +def copysign_float_impl(context, builder, sig, args): + lty = args[0].type + mod = builder.module + fn = cgutils.get_or_insert_function(mod, llvmlite.ir.FunctionType(lty, (lty, lty)), + 'llvm.copysign.%s' % lty.intrinsic_name) + res = builder.call(fn, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + + +@lower(math.frexp, types.Float) +def frexp_impl(context, builder, sig, args): + val, = args + fltty = context.get_data_type(sig.args[0]) + intty = context.get_data_type(sig.return_type[1]) + expptr = cgutils.alloca_once(builder, intty, name='exp') + fnty = llvmlite.ir.FunctionType(fltty, (fltty, llvmlite.ir.PointerType(intty))) + fname = { + "float": "numba_frexpf", + "double": "numba_frexp", + }[str(fltty)] + fn = cgutils.get_or_insert_function(builder.module, fnty, fname) + res = builder.call(fn, (val, expptr)) + res = cgutils.make_anonymous_struct(builder, (res, builder.load(expptr))) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.ldexp, types.Float, types.intc) +def ldexp_impl(context, builder, sig, args): + val, exp = args + fltty, intty = map(context.get_data_type, sig.args) + fnty = llvmlite.ir.FunctionType(fltty, (fltty, intty)) + fname = { + "float": "numba_ldexpf", + "double": "numba_ldexp", + }[str(fltty)] + fn = cgutils.insert_pure_function(builder.module, fnty, name=fname) + # The exponent is a C `int`, and ABIs such as PowerPC64LE ELFv2 + # require the caller to sign-extend it into the full argument + # register. A bare i32 parameter carries no signedness, so LLVM + # does not, and a negative exponent reaches the callee as a large + # positive one. See issue #8489. + fn.args[1].add_attribute('signext') + res = builder.call(fn, (val, exp)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + + +@lower(math.atan2, types.int64, types.int64) +def atan2_s64_impl(context, builder, sig, args): + [y, x] = args + y = builder.sitofp(y, llvmlite.ir.DoubleType()) + x = builder.sitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + return atan2_float_impl(context, builder, fsig, (y, x)) + +@lower(math.atan2, types.uint64, types.uint64) +def atan2_u64_impl(context, builder, sig, args): + [y, x] = args + y = builder.uitofp(y, llvmlite.ir.DoubleType()) + x = builder.uitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + return atan2_float_impl(context, builder, fsig, (y, x)) + +@lower(math.atan2, types.Float, types.Float) +def atan2_float_impl(context, builder, sig, args): + assert len(args) == 2 + mod = builder.module + ty = sig.args[0] + lty = context.get_value_type(ty) + func_name = { + types.float32: "atan2f", + types.float64: "atan2" + }[ty] + fnty = llvmlite.ir.FunctionType(lty, (lty, lty)) + fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name) + res = builder.call(fn, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + + +@lower(math.hypot, types.int64, types.int64) +def hypot_s64_impl(context, builder, sig, args): + [x, y] = args + y = builder.sitofp(y, llvmlite.ir.DoubleType()) + x = builder.sitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + res = hypot_float_impl(context, builder, fsig, (x, y)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.hypot, types.uint64, types.uint64) +def hypot_u64_impl(context, builder, sig, args): + [x, y] = args + y = builder.sitofp(y, llvmlite.ir.DoubleType()) + x = builder.sitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + res = hypot_float_impl(context, builder, fsig, (x, y)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.hypot, types.Float, types.Float) +def hypot_float_impl(context, builder, sig, args): + xty, yty = sig.args + assert xty == yty == sig.return_type + x, y = args + + # Windows has alternate names for hypot/hypotf, see + # https://msdn.microsoft.com/fr-fr/library/a9yb3dbt%28v=vs.80%29.aspx + fname = { + types.float32: "_hypotf" if sys.platform == 'win32' else "hypotf", + types.float64: "_hypot" if sys.platform == 'win32' else "hypot", + }[xty] + plat_hypot = types.ExternalFunction(fname, sig) + + if sys.platform == 'win32' and config.MACHINE_BITS == 32: + inf = xty(float('inf')) + + def hypot_impl(x, y): + if math.isinf(x) or math.isinf(y): + return inf + return plat_hypot(x, y) + else: + def hypot_impl(x, y): + return plat_hypot(x, y) + + res = context.compile_internal(builder, hypot_impl, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + +@lower(math.radians, types.Float) +def radians_float_impl(context, builder, sig, args): + [x] = args + coef = context.get_constant(sig.return_type, math.pi / 180) + res = builder.fmul(x, coef) + return impl_ret_untracked(context, builder, sig.return_type, res) + +unary_math_int_impl(math.radians, radians_float_impl) + +# ----------------------------------------------------------------------------- + +@lower(math.degrees, types.Float) +def degrees_float_impl(context, builder, sig, args): + [x] = args + coef = context.get_constant(sig.return_type, 180 / math.pi) + res = builder.fmul(x, coef) + return impl_ret_untracked(context, builder, sig.return_type, res) + +unary_math_int_impl(math.degrees, degrees_float_impl) + +# ----------------------------------------------------------------------------- + +@lower(math.pow, types.Float, types.Float) +@lower(math.pow, types.Float, types.Integer) +def pow_impl(context, builder, sig, args): + impl = context.get_function(operator.pow, sig) + return impl(builder, args) + +# ----------------------------------------------------------------------------- + +@lower(math.nextafter, types.Float, types.Float) +def nextafter_impl(context, builder, sig, args): + assert len(args) == 2 + ty = sig.args[0] + lty = context.get_value_type(ty) + func_name = { + types.float32: "nextafterf", + types.float64: "nextafter" + }[ty] + fnty = llvmlite.ir.FunctionType(lty, (lty, lty)) + fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name) + res = builder.call(fn, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# ----------------------------------------------------------------------------- + +def _unsigned(T): + """Convert integer to unsigned integer of equivalent width.""" + pass + +@overload(_unsigned) +def _unsigned_impl(T): + if T in types.unsigned_domain: + return lambda T: T + elif T in types.signed_domain: + newT = getattr(types, 'uint{}'.format(T.bitwidth)) + return lambda T: newT(T) + + +def gcd_impl(context, builder, sig, args): + xty, yty = sig.args + assert xty == yty == sig.return_type + x, y = args + + def gcd(a, b): + """ + Stein's algorithm, heavily cribbed from Julia implementation. + """ + T = type(a) + if a == 0: return abs(b) + if b == 0: return abs(a) + za = trailing_zeros(a) + zb = trailing_zeros(b) + k = min(za, zb) + # Uses np.*_shift instead of operators due to return types + u = _unsigned(abs(np.right_shift(a, za))) + v = _unsigned(abs(np.right_shift(b, zb))) + while u != v: + if u > v: + u, v = v, u + v -= u + v = np.right_shift(v, trailing_zeros(v)) + r = np.left_shift(T(u), k) + return r + + res = context.compile_internal(builder, gcd, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +lower(math.gcd, types.Integer, types.Integer)(gcd_impl) diff --git a/shared/package-files/76/7678faccdbc62839671fb47e88e81ca3a6b45383a6081834ccbf13b49488e4ce/blob b/shared/package-files/76/7678faccdbc62839671fb47e88e81ca3a6b45383a6081834ccbf13b49488e4ce/blob new file mode 100644 index 0000000000000000000000000000000000000000..7671a7ad7921d618cfdb98ba6baa60f24e3a9316 --- /dev/null +++ b/shared/package-files/76/7678faccdbc62839671fb47e88e81ca3a6b45383a6081834ccbf13b49488e4ce/blob @@ -0,0 +1,1171 @@ +"""Univariate features selection.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy import special, stats +from scipy.sparse import issparse + +from ..base import BaseEstimator, _fit_context +from ..preprocessing import LabelBinarizer +from ..utils import as_float_array, check_array, check_X_y, safe_mask, safe_sqr +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.extmath import row_norms, safe_sparse_dot +from ..utils.validation import check_is_fitted, validate_data +from ._base import SelectorMixin + + +def _clean_nans(scores): + """ + Fixes Issue #1240: NaNs can't be properly compared, so change them to the + smallest value of scores's dtype. -inf seems to be unreliable. + """ + # XXX where should this function be called? fit? scoring functions + # themselves? + scores = as_float_array(scores, copy=True) + scores[np.isnan(scores)] = np.finfo(scores.dtype).min + return scores + + +###################################################################### +# Scoring functions + + +# The following function is a rewriting of scipy.stats.f_oneway +# Contrary to the scipy.stats.f_oneway implementation it does not +# copy the data while keeping the inputs unchanged. +def f_oneway(*args): + """Perform a 1-way ANOVA. + + The one-way ANOVA tests the null hypothesis that 2 or more groups have + the same population mean. The test is applied to samples from two or + more groups, possibly with differing sizes. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + *args : {array-like, sparse matrix} + Sample1, sample2... The sample measurements should be given as + arguments. + + Returns + ------- + f_statistic : float + The computed F-value of the test. + p_value : float + The associated p-value from the F-distribution. + + Notes + ----- + The ANOVA test has important assumptions that must be satisfied in order + for the associated p-value to be valid. + + 1. The samples are independent + 2. Each sample is from a normally distributed population + 3. The population standard deviations of the groups are all equal. This + property is known as homoscedasticity. + + If these assumptions are not true for a given set of data, it may still be + possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`_) although + with some loss of power. + + The algorithm is from Heiman[2], pp.394-7. + + See ``scipy.stats.f_oneway`` that should give the same results while + being less efficient. + + References + ---------- + .. [1] Lowry, Richard. "Concepts and Applications of Inferential + Statistics". Chapter 14. + http://vassarstats.net/textbook + + .. [2] Heiman, G.W. Research Methods in Statistics. 2002. + """ + n_classes = len(args) + args = [as_float_array(a) for a in args] + n_samples_per_class = np.array([a.shape[0] for a in args]) + n_samples = np.sum(n_samples_per_class) + ss_alldata = sum(safe_sqr(a).sum(axis=0) for a in args) + sums_args = [np.asarray(a.sum(axis=0)) for a in args] + square_of_sums_alldata = sum(sums_args) ** 2 + square_of_sums_args = [s**2 for s in sums_args] + sstot = ss_alldata - square_of_sums_alldata / float(n_samples) + ssbn = 0.0 + for k, _ in enumerate(args): + ssbn += square_of_sums_args[k] / n_samples_per_class[k] + ssbn -= square_of_sums_alldata / float(n_samples) + sswn = sstot - ssbn + dfbn = n_classes - 1 + dfwn = n_samples - n_classes + msb = ssbn / float(dfbn) + msw = sswn / float(dfwn) + constant_features_idx = np.where(msw == 0.0)[0] + if np.nonzero(msb)[0].size != msb.size and constant_features_idx.size: + warnings.warn("Features %s are constant." % constant_features_idx, UserWarning) + f = msb / msw + # flatten matrix to vector in sparse case + f = np.asarray(f).ravel() + prob = special.fdtrc(dfbn, dfwn, f) + return f, prob + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def f_classif(X, y): + """Compute the ANOVA F-value for the provided sample. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The set of regressors that will be tested sequentially. + + y : array-like of shape (n_samples,) + The target vector. + + Returns + ------- + f_statistic : ndarray of shape (n_features,) + F-statistic for each feature. + + p_values : ndarray of shape (n_features,) + P-values associated with the F-statistic. + + See Also + -------- + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.feature_selection import f_classif + >>> X, y = make_classification( + ... n_samples=100, n_features=10, n_informative=2, n_clusters_per_class=1, + ... shuffle=False, random_state=42 + ... ) + >>> f_statistic, p_values = f_classif(X, y) + >>> f_statistic + array([2.21e+02, 7.02e-01, 1.70e+00, 9.31e-01, + 5.41e+00, 3.25e-01, 4.71e-02, 5.72e-01, + 7.54e-01, 8.90e-02]) + >>> p_values + array([7.14e-27, 4.04e-01, 1.96e-01, 3.37e-01, + 2.21e-02, 5.70e-01, 8.29e-01, 4.51e-01, + 3.87e-01, 7.66e-01]) + """ + X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"]) + args = [X[safe_mask(X, y == k)] for k in np.unique(y)] + return f_oneway(*args) + + +def _chisquare(f_obs, f_exp): + """Fast replacement for scipy.stats.chisquare. + + Version from https://github.com/scipy/scipy/pull/2525 with additional + optimizations. + """ + f_obs = np.asarray(f_obs, dtype=np.float64) + + k = len(f_obs) + # Reuse f_obs for chi-squared statistics + chisq = f_obs + chisq -= f_exp + chisq **= 2 + with np.errstate(invalid="ignore"): + chisq /= f_exp + chisq = chisq.sum(axis=0) + return chisq, special.chdtrc(k - 1, chisq) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def chi2(X, y): + """Compute chi-squared stats between each non-negative feature and class. + + This score can be used to select the `n_features` features with the + highest values for the test chi-squared statistic from X, which must + contain only **non-negative integer feature values** such as booleans or frequencies + (e.g., term counts in document classification), relative to the classes. + + If some of your features are continuous, you need to bin them, for + example by using :class:`~sklearn.preprocessing.KBinsDiscretizer`. + + Recall that the chi-square test measures dependence between stochastic + variables, so using this function "weeds out" the features that are the + most likely to be independent of class and therefore irrelevant for + classification. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Sample vectors. + + y : array-like of shape (n_samples,) + Target vector (class labels). + + Returns + ------- + chi2 : ndarray of shape (n_features,) + Chi2 statistics for each feature. + + p_values : ndarray of shape (n_features,) + P-values for each feature. + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + f_regression : F-value between label/feature for regression tasks. + + Notes + ----- + Complexity of this algorithm is O(n_classes * n_features). + + Examples + -------- + >>> import numpy as np + >>> from sklearn.feature_selection import chi2 + >>> X = np.array([[1, 1, 3], + ... [0, 1, 5], + ... [5, 4, 1], + ... [6, 6, 2], + ... [1, 4, 0], + ... [0, 0, 0]]) + >>> y = np.array([1, 1, 0, 0, 2, 2]) + >>> chi2_stats, p_values = chi2(X, y) + >>> chi2_stats + array([15.3, 6.5 , 8.9]) + >>> p_values + array([0.000456, 0.0387, 0.0116 ]) + """ + + # XXX: we might want to do some of the following in logspace instead for + # numerical stability. + # Converting X to float allows getting better performance for the + # safe_sparse_dot call made below. + X = check_array(X, accept_sparse="csr", dtype=(np.float64, np.float32)) + if np.any((X.data if issparse(X) else X) < 0): + raise ValueError("Input X must be non-negative.") + + # Use a sparse representation for Y by default to reduce memory usage when + # y has many unique classes. + Y = LabelBinarizer(sparse_output=True).fit_transform(y) + if Y.shape[1] == 1: + Y = Y.toarray() + Y = np.append(1 - Y, Y, axis=1) + + observed = safe_sparse_dot(Y.T, X) # n_classes * n_features + + if issparse(observed): + # convert back to a dense array before calling _chisquare + # XXX: could _chisquare be reimplement to accept sparse matrices for + # cases where both n_classes and n_features are large (and X is + # sparse)? + observed = observed.toarray() + + feature_count = X.sum(axis=0).reshape(1, -1) + class_prob = Y.mean(axis=0).reshape(1, -1) + expected = np.dot(class_prob.T, feature_count) + + return _chisquare(observed, expected) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like"], + "center": ["boolean"], + "force_finite": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def r_regression(X, y, *, center=True, force_finite=True): + """Compute Pearson's r for each features and the target. + + Pearson's r is also known as the Pearson correlation coefficient. + + Linear model for testing the individual effect of each of many regressors. + This is a scoring function to be used in a feature selection procedure, not + a free standing feature selection procedure. + + The cross correlation between each regressor and the target is computed + as:: + + E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y)) + + For more on usage see the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix. + + y : array-like of shape (n_samples,) + The target vector. + + center : bool, default=True + Whether or not to center the data matrix `X` and the target vector `y`. + By default, `X` and `y` will be centered. + + force_finite : bool, default=True + Whether or not to force the Pearson's R correlation to be finite. + In the particular case where some features in `X` or the target `y` + are constant, the Pearson's R correlation is not defined. When + `force_finite=False`, a correlation of `np.nan` is returned to + acknowledge this case. When `force_finite=True`, this value will be + forced to a minimal correlation of `0.0`. + + .. versionadded:: 1.1 + + Returns + ------- + correlation_coefficient : ndarray of shape (n_features,) + Pearson's R correlation coefficients of features. + + See Also + -------- + f_regression: Univariate linear regression tests returning f-statistic + and p-values. + mutual_info_regression: Mutual information for a continuous target. + f_classif: ANOVA F-value between label/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + + Examples + -------- + >>> from sklearn.datasets import make_regression + >>> from sklearn.feature_selection import r_regression + >>> X, y = make_regression( + ... n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42 + ... ) + >>> r_regression(X, y) + array([-0.157, 1. , -0.229]) + """ + X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"], dtype=np.float64) + n_samples = X.shape[0] + + # Compute centered values + # Note that E[(x - mean(x))*(y - mean(y))] = E[x*(y - mean(y))], so we + # need not center X + if center: + y = y - np.mean(y) + # TODO: for Scipy <= 1.10, `isspmatrix(X)` returns `True` for sparse arrays. + # Here, we check the output of the `.mean` operation that returns a `np.matrix` + # for sparse matrices while a `np.array` for dense and sparse arrays. + # We can reconsider using `isspmatrix` when the minimum version is + # SciPy >= 1.11 + X_means = X.mean(axis=0) + X_means = X_means.getA1() if isinstance(X_means, np.matrix) else X_means + # Compute the scaled standard deviations via moments + X_norms = np.sqrt(row_norms(X.T, squared=True) - n_samples * X_means**2) + else: + X_norms = row_norms(X.T) + + correlation_coefficient = safe_sparse_dot(y, X) + with np.errstate(divide="ignore", invalid="ignore"): + correlation_coefficient /= X_norms + correlation_coefficient /= np.linalg.norm(y) + + if force_finite and not np.isfinite(correlation_coefficient).all(): + # case where the target or some features are constant + # the correlation coefficient(s) is/are set to the minimum (i.e. 0.0) + nan_mask = np.isnan(correlation_coefficient) + correlation_coefficient[nan_mask] = 0.0 + return correlation_coefficient + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like"], + "center": ["boolean"], + "force_finite": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def f_regression(X, y, *, center=True, force_finite=True): + """Univariate linear regression tests returning F-statistic and p-values. + + Quick linear model for testing the effect of a single regressor, + sequentially for many regressors. + + This is done in 2 steps: + + 1. The cross correlation between each regressor and the target is computed + using :func:`r_regression` as:: + + E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y)) + + 2. It is converted to an F score and then to a p-value. + + :func:`f_regression` is derived from :func:`r_regression` and will rank + features in the same order if all the features are positively correlated + with the target. + + Note however that contrary to :func:`f_regression`, :func:`r_regression` + values lie in [-1, 1] and can thus be negative. :func:`f_regression` is + therefore recommended as a feature selection criterion to identify + potentially predictive feature for a downstream classifier, irrespective of + the sign of the association with the target variable. + + Furthermore :func:`f_regression` returns p-values while + :func:`r_regression` does not. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix. + + y : array-like of shape (n_samples,) + The target vector. + + center : bool, default=True + Whether or not to center the data matrix `X` and the target vector `y`. + By default, `X` and `y` will be centered. + + force_finite : bool, default=True + Whether or not to force the F-statistics and associated p-values to + be finite. There are two cases where the F-statistic is expected to not + be finite: + + - when the target `y` or some features in `X` are constant. In this + case, the Pearson's R correlation is not defined leading to obtain + `np.nan` values in the F-statistic and p-value. When + `force_finite=True`, the F-statistic is set to `0.0` and the + associated p-value is set to `1.0`. + - when a feature in `X` is perfectly correlated (or + anti-correlated) with the target `y`. In this case, the F-statistic + is expected to be `np.inf`. When `force_finite=True`, the F-statistic + is set to `np.finfo(dtype).max` and the associated p-value is set to + `0.0`. + + .. versionadded:: 1.1 + + Returns + ------- + f_statistic : ndarray of shape (n_features,) + F-statistic for each feature. + + p_values : ndarray of shape (n_features,) + P-values associated with the F-statistic. + + See Also + -------- + r_regression: Pearson's R between label/feature for regression tasks. + f_classif: ANOVA F-value between label/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. + SelectPercentile: Select features based on percentile of the highest + scores. + + Examples + -------- + >>> from sklearn.datasets import make_regression + >>> from sklearn.feature_selection import f_regression + >>> X, y = make_regression( + ... n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42 + ... ) + >>> f_statistic, p_values = f_regression(X, y) + >>> f_statistic + array([1.21, 2.67e13, 2.66]) + >>> p_values + array([0.276, 1.54e-283, 0.11]) + """ + correlation_coefficient = r_regression( + X, y, center=center, force_finite=force_finite + ) + deg_of_freedom = y.size - (2 if center else 1) + + corr_coef_squared = correlation_coefficient**2 + + with np.errstate(divide="ignore", invalid="ignore"): + f_statistic = corr_coef_squared / (1 - corr_coef_squared) * deg_of_freedom + p_values = stats.f.sf(f_statistic, 1, deg_of_freedom) + + if force_finite and not np.isfinite(f_statistic).all(): + # case where there is a perfect (anti-)correlation + # f-statistics can be set to the maximum and p-values to zero + mask_inf = np.isinf(f_statistic) + f_statistic[mask_inf] = np.finfo(f_statistic.dtype).max + # case where the target or some features are constant + # f-statistics would be minimum and thus p-values large + mask_nan = np.isnan(f_statistic) + f_statistic[mask_nan] = 0.0 + p_values[mask_nan] = 1.0 + return f_statistic, p_values + + +###################################################################### +# Base classes + + +class _BaseFilter(SelectorMixin, BaseEstimator): + """Initialize the univariate feature selection. + + Parameters + ---------- + score_func : callable + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues) or a single array with scores. + """ + + _parameter_constraints: dict = {"score_func": [callable]} + + def __init__(self, score_func): + self.score_func = score_func + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Run score function on (X, y) and get the appropriate features. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training input samples. + + y : array-like of shape (n_samples,) or None + The target values (class labels in classification, real numbers in + regression). If the selector is unsupervised then `y` can be set to `None`. + + Returns + ------- + self : object + Returns the instance itself. + """ + if y is None: + X = validate_data(self, X, accept_sparse=["csr", "csc"]) + else: + X, y = validate_data( + self, X, y, accept_sparse=["csr", "csc"], multi_output=True + ) + + self._check_params(X, y) + score_func_ret = self.score_func(X, y) + if isinstance(score_func_ret, (list, tuple)): + self.scores_, self.pvalues_ = score_func_ret + self.pvalues_ = np.asarray(self.pvalues_) + else: + self.scores_ = score_func_ret + self.pvalues_ = None + + self.scores_ = np.asarray(self.scores_) + + return self + + def _check_params(self, X, y): + pass + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.required = True + tags.input_tags.sparse = True + return tags + + +###################################################################### +# Specific filters +###################################################################### +class SelectPercentile(_BaseFilter): + """Select features according to a percentile of the highest scores. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues) or a single array with scores. + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + .. versionadded:: 0.18 + + percentile : int, default=10 + Percent of features to keep. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores, None if `score_func` returned only scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + mutual_info_classif : Mutual information for a discrete target. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Notes + ----- + Ties between features with equal scores will be broken in an unspecified + way. + + This filter supports unsupervised feature selection that only requests `X` for + computing the scores. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.feature_selection import SelectPercentile, chi2 + >>> X, y = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> X_new = SelectPercentile(chi2, percentile=10).fit_transform(X, y) + >>> X_new.shape + (1797, 7) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "percentile": [Interval(Real, 0, 100, closed="both")], + } + + def __init__(self, score_func=f_classif, *, percentile=10): + super().__init__(score_func=score_func) + self.percentile = percentile + + def _get_support_mask(self): + check_is_fitted(self) + + # Cater for NaNs + if self.percentile == 100: + return np.ones(len(self.scores_), dtype=bool) + elif self.percentile == 0: + return np.zeros(len(self.scores_), dtype=bool) + + scores = _clean_nans(self.scores_) + threshold = np.percentile(scores, 100 - self.percentile) + mask = scores > threshold + ties = np.where(scores == threshold)[0] + if len(ties): + max_feats = int(len(scores) * self.percentile / 100) + kept_ties = ties[: max_feats - mask.sum()] + mask[kept_ties] = True + return mask + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.required = False + return tags + + +class SelectKBest(_BaseFilter): + """Select features according to the k highest scores. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues) or a single array with scores. + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + .. versionadded:: 0.18 + + k : int or "all", default=10 + Number of top features to select. + The "all" option bypasses selection, for use in a parameter search. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores, None if `score_func` returned only scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif: ANOVA F-value between label/feature for classification tasks. + mutual_info_classif: Mutual information for a discrete target. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + mutual_info_regression: Mutual information for a continuous target. + SelectPercentile: Select features based on percentile of the highest + scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Notes + ----- + Ties between features with equal scores will be broken in an unspecified + way. + + This filter supports unsupervised feature selection that only requests `X` for + computing the scores. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.feature_selection import SelectKBest, chi2 + >>> X, y = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y) + >>> X_new.shape + (1797, 20) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "k": [StrOptions({"all"}), Interval(Integral, 0, None, closed="left")], + } + + def __init__(self, score_func=f_classif, *, k=10): + super().__init__(score_func=score_func) + self.k = k + + def _check_params(self, X, y): + if not isinstance(self.k, str) and self.k > X.shape[1]: + warnings.warn( + f"k={self.k} is greater than n_features={X.shape[1]}. " + "All the features will be returned." + ) + + def _get_support_mask(self): + check_is_fitted(self) + + if self.k == "all": + return np.ones(self.scores_.shape, dtype=bool) + elif self.k == 0: + return np.zeros(self.scores_.shape, dtype=bool) + else: + scores = _clean_nans(self.scores_) + mask = np.zeros(scores.shape, dtype=bool) + + # Request a stable sort. Mergesort takes more memory (~40MB per + # megafeature on x86-64). + mask[np.argsort(scores, kind="mergesort")[-self.k :]] = 1 + return mask + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.required = False + return tags + + +class SelectFpr(_BaseFilter): + """Filter: Select the pvalues below alpha based on a FPR test. + + FPR test stands for False Positive Rate test. It controls the total + amount of false detections. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + alpha : float, default=5e-2 + Features with p-values less than `alpha` are selected. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + chi2 : Chi-squared stats of non-negative features for classification tasks. + mutual_info_classif: Mutual information for a discrete target. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import SelectFpr, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> X_new = SelectFpr(chi2, alpha=0.01).fit_transform(X, y) + >>> X_new.shape + (569, 16) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "alpha": [Interval(Real, 0, 1, closed="both")], + } + + def __init__(self, score_func=f_classif, *, alpha=5e-2): + super().__init__(score_func=score_func) + self.alpha = alpha + + def _get_support_mask(self): + check_is_fitted(self) + + return self.pvalues_ < self.alpha + + +class SelectFdr(_BaseFilter): + """Filter: Select the p-values for an estimated false discovery rate. + + This uses the Benjamini-Hochberg procedure. ``alpha`` is an upper bound + on the expected false discovery rate. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + alpha : float, default=5e-2 + The highest uncorrected p-value for features to keep. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + mutual_info_classif : Mutual information for a discrete target. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + References + ---------- + https://en.wikipedia.org/wiki/False_discovery_rate + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import SelectFdr, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> X_new = SelectFdr(chi2, alpha=0.01).fit_transform(X, y) + >>> X_new.shape + (569, 16) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "alpha": [Interval(Real, 0, 1, closed="both")], + } + + def __init__(self, score_func=f_classif, *, alpha=5e-2): + super().__init__(score_func=score_func) + self.alpha = alpha + + def _get_support_mask(self): + check_is_fitted(self) + + n_features = len(self.pvalues_) + sv = np.sort(self.pvalues_) + selected = sv[ + sv <= float(self.alpha) / n_features * np.arange(1, n_features + 1) + ] + if selected.size == 0: + return np.zeros_like(self.pvalues_, dtype=bool) + return self.pvalues_ <= selected.max() + + +class SelectFwe(_BaseFilter): + """Filter: Select the p-values corresponding to Family-wise error rate. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + alpha : float, default=5e-2 + The highest uncorrected p-value for features to keep. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import SelectFwe, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> X_new = SelectFwe(chi2, alpha=0.01).fit_transform(X, y) + >>> X_new.shape + (569, 15) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "alpha": [Interval(Real, 0, 1, closed="both")], + } + + def __init__(self, score_func=f_classif, *, alpha=5e-2): + super().__init__(score_func=score_func) + self.alpha = alpha + + def _get_support_mask(self): + check_is_fitted(self) + + return self.pvalues_ < self.alpha / len(self.pvalues_) + + +###################################################################### +# Generic filter +###################################################################### + + +# TODO this class should fit on either p-values or scores, +# depending on the mode. +class GenericUnivariateSelect(_BaseFilter): + """Univariate feature selector with configurable strategy. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). For modes 'percentile' or 'kbest' it can return + a single array scores. + + mode : {'percentile', 'k_best', 'fpr', 'fdr', 'fwe'}, default='percentile' + Feature selection mode. Note that the `'percentile'` and `'kbest'` + modes are supporting unsupervised feature selection (when `y` is `None`). + + param : "all", float or int, default=1e-5 + Parameter of the corresponding mode. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores, None if `score_func` returned scores only. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + mutual_info_classif : Mutual information for a discrete target. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import GenericUnivariateSelect, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> transformer = GenericUnivariateSelect(chi2, mode='k_best', param=20) + >>> X_new = transformer.fit_transform(X, y) + >>> X_new.shape + (569, 20) + """ + + _selection_modes: dict = { + "percentile": SelectPercentile, + "k_best": SelectKBest, + "fpr": SelectFpr, + "fdr": SelectFdr, + "fwe": SelectFwe, + } + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "mode": [StrOptions(set(_selection_modes.keys()))], + "param": [Interval(Real, 0, None, closed="left"), StrOptions({"all"})], + } + + def __init__(self, score_func=f_classif, *, mode="percentile", param=1e-5): + super().__init__(score_func=score_func) + self.mode = mode + self.param = param + + def _make_selector(self): + selector = self._selection_modes[self.mode](score_func=self.score_func) + + # Now perform some acrobatics to set the right named parameter in + # the selector + possible_params = selector._get_param_names() + possible_params.remove("score_func") + selector.set_params(**{possible_params[0]: self.param}) + + return selector + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + return tags + + def _check_params(self, X, y): + self._make_selector()._check_params(X, y) + + def _get_support_mask(self): + check_is_fitted(self) + + selector = self._make_selector() + selector.pvalues_ = self.pvalues_ + selector.scores_ = self.scores_ + return selector._get_support_mask() diff --git a/shared/package-files/76/767a554a1c2cacfcde3dfd50d95481a8f29dfe736626d344d777c0f1aef6b165/blob b/shared/package-files/76/767a554a1c2cacfcde3dfd50d95481a8f29dfe736626d344d777c0f1aef6b165/blob new file mode 100644 index 0000000000000000000000000000000000000000..d42b2d58a61ea4d1f63454b76fcb3929f1089220 Binary files /dev/null and b/shared/package-files/76/767a554a1c2cacfcde3dfd50d95481a8f29dfe736626d344d777c0f1aef6b165/blob differ diff --git a/shared/package-files/76/767b5b677853b7cdc0087fe410f95fc505722f1e60260049a54aaa59b763f429/blob b/shared/package-files/76/767b5b677853b7cdc0087fe410f95fc505722f1e60260049a54aaa59b763f429/blob new file mode 100644 index 0000000000000000000000000000000000000000..414912b74a4f538b14a5cd7ae103fc60c4edf0f8 --- /dev/null +++ b/shared/package-files/76/767b5b677853b7cdc0087fe410f95fc505722f1e60260049a54aaa59b763f429/blob @@ -0,0 +1,1125 @@ +"""A simple configuration system.""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import argparse +import copy +import json +import os +import re +import sys +import typing as t +import warnings + +from traitlets.traitlets import Any, Container, Dict, HasTraits, List, Undefined + +from ..utils import cast_unicode, filefind + + +# ----------------------------------------------------------------------------- +# Exceptions +# ----------------------------------------------------------------------------- + + +class ConfigError(Exception): + pass + + +class ConfigLoaderError(ConfigError): + pass + + +class ConfigFileNotFound(ConfigError): # noqa + pass + + +class ArgumentError(ConfigLoaderError): + pass + + +# ----------------------------------------------------------------------------- +# Argparse fix +# ----------------------------------------------------------------------------- + +# Unfortunately argparse by default prints help messages to stderr instead of +# stdout. This makes it annoying to capture long help screens at the command +# line, since one must know how to pipe stderr, which many users don't know how +# to do. So we override the print_help method with one that defaults to +# stdout and use our class instead. + + +class _Sentinel: + def __repr__(self): + return "" + + def __str__(self): + return "" + + +_deprecated = _Sentinel() + + +class ArgumentParser(argparse.ArgumentParser): + """Simple argparse subclass that prints help to stdout by default.""" + + def print_help(self, file=None): + if file is None: + file = sys.stdout + return super().print_help(file) + + print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__ + + +# ----------------------------------------------------------------------------- +# Config class for holding config information +# ----------------------------------------------------------------------------- + + +def execfile(fname, glob): + with open(fname, "rb") as f: + exec(compile(f.read(), fname, "exec"), glob, glob) # noqa + + +class LazyConfigValue(HasTraits): + """Proxy object for exposing methods on configurable containers + + These methods allow appending/extending/updating + to add to non-empty defaults instead of clobbering them. + + Exposes: + + - append, extend, insert on lists + - update on dicts + - update, add on sets + """ + + _value = None + + # list methods + _extend = List() + _prepend = List() + _inserts = List() + + def append(self, obj): + """Append an item to a List""" + self._extend.append(obj) + + def extend(self, other): + """Extend a list""" + self._extend.extend(other) + + def prepend(self, other): + """like list.extend, but for the front""" + self._prepend[:0] = other + + def merge_into(self, other): + """ + Merge with another earlier LazyConfigValue or an earlier container. + This is useful when having global system-wide configuration files. + + Self is expected to have higher precedence. + + Parameters + ---------- + other : LazyConfigValue or container + + Returns + ------- + LazyConfigValue + if ``other`` is also lazy, a reified container otherwise. + """ + if isinstance(other, LazyConfigValue): + other._extend.extend(self._extend) + self._extend = other._extend + + self._prepend.extend(other._prepend) + + other._inserts.extend(self._inserts) + self._inserts = other._inserts + + if self._update: + other.update(self._update) + self._update = other._update + return self + else: + # other is a container, reify now. + return self.get_value(other) + + def insert(self, index, other): + if not isinstance(index, int): + raise TypeError("An integer is required") + self._inserts.append((index, other)) + + # dict methods + # update is used for both dict and set + _update = Any() + + def update(self, other): + """Update either a set or dict""" + if self._update is None: + if isinstance(other, dict): + self._update = {} + else: + self._update = set() + self._update.update(other) + + # set methods + def add(self, obj): + """Add an item to a set""" + self.update({obj}) + + def get_value(self, initial): + """construct the value from the initial one + + after applying any insert / extend / update changes + """ + if self._value is not None: + return self._value + value = copy.deepcopy(initial) + if isinstance(value, list): + for idx, obj in self._inserts: + value.insert(idx, obj) + value[:0] = self._prepend + value.extend(self._extend) + + elif isinstance(value, dict): + if self._update: + value.update(self._update) + elif isinstance(value, set): + if self._update: + value.update(self._update) + self._value = value + return value + + def to_dict(self): + """return JSONable dict form of my data + + Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples. + """ + d = {} + if self._update: + d["update"] = self._update + if self._extend: + d["extend"] = self._extend + if self._prepend: + d["prepend"] = self._prepend + elif self._inserts: + d["inserts"] = self._inserts + return d + + def __repr__(self): + if self._value is not None: + return f"<{self.__class__.__name__} value={self._value!r}>" + else: + return f"<{self.__class__.__name__} {self.to_dict()!r}>" + + +def _is_section_key(key): + """Is a Config key a section name (does it start with a capital)?""" + if key and key[0].upper() == key[0] and not key.startswith("_"): + return True + else: + return False + + +class Config(dict): # type:ignore[type-arg] + """An attribute-based dict that can do smart merges. + + Accessing a field on a config object for the first time populates the key + with either a nested Config object for keys starting with capitals + or :class:`.LazyConfigValue` for lowercase keys, + allowing quick assignments such as:: + + c = Config() + c.Class.int_trait = 5 + c.Class.list_trait.append("x") + + """ + + def __init__(self, *args, **kwds): + dict.__init__(self, *args, **kwds) + self._ensure_subconfig() + + def _ensure_subconfig(self): + """ensure that sub-dicts that should be Config objects are + + casts dicts that are under section keys to Config objects, + which is necessary for constructing Config objects from dict literals. + """ + for key in self: + obj = self[key] + if _is_section_key(key) and isinstance(obj, dict) and not isinstance(obj, Config): + setattr(self, key, Config(obj)) + + def _merge(self, other): + """deprecated alias, use Config.merge()""" + self.merge(other) + + def merge(self, other): + """merge another config object into this one""" + to_update = {} + for k, v in other.items(): + if k not in self: + to_update[k] = v + else: # I have this key + if isinstance(v, Config) and isinstance(self[k], Config): + # Recursively merge common sub Configs + self[k].merge(v) + elif isinstance(v, LazyConfigValue): + self[k] = v.merge_into(self[k]) + else: + # Plain updates for non-Configs + to_update[k] = v + + self.update(to_update) + + def collisions(self, other: "Config") -> t.Dict[str, t.Any]: + """Check for collisions between two config objects. + + Returns a dict of the form {"Class": {"trait": "collision message"}}`, + indicating which values have been ignored. + + An empty dict indicates no collisions. + """ + collisions: t.Dict[str, t.Any] = {} + for section in self: + if section not in other: + continue + mine = self[section] + theirs = other[section] + for key in mine: + if key in theirs and mine[key] != theirs[key]: + collisions.setdefault(section, {}) + collisions[section][key] = f"{mine[key]!r} ignored, using {theirs[key]!r}" + return collisions + + def __contains__(self, key): + # allow nested contains of the form `"Section.key" in config` + if "." in key: + first, remainder = key.split(".", 1) + if first not in self: + return False + return remainder in self[first] + + return super().__contains__(key) + + # .has_key is deprecated for dictionaries. + has_key = __contains__ + + def _has_section(self, key): + return _is_section_key(key) and key in self + + def copy(self): + return type(self)(dict.copy(self)) + + def __copy__(self): + return self.copy() + + def __deepcopy__(self, memo): + new_config = type(self)() + for key, value in self.items(): + if isinstance(value, (Config, LazyConfigValue)): + # deep copy config objects + value = copy.deepcopy(value, memo) + elif type(value) in {dict, list, set, tuple}: + # shallow copy plain container traits + value = copy.copy(value) + new_config[key] = value + return new_config + + def __getitem__(self, key): + try: + return dict.__getitem__(self, key) + except KeyError: + if _is_section_key(key): + c = Config() + dict.__setitem__(self, key, c) + return c + elif not key.startswith("_"): + # undefined, create lazy value, used for container methods + v = LazyConfigValue() + dict.__setitem__(self, key, v) + return v + else: + raise KeyError + + def __setitem__(self, key, value): + if _is_section_key(key): + if not isinstance(value, Config): + raise ValueError( + "values whose keys begin with an uppercase " + "char must be Config instances: %r, %r" % (key, value) + ) + dict.__setitem__(self, key, value) + + def __getattr__(self, key): + if key.startswith("__"): + return dict.__getattr__(self, key) # type:ignore[attr-defined] + try: + return self.__getitem__(key) + except KeyError as e: + raise AttributeError(e) from e + + def __setattr__(self, key, value): + if key.startswith("__"): + return dict.__setattr__(self, key, value) + try: + self.__setitem__(key, value) + except KeyError as e: + raise AttributeError(e) from e + + def __delattr__(self, key): + if key.startswith("__"): + return dict.__delattr__(self, key) + try: + dict.__delitem__(self, key) + except KeyError as e: + raise AttributeError(e) from e + + +class DeferredConfig: + """Class for deferred-evaluation of config from CLI""" + + pass + + def get_value(self, trait): + raise NotImplementedError("Implement in subclasses") + + def _super_repr(self): + # explicitly call super on direct parent + return super(self.__class__, self).__repr__() + + +class DeferredConfigString(str, DeferredConfig): + """Config value for loading config from a string + + Interpretation is deferred until it is loaded into the trait. + + Subclass of str for backward compatibility. + + This class is only used for values that are not listed + in the configurable classes. + + When config is loaded, `trait.from_string` will be used. + + If an error is raised in `.from_string`, + the original string is returned. + + .. versionadded:: 5.0 + """ + + def get_value(self, trait): + """Get the value stored in this string""" + s = str(self) + try: + return trait.from_string(s) + except Exception: + # exception casting from string, + # let the original string lie. + # this will raise a more informative error when config is loaded. + return s + + def __repr__(self): + return f"{self.__class__.__name__}({self._super_repr()})" + + +class DeferredConfigList(list, DeferredConfig): # type:ignore[type-arg] + """Config value for loading config from a list of strings + + Interpretation is deferred until it is loaded into the trait. + + This class is only used for values that are not listed + in the configurable classes. + + When config is loaded, `trait.from_string_list` will be used. + + If an error is raised in `.from_string_list`, + the original string list is returned. + + .. versionadded:: 5.0 + """ + + def get_value(self, trait): + """Get the value stored in this string""" + if hasattr(trait, "from_string_list"): + src = list(self) + cast = trait.from_string_list + else: + # only allow one item + if len(self) > 1: + raise ValueError( + f"{trait.name} only accepts one value, got {len(self)}: {list(self)}" + ) + src = self[0] + cast = trait.from_string + + try: + return cast(src) + except Exception: + # exception casting from string, + # let the original value lie. + # this will raise a more informative error when config is loaded. + return src + + def __repr__(self): + return f"{self.__class__.__name__}({self._super_repr()})" + + +# ----------------------------------------------------------------------------- +# Config loading classes +# ----------------------------------------------------------------------------- + + +class ConfigLoader: + """A object for loading configurations from just about anywhere. + + The resulting configuration is packaged as a :class:`Config`. + + Notes + ----- + A :class:`ConfigLoader` does one thing: load a config from a source + (file, command line arguments) and returns the data as a :class:`Config` object. + There are lots of things that :class:`ConfigLoader` does not do. It does + not implement complex logic for finding config files. It does not handle + default values or merge multiple configs. These things need to be + handled elsewhere. + """ + + def _log_default(self): + from traitlets.log import get_logger + + return get_logger() + + def __init__(self, log=None): + """A base class for config loaders. + + log : instance of :class:`logging.Logger` to use. + By default logger of :meth:`traitlets.config.application.Application.instance()` + will be used + + Examples + -------- + >>> cl = ConfigLoader() + >>> config = cl.load_config() + >>> config + {} + """ + self.clear() + if log is None: + self.log = self._log_default() + self.log.debug("Using default logger") + else: + self.log = log + + def clear(self): + self.config = Config() + + def load_config(self): + """Load a config from somewhere, return a :class:`Config` instance. + + Usually, this will cause self.config to be set and then returned. + However, in most cases, :meth:`ConfigLoader.clear` should be called + to erase any previous state. + """ + self.clear() + return self.config + + +class FileConfigLoader(ConfigLoader): + """A base class for file based configurations. + + As we add more file based config loaders, the common logic should go + here. + """ + + def __init__(self, filename, path=None, **kw): + """Build a config loader for a filename and path. + + Parameters + ---------- + filename : str + The file name of the config file. + path : str, list, tuple + The path to search for the config file on, or a sequence of + paths to try in order. + """ + super().__init__(**kw) + self.filename = filename + self.path = path + self.full_filename = "" + + def _find_file(self): + """Try to find the file by searching the paths.""" + self.full_filename = filefind(self.filename, self.path) + + +class JSONFileConfigLoader(FileConfigLoader): + """A JSON file loader for config + + Can also act as a context manager that rewrite the configuration file to disk on exit. + + Example:: + + with JSONFileConfigLoader('myapp.json','/home/jupyter/configurations/') as c: + c.MyNewConfigurable.new_value = 'Updated' + + """ + + def load_config(self): + """Load the config from a file and return it as a Config object.""" + self.clear() + try: + self._find_file() + except OSError as e: + raise ConfigFileNotFound(str(e)) from e + dct = self._read_file_as_dict() + self.config = self._convert_to_config(dct) + return self.config + + def _read_file_as_dict(self): + with open(self.full_filename) as f: + return json.load(f) + + def _convert_to_config(self, dictionary): + if "version" in dictionary: + version = dictionary.pop("version") + else: + version = 1 + + if version == 1: + return Config(dictionary) + else: + raise ValueError(f"Unknown version of JSON config file: {version}") + + def __enter__(self): + self.load_config() + return self.config + + def __exit__(self, exc_type, exc_value, traceback): + """ + Exit the context manager but do not handle any errors. + + In case of any error, we do not want to write the potentially broken + configuration to disk. + """ + self.config.version = 1 + json_config = json.dumps(self.config, indent=2) + with open(self.full_filename, "w") as f: + f.write(json_config) + + +class PyFileConfigLoader(FileConfigLoader): + """A config loader for pure python files. + + This is responsible for locating a Python config file by filename and + path, then executing it to construct a Config object. + """ + + def load_config(self): + """Load the config from a file and return it as a Config object.""" + self.clear() + try: + self._find_file() + except OSError as e: + raise ConfigFileNotFound(str(e)) from e + self._read_file_as_dict() + return self.config + + def load_subconfig(self, fname, path=None): + """Injected into config file namespace as load_subconfig""" + if path is None: + path = self.path + + loader = self.__class__(fname, path) + try: + sub_config = loader.load_config() + except ConfigFileNotFound: + # Pass silently if the sub config is not there, + # treat it as an empty config file. + pass + else: + self.config.merge(sub_config) + + def _read_file_as_dict(self): + """Load the config file into self.config, with recursive loading.""" + + def get_config(): + """Unnecessary now, but a deprecation warning is more trouble than it's worth.""" + return self.config + + namespace = dict( + c=self.config, + load_subconfig=self.load_subconfig, + get_config=get_config, + __file__=self.full_filename, + ) + conf_filename = self.full_filename + with open(conf_filename, "rb") as f: + exec(compile(f.read(), conf_filename, "exec"), namespace, namespace) # noqa + + +class CommandLineConfigLoader(ConfigLoader): + """A config loader for command line arguments. + + As we add more command line based loaders, the common logic should go + here. + """ + + def _exec_config_str(self, lhs, rhs, trait=None): + """execute self.config. = + + * expands ~ with expanduser + * interprets value with trait if available + """ + value = rhs + if isinstance(value, DeferredConfig): + if trait: + # trait available, reify config immediately + value = value.get_value(trait) + elif isinstance(rhs, DeferredConfigList) and len(rhs) == 1: + # single item, make it a deferred str + value = DeferredConfigString(os.path.expanduser(rhs[0])) + else: + if trait: + value = trait.from_string(value) + else: + value = DeferredConfigString(value) + + *path, key = lhs.split(".") + section = self.config + for part in path: + section = section[part] + section[key] = value + return + + def _load_flag(self, cfg): + """update self.config from a flag, which can be a dict or Config""" + if isinstance(cfg, (dict, Config)): + # don't clobber whole config sections, update + # each section from config: + for sec, c in cfg.items(): + self.config[sec].update(c) + else: + raise TypeError("Invalid flag: %r" % cfg) + + +# match --Class.trait keys for argparse +# matches: +# --Class.trait +# --x +# -x + +class_trait_opt_pattern = re.compile(r"^\-?\-[A-Za-z][\w]*(\.[\w]+)*$") + +_DOT_REPLACEMENT = "__DOT__" +_DASH_REPLACEMENT = "__DASH__" + + +class _KVAction(argparse.Action): + """Custom argparse action for handling --Class.trait=x + + Always + """ + + def __call__(self, parser, namespace, values, option_string=None): + if isinstance(values, str): + values = [values] + values = ["-" if v is _DASH_REPLACEMENT else v for v in values] + items = getattr(namespace, self.dest, None) + if items is None: + items = DeferredConfigList() + else: + items = DeferredConfigList(items) + items.extend(values) + setattr(namespace, self.dest, items) + + +class _DefaultOptionDict(dict): # type:ignore[type-arg] + """Like the default options dict + + but acts as if all --Class.trait options are predefined + """ + + def _add_kv_action(self, key): + self[key] = _KVAction( + option_strings=[key], + dest=key.lstrip("-").replace(".", _DOT_REPLACEMENT), + # use metavar for display purposes + metavar=key.lstrip("-"), + ) + + def __contains__(self, key): + if "=" in key: + return False + if super().__contains__(key): + return True + + if key.startswith("-") and class_trait_opt_pattern.match(key): + self._add_kv_action(key) + return True + return False + + def __getitem__(self, key): + if key in self: + return super().__getitem__(key) + else: + raise KeyError(key) + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + +class _KVArgParser(argparse.ArgumentParser): + """subclass of ArgumentParser where any --Class.trait option is implicitly defined""" + + def parse_known_args(self, args=None, namespace=None): + # must be done immediately prior to parsing because if we do it in init, + # registration of explicit actions via parser.add_option will fail during setup + for container in (self, self._optionals): + container._option_string_actions = _DefaultOptionDict(container._option_string_actions) + return super().parse_known_args(args, namespace) + + +class ArgParseConfigLoader(CommandLineConfigLoader): + """A loader that uses the argparse module to load from the command line.""" + + parser_class = ArgumentParser + Flags = t.Union[str, t.Tuple[str, ...]] + + def __init__( + self, + argv: t.Optional[t.List[str]] = None, + aliases: t.Optional[t.Dict[Flags, str]] = None, + flags: t.Optional[t.Dict[Flags, str]] = None, + log: t.Any = None, + classes: t.Optional[t.List[t.Type[t.Any]]] = None, + *parser_args: t.Any, + **parser_kw: t.Any, + ) -> None: + """Create a config loader for use with argparse. + + Parameters + ---------- + classes : optional, list + The classes to scan for *container* config-traits and decide + for their "multiplicity" when adding them as *argparse* arguments. + argv : optional, list + If given, used to read command-line arguments from, otherwise + sys.argv[1:] is used. + *parser_args : tuple + A tuple of positional arguments that will be passed to the + constructor of :class:`argparse.ArgumentParser`. + **parser_kw : dict + A tuple of keyword arguments that will be passed to the + constructor of :class:`argparse.ArgumentParser`. + aliases : dict of str to str + Dict of aliases to full traitlets names for CLI parsing + flags : dict of str to str + Dict of flags to full traitlets names for CLI parsing + log + Passed to `ConfigLoader` + + Returns + ------- + config : Config + The resulting Config object. + """ + classes = classes or [] + super(CommandLineConfigLoader, self).__init__(log=log) + self.clear() + if argv is None: + argv = sys.argv[1:] + self.argv = argv + self.aliases = aliases or {} + self.flags = flags or {} + self.classes = classes + + self.parser_args = parser_args + self.version = parser_kw.pop("version", None) + kwargs = dict(argument_default=argparse.SUPPRESS) + kwargs.update(parser_kw) + self.parser_kw = kwargs + + def load_config(self, argv=None, aliases=None, flags=_deprecated, classes=None): + """Parse command line arguments and return as a Config object. + + Parameters + ---------- + argv : optional, list + If given, a list with the structure of sys.argv[1:] to parse + arguments from. If not given, the instance's self.argv attribute + (given at construction time) is used. + flags + Deprecated in traitlets 5.0, instanciate the config loader with the flags. + + """ + + if flags is not _deprecated: + warnings.warn( + "The `flag` argument to load_config is deprecated since Traitlets " + f"5.0 and will be ignored, pass flags the `{type(self)}` constructor.", + DeprecationWarning, + stacklevel=2, + ) + + self.clear() + if argv is None: + argv = self.argv + if aliases is not None: + self.aliases = aliases + if classes is not None: + self.classes = classes + self._create_parser() + self._parse_args(argv) + self._convert_to_config() + return self.config + + def get_extra_args(self): + if hasattr(self, "extra_args"): + return self.extra_args + else: + return [] + + def _create_parser(self): + self.parser = self.parser_class( + *self.parser_args, **self.parser_kw # type:ignore[arg-type] + ) + self._add_arguments(self.aliases, self.flags, self.classes) + + def _add_arguments(self, aliases, flags, classes): + raise NotImplementedError("subclasses must implement _add_arguments") + + def _parse_args(self, args): + """self.parser->self.parsed_data""" + uargs = [cast_unicode(a) for a in args] + + unpacked_aliases: t.Dict[str, str] = {} + if self.aliases: + unpacked_aliases = {} + for alias, alias_target in self.aliases.items(): + if alias in self.flags: + continue + if not isinstance(alias, tuple): + alias = (alias,) + for al in alias: + if len(al) == 1: + unpacked_aliases["-" + al] = "--" + alias_target + unpacked_aliases["--" + al] = "--" + alias_target + + def _replace(arg): + if arg == "-": + return _DASH_REPLACEMENT + for k, v in unpacked_aliases.items(): + if arg == k: + return v + if arg.startswith(k + "="): + return v + "=" + arg[len(k) + 1 :] + return arg + + if "--" in uargs: + idx = uargs.index("--") + extra_args = uargs[idx + 1 :] + to_parse = uargs[:idx] + else: + extra_args = [] + to_parse = uargs + to_parse = [_replace(a) for a in to_parse] + + self.parsed_data = self.parser.parse_args(to_parse) + self.extra_args = extra_args + + def _convert_to_config(self): + """self.parsed_data->self.config""" + for k, v in vars(self.parsed_data).items(): + *path, key = k.split(".") + section = self.config + for p in path: + section = section[p] + setattr(section, key, v) + + +class _FlagAction(argparse.Action): + """ArgParse action to handle a flag""" + + def __init__(self, *args, **kwargs): + self.flag = kwargs.pop("flag") + self.alias = kwargs.pop("alias", None) + kwargs["const"] = Undefined + if not self.alias: + kwargs["nargs"] = 0 + super().__init__(*args, **kwargs) + + def __call__(self, parser, namespace, values, option_string=None): + if self.nargs == 0 or values is Undefined: + if not hasattr(namespace, "_flags"): + namespace._flags = [] + namespace._flags.append(self.flag) + else: + setattr(namespace, self.alias, values) + + +class KVArgParseConfigLoader(ArgParseConfigLoader): + """A config loader that loads aliases and flags with argparse, + + as well as arbitrary --Class.trait value + """ + + parser_class = _KVArgParser # type:ignore[assignment] + + def _add_arguments(self, aliases, flags, classes): + alias_flags: t.Dict[str, t.Any] = {} + argparse_kwds: t.Dict[str, t.Any] + paa = self.parser.add_argument + self.parser.set_defaults(_flags=[]) + paa("extra_args", nargs="*") + + # An index of all container traits collected:: + # + # { : (, ) } + # + # Used to add the correct type into the `config` tree. + # Used also for aliases, not to re-collect them. + self.argparse_traits = argparse_traits = {} + for cls in classes: + for traitname, trait in cls.class_traits(config=True).items(): + argname = f"{cls.__name__}.{traitname}" + argparse_kwds = {"type": str} + if isinstance(trait, (Container, Dict)): + multiplicity = trait.metadata.get("multiplicity", "append") + if multiplicity == "append": + argparse_kwds["action"] = multiplicity + else: + argparse_kwds["nargs"] = multiplicity + argparse_traits[argname] = (trait, argparse_kwds) + + for keys, (value, _) in flags.items(): + if not isinstance(keys, tuple): + keys = (keys,) + for key in keys: + if key in aliases: + alias_flags[aliases[key]] = value + continue + keys = ("-" + key, "--" + key) if len(key) == 1 else ("--" + key,) + paa(*keys, action=_FlagAction, flag=value) + + for keys, traitname in aliases.items(): + if not isinstance(keys, tuple): + keys = (keys,) + + for key in keys: + argparse_kwds = { + "type": str, + "dest": traitname.replace(".", _DOT_REPLACEMENT), + "metavar": traitname, + } + if traitname in argparse_traits: + argparse_kwds.update(argparse_traits[traitname][1]) + if "action" in argparse_kwds and traitname in alias_flags: + # flag sets 'action', so can't have flag & alias with custom action + # on the same name + raise ArgumentError( + "The alias `%s` for the 'append' sequence " + "config-trait `%s` cannot be also a flag!'" % (key, traitname) + ) + if traitname in alias_flags: + # alias and flag. + # when called with 0 args: flag + # when called with >= 1: alias + argparse_kwds.setdefault("nargs", "?") + argparse_kwds["action"] = _FlagAction + argparse_kwds["flag"] = alias_flags[traitname] + argparse_kwds["alias"] = traitname + keys = ("-" + key, "--" + key) if len(key) == 1 else ("--" + key,) + paa(*keys, **argparse_kwds) + + def _convert_to_config(self): + """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" + extra_args = self.extra_args + + for lhs, rhs in vars(self.parsed_data).items(): + if lhs == "extra_args": + self.extra_args = ["-" if a == _DASH_REPLACEMENT else a for a in rhs] + extra_args + continue + elif lhs == "_flags": + # _flags will be handled later + continue + + lhs = lhs.replace(_DOT_REPLACEMENT, ".") + if "." not in lhs: + self._handle_unrecognized_alias(lhs) + trait = None + + if isinstance(rhs, list): + rhs = DeferredConfigList(rhs) + elif isinstance(rhs, str): + rhs = DeferredConfigString(rhs) + + trait = self.argparse_traits.get(lhs) + if trait: + trait = trait[0] + + # eval the KV assignment + try: + self._exec_config_str(lhs, rhs, trait) + except Exception as e: + # cast deferred to nicer repr for the error + # DeferredList->list, etc + if isinstance(rhs, DeferredConfig): + rhs = rhs._super_repr() + raise ArgumentError(f"Error loading argument {lhs}={rhs}, {e}") from e + + for subc in self.parsed_data._flags: + self._load_flag(subc) + + def _handle_unrecognized_alias(self, arg: str) -> None: + """Handling for unrecognized alias arguments + + Probably a mistyped alias. By default just log a warning, + but users can override this to raise an error instead, e.g. + self.parser.error("Unrecognized alias: '%s'" % arg) + """ + self.log.warning("Unrecognized alias: '%s', it will have no effect.", arg) + + +class KeyValueConfigLoader(KVArgParseConfigLoader): + """Deprecated in traitlets 5.0 + + Use KVArgParseConfigLoader + """ + + def __init__(self, *args, **kwargs): + warnings.warn( + "KeyValueConfigLoader is deprecated since Traitlets 5.0." + " Use KVArgParseConfigLoader instead.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) + + +def load_pyconfig_files(config_files, path): + """Load multiple Python config files, merging each of them in turn. + + Parameters + ---------- + config_files : list of str + List of config files names to load and merge into the config. + path : unicode + The full path to the location of the config files. + """ + config = Config() + for cf in config_files: + loader = PyFileConfigLoader(cf, path=path) + try: + next_config = loader.load_config() + except ConfigFileNotFound: + pass + except Exception: + raise + else: + config.merge(next_config) + return config diff --git a/shared/package-files/76/767b601ba41b949503e2a1a2e945c444d22ab13ea80db181f228c296bb61556c/blob b/shared/package-files/76/767b601ba41b949503e2a1a2e945c444d22ab13ea80db181f228c296bb61556c/blob new file mode 100644 index 0000000000000000000000000000000000000000..6455eb2bfe15cc23eb287f6e2d7daee104724ee5 --- /dev/null +++ b/shared/package-files/76/767b601ba41b949503e2a1a2e945c444d22ab13ea80db181f228c296bb61556c/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _copy_from_and_resize_out(const at::Tensor & self, const at::Tensor & dst, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/76/767c772df5fec424631e48baa13cfa55498f4d7be9b41d1071b34bf52cc28fa8/blob b/shared/package-files/76/767c772df5fec424631e48baa13cfa55498f4d7be9b41d1071b34bf52cc28fa8/blob new file mode 100644 index 0000000000000000000000000000000000000000..9e0cd1eaa4177c1dff1423bca31037e3cc96a112 --- /dev/null +++ b/shared/package-files/76/767c772df5fec424631e48baa13cfa55498f4d7be9b41d1071b34bf52cc28fa8/blob @@ -0,0 +1,2444 @@ +Metadata-Version: 2.4 +Name: fonttools +Version: 4.65.0 +Summary: Tools to manipulate font files +Home-page: http://github.com/fonttools/fonttools +Author: Just van Rossum +Author-email: just@letterror.com +Maintainer: Behdad Esfahbod +Maintainer-email: behdad@behdad.org +License: MIT +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: Other Environment +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: End Users/Desktop +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Text Processing :: Fonts +Classifier: Topic :: Multimedia :: Graphics +Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.external +Provides-Extra: ufo +Provides-Extra: lxml +Requires-Dist: lxml>=4.0; extra == "lxml" +Provides-Extra: woff +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "woff" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "woff" +Requires-Dist: zopfli>=0.1.4; extra == "woff" +Provides-Extra: unicode +Requires-Dist: unicodedata2>=17.0.0; python_version <= "3.14" and extra == "unicode" +Provides-Extra: graphite +Requires-Dist: lz4>=1.7.4.2; extra == "graphite" +Provides-Extra: interpolatable +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "interpolatable" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "interpolatable" +Requires-Dist: pycairo; extra == "interpolatable" +Provides-Extra: plot +Requires-Dist: matplotlib; extra == "plot" +Provides-Extra: symfont +Requires-Dist: sympy; extra == "symfont" +Provides-Extra: type1 +Requires-Dist: xattr; sys_platform == "darwin" and extra == "type1" +Provides-Extra: pathops +Requires-Dist: skia-pathops>=0.5.0; extra == "pathops" +Provides-Extra: repacker +Requires-Dist: uharfbuzz>=0.45.0; extra == "repacker" +Provides-Extra: all +Requires-Dist: lxml>=4.0; extra == "all" +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "all" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "all" +Requires-Dist: zopfli>=0.1.4; extra == "all" +Requires-Dist: unicodedata2>=17.0.0; python_version <= "3.14" and extra == "all" +Requires-Dist: lz4>=1.7.4.2; extra == "all" +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "all" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "all" +Requires-Dist: pycairo; extra == "all" +Requires-Dist: matplotlib; extra == "all" +Requires-Dist: sympy; extra == "all" +Requires-Dist: xattr; sys_platform == "darwin" and extra == "all" +Requires-Dist: skia-pathops>=0.5.0; extra == "all" +Requires-Dist: uharfbuzz>=0.45.0; extra == "all" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: platform +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +|CI Build Status| |Coverage Status| |PyPI| |Gitter Chat| + +What is this? +~~~~~~~~~~~~~ + +| fontTools is a library for manipulating fonts, written in Python. The + project includes the TTX tool, that can convert TrueType and OpenType + fonts to and from an XML text format, which is also called TTX. It + supports TrueType, OpenType, AFM and to an extent Type 1 and some + Mac-specific formats. The project has an `MIT open-source + license `__. +| Among other things this means you can use it free of charge. + +`User documentation `_ and +`developer documentation `_ +are available at `Read the Docs `_. + +Installation +~~~~~~~~~~~~ + +FontTools requires `Python `__ 3.10 +or later. We try to follow the same schedule of minimum Python version support as +NumPy (see `NEP 29 `__). + +The package is listed in the Python Package Index (PyPI), so you can +install it with `pip `__: + +.. code:: sh + + pip install fonttools + +If you would like to contribute to its development, you can clone the +repository from GitHub, install the package in 'editable' mode and +modify the source code in place. We recommend creating a virtual +environment, using `virtualenv `__ or +Python 3 `venv `__ module. + +.. code:: sh + + # download the source code to 'fonttools' folder + git clone https://github.com/fonttools/fonttools.git + cd fonttools + + # create new virtual environment called e.g. 'fonttools-venv', or anything you like + python -m virtualenv fonttools-venv + + # source the `activate` shell script to enter the environment (Unix-like); to exit, just type `deactivate` + . fonttools-venv/bin/activate + + # to activate the virtual environment in Windows `cmd.exe`, do + fonttools-venv\Scripts\activate.bat + + # install in 'editable' mode + pip install -e . + +Optional Requirements +--------------------- + +The ``fontTools`` package currently has no (required) external dependencies +besides the modules included in the Python Standard Library. +However, a few extra dependencies are required by some of its modules, which +are needed to unlock optional features. +The ``fonttools`` PyPI distribution also supports so-called "extras", i.e. a +set of keywords that describe a group of additional dependencies, which can be +used when installing via pip, or when specifying a requirement. +For example: + +.. code:: sh + + pip install fonttools[ufo,lxml,woff,unicode] + +This command will install fonttools, as well as the optional dependencies that +are required to unlock the extra features named "ufo", etc. + +- ``Lib/fontTools/misc/etree.py`` + + The module exports a ElementTree-like API for reading/writing XML files, and + allows to use as the backend either the built-in ``xml.etree`` module or + `lxml `__. The latter is preferred whenever present, + as it is generally faster and more secure. + + *Extra:* ``lxml`` + +- ``Lib/fontTools/ttLib/woff2.py`` + + Module to compress/decompress WOFF 2.0 web fonts; it requires: + + * `brotli `__: Python bindings of + the Brotli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/ttLib/sfnt.py`` + + To better compress WOFF 1.0 web fonts, the following module can be used + instead of the built-in ``zlib`` library: + + * `zopfli `__: Python bindings of + the Zopfli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/unicode.py`` + + To display the Unicode character names when dumping the ``cmap`` table + with ``ttx`` we use the ``unicodedata`` module in the Standard Library. + The version included in there varies between different Python versions. + To use the latest available data, you can install: + + * `unicodedata2 `__: + ``unicodedata`` backport for Python 3.x updated to the latest Unicode + version 17.0. + + *Extra:* ``unicode`` + +- ``Lib/fontTools/varLib/interpolatable.py`` + + Module for finding wrong contour/component order between different masters. + It requires one of the following packages in order to solve the so-called + "minimum weight perfect matching problem in bipartite graphs", or + the Assignment problem: + + * `scipy `__: the Scientific Library + for Python, which internally uses `NumPy `__ + arrays and hence is very fast; + * `munkres `__: a pure-Python + module that implements the Hungarian or Kuhn-Munkres algorithm. Slower than + SciPy, but useful for minimalistic systems where adding SciPy is undesirable. + + This ensures both performance (via SciPy) and minimal footprint (via Munkres) + are possible. + + To plot the results to a PDF or HTML format, you also need to install: + + * `pycairo `__: Python bindings for the + Cairo graphics library. Note that wheels are currently only available for + Windows, for other platforms see pycairo's `installation instructions + `__. + + *Extra:* ``interpolatable`` + +- ``Lib/fontTools/varLib/plot.py`` + + Module for visualizing DesignSpaceDocument and resulting VariationModel. + + * `matplotlib `__: 2D plotting library. + + *Extra:* ``plot`` + +- ``Lib/fontTools/misc/symfont.py`` + + Advanced module for symbolic font statistics analysis; it requires: + + * `sympy `__: the Python library for + symbolic mathematics. + + *Extra:* ``symfont`` + +- ``Lib/fontTools/t1Lib.py`` + + To get the file creator and type of Macintosh PostScript Type 1 fonts + on Python 3 you need to install the following module, as the old ``MacOS`` + module is no longer included in Mac Python: + + * `xattr `__: Python wrapper for + extended filesystem attributes (macOS platform only). + + *Extra:* ``type1`` + +- ``Lib/fontTools/ttLib/removeOverlaps.py`` + + Simplify TrueType glyphs by merging overlapping contours and components. + + * `skia-pathops `__: Python + bindings for the Skia library's PathOps module, performing boolean + operations on paths (union, intersection, etc.). + + *Extra:* ``pathops`` + +- ``Lib/fontTools/ufoLib`` + + Package for reading and writing UFO source files; if available, it will use: + + * `fs `__: (aka ``pyfilesystem2``) filesystem abstraction layer + + for reading and writing UFOs to the local filesystem or zip files (.ufoz), instead of + the built-in ``fontTools.misc.filesystem`` package. + The reader and writer classes can in theory also accept any object compatible the + ``fs.base.FS`` interface, although not all have been tested. + +- ``Lib/fontTools/pens/cocoaPen.py`` and ``Lib/fontTools/pens/quartzPen.py`` + + Pens for drawing glyphs with Cocoa ``NSBezierPath`` or ``CGPath`` require: + + * `PyObjC `__: the bridge between + Python and the Objective-C runtime (macOS platform only). + +- ``Lib/fontTools/pens/qtPen.py`` + + Pen for drawing glyphs with Qt's ``QPainterPath``, requires: + + * `PyQt5 `__: Python bindings for + the Qt cross platform UI and application toolkit. + +- ``Lib/fontTools/pens/reportLabPen.py`` + + Pen to drawing glyphs as PNG images, requires: + + * `reportlab `__: Python toolkit + for generating PDFs and graphics. + +- ``Lib/fontTools/pens/freetypePen.py`` + + Pen to drawing glyphs with FreeType as raster images, requires: + + * `freetype-py `__: Python binding + for the FreeType library. + +- ``Lib/fontTools/ttLib/tables/otBase.py`` + + Use the Harfbuzz library to serialize GPOS/GSUB using ``hb_repack`` method, requires: + + * `uharfbuzz `__: Streamlined Cython + bindings for the harfbuzz shaping engine + + *Extra:* ``repacker`` + +How to make a new release +~~~~~~~~~~~~~~~~~~~~~~~~~ + +1) Update ``NEWS.rst`` with all the changes since the last release. Write a + changelog entry for each PR, with one or two short sentences summarizing it, + as well as links to the PR and relevant issues addressed by the PR. Do not + put a new title, the next command will do it for you. +2) Use semantic versioning to decide whether the new release will be a 'major', + 'minor' or 'patch' release. It's usually one of the latter two, depending on + whether new backward compatible APIs were added, or simply some bugs were fixed. +3) From inside a venv, first do ``pip install -r dev-requirements.txt``, then run + the ``python setup.py release`` command from the tip of the ``main`` branch. + By default this bumps the third or 'patch' digit only, unless you pass ``--major`` + or ``--minor`` to bump respectively the first or second digit. + This bumps the package version string, extracts the changes since the latest + version from ``NEWS.rst``, and uses that text to create an annotated git tag + (or a signed git tag if you pass the ``--sign`` option and your git and Github + account are configured for `signing commits `__ + using a GPG key). + It also commits an additional version bump which opens the main branch for + the subsequent developmental cycle +4) Push both the tag and commit to the upstream repository, by running the command + ``git push --follow-tags``. Note: it may push other local tags as well, be + careful. +5) Let the CI build the wheel and source distribution packages and verify both + get uploaded to the Python Package Index (PyPI). +6) [Optional] Go to fonttools `Github Releases `__ + page and create a new release, copy-pasting the content of the git tag + message. This way, the release notes are nicely formatted as markdown, and + users watching the repo will get an email notification. One day we shall + automate that too. + + +Acknowledgments +~~~~~~~~~~~~~~~~ + +In alphabetical order: + +aschmitz, Olivier Berten, Samyak Bhuta, Erik van Blokland, Petr van Blokland, +Jelle Bosma, Sascha Brawer, Tom Byrer, Antonio Cavedoni, Frédéric Coiffier, +Vincent Connare, David Corbett, Simon Cozens, Dave Crossland, Simon Daniels, +Peter Dekkers, Behdad Esfahbod, Behnam Esfahbod, Hannes Famira, Sam Fishman, +Matt Fontaine, Takaaki Fuji, Rob Hagemans, Yannis Haralambous, Greg Hitchcock, +Jeremie Hornus, Khaled Hosny, John Hudson, Denis Moyogo Jacquerye, Jack Jansen, +Tom Kacvinsky, Jens Kutilek, Antoine Leca, Werner Lemberg, Tal Leming, Liang Hai, Peter +Lofting, Cosimo Lupo, Olli Meier, Masaya Nakamura, Dave Opstad, Laurence Penney, +Roozbeh Pournader, Garret Rieger, Read Roberts, Colin Rofls, Guido van Rossum, +Just van Rossum, Andreas Seidel, Georg Seifert, Chris Simpkins, Miguel Sousa, +Adam Twardoch, Adrien Tétar, Vitaly Volkov, Paul Wise. + +Copyrights +~~~~~~~~~~ + +| Copyright (c) 1999-2004 Just van Rossum, LettError + (just@letterror.com) +| See `LICENSE `__ for the full license. + +Copyright (c) 2000 BeOpen.com. All Rights Reserved. + +Copyright (c) 1995-2001 Corporation for National Research Initiatives. +All Rights Reserved. + +Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All +Rights Reserved. + +Have fun! + +.. |CI Build Status| image:: https://github.com/fonttools/fonttools/workflows/Test/badge.svg + :target: https://github.com/fonttools/fonttools/actions?query=workflow%3ATest +.. |Coverage Status| image:: https://codecov.io/gh/fonttools/fonttools/branch/main/graph/badge.svg + :target: https://codecov.io/gh/fonttools/fonttools +.. |PyPI| image:: https://img.shields.io/pypi/v/fonttools.svg + :target: https://pypi.org/project/FontTools +.. |Gitter Chat| image:: https://badges.gitter.im/fonttools-dev/Lobby.svg + :alt: Join the chat at https://gitter.im/fonttools-dev/Lobby + :target: https://gitter.im/fonttools-dev/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + +Changelog +~~~~~~~~~ + +4.65.0 (released 2026-09-10) +---------------------------- + +- [glyf] Add ``__iter__``, ``items`` and ``values`` methods to the ``glyf`` table + to make it more dict-like (#4156). +- [feaLib] Escape the anonymous block tag when scanning for its terminator, so tags + containing regex metacharacters are matched literally (#4167). +- [varLib] Strip directory components from ```` when + deriving the output filename in the ``varLib`` command line, so a designspace + cannot write outside the output directory (#4168). +- [feaLib] Fix tracking of the current script and language across redundant + ``script`` statements. Rules following a ``script`` statement that names the + first declared language system no longer end up under the ``DFLT`` script, and + a ``script`` statement naming the already-current script still narrows the + language systems and terminates the current lookup while leaving the + ``lookupflag`` alone, matching makeotf (#1824, #2522, #4169). +- [varLib.interpolatable] Escape glyph names in the HTML report (#4172). +- [otlLib] Fix overflow handling when building contextual lookups: offset overflows + now raise ``OTLOffsetOverflowError`` instead of ``AttributeError`` so another + contextual format can be tried (regression from #3439). When all formats + overflow, split the ruleset in halves until it fits (#4171). + +4.64.0 (released 2026-08-31) +---------------------------- + +- [feaLib] Fix name-table parsing for multibyte Mac encodings (#1196, #4092). +- [ttProgram] Also indent TrueType assembly following ``IDEF[ ]``, like function + definitions (#4093). +- [subset] Keep East Asian spacing ``palt`` by default (#4094). +- [subset] Bug fix for MATH table in which constructions for glyphs that are only + added during MATH closure were kept (#4096). +- [ufoLib] Make glyph-to-group construction accessible outside of lookup function + (#4102). +- [glyf] Use reverse glyph map for O(1) ``__setitem__`` membership (#4103). +- [ttLib] Fix ``fixLookupOverFlows()`` reporting success when it had not promoted + any lookup to Extension, masking unresolvable overflows. +- [ttLib] Add support for TrueType Collection version 2 (#4100). +- [ttLib] Pin a single head.modified timestamp across ``TTCollection.save`` (#4111). +- [ttLib] Give an actionable error when LookupList overflow is unrecoverable (#4109). +- [ttLib] Add support for the AAT bitmap tables ``bhed``, ``bdat``, ``bloc``, + variants of ``head``, ``EBDT``, ``EBLC`` used in legacy Apple bitmap-only fonts + (#4115). +- [ttLib] Check ``OS/2`` fsSelection/macStyle consistency against ``bhed`` as well + as ``head`` (#4118, #4119). +- [misc.roundTools] Add types and documentation (#4123). +- [varLib.instancer] Instance the ``BASE`` table (#4137). +- [varLib.instancer] Fix Private-dict ``vsindex`` handling in ``instantiateCFF2`` + (#4129, #4132). +- [varLib.instancer] Fix crash instancing CFF2 fonts without a VariationStore + (#4130, #4131). +- [sfnt] Raise ``TTLibError`` instead of ``AssertionError`` or ``struct.error`` + when reading a font truncated within the table directory or a table entry + (#4147, #4149). +- [misc.xmlWriter] Escape the ``]]>`` terminator inside CDATA sections, so an SVG + document containing it can no longer smuggle markup past a TTX round trip + (#4139). +- [varLib.instancer] Implement avar2 partial-instancing: the avar version 2 + ItemVariationStore is adjusted so that remaining axes behave the same after + limiting the designspace (#4045). +- [feaLib] Add shorthand for the value at the default location in a variable + scalar: ``(100 wght=900:120)`` means ``(wght=400:100 wght=900:120)`` when the + wght default is 400 (#4024). +- [cmap] Raise ``TTLibError`` for a truncated or out-of-bounds cmap subtable + header (#4151). +- [designspaceLib] Reject conflicting duplicate inputs in axis maps instead of + silently keeping the last one (#4153). +- [designspaceLib] Read an empty ```` element as an empty lib instead of + raising ``IndexError`` (#4142, #4144). +- [colorLib] Raise a legible error when a COLRv0 layer, or a COLRv1 PaintGlyph or + PaintColrGlyph, references a glyph missing from the glyphMap, instead of failing + obscurely later (#2629, #4141). +- [cmap] Don't drop subtables in unsupported formats when compiling or dumping a + font read from binary (#4136). +- [ttLib] Implement ``splitSinglePos`` so GPOS lookup type 1 offset overflows can + be recovered by splitting the subtable (#4091, #4108). +- [cmap] Round-trip empty Macintosh format 2 subtables (#3663, #4117). +- [glyf] Raise ``TTLibError`` instead of ``RecursionError`` when ``recalcBounds()`` + hits a composite-component reference cycle (#3899, #4116). +- [svgLib] Fix crash parsing an SVG path with consecutive closepath commands + (``Z Z``) (#4122). +- [ttLib] Fix ``DefaultTable`` type annotations (#4126). +- [ttLib] Add support for the ``EBSC`` (Embedded Bitmap Scaling) table (#4113). +- [svgLib] Suppress spurious close segments caused by floating-point drift in + relative path commands (#3860, #4127). +- [qu2cu] Fix ``TypeError`` in the Cython-compiled build when ``Qu2CuPen`` passes + tuple splines (#4160). +- [mort] Add semantic decompilation, TTX, and compilation support for + rearrangement, contextual-substitution, ligature, and insertion subtables + (#4158, #4159, #4161). +- [svgLib] Start a new subpath at the just-closed subpath's initial point when a + drawto command follows a closepath, per SVG spec (#4154, #4155). +- [misc.filesystem] **SECURITY** Reject paths that resolve outside the filesystem + root: a malicious UFO could read arbitrary files via ``..`` components in + ``contents.plist``, and a crafted ``.ufoz`` could create files outside its + temporary mirror (#4124). +- [ttLib] **SECURITY** Sanitise glyph names used as filenames in EBDT/CBDT + ``ttx -z extfile`` export, preventing arbitrary file writes from untrusted + fonts (#4128). +- [misc.etree] **SECURITY** Don't resolve external XML entities in ``XMLParser`` + when lxml is used, preventing XXE file disclosure on lxml < 5.0 (#4145). +- [subset] Fully prune ``VARC`` auxiliary data: collect and remap variation + indices referenced by condition tables when subsetting the ``MultiVarStore``, + and drop the ``AxisIndicesList``, ``ConditionList``, and ``MultiVarStore`` + when they end up empty (#4162). + +4.63.0 (released 2026-05-14) +---------------------------- + +- [ttLib] Add support for Apple Color Emoji ``bgcl`` table (#4065). +- [ttLib] Add support for ``IFT`` and ``IFTX`` tables (Incremental Font Transfer, + PatchMapFormat2) (#4070, #4072). +- [otData] Introduce ``FieldSpec`` dataclass for OpenType table schema definitions, + replacing raw tuples in ``otData.py`` (#4076). +- [Feat] Show ``name`` table strings as comments next to label IDs in TTX output, + matching the convention used by ``fvar``, ``STAT``, ``trak`` (#4089). +- [cu2qu] Fix Cython complex-division rounding difference in + ``split_cubic_into_three`` that could cause ±1 off-curve coordinate shifts + (#3928, #4083). +- [designspaceLib] Fix ``map_backward`` for many-to-one (flat-segment) axis maps + that silently dropped entries via dict comprehension + (googlefonts/ufo2ft#978, #4085). +- [OS/2] Fix ``setUnicodeRanges`` to accept reserved bits 123-127, restoring + round-trip with ``getUnicodeRanges`` and fixing ``recalcUnicodeRanges`` crash + in the subsetter (#4087, #4088). +- [cython] Declare Cython extensions as free-threading compatible on Python 3.13+, + so that importing them on free-threaded Python no longer re-enables the GIL + (#4073, #4090). + +4.62.1 (released 2026-03-13) +---------------------------- + +- [feaLib] Extend contextual rule merging to all rule types: single subst, GSUB/GPOS + named lookups, ignore rules, and chained alternate subst (#4061). + +4.62.0 (released 2026-03-09) +---------------------------- + +- [diff] Add new ``fonttools diff`` command for comparing font files, imported from the + ``fdiff`` project and heavily reworked (#1190, #4007, #4009, #4011, #4013, #4019). +- [feaLib] Fix ``VariableScalar`` interpolation bug with non-linear avar mappings. Also + decouple ``VariableScalar`` from compiled fonts, allowing it to work with designspace data + before compilation (#3938, #4054). +- [feaLib] Fix ``VariableScalar`` axis ordering and iterative delta rounding to match fontc + behavior (#4053). +- [feaLib] Merge chained multi subst rules with same context into a single subtable instead of + emitting one subtable per glyph (#4016, #4058). +- [feaLib] Pass location to ``ConditionsetStatement`` to fix glyphsLib round-tripping + (fontra/fontra-glyphs#130, #4057). +- [feaLib] Write ``0xFFFF`` instead of ``0`` for missing nameIDs in ``cv`` feature params + (#4010, #4012). +- [cmap] Fix ``CmapSubtable.__lt__()`` ``TypeError`` on Python 3 when subtables share the + same encoding record, and add compile-time validation for unique encoding records (#4035, + #4055). +- [svgLib] Skip non-element XML nodes (comments, processing instructions) when drawing SVG + paths (#4042, #4043). +- [glifLib] Fix regression reading glyph outlines when ``glyphObject=None`` (#4030, #4031). +- [pointPen] Fix ``SegmentToPointPen`` edge case: only remove a duplicate final point on + ``closePath()`` if it is an on-curve point (#4014, #4015). +- [cffLib] **SECURITY** Replace ``eval()`` with ``safeEval()`` in ``parseBlendList()`` to + prevent arbitrary code execution from crafted TTX files (#4039, #4040). +- [ttLib] Remove defunct Adobe SING Glyphlet tables (``META``, ``SING``, ``GMAP``, ``GPKG``) + (#4044). +- [varLib.interpolatable] Various bugfixes: fix swapped nodeTypes assignment, duplicate + kink-detector condition, typos, CFF2 vsindex parsing, glyph existence check, and plot + helpers (#4046). +- [varLib.models] Fix ``getSubModel`` not forwarding ``extrapolate``/``axisRanges``; check + location uniqueness after stripping zeros (#4047). +- [varLib] Fix ``--variable-fonts`` filter in ``build_many``; remove dead code and fix + comments (#4048). +- [avar] Preserve existing name table in build; keep ``unbuild`` return types consistent; + validate ``map`` CLI coordinates (#4051). +- [cu2qu/qu2cu] Add input validation: reject non-positive tolerances, validate curve inputs + and list lengths (#4052). +- [colorLib] Raise a clear ``ColorLibError`` when base glyphs are missing from glyphMap, + instead of a confusing ``KeyError`` (#4041). +- [glyf] Remove unnecessary ``fvar`` table dependency (#4017). +- [fvar/trak] Remove unnecessary ``name`` table dependency (#4018). +- [ufoLib] Relax guideline validation to follow the updated spec (#3537, #3553). +- [ttFont] Fix ``saveXML`` regression with empty table lists, clarify docstring (#4025, #4026, + #4056). +- [setup.py] Link ``libm`` for Cython extensions using math functions (#4028, #4029). +- Add typing annotations for ``DSIG``, ``DefaultTable``, ``ttProgram`` (#4033). + +4.61.1 (released 2025-12-12) +---------------------------- + +- [otlLib] buildCoverage: return empty Coverage instead of None (#4003, #4004). +- [instancer] bug fix in ``avar2`` full instancing (#4002). +- [designspaceLib] Preserve empty conditionsets when serializing to XML (#4001). +- [fontBu ilder] Fix FontBuilder ``setupOS2()`` default params globally polluted (#3996, #3997). +- [ttFont] Add more typing annotations to ttFont, xmlWriter, sfnt, varLib.models and others (#3952, #3826). +- Explicitly test and declare support for Python 3.14, even though we were already shipping pre-built wheels for it (#3990). + +4.60.2 (released 2025-12-09) +---------------------------- + +- **Backport release** Same as 4.61.0 but without "Drop support for EOL Python 3.9" change to allow + downstream projects still on Python 3.9 to avail of the security fix for CVE-2025-66034 (#3994, #3999). + +4.61.0 (released 2025-11-28) +---------------------------- + +- [varLib.main]: **SECURITY** Only use basename(vf.filename) to prevent path traversal attacks when + running ``fonttools varLib`` command, or code which invokes ``fonttools.varLib.main()``. + Fixes CVE-2025-66034, see: + https://github.com/fonttools/fonttools/security/advisories/GHSA-768j-98cg-p3fv. +- [feaLib] Sort BaseLangSysRecords by tag (#3986). +- Drop support for EOL Python 3.9 (#3982). +- [instancer] Support --remove-overlaps for fonts with CFF2 table (#3975). +- [CFF2ToCFF] Add --remove-overlaps option (#3976). +- [feaLib] Raise an error for rsub with NULL target (#3979). +- [bezierTools] Fix logic bug in curveCurveIntersections (#3963). +- [feaLib] Error when condition sets have the same name (#3958). +- [cu2qu.ufo] skip processing empty glyphs to support sparse kerning masters (#3956). +- [unicodedata] Update to Unicode 17. Require ``unicodedata2 >= 17.0.0`` when installed with 'unicode' extra. + +4.60.1 (released 2025-09-29) +---------------------------- + +- [ufoLib] Reverted accidental method name change in ``UFOReader.getKerningGroupConversionRenameMaps`` + that broke compatibility with downstream projects like defcon (#3948, #3947, robotools/defcon#478). +- [ufoLib] Added test coverage for ``getKerningGroupConversionRenameMaps`` method (#3950). +- [subset] Don't try to subset BASE table; pass it through by default instead (#3949). +- [subset] Remove empty BaseRecord entries in MarkBasePos lookups (#3897, #3892). +- [subset] Add pruning for MarkLigPos and MarkMarkPos lookups (#3946). +- [subset] Remove duplicate features when subsetting (#3945). +- [Docs] Added documentation for the visitor module (#3944). + +4.60.0 (released 2025-09-17) +---------------------------- + +- [pointPen] Allow ``reverseFlipped`` parameter of ``DecomposingPointPen`` to take a ``ReverseFlipped`` + enum value to control whether/how to reverse contour direction of flipped components, in addition to + the existing True/False. This allows to set ``ReverseFlipped.ON_CURVE_FIRST`` to ensure that + the decomposed outline starts with an on-curve point before being reversed, for better consistency + with other segment-oriented contour transformations. The change is backward compatible, and the + default behavior hasn't changed (#3934). +- [filterPen] Added ``ContourFilterPointPen``, base pen for buffered contour operations, and + ``OnCurveStartPointPen`` filter to ensure contours start with an on-curve point (#3934). +- [cu2qu] Fixed difference in cython vs pure-python complex division by real number (#3930). +- [varLib.avar] Refactored and added some new sub-modules and scripts (#3926). + * ``varLib.avar.build`` module to build avar (and a missing fvar) binaries into a possibly empty TTFont, + * ``varLib.avar.unbuild`` module to print a .designspace snippet that would generate the same avar binary, + * ``varLib.avar.map`` module to take TTFont and do the mapping, in user/normalized space, + * ``varLib.avar.plan`` module moved from ``varLib.avarPlanner``. + The bare ``fonttools varLib.avar`` script is deprecated, in favour of ``fonttools varLib.avar.build`` (or ``unbuild``). +- [interpolatable] Clarify ``linear_sum_assignment`` backend options and minimal dependency + usage (#3927). +- [post] Speed up ``build_psNameMapping`` (#3923). +- [ufoLib] Added typing annotations to fontTools.ufoLib (#3875). + +4.59.2 (released 2025-08-27) +---------------------------- + +- [varLib] Clear ``USE_MY_METRICS`` component flags when inconsistent across masters (#3912). +- [varLib.instancer] Avoid negative advance width/height values when instatiating HVAR/VVAR, + (unlikely in well-behaved fonts) (#3918). +- [subset] Fix shaping behaviour when pruning empty mark sets (#3915, harfbuzz/harfbuzz#5499). +- [cu2qu] Fixed ``dot()`` product of perpendicular vectors not always returning exactly 0.0 + in all Python implementations (#3911) +- [varLib.instancer] Implemented fully-instantiating ``avar2`` fonts (#3909). +- [feaLib] Allow float values in ``VariableScalar``'s axis locations (#3906, #3907). +- [cu2qu] Handle special case in ``calc_intersect`` for degenerate cubic curves where 3 to 4 + control points are equal (#3904). + +4.59.1 (released 2025-08-14) +---------------------------- + +- [featureVars] Update OS/2.usMaxContext if possible after addFeatureVariationsRaw (#3894). +- [vhmtx] raise TTLibError('not enough data...') when hmtx/vmtx are truncated (#3843, #3901). +- [feaLib] Combine duplicate features that have the same set of lookups regardless of the order in which those lookups are added to the feature (#3895). +- [varLib] Deprecate ``varLib.mutator`` in favor of ``varLib.instancer``. The latter + provides equivalent full (static font) instancing in addition to partial VF instancing. + CLI users should replace ``fonttools varLib.mutator`` with ``fonttools varLib.instancer``. + API users should migrate to ``fontTools.varLib.instancer.instantiateVariableFont`` (#2680). + + +4.59.0 (released 2025-07-16) +---------------------------- + +- Removed hard-dependency on pyfilesystem2 (``fs`` package) from ``fonttools[ufo]`` extra. + This is replaced by the `fontTools.misc.filesystem` package, a stdlib-only, drop-in + replacement for the subset of the pyfilesystem2's API used by ``fontTools.ufoLib``. + The latter should continue to work with the upstream ``fs`` (we even test with/without). + Clients who wish to continue using ``fs`` can do so by depending on it directly instead + of via the ``fonttools[ufo]`` extra (#3885, #3620). +- [xmlWriter] Replace illegal XML characters (e.g. control or non-characters) with "?" + when dumping to ttx (#3868, #71). +- [varLib.hvar] Fixed vertical metrics fields copy/pasta error (#3884). +- Micro optimizations in ttLib and sstruct modules (#3878, #3879). +- [unicodedata] Add Garay script to RTL_SCRIPTS (#3882). +- [roundingPen] Remove unreliable kwarg usage. Argument names aren’t consistent among + point pens’ ``.addComponent()`` implementations, in particular ``baseGlyphName`` + vs ``glyphName`` (#3880). + +4.58.5 (released 2025-07-03) +---------------------------- + +- [feaLib] Don't try to combine ligature & multisub rules (#3874). +- [feaLib/ast] Use weakref proxies to avoid cycles in visitor (#3873). +- [varLib.instancer] Fixed instancing CFF2 fonts where VarData contains more than 64k items (#3858). + +4.58.4 (released 2025-06-13) +---------------------------- + +- [feaLib] Allow for empty MarkFilter & MarkAttach sets (#3856). + +4.58.3 (released 2025-06-13) +---------------------------- + +- [feaLib] Fixed iterable check for Python 3.13.4 and newer (#3854, #3855). + +4.58.2 (released 2025-06-06) +---------------------------- + +- [ttLib.reorderGlyphs] Handle CFF2 when reordering glyphs (#3852) +- [subset] Copy name IDs in use before scrapping or scrambling them for webfonts (#3853) + +4.58.1 (released 2025-05-28) +---------------------------- + +- [varLib] Make sure that fvar named instances only reuse name ID 2 or 17 if they are at the default location across all axes, to match OT spec requirement (#3831). +- [feaLib] Improve single substitution promotion to multiple/ligature substitutions, fixing a few bugs as well (#3849). +- [loggingTools] Make ``Timer._time`` a static method that doesn't take self, makes it easier to override (#3836). +- [featureVars] Use ``None`` for empty ConditionSet, which translates to a null offset in the compiled table (#3850). +- [feaLib] Raise an error on conflicting ligature substitution rules instead of silently taking the last one (#3835). +- Add typing annotations to T2CharStringPen (#3837). +- [feaLib] Add single substitutions that were promoted to multiple or ligature substitutions to ``aalt`` feature (#3847). +- [featureVars] Create a default ``LangSys`` in a ``ScriptRecord`` if missing when adding feature variations to existing GSUB later in the build (#3838). +- [symfont] Added a ``main()``. +- [cffLib.specializer] Fix rmoveto merging when blends used (#3839, #3840). +- [pyftmerge] Add support for cmap format 14 in the merge tool (#3830). +- [varLib.instancer/cff2] Fix vsindex of Private dicts when instantiating (#3828, #3232). +- Update text file read to use UTF-8 with optional BOM so it works with e.g. Windows Notepad.exe (#3824). +- [varLib] Ensure that instances only reuse name ID 2 or 17 if they are at the default location across all axes (#3831). +- [varLib] Create a dflt LangSys in a ScriptRecord when adding variations later, to fix an avoidable crash in an edge case (#3838). + +4.58.0 (released 2025-05-10) +---------------------------- + +- Drop Python 3.8, require 3.9+ (#3819) +- [HVAR, VVAR] Prune unused regions when using a direct mapping (#3797) +- [Docs] Improvements to ufoLib documentation (#3721) +- [Docs] Improvements to varLib documentation (#3727) +- [Docs] Improvements to Pens and pen-module documentation (#3724) +- [Docs] Miscellany updates to docs (misc modules and smaller modules) (#3730) +- [subset] Close codepoints over BiDi mirror variants. (#3801) +- [feaLib] Fix serializing ChainContextPosStatement and + ChainContextSubstStatement in some rare cases (#3788) +- [designspaceLib] Clarify user expectations for getStatNames (#2892) +- [GVAR] Add support for new `GVAR` table (#3728) +- [TSI0, TSI5] Derive number of entries to decompile from data length (#2477) +- [ttLib] Fix `AttributeError` when reporting table overflow (#3808) +- [ttLib] Apply rounding more often in getCoordinates (#3798) +- [ttLib] Ignore component bounds if empty (#3799) +- [ttLib] Change the separator for duplicate glyph names from "#" to "." (#3809) +- [feaLib] Support subtable breaks in CursivePos, MarkBasePos, MarkToLigPos and + MarkToMarkPos lookups (#3800, #3807) +- [feaLib] If the same lookup has single substitutions and ligature + substitutions, upgrade single substitutions to ligature substitutions with + one input glyph (#3805) +- [feaLib] Correctly handle in single pos lookups (#3803) +- [feaLib] Remove duplicates from class pair pos classes instead of raising an + error (#3804) +- [feaLib] Support creating extension lookups using useExtenion lookup flag + instead of silently ignoring it (#3811) +- [STAT] Add typing for the simpler STAT arguments (#3812) +- [otlLib.builder] Add future import for annotations (#3814) +- [cffLib] Fix reading supplement encoding (#3813) +- [voltLib] Add some missing functionality and fixes to voltLib and VoltToFea, + making the conversion to feature files more robust. Add also `fonttools + voltLib` command line tool to compile VOLT sources directly (doing an + intermediate fea conversion internally) (#3818) +- [pens] Add some PointPen annotations (#3820) + +4.57.0 (released 2025-04-03) +---------------------------- + +- [ttLib.__main__] Add `--no-recalc-timestamp` flag (#3771) +- [ttLib.__main__] Add `-b` (recalcBBoxes=False) flag (#3772) +- [cmap] Speed up glyphOrder loading from cmap (#3774) +- [ttLib.__main__] Improvements around the `-t` flag (#3776) +- [Debg] Fix parsing from XML; add roundtrip tests (#3781) +- [fealib] Support \*Base.MinMax tables (#3783, #3786) +- [config] Add OPTIMIZE_FONT_SPEED (#3784) +- [varLib.hvar] New module to add HVAR table to the font (#3780) +- [otlLib.optimize] Fix crash when the provided TTF does not contain a `GPOS` (#3794) + +4.56.0 (released 2025-02-07) +---------------------------- + +- [varStore] Sort the input todo list with the same sorting key used for the opimizer's output (#3767). +- [otData] Fix DeviceTable's ``DeltaValue`` repeat value which caused a crash after importing from XML and then compiling a GPOS containing Device tables (#3758). +- [feaLib] Make ``FeatureLibError`` pickleable, so client can e.g. use feaLib to can compile features in parallel with multiprocessing (#3762). +- [varLib/gvar] Removed workaround for old, long-fixed macOS bug about composite glyphs with all zero deltas (#1381, #1788). +- [Docs] Updated ttLib documentation, beefed up TTFont and TTGlyphSet explanations (#3720). + +4.55.8 (released 2025-01-29) +---------------------------- + +- [MetaTools] Fixed bug in buildUCD.py script whereby the first non-header line of some UCD text file was being skipped. This affected in particular the U+00B7 (MIDDLE DOT) entry of ScriptExtensions.txt (#3756). + +4.55.7 (released 2025-01-28) +---------------------------- + +- Shorten the changelog included in PyPI package description to accommodate maximum length limit imposed by Azure DevOps. No actual code changes since v4.55.6 (#3754). + +4.55.6 (released 2025-01-24) +---------------------------- + +- [glyf] Fixed regression introduced in 4.55.5 when computing bounds of nested composite glyphs with transformed components (#3752). + +4.55.5 (released 2025-01-23) +---------------------------- + +- [glyf] Fixed recalcBounds of transformed components with unrounded coordinates (#3750). +- [feaLib] Allow duplicate script/language statements (#3749). + +4.55.4 (released 2025-01-21) +---------------------------- + +- [bezierTools] Fixed ``splitCubicAtT`` sometimes not returning identical start/end points as result of numerical precision (#3742, #3743). +- [feaLib/ast] Fixed docstring of ``AlternateSubstStatement`` (#3735). +- [transform] Typing fixes (#3734). + +4.55.3 (released 2024-12-10) +---------------------------- + +- [Docs] fill out ttLib table section [#3716] +- [feaLib] More efficient inline format 4 lookups [#3726] + +4.55.2 (released 2024-12-05) +---------------------------- + +- [Docs] update Sphinx config (#3712) +- [designspaceLib] Allow axisOrdering to be set to zero (#3715) +- [feaLib] Don’t modify variable anchors in place (#3717) + +4.55.1 (released 2024-12-02) +---------------------------- + +- [ttGlyphSet] Support VARC CFF2 fonts (#3683) +- [DecomposedTransform] Document and implement always skewY == 0 (#3697) +- [varLib] "Fix" cython iup issue? (#3704) +- Cython minor refactor (#3705) + + +4.55.0 (released 2024-11-14) +---------------------------- + +- [cffLib.specializer] Adjust stack use calculation (#3689) +- [varLib] Lets not add mac names if the rest of name doesn't have them (#3688) +- [ttLib.reorderGlyphs] Update CFF table charstrings and charset (#3682) +- [cffLib.specializer] Add cmdline to specialize a CFF2 font (#3675, #3679) +- [CFF2] Lift uint16 VariationStore.length limitation (#3674) +- [subset] consider variation selectors subsetting cmap14 (#3672) +- [varLib.interpolatable] Support CFF2 fonts (#3670) +- Set isfinal to true in XML parser for proper resource cleanup (#3669) +- [removeOverlaps] Fix CFF CharString width (#3659) +- [glyf] Add optimizeSize option (#3657) +- Python 3.13 support (#3656) +- [TupleVariation] Optimize for loading speed, not size (#3650, #3653) + + +4.54.1 (released 2024-09-24) +---------------------------- + +- [unicodedata] Update to Unicode 16 +- [subset] Escape ``\\`` in doc string + +4.54.0 (released 2024-09-23) +---------------------------- + +- [Docs] Small docs cleanups by @n8willis (#3611) +- [Docs] cleanup code blocks by @n8willis (#3627) +- [Docs] fix Sphinx builds by @n8willis (#3625) +- [merge] Minor fixes to documentation for merge by @drj11 (#3588) +- [subset] Small tweaks to pyftsubset documentation by @RoelN (#3633) +- [Tests] Do not require fonttools command to be available by @behdad (#3612) +- [Tests] subset_test: add failing test to reproduce issue #3616 by @anthrotype (#3622) +- [ttLib] NameRecordVisitor: include whole sequence of character variants' UI labels, not just the first by @anthrotype (#3617) +- [varLib.avar] Reconstruct mappings from binary by @behdad (#3598) +- [varLib.instancer] Fix visual artefacts with partial L2 instancing by @Hoolean (#3635) +- [varLib.interpolatable] Support discrete axes in .designspace by @behdad (#3599) +- [varLib.models] By default, assume OpenType-like normalized space by @behdad (#3601) + +4.53.1 (released 2024-07-05) +---------------------------- + +- [feaLib] Improve the sharing of inline chained lookups (#3559) +- [otlLib] Correct the calculation of OS/2.usMaxContext with reversed chaining contextual single substitutions (#3569) +- [misc.visitor] Visitors search the inheritance chain of objects they are visiting (#3581) + +4.53.0 (released 2024-05-31) +---------------------------- + +- [ttLib.removeOverlaps] Support CFF table to aid in downconverting CFF2 fonts (#3528) +- [avar] Fix crash when accessing not-yet-existing attribute (#3550) +- [docs] Add buildMathTable to otlLib.builder documentation (#3540) +- [feaLib] Allow UTF-8 with BOM when reading features (#3495) +- [SVGPathPen] Revert rounding coordinates to two decimal places by default (#3543) +- [varLib.instancer] Refix output filename decision-making (#3545, #3544, #3548) + +4.52.4 (released 2024-05-27) +---------------------------- + +- [varLib.cff] Restore and deprecate convertCFFtoCFF2 that was removed in 4.52.0 + release as it is used by downstream projects (#3535). + +4.52.3 (released 2024-05-27) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.2. No other code changes. + +4.52.2 (released 2024-05-27) +---------------------------- + +- [varLib.interpolatable] Ensure that scipy/numpy output is JSON-serializable + (#3522, #3526). +- [housekeeping] Regenerate table lists, to fix pyinstaller packaging of the new + ``VARC`` table (#3531, #3529). +- [cffLib] Make CFFToCFF2 and CFF2ToCFF more robust (#3521, #3525). + +4.52.1 (released 2024-05-24) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.0. No other code changes. + +4.52.0 (released 2024-05-24) +---------------------------- + +- Added support for the new ``VARC`` (Variable Composite) table that is being + proposed to OpenType spec (#3395). For more info: + https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md +- [ttLib.__main__] Fixed decompiling all tables (90fed08). +- [feaLib] Don't reference the same lookup index multiple times within the same + feature record, it is only applied once anyway (#3520). +- [cffLib] Moved methods to desubroutinize, remove hints and unused subroutines + from subset module to cffLib (#3517). +- [varLib.instancer] Added support for partial-instancing CFF2 tables! Also, added + method to down-convert from CFF2 to CFF 1.0, and CLI entry points to convert + CFF<->CFF2 (#3506). +- [subset] Prune unused user name IDs even with --name-IDs='*' (#3410). +- [ttx] use GNU-style getopt to intermix options and positional arguments (#3509). +- [feaLib.variableScalar] Fixed ``value_at_location()`` method (#3491) +- [psCharStrings] Shorten output of ``encodeFloat`` (#3492). +- [bezierTools] Fix infinite-recursion in ``calcCubicArcLength`` (#3502). +- [avar2] Implement ``avar2`` support in ``TTFont.getGlyphSet()`` (#3473). + +4.51.0 (released 2024-04-05) +---------------------------- + +- [ttLib] Optimization on loading aux fields (#3464). +- [ttFont] Add reorderGlyphs (#3468). + +4.50.0 (released 2024-03-15) +---------------------------- + +- [pens] Added decomposing filter pens that draw components as regular contours (#3460). +- [instancer] Drop explicit no-op axes from TupleVariations (#3457). +- [cu2qu/ufo] Return set of modified glyph names from fonts_to_quadratic (#3456). + +4.49.0 (released 2024-02-15) +---------------------------- + +- [otlLib] Add API for building ``MATH`` table (#3446) + +4.48.1 (released 2024-02-06) +---------------------------- + +- Fixed uploading wheels to PyPI, no code changes since v4.48.0. + +4.48.0 (released 2024-02-06) +---------------------------- + +- [varLib] Do not log when there are no OTL tables to be merged. +- [setup.py] Do not restrict lxml<5 any more, tests pass just fine with lxml>=5. +- [feaLib] Remove glyph and class names length restrictions in FEA (#3424). +- [roundingPens] Added ``transformRoundFunc`` parameter to the rounding pens to allow + for custom rounding of the components' transforms (#3426). +- [feaLib] Keep declaration order of ligature components within a ligature set, instead + of sorting by glyph name (#3429). +- [feaLib] Fixed ordering of alternates in ``aalt`` lookups, following the declaration + order of feature references within the ``aalt`` feature block (#3430). +- [varLib.instancer] Fixed a bug in the instancer's IUP optimization (#3432). +- [sbix] Support sbix glyphs with new graphicType "flip" (#3433). +- [svgPathPen] Added ``--glyphs`` option to dump the SVG paths for the named glyphs + in the font (0572f78). +- [designspaceLib] Added "description" attribute to ```` and ```` + elements, and allow multiple ```` elements to group ```` elements + that are logically related (#3435, #3437). +- [otlLib] Correctly choose the most compact GSUB contextual lookup format (#3439). + +4.47.2 (released 2024-01-11) +---------------------------- + +Minor release to fix uploading wheels to PyPI. + +4.47.1 (released 2024-01-11) +---------------------------- + +- [merge] Improve help message and add standard command line options (#3408) +- [otlLib] Pass ``ttFont`` to ``name.addName`` in ``buildStatTable`` (#3406) +- [featureVars] Re-use ``FeatureVariationRecord``'s when possible (#3413) + +4.47.0 (released 2023-12-18) +---------------------------- + +- [varLib.models] New API for VariationModel: ``getMasterScalars`` and + ``interpolateFromValuesAndScalars``. +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + add a Summary page in the front, and an Index and Table-of-Contents in the back. + Change the page size to Letter. +- [Docs/designspaceLib] Defined a new ``public.fontInfo`` lib key, not used anywhere yet (#3358). + +4.46.0 (released 2023-12-02) +---------------------------- + +- [featureVars] Allow to register the same set of substitution rules to multiple features. + The ``addFeatureVariations`` function can now take a list of featureTags; similarly, the + lib key 'com.github.fonttools.varLib.featureVarsFeatureTag' can now take a + comma-separateed string of feature tags (e.g. "salt,ss01") instead of a single tag (#3360). +- [featureVars] Don't overwrite GSUB FeatureVariations, but append new records to it + for features which are not already there. But raise ``VarLibError`` if the feature tag + already has feature variations associated with it (#3363). +- [varLib] Added ``addGSUBFeatureVariations`` function to add GSUB Feature Variations + to an existing variable font from rules defined in a DesignSpace document (#3362). +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + a new test for "underweight" glyphs. The new test reports quite a few false-positives + though. Please send feedback. + +4.45.1 (released 2023-11-23) +---------------------------- + +- [varLib.interpolatable] Various bugfixes and improvements, better reporting, reduced + false positives. +- [ttGlyphSet] Added option to not recalculate glyf bounds (#3348). + +4.45.0 (released 2023-11-20) +---------------------------- + +- [varLib.interpolatable] Vastly improved algorithms. Also available now is ``--pdf`` + and ``--html`` options to generate a PDF or HTML report of the interpolation issues. + The PDF/HTML report showcases the problematic masters, the interpolated broken + glyph, as well as the proposed fixed version. + +4.44.3 (released 2023-11-15) +---------------------------- + +- [subset] Only prune codepage ranges for OS/2.version >= 1, ignore otherwise (#3334). +- [instancer] Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing + MVAR table containing 'hasc', 'hdsc' or 'hlgp' tags (#3297). + +4.44.2 (released 2023-11-14) +---------------------------- + +- [glyf] Have ``Glyph.recalcBounds`` skip empty components (base glyph with no contours) + when computing the bounding box of composite glyphs. This simply restores the existing + behavior before some changes were introduced in fonttools 4.44.0 (#3333). + +4.44.1 (released 2023-11-14) +---------------------------- + +- [feaLib] Ensure variable mark anchors are deep-copied while building since they + get modified in-place and later reused (#3330). +- [OS/2|subset] Added method to ``recalcCodePageRanges`` to OS/2 table class; added + ``--prune-codepage-ranges`` to `fonttools subset` command (#3328, #2607). + +4.44.0 (released 2023-11-03) +---------------------------- + +- [instancer] Recalc OS/2 AvgCharWidth after instancing if default changes (#3317). +- [otlLib] Make ClassDefBuilder class order match varLib.merger's, i.e. large + classes first, then glyph lexicographic order (#3321, #3324). +- [instancer] Allow not specifying any of min:default:max values and let be filled + up with fvar's values (#3322, #3323). +- [instancer] When running --update-name-table ignore axes that have no STAT axis + values (#3318, #3319). +- [Debg] When dumping to ttx, write the embedded JSON as multi-line string with + indentation (92cbfee0d). +- [varStore] Handle > 65535 items per encoding by splitting VarData subtable (#3310). +- [subset] Handle null-offsets in MarkLigPos subtables. +- [subset] Keep East Asian spacing fatures vhal, halt, chws, vchw by default (#3305). +- [instancer.solver] Fixed case where axisDef < lower and upper < axisMax (#3304). +- [glyf] Speed up compilation, mostly around ``recalcBounds`` (#3301). +- [varLib.interpolatable] Speed it up when working on variable fonts, plus various + micro-optimizations (#3300). +- Require unicodedata2 >= 15.1.0 when installed with 'unicode' extra, contains UCD 15.1. + +4.43.1 (released 2023-10-06) +---------------------------- + +- [EBDT] Fixed TypeError exception in `_reverseBytes` method triggered when dumping + some bitmap fonts with `ttx -z bitwise` option (#3162). +- [v/hhea] Fixed UnboundLocalError exception in ``recalc`` method when no vmtx or hmtx + tables are present (#3290). +- [bezierTools] Fixed incorrectly typed cython local variable leading to TypeError when + calling ``calcQuadraticArcLength`` (#3288). +- [feaLib/otlLib] Better error message when building Coverage table with missing glyph (#3286). + +4.43.0 (released 2023-09-29) +---------------------------- + +- [subset] Set up lxml ``XMLParser(resolve_entities=False)`` when parsing OT-SVG documents + to prevent XML External Entity (XXE) attacks (9f61271dc): + https://codeql.github.com/codeql-query-help/python/py-xxe/ +- [varLib.iup] Added workaround for a Cython bug in ``iup_delta_optimize`` that was + leading to IUP tolerance being incorrectly initialised, resulting in sub-optimal deltas + (60126435d, cython/cython#5732). +- [varLib] Added new command-line entry point ``fonttools varLib.avar`` to add an + ``avar`` table to an existing VF from axes mappings in a .designspace file (0a3360e52). +- [instancer] Fixed bug whereby no longer used variation regions were not correctly pruned + after VarData optimization (#3268). +- Added support for Python 3.12 (#3283). + +4.42.1 (released 2023-08-20) +---------------------------- + +- [t1Lib] Fixed several Type 1 issues (#3238, #3240). +- [otBase/packer] Allow sharing tables reached by different offset sizes (#3241, #3236). +- [varLib/merger] Fix Cursive attachment merging error when all anchors are NULL (#3248, #3247). +- [ttLib] Fixed warning when calling ``addMultilingualName`` and ``ttFont`` parameter was not + passed on to ``findMultilingualName`` (#3253). + +4.42.0 (released 2023-08-02) +---------------------------- + +- [varLib] Use sentinel value 0xFFFF to mark a glyph advance in hmtx/vmtx as non + participating, allowing sparse masters to contain glyphs for variation purposes other + than {H,V}VAR (#3235). +- [varLib/cff] Treat empty glyphs in non-default masters as missing, thus not participating + in CFF2 delta computation, similarly to how varLib already treats them for gvar (#3234). +- Added varLib.avarPlanner script to deduce 'correct' avar v1 axis mappings based on + glyph average weights (#3223). + +4.41.1 (released 2023-07-21) +---------------------------- + +- [subset] Fixed perf regression in v4.41.0 by making ``NameRecordVisitor`` only visit + tables that do contain nameID references (#3213, #3214). +- [varLib.instancer] Support instancing fonts containing null ConditionSet offsets in + FeatureVariationRecords (#3211, #3212). +- [statisticsPen] Report font glyph-average weight/width and font-wide slant. +- [fontBuilder] Fixed head.created date incorrectly set to 0 instead of the current + timestamp, regression introduced in v4.40.0 (#3210). +- [varLib.merger] Support sparse ``CursivePos`` masters (#3209). + +4.41.0 (released 2023-07-12) +---------------------------- + +- [fontBuilder] Fixed bug in setupOS2 with default panose attribute incorrectly being + set to a dict instead of a Panose object (#3201). +- [name] Added method to ``removeUnusedNameRecords`` in the user range (#3185). +- [varLib.instancer] Fixed issue with L4 instancing (moving default) (#3179). +- [cffLib] Use latin1 so we can roundtrip non-ASCII in {Full,Font,Family}Name (#3202). +- [designspaceLib] Mark as optional in docs (as it is in the code). +- [glyf-1] Fixed drawPoints() bug whereby last cubic segment becomes quadratic (#3189, #3190). +- [fontBuilder] Propagate the 'hidden' flag to the fvar Axis instance (#3184). +- [fontBuilder] Update setupAvar() to also support avar 2, fixing ``_add_avar()`` call + site (#3183). +- Added new ``voltLib.voltToFea`` submodule (originally Tiro Typeworks' "Volto") for + converting VOLT OpenType Layout sources to FEA format (#3164). + +4.40.0 (released 2023-06-12) +---------------------------- + +- Published native binary wheels to PyPI for all the python minor versions and platform + and architectures currently supported that would benefit from this. They will include + precompiled Cython-accelerated modules (e.g. cu2qu) without requiring to compile them + from source. The pure-python wheel and source distribution will continue to be + published as always (pip will automatically chose them when no binary wheel is + available for the given platform, e.g. pypy). Use ``pip install --no-binary=fonttools fonttools`` + to expliclity request pip to install from the pure-python source. +- [designspaceLib|varLib] Add initial support for specifying axis mappings and build + ``avar2`` table from those (#3123). +- [feaLib] Support variable ligature caret position (#3130). +- [varLib|glyf] Added option to --drop-implied-oncurves; test for impliable oncurve + points either before or after rounding (#3146, #3147, #3155, #3156). +- [TTGlyphPointPen] Don't error with empty contours, simply ignore them (#3145). +- [sfnt] Fixed str vs bytes remnant of py3 transition in code dealing with de/compiling + WOFF metadata (#3129). +- [instancer-solver] Fixed bug when moving default instance with sparse masters (#3139, #3140). +- [feaLib] Simplify variable scalars that don’t vary (#3132). +- [pens] Added filter pen that explicitly emits closing line when lastPt != movePt (#3100). +- [varStore] Improve optimize algorithm and better document the algorithm (#3124, #3127). + Added ``quantization`` option (#3126). +- Added CI workflow config file for building native binary wheels (#3121). +- [fontBuilder] Added glyphDataFormat=0 option; raise error when glyphs contain cubic + outlines but glyphDataFormat was not explicitly set to 1 (#3113, #3119). +- [subset] Prune emptied GDEF.MarkGlyphSetsDef and remap indices; ensure GDEF is + subsetted before GSUB and GPOS (#3114, #3118). +- [xmlReader] Fixed issue whereby DSIG table data was incorrectly parsed (#3115, #2614). +- [varLib/merger] Fixed merging of SinglePos with pos=0 (#3111, #3112). +- [feaLib] Demote "Feature has not been defined" error to a warning when building aalt + and referenced feature is empty (#3110). +- [feaLib] Dedupe multiple substitutions with classes (#3105). + +4.39.4 (released 2023-05-10) +---------------------------- + +- [varLib.interpolatable] Allow for sparse masters (#3075) +- [merge] Handle differing default/nominalWidthX in CFF (#3070) +- [ttLib] Add missing main.py file to ttLib package (#3088) +- [ttx] Fix missing composite instructions in XML (#3092) +- [ttx] Fix split tables option to work on filenames containing '%' (#3096) +- [featureVars] Process lookups for features other than rvrn last (#3099) +- [feaLib] support multiple substitution with classes (#3103) + +4.39.3 (released 2023-03-28) +---------------------------- + +- [sbix] Fixed TypeError when compiling empty glyphs whose imageData is None, regression + was introduced in v4.39 (#3059). +- [ttFont] Fixed AttributeError on python <= 3.10 when opening a TTFont from a tempfile + SpooledTemporaryFile, seekable method only added on python 3.11 (#3052). + +4.39.2 (released 2023-03-16) +---------------------------- + +- [varLib] Fixed regression introduced in 4.39.1 whereby an incomplete 'STAT' table + would be built even though a DesignSpace v5 did contain 'STAT' definitions (#3045, #3046). + +4.39.1 (released 2023-03-16) +---------------------------- + +- [avar2] Added experimental support for reading/writing avar version 2 as specified in + this draft proposal: https://github.com/harfbuzz/boring-expansion-spec/blob/main/avar2.md +- [glifLib] Wrap underlying XML library exceptions with GlifLibError when parsing GLIFs, + and also print the name and path of the glyph that fails to be parsed (#3042). +- [feaLib] Consult avar for normalizing user-space values in ConditionSets and in + VariableScalars (#3042, #3043). +- [ttProgram] Handle string input to Program.fromAssembly() (#3038). +- [otlLib] Added a config option to emit GPOS 7 lookups, currently disabled by default + because of a macOS bug (#3034). +- [COLRv1] Added method to automatically compute ClipBoxes (#3027). +- [ttFont] Fixed getGlyphID to raise KeyError on missing glyphs instead of returning + None. The regression was introduced in v4.27.0 (#3032). +- [sbix] Fixed UnboundLocalError: cannot access local variable 'rawdata' (#3031). +- [varLib] When building VF, do not overwrite a pre-existing ``STAT`` table that was built + with feaLib from FEA feature file. Also, added support for building multiple VFs + defined in Designspace v5 from ``fonttools varLib`` script (#3024). +- [mtiLib] Only add ``Debg`` table with lookup names when ``FONTTOOLS_LOOKUP_DEBUGGING`` + env variable is set (#3023). + +4.39.0 (released 2023-03-06) +---------------------------- + +- [mtiLib] Optionally add `Debg` debug info for MTI feature builds (#3018). +- [ttx] Support reading input file from standard input using special `-` character, + similar to existing `-o -` option to write output to standard output (#3020). +- [cython] Prevent ``cython.compiled`` raise AttributeError if cython not installed + properly (#3017). +- [OS/2] Guard against ZeroDivisionError when calculating xAvgCharWidth in the unlikely + scenario no glyph has non-zero advance (#3015). +- [subset] Recompute xAvgCharWidth independently of --no-prune-unicode-ranges, + previously the two options were involuntarily bundled together (#3012). +- [fontBuilder] Add ``debug`` parameter to addOpenTypeFeatures method to add source + debugging information to the font in the ``Debg`` private table (#3008). +- [name] Make NameRecord `__lt__` comparison not fail on Unicode encoding errors (#3006). +- [featureVars] Fixed bug in ``overlayBox`` (#3003, #3005). +- [glyf] Added experimental support for cubic bezier curves in TrueType glyf table, as + outlined in glyf v1 proposal (#2988): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-cubicOutlines.md +- Added new qu2cu module and related qu2cuPen, the reverse of cu2qu for converting + TrueType quadratic splines to cubic bezier curves (#2993). +- [glyf] Added experimental support for reading and writing Variable Composites/Components + as defined in glyf v1 spec proposal (#2958): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-varComposites.md. +- [pens]: Added `addVarComponent` method to pen protocols' base classes, which pens can implement + to handle varcomponents (by default they get decomposed) (#2958). +- [misc.transform] Added DecomposedTransform class which implements an affine transformation + with separate translate, rotation, scale, skew, and transformation-center components (#2598) +- [sbix] Ensure Glyph.referenceGlyphName is set; fixes error after dumping and + re-compiling sbix table with 'dupe' glyphs (#2984). +- [feaLib] Be cleverer when merging chained single substitutions into same lookup + when they are specified using the inline notation (#2150, #2974). +- [instancer] Clamp user-inputted axis ranges to those of fvar (#2959). +- [otBase/subset] Define ``__getstate__`` for BaseTable so that a copied/pickled 'lazy' + object gets its own OTTableReader to read from; incidentally fixes a bug while + subsetting COLRv1 table containing ClipBoxes on python 3.11 (#2965, #2968). +- [sbix] Handle glyphs with "dupe" graphic type on compile correctly (#2963). +- [glyf] ``endPointsOfContours`` field should be unsigned! Kudos to behdad for + spotting one of the oldest bugs in FT. Probably nobody has ever dared to make + glyphs with more than 32767 points... (#2957). +- [feaLib] Fixed handling of ``ignore`` statements with unmarked glyphs to match + makeotf behavior, which assumes the first glyph is marked (#2950). +- Reformatted code with ``black`` and enforce new code style via CI check (#2925). +- [feaLib] Sort name table entries following OT spec prescribed order in the builder (#2927). +- [cu2quPen] Add Cu2QuMultiPen that converts multiple outlines at a time in + interpolation compatible way; its methods take a list of tuples arguments + that would normally be passed to individual segment pens, and at the end it + dispatches the converted outlines to each pen (#2912). +- [reverseContourPen/ttGlyphPen] Add outputImpliedClosingLine option (#2913, #2914, + #2921, #2922, #2995). +- [gvar] Avoid expanding all glyphs unnecessarily upon compile (#2918). +- [scaleUpem] Fixed bug whereby CFF2 vsindex was scaled; it should not (#2893, #2894). +- [designspaceLib] Add DS.getAxisByTag and refactor getAxis (#2891). +- [unicodedata] map Zmth<->math in ot_tag_{to,from}_script (#1737, #2889). +- [woff2] Support encoding/decoding OVERLAP_SIMPLE glyf flags (#2576, #2884). +- [instancer] Update OS/2 class and post.italicAngle when default moved (L4) +- Dropped support for Python 3.7 which reached EOL, fontTools requires 3.8+. +- [instancer] Fixed instantiateFeatureVariations logic when a rule range becomes + default-applicable (#2737, #2880). +- [ttLib] Add main to ttFont and ttCollection that just decompile and re-compile the + input font (#2869). +- [featureVars] Insert 'rvrn' lookup at the beginning of LookupList, to work around bug + in Apple implementation of 'rvrn' feature which the spec says it should be processed + early whereas on macOS 10.15 it follows lookup order (#2140, #2867). +- [instancer/mutator] Remove 'DSIG' table if present. +- [svgPathPen] Don't close path in endPath(), assume open unless closePath() (#2089, #2865). + +4.38.0 (released 2022-10-21) +---------------------------- + +- [varLib.instancer] Added support for L4 instancing, i.e. moving the default value of + an axis while keeping it variable. Thanks Behdad! (#2728, #2861). + It's now also possible to restrict an axis min/max values beyond the current default + value, e.g. a font wght has min=100, def=400, max=900 and you want a partial VF that + only varies between 500 and 700, you can now do that. + You can either specify two min/max values (wght=500:700), and the new default will be + set to either the minimum or maximum, depending on which one is closer to the current + default (e.g. 500 in this case). Or you can specify three values (e.g. wght=500:600:700) + to specify the new default value explicitly. +- [otlLib/featureVars] Set a few Count values so one doesn't need to compile the font + to update them (#2860). +- [varLib.models] Make extrapolation work for 2-master models as well where one master + is at the default location (#2843, #2846). + Add optional extrapolate=False to normalizeLocation() (#2847, #2849). +- [varLib.cff] Fixed sub-optimal packing of CFF2 deltas by no longer rounding them to + integer (#2838). +- [scaleUpem] Calculate numShorts in VarData after scale; handle CFF hintmasks (#2840). + +4.37.4 (released 2022-09-30) +---------------------------- + +- [subset] Keep nameIDs used by CPAL palette entry labels (#2837). +- [varLib] Avoid negative hmtx values when creating font from variable CFF2 font (#2827). +- [instancer] Don't prune stat.ElidedFallbackNameID (#2828). +- [unicodedata] Update Scripts/Blocks to Unicode 15.0 (#2833). + +4.37.3 (released 2022-09-20) +---------------------------- + +- Fix arguments in calls to (glyf) glyph.draw() and drawPoints(), whereby offset wasn't + correctly passed down; this fix also exposed a second bug, where lsb and tsb were not + set (#2824, #2825, adobe-type-tools/afdko#1560). + +4.37.2 (released 2022-09-15) +---------------------------- + +- [subset] Keep CPAL table and don't attempt to prune unused color indices if OT-SVG + table is present even if COLR table was subsetted away; OT-SVG may be referencing the + CPAL table; for now we assume that's the case (#2814, #2815). +- [varLib.instancer] Downgrade GPOS/GSUB version if there are no more FeatureVariations + after instancing (#2812). +- [subset] Added ``--no-lazy`` to optionally load fonts eagerly (mostly to ease + debugging of table lazy loading, no practical effects) (#2807). +- [varLib] Avoid building empty COLR.DeltaSetIndexMap with only identity mappings (#2803). +- [feaLib] Allow multiple value record types (by promoting to the most general format) + within the same PairPos subtable; e.g. this allows variable and non variable kerning + rules to share the same subtable. This also fixes a bug whereby some kerning pairs + would become unreachable while shapiong because of premature subtable splitting (#2772, #2776). +- [feaLib] Speed up ``VarScalar`` by caching models for recurring master locations (#2798). +- [feaLib] Optionally cythonize ``feaLib.lexer``, speeds up parsing FEA a bit (#2799). +- [designspaceLib] Avoid crash when handling unbounded rule conditions (#2797). +- [post] Don't crash if ``post`` legacy format 1 is malformed/improperly used (#2786) +- [gvar] Don't be "lazy" (load all glyph variations up front) when TTFont.lazy=False (#2771). +- [TTFont] Added ``normalizeLocation`` method to normalize a location dict from the + font's defined axes space (also known as "user space") into the normalized (-1..+1) + space. It applies ``avar`` mapping if the font contains an ``avar`` table (#2789). +- [TTVarGlyphSet] Support drawing glyph instances from CFF2 variable glyph set (#2784). +- [fontBuilder] Do not error when building cmap if there are zero code points (#2785). +- [varLib.plot] Added ability to plot a variation model and set of accompaning master + values corresponding to the model's master locations into a pyplot figure (#2767). +- [Snippets] Added ``statShape.py`` script to draw statistical shape of a glyph as an + ellips (requires pycairo) (baecd88). +- [TTVarGlyphSet] implement drawPoints natively, avoiding going through + SegmentToPointPen (#2778). +- [TTVarGlyphSet] Fixed bug whereby drawing a composite glyph multiple times, its + components would shif; needed an extra copy (#2774). + +4.37.1 (released 2022-08-24) +---------------------------- + +- [subset] Fixed regression introduced with v4.37.0 while subsetting the VarStore of + ``HVAR`` and ``VVAR`` tables, whereby an ``AttributeError: subset_varidxes`` was + thrown because an apparently unused import statement (with the side-effect of + dynamically binding that ``subset_varidxes`` method to the VarStore class) had been + accidentally deleted in an unrelated PR (#2679, #2773). +- [pens] Added ``cairoPen`` (#2678). +- [gvar] Read ``gvar`` more lazily by not parsing all of the ``glyf`` table (#2771). +- [ttGlyphSet] Make ``drawPoints(pointPen)`` method work for CFF fonts as well via + adapter pen (#2770). + +4.37.0 (released 2022-08-23) +---------------------------- + +- [varLib.models] Reverted PR #2717 which added support for "narrow tents" in v4.36.0, + as it introduced a regression (#2764, #2765). It will be restored in upcoming release + once we found a solution to the bug. +- [cff.specializer] Fixed issue in charstring generalizer with the ``blend`` operator + (#2750, #1975). +- [varLib.models] Added support for extrapolation (#2757). +- [ttGlyphSet] Ensure the newly added ``_TTVarGlyphSet`` inherits from ``_TTGlyphSet`` + to keep backward compatibility with existing API (#2762). +- [kern] Allow compiling legacy kern tables with more than 64k entries (d21cfdede). +- [visitor] Added new visitor API to traverse tree of objects and dispatch based + on the attribute type: cf. ``fontTools.misc.visitor`` and ``fontTools.ttLib.ttVisitor``. Added ``fontTools.ttLib.scaleUpem`` module that uses the latter to + change a font's units-per-em and scale all the related fields accordingly (#2718, + #2755). + +4.36.0 (released 2022-08-17) +---------------------------- + +- [varLib.models] Use a simpler model that generates narrower "tents" (regions, master + supports) whenever possible: specifically when any two axes that actively "cooperate" + (have masters at non-zero positions for both axes) have a complete set of intermediates. + The simpler algorithm produces fewer overlapping regions and behaves better with + respect to rounding at the peak positions than the generic solver, always matching + intermediate masters exactly, instead of maximally 0.5 units off. This may be useful + when 100% metrics compatibility is desired (#2218, #2717). +- [feaLib] Remove warning when about ``GDEF`` not being built when explicitly not + requested; don't build one unconditonally even when not requested (#2744, also works + around #2747). +- [ttFont] ``TTFont.getGlyphSet`` method now supports selecting a location that + represents an instance of a variable font (supports both user-scale and normalized + axes coordinates via the ``normalized=False`` parameter). Currently this only works + for TrueType-flavored variable fonts (#2738). + +4.35.0 (released 2022-08-15) +---------------------------- + +- [otData/otConverters] Added support for 'biased' PaintSweepGradient start/end angles + to match latest COLRv1 spec (#2743). +- [varLib.instancer] Fixed bug in ``_instantiateFeatureVariations`` when at the same + time pinning one axis and restricting the range of a subsequent axis; the wrong axis + tag was being used in the latter step (as the records' axisIdx was updated in the + preceding step but looked up using the old axes order in the following step) (#2733, + #2734). +- [mtiLib] Pad script tags with space when less than 4 char long (#1727). +- [merge] Use ``'.'`` instead of ``'#'`` in duplicate glyph names (#2742). +- [gvar] Added support for lazily loading glyph variations (#2741). +- [varLib] In ``build_many``, we forgot to pass on ``colr_layer_reuse`` parameter to + the ``build`` method (#2730). +- [svgPathPen] Add a main that prints SVG for input text (6df779fd). +- [cffLib.width] Fixed off-by-one in optimized values; previous code didn't match the + code block above it (2963fa50). +- [varLib.interpolatable] Support reading .designspace and .glyphs files (via optional + ``glyphsLib``). +- Compile some modules with Cython when available and building/installing fonttools + from source: ``varLib.iup`` (35% faster), ``pens.momentsPen`` (makes + ``varLib.interpolatable`` 3x faster). +- [feaLib] Allow features to be built for VF without also building a GDEF table (e.g. + only build GSUB); warn when GDEF would be needed but isn't requested (#2705, 2694). +- [otBase] Fixed ``AttributeError`` when uharfbuzz < 0.23.0 and 'repack' method is + missing (32aa8eaf). Use new ``uharfbuzz.repack_with_tag`` when available (since + uharfbuzz>=0.30.0), enables table-specific optimizations to be performed during + repacking (#2724). +- [statisticsPen] By default report all glyphs (4139d891). Avoid division-by-zero + (52b28f90). +- [feaLib] Added missing required argument to FeatureLibError exception (#2693) +- [varLib.merge] Fixed error during error reporting (#2689). Fixed undefined + ``NotANone`` variable (#2714). + +4.34.4 (released 2022-07-07) +---------------------------- + +- Fixed typo in varLib/merger.py that causes NameError merging COLR glyphs + containing more than 255 layers (#2685). + +4.34.3 (released 2022-07-07) +---------------------------- + +- [designspaceLib] Don't make up bad PS names when no STAT data (#2684) + +4.34.2 (released 2022-07-06) +---------------------------- + +- [varStore/subset] fixed KeyError exception to do with NO_VARIATION_INDEX while + subsetting varidxes in GPOS/GDEF (a08140d). + +4.34.1 (released 2022-07-06) +---------------------------- + +- [instancer] When optimizing HVAR/VVAR VarStore, use_NO_VARIATION_INDEX=False to avoid + including NO_VARIATION_INDEX in AdvWidthMap, RsbMap, LsbMap mappings, which would + push the VarIdx width to maximum (4bytes), which is not desirable. This also fixes + a hard crash when attempting to subset a varfont after it had been partially instanced + with use_NO_VARIATION_INDEX=True. + +4.34.0 (released 2022-07-06) +---------------------------- + +- [instancer] Set RIBBI bits in head and OS/2 table when cutting instances and the + subfamily nameID=2 contains strings like 'Italic' or 'Bold' (#2673). +- [otTraverse] Addded module containing methods for traversing trees of otData tables + (#2660). +- [otTables] Made DeltaSetIndexMap TTX dump less verbose by omitting no-op entries + (#2660). +- [colorLib.builder] Added option to disable PaintColrLayers's reuse of layers from + LayerList (#2660). +- [varLib] Added support for merging multiple master COLRv1 tables into a variable + COLR table (#2660, #2328). Base color glyphs of same name in different masters must have + identical paint graph structure (incl. number of layers, palette indices, number + of color line stops, corresponding paint formats at each level of the graph), + but can differ in the variable fields (e.g. PaintSolid.Alpha). PaintVar* tables + are produced when this happens and a VarStore/DeltaSetIndexMap is added to the + variable COLR table. It is possible for non-default masters to be 'sparse', i.e. + omit some of the color glyphs present in the default master. +- [feaLib] Let the Parser set nameIDs 1 through 6 that were previously reserved (#2675). +- [varLib.varStore] Support NO_VARIATION_INDEX in optimizer and instancer. +- [feaLib] Show all missing glyphs at once at end of parsing (#2665). +- [varLib.iup] Rewrite force-set conditions and limit DP loopback length (#2651). + For Noto Sans, IUP time drops from 23s down to 9s, with only a slight size increase + in the final font. This basically turns the algorithm from O(n^3) into O(n). +- [featureVars] Report about missing glyphs in substitution rules (#2654). +- [mutator/instancer] Added CLI flag to --no-recalc-timestamp (#2649). +- [SVG] Allow individual SVG documents in SVG OT table to be compressed on uncompressed, + and remember that when roundtripping to/from ttx. The SVG.docList is now a list + of SVGDocument namedtuple-like dataclass containing an extra ``compressed`` field, + and no longer a bare 3-tuple (#2645). +- [designspaceLib] Check for descriptor types with hasattr() to allow custom classes + that don't inherit the default descriptors (#2634). +- [subset] Enable sharing across subtables of extension lookups for harfbuzz packing + (#2626). Updated how table packing falls back to fontTools from harfbuzz (#2668). +- [subset] Updated default feature tags following current Harfbuzz (#2637). +- [svgLib] Fixed regex for real number to support e.g. 1e-4 in addition to 1.0e-4. + Support parsing negative rx, ry on arc commands (#2596, #2611). +- [subset] Fixed subsetting SinglePosFormat2 when ValueFormat=0 (#2603). + +4.33.3 (released 2022-04-26) +---------------------------- + +- [designspaceLib] Fixed typo in ``deepcopyExceptFonts`` method, preventing font + references to be transferred (#2600). Fixed another typo in the name of ``Range`` + dataclass's ``__post_init__`` magic method (#2597). + +4.33.2 (released 2022-04-22) +---------------------------- + +- [otBase] Make logging less verbose when harfbuzz fails to serialize. Do not exit + at the first failure but continue attempting to fix offset overflow error using + the pure-python serializer even when the ``USE_HARFBUZZ_REPACKER`` option was + explicitly set to ``True``. This is normal with fonts with relatively large + tables, at least until hb.repack implements proper table splitting. + +4.33.1 (released 2022-04-22) +---------------------------- + +- [otlLib] Put back the ``FONTTOOLS_GPOS_COMPACT_MODE`` environment variable to fix + regression in ufo2ft (and thus fontmake) introduced with v4.33.0 (#2592, #2593). + This is deprecated and will be removed one ufo2ft gets updated to use the new + config setup. + +4.33.0 (released 2022-04-21) +---------------------------- + +- [OS/2 / merge] Automatically recalculate ``OS/2.xAvgCharWidth`` after merging + fonts with ``fontTools.merge`` (#2591, #2538). +- [misc/config] Added ``fontTools.misc.configTools`` module, a generic configuration + system (#2416, #2439). + Added ``fontTools.config`` module, a fontTools-specific configuration + system using ``configTools`` above. + Attached a ``Config`` object to ``TTFont``. +- [otlLib] Replaced environment variable for GPOS compression level with an + equivalent option using the new config system. +- [designspaceLib] Incremented format version to 5.0 (#2436). + Added discrete axes, variable fonts, STAT information, either design- or + user-space location on instances. + Added ``fontTools.designspaceLib.split`` module to split a designspace + into sub-spaces that interpolate and that represent the variable fonts + listed in the document. + Made instance names optional and allow computing them from STAT data instead. + Added ``fontTools.designspaceLib.statNames`` module. + Allow instances to have the same location as a previously defined STAT label. + Deprecated some attributes: + ``SourceDescriptor``: ``copyLib``, ``copyInfo``, ``copyGroups``, ``copyFeatures``. + ``InstanceDescriptor``: ``kerning``, ``info``; ``glyphs``: use rules or sparse + sources. + For both, ``location``: use the more explicit designLocation. + Note: all are soft deprecations and existing code should keep working. + Updated documentation for Python methods and the XML format. +- [varLib] Added ``build_many`` to build several variable fonts from a single + designspace document (#2436). + Added ``fontTools.varLib.stat`` module to build STAT tables from a designspace + document. +- [otBase] Try to use the Harfbuzz Repacker for packing GSUB/GPOS tables when + ``uharfbuzz`` python bindings are available (#2552). Disable it by setting the + "fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER" config option to ``False``. + If the option is set explicitly to ``True`` but ``uharfbuzz`` can't be imported + or fails to serialize for any reasons, an error will be raised (ImportError or + uharfbuzz errors). +- [CFF/T2] Ensure that ``pen.closePath()`` gets called for CFF2 charstrings (#2577). + Handle implicit CFF2 closePath within ``T2OutlineExtractor`` (#2580). + +4.32.0 (released 2022-04-08) +---------------------------- + +- [otlLib] Disable GPOS7 optimization to work around bug in Apple CoreText. + Always force Chaining GPOS8 for now (#2540). +- [glifLib] Added ``outputImpliedClosingLine=False`` parameter to ``Glyph.draw()``, + to control behaviour of ``PointToSegmentPen`` (6b4e2e7). +- [varLib.interpolatable] Check for wrong contour starting point (#2571). +- [cffLib] Remove leftover ``GlobalState`` class and fix calls to ``TopDictIndex()`` + (#2569, #2570). +- [instancer] Clear ``AxisValueArray`` if it is empty after instantiating (#2563). + +4.31.2 (released 2022-03-22) +---------------------------- + +- [varLib] fix instantiation of GPOS SinglePos values (#2555). + +4.31.1 (released 2022-03-18) +---------------------------- + +- [subset] fix subsetting OT-SVG when glyph id attribute is on the root ```` + element (#2553). + +4.31.0 (released 2022-03-18) +---------------------------- + +- [ttCollection] Fixed 'ResourceWarning: unclosed file' warning (#2549). +- [varLib.merger] Handle merging SinglePos with valueformat=0 (#2550). +- [ttFont] Update glyf's glyphOrder when calling TTFont.setGlyphOrder() (#2544). +- [ttFont] Added ``ensureDecompiled`` method to load all tables irrespective + of the ``lazy`` attribute (#2551). +- [otBase] Added ``iterSubTable`` method to iterate over BaseTable's children of + type BaseTable; useful for traversing a tree of otTables (#2551). + +4.30.0 (released 2022-03-10) +---------------------------- + +- [varLib] Added debug logger showing the glyph name for which ``gvar`` is built (#2542). +- [varLib.errors] Fixed undefined names in ``FoundANone`` and ``UnsupportedFormat`` + exceptions (ac4d5611). +- [otlLib.builder] Added ``windowsNames`` and ``macNames`` (bool) parameters to the + ``buildStatTabe`` function, so that one can select whether to only add one or both + of the two sets (#2528). +- [t1Lib] Added the ability to recreate PostScript stream (#2504). +- [name] Added ``getFirstDebugName``, ``getBest{Family,SubFamily,Full}Name`` methods (#2526). + +4.29.1 (released 2022-02-01) +---------------------------- + +- [colorLib] Fixed rounding issue with radial gradient's start/end circles inside + one another (#2521). +- [freetypePen] Handle rotate/skew transform when auto-computing width/height of the + buffer; raise PenError wen missing moveTo (#2517) + +4.29.0 (released 2022-01-24) +---------------------------- + +- [ufoLib] Fixed illegal characters and expanded reserved filenames (#2506). +- [COLRv1] Don't emit useless PaintColrLayers of lenght=1 in LayerListBuilder (#2513). +- [ttx] Removed legacy ``waitForKeyPress`` method on Windows (#2509). +- [pens] Added FreeTypePen that uses ``freetype-py`` and the pen protocol for + rasterizating outline paths (#2494). +- [unicodedata] Updated the script direction list to Unicode 14.0 (#2484). + Bumped unicodedata2 dependency to 14.0 (#2499). +- [psLib] Fixed type of ``fontName`` in ``suckfont`` (#2496). + +4.28.5 (released 2021-12-19) +---------------------------- + +- [svgPathPen] Continuation of #2471: make sure all occurrences of ``str()`` are now + replaced with user-defined ``ntos`` callable. +- [merge] Refactored code into submodules, plus several bugfixes and improvements: + fixed duplicate-glyph-resolution GSUB-lookup generation code; use tolerance in glyph + comparison for empty glyph's width; ignore space of default ignorable glyphs; + downgrade duplicates-resolution missing-GSUB from assert to warn; added --drop-tables + option (#2473, #2475, #2476). + +4.28.4 (released 2021-12-15) +---------------------------- + +- [merge] Merge GDEF marksets in Lookups properly (#2474). +- [feaLib] Have ``fontTools feaLib`` script exit with error code when build fails (#2459) +- [svgPathPen] Added ``ntos`` option to customize number formatting (e.g. rounding) (#2471). +- [subset] Speed up subsetting of large CFF fonts (#2467). +- [otTables] Speculatively promote lookups to extension to speed up compilation. If the + offset to lookup N is too big to fit in a ushort, the offset to lookup N+1 is going to + be too big as well, so we promote to extension all lookups from lookup N onwards (#2465). + +4.28.3 (released 2021-12-03) +---------------------------- + +- [subset] Fixed bug while subsetting ``COLR`` table, whereby incomplete layer records + pointing to missing glyphs were being retained leading to ``struct.error`` upon + compiling. Make it so that ``glyf`` glyph closure, which follows the ``COLR`` glyph + closure, does not influence the ``COLR`` table subsetting (#2461, #2462). +- [docs] Fully document the ``cmap`` and ``glyf`` tables (#2454, #2457). +- [colorLib.unbuilder] Fixed CLI by deleting no longer existing parameter (180bb1867). + +4.28.2 (released 2021-11-22) +---------------------------- + +- [otlLib] Remove duplicates when building coverage (#2433). +- [docs] Add interrogate configuration (#2443). +- [docs] Remove comment about missing “start” optional argument to ``calcChecksum`` (#2448). +- [cu2qu/cli] Adapt to the latest ufoLib2. +- [subset] Support subsetting SVG table and remove it from the list of drop by default tables (#534). +- [subset] add ``--pretty-svg`` option to pretty print SVG table contents (#2452). +- [merge] Support merging ``CFF`` tables (CID-keyed ``CFF`` is still not supported) (#2447). +- [merge] Support ``--output-file`` (#2447). +- [docs] Split table docs into individual pages (#2444). +- [feaLib] Forbid empty classes (#2446). +- [docs] Improve documentation for ``fontTools.ttLib.ttFont`` (#2442). + +4.28.1 (released 2021-11-08) +---------------------------- + +- [subset] Fixed AttributeError while traversing a color glyph's Paint graph when there is no + LayerList, which is optional (#2441). + +4.28.0 (released 2021-11-05) +---------------------------- + +- Dropped support for EOL Python 3.6, require Python 3.7 (#2417). +- [ufoLib/glifLib] Make filename-clash checks faster by using a set instead of a list (#2422). +- [subset] Don't crash if optional ClipList and LayerList are ``None`` (empty) (#2424, 2439). +- [OT-SVG] Removed support for old deprecated version 1 and embedded color palettes, + which were never officially part of the OpenType SVG spec. Upon compile, reuse offsets + to SVG documents that are identical (#2430). +- [feaLib] Added support for Variable Feature File syntax. This is experimental and subject + to change until it is finalized in the Adobe FEA spec (#2432). +- [unicodedata] Update Scripts/ScriptExtensions/Blocks to UnicodeData 14.0 (#2437). + +4.27.1 (released 2021-09-23) +---------------------------- + +- [otlLib] Fixed error when chained contextual lookup builder overflows (#2404, #2411). +- [bezierTools] Fixed two floating-point bugs: one when computing `t` for a point + lying on an almost horizontal/vertical line; another when computing the intersection + point between a curve and a line (#2413). + +4.27.0 (released 2021-09-14) +---------------------------- + +- [ttLib/otTables] Cleaned up virtual GID handling: allow virtual GIDs in ``Coverage`` + and ``ClassDef`` readers; removed unused ``allowVID`` argument from ``TTFont`` + constructor, and ``requireReal`` argument in ``TTFont.getGlyphID`` method. + Make ``TTFont.setGlyphOrder`` clear reverse glyphOrder map, and assume ``glyphOrder`` + internal attribute is never modified outside setGlyphOrder; added ``TTFont.getGlyphNameMany`` + and ``getGlyphIDMany`` (#1536, #1654, #2334, #2398). +- [py23] Dropped internal use of ``fontTools.py23`` module to fix deprecation warnings + in client code that imports from fontTools (#2234, #2399, #2400). +- [subset] Fix subsetting COLRv1 clip boxes when font is loaded lazily (#2408). + +4.26.2 (released 2021-08-09) +---------------------------- + +- [otTables] Added missing ``CompositeMode.PLUS`` operator (#2390). + +4.26.1 (released 2021-08-03) +---------------------------- + +- [transform] Added ``transformVector`` and ``transformVectors`` methods to the + ``Transform`` class. Similar to ``transformPoint`` but ignore the translation + part (#2386). + +4.26.0 (released 2021-08-03) +---------------------------- + +- [xmlWriter] Default to ``"\n"`` for ``newlinestr`` instead of platform-specific + ``os.linesep`` (#2384). +- [otData] Define COLRv1 ClipList and ClipBox (#2379). +- [removeOverlaps/instancer] Added --ignore-overlap-errors option to work around + Skia PathOps.Simplify bug (#2382, #2363, google/fonts#3365). +- NOTE: This will be the last version to support Python 3.6. FontTools will require + Python 3.7 or above from the next release (#2350) + +4.25.2 (released 2021-07-26) +---------------------------- + +- [COLRv1] Various changes to sync with the latest CORLv1 draft spec. In particular: + define COLR.VarIndexMap, remove/inline ColorIndex struct, add VarIndexBase to ``PaintVar*`` tables (#2372); + add reduced-precicion specialized transform Paints; + define Angle as fraction of half circle encoded as F2Dot14; + use FWORD (int16) for all Paint center coordinates; + change PaintTransform to have an offset to Affine2x3; +- [ttLib] when importing XML, only set sfntVersion if the font has no reader and is empty (#2376) + +4.25.1 (released 2021-07-16) +---------------------------- + +- [ttGlyphPen] Fixed bug in ``TTGlyphPointPen``, whereby open contours (i.e. starting + with segmentType "move") would throw ``NotImplementedError``. They are now treated + as if they are closed, like with the ``TTGlyphPen`` (#2364, #2366). + +4.25.0 (released 2021-07-05) +---------------------------- + +- [tfmLib] Added new library for parsing TeX Font Metric (TFM) files (#2354). +- [TupleVariation] Make shared tuples order deterministic on python < 3.7 where + Counter (subclass of dict) doesn't remember insertion order (#2351, #2353). +- [otData] Renamed COLRv1 structs to remove 'v1' suffix and match the updated draft + spec: 'LayerV1List' -> 'LayerList', 'BaseGlyphV1List' -> 'BaseGlyphList', + 'BaseGlyphV1Record' -> 'BaseGlyphPaintRecord' (#2346). + Added 8 new ``PaintScale*`` tables: with/without centers, uniform vs non-uniform. + Added ``*AroundCenter`` variants to ``PaintRotate`` and ``PaintSkew``: the default + versions no longer have centerX/Y, but default to origin. + ``PaintRotate``, ``PaintSkew`` and ``PaintComposite`` formats were re-numbered. + NOTE: these are breaking changes; clients using the experimental COLRv1 API will + have to be updated (#2348). +- [pointPens] Allow ``GuessSmoothPointPen`` to accept a tolerance. Fixed call to + ``math.atan2`` with x/y parameters inverted. Sync the code with fontPens (#2344). +- [post] Fixed parsing ``post`` table format 2.0 when it contains extra garbage + at the end of the stringData array (#2314). +- [subset] drop empty features unless 'size' with FeatureParams table (#2324). +- [otlLib] Added ``otlLib.optimize`` module; added GPOS compaction algorithm. + The compaction can be run on existing fonts with ``fonttools otlLib.optimize`` + or using the snippet ``compact_gpos.py``. There's experimental support for + compacting fonts at compilation time using an environment variable, but that + might be removed later (#2326). + +4.24.4 (released 2021-05-25) +---------------------------- + +- [subset/instancer] Fixed ``AttributeError`` when instantiating a VF that + contains GPOS ValueRecords with ``Device`` tables but without the respective + non-Device values (e.g. ``XAdvDevice`` without ``XAdvance``). When not + explicitly set, the latter are assumed to be 0 (#2323). + +4.24.3 (released 2021-05-20) +---------------------------- + +- [otTables] Fixed ``AttributeError`` in methods that split LigatureSubst, + MultipleSubst and AlternateSubst subtables when an offset overflow occurs. + The ``Format`` attribute was removed in v4.22.0 (#2319). + +4.24.2 (released 2021-05-20) +---------------------------- + +- [ttGlyphPen] Fixed typing annotation of TTGlyphPen glyphSet parameter (#2315). +- Fixed two instances of DeprecationWarning: invalid escape sequence (#2311). + +4.24.1 (released 2021-05-20) +---------------------------- + +- [subset] Fixed AttributeError when SinglePos subtable has None Value (ValueFormat 0) + (#2312, #2313). + +4.24.0 (released 2021-05-17) +---------------------------- + +- [pens] Add ``ttGlyphPen.TTGlyphPointPen`` similar to ``TTGlyphPen`` (#2205). + +4.23.1 (released 2021-05-14) +---------------------------- + +- [subset] Fix ``KeyError`` after subsetting ``COLR`` table that initially contains + both v0 and v1 color glyphs when the subset only requested v1 glyphs; we were + not pruning the v0 portion of the table (#2308). +- [colorLib] Set ``LayerV1List`` attribute to ``None`` when empty, it's optional + in CORLv1 (#2308). + +4.23.0 (released 2021-05-13) +---------------------------- + +- [designspaceLib] Allow to use ``\\UNC`` absolute paths on Windows (#2299, #2306). +- [varLib.merger] Fixed bug where ``VarLibMergeError`` was raised with incorrect + parameters (#2300). +- [feaLib] Allow substituting a glyph class with ``NULL`` to delete multiple glyphs + (#2303). +- [glyf] Fixed ``NameError`` exception in ``getPhantomPoints`` (#2295, #2305). +- [removeOverlaps] Retry pathops.simplify after rounding path coordinates to integers + if it fails the first time using floats, to work around a rare and hard to debug + Skia bug (#2288). +- [varLib] Added support for building, reading, writing and optimizing 32-bit + ``ItemVariationStore`` as used in COLRv1 table (#2285). +- [otBase/otConverters] Add array readers/writers for int types (#2285). +- [feaLib] Allow more than one lookahead glyph/class in contextual positioning with + "value at end" (#2293, #2294). +- [COLRv1] Default varIdx should be 0xFFFFFFFF (#2297, #2298). +- [pens] Make RecordingPointPen actually pass on identifiers; replace asserts with + explicit ``PenError`` exception (#2284). +- [mutator] Round lsb for CF2 fonts as well (#2286). + +4.22.1 (released 2021-04-26) +---------------------------- + +- [feaLib] Skip references to named lookups if the lookup block definition + is empty, similarly to makeotf. This also fixes an ``AttributeError`` while + generating ``aalt`` feature (#2276, #2277). +- [subset] Fixed bug with ``--no-hinting`` implementation for Device tables (#2272, + #2275). The previous code was alwyas dropping Device tables if no-hinting was + requested, but some Device tables (DeltaFormat=0x8000) are also used to encode + variation indices and need to be retained. +- [otBase] Fixed bug in getting the ValueRecordSize when decompiling ``MVAR`` + table with ``lazy=True`` (#2273, #2274). +- [varLib/glyf/gvar] Optimized and simplified ``GlyphCoordinates`` and + ``TupleVariation`` classes, use ``bytearray`` where possible, refactored + phantom-points calculations. We measured about 30% speedup in total time + of loading master ttfs, building gvar, and saving (#2261, #2266). +- [subset] Fixed ``AssertionError`` while pruning unused CPAL palettes when + ``0xFFFF`` is present (#2257, #2259). + +4.22.0 (released 2021-04-01) +---------------------------- + +- [ttLib] Remove .Format from Coverage, ClassDef, SingleSubst, LigatureSubst, + AlternateSubst, MultipleSubst (#2238). + ATTENTION: This will change your TTX dumps! +- [misc.arrayTools] move Vector to its own submodule, and rewrite as a tuple + subclass (#2201). +- [docs] Added a terminology section for varLib (#2209). +- [varLib] Move rounding to VariationModel, to avoid error accumulation from + multiple deltas (#2214) +- [varLib] Explain merge errors in more human-friendly terms (#2223, #2226) +- [otlLib] Correct some documentation (#2225) +- [varLib/otlLib] Allow merging into VariationFont without first saving GPOS + PairPos2 (#2229) +- [subset] Improve PairPosFormat2 subsetting (#2221) +- [ttLib] TTFont.save: create file on disk as late as possible (#2253) +- [cffLib] Add missing CFF2 dict operators LanguageGroup and ExpansionFactor + (#2249) + ATTENTION: This will change your TTX dumps! + +4.21.1 (released 2021-02-26) +---------------------------- + +- [pens] Reverted breaking change that turned ``AbstractPen`` and ``AbstractPointPen`` + into abstract base classes (#2164, #2198). + +4.21.0 (released 2021-02-26) +---------------------------- + +- [feaLib] Indent anchor statements in ``asFea()`` to make them more legible and + diff-able (#2193). +- [pens] Turn ``AbstractPen`` and ``AbstractPointPen`` into abstract base classes + (#2164). +- [feaLib] Added support for parsing and building ``STAT`` table from AFDKO feature + files (#2039). +- [instancer] Added option to update name table of generated instance using ``STAT`` + table's axis values (#2189). +- [bezierTools] Added functions to compute bezier point-at-time, as well as line-line, + curve-line and curve-curve intersections (#2192). + +4.20.0 (released 2021-02-15) +---------------------------- + +- [COLRv1] Added ``unbuildColrV1`` to deconstruct COLRv1 otTables to raw json-able + data structure; it does the reverse of ``buildColrV1`` (#2171). +- [feaLib] Allow ``sub X by NULL`` sequence to delete a glyph (#2170). +- [arrayTools] Fixed ``Vector`` division (#2173). +- [COLRv1] Define new ``PaintSweepGradient`` (#2172). +- [otTables] Moved ``Paint.Format`` enum class outside of ``Paint`` class definition, + now named ``PaintFormat``. It was clashing with paint instance ``Format`` attribute + and thus was breaking lazy load of COLR table which relies on magic ``__getattr__`` + (#2175). +- [COLRv1] Replace hand-coded builder functions with otData-driven dynamic + implementation (#2181). +- [COLRv1] Define additional static (non-variable) Paint formats (#2181). +- [subset] Added support for subsetting COLR v1 and CPAL tables (#2174, #2177). +- [fontBuilder] Allow ``setupFvar`` to optionally take ``designspaceLib.AxisDescriptor`` + objects. Added new ``setupAvar`` method. Support localised names for axes and + named instances (#2185). + +4.19.1 (released 2021-01-28) +---------------------------- + +- [woff2] An initial off-curve point with an overlap flag now stays an off-curve + point after compression. + +4.19.0 (released 2021-01-25) +---------------------------- + +- [codecs] Handle ``errors`` parameter different from 'strict' for the custom + extended mac encodings (#2137, #2132). +- [featureVars] Raise better error message when a script is missing the required + default language system (#2154). +- [COLRv1] Avoid abrupt change caused by rounding ``PaintRadialGradient.c0`` when + the start circle almost touches the end circle's perimeter (#2148). +- [COLRv1] Support building unlimited lists of paints as 255-ary trees of + ``PaintColrLayers`` tables (#2153). +- [subset] Prune redundant format-12 cmap subtables when all non-BMP characters + are dropped (#2146). +- [basePen] Raise ``MissingComponentError`` instead of bare ``KeyError`` when a + referenced component is missing (#2145). + +4.18.2 (released 2020-12-16) +---------------------------- + +- [COLRv1] Implemented ``PaintTranslate`` paint format (#2129). +- [varLib.cff] Fixed unbound local variable error (#1787). +- [otlLib] Don't crash when creating OpenType class definitions if some glyphs + occur more than once (#2125). + +4.18.1 (released 2020-12-09) +---------------------------- + +- [colorLib] Speed optimization for ``LayerV1ListBuilder`` (#2119). +- [mutator] Fixed missing tab in ``interpolate_cff2_metrics`` (0957dc7a). + +4.18.0 (released 2020-12-04) +---------------------------- + +- [COLRv1] Update to latest draft: added ``PaintRotate`` and ``PaintSkew`` (#2118). +- [woff2] Support new ``brotlicffi`` bindings for PyPy (#2117). +- [glifLib] Added ``expectContentsFile`` parameter to ``GlyphSet``, for use when + reading existing UFOs, to comply with the specification stating that a + ``contents.plist`` file must exist in a glyph set (#2114). +- [subset] Allow ``LangSys`` tags in ``--layout-scripts`` option (#2112). For example: + ``--layout-scripts=arab.dflt,arab.URD,latn``; this will keep ``DefaultLangSys`` + and ``URD`` language for ``arab`` script, and all languages for ``latn`` script. +- [varLib.interpolatable] Allow UFOs to be checked; report open paths, non existant + glyphs; add a ``--json`` option to produce a machine-readable list of + incompatibilities +- [pens] Added ``QuartzPen`` to create ``CGPath`` from glyph outlines on macOS. + Requires pyobjc (#2107). +- [feaLib] You can export ``FONTTOOLS_LOOKUP_DEBUGGING=1`` to enable feature file + debugging info stored in ``Debg`` table (#2106). +- [otlLib] Build more efficient format 1 and format 2 contextual lookups whenever + possible (#2101). + +4.17.1 (released 2020-11-16) +---------------------------- + +- [colorLib] Fixed regression in 4.17.0 when building COLR v0 table; when color + layers are stored in UFO lib plist, we can't distinguish tuples from lists so + we need to accept either types (e5439eb9, googlefonts/ufo2ft/issues#426). + +4.17.0 (released 2020-11-12) +---------------------------- + +- [colorLib/otData] Updated to latest draft ``COLR`` v1 spec (#2092). +- [svgLib] Fixed parsing error when arc commands' boolean flags are not separated + by space or comma (#2094). +- [varLib] Interpret empty non-default glyphs as 'missing', if the default glyph is + not empty (#2082). +- [feaLib.builder] Only stash lookup location for ``Debg`` if ``Builder.buildLookups_`` + has cooperated (#2065, #2067). +- [varLib] Fixed bug in VarStore optimizer (#2073, #2083). +- [varLib] Add designspace lib key for custom feavar feature tag (#2080). +- Add HashPointPen adapted from psautohint. With this pen, a hash value of a glyph + can be computed, which can later be used to detect glyph changes (#2005). + +4.16.1 (released 2020-10-05) +---------------------------- + +- [varLib.instancer] Fixed ``TypeError`` exception when instantiating a VF with + a GSUB table 1.1 in which ``FeatureVariations`` attribute is present but set to + ``None`` -- indicating that optional ``FeatureVariations`` is missing (#2077). +- [glifLib] Make ``x`` and ``y`` attributes of the ``point`` element required + even when validation is turned off, and raise a meaningful ``GlifLibError`` + message when that happens (#2075). + +4.16.0 (released 2020-09-30) +---------------------------- + +- [removeOverlaps] Added new module and ``removeOverlaps`` function that merges + overlapping contours and components in TrueType glyphs. It requires the + `skia-pathops `__ module. + Note that removing overlaps invalidates the TrueType hinting (#2068). +- [varLib.instancer] Added ``--remove-overlaps`` command-line option. + The ``overlap`` option in ``instantiateVariableFont`` now takes an ``OverlapMode`` + enum: 0: KEEP_AND_DONT_SET_FLAGS, 1: KEEP_AND_SET_FLAGS (default), and 2: REMOVE. + The latter is equivalent to calling ``removeOverlaps`` on the generated static + instance. The option continues to accept ``bool`` value for backward compatibility. + + +4.15.0 (released 2020-09-21) +---------------------------- + +- [plistlib] Added typing annotations to plistlib module. Set up mypy static + typechecker to run automatically on CI (#2061). +- [ttLib] Implement private ``Debg`` table, a reverse-DNS namespaced JSON dict. +- [feaLib] Optionally add an entry into the ``Debg`` table with the original + lookup name (if any), feature name / script / language combination (if any), + and original source filename and line location. Annotate the ttx output for + a lookup with the information from the Debg table (#2052). +- [sfnt] Disabled checksum checking by default in ``SFNTReader`` (#2058). +- [Docs] Document ``mtiLib`` module (#2027). +- [varLib.interpolatable] Added checks for contour node count and operation type + of each node (#2054). +- [ttLib] Added API to register custom table packer/unpacker classes (#2055). + +4.14.0 (released 2020-08-19) +---------------------------- + +- [feaLib] Allow anonymous classes in LookupFlags definitions (#2037). +- [Docs] Better document DesignSpace rules processing order (#2041). +- [ttLib] Fixed 21-year old bug in ``maxp.maxComponentDepth`` calculation (#2044, + #2045). +- [varLib.models] Fixed misspelled argument name in CLI entry point (81d0042a). +- [subset] When subsetting GSUB v1.1, fixed TypeError by checking whether the + optional FeatureVariations table is present (e63ecc5b). +- [Snippets] Added snippet to show how to decompose glyphs in a TTF (#2030). +- [otlLib] Generate GSUB type 5 and GPOS type 7 contextual lookups where appropriate + (#2016). + +4.13.0 (released 2020-07-10) +---------------------------- + +- [feaLib/otlLib] Moved lookup subtable builders from feaLib to otlLib; refactored + some common code (#2004, #2007). +- [docs] Document otlLib module (#2009). +- [glifLib] Fixed bug with some UFO .glif filenames clashing on case-insensitive + filesystems (#2001, #2002). +- [colorLib] Updated COLRv1 implementation following changes in the draft spec: + (#2008, googlefonts/colr-gradients-spec#24). + +4.12.1 (released 2020-06-16) +---------------------------- + +- [_n_a_m_e] Fixed error in ``addMultilingualName`` with one-character names. + Only attempt to recovered malformed UTF-16 data from a ``bytes`` string, + not from unicode ``str`` (#1997, #1998). + +4.12.0 (released 2020-06-09) +---------------------------- + +- [otlLib/varLib] Ensure that the ``AxisNameID`` in the ``STAT`` and ``fvar`` + tables is grater than 255 as per OpenType spec (#1985, #1986). +- [docs] Document more modules in ``fontTools.misc`` package: ``filenames``, + ``fixedTools``, ``intTools``, ``loggingTools``, ``macCreatorType``, ``macRes``, + ``plistlib`` (#1981). +- [OS/2] Don't calculate whole sets of unicode codepoints, use faster and more memory + efficient ranges and bisect lookups (#1984). +- [voltLib] Support writing back abstract syntax tree as VOLT data (#1983). +- [voltLib] Accept DO_NOT_TOUCH_CMAP keyword (#1987). +- [subset/merge] Fixed a namespace clash involving a private helper class (#1955). + +4.11.0 (released 2020-05-28) +---------------------------- + +- [feaLib] Introduced ``includeDir`` parameter on Parser and IncludingLexer to + explicitly specify the directory to search when ``include()`` statements are + encountered (#1973). +- [ufoLib] Silently delete duplicate glyphs within the same kerning group when reading + groups (#1970). +- [ttLib] Set version of COLR table when decompiling COLRv1 (commit 9d8a7e2). + +4.10.2 (released 2020-05-20) +---------------------------- + +- [sfnt] Fixed ``NameError: SimpleNamespace`` while reading TTC header. The regression + was introduced with 4.10.1 after removing ``py23`` star import. + +4.10.1 (released 2020-05-19) +---------------------------- + +- [sfnt] Make ``SFNTReader`` pickleable even when TTFont is loaded with lazy=True + option and thus keeps a reference to an external file (#1962, #1967). +- [feaLib.ast] Restore backward compatibility (broken in 4.10 with #1905) for + ``ChainContextPosStatement`` and ``ChainContextSubstStatement`` classes. + Make them accept either list of lookups or list of lists of lookups (#1961). +- [docs] Document some modules in ``fontTools.misc`` package: ``arrayTools``, + ``bezierTools`` ``cliTools`` and ``eexec`` (#1956). +- [ttLib._n_a_m_e] Fixed ``findMultilingualName()`` when name record's ``string`` is + encoded as bytes sequence (#1963). + +4.10.0 (released 2020-05-15) +---------------------------- + +- [varLib] Allow feature variations to be active across the entire space (#1957). +- [ufoLib] Added support for ``formatVersionMinor`` in UFO's ``fontinfo.plist`` and for + ``formatMinor`` attribute in GLIF file as discussed in unified-font-object/ufo-spec#78. + No changes in reading or writing UFOs until an upcoming (non-0) minor update of the + UFO specification is published (#1786). +- [merge] Fixed merging fonts with different versions of ``OS/2`` table (#1865, #1952). +- [subset] Fixed ``AttributeError`` while subsetting ``ContextSubst`` and ``ContextPos`` + Format 3 subtable (#1879, #1944). +- [ttLib.table._m_e_t_a] if data happens to be ascii, emit comment in TTX (#1938). +- [feaLib] Support multiple lookups per glyph position (#1905). +- [psCharStrings] Use inheritance to avoid repeated code in initializer (#1932). +- [Doc] Improved documentation for the following modules: ``afmLib`` (#1933), ``agl`` + (#1934), ``cffLib`` (#1935), ``cu2qu`` (#1937), ``encodings`` (#1940), ``feaLib`` + (#1941), ``merge`` (#1949). +- [Doc] Split off developer-centric info to new page, making front page of docs more + user-focused. List all utilities and sub-modules with brief descriptions. + Make README more concise and focused (#1914). +- [otlLib] Add function to build STAT table from high-level description (#1926). +- [ttLib._n_a_m_e] Add ``findMultilingualName()`` method (#1921). +- [unicodedata] Update ``RTL_SCRIPTS`` for Unicode 13.0 (#1925). +- [gvar] Sort ``gvar`` XML output by glyph name, not glyph order (#1907, #1908). +- [Doc] Added help options to ``fonttools`` command line tool (#1913, #1920). + Ensure all fonttools CLI tools have help documentation (#1948). +- [ufoLib] Only write fontinfo.plist when there actually is content (#1911). + +4.9.0 (released 2020-04-29) +--------------------------- + +- [subset] Fixed subsetting of FeatureVariations table. The subsetter no longer drops + FeatureVariationRecords that have empty substitutions as that will keep the search + going and thus change the logic. It will only drop empty records that occur at the + end of the FeatureVariationRecords array (#1881). +- [subset] Remove FeatureVariations table and downgrade GSUB/GPOS to version 0x10000 + when FeatureVariations contain no FeatureVariationRecords after subsetting (#1903). +- [agl] Add support for legacy Adobe Glyph List of glyph names in ``fontTools.agl`` + (#1895). +- [feaLib] Ignore superfluous script statements (#1883). +- [feaLib] Hide traceback by default on ``fonttools feaLib`` command line. + Use ``--traceback`` option to show (#1898). +- [feaLib] Check lookup index in chaining sub/pos lookups and print better error + message (#1896, #1897). +- [feaLib] Fix building chained alt substitutions (#1902). +- [Doc] Included all fontTools modules in the sphinx-generated documentation, and + published it to ReadTheDocs for continuous documentation of the fontTools project + (#1333). Check it out at https://fonttools.readthedocs.io/. Thanks to Chris Simpkins! +- [transform] The ``Transform`` class is now subclass of ``typing.NamedTuple``. No + change in functionality (#1904). + + +4.8.1 (released 2020-04-17) +--------------------------- + +- [feaLib] Fixed ``AttributeError: 'NoneType' has no attribute 'getAlternateGlyphs'`` + when ``aalt`` feature references a chain contextual substitution lookup + (googlefonts/fontmake#648, #1878). + +4.8.0 (released 2020-04-16) +--------------------------- + +- [feaLib] If Parser is initialized without a ``glyphNames`` parameter, it cannot + distinguish between a glyph name containing an hyphen, or a range of glyph names; + instead of raising an error, it now interprets them as literal glyph names, while + also outputting a logging warning to alert user about the ambiguity (#1768, #1870). +- [feaLib] When serializing AST to string, emit spaces around hyphens that denote + ranges. Also, fixed an issue with CID ranges when round-tripping AST->string->AST + (#1872). +- [Snippets/otf2ttf] In otf2ttf.py script update LSB in hmtx to match xMin (#1873). +- [colorLib] Added experimental support for building ``COLR`` v1 tables as per + the `colr-gradients-spec `__ + draft proposal. **NOTE**: both the API and the XML dump of ``COLR`` v1 are + susceptible to change while the proposal is being discussed and formalized (#1822). + +4.7.0 (released 2020-04-03) +--------------------------- + +- [cu2qu] Added ``fontTools.cu2qu`` package, imported from the original + `cu2qu `__ project. The ``cu2qu.pens`` module + was moved to ``fontTools.pens.cu2quPen``. The optional cu2qu extension module + can be compiled by installing `Cython `__ before installing + fonttools from source (i.e. git repo or sdist tarball). The wheel package that + is published on PyPI (i.e. the one ``pip`` downloads, unless ``--no-binary`` + option is used), will continue to be pure-Python for now (#1868). + +4.6.0 (released 2020-03-24) +--------------------------- + +- [varLib] Added support for building variable ``BASE`` table version 1.1 (#1858). +- [CPAL] Added ``fromRGBA`` method to ``Color`` class (#1861). + + +4.5.0 (released 2020-03-20) +--------------------------- + +- [designspaceLib] Added ``add{Axis,Source,Instance,Rule}Descriptor`` methods to + ``DesignSpaceDocument`` class, to initialize new descriptor objects using keyword + arguments, and at the same time append them to the current document (#1860). +- [unicodedata] Update to Unicode 13.0 (#1859). + +4.4.3 (released 2020-03-13) +--------------------------- + +- [varLib] Always build ``gvar`` table for TrueType-flavored Variable Fonts, + even if it contains no variation data. The table is required according to + the OpenType spec (#1855, #1857). + +4.4.2 (released 2020-03-12) +--------------------------- + +- [ttx] Annotate ``LookupFlag`` in XML dump with comment explaining what bits + are set and what they mean (#1850). +- [feaLib] Added more descriptive message to ``IncludedFeaNotFound`` error (#1842). + +4.4.1 (released 2020-02-26) +--------------------------- + +- [woff2] Skip normalizing ``glyf`` and ``loca`` tables if these are missing from + a font (e.g. in NotoColorEmoji using ``CBDT/CBLC`` tables). +- [timeTools] Use non-localized date parsing in ``timestampFromString``, to fix + error when non-English ``LC_TIME`` locale is set (#1838, #1839). +- [fontBuilder] Make sure the CFF table generated by fontBuilder can be used by varLib + without having to compile and decompile the table first. This was breaking in + converting the CFF table to CFF2 due to some unset attributes (#1836). + +4.4.0 (released 2020-02-18) +--------------------------- + +- [colorLib] Added ``fontTools.colorLib.builder`` module, initially with ``buildCOLR`` + and ``buildCPAL`` public functions. More color font formats will follow (#1827). +- [fontBuilder] Added ``setupCOLR`` and ``setupCPAL`` methods (#1826). +- [ttGlyphPen] Quantize ``GlyphComponent.transform`` floats to ``F2Dot14`` to fix + round-trip issue when computing bounding boxes of transformed components (#1830). +- [glyf] If a component uses reference points (``firstPt`` and ``secondPt``) for + alignment (instead of X and Y offsets), compute the effective translation offset + *after* having applied any transform (#1831). +- [glyf] When all glyphs have zero contours, compile ``glyf`` table data as a single + null byte in order to pass validation by OTS and Windows (#1829). +- [feaLib] Parsing feature code now ensures that referenced glyph names are part of + the known glyph set, unless a glyph set was not provided. +- [varLib] When filling in the default axis value for a missing location of a source or + instance, correctly map the value forward. +- [varLib] The avar table can now contain mapping output values that are greater than + OR EQUAL to the preceeding value, as the avar specification allows this. +- [varLib] The errors of the module are now ordered hierarchically below VarLibError. + See #1821. + +4.3.0 (released 2020-02-03) +--------------------------- + +- [EBLC/CBLC] Fixed incorrect padding length calculation for Format 3 IndexSubTable + (#1817, #1818). +- [varLib] Fixed error when merging OTL tables and TTFonts were loaded as ``lazy=True`` + (#1808, #1809). +- [varLib] Allow to use master fonts containing ``CFF2`` table when building VF (#1816). +- [ttLib] Make ``recalcBBoxes`` option work also with ``CFF2`` table (#1816). +- [feaLib] Don't reset ``lookupflag`` in lookups defined inside feature blocks. + They will now inherit the current ``lookupflag`` of the feature. This is what + Adobe ``makeotf`` also does in this case (#1815). +- [feaLib] Fixed bug with mixed single/multiple substitutions. If a single substitution + involved a glyph class, we were incorrectly using only the first glyph in the class + (#1814). + +4.2.5 (released 2020-01-29) +--------------------------- + +- [feaLib] Do not fail on duplicate multiple substitutions, only warn (#1811). +- [subset] Optimize SinglePos subtables to Format 1 if all ValueRecords are the same + (#1802). + +4.2.4 (released 2020-01-09) +--------------------------- + +- [unicodedata] Update RTL_SCRIPTS for Unicode 11 and 12. + +4.2.3 (released 2020-01-07) +--------------------------- + +- [otTables] Fixed bug when splitting `MarkBasePos` subtables as offsets overflow. + The mark class values in the split subtable were not being updated, leading to + invalid mark-base attachments (#1797, googlefonts/noto-source#145). +- [feaLib] Only log a warning instead of error when features contain duplicate + substitutions (#1767). +- [glifLib] Strip XML comments when parsing with lxml (#1784, #1785). + +4.2.2 (released 2019-12-12) +--------------------------- + +- [subset] Fixed issue with subsetting FeatureVariations table when the index + of features changes as features get dropped. The feature index need to be + remapped to point to index of the remaining features (#1777, #1782). +- [fontBuilder] Added `addFeatureVariations` method to `FontBuilder` class. This + is a shorthand for calling `featureVars.addFeatureVariations` on the builder's + TTFont object (#1781). +- [glyf] Fixed the flags bug in glyph.drawPoints() like we did for glyph.draw() + (#1771, #1774). + +4.2.1 (released 2019-12-06) +--------------------------- + +- [glyf] Use the ``flagOnCurve`` bit mask in ``glyph.draw()``, so that we ignore + the ``overlap`` flag that may be set when instantiating variable fonts (#1771). + +4.2.0 (released 2019-11-28) +--------------------------- + +- [pens] Added the following pens: + + * ``roundingPen.RoundingPen``: filter pen that rounds coordinates and components' + offsets to integer; + * ``roundingPen.RoundingPointPen``: like the above, but using PointPen protocol. + * ``filterPen.FilterPointPen``: base class for filter point pens; + * ``transformPen.TransformPointPen``: filter point pen to apply affine transform; + * ``recordingPen.RecordingPointPen``: records and replays point-pen commands. + +- [ttGlyphPen] Always round float coordinates and component offsets to integers + (#1763). +- [ufoLib] When converting kerning groups from UFO2 to UFO3, avoid confusing + groups with the same name as one of the glyphs (#1761, #1762, + unified-font-object/ufo-spec#98). + +4.1.0 (released 2019-11-18) +--------------------------- + +- [instancer] Implemented restricting axis ranges (level 3 partial instancing). + You can now pass ``{axis_tag: (min, max)}`` tuples as input to the + ``instantiateVariableFont`` function. Note that changing the default axis + position is not supported yet. The command-line script also accepts axis ranges + in the form of colon-separated float values, e.g. ``wght=400:700`` (#1753, #1537). +- [instancer] Never drop STAT ``DesignAxis`` records, but only prune out-of-range + ``AxisValue`` records. +- [otBase/otTables] Enforce that VarStore.RegionAxisCount == fvar.axisCount, even + when regions list is empty to appease OTS < v8.0 (#1752). +- [designspaceLib] Defined new ``processing`` attribute for ```` element, + with values "first" or "last", plus other editorial changes to DesignSpace + specification. Bumped format version to 4.1 (#1750). +- [varLib] Improved error message when masters' glyph orders do not match (#1758, + #1759). +- [featureVars] Allow to specify custom feature tag in ``addFeatureVariations``; + allow said feature to already exist, in which case we append new lookup indices + to existing features. Implemented ```` attribute ``processing`` according to + DesignSpace specification update in #1750. Depending on this flag, we generate + either an 'rvrn' (always processed first) or a 'rclt' feature (follows lookup order, + therefore last) (#1747, #1625, #1371). +- [ttCollection] Added support for context manager auto-closing via ``with`` statement + like with ``TTFont`` (#1751). +- [unicodedata] Require unicodedata2 >= 12.1.0. +- [py2.py3] Removed yet more PY2 vestiges (#1743). +- [_n_a_m_e] Fixed issue when comparing NameRecords with different string types (#1742). +- [fixedTools] Changed ``fixedToFloat`` to not do any rounding but simply return + ``value / (1 << precisionBits)``. Added ``floatToFixedToStr`` and + ``strToFixedToFloat`` functions to be used when loading from or dumping to XML. + Fixed values (e.g. fvar axes and instance coordinates, avar mappings, etc.) are + are now stored as un-rounded decimal floats upon decompiling (#1740, #737). +- [feaLib] Fixed handling of multiple ``LigatureCaret`` statements for the same glyph. + Only the first rule per glyph is used, additional ones are ignored (#1733). + +4.0.2 (released 2019-09-26) +--------------------------- + +- [voltLib] Added support for ``ALL`` and ``NONE`` in ``PROCESS_MARKS`` (#1732). +- [Silf] Fixed issue in ``Silf`` table compilation and decompilation regarding str vs + bytes in python3 (#1728). +- [merge] Handle duplicate glyph names better: instead of appending font index to + all glyph names, use similar code like we use in ``post`` and ``CFF`` tables (#1729). + +4.0.1 (released 2019-09-11) +--------------------------- + +- [otTables] Support fixing offset overflows in ``MultipleSubst`` lookup subtables + (#1706). +- [subset] Prune empty strikes in ``EBDT`` and ``CBDT`` table data (#1698, #1633). +- [pens] Fixed issue in ``PointToSegmentPen`` when last point of closed contour has + same coordinates as the starting point and was incorrectly dropped (#1720). +- [Graphite] Fixed ``Sill`` table output to pass OTS (#1705). +- [name] Added ``removeNames`` method to ``table__n_a_m_e`` class (#1719). +- [ttLib] Added aliases for renamed entries ``ascender`` and ``descender`` in + ``hhea`` table (#1715). + +4.0.0 (released 2019-08-22) +--------------------------- + +- NOTE: The v4.x version series only supports Python 3.6 or greater. You can keep + using fonttools 3.x if you need support for Python 2. +- [py23] Removed all the python2-only code since it is no longer reachable, thus + unused; only the Python3 symbols were kept, but these are no-op. The module is now + DEPRECATED and will removed in the future. +- [ttLib] Fixed UnboundLocalError for empty loca/glyph tables (#1680). Also, allow + the glyf table to be incomplete when dumping to XML (#1681). +- [varLib.models] Fixed KeyError while sorting masters and there are no on-axis for + a given axis (38a8eb0e). +- [cffLib] Make sure glyph names are unique (#1699). +- [feaLib] Fix feature parser to correctly handle octal numbers (#1700). + +\... see `here `__ for earlier changes diff --git a/shared/package-files/76/76802a479a38bcc98bbc5e8ca57c2dfa0fb8d35f1f18dfd9be374f63800e3b27/blob b/shared/package-files/76/76802a479a38bcc98bbc5e8ca57c2dfa0fb8d35f1f18dfd9be374f63800e3b27/blob new file mode 100644 index 0000000000000000000000000000000000000000..1129d899c89752eb1e6af264fc8dfcef0c862bcd --- /dev/null +++ b/shared/package-files/76/76802a479a38bcc98bbc5e8ca57c2dfa0fb8d35f1f18dfd9be374f63800e3b27/blob @@ -0,0 +1,135 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +$ops_headers +#endif + +#include +#include +#include + +namespace torch { + +/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types +/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to +/// support it in the future by iterating over all sub-lists to find +/// the largest data type that can represent all of the elements, or by using +/// variadic templates. +/// +/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` / +/// (nested) braced-init-list of floating-point types always produces a tensor of dtype +/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior. +/// +/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` / +/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong` +/// (aka. int64_t), matching Python `torch.tensor` behavior. +/// +/// NOTE: The following dtypes are not supported by `torch::tensor` currently: +/// - `unsigned int` +/// - `unsigned long int` +/// - `unsigned long long int` +/// - `long long int` +inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) { + return autograd::make_variable( + // note: we remove the requires_grad setting from the TensorOptions because + // it is ignored anyways (and we actually have an assertion that it isn't set + // which would fail otherwise). We handle requires_grad explicitly here + // instead of passing it through to the kernel. + tensor_data_container.convert_to_tensor(options.requires_grad(c10::nullopt)), + options.requires_grad()); +} + +/// A generic deleter function. +using Deleter = std::function; +using at::MemoryFormat; + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor, `strides` the +/// stride in each dimension. The `deleter` function (a +/// `std::function`) will be called on the `data` when the Tensor +/// data would normally be deallocated. The `TensorOptions` specify additional +/// configuration options for the returned tensor, such as what type to +/// interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + at::IntArrayRef strides, + const Deleter& deleter, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, strides, deleter, options.requires_grad(c10::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor, `strides` the +/// stride in each dimension. The `TensorOptions` +/// specify additional configuration options for the returned tensor, such as +/// what type to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + at::IntArrayRef strides, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, strides, options.requires_grad(c10::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor. The `deleter` +/// (a `std::function`) function will be called on the `data` when +/// the Tensor data would normally be deallocated. The `TensorOptions` specify +/// additional configuration options for the returned tensor, such as what type +/// to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + const Deleter& deleter, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, deleter, options.requires_grad(c10::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor. The +/// `TensorOptions` specify additional configuration options for the returned +/// tensor, such as what type to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, options.requires_grad(c10::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +${function_definitions} + +} // namespace torch diff --git a/shared/package-files/76/7684b332f93fe7efecd5c604b31fe174f3889499cd03b6ccfbb8a53a3562af83/blob b/shared/package-files/76/7684b332f93fe7efecd5c604b31fe174f3889499cd03b6ccfbb8a53a3562af83/blob new file mode 100644 index 0000000000000000000000000000000000000000..e84837bf96056eab70a53f18ab8eebadc1bd5f8e --- /dev/null +++ b/shared/package-files/76/7684b332f93fe7efecd5c604b31fe174f3889499cd03b6ccfbb8a53a3562af83/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor adaptive_avg_pool1d(const at::Tensor & self, at::IntArrayRef output_size); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/76/76890532578c5445455710604a4adc9f87f8c8ced1851df3924d220d018e0bf5/blob b/shared/package-files/76/76890532578c5445455710604a4adc9f87f8c8ced1851df3924d220d018e0bf5/blob new file mode 100644 index 0000000000000000000000000000000000000000..bbee52256e31ac2431edb921aa42c10dd8b4373b --- /dev/null +++ b/shared/package-files/76/76890532578c5445455710604a4adc9f87f8c8ced1851df3924d220d018e0bf5/blob @@ -0,0 +1 @@ +from .urllib.response import * diff --git a/shared/package-files/76/768aabdb0c67ac40f83090e5931434ec616f69a817dfa1d46fbee5cbfbc8b8a4/blob b/shared/package-files/76/768aabdb0c67ac40f83090e5931434ec616f69a817dfa1d46fbee5cbfbc8b8a4/blob new file mode 100644 index 0000000000000000000000000000000000000000..085ab096915bbc4a3761b71736b4dd14f1ff779f --- /dev/null +++ b/shared/package-files/76/768aabdb0c67ac40f83090e5931434ec616f69a817dfa1d46fbee5cbfbc8b8a4/blob @@ -0,0 +1,181 @@ +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.core.numbers import Integer + + +class PlotInterval: + """ + """ + _v, _v_min, _v_max, _v_steps = None, None, None, None + + def require_all_args(f): + def check(self, *args, **kwargs): + for g in [self._v, self._v_min, self._v_max, self._v_steps]: + if g is None: + raise ValueError("PlotInterval is incomplete.") + return f(self, *args, **kwargs) + return check + + def __init__(self, *args): + if len(args) == 1: + if isinstance(args[0], PlotInterval): + self.fill_from(args[0]) + return + elif isinstance(args[0], str): + try: + args = eval(args[0]) + except TypeError: + s_eval_error = "Could not interpret string %s." + raise ValueError(s_eval_error % (args[0])) + elif isinstance(args[0], (tuple, list)): + args = args[0] + else: + raise ValueError("Not an interval.") + if not isinstance(args, (tuple, list)) or len(args) > 4: + f_error = "PlotInterval must be a tuple or list of length 4 or less." + raise ValueError(f_error) + + args = list(args) + if len(args) > 0 and (args[0] is None or isinstance(args[0], Symbol)): + self.v = args.pop(0) + if len(args) in [2, 3]: + self.v_min = args.pop(0) + self.v_max = args.pop(0) + if len(args) == 1: + self.v_steps = args.pop(0) + elif len(args) == 1: + self.v_steps = args.pop(0) + + def get_v(self): + return self._v + + def set_v(self, v): + if v is None: + self._v = None + return + if not isinstance(v, Symbol): + raise ValueError("v must be a SymPy Symbol.") + self._v = v + + def get_v_min(self): + return self._v_min + + def set_v_min(self, v_min): + if v_min is None: + self._v_min = None + return + try: + self._v_min = sympify(v_min) + float(self._v_min.evalf()) + except TypeError: + raise ValueError("v_min could not be interpreted as a number.") + + def get_v_max(self): + return self._v_max + + def set_v_max(self, v_max): + if v_max is None: + self._v_max = None + return + try: + self._v_max = sympify(v_max) + float(self._v_max.evalf()) + except TypeError: + raise ValueError("v_max could not be interpreted as a number.") + + def get_v_steps(self): + return self._v_steps + + def set_v_steps(self, v_steps): + if v_steps is None: + self._v_steps = None + return + if isinstance(v_steps, int): + v_steps = Integer(v_steps) + elif not isinstance(v_steps, Integer): + raise ValueError("v_steps must be an int or SymPy Integer.") + if v_steps <= S.Zero: + raise ValueError("v_steps must be positive.") + self._v_steps = v_steps + + @require_all_args + def get_v_len(self): + return self.v_steps + 1 + + v = property(get_v, set_v) + v_min = property(get_v_min, set_v_min) + v_max = property(get_v_max, set_v_max) + v_steps = property(get_v_steps, set_v_steps) + v_len = property(get_v_len) + + def fill_from(self, b): + if b.v is not None: + self.v = b.v + if b.v_min is not None: + self.v_min = b.v_min + if b.v_max is not None: + self.v_max = b.v_max + if b.v_steps is not None: + self.v_steps = b.v_steps + + @staticmethod + def try_parse(*args): + """ + Returns a PlotInterval if args can be interpreted + as such, otherwise None. + """ + if len(args) == 1 and isinstance(args[0], PlotInterval): + return args[0] + try: + return PlotInterval(*args) + except ValueError: + return None + + def _str_base(self): + return ",".join([str(self.v), str(self.v_min), + str(self.v_max), str(self.v_steps)]) + + def __repr__(self): + """ + A string representing the interval in class constructor form. + """ + return "PlotInterval(%s)" % (self._str_base()) + + def __str__(self): + """ + A string representing the interval in list form. + """ + return "[%s]" % (self._str_base()) + + @require_all_args + def assert_complete(self): + pass + + @require_all_args + def vrange(self): + """ + Yields v_steps+1 SymPy numbers ranging from + v_min to v_max. + """ + d = (self.v_max - self.v_min) / self.v_steps + for i in range(self.v_steps + 1): + a = self.v_min + (d * Integer(i)) + yield a + + @require_all_args + def vrange2(self): + """ + Yields v_steps pairs of SymPy numbers ranging from + (v_min, v_min + step) to (v_max - step, v_max). + """ + d = (self.v_max - self.v_min) / self.v_steps + a = self.v_min + (d * S.Zero) + for i in range(self.v_steps): + b = self.v_min + (d * Integer(i + 1)) + yield a, b + a = b + + def frange(self): + for i in self.vrange(): + yield float(i.evalf()) diff --git a/shared/package-files/76/768af81840f3b02a0f95296c0e090915eb8b70a0f893e8be756c8b20580752bc/blob b/shared/package-files/76/768af81840f3b02a0f95296c0e090915eb8b70a0f893e8be756c8b20580752bc/blob new file mode 100644 index 0000000000000000000000000000000000000000..e7eef9e550737d2ec979f2ab0c661187cc47e94d --- /dev/null +++ b/shared/package-files/76/768af81840f3b02a0f95296c0e090915eb8b70a0f893e8be756c8b20580752bc/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor crow_indices_copy(const at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/76/768c084cd5771b1abcc01dd776a8b2442b440e7f37fc690b706262427cccd660/blob b/shared/package-files/76/768c084cd5771b1abcc01dd776a8b2442b440e7f37fc690b706262427cccd660/blob new file mode 100644 index 0000000000000000000000000000000000000000..88a9a259ac8ec87255b25b3e15375b1c92099999 --- /dev/null +++ b/shared/package-files/76/768c084cd5771b1abcc01dd776a8b2442b440e7f37fc690b706262427cccd660/blob @@ -0,0 +1,87 @@ +__all__ = [ + "dtypes", + "localize_pydatetime", + "NaT", + "NaTType", + "iNaT", + "nat_strings", + "OutOfBoundsDatetime", + "OutOfBoundsTimedelta", + "IncompatibleFrequency", + "Period", + "Resolution", + "Timedelta", + "normalize_i8_timestamps", + "is_date_array_normalized", + "dt64arr_to_periodarr", + "delta_to_nanoseconds", + "ints_to_pydatetime", + "ints_to_pytimedelta", + "get_resolution", + "Timestamp", + "tz_convert_from_utc_single", + "tz_convert_from_utc", + "to_offset", + "Tick", + "BaseOffset", + "tz_compare", + "is_unitless", + "astype_overflowsafe", + "get_unit_from_dtype", + "periods_per_day", + "periods_per_second", + "guess_datetime_format", + "add_overflowsafe", + "get_supported_dtype", + "is_supported_dtype", +] + +from pandas._libs.tslibs import dtypes # pylint: disable=import-self +from pandas._libs.tslibs.conversion import localize_pydatetime +from pandas._libs.tslibs.dtypes import ( + Resolution, + periods_per_day, + periods_per_second, +) +from pandas._libs.tslibs.nattype import ( + NaT, + NaTType, + iNaT, + nat_strings, +) +from pandas._libs.tslibs.np_datetime import ( + OutOfBoundsDatetime, + OutOfBoundsTimedelta, + add_overflowsafe, + astype_overflowsafe, + get_supported_dtype, + is_supported_dtype, + is_unitless, + py_get_unit_from_dtype as get_unit_from_dtype, +) +from pandas._libs.tslibs.offsets import ( + BaseOffset, + Tick, + to_offset, +) +from pandas._libs.tslibs.parsing import guess_datetime_format +from pandas._libs.tslibs.period import ( + IncompatibleFrequency, + Period, +) +from pandas._libs.tslibs.timedeltas import ( + Timedelta, + delta_to_nanoseconds, + ints_to_pytimedelta, +) +from pandas._libs.tslibs.timestamps import Timestamp +from pandas._libs.tslibs.timezones import tz_compare +from pandas._libs.tslibs.tzconversion import tz_convert_from_utc_single +from pandas._libs.tslibs.vectorized import ( + dt64arr_to_periodarr, + get_resolution, + ints_to_pydatetime, + is_date_array_normalized, + normalize_i8_timestamps, + tz_convert_from_utc, +) diff --git a/shared/package-files/76/768e1d29509bc427a484cff2b4981ca7b89083057a011b71bc5799843ee9b618/blob b/shared/package-files/76/768e1d29509bc427a484cff2b4981ca7b89083057a011b71bc5799843ee9b618/blob new file mode 100644 index 0000000000000000000000000000000000000000..a6a42a350f2023cd466672fd882fad459eab2495 --- /dev/null +++ b/shared/package-files/76/768e1d29509bc427a484cff2b4981ca7b89083057a011b71bc5799843ee9b618/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _cslt_compress(const at::Tensor & input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/76/7690cd5b7c25f743569466d246346c68c03566eb818f28aa6bb16f300de1e3b5/blob b/shared/package-files/76/7690cd5b7c25f743569466d246346c68c03566eb818f28aa6bb16f300de1e3b5/blob new file mode 100644 index 0000000000000000000000000000000000000000..8ecff044f5ef1dd8b7e23f2a67ca067d4e6d1b2b --- /dev/null +++ b/shared/package-files/76/7690cd5b7c25f743569466d246346c68c03566eb818f28aa6bb16f300de1e3b5/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor index_put(const at::Tensor & self, const c10::List> & indices, const at::Tensor & values, bool accumulate=false); +TORCH_API at::Tensor & index_put_out(const at::Tensor & self, const c10::List> & indices, const at::Tensor & values, bool accumulate, at::Tensor & out); +TORCH_API at::Tensor & index_put_(at::Tensor & self, const c10::List> & indices, const at::Tensor & values, bool accumulate=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/76/7691c84634882905fc216bd86271ef6916404d9afa8c0154475d7afa0ae4804a/blob b/shared/package-files/76/7691c84634882905fc216bd86271ef6916404d9afa8c0154475d7afa0ae4804a/blob new file mode 100644 index 0000000000000000000000000000000000000000..55fab16fb10461c6962cc1f107f790d2ffb20002 --- /dev/null +++ b/shared/package-files/76/7691c84634882905fc216bd86271ef6916404d9afa8c0154475d7afa0ae4804a/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor _upsample_bilinear2d_aa(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor _upsample_bilinear2d_aa_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/76/76922bfc33915868a1ad9657927599d6d836324fa41c64b4d3510fee27ed9450/blob b/shared/package-files/76/76922bfc33915868a1ad9657927599d6d836324fa41c64b4d3510fee27ed9450/blob new file mode 100644 index 0000000000000000000000000000000000000000..f07f0b45062b33c41d531e79816f774abd2c9b78 --- /dev/null +++ b/shared/package-files/76/76922bfc33915868a1ad9657927599d6d836324fa41c64b4d3510fee27ed9450/blob @@ -0,0 +1,52 @@ +Metadata-Version: 2.1 +Name: attrs +Version: 23.1.0 +Summary: Classes Without Boilerplate +Project-URL: Documentation, https://www.attrs.org/ +Project-URL: Changelog, https://www.attrs.org/en/stable/changelog.html +Project-URL: Bug Tracker, https://github.com/python-attrs/attrs/issues +Project-URL: Source Code, https://github.com/python-attrs/attrs +Project-URL: Funding, https://github.com/sponsors/hynek +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-attrs?utm_source=pypi-attrs&utm_medium=pypi +Author-email: Hynek Schlawack +License-Expression: MIT +License-File: LICENSE +Keywords: attribute,boilerplate,class +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Requires-Dist: importlib-metadata; python_version < '3.8' +Provides-Extra: cov +Requires-Dist: attrs[tests]; extra == 'cov' +Requires-Dist: coverage[toml]>=5.3; extra == 'cov' +Provides-Extra: dev +Requires-Dist: attrs[docs,tests]; extra == 'dev' +Requires-Dist: pre-commit; extra == 'dev' +Provides-Extra: docs +Requires-Dist: furo; extra == 'docs' +Requires-Dist: myst-parser; extra == 'docs' +Requires-Dist: sphinx; extra == 'docs' +Requires-Dist: sphinx-notfound-page; extra == 'docs' +Requires-Dist: sphinxcontrib-towncrier; extra == 'docs' +Requires-Dist: towncrier; extra == 'docs' +Requires-Dist: zope-interface; extra == 'docs' +Provides-Extra: tests +Requires-Dist: attrs[tests-no-zope]; extra == 'tests' +Requires-Dist: zope-interface; extra == 'tests' +Provides-Extra: tests-no-zope +Requires-Dist: cloudpickle; platform_python_implementation == 'CPython' and extra == 'tests-no-zope' +Requires-Dist: hypothesis; extra == 'tests-no-zope' +Requires-Dist: mypy>=1.1.1; platform_python_implementation == 'CPython' and extra == 'tests-no-zope' +Requires-Dist: pympler; extra == 'tests-no-zope' +Requires-Dist: pytest-mypy-plugins; platform_python_implementation == 'CPython' and python_version < '3.11' and extra == 'tests-no-zope' +Requires-Dist: pytest-xdist[psutil]; extra == 'tests-no-zope' +Requires-Dist: pytest>=4.3.0; extra == 'tests-no-zope' diff --git a/shared/package-files/76/7693d6c829f14544e168aea7a46bcde7f7e153e293d5bd4689f5394e3dc01cc2/blob b/shared/package-files/76/7693d6c829f14544e168aea7a46bcde7f7e153e293d5bd4689f5394e3dc01cc2/blob new file mode 100644 index 0000000000000000000000000000000000000000..1375162d9e1015009ea2a1c7ce098340231074f3 --- /dev/null +++ b/shared/package-files/76/7693d6c829f14544e168aea7a46bcde7f7e153e293d5bd4689f5394e3dc01cc2/blob @@ -0,0 +1,120 @@ +import numpy as np +import math +from numba import cuda, double, void +from numba.cuda.testing import unittest, CUDATestCase + + +RISKFREE = 0.02 +VOLATILITY = 0.30 + +A1 = 0.31938153 +A2 = -0.356563782 +A3 = 1.781477937 +A4 = -1.821255978 +A5 = 1.330274429 +RSQRT2PI = 0.39894228040143267793994605993438 + + +def cnd(d): + K = 1.0 / (1.0 + 0.2316419 * np.abs(d)) + ret_val = (RSQRT2PI * np.exp(-0.5 * d * d) * + (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))))) + return np.where(d > 0, 1.0 - ret_val, ret_val) + + +def black_scholes(callResult, putResult, stockPrice, optionStrike, optionYears, + Riskfree, Volatility): + S = stockPrice + X = optionStrike + T = optionYears + R = Riskfree + V = Volatility + sqrtT = np.sqrt(T) + d1 = (np.log(S / X) + (R + 0.5 * V * V) * T) / (V * sqrtT) + d2 = d1 - V * sqrtT + cndd1 = cnd(d1) + cndd2 = cnd(d2) + + expRT = np.exp(- R * T) + callResult[:] = (S * cndd1 - X * expRT * cndd2) + putResult[:] = (X * expRT * (1.0 - cndd2) - S * (1.0 - cndd1)) + + +def randfloat(rand_var, low, high): + return (1.0 - rand_var) * low + rand_var * high + + +class TestBlackScholes(CUDATestCase): + def test_blackscholes(self): + OPT_N = 400 + iterations = 2 + + stockPrice = randfloat(np.random.random(OPT_N), 5.0, 30.0) + optionStrike = randfloat(np.random.random(OPT_N), 1.0, 100.0) + optionYears = randfloat(np.random.random(OPT_N), 0.25, 10.0) + + callResultNumpy = np.zeros(OPT_N) + putResultNumpy = -np.ones(OPT_N) + + callResultNumba = np.zeros(OPT_N) + putResultNumba = -np.ones(OPT_N) + + # numpy + for i in range(iterations): + black_scholes(callResultNumpy, putResultNumpy, stockPrice, + optionStrike, optionYears, RISKFREE, VOLATILITY) + + @cuda.jit(double(double), device=True, inline=True) + def cnd_cuda(d): + K = 1.0 / (1.0 + 0.2316419 * math.fabs(d)) + ret_val = (RSQRT2PI * math.exp(-0.5 * d * d) * + (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))))) + if d > 0: + ret_val = 1.0 - ret_val + return ret_val + + @cuda.jit(void(double[:], double[:], double[:], double[:], double[:], + double, double)) + def black_scholes_cuda(callResult, putResult, S, X, T, R, V): + i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x + if i >= S.shape[0]: + return + sqrtT = math.sqrt(T[i]) + d1 = ((math.log(S[i] / X[i]) + (R + 0.5 * V * V) * T[i]) + / (V * sqrtT)) + d2 = d1 - V * sqrtT + cndd1 = cnd_cuda(d1) + cndd2 = cnd_cuda(d2) + + expRT = math.exp((-1. * R) * T[i]) + callResult[i] = (S[i] * cndd1 - X[i] * expRT * cndd2) + putResult[i] = (X[i] * expRT * (1.0 - cndd2) - S[i] * (1.0 - cndd1)) + + # numba + blockdim = 512, 1 + griddim = int(math.ceil(float(OPT_N) / blockdim[0])), 1 + stream = cuda.stream() + d_callResult = cuda.to_device(callResultNumba, stream) + d_putResult = cuda.to_device(putResultNumba, stream) + d_stockPrice = cuda.to_device(stockPrice, stream) + d_optionStrike = cuda.to_device(optionStrike, stream) + d_optionYears = cuda.to_device(optionYears, stream) + + for i in range(iterations): + black_scholes_cuda[griddim, blockdim, stream]( + d_callResult, d_putResult, d_stockPrice, d_optionStrike, + d_optionYears, RISKFREE, VOLATILITY) + d_callResult.copy_to_host(callResultNumba, stream) + d_putResult.copy_to_host(putResultNumba, stream) + stream.synchronize() + + delta = np.abs(callResultNumpy - callResultNumba) + L1norm = delta.sum() / np.abs(callResultNumpy).sum() + + max_abs_err = delta.max() + self.assertTrue(L1norm < 1e-13) + self.assertTrue(max_abs_err < 1e-13) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/76/769712f0ac1c276589ec190ea7809961a53246ec3b5364bd1b3bd5c0a5228508/blob b/shared/package-files/76/769712f0ac1c276589ec190ea7809961a53246ec3b5364bd1b3bd5c0a5228508/blob new file mode 100644 index 0000000000000000000000000000000000000000..2efbb305a9b2fc75fcd52f42486f28d33d92020a --- /dev/null +++ b/shared/package-files/76/769712f0ac1c276589ec190ea7809961a53246ec3b5364bd1b3bd5c0a5228508/blob @@ -0,0 +1,79 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# Copyright (C) 2015 Red Hat, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class URI(dns.rdata.Rdata): + """URI record""" + + # see RFC 7553 + + __slots__ = ["priority", "weight", "target"] + + def __init__(self, rdclass, rdtype, priority, weight, target): + super().__init__(rdclass, rdtype) + self.priority = self._as_uint16(priority) + self.weight = self._as_uint16(weight) + self.target = self._as_bytes(target, True) + if len(self.target) == 0: + raise dns.exception.SyntaxError("URI target cannot be empty") + + def to_text(self, origin=None, relativize=True, **kw): + return '%d %d "%s"' % (self.priority, self.weight, self.target.decode()) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + priority = tok.get_uint16() + weight = tok.get_uint16() + target = tok.get().unescape() + if not (target.is_quoted_string() or target.is_identifier()): + raise dns.exception.SyntaxError("URI target must be a string") + return cls(rdclass, rdtype, priority, weight, target.value) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + two_ints = struct.pack("!HH", self.priority, self.weight) + file.write(two_ints) + file.write(self.target) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (priority, weight) = parser.get_struct("!HH") + target = parser.get_remaining() + if len(target) == 0: + raise dns.exception.FormError("URI target may not be empty") + return cls(rdclass, rdtype, priority, weight, target) + + def _processing_priority(self): + return self.priority + + def _processing_weight(self): + return self.weight + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.weighted_processing_order(iterable) diff --git a/shared/package-files/76/7699d52bc6c02d8b0bfca6aa0c2aa155b2170cba80b6e8099dc719d10fb3db11/blob b/shared/package-files/76/7699d52bc6c02d8b0bfca6aa0c2aa155b2170cba80b6e8099dc719d10fb3db11/blob new file mode 100644 index 0000000000000000000000000000000000000000..113685a9a88a01206dae1adbc0ffbb3669fb2466 --- /dev/null +++ b/shared/package-files/76/7699d52bc6c02d8b0bfca6aa0c2aa155b2170cba80b6e8099dc719d10fb3db11/blob @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_log2(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_log2(at::TensorList self) { + return at::_ops::_foreach_log2::call(self); +} + +// aten::_foreach_log2_(Tensor(a!)[] self) -> () +inline void _foreach_log2_(at::TensorList self) { + return at::_ops::_foreach_log2_::call(self); +} + +// aten::_foreach_log2.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_log2_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_log2_out::call(self, out); +} +// aten::_foreach_log2.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_log2_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_log2_out::call(self, out); +} + +} diff --git a/shared/package-files/76/769dc159e972d04fa9a7717a7e6a71fcc755cd8f5ddd508701d372a3a3adcd60/blob b/shared/package-files/76/769dc159e972d04fa9a7717a7e6a71fcc755cd8f5ddd508701d372a3a3adcd60/blob new file mode 100644 index 0000000000000000000000000000000000000000..38f287066ab8151dfe12c2d744675fc0d34b245c --- /dev/null +++ b/shared/package-files/76/769dc159e972d04fa9a7717a7e6a71fcc755cd8f5ddd508701d372a3a3adcd60/blob @@ -0,0 +1,5 @@ +import types + +from .distribution import Distribution + +def get_metadata(path_or_module: str | types.ModuleType, metadata_version: str | None = ...) -> Distribution | None: ... diff --git a/shared/package-files/76/769eca2dd0d3755d2de8b13a78ab756d5b09db2d9ed5cf0b41bf1ba523513d3d/blob b/shared/package-files/76/769eca2dd0d3755d2de8b13a78ab756d5b09db2d9ed5cf0b41bf1ba523513d3d/blob new file mode 100644 index 0000000000000000000000000000000000000000..fb05137533a0b558963750d74046544e741fc79d --- /dev/null +++ b/shared/package-files/76/769eca2dd0d3755d2de8b13a78ab756d5b09db2d9ed5cf0b41bf1ba523513d3d/blob @@ -0,0 +1,13 @@ +# Package Information for pkg-config + +prefix=/opt/conda +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include + +Name: libpcre2-16 +Description: PCRE2 - Perl compatible regular expressions C library (2nd API) with 16 bit character support +Version: 10.42 +Libs: -L${libdir} -lpcre2-16 +Libs.private: +Cflags: -I${includedir} diff --git a/shared/package-files/76/769eee366305ef204a92527d985cbb98636fe46198249037ef1fcac4899322cc/blob b/shared/package-files/76/769eee366305ef204a92527d985cbb98636fe46198249037ef1fcac4899322cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..257feb4d835a7341c2b4bc970bc7ce24f8cfa27d --- /dev/null +++ b/shared/package-files/76/769eee366305ef204a92527d985cbb98636fe46198249037ef1fcac4899322cc/blob @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_cos(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_cos(at::TensorList self) { + return at::_ops::_foreach_cos::call(self); +} + +// aten::_foreach_cos_(Tensor(a!)[] self) -> () +inline void _foreach_cos_(at::TensorList self) { + return at::_ops::_foreach_cos_::call(self); +} + +// aten::_foreach_cos.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_cos_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_cos_out::call(self, out); +} +// aten::_foreach_cos.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_cos_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_cos_out::call(self, out); +} + +} diff --git a/shared/package-files/76/769fa2b378b91907e5ea562ba3e70cdacb5cc973ef44cd1f907dd33db1e8832d/blob b/shared/package-files/76/769fa2b378b91907e5ea562ba3e70cdacb5cc973ef44cd1f907dd33db1e8832d/blob new file mode 100644 index 0000000000000000000000000000000000000000..ab3eaac852f7a506a35abab154dcc10321f8b5fb --- /dev/null +++ b/shared/package-files/76/769fa2b378b91907e5ea562ba3e70cdacb5cc973ef44cd1f907dd33db1e8832d/blob @@ -0,0 +1,7943 @@ +from __future__ import annotations + +from collections import abc +from datetime import datetime +import functools +from itertools import zip_longest +import operator +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Literal, + NoReturn, + cast, + final, + overload, +) +import warnings + +import numpy as np + +from pandas._config import ( + get_option, + using_copy_on_write, + using_string_dtype, +) + +from pandas._libs import ( + NaT, + algos as libalgos, + index as libindex, + lib, + writers, +) +from pandas._libs.internals import BlockValuesRefs +import pandas._libs.join as libjoin +from pandas._libs.lib import ( + is_datetime_array, + no_default, +) +from pandas._libs.tslibs import ( + IncompatibleFrequency, + OutOfBoundsDatetime, + Timestamp, + tz_compare, +) +from pandas._typing import ( + AnyAll, + ArrayLike, + Axes, + Axis, + DropKeep, + DtypeObj, + F, + IgnoreRaise, + IndexLabel, + JoinHow, + Level, + NaPosition, + ReindexMethod, + Self, + Shape, + npt, +) +from pandas.compat.numpy import function as nv +from pandas.errors import ( + DuplicateLabelError, + InvalidIndexError, +) +from pandas.util._decorators import ( + Appender, + cache_readonly, + deprecate_nonkeyword_arguments, + doc, +) +from pandas.util._exceptions import ( + find_stack_level, + rewrite_exception, +) + +from pandas.core.dtypes.astype import ( + astype_array, + astype_is_view, +) +from pandas.core.dtypes.cast import ( + LossySetitemError, + can_hold_element, + common_dtype_categorical_compat, + find_result_type, + infer_dtype_from, + maybe_cast_pointwise_result, + np_can_hold_element, +) +from pandas.core.dtypes.common import ( + ensure_int64, + ensure_object, + ensure_platform_int, + is_any_real_numeric_dtype, + is_bool_dtype, + is_ea_or_datetimelike_dtype, + is_float, + is_hashable, + is_integer, + is_iterator, + is_list_like, + is_numeric_dtype, + is_object_dtype, + is_scalar, + is_signed_integer_dtype, + is_string_dtype, + needs_i8_conversion, + pandas_dtype, + validate_all_hashable, +) +from pandas.core.dtypes.concat import concat_compat +from pandas.core.dtypes.dtypes import ( + ArrowDtype, + CategoricalDtype, + DatetimeTZDtype, + ExtensionDtype, + IntervalDtype, + PeriodDtype, + SparseDtype, +) +from pandas.core.dtypes.generic import ( + ABCCategoricalIndex, + ABCDataFrame, + ABCDatetimeIndex, + ABCIntervalIndex, + ABCMultiIndex, + ABCPeriodIndex, + ABCRangeIndex, + ABCSeries, + ABCTimedeltaIndex, +) +from pandas.core.dtypes.inference import is_dict_like +from pandas.core.dtypes.missing import ( + array_equivalent, + is_valid_na_for_dtype, + isna, +) + +from pandas.core import ( + arraylike, + nanops, + ops, +) +from pandas.core.accessor import CachedAccessor +import pandas.core.algorithms as algos +from pandas.core.array_algos.putmask import ( + setitem_datetimelike_compat, + validate_putmask, +) +from pandas.core.arrays import ( + ArrowExtensionArray, + BaseMaskedArray, + Categorical, + DatetimeArray, + ExtensionArray, + TimedeltaArray, +) +from pandas.core.arrays.string_ import ( + StringArray, + StringDtype, +) +from pandas.core.base import ( + IndexOpsMixin, + PandasObject, +) +import pandas.core.common as com +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, + sanitize_array, +) +from pandas.core.indexers import ( + disallow_ndim_indexing, + is_valid_positional_slice, +) +from pandas.core.indexes.frozen import FrozenList +from pandas.core.missing import clean_reindex_fill_method +from pandas.core.ops import get_op_result_name +from pandas.core.ops.invalid import make_invalid_op +from pandas.core.sorting import ( + ensure_key_mapped, + get_group_index_sorter, + nargsort, +) +from pandas.core.strings.accessor import StringMethods + +from pandas.io.formats.printing import ( + PrettyDict, + default_pprint, + format_object_summary, + pprint_thing, +) + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Iterable, + Sequence, + ) + + from pandas import ( + CategoricalIndex, + DataFrame, + MultiIndex, + Series, + ) + from pandas.core.arrays import ( + IntervalArray, + PeriodArray, + ) + +__all__ = ["Index"] + +_unsortable_types = frozenset(("mixed", "mixed-integer")) + +_index_doc_kwargs: dict[str, str] = { + "klass": "Index", + "inplace": "", + "target_klass": "Index", + "raises_section": "", + "unique": "Index", + "duplicated": "np.ndarray", +} +_index_shared_docs: dict[str, str] = {} +str_t = str + +_dtype_obj = np.dtype("object") + +_masked_engines = { + "Complex128": libindex.MaskedComplex128Engine, + "Complex64": libindex.MaskedComplex64Engine, + "Float64": libindex.MaskedFloat64Engine, + "Float32": libindex.MaskedFloat32Engine, + "UInt64": libindex.MaskedUInt64Engine, + "UInt32": libindex.MaskedUInt32Engine, + "UInt16": libindex.MaskedUInt16Engine, + "UInt8": libindex.MaskedUInt8Engine, + "Int64": libindex.MaskedInt64Engine, + "Int32": libindex.MaskedInt32Engine, + "Int16": libindex.MaskedInt16Engine, + "Int8": libindex.MaskedInt8Engine, + "boolean": libindex.MaskedBoolEngine, + "double[pyarrow]": libindex.MaskedFloat64Engine, + "float64[pyarrow]": libindex.MaskedFloat64Engine, + "float32[pyarrow]": libindex.MaskedFloat32Engine, + "float[pyarrow]": libindex.MaskedFloat32Engine, + "uint64[pyarrow]": libindex.MaskedUInt64Engine, + "uint32[pyarrow]": libindex.MaskedUInt32Engine, + "uint16[pyarrow]": libindex.MaskedUInt16Engine, + "uint8[pyarrow]": libindex.MaskedUInt8Engine, + "int64[pyarrow]": libindex.MaskedInt64Engine, + "int32[pyarrow]": libindex.MaskedInt32Engine, + "int16[pyarrow]": libindex.MaskedInt16Engine, + "int8[pyarrow]": libindex.MaskedInt8Engine, + "bool[pyarrow]": libindex.MaskedBoolEngine, +} + + +def _maybe_return_indexers(meth: F) -> F: + """ + Decorator to simplify 'return_indexers' checks in Index.join. + """ + + @functools.wraps(meth) + def join( + self, + other: Index, + *, + how: JoinHow = "left", + level=None, + return_indexers: bool = False, + sort: bool = False, + ): + join_index, lidx, ridx = meth(self, other, how=how, level=level, sort=sort) + if not return_indexers: + return join_index + + if lidx is not None: + lidx = ensure_platform_int(lidx) + if ridx is not None: + ridx = ensure_platform_int(ridx) + return join_index, lidx, ridx + + return cast(F, join) + + +def _new_Index(cls, d): + """ + This is called upon unpickling, rather than the default which doesn't + have arguments and breaks __new__. + """ + # required for backward compat, because PI can't be instantiated with + # ordinals through __new__ GH #13277 + if issubclass(cls, ABCPeriodIndex): + from pandas.core.indexes.period import _new_PeriodIndex + + return _new_PeriodIndex(cls, **d) + + if issubclass(cls, ABCMultiIndex): + if "labels" in d and "codes" not in d: + # GH#23752 "labels" kwarg has been replaced with "codes" + d["codes"] = d.pop("labels") + + # Since this was a valid MultiIndex at pickle-time, we don't need to + # check validty at un-pickle time. + d["verify_integrity"] = False + + elif "dtype" not in d and "data" in d: + # Prevent Index.__new__ from conducting inference; + # "data" key not in RangeIndex + d["dtype"] = d["data"].dtype + return cls.__new__(cls, **d) + + +class Index(IndexOpsMixin, PandasObject): + """ + Immutable sequence used for indexing and alignment. + + The basic object storing axis labels for all pandas objects. + + .. versionchanged:: 2.0.0 + + Index can hold all numpy numeric dtypes (except float16). Previously only + int64/uint64/float64 dtypes were accepted. + + Parameters + ---------- + data : array-like (1-dimensional) + dtype : str, numpy.dtype, or ExtensionDtype, optional + Data type for the output Index. If not specified, this will be + inferred from `data`. + See the :ref:`user guide ` for more usages. + copy : bool, default False + Copy input data. + name : object + Name to be stored in the index. + tupleize_cols : bool (default: True) + When True, attempt to create a MultiIndex if possible. + + See Also + -------- + RangeIndex : Index implementing a monotonic integer range. + CategoricalIndex : Index of :class:`Categorical` s. + MultiIndex : A multi-level, or hierarchical Index. + IntervalIndex : An Index of :class:`Interval` s. + DatetimeIndex : Index of datetime64 data. + TimedeltaIndex : Index of timedelta64 data. + PeriodIndex : Index of Period data. + + Notes + ----- + An Index instance can **only** contain hashable objects. + An Index instance *can not* hold numpy float16 dtype. + + Examples + -------- + >>> pd.Index([1, 2, 3]) + Index([1, 2, 3], dtype='int64') + + >>> pd.Index(list('abc')) + Index(['a', 'b', 'c'], dtype='object') + + >>> pd.Index([1, 2, 3], dtype="uint8") + Index([1, 2, 3], dtype='uint8') + """ + + # similar to __array_priority__, positions Index after Series and DataFrame + # but before ExtensionArray. Should NOT be overridden by subclasses. + __pandas_priority__ = 2000 + + # Cython methods; see github.com/cython/cython/issues/2647 + # for why we need to wrap these instead of making them class attributes + # Moreover, cython will choose the appropriate-dtyped sub-function + # given the dtypes of the passed arguments + + @final + def _left_indexer_unique(self, other: Self) -> npt.NDArray[np.intp]: + # Caller is responsible for ensuring other.dtype == self.dtype + sv = self._get_join_target() + ov = other._get_join_target() + # similar but not identical to ov.searchsorted(sv) + return libjoin.left_join_indexer_unique(sv, ov) + + @final + def _left_indexer( + self, other: Self + ) -> tuple[ArrayLike, npt.NDArray[np.intp], npt.NDArray[np.intp]]: + # Caller is responsible for ensuring other.dtype == self.dtype + sv = self._get_join_target() + ov = other._get_join_target() + joined_ndarray, lidx, ridx = libjoin.left_join_indexer(sv, ov) + joined = self._from_join_target(joined_ndarray) + return joined, lidx, ridx + + @final + def _inner_indexer( + self, other: Self + ) -> tuple[ArrayLike, npt.NDArray[np.intp], npt.NDArray[np.intp]]: + # Caller is responsible for ensuring other.dtype == self.dtype + sv = self._get_join_target() + ov = other._get_join_target() + joined_ndarray, lidx, ridx = libjoin.inner_join_indexer(sv, ov) + joined = self._from_join_target(joined_ndarray) + return joined, lidx, ridx + + @final + def _outer_indexer( + self, other: Self + ) -> tuple[ArrayLike, npt.NDArray[np.intp], npt.NDArray[np.intp]]: + # Caller is responsible for ensuring other.dtype == self.dtype + sv = self._get_join_target() + ov = other._get_join_target() + joined_ndarray, lidx, ridx = libjoin.outer_join_indexer(sv, ov) + joined = self._from_join_target(joined_ndarray) + return joined, lidx, ridx + + _typ: str = "index" + _data: ExtensionArray | np.ndarray + _data_cls: type[ExtensionArray] | tuple[type[np.ndarray], type[ExtensionArray]] = ( + np.ndarray, + ExtensionArray, + ) + _id: object | None = None + _name: Hashable = None + # MultiIndex.levels previously allowed setting the index name. We + # don't allow this anymore, and raise if it happens rather than + # failing silently. + _no_setting_name: bool = False + _comparables: list[str] = ["name"] + _attributes: list[str] = ["name"] + + @cache_readonly + def _can_hold_strings(self) -> bool: + return not is_numeric_dtype(self.dtype) + + _engine_types: dict[np.dtype | ExtensionDtype, type[libindex.IndexEngine]] = { + np.dtype(np.int8): libindex.Int8Engine, + np.dtype(np.int16): libindex.Int16Engine, + np.dtype(np.int32): libindex.Int32Engine, + np.dtype(np.int64): libindex.Int64Engine, + np.dtype(np.uint8): libindex.UInt8Engine, + np.dtype(np.uint16): libindex.UInt16Engine, + np.dtype(np.uint32): libindex.UInt32Engine, + np.dtype(np.uint64): libindex.UInt64Engine, + np.dtype(np.float32): libindex.Float32Engine, + np.dtype(np.float64): libindex.Float64Engine, + np.dtype(np.complex64): libindex.Complex64Engine, + np.dtype(np.complex128): libindex.Complex128Engine, + } + + @property + def _engine_type( + self, + ) -> type[libindex.IndexEngine | libindex.ExtensionEngine]: + return self._engine_types.get(self.dtype, libindex.ObjectEngine) + + # whether we support partial string indexing. Overridden + # in DatetimeIndex and PeriodIndex + _supports_partial_string_indexing = False + + _accessors = {"str"} + + str = CachedAccessor("str", StringMethods) + + _references = None + + # -------------------------------------------------------------------- + # Constructors + + def __new__( + cls, + data=None, + dtype=None, + copy: bool = False, + name=None, + tupleize_cols: bool = True, + ) -> Self: + from pandas.core.indexes.range import RangeIndex + + name = maybe_extract_name(name, data, cls) + + if dtype is not None: + dtype = pandas_dtype(dtype) + + data_dtype = getattr(data, "dtype", None) + + refs = None + if not copy and isinstance(data, (ABCSeries, Index)): + refs = data._references + + is_pandas_object = isinstance(data, (ABCSeries, Index, ExtensionArray)) + + # range + if isinstance(data, (range, RangeIndex)): + result = RangeIndex(start=data, copy=copy, name=name) + if dtype is not None: + return result.astype(dtype, copy=False) + # error: Incompatible return value type (got "MultiIndex", + # expected "Self") + return result # type: ignore[return-value] + + elif is_ea_or_datetimelike_dtype(dtype): + # non-EA dtype indexes have special casting logic, so we punt here + if isinstance(data, (set, frozenset)): + data = list(data) + + elif is_ea_or_datetimelike_dtype(data_dtype): + pass + + elif isinstance(data, (np.ndarray, Index, ABCSeries)): + if isinstance(data, ABCMultiIndex): + data = data._values + + if data.dtype.kind not in "iufcbmM": + # GH#11836 we need to avoid having numpy coerce + # things that look like ints/floats to ints unless + # they are actually ints, e.g. '0' and 0.0 + # should not be coerced + data = com.asarray_tuplesafe(data, dtype=_dtype_obj) + + elif is_scalar(data): + raise cls._raise_scalar_data_error(data) + elif hasattr(data, "__array__"): + return cls(np.asarray(data), dtype=dtype, copy=copy, name=name) + elif not is_list_like(data) and not isinstance(data, memoryview): + # 2022-11-16 the memoryview check is only necessary on some CI + # builds, not clear why + raise cls._raise_scalar_data_error(data) + + else: + if tupleize_cols: + # GH21470: convert iterable to list before determining if empty + if is_iterator(data): + data = list(data) + + if data and all(isinstance(e, tuple) for e in data): + # we must be all tuples, otherwise don't construct + # 10697 + from pandas.core.indexes.multi import MultiIndex + + # error: Incompatible return value type (got "MultiIndex", + # expected "Self") + return MultiIndex.from_tuples( # type: ignore[return-value] + data, names=name + ) + # other iterable of some kind + + if not isinstance(data, (list, tuple)): + # we allow set/frozenset, which Series/sanitize_array does not, so + # cast to list here + data = list(data) + if len(data) == 0: + # unlike Series, we default to object dtype: + data = np.array(data, dtype=object) + + if len(data) and isinstance(data[0], tuple): + # Ensure we get 1-D array of tuples instead of 2D array. + data = com.asarray_tuplesafe(data, dtype=_dtype_obj) + + try: + arr = sanitize_array(data, None, dtype=dtype, copy=copy) + except ValueError as err: + if "index must be specified when data is not list-like" in str(err): + raise cls._raise_scalar_data_error(data) from err + if "Data must be 1-dimensional" in str(err): + raise ValueError("Index data must be 1-dimensional") from err + raise + arr = ensure_wrapped_if_datetimelike(arr) + + klass = cls._dtype_to_subclass(arr.dtype) + + arr = klass._ensure_array(arr, arr.dtype, copy=False) + result = klass._simple_new(arr, name, refs=refs) + if dtype is None and is_pandas_object and data_dtype == np.object_: + if result.dtype != data_dtype: + warnings.warn( + "Dtype inference on a pandas object " + "(Series, Index, ExtensionArray) is deprecated. The Index " + "constructor will keep the original dtype in the future. " + "Call `infer_objects` on the result to get the old " + "behavior.", + FutureWarning, + stacklevel=2, + ) + return result # type: ignore[return-value] + + @classmethod + def _ensure_array(cls, data, dtype, copy: bool): + """ + Ensure we have a valid array to pass to _simple_new. + """ + if data.ndim > 1: + # GH#13601, GH#20285, GH#27125 + raise ValueError("Index data must be 1-dimensional") + elif dtype == np.float16: + # float16 not supported (no indexing engine) + raise NotImplementedError("float16 indexes are not supported") + + if copy: + # asarray_tuplesafe does not always copy underlying data, + # so need to make sure that this happens + data = data.copy() + return data + + @final + @classmethod + def _dtype_to_subclass(cls, dtype: DtypeObj): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + + if isinstance(dtype, ExtensionDtype): + return dtype.index_class + + if dtype.kind == "M": + from pandas import DatetimeIndex + + return DatetimeIndex + + elif dtype.kind == "m": + from pandas import TimedeltaIndex + + return TimedeltaIndex + + elif dtype.kind == "O": + # NB: assuming away MultiIndex + return Index + + elif issubclass(dtype.type, str) or is_numeric_dtype(dtype): + return Index + + raise NotImplementedError(dtype) + + # NOTE for new Index creation: + + # - _simple_new: It returns new Index with the same type as the caller. + # All metadata (such as name) must be provided by caller's responsibility. + # Using _shallow_copy is recommended because it fills these metadata + # otherwise specified. + + # - _shallow_copy: It returns new Index with the same type (using + # _simple_new), but fills caller's metadata otherwise specified. Passed + # kwargs will overwrite corresponding metadata. + + # See each method's docstring. + + @classmethod + def _simple_new( + cls, values: ArrayLike, name: Hashable | None = None, refs=None + ) -> Self: + """ + We require that we have a dtype compat for the values. If we are passed + a non-dtype compat, then coerce using the constructor. + + Must be careful not to recurse. + """ + assert isinstance(values, cls._data_cls), type(values) + + result = object.__new__(cls) + result._data = values + result._name = name + result._cache = {} + result._reset_identity() + if refs is not None: + result._references = refs + else: + result._references = BlockValuesRefs() + result._references.add_index_reference(result) + + return result + + @classmethod + def _with_infer(cls, *args, **kwargs): + """ + Constructor that uses the 1.0.x behavior inferring numeric dtypes + for ndarray[object] inputs. + """ + result = cls(*args, **kwargs) + + if result.dtype == _dtype_obj and not result._is_multi: + # error: Argument 1 to "maybe_convert_objects" has incompatible type + # "Union[ExtensionArray, ndarray[Any, Any]]"; expected + # "ndarray[Any, Any]" + values = lib.maybe_convert_objects(result._values) # type: ignore[arg-type] + if values.dtype.kind in "iufb": + return Index(values, name=result.name) + + return result + + @cache_readonly + def _constructor(self) -> type[Self]: + return type(self) + + @final + def _maybe_check_unique(self) -> None: + """ + Check that an Index has no duplicates. + + This is typically only called via + `NDFrame.flags.allows_duplicate_labels.setter` when it's set to + True (duplicates aren't allowed). + + Raises + ------ + DuplicateLabelError + When the index is not unique. + """ + if not self.is_unique: + msg = """Index has duplicates.""" + duplicates = self._format_duplicate_message() + msg += f"\n{duplicates}" + + raise DuplicateLabelError(msg) + + @final + def _format_duplicate_message(self) -> DataFrame: + """ + Construct the DataFrame for a DuplicateLabelError. + + This returns a DataFrame indicating the labels and positions + of duplicates in an index. This should only be called when it's + already known that duplicates are present. + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'a']) + >>> idx._format_duplicate_message() + positions + label + a [0, 2] + """ + from pandas import Series + + duplicates = self[self.duplicated(keep="first")].unique() + assert len(duplicates) + + out = ( + Series(np.arange(len(self)), copy=False) + .groupby(self, observed=False) + .agg(list)[duplicates] + ) + if self._is_multi: + # test_format_duplicate_labels_message_multi + # error: "Type[Index]" has no attribute "from_tuples" [attr-defined] + out.index = type(self).from_tuples(out.index) # type: ignore[attr-defined] + + if self.nlevels == 1: + out = out.rename_axis("label") + return out.to_frame(name="positions") + + # -------------------------------------------------------------------- + # Index Internals Methods + + def _shallow_copy(self, values, name: Hashable = no_default) -> Self: + """ + Create a new Index with the same class as the caller, don't copy the + data, use the same object attributes with passed in attributes taking + precedence. + + *this is an internal non-public method* + + Parameters + ---------- + values : the values to create the new Index, optional + name : Label, defaults to self.name + """ + name = self._name if name is no_default else name + + return self._simple_new(values, name=name, refs=self._references) + + def _view(self) -> Self: + """ + fastpath to make a shallow copy, i.e. new object with same data. + """ + result = self._simple_new(self._values, name=self._name, refs=self._references) + + result._cache = self._cache + return result + + @final + def _rename(self, name: Hashable) -> Self: + """ + fastpath for rename if new name is already validated. + """ + result = self._view() + result._name = name + return result + + @final + def is_(self, other) -> bool: + """ + More flexible, faster check like ``is`` but that works through views. + + Note: this is *not* the same as ``Index.identical()``, which checks + that metadata is also the same. + + Parameters + ---------- + other : object + Other object to compare against. + + Returns + ------- + bool + True if both have same underlying data, False otherwise. + + See Also + -------- + Index.identical : Works like ``Index.is_`` but also checks metadata. + + Examples + -------- + >>> idx1 = pd.Index(['1', '2', '3']) + >>> idx1.is_(idx1.view()) + True + + >>> idx1.is_(idx1.copy()) + False + """ + if self is other: + return True + elif not hasattr(other, "_id"): + return False + elif self._id is None or other._id is None: + return False + else: + return self._id is other._id + + @final + def _reset_identity(self) -> None: + """ + Initializes or resets ``_id`` attribute with new object. + """ + self._id = object() + + @final + def _cleanup(self) -> None: + self._engine.clear_mapping() + + @cache_readonly + def _engine( + self, + ) -> libindex.IndexEngine | libindex.ExtensionEngine | libindex.MaskedIndexEngine: + # For base class (object dtype) we get ObjectEngine + target_values = self._get_engine_target() + + if isinstance(self._values, ArrowExtensionArray) and self.dtype.kind in "Mm": + import pyarrow as pa + + pa_type = self._values._pa_array.type + if pa.types.is_timestamp(pa_type): + target_values = self._values._to_datetimearray() + return libindex.DatetimeEngine(target_values._ndarray) + elif pa.types.is_duration(pa_type): + target_values = self._values._to_timedeltaarray() + return libindex.TimedeltaEngine(target_values._ndarray) + + if isinstance(target_values, ExtensionArray): + if isinstance(target_values, (BaseMaskedArray, ArrowExtensionArray)): + try: + return _masked_engines[target_values.dtype.name](target_values) + except KeyError: + # Not supported yet e.g. decimal + pass + elif self._engine_type is libindex.ObjectEngine: + return libindex.ExtensionEngine(target_values) + + target_values = cast(np.ndarray, target_values) + # to avoid a reference cycle, bind `target_values` to a local variable, so + # `self` is not passed into the lambda. + if target_values.dtype == bool: + return libindex.BoolEngine(target_values) + elif target_values.dtype == np.complex64: + return libindex.Complex64Engine(target_values) + elif target_values.dtype == np.complex128: + return libindex.Complex128Engine(target_values) + elif needs_i8_conversion(self.dtype): + # We need to keep M8/m8 dtype when initializing the Engine, + # but don't want to change _get_engine_target bc it is used + # elsewhere + # error: Item "ExtensionArray" of "Union[ExtensionArray, + # ndarray[Any, Any]]" has no attribute "_ndarray" [union-attr] + target_values = self._data._ndarray # type: ignore[union-attr] + elif is_string_dtype(self.dtype) and not is_object_dtype(self.dtype): + return libindex.StringObjectEngine(target_values, self.dtype.na_value) # type: ignore[union-attr] + + # error: Argument 1 to "ExtensionEngine" has incompatible type + # "ndarray[Any, Any]"; expected "ExtensionArray" + return self._engine_type(target_values) # type: ignore[arg-type] + + @final + @cache_readonly + def _dir_additions_for_owner(self) -> set[str_t]: + """ + Add the string-like labels to the owner dataframe/series dir output. + + If this is a MultiIndex, it's first level values are used. + """ + return { + c + for c in self.unique(level=0)[: get_option("display.max_dir_items")] + if isinstance(c, str) and c.isidentifier() + } + + # -------------------------------------------------------------------- + # Array-Like Methods + + # ndarray compat + def __len__(self) -> int: + """ + Return the length of the Index. + """ + return len(self._data) + + def __array__(self, dtype=None, copy=None) -> np.ndarray: + """ + The array interface, return my values. + """ + if copy is None: + # Note, that the if branch exists for NumPy 1.x support + return np.asarray(self._data, dtype=dtype) + + return np.array(self._data, dtype=dtype, copy=copy) + + def __array_ufunc__(self, ufunc: np.ufunc, method: str_t, *inputs, **kwargs): + if any(isinstance(other, (ABCSeries, ABCDataFrame)) for other in inputs): + return NotImplemented + + result = arraylike.maybe_dispatch_ufunc_to_dunder_op( + self, ufunc, method, *inputs, **kwargs + ) + if result is not NotImplemented: + return result + + if "out" in kwargs: + # e.g. test_dti_isub_tdi + return arraylike.dispatch_ufunc_with_out( + self, ufunc, method, *inputs, **kwargs + ) + + if method == "reduce": + result = arraylike.dispatch_reduction_ufunc( + self, ufunc, method, *inputs, **kwargs + ) + if result is not NotImplemented: + return result + + new_inputs = [x if x is not self else x._values for x in inputs] + result = getattr(ufunc, method)(*new_inputs, **kwargs) + if ufunc.nout == 2: + # i.e. np.divmod, np.modf, np.frexp + return tuple(self.__array_wrap__(x) for x in result) + elif method == "reduce": + result = lib.item_from_zerodim(result) + return result + + if result.dtype == np.float16: + result = result.astype(np.float32) + + return self.__array_wrap__(result) + + @final + def __array_wrap__(self, result, context=None, return_scalar=False): + """ + Gets called after a ufunc and other functions e.g. np.split. + """ + result = lib.item_from_zerodim(result) + if (not isinstance(result, Index) and is_bool_dtype(result.dtype)) or np.ndim( + result + ) > 1: + # exclude Index to avoid warning from is_bool_dtype deprecation; + # in the Index case it doesn't matter which path we go down. + # reached in plotting tests with e.g. np.nonzero(index) + return result + + return Index(result, name=self.name) + + @cache_readonly + def dtype(self) -> DtypeObj: + """ + Return the dtype object of the underlying data. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.dtype + dtype('int64') + """ + return self._data.dtype + + @final + def ravel(self, order: str_t = "C") -> Self: + """ + Return a view on self. + + Returns + ------- + Index + + See Also + -------- + numpy.ndarray.ravel : Return a flattened array. + + Examples + -------- + >>> s = pd.Series([1, 2, 3], index=['a', 'b', 'c']) + >>> s.index.ravel() + Index(['a', 'b', 'c'], dtype='object') + """ + return self[:] + + def view(self, cls=None): + # we need to see if we are subclassing an + # index type here + if cls is not None and not hasattr(cls, "_typ"): + dtype = cls + if isinstance(cls, str): + dtype = pandas_dtype(cls) + + if needs_i8_conversion(dtype): + idx_cls = self._dtype_to_subclass(dtype) + arr = self.array.view(dtype) + if isinstance(arr, ExtensionArray): + # here we exclude non-supported dt64/td64 dtypes + return idx_cls._simple_new( + arr, name=self.name, refs=self._references + ) + return arr + + result = self._data.view(cls) + else: + if cls is not None: + warnings.warn( + # GH#55709 + f"Passing a type in {type(self).__name__}.view is deprecated " + "and will raise in a future version. " + "Call view without any argument to retain the old behavior.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + result = self._view() + if isinstance(result, Index): + result._id = self._id + return result + + def astype(self, dtype, copy: bool = True): + """ + Create an Index with values cast to dtypes. + + The class of a new Index is determined by dtype. When conversion is + impossible, a TypeError exception is raised. + + Parameters + ---------- + dtype : numpy dtype or pandas type + Note that any signed integer `dtype` is treated as ``'int64'``, + and any unsigned integer `dtype` is treated as ``'uint64'``, + regardless of the size. + copy : bool, default True + By default, astype always returns a newly allocated object. + If copy is set to False and internal requirements on dtype are + satisfied, the original data is used to create a new Index + or the original Index is returned. + + Returns + ------- + Index + Index with values cast to specified dtype. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.astype('float') + Index([1.0, 2.0, 3.0], dtype='float64') + """ + if dtype is not None: + dtype = pandas_dtype(dtype) + + if self.dtype == dtype: + # Ensure that self.astype(self.dtype) is self + return self.copy() if copy else self + + values = self._data + if isinstance(values, ExtensionArray): + with rewrite_exception(type(values).__name__, type(self).__name__): + new_values = values.astype(dtype, copy=copy) + + elif isinstance(dtype, ExtensionDtype): + cls = dtype.construct_array_type() + # Note: for RangeIndex and CategoricalDtype self vs self._values + # behaves differently here. + new_values = cls._from_sequence(self, dtype=dtype, copy=copy) + + else: + # GH#13149 specifically use astype_array instead of astype + new_values = astype_array(values, dtype=dtype, copy=copy) + + # pass copy=False because any copying will be done in the astype above + result = Index(new_values, name=self.name, dtype=new_values.dtype, copy=False) + if ( + not copy + and self._references is not None + and astype_is_view(self.dtype, dtype) + ): + result._references = self._references + result._references.add_index_reference(result) + return result + + _index_shared_docs[ + "take" + ] = """ + Return a new %(klass)s of the values selected by the indices. + + For internal compatibility with numpy arrays. + + Parameters + ---------- + indices : array-like + Indices to be taken. + axis : int, optional + The axis over which to select values, always 0. + allow_fill : bool, default True + fill_value : scalar, default None + If allow_fill=True and fill_value is not None, indices specified by + -1 are regarded as NA. If Index doesn't hold NA, raise ValueError. + + Returns + ------- + Index + An index formed of elements at the given indices. Will be the same + type as self, except for RangeIndex. + + See Also + -------- + numpy.ndarray.take: Return an array formed from the + elements of a at the given indices. + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx.take([2, 2, 1, 2]) + Index(['c', 'c', 'b', 'c'], dtype='object') + """ + + @Appender(_index_shared_docs["take"] % _index_doc_kwargs) + def take( + self, + indices, + axis: Axis = 0, + allow_fill: bool = True, + fill_value=None, + **kwargs, + ) -> Self: + if kwargs: + nv.validate_take((), kwargs) + if is_scalar(indices): + raise TypeError("Expected indices to be array-like") + indices = ensure_platform_int(indices) + allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices) + + # Note: we discard fill_value and use self._na_value, only relevant + # in the case where allow_fill is True and fill_value is not None + values = self._values + if isinstance(values, np.ndarray): + taken = algos.take( + values, indices, allow_fill=allow_fill, fill_value=self._na_value + ) + else: + # algos.take passes 'axis' keyword which not all EAs accept + taken = values.take( + indices, allow_fill=allow_fill, fill_value=self._na_value + ) + return self._constructor._simple_new(taken, name=self.name) + + @final + def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool: + """ + We only use pandas-style take when allow_fill is True _and_ + fill_value is not None. + """ + if allow_fill and fill_value is not None: + # only fill if we are passing a non-None fill_value + if self._can_hold_na: + if (indices < -1).any(): + raise ValueError( + "When allow_fill=True and fill_value is not None, " + "all indices must be >= -1" + ) + else: + cls_name = type(self).__name__ + raise ValueError( + f"Unable to fill values because {cls_name} cannot contain NA" + ) + else: + allow_fill = False + return allow_fill + + _index_shared_docs[ + "repeat" + ] = """ + Repeat elements of a %(klass)s. + + Returns a new %(klass)s where each element of the current %(klass)s + is repeated consecutively a given number of times. + + Parameters + ---------- + repeats : int or array of ints + The number of repetitions for each element. This should be a + non-negative integer. Repeating 0 times will return an empty + %(klass)s. + axis : None + Must be ``None``. Has no effect but is accepted for compatibility + with numpy. + + Returns + ------- + %(klass)s + Newly created %(klass)s with repeated elements. + + See Also + -------- + Series.repeat : Equivalent function for Series. + numpy.repeat : Similar method for :class:`numpy.ndarray`. + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx + Index(['a', 'b', 'c'], dtype='object') + >>> idx.repeat(2) + Index(['a', 'a', 'b', 'b', 'c', 'c'], dtype='object') + >>> idx.repeat([1, 2, 3]) + Index(['a', 'b', 'b', 'c', 'c', 'c'], dtype='object') + """ + + @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) + def repeat(self, repeats, axis: None = None) -> Self: + repeats = ensure_platform_int(repeats) + nv.validate_repeat((), {"axis": axis}) + res_values = self._values.repeat(repeats) + + # _constructor so RangeIndex-> Index with an int64 dtype + return self._constructor._simple_new(res_values, name=self.name) + + # -------------------------------------------------------------------- + # Copying Methods + + def copy( + self, + name: Hashable | None = None, + deep: bool = False, + ) -> Self: + """ + Make a copy of this object. + + Name is set on the new object. + + Parameters + ---------- + name : Label, optional + Set name for new object. + deep : bool, default False + + Returns + ------- + Index + Index refer to new object which is a copy of this object. + + Notes + ----- + In most cases, there should be no functional difference from using + ``deep``, but if ``deep`` is passed it will attempt to deepcopy. + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'c']) + >>> new_idx = idx.copy() + >>> idx is new_idx + False + """ + + name = self._validate_names(name=name, deep=deep)[0] + if deep: + new_data = self._data.copy() + new_index = type(self)._simple_new(new_data, name=name) + else: + new_index = self._rename(name=name) + return new_index + + @final + def __copy__(self, **kwargs) -> Self: + return self.copy(**kwargs) + + @final + def __deepcopy__(self, memo=None) -> Self: + """ + Parameters + ---------- + memo, default None + Standard signature. Unused + """ + return self.copy(deep=True) + + # -------------------------------------------------------------------- + # Rendering Methods + + @final + def __repr__(self) -> str_t: + """ + Return a string representation for this object. + """ + klass_name = type(self).__name__ + data = self._format_data() + attrs = self._format_attrs() + attrs_str = [f"{k}={v}" for k, v in attrs] + prepr = ", ".join(attrs_str) + + return f"{klass_name}({data}{prepr})" + + @property + def _formatter_func(self): + """ + Return the formatter function. + """ + return default_pprint + + @final + def _format_data(self, name=None) -> str_t: + """ + Return the formatted data as a unicode string. + """ + # do we want to justify (only do so for non-objects) + is_justify = True + + if self.inferred_type == "string": + is_justify = False + elif isinstance(self.dtype, CategoricalDtype): + self = cast("CategoricalIndex", self) + if is_object_dtype(self.categories.dtype): + is_justify = False + elif isinstance(self, ABCRangeIndex): + # We will do the relevant formatting via attrs + return "" + + return format_object_summary( + self, + self._formatter_func, + is_justify=is_justify, + name=name, + line_break_each_value=self._is_multi, + ) + + def _format_attrs(self) -> list[tuple[str_t, str_t | int | bool | None]]: + """ + Return a list of tuples of the (attr,formatted_value). + """ + attrs: list[tuple[str_t, str_t | int | bool | None]] = [] + + if not self._is_multi: + attrs.append(("dtype", f"'{self.dtype}'")) + + if self.name is not None: + attrs.append(("name", default_pprint(self.name))) + elif self._is_multi and any(x is not None for x in self.names): + attrs.append(("names", default_pprint(self.names))) + + max_seq_items = get_option("display.max_seq_items") or len(self) + if len(self) > max_seq_items: + attrs.append(("length", len(self))) + return attrs + + @final + def _get_level_names(self) -> Hashable | Sequence[Hashable]: + """ + Return a name or list of names with None replaced by the level number. + """ + if self._is_multi: + return [ + level if name is None else name for level, name in enumerate(self.names) + ] + else: + return 0 if self.name is None else self.name + + @final + def _mpl_repr(self) -> np.ndarray: + # how to represent ourselves to matplotlib + if isinstance(self.dtype, np.dtype) and self.dtype.kind != "M": + return cast(np.ndarray, self.values) + return self.astype(object, copy=False)._values + + def format( + self, + name: bool = False, + formatter: Callable | None = None, + na_rep: str_t = "NaN", + ) -> list[str_t]: + """ + Render a string representation of the Index. + """ + warnings.warn( + # GH#55413 + f"{type(self).__name__}.format is deprecated and will be removed " + "in a future version. Convert using index.astype(str) or " + "index.map(formatter) instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + header = [] + if name: + header.append( + pprint_thing(self.name, escape_chars=("\t", "\r", "\n")) + if self.name is not None + else "" + ) + + if formatter is not None: + return header + list(self.map(formatter)) + + return self._format_with_header(header=header, na_rep=na_rep) + + _default_na_rep = "NaN" + + @final + def _format_flat( + self, + *, + include_name: bool, + formatter: Callable | None = None, + ) -> list[str_t]: + """ + Render a string representation of the Index. + """ + header = [] + if include_name: + header.append( + pprint_thing(self.name, escape_chars=("\t", "\r", "\n")) + if self.name is not None + else "" + ) + + if formatter is not None: + return header + list(self.map(formatter)) + + return self._format_with_header(header=header, na_rep=self._default_na_rep) + + def _format_with_header(self, *, header: list[str_t], na_rep: str_t) -> list[str_t]: + from pandas.io.formats.format import format_array + + values = self._values + + if ( + is_object_dtype(values.dtype) + or is_string_dtype(values.dtype) + or isinstance(self.dtype, (IntervalDtype, CategoricalDtype)) + ): + # TODO: why do we need different justify for these cases? + justify = "all" + else: + justify = "left" + # passing leading_space=False breaks test_format_missing, + # test_index_repr_in_frame_with_nan, but would otherwise make + # trim_front unnecessary + formatted = format_array(values, None, justify=justify) + result = trim_front(formatted) + return header + result + + def _get_values_for_csv( + self, + *, + na_rep: str_t = "", + decimal: str_t = ".", + float_format=None, + date_format=None, + quoting=None, + ) -> npt.NDArray[np.object_]: + return get_values_for_csv( + self._values, + na_rep=na_rep, + decimal=decimal, + float_format=float_format, + date_format=date_format, + quoting=quoting, + ) + + def _summary(self, name=None) -> str_t: + """ + Return a summarized representation. + + Parameters + ---------- + name : str + name to use in the summary representation + + Returns + ------- + String with a summarized representation of the index + """ + if len(self) > 0: + head = self[0] + if hasattr(head, "format") and not isinstance(head, str): + head = head.format() + elif needs_i8_conversion(self.dtype): + # e.g. Timedelta, display as values, not quoted + head = self._formatter_func(head).replace("'", "") + tail = self[-1] + if hasattr(tail, "format") and not isinstance(tail, str): + tail = tail.format() + elif needs_i8_conversion(self.dtype): + # e.g. Timedelta, display as values, not quoted + tail = self._formatter_func(tail).replace("'", "") + + index_summary = f", {head} to {tail}" + else: + index_summary = "" + + if name is None: + name = type(self).__name__ + return f"{name}: {len(self)} entries{index_summary}" + + # -------------------------------------------------------------------- + # Conversion Methods + + def to_flat_index(self) -> Self: + """ + Identity method. + + This is implemented for compatibility with subclass implementations + when chaining. + + Returns + ------- + pd.Index + Caller. + + See Also + -------- + MultiIndex.to_flat_index : Subclass implementation. + """ + return self + + @final + def to_series(self, index=None, name: Hashable | None = None) -> Series: + """ + Create a Series with both index and values equal to the index keys. + + Useful with map for returning an indexer based on an index. + + Parameters + ---------- + index : Index, optional + Index of resulting Series. If None, defaults to original index. + name : str, optional + Name of resulting Series. If None, defaults to name of original + index. + + Returns + ------- + Series + The dtype will be based on the type of the Index values. + + See Also + -------- + Index.to_frame : Convert an Index to a DataFrame. + Series.to_frame : Convert Series to DataFrame. + + Examples + -------- + >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') + + By default, the original index and original name is reused. + + >>> idx.to_series() + animal + Ant Ant + Bear Bear + Cow Cow + Name: animal, dtype: object + + To enforce a new index, specify new labels to ``index``: + + >>> idx.to_series(index=[0, 1, 2]) + 0 Ant + 1 Bear + 2 Cow + Name: animal, dtype: object + + To override the name of the resulting column, specify ``name``: + + >>> idx.to_series(name='zoo') + animal + Ant Ant + Bear Bear + Cow Cow + Name: zoo, dtype: object + """ + from pandas import Series + + if index is None: + index = self._view() + if name is None: + name = self.name + + return Series(self._values.copy(), index=index, name=name) + + def to_frame( + self, index: bool = True, name: Hashable = lib.no_default + ) -> DataFrame: + """ + Create a DataFrame with a column containing the Index. + + Parameters + ---------- + index : bool, default True + Set the index of the returned DataFrame as the original Index. + + name : object, defaults to index.name + The passed name should substitute for the index name (if it has + one). + + Returns + ------- + DataFrame + DataFrame containing the original Index data. + + See Also + -------- + Index.to_series : Convert an Index to a Series. + Series.to_frame : Convert Series to DataFrame. + + Examples + -------- + >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') + >>> idx.to_frame() + animal + animal + Ant Ant + Bear Bear + Cow Cow + + By default, the original Index is reused. To enforce a new Index: + + >>> idx.to_frame(index=False) + animal + 0 Ant + 1 Bear + 2 Cow + + To override the name of the resulting column, specify `name`: + + >>> idx.to_frame(index=False, name='zoo') + zoo + 0 Ant + 1 Bear + 2 Cow + """ + from pandas import DataFrame + + if name is lib.no_default: + name = self._get_level_names() + result = DataFrame({name: self}, copy=not using_copy_on_write()) + + if index: + result.index = self + return result + + # -------------------------------------------------------------------- + # Name-Centric Methods + + @property + def name(self) -> Hashable: + """ + Return Index or MultiIndex name. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3], name='x') + >>> idx + Index([1, 2, 3], dtype='int64', name='x') + >>> idx.name + 'x' + """ + return self._name + + @name.setter + def name(self, value: Hashable) -> None: + if self._no_setting_name: + # Used in MultiIndex.levels to avoid silently ignoring name updates. + raise RuntimeError( + "Cannot set name on a level of a MultiIndex. Use " + "'MultiIndex.set_names' instead." + ) + maybe_extract_name(value, None, type(self)) + self._name = value + + @final + def _validate_names( + self, name=None, names=None, deep: bool = False + ) -> list[Hashable]: + """ + Handles the quirks of having a singular 'name' parameter for general + Index and plural 'names' parameter for MultiIndex. + """ + from copy import deepcopy + + if names is not None and name is not None: + raise TypeError("Can only provide one of `names` and `name`") + if names is None and name is None: + new_names = deepcopy(self.names) if deep else self.names + elif names is not None: + if not is_list_like(names): + raise TypeError("Must pass list-like as `names`.") + new_names = names + elif not is_list_like(name): + new_names = [name] + else: + new_names = name + + if len(new_names) != len(self.names): + raise ValueError( + f"Length of new names must be {len(self.names)}, got {len(new_names)}" + ) + + # All items in 'new_names' need to be hashable + validate_all_hashable(*new_names, error_name=f"{type(self).__name__}.name") + + return new_names + + def _get_default_index_names( + self, names: Hashable | Sequence[Hashable] | None = None, default=None + ) -> list[Hashable]: + """ + Get names of index. + + Parameters + ---------- + names : int, str or 1-dimensional list, default None + Index names to set. + default : str + Default name of index. + + Raises + ------ + TypeError + if names not str or list-like + """ + from pandas.core.indexes.multi import MultiIndex + + if names is not None: + if isinstance(names, (int, str)): + names = [names] + + if not isinstance(names, list) and names is not None: + raise ValueError("Index names must be str or 1-dimensional list") + + if not names: + if isinstance(self, MultiIndex): + names = com.fill_missing_names(self.names) + else: + names = [default] if self.name is None else [self.name] + + return names + + def _get_names(self) -> FrozenList: + return FrozenList((self.name,)) + + def _set_names(self, values, *, level=None) -> None: + """ + Set new names on index. Each name has to be a hashable type. + + Parameters + ---------- + values : str or sequence + name(s) to set + level : int, level name, or sequence of int/level names (default None) + If the index is a MultiIndex (hierarchical), level(s) to set (None + for all levels). Otherwise level must be None + + Raises + ------ + TypeError if each name is not hashable. + """ + if not is_list_like(values): + raise ValueError("Names must be a list-like") + if len(values) != 1: + raise ValueError(f"Length of new names must be 1, got {len(values)}") + + # GH 20527 + # All items in 'name' need to be hashable: + validate_all_hashable(*values, error_name=f"{type(self).__name__}.name") + + self._name = values[0] + + names = property(fset=_set_names, fget=_get_names) + + @overload + def set_names(self, names, *, level=..., inplace: Literal[False] = ...) -> Self: + ... + + @overload + def set_names(self, names, *, level=..., inplace: Literal[True]) -> None: + ... + + @overload + def set_names(self, names, *, level=..., inplace: bool = ...) -> Self | None: + ... + + def set_names(self, names, *, level=None, inplace: bool = False) -> Self | None: + """ + Set Index or MultiIndex name. + + Able to set new names partially and by level. + + Parameters + ---------- + + names : label or list of label or dict-like for MultiIndex + Name(s) to set. + + .. versionchanged:: 1.3.0 + + level : int, label or list of int or label, optional + If the index is a MultiIndex and names is not dict-like, level(s) to set + (None for all levels). Otherwise level must be None. + + .. versionchanged:: 1.3.0 + + inplace : bool, default False + Modifies the object directly, instead of creating a new Index or + MultiIndex. + + Returns + ------- + Index or None + The same type as the caller or None if ``inplace=True``. + + See Also + -------- + Index.rename : Able to set new names without level. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3, 4]) + >>> idx + Index([1, 2, 3, 4], dtype='int64') + >>> idx.set_names('quarter') + Index([1, 2, 3, 4], dtype='int64', name='quarter') + + >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], + ... [2018, 2019]]) + >>> idx + MultiIndex([('python', 2018), + ('python', 2019), + ( 'cobra', 2018), + ( 'cobra', 2019)], + ) + >>> idx = idx.set_names(['kind', 'year']) + >>> idx.set_names('species', level=0) + MultiIndex([('python', 2018), + ('python', 2019), + ( 'cobra', 2018), + ( 'cobra', 2019)], + names=['species', 'year']) + + When renaming levels with a dict, levels can not be passed. + + >>> idx.set_names({'kind': 'snake'}) + MultiIndex([('python', 2018), + ('python', 2019), + ( 'cobra', 2018), + ( 'cobra', 2019)], + names=['snake', 'year']) + """ + if level is not None and not isinstance(self, ABCMultiIndex): + raise ValueError("Level must be None for non-MultiIndex") + + if level is not None and not is_list_like(level) and is_list_like(names): + raise TypeError("Names must be a string when a single level is provided.") + + if not is_list_like(names) and level is None and self.nlevels > 1: + raise TypeError("Must pass list-like as `names`.") + + if is_dict_like(names) and not isinstance(self, ABCMultiIndex): + raise TypeError("Can only pass dict-like as `names` for MultiIndex.") + + if is_dict_like(names) and level is not None: + raise TypeError("Can not pass level for dictlike `names`.") + + if isinstance(self, ABCMultiIndex) and is_dict_like(names) and level is None: + # Transform dict to list of new names and corresponding levels + level, names_adjusted = [], [] + for i, name in enumerate(self.names): + if name in names.keys(): + level.append(i) + names_adjusted.append(names[name]) + names = names_adjusted + + if not is_list_like(names): + names = [names] + if level is not None and not is_list_like(level): + level = [level] + + if inplace: + idx = self + else: + idx = self._view() + + idx._set_names(names, level=level) + if not inplace: + return idx + return None + + @overload + def rename(self, name, *, inplace: Literal[False] = ...) -> Self: + ... + + @overload + def rename(self, name, *, inplace: Literal[True]) -> None: + ... + + @deprecate_nonkeyword_arguments( + version="3.0", allowed_args=["self", "name"], name="rename" + ) + def rename(self, name, inplace: bool = False) -> Self | None: + """ + Alter Index or MultiIndex name. + + Able to set new names without level. Defaults to returning new index. + Length of names must match number of levels in MultiIndex. + + Parameters + ---------- + name : label or list of labels + Name(s) to set. + inplace : bool, default False + Modifies the object directly, instead of creating a new Index or + MultiIndex. + + Returns + ------- + Index or None + The same type as the caller or None if ``inplace=True``. + + See Also + -------- + Index.set_names : Able to set new names partially and by level. + + Examples + -------- + >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score') + >>> idx.rename('grade') + Index(['A', 'C', 'A', 'B'], dtype='object', name='grade') + + >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], + ... [2018, 2019]], + ... names=['kind', 'year']) + >>> idx + MultiIndex([('python', 2018), + ('python', 2019), + ( 'cobra', 2018), + ( 'cobra', 2019)], + names=['kind', 'year']) + >>> idx.rename(['species', 'year']) + MultiIndex([('python', 2018), + ('python', 2019), + ( 'cobra', 2018), + ( 'cobra', 2019)], + names=['species', 'year']) + >>> idx.rename('species') + Traceback (most recent call last): + TypeError: Must pass list-like as `names`. + """ + return self.set_names([name], inplace=inplace) + + # -------------------------------------------------------------------- + # Level-Centric Methods + + @property + def nlevels(self) -> int: + """ + Number of levels. + """ + return 1 + + def _sort_levels_monotonic(self) -> Self: + """ + Compat with MultiIndex. + """ + return self + + @final + def _validate_index_level(self, level) -> None: + """ + Validate index level. + + For single-level Index getting level number is a no-op, but some + verification must be done like in MultiIndex. + + """ + if isinstance(level, int): + if level < 0 and level != -1: + raise IndexError( + "Too many levels: Index has only 1 level, " + f"{level} is not a valid level number" + ) + if level > 0: + raise IndexError( + f"Too many levels: Index has only 1 level, not {level + 1}" + ) + elif level != self.name: + raise KeyError( + f"Requested level ({level}) does not match index name ({self.name})" + ) + + def _get_level_number(self, level) -> int: + self._validate_index_level(level) + return 0 + + def sortlevel( + self, + level=None, + ascending: bool | list[bool] = True, + sort_remaining=None, + na_position: NaPosition = "first", + ): + """ + For internal compatibility with the Index API. + + Sort the Index. This is for compat with MultiIndex + + Parameters + ---------- + ascending : bool, default True + False to sort in descending order + na_position : {'first' or 'last'}, default 'first' + Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at + the end. + + .. versionadded:: 2.1.0 + + level, sort_remaining are compat parameters + + Returns + ------- + Index + """ + if not isinstance(ascending, (list, bool)): + raise TypeError( + "ascending must be a single bool value or" + "a list of bool values of length 1" + ) + + if isinstance(ascending, list): + if len(ascending) != 1: + raise TypeError("ascending must be a list of bool values of length 1") + ascending = ascending[0] + + if not isinstance(ascending, bool): + raise TypeError("ascending must be a bool value") + + return self.sort_values( + return_indexer=True, ascending=ascending, na_position=na_position + ) + + def _get_level_values(self, level) -> Index: + """ + Return an Index of values for requested level. + + This is primarily useful to get an individual level of values from a + MultiIndex, but is provided on Index as well for compatibility. + + Parameters + ---------- + level : int or str + It is either the integer position or the name of the level. + + Returns + ------- + Index + Calling object, as there is only one level in the Index. + + See Also + -------- + MultiIndex.get_level_values : Get values for a level of a MultiIndex. + + Notes + ----- + For Index, level should be 0, since there are no multiple levels. + + Examples + -------- + >>> idx = pd.Index(list('abc')) + >>> idx + Index(['a', 'b', 'c'], dtype='object') + + Get level values by supplying `level` as integer: + + >>> idx.get_level_values(0) + Index(['a', 'b', 'c'], dtype='object') + """ + self._validate_index_level(level) + return self + + get_level_values = _get_level_values + + @final + def droplevel(self, level: IndexLabel = 0): + """ + Return index with requested level(s) removed. + + If resulting index has only 1 level left, the result will be + of Index type, not MultiIndex. The original index is not modified inplace. + + Parameters + ---------- + level : int, str, or list-like, default 0 + If a string is given, must be the name of a level + If list-like, elements must be names or indexes of levels. + + Returns + ------- + Index or MultiIndex + + Examples + -------- + >>> mi = pd.MultiIndex.from_arrays( + ... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z']) + >>> mi + MultiIndex([(1, 3, 5), + (2, 4, 6)], + names=['x', 'y', 'z']) + + >>> mi.droplevel() + MultiIndex([(3, 5), + (4, 6)], + names=['y', 'z']) + + >>> mi.droplevel(2) + MultiIndex([(1, 3), + (2, 4)], + names=['x', 'y']) + + >>> mi.droplevel('z') + MultiIndex([(1, 3), + (2, 4)], + names=['x', 'y']) + + >>> mi.droplevel(['x', 'y']) + Index([5, 6], dtype='int64', name='z') + """ + if not isinstance(level, (tuple, list)): + level = [level] + + levnums = sorted(self._get_level_number(lev) for lev in level)[::-1] + + return self._drop_level_numbers(levnums) + + @final + def _drop_level_numbers(self, levnums: list[int]): + """ + Drop MultiIndex levels by level _number_, not name. + """ + + if not levnums and not isinstance(self, ABCMultiIndex): + return self + if len(levnums) >= self.nlevels: + raise ValueError( + f"Cannot remove {len(levnums)} levels from an index with " + f"{self.nlevels} levels: at least one level must be left." + ) + # The two checks above guarantee that here self is a MultiIndex + self = cast("MultiIndex", self) + + new_levels = list(self.levels) + new_codes = list(self.codes) + new_names = list(self.names) + + for i in levnums: + new_levels.pop(i) + new_codes.pop(i) + new_names.pop(i) + + if len(new_levels) == 1: + lev = new_levels[0] + + if len(lev) == 0: + # If lev is empty, lev.take will fail GH#42055 + if len(new_codes[0]) == 0: + # GH#45230 preserve RangeIndex here + # see test_reset_index_empty_rangeindex + result = lev[:0] + else: + res_values = algos.take(lev._values, new_codes[0], allow_fill=True) + # _constructor instead of type(lev) for RangeIndex compat GH#35230 + result = lev._constructor._simple_new(res_values, name=new_names[0]) + else: + # set nan if needed + mask = new_codes[0] == -1 + result = new_levels[0].take(new_codes[0]) + if mask.any(): + result = result.putmask(mask, np.nan) + + result._name = new_names[0] + + return result + else: + from pandas.core.indexes.multi import MultiIndex + + return MultiIndex( + levels=new_levels, + codes=new_codes, + names=new_names, + verify_integrity=False, + ) + + # -------------------------------------------------------------------- + # Introspection Methods + + @cache_readonly + @final + def _can_hold_na(self) -> bool: + if isinstance(self.dtype, ExtensionDtype): + return self.dtype._can_hold_na + if self.dtype.kind in "iub": + return False + return True + + @property + def is_monotonic_increasing(self) -> bool: + """ + Return a boolean if the values are equal or increasing. + + Returns + ------- + bool + + See Also + -------- + Index.is_monotonic_decreasing : Check if the values are equal or decreasing. + + Examples + -------- + >>> pd.Index([1, 2, 3]).is_monotonic_increasing + True + >>> pd.Index([1, 2, 2]).is_monotonic_increasing + True + >>> pd.Index([1, 3, 2]).is_monotonic_increasing + False + """ + return self._engine.is_monotonic_increasing + + @property + def is_monotonic_decreasing(self) -> bool: + """ + Return a boolean if the values are equal or decreasing. + + Returns + ------- + bool + + See Also + -------- + Index.is_monotonic_increasing : Check if the values are equal or increasing. + + Examples + -------- + >>> pd.Index([3, 2, 1]).is_monotonic_decreasing + True + >>> pd.Index([3, 2, 2]).is_monotonic_decreasing + True + >>> pd.Index([3, 1, 2]).is_monotonic_decreasing + False + """ + return self._engine.is_monotonic_decreasing + + @final + @property + def _is_strictly_monotonic_increasing(self) -> bool: + """ + Return if the index is strictly monotonic increasing + (only increasing) values. + + Examples + -------- + >>> Index([1, 2, 3])._is_strictly_monotonic_increasing + True + >>> Index([1, 2, 2])._is_strictly_monotonic_increasing + False + >>> Index([1, 3, 2])._is_strictly_monotonic_increasing + False + """ + return self.is_unique and self.is_monotonic_increasing + + @final + @property + def _is_strictly_monotonic_decreasing(self) -> bool: + """ + Return if the index is strictly monotonic decreasing + (only decreasing) values. + + Examples + -------- + >>> Index([3, 2, 1])._is_strictly_monotonic_decreasing + True + >>> Index([3, 2, 2])._is_strictly_monotonic_decreasing + False + >>> Index([3, 1, 2])._is_strictly_monotonic_decreasing + False + """ + return self.is_unique and self.is_monotonic_decreasing + + @cache_readonly + def is_unique(self) -> bool: + """ + Return if the index has unique values. + + Returns + ------- + bool + + See Also + -------- + Index.has_duplicates : Inverse method that checks if it has duplicate values. + + Examples + -------- + >>> idx = pd.Index([1, 5, 7, 7]) + >>> idx.is_unique + False + + >>> idx = pd.Index([1, 5, 7]) + >>> idx.is_unique + True + + >>> idx = pd.Index(["Watermelon", "Orange", "Apple", + ... "Watermelon"]).astype("category") + >>> idx.is_unique + False + + >>> idx = pd.Index(["Orange", "Apple", + ... "Watermelon"]).astype("category") + >>> idx.is_unique + True + """ + return self._engine.is_unique + + @final + @property + def has_duplicates(self) -> bool: + """ + Check if the Index has duplicate values. + + Returns + ------- + bool + Whether or not the Index has duplicate values. + + See Also + -------- + Index.is_unique : Inverse method that checks if it has unique values. + + Examples + -------- + >>> idx = pd.Index([1, 5, 7, 7]) + >>> idx.has_duplicates + True + + >>> idx = pd.Index([1, 5, 7]) + >>> idx.has_duplicates + False + + >>> idx = pd.Index(["Watermelon", "Orange", "Apple", + ... "Watermelon"]).astype("category") + >>> idx.has_duplicates + True + + >>> idx = pd.Index(["Orange", "Apple", + ... "Watermelon"]).astype("category") + >>> idx.has_duplicates + False + """ + return not self.is_unique + + @final + def is_boolean(self) -> bool: + """ + Check if the Index only consists of booleans. + + .. deprecated:: 2.0.0 + Use `pandas.api.types.is_bool_dtype` instead. + + Returns + ------- + bool + Whether or not the Index only consists of booleans. + + See Also + -------- + is_integer : Check if the Index only consists of integers (deprecated). + is_floating : Check if the Index is a floating type (deprecated). + is_numeric : Check if the Index only consists of numeric data (deprecated). + is_object : Check if the Index is of the object dtype (deprecated). + is_categorical : Check if the Index holds categorical data. + is_interval : Check if the Index holds Interval objects (deprecated). + + Examples + -------- + >>> idx = pd.Index([True, False, True]) + >>> idx.is_boolean() # doctest: +SKIP + True + + >>> idx = pd.Index(["True", "False", "True"]) + >>> idx.is_boolean() # doctest: +SKIP + False + + >>> idx = pd.Index([True, False, "True"]) + >>> idx.is_boolean() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_boolean is deprecated. " + "Use pandas.api.types.is_bool_type instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.inferred_type in ["boolean"] + + @final + def is_integer(self) -> bool: + """ + Check if the Index only consists of integers. + + .. deprecated:: 2.0.0 + Use `pandas.api.types.is_integer_dtype` instead. + + Returns + ------- + bool + Whether or not the Index only consists of integers. + + See Also + -------- + is_boolean : Check if the Index only consists of booleans (deprecated). + is_floating : Check if the Index is a floating type (deprecated). + is_numeric : Check if the Index only consists of numeric data (deprecated). + is_object : Check if the Index is of the object dtype. (deprecated). + is_categorical : Check if the Index holds categorical data (deprecated). + is_interval : Check if the Index holds Interval objects (deprecated). + + Examples + -------- + >>> idx = pd.Index([1, 2, 3, 4]) + >>> idx.is_integer() # doctest: +SKIP + True + + >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) + >>> idx.is_integer() # doctest: +SKIP + False + + >>> idx = pd.Index(["Apple", "Mango", "Watermelon"]) + >>> idx.is_integer() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_integer is deprecated. " + "Use pandas.api.types.is_integer_dtype instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.inferred_type in ["integer"] + + @final + def is_floating(self) -> bool: + """ + Check if the Index is a floating type. + + .. deprecated:: 2.0.0 + Use `pandas.api.types.is_float_dtype` instead + + The Index may consist of only floats, NaNs, or a mix of floats, + integers, or NaNs. + + Returns + ------- + bool + Whether or not the Index only consists of only consists of floats, NaNs, or + a mix of floats, integers, or NaNs. + + See Also + -------- + is_boolean : Check if the Index only consists of booleans (deprecated). + is_integer : Check if the Index only consists of integers (deprecated). + is_numeric : Check if the Index only consists of numeric data (deprecated). + is_object : Check if the Index is of the object dtype. (deprecated). + is_categorical : Check if the Index holds categorical data (deprecated). + is_interval : Check if the Index holds Interval objects (deprecated). + + Examples + -------- + >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) + >>> idx.is_floating() # doctest: +SKIP + True + + >>> idx = pd.Index([1.0, 2.0, np.nan, 4.0]) + >>> idx.is_floating() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 2, 3, 4, np.nan]) + >>> idx.is_floating() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 2, 3, 4]) + >>> idx.is_floating() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_floating is deprecated. " + "Use pandas.api.types.is_float_dtype instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.inferred_type in ["floating", "mixed-integer-float", "integer-na"] + + @final + def is_numeric(self) -> bool: + """ + Check if the Index only consists of numeric data. + + .. deprecated:: 2.0.0 + Use `pandas.api.types.is_numeric_dtype` instead. + + Returns + ------- + bool + Whether or not the Index only consists of numeric data. + + See Also + -------- + is_boolean : Check if the Index only consists of booleans (deprecated). + is_integer : Check if the Index only consists of integers (deprecated). + is_floating : Check if the Index is a floating type (deprecated). + is_object : Check if the Index is of the object dtype. (deprecated). + is_categorical : Check if the Index holds categorical data (deprecated). + is_interval : Check if the Index holds Interval objects (deprecated). + + Examples + -------- + >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) + >>> idx.is_numeric() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 2, 3, 4.0]) + >>> idx.is_numeric() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 2, 3, 4]) + >>> idx.is_numeric() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 2, 3, 4.0, np.nan]) + >>> idx.is_numeric() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 2, 3, 4.0, np.nan, "Apple"]) + >>> idx.is_numeric() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_numeric is deprecated. " + "Use pandas.api.types.is_any_real_numeric_dtype instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.inferred_type in ["integer", "floating"] + + @final + def is_object(self) -> bool: + """ + Check if the Index is of the object dtype. + + .. deprecated:: 2.0.0 + Use `pandas.api.types.is_object_dtype` instead. + + Returns + ------- + bool + Whether or not the Index is of the object dtype. + + See Also + -------- + is_boolean : Check if the Index only consists of booleans (deprecated). + is_integer : Check if the Index only consists of integers (deprecated). + is_floating : Check if the Index is a floating type (deprecated). + is_numeric : Check if the Index only consists of numeric data (deprecated). + is_categorical : Check if the Index holds categorical data (deprecated). + is_interval : Check if the Index holds Interval objects (deprecated). + + Examples + -------- + >>> idx = pd.Index(["Apple", "Mango", "Watermelon"]) + >>> idx.is_object() # doctest: +SKIP + True + + >>> idx = pd.Index(["Apple", "Mango", 2.0]) + >>> idx.is_object() # doctest: +SKIP + True + + >>> idx = pd.Index(["Watermelon", "Orange", "Apple", + ... "Watermelon"]).astype("category") + >>> idx.is_object() # doctest: +SKIP + False + + >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) + >>> idx.is_object() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_object is deprecated." + "Use pandas.api.types.is_object_dtype instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + return is_object_dtype(self.dtype) + + @final + def is_categorical(self) -> bool: + """ + Check if the Index holds categorical data. + + .. deprecated:: 2.0.0 + Use `isinstance(index.dtype, pd.CategoricalDtype)` instead. + + Returns + ------- + bool + True if the Index is categorical. + + See Also + -------- + CategoricalIndex : Index for categorical data. + is_boolean : Check if the Index only consists of booleans (deprecated). + is_integer : Check if the Index only consists of integers (deprecated). + is_floating : Check if the Index is a floating type (deprecated). + is_numeric : Check if the Index only consists of numeric data (deprecated). + is_object : Check if the Index is of the object dtype. (deprecated). + is_interval : Check if the Index holds Interval objects (deprecated). + + Examples + -------- + >>> idx = pd.Index(["Watermelon", "Orange", "Apple", + ... "Watermelon"]).astype("category") + >>> idx.is_categorical() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 3, 5, 7]) + >>> idx.is_categorical() # doctest: +SKIP + False + + >>> s = pd.Series(["Peter", "Victor", "Elisabeth", "Mar"]) + >>> s + 0 Peter + 1 Victor + 2 Elisabeth + 3 Mar + dtype: object + >>> s.index.is_categorical() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_categorical is deprecated." + "Use pandas.api.types.is_categorical_dtype instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + + return self.inferred_type in ["categorical"] + + @final + def is_interval(self) -> bool: + """ + Check if the Index holds Interval objects. + + .. deprecated:: 2.0.0 + Use `isinstance(index.dtype, pd.IntervalDtype)` instead. + + Returns + ------- + bool + Whether or not the Index holds Interval objects. + + See Also + -------- + IntervalIndex : Index for Interval objects. + is_boolean : Check if the Index only consists of booleans (deprecated). + is_integer : Check if the Index only consists of integers (deprecated). + is_floating : Check if the Index is a floating type (deprecated). + is_numeric : Check if the Index only consists of numeric data (deprecated). + is_object : Check if the Index is of the object dtype. (deprecated). + is_categorical : Check if the Index holds categorical data (deprecated). + + Examples + -------- + >>> idx = pd.Index([pd.Interval(left=0, right=5), + ... pd.Interval(left=5, right=10)]) + >>> idx.is_interval() # doctest: +SKIP + True + + >>> idx = pd.Index([1, 3, 5, 7]) + >>> idx.is_interval() # doctest: +SKIP + False + """ + warnings.warn( + f"{type(self).__name__}.is_interval is deprecated." + "Use pandas.api.types.is_interval_dtype instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.inferred_type in ["interval"] + + @final + def _holds_integer(self) -> bool: + """ + Whether the type is an integer type. + """ + return self.inferred_type in ["integer", "mixed-integer"] + + @final + def holds_integer(self) -> bool: + """ + Whether the type is an integer type. + + .. deprecated:: 2.0.0 + Use `pandas.api.types.infer_dtype` instead + """ + warnings.warn( + f"{type(self).__name__}.holds_integer is deprecated. " + "Use pandas.api.types.infer_dtype instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self._holds_integer() + + @cache_readonly + def inferred_type(self) -> str_t: + """ + Return a string of the type inferred from the values. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.inferred_type + 'integer' + """ + return lib.infer_dtype(self._values, skipna=False) + + @cache_readonly + @final + def _is_all_dates(self) -> bool: + """ + Whether or not the index values only consist of dates. + """ + if needs_i8_conversion(self.dtype): + return True + elif self.dtype != _dtype_obj: + # TODO(ExtensionIndex): 3rd party EA might override? + # Note: this includes IntervalIndex, even when the left/right + # contain datetime-like objects. + return False + elif self._is_multi: + return False + return is_datetime_array(ensure_object(self._values)) + + @final + @cache_readonly + def _is_multi(self) -> bool: + """ + Cached check equivalent to isinstance(self, MultiIndex) + """ + return isinstance(self, ABCMultiIndex) + + # -------------------------------------------------------------------- + # Pickle Methods + + def __reduce__(self): + d = {"data": self._data, "name": self.name} + return _new_Index, (type(self), d), None + + # -------------------------------------------------------------------- + # Null Handling Methods + + @cache_readonly + def _na_value(self): + """The expected NA value to use with this index.""" + dtype = self.dtype + if isinstance(dtype, np.dtype): + if dtype.kind in "mM": + return NaT + return np.nan + return dtype.na_value + + @cache_readonly + def _isnan(self) -> npt.NDArray[np.bool_]: + """ + Return if each value is NaN. + """ + if self._can_hold_na: + return isna(self) + else: + # shouldn't reach to this condition by checking hasnans beforehand + values = np.empty(len(self), dtype=np.bool_) + values.fill(False) + return values + + @cache_readonly + def hasnans(self) -> bool: + """ + Return True if there are any NaNs. + + Enables various performance speedups. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 3], index=['a', 'b', None]) + >>> s + a 1 + b 2 + None 3 + dtype: int64 + >>> s.index.hasnans + True + """ + if self._can_hold_na: + return bool(self._isnan.any()) + else: + return False + + @final + def isna(self) -> npt.NDArray[np.bool_]: + """ + Detect missing values. + + Return a boolean same-sized object indicating if the values are NA. + NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get + mapped to ``True`` values. + Everything else get mapped to ``False`` values. Characters such as + empty strings `''` or :attr:`numpy.inf` are not considered NA values. + + Returns + ------- + numpy.ndarray[bool] + A boolean array of whether my values are NA. + + See Also + -------- + Index.notna : Boolean inverse of isna. + Index.dropna : Omit entries with missing values. + isna : Top-level isna. + Series.isna : Detect missing values in Series object. + + Examples + -------- + Show which entries in a pandas.Index are NA. The result is an + array. + + >>> idx = pd.Index([5.2, 6.0, np.nan]) + >>> idx + Index([5.2, 6.0, nan], dtype='float64') + >>> idx.isna() + array([False, False, True]) + + Empty strings are not considered NA values. None is considered an NA + value. + + >>> idx = pd.Index(['black', '', 'red', None]) + >>> idx + Index(['black', '', 'red', None], dtype='object') + >>> idx.isna() + array([False, False, False, True]) + + For datetimes, `NaT` (Not a Time) is considered as an NA value. + + >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'), + ... pd.Timestamp(''), None, pd.NaT]) + >>> idx + DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'], + dtype='datetime64[ns]', freq=None) + >>> idx.isna() + array([False, True, True, True]) + """ + return self._isnan + + isnull = isna + + @final + def notna(self) -> npt.NDArray[np.bool_]: + """ + Detect existing (non-missing) values. + + Return a boolean same-sized object indicating if the values are not NA. + Non-missing values get mapped to ``True``. Characters such as empty + strings ``''`` or :attr:`numpy.inf` are not considered NA values. + NA values, such as None or :attr:`numpy.NaN`, get mapped to ``False`` + values. + + Returns + ------- + numpy.ndarray[bool] + Boolean array to indicate which entries are not NA. + + See Also + -------- + Index.notnull : Alias of notna. + Index.isna: Inverse of notna. + notna : Top-level notna. + + Examples + -------- + Show which entries in an Index are not NA. The result is an + array. + + >>> idx = pd.Index([5.2, 6.0, np.nan]) + >>> idx + Index([5.2, 6.0, nan], dtype='float64') + >>> idx.notna() + array([ True, True, False]) + + Empty strings are not considered NA values. None is considered a NA + value. + + >>> idx = pd.Index(['black', '', 'red', None]) + >>> idx + Index(['black', '', 'red', None], dtype='object') + >>> idx.notna() + array([ True, True, True, False]) + """ + return ~self.isna() + + notnull = notna + + def fillna(self, value=None, downcast=lib.no_default): + """ + Fill NA/NaN values with the specified value. + + Parameters + ---------- + value : scalar + Scalar value to use to fill holes (e.g. 0). + This value cannot be a list-likes. + downcast : dict, default is None + A dict of item->dtype of what to downcast if possible, + or the string 'infer' which will try to downcast to an appropriate + equal type (e.g. float64 to int64 if possible). + + .. deprecated:: 2.1.0 + + Returns + ------- + Index + + See Also + -------- + DataFrame.fillna : Fill NaN values of a DataFrame. + Series.fillna : Fill NaN Values of a Series. + + Examples + -------- + >>> idx = pd.Index([np.nan, np.nan, 3]) + >>> idx.fillna(0) + Index([0.0, 0.0, 3.0], dtype='float64') + """ + if not is_scalar(value): + raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}") + if downcast is not lib.no_default: + warnings.warn( + f"The 'downcast' keyword in {type(self).__name__}.fillna is " + "deprecated and will be removed in a future version. " + "It was previously silently ignored.", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + downcast = None + + if self.hasnans: + result = self.putmask(self._isnan, value) + if downcast is None: + # no need to care metadata other than name + # because it can't have freq if it has NaTs + # _with_infer needed for test_fillna_categorical + return Index._with_infer(result, name=self.name) + raise NotImplementedError( + f"{type(self).__name__}.fillna does not support 'downcast' " + "argument values other than 'None'." + ) + return self._view() + + def dropna(self, how: AnyAll = "any") -> Self: + """ + Return Index without NA/NaN values. + + Parameters + ---------- + how : {'any', 'all'}, default 'any' + If the Index is a MultiIndex, drop the value when any or all levels + are NaN. + + Returns + ------- + Index + + Examples + -------- + >>> idx = pd.Index([1, np.nan, 3]) + >>> idx.dropna() + Index([1.0, 3.0], dtype='float64') + """ + if how not in ("any", "all"): + raise ValueError(f"invalid how option: {how}") + + if self.hasnans: + res_values = self._values[~self._isnan] + return type(self)._simple_new(res_values, name=self.name) + return self._view() + + # -------------------------------------------------------------------- + # Uniqueness Methods + + def unique(self, level: Hashable | None = None) -> Self: + """ + Return unique values in the index. + + Unique values are returned in order of appearance, this does NOT sort. + + Parameters + ---------- + level : int or hashable, optional + Only return values from specified level (for MultiIndex). + If int, gets the level by integer position, else by level name. + + Returns + ------- + Index + + See Also + -------- + unique : Numpy array of unique values in that column. + Series.unique : Return unique values of Series object. + + Examples + -------- + >>> idx = pd.Index([1, 1, 2, 3, 3]) + >>> idx.unique() + Index([1, 2, 3], dtype='int64') + """ + if level is not None: + self._validate_index_level(level) + + if self.is_unique: + return self._view() + + result = super().unique() + return self._shallow_copy(result) + + def drop_duplicates(self, *, keep: DropKeep = "first") -> Self: + """ + Return Index with duplicate values removed. + + Parameters + ---------- + keep : {'first', 'last', ``False``}, default 'first' + - 'first' : Drop duplicates except for the first occurrence. + - 'last' : Drop duplicates except for the last occurrence. + - ``False`` : Drop all duplicates. + + Returns + ------- + Index + + See Also + -------- + Series.drop_duplicates : Equivalent method on Series. + DataFrame.drop_duplicates : Equivalent method on DataFrame. + Index.duplicated : Related method on Index, indicating duplicate + Index values. + + Examples + -------- + Generate an pandas.Index with duplicate values. + + >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo']) + + The `keep` parameter controls which duplicate values are removed. + The value 'first' keeps the first occurrence for each + set of duplicated entries. The default value of keep is 'first'. + + >>> idx.drop_duplicates(keep='first') + Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object') + + The value 'last' keeps the last occurrence for each set of duplicated + entries. + + >>> idx.drop_duplicates(keep='last') + Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object') + + The value ``False`` discards all sets of duplicated entries. + + >>> idx.drop_duplicates(keep=False) + Index(['cow', 'beetle', 'hippo'], dtype='object') + """ + if self.is_unique: + return self._view() + + return super().drop_duplicates(keep=keep) + + def duplicated(self, keep: DropKeep = "first") -> npt.NDArray[np.bool_]: + """ + Indicate duplicate index values. + + Duplicated values are indicated as ``True`` values in the resulting + array. Either all duplicates, all except the first, or all except the + last occurrence of duplicates can be indicated. + + Parameters + ---------- + keep : {'first', 'last', False}, default 'first' + The value or values in a set of duplicates to mark as missing. + + - 'first' : Mark duplicates as ``True`` except for the first + occurrence. + - 'last' : Mark duplicates as ``True`` except for the last + occurrence. + - ``False`` : Mark all duplicates as ``True``. + + Returns + ------- + np.ndarray[bool] + + See Also + -------- + Series.duplicated : Equivalent method on pandas.Series. + DataFrame.duplicated : Equivalent method on pandas.DataFrame. + Index.drop_duplicates : Remove duplicate values from Index. + + Examples + -------- + By default, for each set of duplicated values, the first occurrence is + set to False and all others to True: + + >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama']) + >>> idx.duplicated() + array([False, False, True, False, True]) + + which is equivalent to + + >>> idx.duplicated(keep='first') + array([False, False, True, False, True]) + + By using 'last', the last occurrence of each set of duplicated values + is set on False and all others on True: + + >>> idx.duplicated(keep='last') + array([ True, False, True, False, False]) + + By setting keep on ``False``, all duplicates are True: + + >>> idx.duplicated(keep=False) + array([ True, False, True, False, True]) + """ + if self.is_unique: + # fastpath available bc we are immutable + return np.zeros(len(self), dtype=bool) + return self._duplicated(keep=keep) + + # -------------------------------------------------------------------- + # Arithmetic & Logical Methods + + def __iadd__(self, other): + # alias for __add__ + return self + other + + @final + def __nonzero__(self) -> NoReturn: + raise ValueError( + f"The truth value of a {type(self).__name__} is ambiguous. " + "Use a.empty, a.bool(), a.item(), a.any() or a.all()." + ) + + __bool__ = __nonzero__ + + # -------------------------------------------------------------------- + # Set Operation Methods + + def _get_reconciled_name_object(self, other): + """ + If the result of a set operation will be self, + return self, unless the name changes, in which + case make a shallow copy of self. + """ + name = get_op_result_name(self, other) + if self.name is not name: + return self.rename(name) + return self + + @final + def _validate_sort_keyword(self, sort): + if sort not in [None, False, True]: + raise ValueError( + "The 'sort' keyword only takes the values of " + f"None, True, or False; {sort} was passed." + ) + + @final + def _dti_setop_align_tzs(self, other: Index, setop: str_t) -> tuple[Index, Index]: + """ + With mismatched timezones, cast both to UTC. + """ + # Caller is responsibelf or checking + # `self.dtype != other.dtype` + if ( + isinstance(self, ABCDatetimeIndex) + and isinstance(other, ABCDatetimeIndex) + and self.tz is not None + and other.tz is not None + ): + # GH#39328, GH#45357 + left = self.tz_convert("UTC") + right = other.tz_convert("UTC") + return left, right + return self, other + + @final + def union(self, other, sort=None): + """ + Form the union of two Index objects. + + If the Index objects are incompatible, both Index objects will be + cast to dtype('object') first. + + Parameters + ---------- + other : Index or array-like + sort : bool or None, default None + Whether to sort the resulting Index. + + * None : Sort the result, except when + + 1. `self` and `other` are equal. + 2. `self` or `other` has length 0. + 3. Some values in `self` or `other` cannot be compared. + A RuntimeWarning is issued in this case. + + * False : do not sort the result. + * True : Sort the result (which may raise TypeError). + + Returns + ------- + Index + + Examples + -------- + Union matching dtypes + + >>> idx1 = pd.Index([1, 2, 3, 4]) + >>> idx2 = pd.Index([3, 4, 5, 6]) + >>> idx1.union(idx2) + Index([1, 2, 3, 4, 5, 6], dtype='int64') + + Union mismatched dtypes + + >>> idx1 = pd.Index(['a', 'b', 'c', 'd']) + >>> idx2 = pd.Index([1, 2, 3, 4]) + >>> idx1.union(idx2) + Index(['a', 'b', 'c', 'd', 1, 2, 3, 4], dtype='object') + + MultiIndex case + + >>> idx1 = pd.MultiIndex.from_arrays( + ... [[1, 1, 2, 2], ["Red", "Blue", "Red", "Blue"]] + ... ) + >>> idx1 + MultiIndex([(1, 'Red'), + (1, 'Blue'), + (2, 'Red'), + (2, 'Blue')], + ) + >>> idx2 = pd.MultiIndex.from_arrays( + ... [[3, 3, 2, 2], ["Red", "Green", "Red", "Green"]] + ... ) + >>> idx2 + MultiIndex([(3, 'Red'), + (3, 'Green'), + (2, 'Red'), + (2, 'Green')], + ) + >>> idx1.union(idx2) + MultiIndex([(1, 'Blue'), + (1, 'Red'), + (2, 'Blue'), + (2, 'Green'), + (2, 'Red'), + (3, 'Green'), + (3, 'Red')], + ) + >>> idx1.union(idx2, sort=False) + MultiIndex([(1, 'Red'), + (1, 'Blue'), + (2, 'Red'), + (2, 'Blue'), + (3, 'Red'), + (3, 'Green'), + (2, 'Green')], + ) + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_name = self._convert_can_do_setop(other) + + if self.dtype != other.dtype: + if ( + isinstance(self, ABCMultiIndex) + and not is_object_dtype(_unpack_nested_dtype(other)) + and len(other) > 0 + ): + raise NotImplementedError( + "Can only union MultiIndex with MultiIndex or Index of tuples, " + "try mi.to_flat_index().union(other) instead." + ) + self, other = self._dti_setop_align_tzs(other, "union") + + dtype = self._find_common_type_compat(other) + left = self.astype(dtype, copy=False) + right = other.astype(dtype, copy=False) + return left.union(right, sort=sort) + + elif not len(other) or self.equals(other): + # NB: whether this (and the `if not len(self)` check below) come before + # or after the dtype equality check above affects the returned dtype + result = self._get_reconciled_name_object(other) + if sort is True: + return result.sort_values() + return result + + elif not len(self): + result = other._get_reconciled_name_object(self) + if sort is True: + return result.sort_values() + return result + + result = self._union(other, sort=sort) + + return self._wrap_setop_result(other, result) + + def _union(self, other: Index, sort: bool | None): + """ + Specific union logic should go here. In subclasses, union behavior + should be overwritten here rather than in `self.union`. + + Parameters + ---------- + other : Index or array-like + sort : False or None, default False + Whether to sort the resulting index. + + * True : sort the result + * False : do not sort the result. + * None : sort the result, except when `self` and `other` are equal + or when the values cannot be compared. + + Returns + ------- + Index + """ + lvals = self._values + rvals = other._values + + if ( + sort in (None, True) + and self.is_monotonic_increasing + and other.is_monotonic_increasing + and not (self.has_duplicates and other.has_duplicates) + and self._can_use_libjoin + and other._can_use_libjoin + ): + # Both are monotonic and at least one is unique, so can use outer join + # (actually don't need either unique, but without this restriction + # test_union_same_value_duplicated_in_both fails) + try: + return self._outer_indexer(other)[0] + except (TypeError, IncompatibleFrequency): + # incomparable objects; should only be for object dtype + value_list = list(lvals) + + # worth making this faster? a very unusual case + value_set = set(lvals) + value_list.extend([x for x in rvals if x not in value_set]) + # If objects are unorderable, we must have object dtype. + return np.array(value_list, dtype=object) + + elif not other.is_unique: + # other has duplicates + result_dups = algos.union_with_duplicates(self, other) + return _maybe_try_sort(result_dups, sort) + + # The rest of this method is analogous to Index._intersection_via_get_indexer + + # Self may have duplicates; other already checked as unique + # find indexes of things in "other" that are not in "self" + if self._index_as_unique: + indexer = self.get_indexer(other) + missing = (indexer == -1).nonzero()[0] + else: + missing = algos.unique1d(self.get_indexer_non_unique(other)[1]) + + result: Index | MultiIndex | ArrayLike + if self._is_multi: + # Preserve MultiIndex to avoid losing dtypes + result = self.append(other.take(missing)) + + else: + if len(missing) > 0: + other_diff = rvals.take(missing) + result = concat_compat((lvals, other_diff)) + else: + result = lvals + + if not self.is_monotonic_increasing or not other.is_monotonic_increasing: + # if both are monotonic then result should already be sorted + result = _maybe_try_sort(result, sort) + + return result + + @final + def _wrap_setop_result(self, other: Index, result) -> Index: + name = get_op_result_name(self, other) + if isinstance(result, Index): + if result.name != name: + result = result.rename(name) + else: + result = self._shallow_copy(result, name=name) + return result + + @final + def intersection(self, other, sort: bool = False): + # default sort keyword is different here from other setops intentionally + # done in GH#25063 + """ + Form the intersection of two Index objects. + + This returns a new Index with elements common to the index and `other`. + + Parameters + ---------- + other : Index or array-like + sort : True, False or None, default False + Whether to sort the resulting index. + + * None : sort the result, except when `self` and `other` are equal + or when the values cannot be compared. + * False : do not sort the result. + * True : Sort the result (which may raise TypeError). + + Returns + ------- + Index + + Examples + -------- + >>> idx1 = pd.Index([1, 2, 3, 4]) + >>> idx2 = pd.Index([3, 4, 5, 6]) + >>> idx1.intersection(idx2) + Index([3, 4], dtype='int64') + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_name = self._convert_can_do_setop(other) + + if self.dtype != other.dtype: + self, other = self._dti_setop_align_tzs(other, "intersection") + + if self.equals(other): + if not self.is_unique: + result = self.unique()._get_reconciled_name_object(other) + else: + result = self._get_reconciled_name_object(other) + if sort is True: + result = result.sort_values() + return result + + if len(self) == 0 or len(other) == 0: + # fastpath; we need to be careful about having commutativity + + if self._is_multi or other._is_multi: + # _convert_can_do_setop ensures that we have both or neither + # We retain self.levels + return self[:0].rename(result_name) + + dtype = self._find_common_type_compat(other) + if self.dtype == dtype: + # Slicing allows us to retain DTI/TDI.freq, RangeIndex + + # Note: self[:0] vs other[:0] affects + # 1) which index's `freq` we get in DTI/TDI cases + # This may be a historical artifact, i.e. no documented + # reason for this choice. + # 2) The `step` we get in RangeIndex cases + if len(self) == 0: + return self[:0].rename(result_name) + else: + return other[:0].rename(result_name) + + return Index([], dtype=dtype, name=result_name) + + elif not self._should_compare(other): + # We can infer that the intersection is empty. + if isinstance(self, ABCMultiIndex): + return self[:0].rename(result_name) + return Index([], name=result_name) + + elif self.dtype != other.dtype: + dtype = self._find_common_type_compat(other) + this = self.astype(dtype, copy=False) + other = other.astype(dtype, copy=False) + return this.intersection(other, sort=sort) + + result = self._intersection(other, sort=sort) + return self._wrap_intersection_result(other, result) + + def _intersection(self, other: Index, sort: bool = False): + """ + intersection specialized to the case with matching dtypes. + """ + if ( + self.is_monotonic_increasing + and other.is_monotonic_increasing + and self._can_use_libjoin + and other._can_use_libjoin + ): + try: + res_indexer, indexer, _ = self._inner_indexer(other) + except TypeError: + # non-comparable; should only be for object dtype + pass + else: + # TODO: algos.unique1d should preserve DTA/TDA + if is_numeric_dtype(self.dtype): + # This is faster, because Index.unique() checks for uniqueness + # before calculating the unique values. + res = algos.unique1d(res_indexer) + else: + result = self.take(indexer) + res = result.drop_duplicates() + return ensure_wrapped_if_datetimelike(res) + + res_values = self._intersection_via_get_indexer(other, sort=sort) + res_values = _maybe_try_sort(res_values, sort) + return res_values + + def _wrap_intersection_result(self, other, result): + # We will override for MultiIndex to handle empty results + return self._wrap_setop_result(other, result) + + @final + def _intersection_via_get_indexer( + self, other: Index | MultiIndex, sort + ) -> ArrayLike | MultiIndex: + """ + Find the intersection of two Indexes using get_indexer. + + Returns + ------- + np.ndarray or ExtensionArray or MultiIndex + The returned array will be unique. + """ + left_unique = self.unique() + right_unique = other.unique() + + # even though we are unique, we need get_indexer_for for IntervalIndex + indexer = left_unique.get_indexer_for(right_unique) + + mask = indexer != -1 + + taker = indexer.take(mask.nonzero()[0]) + if sort is False: + # sort bc we want the elements in the same order they are in self + # unnecessary in the case with sort=None bc we will sort later + taker = np.sort(taker) + + result: MultiIndex | ExtensionArray | np.ndarray + if isinstance(left_unique, ABCMultiIndex): + result = left_unique.take(taker) + else: + result = left_unique.take(taker)._values + return result + + @final + def difference(self, other, sort=None): + """ + Return a new Index with elements of index not in `other`. + + This is the set difference of two Index objects. + + Parameters + ---------- + other : Index or array-like + sort : bool or None, default None + Whether to sort the resulting index. By default, the + values are attempted to be sorted, but any TypeError from + incomparable elements is caught by pandas. + + * None : Attempt to sort the result, but catch any TypeErrors + from comparing incomparable elements. + * False : Do not sort the result. + * True : Sort the result (which may raise TypeError). + + Returns + ------- + Index + + Examples + -------- + >>> idx1 = pd.Index([2, 1, 3, 4]) + >>> idx2 = pd.Index([3, 4, 5, 6]) + >>> idx1.difference(idx2) + Index([1, 2], dtype='int64') + >>> idx1.difference(idx2, sort=False) + Index([2, 1], dtype='int64') + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_name = self._convert_can_do_setop(other) + + # Note: we do NOT call _dti_setop_align_tzs here, as there + # is no requirement that .difference be commutative, so it does + # not cast to object. + + if self.equals(other): + # Note: we do not (yet) sort even if sort=None GH#24959 + return self[:0].rename(result_name) + + if len(other) == 0: + # Note: we do not (yet) sort even if sort=None GH#24959 + result = self.unique().rename(result_name) + if sort is True: + return result.sort_values() + return result + + if not self._should_compare(other): + # Nothing matches -> difference is everything + result = self.unique().rename(result_name) + if sort is True: + return result.sort_values() + return result + + result = self._difference(other, sort=sort) + return self._wrap_difference_result(other, result) + + def _difference(self, other, sort): + # overridden by RangeIndex + this = self + if isinstance(self, ABCCategoricalIndex) and self.hasnans and other.hasnans: + this = this.dropna() + other = other.unique() + the_diff = this[other.get_indexer_for(this) == -1] + the_diff = the_diff if this.is_unique else the_diff.unique() + the_diff = _maybe_try_sort(the_diff, sort) + return the_diff + + def _wrap_difference_result(self, other, result): + # We will override for MultiIndex to handle empty results + return self._wrap_setop_result(other, result) + + def symmetric_difference(self, other, result_name=None, sort=None): + """ + Compute the symmetric difference of two Index objects. + + Parameters + ---------- + other : Index or array-like + result_name : str + sort : bool or None, default None + Whether to sort the resulting index. By default, the + values are attempted to be sorted, but any TypeError from + incomparable elements is caught by pandas. + + * None : Attempt to sort the result, but catch any TypeErrors + from comparing incomparable elements. + * False : Do not sort the result. + * True : Sort the result (which may raise TypeError). + + Returns + ------- + Index + + Notes + ----- + ``symmetric_difference`` contains elements that appear in either + ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by + ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates + dropped. + + Examples + -------- + >>> idx1 = pd.Index([1, 2, 3, 4]) + >>> idx2 = pd.Index([2, 3, 4, 5]) + >>> idx1.symmetric_difference(idx2) + Index([1, 5], dtype='int64') + """ + self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_name_update = self._convert_can_do_setop(other) + if result_name is None: + result_name = result_name_update + + if self.dtype != other.dtype: + self, other = self._dti_setop_align_tzs(other, "symmetric_difference") + + if not self._should_compare(other): + return self.union(other, sort=sort).rename(result_name) + + elif self.dtype != other.dtype: + dtype = self._find_common_type_compat(other) + this = self.astype(dtype, copy=False) + that = other.astype(dtype, copy=False) + return this.symmetric_difference(that, sort=sort).rename(result_name) + + this = self.unique() + other = other.unique() + indexer = this.get_indexer_for(other) + + # {this} minus {other} + common_indexer = indexer.take((indexer != -1).nonzero()[0]) + left_indexer = np.setdiff1d( + np.arange(this.size), common_indexer, assume_unique=True + ) + left_diff = this.take(left_indexer) + + # {other} minus {this} + right_indexer = (indexer == -1).nonzero()[0] + right_diff = other.take(right_indexer) + + res_values = left_diff.append(right_diff) + result = _maybe_try_sort(res_values, sort) + + if not self._is_multi: + return Index(result, name=result_name, dtype=res_values.dtype) + else: + left_diff = cast("MultiIndex", left_diff) + if len(result) == 0: + # result might be an Index, if other was an Index + return left_diff.remove_unused_levels().set_names(result_name) + return result.set_names(result_name) + + @final + def _assert_can_do_setop(self, other) -> bool: + if not is_list_like(other): + raise TypeError("Input must be Index or array-like") + return True + + def _convert_can_do_setop(self, other) -> tuple[Index, Hashable]: + if not isinstance(other, Index): + other = Index(other, name=self.name) + result_name = self.name + else: + result_name = get_op_result_name(self, other) + return other, result_name + + # -------------------------------------------------------------------- + # Indexing Methods + + def get_loc(self, key): + """ + Get integer location, slice or boolean mask for requested label. + + Parameters + ---------- + key : label + + Returns + ------- + int if unique index, slice if monotonic index, else mask + + Examples + -------- + >>> unique_index = pd.Index(list('abc')) + >>> unique_index.get_loc('b') + 1 + + >>> monotonic_index = pd.Index(list('abbc')) + >>> monotonic_index.get_loc('b') + slice(1, 3, None) + + >>> non_monotonic_index = pd.Index(list('abcb')) + >>> non_monotonic_index.get_loc('b') + array([False, True, False, True]) + """ + casted_key = self._maybe_cast_indexer(key) + try: + return self._engine.get_loc(casted_key) + except KeyError as err: + if isinstance(casted_key, slice) or ( + isinstance(casted_key, abc.Iterable) + and any(isinstance(x, slice) for x in casted_key) + ): + raise InvalidIndexError(key) + raise KeyError(key) from err + except TypeError: + # If we have a listlike key, _check_indexing_error will raise + # InvalidIndexError. Otherwise we fall through and re-raise + # the TypeError. + self._check_indexing_error(key) + raise + + @final + def get_indexer( + self, + target, + method: ReindexMethod | None = None, + limit: int | None = None, + tolerance=None, + ) -> npt.NDArray[np.intp]: + """ + Compute indexer and mask for new index given the current index. + + The indexer should be then used as an input to ndarray.take to align the + current data to the new index. + + Parameters + ---------- + target : Index + method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional + * default: exact matches only. + * pad / ffill: find the PREVIOUS index value if no exact match. + * backfill / bfill: use NEXT index value if no exact match + * nearest: use the NEAREST index value if no exact match. Tied + distances are broken by preferring the larger index value. + limit : int, optional + Maximum number of consecutive labels in ``target`` to match for + inexact matches. + tolerance : optional + Maximum distance between original and new labels for inexact + matches. The values of the index at the matching locations must + satisfy the equation ``abs(index[indexer] - target) <= tolerance``. + + Tolerance may be a scalar value, which applies the same tolerance + to all values, or list-like, which applies variable tolerance per + element. List-like includes list, tuple, array, Series, and must be + the same size as the index and its dtype must exactly match the + index's type. + + Returns + ------- + np.ndarray[np.intp] + Integers from 0 to n - 1 indicating that the index at these + positions matches the corresponding target values. Missing values + in the target are marked by -1. + + Notes + ----- + Returns -1 for unmatched values, for further explanation see the + example below. + + Examples + -------- + >>> index = pd.Index(['c', 'a', 'b']) + >>> index.get_indexer(['a', 'b', 'x']) + array([ 1, 2, -1]) + + Notice that the return value is an array of locations in ``index`` + and ``x`` is marked by -1, as it is not in ``index``. + """ + method = clean_reindex_fill_method(method) + orig_target = target + target = self._maybe_cast_listlike_indexer(target) + + self._check_indexing_method(method, limit, tolerance) + + if not self._index_as_unique: + raise InvalidIndexError(self._requires_unique_msg) + + if len(target) == 0: + return np.array([], dtype=np.intp) + + if not self._should_compare(target) and not self._should_partial_index(target): + # IntervalIndex get special treatment bc numeric scalars can be + # matched to Interval scalars + return self._get_indexer_non_comparable(target, method=method, unique=True) + + if isinstance(self.dtype, CategoricalDtype): + # _maybe_cast_listlike_indexer ensures target has our dtype + # (could improve perf by doing _should_compare check earlier?) + assert self.dtype == target.dtype + + indexer = self._engine.get_indexer(target.codes) + if self.hasnans and target.hasnans: + # After _maybe_cast_listlike_indexer, target elements which do not + # belong to some category are changed to NaNs + # Mask to track actual NaN values compared to inserted NaN values + # GH#45361 + target_nans = isna(orig_target) + loc = self.get_loc(np.nan) + mask = target.isna() + indexer[target_nans] = loc + indexer[mask & ~target_nans] = -1 + return indexer + + if isinstance(target.dtype, CategoricalDtype): + # potential fastpath + # get an indexer for unique categories then propagate to codes via take_nd + # get_indexer instead of _get_indexer needed for MultiIndex cases + # e.g. test_append_different_columns_types + categories_indexer = self.get_indexer(target.categories) + + indexer = algos.take_nd(categories_indexer, target.codes, fill_value=-1) + + if (not self._is_multi and self.hasnans) and target.hasnans: + # Exclude MultiIndex because hasnans raises NotImplementedError + # we should only get here if we are unique, so loc is an integer + # GH#41934 + loc = self.get_loc(np.nan) + mask = target.isna() + indexer[mask] = loc + + return ensure_platform_int(indexer) + + pself, ptarget = self._maybe_downcast_for_indexing(target) + if pself is not self or ptarget is not target: + return pself.get_indexer( + ptarget, method=method, limit=limit, tolerance=tolerance + ) + + if self.dtype == target.dtype and self.equals(target): + # Only call equals if we have same dtype to avoid inference/casting + return np.arange(len(target), dtype=np.intp) + + if self.dtype != target.dtype and not self._should_partial_index(target): + # _should_partial_index e.g. IntervalIndex with numeric scalars + # that can be matched to Interval scalars. + dtype = self._find_common_type_compat(target) + + this = self.astype(dtype, copy=False) + target = target.astype(dtype, copy=False) + return this._get_indexer( + target, method=method, limit=limit, tolerance=tolerance + ) + + return self._get_indexer(target, method, limit, tolerance) + + def _get_indexer( + self, + target: Index, + method: str_t | None = None, + limit: int | None = None, + tolerance=None, + ) -> npt.NDArray[np.intp]: + if tolerance is not None: + tolerance = self._convert_tolerance(tolerance, target) + + if method in ["pad", "backfill"]: + indexer = self._get_fill_indexer(target, method, limit, tolerance) + elif method == "nearest": + indexer = self._get_nearest_indexer(target, limit, tolerance) + else: + if target._is_multi and self._is_multi: + engine = self._engine + # error: Item "IndexEngine" of "Union[IndexEngine, ExtensionEngine]" + # has no attribute "_extract_level_codes" + tgt_values = engine._extract_level_codes( # type: ignore[union-attr] + target + ) + else: + tgt_values = target._get_engine_target() + + indexer = self._engine.get_indexer(tgt_values) + + return ensure_platform_int(indexer) + + @final + def _should_partial_index(self, target: Index) -> bool: + """ + Should we attempt partial-matching indexing? + """ + if isinstance(self.dtype, IntervalDtype): + if isinstance(target.dtype, IntervalDtype): + return False + # "Index" has no attribute "left" + return self.left._should_compare(target) # type: ignore[attr-defined] + return False + + @final + def _check_indexing_method( + self, + method: str_t | None, + limit: int | None = None, + tolerance=None, + ) -> None: + """ + Raise if we have a get_indexer `method` that is not supported or valid. + """ + if method not in [None, "bfill", "backfill", "pad", "ffill", "nearest"]: + # in practice the clean_reindex_fill_method call would raise + # before we get here + raise ValueError("Invalid fill method") # pragma: no cover + + if self._is_multi: + if method == "nearest": + raise NotImplementedError( + "method='nearest' not implemented yet " + "for MultiIndex; see GitHub issue 9365" + ) + if method in ("pad", "backfill"): + if tolerance is not None: + raise NotImplementedError( + "tolerance not implemented yet for MultiIndex" + ) + + if isinstance(self.dtype, (IntervalDtype, CategoricalDtype)): + # GH#37871 for now this is only for IntervalIndex and CategoricalIndex + if method is not None: + raise NotImplementedError( + f"method {method} not yet implemented for {type(self).__name__}" + ) + + if method is None: + if tolerance is not None: + raise ValueError( + "tolerance argument only valid if doing pad, " + "backfill or nearest reindexing" + ) + if limit is not None: + raise ValueError( + "limit argument only valid if doing pad, " + "backfill or nearest reindexing" + ) + + def _convert_tolerance(self, tolerance, target: np.ndarray | Index) -> np.ndarray: + # override this method on subclasses + tolerance = np.asarray(tolerance) + if target.size != tolerance.size and tolerance.size > 1: + raise ValueError("list-like tolerance size must match target index size") + elif is_numeric_dtype(self) and not np.issubdtype(tolerance.dtype, np.number): + if tolerance.ndim > 0: + raise ValueError( + f"tolerance argument for {type(self).__name__} with dtype " + f"{self.dtype} must contain numeric elements if it is list type" + ) + + raise ValueError( + f"tolerance argument for {type(self).__name__} with dtype {self.dtype} " + f"must be numeric if it is a scalar: {repr(tolerance)}" + ) + return tolerance + + @final + def _get_fill_indexer( + self, target: Index, method: str_t, limit: int | None = None, tolerance=None + ) -> npt.NDArray[np.intp]: + if self._is_multi: + if not (self.is_monotonic_increasing or self.is_monotonic_decreasing): + raise ValueError("index must be monotonic increasing or decreasing") + encoded = self.append(target)._engine.values # type: ignore[union-attr] + self_encoded = Index(encoded[: len(self)]) + target_encoded = Index(encoded[len(self) :]) + return self_encoded._get_fill_indexer( + target_encoded, method, limit, tolerance + ) + + if self.is_monotonic_increasing and target.is_monotonic_increasing: + target_values = target._get_engine_target() + own_values = self._get_engine_target() + if not isinstance(target_values, np.ndarray) or not isinstance( + own_values, np.ndarray + ): + raise NotImplementedError + + if method == "pad": + indexer = libalgos.pad(own_values, target_values, limit=limit) + else: + # i.e. "backfill" + indexer = libalgos.backfill(own_values, target_values, limit=limit) + else: + indexer = self._get_fill_indexer_searchsorted(target, method, limit) + if tolerance is not None and len(self): + indexer = self._filter_indexer_tolerance(target, indexer, tolerance) + return indexer + + @final + def _get_fill_indexer_searchsorted( + self, target: Index, method: str_t, limit: int | None = None + ) -> npt.NDArray[np.intp]: + """ + Fallback pad/backfill get_indexer that works for monotonic decreasing + indexes and non-monotonic targets. + """ + if limit is not None: + raise ValueError( + f"limit argument for {repr(method)} method only well-defined " + "if index and target are monotonic" + ) + + side: Literal["left", "right"] = "left" if method == "pad" else "right" + + # find exact matches first (this simplifies the algorithm) + indexer = self.get_indexer(target) + nonexact = indexer == -1 + indexer[nonexact] = self._searchsorted_monotonic(target[nonexact], side) + if side == "left": + # searchsorted returns "indices into a sorted array such that, + # if the corresponding elements in v were inserted before the + # indices, the order of a would be preserved". + # Thus, we need to subtract 1 to find values to the left. + indexer[nonexact] -= 1 + # This also mapped not found values (values of 0 from + # np.searchsorted) to -1, which conveniently is also our + # sentinel for missing values + else: + # Mark indices to the right of the largest value as not found + indexer[indexer == len(self)] = -1 + return indexer + + @final + def _get_nearest_indexer( + self, target: Index, limit: int | None, tolerance + ) -> npt.NDArray[np.intp]: + """ + Get the indexer for the nearest index labels; requires an index with + values that can be subtracted from each other (e.g., not strings or + tuples). + """ + if not len(self): + return self._get_fill_indexer(target, "pad") + + left_indexer = self.get_indexer(target, "pad", limit=limit) + right_indexer = self.get_indexer(target, "backfill", limit=limit) + + left_distances = self._difference_compat(target, left_indexer) + right_distances = self._difference_compat(target, right_indexer) + + op = operator.lt if self.is_monotonic_increasing else operator.le + indexer = np.where( + # error: Argument 1&2 has incompatible type "Union[ExtensionArray, + # ndarray[Any, Any]]"; expected "Union[SupportsDunderLE, + # SupportsDunderGE, SupportsDunderGT, SupportsDunderLT]" + op(left_distances, right_distances) # type: ignore[arg-type] + | (right_indexer == -1), + left_indexer, + right_indexer, + ) + if tolerance is not None: + indexer = self._filter_indexer_tolerance(target, indexer, tolerance) + return indexer + + @final + def _filter_indexer_tolerance( + self, + target: Index, + indexer: npt.NDArray[np.intp], + tolerance, + ) -> npt.NDArray[np.intp]: + distance = self._difference_compat(target, indexer) + + return np.where(distance <= tolerance, indexer, -1) + + @final + def _difference_compat( + self, target: Index, indexer: npt.NDArray[np.intp] + ) -> ArrayLike: + # Compatibility for PeriodArray, for which __sub__ returns an ndarray[object] + # of DateOffset objects, which do not support __abs__ (and would be slow + # if they did) + + if isinstance(self.dtype, PeriodDtype): + # Note: we only get here with matching dtypes + own_values = cast("PeriodArray", self._data)._ndarray + target_values = cast("PeriodArray", target._data)._ndarray + diff = own_values[indexer] - target_values + else: + # error: Unsupported left operand type for - ("ExtensionArray") + diff = self._values[indexer] - target._values # type: ignore[operator] + return abs(diff) + + # -------------------------------------------------------------------- + # Indexer Conversion Methods + + @final + def _validate_positional_slice(self, key: slice) -> None: + """ + For positional indexing, a slice must have either int or None + for each of start, stop, and step. + """ + self._validate_indexer("positional", key.start, "iloc") + self._validate_indexer("positional", key.stop, "iloc") + self._validate_indexer("positional", key.step, "iloc") + + def _convert_slice_indexer(self, key: slice, kind: Literal["loc", "getitem"]): + """ + Convert a slice indexer. + + By definition, these are labels unless 'iloc' is passed in. + Floats are not allowed as the start, step, or stop of the slice. + + Parameters + ---------- + key : label of the slice bound + kind : {'loc', 'getitem'} + """ + + # potentially cast the bounds to integers + start, stop, step = key.start, key.stop, key.step + + # figure out if this is a positional indexer + is_index_slice = is_valid_positional_slice(key) + + # TODO(GH#50617): once Series.__[gs]etitem__ is removed we should be able + # to simplify this. + if lib.is_np_dtype(self.dtype, "f"): + # We always treat __getitem__ slicing as label-based + # translate to locations + if kind == "getitem" and is_index_slice and not start == stop and step != 0: + # exclude step=0 from the warning because it will raise anyway + # start/stop both None e.g. [:] or [::-1] won't change. + # exclude start==stop since it will be empty either way, or + # will be [:] or [::-1] which won't change + warnings.warn( + # GH#49612 + "The behavior of obj[i:j] with a float-dtype index is " + "deprecated. In a future version, this will be treated as " + "positional instead of label-based. For label-based slicing, " + "use obj.loc[i:j] instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + return self.slice_indexer(start, stop, step) + + if kind == "getitem": + # called from the getitem slicers, validate that we are in fact integers + if is_index_slice: + # In this case the _validate_indexer checks below are redundant + return key + elif self.dtype.kind in "iu": + # Note: these checks are redundant if we know is_index_slice + self._validate_indexer("slice", key.start, "getitem") + self._validate_indexer("slice", key.stop, "getitem") + self._validate_indexer("slice", key.step, "getitem") + return key + + # convert the slice to an indexer here; checking that the user didn't + # pass a positional slice to loc + is_positional = is_index_slice and self._should_fallback_to_positional + + # if we are mixed and have integers + if is_positional: + try: + # Validate start & stop + if start is not None: + self.get_loc(start) + if stop is not None: + self.get_loc(stop) + is_positional = False + except KeyError: + pass + + if com.is_null_slice(key): + # It doesn't matter if we are positional or label based + indexer = key + elif is_positional: + if kind == "loc": + # GH#16121, GH#24612, GH#31810 + raise TypeError( + "Slicing a positional slice with .loc is not allowed, " + "Use .loc with labels or .iloc with positions instead.", + ) + indexer = key + else: + indexer = self.slice_indexer(start, stop, step) + + return indexer + + @final + def _raise_invalid_indexer( + self, + form: Literal["slice", "positional"], + key, + reraise: lib.NoDefault | None | Exception = lib.no_default, + ) -> None: + """ + Raise consistent invalid indexer message. + """ + msg = ( + f"cannot do {form} indexing on {type(self).__name__} with these " + f"indexers [{key}] of type {type(key).__name__}" + ) + if reraise is not lib.no_default: + raise TypeError(msg) from reraise + raise TypeError(msg) + + # -------------------------------------------------------------------- + # Reindex Methods + + @final + def _validate_can_reindex(self, indexer: np.ndarray) -> None: + """ + Check if we are allowing reindexing with this particular indexer. + + Parameters + ---------- + indexer : an integer ndarray + + Raises + ------ + ValueError if its a duplicate axis + """ + # trying to reindex on an axis with duplicates + if not self._index_as_unique and len(indexer): + raise ValueError("cannot reindex on an axis with duplicate labels") + + def reindex( + self, + target, + method: ReindexMethod | None = None, + level=None, + limit: int | None = None, + tolerance: float | None = None, + ) -> tuple[Index, npt.NDArray[np.intp] | None]: + """ + Create index with target's values. + + Parameters + ---------- + target : an iterable + method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional + * default: exact matches only. + * pad / ffill: find the PREVIOUS index value if no exact match. + * backfill / bfill: use NEXT index value if no exact match + * nearest: use the NEAREST index value if no exact match. Tied + distances are broken by preferring the larger index value. + level : int, optional + Level of multiindex. + limit : int, optional + Maximum number of consecutive labels in ``target`` to match for + inexact matches. + tolerance : int or float, optional + Maximum distance between original and new labels for inexact + matches. The values of the index at the matching locations must + satisfy the equation ``abs(index[indexer] - target) <= tolerance``. + + Tolerance may be a scalar value, which applies the same tolerance + to all values, or list-like, which applies variable tolerance per + element. List-like includes list, tuple, array, Series, and must be + the same size as the index and its dtype must exactly match the + index's type. + + Returns + ------- + new_index : pd.Index + Resulting index. + indexer : np.ndarray[np.intp] or None + Indices of output values in original index. + + Raises + ------ + TypeError + If ``method`` passed along with ``level``. + ValueError + If non-unique multi-index + ValueError + If non-unique index and ``method`` or ``limit`` passed. + + See Also + -------- + Series.reindex : Conform Series to new index with optional filling logic. + DataFrame.reindex : Conform DataFrame to new index with optional filling logic. + + Examples + -------- + >>> idx = pd.Index(['car', 'bike', 'train', 'tractor']) + >>> idx + Index(['car', 'bike', 'train', 'tractor'], dtype='object') + >>> idx.reindex(['car', 'bike']) + (Index(['car', 'bike'], dtype='object'), array([0, 1])) + """ + # GH6552: preserve names when reindexing to non-named target + # (i.e. neither Index nor Series). + preserve_names = not hasattr(target, "name") + + # GH7774: preserve dtype/tz if target is empty and not an Index. + target = ensure_has_len(target) # target may be an iterator + + if not isinstance(target, Index) and len(target) == 0: + if level is not None and self._is_multi: + # "Index" has no attribute "levels"; maybe "nlevels"? + idx = self.levels[level] # type: ignore[attr-defined] + else: + idx = self + target = idx[:0] + else: + target = ensure_index(target) + + if level is not None and ( + isinstance(self, ABCMultiIndex) or isinstance(target, ABCMultiIndex) + ): + if method is not None: + raise TypeError("Fill method not supported if level passed") + + # TODO: tests where passing `keep_order=not self._is_multi` + # makes a difference for non-MultiIndex case + target, indexer, _ = self._join_level( + target, level, how="right", keep_order=not self._is_multi + ) + + else: + if self.equals(target): + indexer = None + else: + if self._index_as_unique: + indexer = self.get_indexer( + target, method=method, limit=limit, tolerance=tolerance + ) + elif self._is_multi: + raise ValueError("cannot handle a non-unique multi-index!") + elif not self.is_unique: + # GH#42568 + raise ValueError("cannot reindex on an axis with duplicate labels") + else: + indexer, _ = self.get_indexer_non_unique(target) + + target = self._wrap_reindex_result(target, indexer, preserve_names) + return target, indexer + + def _wrap_reindex_result(self, target, indexer, preserve_names: bool): + target = self._maybe_preserve_names(target, preserve_names) + return target + + def _maybe_preserve_names(self, target: Index, preserve_names: bool): + if preserve_names and target.nlevels == 1 and target.name != self.name: + target = target.copy(deep=False) + target.name = self.name + return target + + @final + def _reindex_non_unique( + self, target: Index + ) -> tuple[Index, npt.NDArray[np.intp], npt.NDArray[np.intp] | None]: + """ + Create a new index with target's values (move/add/delete values as + necessary) use with non-unique Index and a possibly non-unique target. + + Parameters + ---------- + target : an iterable + + Returns + ------- + new_index : pd.Index + Resulting index. + indexer : np.ndarray[np.intp] + Indices of output values in original index. + new_indexer : np.ndarray[np.intp] or None + + """ + target = ensure_index(target) + if len(target) == 0: + # GH#13691 + return self[:0], np.array([], dtype=np.intp), None + + indexer, missing = self.get_indexer_non_unique(target) + check = indexer != -1 + new_labels: Index | np.ndarray = self.take(indexer[check]) + new_indexer = None + + if len(missing): + length = np.arange(len(indexer), dtype=np.intp) + + missing = ensure_platform_int(missing) + missing_labels = target.take(missing) + missing_indexer = length[~check] + cur_labels = self.take(indexer[check]).values + cur_indexer = length[check] + + # Index constructor below will do inference + new_labels = np.empty((len(indexer),), dtype=object) + new_labels[cur_indexer] = cur_labels + new_labels[missing_indexer] = missing_labels + + # GH#38906 + if not len(self): + new_indexer = np.arange(0, dtype=np.intp) + + # a unique indexer + elif target.is_unique: + # see GH5553, make sure we use the right indexer + new_indexer = np.arange(len(indexer), dtype=np.intp) + new_indexer[cur_indexer] = np.arange(len(cur_labels)) + new_indexer[missing_indexer] = -1 + + # we have a non_unique selector, need to use the original + # indexer here + else: + # need to retake to have the same size as the indexer + indexer[~check] = -1 + + # reset the new indexer to account for the new size + new_indexer = np.arange(len(self.take(indexer)), dtype=np.intp) + new_indexer[~check] = -1 + + if not isinstance(self, ABCMultiIndex): + new_index = Index(new_labels, name=self.name) + else: + new_index = type(self).from_tuples(new_labels, names=self.names) + return new_index, indexer, new_indexer + + # -------------------------------------------------------------------- + # Join Methods + + @overload + def join( + self, + other: Index, + *, + how: JoinHow = ..., + level: Level = ..., + return_indexers: Literal[True], + sort: bool = ..., + ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + ... + + @overload + def join( + self, + other: Index, + *, + how: JoinHow = ..., + level: Level = ..., + return_indexers: Literal[False] = ..., + sort: bool = ..., + ) -> Index: + ... + + @overload + def join( + self, + other: Index, + *, + how: JoinHow = ..., + level: Level = ..., + return_indexers: bool = ..., + sort: bool = ..., + ) -> Index | tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + ... + + @final + @_maybe_return_indexers + def join( + self, + other: Index, + *, + how: JoinHow = "left", + level: Level | None = None, + return_indexers: bool = False, + sort: bool = False, + ) -> Index | tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + """ + Compute join_index and indexers to conform data structures to the new index. + + Parameters + ---------- + other : Index + how : {'left', 'right', 'inner', 'outer'} + level : int or level name, default None + return_indexers : bool, default False + sort : bool, default False + Sort the join keys lexicographically in the result Index. If False, + the order of the join keys depends on the join type (how keyword). + + Returns + ------- + join_index, (left_indexer, right_indexer) + + Examples + -------- + >>> idx1 = pd.Index([1, 2, 3]) + >>> idx2 = pd.Index([4, 5, 6]) + >>> idx1.join(idx2, how='outer') + Index([1, 2, 3, 4, 5, 6], dtype='int64') + """ + other = ensure_index(other) + sort = sort or how == "outer" + + if isinstance(self, ABCDatetimeIndex) and isinstance(other, ABCDatetimeIndex): + if (self.tz is None) ^ (other.tz is None): + # Raise instead of casting to object below. + raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") + + if not self._is_multi and not other._is_multi: + # We have specific handling for MultiIndex below + pself, pother = self._maybe_downcast_for_indexing(other) + if pself is not self or pother is not other: + return pself.join( + pother, how=how, level=level, return_indexers=True, sort=sort + ) + + # try to figure out the join level + # GH3662 + if level is None and (self._is_multi or other._is_multi): + # have the same levels/names so a simple join + if self.names == other.names: + pass + else: + return self._join_multi(other, how=how) + + # join on the level + if level is not None and (self._is_multi or other._is_multi): + return self._join_level(other, level, how=how) + + if len(self) == 0 or len(other) == 0: + try: + return self._join_empty(other, how, sort) + except TypeError: + # object dtype; non-comparable objects + pass + + if self.dtype != other.dtype: + dtype = self._find_common_type_compat(other) + this = self.astype(dtype, copy=False) + other = other.astype(dtype, copy=False) + return this.join(other, how=how, return_indexers=True) + elif ( + isinstance(self, ABCCategoricalIndex) + and isinstance(other, ABCCategoricalIndex) + and not self.ordered + and not self.categories.equals(other.categories) + ): + # dtypes are "equal" but categories are in different order + other = Index(other._values.reorder_categories(self.categories)) + + _validate_join_method(how) + + if ( + self.is_monotonic_increasing + and other.is_monotonic_increasing + and self._can_use_libjoin + and other._can_use_libjoin + and (self.is_unique or other.is_unique) + ): + try: + return self._join_monotonic(other, how=how) + except TypeError: + # object dtype; non-comparable objects + pass + elif not self.is_unique or not other.is_unique: + return self._join_non_unique(other, how=how, sort=sort) + + return self._join_via_get_indexer(other, how, sort) + + @final + def _join_empty( + self, other: Index, how: JoinHow, sort: bool + ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + assert len(self) == 0 or len(other) == 0 + _validate_join_method(how) + + lidx: np.ndarray | None + ridx: np.ndarray | None + + if len(other): + how = cast(JoinHow, {"left": "right", "right": "left"}.get(how, how)) + join_index, ridx, lidx = other._join_empty(self, how, sort) + elif how in ["left", "outer"]: + if sort and not self.is_monotonic_increasing: + lidx = self.argsort() + join_index = self.take(lidx) + else: + lidx = None + join_index = self._view() + ridx = np.broadcast_to(np.intp(-1), len(join_index)) + else: + join_index = other._view() + lidx = np.array([], dtype=np.intp) + ridx = None + return join_index, lidx, ridx + + @final + def _join_via_get_indexer( + self, other: Index, how: JoinHow, sort: bool + ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + # Fallback if we do not have any fastpaths available based on + # uniqueness/monotonicity + + # Note: at this point we have checked matching dtypes + + if how == "left": + join_index = self.sort_values() if sort else self + elif how == "right": + join_index = other.sort_values() if sort else other + elif how == "inner": + join_index = self.intersection(other, sort=sort) + elif how == "outer": + try: + join_index = self.union(other, sort=sort) + except TypeError: + join_index = self.union(other) + try: + join_index = _maybe_try_sort(join_index, sort) + except TypeError: + pass + + if join_index is self: + lindexer = None + else: + lindexer = self.get_indexer_for(join_index) + if join_index is other: + rindexer = None + else: + rindexer = other.get_indexer_for(join_index) + return join_index, lindexer, rindexer + + @final + def _join_multi(self, other: Index, how: JoinHow): + from pandas.core.indexes.multi import MultiIndex + from pandas.core.reshape.merge import restore_dropped_levels_multijoin + + # figure out join names + self_names_list = list(com.not_none(*self.names)) + other_names_list = list(com.not_none(*other.names)) + self_names_order = self_names_list.index + other_names_order = other_names_list.index + self_names = set(self_names_list) + other_names = set(other_names_list) + overlap = self_names & other_names + + # need at least 1 in common + if not overlap: + raise ValueError("cannot join with no overlapping index names") + + if isinstance(self, MultiIndex) and isinstance(other, MultiIndex): + # Drop the non-matching levels from left and right respectively + ldrop_names = sorted(self_names - overlap, key=self_names_order) + rdrop_names = sorted(other_names - overlap, key=other_names_order) + + # if only the order differs + if not len(ldrop_names + rdrop_names): + self_jnlevels = self + other_jnlevels = other.reorder_levels(self.names) + else: + self_jnlevels = self.droplevel(ldrop_names) + other_jnlevels = other.droplevel(rdrop_names) + + # Join left and right + # Join on same leveled multi-index frames is supported + join_idx, lidx, ridx = self_jnlevels.join( + other_jnlevels, how=how, return_indexers=True + ) + + # Restore the dropped levels + # Returned index level order is + # common levels, ldrop_names, rdrop_names + dropped_names = ldrop_names + rdrop_names + + # error: Argument 5/6 to "restore_dropped_levels_multijoin" has + # incompatible type "Optional[ndarray[Any, dtype[signedinteger[Any + # ]]]]"; expected "ndarray[Any, dtype[signedinteger[Any]]]" + levels, codes, names = restore_dropped_levels_multijoin( + self, + other, + dropped_names, + join_idx, + lidx, # type: ignore[arg-type] + ridx, # type: ignore[arg-type] + ) + + # Re-create the multi-index + multi_join_idx = MultiIndex( + levels=levels, codes=codes, names=names, verify_integrity=False + ) + + multi_join_idx = multi_join_idx.remove_unused_levels() + + # maintain the order of the index levels + if how == "right": + level_order = other_names_list + ldrop_names + else: + level_order = self_names_list + rdrop_names + multi_join_idx = multi_join_idx.reorder_levels(level_order) + + return multi_join_idx, lidx, ridx + + jl = next(iter(overlap)) + + # Case where only one index is multi + # make the indices into mi's that match + flip_order = False + if isinstance(self, MultiIndex): + self, other = other, self + flip_order = True + # flip if join method is right or left + flip: dict[JoinHow, JoinHow] = {"right": "left", "left": "right"} + how = flip.get(how, how) + + level = other.names.index(jl) + result = self._join_level(other, level, how=how) + + if flip_order: + return result[0], result[2], result[1] + return result + + @final + def _join_non_unique( + self, other: Index, how: JoinHow = "left", sort: bool = False + ) -> tuple[Index, npt.NDArray[np.intp], npt.NDArray[np.intp]]: + from pandas.core.reshape.merge import get_join_indexers_non_unique + + # We only get here if dtypes match + assert self.dtype == other.dtype + + left_idx, right_idx = get_join_indexers_non_unique( + self._values, other._values, how=how, sort=sort + ) + mask = left_idx == -1 + + join_idx = self.take(left_idx) + right = other.take(right_idx) + join_index = join_idx.putmask(mask, right) + if isinstance(join_index, ABCMultiIndex) and how == "outer": + # test_join_index_levels + join_index = join_index._sort_levels_monotonic() + return join_index, left_idx, right_idx + + @final + def _join_level( + self, other: Index, level, how: JoinHow = "left", keep_order: bool = True + ) -> tuple[MultiIndex, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + """ + The join method *only* affects the level of the resulting + MultiIndex. Otherwise it just exactly aligns the Index data to the + labels of the level in the MultiIndex. + + If ```keep_order == True```, the order of the data indexed by the + MultiIndex will not be changed; otherwise, it will tie out + with `other`. + """ + from pandas.core.indexes.multi import MultiIndex + + def _get_leaf_sorter(labels: list[np.ndarray]) -> npt.NDArray[np.intp]: + """ + Returns sorter for the inner most level while preserving the + order of higher levels. + + Parameters + ---------- + labels : list[np.ndarray] + Each ndarray has signed integer dtype, not necessarily identical. + + Returns + ------- + np.ndarray[np.intp] + """ + if labels[0].size == 0: + return np.empty(0, dtype=np.intp) + + if len(labels) == 1: + return get_group_index_sorter(ensure_platform_int(labels[0])) + + # find indexers of beginning of each set of + # same-key labels w.r.t all but last level + tic = labels[0][:-1] != labels[0][1:] + for lab in labels[1:-1]: + tic |= lab[:-1] != lab[1:] + + starts = np.hstack(([True], tic, [True])).nonzero()[0] + lab = ensure_int64(labels[-1]) + return lib.get_level_sorter(lab, ensure_platform_int(starts)) + + if isinstance(self, MultiIndex) and isinstance(other, MultiIndex): + raise TypeError("Join on level between two MultiIndex objects is ambiguous") + + left, right = self, other + + flip_order = not isinstance(self, MultiIndex) + if flip_order: + left, right = right, left + flip: dict[JoinHow, JoinHow] = {"right": "left", "left": "right"} + how = flip.get(how, how) + + assert isinstance(left, MultiIndex) + + level = left._get_level_number(level) + old_level = left.levels[level] + + if not right.is_unique: + raise NotImplementedError( + "Index._join_level on non-unique index is not implemented" + ) + + new_level, left_lev_indexer, right_lev_indexer = old_level.join( + right, how=how, return_indexers=True + ) + + if left_lev_indexer is None: + if keep_order or len(left) == 0: + left_indexer = None + join_index = left + else: # sort the leaves + left_indexer = _get_leaf_sorter(left.codes[: level + 1]) + join_index = left[left_indexer] + + else: + left_lev_indexer = ensure_platform_int(left_lev_indexer) + rev_indexer = lib.get_reverse_indexer(left_lev_indexer, len(old_level)) + old_codes = left.codes[level] + + taker = old_codes[old_codes != -1] + new_lev_codes = rev_indexer.take(taker) + + new_codes = list(left.codes) + new_codes[level] = new_lev_codes + + new_levels = list(left.levels) + new_levels[level] = new_level + + if keep_order: # just drop missing values. o.w. keep order + left_indexer = np.arange(len(left), dtype=np.intp) + left_indexer = cast(np.ndarray, left_indexer) + mask = new_lev_codes != -1 + if not mask.all(): + new_codes = [lab[mask] for lab in new_codes] + left_indexer = left_indexer[mask] + + else: # tie out the order with other + if level == 0: # outer most level, take the fast route + max_new_lev = 0 if len(new_lev_codes) == 0 else new_lev_codes.max() + ngroups = 1 + max_new_lev + left_indexer, counts = libalgos.groupsort_indexer( + new_lev_codes, ngroups + ) + + # missing values are placed first; drop them! + left_indexer = left_indexer[counts[0] :] + new_codes = [lab[left_indexer] for lab in new_codes] + + else: # sort the leaves + mask = new_lev_codes != -1 + mask_all = mask.all() + if not mask_all: + new_codes = [lab[mask] for lab in new_codes] + + left_indexer = _get_leaf_sorter(new_codes[: level + 1]) + new_codes = [lab[left_indexer] for lab in new_codes] + + # left_indexers are w.r.t masked frame. + # reverse to original frame! + if not mask_all: + left_indexer = mask.nonzero()[0][left_indexer] + + join_index = MultiIndex( + levels=new_levels, + codes=new_codes, + names=left.names, + verify_integrity=False, + ) + + if right_lev_indexer is not None: + right_indexer = right_lev_indexer.take(join_index.codes[level]) + else: + right_indexer = join_index.codes[level] + + if flip_order: + left_indexer, right_indexer = right_indexer, left_indexer + + left_indexer = ( + None if left_indexer is None else ensure_platform_int(left_indexer) + ) + right_indexer = ( + None if right_indexer is None else ensure_platform_int(right_indexer) + ) + return join_index, left_indexer, right_indexer + + @final + def _join_monotonic( + self, other: Index, how: JoinHow = "left" + ) -> tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]: + # We only get here with matching dtypes and both monotonic increasing + assert other.dtype == self.dtype + assert self._can_use_libjoin and other._can_use_libjoin + + if self.equals(other): + # This is a convenient place for this check, but its correctness + # does not depend on monotonicity, so it could go earlier + # in the calling method. + ret_index = other if how == "right" else self + return ret_index, None, None + + ridx: npt.NDArray[np.intp] | None + lidx: npt.NDArray[np.intp] | None + + if self.is_unique and other.is_unique: + # We can perform much better than the general case + if how == "left": + join_index = self + lidx = None + ridx = self._left_indexer_unique(other) + elif how == "right": + join_index = other + lidx = other._left_indexer_unique(self) + ridx = None + elif how == "inner": + join_array, lidx, ridx = self._inner_indexer(other) + join_index = self._wrap_joined_index(join_array, other, lidx, ridx) + elif how == "outer": + join_array, lidx, ridx = self._outer_indexer(other) + join_index = self._wrap_joined_index(join_array, other, lidx, ridx) + else: + if how == "left": + join_array, lidx, ridx = self._left_indexer(other) + elif how == "right": + join_array, ridx, lidx = other._left_indexer(self) + elif how == "inner": + join_array, lidx, ridx = self._inner_indexer(other) + elif how == "outer": + join_array, lidx, ridx = self._outer_indexer(other) + + assert lidx is not None + assert ridx is not None + + join_index = self._wrap_joined_index(join_array, other, lidx, ridx) + + lidx = None if lidx is None else ensure_platform_int(lidx) + ridx = None if ridx is None else ensure_platform_int(ridx) + return join_index, lidx, ridx + + def _wrap_joined_index( + self, + joined: ArrayLike, + other: Self, + lidx: npt.NDArray[np.intp], + ridx: npt.NDArray[np.intp], + ) -> Self: + assert other.dtype == self.dtype + + if isinstance(self, ABCMultiIndex): + name = self.names if self.names == other.names else None + # error: Incompatible return value type (got "MultiIndex", + # expected "Self") + mask = lidx == -1 + join_idx = self.take(lidx) + right = cast("MultiIndex", other.take(ridx)) + join_index = join_idx.putmask(mask, right)._sort_levels_monotonic() + return join_index.set_names(name) # type: ignore[return-value] + else: + name = get_op_result_name(self, other) + return self._constructor._with_infer(joined, name=name, dtype=self.dtype) + + @final + @cache_readonly + def _can_use_libjoin(self) -> bool: + """ + Whether we can use the fastpaths implemented in _libs.join. + + This is driven by whether (in monotonic increasing cases that are + guaranteed not to have NAs) we can convert to a np.ndarray without + making a copy. If we cannot, this negates the performance benefit + of using libjoin. + """ + if type(self) is Index: + # excludes EAs, but include masks, we get here with monotonic + # values only, meaning no NA + return ( + isinstance(self.dtype, np.dtype) + or isinstance(self._values, (ArrowExtensionArray, BaseMaskedArray)) + or ( + isinstance(self.dtype, StringDtype) + and self.dtype.storage == "python" + ) + ) + # Exclude index types where the conversion to numpy converts to object dtype, + # which negates the performance benefit of libjoin + # Subclasses should override to return False if _get_join_target is + # not zero-copy. + # TODO: exclude RangeIndex (which allocates memory)? + # Doing so seems to break test_concat_datetime_timezone + return not isinstance(self, (ABCIntervalIndex, ABCMultiIndex)) + + # -------------------------------------------------------------------- + # Uncategorized Methods + + @property + def values(self) -> ArrayLike: + """ + Return an array representing the data in the Index. + + .. warning:: + + We recommend using :attr:`Index.array` or + :meth:`Index.to_numpy`, depending on whether you need + a reference to the underlying data or a NumPy array. + + Returns + ------- + array: numpy.ndarray or ExtensionArray + + See Also + -------- + Index.array : Reference to the underlying data. + Index.to_numpy : A NumPy array representing the underlying data. + + Examples + -------- + For :class:`pandas.Index`: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.values + array([1, 2, 3]) + + For :class:`pandas.IntervalIndex`: + + >>> idx = pd.interval_range(start=0, end=5) + >>> idx.values + + [(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]] + Length: 5, dtype: interval[int64, right] + """ + if using_copy_on_write(): + data = self._data + if isinstance(data, np.ndarray): + data = data.view() + data.flags.writeable = False + return data + return self._data + + @cache_readonly + @doc(IndexOpsMixin.array) + def array(self) -> ExtensionArray: + array = self._data + if isinstance(array, np.ndarray): + from pandas.core.arrays.numpy_ import NumpyExtensionArray + + array = NumpyExtensionArray(array) + return array + + @property + def _values(self) -> ExtensionArray | np.ndarray: + """ + The best array representation. + + This is an ndarray or ExtensionArray. + + ``_values`` are consistent between ``Series`` and ``Index``. + + It may differ from the public '.values' method. + + index | values | _values | + ----------------- | --------------- | ------------- | + Index | ndarray | ndarray | + CategoricalIndex | Categorical | Categorical | + DatetimeIndex | ndarray[M8ns] | DatetimeArray | + DatetimeIndex[tz] | ndarray[M8ns] | DatetimeArray | + PeriodIndex | ndarray[object] | PeriodArray | + IntervalIndex | IntervalArray | IntervalArray | + + See Also + -------- + values : Values + """ + return self._data + + def _get_engine_target(self) -> ArrayLike: + """ + Get the ndarray or ExtensionArray that we can pass to the IndexEngine + constructor. + """ + vals = self._values + if isinstance(vals, StringArray): + # GH#45652 much more performant than ExtensionEngine + return vals._ndarray + if isinstance(vals, ArrowExtensionArray) and self.dtype.kind in "Mm": + import pyarrow as pa + + pa_type = vals._pa_array.type + if pa.types.is_timestamp(pa_type): + vals = vals._to_datetimearray() + return vals._ndarray.view("i8") + elif pa.types.is_duration(pa_type): + vals = vals._to_timedeltaarray() + return vals._ndarray.view("i8") + if ( + type(self) is Index + and isinstance(self._values, ExtensionArray) + and not isinstance(self._values, BaseMaskedArray) + and not ( + isinstance(self._values, ArrowExtensionArray) + and is_numeric_dtype(self.dtype) + # Exclude decimal + and self.dtype.kind != "O" + ) + ): + # TODO(ExtensionIndex): remove special-case, just use self._values + return self._values.astype(object) + return vals + + @final + def _get_join_target(self) -> np.ndarray: + """ + Get the ndarray or ExtensionArray that we can pass to the join + functions. + """ + if isinstance(self._values, BaseMaskedArray): + # This is only used if our array is monotonic, so no NAs present + return self._values._data + elif isinstance(self._values, ArrowExtensionArray): + # This is only used if our array is monotonic, so no missing values + # present + return self._values.to_numpy() + + # TODO: exclude ABCRangeIndex case here as it copies + target = self._get_engine_target() + if not isinstance(target, np.ndarray): + raise ValueError("_can_use_libjoin should return False.") + return target + + def _from_join_target(self, result: np.ndarray) -> ArrayLike: + """ + Cast the ndarray returned from one of the libjoin.foo_indexer functions + back to type(self._data). + """ + if isinstance(self.values, BaseMaskedArray): + return type(self.values)(result, np.zeros(result.shape, dtype=np.bool_)) + elif isinstance(self.values, (ArrowExtensionArray, StringArray)): + return type(self.values)._from_sequence(result, dtype=self.dtype) + return result + + @doc(IndexOpsMixin._memory_usage) + def memory_usage(self, deep: bool = False) -> int: + result = self._memory_usage(deep=deep) + + # include our engine hashtable + result += self._engine.sizeof(deep=deep) + return result + + @final + def where(self, cond, other=None) -> Index: + """ + Replace values where the condition is False. + + The replacement is taken from other. + + Parameters + ---------- + cond : bool array-like with the same length as self + Condition to select the values on. + other : scalar, or array-like, default None + Replacement if the condition is False. + + Returns + ------- + pandas.Index + A copy of self with values replaced from other + where the condition is False. + + See Also + -------- + Series.where : Same method for Series. + DataFrame.where : Same method for DataFrame. + + Examples + -------- + >>> idx = pd.Index(['car', 'bike', 'train', 'tractor']) + >>> idx + Index(['car', 'bike', 'train', 'tractor'], dtype='object') + >>> idx.where(idx.isin(['car', 'train']), 'other') + Index(['car', 'other', 'train', 'other'], dtype='object') + """ + if isinstance(self, ABCMultiIndex): + raise NotImplementedError( + ".where is not supported for MultiIndex operations" + ) + cond = np.asarray(cond, dtype=bool) + return self.putmask(~cond, other) + + # construction helpers + @final + @classmethod + def _raise_scalar_data_error(cls, data): + # We return the TypeError so that we can raise it from the constructor + # in order to keep mypy happy + raise TypeError( + f"{cls.__name__}(...) must be called with a collection of some " + f"kind, {repr(data) if not isinstance(data, np.generic) else str(data)} " + "was passed" + ) + + def _validate_fill_value(self, value): + """ + Check if the value can be inserted into our array without casting, + and convert it to an appropriate native type if necessary. + + Raises + ------ + TypeError + If the value cannot be inserted into an array of this dtype. + """ + dtype = self.dtype + if isinstance(dtype, np.dtype) and dtype.kind not in "mM": + # return np_can_hold_element(dtype, value) + try: + return np_can_hold_element(dtype, value) + except LossySetitemError as err: + # re-raise as TypeError for consistency + raise TypeError from err + elif not can_hold_element(self._values, value): + raise TypeError + return value + + def _is_memory_usage_qualified(self) -> bool: + """ + Return a boolean if we need a qualified .info display. + """ + return is_object_dtype(self.dtype) or ( + is_string_dtype(self.dtype) and self.dtype.storage == "python" # type: ignore[union-attr] + ) + + def __contains__(self, key: Any) -> bool: + """ + Return a boolean indicating whether the provided key is in the index. + + Parameters + ---------- + key : label + The key to check if it is present in the index. + + Returns + ------- + bool + Whether the key search is in the index. + + Raises + ------ + TypeError + If the key is not hashable. + + See Also + -------- + Index.isin : Returns an ndarray of boolean dtype indicating whether the + list-like key is in the index. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3, 4]) + >>> idx + Index([1, 2, 3, 4], dtype='int64') + + >>> 2 in idx + True + >>> 6 in idx + False + """ + hash(key) + try: + return key in self._engine + except (OverflowError, TypeError, ValueError): + return False + + # https://github.com/python/typeshed/issues/2148#issuecomment-520783318 + # Incompatible types in assignment (expression has type "None", base class + # "object" defined the type as "Callable[[object], int]") + __hash__: ClassVar[None] # type: ignore[assignment] + + @final + def __setitem__(self, key, value) -> None: + raise TypeError("Index does not support mutable operations") + + def __getitem__(self, key): + """ + Override numpy.ndarray's __getitem__ method to work as desired. + + This function adds lists and Series as valid boolean indexers + (ndarrays only supports ndarray with dtype=bool). + + If resulting ndim != 1, plain ndarray is returned instead of + corresponding `Index` subclass. + + """ + getitem = self._data.__getitem__ + + if is_integer(key) or is_float(key): + # GH#44051 exclude bool, which would return a 2d ndarray + key = com.cast_scalar_indexer(key) + return getitem(key) + + if isinstance(key, slice): + # This case is separated from the conditional above to avoid + # pessimization com.is_bool_indexer and ndim checks. + return self._getitem_slice(key) + + if com.is_bool_indexer(key): + # if we have list[bools, length=1e5] then doing this check+convert + # takes 166 µs + 2.1 ms and cuts the ndarray.__getitem__ + # time below from 3.8 ms to 496 µs + # if we already have ndarray[bool], the overhead is 1.4 µs or .25% + if isinstance(getattr(key, "dtype", None), ExtensionDtype): + key = key.to_numpy(dtype=bool, na_value=False) + else: + key = np.asarray(key, dtype=bool) + + if not isinstance(self.dtype, ExtensionDtype): + if len(key) == 0 and len(key) != len(self): + warnings.warn( + "Using a boolean indexer with length 0 on an Index with " + "length greater than 0 is deprecated and will raise in a " + "future version.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + result = getitem(key) + # Because we ruled out integer above, we always get an arraylike here + if result.ndim > 1: + disallow_ndim_indexing(result) + + # NB: Using _constructor._simple_new would break if MultiIndex + # didn't override __getitem__ + return self._constructor._simple_new(result, name=self._name) + + def _getitem_slice(self, slobj: slice) -> Self: + """ + Fastpath for __getitem__ when we know we have a slice. + """ + res = self._data[slobj] + result = type(self)._simple_new(res, name=self._name, refs=self._references) + if "_engine" in self._cache: + reverse = slobj.step is not None and slobj.step < 0 + result._engine._update_from_sliced(self._engine, reverse=reverse) # type: ignore[union-attr] + + return result + + @final + def _can_hold_identifiers_and_holds_name(self, name) -> bool: + """ + Faster check for ``name in self`` when we know `name` is a Python + identifier (e.g. in NDFrame.__getattr__, which hits this to support + . key lookup). For indexes that can't hold identifiers (everything + but object & categorical) we just return False. + + https://github.com/pandas-dev/pandas/issues/19764 + """ + if ( + is_object_dtype(self.dtype) + or is_string_dtype(self.dtype) + or isinstance(self.dtype, CategoricalDtype) + ): + return name in self + return False + + def append(self, other: Index | Sequence[Index]) -> Index: + """ + Append a collection of Index options together. + + Parameters + ---------- + other : Index or list/tuple of indices + + Returns + ------- + Index + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx.append(pd.Index([4])) + Index([1, 2, 3, 4], dtype='int64') + """ + to_concat = [self] + + if isinstance(other, (list, tuple)): + to_concat += list(other) + else: + # error: Argument 1 to "append" of "list" has incompatible type + # "Union[Index, Sequence[Index]]"; expected "Index" + to_concat.append(other) # type: ignore[arg-type] + + for obj in to_concat: + if not isinstance(obj, Index): + raise TypeError("all inputs must be Index") + + names = {obj.name for obj in to_concat} + name = None if len(names) > 1 else self.name + + return self._concat(to_concat, name) + + def _concat(self, to_concat: list[Index], name: Hashable) -> Index: + """ + Concatenate multiple Index objects. + """ + to_concat_vals = [x._values for x in to_concat] + + result = concat_compat(to_concat_vals) + + return Index._with_infer(result, name=name) + + def putmask(self, mask, value) -> Index: + """ + Return a new Index of the values set with the mask. + + Returns + ------- + Index + + See Also + -------- + numpy.ndarray.putmask : Changes elements of an array + based on conditional and input values. + + Examples + -------- + >>> idx1 = pd.Index([1, 2, 3]) + >>> idx2 = pd.Index([5, 6, 7]) + >>> idx1.putmask([True, False, False], idx2) + Index([5, 2, 3], dtype='int64') + """ + mask, noop = validate_putmask(self._values, mask) + if noop: + return self.copy() + + if self.dtype != object and is_valid_na_for_dtype(value, self.dtype): + # e.g. None -> np.nan, see also Block._standardize_fill_value + value = self._na_value + + try: + converted = self._validate_fill_value(value) + except (LossySetitemError, ValueError, TypeError) as err: + if is_object_dtype(self.dtype): # pragma: no cover + raise err + + # See also: Block.coerce_to_target_dtype + dtype = self._find_common_type_compat(value) + return self.astype(dtype).putmask(mask, value) + + values = self._values.copy() + + if isinstance(values, np.ndarray): + converted = setitem_datetimelike_compat(values, mask.sum(), converted) + np.putmask(values, mask, converted) + + else: + # Note: we use the original value here, not converted, as + # _validate_fill_value is not idempotent + values._putmask(mask, value) + + return self._shallow_copy(values) + + def equals(self, other: Any) -> bool: + """ + Determine if two Index object are equal. + + The things that are being compared are: + + * The elements inside the Index object. + * The order of the elements inside the Index object. + + Parameters + ---------- + other : Any + The other object to compare against. + + Returns + ------- + bool + True if "other" is an Index and it has the same elements and order + as the calling index; False otherwise. + + Examples + -------- + >>> idx1 = pd.Index([1, 2, 3]) + >>> idx1 + Index([1, 2, 3], dtype='int64') + >>> idx1.equals(pd.Index([1, 2, 3])) + True + + The elements inside are compared + + >>> idx2 = pd.Index(["1", "2", "3"]) + >>> idx2 + Index(['1', '2', '3'], dtype='object') + + >>> idx1.equals(idx2) + False + + The order is compared + + >>> ascending_idx = pd.Index([1, 2, 3]) + >>> ascending_idx + Index([1, 2, 3], dtype='int64') + >>> descending_idx = pd.Index([3, 2, 1]) + >>> descending_idx + Index([3, 2, 1], dtype='int64') + >>> ascending_idx.equals(descending_idx) + False + + The dtype is *not* compared + + >>> int64_idx = pd.Index([1, 2, 3], dtype='int64') + >>> int64_idx + Index([1, 2, 3], dtype='int64') + >>> uint64_idx = pd.Index([1, 2, 3], dtype='uint64') + >>> uint64_idx + Index([1, 2, 3], dtype='uint64') + >>> int64_idx.equals(uint64_idx) + True + """ + if self.is_(other): + return True + + if not isinstance(other, Index): + return False + + if len(self) != len(other): + # quickly return if the lengths are different + return False + + if ( + isinstance(self.dtype, StringDtype) + and self.dtype.na_value is np.nan + and other.dtype != self.dtype + ): + # TODO(infer_string) can we avoid this special case? + # special case for object behavior + return other.equals(self.astype(object)) + + if is_object_dtype(self.dtype) and not is_object_dtype(other.dtype): + # if other is not object, use other's logic for coercion + return other.equals(self) + + if isinstance(other, ABCMultiIndex): + # d-level MultiIndex can equal d-tuple Index + return other.equals(self) + + if isinstance(self._values, ExtensionArray): + # Dispatch to the ExtensionArray's .equals method. + if not isinstance(other, type(self)): + return False + + earr = cast(ExtensionArray, self._data) + return earr.equals(other._data) + + if isinstance(other.dtype, ExtensionDtype): + # All EA-backed Index subclasses override equals + return other.equals(self) + + return array_equivalent(self._values, other._values) + + @final + def identical(self, other) -> bool: + """ + Similar to equals, but checks that object attributes and types are also equal. + + Returns + ------- + bool + If two Index objects have equal elements and same type True, + otherwise False. + + Examples + -------- + >>> idx1 = pd.Index(['1', '2', '3']) + >>> idx2 = pd.Index(['1', '2', '3']) + >>> idx2.identical(idx1) + True + + >>> idx1 = pd.Index(['1', '2', '3'], name="A") + >>> idx2 = pd.Index(['1', '2', '3'], name="B") + >>> idx2.identical(idx1) + False + """ + return ( + self.equals(other) + and all( + getattr(self, c, None) == getattr(other, c, None) + for c in self._comparables + ) + and type(self) == type(other) + and self.dtype == other.dtype + ) + + @final + def asof(self, label): + """ + Return the label from the index, or, if not present, the previous one. + + Assuming that the index is sorted, return the passed index label if it + is in the index, or return the previous index label if the passed one + is not in the index. + + Parameters + ---------- + label : object + The label up to which the method returns the latest index label. + + Returns + ------- + object + The passed label if it is in the index. The previous label if the + passed label is not in the sorted index or `NaN` if there is no + such label. + + See Also + -------- + Series.asof : Return the latest value in a Series up to the + passed index. + merge_asof : Perform an asof merge (similar to left join but it + matches on nearest key rather than equal key). + Index.get_loc : An `asof` is a thin wrapper around `get_loc` + with method='pad'. + + Examples + -------- + `Index.asof` returns the latest index label up to the passed label. + + >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03']) + >>> idx.asof('2014-01-01') + '2013-12-31' + + If the label is in the index, the method returns the passed label. + + >>> idx.asof('2014-01-02') + '2014-01-02' + + If all of the labels in the index are later than the passed label, + NaN is returned. + + >>> idx.asof('1999-01-02') + nan + + If the index is not sorted, an error is raised. + + >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02', + ... '2014-01-03']) + >>> idx_not_sorted.asof('2013-12-31') + Traceback (most recent call last): + ValueError: index must be monotonic increasing or decreasing + """ + self._searchsorted_monotonic(label) # validate sortedness + try: + loc = self.get_loc(label) + except (KeyError, TypeError): + # KeyError -> No exact match, try for padded + # TypeError -> passed e.g. non-hashable, fall through to get + # the tested exception message + indexer = self.get_indexer([label], method="pad") + if indexer.ndim > 1 or indexer.size > 1: + raise TypeError("asof requires scalar valued input") + loc = indexer.item() + if loc == -1: + return self._na_value + else: + if isinstance(loc, slice): + loc = loc.indices(len(self))[-1] + + return self[loc] + + def asof_locs( + self, where: Index, mask: npt.NDArray[np.bool_] + ) -> npt.NDArray[np.intp]: + """ + Return the locations (indices) of labels in the index. + + As in the :meth:`pandas.Index.asof`, if the label (a particular entry in + ``where``) is not in the index, the latest index label up to the + passed label is chosen and its index returned. + + If all of the labels in the index are later than a label in ``where``, + -1 is returned. + + ``mask`` is used to ignore ``NA`` values in the index during calculation. + + Parameters + ---------- + where : Index + An Index consisting of an array of timestamps. + mask : np.ndarray[bool] + Array of booleans denoting where values in the original + data are not ``NA``. + + Returns + ------- + np.ndarray[np.intp] + An array of locations (indices) of the labels from the index + which correspond to the return values of :meth:`pandas.Index.asof` + for every element in ``where``. + + See Also + -------- + Index.asof : Return the label from the index, or, if not present, the + previous one. + + Examples + -------- + >>> idx = pd.date_range('2023-06-01', periods=3, freq='D') + >>> where = pd.DatetimeIndex(['2023-05-30 00:12:00', '2023-06-01 00:00:00', + ... '2023-06-02 23:59:59']) + >>> mask = np.ones(3, dtype=bool) + >>> idx.asof_locs(where, mask) + array([-1, 0, 1]) + + We can use ``mask`` to ignore certain values in the index during calculation. + + >>> mask[1] = False + >>> idx.asof_locs(where, mask) + array([-1, 0, 0]) + """ + # error: No overload variant of "searchsorted" of "ndarray" matches argument + # types "Union[ExtensionArray, ndarray[Any, Any]]", "str" + # TODO: will be fixed when ExtensionArray.searchsorted() is fixed + locs = self._values[mask].searchsorted( + where._values, side="right" # type: ignore[call-overload] + ) + locs = np.where(locs > 0, locs - 1, 0) + + result = np.arange(len(self), dtype=np.intp)[mask].take(locs) + + first_value = self._values[mask.argmax()] + result[(locs == 0) & (where._values < first_value)] = -1 + + return result + + @overload + def sort_values( + self, + *, + return_indexer: Literal[False] = ..., + ascending: bool = ..., + na_position: NaPosition = ..., + key: Callable | None = ..., + ) -> Self: + ... + + @overload + def sort_values( + self, + *, + return_indexer: Literal[True], + ascending: bool = ..., + na_position: NaPosition = ..., + key: Callable | None = ..., + ) -> tuple[Self, np.ndarray]: + ... + + @overload + def sort_values( + self, + *, + return_indexer: bool = ..., + ascending: bool = ..., + na_position: NaPosition = ..., + key: Callable | None = ..., + ) -> Self | tuple[Self, np.ndarray]: + ... + + @deprecate_nonkeyword_arguments( + version="3.0", allowed_args=["self"], name="sort_values" + ) + def sort_values( + self, + return_indexer: bool = False, + ascending: bool = True, + na_position: NaPosition = "last", + key: Callable | None = None, + ) -> Self | tuple[Self, np.ndarray]: + """ + Return a sorted copy of the index. + + Return a sorted copy of the index, and optionally return the indices + that sorted the index itself. + + Parameters + ---------- + return_indexer : bool, default False + Should the indices that would sort the index be returned. + ascending : bool, default True + Should the index values be sorted in an ascending order. + na_position : {'first' or 'last'}, default 'last' + Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at + the end. + key : callable, optional + If not None, apply the key function to the index values + before sorting. This is similar to the `key` argument in the + builtin :meth:`sorted` function, with the notable difference that + this `key` function should be *vectorized*. It should expect an + ``Index`` and return an ``Index`` of the same shape. + + Returns + ------- + sorted_index : pandas.Index + Sorted copy of the index. + indexer : numpy.ndarray, optional + The indices that the index itself was sorted by. + + See Also + -------- + Series.sort_values : Sort values of a Series. + DataFrame.sort_values : Sort values in a DataFrame. + + Examples + -------- + >>> idx = pd.Index([10, 100, 1, 1000]) + >>> idx + Index([10, 100, 1, 1000], dtype='int64') + + Sort values in ascending order (default behavior). + + >>> idx.sort_values() + Index([1, 10, 100, 1000], dtype='int64') + + Sort values in descending order, and also get the indices `idx` was + sorted by. + + >>> idx.sort_values(ascending=False, return_indexer=True) + (Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2])) + """ + if key is None and ( + (ascending and self.is_monotonic_increasing) + or (not ascending and self.is_monotonic_decreasing) + ): + if return_indexer: + indexer = np.arange(len(self), dtype=np.intp) + return self.copy(), indexer + else: + return self.copy() + + # GH 35584. Sort missing values according to na_position kwarg + # ignore na_position for MultiIndex + if not isinstance(self, ABCMultiIndex): + _as = nargsort( + items=self, ascending=ascending, na_position=na_position, key=key + ) + else: + idx = cast(Index, ensure_key_mapped(self, key)) + _as = idx.argsort(na_position=na_position) + if not ascending: + _as = _as[::-1] + + sorted_index = self.take(_as) + + if return_indexer: + return sorted_index, _as + else: + return sorted_index + + @final + def sort(self, *args, **kwargs): + """ + Use sort_values instead. + """ + raise TypeError("cannot sort an Index object in-place, use sort_values instead") + + def shift(self, periods: int = 1, freq=None): + """ + Shift index by desired number of time frequency increments. + + This method is for shifting the values of datetime-like indexes + by a specified time increment a given number of times. + + Parameters + ---------- + periods : int, default 1 + Number of periods (or increments) to shift by, + can be positive or negative. + freq : pandas.DateOffset, pandas.Timedelta or str, optional + Frequency increment to shift by. + If None, the index is shifted by its own `freq` attribute. + Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc. + + Returns + ------- + pandas.Index + Shifted index. + + See Also + -------- + Series.shift : Shift values of Series. + + Notes + ----- + This method is only implemented for datetime-like index classes, + i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex. + + Examples + -------- + Put the first 5 month starts of 2011 into an index. + + >>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS') + >>> month_starts + DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01', + '2011-05-01'], + dtype='datetime64[ns]', freq='MS') + + Shift the index by 10 days. + + >>> month_starts.shift(10, freq='D') + DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11', + '2011-05-11'], + dtype='datetime64[ns]', freq=None) + + The default value of `freq` is the `freq` attribute of the index, + which is 'MS' (month start) in this example. + + >>> month_starts.shift(10) + DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01', + '2012-03-01'], + dtype='datetime64[ns]', freq='MS') + """ + raise NotImplementedError( + f"This method is only implemented for DatetimeIndex, PeriodIndex and " + f"TimedeltaIndex; Got type {type(self).__name__}" + ) + + def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]: + """ + Return the integer indices that would sort the index. + + Parameters + ---------- + *args + Passed to `numpy.ndarray.argsort`. + **kwargs + Passed to `numpy.ndarray.argsort`. + + Returns + ------- + np.ndarray[np.intp] + Integer indices that would sort the index if used as + an indexer. + + See Also + -------- + numpy.argsort : Similar method for NumPy arrays. + Index.sort_values : Return sorted copy of Index. + + Examples + -------- + >>> idx = pd.Index(['b', 'a', 'd', 'c']) + >>> idx + Index(['b', 'a', 'd', 'c'], dtype='object') + + >>> order = idx.argsort() + >>> order + array([1, 0, 3, 2]) + + >>> idx[order] + Index(['a', 'b', 'c', 'd'], dtype='object') + """ + # This works for either ndarray or EA, is overridden + # by RangeIndex, MultIIndex + return self._data.argsort(*args, **kwargs) + + def _check_indexing_error(self, key): + if not is_scalar(key): + # if key is not a scalar, directly raise an error (the code below + # would convert to numpy arrays and raise later any way) - GH29926 + raise InvalidIndexError(key) + + @cache_readonly + def _should_fallback_to_positional(self) -> bool: + """ + Should an integer key be treated as positional? + """ + return self.inferred_type not in { + "integer", + "mixed-integer", + "floating", + "complex", + } + + _index_shared_docs[ + "get_indexer_non_unique" + ] = """ + Compute indexer and mask for new index given the current index. + + The indexer should be then used as an input to ndarray.take to align the + current data to the new index. + + Parameters + ---------- + target : %(target_klass)s + + Returns + ------- + indexer : np.ndarray[np.intp] + Integers from 0 to n - 1 indicating that the index at these + positions matches the corresponding target values. Missing values + in the target are marked by -1. + missing : np.ndarray[np.intp] + An indexer into the target of the values not found. + These correspond to the -1 in the indexer array. + + Examples + -------- + >>> index = pd.Index(['c', 'b', 'a', 'b', 'b']) + >>> index.get_indexer_non_unique(['b', 'b']) + (array([1, 3, 4, 1, 3, 4]), array([], dtype=int64)) + + In the example below there are no matched values. + + >>> index = pd.Index(['c', 'b', 'a', 'b', 'b']) + >>> index.get_indexer_non_unique(['q', 'r', 't']) + (array([-1, -1, -1]), array([0, 1, 2])) + + For this reason, the returned ``indexer`` contains only integers equal to -1. + It demonstrates that there's no match between the index and the ``target`` + values at these positions. The mask [0, 1, 2] in the return value shows that + the first, second, and third elements are missing. + + Notice that the return value is a tuple contains two items. In the example + below the first item is an array of locations in ``index``. The second + item is a mask shows that the first and third elements are missing. + + >>> index = pd.Index(['c', 'b', 'a', 'b', 'b']) + >>> index.get_indexer_non_unique(['f', 'b', 's']) + (array([-1, 1, 3, 4, -1]), array([0, 2])) + """ + + @Appender(_index_shared_docs["get_indexer_non_unique"] % _index_doc_kwargs) + def get_indexer_non_unique( + self, target + ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + target = self._maybe_cast_listlike_indexer(target) + + if not self._should_compare(target) and not self._should_partial_index(target): + # _should_partial_index e.g. IntervalIndex with numeric scalars + # that can be matched to Interval scalars. + return self._get_indexer_non_comparable(target, method=None, unique=False) + + pself, ptarget = self._maybe_downcast_for_indexing(target) + if pself is not self or ptarget is not target: + return pself.get_indexer_non_unique(ptarget) + + if self.dtype != target.dtype: + # TODO: if object, could use infer_dtype to preempt costly + # conversion if still non-comparable? + dtype = self._find_common_type_compat(target) + + this = self.astype(dtype, copy=False) + that = target.astype(dtype, copy=False) + return this.get_indexer_non_unique(that) + + # TODO: get_indexer has fastpaths for both Categorical-self and + # Categorical-target. Can we do something similar here? + + # Note: _maybe_downcast_for_indexing ensures we never get here + # with MultiIndex self and non-Multi target + if self._is_multi and target._is_multi: + engine = self._engine + # Item "IndexEngine" of "Union[IndexEngine, ExtensionEngine]" has + # no attribute "_extract_level_codes" + tgt_values = engine._extract_level_codes(target) # type: ignore[union-attr] + else: + tgt_values = target._get_engine_target() + + indexer, missing = self._engine.get_indexer_non_unique(tgt_values) + return ensure_platform_int(indexer), ensure_platform_int(missing) + + @final + def get_indexer_for(self, target) -> npt.NDArray[np.intp]: + """ + Guaranteed return of an indexer even when non-unique. + + This dispatches to get_indexer or get_indexer_non_unique + as appropriate. + + Returns + ------- + np.ndarray[np.intp] + List of indices. + + Examples + -------- + >>> idx = pd.Index([np.nan, 'var1', np.nan]) + >>> idx.get_indexer_for([np.nan]) + array([0, 2]) + """ + if self._index_as_unique: + return self.get_indexer(target) + indexer, _ = self.get_indexer_non_unique(target) + return indexer + + def _get_indexer_strict(self, key, axis_name: str_t) -> tuple[Index, np.ndarray]: + """ + Analogue to get_indexer that raises if any elements are missing. + """ + keyarr = key + if not isinstance(keyarr, Index): + keyarr = com.asarray_tuplesafe(keyarr) + + if self._index_as_unique: + indexer = self.get_indexer_for(keyarr) + keyarr = self.reindex(keyarr)[0] + else: + keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr) + + self._raise_if_missing(keyarr, indexer, axis_name) + + keyarr = self.take(indexer) + if isinstance(key, Index): + # GH 42790 - Preserve name from an Index + keyarr.name = key.name + if lib.is_np_dtype(keyarr.dtype, "mM") or isinstance( + keyarr.dtype, DatetimeTZDtype + ): + # DTI/TDI.take can infer a freq in some cases when we dont want one + if isinstance(key, list) or ( + isinstance(key, type(self)) + # "Index" has no attribute "freq" + and key.freq is None # type: ignore[attr-defined] + ): + keyarr = keyarr._with_freq(None) + + return keyarr, indexer + + def _raise_if_missing(self, key, indexer, axis_name: str_t) -> None: + """ + Check that indexer can be used to return a result. + + e.g. at least one element was found, + unless the list of keys was actually empty. + + Parameters + ---------- + key : list-like + Targeted labels (only used to show correct error message). + indexer: array-like of booleans + Indices corresponding to the key, + (with -1 indicating not found). + axis_name : str + + Raises + ------ + KeyError + If at least one key was requested but none was found. + """ + if len(key) == 0: + return + + # Count missing values + missing_mask = indexer < 0 + nmissing = missing_mask.sum() + + if nmissing: + if nmissing == len(indexer): + raise KeyError(f"None of [{key}] are in the [{axis_name}]") + + not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique()) + raise KeyError(f"{not_found} not in index") + + @overload + def _get_indexer_non_comparable( + self, target: Index, method, unique: Literal[True] = ... + ) -> npt.NDArray[np.intp]: + ... + + @overload + def _get_indexer_non_comparable( + self, target: Index, method, unique: Literal[False] + ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + ... + + @overload + def _get_indexer_non_comparable( + self, target: Index, method, unique: bool = True + ) -> npt.NDArray[np.intp] | tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + ... + + @final + def _get_indexer_non_comparable( + self, target: Index, method, unique: bool = True + ) -> npt.NDArray[np.intp] | tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: + """ + Called from get_indexer or get_indexer_non_unique when the target + is of a non-comparable dtype. + + For get_indexer lookups with method=None, get_indexer is an _equality_ + check, so non-comparable dtypes mean we will always have no matches. + + For get_indexer lookups with a method, get_indexer is an _inequality_ + check, so non-comparable dtypes mean we will always raise TypeError. + + Parameters + ---------- + target : Index + method : str or None + unique : bool, default True + * True if called from get_indexer. + * False if called from get_indexer_non_unique. + + Raises + ------ + TypeError + If doing an inequality check, i.e. method is not None. + """ + if method is not None: + other_dtype = _unpack_nested_dtype(target) + raise TypeError(f"Cannot compare dtypes {self.dtype} and {other_dtype}") + + no_matches = -1 * np.ones(target.shape, dtype=np.intp) + if unique: + # This is for get_indexer + return no_matches + else: + # This is for get_indexer_non_unique + missing = np.arange(len(target), dtype=np.intp) + return no_matches, missing + + @property + def _index_as_unique(self) -> bool: + """ + Whether we should treat this as unique for the sake of + get_indexer vs get_indexer_non_unique. + + For IntervalIndex compat. + """ + return self.is_unique + + _requires_unique_msg = "Reindexing only valid with uniquely valued Index objects" + + @final + def _maybe_downcast_for_indexing(self, other: Index) -> tuple[Index, Index]: + """ + When dealing with an object-dtype Index and a non-object Index, see + if we can upcast the object-dtype one to improve performance. + """ + + if isinstance(self, ABCDatetimeIndex) and isinstance(other, ABCDatetimeIndex): + if ( + self.tz is not None + and other.tz is not None + and not tz_compare(self.tz, other.tz) + ): + # standardize on UTC + return self.tz_convert("UTC"), other.tz_convert("UTC") + + elif self.inferred_type == "date" and isinstance(other, ABCDatetimeIndex): + try: + return type(other)(self), other + except OutOfBoundsDatetime: + return self, other + elif self.inferred_type == "timedelta" and isinstance(other, ABCTimedeltaIndex): + # TODO: we dont have tests that get here + return type(other)(self), other + + elif self.dtype.kind == "u" and other.dtype.kind == "i": + # GH#41873 + if other.min() >= 0: + # lookup min as it may be cached + # TODO: may need itemsize check if we have non-64-bit Indexes + return self, other.astype(self.dtype) + + elif self._is_multi and not other._is_multi: + try: + # "Type[Index]" has no attribute "from_tuples" + other = type(self).from_tuples(other) # type: ignore[attr-defined] + except (TypeError, ValueError): + # let's instead try with a straight Index + self = Index(self._values) + + if not is_object_dtype(self.dtype) and is_object_dtype(other.dtype): + # Reverse op so we dont need to re-implement on the subclasses + other, self = other._maybe_downcast_for_indexing(self) + + return self, other + + @final + def _find_common_type_compat(self, target) -> DtypeObj: + """ + Implementation of find_common_type that adjusts for Index-specific + special cases. + """ + target_dtype, _ = infer_dtype_from(target) + + if using_string_dtype(): + # special case: if left or right is a zero-length RangeIndex or + # Index[object], those can be created by the default empty constructors + # -> for that case ignore this dtype and always return the other + # (https://github.com/pandas-dev/pandas/pull/60797) + from pandas.core.indexes.range import RangeIndex + + if len(self) == 0 and ( + isinstance(self, RangeIndex) or self.dtype == np.object_ + ): + if target_dtype.kind == "M": + if hasattr(target_dtype, "tz"): + target_dtype_ns = DatetimeTZDtype("ns", tz=target_dtype.tz) + else: + target_dtype_ns = np.dtype("datetime64[ns]") # type: ignore[assignment] + try: + Index(target, dtype=target_dtype_ns, copy=False) + except OutOfBoundsDatetime: + return np.dtype(object) + except Exception: + pass + return target_dtype_ns + return target_dtype + if ( + isinstance(target, Index) + and len(target) == 0 + and (isinstance(target, RangeIndex) or target_dtype == np.object_) + ): + return self.dtype + + # special case: if one dtype is uint64 and the other a signed int, return object + # See https://github.com/pandas-dev/pandas/issues/26778 for discussion + # Now it's: + # * float | [u]int -> float + # * uint64 | signed int -> object + # We may change union(float | [u]int) to go to object. + if self.dtype == "uint64" or target_dtype == "uint64": + if is_signed_integer_dtype(self.dtype) or is_signed_integer_dtype( + target_dtype + ): + return _dtype_obj + + dtype = find_result_type(self.dtype, target) + dtype = common_dtype_categorical_compat([self, target], dtype) + return dtype + + @final + def _should_compare(self, other: Index) -> bool: + """ + Check if `self == other` can ever have non-False entries. + """ + + # NB: we use inferred_type rather than is_bool_dtype to catch + # object_dtype_of_bool and categorical[object_dtype_of_bool] cases + if ( + other.inferred_type == "boolean" and is_any_real_numeric_dtype(self.dtype) + ) or ( + self.inferred_type == "boolean" and is_any_real_numeric_dtype(other.dtype) + ): + # GH#16877 Treat boolean labels passed to a numeric index as not + # found. Without this fix False and True would be treated as 0 and 1 + # respectively. + return False + + dtype = _unpack_nested_dtype(other) + return ( + self._is_comparable_dtype(dtype) + or is_object_dtype(dtype) + or is_string_dtype(dtype) + ) + + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + """ + Can we compare values of the given dtype to our own? + """ + if self.dtype.kind == "b": + return dtype.kind == "b" + elif is_numeric_dtype(self.dtype): + return is_numeric_dtype(dtype) + # TODO: this was written assuming we only get here with object-dtype, + # which is no longer correct. Can we specialize for EA? + return True + + @final + def groupby(self, values) -> PrettyDict[Hashable, np.ndarray]: + """ + Group the index labels by a given array of values. + + Parameters + ---------- + values : array + Values used to determine the groups. + + Returns + ------- + dict + {group name -> group labels} + """ + # TODO: if we are a MultiIndex, we can do better + # that converting to tuples + if isinstance(values, ABCMultiIndex): + values = values._values + values = Categorical(values) + result = values._reverse_indexer() + + # map to the label + result = {k: self.take(v) for k, v in result.items()} + + return PrettyDict(result) + + def map(self, mapper, na_action: Literal["ignore"] | None = None): + """ + Map values using an input mapping or function. + + Parameters + ---------- + mapper : function, dict, or Series + Mapping correspondence. + na_action : {None, 'ignore'} + If 'ignore', propagate NA values, without passing them to the + mapping correspondence. + + Returns + ------- + Union[Index, MultiIndex] + The output of the mapping function applied to the index. + If the function returns a tuple with more than one element + a MultiIndex will be returned. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx.map({1: 'a', 2: 'b', 3: 'c'}) + Index(['a', 'b', 'c'], dtype='object') + + Using `map` with a function: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx.map('I am a {}'.format) + Index(['I am a 1', 'I am a 2', 'I am a 3'], dtype='object') + + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx.map(lambda x: x.upper()) + Index(['A', 'B', 'C'], dtype='object') + """ + from pandas.core.indexes.multi import MultiIndex + + new_values = self._map_values(mapper, na_action=na_action) + + # we can return a MultiIndex + if new_values.size and isinstance(new_values[0], tuple): + if isinstance(self, MultiIndex): + names = self.names + elif self.name: + names = [self.name] * len(new_values[0]) + else: + names = None + return MultiIndex.from_tuples(new_values, names=names) + + dtype = None + if not new_values.size: + # empty + dtype = self.dtype + + # e.g. if we are floating and new_values is all ints, then we + # don't want to cast back to floating. But if we are UInt64 + # and new_values is all ints, we want to try. + same_dtype = lib.infer_dtype(new_values, skipna=False) == self.inferred_type + if same_dtype: + new_values = maybe_cast_pointwise_result( + new_values, self.dtype, same_dtype=same_dtype + ) + + return Index._with_infer(new_values, dtype=dtype, copy=False, name=self.name) + + # TODO: De-duplicate with map, xref GH#32349 + @final + def _transform_index(self, func, *, level=None) -> Index: + """ + Apply function to all values found in index. + + This includes transforming multiindex entries separately. + Only apply function to one level of the MultiIndex if level is specified. + """ + if isinstance(self, ABCMultiIndex): + values = [ + self.get_level_values(i).map(func) + if i == level or level is None + else self.get_level_values(i) + for i in range(self.nlevels) + ] + return type(self).from_arrays(values) + else: + items = [func(x) for x in self] + return Index(items, name=self.name, tupleize_cols=False) + + def isin(self, values, level=None) -> npt.NDArray[np.bool_]: + """ + Return a boolean array where the index values are in `values`. + + Compute boolean array of whether each index value is found in the + passed set of values. The length of the returned boolean array matches + the length of the index. + + Parameters + ---------- + values : set or list-like + Sought values. + level : str or int, optional + Name or position of the index level to use (if the index is a + `MultiIndex`). + + Returns + ------- + np.ndarray[bool] + NumPy array of boolean values. + + See Also + -------- + Series.isin : Same for Series. + DataFrame.isin : Same method for DataFrames. + + Notes + ----- + In the case of `MultiIndex` you must either specify `values` as a + list-like object containing tuples that are the same length as the + number of levels, or specify `level`. Otherwise it will raise a + ``ValueError``. + + If `level` is specified: + + - if it is the name of one *and only one* index level, use that level; + - otherwise it should be a number indicating level position. + + Examples + -------- + >>> idx = pd.Index([1,2,3]) + >>> idx + Index([1, 2, 3], dtype='int64') + + Check whether each index value in a list of values. + + >>> idx.isin([1, 4]) + array([ True, False, False]) + + >>> midx = pd.MultiIndex.from_arrays([[1,2,3], + ... ['red', 'blue', 'green']], + ... names=('number', 'color')) + >>> midx + MultiIndex([(1, 'red'), + (2, 'blue'), + (3, 'green')], + names=['number', 'color']) + + Check whether the strings in the 'color' level of the MultiIndex + are in a list of colors. + + >>> midx.isin(['red', 'orange', 'yellow'], level='color') + array([ True, False, False]) + + To check across the levels of a MultiIndex, pass a list of tuples: + + >>> midx.isin([(1, 'red'), (3, 'red')]) + array([ True, False, False]) + """ + if level is not None: + self._validate_index_level(level) + return algos.isin(self._values, values) + + def _get_string_slice(self, key: str_t): + # this is for partial string indexing, + # overridden in DatetimeIndex, TimedeltaIndex and PeriodIndex + raise NotImplementedError + + def slice_indexer( + self, + start: Hashable | None = None, + end: Hashable | None = None, + step: int | None = None, + ) -> slice: + """ + Compute the slice indexer for input labels and step. + + Index needs to be ordered and unique. + + Parameters + ---------- + start : label, default None + If None, defaults to the beginning. + end : label, default None + If None, defaults to the end. + step : int, default None + + Returns + ------- + slice + + Raises + ------ + KeyError : If key does not exist, or key is not unique and index is + not ordered. + + Notes + ----- + This function assumes that the data is sorted, so use at your own peril + + Examples + -------- + This is a method on all index types. For example you can do: + + >>> idx = pd.Index(list('abcd')) + >>> idx.slice_indexer(start='b', end='c') + slice(1, 3, None) + + >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')]) + >>> idx.slice_indexer(start='b', end=('c', 'g')) + slice(1, 3, None) + """ + start_slice, end_slice = self.slice_locs(start, end, step=step) + + # return a slice + if not is_scalar(start_slice): + raise AssertionError("Start slice bound is non-scalar") + if not is_scalar(end_slice): + raise AssertionError("End slice bound is non-scalar") + + return slice(start_slice, end_slice, step) + + def _maybe_cast_indexer(self, key): + """ + If we have a float key and are not a floating index, then try to cast + to an int if equivalent. + """ + return key + + def _maybe_cast_listlike_indexer(self, target) -> Index: + """ + Analogue to maybe_cast_indexer for get_indexer instead of get_loc. + """ + target_index = ensure_index(target) + if ( + not hasattr(target, "dtype") + and self.dtype == object + and target_index.dtype == "string" + ): + # If we started with a list-like, avoid inference to string dtype if self + # is object dtype (coercing to string dtype will alter the missing values) + target_index = Index(target, dtype=self.dtype) + return target_index + + @final + def _validate_indexer( + self, + form: Literal["positional", "slice"], + key, + kind: Literal["getitem", "iloc"], + ) -> None: + """ + If we are positional indexer, validate that we have appropriate + typed bounds must be an integer. + """ + if not lib.is_int_or_none(key): + self._raise_invalid_indexer(form, key) + + def _maybe_cast_slice_bound(self, label, side: str_t): + """ + This function should be overloaded in subclasses that allow non-trivial + casting on label-slice bounds, e.g. datetime-like indices allowing + strings containing formatted datetimes. + + Parameters + ---------- + label : object + side : {'left', 'right'} + + Returns + ------- + label : object + + Notes + ----- + Value of `side` parameter should be validated in caller. + """ + + # We are a plain index here (sub-class override this method if they + # wish to have special treatment for floats/ints, e.g. datetimelike Indexes + + if is_numeric_dtype(self.dtype): + return self._maybe_cast_indexer(label) + + # reject them, if index does not contain label + if (is_float(label) or is_integer(label)) and label not in self: + self._raise_invalid_indexer("slice", label) + + return label + + def _searchsorted_monotonic(self, label, side: Literal["left", "right"] = "left"): + if self.is_monotonic_increasing: + return self.searchsorted(label, side=side) + elif self.is_monotonic_decreasing: + # np.searchsorted expects ascending sort order, have to reverse + # everything for it to work (element ordering, search side and + # resulting value). + pos = self[::-1].searchsorted( + label, side="right" if side == "left" else "left" + ) + return len(self) - pos + + raise ValueError("index must be monotonic increasing or decreasing") + + def get_slice_bound(self, label, side: Literal["left", "right"]) -> int: + """ + Calculate slice bound that corresponds to given label. + + Returns leftmost (one-past-the-rightmost if ``side=='right'``) position + of given label. + + Parameters + ---------- + label : object + side : {'left', 'right'} + + Returns + ------- + int + Index of label. + + See Also + -------- + Index.get_loc : Get integer location, slice or boolean mask for requested + label. + + Examples + -------- + >>> idx = pd.RangeIndex(5) + >>> idx.get_slice_bound(3, 'left') + 3 + + >>> idx.get_slice_bound(3, 'right') + 4 + + If ``label`` is non-unique in the index, an error will be raised. + + >>> idx_duplicate = pd.Index(['a', 'b', 'a', 'c', 'd']) + >>> idx_duplicate.get_slice_bound('a', 'left') + Traceback (most recent call last): + KeyError: Cannot get left slice bound for non-unique label: 'a' + """ + + if side not in ("left", "right"): + raise ValueError( + "Invalid value for side kwarg, must be either " + f"'left' or 'right': {side}" + ) + + original_label = label + + # For datetime indices label may be a string that has to be converted + # to datetime boundary according to its resolution. + label = self._maybe_cast_slice_bound(label, side) + + # we need to look up the label + try: + slc = self.get_loc(label) + except KeyError as err: + try: + return self._searchsorted_monotonic(label, side) + except ValueError: + # raise the original KeyError + raise err + + if isinstance(slc, np.ndarray): + # get_loc may return a boolean array, which + # is OK as long as they are representable by a slice. + assert is_bool_dtype(slc.dtype) + slc = lib.maybe_booleans_to_slice(slc.view("u1")) + if isinstance(slc, np.ndarray): + raise KeyError( + f"Cannot get {side} slice bound for non-unique " + f"label: {repr(original_label)}" + ) + + if isinstance(slc, slice): + if side == "left": + return slc.start + else: + return slc.stop + else: + if side == "right": + return slc + 1 + else: + return slc + + def slice_locs(self, start=None, end=None, step=None) -> tuple[int, int]: + """ + Compute slice locations for input labels. + + Parameters + ---------- + start : label, default None + If None, defaults to the beginning. + end : label, default None + If None, defaults to the end. + step : int, defaults None + If None, defaults to 1. + + Returns + ------- + tuple[int, int] + + See Also + -------- + Index.get_loc : Get location for a single label. + + Notes + ----- + This method only works if the index is monotonic or unique. + + Examples + -------- + >>> idx = pd.Index(list('abcd')) + >>> idx.slice_locs(start='b', end='c') + (1, 3) + """ + inc = step is None or step >= 0 + + if not inc: + # If it's a reverse slice, temporarily swap bounds. + start, end = end, start + + # GH 16785: If start and end happen to be date strings with UTC offsets + # attempt to parse and check that the offsets are the same + if isinstance(start, (str, datetime)) and isinstance(end, (str, datetime)): + try: + ts_start = Timestamp(start) + ts_end = Timestamp(end) + except (ValueError, TypeError): + pass + else: + if not tz_compare(ts_start.tzinfo, ts_end.tzinfo): + raise ValueError("Both dates must have the same UTC offset") + + start_slice = None + if start is not None: + start_slice = self.get_slice_bound(start, "left") + if start_slice is None: + start_slice = 0 + + end_slice = None + if end is not None: + end_slice = self.get_slice_bound(end, "right") + if end_slice is None: + end_slice = len(self) + + if not inc: + # Bounds at this moment are swapped, swap them back and shift by 1. + # + # slice_locs('B', 'A', step=-1): s='B', e='A' + # + # s='A' e='B' + # AFTER SWAP: | | + # v ------------------> V + # ----------------------------------- + # | | |A|A|A|A| | | | | |B|B| | | | | + # ----------------------------------- + # ^ <------------------ ^ + # SHOULD BE: | | + # end=s-1 start=e-1 + # + end_slice, start_slice = start_slice - 1, end_slice - 1 + + # i == -1 triggers ``len(self) + i`` selection that points to the + # last element, not before-the-first one, subtracting len(self) + # compensates that. + if end_slice == -1: + end_slice -= len(self) + if start_slice == -1: + start_slice -= len(self) + + return start_slice, end_slice + + def delete(self, loc) -> Self: + """ + Make new Index with passed location(-s) deleted. + + Parameters + ---------- + loc : int or list of int + Location of item(-s) which will be deleted. + Use a list of locations to delete more than one value at the same time. + + Returns + ------- + Index + Will be same type as self, except for RangeIndex. + + See Also + -------- + numpy.delete : Delete any rows and column from NumPy array (ndarray). + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx.delete(1) + Index(['a', 'c'], dtype='object') + + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx.delete([0, 2]) + Index(['b'], dtype='object') + """ + values = self._values + res_values: ArrayLike + if isinstance(values, np.ndarray): + # TODO(__array_function__): special casing will be unnecessary + res_values = np.delete(values, loc) + else: + res_values = values.delete(loc) + + # _constructor so RangeIndex-> Index with an int64 dtype + return self._constructor._simple_new(res_values, name=self.name) + + def insert(self, loc: int, item) -> Index: + """ + Make new Index inserting new item at location. + + Follows Python numpy.insert semantics for negative values. + + Parameters + ---------- + loc : int + item : object + + Returns + ------- + Index + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx.insert(1, 'x') + Index(['a', 'x', 'b', 'c'], dtype='object') + """ + item = lib.item_from_zerodim(item) + if is_valid_na_for_dtype(item, self.dtype) and self.dtype != object: + item = self._na_value + + arr = self._values + + if using_string_dtype() and len(self) == 0 and self.dtype == np.object_: + # special case: if we are an empty object-dtype Index, also + # take into account the inserted item for the resulting dtype + # (https://github.com/pandas-dev/pandas/pull/60797) + dtype = self._find_common_type_compat(item) + if dtype != self.dtype: + return self.astype(dtype).insert(loc, item) + + try: + if isinstance(arr, ExtensionArray): + res_values = arr.insert(loc, item) + return type(self)._simple_new(res_values, name=self.name) + else: + item = self._validate_fill_value(item) + except (TypeError, ValueError, LossySetitemError): + # e.g. trying to insert an integer into a DatetimeIndex + # We cannot keep the same dtype, so cast to the (often object) + # minimal shared dtype before doing the insert. + dtype = self._find_common_type_compat(item) + if dtype == self.dtype: + # EA's might run into recursion errors if loc is invalid + raise + return self.astype(dtype).insert(loc, item) + + if arr.dtype != object or not isinstance( + item, (tuple, np.datetime64, np.timedelta64) + ): + # with object-dtype we need to worry about numpy incorrectly casting + # dt64/td64 to integer, also about treating tuples as sequences + # special-casing dt64/td64 https://github.com/numpy/numpy/issues/12550 + casted = arr.dtype.type(item) + new_values = np.insert(arr, loc, casted) + + else: + # error: No overload variant of "insert" matches argument types + # "ndarray[Any, Any]", "int", "None" + new_values = np.insert(arr, loc, None) # type: ignore[call-overload] + loc = loc if loc >= 0 else loc - 1 + new_values[loc] = item + + out = Index._with_infer(new_values, name=self.name) + if ( + using_string_dtype() + and is_string_dtype(out.dtype) + and new_values.dtype == object + ): + out = out.astype(new_values.dtype) + if self.dtype == object and out.dtype != object: + # GH#51363 + warnings.warn( + "The behavior of Index.insert with object-dtype is deprecated, " + "in a future version this will return an object-dtype Index " + "instead of inferring a non-object dtype. To retain the old " + "behavior, do `idx.insert(loc, item).infer_objects(copy=False)`", + FutureWarning, + stacklevel=find_stack_level(), + ) + return out + + def drop( + self, + labels: Index | np.ndarray | Iterable[Hashable], + errors: IgnoreRaise = "raise", + ) -> Index: + """ + Make new Index with passed list of labels deleted. + + Parameters + ---------- + labels : array-like or scalar + errors : {'ignore', 'raise'}, default 'raise' + If 'ignore', suppress error and existing labels are dropped. + + Returns + ------- + Index + Will be same type as self, except for RangeIndex. + + Raises + ------ + KeyError + If not all of the labels are found in the selected axis + + Examples + -------- + >>> idx = pd.Index(['a', 'b', 'c']) + >>> idx.drop(['a']) + Index(['b', 'c'], dtype='object') + """ + if not isinstance(labels, Index): + # avoid materializing e.g. RangeIndex + arr_dtype = "object" if self.dtype == "object" else None + labels = com.index_labels_to_array(labels, dtype=arr_dtype) + + indexer = self.get_indexer_for(labels) + mask = indexer == -1 + if mask.any(): + if errors != "ignore": + raise KeyError(f"{labels[mask].tolist()} not found in axis") + indexer = indexer[~mask] + return self.delete(indexer) + + @final + def infer_objects(self, copy: bool = True) -> Index: + """ + If we have an object dtype, try to infer a non-object dtype. + + Parameters + ---------- + copy : bool, default True + Whether to make a copy in cases where no inference occurs. + """ + if self._is_multi: + raise NotImplementedError( + "infer_objects is not implemented for MultiIndex. " + "Use index.to_frame().infer_objects() instead." + ) + if self.dtype != object: + return self.copy() if copy else self + + values = self._values + values = cast("npt.NDArray[np.object_]", values) + res_values = lib.maybe_convert_objects( + values, + convert_non_numeric=True, + ) + if copy and res_values is values: + return self.copy() + result = Index(res_values, name=self.name) + if not copy and res_values is values and self._references is not None: + result._references = self._references + result._references.add_index_reference(result) + return result + + @final + def diff(self, periods: int = 1) -> Index: + """ + Computes the difference between consecutive values in the Index object. + + If periods is greater than 1, computes the difference between values that + are `periods` number of positions apart. + + Parameters + ---------- + periods : int, optional + The number of positions between the current and previous + value to compute the difference with. Default is 1. + + Returns + ------- + Index + A new Index object with the computed differences. + + Examples + -------- + >>> import pandas as pd + >>> idx = pd.Index([10, 20, 30, 40, 50]) + >>> idx.diff() + Index([nan, 10.0, 10.0, 10.0, 10.0], dtype='float64') + + """ + return Index(self.to_series().diff(periods)) + + @final + def round(self, decimals: int = 0) -> Self: + """ + Round each value in the Index to the given number of decimals. + + Parameters + ---------- + decimals : int, optional + Number of decimal places to round to. If decimals is negative, + it specifies the number of positions to the left of the decimal point. + + Returns + ------- + Index + A new Index with the rounded values. + + Examples + -------- + >>> import pandas as pd + >>> idx = pd.Index([10.1234, 20.5678, 30.9123, 40.4567, 50.7890]) + >>> idx.round(decimals=2) + Index([10.12, 20.57, 30.91, 40.46, 50.79], dtype='float64') + + """ + return self._constructor(self.to_series().round(decimals)) + + # -------------------------------------------------------------------- + # Generated Arithmetic, Comparison, and Unary Methods + + def _cmp_method(self, other, op): + """ + Wrapper used to dispatch comparison operations. + """ + if self.is_(other): + # fastpath + if op in {operator.eq, operator.le, operator.ge}: + arr = np.ones(len(self), dtype=bool) + if self._can_hold_na and not isinstance(self, ABCMultiIndex): + # TODO: should set MultiIndex._can_hold_na = False? + arr[self.isna()] = False + return arr + elif op is operator.ne: + arr = np.zeros(len(self), dtype=bool) + if self._can_hold_na and not isinstance(self, ABCMultiIndex): + arr[self.isna()] = True + return arr + + if isinstance(other, (np.ndarray, Index, ABCSeries, ExtensionArray)) and len( + self + ) != len(other): + raise ValueError("Lengths must match to compare") + + if not isinstance(other, ABCMultiIndex): + other = extract_array(other, extract_numpy=True) + else: + other = np.asarray(other) + + if is_object_dtype(self.dtype) and isinstance(other, ExtensionArray): + # e.g. PeriodArray, Categorical + result = op(self._values, other) + + elif isinstance(self._values, ExtensionArray): + result = op(self._values, other) + + elif is_object_dtype(self.dtype) and not isinstance(self, ABCMultiIndex): + # don't pass MultiIndex + result = ops.comp_method_OBJECT_ARRAY(op, self._values, other) + + else: + result = ops.comparison_op(self._values, other, op) + + return result + + @final + def _logical_method(self, other, op): + res_name = ops.get_op_result_name(self, other) + + lvalues = self._values + rvalues = extract_array(other, extract_numpy=True, extract_range=True) + + res_values = ops.logical_op(lvalues, rvalues, op) + return self._construct_result(res_values, name=res_name) + + @final + def _construct_result(self, result, name): + if isinstance(result, tuple): + return ( + Index(result[0], name=name, dtype=result[0].dtype), + Index(result[1], name=name, dtype=result[1].dtype), + ) + return Index(result, name=name, dtype=result.dtype) + + def _arith_method(self, other, op): + if ( + isinstance(other, Index) + and is_object_dtype(other.dtype) + and type(other) is not Index + ): + # We return NotImplemented for object-dtype index *subclasses* so they have + # a chance to implement ops before we unwrap them. + # See https://github.com/pandas-dev/pandas/issues/31109 + return NotImplemented + + return super()._arith_method(other, op) + + @final + def _unary_method(self, op): + result = op(self._values) + return Index(result, name=self.name) + + def __abs__(self) -> Index: + return self._unary_method(operator.abs) + + def __neg__(self) -> Index: + return self._unary_method(operator.neg) + + def __pos__(self) -> Index: + return self._unary_method(operator.pos) + + def __invert__(self) -> Index: + # GH#8875 + return self._unary_method(operator.inv) + + # -------------------------------------------------------------------- + # Reductions + + def any(self, *args, **kwargs): + """ + Return whether any element is Truthy. + + Parameters + ---------- + *args + Required for compatibility with numpy. + **kwargs + Required for compatibility with numpy. + + Returns + ------- + bool or array-like (if axis is specified) + A single element array-like may be converted to bool. + + See Also + -------- + Index.all : Return whether all elements are True. + Series.all : Return whether all elements are True. + + Notes + ----- + Not a Number (NaN), positive infinity and negative infinity + evaluate to True because these are not equal to zero. + + Examples + -------- + >>> index = pd.Index([0, 1, 2]) + >>> index.any() + True + + >>> index = pd.Index([0, 0, 0]) + >>> index.any() + False + """ + nv.validate_any(args, kwargs) + self._maybe_disable_logical_methods("any") + vals = self._values + if not isinstance(vals, np.ndarray): + # i.e. EA, call _reduce instead of "any" to get TypeError instead + # of AttributeError + return vals._reduce("any") + return np.any(vals) + + def all(self, *args, **kwargs): + """ + Return whether all elements are Truthy. + + Parameters + ---------- + *args + Required for compatibility with numpy. + **kwargs + Required for compatibility with numpy. + + Returns + ------- + bool or array-like (if axis is specified) + A single element array-like may be converted to bool. + + See Also + -------- + Index.any : Return whether any element in an Index is True. + Series.any : Return whether any element in a Series is True. + Series.all : Return whether all elements in a Series are True. + + Notes + ----- + Not a Number (NaN), positive infinity and negative infinity + evaluate to True because these are not equal to zero. + + Examples + -------- + True, because nonzero integers are considered True. + + >>> pd.Index([1, 2, 3]).all() + True + + False, because ``0`` is considered False. + + >>> pd.Index([0, 1, 2]).all() + False + """ + nv.validate_all(args, kwargs) + self._maybe_disable_logical_methods("all") + vals = self._values + if not isinstance(vals, np.ndarray): + # i.e. EA, call _reduce instead of "all" to get TypeError instead + # of AttributeError + return vals._reduce("all") + return np.all(vals) + + @final + def _maybe_disable_logical_methods(self, opname: str_t) -> None: + """ + raise if this Index subclass does not support any or all. + """ + if ( + isinstance(self, ABCMultiIndex) + # TODO(3.0): PeriodArray and DatetimeArray any/all will raise, + # so checking needs_i8_conversion will be unnecessary + or (needs_i8_conversion(self.dtype) and self.dtype.kind != "m") + ): + # This call will raise + make_invalid_op(opname)(self) + + @Appender(IndexOpsMixin.argmin.__doc__) + def argmin(self, axis=None, skipna: bool = True, *args, **kwargs) -> int: + nv.validate_argmin(args, kwargs) + nv.validate_minmax_axis(axis) + + if not self._is_multi and self.hasnans: + # Take advantage of cache + mask = self._isnan + if not skipna or mask.all(): + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return -1 + return super().argmin(skipna=skipna) + + @Appender(IndexOpsMixin.argmax.__doc__) + def argmax(self, axis=None, skipna: bool = True, *args, **kwargs) -> int: + nv.validate_argmax(args, kwargs) + nv.validate_minmax_axis(axis) + + if not self._is_multi and self.hasnans: + # Take advantage of cache + mask = self._isnan + if not skipna or mask.all(): + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return -1 + return super().argmax(skipna=skipna) + + def min(self, axis=None, skipna: bool = True, *args, **kwargs): + """ + Return the minimum value of the Index. + + Parameters + ---------- + axis : {None} + Dummy argument for consistency with Series. + skipna : bool, default True + Exclude NA/null values when showing the result. + *args, **kwargs + Additional arguments and keywords for compatibility with NumPy. + + Returns + ------- + scalar + Minimum value. + + See Also + -------- + Index.max : Return the maximum value of the object. + Series.min : Return the minimum value in a Series. + DataFrame.min : Return the minimum values in a DataFrame. + + Examples + -------- + >>> idx = pd.Index([3, 2, 1]) + >>> idx.min() + 1 + + >>> idx = pd.Index(['c', 'b', 'a']) + >>> idx.min() + 'a' + + For a MultiIndex, the minimum is determined lexicographically. + + >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)]) + >>> idx.min() + ('a', 1) + """ + nv.validate_min(args, kwargs) + nv.validate_minmax_axis(axis) + + if not len(self): + return self._na_value + + if len(self) and self.is_monotonic_increasing: + # quick check + first = self[0] + if not isna(first): + return first + + if not self._is_multi and self.hasnans: + # Take advantage of cache + mask = self._isnan + if not skipna or mask.all(): + return self._na_value + + if not self._is_multi and not isinstance(self._values, np.ndarray): + return self._values._reduce(name="min", skipna=skipna) + + return nanops.nanmin(self._values, skipna=skipna) + + def max(self, axis=None, skipna: bool = True, *args, **kwargs): + """ + Return the maximum value of the Index. + + Parameters + ---------- + axis : int, optional + For compatibility with NumPy. Only 0 or None are allowed. + skipna : bool, default True + Exclude NA/null values when showing the result. + *args, **kwargs + Additional arguments and keywords for compatibility with NumPy. + + Returns + ------- + scalar + Maximum value. + + See Also + -------- + Index.min : Return the minimum value in an Index. + Series.max : Return the maximum value in a Series. + DataFrame.max : Return the maximum values in a DataFrame. + + Examples + -------- + >>> idx = pd.Index([3, 2, 1]) + >>> idx.max() + 3 + + >>> idx = pd.Index(['c', 'b', 'a']) + >>> idx.max() + 'c' + + For a MultiIndex, the maximum is determined lexicographically. + + >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)]) + >>> idx.max() + ('b', 2) + """ + + nv.validate_max(args, kwargs) + nv.validate_minmax_axis(axis) + + if not len(self): + return self._na_value + + if len(self) and self.is_monotonic_increasing: + # quick check + last = self[-1] + if not isna(last): + return last + + if not self._is_multi and self.hasnans: + # Take advantage of cache + mask = self._isnan + if not skipna or mask.all(): + return self._na_value + + if not self._is_multi and not isinstance(self._values, np.ndarray): + return self._values._reduce(name="max", skipna=skipna) + + return nanops.nanmax(self._values, skipna=skipna) + + # -------------------------------------------------------------------- + + @final + @property + def shape(self) -> Shape: + """ + Return a tuple of the shape of the underlying data. + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.shape + (3,) + """ + # See GH#27775, GH#27384 for history/reasoning in how this is defined. + return (len(self),) + + +def ensure_index_from_sequences(sequences, names=None) -> Index: + """ + Construct an index from sequences of data. + + A single sequence returns an Index. Many sequences returns a + MultiIndex. + + Parameters + ---------- + sequences : sequence of sequences + names : sequence of str + + Returns + ------- + index : Index or MultiIndex + + Examples + -------- + >>> ensure_index_from_sequences([[1, 2, 3]], names=["name"]) + Index([1, 2, 3], dtype='int64', name='name') + + >>> ensure_index_from_sequences([["a", "a"], ["a", "b"]], names=["L1", "L2"]) + MultiIndex([('a', 'a'), + ('a', 'b')], + names=['L1', 'L2']) + + See Also + -------- + ensure_index + """ + from pandas.core.indexes.multi import MultiIndex + + if len(sequences) == 1: + if names is not None: + names = names[0] + return Index(sequences[0], name=names) + else: + return MultiIndex.from_arrays(sequences, names=names) + + +def ensure_index(index_like: Axes, copy: bool = False) -> Index: + """ + Ensure that we have an index from some index-like object. + + Parameters + ---------- + index_like : sequence + An Index or other sequence + copy : bool, default False + + Returns + ------- + index : Index or MultiIndex + + See Also + -------- + ensure_index_from_sequences + + Examples + -------- + >>> ensure_index(['a', 'b']) + Index(['a', 'b'], dtype='object') + + >>> ensure_index([('a', 'a'), ('b', 'c')]) + Index([('a', 'a'), ('b', 'c')], dtype='object') + + >>> ensure_index([['a', 'a'], ['b', 'c']]) + MultiIndex([('a', 'b'), + ('a', 'c')], + ) + """ + if isinstance(index_like, Index): + if copy: + index_like = index_like.copy() + return index_like + + if isinstance(index_like, ABCSeries): + name = index_like.name + return Index(index_like, name=name, copy=copy) + + if is_iterator(index_like): + index_like = list(index_like) + + if isinstance(index_like, list): + if type(index_like) is not list: # noqa: E721 + # must check for exactly list here because of strict type + # check in clean_index_list + index_like = list(index_like) + + if len(index_like) and lib.is_all_arraylike(index_like): + from pandas.core.indexes.multi import MultiIndex + + return MultiIndex.from_arrays(index_like) + else: + return Index(index_like, copy=copy, tupleize_cols=False) + else: + return Index(index_like, copy=copy) + + +def ensure_has_len(seq): + """ + If seq is an iterator, put its values into a list. + """ + try: + len(seq) + except TypeError: + return list(seq) + else: + return seq + + +def trim_front(strings: list[str]) -> list[str]: + """ + Trims zeros and decimal points. + + Examples + -------- + >>> trim_front([" a", " b"]) + ['a', 'b'] + + >>> trim_front([" a", " "]) + ['a', ''] + """ + if not strings: + return strings + while all(strings) and all(x[0] == " " for x in strings): + strings = [x[1:] for x in strings] + return strings + + +def _validate_join_method(method: str) -> None: + if method not in ["left", "right", "inner", "outer"]: + raise ValueError(f"do not recognize join method {method}") + + +def maybe_extract_name(name, obj, cls) -> Hashable: + """ + If no name is passed, then extract it from data, validating hashability. + """ + if name is None and isinstance(obj, (Index, ABCSeries)): + # Note we don't just check for "name" attribute since that would + # pick up e.g. dtype.name + name = obj.name + + # GH#29069 + if not is_hashable(name): + raise TypeError(f"{cls.__name__}.name must be a hashable type") + + return name + + +def get_unanimous_names(*indexes: Index) -> tuple[Hashable, ...]: + """ + Return common name if all indices agree, otherwise None (level-by-level). + + Parameters + ---------- + indexes : list of Index objects + + Returns + ------- + list + A list representing the unanimous 'names' found. + """ + name_tups = [tuple(i.names) for i in indexes] + name_sets = [{*ns} for ns in zip_longest(*name_tups)] + names = tuple(ns.pop() if len(ns) == 1 else None for ns in name_sets) + return names + + +def _unpack_nested_dtype(other: Index) -> DtypeObj: + """ + When checking if our dtype is comparable with another, we need + to unpack CategoricalDtype to look at its categories.dtype. + + Parameters + ---------- + other : Index + + Returns + ------- + np.dtype or ExtensionDtype + """ + dtype = other.dtype + if isinstance(dtype, CategoricalDtype): + # If there is ever a SparseIndex, this could get dispatched + # here too. + return dtype.categories.dtype + elif isinstance(dtype, ArrowDtype): + # GH 53617 + import pyarrow as pa + + if pa.types.is_dictionary(dtype.pyarrow_dtype): + other = other[:0].astype(ArrowDtype(dtype.pyarrow_dtype.value_type)) + return other.dtype + + +def _maybe_try_sort(result: Index | ArrayLike, sort: bool | None): + if sort is not False: + try: + # error: Incompatible types in assignment (expression has type + # "Union[ExtensionArray, ndarray[Any, Any], Index, Series, + # Tuple[Union[Union[ExtensionArray, ndarray[Any, Any]], Index, Series], + # ndarray[Any, Any]]]", variable has type "Union[Index, + # Union[ExtensionArray, ndarray[Any, Any]]]") + result = algos.safe_sort(result) # type: ignore[assignment] + except TypeError as err: + if sort is True: + raise + warnings.warn( + f"{err}, sort order is undefined for incomparable objects.", + RuntimeWarning, + stacklevel=find_stack_level(), + ) + return result + + +def get_values_for_csv( + values: ArrayLike, + *, + date_format, + na_rep: str = "nan", + quoting=None, + float_format=None, + decimal: str = ".", +) -> npt.NDArray[np.object_]: + """ + Convert to types which can be consumed by the standard library's + csv.writer.writerows. + """ + if isinstance(values, Categorical) and values.categories.dtype.kind in "Mm": + # GH#40754 Convert categorical datetimes to datetime array + values = algos.take_nd( + values.categories._values, + ensure_platform_int(values._codes), + fill_value=na_rep, + ) + + values = ensure_wrapped_if_datetimelike(values) + + if isinstance(values, (DatetimeArray, TimedeltaArray)): + if values.ndim == 1: + result = values._format_native_types(na_rep=na_rep, date_format=date_format) + result = result.astype(object, copy=False) + return result + + # GH#21734 Process every column separately, they might have different formats + results_converted = [] + for i in range(len(values)): + result = values[i, :]._format_native_types( + na_rep=na_rep, date_format=date_format + ) + results_converted.append(result.astype(object, copy=False)) + return np.vstack(results_converted) + + elif isinstance(values.dtype, PeriodDtype): + # TODO: tests that get here in column path + values = cast("PeriodArray", values) + res = values._format_native_types(na_rep=na_rep, date_format=date_format) + return res + + elif isinstance(values.dtype, IntervalDtype): + # TODO: tests that get here in column path + values = cast("IntervalArray", values) + mask = values.isna() + if not quoting: + result = np.asarray(values).astype(str) + else: + result = np.array(values, dtype=object, copy=True) + + result[mask] = na_rep + return result + + elif values.dtype.kind == "f" and not isinstance(values.dtype, SparseDtype): + # see GH#13418: no special formatting is desired at the + # output (important for appropriate 'quoting' behaviour), + # so do not pass it through the FloatArrayFormatter + if float_format is None and decimal == ".": + mask = isna(values) + + if not quoting: + values = values.astype(str) + else: + values = np.array(values, dtype="object") + + values[mask] = na_rep + values = values.astype(object, copy=False) + return values + + from pandas.io.formats.format import FloatArrayFormatter + + formatter = FloatArrayFormatter( + values, + na_rep=na_rep, + float_format=float_format, + decimal=decimal, + quoting=quoting, + fixed_width=False, + ) + res = formatter.get_result_as_array() + res = res.astype(object, copy=False) + return res + + elif isinstance(values, ExtensionArray): + mask = isna(values) + + new_values = np.asarray(values.astype(object)) + new_values[mask] = na_rep + return new_values + + else: + mask = isna(values) + itemsize = writers.word_len(na_rep) + + if values.dtype != _dtype_obj and not quoting and itemsize: + values = values.astype(str) + if values.dtype.itemsize / np.dtype("U1").itemsize < itemsize: + # enlarge for the na_rep + values = values.astype(f" + +#include "arrow/io/interfaces.h" +#include "arrow/util/visibility.h" + +namespace arrow { +namespace io { + +// Output stream that just writes to stdout. +class ARROW_EXPORT StdoutStream : public OutputStream { + public: + StdoutStream(); + ~StdoutStream() override {} + + Status Close() override; + bool closed() const override; + + Result Tell() const override; + + Status Write(const void* data, int64_t nbytes) override; + + private: + int64_t pos_; +}; + +// Output stream that just writes to stderr. +class ARROW_EXPORT StderrStream : public OutputStream { + public: + StderrStream(); + ~StderrStream() override {} + + Status Close() override; + bool closed() const override; + + Result Tell() const override; + + Status Write(const void* data, int64_t nbytes) override; + + private: + int64_t pos_; +}; + +// Input stream that just reads from stdin. +class ARROW_EXPORT StdinStream : public InputStream { + public: + StdinStream(); + ~StdinStream() override {} + + Status Close() override; + bool closed() const override; + + Result Tell() const override; + + Result Read(int64_t nbytes, void* out) override; + + Result> Read(int64_t nbytes) override; + + private: + int64_t pos_; +}; + +} // namespace io +} // namespace arrow diff --git a/shared/package-files/76/76a3b022802adcc731adcd0411ea899e70ef258085cf9940d097b056e3838417/blob b/shared/package-files/76/76a3b022802adcc731adcd0411ea899e70ef258085cf9940d097b056e3838417/blob new file mode 100644 index 0000000000000000000000000000000000000000..7db1921369023eaf05c65bf537c259de3f2a81cb --- /dev/null +++ b/shared/package-files/76/76a3b022802adcc731adcd0411ea899e70ef258085cf9940d097b056e3838417/blob @@ -0,0 +1,236 @@ +""" +Tests for offsets.BDay +""" +from __future__ import annotations + +from datetime import ( + date, + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas._libs.tslibs.offsets import ( + ApplyTypeError, + BDay, + BMonthEnd, +) + +from pandas import ( + DatetimeIndex, + Timedelta, + _testing as tm, +) +from pandas.tests.tseries.offsets.common import ( + assert_is_on_offset, + assert_offset_equal, +) + +from pandas.tseries import offsets + + +@pytest.fixture +def dt(): + return datetime(2008, 1, 1) + + +@pytest.fixture +def _offset(): + return BDay + + +@pytest.fixture +def offset(_offset): + return _offset() + + +@pytest.fixture +def offset2(_offset): + return _offset(2) + + +class TestBusinessDay: + def test_different_normalize_equals(self, _offset, offset2): + # GH#21404 changed __eq__ to return False when `normalize` does not match + offset = _offset() + offset2 = _offset(normalize=True) + assert offset != offset2 + + def test_repr(self, offset, offset2): + assert repr(offset) == "" + assert repr(offset2) == "<2 * BusinessDays>" + + expected = "" + assert repr(offset + timedelta(1)) == expected + + def test_with_offset(self, dt, offset): + offset = offset + timedelta(hours=2) + + assert (dt + offset) == datetime(2008, 1, 2, 2) + + @pytest.mark.parametrize( + "td", + [ + Timedelta(hours=2), + Timedelta(hours=2).to_pytimedelta(), + Timedelta(hours=2).to_timedelta64(), + ], + ids=lambda x: type(x), + ) + def test_with_offset_index(self, td, dt, offset): + dti = DatetimeIndex([dt]) + expected = DatetimeIndex([datetime(2008, 1, 2, 2)]) + + result = dti + (td + offset) + tm.assert_index_equal(result, expected) + + result = dti + (offset + td) + tm.assert_index_equal(result, expected) + + def test_eq(self, offset2): + assert offset2 == offset2 + + def test_hash(self, offset2): + assert hash(offset2) == hash(offset2) + + def test_add_datetime(self, dt, offset2): + assert offset2 + dt == datetime(2008, 1, 3) + assert offset2 + np.datetime64("2008-01-01 00:00:00") == datetime(2008, 1, 3) + + def testRollback1(self, dt, _offset): + assert _offset(10).rollback(dt) == dt + + def testRollback2(self, _offset): + assert _offset(10).rollback(datetime(2008, 1, 5)) == datetime(2008, 1, 4) + + def testRollforward1(self, dt, _offset): + assert _offset(10).rollforward(dt) == dt + + def testRollforward2(self, _offset): + assert _offset(10).rollforward(datetime(2008, 1, 5)) == datetime(2008, 1, 7) + + def test_roll_date_object(self, offset): + dt = date(2012, 9, 15) + + result = offset.rollback(dt) + assert result == datetime(2012, 9, 14) + + result = offset.rollforward(dt) + assert result == datetime(2012, 9, 17) + + offset = offsets.Day() + result = offset.rollback(dt) + assert result == datetime(2012, 9, 15) + + result = offset.rollforward(dt) + assert result == datetime(2012, 9, 15) + + @pytest.mark.parametrize( + "dt, expected", + [ + (datetime(2008, 1, 1), True), + (datetime(2008, 1, 5), False), + ], + ) + def test_is_on_offset(self, offset, dt, expected): + assert_is_on_offset(offset, dt, expected) + + apply_cases: list[tuple[int, dict[datetime, datetime]]] = [ + ( + 1, + { + datetime(2008, 1, 1): datetime(2008, 1, 2), + datetime(2008, 1, 4): datetime(2008, 1, 7), + datetime(2008, 1, 5): datetime(2008, 1, 7), + datetime(2008, 1, 6): datetime(2008, 1, 7), + datetime(2008, 1, 7): datetime(2008, 1, 8), + }, + ), + ( + 2, + { + datetime(2008, 1, 1): datetime(2008, 1, 3), + datetime(2008, 1, 4): datetime(2008, 1, 8), + datetime(2008, 1, 5): datetime(2008, 1, 8), + datetime(2008, 1, 6): datetime(2008, 1, 8), + datetime(2008, 1, 7): datetime(2008, 1, 9), + }, + ), + ( + -1, + { + datetime(2008, 1, 1): datetime(2007, 12, 31), + datetime(2008, 1, 4): datetime(2008, 1, 3), + datetime(2008, 1, 5): datetime(2008, 1, 4), + datetime(2008, 1, 6): datetime(2008, 1, 4), + datetime(2008, 1, 7): datetime(2008, 1, 4), + datetime(2008, 1, 8): datetime(2008, 1, 7), + }, + ), + ( + -2, + { + datetime(2008, 1, 1): datetime(2007, 12, 28), + datetime(2008, 1, 4): datetime(2008, 1, 2), + datetime(2008, 1, 5): datetime(2008, 1, 3), + datetime(2008, 1, 6): datetime(2008, 1, 3), + datetime(2008, 1, 7): datetime(2008, 1, 3), + datetime(2008, 1, 8): datetime(2008, 1, 4), + datetime(2008, 1, 9): datetime(2008, 1, 7), + }, + ), + ( + 0, + { + datetime(2008, 1, 1): datetime(2008, 1, 1), + datetime(2008, 1, 4): datetime(2008, 1, 4), + datetime(2008, 1, 5): datetime(2008, 1, 7), + datetime(2008, 1, 6): datetime(2008, 1, 7), + datetime(2008, 1, 7): datetime(2008, 1, 7), + }, + ), + ] + + @pytest.mark.parametrize("case", apply_cases) + def test_apply(self, case, _offset): + n, cases = case + offset = _offset(n) + for base, expected in cases.items(): + assert_offset_equal(offset, base, expected) + + def test_apply_large_n(self, _offset): + dt = datetime(2012, 10, 23) + + result = dt + _offset(10) + assert result == datetime(2012, 11, 6) + + result = dt + _offset(100) - _offset(100) + assert result == dt + + off = _offset() * 6 + rs = datetime(2012, 1, 1) - off + xp = datetime(2011, 12, 23) + assert rs == xp + + st = datetime(2011, 12, 18) + rs = st + off + xp = datetime(2011, 12, 26) + assert rs == xp + + off = _offset() * 10 + rs = datetime(2014, 1, 5) + off # see #5890 + xp = datetime(2014, 1, 17) + assert rs == xp + + def test_apply_corner(self, _offset): + if _offset is BDay: + msg = "Only know how to combine business day with datetime or timedelta" + else: + msg = ( + "Only know how to combine trading day " + "with datetime, datetime64 or timedelta" + ) + with pytest.raises(ApplyTypeError, match=msg): + _offset()._apply(BMonthEnd()) diff --git a/shared/package-files/76/76a3ef28d2a5fef73f3083c3712e9ceb53c1d833427d3bc784fe5be5013a3872/blob b/shared/package-files/76/76a3ef28d2a5fef73f3083c3712e9ceb53c1d833427d3bc784fe5be5013a3872/blob new file mode 100644 index 0000000000000000000000000000000000000000..81a1c020ee7a351ea1b9b2c0b4cd2be121283035 --- /dev/null +++ b/shared/package-files/76/76a3ef28d2a5fef73f3083c3712e9ceb53c1d833427d3bc784fe5be5013a3872/blob @@ -0,0 +1,76 @@ + + + +* make groupstats into a class with additional functions for easy access + use bincount but loop over 2d, or maybe two versions 1d,2d (or nd?) + similar to groupbys + class GroupStats + init with label data + attributes/properties on demand: mean, var, callback, devfrommean, meanarr, vararr + does var need bias option ? yes? + def groupmean(label, data) + def groupvar(label, data) + def groupnormalize(label, data, reweight = True) + + +* ANOVA wrapper usage example + discussed on mailing list and proposed by Skipper + create design matrix + create restriction matrices for F tests, t tests + ? normalization redundant ? + reports ANOVA style + +* maybe: quick helpers for structured arrays and masked arrays + formula for selection of variables + specification for which variable are factors + Anova(y, use='x1;x2;x3', factors='x2', data = dataarray) + or + Anova(y, use='x1; x2:F; x3', data = dataarray) + + masked arrays need row compression + + +* meta object + for variable names, and .... ? + +* OLSR, OLS with linear restriction -> design changes ? + need to overwrite params_cov calculation - move it back to models + +* regression: OLS, WLS + - add prediction + + +* Granger causality test: which test statistic, F test is easiest, LR, Wald ? -> easy + in R: example in Wikipedia + +* get lag matrix helper function to use lagged dependent and lagged independent regressors + +* nonlinear hypothesis tests for the estimate parameters, delta method ? -> easy, but derivatives by hand w/o sympy + +* minimal PCA, PCR, or PLS (NIPALS): interesting also for finance but not urgent -> messy multiplicity of definitions ? + +* non-linear least squares: + use/imitate scipy.interpolate curvefit + full set of results statistics + +* tests -> needed + - GLSAR: check, R's gls + - ARMA: check R for arma, e.g., dynamo, also look more closely at GARCH_UCSD (BSD) and offspring (license ?) + +* other models in draft stage -> requires cleaning + - gaussian process -> might fit in + - multinomial logit -> requires ML, result statistics do not fit into current classes ? + +* stochastic processes, time series -> first step is relatively easy + more simulators, random process generators, for fun and Monte Carlo and testing + estimators to follow + first group GARCH, + continuous time: not until I need them + +* other multivariate analysis + discriminance, factor analysis, more anova: not my business + +* MLE, GMM: big open question -> needs to wait until we have more code that uses it + difference of approaches + - parametric assumptions, distributions fully specified - problem misspecification + - efficient estimation with full information MLE + -> example panel data, yogurt paper diff --git a/shared/package-files/76/76a43f0176cfed4e4400428f94b03407011acac7301391f53f32177cbfe38455/blob b/shared/package-files/76/76a43f0176cfed4e4400428f94b03407011acac7301391f53f32177cbfe38455/blob new file mode 100644 index 0000000000000000000000000000000000000000..5b6bff06accc986ed82891ea5ed38b3cccd22b9e Binary files /dev/null and b/shared/package-files/76/76a43f0176cfed4e4400428f94b03407011acac7301391f53f32177cbfe38455/blob differ diff --git a/shared/package-files/76/76a5533a8e6540635af3c9621a099183f5cb68edba3ea9951fe8bff4ff95d428/blob b/shared/package-files/76/76a5533a8e6540635af3c9621a099183f5cb68edba3ea9951fe8bff4ff95d428/blob new file mode 100644 index 0000000000000000000000000000000000000000..876c7fda856fc82cf4cd076213ebad21b2915074 --- /dev/null +++ b/shared/package-files/76/76a5533a8e6540635af3c9621a099183f5cb68edba3ea9951fe8bff4ff95d428/blob @@ -0,0 +1,155 @@ +# coding: utf-8 +"""Tests for profile-related functions. + +Currently only the startup-dir functionality is tested, but more tests should +be added for: + + * ipython profile create + * ipython profile list + * ipython profile create --parallel + * security dir permissions + +Authors +------- + +* MinRK + +""" + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import shutil +import sys +import tempfile +from pathlib import Path +from unittest import TestCase + +from tempfile import TemporaryDirectory + +from IPython.core.profileapp import list_bundled_profiles, list_profiles_in +from IPython.core.profiledir import ProfileDir +from IPython.testing import decorators as dec +from IPython.testing import tools as tt +from IPython.utils.process import getoutput + +#----------------------------------------------------------------------------- +# Globals +#----------------------------------------------------------------------------- +TMP_TEST_DIR = Path(tempfile.mkdtemp()) +HOME_TEST_DIR = TMP_TEST_DIR / "home_test_dir" +IP_TEST_DIR = HOME_TEST_DIR / ".ipython" + +# +# Setup/teardown functions/decorators +# + +def setup_module(): + """Setup test environment for the module: + + - Adds dummy home dir tree + """ + # Do not mask exceptions here. In particular, catching WindowsError is a + # problem because that exception is only defined on Windows... + (Path.cwd() / IP_TEST_DIR).mkdir(parents=True) + + +def teardown_module(): + """Teardown test environment for the module: + + - Remove dummy home dir tree + """ + # Note: we remove the parent test dir, which is the root of all test + # subdirs we may have created. Use shutil instead of os.removedirs, so + # that non-empty directories are all recursively removed. + shutil.rmtree(TMP_TEST_DIR) + + +#----------------------------------------------------------------------------- +# Test functions +#----------------------------------------------------------------------------- +class ProfileStartupTest(TestCase): + def setUp(self): + # create profile dir + self.pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, "test") + self.options = ["--ipython-dir", IP_TEST_DIR, "--profile", "test"] + self.fname = TMP_TEST_DIR / "test.py" + + def tearDown(self): + # We must remove this profile right away so its presence doesn't + # confuse other tests. + shutil.rmtree(self.pd.location) + + def init(self, startup_file, startup, test): + # write startup python file + with open(Path(self.pd.startup_dir) / startup_file, "w", encoding="utf-8") as f: + f.write(startup) + # write simple test file, to check that the startup file was run + with open(self.fname, "w", encoding="utf-8") as f: + f.write(test) + + def validate(self, output): + tt.ipexec_validate(self.fname, output, "", options=self.options) + + def test_startup_py(self): + self.init('00-start.py', 'zzz=123\n', 'print(zzz)\n') + self.validate('123') + + def test_startup_ipy(self): + self.init('00-start.ipy', '%xmode plain\n', '') + self.validate('Exception reporting mode: Plain') + + +def test_list_profiles_in(): + # No need to remove these directories and files, as they will get nuked in + # the module-level teardown. + td = Path(tempfile.mkdtemp(dir=TMP_TEST_DIR)) + for name in ("profile_foo", "profile_hello", "not_a_profile"): + Path(td / name).mkdir(parents=True) + if dec.unicode_paths: + Path(td / "profile_ünicode").mkdir(parents=True) + + with open(td / "profile_file", "w", encoding="utf-8") as f: + f.write("I am not a profile directory") + profiles = list_profiles_in(td) + + # unicode normalization can turn u'ünicode' into u'u\0308nicode', + # so only check for *nicode, and that creating a ProfileDir from the + # name remains valid + found_unicode = False + for p in list(profiles): + if p.endswith('nicode'): + pd = ProfileDir.find_profile_dir_by_name(td, p) + profiles.remove(p) + found_unicode = True + break + if dec.unicode_paths: + assert found_unicode is True + assert set(profiles) == {"foo", "hello"} + + +def test_list_bundled_profiles(): + # This variable will need to be updated when a new profile gets bundled + bundled = sorted(list_bundled_profiles()) + assert bundled == [] + + +def test_profile_create_ipython_dir(): + """ipython profile create respects --ipython-dir""" + with TemporaryDirectory() as td: + getoutput( + [ + sys.executable, + "-m", + "IPython", + "profile", + "create", + "foo", + "--ipython-dir=%s" % td, + ] + ) + profile_dir = Path(td) / "profile_foo" + assert Path(profile_dir).exists() + ipython_config = profile_dir / "ipython_config.py" + assert Path(ipython_config).exists() diff --git a/shared/package-files/76/76ab3252924e71e859d7d90e8d3db13b6554975cfcac0fdadced4de7f8779330/blob b/shared/package-files/76/76ab3252924e71e859d7d90e8d3db13b6554975cfcac0fdadced4de7f8779330/blob new file mode 100644 index 0000000000000000000000000000000000000000..fabe4f73c8d8085cffc2792dee4c1629a87b8b35 --- /dev/null +++ b/shared/package-files/76/76ab3252924e71e859d7d90e8d3db13b6554975cfcac0fdadced4de7f8779330/blob @@ -0,0 +1,344 @@ +"""Interface to the libbzip2 compression library. + +This module provides a file interface, classes for incremental +(de)compression, and functions for one-shot (de)compression. +""" + +__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", + "open", "compress", "decompress"] + +__author__ = "Nadeem Vawda " + +from builtins import open as _builtin_open +import io +import os +import _compression + +from _bz2 import BZ2Compressor, BZ2Decompressor + + +_MODE_CLOSED = 0 +_MODE_READ = 1 +# Value 2 no longer used +_MODE_WRITE = 3 + + +class BZ2File(_compression.BaseStream): + + """A file object providing transparent bzip2 (de)compression. + + A BZ2File can act as a wrapper for an existing file object, or refer + directly to a named file on disk. + + Note that BZ2File provides a *binary* file interface - data read is + returned as bytes, and data to be written should be given as bytes. + """ + + def __init__(self, filename, mode="r", *, compresslevel=9): + """Open a bzip2-compressed file. + + If filename is a str, bytes, or PathLike object, it gives the + name of the file to be opened. Otherwise, it should be a file + object, which will be used to read or write the compressed data. + + mode can be 'r' for reading (default), 'w' for (over)writing, + 'x' for creating exclusively, or 'a' for appending. These can + equivalently be given as 'rb', 'wb', 'xb', and 'ab'. + + If mode is 'w', 'x' or 'a', compresslevel can be a number between 1 + and 9 specifying the level of compression: 1 produces the least + compression, and 9 (default) produces the most compression. + + If mode is 'r', the input file may be the concatenation of + multiple compressed streams. + """ + self._fp = None + self._closefp = False + self._mode = _MODE_CLOSED + + if not (1 <= compresslevel <= 9): + raise ValueError("compresslevel must be between 1 and 9") + + if mode in ("", "r", "rb"): + mode = "rb" + mode_code = _MODE_READ + elif mode in ("w", "wb"): + mode = "wb" + mode_code = _MODE_WRITE + self._compressor = BZ2Compressor(compresslevel) + elif mode in ("x", "xb"): + mode = "xb" + mode_code = _MODE_WRITE + self._compressor = BZ2Compressor(compresslevel) + elif mode in ("a", "ab"): + mode = "ab" + mode_code = _MODE_WRITE + self._compressor = BZ2Compressor(compresslevel) + else: + raise ValueError("Invalid mode: %r" % (mode,)) + + if isinstance(filename, (str, bytes, os.PathLike)): + self._fp = _builtin_open(filename, mode) + self._closefp = True + self._mode = mode_code + elif hasattr(filename, "read") or hasattr(filename, "write"): + self._fp = filename + self._mode = mode_code + else: + raise TypeError("filename must be a str, bytes, file or PathLike object") + + if self._mode == _MODE_READ: + raw = _compression.DecompressReader(self._fp, + BZ2Decompressor, trailing_error=OSError) + self._buffer = io.BufferedReader(raw) + else: + self._pos = 0 + + def close(self): + """Flush and close the file. + + May be called more than once without error. Once the file is + closed, any other operation on it will raise a ValueError. + """ + if self._mode == _MODE_CLOSED: + return + try: + if self._mode == _MODE_READ: + self._buffer.close() + elif self._mode == _MODE_WRITE: + self._fp.write(self._compressor.flush()) + self._compressor = None + finally: + try: + if self._closefp: + self._fp.close() + finally: + self._fp = None + self._closefp = False + self._mode = _MODE_CLOSED + self._buffer = None + + @property + def closed(self): + """True if this file is closed.""" + return self._mode == _MODE_CLOSED + + def fileno(self): + """Return the file descriptor for the underlying file.""" + self._check_not_closed() + return self._fp.fileno() + + def seekable(self): + """Return whether the file supports seeking.""" + return self.readable() and self._buffer.seekable() + + def readable(self): + """Return whether the file was opened for reading.""" + self._check_not_closed() + return self._mode == _MODE_READ + + def writable(self): + """Return whether the file was opened for writing.""" + self._check_not_closed() + return self._mode == _MODE_WRITE + + def peek(self, n=0): + """Return buffered data without advancing the file position. + + Always returns at least one byte of data, unless at EOF. + The exact number of bytes returned is unspecified. + """ + self._check_can_read() + # Relies on the undocumented fact that BufferedReader.peek() + # always returns at least one byte (except at EOF), independent + # of the value of n + return self._buffer.peek(n) + + def read(self, size=-1): + """Read up to size uncompressed bytes from the file. + + If size is negative or omitted, read until EOF is reached. + Returns b'' if the file is already at EOF. + """ + self._check_can_read() + return self._buffer.read(size) + + def read1(self, size=-1): + """Read up to size uncompressed bytes, while trying to avoid + making multiple reads from the underlying stream. Reads up to a + buffer's worth of data if size is negative. + + Returns b'' if the file is at EOF. + """ + self._check_can_read() + if size < 0: + size = io.DEFAULT_BUFFER_SIZE + return self._buffer.read1(size) + + def readinto(self, b): + """Read bytes into b. + + Returns the number of bytes read (0 for EOF). + """ + self._check_can_read() + return self._buffer.readinto(b) + + def readline(self, size=-1): + """Read a line of uncompressed bytes from the file. + + The terminating newline (if present) is retained. If size is + non-negative, no more than size bytes will be read (in which + case the line may be incomplete). Returns b'' if already at EOF. + """ + if not isinstance(size, int): + if not hasattr(size, "__index__"): + raise TypeError("Integer argument expected") + size = size.__index__() + self._check_can_read() + return self._buffer.readline(size) + + def readlines(self, size=-1): + """Read a list of lines of uncompressed bytes from the file. + + size can be specified to control the number of lines read: no + further lines will be read once the total size of the lines read + so far equals or exceeds size. + """ + if not isinstance(size, int): + if not hasattr(size, "__index__"): + raise TypeError("Integer argument expected") + size = size.__index__() + self._check_can_read() + return self._buffer.readlines(size) + + def write(self, data): + """Write a byte string to the file. + + Returns the number of uncompressed bytes written, which is + always the length of data in bytes. Note that due to buffering, + the file on disk may not reflect the data written until close() + is called. + """ + self._check_can_write() + if isinstance(data, (bytes, bytearray)): + length = len(data) + else: + # accept any data that supports the buffer protocol + data = memoryview(data) + length = data.nbytes + + compressed = self._compressor.compress(data) + self._fp.write(compressed) + self._pos += length + return length + + def writelines(self, seq): + """Write a sequence of byte strings to the file. + + Returns the number of uncompressed bytes written. + seq can be any iterable yielding byte strings. + + Line separators are not added between the written byte strings. + """ + return _compression.BaseStream.writelines(self, seq) + + def seek(self, offset, whence=io.SEEK_SET): + """Change the file position. + + The new position is specified by offset, relative to the + position indicated by whence. Values for whence are: + + 0: start of stream (default); offset must not be negative + 1: current stream position + 2: end of stream; offset must not be positive + + Returns the new file position. + + Note that seeking is emulated, so depending on the parameters, + this operation may be extremely slow. + """ + self._check_can_seek() + return self._buffer.seek(offset, whence) + + def tell(self): + """Return the current file position.""" + self._check_not_closed() + if self._mode == _MODE_READ: + return self._buffer.tell() + return self._pos + + +def open(filename, mode="rb", compresslevel=9, + encoding=None, errors=None, newline=None): + """Open a bzip2-compressed file in binary or text mode. + + The filename argument can be an actual filename (a str, bytes, or + PathLike object), or an existing file object to read from or write + to. + + The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or + "ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode. + The default mode is "rb", and the default compresslevel is 9. + + For binary mode, this function is equivalent to the BZ2File + constructor: BZ2File(filename, mode, compresslevel). In this case, + the encoding, errors and newline arguments must not be provided. + + For text mode, a BZ2File object is created, and wrapped in an + io.TextIOWrapper instance with the specified encoding, error + handling behavior, and line ending(s). + + """ + if "t" in mode: + if "b" in mode: + raise ValueError("Invalid mode: %r" % (mode,)) + else: + if encoding is not None: + raise ValueError("Argument 'encoding' not supported in binary mode") + if errors is not None: + raise ValueError("Argument 'errors' not supported in binary mode") + if newline is not None: + raise ValueError("Argument 'newline' not supported in binary mode") + + bz_mode = mode.replace("t", "") + binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel) + + if "t" in mode: + encoding = io.text_encoding(encoding) + return io.TextIOWrapper(binary_file, encoding, errors, newline) + else: + return binary_file + + +def compress(data, compresslevel=9): + """Compress a block of data. + + compresslevel, if given, must be a number between 1 and 9. + + For incremental compression, use a BZ2Compressor object instead. + """ + comp = BZ2Compressor(compresslevel) + return comp.compress(data) + comp.flush() + + +def decompress(data): + """Decompress a block of data. + + For incremental decompression, use a BZ2Decompressor object instead. + """ + results = [] + while data: + decomp = BZ2Decompressor() + try: + res = decomp.decompress(data) + except OSError: + if results: + break # Leftover data is not a valid bzip2 stream; ignore it. + else: + raise # Error on the first iteration; bail out. + results.append(res) + if not decomp.eof: + raise ValueError("Compressed data ended before the " + "end-of-stream marker was reached") + data = decomp.unused_data + return b"".join(results) diff --git a/shared/package-files/76/76ab5514d39f72320d00ccda27eb47896e923b7ed9c15b554f527b492ef25a1d/blob b/shared/package-files/76/76ab5514d39f72320d00ccda27eb47896e923b7ed9c15b554f527b492ef25a1d/blob new file mode 100644 index 0000000000000000000000000000000000000000..49559197addec08a8b43a62e90c2c3fa0d97debf --- /dev/null +++ b/shared/package-files/76/76ab5514d39f72320d00ccda27eb47896e923b7ed9c15b554f527b492ef25a1d/blob @@ -0,0 +1,33 @@ +from typing import Any, Optional + +deque: Any +missing: Any +RegexType: Any +HELP_HTML: Any +OBJECT_DUMP_HTML: Any + +def debug_repr(obj): ... +def dump(obj=...): ... + +class _Helper: + def __call__(self, topic: Optional[Any] = ...): ... + +helper: Any + +class DebugReprGenerator: + def __init__(self): ... + list_repr: Any + tuple_repr: Any + set_repr: Any + frozenset_repr: Any + deque_repr: Any + def regex_repr(self, obj): ... + def string_repr(self, obj, limit: int = ...): ... + def dict_repr(self, d, recursive, limit: int = ...): ... + def object_repr(self, obj): ... + def dispatch_repr(self, obj, recursive): ... + def fallback_repr(self): ... + def repr(self, obj): ... + def dump_object(self, obj): ... + def dump_locals(self, d): ... + def render_object_dump(self, items, title, repr: Optional[Any] = ...): ... diff --git a/shared/package-files/76/76ad67dbd42653c42fe8a24864bf052951aadd1383aae4c66d69588137134888/blob b/shared/package-files/76/76ad67dbd42653c42fe8a24864bf052951aadd1383aae4c66d69588137134888/blob new file mode 100644 index 0000000000000000000000000000000000000000..f2e7e81d78d3f6acf83817c19aa37fc29002a866 --- /dev/null +++ b/shared/package-files/76/76ad67dbd42653c42fe8a24864bf052951aadd1383aae4c66d69588137134888/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::linalg_svdvals(Tensor A, *, str? driver=None) -> Tensor +inline at::Tensor linalg_svdvals(const at::Tensor & A, c10::optional driver=c10::nullopt) { + return at::_ops::linalg_svdvals::call(A, driver); +} + +// aten::linalg_svdvals.out(Tensor A, *, str? driver=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_svdvals_out(at::Tensor & out, const at::Tensor & A, c10::optional driver=c10::nullopt) { + return at::_ops::linalg_svdvals_out::call(A, driver, out); +} +// aten::linalg_svdvals.out(Tensor A, *, str? driver=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_svdvals_outf(const at::Tensor & A, c10::optional driver, at::Tensor & out) { + return at::_ops::linalg_svdvals_out::call(A, driver, out); +} + +} diff --git a/shared/package-files/76/76affafe7d2fedc533f58ce25e7fa064535cf7162d37167c7b14ecce258833bb/blob b/shared/package-files/76/76affafe7d2fedc533f58ce25e7fa064535cf7162d37167c7b14ecce258833bb/blob new file mode 100644 index 0000000000000000000000000000000000000000..f68323b0c8eb7fc999dead349ea3bd3a6da66bd4 Binary files /dev/null and b/shared/package-files/76/76affafe7d2fedc533f58ce25e7fa064535cf7162d37167c7b14ecce258833bb/blob differ diff --git a/shared/package-files/76/76b01a6d5c38139905f979e03a9a015dd360e22a6263385f7299044f539b562d/blob b/shared/package-files/76/76b01a6d5c38139905f979e03a9a015dd360e22a6263385f7299044f539b562d/blob new file mode 100644 index 0000000000000000000000000000000000000000..0b07600fb6125e856e2fbdd476b2e3e03c97bd4b --- /dev/null +++ b/shared/package-files/76/76b01a6d5c38139905f979e03a9a015dd360e22a6263385f7299044f539b562d/blob @@ -0,0 +1,93 @@ +predict_1,predict_2,predict_3,predict_diag1,predict_diag2,predict_diag3,predict_int1,predict_int2,predict_int3,predict_exog1_1,predict_exog1_2,predict_exog1_3,predict_exog2_1,predict_exog2_2,predict_exog2_3,predict_var2_1,predict_var2_2,dyn_predict_1,dyn_predict_2,dyn_predict_3,dyn_predict_diag1,dyn_predict_diag2,dyn_predict_diag3,dyn_predict_int1,dyn_predict_int2,dyn_predict_int3,dyn_predict_var2_1,dyn_predict_var2_2,fcast_exog1_dln_inv,fcast_exog1_dln_inc,fcast_exog1_dln_consump,fcast_exog2_dln_inv,fcast_exog2_dln_inc,fcast_exog2_dln_consump +,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +0,0,0,0,0,0,.017993,.0206546,.0198753,,,,,,,0,0,0,0,0,0,0,0,.017993,.0206546,.0198753,0,0,,,,,, +.0219036,.015239,.0205644,.0219323,.015408,.0205827,.0222069,.0178744,.023416,.0240228,.0116697,.0155036,.0274188,.0195343,.0234162,.0291779,.0214276,.0219036,.015239,.0205644,.0219323,.015408,.0205827,.0222069,.0178744,.023416,.0291779,.0214276,,,,,, +.0286807,.0290166,.0307121,.0287198,.0292086,.0308044,.0278614,.0220684,.0228171,.0325758,.0226331,.0217584,.0330271,.0236782,.0228099,.0365168,.0299893,.0286807,.0290166,.0307121,.0287198,.0292086,.0308044,.0278614,.0220684,.0228171,.0365168,.0299893,,,,,, +.0213229,.0250984,.0171728,.021225,.0251252,.0173499,.0211601,.0243908,.0164511,.0246534,.020032,.0101589,.0273071,.0261775,.0163418,.0210618,.0275606,.0213229,.0250984,.0171728,.021225,.0251252,.0173499,.0211601,.0243908,.0164511,.0210618,.0275606,,,,,, +.0053626,.0244219,.022593,.0055324,.0245271,.0226514,.0053418,.0233062,.0212843,.0078678,.0201839,.0167408,.0098265,.0247198,.0213045,.0008339,.025076,.0158976,.0166997,.0180117,.0161077,.0169354,.0181261,.0155766,.0196724,.0214068,.016601,.0195765,,,,,, +.0152812,.001603,.0115397,.0153171,.0017642,.0114732,.0166697,.0134123,.024661,.0152486,.00144,.0112098,.0210356,.0148418,.0246933,.0306755,.0229331,.0155252,.0155309,.0138104,.0156066,.0157223,.0140464,.0195002,.0210119,.0193583,.0213424,.0207717,,,,,, +.0310255,.0307515,.0132727,.0307157,.0306726,.0135935,.0304952,.0281367,.0105641,.0352956,.0246831,.0049285,.0376171,.0300593,.0103376,.0131385,.0096833,.0118529,.0125056,.012006,.0120795,.0127661,.0122276,.0173198,.0205541,.0200522,.0168285,.0177828,,,,,, +.0154957,.0186156,.0234295,.0156176,.0187921,.0234372,.0156334,.0192535,.0240207,.0173325,.0154124,.0189349,.0195353,.0205137,.0240673,.0119374,.0163648,.0104293,.0106435,.009926,.0106197,.0108977,.0101749,.0182681,.0206824,.0198207,.0161775,.0171797,,,,,, +.0016842,.018106,.0124847,.0017576,.0181204,.01257,.0023183,.0230567,.0180721,.0031342,.015819,.0094044,.0068423,.0244065,.0180443,.0064078,.0263343,.0085524,.0088723,.0083608,.0087764,.0091352,.0086051,.0178907,.0206484,.019891,.0148133,.0154455,,,,,, +.0284541,.0204126,.0171175,.0283153,.0204857,.0172589,.0284523,.0214,.0182537,.0309551,.0166898,.0119326,.0336321,.0228894,.0181701,.0121113,.0153868,.0072352,.0074501,.0069959,.0074494,.0077052,.0072372,.0180287,.0206555,.0198713,.0138072,.0144635,,,,,, +.01227,.0136681,.0181741,.0123676,.0138123,.0181713,.0128614,.0182774,.0232453,.0132226,.0119566,.0157784,.0164452,.0194196,.0232869,.0238754,.0188439,.0060418,.0062407,.0058667,.0062548,.0064862,.0060975,.0179814,.0206547,.019876,.0126159,.0132462,,,,,, +.0153997,.0147606,.0130408,.015365,.0148208,.0131198,.0160075,.0202455,.0192012,.0166369,.0129135,.0105026,.0203546,.0215229,.0191646,.0201475,.0194606,.005071,.0052315,.0049165,.0052735,.0054632,.0051347,.0179965,.0206544,.0198752,.0117151,.0122784,,,,,, +.0452093,.0043659,.0115588,.0449143,.0045154,.0116165,.0460012,.0132133,.0214426,.0460411,.0033797,.0100354,.0509036,.0146405,.0213649,.0513044,.0046492,.0042482,.0043847,.0041209,.0044396,.0046009,.0043244,.017992,.0206547,.0198752,.0107843,.0113051,,,,,, +-.0308253,.0183067,.0090861,-.0304762,.0182545,.0091148,-.0296423,.0260625,.0178247,-.0307674,.0179755,.0088939,-.026909,.0269109,.0178838,-.0142943,.0157543,.0035612,.003675,.0034539,.0037394,.0038748,.0036419,.0179932,.0206545,.0198753,.0099649,.0104487,,,,,, +.0084279,.0141093,.0134112,.008477,.0141778,.0134569,.009166,.0201749,.0201967,.009106,.0130421,.0119872,.0126318,.0212072,.0202022,-.0149168,.0217644,.0029847,.0030802,.0028949,.0031491,.0032633,.0030672,.017993,.0206546,.0198752,.0091911,.0096364,,,,,, +.0174139,.016467,.0191551,.0174551,.0166018,.0191911,.0177479,.0192371,.0221892,.0185175,.014658,.0166459,.0209078,.0201936,.0222153,.0193026,.0199788,.0025017,.0025817,.0024264,.0026522,.0027483,.0025831,.017993,.0206546,.0198753,.008487,.0088979,,,,,, +.0333252,.0269773,.0221253,.0331774,.0270646,.0223049,.0327602,.0232518,.0179766,.0362335,.0226783,.016172,.0369761,.0243982,.0179024,.027821,.0212826,.0020968,.0021639,.0020337,.0022336,.0023146,.0021755,.017993,.0206546,.0198752,.0078311,.0082105,,,,,, +-.0098444,.0046119,.0082608,-.0096281,.0046854,.0081933,-.008177,.0175129,.0226559,-.0111728,.0064814,.0109563,-.0061125,.0182001,.0227466,.0090279,.0197315,.0017574,.0018137,.0017045,.0018811,.0019493,.0018321,.017993,.0206546,.0198753,.0072289,.0075791,,,,,, +.0181736,.0159572,.0114471,.0180728,.0159841,.0115675,.0187115,.0212278,.0174139,.0191709,.0146914,.0097642,.0224297,.0222383,.0173572,.0070974,.0139059,.001473,.0015201,.0014287,.0015842,.0016417,.001543,.017993,.0206546,.0198753,.0066716,.0069948,,,,,, +.0277111,.0282975,.0340761,.0278257,.0285451,.0341181,.0268654,.0207146,.0254008,.0301263,.0242147,.0283695,.0288889,.0213492,.0254865,.027889,.0247586,.0012346,.0012741,.0011974,.0013342,.0013826,.0012995,.017993,.0206546,.0198753,.0061579,.0064562,,,,,, +.0314369,.0199549,.0187331,.0312993,.0200574,.0188593,.031378,.0204889,.0193325,.0331166,.0175808,.0154465,.0347659,.0214003,.0192893,.0432999,.0298763,.0010348,.0010679,.0010036,.0011236,.0011644,.0010944,.017993,.0206546,.0198753,.0056834,.0059588,,,,,, +.0249369,.0311732,.0276795,.0249449,.0312988,.027822,.0241242,.0243906,.0200423,.0276228,.0270076,.0219563,.0268023,.0251074,.0200445,.0230672,.0238666,.0008673,.000895,.0008412,.0009463,.0009806,.0009217,.017993,.0206546,.0198753,.0052457,.0054998,,,,,, +.0226227,.0189283,.0183121,.0225767,.0190301,.0184039,.0227616,.0205543,.0201161,.0237223,.0173598,.0161806,.0254098,.0212679,.0201125,.0257267,.0258167,.0007269,.0007502,.0007051,.000797,.0008259,.0007762,.017993,.0206546,.0198753,.0048416,.0050761,,,,,, +.0206391,.0183528,.0147666,.0205545,.018407,.014886,.0209253,.0214154,.0182328,.0215931,.0171426,.0131695,.0237526,.0221437,.0182011,.0198942,.0164757,.0006093,.0006288,.0005909,.0006712,.0006955,.0006537,.017993,.0206546,.0198753,.0044687,.0046851,,,,,, +.0064361,.0123588,.0062243,.0063902,.0123374,.0063249,.007476,.0214799,.0165364,.0062105,.0130622,.0073601,.0101345,.0221494,.0165028,.0023057,.0104471,.0005107,.000527,.0004953,.0005653,.0005858,.0005506,.017993,.0206546,.0198753,.0041244,.0043242,,,,,, +.0155921,.009804,.0120788,.0155744,.0098965,.0121083,.0165001,.0177769,.0209871,.0151424,.0106634,.0133319,.018439,.0182976,.0210128,.0110352,.0084571,.000428,.0004417,.0004151,.0004761,.0004933,.0004637,.017993,.0206546,.0198753,.0038067,.0039911,,,,,, +.0299575,.0169379,.0245207,.0299609,.0171528,.0245389,.0299509,.0171625,.0246345,.0306122,.0158736,.0230132,.031338,.0175545,.0247044,.0403971,.0186751,.0003587,.0003702,.0003479,.0004009,.0004155,.0003905,.017993,.0206546,.0198753,.0035135,.0036837,,,,,, +-.0172722,-.0142972,-.0190914,-.0173296,-.0144513,-.019101,-.0137672,.0156842,.0146928,-.0215492,-.0070201,-.0087462,-.011505,.0162406,.0146565,.0082196,.0043511,.0003007,.0003103,.0002916,.0003377,.0003499,.0003289,.017993,.0206546,.0198753,.0032429,.0034,,,,,, +.0321264,.0165184,.0131974,.0319078,.0165722,.0133468,.0323852,.0202088,.0173925,.0328862,.0158415,.0123208,.0350353,.0208184,.0173281,.0013488,-.0109963,.000252,.0002601,.0002444,.0002844,.0002947,.000277,.017993,.0206546,.0198753,.0029931,.0031381,,,,,, +.0110035,-.0049469,.0022687,.0109659,-.0048623,.0022148,.0130487,.012816,.0221412,.0083397,-.0005477,.0084275,.0142469,.0131323,.022191,.0309398,.0024609,.0002112,.000218,.0002049,.0002395,.0002482,.0002333,.017993,.0206546,.0198753,.0027625,.0028963,,,,,, +.0134224,.0092759,.0041027,.0132885,.0092555,.0042106,.0145848,.0200068,.0162319,.0126186,.0110589,.0067327,.0166764,.0204561,.0161873,.0132994,.0000422,.000177,.0001827,.0001717,.0002017,.000209,.0001964,.017993,.0206546,.0198753,.0025497,.0026732,,,,,, +-.0129232,.0109613,.0095938,-.0126974,.0109935,.0095801,-.0116011,.020808,.0206114,-.0145954,.0135551,.0134188,-.0114635,.020808,.0207159,-.0136073,.010725,.0001484,.0001531,.0001439,.0001699,.000176,.0001654,.017993,.0206546,.0198753,.0023533,.0024673,,,,,, +.0370364,.0124037,.0209094,.0369347,.0126113,.0209344,.0372688,.0153276,.0240707,.0369543,.0127017,.0212882,.0381709,.0155191,.0241228,.0339027,.0177888,.0001244,.0001284,.0001206,.0001431,.0001482,.0001393,.017993,.0206546,.0198753,.002172,.0022773,,,,,, +.02196,.0242538,.0181303,.0218787,.0243028,.0182879,.0218124,.0235982,.0174414,.02292,.0231369,.0167299,.0232184,.0238279,.0174251,.0309038,.0189547,.0001042,.0001076,.0001011,.0001205,.0001248,.0001173,.017993,.0206546,.0198753,.0020047,.0021018,,,,,, +.0088349,.0167866,.0180935,.0089439,.0168989,.0181198,.0093028,.0202276,.0218874,.0082781,.0177047,.0195069,.0093387,.0201608,.021978,.0115932,.0215607,.0000874,.0000902,.0000847,.0001015,.0001051,.0000988,.017993,.0206546,.0198753,.0018503,.0019399,,,,,, +.0138939,.024108,.0195192,.0139224,.0241751,.0196347,.0138397,.0235647,.0189165,.0143786,.0235815,.0189646,.0143731,.0235688,.0189519,.0087818,.0252103,.0000732,.0000756,.000071,.0000855,.0000885,.0000832,.017993,.0206546,.0198753,.0017078,.0017905,,,,,, +.0330778,.0207476,.0218912,.0329739,.0208897,.0219959,.0328737,.0198843,.0208813,.0336476,.0201649,.021145,.0335446,.0199263,.020905,.0286047,.0213656,.0000614,.0000633,.0000595,.000072,.0000746,.0000701,.017993,.0206546,.0198753,.0015762,.0016526,,,,,, +.0081263,.0220489,.0207024,.008251,.0221499,.0207616,.0082445,.0224003,.0210481,.0079643,.0223754,.0213353,.0078801,.0221805,.0211392,.0183623,.0254464,.0000514,.0000531,.0000499,.0000606,.0000628,.000059,.017993,.0206546,.0198753,.0014548,.0015253,,,,,, +.011879,.0244902,.0228246,.0119847,.0246012,.0229009,.0117529,.022899,.0209907,.0120502,.0243161,.0227571,.0113293,.0226466,.0210774,.0087348,.0304176,.0000431,.0000445,.0000418,.000051,.0000529,.0000497,.017993,.0206546,.0198753,.0013427,.0014078,,,,,, +.01809,.0186676,.0116053,.0179731,.0186714,.0117571,.0184724,.022687,.0161985,.0178595,.0195854,.0130797,.0191889,.022664,.016177,.0097604,.0206746,.0000361,.0000373,.0000351,.000043,.0000445,.0000419,.017993,.0206546,.0198753,.0012393,.0012993,,,,,, +.0294821,.0248464,.0270555,.0294779,.0250242,.0271408,.0289747,.0208104,.0224412,.0300641,.0240988,.0261054,.0285244,.0205329,.0225178,.0231262,.0184518,.0000303,.0000313,.0000294,.0000362,.0000375,.0000353,.017993,.0206546,.0198753,.0011438,.0011993,,,,,, +-.0030156,.0281165,.025027,-.0027422,.028219,.0250779,-.0031805,.0251046,.0215796,-.0031445,.02823,.0254405,-.004739,.0245374,.0217254,.0070327,.0371209,.0000254,.0000262,.0000246,.0000305,.0000316,.0000297,.017993,.0206546,.0198753,.0010557,.0011069,,,,,, +.0247474,.0292947,.0285182,.0247861,.0294501,.0286273,.0240233,.0231085,.0215124,.0255774,.0281547,.0270765,.0232244,.0227055,.021594,.0144461,.0374782,.0000213,.000022,.0000206,.0000257,.0000266,.000025,.017993,.0206546,.0198753,.0009744,.0010216,,,,,, +.032296,.0287394,.022822,.0321585,.02882,.0230124,.0316298,.0240781,.0176312,.0333547,.0275965,.0213966,.0317359,.0238476,.0176249,.0270765,.0278669,.0000178,.0000184,.0000173,.0000216,.0000224,.0000211,.017993,.0206546,.0198753,.0008994,.0009429,,,,,, +.0060403,.0119842,.0066905,.0060096,.011973,.0067799,.0070959,.021155,.0170451,.0042349,.0153211,.0115753,.0065944,.0207852,.0170728,.0072685,.0147909,.0000149,.0000154,.0000145,.0000182,.0000189,.0000177,.017993,.0206546,.0198753,.0008301,.0008703,,,,,, +.0238965,.0277514,.0268631,.0239257,.0278966,.0269696,.0233119,.0227999,.0212506,.0243008,.0273343,.0264434,.0221084,.0222571,.0213352,.0101319,.0185324,.0000125,.0000129,.0000122,.0000153,.0000159,.0000149,.017993,.0206546,.0198753,.0007661,.0008032,,,,,, +.0257059,.0188137,.0206921,.0256713,.0189529,.0207645,.0257484,.0195978,.0215147,.0250379,.0201773,.0227175,.0245545,.0190577,.0215911,.0332744,.0268419,.0000105,.0000108,.0000102,.0000129,.0000134,.0000126,.017993,.0206546,.0198753,.0007071,.0007414,,,,,, +.0318195,.0261582,.0275483,.0317902,.0263321,.0276512,.0311918,.0212546,.0219722,.0321183,.0259622,.0273972,.0298251,.0206516,.0220541,.0373762,.0254131,8.80e-06,9.08e-06,8.54e-06,.0000109,.0000113,.0000106,.017993,.0206546,.0198753,.0006526,.0006843,,,,,, +.0218903,.0290997,.0231629,.0218643,.0291771,.0233223,.0213486,.0247748,.0183299,.0222567,.0289444,.0231714,.0201981,.024177,.0183749,.0230677,.0287736,7.38e-06,7.61e-06,7.16e-06,9.16e-06,9.49e-06,8.92e-06,.017993,.0206546,.0198753,.0006024,.0006316,,,,,, +.0093965,.0038019,.0103721,.0094565,.0039227,.0103284,.0107756,.0153209,.0232041,.0061644,.0091049,.0178977,.0085001,.0145141,.02334,.0233293,.0196793,6.18e-06,6.38e-06,6.00e-06,7.72e-06,8.00e-06,7.52e-06,.017993,.0206546,.0198753,.000556,.0005829,,,,,, +.0396162,.0299035,.0237923,.0394114,.0299908,.024008,.0387532,.0240098,.0172291,.0405326,.0291324,.022893,.0380966,.0234911,.0172172,.0289755,.0158416,5.18e-06,5.35e-06,5.03e-06,6.50e-06,6.73e-06,6.33e-06,.017993,.0206546,.0198753,.0005131,.000538,,,,,, +.0207615,.0221776,.0217302,.0207723,.0222983,.0218173,.0206618,.0214347,.0208541,.019973,.0237457,.0241025,.0186189,.0206098,.0209475,.0253772,.022058,4.34e-06,4.48e-06,4.21e-06,5.47e-06,5.67e-06,5.33e-06,.017993,.0206546,.0198753,.0004736,.0004966,,,,,, +.0166964,.0299388,.0208938,.0166778,.0299727,.021074,.0162386,.0262211,.0167821,.0167428,.0303776,.0217919,.0146099,.0254383,.0168224,.0075113,.025614,3.64e-06,3.76e-06,3.53e-06,4.61e-06,4.78e-06,4.49e-06,.017993,.0206546,.0198753,.0004371,.0004583,,,,,, +.0225149,.0088279,.0111192,.0224152,.0089187,.0111686,.0233993,.0171256,.0204085,.0200832,.0131761,.0173285,.0214349,.0163064,.0204778,.0216259,.0155451,3.05e-06,3.15e-06,2.96e-06,3.88e-06,4.02e-06,3.78e-06,.017993,.0206546,.0198753,.0004035,.000423,,,,,, +.0197268,.0098573,.0129679,.0196816,.0099643,.0130003,.0205494,.017301,.021275,.0172224,.0142327,.0192232,.0181442,.0163672,.0213708,.0305007,.0097599,2.56e-06,2.64e-06,2.48e-06,3.27e-06,3.39e-06,3.18e-06,.017993,.0206546,.0198753,.0003724,.0003904,,,,,, +.0251093,.0169877,.017058,.0250292,.0170904,.0171478,.0253514,.0197126,.0200972,.0235762,.0199072,.0213047,.0230891,.0187792,.0201699,.0294964,.0138316,2.14e-06,2.21e-06,2.08e-06,2.75e-06,2.85e-06,2.68e-06,.017993,.0206546,.0198753,.0003437,.0003604,,,,,, +.0102939,.0185643,.0136574,.0102954,.0185956,.0137609,.0107471,.0224621,.0180641,.008459,.0219611,.0186675,.0082324,.0214363,.0181395,.0111789,.016782,1.80e-06,1.85e-06,1.74e-06,2.32e-06,2.40e-06,2.26e-06,.017993,.0206546,.0198753,.0003172,.0003326,,,,,, +.0371635,.0148159,.0200306,.0370272,.0149881,.0200958,.0372791,.0169212,.022318,.0355415,.0178678,.0243836,.0346923,.0159012,.022405,.0352418,.0146963,1.51e-06,1.55e-06,1.46e-06,1.95e-06,2.02e-06,1.90e-06,.017993,.0206546,.0198753,.0002928,.000307,,,,,, +.0329035,.0256919,.0269775,.0328562,.0258623,.0270844,.0323,.0211053,.021763,.0323608,.0269502,.0288964,.0293435,.0199627,.0218662,.0453169,.0219867,1.26e-06,1.30e-06,1.22e-06,1.64e-06,1.70e-06,1.60e-06,.017993,.0206546,.0198753,.0002702,.0002833,,,,,, +.0175841,.0109321,.0130581,.017555,.0110294,.0130963,.0183755,.0179929,.0209435,.0147708,.0158331,.0200841,.0151864,.0167956,.0210526,.0343512,.0213019,1.06e-06,1.09e-06,1.03e-06,1.39e-06,1.44e-06,1.35e-06,.017993,.0206546,.0198753,.0002494,.0002615,,,,,, +.0231837,.0206712,.0215867,.0231778,.020805,.0216642,.0231369,.0205035,.0213443,.0216029,.0235707,.0258312,.0197278,.0192282,.0214622,.0264961,.0183737,8.87e-07,9.15e-07,8.60e-07,1.17e-06,1.21e-06,1.14e-06,.017993,.0206546,.0198753,.0002302,.0002414,,,,,, +.0478456,.0302042,.0318409,.047697,.0304105,.0319928,.0466501,.021283,.0217609,.0480865,.0303495,.0321734,.0436522,.0200803,.0218415,.0478389,.0257753,7.43e-07,7.67e-07,7.21e-07,9.82e-07,1.02e-06,9.57e-07,.017993,.0206546,.0198753,.0002125,.0002228,,,,,, +.0134735,.0150288,.0051387,.0133156,.0149697,.0053058,.0142854,.0228803,.0140899,.011004,.0198226,.0121471,.0118401,.021759,.0140954,.0218153,.0166693,6.23e-07,6.43e-07,6.04e-07,8.27e-07,8.57e-07,8.06e-07,.017993,.0206546,.0198753,.0001961,.0002056,,,,,, +.0117675,.0171662,.0125747,.0117446,.0171953,.0126778,.0123041,.0219279,.0179548,.0092925,.0216689,.0191465,.008818,.0205701,.0180409,-.0038577,.0067066,5.22e-07,5.39e-07,5.06e-07,6.97e-07,7.22e-07,6.79e-07,.017993,.0206546,.0198753,.000181,.0001898,,,,,, +.0168405,.0176618,.013851,.0167841,.0177074,.0139609,.0172437,.0215266,.0182178,.0145031,.0219802,.0201469,.0137103,.0201443,.0182998,.0075227,.0137997,4.38e-07,4.52e-07,4.24e-07,5.87e-07,6.08e-07,5.72e-07,.017993,.0206546,.0198753,.0001671,.0001752,,,,,, +.0038277,.0110742,.0097856,.0038819,.0111158,.0098216,.0048924,.0198479,.0196266,.0001787,.0173113,.0187748,.0006016,.0182908,.0197603,.0048979,.0141053,3.67e-07,3.79e-07,3.56e-07,4.94e-07,5.12e-07,4.81e-07,.017993,.0206546,.0198753,.0001542,.0001617,,,,,, +.0222672,.0127174,.0162343,.0222331,.0128467,.0162722,.0228121,.0177577,.0218282,.0192577,.0179543,.023733,.0184978,.0161946,.0219626,.0218916,.0142841,3.07e-07,3.17e-07,2.98e-07,4.16e-07,4.31e-07,4.05e-07,.017993,.0206546,.0198753,.0001423,.0001492,,,,,, +.0145178,.0212164,.0137079,.014457,.0212256,.0138563,.014758,.0236732,.0165367,.0123504,.0253578,.0198131,.0109737,.0221696,.0166055,.012645,.0160804,2.58e-07,2.66e-07,2.50e-07,3.51e-07,3.63e-07,3.41e-07,.017993,.0206546,.0198753,.0001314,.0001377,,,,,, +.0001037,.01006,.0062556,.0001409,.0100576,.0063083,.0013657,.0205615,.0180768,-.0039597,.0170619,.0163556,-.0031693,.0188924,.0181973,-.0054252,.0121337,2.16e-07,2.23e-07,2.09e-07,2.95e-07,3.06e-07,2.88e-07,.017993,.0206546,.0198753,.0001212,.0001271,,,,,, +.0278626,.0166797,.0154625,.0277276,.0167632,.0155751,.0281202,.0198629,.0190443,.0253616,.0213529,.0222137,.0240366,.0182845,.0191266,.0146551,.0096111,1.81e-07,1.87e-07,1.76e-07,2.49e-07,2.58e-07,2.42e-07,.017993,.0206546,.0198753,.0001119,.0001173,,,,,, +.0200701,.0178867,.0150175,.0199993,.0179488,.0151265,.0203849,.0211145,.018658,.0173967,.022785,.0221285,.0159493,.019433,.0187561,.0209873,.013162,1.52e-07,1.57e-07,1.47e-07,2.09e-07,2.17e-07,2.04e-07,.017993,.0206546,.0198753,.0001033,.0001083,,,,,, +.0135912,.0161049,.0157796,.0136144,.0161919,.0158383,.0140835,.0202714,.020427,.0103678,.0217114,.0238805,.0089485,.0184247,.0205737,.015036,.0166829,1.27e-07,1.31e-07,1.23e-07,1.76e-07,1.83e-07,1.72e-07,.017993,.0206546,.0198753,.0000953,.0000999,,,,,, +.0069156,.0109608,.0089604,.0069239,.0109928,.0090137,.0079612,.0198552,.018955,.0028472,.0179986,.0190904,.0028456,.0179949,.0190867,.0091651,.0154689,1.07e-07,1.10e-07,1.03e-07,1.49e-07,1.54e-07,1.45e-07,.017993,.0206546,.0198753,.000088,.0000922,,,,,, +.0103361,.0158699,.0125043,.0103363,.0159096,.0125879,.0109687,.0213132,.0186319,.0068879,.0219476,.0213064,.0057943,.0194148,.0187582,.0031334,.0128605,8.93e-08,9.22e-08,8.66e-08,1.25e-07,1.30e-07,1.22e-07,.017993,.0206546,.0198753,.0000812,.0000851,,,,,, +.0113839,.014007,.0164222,.0114569,.014122,.016441,.0120115,.0190428,.0220046,.0075665,.0204645,.025704,.0060587,.0169726,.0221908,.0126426,.0178327,7.49e-08,7.73e-08,7.26e-08,1.05e-07,1.09e-07,1.03e-07,.017993,.0206546,.0198753,.0000749,.0000786,.03636742,.00517273,.00598955,.03636742,.00517273,.00598955 +-.0027276,.0058189,.0039237,-.0026716,.0058207,.0039423,-.0011282,.0190754,.0188192,-.0079303,.0146405,.0165778,-.0069024,.0170211,.018973,.0048935,.0154488,6.28e-08,6.48e-08,6.09e-08,8.87e-08,9.19e-08,8.64e-08,.017993,.0206546,.0198753,.0000692,.0000725,-.00793034,.01464049,.01657784,-.00690238,.01702106,.01897295 +.0055591,.003654,.0042742,.0055527,.003699,.0042925,.0215153,.0199098,.0198089,.0305392,.0268776,.0300643,.0268477,.0183287,.0214632,.0067016,.0094511,5.26e-08,5.43e-08,5.10e-08,7.47e-08,7.74e-08,7.28e-08,.017993,.0206546,.0198753,.0000638,.0000669,.0160739,.02012147,.02199483,.0171472,.01792572,.01944241 +.003148,.0036684,.0030844,.0031732,.0037017,.0031332,.016877,.0208053,.0196935,.0107513,.0340083,.0271967,.0065679,.0243204,.0174497,.0125682,.0106929,4.41e-08,4.55e-08,4.28e-08,6.29e-08,6.52e-08,6.13e-08,.017993,.0206546,.0198753,.0000589,.0000618,.01659306,.02444523,.02489617,.01143598,.01863869,.01945406 +.0027846,.0028236,.0027936,.0028279,.0028789,.0028363,.0181704,.020565,.0199521,-.0152357,.0098945,.0187777,-.013672,.0135156,.0224209,.0081393,.0088935,3.69e-08,3.81e-08,3.58e-08,5.30e-08,5.49e-08,5.16e-08,.017993,.0206546,.0198753,.0000544,.000057,.0204207,.02664834,.02723967,.01290555,.0183615,.01965279 +.0023953,.0024608,.0022628,.0024328,.0025122,.0023157,.0179842,.020685,.0198382,.0103497,.025907,.0243547,.0079006,.0202352,.0186483,.0080913,.0087836,3.10e-08,3.20e-08,3.00e-08,4.46e-08,4.62e-08,4.35e-08,.017993,.0206546,.0198753,.0000502,.0000526,.02222549,.02837583,.02855637,.01247984,.01842648,.01954222 +.0019551,.0020296,.0019242,.0020029,.0020858,.0019753,.0179749,.0206433,.0198897,.0226094,.031164,.0267729,.0186704,.0220421,.0175953,.0075642,.0077824,2.60e-08,2.68e-08,2.52e-08,3.76e-08,3.89e-08,3.66e-08,.017993,.0206546,.0198753,.0000463,.0000486,.0234474,.02945931,.02960303,.01236002,.01833018,.01958445 +.0016649,.001712,.0016036,.0017097,.0017663,.0016555,.0180055,.0206582,.0198699,.0027905,.0119682,.0254323,.002643,.0116265,.0250884,.0070135,.0073465,2.18e-08,2.25e-08,2.11e-08,3.17e-08,3.28e-08,3.08e-08,.017993,.0206546,.0198753,.0000428,.0000448,.02436736,.03030084,.03034035,.01225167,.01829402,.01955606 +.0013845,.0014315,.001347,.0014305,.0014846,.0013967,.0179868,.0206534,.0198771,.0115349,.0246337,.0229099,.0093956,.0196794,.0179253,.0063661,.0067022,1.82e-08,1.88e-08,1.77e-08,2.67e-08,2.76e-08,2.60e-08,.017993,.0206546,.0198753,.0000395,.0000414,.02500241,.03094387,.03094928,.01209588,.01823582,.01955612 +.0011646,.0012008,.0011281,.0012082,.0012511,.0011756,.0179957,.0206549,.0198747,.0038793,.0160966,.018469,.0039349,.0162255,.0185986,.0059448,.0062251,1.53e-08,1.58e-08,1.48e-08,2.24e-08,2.33e-08,2.19e-08,.017993,.0206546,.0198753,.0000364,.0000382,.02552945,.03148638,.03146069,.0119706,.01818504,.01954545 +.0009746,.0010062,.0009458,.0010163,.0010534,.0009902,.017992,.0206545,.0198754,.0160767,.0188134,.025874,.0143691,.014859,.0218955,.0054623,.0057248,1.28e-08,1.32e-08,1.24e-08,1.89e-08,1.96e-08,1.84e-08,.017993,.0206546,.0198753,.0000336,.0000353,.02596239,.03196261,.03192055,.0118304,.01813191,.01953856 +.0008174,.0008434,.0007926,.0008563,.0008873,.0008339,.0179934,.0206546,.0198752,-.0035794,.0178074,.0205743,-.0040448,.0167296,.01949,.0050485,.0052949,1.07e-08,1.11e-08,1.04e-08,1.59e-08,1.65e-08,1.55e-08,.017993,.0206546,.0198753,.000031,.0000325,.02635096,.03240093,.03234732,.01169658,.01807946,.01953042 +.0006849,.0007069,.0006644,.000721,.0007472,.0007023,.0179929,.0206546,.0198753,.0124855,.0231741,.0234209,.0103833,.0183059,.0185229,.0046559,.0048813,9.00e-09,9.29e-09,8.73e-09,1.34e-08,1.39e-08,1.31e-08,.017993,.0206546,.0198753,.0000286,.00003,.02670838,.032816,.03275489,.01156026,.01802684,.01952266 +.0005741,.0005925,.0005568,.0006073,.0006293,.0005915,.0179931,.0206546,.0198753,.0180613,.0164314,.0240679,.0168902,.0137195,.0213394,.0043002,.0045082,7.54e-09,7.78e-09,7.32e-09,1.13e-08,1.17e-08,1.10e-08,.017993,.0206546,.0198753,.0000264,.0000277,.02704873,.03321726,.03315077,.01142485,.01797425,.01951479 +.0004812,.0004966,.0004667,.0005114,.00053,.0004981,.017993,.0206546,.0198753,.0087128,.0137087,.020188,.0086932,.0136633,.0201423,.0039671,.0041595,6.32e-09,6.52e-09,6.13e-09,9.51e-09,9.86e-09,9.26e-09,.017993,.0206546,.0198753,.0000244,.0000256,.02737831,.03361022,.03353969,.01128913,.01792166,.01950695 +.0004033,.0004162,.0003912,.0004307,.0004463,.0004195,.017993,.0206546,.0198753,-.0157479,.0118112,.0128117,-.0139929,.0158755,.0169009,.0036624,.0038398,5.30e-09,5.47e-09,5.14e-09,8.01e-09,8.30e-09,7.80e-09,.017993,.0206546,.0198753,.0000225,.0000236,.0277016,.0339982,.03392442,.01115351,.01786907,.0194991 +.000338,.0003489,.0003279,.0003627,.0003759,.0003533,.017993,.0206546,.0198753,-.0025344,.0154519,.018825,-.0025207,.0154837,.018857,.0033799,.0035436,4.44e-09,4.58e-09,4.31e-09,6.75e-09,6.99e-09,6.57e-09,.017993,.0206546,.0198753,.0000208,.0000218,.02802107,.03438319,.03430664,.01101786,.01781647,.01949126 diff --git a/shared/package-files/76/76b1b7295c4573c31846b7649b7a0959a8af06f65e72aea974aa0511e9af1766/blob b/shared/package-files/76/76b1b7295c4573c31846b7649b7a0959a8af06f65e72aea974aa0511e9af1766/blob new file mode 100644 index 0000000000000000000000000000000000000000..e338b8b5ba3dd5b0957a41cc14bb17ca3e991473 --- /dev/null +++ b/shared/package-files/76/76b1b7295c4573c31846b7649b7a0959a8af06f65e72aea974aa0511e9af1766/blob @@ -0,0 +1,9 @@ +import sys +from typing import List, Optional, Tuple + +if sys.platform == "win32": + + ActionText: List[Tuple[str, str, Optional[str]]] + UIText: List[Tuple[str, Optional[str]]] + + tables: List[str] diff --git a/shared/package-files/76/76b1d44de6462b6d767c2171b66eb978e3dd5d0aa4f15578fcbf2c4581919cc4/blob b/shared/package-files/76/76b1d44de6462b6d767c2171b66eb978e3dd5d0aa4f15578fcbf2c4581919cc4/blob new file mode 100644 index 0000000000000000000000000000000000000000..4e507f266293a5a145164639be180e88ed8ed448 --- /dev/null +++ b/shared/package-files/76/76b1d44de6462b6d767c2171b66eb978e3dd5d0aa4f15578fcbf2c4581919cc4/blob @@ -0,0 +1,77 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Record locking to manage potential repodata / repodata metadata file contention +between conda processes. Try to acquire a lock on a single byte in the metadat +file; modify both files; then release the lock. +""" + +import time +import warnings +from contextlib import contextmanager + +from conda.base.context import context + +LOCK_BYTE = 21 # mamba interop +LOCK_ATTEMPTS = 10 +LOCK_SLEEP = 1 + + +@contextmanager +def _lock_noop(fd): + """When locking is not available.""" + yield + + +try: # pragma: no cover + import msvcrt + + @contextmanager + def _lock_impl(fd): # type: ignore + tell = fd.tell() + fd.seek(LOCK_BYTE) + msvcrt.locking(fd.fileno(), msvcrt.LK_LOCK, 1) # type: ignore + try: + fd.seek(tell) + yield + finally: + fd.seek(LOCK_BYTE) + msvcrt.locking(fd.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore + +except ImportError: + try: + import fcntl + except ImportError: # pragma: no cover + # "fcntl Availibility: not Emscripten, not WASI." + warnings.warn("file locking not available") + + _lock_impl = _lock_noop # type: ignore + + else: + + class _lock_impl: + def __init__(self, fd): + self.fd = fd + + def __enter__(self): + for attempt in range(LOCK_ATTEMPTS): + try: + # msvcrt locking does something similar + fcntl.lockf( + self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 1, LOCK_BYTE + ) + break + except OSError: + if attempt > LOCK_ATTEMPTS - 2: + raise + time.sleep(LOCK_SLEEP) + + def __exit__(self, *exc): + fcntl.lockf(self.fd, fcntl.LOCK_UN, 1, LOCK_BYTE) + + +def lock(fd): + if "jlap" in context.experimental or "lock" in context.experimental: + # locking required for jlap + return _lock_impl(fd) + return _lock_noop(fd) diff --git a/shared/package-files/76/76b8f1bfe072231a1d9e7f8501310e27c0d08048c48f7422860b6477c142c438/blob b/shared/package-files/76/76b8f1bfe072231a1d9e7f8501310e27c0d08048c48f7422860b6477c142c438/blob new file mode 100644 index 0000000000000000000000000000000000000000..3a0d330ffd2f08396290960527fc8fc186356161 Binary files /dev/null and b/shared/package-files/76/76b8f1bfe072231a1d9e7f8501310e27c0d08048c48f7422860b6477c142c438/blob differ diff --git a/shared/package-files/76/76b96c5b0c59e65426b5d053c8be047b6e2b231b9b62ea381902d1603d45cbd7/blob b/shared/package-files/76/76b96c5b0c59e65426b5d053c8be047b6e2b231b9b62ea381902d1603d45cbd7/blob new file mode 100644 index 0000000000000000000000000000000000000000..8ffcc363904171c64541de187caec1d712283825 --- /dev/null +++ b/shared/package-files/76/76b96c5b0c59e65426b5d053c8be047b6e2b231b9b62ea381902d1603d45cbd7/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_shifted_chebyshev_polynomial_u : public TensorIteratorBase { + + + void meta(const at::Tensor & x, const at::Tensor & n); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/76/76ba1ada9d033e394ba5fb53932b1e46d462596c05105b819ac2a60040729072/blob b/shared/package-files/76/76ba1ada9d033e394ba5fb53932b1e46d462596c05105b819ac2a60040729072/blob new file mode 100644 index 0000000000000000000000000000000000000000..56fbddfffa5cdc57a5d626051002de36435c69ba --- /dev/null +++ b/shared/package-files/76/76ba1ada9d033e394ba5fb53932b1e46d462596c05105b819ac2a60040729072/blob @@ -0,0 +1,3 @@ +# This is a slight lie, the implementations aren't exactly identical +# However, in all likelihood, the differences are inconsequential +from decimal import * diff --git a/shared/package-files/76/76baf634bacad5ec27e058cca695f272901435b64443420032c755c7c9f193a2/blob b/shared/package-files/76/76baf634bacad5ec27e058cca695f272901435b64443420032c755c7c9f193a2/blob new file mode 100644 index 0000000000000000000000000000000000000000..f147f55afd1438436767960e0487d5d9e7161c8f --- /dev/null +++ b/shared/package-files/76/76baf634bacad5ec27e058cca695f272901435b64443420032c755c7c9f193a2/blob @@ -0,0 +1,7 @@ +VARIABLES X,Y +CONSTANTS A,B,R +EQN[1] = A*X^3+B*Y^2-R +EQN[2] = A*SIN(X)^2 + B*COS(2*Y) - R^2 +INPUT A=2.0, B=3.0, R=1.0 +INPUT X = 30 DEG, Y = 3.14 +CODE NONLINEAR(EQN,X,Y) some_filename.c diff --git a/shared/package-files/76/76bb1da1de5a995f5318293ea84d91c2cbc0a29efc20a108d5682e5457ddf6bb/blob b/shared/package-files/76/76bb1da1de5a995f5318293ea84d91c2cbc0a29efc20a108d5682e5457ddf6bb/blob new file mode 100644 index 0000000000000000000000000000000000000000..e4c50de7f382f62d4ae6e0cc0443e480487c65e2 --- /dev/null +++ b/shared/package-files/76/76bb1da1de5a995f5318293ea84d91c2cbc0a29efc20a108d5682e5457ddf6bb/blob @@ -0,0 +1,62 @@ +import io + +import networkx as nx +from networkx.readwrite.p2g import read_p2g, write_p2g +from networkx.utils import edges_equal + + +class TestP2G: + @classmethod + def setup_class(cls): + cls.G = nx.Graph(name="test") + e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] + cls.G.add_edges_from(e) + cls.G.add_node("g") + cls.DG = nx.DiGraph(cls.G) + + def test_read_p2g(self): + s = b"""\ +name +3 4 +a +1 2 +b + +c +0 2 +""" + bytesIO = io.BytesIO(s) + G = read_p2g(bytesIO) + assert G.name == "name" + assert sorted(G) == ["a", "b", "c"] + edges = [(str(u), str(v)) for u, v in G.edges()] + assert edges_equal(G.edges(), [("a", "c"), ("a", "b"), ("c", "a"), ("c", "c")]) + + def test_write_p2g(self): + s = b"""foo +3 2 +1 +1 +2 +2 +3 + +""" + fh = io.BytesIO() + G = nx.DiGraph() + G.name = "foo" + G.add_edges_from([(1, 2), (2, 3)]) + write_p2g(G, fh) + fh.seek(0) + r = fh.read() + assert r == s + + def test_write_read_p2g(self): + fh = io.BytesIO() + G = nx.DiGraph() + G.name = "foo" + G.add_edges_from([("a", "b"), ("b", "c")]) + write_p2g(G, fh) + fh.seek(0) + H = read_p2g(fh) + assert edges_equal(G.edges(), H.edges()) diff --git a/shared/package-files/76/76bb6afcde21e84fb6e6fb10b8924ee127397545f20b02164c7334a3321cf202/blob b/shared/package-files/76/76bb6afcde21e84fb6e6fb10b8924ee127397545f20b02164c7334a3321cf202/blob new file mode 100644 index 0000000000000000000000000000000000000000..af3dee1880d2e0625c3e8a2f77aade21ac4f5c13 --- /dev/null +++ b/shared/package-files/76/76bb6afcde21e84fb6e6fb10b8924ee127397545f20b02164c7334a3321cf202/blob @@ -0,0 +1,351 @@ +from datetime import timedelta +import re + +from dateutil.tz import gettz +import pytest +import pytz +from pytz.exceptions import ( + AmbiguousTimeError, + NonExistentTimeError, +) + +from pandas._libs.tslibs.dtypes import NpyDatetimeUnit +from pandas.errors import OutOfBoundsDatetime + +from pandas import ( + NaT, + Timestamp, +) + +try: + from zoneinfo import ZoneInfo +except ImportError: + # Cannot assign to a type + ZoneInfo = None # type: ignore[misc, assignment] + + +class TestTimestampTZLocalize: + @pytest.mark.skip_ubsan + def test_tz_localize_pushes_out_of_bounds(self): + # GH#12677 + # tz_localize that pushes away from the boundary is OK + msg = ( + f"Converting {Timestamp.min.strftime('%Y-%m-%d %H:%M:%S')} " + f"underflows past {Timestamp.min}" + ) + pac = Timestamp.min.tz_localize("US/Pacific") + assert pac._value > Timestamp.min._value + pac.tz_convert("Asia/Tokyo") # tz_convert doesn't change value + with pytest.raises(OutOfBoundsDatetime, match=msg): + Timestamp.min.tz_localize("Asia/Tokyo") + + # tz_localize that pushes away from the boundary is OK + msg = ( + f"Converting {Timestamp.max.strftime('%Y-%m-%d %H:%M:%S')} " + f"overflows past {Timestamp.max}" + ) + tokyo = Timestamp.max.tz_localize("Asia/Tokyo") + assert tokyo._value < Timestamp.max._value + tokyo.tz_convert("US/Pacific") # tz_convert doesn't change value + with pytest.raises(OutOfBoundsDatetime, match=msg): + Timestamp.max.tz_localize("US/Pacific") + + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) + def test_tz_localize_ambiguous_bool(self, unit): + # make sure that we are correctly accepting bool values as ambiguous + # GH#14402 + ts = Timestamp("2015-11-01 01:00:03").as_unit(unit) + expected0 = Timestamp("2015-11-01 01:00:03-0500", tz="US/Central") + expected1 = Timestamp("2015-11-01 01:00:03-0600", tz="US/Central") + + msg = "Cannot infer dst time from 2015-11-01 01:00:03" + with pytest.raises(pytz.AmbiguousTimeError, match=msg): + ts.tz_localize("US/Central") + + with pytest.raises(pytz.AmbiguousTimeError, match=msg): + ts.tz_localize("dateutil/US/Central") + + if ZoneInfo is not None: + try: + tz = ZoneInfo("US/Central") + except KeyError: + # no tzdata + pass + else: + with pytest.raises(pytz.AmbiguousTimeError, match=msg): + ts.tz_localize(tz) + + result = ts.tz_localize("US/Central", ambiguous=True) + assert result == expected0 + assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value + + result = ts.tz_localize("US/Central", ambiguous=False) + assert result == expected1 + assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value + + def test_tz_localize_ambiguous(self): + ts = Timestamp("2014-11-02 01:00") + ts_dst = ts.tz_localize("US/Eastern", ambiguous=True) + ts_no_dst = ts.tz_localize("US/Eastern", ambiguous=False) + + assert ts_no_dst._value - ts_dst._value == 3600 + msg = re.escape( + "'ambiguous' parameter must be one of: " + "True, False, 'NaT', 'raise' (default)" + ) + with pytest.raises(ValueError, match=msg): + ts.tz_localize("US/Eastern", ambiguous="infer") + + # GH#8025 + msg = "Cannot localize tz-aware Timestamp, use tz_convert for conversions" + with pytest.raises(TypeError, match=msg): + Timestamp("2011-01-01", tz="US/Eastern").tz_localize("Asia/Tokyo") + + msg = "Cannot convert tz-naive Timestamp, use tz_localize to localize" + with pytest.raises(TypeError, match=msg): + Timestamp("2011-01-01").tz_convert("Asia/Tokyo") + + @pytest.mark.parametrize( + "stamp, tz", + [ + ("2015-03-08 02:00", "US/Eastern"), + ("2015-03-08 02:30", "US/Pacific"), + ("2015-03-29 02:00", "Europe/Paris"), + ("2015-03-29 02:30", "Europe/Belgrade"), + ], + ) + def test_tz_localize_nonexistent(self, stamp, tz): + # GH#13057 + ts = Timestamp(stamp) + with pytest.raises(NonExistentTimeError, match=stamp): + ts.tz_localize(tz) + # GH 22644 + with pytest.raises(NonExistentTimeError, match=stamp): + ts.tz_localize(tz, nonexistent="raise") + assert ts.tz_localize(tz, nonexistent="NaT") is NaT + + @pytest.mark.parametrize( + "stamp, tz, forward_expected, backward_expected", + [ + ( + "2015-03-29 02:00:00", + "Europe/Warsaw", + "2015-03-29 03:00:00", + "2015-03-29 01:59:59", + ), # utc+1 -> utc+2 + ( + "2023-03-12 02:00:00", + "America/Los_Angeles", + "2023-03-12 03:00:00", + "2023-03-12 01:59:59", + ), # utc-8 -> utc-7 + ( + "2023-03-26 01:00:00", + "Europe/London", + "2023-03-26 02:00:00", + "2023-03-26 00:59:59", + ), # utc+0 -> utc+1 + ( + "2023-03-26 00:00:00", + "Atlantic/Azores", + "2023-03-26 01:00:00", + "2023-03-25 23:59:59", + ), # utc-1 -> utc+0 + ], + ) + def test_tz_localize_nonexistent_shift( + self, stamp, tz, forward_expected, backward_expected + ): + ts = Timestamp(stamp) + forward_ts = ts.tz_localize(tz, nonexistent="shift_forward") + assert forward_ts == Timestamp(forward_expected, tz=tz) + backward_ts = ts.tz_localize(tz, nonexistent="shift_backward") + assert backward_ts == Timestamp(backward_expected, tz=tz) + + def test_tz_localize_ambiguous_raise(self): + # GH#13057 + ts = Timestamp("2015-11-1 01:00") + msg = "Cannot infer dst time from 2015-11-01 01:00:00," + with pytest.raises(AmbiguousTimeError, match=msg): + ts.tz_localize("US/Pacific", ambiguous="raise") + + def test_tz_localize_nonexistent_invalid_arg(self, warsaw): + # GH 22644 + tz = warsaw + ts = Timestamp("2015-03-29 02:00:00") + msg = ( + "The nonexistent argument must be one of 'raise', 'NaT', " + "'shift_forward', 'shift_backward' or a timedelta object" + ) + with pytest.raises(ValueError, match=msg): + ts.tz_localize(tz, nonexistent="foo") + + @pytest.mark.parametrize( + "stamp", + [ + "2014-02-01 09:00", + "2014-07-08 09:00", + "2014-11-01 17:00", + "2014-11-05 00:00", + ], + ) + def test_tz_localize_roundtrip(self, stamp, tz_aware_fixture): + tz = tz_aware_fixture + ts = Timestamp(stamp) + localized = ts.tz_localize(tz) + assert localized == Timestamp(stamp, tz=tz) + + msg = "Cannot localize tz-aware Timestamp" + with pytest.raises(TypeError, match=msg): + localized.tz_localize(tz) + + reset = localized.tz_localize(None) + assert reset == ts + assert reset.tzinfo is None + + def test_tz_localize_ambiguous_compat(self): + # validate that pytz and dateutil are compat for dst + # when the transition happens + naive = Timestamp("2013-10-27 01:00:00") + + pytz_zone = "Europe/London" + dateutil_zone = "dateutil/Europe/London" + result_pytz = naive.tz_localize(pytz_zone, ambiguous=False) + result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=False) + assert result_pytz._value == result_dateutil._value + assert result_pytz._value == 1382835600 + + # fixed ambiguous behavior + # see gh-14621, GH#45087 + assert result_pytz.to_pydatetime().tzname() == "GMT" + assert result_dateutil.to_pydatetime().tzname() == "GMT" + assert str(result_pytz) == str(result_dateutil) + + # 1 hour difference + result_pytz = naive.tz_localize(pytz_zone, ambiguous=True) + result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=True) + assert result_pytz._value == result_dateutil._value + assert result_pytz._value == 1382832000 + + # see gh-14621 + assert str(result_pytz) == str(result_dateutil) + assert ( + result_pytz.to_pydatetime().tzname() + == result_dateutil.to_pydatetime().tzname() + ) + + @pytest.mark.parametrize( + "tz", + [ + pytz.timezone("US/Eastern"), + gettz("US/Eastern"), + "US/Eastern", + "dateutil/US/Eastern", + ], + ) + def test_timestamp_tz_localize(self, tz): + stamp = Timestamp("3/11/2012 04:00") + + result = stamp.tz_localize(tz) + expected = Timestamp("3/11/2012 04:00", tz=tz) + assert result.hour == expected.hour + assert result == expected + + @pytest.mark.parametrize( + "start_ts, tz, end_ts, shift", + [ + ["2015-03-29 02:20:00", "Europe/Warsaw", "2015-03-29 03:00:00", "forward"], + [ + "2015-03-29 02:20:00", + "Europe/Warsaw", + "2015-03-29 01:59:59.999999999", + "backward", + ], + [ + "2015-03-29 02:20:00", + "Europe/Warsaw", + "2015-03-29 03:20:00", + timedelta(hours=1), + ], + [ + "2015-03-29 02:20:00", + "Europe/Warsaw", + "2015-03-29 01:20:00", + timedelta(hours=-1), + ], + ["2018-03-11 02:33:00", "US/Pacific", "2018-03-11 03:00:00", "forward"], + [ + "2018-03-11 02:33:00", + "US/Pacific", + "2018-03-11 01:59:59.999999999", + "backward", + ], + [ + "2018-03-11 02:33:00", + "US/Pacific", + "2018-03-11 03:33:00", + timedelta(hours=1), + ], + [ + "2018-03-11 02:33:00", + "US/Pacific", + "2018-03-11 01:33:00", + timedelta(hours=-1), + ], + ], + ) + @pytest.mark.parametrize("tz_type", ["", "dateutil/"]) + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) + def test_timestamp_tz_localize_nonexistent_shift( + self, start_ts, tz, end_ts, shift, tz_type, unit + ): + # GH 8917, 24466 + tz = tz_type + tz + if isinstance(shift, str): + shift = "shift_" + shift + ts = Timestamp(start_ts).as_unit(unit) + result = ts.tz_localize(tz, nonexistent=shift) + expected = Timestamp(end_ts).tz_localize(tz) + + if unit == "us": + assert result == expected.replace(nanosecond=0) + elif unit == "ms": + micros = expected.microsecond - expected.microsecond % 1000 + assert result == expected.replace(microsecond=micros, nanosecond=0) + elif unit == "s": + assert result == expected.replace(microsecond=0, nanosecond=0) + else: + assert result == expected + assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value + + @pytest.mark.parametrize("offset", [-1, 1]) + def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset, warsaw): + # GH 8917, 24466 + tz = warsaw + ts = Timestamp("2015-03-29 02:20:00") + msg = "The provided timedelta will relocalize on a nonexistent time" + with pytest.raises(ValueError, match=msg): + ts.tz_localize(tz, nonexistent=timedelta(seconds=offset)) + + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) + def test_timestamp_tz_localize_nonexistent_NaT(self, warsaw, unit): + # GH 8917 + tz = warsaw + ts = Timestamp("2015-03-29 02:20:00").as_unit(unit) + result = ts.tz_localize(tz, nonexistent="NaT") + assert result is NaT + + @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"]) + def test_timestamp_tz_localize_nonexistent_raise(self, warsaw, unit): + # GH 8917 + tz = warsaw + ts = Timestamp("2015-03-29 02:20:00").as_unit(unit) + msg = "2015-03-29 02:20:00" + with pytest.raises(pytz.NonExistentTimeError, match=msg): + ts.tz_localize(tz, nonexistent="raise") + msg = ( + "The nonexistent argument must be one of 'raise', 'NaT', " + "'shift_forward', 'shift_backward' or a timedelta object" + ) + with pytest.raises(ValueError, match=msg): + ts.tz_localize(tz, nonexistent="foo") diff --git a/shared/package-files/76/76bbc23fbb43e2bb5ab63724ef610f9a73cb251c8e845dddd5c68564c3bacae3/blob b/shared/package-files/76/76bbc23fbb43e2bb5ab63724ef610f9a73cb251c8e845dddd5c68564c3bacae3/blob new file mode 100644 index 0000000000000000000000000000000000000000..a7130019366087af497a9d1dde6b4b50552b48ee --- /dev/null +++ b/shared/package-files/76/76bbc23fbb43e2bb5ab63724ef610f9a73cb251c8e845dddd5c68564c3bacae3/blob @@ -0,0 +1,47 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value) +inline ::std::tuple _scaled_dot_product_flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, c10::optional scale=c10::nullopt) { + return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale); +} +namespace symint { + template ::value>> + ::std::tuple _scaled_dot_product_flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, c10::optional scale=c10::nullopt) { + return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale); + } +} + +// aten::_scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value) +inline ::std::tuple _scaled_dot_product_flash_attention_backward_symint(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, c10::optional scale=c10::nullopt) { + return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale); +} +namespace symint { + template ::value>> + ::std::tuple _scaled_dot_product_flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, c10::optional scale=c10::nullopt) { + return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale); + } +} + +} diff --git a/shared/package-files/76/76bc49914b92ab7171d266938a03b37b9c8500e54c7412bb3684c71cd6eb8c48/blob b/shared/package-files/76/76bc49914b92ab7171d266938a03b37b9c8500e54c7412bb3684c71cd6eb8c48/blob new file mode 100644 index 0000000000000000000000000000000000000000..f0b6cfe5566a323b1e5f46d15d474c8ed92a7d93 --- /dev/null +++ b/shared/package-files/76/76bc49914b92ab7171d266938a03b37b9c8500e54c7412bb3684c71cd6eb8c48/blob @@ -0,0 +1,5724 @@ +error(0.008655238509357574342) D0 +error(0.005024469318403113061) D0 D2 +error(0.02385083467008956501) D0 D12 +error(0.002593846009587910239) D0 D12 ^ D13 +error(0.003081980007151399487) D0 D16 +error(0.002639902755890996891) D0 D16 ^ D13 +error(0.003842184335238879849) D0 D17 +error(0.002898253173592019605) D0 D17 ^ D13 +error(0.005847390600468179572) D1 D2 +error(0.00470139416974259608) D1 D2 ^ D18 +error(0.005000000000000000104) D1 D3 +error(0.02294150266429712676) D1 D15 +error(0.001906248377317176128) D1 D15 ^ D18 +error(0.0006997984483601198211) D1 D16 +error(0.001820766478220035541) D1 D16 ^ D18 +error(0.005204352400264394309) D1 D22 +error(0.001376370049693818745) D1 D22 ^ D18 +error(0.001605554510721137395) D1 D23 +error(0.001952560822939575095) D1 D23 ^ D18 +error(0.006275919669771217249) D2 D4 +error(0.001904843166178856947) D2 D4 ^ D19 +error(0.005000000000000000104) D2 D5 +error(0.01438732184361913788) D2 D16 +error(0.003177229025012474027) D2 D16 ^ D18 +error(0.002530464125309941741) D2 D16 ^ D18 D19 +error(0.002458457245041275729) D2 D16 ^ D19 +error(0.003265387281230920733) D2 D17 +error(0.000970360803632365162) D2 D17 ^ D18 +error(0.00250032283827045709) D2 D17 ^ D19 +error(0.003038127683575976047) D2 D23 +error(0.001172667442871833457) D2 D23 ^ D18 +error(0.0008837488006332886803) D2 D23 ^ D18 D19 +error(0.001240428526522836632) D2 D23 ^ D19 +error(0.0006178055609271660689) D2 D24 +error(7.096080795259620958e-05) D2 D24 ^ D18 +error(0.001081143338068574992) D2 D24 ^ D19 +error(0.0009369046358264651684) D2 D24 ^ D19 ^ D18 +error(0.005593658285465700174) D3 D5 +error(0.004569721578299409774) D3 D5 ^ D27 +error(0.03950266606113288226) D3 D22 +error(0.001884311356946611867) D3 D22 ^ D26 +error(0.002226676009275529045) D3 D22 ^ D26 D27 +error(0.002086279969986123452) D3 D22 ^ D27 +error(0.00159647570303038432) D3 D23 ^ D27 +error(0.0007239948757035712286) D3 D23 ^ D27 ^ D26 +error(0.001650214836977731154) D3 D30 +error(0.001211556913876224396) D3 D30 ^ D27 +error(0.01907030317590463833) D3 L0 +error(0.005304057682657864307) D3 L0 ^ D26 +error(0.01000000000000000021) D4 +error(0.01022375167558531306) D4 D6 +error(0.02578891967104643759) D4 D17 +error(0.001152350383394511787) D4 D17 ^ D19 +error(0.001376025493773692845) D4 D17 ^ D19 D20 +error(0.005872705044934519412) D4 D24 +error(0.001749589987933984148) D4 D24 ^ D19 +error(0.001881410645403374217) D4 D24 ^ D19 D20 +error(0.002387782738057993813) D4 D25 +error(0.001829746206618500888) D4 D25 ^ D20 +error(0.006650416618942734878) D5 D6 +error(0.003515679669745677607) D5 D6 ^ D28 +error(0.01037112596814665499) D5 D7 +error(0.02460761282020398205) D5 D23 +error(0.0006975140190207176081) D5 D23 ^ D27 +error(0.001372698168418071043) D5 D23 ^ D27 D28 +error(0.00115532882766365805) D5 D23 ^ D28 +error(0.002805947800495274709) D5 D24 +error(0.001699683344044926455) D5 D24 ^ D28 +error(0.01115601499714597919) D5 D30 +error(0.004273239826837275587) D5 D30 ^ D27 +error(0.003002831672363350836) D5 D30 ^ D27 D28 +error(0.001637331733113899564) D5 D30 ^ D28 +error(0.002244537807748606291) D5 D31 +error(0.0006532885557748213711) D5 D31 ^ D27 +error(0.001022249001719845651) D5 D31 ^ D28 +error(0.0002132150662408971236) D5 D31 ^ D28 ^ D27 +error(0.005758483918589984464) D6 D8 +error(0.003550988116016024626) D6 D8 ^ D29 +error(0.005000000000000000104) D6 D9 +error(0.01703358165324024912) D6 D24 +error(0.001271258653088126701) D6 D24 ^ D28 +error(0.00224356235292966005) D6 D24 ^ D28 D29 +error(0.002885827884710010643) D6 D25 +error(0.0005051308506302734777) D6 D25 ^ D28 +error(0.004076463627353216039) D6 D25 ^ D29 +error(0.000203580423988370887) D6 D25 ^ D29 ^ D28 +error(0.002431196427624318819) D6 D31 +error(0.003125941233153487972) D6 D31 ^ D28 +error(0.0008647728610668012827) D6 D31 ^ D28 D29 +error(0.001517848491436716218) D6 D31 ^ D29 +error(0.0002714407081137687017) D6 D32 +error(0.0009021270802836080672) D6 D32 ^ D28 +error(0.00253964821412265996) D6 D32 ^ D29 +error(0.006924529709978695206) D7 D9 +error(0.003653988750809223762) D7 D9 ^ D34 +error(0.03057232115834057282) D7 D30 +error(0.001330320245957783507) D7 D30 ^ D33 +error(0.001992897384221435468) D7 D30 ^ D33 D34 +error(0.002844173335440609938) D7 D30 ^ D34 +error(0.000773420062421033218) D7 D31 +error(2.788455091301460871e-05) D7 D31 ^ D33 +error(0.002639910985012601085) D7 D31 ^ D34 +error(0.0003665501902501303662) D7 D35 +error(0.002292668454280364938) D7 D35 ^ D34 +error(0.01529195820190704276) D7 L0 +error(0.004930909296564087337) D7 L0 ^ D33 +error(0.01456596776324312406) D8 +error(0.005950721831066263512) D8 D10 +error(0.01799893042501904059) D8 D25 +error(0.004713106238700603447) D8 D25 ^ D29 +error(0.004961014084312916593) D8 D32 +error(0.003603146795558741927) D8 D32 ^ D29 +error(0.008028364268208243448) D9 D10 +error(0.005800096362452544785) D9 D11 +error(0.01491120932979404616) D9 D31 +error(0.002147770077840551947) D9 D31 ^ D34 +error(0.003469772739516459661) D9 D32 +error(0.0006207378574178157868) D9 D32 ^ D34 +error(0.004306789500893352073) D9 D35 +error(0.00406013847108747418) D9 D35 ^ D34 +error(0.02090505228620892497) D10 D32 +error(0.01902843583800578608) D11 D35 +error(0.007732774435574031255) D11 L0 +error(0.005000000000000000104) D12 +error(0.01377140191755609096) D12 D16 +error(0.01316254369706144553) D12 D16 ^ D13 +error(0.02857365717892044674) D12 D36 +error(0.008187804202290056149) D12 D36 ^ D37 +error(0.006752054900691314455) D12 D40 +error(0.006349781933249819092) D12 D40 ^ D13 +error(0.004978707893828611571) D12 D40 ^ D37 +error(0.003764221099563926434) D12 D40 ^ D37 ^ D13 +error(0.00305811170313690121) D12 D41 +error(0.001355606463823049281) D12 D41 ^ D13 +error(0.002720072101049827822) D12 D41 ^ D13 D37 +error(0.0007162514653201519817) D12 D41 ^ D37 +error(0.005000000000000000104) D12 ^ D13 +error(0.006213397302591005048) D13 D37 ^ D12 +error(0.0251273856648333363) D13 +error(0.005000000000000000104) D13 D14 +error(0.001774539130170788102) D13 D14 ^ D12 +error(0.0002796968619654203862) D13 D14 ^ D16 D41 +error(0.0114336008299408369) D13 D14 ^ D17 +error(0.005002346730345576947) D13 D14 ^ D17 D41 +error(0.002901359869863939615) D13 D14 ^ D41 +error(0.0005821292772265862199) D13 D14 ^ D41 ^ D12 +error(0.02118600373088091321) D13 D19 +error(0.01342708442026241747) D13 D19 ^ D16 D17 +error(0.04837432224380126128) D13 D37 +error(0.003553059407795153887) D13 D37 ^ D40 D41 +error(0.004155872962511489473) D13 D37 ^ D41 +error(0.003535743537937868341) D13 D42 +error(0.002372881073082702946) D13 D42 ^ D16 D40 +error(3.088814442772618024e-05) D13 D42 ^ D16 D41 +error(0.0002677743536514186166) D13 D42 ^ D40 D41 +error(0.002766432488590481534) D13 D43 +error(0.002003001371357753489) D13 D43 ^ D16 D17 +error(0.0007617751072712451808) D13 D43 ^ D16 D40 +error(0.001724437185270334552) D13 D43 ^ D16 D41 +error(0.001091467339713199239) D13 D43 ^ D17 D41 +error(0.00195910551946494333) D13 D43 ^ D40 D41 +error(0.006077484115278257611) D13 ^ D0 +error(0.001742240094141442406) D13 ^ D17 +error(0.005000000000000000104) D14 +error(0.01330062400984628572) D14 D20 +error(0.01283032591083298896) D14 D20 ^ D17 +error(0.006444335023303983563) D14 D37 +error(0.0006733172831601593735) D14 D37 ^ D12 +error(0.005862290075143809613) D14 D37 ^ D41 +error(0.0008136568950686870862) D14 D37 ^ D41 ^ D12 +error(0.02804448788546923255) D14 D38 +error(0.01224644515584789178) D14 D38 ^ D41 +error(0.002167760793218917112) D14 D43 +error(0.0006482439155634309039) D14 D43 ^ D16 D17 +error(0.0006554643296627914477) D14 D43 ^ D16 D41 +error(0.0001808182923138514173) D14 D43 ^ D17 +error(0.002038558843002732067) D14 D43 ^ D17 D41 +error(0.0001340785921504384238) D14 D43 ^ D41 +error(0.003575688005574470616) D14 D44 +error(0.004475310371346201757) D14 D44 ^ D17 +error(0.00345098355018136219) D14 D44 ^ D41 +error(0.001693218948738322736) D14 D44 ^ D41 ^ D17 +error(0.00850664353847604103) D14 ^ D17 +error(0.007196430039866323104) D15 D16 +error(0.01043686886672560814) D15 D16 ^ D18 +error(0.002350509443893264785) D15 D16 ^ D18 D42 +error(0.0001924701327169168889) D15 D16 ^ D19 D42 +error(0.001328444822298451792) D15 D16 ^ D42 +error(0.0004422428033818157967) D15 D16 ^ D42 ^ D13 +error(0.01529801502436754952) D15 D22 +error(0.01309711380134978911) D15 D22 ^ D18 +error(0.02321446919291771452) D15 D39 +error(0.003758964575596710975) D15 D39 ^ D42 +error(0.001583423248511523895) D15 D40 +error(0.0004350561070420648989) D15 D40 ^ D13 +error(0.002418582978257866924) D15 D40 ^ D42 +error(0.0002796298770619333766) D15 D40 ^ D42 ^ D13 +error(0.002780585570467565895) D15 D46 +error(0.003659131334418356651) D15 D46 ^ D18 +error(0.002445659219989861598) D15 D46 ^ D42 +error(0.001480500595323643509) D15 D46 ^ D42 ^ D18 +error(0.002342039754099378614) D15 D47 +error(0.0003971852223546843471) D15 D47 ^ D18 D19 +error(0.001695357924281432841) D15 D47 ^ D18 D42 +error(0.000109853332386578866) D15 D47 ^ D19 D42 +error(4.517129173657599629e-05) D15 D47 ^ D42 +error(0.007870472908413491883) D16 D17 +error(0.005074485280850761157) D16 D17 ^ D13 +error(0.001537991900304986215) D16 D17 ^ D19 +error(9.842927005612744657e-05) D16 D17 ^ D19 D20 +error(0.001729297765277910352) D16 D17 ^ D19 D43 +error(0.0008369239912465332564) D16 D17 ^ D20 D43 +error(0.01568866679172467929) D16 D23 +error(0.01062103645539586548) D16 D23 ^ D18 D19 +error(0.02800496972801020182) D16 D40 +error(0.008857345427632928175) D16 D40 ^ D13 +error(0.001330748570182143991) D16 D40 ^ D42 +error(0.002708890916997034985) D16 D40 ^ D42 D43 +error(0.004269470014870236155) D16 D41 +error(9.74753423978128047e-05) D16 D41 ^ D42 D43 +error(0.003795022050357953376) D16 D47 +error(0.002450806810346344965) D16 D47 ^ D18 D19 +error(0.001182325052329548159) D16 D47 ^ D18 D42 +error(0.001394230569165803022) D16 D47 ^ D19 D42 +error(0.001347851322040039988) D16 D47 ^ D19 D43 +error(0.00173532620606171189) D16 D47 ^ D42 D43 +error(0.003116053244494311654) D16 D48 +error(7.316842974601893705e-05) D16 D48 ^ D19 D20 +error(0.00015381139946745172) D16 D48 ^ D19 D42 +error(0.0008071141978608846294) D16 D48 ^ D19 D43 +error(0.0001061468001811654107) D16 D48 ^ D20 D43 +error(0.0004214225008490263334) D16 D48 ^ D42 D43 +error(0.01000000000000000021) D17 +error(0.02605595841162460999) D17 D24 +error(0.0244451364355503728) D17 D24 ^ D19 D20 +error(0.03102491946459741065) D17 D41 +error(0.002140803014291666959) D17 D41 ^ D43 D44 +error(0.005011204418027772993) D17 D48 +error(0.002409795170171074013) D17 D48 ^ D19 D20 +error(0.0004867120612278240106) D17 D48 ^ D19 D43 +error(0.001734557560692578373) D17 D48 ^ D20 D43 +error(0.0008310577286774427754) D17 D48 ^ D20 D44 +error(0.002876015875940871915) D17 D48 ^ D43 D44 +error(5.689899368434303708e-05) D17 D49 +error(0.0005376255601673666108) D17 D49 ^ D20 D43 +error(0.001860052998044929096) D17 D49 ^ D20 D44 +error(0.0003270350619594853282) D17 D49 ^ D43 D44 +error(0.0001684762268719733065) D17 ^ D20 +error(0.01870778303321152247) D18 +error(0.008315897094965439204) D18 D19 +error(3.247691960770352984e-05) D18 D19 ^ D22 D23 +error(0.0002437602896713224755) D18 D19 ^ D22 D47 +error(0.002910193005919642101) D18 D19 ^ D23 D47 +error(0.01418979193457329917) D18 D27 +error(0.0123550349978960982) D18 D27 ^ D22 D23 +error(0.03402876169483597113) D18 D42 +error(0.00297341913608773151) D18 D42 ^ D46 D47 +error(0.00167198142382841866) D18 D50 +error(0.001978739641503692373) D18 D50 ^ D22 D46 +error(0.0003739016887504405208) D18 D50 ^ D22 D47 +error(0.0006191581992012207009) D18 D50 ^ D46 D47 +error(0.003564405145362673812) D18 D51 +error(0.002427865772048852337) D18 D51 ^ D22 D23 +error(0.002016980215619930579) D18 D51 ^ D22 D46 +error(0.001665163685732147384) D18 D51 ^ D22 D47 +error(0.001089534673102127496) D18 D51 ^ D23 D47 +error(0.002441047980058794978) D18 D51 ^ D46 D47 +error(0.0004010735829825645671) D18 ^ D46 L0 +error(0.0040421911780430652) D22 D46 ^ D18 +error(0.01801776806024180805) D19 +error(0.005678727598453678707) D19 D20 +error(0.000607895799866905789) D19 D20 ^ D23 D48 +error(0.0025882004664708534) D19 D20 ^ D24 D48 +error(0.01618476697258476593) D19 D28 +error(0.01610719351302367791) D19 D28 ^ D23 D24 +error(0.004930101446126109246) D19 D42 +error(0.0002881881964098772803) D19 D42 ^ D47 D48 +error(0.04574271143269240114) D19 D43 +error(0.001860329697148833646) D19 D43 ^ D47 D48 +error(0.00255198772447796712) D19 D51 +error(0.0005047023561676590529) D19 D51 ^ D22 D23 +error(0.001452256159036316528) D19 D51 ^ D23 D47 +error(5.222076102721136015e-05) D19 D51 ^ D23 D48 +error(0.0009987913400580498199) D19 D51 ^ D47 D48 +error(0.001430194805650022039) D19 D52 +error(0.002007285104460634732) D19 D52 ^ D23 D24 +error(0.001224248109508729171) D19 D52 ^ D23 D47 +error(0.002303664480707598265) D19 D52 ^ D23 D48 +error(0.0009171454591137486075) D19 D52 ^ D24 D48 +error(0.002191714195832245807) D19 D52 ^ D47 D48 +error(0.0007817237497497185909) D19 ^ D4 +error(0.003026388420657975115) D19 ^ D17 +error(0.01000000000000000021) D20 +error(0.00824641611822066016) D20 D21 +error(0.0007539726056751901205) D20 D21 ^ D17 +error(0.0001210959338265430346) D20 D21 ^ D24 D49 +error(0.01065514566545480192) D20 D21 ^ D25 +error(0.005273755897734558329) D20 D21 ^ D25 D49 +error(0.00184597880693155897) D20 D21 ^ D49 +error(0.01341043799155718606) D20 D29 +error(0.0101098775148154036) D20 D29 ^ D24 D25 +error(0.003249664646197158047) D20 D43 +error(2.258206681107317873e-05) D20 D43 ^ D48 D49 +error(0.02265899218759278091) D20 D44 +error(0.004590199147543793691) D20 D44 ^ D17 +error(0.002645517561442980222) D20 D44 ^ D48 D49 +error(0.0005399062537493103456) D20 D44 ^ D49 +error(0.002277233782169691897) D20 D52 +error(0.0002528250109153119818) D20 D52 ^ D23 D24 +error(0.0006205257979712591916) D20 D52 ^ D23 D48 +error(0.001404758555723596139) D20 D52 ^ D24 D48 +error(0.0002405291802527288812) D20 D52 ^ D24 D49 +error(0.0003097319487677911579) D20 D52 ^ D48 D49 +error(0.001047705250796779949) D20 D53 +error(0.00237092510280944831) D20 D53 ^ D24 D25 +error(0.001037220928621594273) D20 D53 ^ D24 D48 +error(0.00238058383085898136) D20 D53 ^ D24 D49 +error(0.0008835768967079051526) D20 D53 ^ D25 D49 +error(0.002259774772269825763) D20 D53 ^ D48 D49 +error(0.005550742479566062211) D20 ^ D4 +error(0.000196918139655712966) D20 ^ D17 ^ D4 +error(0.0003914310350318868695) D20 ^ D19 ^ D4 +error(0.0006890297376732726917) D20 ^ D19 ^ D17 +error(0.002126486990335552194) D20 ^ D25 +error(0.04302617862843365754) D21 +error(0.00225151851890723325) D21 D44 +error(0.0001797993500064738813) D21 D44 ^ D17 +error(0.002356030447914673944) D21 D44 ^ D49 +error(0.0345566698397392208) D21 D45 +error(0.005003744614217759193) D21 D45 ^ D49 +error(0.001837583674123140394) D21 D53 +error(9.255458431562874132e-05) D21 D53 ^ D24 D25 +error(0.0002126721966588340058) D21 D53 ^ D24 D49 +error(0.002035990511446809058) D21 D53 ^ D25 D49 +error(0.02449591662043165696) D21 ^ D25 +error(0.0009042125990949610812) D21 ^ D49 +error(0.001560696983551172019) D21 ^ D49 ^ D25 +error(0.01139979382322551041) D22 D23 +error(0.0008839214736401847673) D22 D23 ^ D18 +error(0.001347828735886647759) D22 D23 ^ D26 +error(0.0005245164796110836402) D22 D23 ^ D27 D28 +error(0.00158847535642978651) D22 D23 ^ D27 D51 +error(0.002133846503678784451) D22 D23 ^ D27 ^ D26 +error(0.04904868400430456576) D22 D46 +error(0.003544968265632814693) D22 D46 ^ D50 D51 +error(0.003865628745054386969) D22 D47 +error(0.000441796954324594226) D22 D47 ^ D50 D51 +error(0.0009740040964997024285) D22 D54 +error(0.00188554410197714988) D22 D54 ^ D27 D51 +error(0.01000000000000000021) D22 L0 +error(0.01136584429027271553) D22 L0 ^ D26 +error(0.003675582362634155064) D26 D50 ^ D22 L0 +error(0.01560166226993598207) D23 D24 +error(0.0001592700776475997331) D23 D24 ^ D19 +error(0.0005433674386330002593) D23 D24 ^ D19 ^ D18 +error(0.001717822324956679546) D23 D24 ^ D28 D29 +error(0.002702669103548420697) D23 D24 ^ D28 D52 +error(0.001427879251377528122) D23 D24 ^ D28 ^ D27 +error(0.0006166556002974491434) D23 D24 ^ D29 D52 +error(0.01571352240609787815) D23 D30 +error(0.01986804758856408268) D23 D30 ^ D27 D28 +error(0.02961831943462597469) D23 D47 +error(0.002972165594026740694) D23 D47 ^ D51 D52 +error(0.00414184937373599394) D23 D48 +error(0.00040167431689305317) D23 D48 ^ D51 D52 +error(0.005690305629853309802) D23 D54 +error(0.006400338574826603191) D23 D54 ^ D27 D28 +error(0.002210171177652492467) D23 D54 ^ D27 D51 +error(0.007612181774541293064) D23 D54 ^ D28 D51 +error(0.001786447785683612389) D23 D54 ^ D28 D52 +error(0.004060767403088009868) D23 D54 ^ D51 D52 +error(0.001749884553720177727) D23 D55 +error(0.0007133736782402601805) D23 D55 ^ D28 D29 +error(0.0005844947904700150375) D23 D55 ^ D28 D51 +error(0.0008217823092129306105) D23 D55 ^ D28 D52 +error(0.0003275095103629303275) D23 D55 ^ D29 D52 +error(0.0006123041623268492663) D23 D55 ^ D51 D52 +error(0.007683732818337842344) D24 D25 +error(0.0002626819396723593068) D24 D25 ^ D20 +error(0.002159776542317827768) D24 D25 ^ D20 ^ D19 +error(0.001065015987171621893) D24 D25 ^ D29 +error(0.001842590021007301871) D24 D25 ^ D29 D53 +error(8.703821125779190218e-05) D24 D25 ^ D29 ^ D28 +error(0.01028956702237640054) D24 D31 +error(0.01090691286506158091) D24 D31 ^ D28 D29 +error(0.02106229162894282872) D24 D48 +error(0.002751152448060949218) D24 D48 ^ D52 D53 +error(0.003538841843038994985) D24 D49 +error(0.0008757110100126239138) D24 D55 +error(0.002941122394742301787) D24 D55 ^ D28 D29 +error(0.001165932778592970644) D24 D55 ^ D28 D52 +error(0.003280475747202545207) D24 D55 ^ D29 D52 +error(0.001642146425221697624) D24 D55 ^ D29 D53 +error(0.002816897898481184048) D24 D55 ^ D52 D53 +error(0.0006886146142845198884) D24 D56 +error(0.0001236420909161301809) D24 D56 ^ D29 +error(0.000685689790586139266) D24 D56 ^ D29 D52 +error(0.001457910846507099421) D24 D56 ^ D29 D53 +error(0.0002590162334421474365) D24 D56 ^ D52 D53 +error(5.747153257964691372e-05) D24 D56 ^ D53 +error(0.01114830864509363043) D25 +error(0.01566927502734416153) D25 D32 +error(0.01881194390920981965) D25 D32 ^ D29 +error(0.02174588721229521807) D25 D49 +error(0.00218188050196639876) D25 D49 ^ D53 +error(0.003449213835088781998) D25 D56 +error(0.002681972083768658158) D25 D56 ^ D29 +error(0.003567239636822126542) D25 D56 ^ D53 +error(0.0009720917822013221739) D25 D56 ^ D53 ^ D29 +error(0.03008591843777828206) D26 +error(0.01375847397471665311) D26 D27 +error(0.002649666246898320105) D26 D27 ^ D3 L0 +error(0.01860571933927756064) D26 D27 ^ D22 L0 +error(0.01809902708512096253) D26 D50 +error(0.01960655168739627516) D27 +error(0.0122858884862790587) D27 D28 +error(0.003973470958629069134) D27 D28 ^ D30 D54 +error(0.01622618785558644153) D27 D33 +error(0.009569410774063247943) D27 D33 ^ D30 L0 +error(0.004973740584631117755) D27 D50 +error(0.003083695718806104061) D27 D50 ^ D22 L0 +error(6.326914210115742673e-05) D27 D50 ^ D54 L0 +error(0.000437796100933523862) D27 D50 ^ D54 L0 ^ D22 L0 +error(0.02802096798889971291) D27 D51 +error(0.0009781054333567957074) D27 D51 ^ D22 L0 +error(0.004258064841452545435) D27 D51 ^ D54 L0 +error(0.002293241519674286358) D27 D57 +error(0.002083689327902756277) D27 D57 ^ D30 L0 +error(0.003184439299356970048) D27 D57 ^ D54 L0 +error(0.0003075964336023181544) D27 D57 ^ D54 L0 ^ D30 L0 +error(0.004292492580379838121) D27 ^ D30 L0 +error(0.001342521129601774357) D27 ^ D30 L0 ^ D3 L0 ^ D26 +error(0.01000000000000000021) D28 +error(0.005000000000000000104) D28 D29 +error(0.001281790782509878391) D28 D29 ^ D30 D31 +error(0.002746525552341930968) D28 D29 ^ D31 D55 +error(0.01024567954789808166) D28 D34 +error(0.0111140179970211847) D28 D34 ^ D30 D31 +error(0.007372542091817689894) D28 D51 +error(0.0007550883971604156709) D28 D51 ^ D54 D55 +error(0.02903602395795713831) D28 D52 +error(0.002102104693332725906) D28 D52 ^ D54 D55 +error(0.003169378669323305153) D28 D57 +error(0.001191557425971731836) D28 D57 ^ D30 D54 +error(0.0001597772101005079804) D28 D57 ^ D30 D55 +error(0.0001021827979209038615) D28 D57 ^ D30 L0 +error(0.0005511678242116416215) D28 D57 ^ D54 D55 +error(1.679354630858518888e-05) D28 D57 ^ D54 L0 +error(0.001533444865295702621) D28 D58 +error(0.001663960370674462397) D28 D58 ^ D30 D31 +error(0.0007716218076495109674) D28 D58 ^ D30 D54 +error(0.001303219383453746829) D28 D58 ^ D30 D55 +error(0.000774858462820291762) D28 D58 ^ D31 D55 +error(0.00202762776909865992) D28 D58 ^ D54 D55 +error(0.02370794125415254944) D29 +error(0.004375250986392631436) D29 D52 +error(0.0001996290527887550252) D29 D52 ^ D55 D56 +error(0.02025078136410074503) D29 D53 +error(0.001389942840017453947) D29 D53 ^ D55 D56 +error(0.001697427904974847281) D29 D58 +error(9.531024276690012293e-05) D29 D58 ^ D30 D31 +error(0.0002003070882208187711) D29 D58 ^ D30 D55 +error(0.001002593182003129989) D29 D58 ^ D31 D55 +error(0.001033248267979413682) D29 ^ D8 +error(0.001003288422730659255) D29 ^ D25 +error(0.008147890508292196174) D30 D31 +error(0.0005075093069069269106) D30 D31 ^ D27 +error(0.001037091761061517811) D30 D31 ^ D28 ^ D27 +error(0.0004619268455969836374) D30 D31 ^ D33 +error(0.00170035907150524186) D30 D31 ^ D34 +error(0.002265174227511792399) D30 D31 ^ D34 D58 +error(0.0003610448547890982083) D30 D31 ^ D58 +error(0.03561013233827770019) D30 D54 +error(0.004322700216861186627) D30 D54 ^ D57 D58 +error(0.003938494697766241337) D30 D55 +error(0.0005358008309723712214) D30 D55 ^ D57 D58 +error(0.002034052694461135468) D30 D59 +error(0.0001466308340950007473) D30 D59 ^ D34 +error(0.001920194442056039194) D30 D59 ^ D34 D58 +error(0.01000000000000000021) D30 L0 +error(0.00160265819750712228) D30 L0 ^ D26 +error(0.005000000000000000104) D30 L0 ^ D33 +error(0.006960888616783743148) D31 D32 +error(0.0006003225837390239452) D31 D32 ^ D28 +error(0.0158467291444123401) D31 D32 ^ D29 +error(0.001494031497363191479) D31 D32 ^ D29 ^ D28 +error(0.0004904702263788265036) D31 D32 ^ D34 +error(0.01552630318798537377) D31 D35 +error(0.01511203328355725448) D31 D35 ^ D34 +error(0.01912154204876750918) D31 D55 +error(0.001896228017575547591) D31 D55 ^ D29 +error(0.003907155462371127326) D31 D55 ^ D58 +error(0.00279557314330079092) D31 D56 +error(0.002620934694098134548) D31 D56 ^ D29 +error(0.0004013694757154773717) D31 D56 ^ D58 +error(0.0001537267977297909955) D31 D56 ^ D58 ^ D29 +error(0.003820638366809637251) D31 D59 +error(0.003421241639577967189) D31 D59 ^ D34 +error(0.004007581078155113968) D31 D59 ^ D58 +error(0.001746012587198167822) D31 D59 ^ D58 ^ D34 +error(0.02606250389870726561) D32 D56 +error(0.002389270985273113726) D32 D56 ^ D29 +error(0.0247500106613791869) D33 +error(0.008623375144712192714) D33 D34 +error(0.001399710922081355688) D33 D34 ^ D7 L0 +error(0.01155816627878904559) D33 D34 ^ D30 L0 +error(0.02738393697272551233) D33 D57 +error(0.004004257617406230957) D33 D57 ^ D30 L0 +error(0.03102848333002911768) D34 +error(0.002736244045764444407) D34 D57 +error(0.002855052799012060792) D34 D57 ^ D30 L0 +error(0.0006116163304378687384) D34 D57 ^ D59 L0 +error(0.0007069775710064596895) D34 D57 ^ D59 L0 ^ D30 L0 +error(0.02229227109480388241) D34 D58 +error(0.001481615400962180704) D34 D58 ^ D30 L0 +error(0.002922078673854252608) D34 D58 ^ D59 L0 +error(0.01405094209712290897) D34 ^ D35 L0 +error(0.0006920585999744716414) D34 ^ D35 L0 ^ D7 L0 ^ D33 +error(0.0004436045414117925178) D34 ^ D35 L0 ^ D33 +error(0.0013622205925644421) D34 ^ D59 L0 +error(0.004149845774982054321) D35 D59 ^ D34 +error(0.01895412426906178255) D35 D59 +error(0.005378537237988686992) D35 L0 +error(0.000244937322424869223) D35 L0 ^ D7 L0 ^ D33 +error(0.001569035131304861389) D35 L0 ^ D33 +error(0.005000000000000000104) D36 +error(0.01668747401411250705) D36 D40 +error(0.01827076257666529827) D36 D40 ^ D37 +error(0.02857365717892044674) D36 D60 +error(0.008187804202290056149) D36 D60 ^ D61 +error(0.006752054900691314455) D36 D64 +error(0.006349781933249819092) D36 D64 ^ D37 +error(0.004978707893828611571) D36 D64 ^ D61 +error(0.003764221099563926434) D36 D64 ^ D61 ^ D37 +error(0.00305811170313690121) D36 D65 +error(0.001355606463823049281) D36 D65 ^ D37 +error(0.002720072101049827822) D36 D65 ^ D37 D61 +error(0.0007162514653201519817) D36 D65 ^ D61 +error(0.005000000000000000104) D36 ^ D37 +error(0.006213397302591005048) D37 D61 ^ D36 +error(0.01000000000000000021) D37 +error(0.007614310746050743754) D37 D38 +error(0.0005954277109348562764) D37 D38 ^ D36 +error(0.000465636753644584143) D37 D38 ^ D40 D41 +error(0.0002796968619654203862) D37 D38 ^ D40 D65 +error(0.01582554105481599749) D37 D38 ^ D41 +error(0.005002346730345576947) D37 D38 ^ D41 D65 +error(0.002901359869863939615) D37 D38 ^ D65 +error(0.0005821292772265862199) D37 D38 ^ D65 ^ D36 +error(0.02094673066392089764) D37 D43 +error(0.01260591433803377043) D37 D43 ^ D40 D41 +error(0.04837432224380126128) D37 D61 +error(0.003553059407795153887) D37 D61 ^ D64 D65 +error(0.004155872962511489473) D37 D61 ^ D65 +error(0.003535743537937868341) D37 D66 +error(0.002372881073082702946) D37 D66 ^ D40 D64 +error(3.088814442772618024e-05) D37 D66 ^ D40 D65 +error(0.0002677743536514186166) D37 D66 ^ D64 D65 +error(0.002766432488590481534) D37 D67 +error(0.002003001371357753489) D37 D67 ^ D40 D41 +error(0.0007617751072712451808) D37 D67 ^ D40 D64 +error(0.001724437185270334552) D37 D67 ^ D40 D65 +error(0.001091467339713199239) D37 D67 ^ D41 D65 +error(0.00195910551946494333) D37 D67 ^ D64 D65 +error(0.01704609170648706262) D38 D44 +error(0.01603323914711612952) D38 D44 ^ D41 +error(0.006444335023303983563) D38 D61 +error(0.0006733172831601593735) D38 D61 ^ D36 +error(0.005862290075143809613) D38 D61 ^ D65 +error(0.0008136568950686870862) D38 D61 ^ D65 ^ D36 +error(0.02804448788546923255) D38 D62 +error(0.01224644515584789178) D38 D62 ^ D65 +error(0.002167760793218917112) D38 D67 +error(0.0006482439155634309039) D38 D67 ^ D40 D41 +error(0.0006554643296627914477) D38 D67 ^ D40 D65 +error(0.0001808182923138514173) D38 D67 ^ D41 +error(0.002038558843002732067) D38 D67 ^ D41 D65 +error(0.0001340785921504384238) D38 D67 ^ D65 +error(0.003575688005574470616) D38 D68 +error(0.004475310371346201757) D38 D68 ^ D41 +error(0.00345098355018136219) D38 D68 ^ D65 +error(0.001693218948738322736) D38 D68 ^ D65 ^ D41 +error(0.009232193128085404779) D39 D40 +error(0.0002630814526406159313) D39 D40 ^ D37 +error(0.009686902281069798351) D39 D40 ^ D42 +error(0.0002516825390100136859) D39 D40 ^ D42 D43 +error(0.002350509443893264785) D39 D40 ^ D42 D66 +error(0.0001924701327169168889) D39 D40 ^ D43 D66 +error(0.001328444822298451792) D39 D40 ^ D66 +error(0.0004422428033818157967) D39 D40 ^ D66 ^ D37 +error(0.01553238535686285622) D39 D46 +error(0.01442107373804212) D39 D46 ^ D42 +error(0.02321446919291771452) D39 D63 +error(0.003758964575596710975) D39 D63 ^ D66 +error(0.001583423248511523895) D39 D64 +error(0.0004350561070420648989) D39 D64 ^ D37 +error(0.002418582978257866924) D39 D64 ^ D66 +error(0.0002796298770619333766) D39 D64 ^ D66 ^ D37 +error(0.002780585570467565895) D39 D70 +error(0.003659131334418356651) D39 D70 ^ D42 +error(0.002445659219989861598) D39 D70 ^ D66 +error(0.001480500595323643509) D39 D70 ^ D66 ^ D42 +error(0.002342039754099378614) D39 D71 +error(0.0003971852223546843471) D39 D71 ^ D42 D43 +error(0.001695357924281432841) D39 D71 ^ D42 D66 +error(0.000109853332386578866) D39 D71 ^ D43 D66 +error(4.517129173657599629e-05) D39 D71 ^ D66 +error(0.009370177167621668649) D40 D41 +error(0.0013749192686105837) D40 D41 ^ D13 +error(0.0004326376275655316982) D40 D41 ^ D42 D43 +error(0.001729297765277910352) D40 D41 ^ D43 D67 +error(0.0008369239912465332564) D40 D41 ^ D44 D67 +error(0.01725430315521830557) D40 D47 +error(0.009937067068622049831) D40 D47 ^ D42 D43 +error(0.02800496972801020182) D40 D64 +error(0.008857345427632928175) D40 D64 ^ D37 +error(0.001330748570182143991) D40 D64 ^ D66 +error(0.002708890916997034985) D40 D64 ^ D66 D67 +error(0.004269470014870236155) D40 D65 +error(9.74753423978128047e-05) D40 D65 ^ D66 D67 +error(0.003795022050357953376) D40 D71 +error(0.002450806810346344965) D40 D71 ^ D42 D43 +error(0.001182325052329548159) D40 D71 ^ D42 D66 +error(0.001394230569165803022) D40 D71 ^ D43 D66 +error(0.001347851322040039988) D40 D71 ^ D43 D67 +error(0.00173532620606171189) D40 D71 ^ D66 D67 +error(0.003116053244494311654) D40 D72 +error(7.316842974601893705e-05) D40 D72 ^ D43 D44 +error(0.00015381139946745172) D40 D72 ^ D43 D66 +error(0.0008071141978608846294) D40 D72 ^ D43 D67 +error(0.0001061468001811654107) D40 D72 ^ D44 D67 +error(0.0004214225008490263334) D40 D72 ^ D66 D67 +error(0.01000000000000000021) D41 +error(0.0270222666017383116) D41 D48 +error(0.02417905793237870235) D41 D48 ^ D43 D44 +error(0.03102491946459741065) D41 D65 +error(0.002140803014291666959) D41 D65 ^ D67 D68 +error(0.005011204418027772993) D41 D72 +error(0.002409795170171074013) D41 D72 ^ D43 D44 +error(0.0004867120612278240106) D41 D72 ^ D43 D67 +error(0.001734557560692578373) D41 D72 ^ D44 D67 +error(0.0008310577286774427754) D41 D72 ^ D44 D68 +error(0.002876015875940871915) D41 D72 ^ D67 D68 +error(5.689899368434303708e-05) D41 D73 +error(0.0005376255601673666108) D41 D73 ^ D44 D67 +error(0.001860052998044929096) D41 D73 ^ D44 D68 +error(0.0003270350619594853282) D41 D73 ^ D67 D68 +error(0.01000000000000000021) D42 +error(0.00998951012393598653) D42 D43 +error(0.0002647118028759689896) D42 D43 ^ D46 D47 +error(0.0002437602896713224755) D42 D43 ^ D46 D71 +error(0.0003259292904997979664) D42 D43 ^ D47 D48 +error(0.002910193005919642101) D42 D43 ^ D47 D71 +error(0.01563311530723593412) D42 D51 +error(0.01148884923131972789) D42 D51 ^ D46 D47 +error(0.03402876169483597113) D42 D66 +error(0.00297341913608773151) D42 D66 ^ D70 D71 +error(0.00167198142382841866) D42 D74 +error(0.001978739641503692373) D42 D74 ^ D46 D70 +error(0.0003739016887504405208) D42 D74 ^ D46 D71 +error(0.0006191581992012207009) D42 D74 ^ D70 D71 +error(0.003564405145362673812) D42 D75 +error(0.002427865772048852337) D42 D75 ^ D46 D47 +error(0.002016980215619930579) D42 D75 ^ D46 D70 +error(0.001665163685732147384) D42 D75 ^ D46 D71 +error(0.001089534673102127496) D42 D75 ^ D47 D71 +error(0.002441047980058794978) D42 D75 ^ D70 D71 +error(0.0004010735829825645671) D42 ^ D70 L0 +error(0.0040421911780430652) D46 D70 ^ D42 +error(0.01013563020920371822) D43 D44 +error(0.0008314930570387067546) D43 D44 ^ D41 +error(0.0001530404613110457714) D43 D44 ^ D47 D48 +error(0.000607895799866905789) D43 D44 ^ D47 D72 +error(3.403628659066277234e-05) D43 D44 ^ D48 D49 +error(0.0025882004664708534) D43 D44 ^ D48 D72 +error(0.01727203508574649132) D43 D52 +error(0.0145277865377167175) D43 D52 ^ D47 D48 +error(0.004930101446126109246) D43 D66 +error(0.0002881881964098772803) D43 D66 ^ D71 D72 +error(0.04574271143269240114) D43 D67 +error(0.001860329697148833646) D43 D67 ^ D71 D72 +error(0.00255198772447796712) D43 D75 +error(0.0005047023561676590529) D43 D75 ^ D46 D47 +error(0.001452256159036316528) D43 D75 ^ D47 D71 +error(5.222076102721136015e-05) D43 D75 ^ D47 D72 +error(0.0009987913400580498199) D43 D75 ^ D71 D72 +error(0.001430194805650022039) D43 D76 +error(0.002007285104460634732) D43 D76 ^ D47 D48 +error(0.001224248109508729171) D43 D76 ^ D47 D71 +error(0.002303664480707598265) D43 D76 ^ D47 D72 +error(0.0009171454591137486075) D43 D76 ^ D48 D72 +error(0.002191714195832245807) D43 D76 ^ D71 D72 +error(0.009797724443923057011) D44 D45 +error(0.0001021472594512653998) D44 D45 ^ D48 D49 +error(0.0001210959338265430346) D44 D45 ^ D48 D73 +error(0.01190918523369760215) D44 D45 ^ D49 +error(0.005273755897734558329) D44 D45 ^ D49 D73 +error(0.00184597880693155897) D44 D45 ^ D73 +error(0.01377684914337177352) D44 D53 +error(0.01093440003708149623) D44 D53 ^ D48 D49 +error(0.003249664646197158047) D44 D67 +error(2.258206681107317873e-05) D44 D67 ^ D72 D73 +error(0.02265899218759278091) D44 D68 +error(0.004590199147543793691) D44 D68 ^ D41 +error(0.002645517561442980222) D44 D68 ^ D72 D73 +error(0.0005399062537493103456) D44 D68 ^ D73 +error(0.002277233782169691897) D44 D76 +error(0.0002528250109153119818) D44 D76 ^ D47 D48 +error(0.0006205257979712591916) D44 D76 ^ D47 D72 +error(0.001404758555723596139) D44 D76 ^ D48 D72 +error(0.0002405291802527288812) D44 D76 ^ D48 D73 +error(0.0003097319487677911579) D44 D76 ^ D72 D73 +error(0.001047705250796779949) D44 D77 +error(0.00237092510280944831) D44 D77 ^ D48 D49 +error(0.001037220928621594273) D44 D77 ^ D48 D72 +error(0.00238058383085898136) D44 D77 ^ D48 D73 +error(0.0008835768967079051526) D44 D77 ^ D49 D73 +error(0.002259774772269825763) D44 D77 ^ D72 D73 +error(0.01260811278973474753) D45 +error(0.00225151851890723325) D45 D68 +error(0.0001797993500064738813) D45 D68 ^ D41 +error(0.002356030447914673944) D45 D68 ^ D73 +error(0.0345566698397392208) D45 D69 +error(0.005003744614217759193) D45 D69 ^ D73 +error(0.001837583674123140394) D45 D77 +error(9.255458431562874132e-05) D45 D77 ^ D48 D49 +error(0.0002126721966588340058) D45 D77 ^ D48 D73 +error(0.002035990511446809058) D45 D77 ^ D49 D73 +error(0.02090970420602020902) D45 ^ D49 +error(0.0009042125990949610812) D45 ^ D73 +error(0.001560696983551172019) D45 ^ D73 ^ D49 +error(0.01374568531695860747) D46 D47 +error(0.0002954516562893196702) D46 D47 ^ D50 D51 +error(0.00158847535642978651) D46 D47 ^ D51 D75 +error(0.04904868400430456576) D46 D70 +error(0.003544968265632814693) D46 D70 ^ D74 D75 +error(0.003865628745054386969) D46 D71 +error(0.000441796954324594226) D46 D71 ^ D74 D75 +error(0.0009740040964997024285) D46 D78 +error(0.00188554410197714988) D46 D78 ^ D51 D75 +error(0.01000000000000000021) D46 L0 +error(0.01186879937024130915) D46 L0 ^ D50 +error(0.003675582362634155064) D50 D74 ^ D46 L0 +error(0.01735160188785484295) D47 D48 +error(0.0007088289629090005787) D47 D48 ^ D51 D52 +error(0.0005313038609727570695) D47 D48 ^ D52 D53 +error(0.002702669103548420697) D47 D48 ^ D52 D76 +error(0.0006166556002974491434) D47 D48 ^ D53 D76 +error(0.0207233958407102431) D47 D54 +error(0.02026670657223518177) D47 D54 ^ D51 D52 +error(0.02961831943462597469) D47 D71 +error(0.002972165594026740694) D47 D71 ^ D75 D76 +error(0.00414184937373599394) D47 D72 +error(0.00040167431689305317) D47 D72 ^ D75 D76 +error(0.005690305629853309802) D47 D78 +error(0.006400338574826603191) D47 D78 ^ D51 D52 +error(0.002210171177652492467) D47 D78 ^ D51 D75 +error(0.007612181774541293064) D47 D78 ^ D52 D75 +error(0.001786447785683612389) D47 D78 ^ D52 D76 +error(0.004060767403088009868) D47 D78 ^ D75 D76 +error(0.001749884553720177727) D47 D79 +error(0.0007133736782402601805) D47 D79 ^ D52 D53 +error(0.0005844947904700150375) D47 D79 ^ D52 D75 +error(0.0008217823092129306105) D47 D79 ^ D52 D76 +error(0.0003275095103629303275) D47 D79 ^ D53 D76 +error(0.0006123041623268492663) D47 D79 ^ D75 D76 +error(0.006835861022765376757) D48 D49 +error(0.0002649652178908865757) D48 D49 ^ D52 D53 +error(0.001842590021007301871) D48 D49 ^ D53 D77 +error(0.01360447555925056555) D48 D55 +error(0.01129163812096881624) D48 D55 ^ D52 D53 +error(0.02106229162894282872) D48 D72 +error(0.002751152448060949218) D48 D72 ^ D76 D77 +error(0.003538841843038994985) D48 D73 +error(0.0008757110100126239138) D48 D79 +error(0.002941122394742301787) D48 D79 ^ D52 D53 +error(0.001165932778592970644) D48 D79 ^ D52 D76 +error(0.003280475747202545207) D48 D79 ^ D53 D76 +error(0.001642146425221697624) D48 D79 ^ D53 D77 +error(0.002816897898481184048) D48 D79 ^ D76 D77 +error(0.0006886146142845198884) D48 D80 +error(0.0001236420909161301809) D48 D80 ^ D53 +error(0.000685689790586139266) D48 D80 ^ D53 D76 +error(0.001457910846507099421) D48 D80 ^ D53 D77 +error(0.0002590162334421474365) D48 D80 ^ D76 D77 +error(5.747153257964691372e-05) D48 D80 ^ D77 +error(0.01247992211153514663) D49 +error(0.01569289063977472726) D49 D56 +error(0.01852761195375728781) D49 D56 ^ D53 +error(0.02174588721229521807) D49 D73 +error(0.00218188050196639876) D49 D73 ^ D77 +error(0.003449213835088781998) D49 D80 +error(0.002681972083768658158) D49 D80 ^ D53 +error(0.003567239636822126542) D49 D80 ^ D77 +error(0.0009720917822013221739) D49 D80 ^ D77 ^ D53 +error(0.007324292691020587581) D50 +error(0.01419500512629780567) D50 D51 +error(0.004023252490778637079) D50 D51 ^ D22 L0 +error(0.01819963975774338549) D50 D51 ^ D46 L0 +error(0.0003570751402298309404) D50 D51 ^ D54 L0 +error(0.0001756962670230916869) D50 D51 ^ D54 L0 ^ D22 L0 +error(0.01809902708512096253) D50 D74 +error(0.0007070126030203428879) D50 ^ D18 ^ D22 L0 +error(0.0006367420184909965315) D50 ^ D18 ^ D46 L0 +error(0.0009194744081342942502) D50 ^ D46 L0 ^ D22 L0 +error(0.0157666913660978944) D51 D52 +error(0.0008063908322377350349) D51 D52 ^ D54 D55 +error(0.003973470958629069134) D51 D52 ^ D54 D78 +error(0.01398924460029779895) D51 D57 +error(0.01203288461110336473) D51 D57 ^ D54 L0 +error(0.004973740584631117755) D51 D74 +error(0.003083695718806104061) D51 D74 ^ D46 L0 +error(6.326914210115742673e-05) D51 D74 ^ D78 L0 +error(0.000437796100933523862) D51 D74 ^ D78 L0 ^ D46 L0 +error(0.02802096798889971291) D51 D75 +error(0.0009781054333567957074) D51 D75 ^ D46 L0 +error(0.004258064841452545435) D51 D75 ^ D78 L0 +error(0.002293241519674286358) D51 D81 +error(0.002083689327902756277) D51 D81 ^ D54 L0 +error(0.003184439299356970048) D51 D81 ^ D78 L0 +error(0.0003075964336023181544) D51 D81 ^ D78 L0 ^ D54 L0 +error(0.008748819907022298975) D52 D53 +error(0.000421573423618385281) D52 D53 ^ D54 D55 +error(0.0004454116616421199392) D52 D53 ^ D55 D56 +error(0.002746525552341930968) D52 D53 ^ D55 D79 +error(0.01349995621294126057) D52 D58 +error(0.01074350301251948692) D52 D58 ^ D54 D55 +error(0.007372542091817689894) D52 D75 +error(0.0007550883971604156709) D52 D75 ^ D78 D79 +error(0.02903602395795713831) D52 D76 +error(0.002102104693332725906) D52 D76 ^ D78 D79 +error(0.003169378669323305153) D52 D81 +error(0.001191557425971731836) D52 D81 ^ D54 D78 +error(0.0001597772101005079804) D52 D81 ^ D54 D79 +error(0.0001021827979209038615) D52 D81 ^ D54 L0 +error(0.0005511678242116416215) D52 D81 ^ D78 D79 +error(1.679354630858518888e-05) D52 D81 ^ D78 L0 +error(0.001533444865295702621) D52 D82 +error(0.001663960370674462397) D52 D82 ^ D54 D55 +error(0.0007716218076495109674) D52 D82 ^ D54 D78 +error(0.001303219383453746829) D52 D82 ^ D54 D79 +error(0.000774858462820291762) D52 D82 ^ D55 D79 +error(0.00202762776909865992) D52 D82 ^ D78 D79 +error(0.01000000000000000021) D53 +error(0.004375250986392631436) D53 D76 +error(0.0001996290527887550252) D53 D76 ^ D79 D80 +error(0.02025078136410074503) D53 D77 +error(0.001389942840017453947) D53 D77 ^ D79 D80 +error(0.001697427904974847281) D53 D82 +error(9.531024276690012293e-05) D53 D82 ^ D54 D55 +error(0.0002003070882208187711) D53 D82 ^ D54 D79 +error(0.001002593182003129989) D53 D82 ^ D55 D79 +error(0.0008256000395826743879) D53 ^ D21 ^ D25 +error(0.001338317341795720308) D53 ^ D21 ^ D49 +error(0.0006122748497196598685) D53 ^ D25 +error(0.0063226352583203747) D54 D55 +error(0.000372850945034607572) D54 D55 ^ D57 D58 +error(0.002265174227511792399) D54 D55 ^ D58 D82 +error(0.0003610448547890982083) D54 D55 ^ D82 +error(0.03561013233827770019) D54 D78 +error(0.004322700216861186627) D54 D78 ^ D81 D82 +error(0.003938494697766241337) D54 D79 +error(0.0005358008309723712214) D54 D79 ^ D81 D82 +error(0.002034052694461135468) D54 D83 +error(0.0001466308340950007473) D54 D83 ^ D58 +error(0.001920194442056039194) D54 D83 ^ D58 D82 +error(0.01000000000000000021) D54 L0 +error(0.008841081898479867529) D55 D56 +error(0.002157536244326195389) D55 D56 ^ D29 +error(0.01163473797751780198) D55 D56 ^ D53 +error(0.0007537756625630134995) D55 D56 ^ D58 +error(0.01724304488913697489) D55 D59 +error(0.01634315707910385593) D55 D59 ^ D58 +error(0.01912154204876750918) D55 D79 +error(0.001896228017575547591) D55 D79 ^ D53 +error(0.003907155462371127326) D55 D79 ^ D82 +error(0.00279557314330079092) D55 D80 +error(0.002620934694098134548) D55 D80 ^ D53 +error(0.0004013694757154773717) D55 D80 ^ D82 +error(0.0001537267977297909955) D55 D80 ^ D82 ^ D53 +error(0.003820638366809637251) D55 D83 +error(0.003421241639577967189) D55 D83 ^ D58 +error(0.004007581078155113968) D55 D83 ^ D82 +error(0.001746012587198167822) D55 D83 ^ D82 ^ D58 +error(0.02606250389870726561) D56 D80 +error(0.002389270985273113726) D56 D80 ^ D53 +error(0.00654546687063310012) D57 D58 +error(0.0021024474767527058) D57 D58 ^ D30 L0 +error(0.01203764022217809065) D57 D58 ^ D54 L0 +error(0.0007246969784635964298) D57 D58 ^ D59 L0 +error(0.0005290423207049268833) D57 D58 ^ D59 L0 ^ D30 L0 +error(0.02738393697272551233) D57 D81 +error(0.004004257617406230957) D57 D81 ^ D54 L0 +error(0.01000000000000000021) D58 +error(0.002736244045764444407) D58 D81 +error(0.002855052799012060792) D58 D81 ^ D54 L0 +error(0.0006116163304378687384) D58 D81 ^ D83 L0 +error(0.0007069775710064596895) D58 D81 ^ D83 L0 ^ D54 L0 +error(0.02229227109480388241) D58 D82 +error(0.001481615400962180704) D58 D82 ^ D54 L0 +error(0.002922078673854252608) D58 D82 ^ D83 L0 +error(0.009906527088549655496) D58 ^ D59 L0 +error(0.0013622205925644421) D58 ^ D83 L0 +error(0.004149845774982054321) D59 D83 ^ D58 +error(0.01895412426906178255) D59 D83 +error(0.005000000000000000104) D59 L0 +error(0.005000000000000000104) D60 +error(0.01668747401411250705) D60 D64 +error(0.01827076257666529827) D60 D64 ^ D61 +error(0.02857365717892044674) D60 D84 +error(0.008187804202290056149) D60 D84 ^ D85 +error(0.006752054900691314455) D60 D88 +error(0.006349781933249819092) D60 D88 ^ D61 +error(0.004978707893828611571) D60 D88 ^ D85 +error(0.003764221099563926434) D60 D88 ^ D85 ^ D61 +error(0.00305811170313690121) D60 D89 +error(0.001355606463823049281) D60 D89 ^ D61 +error(0.002720072101049827822) D60 D89 ^ D61 D85 +error(0.0007162514653201519817) D60 D89 ^ D85 +error(0.005000000000000000104) D60 ^ D61 +error(0.006213397302591005048) D61 D85 ^ D60 +error(0.01000000000000000021) D61 +error(0.007614310746050743754) D61 D62 +error(0.0005954277109348562764) D61 D62 ^ D60 +error(0.000465636753644584143) D61 D62 ^ D64 D65 +error(0.0002796968619654203862) D61 D62 ^ D64 D89 +error(0.01582554105481599749) D61 D62 ^ D65 +error(0.005002346730345576947) D61 D62 ^ D65 D89 +error(0.002901359869863939615) D61 D62 ^ D89 +error(0.0005821292772265862199) D61 D62 ^ D89 ^ D60 +error(0.02094673066392089764) D61 D67 +error(0.01260591433803377043) D61 D67 ^ D64 D65 +error(0.04837432224380126128) D61 D85 +error(0.003553059407795153887) D61 D85 ^ D88 D89 +error(0.004155872962511489473) D61 D85 ^ D89 +error(0.003535743537937868341) D61 D90 +error(0.002372881073082702946) D61 D90 ^ D64 D88 +error(3.088814442772618024e-05) D61 D90 ^ D64 D89 +error(0.0002677743536514186166) D61 D90 ^ D88 D89 +error(0.002766432488590481534) D61 D91 +error(0.002003001371357753489) D61 D91 ^ D64 D65 +error(0.0007617751072712451808) D61 D91 ^ D64 D88 +error(0.001724437185270334552) D61 D91 ^ D64 D89 +error(0.001091467339713199239) D61 D91 ^ D65 D89 +error(0.00195910551946494333) D61 D91 ^ D88 D89 +error(0.01704609170648706262) D62 D68 +error(0.01603323914711612952) D62 D68 ^ D65 +error(0.006444335023303983563) D62 D85 +error(0.0006733172831601593735) D62 D85 ^ D60 +error(0.005862290075143809613) D62 D85 ^ D89 +error(0.0008136568950686870862) D62 D85 ^ D89 ^ D60 +error(0.02804448788546923255) D62 D86 +error(0.01224644515584789178) D62 D86 ^ D89 +error(0.002167760793218917112) D62 D91 +error(0.0006482439155634309039) D62 D91 ^ D64 D65 +error(0.0006554643296627914477) D62 D91 ^ D64 D89 +error(0.0001808182923138514173) D62 D91 ^ D65 +error(0.002038558843002732067) D62 D91 ^ D65 D89 +error(0.0001340785921504384238) D62 D91 ^ D89 +error(0.003575688005574470616) D62 D92 +error(0.004475310371346201757) D62 D92 ^ D65 +error(0.00345098355018136219) D62 D92 ^ D89 +error(0.001693218948738322736) D62 D92 ^ D89 ^ D65 +error(0.009232193128085404779) D63 D64 +error(0.0002630814526406159313) D63 D64 ^ D61 +error(0.009686902281069798351) D63 D64 ^ D66 +error(0.0002516825390100136859) D63 D64 ^ D66 D67 +error(0.002350509443893264785) D63 D64 ^ D66 D90 +error(0.0001924701327169168889) D63 D64 ^ D67 D90 +error(0.001328444822298451792) D63 D64 ^ D90 +error(0.0004422428033818157967) D63 D64 ^ D90 ^ D61 +error(0.01553238535686285622) D63 D70 +error(0.01442107373804212) D63 D70 ^ D66 +error(0.02321446919291771452) D63 D87 +error(0.003758964575596710975) D63 D87 ^ D90 +error(0.001583423248511523895) D63 D88 +error(0.0004350561070420648989) D63 D88 ^ D61 +error(0.002418582978257866924) D63 D88 ^ D90 +error(0.0002796298770619333766) D63 D88 ^ D90 ^ D61 +error(0.002780585570467565895) D63 D94 +error(0.003659131334418356651) D63 D94 ^ D66 +error(0.002445659219989861598) D63 D94 ^ D90 +error(0.001480500595323643509) D63 D94 ^ D90 ^ D66 +error(0.002342039754099378614) D63 D95 +error(0.0003971852223546843471) D63 D95 ^ D66 D67 +error(0.001695357924281432841) D63 D95 ^ D66 D90 +error(0.000109853332386578866) D63 D95 ^ D67 D90 +error(4.517129173657599629e-05) D63 D95 ^ D90 +error(0.009370177167621668649) D64 D65 +error(0.0013749192686105837) D64 D65 ^ D37 +error(0.0004326376275655316982) D64 D65 ^ D66 D67 +error(0.001729297765277910352) D64 D65 ^ D67 D91 +error(0.0008369239912465332564) D64 D65 ^ D68 D91 +error(0.01725430315521830557) D64 D71 +error(0.009937067068622049831) D64 D71 ^ D66 D67 +error(0.02800496972801020182) D64 D88 +error(0.008857345427632928175) D64 D88 ^ D61 +error(0.001330748570182143991) D64 D88 ^ D90 +error(0.002708890916997034985) D64 D88 ^ D90 D91 +error(0.004269470014870236155) D64 D89 +error(9.74753423978128047e-05) D64 D89 ^ D90 D91 +error(0.003795022050357953376) D64 D95 +error(0.002450806810346344965) D64 D95 ^ D66 D67 +error(0.001182325052329548159) D64 D95 ^ D66 D90 +error(0.001394230569165803022) D64 D95 ^ D67 D90 +error(0.001347851322040039988) D64 D95 ^ D67 D91 +error(0.00173532620606171189) D64 D95 ^ D90 D91 +error(0.003116053244494311654) D64 D96 +error(7.316842974601893705e-05) D64 D96 ^ D67 D68 +error(0.00015381139946745172) D64 D96 ^ D67 D90 +error(0.0008071141978608846294) D64 D96 ^ D67 D91 +error(0.0001061468001811654107) D64 D96 ^ D68 D91 +error(0.0004214225008490263334) D64 D96 ^ D90 D91 +error(0.01000000000000000021) D65 +error(0.0270222666017383116) D65 D72 +error(0.02417905793237870235) D65 D72 ^ D67 D68 +error(0.03102491946459741065) D65 D89 +error(0.002140803014291666959) D65 D89 ^ D91 D92 +error(0.005011204418027772993) D65 D96 +error(0.002409795170171074013) D65 D96 ^ D67 D68 +error(0.0004867120612278240106) D65 D96 ^ D67 D91 +error(0.001734557560692578373) D65 D96 ^ D68 D91 +error(0.0008310577286774427754) D65 D96 ^ D68 D92 +error(0.002876015875940871915) D65 D96 ^ D91 D92 +error(5.689899368434303708e-05) D65 D97 +error(0.0005376255601673666108) D65 D97 ^ D68 D91 +error(0.001860052998044929096) D65 D97 ^ D68 D92 +error(0.0003270350619594853282) D65 D97 ^ D91 D92 +error(0.01000000000000000021) D66 +error(0.00998951012393598653) D66 D67 +error(0.0002647118028759689896) D66 D67 ^ D70 D71 +error(0.0002437602896713224755) D66 D67 ^ D70 D95 +error(0.0003259292904997979664) D66 D67 ^ D71 D72 +error(0.002910193005919642101) D66 D67 ^ D71 D95 +error(0.01563311530723593412) D66 D75 +error(0.01148884923131972789) D66 D75 ^ D70 D71 +error(0.03402876169483597113) D66 D90 +error(0.00297341913608773151) D66 D90 ^ D94 D95 +error(0.00167198142382841866) D66 D98 +error(0.001978739641503692373) D66 D98 ^ D70 D94 +error(0.0003739016887504405208) D66 D98 ^ D70 D95 +error(0.0006191581992012207009) D66 D98 ^ D94 D95 +error(0.003564405145362673812) D66 D99 +error(0.002427865772048852337) D66 D99 ^ D70 D71 +error(0.002016980215619930579) D66 D99 ^ D70 D94 +error(0.001665163685732147384) D66 D99 ^ D70 D95 +error(0.001089534673102127496) D66 D99 ^ D71 D95 +error(0.002441047980058794978) D66 D99 ^ D94 D95 +error(0.0004010735829825645671) D66 ^ D94 L0 +error(0.0040421911780430652) D70 D94 ^ D66 +error(0.01013563020920371822) D67 D68 +error(0.0008314930570387067546) D67 D68 ^ D65 +error(0.0001530404613110457714) D67 D68 ^ D71 D72 +error(0.000607895799866905789) D67 D68 ^ D71 D96 +error(3.403628659066277234e-05) D67 D68 ^ D72 D73 +error(0.0025882004664708534) D67 D68 ^ D72 D96 +error(0.01727203508574649132) D67 D76 +error(0.0145277865377167175) D67 D76 ^ D71 D72 +error(0.004930101446126109246) D67 D90 +error(0.0002881881964098772803) D67 D90 ^ D95 D96 +error(0.04574271143269240114) D67 D91 +error(0.001860329697148833646) D67 D91 ^ D95 D96 +error(0.00255198772447796712) D67 D99 +error(0.0005047023561676590529) D67 D99 ^ D70 D71 +error(0.001452256159036316528) D67 D99 ^ D71 D95 +error(5.222076102721136015e-05) D67 D99 ^ D71 D96 +error(0.0009987913400580498199) D67 D99 ^ D95 D96 +error(0.001430194805650022039) D67 D100 +error(0.002007285104460634732) D67 D100 ^ D71 D72 +error(0.001224248109508729171) D67 D100 ^ D71 D95 +error(0.002303664480707598265) D67 D100 ^ D71 D96 +error(0.0009171454591137486075) D67 D100 ^ D72 D96 +error(0.002191714195832245807) D67 D100 ^ D95 D96 +error(0.009797724443923057011) D68 D69 +error(0.0001021472594512653998) D68 D69 ^ D72 D73 +error(0.0001210959338265430346) D68 D69 ^ D72 D97 +error(0.01190918523369760215) D68 D69 ^ D73 +error(0.005273755897734558329) D68 D69 ^ D73 D97 +error(0.00184597880693155897) D68 D69 ^ D97 +error(0.01377684914337177352) D68 D77 +error(0.01093440003708149623) D68 D77 ^ D72 D73 +error(0.003249664646197158047) D68 D91 +error(2.258206681107317873e-05) D68 D91 ^ D96 D97 +error(0.02265899218759278091) D68 D92 +error(0.004590199147543793691) D68 D92 ^ D65 +error(0.002645517561442980222) D68 D92 ^ D96 D97 +error(0.0005399062537493103456) D68 D92 ^ D97 +error(0.002277233782169691897) D68 D100 +error(0.0002528250109153119818) D68 D100 ^ D71 D72 +error(0.0006205257979712591916) D68 D100 ^ D71 D96 +error(0.001404758555723596139) D68 D100 ^ D72 D96 +error(0.0002405291802527288812) D68 D100 ^ D72 D97 +error(0.0003097319487677911579) D68 D100 ^ D96 D97 +error(0.001047705250796779949) D68 D101 +error(0.00237092510280944831) D68 D101 ^ D72 D73 +error(0.001037220928621594273) D68 D101 ^ D72 D96 +error(0.00238058383085898136) D68 D101 ^ D72 D97 +error(0.0008835768967079051526) D68 D101 ^ D73 D97 +error(0.002259774772269825763) D68 D101 ^ D96 D97 +error(0.01260811278973474753) D69 +error(0.00225151851890723325) D69 D92 +error(0.0001797993500064738813) D69 D92 ^ D65 +error(0.002356030447914673944) D69 D92 ^ D97 +error(0.0345566698397392208) D69 D93 +error(0.005003744614217759193) D69 D93 ^ D97 +error(0.001837583674123140394) D69 D101 +error(9.255458431562874132e-05) D69 D101 ^ D72 D73 +error(0.0002126721966588340058) D69 D101 ^ D72 D97 +error(0.002035990511446809058) D69 D101 ^ D73 D97 +error(0.02090970420602020902) D69 ^ D73 +error(0.0009042125990949610812) D69 ^ D97 +error(0.001560696983551172019) D69 ^ D97 ^ D73 +error(0.01374568531695860747) D70 D71 +error(0.0002954516562893196702) D70 D71 ^ D74 D75 +error(0.00158847535642978651) D70 D71 ^ D75 D99 +error(0.04904868400430456576) D70 D94 +error(0.003544968265632814693) D70 D94 ^ D98 D99 +error(0.003865628745054386969) D70 D95 +error(0.000441796954324594226) D70 D95 ^ D98 D99 +error(0.0009740040964997024285) D70 D102 +error(0.00188554410197714988) D70 D102 ^ D75 D99 +error(0.01000000000000000021) D70 L0 +error(0.01186879937024130915) D70 L0 ^ D74 +error(0.003675582362634155064) D74 D98 ^ D70 L0 +error(0.01735160188785484295) D71 D72 +error(0.0007088289629090005787) D71 D72 ^ D75 D76 +error(0.0005313038609727570695) D71 D72 ^ D76 D77 +error(0.002702669103548420697) D71 D72 ^ D76 D100 +error(0.0006166556002974491434) D71 D72 ^ D77 D100 +error(0.0207233958407102431) D71 D78 +error(0.02026670657223518177) D71 D78 ^ D75 D76 +error(0.02961831943462597469) D71 D95 +error(0.002972165594026740694) D71 D95 ^ D99 D100 +error(0.00414184937373599394) D71 D96 +error(0.00040167431689305317) D71 D96 ^ D99 D100 +error(0.005690305629853309802) D71 D102 +error(0.006400338574826603191) D71 D102 ^ D75 D76 +error(0.002210171177652492467) D71 D102 ^ D75 D99 +error(0.007612181774541293064) D71 D102 ^ D76 D99 +error(0.001786447785683612389) D71 D102 ^ D76 D100 +error(0.004060767403088009868) D71 D102 ^ D99 D100 +error(0.001749884553720177727) D71 D103 +error(0.0007133736782402601805) D71 D103 ^ D76 D77 +error(0.0005844947904700150375) D71 D103 ^ D76 D99 +error(0.0008217823092129306105) D71 D103 ^ D76 D100 +error(0.0003275095103629303275) D71 D103 ^ D77 D100 +error(0.0006123041623268492663) D71 D103 ^ D99 D100 +error(0.006835861022765376757) D72 D73 +error(0.0002649652178908865757) D72 D73 ^ D76 D77 +error(0.001842590021007301871) D72 D73 ^ D77 D101 +error(0.01360447555925056555) D72 D79 +error(0.01129163812096881624) D72 D79 ^ D76 D77 +error(0.02106229162894282872) D72 D96 +error(0.002751152448060949218) D72 D96 ^ D100 D101 +error(0.003538841843038994985) D72 D97 +error(0.0008757110100126239138) D72 D103 +error(0.002941122394742301787) D72 D103 ^ D76 D77 +error(0.001165932778592970644) D72 D103 ^ D76 D100 +error(0.003280475747202545207) D72 D103 ^ D77 D100 +error(0.001642146425221697624) D72 D103 ^ D77 D101 +error(0.002816897898481184048) D72 D103 ^ D100 D101 +error(0.0006886146142845198884) D72 D104 +error(0.0001236420909161301809) D72 D104 ^ D77 +error(0.000685689790586139266) D72 D104 ^ D77 D100 +error(0.001457910846507099421) D72 D104 ^ D77 D101 +error(0.0002590162334421474365) D72 D104 ^ D100 D101 +error(5.747153257964691372e-05) D72 D104 ^ D101 +error(0.01247992211153514663) D73 +error(0.01569289063977472726) D73 D80 +error(0.01852761195375728781) D73 D80 ^ D77 +error(0.02174588721229521807) D73 D97 +error(0.00218188050196639876) D73 D97 ^ D101 +error(0.003449213835088781998) D73 D104 +error(0.002681972083768658158) D73 D104 ^ D77 +error(0.003567239636822126542) D73 D104 ^ D101 +error(0.0009720917822013221739) D73 D104 ^ D101 ^ D77 +error(0.007324292691020587581) D74 +error(0.01419500512629780567) D74 D75 +error(0.004023252490778637079) D74 D75 ^ D46 L0 +error(0.01819963975774338549) D74 D75 ^ D70 L0 +error(0.0003570751402298309404) D74 D75 ^ D78 L0 +error(0.0001756962670230916869) D74 D75 ^ D78 L0 ^ D46 L0 +error(0.01809902708512096253) D74 D98 +error(0.0007070126030203428879) D74 ^ D42 ^ D46 L0 +error(0.0006367420184909965315) D74 ^ D42 ^ D70 L0 +error(0.0009194744081342942502) D74 ^ D70 L0 ^ D46 L0 +error(0.0157666913660978944) D75 D76 +error(0.0008063908322377350349) D75 D76 ^ D78 D79 +error(0.003973470958629069134) D75 D76 ^ D78 D102 +error(0.01398924460029779895) D75 D81 +error(0.01203288461110336473) D75 D81 ^ D78 L0 +error(0.004973740584631117755) D75 D98 +error(0.003083695718806104061) D75 D98 ^ D70 L0 +error(6.326914210115742673e-05) D75 D98 ^ D102 L0 +error(0.000437796100933523862) D75 D98 ^ D102 L0 ^ D70 L0 +error(0.02802096798889971291) D75 D99 +error(0.0009781054333567957074) D75 D99 ^ D70 L0 +error(0.004258064841452545435) D75 D99 ^ D102 L0 +error(0.002293241519674286358) D75 D105 +error(0.002083689327902756277) D75 D105 ^ D78 L0 +error(0.003184439299356970048) D75 D105 ^ D102 L0 +error(0.0003075964336023181544) D75 D105 ^ D102 L0 ^ D78 L0 +error(0.008748819907022298975) D76 D77 +error(0.000421573423618385281) D76 D77 ^ D78 D79 +error(0.0004454116616421199392) D76 D77 ^ D79 D80 +error(0.002746525552341930968) D76 D77 ^ D79 D103 +error(0.01349995621294126057) D76 D82 +error(0.01074350301251948692) D76 D82 ^ D78 D79 +error(0.007372542091817689894) D76 D99 +error(0.0007550883971604156709) D76 D99 ^ D102 D103 +error(0.02903602395795713831) D76 D100 +error(0.002102104693332725906) D76 D100 ^ D102 D103 +error(0.003169378669323305153) D76 D105 +error(0.001191557425971731836) D76 D105 ^ D78 D102 +error(0.0001597772101005079804) D76 D105 ^ D78 D103 +error(0.0001021827979209038615) D76 D105 ^ D78 L0 +error(0.0005511678242116416215) D76 D105 ^ D102 D103 +error(1.679354630858518888e-05) D76 D105 ^ D102 L0 +error(0.001533444865295702621) D76 D106 +error(0.001663960370674462397) D76 D106 ^ D78 D79 +error(0.0007716218076495109674) D76 D106 ^ D78 D102 +error(0.001303219383453746829) D76 D106 ^ D78 D103 +error(0.000774858462820291762) D76 D106 ^ D79 D103 +error(0.00202762776909865992) D76 D106 ^ D102 D103 +error(0.01000000000000000021) D77 +error(0.004375250986392631436) D77 D100 +error(0.0001996290527887550252) D77 D100 ^ D103 D104 +error(0.02025078136410074503) D77 D101 +error(0.001389942840017453947) D77 D101 ^ D103 D104 +error(0.001697427904974847281) D77 D106 +error(9.531024276690012293e-05) D77 D106 ^ D78 D79 +error(0.0002003070882208187711) D77 D106 ^ D78 D103 +error(0.001002593182003129989) D77 D106 ^ D79 D103 +error(0.0008256000395826743879) D77 ^ D45 ^ D49 +error(0.001338317341795720308) D77 ^ D45 ^ D73 +error(0.0006122748497196598685) D77 ^ D49 +error(0.0063226352583203747) D78 D79 +error(0.000372850945034607572) D78 D79 ^ D81 D82 +error(0.002265174227511792399) D78 D79 ^ D82 D106 +error(0.0003610448547890982083) D78 D79 ^ D106 +error(0.03561013233827770019) D78 D102 +error(0.004322700216861186627) D78 D102 ^ D105 D106 +error(0.003938494697766241337) D78 D103 +error(0.0005358008309723712214) D78 D103 ^ D105 D106 +error(0.002034052694461135468) D78 D107 +error(0.0001466308340950007473) D78 D107 ^ D82 +error(0.001920194442056039194) D78 D107 ^ D82 D106 +error(0.01000000000000000021) D78 L0 +error(0.008841081898479867529) D79 D80 +error(0.002157536244326195389) D79 D80 ^ D53 +error(0.01163473797751780198) D79 D80 ^ D77 +error(0.0007537756625630134995) D79 D80 ^ D82 +error(0.01724304488913697489) D79 D83 +error(0.01634315707910385593) D79 D83 ^ D82 +error(0.01912154204876750918) D79 D103 +error(0.001896228017575547591) D79 D103 ^ D77 +error(0.003907155462371127326) D79 D103 ^ D106 +error(0.00279557314330079092) D79 D104 +error(0.002620934694098134548) D79 D104 ^ D77 +error(0.0004013694757154773717) D79 D104 ^ D106 +error(0.0001537267977297909955) D79 D104 ^ D106 ^ D77 +error(0.003820638366809637251) D79 D107 +error(0.003421241639577967189) D79 D107 ^ D82 +error(0.004007581078155113968) D79 D107 ^ D106 +error(0.001746012587198167822) D79 D107 ^ D106 ^ D82 +error(0.02606250389870726561) D80 D104 +error(0.002389270985273113726) D80 D104 ^ D77 +error(0.00654546687063310012) D81 D82 +error(0.0021024474767527058) D81 D82 ^ D54 L0 +error(0.01203764022217809065) D81 D82 ^ D78 L0 +error(0.0007246969784635964298) D81 D82 ^ D83 L0 +error(0.0005290423207049268833) D81 D82 ^ D83 L0 ^ D54 L0 +error(0.02738393697272551233) D81 D105 +error(0.004004257617406230957) D81 D105 ^ D78 L0 +error(0.01000000000000000021) D82 +error(0.002736244045764444407) D82 D105 +error(0.002855052799012060792) D82 D105 ^ D78 L0 +error(0.0006116163304378687384) D82 D105 ^ D107 L0 +error(0.0007069775710064596895) D82 D105 ^ D107 L0 ^ D78 L0 +error(0.02229227109480388241) D82 D106 +error(0.001481615400962180704) D82 D106 ^ D78 L0 +error(0.002922078673854252608) D82 D106 ^ D107 L0 +error(0.009906527088549655496) D82 ^ D83 L0 +error(0.0013622205925644421) D82 ^ D107 L0 +error(0.004149845774982054321) D83 D107 ^ D82 +error(0.01895412426906178255) D83 D107 +error(0.005000000000000000104) D83 L0 +error(0.005000000000000000104) D84 +error(0.01668747401411250705) D84 D88 +error(0.01827076257666529827) D84 D88 ^ D85 +error(0.02857365717892044674) D84 D108 +error(0.008187804202290056149) D84 D108 ^ D109 +error(0.006752054900691314455) D84 D112 +error(0.006349781933249819092) D84 D112 ^ D85 +error(0.004978707893828611571) D84 D112 ^ D109 +error(0.003764221099563926434) D84 D112 ^ D109 ^ D85 +error(0.00305811170313690121) D84 D113 +error(0.001355606463823049281) D84 D113 ^ D85 +error(0.002720072101049827822) D84 D113 ^ D85 D109 +error(0.0007162514653201519817) D84 D113 ^ D109 +error(0.005000000000000000104) D84 ^ D85 +error(0.006213397302591005048) D85 D109 ^ D84 +error(0.01000000000000000021) D85 +error(0.007614310746050743754) D85 D86 +error(0.0005954277109348562764) D85 D86 ^ D84 +error(0.000465636753644584143) D85 D86 ^ D88 D89 +error(0.0002796968619654203862) D85 D86 ^ D88 D113 +error(0.01582554105481599749) D85 D86 ^ D89 +error(0.005002346730345576947) D85 D86 ^ D89 D113 +error(0.002901359869863939615) D85 D86 ^ D113 +error(0.0005821292772265862199) D85 D86 ^ D113 ^ D84 +error(0.02094673066392089764) D85 D91 +error(0.01260591433803377043) D85 D91 ^ D88 D89 +error(0.04837432224380126128) D85 D109 +error(0.003553059407795153887) D85 D109 ^ D112 D113 +error(0.004155872962511489473) D85 D109 ^ D113 +error(0.003535743537937868341) D85 D114 +error(0.002372881073082702946) D85 D114 ^ D88 D112 +error(3.088814442772618024e-05) D85 D114 ^ D88 D113 +error(0.0002677743536514186166) D85 D114 ^ D112 D113 +error(0.002766432488590481534) D85 D115 +error(0.002003001371357753489) D85 D115 ^ D88 D89 +error(0.0007617751072712451808) D85 D115 ^ D88 D112 +error(0.001724437185270334552) D85 D115 ^ D88 D113 +error(0.001091467339713199239) D85 D115 ^ D89 D113 +error(0.00195910551946494333) D85 D115 ^ D112 D113 +error(0.01704609170648706262) D86 D92 +error(0.01603323914711612952) D86 D92 ^ D89 +error(0.006444335023303983563) D86 D109 +error(0.0006733172831601593735) D86 D109 ^ D84 +error(0.005862290075143809613) D86 D109 ^ D113 +error(0.0008136568950686870862) D86 D109 ^ D113 ^ D84 +error(0.02804448788546923255) D86 D110 +error(0.01224644515584789178) D86 D110 ^ D113 +error(0.002167760793218917112) D86 D115 +error(0.0006482439155634309039) D86 D115 ^ D88 D89 +error(0.0006554643296627914477) D86 D115 ^ D88 D113 +error(0.0001808182923138514173) D86 D115 ^ D89 +error(0.002038558843002732067) D86 D115 ^ D89 D113 +error(0.0001340785921504384238) D86 D115 ^ D113 +error(0.003575688005574470616) D86 D116 +error(0.004475310371346201757) D86 D116 ^ D89 +error(0.00345098355018136219) D86 D116 ^ D113 +error(0.001693218948738322736) D86 D116 ^ D113 ^ D89 +error(0.009232193128085404779) D87 D88 +error(0.0002630814526406159313) D87 D88 ^ D85 +error(0.009686902281069798351) D87 D88 ^ D90 +error(0.0002516825390100136859) D87 D88 ^ D90 D91 +error(0.002350509443893264785) D87 D88 ^ D90 D114 +error(0.0001924701327169168889) D87 D88 ^ D91 D114 +error(0.001328444822298451792) D87 D88 ^ D114 +error(0.0004422428033818157967) D87 D88 ^ D114 ^ D85 +error(0.01553238535686285622) D87 D94 +error(0.01442107373804212) D87 D94 ^ D90 +error(0.02321446919291771452) D87 D111 +error(0.003758964575596710975) D87 D111 ^ D114 +error(0.001583423248511523895) D87 D112 +error(0.0004350561070420648989) D87 D112 ^ D85 +error(0.002418582978257866924) D87 D112 ^ D114 +error(0.0002796298770619333766) D87 D112 ^ D114 ^ D85 +error(0.002780585570467565895) D87 D118 +error(0.003659131334418356651) D87 D118 ^ D90 +error(0.002445659219989861598) D87 D118 ^ D114 +error(0.001480500595323643509) D87 D118 ^ D114 ^ D90 +error(0.002342039754099378614) D87 D119 +error(0.0003971852223546843471) D87 D119 ^ D90 D91 +error(0.001695357924281432841) D87 D119 ^ D90 D114 +error(0.000109853332386578866) D87 D119 ^ D91 D114 +error(4.517129173657599629e-05) D87 D119 ^ D114 +error(0.009370177167621668649) D88 D89 +error(0.0013749192686105837) D88 D89 ^ D61 +error(0.0004326376275655316982) D88 D89 ^ D90 D91 +error(0.001729297765277910352) D88 D89 ^ D91 D115 +error(0.0008369239912465332564) D88 D89 ^ D92 D115 +error(0.01725430315521830557) D88 D95 +error(0.009937067068622049831) D88 D95 ^ D90 D91 +error(0.02800496972801020182) D88 D112 +error(0.008857345427632928175) D88 D112 ^ D85 +error(0.001330748570182143991) D88 D112 ^ D114 +error(0.002708890916997034985) D88 D112 ^ D114 D115 +error(0.004269470014870236155) D88 D113 +error(9.74753423978128047e-05) D88 D113 ^ D114 D115 +error(0.003795022050357953376) D88 D119 +error(0.002450806810346344965) D88 D119 ^ D90 D91 +error(0.001182325052329548159) D88 D119 ^ D90 D114 +error(0.001394230569165803022) D88 D119 ^ D91 D114 +error(0.001347851322040039988) D88 D119 ^ D91 D115 +error(0.00173532620606171189) D88 D119 ^ D114 D115 +error(0.003116053244494311654) D88 D120 +error(7.316842974601893705e-05) D88 D120 ^ D91 D92 +error(0.00015381139946745172) D88 D120 ^ D91 D114 +error(0.0008071141978608846294) D88 D120 ^ D91 D115 +error(0.0001061468001811654107) D88 D120 ^ D92 D115 +error(0.0004214225008490263334) D88 D120 ^ D114 D115 +error(0.01000000000000000021) D89 +error(0.0270222666017383116) D89 D96 +error(0.02417905793237870235) D89 D96 ^ D91 D92 +error(0.03102491946459741065) D89 D113 +error(0.002140803014291666959) D89 D113 ^ D115 D116 +error(0.005011204418027772993) D89 D120 +error(0.002409795170171074013) D89 D120 ^ D91 D92 +error(0.0004867120612278240106) D89 D120 ^ D91 D115 +error(0.001734557560692578373) D89 D120 ^ D92 D115 +error(0.0008310577286774427754) D89 D120 ^ D92 D116 +error(0.002876015875940871915) D89 D120 ^ D115 D116 +error(5.689899368434303708e-05) D89 D121 +error(0.0005376255601673666108) D89 D121 ^ D92 D115 +error(0.001860052998044929096) D89 D121 ^ D92 D116 +error(0.0003270350619594853282) D89 D121 ^ D115 D116 +error(0.01000000000000000021) D90 +error(0.00998951012393598653) D90 D91 +error(0.0002647118028759689896) D90 D91 ^ D94 D95 +error(0.0002437602896713224755) D90 D91 ^ D94 D119 +error(0.0003259292904997979664) D90 D91 ^ D95 D96 +error(0.002910193005919642101) D90 D91 ^ D95 D119 +error(0.01563311530723593412) D90 D99 +error(0.01148884923131972789) D90 D99 ^ D94 D95 +error(0.03402876169483597113) D90 D114 +error(0.00297341913608773151) D90 D114 ^ D118 D119 +error(0.00167198142382841866) D90 D122 +error(0.001978739641503692373) D90 D122 ^ D94 D118 +error(0.0003739016887504405208) D90 D122 ^ D94 D119 +error(0.0006191581992012207009) D90 D122 ^ D118 D119 +error(0.003564405145362673812) D90 D123 +error(0.002427865772048852337) D90 D123 ^ D94 D95 +error(0.002016980215619930579) D90 D123 ^ D94 D118 +error(0.001665163685732147384) D90 D123 ^ D94 D119 +error(0.001089534673102127496) D90 D123 ^ D95 D119 +error(0.002441047980058794978) D90 D123 ^ D118 D119 +error(0.0004010735829825645671) D90 ^ D118 L0 +error(0.0040421911780430652) D94 D118 ^ D90 +error(0.01013563020920371822) D91 D92 +error(0.0008314930570387067546) D91 D92 ^ D89 +error(0.0001530404613110457714) D91 D92 ^ D95 D96 +error(0.000607895799866905789) D91 D92 ^ D95 D120 +error(3.403628659066277234e-05) D91 D92 ^ D96 D97 +error(0.0025882004664708534) D91 D92 ^ D96 D120 +error(0.01727203508574649132) D91 D100 +error(0.0145277865377167175) D91 D100 ^ D95 D96 +error(0.004930101446126109246) D91 D114 +error(0.0002881881964098772803) D91 D114 ^ D119 D120 +error(0.04574271143269240114) D91 D115 +error(0.001860329697148833646) D91 D115 ^ D119 D120 +error(0.00255198772447796712) D91 D123 +error(0.0005047023561676590529) D91 D123 ^ D94 D95 +error(0.001452256159036316528) D91 D123 ^ D95 D119 +error(5.222076102721136015e-05) D91 D123 ^ D95 D120 +error(0.0009987913400580498199) D91 D123 ^ D119 D120 +error(0.001430194805650022039) D91 D124 +error(0.002007285104460634732) D91 D124 ^ D95 D96 +error(0.001224248109508729171) D91 D124 ^ D95 D119 +error(0.002303664480707598265) D91 D124 ^ D95 D120 +error(0.0009171454591137486075) D91 D124 ^ D96 D120 +error(0.002191714195832245807) D91 D124 ^ D119 D120 +error(0.009797724443923057011) D92 D93 +error(0.0001021472594512653998) D92 D93 ^ D96 D97 +error(0.0001210959338265430346) D92 D93 ^ D96 D121 +error(0.01190918523369760215) D92 D93 ^ D97 +error(0.005273755897734558329) D92 D93 ^ D97 D121 +error(0.00184597880693155897) D92 D93 ^ D121 +error(0.01377684914337177352) D92 D101 +error(0.01093440003708149623) D92 D101 ^ D96 D97 +error(0.003249664646197158047) D92 D115 +error(2.258206681107317873e-05) D92 D115 ^ D120 D121 +error(0.02265899218759278091) D92 D116 +error(0.004590199147543793691) D92 D116 ^ D89 +error(0.002645517561442980222) D92 D116 ^ D120 D121 +error(0.0005399062537493103456) D92 D116 ^ D121 +error(0.002277233782169691897) D92 D124 +error(0.0002528250109153119818) D92 D124 ^ D95 D96 +error(0.0006205257979712591916) D92 D124 ^ D95 D120 +error(0.001404758555723596139) D92 D124 ^ D96 D120 +error(0.0002405291802527288812) D92 D124 ^ D96 D121 +error(0.0003097319487677911579) D92 D124 ^ D120 D121 +error(0.001047705250796779949) D92 D125 +error(0.00237092510280944831) D92 D125 ^ D96 D97 +error(0.001037220928621594273) D92 D125 ^ D96 D120 +error(0.00238058383085898136) D92 D125 ^ D96 D121 +error(0.0008835768967079051526) D92 D125 ^ D97 D121 +error(0.002259774772269825763) D92 D125 ^ D120 D121 +error(0.01260811278973474753) D93 +error(0.00225151851890723325) D93 D116 +error(0.0001797993500064738813) D93 D116 ^ D89 +error(0.002356030447914673944) D93 D116 ^ D121 +error(0.0345566698397392208) D93 D117 +error(0.005003744614217759193) D93 D117 ^ D121 +error(0.001837583674123140394) D93 D125 +error(9.255458431562874132e-05) D93 D125 ^ D96 D97 +error(0.0002126721966588340058) D93 D125 ^ D96 D121 +error(0.002035990511446809058) D93 D125 ^ D97 D121 +error(0.02090970420602020902) D93 ^ D97 +error(0.0009042125990949610812) D93 ^ D121 +error(0.001560696983551172019) D93 ^ D121 ^ D97 +error(0.01374568531695860747) D94 D95 +error(0.0002954516562893196702) D94 D95 ^ D98 D99 +error(0.00158847535642978651) D94 D95 ^ D99 D123 +error(0.04904868400430456576) D94 D118 +error(0.003544968265632814693) D94 D118 ^ D122 D123 +error(0.003865628745054386969) D94 D119 +error(0.000441796954324594226) D94 D119 ^ D122 D123 +error(0.0009740040964997024285) D94 D126 +error(0.00188554410197714988) D94 D126 ^ D99 D123 +error(0.01000000000000000021) D94 L0 +error(0.01186879937024130915) D94 L0 ^ D98 +error(0.003675582362634155064) D98 D122 ^ D94 L0 +error(0.01735160188785484295) D95 D96 +error(0.0007088289629090005787) D95 D96 ^ D99 D100 +error(0.0005313038609727570695) D95 D96 ^ D100 D101 +error(0.002702669103548420697) D95 D96 ^ D100 D124 +error(0.0006166556002974491434) D95 D96 ^ D101 D124 +error(0.0207233958407102431) D95 D102 +error(0.02026670657223518177) D95 D102 ^ D99 D100 +error(0.02961831943462597469) D95 D119 +error(0.002972165594026740694) D95 D119 ^ D123 D124 +error(0.00414184937373599394) D95 D120 +error(0.00040167431689305317) D95 D120 ^ D123 D124 +error(0.005690305629853309802) D95 D126 +error(0.006400338574826603191) D95 D126 ^ D99 D100 +error(0.002210171177652492467) D95 D126 ^ D99 D123 +error(0.007612181774541293064) D95 D126 ^ D100 D123 +error(0.001786447785683612389) D95 D126 ^ D100 D124 +error(0.004060767403088009868) D95 D126 ^ D123 D124 +error(0.001749884553720177727) D95 D127 +error(0.0007133736782402601805) D95 D127 ^ D100 D101 +error(0.0005844947904700150375) D95 D127 ^ D100 D123 +error(0.0008217823092129306105) D95 D127 ^ D100 D124 +error(0.0003275095103629303275) D95 D127 ^ D101 D124 +error(0.0006123041623268492663) D95 D127 ^ D123 D124 +error(0.006835861022765376757) D96 D97 +error(0.0002649652178908865757) D96 D97 ^ D100 D101 +error(0.001842590021007301871) D96 D97 ^ D101 D125 +error(0.01360447555925056555) D96 D103 +error(0.01129163812096881624) D96 D103 ^ D100 D101 +error(0.02106229162894282872) D96 D120 +error(0.002751152448060949218) D96 D120 ^ D124 D125 +error(0.003538841843038994985) D96 D121 +error(0.0008757110100126239138) D96 D127 +error(0.002941122394742301787) D96 D127 ^ D100 D101 +error(0.001165932778592970644) D96 D127 ^ D100 D124 +error(0.003280475747202545207) D96 D127 ^ D101 D124 +error(0.001642146425221697624) D96 D127 ^ D101 D125 +error(0.002816897898481184048) D96 D127 ^ D124 D125 +error(0.0006886146142845198884) D96 D128 +error(0.0001236420909161301809) D96 D128 ^ D101 +error(0.000685689790586139266) D96 D128 ^ D101 D124 +error(0.001457910846507099421) D96 D128 ^ D101 D125 +error(0.0002590162334421474365) D96 D128 ^ D124 D125 +error(5.747153257964691372e-05) D96 D128 ^ D125 +error(0.01247992211153514663) D97 +error(0.01569289063977472726) D97 D104 +error(0.01852761195375728781) D97 D104 ^ D101 +error(0.02174588721229521807) D97 D121 +error(0.00218188050196639876) D97 D121 ^ D125 +error(0.003449213835088781998) D97 D128 +error(0.002681972083768658158) D97 D128 ^ D101 +error(0.003567239636822126542) D97 D128 ^ D125 +error(0.0009720917822013221739) D97 D128 ^ D125 ^ D101 +error(0.007324292691020587581) D98 +error(0.01419500512629780567) D98 D99 +error(0.004023252490778637079) D98 D99 ^ D70 L0 +error(0.01819963975774338549) D98 D99 ^ D94 L0 +error(0.0003570751402298309404) D98 D99 ^ D102 L0 +error(0.0001756962670230916869) D98 D99 ^ D102 L0 ^ D70 L0 +error(0.01809902708512096253) D98 D122 +error(0.0007070126030203428879) D98 ^ D66 ^ D70 L0 +error(0.0006367420184909965315) D98 ^ D66 ^ D94 L0 +error(0.0009194744081342942502) D98 ^ D94 L0 ^ D70 L0 +error(0.0157666913660978944) D99 D100 +error(0.0008063908322377350349) D99 D100 ^ D102 D103 +error(0.003973470958629069134) D99 D100 ^ D102 D126 +error(0.01398924460029779895) D99 D105 +error(0.01203288461110336473) D99 D105 ^ D102 L0 +error(0.004973740584631117755) D99 D122 +error(0.003083695718806104061) D99 D122 ^ D94 L0 +error(6.326914210115742673e-05) D99 D122 ^ D126 L0 +error(0.000437796100933523862) D99 D122 ^ D126 L0 ^ D94 L0 +error(0.02802096798889971291) D99 D123 +error(0.0009781054333567957074) D99 D123 ^ D94 L0 +error(0.004258064841452545435) D99 D123 ^ D126 L0 +error(0.002293241519674286358) D99 D129 +error(0.002083689327902756277) D99 D129 ^ D102 L0 +error(0.003184439299356970048) D99 D129 ^ D126 L0 +error(0.0003075964336023181544) D99 D129 ^ D126 L0 ^ D102 L0 +error(0.008748819907022298975) D100 D101 +error(0.000421573423618385281) D100 D101 ^ D102 D103 +error(0.0004454116616421199392) D100 D101 ^ D103 D104 +error(0.002746525552341930968) D100 D101 ^ D103 D127 +error(0.01349995621294126057) D100 D106 +error(0.01074350301251948692) D100 D106 ^ D102 D103 +error(0.007372542091817689894) D100 D123 +error(0.0007550883971604156709) D100 D123 ^ D126 D127 +error(0.02903602395795713831) D100 D124 +error(0.002102104693332725906) D100 D124 ^ D126 D127 +error(0.003169378669323305153) D100 D129 +error(0.001191557425971731836) D100 D129 ^ D102 D126 +error(0.0001597772101005079804) D100 D129 ^ D102 D127 +error(0.0001021827979209038615) D100 D129 ^ D102 L0 +error(0.0005511678242116416215) D100 D129 ^ D126 D127 +error(1.679354630858518888e-05) D100 D129 ^ D126 L0 +error(0.001533444865295702621) D100 D130 +error(0.001663960370674462397) D100 D130 ^ D102 D103 +error(0.0007716218076495109674) D100 D130 ^ D102 D126 +error(0.001303219383453746829) D100 D130 ^ D102 D127 +error(0.000774858462820291762) D100 D130 ^ D103 D127 +error(0.00202762776909865992) D100 D130 ^ D126 D127 +error(0.01000000000000000021) D101 +error(0.004375250986392631436) D101 D124 +error(0.0001996290527887550252) D101 D124 ^ D127 D128 +error(0.02025078136410074503) D101 D125 +error(0.001389942840017453947) D101 D125 ^ D127 D128 +error(0.001697427904974847281) D101 D130 +error(9.531024276690012293e-05) D101 D130 ^ D102 D103 +error(0.0002003070882208187711) D101 D130 ^ D102 D127 +error(0.001002593182003129989) D101 D130 ^ D103 D127 +error(0.0008256000395826743879) D101 ^ D69 ^ D73 +error(0.001338317341795720308) D101 ^ D69 ^ D97 +error(0.0006122748497196598685) D101 ^ D73 +error(0.0063226352583203747) D102 D103 +error(0.000372850945034607572) D102 D103 ^ D105 D106 +error(0.002265174227511792399) D102 D103 ^ D106 D130 +error(0.0003610448547890982083) D102 D103 ^ D130 +error(0.03561013233827770019) D102 D126 +error(0.004322700216861186627) D102 D126 ^ D129 D130 +error(0.003938494697766241337) D102 D127 +error(0.0005358008309723712214) D102 D127 ^ D129 D130 +error(0.002034052694461135468) D102 D131 +error(0.0001466308340950007473) D102 D131 ^ D106 +error(0.001920194442056039194) D102 D131 ^ D106 D130 +error(0.01000000000000000021) D102 L0 +error(0.008841081898479867529) D103 D104 +error(0.002157536244326195389) D103 D104 ^ D77 +error(0.01163473797751780198) D103 D104 ^ D101 +error(0.0007537756625630134995) D103 D104 ^ D106 +error(0.01724304488913697489) D103 D107 +error(0.01634315707910385593) D103 D107 ^ D106 +error(0.01912154204876750918) D103 D127 +error(0.001896228017575547591) D103 D127 ^ D101 +error(0.003907155462371127326) D103 D127 ^ D130 +error(0.00279557314330079092) D103 D128 +error(0.002620934694098134548) D103 D128 ^ D101 +error(0.0004013694757154773717) D103 D128 ^ D130 +error(0.0001537267977297909955) D103 D128 ^ D130 ^ D101 +error(0.003820638366809637251) D103 D131 +error(0.003421241639577967189) D103 D131 ^ D106 +error(0.004007581078155113968) D103 D131 ^ D130 +error(0.001746012587198167822) D103 D131 ^ D130 ^ D106 +error(0.02606250389870726561) D104 D128 +error(0.002389270985273113726) D104 D128 ^ D101 +error(0.00654546687063310012) D105 D106 +error(0.0021024474767527058) D105 D106 ^ D78 L0 +error(0.01203764022217809065) D105 D106 ^ D102 L0 +error(0.0007246969784635964298) D105 D106 ^ D107 L0 +error(0.0005290423207049268833) D105 D106 ^ D107 L0 ^ D78 L0 +error(0.02738393697272551233) D105 D129 +error(0.004004257617406230957) D105 D129 ^ D102 L0 +error(0.01000000000000000021) D106 +error(0.002736244045764444407) D106 D129 +error(0.002855052799012060792) D106 D129 ^ D102 L0 +error(0.0006116163304378687384) D106 D129 ^ D131 L0 +error(0.0007069775710064596895) D106 D129 ^ D131 L0 ^ D102 L0 +error(0.02229227109480388241) D106 D130 +error(0.001481615400962180704) D106 D130 ^ D102 L0 +error(0.002922078673854252608) D106 D130 ^ D131 L0 +error(0.009906527088549655496) D106 ^ D107 L0 +error(0.0013622205925644421) D106 ^ D131 L0 +error(0.004149845774982054321) D107 D131 ^ D106 +error(0.01895412426906178255) D107 D131 +error(0.005000000000000000104) D107 L0 +error(0.005000000000000000104) D108 +error(0.01668747401411250705) D108 D112 +error(0.01827076257666529827) D108 D112 ^ D109 +error(0.02857365717892044674) D108 D132 +error(0.008187804202290056149) D108 D132 ^ D133 +error(0.006752054900691314455) D108 D136 +error(0.006349781933249819092) D108 D136 ^ D109 +error(0.004978707893828611571) D108 D136 ^ D133 +error(0.003764221099563926434) D108 D136 ^ D133 ^ D109 +error(0.00305811170313690121) D108 D137 +error(0.001355606463823049281) D108 D137 ^ D109 +error(0.002720072101049827822) D108 D137 ^ D109 D133 +error(0.0007162514653201519817) D108 D137 ^ D133 +error(0.005000000000000000104) D108 ^ D109 +error(0.006213397302591005048) D109 D133 ^ D108 +error(0.01000000000000000021) D109 +error(0.007614310746050743754) D109 D110 +error(0.0005954277109348562764) D109 D110 ^ D108 +error(0.000465636753644584143) D109 D110 ^ D112 D113 +error(0.0002796968619654203862) D109 D110 ^ D112 D137 +error(0.01582554105481599749) D109 D110 ^ D113 +error(0.005002346730345576947) D109 D110 ^ D113 D137 +error(0.002901359869863939615) D109 D110 ^ D137 +error(0.0005821292772265862199) D109 D110 ^ D137 ^ D108 +error(0.02094673066392089764) D109 D115 +error(0.01260591433803377043) D109 D115 ^ D112 D113 +error(0.04837432224380126128) D109 D133 +error(0.003553059407795153887) D109 D133 ^ D136 D137 +error(0.004155872962511489473) D109 D133 ^ D137 +error(0.003535743537937868341) D109 D138 +error(0.002372881073082702946) D109 D138 ^ D112 D136 +error(3.088814442772618024e-05) D109 D138 ^ D112 D137 +error(0.0002677743536514186166) D109 D138 ^ D136 D137 +error(0.002766432488590481534) D109 D139 +error(0.002003001371357753489) D109 D139 ^ D112 D113 +error(0.0007617751072712451808) D109 D139 ^ D112 D136 +error(0.001724437185270334552) D109 D139 ^ D112 D137 +error(0.001091467339713199239) D109 D139 ^ D113 D137 +error(0.00195910551946494333) D109 D139 ^ D136 D137 +error(0.01704609170648706262) D110 D116 +error(0.01603323914711612952) D110 D116 ^ D113 +error(0.006444335023303983563) D110 D133 +error(0.0006733172831601593735) D110 D133 ^ D108 +error(0.005862290075143809613) D110 D133 ^ D137 +error(0.0008136568950686870862) D110 D133 ^ D137 ^ D108 +error(0.02804448788546923255) D110 D134 +error(0.01224644515584789178) D110 D134 ^ D137 +error(0.002167760793218917112) D110 D139 +error(0.0006482439155634309039) D110 D139 ^ D112 D113 +error(0.0006554643296627914477) D110 D139 ^ D112 D137 +error(0.0001808182923138514173) D110 D139 ^ D113 +error(0.002038558843002732067) D110 D139 ^ D113 D137 +error(0.0001340785921504384238) D110 D139 ^ D137 +error(0.003575688005574470616) D110 D140 +error(0.004475310371346201757) D110 D140 ^ D113 +error(0.00345098355018136219) D110 D140 ^ D137 +error(0.001693218948738322736) D110 D140 ^ D137 ^ D113 +error(0.009232193128085404779) D111 D112 +error(0.0002630814526406159313) D111 D112 ^ D109 +error(0.009686902281069798351) D111 D112 ^ D114 +error(0.0002516825390100136859) D111 D112 ^ D114 D115 +error(0.002350509443893264785) D111 D112 ^ D114 D138 +error(0.0001924701327169168889) D111 D112 ^ D115 D138 +error(0.001328444822298451792) D111 D112 ^ D138 +error(0.0004422428033818157967) D111 D112 ^ D138 ^ D109 +error(0.01553238535686285622) D111 D118 +error(0.01442107373804212) D111 D118 ^ D114 +error(0.02321446919291771452) D111 D135 +error(0.003758964575596710975) D111 D135 ^ D138 +error(0.001583423248511523895) D111 D136 +error(0.0004350561070420648989) D111 D136 ^ D109 +error(0.002418582978257866924) D111 D136 ^ D138 +error(0.0002796298770619333766) D111 D136 ^ D138 ^ D109 +error(0.002780585570467565895) D111 D142 +error(0.003659131334418356651) D111 D142 ^ D114 +error(0.002445659219989861598) D111 D142 ^ D138 +error(0.001480500595323643509) D111 D142 ^ D138 ^ D114 +error(0.002342039754099378614) D111 D143 +error(0.0003971852223546843471) D111 D143 ^ D114 D115 +error(0.001695357924281432841) D111 D143 ^ D114 D138 +error(0.000109853332386578866) D111 D143 ^ D115 D138 +error(4.517129173657599629e-05) D111 D143 ^ D138 +error(0.009370177167621668649) D112 D113 +error(0.0013749192686105837) D112 D113 ^ D85 +error(0.0004326376275655316982) D112 D113 ^ D114 D115 +error(0.001729297765277910352) D112 D113 ^ D115 D139 +error(0.0008369239912465332564) D112 D113 ^ D116 D139 +error(0.01725430315521830557) D112 D119 +error(0.009937067068622049831) D112 D119 ^ D114 D115 +error(0.02800496972801020182) D112 D136 +error(0.008857345427632928175) D112 D136 ^ D109 +error(0.001330748570182143991) D112 D136 ^ D138 +error(0.002708890916997034985) D112 D136 ^ D138 D139 +error(0.004269470014870236155) D112 D137 +error(9.74753423978128047e-05) D112 D137 ^ D138 D139 +error(0.003795022050357953376) D112 D143 +error(0.002450806810346344965) D112 D143 ^ D114 D115 +error(0.001182325052329548159) D112 D143 ^ D114 D138 +error(0.001394230569165803022) D112 D143 ^ D115 D138 +error(0.001347851322040039988) D112 D143 ^ D115 D139 +error(0.00173532620606171189) D112 D143 ^ D138 D139 +error(0.003116053244494311654) D112 D144 +error(7.316842974601893705e-05) D112 D144 ^ D115 D116 +error(0.00015381139946745172) D112 D144 ^ D115 D138 +error(0.0008071141978608846294) D112 D144 ^ D115 D139 +error(0.0001061468001811654107) D112 D144 ^ D116 D139 +error(0.0004214225008490263334) D112 D144 ^ D138 D139 +error(0.01000000000000000021) D113 +error(0.0270222666017383116) D113 D120 +error(0.02417905793237870235) D113 D120 ^ D115 D116 +error(0.03102491946459741065) D113 D137 +error(0.002140803014291666959) D113 D137 ^ D139 D140 +error(0.005011204418027772993) D113 D144 +error(0.002409795170171074013) D113 D144 ^ D115 D116 +error(0.0004867120612278240106) D113 D144 ^ D115 D139 +error(0.001734557560692578373) D113 D144 ^ D116 D139 +error(0.0008310577286774427754) D113 D144 ^ D116 D140 +error(0.002876015875940871915) D113 D144 ^ D139 D140 +error(5.689899368434303708e-05) D113 D145 +error(0.0005376255601673666108) D113 D145 ^ D116 D139 +error(0.001860052998044929096) D113 D145 ^ D116 D140 +error(0.0003270350619594853282) D113 D145 ^ D139 D140 +error(0.01000000000000000021) D114 +error(0.00998951012393598653) D114 D115 +error(0.0002647118028759689896) D114 D115 ^ D118 D119 +error(0.0002437602896713224755) D114 D115 ^ D118 D143 +error(0.0003259292904997979664) D114 D115 ^ D119 D120 +error(0.002910193005919642101) D114 D115 ^ D119 D143 +error(0.01563311530723593412) D114 D123 +error(0.01148884923131972789) D114 D123 ^ D118 D119 +error(0.03402876169483597113) D114 D138 +error(0.00297341913608773151) D114 D138 ^ D142 D143 +error(0.00167198142382841866) D114 D146 +error(0.001978739641503692373) D114 D146 ^ D118 D142 +error(0.0003739016887504405208) D114 D146 ^ D118 D143 +error(0.0006191581992012207009) D114 D146 ^ D142 D143 +error(0.003564405145362673812) D114 D147 +error(0.002427865772048852337) D114 D147 ^ D118 D119 +error(0.002016980215619930579) D114 D147 ^ D118 D142 +error(0.001665163685732147384) D114 D147 ^ D118 D143 +error(0.001089534673102127496) D114 D147 ^ D119 D143 +error(0.002441047980058794978) D114 D147 ^ D142 D143 +error(0.0004010735829825645671) D114 ^ D142 L0 +error(0.0040421911780430652) D118 D142 ^ D114 +error(0.01013563020920371822) D115 D116 +error(0.0008314930570387067546) D115 D116 ^ D113 +error(0.0001530404613110457714) D115 D116 ^ D119 D120 +error(0.000607895799866905789) D115 D116 ^ D119 D144 +error(3.403628659066277234e-05) D115 D116 ^ D120 D121 +error(0.0025882004664708534) D115 D116 ^ D120 D144 +error(0.01727203508574649132) D115 D124 +error(0.0145277865377167175) D115 D124 ^ D119 D120 +error(0.004930101446126109246) D115 D138 +error(0.0002881881964098772803) D115 D138 ^ D143 D144 +error(0.04574271143269240114) D115 D139 +error(0.001860329697148833646) D115 D139 ^ D143 D144 +error(0.00255198772447796712) D115 D147 +error(0.0005047023561676590529) D115 D147 ^ D118 D119 +error(0.001452256159036316528) D115 D147 ^ D119 D143 +error(5.222076102721136015e-05) D115 D147 ^ D119 D144 +error(0.0009987913400580498199) D115 D147 ^ D143 D144 +error(0.001430194805650022039) D115 D148 +error(0.002007285104460634732) D115 D148 ^ D119 D120 +error(0.001224248109508729171) D115 D148 ^ D119 D143 +error(0.002303664480707598265) D115 D148 ^ D119 D144 +error(0.0009171454591137486075) D115 D148 ^ D120 D144 +error(0.002191714195832245807) D115 D148 ^ D143 D144 +error(0.009797724443923057011) D116 D117 +error(0.0001021472594512653998) D116 D117 ^ D120 D121 +error(0.0001210959338265430346) D116 D117 ^ D120 D145 +error(0.01190918523369760215) D116 D117 ^ D121 +error(0.005273755897734558329) D116 D117 ^ D121 D145 +error(0.00184597880693155897) D116 D117 ^ D145 +error(0.01377684914337177352) D116 D125 +error(0.01093440003708149623) D116 D125 ^ D120 D121 +error(0.003249664646197158047) D116 D139 +error(2.258206681107317873e-05) D116 D139 ^ D144 D145 +error(0.02265899218759278091) D116 D140 +error(0.004590199147543793691) D116 D140 ^ D113 +error(0.002645517561442980222) D116 D140 ^ D144 D145 +error(0.0005399062537493103456) D116 D140 ^ D145 +error(0.002277233782169691897) D116 D148 +error(0.0002528250109153119818) D116 D148 ^ D119 D120 +error(0.0006205257979712591916) D116 D148 ^ D119 D144 +error(0.001404758555723596139) D116 D148 ^ D120 D144 +error(0.0002405291802527288812) D116 D148 ^ D120 D145 +error(0.0003097319487677911579) D116 D148 ^ D144 D145 +error(0.001047705250796779949) D116 D149 +error(0.00237092510280944831) D116 D149 ^ D120 D121 +error(0.001037220928621594273) D116 D149 ^ D120 D144 +error(0.00238058383085898136) D116 D149 ^ D120 D145 +error(0.0008835768967079051526) D116 D149 ^ D121 D145 +error(0.002259774772269825763) D116 D149 ^ D144 D145 +error(0.01260811278973474753) D117 +error(0.00225151851890723325) D117 D140 +error(0.0001797993500064738813) D117 D140 ^ D113 +error(0.002356030447914673944) D117 D140 ^ D145 +error(0.0345566698397392208) D117 D141 +error(0.005003744614217759193) D117 D141 ^ D145 +error(0.001837583674123140394) D117 D149 +error(9.255458431562874132e-05) D117 D149 ^ D120 D121 +error(0.0002126721966588340058) D117 D149 ^ D120 D145 +error(0.002035990511446809058) D117 D149 ^ D121 D145 +error(0.02090970420602020902) D117 ^ D121 +error(0.0009042125990949610812) D117 ^ D145 +error(0.001560696983551172019) D117 ^ D145 ^ D121 +error(0.01374568531695860747) D118 D119 +error(0.0002954516562893196702) D118 D119 ^ D122 D123 +error(0.00158847535642978651) D118 D119 ^ D123 D147 +error(0.04904868400430456576) D118 D142 +error(0.003544968265632814693) D118 D142 ^ D146 D147 +error(0.003865628745054386969) D118 D143 +error(0.000441796954324594226) D118 D143 ^ D146 D147 +error(0.0009740040964997024285) D118 D150 +error(0.00188554410197714988) D118 D150 ^ D123 D147 +error(0.01000000000000000021) D118 L0 +error(0.01186879937024130915) D118 L0 ^ D122 +error(0.003675582362634155064) D122 D146 ^ D118 L0 +error(0.01735160188785484295) D119 D120 +error(0.0007088289629090005787) D119 D120 ^ D123 D124 +error(0.0005313038609727570695) D119 D120 ^ D124 D125 +error(0.002702669103548420697) D119 D120 ^ D124 D148 +error(0.0006166556002974491434) D119 D120 ^ D125 D148 +error(0.0207233958407102431) D119 D126 +error(0.02026670657223518177) D119 D126 ^ D123 D124 +error(0.02961831943462597469) D119 D143 +error(0.002972165594026740694) D119 D143 ^ D147 D148 +error(0.00414184937373599394) D119 D144 +error(0.00040167431689305317) D119 D144 ^ D147 D148 +error(0.005690305629853309802) D119 D150 +error(0.006400338574826603191) D119 D150 ^ D123 D124 +error(0.002210171177652492467) D119 D150 ^ D123 D147 +error(0.007612181774541293064) D119 D150 ^ D124 D147 +error(0.001786447785683612389) D119 D150 ^ D124 D148 +error(0.004060767403088009868) D119 D150 ^ D147 D148 +error(0.001749884553720177727) D119 D151 +error(0.0007133736782402601805) D119 D151 ^ D124 D125 +error(0.0005844947904700150375) D119 D151 ^ D124 D147 +error(0.0008217823092129306105) D119 D151 ^ D124 D148 +error(0.0003275095103629303275) D119 D151 ^ D125 D148 +error(0.0006123041623268492663) D119 D151 ^ D147 D148 +error(0.006835861022765376757) D120 D121 +error(0.0002649652178908865757) D120 D121 ^ D124 D125 +error(0.001842590021007301871) D120 D121 ^ D125 D149 +error(0.01360447555925056555) D120 D127 +error(0.01129163812096881624) D120 D127 ^ D124 D125 +error(0.02106229162894282872) D120 D144 +error(0.002751152448060949218) D120 D144 ^ D148 D149 +error(0.003538841843038994985) D120 D145 +error(0.0008757110100126239138) D120 D151 +error(0.002941122394742301787) D120 D151 ^ D124 D125 +error(0.001165932778592970644) D120 D151 ^ D124 D148 +error(0.003280475747202545207) D120 D151 ^ D125 D148 +error(0.001642146425221697624) D120 D151 ^ D125 D149 +error(0.002816897898481184048) D120 D151 ^ D148 D149 +error(0.0006886146142845198884) D120 D152 +error(0.0001236420909161301809) D120 D152 ^ D125 +error(0.000685689790586139266) D120 D152 ^ D125 D148 +error(0.001457910846507099421) D120 D152 ^ D125 D149 +error(0.0002590162334421474365) D120 D152 ^ D148 D149 +error(5.747153257964691372e-05) D120 D152 ^ D149 +error(0.01247992211153514663) D121 +error(0.01569289063977472726) D121 D128 +error(0.01852761195375728781) D121 D128 ^ D125 +error(0.02174588721229521807) D121 D145 +error(0.00218188050196639876) D121 D145 ^ D149 +error(0.003449213835088781998) D121 D152 +error(0.002681972083768658158) D121 D152 ^ D125 +error(0.003567239636822126542) D121 D152 ^ D149 +error(0.0009720917822013221739) D121 D152 ^ D149 ^ D125 +error(0.007324292691020587581) D122 +error(0.01419500512629780567) D122 D123 +error(0.004023252490778637079) D122 D123 ^ D94 L0 +error(0.01819963975774338549) D122 D123 ^ D118 L0 +error(0.0003570751402298309404) D122 D123 ^ D126 L0 +error(0.0001756962670230916869) D122 D123 ^ D126 L0 ^ D94 L0 +error(0.01809902708512096253) D122 D146 +error(0.0007070126030203428879) D122 ^ D90 ^ D94 L0 +error(0.0006367420184909965315) D122 ^ D90 ^ D118 L0 +error(0.0009194744081342942502) D122 ^ D118 L0 ^ D94 L0 +error(0.0157666913660978944) D123 D124 +error(0.0008063908322377350349) D123 D124 ^ D126 D127 +error(0.003973470958629069134) D123 D124 ^ D126 D150 +error(0.01398924460029779895) D123 D129 +error(0.01203288461110336473) D123 D129 ^ D126 L0 +error(0.004973740584631117755) D123 D146 +error(0.003083695718806104061) D123 D146 ^ D118 L0 +error(6.326914210115742673e-05) D123 D146 ^ D150 L0 +error(0.000437796100933523862) D123 D146 ^ D150 L0 ^ D118 L0 +error(0.02802096798889971291) D123 D147 +error(0.0009781054333567957074) D123 D147 ^ D118 L0 +error(0.004258064841452545435) D123 D147 ^ D150 L0 +error(0.002293241519674286358) D123 D153 +error(0.002083689327902756277) D123 D153 ^ D126 L0 +error(0.003184439299356970048) D123 D153 ^ D150 L0 +error(0.0003075964336023181544) D123 D153 ^ D150 L0 ^ D126 L0 +error(0.008748819907022298975) D124 D125 +error(0.000421573423618385281) D124 D125 ^ D126 D127 +error(0.0004454116616421199392) D124 D125 ^ D127 D128 +error(0.002746525552341930968) D124 D125 ^ D127 D151 +error(0.01349995621294126057) D124 D130 +error(0.01074350301251948692) D124 D130 ^ D126 D127 +error(0.007372542091817689894) D124 D147 +error(0.0007550883971604156709) D124 D147 ^ D150 D151 +error(0.02903602395795713831) D124 D148 +error(0.002102104693332725906) D124 D148 ^ D150 D151 +error(0.003169378669323305153) D124 D153 +error(0.001191557425971731836) D124 D153 ^ D126 D150 +error(0.0001597772101005079804) D124 D153 ^ D126 D151 +error(0.0001021827979209038615) D124 D153 ^ D126 L0 +error(0.0005511678242116416215) D124 D153 ^ D150 D151 +error(1.679354630858518888e-05) D124 D153 ^ D150 L0 +error(0.001533444865295702621) D124 D154 +error(0.001663960370674462397) D124 D154 ^ D126 D127 +error(0.0007716218076495109674) D124 D154 ^ D126 D150 +error(0.001303219383453746829) D124 D154 ^ D126 D151 +error(0.000774858462820291762) D124 D154 ^ D127 D151 +error(0.00202762776909865992) D124 D154 ^ D150 D151 +error(0.01000000000000000021) D125 +error(0.004375250986392631436) D125 D148 +error(0.0001996290527887550252) D125 D148 ^ D151 D152 +error(0.02025078136410074503) D125 D149 +error(0.001389942840017453947) D125 D149 ^ D151 D152 +error(0.001697427904974847281) D125 D154 +error(9.531024276690012293e-05) D125 D154 ^ D126 D127 +error(0.0002003070882208187711) D125 D154 ^ D126 D151 +error(0.001002593182003129989) D125 D154 ^ D127 D151 +error(0.0008256000395826743879) D125 ^ D93 ^ D97 +error(0.001338317341795720308) D125 ^ D93 ^ D121 +error(0.0006122748497196598685) D125 ^ D97 +error(0.0063226352583203747) D126 D127 +error(0.000372850945034607572) D126 D127 ^ D129 D130 +error(0.002265174227511792399) D126 D127 ^ D130 D154 +error(0.0003610448547890982083) D126 D127 ^ D154 +error(0.03561013233827770019) D126 D150 +error(0.004322700216861186627) D126 D150 ^ D153 D154 +error(0.003938494697766241337) D126 D151 +error(0.0005358008309723712214) D126 D151 ^ D153 D154 +error(0.002034052694461135468) D126 D155 +error(0.0001466308340950007473) D126 D155 ^ D130 +error(0.001920194442056039194) D126 D155 ^ D130 D154 +error(0.01000000000000000021) D126 L0 +error(0.008841081898479867529) D127 D128 +error(0.002157536244326195389) D127 D128 ^ D101 +error(0.01163473797751780198) D127 D128 ^ D125 +error(0.0007537756625630134995) D127 D128 ^ D130 +error(0.01724304488913697489) D127 D131 +error(0.01634315707910385593) D127 D131 ^ D130 +error(0.01912154204876750918) D127 D151 +error(0.001896228017575547591) D127 D151 ^ D125 +error(0.003907155462371127326) D127 D151 ^ D154 +error(0.00279557314330079092) D127 D152 +error(0.002620934694098134548) D127 D152 ^ D125 +error(0.0004013694757154773717) D127 D152 ^ D154 +error(0.0001537267977297909955) D127 D152 ^ D154 ^ D125 +error(0.003820638366809637251) D127 D155 +error(0.003421241639577967189) D127 D155 ^ D130 +error(0.004007581078155113968) D127 D155 ^ D154 +error(0.001746012587198167822) D127 D155 ^ D154 ^ D130 +error(0.02606250389870726561) D128 D152 +error(0.002389270985273113726) D128 D152 ^ D125 +error(0.00654546687063310012) D129 D130 +error(0.0021024474767527058) D129 D130 ^ D102 L0 +error(0.01203764022217809065) D129 D130 ^ D126 L0 +error(0.0007246969784635964298) D129 D130 ^ D131 L0 +error(0.0005290423207049268833) D129 D130 ^ D131 L0 ^ D102 L0 +error(0.02738393697272551233) D129 D153 +error(0.004004257617406230957) D129 D153 ^ D126 L0 +error(0.01000000000000000021) D130 +error(0.002736244045764444407) D130 D153 +error(0.002855052799012060792) D130 D153 ^ D126 L0 +error(0.0006116163304378687384) D130 D153 ^ D155 L0 +error(0.0007069775710064596895) D130 D153 ^ D155 L0 ^ D126 L0 +error(0.02229227109480388241) D130 D154 +error(0.001481615400962180704) D130 D154 ^ D126 L0 +error(0.002922078673854252608) D130 D154 ^ D155 L0 +error(0.009906527088549655496) D130 ^ D131 L0 +error(0.0013622205925644421) D130 ^ D155 L0 +error(0.004149845774982054321) D131 D155 ^ D130 +error(0.01895412426906178255) D131 D155 +error(0.005000000000000000104) D131 L0 +error(0.005000000000000000104) D132 +error(0.01668747401411250705) D132 D136 +error(0.01827076257666529827) D132 D136 ^ D133 +error(0.02857365717892044674) D132 D156 +error(0.008187804202290056149) D132 D156 ^ D157 +error(0.006752054900691314455) D132 D160 +error(0.006349781933249819092) D132 D160 ^ D133 +error(0.004978707893828611571) D132 D160 ^ D157 +error(0.003764221099563926434) D132 D160 ^ D157 ^ D133 +error(0.00305811170313690121) D132 D161 +error(0.001355606463823049281) D132 D161 ^ D133 +error(0.002720072101049827822) D132 D161 ^ D133 D157 +error(0.0007162514653201519817) D132 D161 ^ D157 +error(0.005000000000000000104) D132 ^ D133 +error(0.006213397302591005048) D133 D157 ^ D132 +error(0.01000000000000000021) D133 +error(0.007614310746050743754) D133 D134 +error(0.0005954277109348562764) D133 D134 ^ D132 +error(0.000465636753644584143) D133 D134 ^ D136 D137 +error(0.0002796968619654203862) D133 D134 ^ D136 D161 +error(0.01582554105481599749) D133 D134 ^ D137 +error(0.005002346730345576947) D133 D134 ^ D137 D161 +error(0.002901359869863939615) D133 D134 ^ D161 +error(0.0005821292772265862199) D133 D134 ^ D161 ^ D132 +error(0.02094673066392089764) D133 D139 +error(0.01260591433803377043) D133 D139 ^ D136 D137 +error(0.04837432224380126128) D133 D157 +error(0.003553059407795153887) D133 D157 ^ D160 D161 +error(0.004155872962511489473) D133 D157 ^ D161 +error(0.003535743537937868341) D133 D162 +error(0.002372881073082702946) D133 D162 ^ D136 D160 +error(3.088814442772618024e-05) D133 D162 ^ D136 D161 +error(0.0002677743536514186166) D133 D162 ^ D160 D161 +error(0.002766432488590481534) D133 D163 +error(0.002003001371357753489) D133 D163 ^ D136 D137 +error(0.0007617751072712451808) D133 D163 ^ D136 D160 +error(0.001724437185270334552) D133 D163 ^ D136 D161 +error(0.001091467339713199239) D133 D163 ^ D137 D161 +error(0.00195910551946494333) D133 D163 ^ D160 D161 +error(0.01704609170648706262) D134 D140 +error(0.01603323914711612952) D134 D140 ^ D137 +error(0.006444335023303983563) D134 D157 +error(0.0006733172831601593735) D134 D157 ^ D132 +error(0.005862290075143809613) D134 D157 ^ D161 +error(0.0008136568950686870862) D134 D157 ^ D161 ^ D132 +error(0.02804448788546923255) D134 D158 +error(0.01224644515584789178) D134 D158 ^ D161 +error(0.002167760793218917112) D134 D163 +error(0.0006482439155634309039) D134 D163 ^ D136 D137 +error(0.0006554643296627914477) D134 D163 ^ D136 D161 +error(0.0001808182923138514173) D134 D163 ^ D137 +error(0.002038558843002732067) D134 D163 ^ D137 D161 +error(0.0001340785921504384238) D134 D163 ^ D161 +error(0.003575688005574470616) D134 D164 +error(0.004475310371346201757) D134 D164 ^ D137 +error(0.00345098355018136219) D134 D164 ^ D161 +error(0.001693218948738322736) D134 D164 ^ D161 ^ D137 +error(0.009232193128085404779) D135 D136 +error(0.0002630814526406159313) D135 D136 ^ D133 +error(0.009686902281069798351) D135 D136 ^ D138 +error(0.0002516825390100136859) D135 D136 ^ D138 D139 +error(0.002350509443893264785) D135 D136 ^ D138 D162 +error(0.0001924701327169168889) D135 D136 ^ D139 D162 +error(0.001328444822298451792) D135 D136 ^ D162 +error(0.0004422428033818157967) D135 D136 ^ D162 ^ D133 +error(0.01553238535686285622) D135 D142 +error(0.01442107373804212) D135 D142 ^ D138 +error(0.02321446919291771452) D135 D159 +error(0.003758964575596710975) D135 D159 ^ D162 +error(0.001583423248511523895) D135 D160 +error(0.0004350561070420648989) D135 D160 ^ D133 +error(0.002418582978257866924) D135 D160 ^ D162 +error(0.0002796298770619333766) D135 D160 ^ D162 ^ D133 +error(0.002780585570467565895) D135 D166 +error(0.003659131334418356651) D135 D166 ^ D138 +error(0.002445659219989861598) D135 D166 ^ D162 +error(0.001480500595323643509) D135 D166 ^ D162 ^ D138 +error(0.002342039754099378614) D135 D167 +error(0.0003971852223546843471) D135 D167 ^ D138 D139 +error(0.001695357924281432841) D135 D167 ^ D138 D162 +error(0.000109853332386578866) D135 D167 ^ D139 D162 +error(4.517129173657599629e-05) D135 D167 ^ D162 +error(0.009370177167621668649) D136 D137 +error(0.0013749192686105837) D136 D137 ^ D109 +error(0.0004326376275655316982) D136 D137 ^ D138 D139 +error(0.001729297765277910352) D136 D137 ^ D139 D163 +error(0.0008369239912465332564) D136 D137 ^ D140 D163 +error(0.01725430315521830557) D136 D143 +error(0.009937067068622049831) D136 D143 ^ D138 D139 +error(0.02800496972801020182) D136 D160 +error(0.008857345427632928175) D136 D160 ^ D133 +error(0.001330748570182143991) D136 D160 ^ D162 +error(0.002708890916997034985) D136 D160 ^ D162 D163 +error(0.004269470014870236155) D136 D161 +error(9.74753423978128047e-05) D136 D161 ^ D162 D163 +error(0.003795022050357953376) D136 D167 +error(0.002450806810346344965) D136 D167 ^ D138 D139 +error(0.001182325052329548159) D136 D167 ^ D138 D162 +error(0.001394230569165803022) D136 D167 ^ D139 D162 +error(0.001347851322040039988) D136 D167 ^ D139 D163 +error(0.00173532620606171189) D136 D167 ^ D162 D163 +error(0.003116053244494311654) D136 D168 +error(7.316842974601893705e-05) D136 D168 ^ D139 D140 +error(0.00015381139946745172) D136 D168 ^ D139 D162 +error(0.0008071141978608846294) D136 D168 ^ D139 D163 +error(0.0001061468001811654107) D136 D168 ^ D140 D163 +error(0.0004214225008490263334) D136 D168 ^ D162 D163 +error(0.01000000000000000021) D137 +error(0.0270222666017383116) D137 D144 +error(0.02417905793237870235) D137 D144 ^ D139 D140 +error(0.03102491946459741065) D137 D161 +error(0.002140803014291666959) D137 D161 ^ D163 D164 +error(0.005011204418027772993) D137 D168 +error(0.002409795170171074013) D137 D168 ^ D139 D140 +error(0.0004867120612278240106) D137 D168 ^ D139 D163 +error(0.001734557560692578373) D137 D168 ^ D140 D163 +error(0.0008310577286774427754) D137 D168 ^ D140 D164 +error(0.002876015875940871915) D137 D168 ^ D163 D164 +error(5.689899368434303708e-05) D137 D169 +error(0.0005376255601673666108) D137 D169 ^ D140 D163 +error(0.001860052998044929096) D137 D169 ^ D140 D164 +error(0.0003270350619594853282) D137 D169 ^ D163 D164 +error(0.01000000000000000021) D138 +error(0.00998951012393598653) D138 D139 +error(0.0002647118028759689896) D138 D139 ^ D142 D143 +error(0.0002437602896713224755) D138 D139 ^ D142 D167 +error(0.0003259292904997979664) D138 D139 ^ D143 D144 +error(0.002910193005919642101) D138 D139 ^ D143 D167 +error(0.01563311530723593412) D138 D147 +error(0.01148884923131972789) D138 D147 ^ D142 D143 +error(0.03402876169483597113) D138 D162 +error(0.00297341913608773151) D138 D162 ^ D166 D167 +error(0.00167198142382841866) D138 D170 +error(0.001978739641503692373) D138 D170 ^ D142 D166 +error(0.0003739016887504405208) D138 D170 ^ D142 D167 +error(0.0006191581992012207009) D138 D170 ^ D166 D167 +error(0.003564405145362673812) D138 D171 +error(0.002427865772048852337) D138 D171 ^ D142 D143 +error(0.002016980215619930579) D138 D171 ^ D142 D166 +error(0.001665163685732147384) D138 D171 ^ D142 D167 +error(0.001089534673102127496) D138 D171 ^ D143 D167 +error(0.002441047980058794978) D138 D171 ^ D166 D167 +error(0.0004010735829825645671) D138 ^ D166 L0 +error(0.0040421911780430652) D142 D166 ^ D138 +error(0.01013563020920371822) D139 D140 +error(0.0008314930570387067546) D139 D140 ^ D137 +error(0.0001530404613110457714) D139 D140 ^ D143 D144 +error(0.000607895799866905789) D139 D140 ^ D143 D168 +error(3.403628659066277234e-05) D139 D140 ^ D144 D145 +error(0.0025882004664708534) D139 D140 ^ D144 D168 +error(0.01727203508574649132) D139 D148 +error(0.0145277865377167175) D139 D148 ^ D143 D144 +error(0.004930101446126109246) D139 D162 +error(0.0002881881964098772803) D139 D162 ^ D167 D168 +error(0.04574271143269240114) D139 D163 +error(0.001860329697148833646) D139 D163 ^ D167 D168 +error(0.00255198772447796712) D139 D171 +error(0.0005047023561676590529) D139 D171 ^ D142 D143 +error(0.001452256159036316528) D139 D171 ^ D143 D167 +error(5.222076102721136015e-05) D139 D171 ^ D143 D168 +error(0.0009987913400580498199) D139 D171 ^ D167 D168 +error(0.001430194805650022039) D139 D172 +error(0.002007285104460634732) D139 D172 ^ D143 D144 +error(0.001224248109508729171) D139 D172 ^ D143 D167 +error(0.002303664480707598265) D139 D172 ^ D143 D168 +error(0.0009171454591137486075) D139 D172 ^ D144 D168 +error(0.002191714195832245807) D139 D172 ^ D167 D168 +error(0.009797724443923057011) D140 D141 +error(0.0001021472594512653998) D140 D141 ^ D144 D145 +error(0.0001210959338265430346) D140 D141 ^ D144 D169 +error(0.01190918523369760215) D140 D141 ^ D145 +error(0.005273755897734558329) D140 D141 ^ D145 D169 +error(0.00184597880693155897) D140 D141 ^ D169 +error(0.01377684914337177352) D140 D149 +error(0.01093440003708149623) D140 D149 ^ D144 D145 +error(0.003249664646197158047) D140 D163 +error(2.258206681107317873e-05) D140 D163 ^ D168 D169 +error(0.02265899218759278091) D140 D164 +error(0.004590199147543793691) D140 D164 ^ D137 +error(0.002645517561442980222) D140 D164 ^ D168 D169 +error(0.0005399062537493103456) D140 D164 ^ D169 +error(0.002277233782169691897) D140 D172 +error(0.0002528250109153119818) D140 D172 ^ D143 D144 +error(0.0006205257979712591916) D140 D172 ^ D143 D168 +error(0.001404758555723596139) D140 D172 ^ D144 D168 +error(0.0002405291802527288812) D140 D172 ^ D144 D169 +error(0.0003097319487677911579) D140 D172 ^ D168 D169 +error(0.001047705250796779949) D140 D173 +error(0.00237092510280944831) D140 D173 ^ D144 D145 +error(0.001037220928621594273) D140 D173 ^ D144 D168 +error(0.00238058383085898136) D140 D173 ^ D144 D169 +error(0.0008835768967079051526) D140 D173 ^ D145 D169 +error(0.002259774772269825763) D140 D173 ^ D168 D169 +error(0.01260811278973474753) D141 +error(0.00225151851890723325) D141 D164 +error(0.0001797993500064738813) D141 D164 ^ D137 +error(0.002356030447914673944) D141 D164 ^ D169 +error(0.0345566698397392208) D141 D165 +error(0.005003744614217759193) D141 D165 ^ D169 +error(0.001837583674123140394) D141 D173 +error(9.255458431562874132e-05) D141 D173 ^ D144 D145 +error(0.0002126721966588340058) D141 D173 ^ D144 D169 +error(0.002035990511446809058) D141 D173 ^ D145 D169 +error(0.02090970420602020902) D141 ^ D145 +error(0.0009042125990949610812) D141 ^ D169 +error(0.001560696983551172019) D141 ^ D169 ^ D145 +error(0.01374568531695860747) D142 D143 +error(0.0002954516562893196702) D142 D143 ^ D146 D147 +error(0.00158847535642978651) D142 D143 ^ D147 D171 +error(0.04904868400430456576) D142 D166 +error(0.003544968265632814693) D142 D166 ^ D170 D171 +error(0.003865628745054386969) D142 D167 +error(0.000441796954324594226) D142 D167 ^ D170 D171 +error(0.0009740040964997024285) D142 D174 +error(0.00188554410197714988) D142 D174 ^ D147 D171 +error(0.01000000000000000021) D142 L0 +error(0.01186879937024130915) D142 L0 ^ D146 +error(0.003675582362634155064) D146 D170 ^ D142 L0 +error(0.01735160188785484295) D143 D144 +error(0.0007088289629090005787) D143 D144 ^ D147 D148 +error(0.0005313038609727570695) D143 D144 ^ D148 D149 +error(0.002702669103548420697) D143 D144 ^ D148 D172 +error(0.0006166556002974491434) D143 D144 ^ D149 D172 +error(0.0207233958407102431) D143 D150 +error(0.02026670657223518177) D143 D150 ^ D147 D148 +error(0.02961831943462597469) D143 D167 +error(0.002972165594026740694) D143 D167 ^ D171 D172 +error(0.00414184937373599394) D143 D168 +error(0.00040167431689305317) D143 D168 ^ D171 D172 +error(0.005690305629853309802) D143 D174 +error(0.006400338574826603191) D143 D174 ^ D147 D148 +error(0.002210171177652492467) D143 D174 ^ D147 D171 +error(0.007612181774541293064) D143 D174 ^ D148 D171 +error(0.001786447785683612389) D143 D174 ^ D148 D172 +error(0.004060767403088009868) D143 D174 ^ D171 D172 +error(0.001749884553720177727) D143 D175 +error(0.0007133736782402601805) D143 D175 ^ D148 D149 +error(0.0005844947904700150375) D143 D175 ^ D148 D171 +error(0.0008217823092129306105) D143 D175 ^ D148 D172 +error(0.0003275095103629303275) D143 D175 ^ D149 D172 +error(0.0006123041623268492663) D143 D175 ^ D171 D172 +error(0.006835861022765376757) D144 D145 +error(0.0002649652178908865757) D144 D145 ^ D148 D149 +error(0.001842590021007301871) D144 D145 ^ D149 D173 +error(0.01360447555925056555) D144 D151 +error(0.01129163812096881624) D144 D151 ^ D148 D149 +error(0.02106229162894282872) D144 D168 +error(0.002751152448060949218) D144 D168 ^ D172 D173 +error(0.003538841843038994985) D144 D169 +error(0.0008757110100126239138) D144 D175 +error(0.002941122394742301787) D144 D175 ^ D148 D149 +error(0.001165932778592970644) D144 D175 ^ D148 D172 +error(0.003280475747202545207) D144 D175 ^ D149 D172 +error(0.001642146425221697624) D144 D175 ^ D149 D173 +error(0.002816897898481184048) D144 D175 ^ D172 D173 +error(0.0006886146142845198884) D144 D176 +error(0.0001236420909161301809) D144 D176 ^ D149 +error(0.000685689790586139266) D144 D176 ^ D149 D172 +error(0.001457910846507099421) D144 D176 ^ D149 D173 +error(0.0002590162334421474365) D144 D176 ^ D172 D173 +error(5.747153257964691372e-05) D144 D176 ^ D173 +error(0.01247992211153514663) D145 +error(0.01569289063977472726) D145 D152 +error(0.01852761195375728781) D145 D152 ^ D149 +error(0.02174588721229521807) D145 D169 +error(0.00218188050196639876) D145 D169 ^ D173 +error(0.003449213835088781998) D145 D176 +error(0.002681972083768658158) D145 D176 ^ D149 +error(0.003567239636822126542) D145 D176 ^ D173 +error(0.0009720917822013221739) D145 D176 ^ D173 ^ D149 +error(0.007324292691020587581) D146 +error(0.01419500512629780567) D146 D147 +error(0.004023252490778637079) D146 D147 ^ D118 L0 +error(0.01819963975774338549) D146 D147 ^ D142 L0 +error(0.0003570751402298309404) D146 D147 ^ D150 L0 +error(0.0001756962670230916869) D146 D147 ^ D150 L0 ^ D118 L0 +error(0.01809902708512096253) D146 D170 +error(0.0007070126030203428879) D146 ^ D114 ^ D118 L0 +error(0.0006367420184909965315) D146 ^ D114 ^ D142 L0 +error(0.0009194744081342942502) D146 ^ D142 L0 ^ D118 L0 +error(0.0157666913660978944) D147 D148 +error(0.0008063908322377350349) D147 D148 ^ D150 D151 +error(0.003973470958629069134) D147 D148 ^ D150 D174 +error(0.01398924460029779895) D147 D153 +error(0.01203288461110336473) D147 D153 ^ D150 L0 +error(0.004973740584631117755) D147 D170 +error(0.003083695718806104061) D147 D170 ^ D142 L0 +error(6.326914210115742673e-05) D147 D170 ^ D174 L0 +error(0.000437796100933523862) D147 D170 ^ D174 L0 ^ D142 L0 +error(0.02802096798889971291) D147 D171 +error(0.0009781054333567957074) D147 D171 ^ D142 L0 +error(0.004258064841452545435) D147 D171 ^ D174 L0 +error(0.002293241519674286358) D147 D177 +error(0.002083689327902756277) D147 D177 ^ D150 L0 +error(0.003184439299356970048) D147 D177 ^ D174 L0 +error(0.0003075964336023181544) D147 D177 ^ D174 L0 ^ D150 L0 +error(0.008748819907022298975) D148 D149 +error(0.000421573423618385281) D148 D149 ^ D150 D151 +error(0.0004454116616421199392) D148 D149 ^ D151 D152 +error(0.002746525552341930968) D148 D149 ^ D151 D175 +error(0.01349995621294126057) D148 D154 +error(0.01074350301251948692) D148 D154 ^ D150 D151 +error(0.007372542091817689894) D148 D171 +error(0.0007550883971604156709) D148 D171 ^ D174 D175 +error(0.02903602395795713831) D148 D172 +error(0.002102104693332725906) D148 D172 ^ D174 D175 +error(0.003169378669323305153) D148 D177 +error(0.001191557425971731836) D148 D177 ^ D150 D174 +error(0.0001597772101005079804) D148 D177 ^ D150 D175 +error(0.0001021827979209038615) D148 D177 ^ D150 L0 +error(0.0005511678242116416215) D148 D177 ^ D174 D175 +error(1.679354630858518888e-05) D148 D177 ^ D174 L0 +error(0.001533444865295702621) D148 D178 +error(0.001663960370674462397) D148 D178 ^ D150 D151 +error(0.0007716218076495109674) D148 D178 ^ D150 D174 +error(0.001303219383453746829) D148 D178 ^ D150 D175 +error(0.000774858462820291762) D148 D178 ^ D151 D175 +error(0.00202762776909865992) D148 D178 ^ D174 D175 +error(0.01000000000000000021) D149 +error(0.004375250986392631436) D149 D172 +error(0.0001996290527887550252) D149 D172 ^ D175 D176 +error(0.02025078136410074503) D149 D173 +error(0.001389942840017453947) D149 D173 ^ D175 D176 +error(0.001697427904974847281) D149 D178 +error(9.531024276690012293e-05) D149 D178 ^ D150 D151 +error(0.0002003070882208187711) D149 D178 ^ D150 D175 +error(0.001002593182003129989) D149 D178 ^ D151 D175 +error(0.0008256000395826743879) D149 ^ D117 ^ D121 +error(0.001338317341795720308) D149 ^ D117 ^ D145 +error(0.0006122748497196598685) D149 ^ D121 +error(0.0063226352583203747) D150 D151 +error(0.000372850945034607572) D150 D151 ^ D153 D154 +error(0.002265174227511792399) D150 D151 ^ D154 D178 +error(0.0003610448547890982083) D150 D151 ^ D178 +error(0.03561013233827770019) D150 D174 +error(0.004322700216861186627) D150 D174 ^ D177 D178 +error(0.003938494697766241337) D150 D175 +error(0.0005358008309723712214) D150 D175 ^ D177 D178 +error(0.002034052694461135468) D150 D179 +error(0.0001466308340950007473) D150 D179 ^ D154 +error(0.001920194442056039194) D150 D179 ^ D154 D178 +error(0.01000000000000000021) D150 L0 +error(0.008841081898479867529) D151 D152 +error(0.002157536244326195389) D151 D152 ^ D125 +error(0.01163473797751780198) D151 D152 ^ D149 +error(0.0007537756625630134995) D151 D152 ^ D154 +error(0.01724304488913697489) D151 D155 +error(0.01634315707910385593) D151 D155 ^ D154 +error(0.01912154204876750918) D151 D175 +error(0.001896228017575547591) D151 D175 ^ D149 +error(0.003907155462371127326) D151 D175 ^ D178 +error(0.00279557314330079092) D151 D176 +error(0.002620934694098134548) D151 D176 ^ D149 +error(0.0004013694757154773717) D151 D176 ^ D178 +error(0.0001537267977297909955) D151 D176 ^ D178 ^ D149 +error(0.003820638366809637251) D151 D179 +error(0.003421241639577967189) D151 D179 ^ D154 +error(0.004007581078155113968) D151 D179 ^ D178 +error(0.001746012587198167822) D151 D179 ^ D178 ^ D154 +error(0.02606250389870726561) D152 D176 +error(0.002389270985273113726) D152 D176 ^ D149 +error(0.00654546687063310012) D153 D154 +error(0.0021024474767527058) D153 D154 ^ D126 L0 +error(0.01203764022217809065) D153 D154 ^ D150 L0 +error(0.0007246969784635964298) D153 D154 ^ D155 L0 +error(0.0005290423207049268833) D153 D154 ^ D155 L0 ^ D126 L0 +error(0.02738393697272551233) D153 D177 +error(0.004004257617406230957) D153 D177 ^ D150 L0 +error(0.01000000000000000021) D154 +error(0.002736244045764444407) D154 D177 +error(0.002855052799012060792) D154 D177 ^ D150 L0 +error(0.0006116163304378687384) D154 D177 ^ D179 L0 +error(0.0007069775710064596895) D154 D177 ^ D179 L0 ^ D150 L0 +error(0.02229227109480388241) D154 D178 +error(0.001481615400962180704) D154 D178 ^ D150 L0 +error(0.002922078673854252608) D154 D178 ^ D179 L0 +error(0.009906527088549655496) D154 ^ D155 L0 +error(0.0013622205925644421) D154 ^ D179 L0 +error(0.004149845774982054321) D155 D179 ^ D154 +error(0.01895412426906178255) D155 D179 +error(0.005000000000000000104) D155 L0 +error(0.005000000000000000104) D156 +error(0.01668747401411250705) D156 D160 +error(0.01827076257666529827) D156 D160 ^ D157 +error(0.02857365717892044674) D156 D180 +error(0.008187804202290056149) D156 D180 ^ D181 +error(0.006752054900691314455) D156 D184 +error(0.006349781933249819092) D156 D184 ^ D157 +error(0.004978707893828611571) D156 D184 ^ D181 +error(0.003764221099563926434) D156 D184 ^ D181 ^ D157 +error(0.00305811170313690121) D156 D185 +error(0.001355606463823049281) D156 D185 ^ D157 +error(0.002720072101049827822) D156 D185 ^ D157 D181 +error(0.0007162514653201519817) D156 D185 ^ D181 +error(0.005000000000000000104) D156 ^ D157 +error(0.006213397302591005048) D157 D181 ^ D156 +error(0.01000000000000000021) D157 +error(0.007614310746050743754) D157 D158 +error(0.0005954277109348562764) D157 D158 ^ D156 +error(0.000465636753644584143) D157 D158 ^ D160 D161 +error(0.0002796968619654203862) D157 D158 ^ D160 D185 +error(0.01582554105481599749) D157 D158 ^ D161 +error(0.005002346730345576947) D157 D158 ^ D161 D185 +error(0.002901359869863939615) D157 D158 ^ D185 +error(0.0005821292772265862199) D157 D158 ^ D185 ^ D156 +error(0.02094673066392089764) D157 D163 +error(0.01260591433803377043) D157 D163 ^ D160 D161 +error(0.04837432224380126128) D157 D181 +error(0.003553059407795153887) D157 D181 ^ D184 D185 +error(0.004155872962511489473) D157 D181 ^ D185 +error(0.003535743537937868341) D157 D186 +error(0.002372881073082702946) D157 D186 ^ D160 D184 +error(3.088814442772618024e-05) D157 D186 ^ D160 D185 +error(0.0002677743536514186166) D157 D186 ^ D184 D185 +error(0.002766432488590481534) D157 D187 +error(0.002003001371357753489) D157 D187 ^ D160 D161 +error(0.0007617751072712451808) D157 D187 ^ D160 D184 +error(0.001724437185270334552) D157 D187 ^ D160 D185 +error(0.001091467339713199239) D157 D187 ^ D161 D185 +error(0.00195910551946494333) D157 D187 ^ D184 D185 +error(0.01704609170648706262) D158 D164 +error(0.01603323914711612952) D158 D164 ^ D161 +error(0.006444335023303983563) D158 D181 +error(0.0006733172831601593735) D158 D181 ^ D156 +error(0.005862290075143809613) D158 D181 ^ D185 +error(0.0008136568950686870862) D158 D181 ^ D185 ^ D156 +error(0.02804448788546923255) D158 D182 +error(0.01224644515584789178) D158 D182 ^ D185 +error(0.002167760793218917112) D158 D187 +error(0.0006482439155634309039) D158 D187 ^ D160 D161 +error(0.0006554643296627914477) D158 D187 ^ D160 D185 +error(0.0001808182923138514173) D158 D187 ^ D161 +error(0.002038558843002732067) D158 D187 ^ D161 D185 +error(0.0001340785921504384238) D158 D187 ^ D185 +error(0.003575688005574470616) D158 D188 +error(0.004475310371346201757) D158 D188 ^ D161 +error(0.00345098355018136219) D158 D188 ^ D185 +error(0.001693218948738322736) D158 D188 ^ D185 ^ D161 +error(0.009232193128085404779) D159 D160 +error(0.0002630814526406159313) D159 D160 ^ D157 +error(0.009686902281069798351) D159 D160 ^ D162 +error(0.0002516825390100136859) D159 D160 ^ D162 D163 +error(0.002350509443893264785) D159 D160 ^ D162 D186 +error(0.0001924701327169168889) D159 D160 ^ D163 D186 +error(0.001328444822298451792) D159 D160 ^ D186 +error(0.0004422428033818157967) D159 D160 ^ D186 ^ D157 +error(0.01553238535686285622) D159 D166 +error(0.01442107373804212) D159 D166 ^ D162 +error(0.02321446919291771452) D159 D183 +error(0.003758964575596710975) D159 D183 ^ D186 +error(0.001583423248511523895) D159 D184 +error(0.0004350561070420648989) D159 D184 ^ D157 +error(0.002418582978257866924) D159 D184 ^ D186 +error(0.0002796298770619333766) D159 D184 ^ D186 ^ D157 +error(0.002780585570467565895) D159 D190 +error(0.003659131334418356651) D159 D190 ^ D162 +error(0.002445659219989861598) D159 D190 ^ D186 +error(0.001480500595323643509) D159 D190 ^ D186 ^ D162 +error(0.002342039754099378614) D159 D191 +error(0.0003971852223546843471) D159 D191 ^ D162 D163 +error(0.001695357924281432841) D159 D191 ^ D162 D186 +error(0.000109853332386578866) D159 D191 ^ D163 D186 +error(4.517129173657599629e-05) D159 D191 ^ D186 +error(0.009370177167621668649) D160 D161 +error(0.0013749192686105837) D160 D161 ^ D133 +error(0.0004326376275655316982) D160 D161 ^ D162 D163 +error(0.001729297765277910352) D160 D161 ^ D163 D187 +error(0.0008369239912465332564) D160 D161 ^ D164 D187 +error(0.01725430315521830557) D160 D167 +error(0.009937067068622049831) D160 D167 ^ D162 D163 +error(0.02800496972801020182) D160 D184 +error(0.008857345427632928175) D160 D184 ^ D157 +error(0.001330748570182143991) D160 D184 ^ D186 +error(0.002708890916997034985) D160 D184 ^ D186 D187 +error(0.004269470014870236155) D160 D185 +error(9.74753423978128047e-05) D160 D185 ^ D186 D187 +error(0.003795022050357953376) D160 D191 +error(0.002450806810346344965) D160 D191 ^ D162 D163 +error(0.001182325052329548159) D160 D191 ^ D162 D186 +error(0.001394230569165803022) D160 D191 ^ D163 D186 +error(0.001347851322040039988) D160 D191 ^ D163 D187 +error(0.00173532620606171189) D160 D191 ^ D186 D187 +error(0.003116053244494311654) D160 D192 +error(7.316842974601893705e-05) D160 D192 ^ D163 D164 +error(0.00015381139946745172) D160 D192 ^ D163 D186 +error(0.0008071141978608846294) D160 D192 ^ D163 D187 +error(0.0001061468001811654107) D160 D192 ^ D164 D187 +error(0.0004214225008490263334) D160 D192 ^ D186 D187 +error(0.01000000000000000021) D161 +error(0.0270222666017383116) D161 D168 +error(0.02417905793237870235) D161 D168 ^ D163 D164 +error(0.03102491946459741065) D161 D185 +error(0.002140803014291666959) D161 D185 ^ D187 D188 +error(0.005011204418027772993) D161 D192 +error(0.002409795170171074013) D161 D192 ^ D163 D164 +error(0.0004867120612278240106) D161 D192 ^ D163 D187 +error(0.001734557560692578373) D161 D192 ^ D164 D187 +error(0.0008310577286774427754) D161 D192 ^ D164 D188 +error(0.002876015875940871915) D161 D192 ^ D187 D188 +error(5.689899368434303708e-05) D161 D193 +error(0.0005376255601673666108) D161 D193 ^ D164 D187 +error(0.001860052998044929096) D161 D193 ^ D164 D188 +error(0.0003270350619594853282) D161 D193 ^ D187 D188 +error(0.01000000000000000021) D162 +error(0.00998951012393598653) D162 D163 +error(0.0002647118028759689896) D162 D163 ^ D166 D167 +error(0.0002437602896713224755) D162 D163 ^ D166 D191 +error(0.0003259292904997979664) D162 D163 ^ D167 D168 +error(0.002910193005919642101) D162 D163 ^ D167 D191 +error(0.01563311530723593412) D162 D171 +error(0.01148884923131972789) D162 D171 ^ D166 D167 +error(0.03402876169483597113) D162 D186 +error(0.00297341913608773151) D162 D186 ^ D190 D191 +error(0.00167198142382841866) D162 D194 +error(0.001978739641503692373) D162 D194 ^ D166 D190 +error(0.0003739016887504405208) D162 D194 ^ D166 D191 +error(0.0006191581992012207009) D162 D194 ^ D190 D191 +error(0.003564405145362673812) D162 D195 +error(0.002427865772048852337) D162 D195 ^ D166 D167 +error(0.002016980215619930579) D162 D195 ^ D166 D190 +error(0.001665163685732147384) D162 D195 ^ D166 D191 +error(0.001089534673102127496) D162 D195 ^ D167 D191 +error(0.002441047980058794978) D162 D195 ^ D190 D191 +error(0.0004010735829825645671) D162 ^ D190 L0 +error(0.0040421911780430652) D166 D190 ^ D162 +error(0.01013563020920371822) D163 D164 +error(0.0008314930570387067546) D163 D164 ^ D161 +error(0.0001530404613110457714) D163 D164 ^ D167 D168 +error(0.000607895799866905789) D163 D164 ^ D167 D192 +error(3.403628659066277234e-05) D163 D164 ^ D168 D169 +error(0.0025882004664708534) D163 D164 ^ D168 D192 +error(0.01727203508574649132) D163 D172 +error(0.0145277865377167175) D163 D172 ^ D167 D168 +error(0.004930101446126109246) D163 D186 +error(0.0002881881964098772803) D163 D186 ^ D191 D192 +error(0.04574271143269240114) D163 D187 +error(0.001860329697148833646) D163 D187 ^ D191 D192 +error(0.00255198772447796712) D163 D195 +error(0.0005047023561676590529) D163 D195 ^ D166 D167 +error(0.001452256159036316528) D163 D195 ^ D167 D191 +error(5.222076102721136015e-05) D163 D195 ^ D167 D192 +error(0.0009987913400580498199) D163 D195 ^ D191 D192 +error(0.001430194805650022039) D163 D196 +error(0.002007285104460634732) D163 D196 ^ D167 D168 +error(0.001224248109508729171) D163 D196 ^ D167 D191 +error(0.002303664480707598265) D163 D196 ^ D167 D192 +error(0.0009171454591137486075) D163 D196 ^ D168 D192 +error(0.002191714195832245807) D163 D196 ^ D191 D192 +error(0.009797724443923057011) D164 D165 +error(0.0001021472594512653998) D164 D165 ^ D168 D169 +error(0.0001210959338265430346) D164 D165 ^ D168 D193 +error(0.01190918523369760215) D164 D165 ^ D169 +error(0.005273755897734558329) D164 D165 ^ D169 D193 +error(0.00184597880693155897) D164 D165 ^ D193 +error(0.01377684914337177352) D164 D173 +error(0.01093440003708149623) D164 D173 ^ D168 D169 +error(0.003249664646197158047) D164 D187 +error(2.258206681107317873e-05) D164 D187 ^ D192 D193 +error(0.02265899218759278091) D164 D188 +error(0.004590199147543793691) D164 D188 ^ D161 +error(0.002645517561442980222) D164 D188 ^ D192 D193 +error(0.0005399062537493103456) D164 D188 ^ D193 +error(0.002277233782169691897) D164 D196 +error(0.0002528250109153119818) D164 D196 ^ D167 D168 +error(0.0006205257979712591916) D164 D196 ^ D167 D192 +error(0.001404758555723596139) D164 D196 ^ D168 D192 +error(0.0002405291802527288812) D164 D196 ^ D168 D193 +error(0.0003097319487677911579) D164 D196 ^ D192 D193 +error(0.001047705250796779949) D164 D197 +error(0.00237092510280944831) D164 D197 ^ D168 D169 +error(0.001037220928621594273) D164 D197 ^ D168 D192 +error(0.00238058383085898136) D164 D197 ^ D168 D193 +error(0.0008835768967079051526) D164 D197 ^ D169 D193 +error(0.002259774772269825763) D164 D197 ^ D192 D193 +error(0.01260811278973474753) D165 +error(0.00225151851890723325) D165 D188 +error(0.0001797993500064738813) D165 D188 ^ D161 +error(0.002356030447914673944) D165 D188 ^ D193 +error(0.0345566698397392208) D165 D189 +error(0.005003744614217759193) D165 D189 ^ D193 +error(0.001837583674123140394) D165 D197 +error(9.255458431562874132e-05) D165 D197 ^ D168 D169 +error(0.0002126721966588340058) D165 D197 ^ D168 D193 +error(0.002035990511446809058) D165 D197 ^ D169 D193 +error(0.02090970420602020902) D165 ^ D169 +error(0.0009042125990949610812) D165 ^ D193 +error(0.001560696983551172019) D165 ^ D193 ^ D169 +error(0.01374568531695860747) D166 D167 +error(0.0002954516562893196702) D166 D167 ^ D170 D171 +error(0.00158847535642978651) D166 D167 ^ D171 D195 +error(0.04904868400430456576) D166 D190 +error(0.003544968265632814693) D166 D190 ^ D194 D195 +error(0.003865628745054386969) D166 D191 +error(0.000441796954324594226) D166 D191 ^ D194 D195 +error(0.0009740040964997024285) D166 D198 +error(0.00188554410197714988) D166 D198 ^ D171 D195 +error(0.01000000000000000021) D166 L0 +error(0.01186879937024130915) D166 L0 ^ D170 +error(0.003675582362634155064) D170 D194 ^ D166 L0 +error(0.01735160188785484295) D167 D168 +error(0.0007088289629090005787) D167 D168 ^ D171 D172 +error(0.0005313038609727570695) D167 D168 ^ D172 D173 +error(0.002702669103548420697) D167 D168 ^ D172 D196 +error(0.0006166556002974491434) D167 D168 ^ D173 D196 +error(0.0207233958407102431) D167 D174 +error(0.02026670657223518177) D167 D174 ^ D171 D172 +error(0.02961831943462597469) D167 D191 +error(0.002972165594026740694) D167 D191 ^ D195 D196 +error(0.00414184937373599394) D167 D192 +error(0.00040167431689305317) D167 D192 ^ D195 D196 +error(0.005690305629853309802) D167 D198 +error(0.006400338574826603191) D167 D198 ^ D171 D172 +error(0.002210171177652492467) D167 D198 ^ D171 D195 +error(0.007612181774541293064) D167 D198 ^ D172 D195 +error(0.001786447785683612389) D167 D198 ^ D172 D196 +error(0.004060767403088009868) D167 D198 ^ D195 D196 +error(0.001749884553720177727) D167 D199 +error(0.0007133736782402601805) D167 D199 ^ D172 D173 +error(0.0005844947904700150375) D167 D199 ^ D172 D195 +error(0.0008217823092129306105) D167 D199 ^ D172 D196 +error(0.0003275095103629303275) D167 D199 ^ D173 D196 +error(0.0006123041623268492663) D167 D199 ^ D195 D196 +error(0.006835861022765376757) D168 D169 +error(0.0002649652178908865757) D168 D169 ^ D172 D173 +error(0.001842590021007301871) D168 D169 ^ D173 D197 +error(0.01360447555925056555) D168 D175 +error(0.01129163812096881624) D168 D175 ^ D172 D173 +error(0.02106229162894282872) D168 D192 +error(0.002751152448060949218) D168 D192 ^ D196 D197 +error(0.003538841843038994985) D168 D193 +error(0.0008757110100126239138) D168 D199 +error(0.002941122394742301787) D168 D199 ^ D172 D173 +error(0.001165932778592970644) D168 D199 ^ D172 D196 +error(0.003280475747202545207) D168 D199 ^ D173 D196 +error(0.001642146425221697624) D168 D199 ^ D173 D197 +error(0.002816897898481184048) D168 D199 ^ D196 D197 +error(0.0006886146142845198884) D168 D200 +error(0.0001236420909161301809) D168 D200 ^ D173 +error(0.000685689790586139266) D168 D200 ^ D173 D196 +error(0.001457910846507099421) D168 D200 ^ D173 D197 +error(0.0002590162334421474365) D168 D200 ^ D196 D197 +error(5.747153257964691372e-05) D168 D200 ^ D197 +error(0.01247992211153514663) D169 +error(0.01569289063977472726) D169 D176 +error(0.01852761195375728781) D169 D176 ^ D173 +error(0.02174588721229521807) D169 D193 +error(0.00218188050196639876) D169 D193 ^ D197 +error(0.003449213835088781998) D169 D200 +error(0.002681972083768658158) D169 D200 ^ D173 +error(0.003567239636822126542) D169 D200 ^ D197 +error(0.0009720917822013221739) D169 D200 ^ D197 ^ D173 +error(0.007324292691020587581) D170 +error(0.01419500512629780567) D170 D171 +error(0.004023252490778637079) D170 D171 ^ D142 L0 +error(0.01819963975774338549) D170 D171 ^ D166 L0 +error(0.0003570751402298309404) D170 D171 ^ D174 L0 +error(0.0001756962670230916869) D170 D171 ^ D174 L0 ^ D142 L0 +error(0.01809902708512096253) D170 D194 +error(0.0007070126030203428879) D170 ^ D138 ^ D142 L0 +error(0.0006367420184909965315) D170 ^ D138 ^ D166 L0 +error(0.0009194744081342942502) D170 ^ D166 L0 ^ D142 L0 +error(0.0157666913660978944) D171 D172 +error(0.0008063908322377350349) D171 D172 ^ D174 D175 +error(0.003973470958629069134) D171 D172 ^ D174 D198 +error(0.01398924460029779895) D171 D177 +error(0.01203288461110336473) D171 D177 ^ D174 L0 +error(0.004973740584631117755) D171 D194 +error(0.003083695718806104061) D171 D194 ^ D166 L0 +error(6.326914210115742673e-05) D171 D194 ^ D198 L0 +error(0.000437796100933523862) D171 D194 ^ D198 L0 ^ D166 L0 +error(0.02802096798889971291) D171 D195 +error(0.0009781054333567957074) D171 D195 ^ D166 L0 +error(0.004258064841452545435) D171 D195 ^ D198 L0 +error(0.002293241519674286358) D171 D201 +error(0.002083689327902756277) D171 D201 ^ D174 L0 +error(0.003184439299356970048) D171 D201 ^ D198 L0 +error(0.0003075964336023181544) D171 D201 ^ D198 L0 ^ D174 L0 +error(0.008748819907022298975) D172 D173 +error(0.000421573423618385281) D172 D173 ^ D174 D175 +error(0.0004454116616421199392) D172 D173 ^ D175 D176 +error(0.002746525552341930968) D172 D173 ^ D175 D199 +error(0.01349995621294126057) D172 D178 +error(0.01074350301251948692) D172 D178 ^ D174 D175 +error(0.007372542091817689894) D172 D195 +error(0.0007550883971604156709) D172 D195 ^ D198 D199 +error(0.02903602395795713831) D172 D196 +error(0.002102104693332725906) D172 D196 ^ D198 D199 +error(0.003169378669323305153) D172 D201 +error(0.001191557425971731836) D172 D201 ^ D174 D198 +error(0.0001597772101005079804) D172 D201 ^ D174 D199 +error(0.0001021827979209038615) D172 D201 ^ D174 L0 +error(0.0005511678242116416215) D172 D201 ^ D198 D199 +error(1.679354630858518888e-05) D172 D201 ^ D198 L0 +error(0.001533444865295702621) D172 D202 +error(0.001663960370674462397) D172 D202 ^ D174 D175 +error(0.0007716218076495109674) D172 D202 ^ D174 D198 +error(0.001303219383453746829) D172 D202 ^ D174 D199 +error(0.000774858462820291762) D172 D202 ^ D175 D199 +error(0.00202762776909865992) D172 D202 ^ D198 D199 +error(0.01000000000000000021) D173 +error(0.004375250986392631436) D173 D196 +error(0.0001996290527887550252) D173 D196 ^ D199 D200 +error(0.02025078136410074503) D173 D197 +error(0.001389942840017453947) D173 D197 ^ D199 D200 +error(0.001697427904974847281) D173 D202 +error(9.531024276690012293e-05) D173 D202 ^ D174 D175 +error(0.0002003070882208187711) D173 D202 ^ D174 D199 +error(0.001002593182003129989) D173 D202 ^ D175 D199 +error(0.0008256000395826743879) D173 ^ D141 ^ D145 +error(0.001338317341795720308) D173 ^ D141 ^ D169 +error(0.0006122748497196598685) D173 ^ D145 +error(0.0063226352583203747) D174 D175 +error(0.000372850945034607572) D174 D175 ^ D177 D178 +error(0.002265174227511792399) D174 D175 ^ D178 D202 +error(0.0003610448547890982083) D174 D175 ^ D202 +error(0.03561013233827770019) D174 D198 +error(0.004322700216861186627) D174 D198 ^ D201 D202 +error(0.003938494697766241337) D174 D199 +error(0.0005358008309723712214) D174 D199 ^ D201 D202 +error(0.002034052694461135468) D174 D203 +error(0.0001466308340950007473) D174 D203 ^ D178 +error(0.001920194442056039194) D174 D203 ^ D178 D202 +error(0.01000000000000000021) D174 L0 +error(0.008841081898479867529) D175 D176 +error(0.002157536244326195389) D175 D176 ^ D149 +error(0.01163473797751780198) D175 D176 ^ D173 +error(0.0007537756625630134995) D175 D176 ^ D178 +error(0.01724304488913697489) D175 D179 +error(0.01634315707910385593) D175 D179 ^ D178 +error(0.01912154204876750918) D175 D199 +error(0.001896228017575547591) D175 D199 ^ D173 +error(0.003907155462371127326) D175 D199 ^ D202 +error(0.00279557314330079092) D175 D200 +error(0.002620934694098134548) D175 D200 ^ D173 +error(0.0004013694757154773717) D175 D200 ^ D202 +error(0.0001537267977297909955) D175 D200 ^ D202 ^ D173 +error(0.003820638366809637251) D175 D203 +error(0.003421241639577967189) D175 D203 ^ D178 +error(0.004007581078155113968) D175 D203 ^ D202 +error(0.001746012587198167822) D175 D203 ^ D202 ^ D178 +error(0.02606250389870726561) D176 D200 +error(0.002389270985273113726) D176 D200 ^ D173 +error(0.00654546687063310012) D177 D178 +error(0.0021024474767527058) D177 D178 ^ D150 L0 +error(0.01203764022217809065) D177 D178 ^ D174 L0 +error(0.0007246969784635964298) D177 D178 ^ D179 L0 +error(0.0005290423207049268833) D177 D178 ^ D179 L0 ^ D150 L0 +error(0.02738393697272551233) D177 D201 +error(0.004004257617406230957) D177 D201 ^ D174 L0 +error(0.01000000000000000021) D178 +error(0.002736244045764444407) D178 D201 +error(0.002855052799012060792) D178 D201 ^ D174 L0 +error(0.0006116163304378687384) D178 D201 ^ D203 L0 +error(0.0007069775710064596895) D178 D201 ^ D203 L0 ^ D174 L0 +error(0.02229227109480388241) D178 D202 +error(0.001481615400962180704) D178 D202 ^ D174 L0 +error(0.002922078673854252608) D178 D202 ^ D203 L0 +error(0.009906527088549655496) D178 ^ D179 L0 +error(0.0013622205925644421) D178 ^ D203 L0 +error(0.004149845774982054321) D179 D203 ^ D178 +error(0.01895412426906178255) D179 D203 +error(0.005000000000000000104) D179 L0 +error(0.005000000000000000104) D180 +error(0.01668747401411250705) D180 D184 +error(0.01827076257666529827) D180 D184 ^ D181 +error(0.02857365717892044674) D180 D204 +error(0.008187804202290056149) D180 D204 ^ D205 +error(0.006752054900691314455) D180 D208 +error(0.006349781933249819092) D180 D208 ^ D181 +error(0.004978707893828611571) D180 D208 ^ D205 +error(0.003764221099563926434) D180 D208 ^ D205 ^ D181 +error(0.00305811170313690121) D180 D209 +error(0.001355606463823049281) D180 D209 ^ D181 +error(0.002720072101049827822) D180 D209 ^ D181 D205 +error(0.0007162514653201519817) D180 D209 ^ D205 +error(0.005000000000000000104) D180 ^ D181 +error(0.006213397302591005048) D181 D205 ^ D180 +error(0.01000000000000000021) D181 +error(0.007614310746050743754) D181 D182 +error(0.0005954277109348562764) D181 D182 ^ D180 +error(0.000465636753644584143) D181 D182 ^ D184 D185 +error(0.0002796968619654203862) D181 D182 ^ D184 D209 +error(0.01582554105481599749) D181 D182 ^ D185 +error(0.005002346730345576947) D181 D182 ^ D185 D209 +error(0.002901359869863939615) D181 D182 ^ D209 +error(0.0005821292772265862199) D181 D182 ^ D209 ^ D180 +error(0.02094673066392089764) D181 D187 +error(0.01260591433803377043) D181 D187 ^ D184 D185 +error(0.04837432224380126128) D181 D205 +error(0.003553059407795153887) D181 D205 ^ D208 D209 +error(0.004155872962511489473) D181 D205 ^ D209 +error(0.003535743537937868341) D181 D210 +error(0.002372881073082702946) D181 D210 ^ D184 D208 +error(3.088814442772618024e-05) D181 D210 ^ D184 D209 +error(0.0002677743536514186166) D181 D210 ^ D208 D209 +error(0.002766432488590481534) D181 D211 +error(0.002003001371357753489) D181 D211 ^ D184 D185 +error(0.0007617751072712451808) D181 D211 ^ D184 D208 +error(0.001724437185270334552) D181 D211 ^ D184 D209 +error(0.001091467339713199239) D181 D211 ^ D185 D209 +error(0.00195910551946494333) D181 D211 ^ D208 D209 +error(0.01704609170648706262) D182 D188 +error(0.01603323914711612952) D182 D188 ^ D185 +error(0.006444335023303983563) D182 D205 +error(0.0006733172831601593735) D182 D205 ^ D180 +error(0.005862290075143809613) D182 D205 ^ D209 +error(0.0008136568950686870862) D182 D205 ^ D209 ^ D180 +error(0.02804448788546923255) D182 D206 +error(0.01224644515584789178) D182 D206 ^ D209 +error(0.002167760793218917112) D182 D211 +error(0.0006482439155634309039) D182 D211 ^ D184 D185 +error(0.0006554643296627914477) D182 D211 ^ D184 D209 +error(0.0001808182923138514173) D182 D211 ^ D185 +error(0.002038558843002732067) D182 D211 ^ D185 D209 +error(0.0001340785921504384238) D182 D211 ^ D209 +error(0.003575688005574470616) D182 D212 +error(0.004475310371346201757) D182 D212 ^ D185 +error(0.00345098355018136219) D182 D212 ^ D209 +error(0.001693218948738322736) D182 D212 ^ D209 ^ D185 +error(0.009232193128085404779) D183 D184 +error(0.0002630814526406159313) D183 D184 ^ D181 +error(0.009686902281069798351) D183 D184 ^ D186 +error(0.0002516825390100136859) D183 D184 ^ D186 D187 +error(0.002350509443893264785) D183 D184 ^ D186 D210 +error(0.0001924701327169168889) D183 D184 ^ D187 D210 +error(0.001328444822298451792) D183 D184 ^ D210 +error(0.0004422428033818157967) D183 D184 ^ D210 ^ D181 +error(0.01553238535686285622) D183 D190 +error(0.01442107373804212) D183 D190 ^ D186 +error(0.02321446919291771452) D183 D207 +error(0.003758964575596710975) D183 D207 ^ D210 +error(0.001583423248511523895) D183 D208 +error(0.0004350561070420648989) D183 D208 ^ D181 +error(0.002418582978257866924) D183 D208 ^ D210 +error(0.0002796298770619333766) D183 D208 ^ D210 ^ D181 +error(0.002780585570467565895) D183 D214 +error(0.003659131334418356651) D183 D214 ^ D186 +error(0.002445659219989861598) D183 D214 ^ D210 +error(0.001480500595323643509) D183 D214 ^ D210 ^ D186 +error(0.002342039754099378614) D183 D215 +error(0.0003971852223546843471) D183 D215 ^ D186 D187 +error(0.001695357924281432841) D183 D215 ^ D186 D210 +error(0.000109853332386578866) D183 D215 ^ D187 D210 +error(4.517129173657599629e-05) D183 D215 ^ D210 +error(0.009370177167621668649) D184 D185 +error(0.0013749192686105837) D184 D185 ^ D157 +error(0.0004326376275655316982) D184 D185 ^ D186 D187 +error(0.001729297765277910352) D184 D185 ^ D187 D211 +error(0.0008369239912465332564) D184 D185 ^ D188 D211 +error(0.01725430315521830557) D184 D191 +error(0.009937067068622049831) D184 D191 ^ D186 D187 +error(0.02800496972801020182) D184 D208 +error(0.008857345427632928175) D184 D208 ^ D181 +error(0.001330748570182143991) D184 D208 ^ D210 +error(0.002708890916997034985) D184 D208 ^ D210 D211 +error(0.004269470014870236155) D184 D209 +error(9.74753423978128047e-05) D184 D209 ^ D210 D211 +error(0.003795022050357953376) D184 D215 +error(0.002450806810346344965) D184 D215 ^ D186 D187 +error(0.001182325052329548159) D184 D215 ^ D186 D210 +error(0.001394230569165803022) D184 D215 ^ D187 D210 +error(0.001347851322040039988) D184 D215 ^ D187 D211 +error(0.00173532620606171189) D184 D215 ^ D210 D211 +error(0.003116053244494311654) D184 D216 +error(7.316842974601893705e-05) D184 D216 ^ D187 D188 +error(0.00015381139946745172) D184 D216 ^ D187 D210 +error(0.0008071141978608846294) D184 D216 ^ D187 D211 +error(0.0001061468001811654107) D184 D216 ^ D188 D211 +error(0.0004214225008490263334) D184 D216 ^ D210 D211 +error(0.01000000000000000021) D185 +error(0.0270222666017383116) D185 D192 +error(0.02417905793237870235) D185 D192 ^ D187 D188 +error(0.03102491946459741065) D185 D209 +error(0.002140803014291666959) D185 D209 ^ D211 D212 +error(0.005011204418027772993) D185 D216 +error(0.002409795170171074013) D185 D216 ^ D187 D188 +error(0.0004867120612278240106) D185 D216 ^ D187 D211 +error(0.001734557560692578373) D185 D216 ^ D188 D211 +error(0.0008310577286774427754) D185 D216 ^ D188 D212 +error(0.002876015875940871915) D185 D216 ^ D211 D212 +error(5.689899368434303708e-05) D185 D217 +error(0.0005376255601673666108) D185 D217 ^ D188 D211 +error(0.001860052998044929096) D185 D217 ^ D188 D212 +error(0.0003270350619594853282) D185 D217 ^ D211 D212 +error(0.01000000000000000021) D186 +error(0.00998951012393598653) D186 D187 +error(0.0002647118028759689896) D186 D187 ^ D190 D191 +error(0.0002437602896713224755) D186 D187 ^ D190 D215 +error(0.0003259292904997979664) D186 D187 ^ D191 D192 +error(0.002910193005919642101) D186 D187 ^ D191 D215 +error(0.01563311530723593412) D186 D195 +error(0.01148884923131972789) D186 D195 ^ D190 D191 +error(0.03402876169483597113) D186 D210 +error(0.00297341913608773151) D186 D210 ^ D214 D215 +error(0.00167198142382841866) D186 D218 +error(0.001978739641503692373) D186 D218 ^ D190 D214 +error(0.0003739016887504405208) D186 D218 ^ D190 D215 +error(0.0006191581992012207009) D186 D218 ^ D214 D215 +error(0.003564405145362673812) D186 D219 +error(0.002427865772048852337) D186 D219 ^ D190 D191 +error(0.002016980215619930579) D186 D219 ^ D190 D214 +error(0.001665163685732147384) D186 D219 ^ D190 D215 +error(0.001089534673102127496) D186 D219 ^ D191 D215 +error(0.002441047980058794978) D186 D219 ^ D214 D215 +error(0.0004010735829825645671) D186 ^ D214 L0 +error(0.0040421911780430652) D190 D214 ^ D186 +error(0.01013563020920371822) D187 D188 +error(0.0008314930570387067546) D187 D188 ^ D185 +error(0.0001530404613110457714) D187 D188 ^ D191 D192 +error(0.000607895799866905789) D187 D188 ^ D191 D216 +error(3.403628659066277234e-05) D187 D188 ^ D192 D193 +error(0.0025882004664708534) D187 D188 ^ D192 D216 +error(0.01727203508574649132) D187 D196 +error(0.0145277865377167175) D187 D196 ^ D191 D192 +error(0.004930101446126109246) D187 D210 +error(0.0002881881964098772803) D187 D210 ^ D215 D216 +error(0.04574271143269240114) D187 D211 +error(0.001860329697148833646) D187 D211 ^ D215 D216 +error(0.00255198772447796712) D187 D219 +error(0.0005047023561676590529) D187 D219 ^ D190 D191 +error(0.001452256159036316528) D187 D219 ^ D191 D215 +error(5.222076102721136015e-05) D187 D219 ^ D191 D216 +error(0.0009987913400580498199) D187 D219 ^ D215 D216 +error(0.001430194805650022039) D187 D220 +error(0.002007285104460634732) D187 D220 ^ D191 D192 +error(0.001224248109508729171) D187 D220 ^ D191 D215 +error(0.002303664480707598265) D187 D220 ^ D191 D216 +error(0.0009171454591137486075) D187 D220 ^ D192 D216 +error(0.002191714195832245807) D187 D220 ^ D215 D216 +error(0.009797724443923057011) D188 D189 +error(0.0001021472594512653998) D188 D189 ^ D192 D193 +error(0.0001210959338265430346) D188 D189 ^ D192 D217 +error(0.01190918523369760215) D188 D189 ^ D193 +error(0.005273755897734558329) D188 D189 ^ D193 D217 +error(0.00184597880693155897) D188 D189 ^ D217 +error(0.01377684914337177352) D188 D197 +error(0.01093440003708149623) D188 D197 ^ D192 D193 +error(0.003249664646197158047) D188 D211 +error(2.258206681107317873e-05) D188 D211 ^ D216 D217 +error(0.02265899218759278091) D188 D212 +error(0.004590199147543793691) D188 D212 ^ D185 +error(0.002645517561442980222) D188 D212 ^ D216 D217 +error(0.0005399062537493103456) D188 D212 ^ D217 +error(0.002277233782169691897) D188 D220 +error(0.0002528250109153119818) D188 D220 ^ D191 D192 +error(0.0006205257979712591916) D188 D220 ^ D191 D216 +error(0.001404758555723596139) D188 D220 ^ D192 D216 +error(0.0002405291802527288812) D188 D220 ^ D192 D217 +error(0.0003097319487677911579) D188 D220 ^ D216 D217 +error(0.001047705250796779949) D188 D221 +error(0.00237092510280944831) D188 D221 ^ D192 D193 +error(0.001037220928621594273) D188 D221 ^ D192 D216 +error(0.00238058383085898136) D188 D221 ^ D192 D217 +error(0.0008835768967079051526) D188 D221 ^ D193 D217 +error(0.002259774772269825763) D188 D221 ^ D216 D217 +error(0.01260811278973474753) D189 +error(0.00225151851890723325) D189 D212 +error(0.0001797993500064738813) D189 D212 ^ D185 +error(0.002356030447914673944) D189 D212 ^ D217 +error(0.0345566698397392208) D189 D213 +error(0.005003744614217759193) D189 D213 ^ D217 +error(0.001837583674123140394) D189 D221 +error(9.255458431562874132e-05) D189 D221 ^ D192 D193 +error(0.0002126721966588340058) D189 D221 ^ D192 D217 +error(0.002035990511446809058) D189 D221 ^ D193 D217 +error(0.02090970420602020902) D189 ^ D193 +error(0.0009042125990949610812) D189 ^ D217 +error(0.001560696983551172019) D189 ^ D217 ^ D193 +error(0.01374568531695860747) D190 D191 +error(0.0002954516562893196702) D190 D191 ^ D194 D195 +error(0.00158847535642978651) D190 D191 ^ D195 D219 +error(0.04904868400430456576) D190 D214 +error(0.003544968265632814693) D190 D214 ^ D218 D219 +error(0.003865628745054386969) D190 D215 +error(0.000441796954324594226) D190 D215 ^ D218 D219 +error(0.0009740040964997024285) D190 D222 +error(0.00188554410197714988) D190 D222 ^ D195 D219 +error(0.01000000000000000021) D190 L0 +error(0.01186879937024130915) D190 L0 ^ D194 +error(0.003675582362634155064) D194 D218 ^ D190 L0 +error(0.01735160188785484295) D191 D192 +error(0.0007088289629090005787) D191 D192 ^ D195 D196 +error(0.0005313038609727570695) D191 D192 ^ D196 D197 +error(0.002702669103548420697) D191 D192 ^ D196 D220 +error(0.0006166556002974491434) D191 D192 ^ D197 D220 +error(0.0207233958407102431) D191 D198 +error(0.02026670657223518177) D191 D198 ^ D195 D196 +error(0.02961831943462597469) D191 D215 +error(0.002972165594026740694) D191 D215 ^ D219 D220 +error(0.00414184937373599394) D191 D216 +error(0.00040167431689305317) D191 D216 ^ D219 D220 +error(0.005690305629853309802) D191 D222 +error(0.006400338574826603191) D191 D222 ^ D195 D196 +error(0.002210171177652492467) D191 D222 ^ D195 D219 +error(0.007612181774541293064) D191 D222 ^ D196 D219 +error(0.001786447785683612389) D191 D222 ^ D196 D220 +error(0.004060767403088009868) D191 D222 ^ D219 D220 +error(0.001749884553720177727) D191 D223 +error(0.0007133736782402601805) D191 D223 ^ D196 D197 +error(0.0005844947904700150375) D191 D223 ^ D196 D219 +error(0.0008217823092129306105) D191 D223 ^ D196 D220 +error(0.0003275095103629303275) D191 D223 ^ D197 D220 +error(0.0006123041623268492663) D191 D223 ^ D219 D220 +error(0.006835861022765376757) D192 D193 +error(0.0002649652178908865757) D192 D193 ^ D196 D197 +error(0.001842590021007301871) D192 D193 ^ D197 D221 +error(0.01360447555925056555) D192 D199 +error(0.01129163812096881624) D192 D199 ^ D196 D197 +error(0.02106229162894282872) D192 D216 +error(0.002751152448060949218) D192 D216 ^ D220 D221 +error(0.003538841843038994985) D192 D217 +error(0.0008757110100126239138) D192 D223 +error(0.002941122394742301787) D192 D223 ^ D196 D197 +error(0.001165932778592970644) D192 D223 ^ D196 D220 +error(0.003280475747202545207) D192 D223 ^ D197 D220 +error(0.001642146425221697624) D192 D223 ^ D197 D221 +error(0.002816897898481184048) D192 D223 ^ D220 D221 +error(0.0006886146142845198884) D192 D224 +error(0.0001236420909161301809) D192 D224 ^ D197 +error(0.000685689790586139266) D192 D224 ^ D197 D220 +error(0.001457910846507099421) D192 D224 ^ D197 D221 +error(0.0002590162334421474365) D192 D224 ^ D220 D221 +error(5.747153257964691372e-05) D192 D224 ^ D221 +error(0.01247992211153514663) D193 +error(0.01569289063977472726) D193 D200 +error(0.01852761195375728781) D193 D200 ^ D197 +error(0.02174588721229521807) D193 D217 +error(0.00218188050196639876) D193 D217 ^ D221 +error(0.003449213835088781998) D193 D224 +error(0.002681972083768658158) D193 D224 ^ D197 +error(0.003567239636822126542) D193 D224 ^ D221 +error(0.0009720917822013221739) D193 D224 ^ D221 ^ D197 +error(0.007324292691020587581) D194 +error(0.01419500512629780567) D194 D195 +error(0.004023252490778637079) D194 D195 ^ D166 L0 +error(0.01819963975774338549) D194 D195 ^ D190 L0 +error(0.0003570751402298309404) D194 D195 ^ D198 L0 +error(0.0001756962670230916869) D194 D195 ^ D198 L0 ^ D166 L0 +error(0.01809902708512096253) D194 D218 +error(0.0007070126030203428879) D194 ^ D162 ^ D166 L0 +error(0.0006367420184909965315) D194 ^ D162 ^ D190 L0 +error(0.0009194744081342942502) D194 ^ D190 L0 ^ D166 L0 +error(0.0157666913660978944) D195 D196 +error(0.0008063908322377350349) D195 D196 ^ D198 D199 +error(0.003973470958629069134) D195 D196 ^ D198 D222 +error(0.01398924460029779895) D195 D201 +error(0.01203288461110336473) D195 D201 ^ D198 L0 +error(0.004973740584631117755) D195 D218 +error(0.003083695718806104061) D195 D218 ^ D190 L0 +error(6.326914210115742673e-05) D195 D218 ^ D222 L0 +error(0.000437796100933523862) D195 D218 ^ D222 L0 ^ D190 L0 +error(0.02802096798889971291) D195 D219 +error(0.0009781054333567957074) D195 D219 ^ D190 L0 +error(0.004258064841452545435) D195 D219 ^ D222 L0 +error(0.002293241519674286358) D195 D225 +error(0.002083689327902756277) D195 D225 ^ D198 L0 +error(0.003184439299356970048) D195 D225 ^ D222 L0 +error(0.0003075964336023181544) D195 D225 ^ D222 L0 ^ D198 L0 +error(0.008748819907022298975) D196 D197 +error(0.000421573423618385281) D196 D197 ^ D198 D199 +error(0.0004454116616421199392) D196 D197 ^ D199 D200 +error(0.002746525552341930968) D196 D197 ^ D199 D223 +error(0.01349995621294126057) D196 D202 +error(0.01074350301251948692) D196 D202 ^ D198 D199 +error(0.007372542091817689894) D196 D219 +error(0.0007550883971604156709) D196 D219 ^ D222 D223 +error(0.02903602395795713831) D196 D220 +error(0.002102104693332725906) D196 D220 ^ D222 D223 +error(0.003169378669323305153) D196 D225 +error(0.001191557425971731836) D196 D225 ^ D198 D222 +error(0.0001597772101005079804) D196 D225 ^ D198 D223 +error(0.0001021827979209038615) D196 D225 ^ D198 L0 +error(0.0005511678242116416215) D196 D225 ^ D222 D223 +error(1.679354630858518888e-05) D196 D225 ^ D222 L0 +error(0.001533444865295702621) D196 D226 +error(0.001663960370674462397) D196 D226 ^ D198 D199 +error(0.0007716218076495109674) D196 D226 ^ D198 D222 +error(0.001303219383453746829) D196 D226 ^ D198 D223 +error(0.000774858462820291762) D196 D226 ^ D199 D223 +error(0.00202762776909865992) D196 D226 ^ D222 D223 +error(0.01000000000000000021) D197 +error(0.004375250986392631436) D197 D220 +error(0.0001996290527887550252) D197 D220 ^ D223 D224 +error(0.02025078136410074503) D197 D221 +error(0.001389942840017453947) D197 D221 ^ D223 D224 +error(0.001697427904974847281) D197 D226 +error(9.531024276690012293e-05) D197 D226 ^ D198 D199 +error(0.0002003070882208187711) D197 D226 ^ D198 D223 +error(0.001002593182003129989) D197 D226 ^ D199 D223 +error(0.0008256000395826743879) D197 ^ D165 ^ D169 +error(0.001338317341795720308) D197 ^ D165 ^ D193 +error(0.0006122748497196598685) D197 ^ D169 +error(0.0063226352583203747) D198 D199 +error(0.000372850945034607572) D198 D199 ^ D201 D202 +error(0.002265174227511792399) D198 D199 ^ D202 D226 +error(0.0003610448547890982083) D198 D199 ^ D226 +error(0.03561013233827770019) D198 D222 +error(0.004322700216861186627) D198 D222 ^ D225 D226 +error(0.003938494697766241337) D198 D223 +error(0.0005358008309723712214) D198 D223 ^ D225 D226 +error(0.002034052694461135468) D198 D227 +error(0.0001466308340950007473) D198 D227 ^ D202 +error(0.001920194442056039194) D198 D227 ^ D202 D226 +error(0.01000000000000000021) D198 L0 +error(0.008841081898479867529) D199 D200 +error(0.002157536244326195389) D199 D200 ^ D173 +error(0.01163473797751780198) D199 D200 ^ D197 +error(0.0007537756625630134995) D199 D200 ^ D202 +error(0.01724304488913697489) D199 D203 +error(0.01634315707910385593) D199 D203 ^ D202 +error(0.01912154204876750918) D199 D223 +error(0.001896228017575547591) D199 D223 ^ D197 +error(0.003907155462371127326) D199 D223 ^ D226 +error(0.00279557314330079092) D199 D224 +error(0.002620934694098134548) D199 D224 ^ D197 +error(0.0004013694757154773717) D199 D224 ^ D226 +error(0.0001537267977297909955) D199 D224 ^ D226 ^ D197 +error(0.003820638366809637251) D199 D227 +error(0.003421241639577967189) D199 D227 ^ D202 +error(0.004007581078155113968) D199 D227 ^ D226 +error(0.001746012587198167822) D199 D227 ^ D226 ^ D202 +error(0.02606250389870726561) D200 D224 +error(0.002389270985273113726) D200 D224 ^ D197 +error(0.00654546687063310012) D201 D202 +error(0.0021024474767527058) D201 D202 ^ D174 L0 +error(0.01203764022217809065) D201 D202 ^ D198 L0 +error(0.0007246969784635964298) D201 D202 ^ D203 L0 +error(0.0005290423207049268833) D201 D202 ^ D203 L0 ^ D174 L0 +error(0.02738393697272551233) D201 D225 +error(0.004004257617406230957) D201 D225 ^ D198 L0 +error(0.01000000000000000021) D202 +error(0.002736244045764444407) D202 D225 +error(0.002855052799012060792) D202 D225 ^ D198 L0 +error(0.0006116163304378687384) D202 D225 ^ D227 L0 +error(0.0007069775710064596895) D202 D225 ^ D227 L0 ^ D198 L0 +error(0.02229227109480388241) D202 D226 +error(0.001481615400962180704) D202 D226 ^ D198 L0 +error(0.002922078673854252608) D202 D226 ^ D227 L0 +error(0.009906527088549655496) D202 ^ D203 L0 +error(0.0013622205925644421) D202 ^ D227 L0 +error(0.004149845774982054321) D203 D227 ^ D202 +error(0.01895412426906178255) D203 D227 +error(0.005000000000000000104) D203 L0 +error(0.005000000000000000104) D204 +error(0.01668747401411250705) D204 D208 +error(0.01827076257666529827) D204 D208 ^ D205 +error(0.02857365717892044674) D204 D228 +error(0.008187804202290056149) D204 D228 ^ D229 +error(0.006752054900691314455) D204 D232 +error(0.006349781933249819092) D204 D232 ^ D205 +error(0.004978707893828611571) D204 D232 ^ D229 +error(0.003764221099563926434) D204 D232 ^ D229 ^ D205 +error(0.00305811170313690121) D204 D233 +error(0.001355606463823049281) D204 D233 ^ D205 +error(0.002720072101049827822) D204 D233 ^ D205 D229 +error(0.0007162514653201519817) D204 D233 ^ D229 +error(0.005000000000000000104) D204 ^ D205 +error(0.006213397302591005048) D205 D229 ^ D204 +error(0.01000000000000000021) D205 +error(0.007614310746050743754) D205 D206 +error(0.0005954277109348562764) D205 D206 ^ D204 +error(0.000465636753644584143) D205 D206 ^ D208 D209 +error(0.0002796968619654203862) D205 D206 ^ D208 D233 +error(0.01582554105481599749) D205 D206 ^ D209 +error(0.005002346730345576947) D205 D206 ^ D209 D233 +error(0.002901359869863939615) D205 D206 ^ D233 +error(0.0005821292772265862199) D205 D206 ^ D233 ^ D204 +error(0.02094673066392089764) D205 D211 +error(0.01260591433803377043) D205 D211 ^ D208 D209 +error(0.04837432224380126128) D205 D229 +error(0.003553059407795153887) D205 D229 ^ D232 D233 +error(0.004155872962511489473) D205 D229 ^ D233 +error(0.003535743537937868341) D205 D234 +error(0.002372881073082702946) D205 D234 ^ D208 D232 +error(3.088814442772618024e-05) D205 D234 ^ D208 D233 +error(0.0002677743536514186166) D205 D234 ^ D232 D233 +error(0.002766432488590481534) D205 D235 +error(0.002003001371357753489) D205 D235 ^ D208 D209 +error(0.0007617751072712451808) D205 D235 ^ D208 D232 +error(0.001724437185270334552) D205 D235 ^ D208 D233 +error(0.001091467339713199239) D205 D235 ^ D209 D233 +error(0.00195910551946494333) D205 D235 ^ D232 D233 +error(0.01704609170648706262) D206 D212 +error(0.01603323914711612952) D206 D212 ^ D209 +error(0.006444335023303983563) D206 D229 +error(0.0006733172831601593735) D206 D229 ^ D204 +error(0.005862290075143809613) D206 D229 ^ D233 +error(0.0008136568950686870862) D206 D229 ^ D233 ^ D204 +error(0.02804448788546923255) D206 D230 +error(0.01224644515584789178) D206 D230 ^ D233 +error(0.002167760793218917112) D206 D235 +error(0.0006482439155634309039) D206 D235 ^ D208 D209 +error(0.0006554643296627914477) D206 D235 ^ D208 D233 +error(0.0001808182923138514173) D206 D235 ^ D209 +error(0.002038558843002732067) D206 D235 ^ D209 D233 +error(0.0001340785921504384238) D206 D235 ^ D233 +error(0.003575688005574470616) D206 D236 +error(0.004475310371346201757) D206 D236 ^ D209 +error(0.00345098355018136219) D206 D236 ^ D233 +error(0.001693218948738322736) D206 D236 ^ D233 ^ D209 +error(0.009232193128085404779) D207 D208 +error(0.0002630814526406159313) D207 D208 ^ D205 +error(0.009686902281069798351) D207 D208 ^ D210 +error(0.0002516825390100136859) D207 D208 ^ D210 D211 +error(0.002350509443893264785) D207 D208 ^ D210 D234 +error(0.0001924701327169168889) D207 D208 ^ D211 D234 +error(0.001328444822298451792) D207 D208 ^ D234 +error(0.0004422428033818157967) D207 D208 ^ D234 ^ D205 +error(0.01553238535686285622) D207 D214 +error(0.01442107373804212) D207 D214 ^ D210 +error(0.02321446919291771452) D207 D231 +error(0.003758964575596710975) D207 D231 ^ D234 +error(0.001583423248511523895) D207 D232 +error(0.0004350561070420648989) D207 D232 ^ D205 +error(0.002418582978257866924) D207 D232 ^ D234 +error(0.0002796298770619333766) D207 D232 ^ D234 ^ D205 +error(0.002780585570467565895) D207 D238 +error(0.003659131334418356651) D207 D238 ^ D210 +error(0.002445659219989861598) D207 D238 ^ D234 +error(0.001480500595323643509) D207 D238 ^ D234 ^ D210 +error(0.002342039754099378614) D207 D239 +error(0.0003971852223546843471) D207 D239 ^ D210 D211 +error(0.001695357924281432841) D207 D239 ^ D210 D234 +error(0.000109853332386578866) D207 D239 ^ D211 D234 +error(4.517129173657599629e-05) D207 D239 ^ D234 +error(0.009370177167621668649) D208 D209 +error(0.0013749192686105837) D208 D209 ^ D181 +error(0.0004326376275655316982) D208 D209 ^ D210 D211 +error(0.001729297765277910352) D208 D209 ^ D211 D235 +error(0.0008369239912465332564) D208 D209 ^ D212 D235 +error(0.01725430315521830557) D208 D215 +error(0.009937067068622049831) D208 D215 ^ D210 D211 +error(0.02800496972801020182) D208 D232 +error(0.008857345427632928175) D208 D232 ^ D205 +error(0.001330748570182143991) D208 D232 ^ D234 +error(0.002708890916997034985) D208 D232 ^ D234 D235 +error(0.004269470014870236155) D208 D233 +error(9.74753423978128047e-05) D208 D233 ^ D234 D235 +error(0.003795022050357953376) D208 D239 +error(0.002450806810346344965) D208 D239 ^ D210 D211 +error(0.001182325052329548159) D208 D239 ^ D210 D234 +error(0.001394230569165803022) D208 D239 ^ D211 D234 +error(0.001347851322040039988) D208 D239 ^ D211 D235 +error(0.00173532620606171189) D208 D239 ^ D234 D235 +error(0.003116053244494311654) D208 D240 +error(7.316842974601893705e-05) D208 D240 ^ D211 D212 +error(0.00015381139946745172) D208 D240 ^ D211 D234 +error(0.0008071141978608846294) D208 D240 ^ D211 D235 +error(0.0001061468001811654107) D208 D240 ^ D212 D235 +error(0.0004214225008490263334) D208 D240 ^ D234 D235 +error(0.01000000000000000021) D209 +error(0.0270222666017383116) D209 D216 +error(0.02417905793237870235) D209 D216 ^ D211 D212 +error(0.03102491946459741065) D209 D233 +error(0.002140803014291666959) D209 D233 ^ D235 D236 +error(0.005011204418027772993) D209 D240 +error(0.002409795170171074013) D209 D240 ^ D211 D212 +error(0.0004867120612278240106) D209 D240 ^ D211 D235 +error(0.001734557560692578373) D209 D240 ^ D212 D235 +error(0.0008310577286774427754) D209 D240 ^ D212 D236 +error(0.002876015875940871915) D209 D240 ^ D235 D236 +error(5.689899368434303708e-05) D209 D241 +error(0.0005376255601673666108) D209 D241 ^ D212 D235 +error(0.001860052998044929096) D209 D241 ^ D212 D236 +error(0.0003270350619594853282) D209 D241 ^ D235 D236 +error(0.01000000000000000021) D210 +error(0.00998951012393598653) D210 D211 +error(0.0002647118028759689896) D210 D211 ^ D214 D215 +error(0.0002437602896713224755) D210 D211 ^ D214 D239 +error(0.0003259292904997979664) D210 D211 ^ D215 D216 +error(0.002910193005919642101) D210 D211 ^ D215 D239 +error(0.01563311530723593412) D210 D219 +error(0.01148884923131972789) D210 D219 ^ D214 D215 +error(0.03402876169483597113) D210 D234 +error(0.00297341913608773151) D210 D234 ^ D238 D239 +error(0.00167198142382841866) D210 D242 +error(0.001978739641503692373) D210 D242 ^ D214 D238 +error(0.0003739016887504405208) D210 D242 ^ D214 D239 +error(0.0006191581992012207009) D210 D242 ^ D238 D239 +error(0.003564405145362673812) D210 D243 +error(0.002427865772048852337) D210 D243 ^ D214 D215 +error(0.002016980215619930579) D210 D243 ^ D214 D238 +error(0.001665163685732147384) D210 D243 ^ D214 D239 +error(0.001089534673102127496) D210 D243 ^ D215 D239 +error(0.002441047980058794978) D210 D243 ^ D238 D239 +error(0.0004010735829825645671) D210 ^ D238 L0 +error(0.0040421911780430652) D214 D238 ^ D210 +error(0.01013563020920371822) D211 D212 +error(0.0008314930570387067546) D211 D212 ^ D209 +error(0.0001530404613110457714) D211 D212 ^ D215 D216 +error(0.000607895799866905789) D211 D212 ^ D215 D240 +error(3.403628659066277234e-05) D211 D212 ^ D216 D217 +error(0.0025882004664708534) D211 D212 ^ D216 D240 +error(0.01727203508574649132) D211 D220 +error(0.0145277865377167175) D211 D220 ^ D215 D216 +error(0.004930101446126109246) D211 D234 +error(0.0002881881964098772803) D211 D234 ^ D239 D240 +error(0.04574271143269240114) D211 D235 +error(0.001860329697148833646) D211 D235 ^ D239 D240 +error(0.00255198772447796712) D211 D243 +error(0.0005047023561676590529) D211 D243 ^ D214 D215 +error(0.001452256159036316528) D211 D243 ^ D215 D239 +error(5.222076102721136015e-05) D211 D243 ^ D215 D240 +error(0.0009987913400580498199) D211 D243 ^ D239 D240 +error(0.001430194805650022039) D211 D244 +error(0.002007285104460634732) D211 D244 ^ D215 D216 +error(0.001224248109508729171) D211 D244 ^ D215 D239 +error(0.002303664480707598265) D211 D244 ^ D215 D240 +error(0.0009171454591137486075) D211 D244 ^ D216 D240 +error(0.002191714195832245807) D211 D244 ^ D239 D240 +error(0.009797724443923057011) D212 D213 +error(0.0001021472594512653998) D212 D213 ^ D216 D217 +error(0.0001210959338265430346) D212 D213 ^ D216 D241 +error(0.01190918523369760215) D212 D213 ^ D217 +error(0.005273755897734558329) D212 D213 ^ D217 D241 +error(0.00184597880693155897) D212 D213 ^ D241 +error(0.01377684914337177352) D212 D221 +error(0.01093440003708149623) D212 D221 ^ D216 D217 +error(0.003249664646197158047) D212 D235 +error(2.258206681107317873e-05) D212 D235 ^ D240 D241 +error(0.02265899218759278091) D212 D236 +error(0.004590199147543793691) D212 D236 ^ D209 +error(0.002645517561442980222) D212 D236 ^ D240 D241 +error(0.0005399062537493103456) D212 D236 ^ D241 +error(0.002277233782169691897) D212 D244 +error(0.0002528250109153119818) D212 D244 ^ D215 D216 +error(0.0006205257979712591916) D212 D244 ^ D215 D240 +error(0.001404758555723596139) D212 D244 ^ D216 D240 +error(0.0002405291802527288812) D212 D244 ^ D216 D241 +error(0.0003097319487677911579) D212 D244 ^ D240 D241 +error(0.001047705250796779949) D212 D245 +error(0.00237092510280944831) D212 D245 ^ D216 D217 +error(0.001037220928621594273) D212 D245 ^ D216 D240 +error(0.00238058383085898136) D212 D245 ^ D216 D241 +error(0.0008835768967079051526) D212 D245 ^ D217 D241 +error(0.002259774772269825763) D212 D245 ^ D240 D241 +error(0.01260811278973474753) D213 +error(0.00225151851890723325) D213 D236 +error(0.0001797993500064738813) D213 D236 ^ D209 +error(0.002356030447914673944) D213 D236 ^ D241 +error(0.0345566698397392208) D213 D237 +error(0.005003744614217759193) D213 D237 ^ D241 +error(0.001837583674123140394) D213 D245 +error(9.255458431562874132e-05) D213 D245 ^ D216 D217 +error(0.0002126721966588340058) D213 D245 ^ D216 D241 +error(0.002035990511446809058) D213 D245 ^ D217 D241 +error(0.02090970420602020902) D213 ^ D217 +error(0.0009042125990949610812) D213 ^ D241 +error(0.001560696983551172019) D213 ^ D241 ^ D217 +error(0.01374568531695860747) D214 D215 +error(0.0002954516562893196702) D214 D215 ^ D218 D219 +error(0.00158847535642978651) D214 D215 ^ D219 D243 +error(0.04904868400430456576) D214 D238 +error(0.003544968265632814693) D214 D238 ^ D242 D243 +error(0.003865628745054386969) D214 D239 +error(0.000441796954324594226) D214 D239 ^ D242 D243 +error(0.0009740040964997024285) D214 D246 +error(0.00188554410197714988) D214 D246 ^ D219 D243 +error(0.01000000000000000021) D214 L0 +error(0.01186879937024130915) D214 L0 ^ D218 +error(0.003675582362634155064) D218 D242 ^ D214 L0 +error(0.01735160188785484295) D215 D216 +error(0.0007088289629090005787) D215 D216 ^ D219 D220 +error(0.0005313038609727570695) D215 D216 ^ D220 D221 +error(0.002702669103548420697) D215 D216 ^ D220 D244 +error(0.0006166556002974491434) D215 D216 ^ D221 D244 +error(0.0207233958407102431) D215 D222 +error(0.02026670657223518177) D215 D222 ^ D219 D220 +error(0.02961831943462597469) D215 D239 +error(0.002972165594026740694) D215 D239 ^ D243 D244 +error(0.00414184937373599394) D215 D240 +error(0.00040167431689305317) D215 D240 ^ D243 D244 +error(0.005690305629853309802) D215 D246 +error(0.006400338574826603191) D215 D246 ^ D219 D220 +error(0.002210171177652492467) D215 D246 ^ D219 D243 +error(0.007612181774541293064) D215 D246 ^ D220 D243 +error(0.001786447785683612389) D215 D246 ^ D220 D244 +error(0.004060767403088009868) D215 D246 ^ D243 D244 +error(0.001749884553720177727) D215 D247 +error(0.0007133736782402601805) D215 D247 ^ D220 D221 +error(0.0005844947904700150375) D215 D247 ^ D220 D243 +error(0.0008217823092129306105) D215 D247 ^ D220 D244 +error(0.0003275095103629303275) D215 D247 ^ D221 D244 +error(0.0006123041623268492663) D215 D247 ^ D243 D244 +error(0.006835861022765376757) D216 D217 +error(0.0002649652178908865757) D216 D217 ^ D220 D221 +error(0.001842590021007301871) D216 D217 ^ D221 D245 +error(0.01360447555925056555) D216 D223 +error(0.01129163812096881624) D216 D223 ^ D220 D221 +error(0.02106229162894282872) D216 D240 +error(0.002751152448060949218) D216 D240 ^ D244 D245 +error(0.003538841843038994985) D216 D241 +error(0.0008757110100126239138) D216 D247 +error(0.002941122394742301787) D216 D247 ^ D220 D221 +error(0.001165932778592970644) D216 D247 ^ D220 D244 +error(0.003280475747202545207) D216 D247 ^ D221 D244 +error(0.001642146425221697624) D216 D247 ^ D221 D245 +error(0.002816897898481184048) D216 D247 ^ D244 D245 +error(0.0006886146142845198884) D216 D248 +error(0.0001236420909161301809) D216 D248 ^ D221 +error(0.000685689790586139266) D216 D248 ^ D221 D244 +error(0.001457910846507099421) D216 D248 ^ D221 D245 +error(0.0002590162334421474365) D216 D248 ^ D244 D245 +error(5.747153257964691372e-05) D216 D248 ^ D245 +error(0.01247992211153514663) D217 +error(0.01569289063977472726) D217 D224 +error(0.01852761195375728781) D217 D224 ^ D221 +error(0.02174588721229521807) D217 D241 +error(0.00218188050196639876) D217 D241 ^ D245 +error(0.003449213835088781998) D217 D248 +error(0.002681972083768658158) D217 D248 ^ D221 +error(0.003567239636822126542) D217 D248 ^ D245 +error(0.0009720917822013221739) D217 D248 ^ D245 ^ D221 +error(0.007324292691020587581) D218 +error(0.01419500512629780567) D218 D219 +error(0.004023252490778637079) D218 D219 ^ D190 L0 +error(0.01819963975774338549) D218 D219 ^ D214 L0 +error(0.0003570751402298309404) D218 D219 ^ D222 L0 +error(0.0001756962670230916869) D218 D219 ^ D222 L0 ^ D190 L0 +error(0.01809902708512096253) D218 D242 +error(0.0007070126030203428879) D218 ^ D186 ^ D190 L0 +error(0.0006367420184909965315) D218 ^ D186 ^ D214 L0 +error(0.0009194744081342942502) D218 ^ D214 L0 ^ D190 L0 +error(0.0157666913660978944) D219 D220 +error(0.0008063908322377350349) D219 D220 ^ D222 D223 +error(0.003973470958629069134) D219 D220 ^ D222 D246 +error(0.01398924460029779895) D219 D225 +error(0.01203288461110336473) D219 D225 ^ D222 L0 +error(0.004973740584631117755) D219 D242 +error(0.003083695718806104061) D219 D242 ^ D214 L0 +error(6.326914210115742673e-05) D219 D242 ^ D246 L0 +error(0.000437796100933523862) D219 D242 ^ D246 L0 ^ D214 L0 +error(0.02802096798889971291) D219 D243 +error(0.0009781054333567957074) D219 D243 ^ D214 L0 +error(0.004258064841452545435) D219 D243 ^ D246 L0 +error(0.002293241519674286358) D219 D249 +error(0.002083689327902756277) D219 D249 ^ D222 L0 +error(0.003184439299356970048) D219 D249 ^ D246 L0 +error(0.0003075964336023181544) D219 D249 ^ D246 L0 ^ D222 L0 +error(0.008748819907022298975) D220 D221 +error(0.000421573423618385281) D220 D221 ^ D222 D223 +error(0.0004454116616421199392) D220 D221 ^ D223 D224 +error(0.002746525552341930968) D220 D221 ^ D223 D247 +error(0.01349995621294126057) D220 D226 +error(0.01074350301251948692) D220 D226 ^ D222 D223 +error(0.007372542091817689894) D220 D243 +error(0.0007550883971604156709) D220 D243 ^ D246 D247 +error(0.02903602395795713831) D220 D244 +error(0.002102104693332725906) D220 D244 ^ D246 D247 +error(0.003169378669323305153) D220 D249 +error(0.001191557425971731836) D220 D249 ^ D222 D246 +error(0.0001597772101005079804) D220 D249 ^ D222 D247 +error(0.0001021827979209038615) D220 D249 ^ D222 L0 +error(0.0005511678242116416215) D220 D249 ^ D246 D247 +error(1.679354630858518888e-05) D220 D249 ^ D246 L0 +error(0.001533444865295702621) D220 D250 +error(0.001663960370674462397) D220 D250 ^ D222 D223 +error(0.0007716218076495109674) D220 D250 ^ D222 D246 +error(0.001303219383453746829) D220 D250 ^ D222 D247 +error(0.000774858462820291762) D220 D250 ^ D223 D247 +error(0.00202762776909865992) D220 D250 ^ D246 D247 +error(0.01000000000000000021) D221 +error(0.004375250986392631436) D221 D244 +error(0.0001996290527887550252) D221 D244 ^ D247 D248 +error(0.02025078136410074503) D221 D245 +error(0.001389942840017453947) D221 D245 ^ D247 D248 +error(0.001697427904974847281) D221 D250 +error(9.531024276690012293e-05) D221 D250 ^ D222 D223 +error(0.0002003070882208187711) D221 D250 ^ D222 D247 +error(0.001002593182003129989) D221 D250 ^ D223 D247 +error(0.0008256000395826743879) D221 ^ D189 ^ D193 +error(0.001338317341795720308) D221 ^ D189 ^ D217 +error(0.0006122748497196598685) D221 ^ D193 +error(0.0063226352583203747) D222 D223 +error(0.000372850945034607572) D222 D223 ^ D225 D226 +error(0.002265174227511792399) D222 D223 ^ D226 D250 +error(0.0003610448547890982083) D222 D223 ^ D250 +error(0.03561013233827770019) D222 D246 +error(0.004322700216861186627) D222 D246 ^ D249 D250 +error(0.003938494697766241337) D222 D247 +error(0.0005358008309723712214) D222 D247 ^ D249 D250 +error(0.002034052694461135468) D222 D251 +error(0.0001466308340950007473) D222 D251 ^ D226 +error(0.001920194442056039194) D222 D251 ^ D226 D250 +error(0.01000000000000000021) D222 L0 +error(0.008841081898479867529) D223 D224 +error(0.002157536244326195389) D223 D224 ^ D197 +error(0.01163473797751780198) D223 D224 ^ D221 +error(0.0007537756625630134995) D223 D224 ^ D226 +error(0.01724304488913697489) D223 D227 +error(0.01634315707910385593) D223 D227 ^ D226 +error(0.01912154204876750918) D223 D247 +error(0.001896228017575547591) D223 D247 ^ D221 +error(0.003907155462371127326) D223 D247 ^ D250 +error(0.00279557314330079092) D223 D248 +error(0.002620934694098134548) D223 D248 ^ D221 +error(0.0004013694757154773717) D223 D248 ^ D250 +error(0.0001537267977297909955) D223 D248 ^ D250 ^ D221 +error(0.003820638366809637251) D223 D251 +error(0.003421241639577967189) D223 D251 ^ D226 +error(0.004007581078155113968) D223 D251 ^ D250 +error(0.001746012587198167822) D223 D251 ^ D250 ^ D226 +error(0.02606250389870726561) D224 D248 +error(0.002389270985273113726) D224 D248 ^ D221 +error(0.00654546687063310012) D225 D226 +error(0.0021024474767527058) D225 D226 ^ D198 L0 +error(0.01203764022217809065) D225 D226 ^ D222 L0 +error(0.0007246969784635964298) D225 D226 ^ D227 L0 +error(0.0005290423207049268833) D225 D226 ^ D227 L0 ^ D198 L0 +error(0.02738393697272551233) D225 D249 +error(0.004004257617406230957) D225 D249 ^ D222 L0 +error(0.01000000000000000021) D226 +error(0.002736244045764444407) D226 D249 +error(0.002855052799012060792) D226 D249 ^ D222 L0 +error(0.0006116163304378687384) D226 D249 ^ D251 L0 +error(0.0007069775710064596895) D226 D249 ^ D251 L0 ^ D222 L0 +error(0.02229227109480388241) D226 D250 +error(0.001481615400962180704) D226 D250 ^ D222 L0 +error(0.002922078673854252608) D226 D250 ^ D251 L0 +error(0.009906527088549655496) D226 ^ D227 L0 +error(0.0013622205925644421) D226 ^ D251 L0 +error(0.004149845774982054321) D227 D251 ^ D226 +error(0.01895412426906178255) D227 D251 +error(0.005000000000000000104) D227 L0 +error(0.005000000000000000104) D228 +error(0.01668747401411250705) D228 D232 +error(0.01827076257666529827) D228 D232 ^ D229 +error(0.02857365717892044674) D228 D252 +error(0.008187804202290056149) D228 D252 ^ D253 +error(0.006752054900691314455) D228 D256 +error(0.006349781933249819092) D228 D256 ^ D229 +error(0.004978707893828611571) D228 D256 ^ D253 +error(0.003764221099563926434) D228 D256 ^ D253 ^ D229 +error(0.00305811170313690121) D228 D257 +error(0.001355606463823049281) D228 D257 ^ D229 +error(0.002720072101049827822) D228 D257 ^ D229 D253 +error(0.0007162514653201519817) D228 D257 ^ D253 +error(0.005000000000000000104) D228 ^ D229 +error(0.006213397302591005048) D229 D253 ^ D228 +error(0.01000000000000000021) D229 +error(0.007614310746050743754) D229 D230 +error(0.0005954277109348562764) D229 D230 ^ D228 +error(0.000465636753644584143) D229 D230 ^ D232 D233 +error(0.0002796968619654203862) D229 D230 ^ D232 D257 +error(0.01582554105481599749) D229 D230 ^ D233 +error(0.005002346730345576947) D229 D230 ^ D233 D257 +error(0.002901359869863939615) D229 D230 ^ D257 +error(0.0005821292772265862199) D229 D230 ^ D257 ^ D228 +error(0.02094673066392089764) D229 D235 +error(0.01260591433803377043) D229 D235 ^ D232 D233 +error(0.04837432224380126128) D229 D253 +error(0.003553059407795153887) D229 D253 ^ D256 D257 +error(0.004155872962511489473) D229 D253 ^ D257 +error(0.003535743537937868341) D229 D258 +error(0.002372881073082702946) D229 D258 ^ D232 D256 +error(3.088814442772618024e-05) D229 D258 ^ D232 D257 +error(0.0002677743536514186166) D229 D258 ^ D256 D257 +error(0.002766432488590481534) D229 D259 +error(0.002003001371357753489) D229 D259 ^ D232 D233 +error(0.0007617751072712451808) D229 D259 ^ D232 D256 +error(0.001724437185270334552) D229 D259 ^ D232 D257 +error(0.001091467339713199239) D229 D259 ^ D233 D257 +error(0.00195910551946494333) D229 D259 ^ D256 D257 +error(0.01704609170648706262) D230 D236 +error(0.01603323914711612952) D230 D236 ^ D233 +error(0.006444335023303983563) D230 D253 +error(0.0006733172831601593735) D230 D253 ^ D228 +error(0.005862290075143809613) D230 D253 ^ D257 +error(0.0008136568950686870862) D230 D253 ^ D257 ^ D228 +error(0.02804448788546923255) D230 D254 +error(0.01224644515584789178) D230 D254 ^ D257 +error(0.002167760793218917112) D230 D259 +error(0.0006482439155634309039) D230 D259 ^ D232 D233 +error(0.0006554643296627914477) D230 D259 ^ D232 D257 +error(0.0001808182923138514173) D230 D259 ^ D233 +error(0.002038558843002732067) D230 D259 ^ D233 D257 +error(0.0001340785921504384238) D230 D259 ^ D257 +error(0.003575688005574470616) D230 D260 +error(0.004475310371346201757) D230 D260 ^ D233 +error(0.00345098355018136219) D230 D260 ^ D257 +error(0.001693218948738322736) D230 D260 ^ D257 ^ D233 +error(0.009232193128085404779) D231 D232 +error(0.0002630814526406159313) D231 D232 ^ D229 +error(0.009686902281069798351) D231 D232 ^ D234 +error(0.0002516825390100136859) D231 D232 ^ D234 D235 +error(0.002350509443893264785) D231 D232 ^ D234 D258 +error(0.0001924701327169168889) D231 D232 ^ D235 D258 +error(0.001328444822298451792) D231 D232 ^ D258 +error(0.0004422428033818157967) D231 D232 ^ D258 ^ D229 +error(0.01553238535686285622) D231 D238 +error(0.01442107373804212) D231 D238 ^ D234 +error(0.02321446919291771452) D231 D255 +error(0.003758964575596710975) D231 D255 ^ D258 +error(0.001583423248511523895) D231 D256 +error(0.0004350561070420648989) D231 D256 ^ D229 +error(0.002418582978257866924) D231 D256 ^ D258 +error(0.0002796298770619333766) D231 D256 ^ D258 ^ D229 +error(0.002780585570467565895) D231 D262 +error(0.003659131334418356651) D231 D262 ^ D234 +error(0.002445659219989861598) D231 D262 ^ D258 +error(0.001480500595323643509) D231 D262 ^ D258 ^ D234 +error(0.002342039754099378614) D231 D263 +error(0.0003971852223546843471) D231 D263 ^ D234 D235 +error(0.001695357924281432841) D231 D263 ^ D234 D258 +error(0.000109853332386578866) D231 D263 ^ D235 D258 +error(4.517129173657599629e-05) D231 D263 ^ D258 +error(0.009370177167621668649) D232 D233 +error(0.0013749192686105837) D232 D233 ^ D205 +error(0.0004326376275655316982) D232 D233 ^ D234 D235 +error(0.001729297765277910352) D232 D233 ^ D235 D259 +error(0.0008369239912465332564) D232 D233 ^ D236 D259 +error(0.01725430315521830557) D232 D239 +error(0.009937067068622049831) D232 D239 ^ D234 D235 +error(0.02800496972801020182) D232 D256 +error(0.008857345427632928175) D232 D256 ^ D229 +error(0.001330748570182143991) D232 D256 ^ D258 +error(0.002708890916997034985) D232 D256 ^ D258 D259 +error(0.004269470014870236155) D232 D257 +error(9.74753423978128047e-05) D232 D257 ^ D258 D259 +error(0.003795022050357953376) D232 D263 +error(0.002450806810346344965) D232 D263 ^ D234 D235 +error(0.001182325052329548159) D232 D263 ^ D234 D258 +error(0.001394230569165803022) D232 D263 ^ D235 D258 +error(0.001347851322040039988) D232 D263 ^ D235 D259 +error(0.00173532620606171189) D232 D263 ^ D258 D259 +error(0.003116053244494311654) D232 D264 +error(7.316842974601893705e-05) D232 D264 ^ D235 D236 +error(0.00015381139946745172) D232 D264 ^ D235 D258 +error(0.0008071141978608846294) D232 D264 ^ D235 D259 +error(0.0001061468001811654107) D232 D264 ^ D236 D259 +error(0.0004214225008490263334) D232 D264 ^ D258 D259 +error(0.01000000000000000021) D233 +error(0.0270222666017383116) D233 D240 +error(0.02417905793237870235) D233 D240 ^ D235 D236 +error(0.03102491946459741065) D233 D257 +error(0.002140803014291666959) D233 D257 ^ D259 D260 +error(0.005011204418027772993) D233 D264 +error(0.002409795170171074013) D233 D264 ^ D235 D236 +error(0.0004867120612278240106) D233 D264 ^ D235 D259 +error(0.001734557560692578373) D233 D264 ^ D236 D259 +error(0.0008310577286774427754) D233 D264 ^ D236 D260 +error(0.002876015875940871915) D233 D264 ^ D259 D260 +error(5.689899368434303708e-05) D233 D265 +error(0.0005376255601673666108) D233 D265 ^ D236 D259 +error(0.001860052998044929096) D233 D265 ^ D236 D260 +error(0.0003270350619594853282) D233 D265 ^ D259 D260 +error(0.01000000000000000021) D234 +error(0.00998951012393598653) D234 D235 +error(0.0002647118028759689896) D234 D235 ^ D238 D239 +error(0.0002437602896713224755) D234 D235 ^ D238 D263 +error(0.0003259292904997979664) D234 D235 ^ D239 D240 +error(0.002910193005919642101) D234 D235 ^ D239 D263 +error(0.01563311530723593412) D234 D243 +error(0.01148884923131972789) D234 D243 ^ D238 D239 +error(0.03402876169483597113) D234 D258 +error(0.00297341913608773151) D234 D258 ^ D262 D263 +error(0.00167198142382841866) D234 D266 +error(0.001978739641503692373) D234 D266 ^ D238 D262 +error(0.0003739016887504405208) D234 D266 ^ D238 D263 +error(0.0006191581992012207009) D234 D266 ^ D262 D263 +error(0.003564405145362673812) D234 D267 +error(0.002427865772048852337) D234 D267 ^ D238 D239 +error(0.002016980215619930579) D234 D267 ^ D238 D262 +error(0.001665163685732147384) D234 D267 ^ D238 D263 +error(0.001089534673102127496) D234 D267 ^ D239 D263 +error(0.002441047980058794978) D234 D267 ^ D262 D263 +error(0.0004010735829825645671) D234 ^ D262 L0 +error(0.0040421911780430652) D238 D262 ^ D234 +error(0.01013563020920371822) D235 D236 +error(0.0008314930570387067546) D235 D236 ^ D233 +error(0.0001530404613110457714) D235 D236 ^ D239 D240 +error(0.000607895799866905789) D235 D236 ^ D239 D264 +error(3.403628659066277234e-05) D235 D236 ^ D240 D241 +error(0.0025882004664708534) D235 D236 ^ D240 D264 +error(0.01727203508574649132) D235 D244 +error(0.0145277865377167175) D235 D244 ^ D239 D240 +error(0.004930101446126109246) D235 D258 +error(0.0002881881964098772803) D235 D258 ^ D263 D264 +error(0.04574271143269240114) D235 D259 +error(0.001860329697148833646) D235 D259 ^ D263 D264 +error(0.00255198772447796712) D235 D267 +error(0.0005047023561676590529) D235 D267 ^ D238 D239 +error(0.001452256159036316528) D235 D267 ^ D239 D263 +error(5.222076102721136015e-05) D235 D267 ^ D239 D264 +error(0.0009987913400580498199) D235 D267 ^ D263 D264 +error(0.001430194805650022039) D235 D268 +error(0.002007285104460634732) D235 D268 ^ D239 D240 +error(0.001224248109508729171) D235 D268 ^ D239 D263 +error(0.002303664480707598265) D235 D268 ^ D239 D264 +error(0.0009171454591137486075) D235 D268 ^ D240 D264 +error(0.002191714195832245807) D235 D268 ^ D263 D264 +error(0.009797724443923057011) D236 D237 +error(0.0001021472594512653998) D236 D237 ^ D240 D241 +error(0.0001210959338265430346) D236 D237 ^ D240 D265 +error(0.01190918523369760215) D236 D237 ^ D241 +error(0.005273755897734558329) D236 D237 ^ D241 D265 +error(0.00184597880693155897) D236 D237 ^ D265 +error(0.01377684914337177352) D236 D245 +error(0.01093440003708149623) D236 D245 ^ D240 D241 +error(0.003249664646197158047) D236 D259 +error(2.258206681107317873e-05) D236 D259 ^ D264 D265 +error(0.02265899218759278091) D236 D260 +error(0.004590199147543793691) D236 D260 ^ D233 +error(0.002645517561442980222) D236 D260 ^ D264 D265 +error(0.0005399062537493103456) D236 D260 ^ D265 +error(0.002277233782169691897) D236 D268 +error(0.0002528250109153119818) D236 D268 ^ D239 D240 +error(0.0006205257979712591916) D236 D268 ^ D239 D264 +error(0.001404758555723596139) D236 D268 ^ D240 D264 +error(0.0002405291802527288812) D236 D268 ^ D240 D265 +error(0.0003097319487677911579) D236 D268 ^ D264 D265 +error(0.001047705250796779949) D236 D269 +error(0.00237092510280944831) D236 D269 ^ D240 D241 +error(0.001037220928621594273) D236 D269 ^ D240 D264 +error(0.00238058383085898136) D236 D269 ^ D240 D265 +error(0.0008835768967079051526) D236 D269 ^ D241 D265 +error(0.002259774772269825763) D236 D269 ^ D264 D265 +error(0.01260811278973474753) D237 +error(0.00225151851890723325) D237 D260 +error(0.0001797993500064738813) D237 D260 ^ D233 +error(0.002356030447914673944) D237 D260 ^ D265 +error(0.0345566698397392208) D237 D261 +error(0.005003744614217759193) D237 D261 ^ D265 +error(0.001837583674123140394) D237 D269 +error(9.255458431562874132e-05) D237 D269 ^ D240 D241 +error(0.0002126721966588340058) D237 D269 ^ D240 D265 +error(0.002035990511446809058) D237 D269 ^ D241 D265 +error(0.02090970420602020902) D237 ^ D241 +error(0.0009042125990949610812) D237 ^ D265 +error(0.001560696983551172019) D237 ^ D265 ^ D241 +error(0.01374568531695860747) D238 D239 +error(0.0002954516562893196702) D238 D239 ^ D242 D243 +error(0.00158847535642978651) D238 D239 ^ D243 D267 +error(0.04904868400430456576) D238 D262 +error(0.003544968265632814693) D238 D262 ^ D266 D267 +error(0.003865628745054386969) D238 D263 +error(0.000441796954324594226) D238 D263 ^ D266 D267 +error(0.0009740040964997024285) D238 D270 +error(0.00188554410197714988) D238 D270 ^ D243 D267 +error(0.01000000000000000021) D238 L0 +error(0.01186879937024130915) D238 L0 ^ D242 +error(0.003675582362634155064) D242 D266 ^ D238 L0 +error(0.01735160188785484295) D239 D240 +error(0.0007088289629090005787) D239 D240 ^ D243 D244 +error(0.0005313038609727570695) D239 D240 ^ D244 D245 +error(0.002702669103548420697) D239 D240 ^ D244 D268 +error(0.0006166556002974491434) D239 D240 ^ D245 D268 +error(0.0207233958407102431) D239 D246 +error(0.02026670657223518177) D239 D246 ^ D243 D244 +error(0.02961831943462597469) D239 D263 +error(0.002972165594026740694) D239 D263 ^ D267 D268 +error(0.00414184937373599394) D239 D264 +error(0.00040167431689305317) D239 D264 ^ D267 D268 +error(0.005690305629853309802) D239 D270 +error(0.006400338574826603191) D239 D270 ^ D243 D244 +error(0.002210171177652492467) D239 D270 ^ D243 D267 +error(0.007612181774541293064) D239 D270 ^ D244 D267 +error(0.001786447785683612389) D239 D270 ^ D244 D268 +error(0.004060767403088009868) D239 D270 ^ D267 D268 +error(0.001749884553720177727) D239 D271 +error(0.0007133736782402601805) D239 D271 ^ D244 D245 +error(0.0005844947904700150375) D239 D271 ^ D244 D267 +error(0.0008217823092129306105) D239 D271 ^ D244 D268 +error(0.0003275095103629303275) D239 D271 ^ D245 D268 +error(0.0006123041623268492663) D239 D271 ^ D267 D268 +error(0.006835861022765376757) D240 D241 +error(0.0002649652178908865757) D240 D241 ^ D244 D245 +error(0.001842590021007301871) D240 D241 ^ D245 D269 +error(0.01360447555925056555) D240 D247 +error(0.01129163812096881624) D240 D247 ^ D244 D245 +error(0.02106229162894282872) D240 D264 +error(0.002751152448060949218) D240 D264 ^ D268 D269 +error(0.003538841843038994985) D240 D265 +error(0.0008757110100126239138) D240 D271 +error(0.002941122394742301787) D240 D271 ^ D244 D245 +error(0.001165932778592970644) D240 D271 ^ D244 D268 +error(0.003280475747202545207) D240 D271 ^ D245 D268 +error(0.001642146425221697624) D240 D271 ^ D245 D269 +error(0.002816897898481184048) D240 D271 ^ D268 D269 +error(0.0006886146142845198884) D240 D272 +error(0.0001236420909161301809) D240 D272 ^ D245 +error(0.000685689790586139266) D240 D272 ^ D245 D268 +error(0.001457910846507099421) D240 D272 ^ D245 D269 +error(0.0002590162334421474365) D240 D272 ^ D268 D269 +error(5.747153257964691372e-05) D240 D272 ^ D269 +error(0.01247992211153514663) D241 +error(0.01569289063977472726) D241 D248 +error(0.01852761195375728781) D241 D248 ^ D245 +error(0.02174588721229521807) D241 D265 +error(0.00218188050196639876) D241 D265 ^ D269 +error(0.003449213835088781998) D241 D272 +error(0.002681972083768658158) D241 D272 ^ D245 +error(0.003567239636822126542) D241 D272 ^ D269 +error(0.0009720917822013221739) D241 D272 ^ D269 ^ D245 +error(0.007324292691020587581) D242 +error(0.01419500512629780567) D242 D243 +error(0.004023252490778637079) D242 D243 ^ D214 L0 +error(0.01819963975774338549) D242 D243 ^ D238 L0 +error(0.0003570751402298309404) D242 D243 ^ D246 L0 +error(0.0001756962670230916869) D242 D243 ^ D246 L0 ^ D214 L0 +error(0.01809902708512096253) D242 D266 +error(0.0007070126030203428879) D242 ^ D210 ^ D214 L0 +error(0.0006367420184909965315) D242 ^ D210 ^ D238 L0 +error(0.0009194744081342942502) D242 ^ D238 L0 ^ D214 L0 +error(0.0157666913660978944) D243 D244 +error(0.0008063908322377350349) D243 D244 ^ D246 D247 +error(0.003973470958629069134) D243 D244 ^ D246 D270 +error(0.01398924460029779895) D243 D249 +error(0.01203288461110336473) D243 D249 ^ D246 L0 +error(0.004973740584631117755) D243 D266 +error(0.003083695718806104061) D243 D266 ^ D238 L0 +error(6.326914210115742673e-05) D243 D266 ^ D270 L0 +error(0.000437796100933523862) D243 D266 ^ D270 L0 ^ D238 L0 +error(0.02802096798889971291) D243 D267 +error(0.0009781054333567957074) D243 D267 ^ D238 L0 +error(0.004258064841452545435) D243 D267 ^ D270 L0 +error(0.002293241519674286358) D243 D273 +error(0.002083689327902756277) D243 D273 ^ D246 L0 +error(0.003184439299356970048) D243 D273 ^ D270 L0 +error(0.0003075964336023181544) D243 D273 ^ D270 L0 ^ D246 L0 +error(0.008748819907022298975) D244 D245 +error(0.000421573423618385281) D244 D245 ^ D246 D247 +error(0.0004454116616421199392) D244 D245 ^ D247 D248 +error(0.002746525552341930968) D244 D245 ^ D247 D271 +error(0.01349995621294126057) D244 D250 +error(0.01074350301251948692) D244 D250 ^ D246 D247 +error(0.007372542091817689894) D244 D267 +error(0.0007550883971604156709) D244 D267 ^ D270 D271 +error(0.02903602395795713831) D244 D268 +error(0.002102104693332725906) D244 D268 ^ D270 D271 +error(0.003169378669323305153) D244 D273 +error(0.001191557425971731836) D244 D273 ^ D246 D270 +error(0.0001597772101005079804) D244 D273 ^ D246 D271 +error(0.0001021827979209038615) D244 D273 ^ D246 L0 +error(0.0005511678242116416215) D244 D273 ^ D270 D271 +error(1.679354630858518888e-05) D244 D273 ^ D270 L0 +error(0.001533444865295702621) D244 D274 +error(0.001663960370674462397) D244 D274 ^ D246 D247 +error(0.0007716218076495109674) D244 D274 ^ D246 D270 +error(0.001303219383453746829) D244 D274 ^ D246 D271 +error(0.000774858462820291762) D244 D274 ^ D247 D271 +error(0.00202762776909865992) D244 D274 ^ D270 D271 +error(0.01000000000000000021) D245 +error(0.004375250986392631436) D245 D268 +error(0.0001996290527887550252) D245 D268 ^ D271 D272 +error(0.02025078136410074503) D245 D269 +error(0.001389942840017453947) D245 D269 ^ D271 D272 +error(0.001697427904974847281) D245 D274 +error(9.531024276690012293e-05) D245 D274 ^ D246 D247 +error(0.0002003070882208187711) D245 D274 ^ D246 D271 +error(0.001002593182003129989) D245 D274 ^ D247 D271 +error(0.0008256000395826743879) D245 ^ D213 ^ D217 +error(0.001338317341795720308) D245 ^ D213 ^ D241 +error(0.0006122748497196598685) D245 ^ D217 +error(0.0063226352583203747) D246 D247 +error(0.000372850945034607572) D246 D247 ^ D249 D250 +error(0.002265174227511792399) D246 D247 ^ D250 D274 +error(0.0003610448547890982083) D246 D247 ^ D274 +error(0.03561013233827770019) D246 D270 +error(0.004322700216861186627) D246 D270 ^ D273 D274 +error(0.003938494697766241337) D246 D271 +error(0.0005358008309723712214) D246 D271 ^ D273 D274 +error(0.002034052694461135468) D246 D275 +error(0.0001466308340950007473) D246 D275 ^ D250 +error(0.001920194442056039194) D246 D275 ^ D250 D274 +error(0.01000000000000000021) D246 L0 +error(0.008841081898479867529) D247 D248 +error(0.002157536244326195389) D247 D248 ^ D221 +error(0.01163473797751780198) D247 D248 ^ D245 +error(0.0007537756625630134995) D247 D248 ^ D250 +error(0.01724304488913697489) D247 D251 +error(0.01634315707910385593) D247 D251 ^ D250 +error(0.01912154204876750918) D247 D271 +error(0.001896228017575547591) D247 D271 ^ D245 +error(0.003907155462371127326) D247 D271 ^ D274 +error(0.00279557314330079092) D247 D272 +error(0.002620934694098134548) D247 D272 ^ D245 +error(0.0004013694757154773717) D247 D272 ^ D274 +error(0.0001537267977297909955) D247 D272 ^ D274 ^ D245 +error(0.003820638366809637251) D247 D275 +error(0.003421241639577967189) D247 D275 ^ D250 +error(0.004007581078155113968) D247 D275 ^ D274 +error(0.001746012587198167822) D247 D275 ^ D274 ^ D250 +error(0.02606250389870726561) D248 D272 +error(0.002389270985273113726) D248 D272 ^ D245 +error(0.00654546687063310012) D249 D250 +error(0.0021024474767527058) D249 D250 ^ D222 L0 +error(0.01203764022217809065) D249 D250 ^ D246 L0 +error(0.0007246969784635964298) D249 D250 ^ D251 L0 +error(0.0005290423207049268833) D249 D250 ^ D251 L0 ^ D222 L0 +error(0.02738393697272551233) D249 D273 +error(0.004004257617406230957) D249 D273 ^ D246 L0 +error(0.01000000000000000021) D250 +error(0.002736244045764444407) D250 D273 +error(0.002855052799012060792) D250 D273 ^ D246 L0 +error(0.0006116163304378687384) D250 D273 ^ D275 L0 +error(0.0007069775710064596895) D250 D273 ^ D275 L0 ^ D246 L0 +error(0.02229227109480388241) D250 D274 +error(0.001481615400962180704) D250 D274 ^ D246 L0 +error(0.002922078673854252608) D250 D274 ^ D275 L0 +error(0.009906527088549655496) D250 ^ D251 L0 +error(0.0013622205925644421) D250 ^ D275 L0 +error(0.004149845774982054321) D251 D275 ^ D250 +error(0.01895412426906178255) D251 D275 +error(0.005000000000000000104) D251 L0 +error(0.005000000000000000104) D252 +error(0.01668747401411250705) D252 D256 +error(0.01827076257666529827) D252 D256 ^ D253 +error(0.02857365717892044674) D252 D276 +error(0.008187804202290056149) D252 D276 ^ D277 +error(0.006752054900691314455) D252 D280 +error(0.006349781933249819092) D252 D280 ^ D253 +error(0.004978707893828611571) D252 D280 ^ D277 +error(0.003764221099563926434) D252 D280 ^ D277 ^ D253 +error(0.00305811170313690121) D252 D281 +error(0.001355606463823049281) D252 D281 ^ D253 +error(0.002720072101049827822) D252 D281 ^ D253 D277 +error(0.0007162514653201519817) D252 D281 ^ D277 +error(0.005000000000000000104) D252 ^ D253 +error(0.006213397302591005048) D253 D277 ^ D252 +error(0.01000000000000000021) D253 +error(0.007614310746050743754) D253 D254 +error(0.0005954277109348562764) D253 D254 ^ D252 +error(0.000465636753644584143) D253 D254 ^ D256 D257 +error(0.0002796968619654203862) D253 D254 ^ D256 D281 +error(0.01582554105481599749) D253 D254 ^ D257 +error(0.005002346730345576947) D253 D254 ^ D257 D281 +error(0.002901359869863939615) D253 D254 ^ D281 +error(0.0005821292772265862199) D253 D254 ^ D281 ^ D252 +error(0.02094673066392089764) D253 D259 +error(0.01260591433803377043) D253 D259 ^ D256 D257 +error(0.04837432224380126128) D253 D277 +error(0.003553059407795153887) D253 D277 ^ D280 D281 +error(0.004155872962511489473) D253 D277 ^ D281 +error(0.003535743537937868341) D253 D282 +error(0.002372881073082702946) D253 D282 ^ D256 D280 +error(3.088814442772618024e-05) D253 D282 ^ D256 D281 +error(0.0002677743536514186166) D253 D282 ^ D280 D281 +error(0.002766432488590481534) D253 D283 +error(0.002003001371357753489) D253 D283 ^ D256 D257 +error(0.0007617751072712451808) D253 D283 ^ D256 D280 +error(0.001724437185270334552) D253 D283 ^ D256 D281 +error(0.001091467339713199239) D253 D283 ^ D257 D281 +error(0.00195910551946494333) D253 D283 ^ D280 D281 +error(0.01704609170648706262) D254 D260 +error(0.01603323914711612952) D254 D260 ^ D257 +error(0.006444335023303983563) D254 D277 +error(0.0006733172831601593735) D254 D277 ^ D252 +error(0.005862290075143809613) D254 D277 ^ D281 +error(0.0008136568950686870862) D254 D277 ^ D281 ^ D252 +error(0.02804448788546923255) D254 D278 +error(0.01224644515584789178) D254 D278 ^ D281 +error(0.002167760793218917112) D254 D283 +error(0.0006482439155634309039) D254 D283 ^ D256 D257 +error(0.0006554643296627914477) D254 D283 ^ D256 D281 +error(0.0001808182923138514173) D254 D283 ^ D257 +error(0.002038558843002732067) D254 D283 ^ D257 D281 +error(0.0001340785921504384238) D254 D283 ^ D281 +error(0.003575688005574470616) D254 D284 +error(0.004475310371346201757) D254 D284 ^ D257 +error(0.00345098355018136219) D254 D284 ^ D281 +error(0.001693218948738322736) D254 D284 ^ D281 ^ D257 +error(0.009232193128085404779) D255 D256 +error(0.0002630814526406159313) D255 D256 ^ D253 +error(0.009686902281069798351) D255 D256 ^ D258 +error(0.0002516825390100136859) D255 D256 ^ D258 D259 +error(0.002350509443893264785) D255 D256 ^ D258 D282 +error(0.0001924701327169168889) D255 D256 ^ D259 D282 +error(0.001328444822298451792) D255 D256 ^ D282 +error(0.0004422428033818157967) D255 D256 ^ D282 ^ D253 +error(0.01553238535686285622) D255 D262 +error(0.01442107373804212) D255 D262 ^ D258 +error(0.02321446919291771452) D255 D279 +error(0.003758964575596710975) D255 D279 ^ D282 +error(0.001583423248511523895) D255 D280 +error(0.0004350561070420648989) D255 D280 ^ D253 +error(0.002418582978257866924) D255 D280 ^ D282 +error(0.0002796298770619333766) D255 D280 ^ D282 ^ D253 +error(0.002780585570467565895) D255 D286 +error(0.003659131334418356651) D255 D286 ^ D258 +error(0.002445659219989861598) D255 D286 ^ D282 +error(0.001480500595323643509) D255 D286 ^ D282 ^ D258 +error(0.002342039754099378614) D255 D287 +error(0.0003971852223546843471) D255 D287 ^ D258 D259 +error(0.001695357924281432841) D255 D287 ^ D258 D282 +error(0.000109853332386578866) D255 D287 ^ D259 D282 +error(4.517129173657599629e-05) D255 D287 ^ D282 +error(0.009370177167621668649) D256 D257 +error(0.0013749192686105837) D256 D257 ^ D229 +error(0.0004326376275655316982) D256 D257 ^ D258 D259 +error(0.001729297765277910352) D256 D257 ^ D259 D283 +error(0.0008369239912465332564) D256 D257 ^ D260 D283 +error(0.01725430315521830557) D256 D263 +error(0.009937067068622049831) D256 D263 ^ D258 D259 +error(0.02800496972801020182) D256 D280 +error(0.008857345427632928175) D256 D280 ^ D253 +error(0.001330748570182143991) D256 D280 ^ D282 +error(0.002708890916997034985) D256 D280 ^ D282 D283 +error(0.004269470014870236155) D256 D281 +error(9.74753423978128047e-05) D256 D281 ^ D282 D283 +error(0.003795022050357953376) D256 D287 +error(0.002450806810346344965) D256 D287 ^ D258 D259 +error(0.001182325052329548159) D256 D287 ^ D258 D282 +error(0.001394230569165803022) D256 D287 ^ D259 D282 +error(0.001347851322040039988) D256 D287 ^ D259 D283 +error(0.00173532620606171189) D256 D287 ^ D282 D283 +error(0.003116053244494311654) D256 D288 +error(7.316842974601893705e-05) D256 D288 ^ D259 D260 +error(0.00015381139946745172) D256 D288 ^ D259 D282 +error(0.0008071141978608846294) D256 D288 ^ D259 D283 +error(0.0001061468001811654107) D256 D288 ^ D260 D283 +error(0.0004214225008490263334) D256 D288 ^ D282 D283 +error(0.01000000000000000021) D257 +error(0.0270222666017383116) D257 D264 +error(0.02417905793237870235) D257 D264 ^ D259 D260 +error(0.03102491946459741065) D257 D281 +error(0.002140803014291666959) D257 D281 ^ D283 D284 +error(0.005011204418027772993) D257 D288 +error(0.002409795170171074013) D257 D288 ^ D259 D260 +error(0.0004867120612278240106) D257 D288 ^ D259 D283 +error(0.001734557560692578373) D257 D288 ^ D260 D283 +error(0.0008310577286774427754) D257 D288 ^ D260 D284 +error(0.002876015875940871915) D257 D288 ^ D283 D284 +error(5.689899368434303708e-05) D257 D289 +error(0.0005376255601673666108) D257 D289 ^ D260 D283 +error(0.001860052998044929096) D257 D289 ^ D260 D284 +error(0.0003270350619594853282) D257 D289 ^ D283 D284 +error(0.01000000000000000021) D258 +error(0.00998951012393598653) D258 D259 +error(0.0002647118028759689896) D258 D259 ^ D262 D263 +error(0.0002437602896713224755) D258 D259 ^ D262 D287 +error(0.0003259292904997979664) D258 D259 ^ D263 D264 +error(0.002910193005919642101) D258 D259 ^ D263 D287 +error(0.01563311530723593412) D258 D267 +error(0.01148884923131972789) D258 D267 ^ D262 D263 +error(0.03402876169483597113) D258 D282 +error(0.00297341913608773151) D258 D282 ^ D286 D287 +error(0.00167198142382841866) D258 D290 +error(0.001978739641503692373) D258 D290 ^ D262 D286 +error(0.0003739016887504405208) D258 D290 ^ D262 D287 +error(0.0006191581992012207009) D258 D290 ^ D286 D287 +error(0.003564405145362673812) D258 D291 +error(0.002427865772048852337) D258 D291 ^ D262 D263 +error(0.002016980215619930579) D258 D291 ^ D262 D286 +error(0.001665163685732147384) D258 D291 ^ D262 D287 +error(0.001089534673102127496) D258 D291 ^ D263 D287 +error(0.002441047980058794978) D258 D291 ^ D286 D287 +error(0.0004010735829825645671) D258 ^ D286 L0 +error(0.0040421911780430652) D262 D286 ^ D258 +error(0.01013563020920371822) D259 D260 +error(0.0008314930570387067546) D259 D260 ^ D257 +error(0.0001530404613110457714) D259 D260 ^ D263 D264 +error(0.000607895799866905789) D259 D260 ^ D263 D288 +error(3.403628659066277234e-05) D259 D260 ^ D264 D265 +error(0.0025882004664708534) D259 D260 ^ D264 D288 +error(0.01727203508574649132) D259 D268 +error(0.0145277865377167175) D259 D268 ^ D263 D264 +error(0.004930101446126109246) D259 D282 +error(0.0002881881964098772803) D259 D282 ^ D287 D288 +error(0.04574271143269240114) D259 D283 +error(0.001860329697148833646) D259 D283 ^ D287 D288 +error(0.00255198772447796712) D259 D291 +error(0.0005047023561676590529) D259 D291 ^ D262 D263 +error(0.001452256159036316528) D259 D291 ^ D263 D287 +error(5.222076102721136015e-05) D259 D291 ^ D263 D288 +error(0.0009987913400580498199) D259 D291 ^ D287 D288 +error(0.001430194805650022039) D259 D292 +error(0.002007285104460634732) D259 D292 ^ D263 D264 +error(0.001224248109508729171) D259 D292 ^ D263 D287 +error(0.002303664480707598265) D259 D292 ^ D263 D288 +error(0.0009171454591137486075) D259 D292 ^ D264 D288 +error(0.002191714195832245807) D259 D292 ^ D287 D288 +error(0.009797724443923057011) D260 D261 +error(0.0001021472594512653998) D260 D261 ^ D264 D265 +error(0.0001210959338265430346) D260 D261 ^ D264 D289 +error(0.01190918523369760215) D260 D261 ^ D265 +error(0.005273755897734558329) D260 D261 ^ D265 D289 +error(0.00184597880693155897) D260 D261 ^ D289 +error(0.01377684914337177352) D260 D269 +error(0.01093440003708149623) D260 D269 ^ D264 D265 +error(0.003249664646197158047) D260 D283 +error(2.258206681107317873e-05) D260 D283 ^ D288 D289 +error(0.02265899218759278091) D260 D284 +error(0.004590199147543793691) D260 D284 ^ D257 +error(0.002645517561442980222) D260 D284 ^ D288 D289 +error(0.0005399062537493103456) D260 D284 ^ D289 +error(0.002277233782169691897) D260 D292 +error(0.0002528250109153119818) D260 D292 ^ D263 D264 +error(0.0006205257979712591916) D260 D292 ^ D263 D288 +error(0.001404758555723596139) D260 D292 ^ D264 D288 +error(0.0002405291802527288812) D260 D292 ^ D264 D289 +error(0.0003097319487677911579) D260 D292 ^ D288 D289 +error(0.001047705250796779949) D260 D293 +error(0.00237092510280944831) D260 D293 ^ D264 D265 +error(0.001037220928621594273) D260 D293 ^ D264 D288 +error(0.00238058383085898136) D260 D293 ^ D264 D289 +error(0.0008835768967079051526) D260 D293 ^ D265 D289 +error(0.002259774772269825763) D260 D293 ^ D288 D289 +error(0.01260811278973474753) D261 +error(0.00225151851890723325) D261 D284 +error(0.0001797993500064738813) D261 D284 ^ D257 +error(0.002356030447914673944) D261 D284 ^ D289 +error(0.0345566698397392208) D261 D285 +error(0.005003744614217759193) D261 D285 ^ D289 +error(0.001837583674123140394) D261 D293 +error(9.255458431562874132e-05) D261 D293 ^ D264 D265 +error(0.0002126721966588340058) D261 D293 ^ D264 D289 +error(0.002035990511446809058) D261 D293 ^ D265 D289 +error(0.02090970420602020902) D261 ^ D265 +error(0.0009042125990949610812) D261 ^ D289 +error(0.001560696983551172019) D261 ^ D289 ^ D265 +error(0.01374568531695860747) D262 D263 +error(0.0002954516562893196702) D262 D263 ^ D266 D267 +error(0.00158847535642978651) D262 D263 ^ D267 D291 +error(0.04904868400430456576) D262 D286 +error(0.003544968265632814693) D262 D286 ^ D290 D291 +error(0.003865628745054386969) D262 D287 +error(0.000441796954324594226) D262 D287 ^ D290 D291 +error(0.0009740040964997024285) D262 D294 +error(0.00188554410197714988) D262 D294 ^ D267 D291 +error(0.01000000000000000021) D262 L0 +error(0.01186879937024130915) D262 L0 ^ D266 +error(0.003675582362634155064) D266 D290 ^ D262 L0 +error(0.01735160188785484295) D263 D264 +error(0.0007088289629090005787) D263 D264 ^ D267 D268 +error(0.0005313038609727570695) D263 D264 ^ D268 D269 +error(0.002702669103548420697) D263 D264 ^ D268 D292 +error(0.0006166556002974491434) D263 D264 ^ D269 D292 +error(0.0207233958407102431) D263 D270 +error(0.02026670657223518177) D263 D270 ^ D267 D268 +error(0.02961831943462597469) D263 D287 +error(0.002972165594026740694) D263 D287 ^ D291 D292 +error(0.00414184937373599394) D263 D288 +error(0.00040167431689305317) D263 D288 ^ D291 D292 +error(0.005690305629853309802) D263 D294 +error(0.006400338574826603191) D263 D294 ^ D267 D268 +error(0.002210171177652492467) D263 D294 ^ D267 D291 +error(0.007612181774541293064) D263 D294 ^ D268 D291 +error(0.001786447785683612389) D263 D294 ^ D268 D292 +error(0.004060767403088009868) D263 D294 ^ D291 D292 +error(0.001749884553720177727) D263 D295 +error(0.0007133736782402601805) D263 D295 ^ D268 D269 +error(0.0005844947904700150375) D263 D295 ^ D268 D291 +error(0.0008217823092129306105) D263 D295 ^ D268 D292 +error(0.0003275095103629303275) D263 D295 ^ D269 D292 +error(0.0006123041623268492663) D263 D295 ^ D291 D292 +error(0.006835861022765376757) D264 D265 +error(0.0002649652178908865757) D264 D265 ^ D268 D269 +error(0.001842590021007301871) D264 D265 ^ D269 D293 +error(0.01360447555925056555) D264 D271 +error(0.01129163812096881624) D264 D271 ^ D268 D269 +error(0.02106229162894282872) D264 D288 +error(0.002751152448060949218) D264 D288 ^ D292 D293 +error(0.003538841843038994985) D264 D289 +error(0.0008757110100126239138) D264 D295 +error(0.002941122394742301787) D264 D295 ^ D268 D269 +error(0.001165932778592970644) D264 D295 ^ D268 D292 +error(0.003280475747202545207) D264 D295 ^ D269 D292 +error(0.001642146425221697624) D264 D295 ^ D269 D293 +error(0.002816897898481184048) D264 D295 ^ D292 D293 +error(0.0006886146142845198884) D264 D296 +error(0.0001236420909161301809) D264 D296 ^ D269 +error(0.000685689790586139266) D264 D296 ^ D269 D292 +error(0.001457910846507099421) D264 D296 ^ D269 D293 +error(0.0002590162334421474365) D264 D296 ^ D292 D293 +error(5.747153257964691372e-05) D264 D296 ^ D293 +error(0.01247992211153514663) D265 +error(0.01569289063977472726) D265 D272 +error(0.01852761195375728781) D265 D272 ^ D269 +error(0.02174588721229521807) D265 D289 +error(0.00218188050196639876) D265 D289 ^ D293 +error(0.003449213835088781998) D265 D296 +error(0.002681972083768658158) D265 D296 ^ D269 +error(0.003567239636822126542) D265 D296 ^ D293 +error(0.0009720917822013221739) D265 D296 ^ D293 ^ D269 +error(0.007324292691020587581) D266 +error(0.01419500512629780567) D266 D267 +error(0.004023252490778637079) D266 D267 ^ D238 L0 +error(0.01819963975774338549) D266 D267 ^ D262 L0 +error(0.0003570751402298309404) D266 D267 ^ D270 L0 +error(0.0001756962670230916869) D266 D267 ^ D270 L0 ^ D238 L0 +error(0.01809902708512096253) D266 D290 +error(0.0007070126030203428879) D266 ^ D234 ^ D238 L0 +error(0.0006367420184909965315) D266 ^ D234 ^ D262 L0 +error(0.0009194744081342942502) D266 ^ D262 L0 ^ D238 L0 +error(0.0157666913660978944) D267 D268 +error(0.0008063908322377350349) D267 D268 ^ D270 D271 +error(0.003973470958629069134) D267 D268 ^ D270 D294 +error(0.01398924460029779895) D267 D273 +error(0.01203288461110336473) D267 D273 ^ D270 L0 +error(0.004973740584631117755) D267 D290 +error(0.003083695718806104061) D267 D290 ^ D262 L0 +error(6.326914210115742673e-05) D267 D290 ^ D294 L0 +error(0.000437796100933523862) D267 D290 ^ D294 L0 ^ D262 L0 +error(0.02802096798889971291) D267 D291 +error(0.0009781054333567957074) D267 D291 ^ D262 L0 +error(0.004258064841452545435) D267 D291 ^ D294 L0 +error(0.002293241519674286358) D267 D297 +error(0.002083689327902756277) D267 D297 ^ D270 L0 +error(0.003184439299356970048) D267 D297 ^ D294 L0 +error(0.0003075964336023181544) D267 D297 ^ D294 L0 ^ D270 L0 +error(0.008748819907022298975) D268 D269 +error(0.000421573423618385281) D268 D269 ^ D270 D271 +error(0.0004454116616421199392) D268 D269 ^ D271 D272 +error(0.002746525552341930968) D268 D269 ^ D271 D295 +error(0.01349995621294126057) D268 D274 +error(0.01074350301251948692) D268 D274 ^ D270 D271 +error(0.007372542091817689894) D268 D291 +error(0.0007550883971604156709) D268 D291 ^ D294 D295 +error(0.02903602395795713831) D268 D292 +error(0.002102104693332725906) D268 D292 ^ D294 D295 +error(0.003169378669323305153) D268 D297 +error(0.001191557425971731836) D268 D297 ^ D270 D294 +error(0.0001597772101005079804) D268 D297 ^ D270 D295 +error(0.0001021827979209038615) D268 D297 ^ D270 L0 +error(0.0005511678242116416215) D268 D297 ^ D294 D295 +error(1.679354630858518888e-05) D268 D297 ^ D294 L0 +error(0.001533444865295702621) D268 D298 +error(0.001663960370674462397) D268 D298 ^ D270 D271 +error(0.0007716218076495109674) D268 D298 ^ D270 D294 +error(0.001303219383453746829) D268 D298 ^ D270 D295 +error(0.000774858462820291762) D268 D298 ^ D271 D295 +error(0.00202762776909865992) D268 D298 ^ D294 D295 +error(0.01000000000000000021) D269 +error(0.004375250986392631436) D269 D292 +error(0.0001996290527887550252) D269 D292 ^ D295 D296 +error(0.02025078136410074503) D269 D293 +error(0.001389942840017453947) D269 D293 ^ D295 D296 +error(0.001697427904974847281) D269 D298 +error(9.531024276690012293e-05) D269 D298 ^ D270 D271 +error(0.0002003070882208187711) D269 D298 ^ D270 D295 +error(0.001002593182003129989) D269 D298 ^ D271 D295 +error(0.0008256000395826743879) D269 ^ D237 ^ D241 +error(0.001338317341795720308) D269 ^ D237 ^ D265 +error(0.0006122748497196598685) D269 ^ D241 +error(0.0063226352583203747) D270 D271 +error(0.000372850945034607572) D270 D271 ^ D273 D274 +error(0.002265174227511792399) D270 D271 ^ D274 D298 +error(0.0003610448547890982083) D270 D271 ^ D298 +error(0.03561013233827770019) D270 D294 +error(0.004322700216861186627) D270 D294 ^ D297 D298 +error(0.003938494697766241337) D270 D295 +error(0.0005358008309723712214) D270 D295 ^ D297 D298 +error(0.002034052694461135468) D270 D299 +error(0.0001466308340950007473) D270 D299 ^ D274 +error(0.001920194442056039194) D270 D299 ^ D274 D298 +error(0.01000000000000000021) D270 L0 +error(0.008841081898479867529) D271 D272 +error(0.002157536244326195389) D271 D272 ^ D245 +error(0.01163473797751780198) D271 D272 ^ D269 +error(0.0007537756625630134995) D271 D272 ^ D274 +error(0.01724304488913697489) D271 D275 +error(0.01634315707910385593) D271 D275 ^ D274 +error(0.01912154204876750918) D271 D295 +error(0.001896228017575547591) D271 D295 ^ D269 +error(0.003907155462371127326) D271 D295 ^ D298 +error(0.00279557314330079092) D271 D296 +error(0.002620934694098134548) D271 D296 ^ D269 +error(0.0004013694757154773717) D271 D296 ^ D298 +error(0.0001537267977297909955) D271 D296 ^ D298 ^ D269 +error(0.003820638366809637251) D271 D299 +error(0.003421241639577967189) D271 D299 ^ D274 +error(0.004007581078155113968) D271 D299 ^ D298 +error(0.001746012587198167822) D271 D299 ^ D298 ^ D274 +error(0.02606250389870726561) D272 D296 +error(0.002389270985273113726) D272 D296 ^ D269 +error(0.00654546687063310012) D273 D274 +error(0.0021024474767527058) D273 D274 ^ D246 L0 +error(0.01203764022217809065) D273 D274 ^ D270 L0 +error(0.0007246969784635964298) D273 D274 ^ D275 L0 +error(0.0005290423207049268833) D273 D274 ^ D275 L0 ^ D246 L0 +error(0.02738393697272551233) D273 D297 +error(0.004004257617406230957) D273 D297 ^ D270 L0 +error(0.01000000000000000021) D274 +error(0.002736244045764444407) D274 D297 +error(0.002855052799012060792) D274 D297 ^ D270 L0 +error(0.0006116163304378687384) D274 D297 ^ D299 L0 +error(0.0007069775710064596895) D274 D297 ^ D299 L0 ^ D270 L0 +error(0.02229227109480388241) D274 D298 +error(0.001481615400962180704) D274 D298 ^ D270 L0 +error(0.002922078673854252608) D274 D298 ^ D299 L0 +error(0.009906527088549655496) D274 ^ D275 L0 +error(0.0013622205925644421) D274 ^ D299 L0 +error(0.004149845774982054321) D275 D299 ^ D274 +error(0.01895412426906178255) D275 D299 +error(0.005000000000000000104) D275 L0 +error(0.005000000000000000104) D276 +error(0.01668747401411250705) D276 D280 +error(0.01827076257666529827) D276 D280 ^ D277 +error(0.02857365717892044674) D276 D300 +error(0.008187804202290056149) D276 D300 ^ D301 +error(0.006752054900691314455) D276 D304 +error(0.006349781933249819092) D276 D304 ^ D277 +error(0.004978707893828611571) D276 D304 ^ D301 +error(0.003764221099563926434) D276 D304 ^ D301 ^ D277 +error(0.00305811170313690121) D276 D305 +error(0.001355606463823049281) D276 D305 ^ D277 +error(0.002720072101049827822) D276 D305 ^ D277 D301 +error(0.0007162514653201519817) D276 D305 ^ D301 +error(0.005000000000000000104) D276 ^ D277 +error(0.006213397302591005048) D277 D301 ^ D276 +error(0.01000000000000000021) D277 +error(0.007614310746050743754) D277 D278 +error(0.0005954277109348562764) D277 D278 ^ D276 +error(0.000465636753644584143) D277 D278 ^ D280 D281 +error(0.0002796968619654203862) D277 D278 ^ D280 D305 +error(0.01582554105481599749) D277 D278 ^ D281 +error(0.005002346730345576947) D277 D278 ^ D281 D305 +error(0.002901359869863939615) D277 D278 ^ D305 +error(0.0005821292772265862199) D277 D278 ^ D305 ^ D276 +error(0.02094673066392089764) D277 D283 +error(0.01260591433803377043) D277 D283 ^ D280 D281 +error(0.04837432224380126128) D277 D301 +error(0.003553059407795153887) D277 D301 ^ D304 D305 +error(0.004155872962511489473) D277 D301 ^ D305 +error(0.003535743537937868341) D277 D306 +error(0.002372881073082702946) D277 D306 ^ D280 D304 +error(3.088814442772618024e-05) D277 D306 ^ D280 D305 +error(0.0002677743536514186166) D277 D306 ^ D304 D305 +error(0.002766432488590481534) D277 D307 +error(0.002003001371357753489) D277 D307 ^ D280 D281 +error(0.0007617751072712451808) D277 D307 ^ D280 D304 +error(0.001724437185270334552) D277 D307 ^ D280 D305 +error(0.001091467339713199239) D277 D307 ^ D281 D305 +error(0.00195910551946494333) D277 D307 ^ D304 D305 +error(0.01704609170648706262) D278 D284 +error(0.01603323914711612952) D278 D284 ^ D281 +error(0.006444335023303983563) D278 D301 +error(0.0006733172831601593735) D278 D301 ^ D276 +error(0.005862290075143809613) D278 D301 ^ D305 +error(0.0008136568950686870862) D278 D301 ^ D305 ^ D276 +error(0.02804448788546923255) D278 D302 +error(0.01224644515584789178) D278 D302 ^ D305 +error(0.002167760793218917112) D278 D307 +error(0.0006482439155634309039) D278 D307 ^ D280 D281 +error(0.0006554643296627914477) D278 D307 ^ D280 D305 +error(0.0001808182923138514173) D278 D307 ^ D281 +error(0.002038558843002732067) D278 D307 ^ D281 D305 +error(0.0001340785921504384238) D278 D307 ^ D305 +error(0.003575688005574470616) D278 D308 +error(0.004475310371346201757) D278 D308 ^ D281 +error(0.00345098355018136219) D278 D308 ^ D305 +error(0.001693218948738322736) D278 D308 ^ D305 ^ D281 +error(0.009232193128085404779) D279 D280 +error(0.0002630814526406159313) D279 D280 ^ D277 +error(0.009686902281069798351) D279 D280 ^ D282 +error(0.0002516825390100136859) D279 D280 ^ D282 D283 +error(0.002350509443893264785) D279 D280 ^ D282 D306 +error(0.0001924701327169168889) D279 D280 ^ D283 D306 +error(0.001328444822298451792) D279 D280 ^ D306 +error(0.0004422428033818157967) D279 D280 ^ D306 ^ D277 +error(0.01553238535686285622) D279 D286 +error(0.01442107373804212) D279 D286 ^ D282 +error(0.02321446919291771452) D279 D303 +error(0.003758964575596710975) D279 D303 ^ D306 +error(0.001583423248511523895) D279 D304 +error(0.0004350561070420648989) D279 D304 ^ D277 +error(0.002418582978257866924) D279 D304 ^ D306 +error(0.0002796298770619333766) D279 D304 ^ D306 ^ D277 +error(0.002780585570467565895) D279 D310 +error(0.003659131334418356651) D279 D310 ^ D282 +error(0.002445659219989861598) D279 D310 ^ D306 +error(0.001480500595323643509) D279 D310 ^ D306 ^ D282 +error(0.002342039754099378614) D279 D311 +error(0.0003971852223546843471) D279 D311 ^ D282 D283 +error(0.001695357924281432841) D279 D311 ^ D282 D306 +error(0.000109853332386578866) D279 D311 ^ D283 D306 +error(4.517129173657599629e-05) D279 D311 ^ D306 +error(0.009370177167621668649) D280 D281 +error(0.0013749192686105837) D280 D281 ^ D253 +error(0.0004326376275655316982) D280 D281 ^ D282 D283 +error(0.001729297765277910352) D280 D281 ^ D283 D307 +error(0.0008369239912465332564) D280 D281 ^ D284 D307 +error(0.01725430315521830557) D280 D287 +error(0.009937067068622049831) D280 D287 ^ D282 D283 +error(0.02800496972801020182) D280 D304 +error(0.008857345427632928175) D280 D304 ^ D277 +error(0.001330748570182143991) D280 D304 ^ D306 +error(0.002708890916997034985) D280 D304 ^ D306 D307 +error(0.004269470014870236155) D280 D305 +error(9.74753423978128047e-05) D280 D305 ^ D306 D307 +error(0.003795022050357953376) D280 D311 +error(0.002450806810346344965) D280 D311 ^ D282 D283 +error(0.001182325052329548159) D280 D311 ^ D282 D306 +error(0.001394230569165803022) D280 D311 ^ D283 D306 +error(0.001347851322040039988) D280 D311 ^ D283 D307 +error(0.00173532620606171189) D280 D311 ^ D306 D307 +error(0.003116053244494311654) D280 D312 +error(7.316842974601893705e-05) D280 D312 ^ D283 D284 +error(0.00015381139946745172) D280 D312 ^ D283 D306 +error(0.0008071141978608846294) D280 D312 ^ D283 D307 +error(0.0001061468001811654107) D280 D312 ^ D284 D307 +error(0.0004214225008490263334) D280 D312 ^ D306 D307 +error(0.01000000000000000021) D281 +error(0.0270222666017383116) D281 D288 +error(0.02417905793237870235) D281 D288 ^ D283 D284 +error(0.03102491946459741065) D281 D305 +error(0.002140803014291666959) D281 D305 ^ D307 D308 +error(0.005011204418027772993) D281 D312 +error(0.002409795170171074013) D281 D312 ^ D283 D284 +error(0.0004867120612278240106) D281 D312 ^ D283 D307 +error(0.001734557560692578373) D281 D312 ^ D284 D307 +error(0.0008310577286774427754) D281 D312 ^ D284 D308 +error(0.002876015875940871915) D281 D312 ^ D307 D308 +error(5.689899368434303708e-05) D281 D313 +error(0.0005376255601673666108) D281 D313 ^ D284 D307 +error(0.001860052998044929096) D281 D313 ^ D284 D308 +error(0.0003270350619594853282) D281 D313 ^ D307 D308 +error(0.01000000000000000021) D282 +error(0.00998951012393598653) D282 D283 +error(0.0002647118028759689896) D282 D283 ^ D286 D287 +error(0.0002437602896713224755) D282 D283 ^ D286 D311 +error(0.0003259292904997979664) D282 D283 ^ D287 D288 +error(0.002910193005919642101) D282 D283 ^ D287 D311 +error(0.01563311530723593412) D282 D291 +error(0.01148884923131972789) D282 D291 ^ D286 D287 +error(0.03402876169483597113) D282 D306 +error(0.00297341913608773151) D282 D306 ^ D310 D311 +error(0.00167198142382841866) D282 D314 +error(0.001978739641503692373) D282 D314 ^ D286 D310 +error(0.0003739016887504405208) D282 D314 ^ D286 D311 +error(0.0006191581992012207009) D282 D314 ^ D310 D311 +error(0.003564405145362673812) D282 D315 +error(0.002427865772048852337) D282 D315 ^ D286 D287 +error(0.002016980215619930579) D282 D315 ^ D286 D310 +error(0.001665163685732147384) D282 D315 ^ D286 D311 +error(0.001089534673102127496) D282 D315 ^ D287 D311 +error(0.002441047980058794978) D282 D315 ^ D310 D311 +error(0.0004010735829825645671) D282 ^ D310 L0 +error(0.0040421911780430652) D286 D310 ^ D282 +error(0.01013563020920371822) D283 D284 +error(0.0008314930570387067546) D283 D284 ^ D281 +error(0.0001530404613110457714) D283 D284 ^ D287 D288 +error(0.000607895799866905789) D283 D284 ^ D287 D312 +error(3.403628659066277234e-05) D283 D284 ^ D288 D289 +error(0.0025882004664708534) D283 D284 ^ D288 D312 +error(0.01727203508574649132) D283 D292 +error(0.0145277865377167175) D283 D292 ^ D287 D288 +error(0.004930101446126109246) D283 D306 +error(0.0002881881964098772803) D283 D306 ^ D311 D312 +error(0.04574271143269240114) D283 D307 +error(0.001860329697148833646) D283 D307 ^ D311 D312 +error(0.00255198772447796712) D283 D315 +error(0.0005047023561676590529) D283 D315 ^ D286 D287 +error(0.001452256159036316528) D283 D315 ^ D287 D311 +error(5.222076102721136015e-05) D283 D315 ^ D287 D312 +error(0.0009987913400580498199) D283 D315 ^ D311 D312 +error(0.001430194805650022039) D283 D316 +error(0.002007285104460634732) D283 D316 ^ D287 D288 +error(0.001224248109508729171) D283 D316 ^ D287 D311 +error(0.002303664480707598265) D283 D316 ^ D287 D312 +error(0.0009171454591137486075) D283 D316 ^ D288 D312 +error(0.002191714195832245807) D283 D316 ^ D311 D312 +error(0.009797724443923057011) D284 D285 +error(0.0001021472594512653998) D284 D285 ^ D288 D289 +error(0.0001210959338265430346) D284 D285 ^ D288 D313 +error(0.01190918523369760215) D284 D285 ^ D289 +error(0.005273755897734558329) D284 D285 ^ D289 D313 +error(0.00184597880693155897) D284 D285 ^ D313 +error(0.01377684914337177352) D284 D293 +error(0.01093440003708149623) D284 D293 ^ D288 D289 +error(0.003249664646197158047) D284 D307 +error(2.258206681107317873e-05) D284 D307 ^ D312 D313 +error(0.02265899218759278091) D284 D308 +error(0.004590199147543793691) D284 D308 ^ D281 +error(0.002645517561442980222) D284 D308 ^ D312 D313 +error(0.0005399062537493103456) D284 D308 ^ D313 +error(0.002277233782169691897) D284 D316 +error(0.0002528250109153119818) D284 D316 ^ D287 D288 +error(0.0006205257979712591916) D284 D316 ^ D287 D312 +error(0.001404758555723596139) D284 D316 ^ D288 D312 +error(0.0002405291802527288812) D284 D316 ^ D288 D313 +error(0.0003097319487677911579) D284 D316 ^ D312 D313 +error(0.001047705250796779949) D284 D317 +error(0.00237092510280944831) D284 D317 ^ D288 D289 +error(0.001037220928621594273) D284 D317 ^ D288 D312 +error(0.00238058383085898136) D284 D317 ^ D288 D313 +error(0.0008835768967079051526) D284 D317 ^ D289 D313 +error(0.002259774772269825763) D284 D317 ^ D312 D313 +error(0.01260811278973474753) D285 +error(0.00225151851890723325) D285 D308 +error(0.0001797993500064738813) D285 D308 ^ D281 +error(0.002356030447914673944) D285 D308 ^ D313 +error(0.0345566698397392208) D285 D309 +error(0.005003744614217759193) D285 D309 ^ D313 +error(0.001837583674123140394) D285 D317 +error(9.255458431562874132e-05) D285 D317 ^ D288 D289 +error(0.0002126721966588340058) D285 D317 ^ D288 D313 +error(0.002035990511446809058) D285 D317 ^ D289 D313 +error(0.02090970420602020902) D285 ^ D289 +error(0.0009042125990949610812) D285 ^ D313 +error(0.001560696983551172019) D285 ^ D313 ^ D289 +error(0.01374568531695860747) D286 D287 +error(0.0002954516562893196702) D286 D287 ^ D290 D291 +error(0.00158847535642978651) D286 D287 ^ D291 D315 +error(0.04904868400430456576) D286 D310 +error(0.003544968265632814693) D286 D310 ^ D314 D315 +error(0.003865628745054386969) D286 D311 +error(0.000441796954324594226) D286 D311 ^ D314 D315 +error(0.0009740040964997024285) D286 D318 +error(0.00188554410197714988) D286 D318 ^ D291 D315 +error(0.01000000000000000021) D286 L0 +error(0.01186879937024130915) D286 L0 ^ D290 +error(0.003675582362634155064) D290 D314 ^ D286 L0 +error(0.01735160188785484295) D287 D288 +error(0.0007088289629090005787) D287 D288 ^ D291 D292 +error(0.0005313038609727570695) D287 D288 ^ D292 D293 +error(0.002702669103548420697) D287 D288 ^ D292 D316 +error(0.0006166556002974491434) D287 D288 ^ D293 D316 +error(0.0207233958407102431) D287 D294 +error(0.02026670657223518177) D287 D294 ^ D291 D292 +error(0.02961831943462597469) D287 D311 +error(0.002972165594026740694) D287 D311 ^ D315 D316 +error(0.00414184937373599394) D287 D312 +error(0.00040167431689305317) D287 D312 ^ D315 D316 +error(0.005690305629853309802) D287 D318 +error(0.006400338574826603191) D287 D318 ^ D291 D292 +error(0.002210171177652492467) D287 D318 ^ D291 D315 +error(0.007612181774541293064) D287 D318 ^ D292 D315 +error(0.001786447785683612389) D287 D318 ^ D292 D316 +error(0.004060767403088009868) D287 D318 ^ D315 D316 +error(0.001749884553720177727) D287 D319 +error(0.0007133736782402601805) D287 D319 ^ D292 D293 +error(0.0005844947904700150375) D287 D319 ^ D292 D315 +error(0.0008217823092129306105) D287 D319 ^ D292 D316 +error(0.0003275095103629303275) D287 D319 ^ D293 D316 +error(0.0006123041623268492663) D287 D319 ^ D315 D316 +error(0.006835861022765376757) D288 D289 +error(0.0002649652178908865757) D288 D289 ^ D292 D293 +error(0.001842590021007301871) D288 D289 ^ D293 D317 +error(0.01360447555925056555) D288 D295 +error(0.01129163812096881624) D288 D295 ^ D292 D293 +error(0.02106229162894282872) D288 D312 +error(0.002751152448060949218) D288 D312 ^ D316 D317 +error(0.003538841843038994985) D288 D313 +error(0.0008757110100126239138) D288 D319 +error(0.002941122394742301787) D288 D319 ^ D292 D293 +error(0.001165932778592970644) D288 D319 ^ D292 D316 +error(0.003280475747202545207) D288 D319 ^ D293 D316 +error(0.001642146425221697624) D288 D319 ^ D293 D317 +error(0.002816897898481184048) D288 D319 ^ D316 D317 +error(0.0006886146142845198884) D288 D320 +error(0.0001236420909161301809) D288 D320 ^ D293 +error(0.000685689790586139266) D288 D320 ^ D293 D316 +error(0.001457910846507099421) D288 D320 ^ D293 D317 +error(0.0002590162334421474365) D288 D320 ^ D316 D317 +error(5.747153257964691372e-05) D288 D320 ^ D317 +error(0.01247992211153514663) D289 +error(0.01569289063977472726) D289 D296 +error(0.01852761195375728781) D289 D296 ^ D293 +error(0.02174588721229521807) D289 D313 +error(0.00218188050196639876) D289 D313 ^ D317 +error(0.003449213835088781998) D289 D320 +error(0.002681972083768658158) D289 D320 ^ D293 +error(0.003567239636822126542) D289 D320 ^ D317 +error(0.0009720917822013221739) D289 D320 ^ D317 ^ D293 +error(0.007324292691020587581) D290 +error(0.01419500512629780567) D290 D291 +error(0.004023252490778637079) D290 D291 ^ D262 L0 +error(0.01819963975774338549) D290 D291 ^ D286 L0 +error(0.0003570751402298309404) D290 D291 ^ D294 L0 +error(0.0001756962670230916869) D290 D291 ^ D294 L0 ^ D262 L0 +error(0.01809902708512096253) D290 D314 +error(0.0007070126030203428879) D290 ^ D258 ^ D262 L0 +error(0.0006367420184909965315) D290 ^ D258 ^ D286 L0 +error(0.0009194744081342942502) D290 ^ D286 L0 ^ D262 L0 +error(0.0157666913660978944) D291 D292 +error(0.0008063908322377350349) D291 D292 ^ D294 D295 +error(0.003973470958629069134) D291 D292 ^ D294 D318 +error(0.01398924460029779895) D291 D297 +error(0.01203288461110336473) D291 D297 ^ D294 L0 +error(0.004973740584631117755) D291 D314 +error(0.003083695718806104061) D291 D314 ^ D286 L0 +error(6.326914210115742673e-05) D291 D314 ^ D318 L0 +error(0.000437796100933523862) D291 D314 ^ D318 L0 ^ D286 L0 +error(0.02802096798889971291) D291 D315 +error(0.0009781054333567957074) D291 D315 ^ D286 L0 +error(0.004258064841452545435) D291 D315 ^ D318 L0 +error(0.002293241519674286358) D291 D321 +error(0.002083689327902756277) D291 D321 ^ D294 L0 +error(0.003184439299356970048) D291 D321 ^ D318 L0 +error(0.0003075964336023181544) D291 D321 ^ D318 L0 ^ D294 L0 +error(0.008748819907022298975) D292 D293 +error(0.000421573423618385281) D292 D293 ^ D294 D295 +error(0.0004454116616421199392) D292 D293 ^ D295 D296 +error(0.002746525552341930968) D292 D293 ^ D295 D319 +error(0.01349995621294126057) D292 D298 +error(0.01074350301251948692) D292 D298 ^ D294 D295 +error(0.007372542091817689894) D292 D315 +error(0.0007550883971604156709) D292 D315 ^ D318 D319 +error(0.02903602395795713831) D292 D316 +error(0.002102104693332725906) D292 D316 ^ D318 D319 +error(0.003169378669323305153) D292 D321 +error(0.001191557425971731836) D292 D321 ^ D294 D318 +error(0.0001597772101005079804) D292 D321 ^ D294 D319 +error(0.0001021827979209038615) D292 D321 ^ D294 L0 +error(0.0005511678242116416215) D292 D321 ^ D318 D319 +error(1.679354630858518888e-05) D292 D321 ^ D318 L0 +error(0.001533444865295702621) D292 D322 +error(0.001663960370674462397) D292 D322 ^ D294 D295 +error(0.0007716218076495109674) D292 D322 ^ D294 D318 +error(0.001303219383453746829) D292 D322 ^ D294 D319 +error(0.000774858462820291762) D292 D322 ^ D295 D319 +error(0.00202762776909865992) D292 D322 ^ D318 D319 +error(0.01000000000000000021) D293 +error(0.004375250986392631436) D293 D316 +error(0.0001996290527887550252) D293 D316 ^ D319 D320 +error(0.02025078136410074503) D293 D317 +error(0.001389942840017453947) D293 D317 ^ D319 D320 +error(0.001697427904974847281) D293 D322 +error(9.531024276690012293e-05) D293 D322 ^ D294 D295 +error(0.0002003070882208187711) D293 D322 ^ D294 D319 +error(0.001002593182003129989) D293 D322 ^ D295 D319 +error(0.0008256000395826743879) D293 ^ D261 ^ D265 +error(0.001338317341795720308) D293 ^ D261 ^ D289 +error(0.0006122748497196598685) D293 ^ D265 +error(0.0063226352583203747) D294 D295 +error(0.000372850945034607572) D294 D295 ^ D297 D298 +error(0.002265174227511792399) D294 D295 ^ D298 D322 +error(0.0003610448547890982083) D294 D295 ^ D322 +error(0.03561013233827770019) D294 D318 +error(0.004322700216861186627) D294 D318 ^ D321 D322 +error(0.003938494697766241337) D294 D319 +error(0.0005358008309723712214) D294 D319 ^ D321 D322 +error(0.002034052694461135468) D294 D323 +error(0.0001466308340950007473) D294 D323 ^ D298 +error(0.001920194442056039194) D294 D323 ^ D298 D322 +error(0.01000000000000000021) D294 L0 +error(0.008841081898479867529) D295 D296 +error(0.002157536244326195389) D295 D296 ^ D269 +error(0.01163473797751780198) D295 D296 ^ D293 +error(0.0007537756625630134995) D295 D296 ^ D298 +error(0.01724304488913697489) D295 D299 +error(0.01634315707910385593) D295 D299 ^ D298 +error(0.01912154204876750918) D295 D319 +error(0.001896228017575547591) D295 D319 ^ D293 +error(0.003907155462371127326) D295 D319 ^ D322 +error(0.00279557314330079092) D295 D320 +error(0.002620934694098134548) D295 D320 ^ D293 +error(0.0004013694757154773717) D295 D320 ^ D322 +error(0.0001537267977297909955) D295 D320 ^ D322 ^ D293 +error(0.003820638366809637251) D295 D323 +error(0.003421241639577967189) D295 D323 ^ D298 +error(0.004007581078155113968) D295 D323 ^ D322 +error(0.001746012587198167822) D295 D323 ^ D322 ^ D298 +error(0.02606250389870726561) D296 D320 +error(0.002389270985273113726) D296 D320 ^ D293 +error(0.00654546687063310012) D297 D298 +error(0.0021024474767527058) D297 D298 ^ D270 L0 +error(0.01203764022217809065) D297 D298 ^ D294 L0 +error(0.0007246969784635964298) D297 D298 ^ D299 L0 +error(0.0005290423207049268833) D297 D298 ^ D299 L0 ^ D270 L0 +error(0.02738393697272551233) D297 D321 +error(0.004004257617406230957) D297 D321 ^ D294 L0 +error(0.01000000000000000021) D298 +error(0.002736244045764444407) D298 D321 +error(0.002855052799012060792) D298 D321 ^ D294 L0 +error(0.0006116163304378687384) D298 D321 ^ D323 L0 +error(0.0007069775710064596895) D298 D321 ^ D323 L0 ^ D294 L0 +error(0.02229227109480388241) D298 D322 +error(0.001481615400962180704) D298 D322 ^ D294 L0 +error(0.002922078673854252608) D298 D322 ^ D323 L0 +error(0.009906527088549655496) D298 ^ D299 L0 +error(0.0013622205925644421) D298 ^ D323 L0 +error(0.004149845774982054321) D299 D323 ^ D298 +error(0.01895412426906178255) D299 D323 +error(0.005000000000000000104) D299 L0 +error(0.005000000000000000104) D300 +error(0.01668747401411250705) D300 D304 +error(0.01827076257666529827) D300 D304 ^ D301 +error(0.02857365717892044674) D300 D324 +error(0.008187804202290056149) D300 D324 ^ D325 +error(0.006752054900691314455) D300 D328 +error(0.006349781933249819092) D300 D328 ^ D301 +error(0.004978707893828611571) D300 D328 ^ D325 +error(0.003764221099563926434) D300 D328 ^ D325 ^ D301 +error(0.00305811170313690121) D300 D329 +error(0.001355606463823049281) D300 D329 ^ D301 +error(0.002720072101049827822) D300 D329 ^ D301 D325 +error(0.0007162514653201519817) D300 D329 ^ D325 +error(0.005000000000000000104) D300 ^ D301 +error(0.006213397302591005048) D301 D325 ^ D300 +error(0.01000000000000000021) D301 +error(0.007614310746050743754) D301 D302 +error(0.0005954277109348562764) D301 D302 ^ D300 +error(0.000465636753644584143) D301 D302 ^ D304 D305 +error(0.0002796968619654203862) D301 D302 ^ D304 D329 +error(0.01582554105481599749) D301 D302 ^ D305 +error(0.005002346730345576947) D301 D302 ^ D305 D329 +error(0.002901359869863939615) D301 D302 ^ D329 +error(0.0005821292772265862199) D301 D302 ^ D329 ^ D300 +error(0.02094673066392089764) D301 D307 +error(0.01260591433803377043) D301 D307 ^ D304 D305 +error(0.04837432224380126128) D301 D325 +error(0.003553059407795153887) D301 D325 ^ D328 D329 +error(0.004155872962511489473) D301 D325 ^ D329 +error(0.003535743537937868341) D301 D330 +error(0.002372881073082702946) D301 D330 ^ D304 D328 +error(3.088814442772618024e-05) D301 D330 ^ D304 D329 +error(0.0002677743536514186166) D301 D330 ^ D328 D329 +error(0.002766432488590481534) D301 D331 +error(0.002003001371357753489) D301 D331 ^ D304 D305 +error(0.0007617751072712451808) D301 D331 ^ D304 D328 +error(0.001724437185270334552) D301 D331 ^ D304 D329 +error(0.001091467339713199239) D301 D331 ^ D305 D329 +error(0.00195910551946494333) D301 D331 ^ D328 D329 +error(0.01704609170648706262) D302 D308 +error(0.01603323914711612952) D302 D308 ^ D305 +error(0.006444335023303983563) D302 D325 +error(0.0006733172831601593735) D302 D325 ^ D300 +error(0.005862290075143809613) D302 D325 ^ D329 +error(0.0008136568950686870862) D302 D325 ^ D329 ^ D300 +error(0.02804448788546923255) D302 D326 +error(0.01224644515584789178) D302 D326 ^ D329 +error(0.002167760793218917112) D302 D331 +error(0.0006482439155634309039) D302 D331 ^ D304 D305 +error(0.0006554643296627914477) D302 D331 ^ D304 D329 +error(0.0001808182923138514173) D302 D331 ^ D305 +error(0.002038558843002732067) D302 D331 ^ D305 D329 +error(0.0001340785921504384238) D302 D331 ^ D329 +error(0.003575688005574470616) D302 D332 +error(0.004475310371346201757) D302 D332 ^ D305 +error(0.00345098355018136219) D302 D332 ^ D329 +error(0.001693218948738322736) D302 D332 ^ D329 ^ D305 +error(0.009232193128085404779) D303 D304 +error(0.0002630814526406159313) D303 D304 ^ D301 +error(0.009686902281069798351) D303 D304 ^ D306 +error(0.0002516825390100136859) D303 D304 ^ D306 D307 +error(0.002350509443893264785) D303 D304 ^ D306 D330 +error(0.0001924701327169168889) D303 D304 ^ D307 D330 +error(0.001328444822298451792) D303 D304 ^ D330 +error(0.0004422428033818157967) D303 D304 ^ D330 ^ D301 +error(0.01553238535686285622) D303 D310 +error(0.01442107373804212) D303 D310 ^ D306 +error(0.02321446919291771452) D303 D327 +error(0.003758964575596710975) D303 D327 ^ D330 +error(0.001583423248511523895) D303 D328 +error(0.0004350561070420648989) D303 D328 ^ D301 +error(0.002418582978257866924) D303 D328 ^ D330 +error(0.0002796298770619333766) D303 D328 ^ D330 ^ D301 +error(0.002780585570467565895) D303 D334 +error(0.003659131334418356651) D303 D334 ^ D306 +error(0.002445659219989861598) D303 D334 ^ D330 +error(0.001480500595323643509) D303 D334 ^ D330 ^ D306 +error(0.002342039754099378614) D303 D335 +error(0.0003971852223546843471) D303 D335 ^ D306 D307 +error(0.001695357924281432841) D303 D335 ^ D306 D330 +error(0.000109853332386578866) D303 D335 ^ D307 D330 +error(4.517129173657599629e-05) D303 D335 ^ D330 +error(0.009370177167621668649) D304 D305 +error(0.0013749192686105837) D304 D305 ^ D277 +error(0.0004326376275655316982) D304 D305 ^ D306 D307 +error(0.001729297765277910352) D304 D305 ^ D307 D331 +error(0.0008369239912465332564) D304 D305 ^ D308 D331 +error(0.01725430315521830557) D304 D311 +error(0.009937067068622049831) D304 D311 ^ D306 D307 +error(0.02800496972801020182) D304 D328 +error(0.008857345427632928175) D304 D328 ^ D301 +error(0.001330748570182143991) D304 D328 ^ D330 +error(0.002708890916997034985) D304 D328 ^ D330 D331 +error(0.004269470014870236155) D304 D329 +error(9.74753423978128047e-05) D304 D329 ^ D330 D331 +error(0.003795022050357953376) D304 D335 +error(0.002450806810346344965) D304 D335 ^ D306 D307 +error(0.001182325052329548159) D304 D335 ^ D306 D330 +error(0.001394230569165803022) D304 D335 ^ D307 D330 +error(0.001347851322040039988) D304 D335 ^ D307 D331 +error(0.00173532620606171189) D304 D335 ^ D330 D331 +error(0.003116053244494311654) D304 D336 +error(7.316842974601893705e-05) D304 D336 ^ D307 D308 +error(0.00015381139946745172) D304 D336 ^ D307 D330 +error(0.0008071141978608846294) D304 D336 ^ D307 D331 +error(0.0001061468001811654107) D304 D336 ^ D308 D331 +error(0.0004214225008490263334) D304 D336 ^ D330 D331 +error(0.01000000000000000021) D305 +error(0.0270222666017383116) D305 D312 +error(0.02417905793237870235) D305 D312 ^ D307 D308 +error(0.03102491946459741065) D305 D329 +error(0.002140803014291666959) D305 D329 ^ D331 D332 +error(0.005011204418027772993) D305 D336 +error(0.002409795170171074013) D305 D336 ^ D307 D308 +error(0.0004867120612278240106) D305 D336 ^ D307 D331 +error(0.001734557560692578373) D305 D336 ^ D308 D331 +error(0.0008310577286774427754) D305 D336 ^ D308 D332 +error(0.002876015875940871915) D305 D336 ^ D331 D332 +error(5.689899368434303708e-05) D305 D337 +error(0.0005376255601673666108) D305 D337 ^ D308 D331 +error(0.001860052998044929096) D305 D337 ^ D308 D332 +error(0.0003270350619594853282) D305 D337 ^ D331 D332 +error(0.01000000000000000021) D306 +error(0.00998951012393598653) D306 D307 +error(0.0002647118028759689896) D306 D307 ^ D310 D311 +error(0.0002437602896713224755) D306 D307 ^ D310 D335 +error(0.0003259292904997979664) D306 D307 ^ D311 D312 +error(0.002910193005919642101) D306 D307 ^ D311 D335 +error(0.01563311530723593412) D306 D315 +error(0.01148884923131972789) D306 D315 ^ D310 D311 +error(0.03402876169483597113) D306 D330 +error(0.00297341913608773151) D306 D330 ^ D334 D335 +error(0.00167198142382841866) D306 D338 +error(0.001978739641503692373) D306 D338 ^ D310 D334 +error(0.0003739016887504405208) D306 D338 ^ D310 D335 +error(0.0006191581992012207009) D306 D338 ^ D334 D335 +error(0.003564405145362673812) D306 D339 +error(0.002427865772048852337) D306 D339 ^ D310 D311 +error(0.002016980215619930579) D306 D339 ^ D310 D334 +error(0.001665163685732147384) D306 D339 ^ D310 D335 +error(0.001089534673102127496) D306 D339 ^ D311 D335 +error(0.002441047980058794978) D306 D339 ^ D334 D335 +error(0.0004010735829825645671) D306 ^ D334 L0 +error(0.0040421911780430652) D310 D334 ^ D306 +error(0.01013563020920371822) D307 D308 +error(0.0008314930570387067546) D307 D308 ^ D305 +error(0.0001530404613110457714) D307 D308 ^ D311 D312 +error(0.000607895799866905789) D307 D308 ^ D311 D336 +error(3.403628659066277234e-05) D307 D308 ^ D312 D313 +error(0.0025882004664708534) D307 D308 ^ D312 D336 +error(0.01727203508574649132) D307 D316 +error(0.0145277865377167175) D307 D316 ^ D311 D312 +error(0.004930101446126109246) D307 D330 +error(0.0002881881964098772803) D307 D330 ^ D335 D336 +error(0.04574271143269240114) D307 D331 +error(0.001860329697148833646) D307 D331 ^ D335 D336 +error(0.00255198772447796712) D307 D339 +error(0.0005047023561676590529) D307 D339 ^ D310 D311 +error(0.001452256159036316528) D307 D339 ^ D311 D335 +error(5.222076102721136015e-05) D307 D339 ^ D311 D336 +error(0.0009987913400580498199) D307 D339 ^ D335 D336 +error(0.001430194805650022039) D307 D340 +error(0.002007285104460634732) D307 D340 ^ D311 D312 +error(0.001224248109508729171) D307 D340 ^ D311 D335 +error(0.002303664480707598265) D307 D340 ^ D311 D336 +error(0.0009171454591137486075) D307 D340 ^ D312 D336 +error(0.002191714195832245807) D307 D340 ^ D335 D336 +error(0.009797724443923057011) D308 D309 +error(0.0001021472594512653998) D308 D309 ^ D312 D313 +error(0.0001210959338265430346) D308 D309 ^ D312 D337 +error(0.01190918523369760215) D308 D309 ^ D313 +error(0.005273755897734558329) D308 D309 ^ D313 D337 +error(0.00184597880693155897) D308 D309 ^ D337 +error(0.01377684914337177352) D308 D317 +error(0.01093440003708149623) D308 D317 ^ D312 D313 +error(0.003249664646197158047) D308 D331 +error(2.258206681107317873e-05) D308 D331 ^ D336 D337 +error(0.02265899218759278091) D308 D332 +error(0.004590199147543793691) D308 D332 ^ D305 +error(0.002645517561442980222) D308 D332 ^ D336 D337 +error(0.0005399062537493103456) D308 D332 ^ D337 +error(0.002277233782169691897) D308 D340 +error(0.0002528250109153119818) D308 D340 ^ D311 D312 +error(0.0006205257979712591916) D308 D340 ^ D311 D336 +error(0.001404758555723596139) D308 D340 ^ D312 D336 +error(0.0002405291802527288812) D308 D340 ^ D312 D337 +error(0.0003097319487677911579) D308 D340 ^ D336 D337 +error(0.001047705250796779949) D308 D341 +error(0.00237092510280944831) D308 D341 ^ D312 D313 +error(0.001037220928621594273) D308 D341 ^ D312 D336 +error(0.00238058383085898136) D308 D341 ^ D312 D337 +error(0.0008835768967079051526) D308 D341 ^ D313 D337 +error(0.002259774772269825763) D308 D341 ^ D336 D337 +error(0.01260811278973474753) D309 +error(0.00225151851890723325) D309 D332 +error(0.0001797993500064738813) D309 D332 ^ D305 +error(0.002356030447914673944) D309 D332 ^ D337 +error(0.0345566698397392208) D309 D333 +error(0.005003744614217759193) D309 D333 ^ D337 +error(0.001837583674123140394) D309 D341 +error(9.255458431562874132e-05) D309 D341 ^ D312 D313 +error(0.0002126721966588340058) D309 D341 ^ D312 D337 +error(0.002035990511446809058) D309 D341 ^ D313 D337 +error(0.02090970420602020902) D309 ^ D313 +error(0.0009042125990949610812) D309 ^ D337 +error(0.001560696983551172019) D309 ^ D337 ^ D313 +error(0.01374568531695860747) D310 D311 +error(0.0002954516562893196702) D310 D311 ^ D314 D315 +error(0.00158847535642978651) D310 D311 ^ D315 D339 +error(0.04904868400430456576) D310 D334 +error(0.003544968265632814693) D310 D334 ^ D338 D339 +error(0.003865628745054386969) D310 D335 +error(0.000441796954324594226) D310 D335 ^ D338 D339 +error(0.0009740040964997024285) D310 D342 +error(0.00188554410197714988) D310 D342 ^ D315 D339 +error(0.01000000000000000021) D310 L0 +error(0.01186879937024130915) D310 L0 ^ D314 +error(0.003675582362634155064) D314 D338 ^ D310 L0 +error(0.01735160188785484295) D311 D312 +error(0.0007088289629090005787) D311 D312 ^ D315 D316 +error(0.0005313038609727570695) D311 D312 ^ D316 D317 +error(0.002702669103548420697) D311 D312 ^ D316 D340 +error(0.0006166556002974491434) D311 D312 ^ D317 D340 +error(0.0207233958407102431) D311 D318 +error(0.02026670657223518177) D311 D318 ^ D315 D316 +error(0.02961831943462597469) D311 D335 +error(0.002972165594026740694) D311 D335 ^ D339 D340 +error(0.00414184937373599394) D311 D336 +error(0.00040167431689305317) D311 D336 ^ D339 D340 +error(0.005690305629853309802) D311 D342 +error(0.006400338574826603191) D311 D342 ^ D315 D316 +error(0.002210171177652492467) D311 D342 ^ D315 D339 +error(0.007612181774541293064) D311 D342 ^ D316 D339 +error(0.001786447785683612389) D311 D342 ^ D316 D340 +error(0.004060767403088009868) D311 D342 ^ D339 D340 +error(0.001749884553720177727) D311 D343 +error(0.0007133736782402601805) D311 D343 ^ D316 D317 +error(0.0005844947904700150375) D311 D343 ^ D316 D339 +error(0.0008217823092129306105) D311 D343 ^ D316 D340 +error(0.0003275095103629303275) D311 D343 ^ D317 D340 +error(0.0006123041623268492663) D311 D343 ^ D339 D340 +error(0.006835861022765376757) D312 D313 +error(0.0002649652178908865757) D312 D313 ^ D316 D317 +error(0.001842590021007301871) D312 D313 ^ D317 D341 +error(0.01360447555925056555) D312 D319 +error(0.01129163812096881624) D312 D319 ^ D316 D317 +error(0.02106229162894282872) D312 D336 +error(0.002751152448060949218) D312 D336 ^ D340 D341 +error(0.003538841843038994985) D312 D337 +error(0.0008757110100126239138) D312 D343 +error(0.002941122394742301787) D312 D343 ^ D316 D317 +error(0.001165932778592970644) D312 D343 ^ D316 D340 +error(0.003280475747202545207) D312 D343 ^ D317 D340 +error(0.001642146425221697624) D312 D343 ^ D317 D341 +error(0.002816897898481184048) D312 D343 ^ D340 D341 +error(0.0006886146142845198884) D312 D344 +error(0.0001236420909161301809) D312 D344 ^ D317 +error(0.000685689790586139266) D312 D344 ^ D317 D340 +error(0.001457910846507099421) D312 D344 ^ D317 D341 +error(0.0002590162334421474365) D312 D344 ^ D340 D341 +error(5.747153257964691372e-05) D312 D344 ^ D341 +error(0.01247992211153514663) D313 +error(0.01569289063977472726) D313 D320 +error(0.01852761195375728781) D313 D320 ^ D317 +error(0.02174588721229521807) D313 D337 +error(0.00218188050196639876) D313 D337 ^ D341 +error(0.003449213835088781998) D313 D344 +error(0.002681972083768658158) D313 D344 ^ D317 +error(0.003567239636822126542) D313 D344 ^ D341 +error(0.0009720917822013221739) D313 D344 ^ D341 ^ D317 +error(0.007324292691020587581) D314 +error(0.01419500512629780567) D314 D315 +error(0.004023252490778637079) D314 D315 ^ D286 L0 +error(0.01819963975774338549) D314 D315 ^ D310 L0 +error(0.0003570751402298309404) D314 D315 ^ D318 L0 +error(0.0001756962670230916869) D314 D315 ^ D318 L0 ^ D286 L0 +error(0.01809902708512096253) D314 D338 +error(0.0007070126030203428879) D314 ^ D282 ^ D286 L0 +error(0.0006367420184909965315) D314 ^ D282 ^ D310 L0 +error(0.0009194744081342942502) D314 ^ D310 L0 ^ D286 L0 +error(0.0157666913660978944) D315 D316 +error(0.0008063908322377350349) D315 D316 ^ D318 D319 +error(0.003973470958629069134) D315 D316 ^ D318 D342 +error(0.01398924460029779895) D315 D321 +error(0.01203288461110336473) D315 D321 ^ D318 L0 +error(0.004973740584631117755) D315 D338 +error(0.003083695718806104061) D315 D338 ^ D310 L0 +error(6.326914210115742673e-05) D315 D338 ^ D342 L0 +error(0.000437796100933523862) D315 D338 ^ D342 L0 ^ D310 L0 +error(0.02802096798889971291) D315 D339 +error(0.0009781054333567957074) D315 D339 ^ D310 L0 +error(0.004258064841452545435) D315 D339 ^ D342 L0 +error(0.002293241519674286358) D315 D345 +error(0.002083689327902756277) D315 D345 ^ D318 L0 +error(0.003184439299356970048) D315 D345 ^ D342 L0 +error(0.0003075964336023181544) D315 D345 ^ D342 L0 ^ D318 L0 +error(0.008748819907022298975) D316 D317 +error(0.000421573423618385281) D316 D317 ^ D318 D319 +error(0.0004454116616421199392) D316 D317 ^ D319 D320 +error(0.002746525552341930968) D316 D317 ^ D319 D343 +error(0.01349995621294126057) D316 D322 +error(0.01074350301251948692) D316 D322 ^ D318 D319 +error(0.007372542091817689894) D316 D339 +error(0.0007550883971604156709) D316 D339 ^ D342 D343 +error(0.02903602395795713831) D316 D340 +error(0.002102104693332725906) D316 D340 ^ D342 D343 +error(0.003169378669323305153) D316 D345 +error(0.001191557425971731836) D316 D345 ^ D318 D342 +error(0.0001597772101005079804) D316 D345 ^ D318 D343 +error(0.0001021827979209038615) D316 D345 ^ D318 L0 +error(0.0005511678242116416215) D316 D345 ^ D342 D343 +error(1.679354630858518888e-05) D316 D345 ^ D342 L0 +error(0.001533444865295702621) D316 D346 +error(0.001663960370674462397) D316 D346 ^ D318 D319 +error(0.0007716218076495109674) D316 D346 ^ D318 D342 +error(0.001303219383453746829) D316 D346 ^ D318 D343 +error(0.000774858462820291762) D316 D346 ^ D319 D343 +error(0.00202762776909865992) D316 D346 ^ D342 D343 +error(0.01000000000000000021) D317 +error(0.004375250986392631436) D317 D340 +error(0.0001996290527887550252) D317 D340 ^ D343 D344 +error(0.02025078136410074503) D317 D341 +error(0.001389942840017453947) D317 D341 ^ D343 D344 +error(0.001697427904974847281) D317 D346 +error(9.531024276690012293e-05) D317 D346 ^ D318 D319 +error(0.0002003070882208187711) D317 D346 ^ D318 D343 +error(0.001002593182003129989) D317 D346 ^ D319 D343 +error(0.0008256000395826743879) D317 ^ D285 ^ D289 +error(0.001338317341795720308) D317 ^ D285 ^ D313 +error(0.0006122748497196598685) D317 ^ D289 +error(0.0063226352583203747) D318 D319 +error(0.000372850945034607572) D318 D319 ^ D321 D322 +error(0.002265174227511792399) D318 D319 ^ D322 D346 +error(0.0003610448547890982083) D318 D319 ^ D346 +error(0.03561013233827770019) D318 D342 +error(0.004322700216861186627) D318 D342 ^ D345 D346 +error(0.003938494697766241337) D318 D343 +error(0.0005358008309723712214) D318 D343 ^ D345 D346 +error(0.002034052694461135468) D318 D347 +error(0.0001466308340950007473) D318 D347 ^ D322 +error(0.001920194442056039194) D318 D347 ^ D322 D346 +error(0.01000000000000000021) D318 L0 +error(0.008841081898479867529) D319 D320 +error(0.002157536244326195389) D319 D320 ^ D293 +error(0.01163473797751780198) D319 D320 ^ D317 +error(0.0007537756625630134995) D319 D320 ^ D322 +error(0.01724304488913697489) D319 D323 +error(0.01634315707910385593) D319 D323 ^ D322 +error(0.01912154204876750918) D319 D343 +error(0.001896228017575547591) D319 D343 ^ D317 +error(0.003907155462371127326) D319 D343 ^ D346 +error(0.00279557314330079092) D319 D344 +error(0.002620934694098134548) D319 D344 ^ D317 +error(0.0004013694757154773717) D319 D344 ^ D346 +error(0.0001537267977297909955) D319 D344 ^ D346 ^ D317 +error(0.003820638366809637251) D319 D347 +error(0.003421241639577967189) D319 D347 ^ D322 +error(0.004007581078155113968) D319 D347 ^ D346 +error(0.001746012587198167822) D319 D347 ^ D346 ^ D322 +error(0.02606250389870726561) D320 D344 +error(0.002389270985273113726) D320 D344 ^ D317 +error(0.00654546687063310012) D321 D322 +error(0.0021024474767527058) D321 D322 ^ D294 L0 +error(0.01203764022217809065) D321 D322 ^ D318 L0 +error(0.0007246969784635964298) D321 D322 ^ D323 L0 +error(0.0005290423207049268833) D321 D322 ^ D323 L0 ^ D294 L0 +error(0.02738393697272551233) D321 D345 +error(0.004004257617406230957) D321 D345 ^ D318 L0 +error(0.01000000000000000021) D322 +error(0.002736244045764444407) D322 D345 +error(0.002855052799012060792) D322 D345 ^ D318 L0 +error(0.0006116163304378687384) D322 D345 ^ D347 L0 +error(0.0007069775710064596895) D322 D345 ^ D347 L0 ^ D318 L0 +error(0.02229227109480388241) D322 D346 +error(0.001481615400962180704) D322 D346 ^ D318 L0 +error(0.002922078673854252608) D322 D346 ^ D347 L0 +error(0.009906527088549655496) D322 ^ D323 L0 +error(0.0013622205925644421) D322 ^ D347 L0 +error(0.004149845774982054321) D323 D347 ^ D322 +error(0.01895412426906178255) D323 D347 +error(0.005000000000000000104) D323 L0 +error(0.005000000000000000104) D324 +error(0.01918438481247945748) D324 D328 +error(0.02071058551185744195) D324 D328 ^ D325 +error(0.04377814647995625918) D324 D348 +error(0.01188529897718188996) D324 D350 +error(0.01071126658254196486) D324 D350 ^ D325 +error(0.005941020411236445052) D324 D352 +error(0.00294663219170643309) D324 D352 ^ D325 +error(0.007074846792480046949) D324 ^ D325 +error(0.002384730488821758514) D324 ^ D326 +error(0.03669112996557038348) D325 +error(0.009597450678890685413) D325 D326 +error(0.01666237140252160853) D325 D326 ^ D329 +error(0.007757505311287541359) D325 D326 ^ D329 D352 +error(0.002877058991001913389) D325 D326 ^ D352 +error(0.02063638255721644138) D325 D331 +error(0.01001996092830572012) D325 D331 ^ D328 D329 +error(0.001226820170544101404) D325 ^ D324 ^ D326 +error(0.004060512068005721342) D325 ^ D352 +error(0.001749319992994063542) D325 ^ D352 ^ D324 ^ D326 +error(0.0218503636082708029) D326 +error(0.01547939247758800541) D326 D332 +error(0.01797478528435371425) D326 D332 ^ D329 +error(0.005000000000000000104) D326 ^ D329 +error(0.02006671972725227251) D326 ^ D352 +error(0.006232563553543974538) D329 D352 ^ D326 +error(0.006269636961950670467) D327 D328 +error(0.003042862240848380213) D327 D328 ^ D325 +error(0.01157945712629009083) D327 D328 ^ D330 +error(0.0007531940206867810631) D327 D328 ^ D330 ^ D331 +error(0.002702825047970536243) D327 D328 ^ D331 +error(0.0169069119354908759) D327 D334 +error(0.01455538868517228419) D327 D334 ^ D330 +error(0.02469495835970719755) D327 D349 +error(0.002221062634574129998) D327 D350 +error(0.001172383034419860557) D327 D350 ^ D325 +error(0.00740052468289655041) D327 D351 +error(0.005498679655336615076) D327 D351 ^ D330 +error(0.0007518763898376036679) D327 D353 +error(0.002100454469649782469) D327 D353 ^ D330 +error(0.0004243049850843272288) D327 D353 ^ D330 ^ D331 +error(0.001611677698978986398) D327 D353 ^ D331 +error(0.01138411749766534038) D328 D329 +error(0.0013749192686105837) D328 D329 ^ D301 +error(0.002103380697277020157) D328 D329 ^ D325 +error(0.00107518769043995154) D328 D329 ^ D326 ^ D325 +error(0.001859517628385704349) D328 D329 ^ D330 D331 +error(0.003602927296252634963) D328 D329 ^ D331 +error(0.01302625204741808713) D328 D335 +error(0.01015439392708241025) D328 D335 ^ D330 D331 +error(0.03391694556148006773) D328 D350 +error(0.01724135776999695738) D328 D350 ^ D325 +error(0.002332328979985697024) D328 D352 +error(0.002939239774061535096) D328 D352 ^ D325 +error(0.0005063130174988513151) D328 D352 ^ D326 ^ D325 +error(0.003815053587922157246) D328 D353 +error(0.002278676483917450694) D328 D353 ^ D330 +error(0.0009337476200032531273) D328 D353 ^ D330 D331 +error(0.001146085419073299312) D328 D353 ^ D331 +error(0.002070979965477363991) D328 D354 +error(0.000954082749545072579) D328 D354 ^ D331 +error(0.000120757215808715512) D328 D354 ^ D331 ^ D332 +error(0.001092899951877852405) D328 D354 ^ D332 +error(0.01000000000000000021) D329 +error(0.02982680198253087264) D329 D336 +error(0.02472172348581217274) D329 D336 ^ D331 D332 +error(0.03468946813398311735) D329 D352 +error(0.0007200062705415781038) D329 D352 ^ D325 +error(0.008157742006085802813) D329 D354 +error(0.001062628622703916349) D329 D354 ^ D331 +error(0.004394016805704291199) D329 D354 ^ D331 D332 +error(0.003173873380943411596) D329 D354 ^ D332 +error(0.003547474900594648449) D329 D356 ^ D332 +error(0.0004720059042094340031) D329 ^ D333 +error(0.02159486962763210172) D330 +error(0.01976576392086598286) D330 D331 +error(0.00241644491935549344) D330 D331 ^ D335 D353 +error(0.01936799239068935294) D330 D339 +error(0.01187173786392144853) D330 D339 ^ D334 D335 +error(0.001130702894898992072) D330 ^ D334 L0 +error(0.001906962914637555908) D330 ^ D351 L0 +error(0.008187316701534800775) D334 D351 ^ D330 +error(0.01964077514409488454) D331 +error(0.008769078168009003874) D331 D332 +error(0.001218441284915559907) D331 D332 ^ D329 +error(0.0003471665210898013977) D331 D332 ^ D336 D337 +error(0.002376455519474188465) D331 D332 ^ D336 D354 +error(0.0214609098695057246) D331 D340 +error(0.01412252853738392086) D331 D340 ^ D335 D336 +error(0.01711872510353103227) D332 +error(0.009863948691477055289) D332 D333 +error(0.009975498857018448573) D332 D333 ^ D337 +error(0.006947681120486145188) D332 D333 ^ D337 D356 +error(0.0007959269038057801855) D332 D333 ^ D356 +error(0.01222207497771867109) D332 D341 +error(0.01083373246932294726) D332 D341 ^ D336 D337 +error(0.0007027894121047431218) D332 ^ D329 +error(0.0005002339700925747309) D332 ^ D329 ^ D333 +error(0.0006374425825548761916) D332 ^ D356 +error(0.0002128576603717332065) D332 ^ D356 ^ D329 ^ D333 +error(0.05104558408154056398) D333 +error(0.02426890559730405031) D333 ^ D337 +error(0.008292074253754498289) D333 ^ D356 +error(0.003234702174141307601) D337 D356 ^ D333 +error(0.01497569539543903809) D334 D335 +error(0.002130101203862866822) D334 D335 ^ D331 +error(0.001088097337080149059) D334 D335 ^ D338 D339 +error(0.001982585401156245625) D334 D335 ^ D339 +error(0.003233980527419012558) D334 D335 ^ D340 +error(0.0539955544997209741) D334 D351 +error(0.001202190685892455795) D334 D353 +error(0.005907664129052033787) D334 D353 ^ D330 +error(0.001584830614592908429) D334 D353 ^ D331 +error(0.001839954586325836822) D334 D355 +error(0.001461361256452791508) D334 D355 ^ D339 +error(0.0002729198798504305708) D334 D355 ^ D339 ^ D340 +error(0.0006013667848756949156) D334 D355 ^ D340 +error(0.01134130184385486254) D334 L0 +error(0.01844861010970370516) D334 L0 ^ D338 +error(0.001498625545488415246) D334 L0 ^ D339 +error(0.02084331873980457481) D335 D336 +error(0.003189377311152606902) D335 D336 ^ D331 +error(0.00182736268608388883) D335 D336 ^ D332 +error(0.004992590792670863718) D335 D336 ^ D340 +error(7.134078518490044704e-05) D335 D336 ^ D341 +error(0.0166935380685430193) D335 D342 +error(0.02263773474483450274) D335 D342 ^ D339 D340 +error(0.03347757693170193977) D335 D353 +error(0.0009468132873999034801) D335 D353 ^ D330 +error(0.004304177117199363238) D335 D353 ^ D331 +error(0.006144941388444680186) D335 D354 +error(0.002143061697220190361) D335 D354 ^ D331 +error(0.0008293533411709687678) D335 D354 ^ D332 +error(0.001065039936720044676) D335 D354 ^ D332 ^ D331 +error(0.01244188223266851079) D335 D355 +error(0.001948574385302965974) D335 D355 ^ D339 +error(0.006558244667528910152) D335 D355 ^ D339 D340 +error(0.009940792164915470547) D335 D355 ^ D340 +error(0.0005382046330117776787) D335 D357 +error(0.0008683743156470332411) D335 D357 ^ D340 +error(0.0004508679451983777149) D335 D357 ^ D340 ^ D341 +error(0.0002575504904604629321) D335 D357 ^ D341 +error(0.008034175788019414649) D336 D337 +error(0.0001683246659204942265) D336 D337 ^ D333 +error(0.001672705656018846692) D336 D337 ^ D333 ^ D332 +error(0.0004402052714216968493) D336 D337 ^ D340 D341 +error(0.002985758368485050013) D336 D337 ^ D341 +error(0.01714603561365261181) D336 D343 +error(0.009857492115139948607) D336 D343 ^ D340 D341 +error(0.02205202978534172645) D336 D354 +error(0.001913125376066497066) D336 D354 ^ D331 +error(0.002527418613635892992) D336 D354 ^ D332 +error(0.002515771875487700111) D336 D356 +error(0.002002328517463291234) D336 D356 ^ D332 +error(0.00161511978105398921) D336 D356 ^ D333 +error(0.004786597038303838474) D336 D357 +error(0.002547853898615782577) D336 D357 ^ D340 +error(0.001489648514896043654) D336 D357 ^ D340 D341 +error(0.003973579576156172771) D336 D357 ^ D341 +error(0.001995322369078949588) D336 D358 +error(0.0002713356154258589727) D336 D358 ^ D341 +error(0.01392973137107778037) D337 +error(0.01730763894528706062) D337 D344 +error(0.01587159829857930429) D337 D344 ^ D341 +error(0.0233103571078222549) D337 D356 +error(0.001440945870913593095) D337 D356 ^ D332 +error(0.009166228815367175042) D337 D358 +error(0.001621331874670360173) D337 D358 ^ D341 +error(0.02259522668895079522) D338 +error(0.01249869578389452979) D338 D339 +error(0.004023252490778637079) D338 D339 ^ D310 L0 +error(0.01730019218721756333) D338 D339 ^ D334 L0 +error(0.001792521159429751997) D338 D339 ^ D342 L0 +error(0.0001756962670230916869) D338 D339 ^ D342 L0 ^ D310 L0 +error(0.0007070126030203428879) D338 ^ D306 ^ D310 L0 +error(0.0006367420184909965315) D338 ^ D306 ^ D334 L0 +error(0.0009194744081342942502) D338 ^ D334 L0 ^ D310 L0 +error(0.01052628655680512559) D339 +error(0.0167255532254306713) D339 D340 +error(0.004831672449854491729) D339 D340 ^ D342 D355 +error(0.01464468674223070796) D339 D345 +error(0.01243062796924763319) D339 D345 ^ D342 L0 +error(0.008879953003465812164) D339 ^ D355 L0 +error(0.0009233770796743755692) D339 ^ D355 L0 ^ D342 L0 +error(0.01000000000000000021) D340 +error(0.01353968709192834678) D340 D341 +error(0.0009892788126156586929) D340 D341 ^ D343 D344 +error(0.002275647744342826524) D340 D341 ^ D343 D357 +error(0.0125630259706371681) D340 D346 +error(0.009920628923220271844) D340 D346 ^ D342 D343 +error(0.001524618276774286586) D340 ^ D342 L0 +error(0.005873909869367705504) D342 D355 ^ D340 +error(0.03470996698688653959) D341 +error(0.0008256000395826743879) D341 ^ D309 ^ D313 +error(0.001338317341795720308) D341 ^ D309 ^ D337 +error(0.0006122748497196598685) D341 ^ D313 +error(0.001929985368253971535) D341 ^ D337 +error(0.01044980301030450781) D342 D343 +error(0.0002547361759692591109) D342 D343 ^ D341 +error(0.0007447832465249080731) D342 D343 ^ D341 ^ D340 +error(0.001984144813023489863) D342 D343 ^ D345 D346 +error(0.0008256137698657388651) D342 D343 ^ D346 +error(0.03688912276262424489) D342 D355 +error(0.001834359543798604053) D342 D357 +error(0.003437339930571798631) D342 D357 ^ D340 +error(0.0009902544966403289961) D342 D357 ^ D341 +error(0.002162323389684260837) D342 D359 +error(0.002256812817633528125) D342 D359 ^ D346 +error(0.01000000000000000021) D342 L0 +error(0.005378962117271826084) D342 L0 ^ D346 +error(0.00887573238397377888) D343 D344 +error(0.002157536244326195389) D343 D344 ^ D317 +error(0.01002690674811951115) D343 D344 ^ D341 +error(0.001332781713046879901) D343 D344 ^ D346 +error(0.01699775161053442007) D343 D347 +error(0.01727595441715807853) D343 D347 ^ D346 +error(0.0212540870978068959) D343 D357 +error(7.176364409958938938e-05) D343 D357 ^ D340 +error(0.003955307785036337939) D343 D357 ^ D341 +error(0.004563219617608596512) D343 D358 +error(0.003295364799125575887) D343 D358 ^ D341 +error(0.005153736672504407972) D343 D359 +error(0.004523224211038038775) D343 D359 ^ D346 +error(0.02703757376752306471) D344 D358 +error(0.0009244914662656692449) D344 D358 ^ D341 +error(0.01472823535452475949) D345 +error(0.009016841617810187823) D345 D346 +error(0.0021024474767527058) D345 D346 ^ D318 L0 +error(0.01092128996386828796) D345 D346 ^ D342 L0 +error(0.0001729202066960502948) D345 D346 ^ D347 L0 +error(0.0005290423207049268833) D345 D346 ^ D347 L0 ^ D318 L0 +error(0.006071602341772838925) D345 ^ D342 L0 +error(0.0303624237566811235) D346 +error(0.009173890860593858845) D346 ^ D347 L0 +error(0.0061667243962701861) D346 ^ D359 L0 +error(0.004397946413945911202) D347 D359 ^ D346 +error(0.01847169182747044475) D347 D359 +error(0.005000000000000000104) D347 L0 +error(0.0290300285077149528) D348 +error(0.02859165242597272449) D348 D350 +error(0.01384588336091374661) D349 D350 +error(0.0136161254006235688) D349 D351 +error(0.01690718307445775864) D350 D352 +error(0.006580508435724430165) D350 D352 ^ D325 +error(0.01242582636176831068) D350 D353 +error(0.01553540419671898751) D351 D353 +error(0.004558683006744603146) D351 D353 ^ D330 +error(0.03422026952306226472) D351 L0 +error(0.02178289751084633297) D352 +error(0.02599526624337161751) D352 D354 +error(0.0005664735554615386989) D352 ^ D324 ^ D326 +error(0.02335694180861983341) D353 D354 +error(0.002986898245729801074) D353 D354 ^ D331 +error(0.01627785051698599217) D353 D355 +error(0.01717107358968519848) D354 D356 +error(0.003170330762423919421) D354 D356 ^ D332 +error(0.01269600556709998829) D354 D357 +error(0.01421026761562650328) D355 D357 +error(0.00283203760692731692) D355 D357 ^ D340 +error(0.0250509884447367992) D355 L0 +error(0.03482360791855716731) D356 +error(0.01658966978276249504) D356 D358 +error(0.0008757980310527166109) D356 ^ D329 ^ D333 +error(0.01697049042470086602) D357 D358 +error(0.003079841124138098501) D357 D358 ^ D341 +error(0.02377404384128611881) D357 D359 +error(0.01647404498091735101) D359 L0 +detector(1, 4, 0) D0 +detector(3, 2, 0) D1 +detector(3, 4, 0) D2 +detector(5, 2, 0) D3 +detector(3, 6, 0) D4 +detector(5, 4, 0) D5 +detector(5, 6, 0) D6 +detector(7, 4, 0) D7 +detector(5, 8, 0) D8 +detector(7, 6, 0) D9 +detector(7, 8, 0) D10 +detector(9, 6, 0) D11 +detector(1, 4, 1) D12 +detector(2, 5, 1) D13 +detector(2, 7, 1) D14 +detector(3, 2, 1) D15 +detector(3, 4, 1) D16 +detector(3, 6, 1) D17 +detector(4, 3, 1) D18 +detector(4, 5, 1) D19 +detector(4, 7, 1) D20 +detector(4, 9, 1) D21 +detector(5, 2, 1) D22 +detector(5, 4, 1) D23 +detector(5, 6, 1) D24 +detector(5, 8, 1) D25 +detector(6, 1, 1) D26 +detector(6, 3, 1) D27 +detector(6, 5, 1) D28 +detector(6, 7, 1) D29 +detector(7, 4, 1) D30 +detector(7, 6, 1) D31 +detector(7, 8, 1) D32 +detector(8, 3, 1) D33 +detector(8, 5, 1) D34 +detector(9, 6, 1) D35 +detector(1, 4, 2) D36 +detector(2, 5, 2) D37 +detector(2, 7, 2) D38 +detector(3, 2, 2) D39 +detector(3, 4, 2) D40 +detector(3, 6, 2) D41 +detector(4, 3, 2) D42 +detector(4, 5, 2) D43 +detector(4, 7, 2) D44 +detector(4, 9, 2) D45 +detector(5, 2, 2) D46 +detector(5, 4, 2) D47 +detector(5, 6, 2) D48 +detector(5, 8, 2) D49 +detector(6, 1, 2) D50 +detector(6, 3, 2) D51 +detector(6, 5, 2) D52 +detector(6, 7, 2) D53 +detector(7, 4, 2) D54 +detector(7, 6, 2) D55 +detector(7, 8, 2) D56 +detector(8, 3, 2) D57 +detector(8, 5, 2) D58 +detector(9, 6, 2) D59 +detector(1, 4, 3) D60 +detector(2, 5, 3) D61 +detector(2, 7, 3) D62 +detector(3, 2, 3) D63 +detector(3, 4, 3) D64 +detector(3, 6, 3) D65 +detector(4, 3, 3) D66 +detector(4, 5, 3) D67 +detector(4, 7, 3) D68 +detector(4, 9, 3) D69 +detector(5, 2, 3) D70 +detector(5, 4, 3) D71 +detector(5, 6, 3) D72 +detector(5, 8, 3) D73 +detector(6, 1, 3) D74 +detector(6, 3, 3) D75 +detector(6, 5, 3) D76 +detector(6, 7, 3) D77 +detector(7, 4, 3) D78 +detector(7, 6, 3) D79 +detector(7, 8, 3) D80 +detector(8, 3, 3) D81 +detector(8, 5, 3) D82 +detector(9, 6, 3) D83 +detector(1, 4, 4) D84 +detector(2, 5, 4) D85 +detector(2, 7, 4) D86 +detector(3, 2, 4) D87 +detector(3, 4, 4) D88 +detector(3, 6, 4) D89 +detector(4, 3, 4) D90 +detector(4, 5, 4) D91 +detector(4, 7, 4) D92 +detector(4, 9, 4) D93 +detector(5, 2, 4) D94 +detector(5, 4, 4) D95 +detector(5, 6, 4) D96 +detector(5, 8, 4) D97 +detector(6, 1, 4) D98 +detector(6, 3, 4) D99 +detector(6, 5, 4) D100 +detector(6, 7, 4) D101 +detector(7, 4, 4) D102 +detector(7, 6, 4) D103 +detector(7, 8, 4) D104 +detector(8, 3, 4) D105 +detector(8, 5, 4) D106 +detector(9, 6, 4) D107 +detector(1, 4, 5) D108 +detector(2, 5, 5) D109 +detector(2, 7, 5) D110 +detector(3, 2, 5) D111 +detector(3, 4, 5) D112 +detector(3, 6, 5) D113 +detector(4, 3, 5) D114 +detector(4, 5, 5) D115 +detector(4, 7, 5) D116 +detector(4, 9, 5) D117 +detector(5, 2, 5) D118 +detector(5, 4, 5) D119 +detector(5, 6, 5) D120 +detector(5, 8, 5) D121 +detector(6, 1, 5) D122 +detector(6, 3, 5) D123 +detector(6, 5, 5) D124 +detector(6, 7, 5) D125 +detector(7, 4, 5) D126 +detector(7, 6, 5) D127 +detector(7, 8, 5) D128 +detector(8, 3, 5) D129 +detector(8, 5, 5) D130 +detector(9, 6, 5) D131 +detector(1, 4, 6) D132 +detector(2, 5, 6) D133 +detector(2, 7, 6) D134 +detector(3, 2, 6) D135 +detector(3, 4, 6) D136 +detector(3, 6, 6) D137 +detector(4, 3, 6) D138 +detector(4, 5, 6) D139 +detector(4, 7, 6) D140 +detector(4, 9, 6) D141 +detector(5, 2, 6) D142 +detector(5, 4, 6) D143 +detector(5, 6, 6) D144 +detector(5, 8, 6) D145 +detector(6, 1, 6) D146 +detector(6, 3, 6) D147 +detector(6, 5, 6) D148 +detector(6, 7, 6) D149 +detector(7, 4, 6) D150 +detector(7, 6, 6) D151 +detector(7, 8, 6) D152 +detector(8, 3, 6) D153 +detector(8, 5, 6) D154 +detector(9, 6, 6) D155 +detector(1, 4, 7) D156 +detector(2, 5, 7) D157 +detector(2, 7, 7) D158 +detector(3, 2, 7) D159 +detector(3, 4, 7) D160 +detector(3, 6, 7) D161 +detector(4, 3, 7) D162 +detector(4, 5, 7) D163 +detector(4, 7, 7) D164 +detector(4, 9, 7) D165 +detector(5, 2, 7) D166 +detector(5, 4, 7) D167 +detector(5, 6, 7) D168 +detector(5, 8, 7) D169 +detector(6, 1, 7) D170 +detector(6, 3, 7) D171 +detector(6, 5, 7) D172 +detector(6, 7, 7) D173 +detector(7, 4, 7) D174 +detector(7, 6, 7) D175 +detector(7, 8, 7) D176 +detector(8, 3, 7) D177 +detector(8, 5, 7) D178 +detector(9, 6, 7) D179 +detector(1, 4, 8) D180 +detector(2, 5, 8) D181 +detector(2, 7, 8) D182 +detector(3, 2, 8) D183 +detector(3, 4, 8) D184 +detector(3, 6, 8) D185 +detector(4, 3, 8) D186 +detector(4, 5, 8) D187 +detector(4, 7, 8) D188 +detector(4, 9, 8) D189 +detector(5, 2, 8) D190 +detector(5, 4, 8) D191 +detector(5, 6, 8) D192 +detector(5, 8, 8) D193 +detector(6, 1, 8) D194 +detector(6, 3, 8) D195 +detector(6, 5, 8) D196 +detector(6, 7, 8) D197 +detector(7, 4, 8) D198 +detector(7, 6, 8) D199 +detector(7, 8, 8) D200 +detector(8, 3, 8) D201 +detector(8, 5, 8) D202 +detector(9, 6, 8) D203 +detector(1, 4, 9) D204 +detector(2, 5, 9) D205 +detector(2, 7, 9) D206 +detector(3, 2, 9) D207 +detector(3, 4, 9) D208 +detector(3, 6, 9) D209 +detector(4, 3, 9) D210 +detector(4, 5, 9) D211 +detector(4, 7, 9) D212 +detector(4, 9, 9) D213 +detector(5, 2, 9) D214 +detector(5, 4, 9) D215 +detector(5, 6, 9) D216 +detector(5, 8, 9) D217 +detector(6, 1, 9) D218 +detector(6, 3, 9) D219 +detector(6, 5, 9) D220 +detector(6, 7, 9) D221 +detector(7, 4, 9) D222 +detector(7, 6, 9) D223 +detector(7, 8, 9) D224 +detector(8, 3, 9) D225 +detector(8, 5, 9) D226 +detector(9, 6, 9) D227 +detector(1, 4, 10) D228 +detector(2, 5, 10) D229 +detector(2, 7, 10) D230 +detector(3, 2, 10) D231 +detector(3, 4, 10) D232 +detector(3, 6, 10) D233 +detector(4, 3, 10) D234 +detector(4, 5, 10) D235 +detector(4, 7, 10) D236 +detector(4, 9, 10) D237 +detector(5, 2, 10) D238 +detector(5, 4, 10) D239 +detector(5, 6, 10) D240 +detector(5, 8, 10) D241 +detector(6, 1, 10) D242 +detector(6, 3, 10) D243 +detector(6, 5, 10) D244 +detector(6, 7, 10) D245 +detector(7, 4, 10) D246 +detector(7, 6, 10) D247 +detector(7, 8, 10) D248 +detector(8, 3, 10) D249 +detector(8, 5, 10) D250 +detector(9, 6, 10) D251 +detector(1, 4, 11) D252 +detector(2, 5, 11) D253 +detector(2, 7, 11) D254 +detector(3, 2, 11) D255 +detector(3, 4, 11) D256 +detector(3, 6, 11) D257 +detector(4, 3, 11) D258 +detector(4, 5, 11) D259 +detector(4, 7, 11) D260 +detector(4, 9, 11) D261 +detector(5, 2, 11) D262 +detector(5, 4, 11) D263 +detector(5, 6, 11) D264 +detector(5, 8, 11) D265 +detector(6, 1, 11) D266 +detector(6, 3, 11) D267 +detector(6, 5, 11) D268 +detector(6, 7, 11) D269 +detector(7, 4, 11) D270 +detector(7, 6, 11) D271 +detector(7, 8, 11) D272 +detector(8, 3, 11) D273 +detector(8, 5, 11) D274 +detector(9, 6, 11) D275 +detector(1, 4, 12) D276 +detector(2, 5, 12) D277 +detector(2, 7, 12) D278 +detector(3, 2, 12) D279 +detector(3, 4, 12) D280 +detector(3, 6, 12) D281 +detector(4, 3, 12) D282 +detector(4, 5, 12) D283 +detector(4, 7, 12) D284 +detector(4, 9, 12) D285 +detector(5, 2, 12) D286 +detector(5, 4, 12) D287 +detector(5, 6, 12) D288 +detector(5, 8, 12) D289 +detector(6, 1, 12) D290 +detector(6, 3, 12) D291 +detector(6, 5, 12) D292 +detector(6, 7, 12) D293 +detector(7, 4, 12) D294 +detector(7, 6, 12) D295 +detector(7, 8, 12) D296 +detector(8, 3, 12) D297 +detector(8, 5, 12) D298 +detector(9, 6, 12) D299 +detector(1, 4, 13) D300 +detector(2, 5, 13) D301 +detector(2, 7, 13) D302 +detector(3, 2, 13) D303 +detector(3, 4, 13) D304 +detector(3, 6, 13) D305 +detector(4, 3, 13) D306 +detector(4, 5, 13) D307 +detector(4, 7, 13) D308 +detector(4, 9, 13) D309 +detector(5, 2, 13) D310 +detector(5, 4, 13) D311 +detector(5, 6, 13) D312 +detector(5, 8, 13) D313 +detector(6, 1, 13) D314 +detector(6, 3, 13) D315 +detector(6, 5, 13) D316 +detector(6, 7, 13) D317 +detector(7, 4, 13) D318 +detector(7, 6, 13) D319 +detector(7, 8, 13) D320 +detector(8, 3, 13) D321 +detector(8, 5, 13) D322 +detector(9, 6, 13) D323 +detector(1, 4, 14) D324 +detector(2, 5, 14) D325 +detector(2, 7, 14) D326 +detector(3, 2, 14) D327 +detector(3, 4, 14) D328 +detector(3, 6, 14) D329 +detector(4, 3, 14) D330 +detector(4, 5, 14) D331 +detector(4, 7, 14) D332 +detector(4, 9, 14) D333 +detector(5, 2, 14) D334 +detector(5, 4, 14) D335 +detector(5, 6, 14) D336 +detector(5, 8, 14) D337 +detector(6, 1, 14) D338 +detector(6, 3, 14) D339 +detector(6, 5, 14) D340 +detector(6, 7, 14) D341 +detector(7, 4, 14) D342 +detector(7, 6, 14) D343 +detector(7, 8, 14) D344 +detector(8, 3, 14) D345 +detector(8, 5, 14) D346 +detector(9, 6, 14) D347 +detector(1, 4, 15) D348 +detector(3, 2, 15) D349 +detector(3, 4, 15) D350 +detector(5, 2, 15) D351 +detector(3, 6, 15) D352 +detector(5, 4, 15) D353 +detector(5, 6, 15) D354 +detector(7, 4, 15) D355 +detector(5, 8, 15) D356 +detector(7, 6, 15) D357 +detector(7, 8, 15) D358 +detector(9, 6, 15) D359 diff --git a/shared/package-files/76/76bdf2ffa9545902fa86ef4c562f561bf5fa5fa594b3b00596f563ba4123c9fc/blob b/shared/package-files/76/76bdf2ffa9545902fa86ef4c562f561bf5fa5fa594b3b00596f563ba4123c9fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..2908689195bcb17f9b64f9cc50972fc0678cb834 --- /dev/null +++ b/shared/package-files/76/76bdf2ffa9545902fa86ef4c562f561bf5fa5fa594b3b00596f563ba4123c9fc/blob @@ -0,0 +1,3305 @@ +error(0.007681120696027961443) D0 +error(0.005000000000000000104) D0 D2 +error(0.02435217654253603314) D0 D12 +error(0.003395653826513682361) D0 D12 ^ D13 +error(0.007343367576632712883) D0 D16 +error(0.00250816086523373942) D0 D16 ^ D13 +error(0.00580234682217913543) D0 D17 +error(0.003899799813717435681) D0 D17 ^ D13 +error(0.005000000000000000104) D1 D2 +error(0.005025101318290612316) D1 D2 ^ D18 +error(0.005077949256700131642) D1 D3 +error(0.02483958374939930144) D1 D15 +error(0.002108782744046447735) D1 D15 ^ D18 +error(0.001091201511526694893) D1 D16 +error(0.002853747301599140421) D1 D16 ^ D18 +error(0.0036585823421669641) D1 D22 +error(0.0009500371630117534398) D1 D22 ^ D18 +error(0.003012834931083416354) D1 D23 +error(0.002314756398019072407) D1 D23 ^ D18 +error(0.005761953553316104953) D2 D4 +error(0.002398869881184226803) D2 D4 ^ D19 +error(0.005000000000000000104) D2 D5 +error(0.01573546904794847698) D2 D16 +error(0.003760824753460646156) D2 D16 ^ D18 +error(0.002457313852606991984) D2 D16 ^ D18 D19 +error(0.003979469536668582205) D2 D17 +error(0.001746430294109884004) D2 D17 ^ D19 +error(0.003946954661509708903) D2 D23 +error(0.001856932998790400803) D2 D23 ^ D18 +error(0.0009977285381924129708) D2 D23 ^ D18 D19 +error(0.001020659296873670761) D2 D23 ^ D19 +error(0.003874990434010786543) D2 D24 +error(0.0001408437964313710819) D2 D24 ^ D19 +error(0.0001477052369225950778) D2 D24 ^ D19 ^ D18 +error(0.007584033013775245274) D3 D5 +error(0.003648001011172162262) D3 D5 ^ D27 +error(0.0391147642117654834) D3 D22 +error(0.002378738791827592677) D3 D22 ^ D26 +error(0.002491655097471815947) D3 D22 ^ D26 D27 +error(0.000361294484248480196) D3 D22 ^ D27 +error(5.382985573363204207e-05) D3 D23 +error(0.000600606420814401719) D3 D23 ^ D26 +error(0.001807490648724153093) D3 D23 ^ D27 +error(0.0007093106579438675707) D3 D23 ^ D27 ^ D26 +error(0.000733286631049638528) D3 D30 +error(0.002640423863050768687) D3 D30 ^ D27 +error(0.02318624648663646093) D3 L0 +error(0.00378854004182004999) D3 L0 ^ D26 +error(0.01204536156969609854) D4 +error(0.009202040920574694471) D4 D6 +error(0.02351103243081879846) D4 D17 +error(0.001937625880063190836) D4 D17 ^ D19 +error(0.001926412691306787599) D4 D17 ^ D19 D20 +error(0.00479191830457440307) D4 D24 +error(0.002545124802861255947) D4 D24 ^ D19 +error(0.001836453233522779066) D4 D24 ^ D19 D20 +error(0.00150154608970924793) D4 D24 ^ D20 +error(0.001524083905688307849) D4 D25 +error(2.264612700412228278e-05) D4 D25 ^ D19 +error(0.001471472872391472574) D4 D25 ^ D20 +error(0.0002294836247443605721) D4 D25 ^ D20 ^ D19 +error(0.007876302233775556161) D5 D6 +error(0.00284639148918946561) D5 D6 ^ D28 +error(0.01138246732167935704) D5 D7 +error(0.02327544476710173907) D5 D23 +error(0.003686080743241770211) D5 D23 ^ D27 +error(0.0007265282317098329008) D5 D23 ^ D27 D28 +error(0.001451242214730071988) D5 D23 ^ D28 +error(0.005658912184581810223) D5 D24 +error(0.00193401126527361039) D5 D24 ^ D28 +error(0.01430584192874615607) D5 D30 +error(0.005669542690869681413) D5 D30 ^ D27 +error(0.001387850108916334002) D5 D30 ^ D27 D28 +error(0.001111375298238935884) D5 D30 ^ D28 +error(0.001152266366939459167) D5 D31 +error(0.000983727247513215431) D5 D31 ^ D27 +error(0.0007835129034806896653) D5 D31 ^ D28 +error(0.0007510685013490198342) D5 D31 ^ D28 ^ D27 +error(0.005142750731569995307) D6 D8 +error(0.003300563206383767562) D6 D8 ^ D29 +error(0.005170471843867374684) D6 D9 +error(0.0175285286658889497) D6 D24 +error(0.00207983365495633581) D6 D24 ^ D28 +error(0.0008215975182038657513) D6 D24 ^ D28 D29 +error(0.004117533114518921733) D6 D25 +error(0.0004041388667885493146) D6 D25 ^ D28 +error(0.002051984944477120397) D6 D25 ^ D29 +error(8.809957007573441916e-05) D6 D25 ^ D29 ^ D28 +error(0.003057170559622724142) D6 D31 +error(0.003153024187272288753) D6 D31 ^ D28 +error(0.0006987179099971302333) D6 D31 ^ D28 D29 +error(0.001029007875522221097) D6 D31 ^ D29 +error(0.0005478092913755297283) D6 D32 +error(5.153005598047054016e-05) D6 D32 ^ D28 +error(0.0002156204946211192079) D6 D32 ^ D29 +error(0.0009747111974296487598) D6 D32 ^ D29 ^ D28 +error(0.008057719875324869524) D7 D9 +error(0.003086116130903066024) D7 D9 ^ D34 +error(0.03557715147258598554) D7 D30 +error(0.0007880888262371368077) D7 D30 ^ D33 +error(0.003146502813273147851) D7 D30 ^ D33 D34 +error(0.0004427526679586572768) D7 D30 ^ D34 +error(0.00220953388666383704) D7 D31 +error(0.0007599417923520538493) D7 D31 ^ D33 +error(0.0009193288382493709212) D7 D31 ^ D34 +error(0.0009714573031720629814) D7 D31 ^ D34 ^ D33 +error(0.002315312169463240675) D7 D35 +error(0.001751409595561265013) D7 D35 ^ D34 +error(0.01173111873557479076) D7 L0 +error(0.003014552797491923397) D7 L0 ^ D33 +error(0.01613149743794339494) D8 +error(0.005535990912960253585) D8 D10 +error(0.01966219057613331073) D8 D25 +error(0.005332623333509005012) D8 D25 ^ D29 +error(0.004061355698050782975) D8 D32 +error(0.002684891687843962791) D8 D32 ^ D29 +error(0.01278949618806468624) D9 D10 +error(0.005000000000000000104) D9 D11 +error(0.01815547116985775228) D9 D31 +error(0.002555173318502646992) D9 D31 ^ D34 +error(0.00551303871958473083) D9 D32 +error(0.000373517281815313241) D9 D32 ^ D34 +error(0.004093182677614420201) D9 D35 +error(0.003524211037293480987) D9 D35 ^ D34 +error(0.02066556609256997579) D10 D32 +error(0.01905181604753974911) D11 D35 +error(0.006690199945610700825) D11 L0 +error(0.005000000000000000104) D12 +error(0.01306525220528499329) D12 D16 +error(0.01500740313700915825) D12 D16 ^ D13 +error(0.02699148979780703964) D12 D36 +error(0.006834185536959506806) D12 D36 ^ D37 +error(0.007139333438785943654) D12 D40 +error(0.005071311220259624129) D12 D40 ^ D13 +error(0.003814151212458829175) D12 D40 ^ D37 +error(0.003241496548438547141) D12 D40 ^ D37 ^ D13 +error(0.003298463924975283609) D12 D41 +error(0.0005561199418532474046) D12 D41 ^ D13 +error(0.003357711680800872477) D12 D41 ^ D13 D37 +error(0.0001277368780254523777) D12 D41 ^ D37 +error(0.005000000000000000104) D12 ^ D13 +error(0.001411320666902509541) D12 ^ D37 +error(0.003813414387094213234) D13 D37 ^ D12 +error(0.02447052096475223898) D13 +error(0.005000000000000000104) D13 D14 +error(0.001838327110500736225) D13 D14 ^ D12 +error(0.0002759327443360799683) D13 D14 ^ D16 D17 +error(9.807043003152089201e-05) D13 D14 ^ D16 D41 +error(0.0129064847419182397) D13 D14 ^ D17 +error(0.00451851992816860136) D13 D14 ^ D17 D41 +error(0.002686865629807736865) D13 D14 ^ D41 +error(0.0008975063743248118788) D13 D14 ^ D41 ^ D12 +error(0.01888390867567710935) D13 D19 +error(0.01082459941846308955) D13 D19 ^ D16 D17 +error(0.04091880631186525091) D13 D37 +error(0.002653181116343675261) D13 D37 ^ D40 D41 +error(0.003298283945553052033) D13 D37 ^ D41 +error(0.00339519176841894272) D13 D42 +error(0.001582986769424157402) D13 D42 ^ D16 D40 +error(0.0004380064685231338712) D13 D42 ^ D16 D41 +error(0.003113535398603530131) D13 D43 +error(0.00247782554596669884) D13 D43 ^ D16 D17 +error(0.001028637261928361376) D13 D43 ^ D16 D40 +error(0.00160650879303555344) D13 D43 ^ D16 D41 +error(0.002443953285749952357) D13 D43 ^ D40 D41 +error(0.004885256139845306489) D13 ^ D0 +error(0.005510153065306554708) D13 ^ D17 +error(0.005000000000000000104) D14 +error(0.01680674974586190279) D14 D20 +error(0.01373536748981028614) D14 D20 ^ D17 +error(0.006342401933687971671) D14 D37 +error(5.731474309590040581e-06) D14 D37 ^ D12 +error(0.004735574936250143592) D14 D37 ^ D41 +error(0.001109758085417464736) D14 D37 ^ D41 ^ D12 +error(0.02590702726501740299) D14 D38 +error(0.01055432121765075004) D14 D38 ^ D41 +error(0.002067699089454209764) D14 D43 +error(0.0004764857434993141063) D14 D43 ^ D16 D17 +error(0.00018791695239074924) D14 D43 ^ D16 D41 +error(0.000543812216206917675) D14 D43 ^ D17 +error(0.002265746668965656213) D14 D43 ^ D17 D41 +error(0.001367685511860447251) D14 D43 ^ D41 +error(0.003309490384053264886) D14 D44 +error(0.002654443592163411442) D14 D44 ^ D17 +error(0.00302472805964318402) D14 D44 ^ D41 +error(0.001061960255450209193) D14 D44 ^ D41 ^ D17 +error(0.009394648987582247118) D14 ^ D17 +error(0.007807900128505026495) D15 D16 +error(0.0005231688707159463545) D15 D16 ^ D13 +error(0.008311810895659792198) D15 D16 ^ D18 +error(0.002531254512948871455) D15 D16 ^ D18 D42 +error(0.002283206907119589377) D15 D16 ^ D42 +error(0.0003647493962551453281) D15 D16 ^ D42 ^ D13 +error(0.01157689832105552805) D15 D22 +error(0.01169706349807630302) D15 D22 ^ D18 +error(0.02206797080950753318) D15 D39 +error(0.003109218220584021499) D15 D39 ^ D42 +error(0.001665473620494837799) D15 D40 +error(0.000751710629973935591) D15 D40 ^ D13 +error(0.002616716571845408533) D15 D40 ^ D42 +error(0.0002422723007377827135) D15 D40 ^ D42 ^ D13 +error(0.002331702848199883327) D15 D46 +error(0.003286376590100200615) D15 D46 ^ D18 +error(0.0016367579652731808) D15 D46 ^ D42 +error(0.0007603124886256211598) D15 D46 ^ D42 ^ D18 +error(0.002579757563572948522) D15 D47 +error(0.0001718132299533660715) D15 D47 ^ D18 +error(0.0001444887456803655346) D15 D47 ^ D18 D19 +error(0.001149196219717257958) D15 D47 ^ D18 D42 +error(1.120540756098161018e-05) D15 D47 ^ D19 D42 +error(0.0005057057902715079122) D15 D47 ^ D42 +error(0.008798784988183058417) D16 D17 +error(0.002760256343384630186) D16 D17 ^ D13 +error(0.0008429297809332041364) D16 D17 ^ D18 +error(0.002265788008652554718) D16 D17 ^ D19 +error(0.0005328953287804814908) D16 D17 ^ D19 D20 +error(0.001413973100792486779) D16 D17 ^ D19 D43 +error(0.0001724825413106183519) D16 D17 ^ D20 D43 +error(0.01446085060295728211) D16 D23 +error(0.008582877750099200675) D16 D23 ^ D18 D19 +error(0.02572510637435859032) D16 D40 +error(0.007006310296506031501) D16 D40 ^ D13 +error(0.001316794376174020356) D16 D40 ^ D42 +error(0.002641791500945908124) D16 D40 ^ D42 D43 +error(0.003414039823895323716) D16 D41 +error(0.0006897576085226444272) D16 D41 ^ D42 D43 +error(0.001694614774715204851) D16 D47 +error(0.002644592536818960674) D16 D47 ^ D18 D19 +error(0.0009441644247071477548) D16 D47 ^ D18 D42 +error(0.001928777394211658768) D16 D47 ^ D19 D42 +error(0.00133008307762702495) D16 D47 ^ D19 D43 +error(0.001038771671501572628) D16 D47 ^ D42 D43 +error(0.0007323574101554897534) D16 D48 +error(0.0006847265269601655836) D16 D48 ^ D19 D20 +error(0.000653390831884755204) D16 D48 ^ D19 D42 +error(0.001523171598481931144) D16 D48 ^ D19 D43 +error(7.585149492345969401e-05) D16 D48 ^ D20 D43 +error(0.0003362069066020665037) D16 D48 ^ D42 D43 +error(0.01000000000000000021) D17 +error(0.01960811477743449119) D17 D24 +error(0.01886944613286497055) D17 D24 ^ D19 D20 +error(0.03300215916333530675) D17 D41 +error(0.00216592434550165339) D17 D41 ^ D43 D44 +error(0.004503622582071078496) D17 D48 +error(0.002318254759649248948) D17 D48 ^ D19 D20 +error(0.000376482607813980331) D17 D48 ^ D19 D43 +error(0.001747378805460943121) D17 D48 ^ D20 D43 +error(0.000593531763207356261) D17 D48 ^ D20 D44 +error(0.00215641765716670028) D17 D48 ^ D43 D44 +error(0.0005765516027016854509) D17 D49 ^ D20 D43 +error(0.0008586384286019724905) D17 D49 ^ D20 D44 +error(0.0004389250296211264098) D17 D49 ^ D43 D44 +error(0.02185291191392015747) D18 +error(0.01513912088078554763) D18 D19 +error(0.0004021940016688471133) D18 D19 ^ D22 D47 +error(0.002080156153275584171) D18 D19 ^ D23 D47 +error(0.0171767396638795658) D18 D27 +error(0.01189450662979684055) D18 D27 ^ D22 D23 +error(0.03443641348695664767) D18 D42 +error(0.002395055567470361167) D18 D42 ^ D46 D47 +error(0.002124958655053427441) D18 D50 +error(0.00220015674251626157) D18 D50 ^ D22 D46 +error(0.0004947019958325036496) D18 D50 ^ D22 D47 +error(0.000374511620403463689) D18 D50 ^ D46 D47 +error(0.004183529412601343783) D18 D51 +error(0.001754250315696467616) D18 D51 ^ D22 D23 +error(0.001890722784335428699) D18 D51 ^ D22 D46 +error(0.002250793337517553033) D18 D51 ^ D22 D47 +error(0.0007981997197410908157) D18 D51 ^ D23 D47 +error(0.001107907099724317985) D18 D51 ^ D46 D47 +error(0.0007396770146007538736) D18 ^ D46 L0 +error(0.00259721580293025044) D22 D46 ^ D18 +error(0.02298150295494920392) D19 +error(0.007857529396357018636) D19 D20 +error(0.0001692053819037444857) D19 D20 ^ D23 D48 +error(0.002214135018659018229) D19 D20 ^ D24 D48 +error(0.01756565363522590711) D19 D28 +error(0.01456292811474488302) D19 D28 ^ D23 D24 +error(0.003460367052192838376) D19 D42 +error(0.001095315529918634281) D19 D42 ^ D47 D48 +error(0.03984696727665810317) D19 D43 +error(0.001792163974324219007) D19 D43 ^ D47 D48 +error(0.001844556973055879161) D19 D51 +error(0.002352941691835960802) D19 D51 ^ D23 D47 +error(0.0004755448116354408215) D19 D51 ^ D23 D48 +error(0.0003335880933664818145) D19 D51 ^ D47 D48 +error(0.00299129553800945051) D19 D52 +error(0.001643907901120499624) D19 D52 ^ D23 D24 +error(0.0007920510235761922101) D19 D52 ^ D23 D47 +error(0.001755098518752947574) D19 D52 ^ D23 D48 +error(0.0006409651334938055956) D19 D52 ^ D24 D48 +error(0.002713297683053161272) D19 D52 ^ D47 D48 +error(0.002446588128343654689) D19 ^ D4 +error(0.001756941758144765428) D19 ^ D17 +error(0.01000000000000000021) D20 +error(0.008630739977717757569) D20 D21 +error(0.0008067285096712303958) D20 D21 ^ D17 +error(0.0003869704899424970443) D20 D21 ^ D24 D49 +error(0.01059658592074075659) D20 D21 ^ D25 +error(0.00477129132198987789) D20 D21 ^ D25 D49 +error(0.002544666137518753445) D20 D21 ^ D49 +error(4.700906300686508247e-05) D20 D21 ^ D49 ^ D17 +error(0.01118226168102920935) D20 D29 +error(0.01039141354022049719) D20 D29 ^ D24 D25 +error(0.002545582488314489331) D20 D43 +error(0.0002826741056434087999) D20 D43 ^ D48 D49 +error(0.02075246121853630346) D20 D44 +error(0.004958470660349788284) D20 D44 ^ D17 +error(0.002257108386287591615) D20 D44 ^ D48 D49 +error(0.00124140148644221425) D20 D44 ^ D49 +error(0.002991512510671469512) D20 D52 +error(0.00177039048010369654) D20 D52 ^ D24 D48 +error(0.0003836293688450126611) D20 D52 ^ D24 D49 +error(0.0002262264940501502628) D20 D52 ^ D48 D49 +error(0.002041760540690738378) D20 D53 +error(0.002387441767965157308) D20 D53 ^ D24 D25 +error(0.0007494691992875175896) D20 D53 ^ D24 D48 +error(0.002474731958226495526) D20 D53 ^ D24 D49 +error(0.0009794943867816497014) D20 D53 ^ D25 D49 +error(0.002171252964640886084) D20 D53 ^ D48 D49 +error(0.005194928521679019993) D20 ^ D4 +error(0.001371781458259862651) D20 ^ D17 ^ D4 +error(0.0006944340653142424711) D20 ^ D19 ^ D17 +error(0.001480078824790611366) D20 ^ D25 +error(0.03087370265247934426) D21 +error(0.001936390295073753699) D21 D44 +error(0.0003618605530372149084) D21 D44 ^ D17 +error(0.002183311663915940733) D21 D44 ^ D49 +error(3.448864583775733021e-05) D21 D44 ^ D49 ^ D17 +error(0.02852939423101608432) D21 D45 +error(0.004253581368126741966) D21 D45 ^ D49 +error(0.002900611666390966702) D21 D53 +error(0.003037154267016145548) D21 D53 ^ D25 D49 +error(0.01854595675701545959) D21 ^ D25 +error(0.001702405640180595101) D21 ^ D49 ^ D25 +error(0.01389019731031490394) D22 D23 +error(0.002302295862077509414) D22 D23 ^ D18 +error(0.0004227867923891711244) D22 D23 ^ D26 +error(0.001528670904408761192) D22 D23 ^ D27 +error(0.0007864893633082394205) D22 D23 ^ D27 D28 +error(0.002175366124230702306) D22 D23 ^ D27 D51 +error(0.0004917502716645330996) D22 D23 ^ D27 ^ D26 +error(0.0002506984111203783999) D22 D23 ^ D28 D51 +error(0.04739892754396989039) D22 D46 +error(0.003781829997311276104) D22 D46 ^ D50 D51 +error(0.002334841659936933052) D22 D47 +error(0.0009422456726712663197) D22 D47 ^ D50 D51 +error(0.0007049855875566741993) D22 D54 ^ D27 D28 +error(0.001934639851703026398) D22 D54 ^ D27 D51 +error(0.0002735044682239881077) D22 D54 ^ D28 D51 +error(0.01486649500752514237) D22 L0 +error(0.01002848284488570135) D22 L0 ^ D26 +error(0.003567715602164565989) D26 D50 ^ D22 L0 +error(0.02156094151956668148) D23 D24 +error(0.005696637679777623135) D23 D24 ^ D19 +error(0.0004904660249372599966) D23 D24 ^ D27 +error(0.0004130837493007218) D23 D24 ^ D28 +error(0.002992427214964349901) D23 D24 ^ D28 D52 +error(0.0001795000384691343984) D23 D24 ^ D28 ^ D27 +error(0.0006609289947131321468) D23 D24 ^ D29 D52 +error(0.01885328704024998719) D23 D30 +error(0.01902893534755487059) D23 D30 ^ D27 D28 +error(0.02642383597330793393) D23 D47 +error(0.003024115804548305978) D23 D47 ^ D51 D52 +error(0.004707627181439803972) D23 D48 +error(0.0003746037177654245069) D23 D48 ^ D51 D52 +error(0.004350875619841032375) D23 D54 +error(0.005915511216720588557) D23 D54 ^ D27 D28 +error(0.001531588657764103561) D23 D54 ^ D27 D51 +error(0.008051354027943246824) D23 D54 ^ D28 D51 +error(0.001525927110233388445) D23 D54 ^ D28 D52 +error(0.003669458466892536359) D23 D54 ^ D51 D52 +error(0.002791113896069163328) D23 D55 +error(0.0006265920696080439726) D23 D55 ^ D28 D29 +error(4.779545894811885375e-05) D23 D55 ^ D28 D51 +error(0.0007337775853727664457) D23 D55 ^ D28 D52 +error(0.000542119306178530532) D23 D55 ^ D29 D52 +error(0.0003556315259281220406) D23 D55 ^ D51 D52 +error(0.00512249491736068395) D24 D25 +error(0.001165231581416754881) D24 D25 ^ D19 +error(0.001827426789742634186) D24 D25 ^ D20 +error(0.0004873355743473531876) D24 D25 ^ D20 ^ D19 +error(0.001456680310650915492) D24 D25 ^ D28 +error(0.001320641525585563789) D24 D25 ^ D29 +error(0.001951411826540530581) D24 D25 ^ D29 D53 +error(0.0001363990548493697222) D24 D25 ^ D53 +error(0.01110604022429731788) D24 D31 +error(0.01061407675307985549) D24 D31 ^ D28 D29 +error(0.02052822027627665413) D24 D48 +error(0.001984955007885169133) D24 D48 ^ D52 D53 +error(0.003128856462034781266) D24 D49 +error(0.0002188780272270664273) D24 D49 ^ D52 D53 +error(0.001173221145237272195) D24 D55 +error(0.00202756533973686608) D24 D55 ^ D28 D29 +error(0.0009147160160308196722) D24 D55 ^ D28 D52 +error(0.002478108585635494659) D24 D55 ^ D29 D52 +error(0.001252272042733494281) D24 D55 ^ D29 D53 +error(0.001947257464455566869) D24 D55 ^ D52 D53 +error(0.001123225366079328791) D24 D56 +error(6.005638908915711567e-05) D24 D56 ^ D29 +error(0.000421482864719889105) D24 D56 ^ D29 D52 +error(0.001261954426493605216) D24 D56 ^ D29 D53 +error(0.0001351826321506347569) D24 D56 ^ D52 D53 +error(0.00011199461596045396) D24 D56 ^ D53 +error(0.01632405034241546024) D25 +error(0.0165812343551939613) D25 D32 +error(0.01606646215043478279) D25 D32 ^ D29 +error(0.02209321612236390953) D25 D49 +error(0.002316639550606935157) D25 D49 ^ D53 +error(0.002146002416089138123) D25 D56 +error(0.002290705055193476176) D25 D56 ^ D29 +error(0.003445577716713628998) D25 D56 ^ D53 +error(0.0008214406114134374529) D25 D56 ^ D53 ^ D29 +error(0.03651993438021459287) D26 +error(0.01324604974631543586) D26 D27 +error(0.002481365011231853254) D26 D27 ^ D3 L0 +error(0.0191032886968939275) D26 D27 ^ D22 L0 +error(0.01987675887419782655) D26 D50 +error(0.01585843688147998976) D27 +error(0.01676472781984414753) D27 D28 +error(0.004363752286817622859) D27 D28 ^ D30 D54 +error(0.01203012742244274555) D27 D33 +error(0.01459566786485524958) D27 D33 ^ D30 L0 +error(0.005113701422269139804) D27 D50 +error(0.002144750650696250309) D27 D50 ^ D22 L0 +error(0.0005987071700741438676) D27 D50 ^ D54 L0 ^ D22 L0 +error(0.02694960105961625996) D27 D51 +error(0.0007380027204231738884) D27 D51 ^ D22 L0 +error(0.003721016964483825438) D27 D51 ^ D54 L0 +error(0.00189763058632084103) D27 D57 +error(0.002269670075562741068) D27 D57 ^ D30 L0 +error(0.003018302741455952676) D27 D57 ^ D54 L0 +error(0.0007595842134098546722) D27 D57 ^ D54 L0 ^ D30 L0 +error(0.0006531842819872120225) D27 ^ D30 L0 +error(0.0001078470586602478011) D27 ^ D30 L0 ^ D26 +error(0.01000000000000000021) D28 +error(0.00721463514005399667) D28 D29 +error(3.209669635179255231e-05) D28 D29 ^ D30 D31 +error(0.0004944029476380669896) D28 D29 ^ D30 D55 +error(0.00250279860763223715) D28 D29 ^ D31 D55 +error(0.01443112259512530776) D28 D34 +error(0.01031888099912844914) D28 D34 ^ D30 D31 +error(0.005038329940921605632) D28 D51 +error(0.0005822770362989852701) D28 D51 ^ D54 D55 +error(0.02718987902130082929) D28 D52 +error(0.001729643906341211826) D28 D52 ^ D54 D55 +error(0.002008286380084761159) D28 D57 +error(0.001184019355023896696) D28 D57 ^ D30 D54 +error(0.0001331019283698714549) D28 D57 ^ D30 D55 +error(0.0003174867051203577348) D28 D57 ^ D30 L0 +error(0.0005499328591647120778) D28 D57 ^ D54 D55 +error(0.0002857008089304124607) D28 D57 ^ D54 L0 +error(0.002378588767130583072) D28 D58 +error(0.001993144322145359512) D28 D58 ^ D30 D31 +error(0.0008444018024559791016) D28 D58 ^ D30 D54 +error(0.001376119481102591443) D28 D58 ^ D30 D55 +error(0.0007272918137137072275) D28 D58 ^ D31 D55 +error(0.001961341429606960809) D28 D58 ^ D54 D55 +error(0.02966638607631793753) D29 +error(0.003847026731771674424) D29 D52 +error(0.0007232425406817723831) D29 D52 ^ D55 D56 +error(0.021773936634121447) D29 D53 +error(0.001313798479028342953) D29 D53 ^ D55 D56 +error(0.003909402514313408024) D29 D58 +error(2.28104599996947481e-05) D29 D58 ^ D30 D55 +error(0.001083963797513874021) D29 D58 ^ D31 D55 +error(0.001233930054392941159) D29 ^ D8 +error(0.0004172084801391751302) D29 ^ D25 +error(0.005000000000000000104) D30 D31 +error(0.001775110629109258494) D30 D31 ^ D27 +error(0.001865078618232202893) D30 D31 ^ D28 +error(0.0007137974773194730735) D30 D31 ^ D28 ^ D27 +error(3.783736237809348548e-05) D30 D31 ^ D33 +error(0.001843798965848620491) D30 D31 ^ D34 +error(0.002288777333365739179) D30 D31 ^ D34 D58 +error(0.0002082982817196510426) D30 D31 ^ D34 ^ D33 +error(0.0006884153111551963907) D30 D31 ^ D58 +error(0.03612550294212107937) D30 D54 +error(0.003986180069234413967) D30 D54 ^ D57 D58 +error(0.004298078915946801359) D30 D55 +error(0.0004818218312557076663) D30 D55 ^ D57 D58 +error(0.001625657018947900294) D30 D59 +error(0.0008012212761801838301) D30 D59 ^ D34 +error(0.001191671275737970267) D30 D59 ^ D34 D58 +error(0.000232923489534182565) D30 D59 ^ D58 +error(0.01000000000000000021) D30 L0 +error(0.0009680142685657574207) D30 L0 ^ D3 L0 ^ D26 +error(0.005000000000000000104) D30 L0 ^ D33 +error(0.01925149187083044153) D31 D32 +error(0.000237380078731830443) D31 D32 ^ D28 +error(0.01384730056512392324) D31 D32 ^ D29 +error(0.0007328120502827266619) D31 D32 ^ D29 ^ D28 +error(0.0005104004521206974808) D31 D32 ^ D34 +error(0.01448335530131279053) D31 D35 +error(0.01572140295511758809) D31 D35 ^ D34 +error(0.02173700185701750789) D31 D55 +error(0.001786549131622320371) D31 D55 ^ D29 +error(0.003912722710223686708) D31 D55 ^ D58 +error(0.002382500552628285216) D31 D56 +error(0.003284071404981582943) D31 D56 ^ D29 +error(0.0001814293687345641638) D31 D56 ^ D58 +error(0.0002952472760400955132) D31 D56 ^ D58 ^ D29 +error(0.003550633146921626862) D31 D59 +error(0.002950093029550475334) D31 D59 ^ D34 +error(0.004198020730678931646) D31 D59 ^ D58 +error(0.001191252727279817816) D31 D59 ^ D58 ^ D34 +error(0.02426465096103480254) D32 D56 +error(0.002887796181740957552) D32 D56 ^ D29 +error(0.02448711277826811847) D33 +error(0.008089557883118048132) D33 D34 +error(0.001120048667423390217) D33 D34 ^ D7 L0 +error(0.01061719353717716953) D33 D34 ^ D30 L0 +error(0.03021538745065696641) D33 D57 +error(0.003655842737286960943) D33 D57 ^ D30 L0 +error(0.0280792727538866152) D34 +error(0.003072153014909577255) D34 D57 +error(0.002126355402752911228) D34 D57 ^ D30 L0 +error(0.0003891207497752700428) D34 D57 ^ D59 L0 +error(0.0004039352375315962947) D34 D57 ^ D59 L0 ^ D30 L0 +error(0.01966590043670931112) D34 D58 +error(0.00116697850444044183) D34 D58 ^ D30 L0 +error(0.002302712672173879219) D34 D58 ^ D59 L0 +error(0.0002579141246643062058) D34 ^ D7 L0 +error(0.01029783759150965441) D34 ^ D35 L0 +error(0.0002678678293755301968) D34 ^ D35 L0 ^ D7 L0 ^ D33 +error(0.0008925839347452218337) D34 ^ D59 L0 +error(0.002919826675589398159) D35 D59 ^ D34 +error(0.01792671575261539293) D35 D59 +error(0.00938576071338041891) D35 L0 +error(0.00110383121371798276) D35 L0 ^ D7 L0 ^ D33 +error(0.0005488575752394959364) D35 L0 ^ D33 +error(0.005000000000000000104) D36 +error(0.01660438028321272949) D36 D40 +error(0.01779114294423248324) D36 D40 ^ D37 +error(0.02699148979780703964) D36 D60 +error(0.006834185536959506806) D36 D60 ^ D61 +error(0.007139333438785943654) D36 D64 +error(0.005071311220259624129) D36 D64 ^ D37 +error(0.003814151212458829175) D36 D64 ^ D61 +error(0.003241496548438547141) D36 D64 ^ D61 ^ D37 +error(0.003298463924975283609) D36 D65 +error(0.0005561199418532474046) D36 D65 ^ D37 +error(0.003357711680800872477) D36 D65 ^ D37 D61 +error(0.0001277368780254523777) D36 D65 ^ D61 +error(0.00612165296323359618) D36 ^ D37 +error(0.001411320666902509541) D36 ^ D61 +error(0.003813414387094213234) D37 D61 ^ D36 +error(0.01000000000000000021) D37 +error(0.007776687944794747655) D37 D38 +error(0.0002239251782426420899) D37 D38 ^ D36 +error(0.0006578014119039935111) D37 D38 ^ D40 D41 +error(9.807043003152089201e-05) D37 D38 ^ D40 D65 +error(0.01462632812957779041) D37 D38 ^ D41 +error(0.00451851992816860136) D37 D38 ^ D41 D65 +error(0.002686865629807736865) D37 D38 ^ D65 +error(0.0008975063743248118788) D37 D38 ^ D65 ^ D36 +error(0.02004352178629314682) D37 D43 +error(0.0126538281966155023) D37 D43 ^ D40 D41 +error(0.04091880631186525091) D37 D61 +error(0.002653181116343675261) D37 D61 ^ D64 D65 +error(0.003298283945553052033) D37 D61 ^ D65 +error(0.00339519176841894272) D37 D66 +error(0.001582986769424157402) D37 D66 ^ D40 D64 +error(0.0004380064685231338712) D37 D66 ^ D40 D65 +error(0.003113535398603530131) D37 D67 +error(0.00247782554596669884) D37 D67 ^ D40 D41 +error(0.001028637261928361376) D37 D67 ^ D40 D64 +error(0.00160650879303555344) D37 D67 ^ D40 D65 +error(0.002443953285749952357) D37 D67 ^ D64 D65 +error(0.01501988426115019766) D38 D44 +error(0.01690133780623802318) D38 D44 ^ D41 +error(0.006342401933687971671) D38 D61 +error(5.731474309590040581e-06) D38 D61 ^ D36 +error(0.004735574936250143592) D38 D61 ^ D65 +error(0.001109758085417464736) D38 D61 ^ D65 ^ D36 +error(0.02590702726501740299) D38 D62 +error(0.01055432121765075004) D38 D62 ^ D65 +error(0.002067699089454209764) D38 D67 +error(0.0004764857434993141063) D38 D67 ^ D40 D41 +error(0.00018791695239074924) D38 D67 ^ D40 D65 +error(0.000543812216206917675) D38 D67 ^ D41 +error(0.002265746668965656213) D38 D67 ^ D41 D65 +error(0.001367685511860447251) D38 D67 ^ D65 +error(0.003309490384053264886) D38 D68 +error(0.002654443592163411442) D38 D68 ^ D41 +error(0.00302472805964318402) D38 D68 ^ D65 +error(0.001061960255450209193) D38 D68 ^ D65 ^ D41 +error(0.008208999602450065339) D39 D40 +error(0.0002490393643702508214) D39 D40 ^ D37 +error(0.008432084388650621515) D39 D40 ^ D42 +error(0.0004018075719304165026) D39 D40 ^ D42 D43 +error(0.002531254512948871455) D39 D40 ^ D42 D66 +error(0.002283206907119589377) D39 D40 ^ D66 +error(0.0003647493962551453281) D39 D40 ^ D66 ^ D37 +error(0.01230414654041589451) D39 D46 +error(0.0105586013131753146) D39 D46 ^ D42 +error(0.02206797080950753318) D39 D63 +error(0.003109218220584021499) D39 D63 ^ D66 +error(0.001665473620494837799) D39 D64 +error(0.000751710629973935591) D39 D64 ^ D37 +error(0.002616716571845408533) D39 D64 ^ D66 +error(0.0002422723007377827135) D39 D64 ^ D66 ^ D37 +error(0.002331702848199883327) D39 D70 +error(0.003286376590100200615) D39 D70 ^ D42 +error(0.0016367579652731808) D39 D70 ^ D66 +error(0.0007603124886256211598) D39 D70 ^ D66 ^ D42 +error(0.002579757563572948522) D39 D71 +error(0.0001718132299533660715) D39 D71 ^ D42 +error(0.0001444887456803655346) D39 D71 ^ D42 D43 +error(0.001149196219717257958) D39 D71 ^ D42 D66 +error(1.120540756098161018e-05) D39 D71 ^ D43 D66 +error(0.0005057057902715079122) D39 D71 ^ D66 +error(0.00860417189101998249) D40 D41 +error(0.0008996636785346223512) D40 D41 ^ D13 +error(0.0007682366505013531362) D40 D41 ^ D42 D43 +error(0.0001543284317303631468) D40 D41 ^ D43 D44 +error(0.001413973100792486779) D40 D41 ^ D43 D67 +error(0.0001724825413106183519) D40 D41 ^ D44 D67 +error(0.01514009713272307031) D40 D47 +error(0.008955358603158896161) D40 D47 ^ D42 D43 +error(0.02572510637435859032) D40 D64 +error(0.007006310296506031501) D40 D64 ^ D37 +error(0.001316794376174020356) D40 D64 ^ D66 +error(0.002641791500945908124) D40 D64 ^ D66 D67 +error(0.003414039823895323716) D40 D65 +error(0.0006897576085226444272) D40 D65 ^ D66 D67 +error(0.001694614774715204851) D40 D71 +error(0.002644592536818960674) D40 D71 ^ D42 D43 +error(0.0009441644247071477548) D40 D71 ^ D42 D66 +error(0.001928777394211658768) D40 D71 ^ D43 D66 +error(0.00133008307762702495) D40 D71 ^ D43 D67 +error(0.001038771671501572628) D40 D71 ^ D66 D67 +error(0.0007323574101554897534) D40 D72 +error(0.0006847265269601655836) D40 D72 ^ D43 D44 +error(0.000653390831884755204) D40 D72 ^ D43 D66 +error(0.001523171598481931144) D40 D72 ^ D43 D67 +error(7.585149492345969401e-05) D40 D72 ^ D44 D67 +error(0.0003362069066020665037) D40 D72 ^ D66 D67 +error(0.01000000000000000021) D41 +error(0.02118071892183423163) D41 D48 +error(0.01736477246236184033) D41 D48 ^ D43 D44 +error(0.03300215916333530675) D41 D65 +error(0.00216592434550165339) D41 D65 ^ D67 D68 +error(0.004503622582071078496) D41 D72 +error(0.002318254759649248948) D41 D72 ^ D43 D44 +error(0.000376482607813980331) D41 D72 ^ D43 D67 +error(0.001747378805460943121) D41 D72 ^ D44 D67 +error(0.000593531763207356261) D41 D72 ^ D44 D68 +error(0.00215641765716670028) D41 D72 ^ D67 D68 +error(0.0005765516027016854509) D41 D73 ^ D44 D67 +error(0.0008586384286019724905) D41 D73 ^ D44 D68 +error(0.0004389250296211264098) D41 D73 ^ D67 D68 +error(0.01000000000000000021) D42 +error(0.009521520337646336568) D42 D43 +error(0.0008398031791907709142) D42 D43 ^ D46 D47 +error(0.0004021940016688471133) D42 D43 ^ D46 D71 +error(0.0005440209884140075275) D42 D43 ^ D47 D48 +error(0.002080156153275584171) D42 D43 ^ D47 D71 +error(0.01675364273324095668) D42 D51 +error(0.01174642302711653881) D42 D51 ^ D46 D47 +error(0.03443641348695664767) D42 D66 +error(0.002395055567470361167) D42 D66 ^ D70 D71 +error(0.002124958655053427441) D42 D74 +error(0.00220015674251626157) D42 D74 ^ D46 D70 +error(0.0004947019958325036496) D42 D74 ^ D46 D71 +error(0.000374511620403463689) D42 D74 ^ D70 D71 +error(0.004183529412601343783) D42 D75 +error(0.001754250315696467616) D42 D75 ^ D46 D47 +error(0.001890722784335428699) D42 D75 ^ D46 D70 +error(0.002250793337517553033) D42 D75 ^ D46 D71 +error(0.0007981997197410908157) D42 D75 ^ D47 D71 +error(0.001107907099724317985) D42 D75 ^ D70 D71 +error(0.0007396770146007538736) D42 ^ D70 L0 +error(0.00259721580293025044) D46 D70 ^ D42 +error(0.00729955180669228116) D43 D44 +error(5.062381541878982895e-05) D43 D44 ^ D17 +error(0.001030199975533826117) D43 D44 ^ D41 +error(0.0006584229463454448032) D43 D44 ^ D47 D48 +error(0.0001692053819037444857) D43 D44 ^ D47 D72 +error(0.0004254426911218613431) D43 D44 ^ D48 D49 +error(0.002214135018659018229) D43 D44 ^ D48 D72 +error(0.01623214291849352578) D43 D52 +error(0.01451260695679871225) D43 D52 ^ D47 D48 +error(0.003460367052192838376) D43 D66 +error(0.001095315529918634281) D43 D66 ^ D71 D72 +error(0.03984696727665810317) D43 D67 +error(0.001792163974324219007) D43 D67 ^ D71 D72 +error(0.001844556973055879161) D43 D75 +error(0.002352941691835960802) D43 D75 ^ D47 D71 +error(0.0004755448116354408215) D43 D75 ^ D47 D72 +error(0.0003335880933664818145) D43 D75 ^ D71 D72 +error(0.00299129553800945051) D43 D76 +error(0.001643907901120499624) D43 D76 ^ D47 D48 +error(0.0007920510235761922101) D43 D76 ^ D47 D71 +error(0.001755098518752947574) D43 D76 ^ D47 D72 +error(0.0006409651334938055956) D43 D76 ^ D48 D72 +error(0.002713297683053161272) D43 D76 ^ D71 D72 +error(0.009726903041435587885) D44 D45 +error(0.0003191744926083531198) D44 D45 ^ D41 +error(0.0006579173063691476581) D44 D45 ^ D48 D49 +error(0.0003869704899424970443) D44 D45 ^ D48 D73 +error(0.01220834273285227936) D44 D45 ^ D49 +error(0.00477129132198987789) D44 D45 ^ D49 D73 +error(0.002544666137518753445) D44 D45 ^ D73 +error(4.700906300686508247e-05) D44 D45 ^ D73 ^ D41 +error(0.01240604439279997979) D44 D53 +error(0.01094083605793164625) D44 D53 ^ D48 D49 +error(0.002545582488314489331) D44 D67 +error(0.0002826741056434087999) D44 D67 ^ D72 D73 +error(0.02075246121853630346) D44 D68 +error(0.004958470660349788284) D44 D68 ^ D41 +error(0.002257108386287591615) D44 D68 ^ D72 D73 +error(0.00124140148644221425) D44 D68 ^ D73 +error(0.002991512510671469512) D44 D76 +error(0.00177039048010369654) D44 D76 ^ D48 D72 +error(0.0003836293688450126611) D44 D76 ^ D48 D73 +error(0.0002262264940501502628) D44 D76 ^ D72 D73 +error(0.002041760540690738378) D44 D77 +error(0.002387441767965157308) D44 D77 ^ D48 D49 +error(0.0007494691992875175896) D44 D77 ^ D48 D72 +error(0.002474731958226495526) D44 D77 ^ D48 D73 +error(0.0009794943867816497014) D44 D77 ^ D49 D73 +error(0.002171252964640886084) D44 D77 ^ D72 D73 +error(0.01102841403074931829) D45 +error(0.001936390295073753699) D45 D68 +error(0.0003618605530372149084) D45 D68 ^ D41 +error(0.002183311663915940733) D45 D68 ^ D73 +error(3.448864583775733021e-05) D45 D68 ^ D73 ^ D41 +error(0.02852939423101608432) D45 D69 +error(0.004253581368126741966) D45 D69 ^ D73 +error(0.002900611666390966702) D45 D77 +error(0.003037154267016145548) D45 D77 ^ D49 D73 +error(0.01597507063807540942) D45 ^ D49 +error(0.001702405640180595101) D45 ^ D73 ^ D49 +error(0.01776770169544816466) D46 D47 +error(0.0001196824171128900416) D46 D47 ^ D18 +error(0.0006586128121373966554) D46 D47 ^ D50 D51 +error(0.002175366124230702306) D46 D47 ^ D51 D75 +error(0.0002506984111203783999) D46 D47 ^ D52 D75 +error(0.04739892754396989039) D46 D70 +error(0.003781829997311276104) D46 D70 ^ D74 D75 +error(0.002334841659936933052) D46 D71 +error(0.0009422456726712663197) D46 D71 ^ D74 D75 +error(0.0007049855875566741993) D46 D78 ^ D51 D52 +error(0.001934639851703026398) D46 D78 ^ D51 D75 +error(0.0002735044682239881077) D46 D78 ^ D52 D75 +error(0.01111336289536665051) D46 L0 +error(0.01173226287006574539) D46 L0 ^ D50 +error(0.003567715602164565989) D50 D74 ^ D46 L0 +error(0.0219173104120194244) D47 D48 +error(0.0006160258984500803633) D47 D48 ^ D51 D52 +error(6.315642213795687697e-05) D47 D48 ^ D52 D53 +error(0.002992427214964349901) D47 D48 ^ D52 D76 +error(0.0006609289947131321468) D47 D48 ^ D53 D76 +error(0.01946623581067056727) D47 D54 +error(0.01983614692690993664) D47 D54 ^ D51 D52 +error(0.02642383597330793393) D47 D71 +error(0.003024115804548305978) D47 D71 ^ D75 D76 +error(0.004707627181439803972) D47 D72 +error(0.0003746037177654245069) D47 D72 ^ D75 D76 +error(0.004350875619841032375) D47 D78 +error(0.005915511216720588557) D47 D78 ^ D51 D52 +error(0.001531588657764103561) D47 D78 ^ D51 D75 +error(0.008051354027943246824) D47 D78 ^ D52 D75 +error(0.001525927110233388445) D47 D78 ^ D52 D76 +error(0.003669458466892536359) D47 D78 ^ D75 D76 +error(0.002791113896069163328) D47 D79 +error(0.0006265920696080439726) D47 D79 ^ D52 D53 +error(4.779545894811885375e-05) D47 D79 ^ D52 D75 +error(0.0007337775853727664457) D47 D79 ^ D52 D76 +error(0.000542119306178530532) D47 D79 ^ D53 D76 +error(0.0003556315259281220406) D47 D79 ^ D75 D76 +error(0.007713185277822201882) D48 D49 +error(0.0002906218459867560932) D48 D49 ^ D53 +error(0.001951411826540530581) D48 D49 ^ D53 D77 +error(0.0001363990548493697222) D48 D49 ^ D77 +error(0.01427946177760987603) D48 D55 +error(0.009134401807325989373) D48 D55 ^ D52 D53 +error(0.02052822027627665413) D48 D72 +error(0.001984955007885169133) D48 D72 ^ D76 D77 +error(0.003128856462034781266) D48 D73 +error(0.0002188780272270664273) D48 D73 ^ D76 D77 +error(0.001173221145237272195) D48 D79 +error(0.00202756533973686608) D48 D79 ^ D52 D53 +error(0.0009147160160308196722) D48 D79 ^ D52 D76 +error(0.002478108585635494659) D48 D79 ^ D53 D76 +error(0.001252272042733494281) D48 D79 ^ D53 D77 +error(0.001947257464455566869) D48 D79 ^ D76 D77 +error(0.001123225366079328791) D48 D80 +error(6.005638908915711567e-05) D48 D80 ^ D53 +error(0.000421482864719889105) D48 D80 ^ D53 D76 +error(0.001261954426493605216) D48 D80 ^ D53 D77 +error(0.0001351826321506347569) D48 D80 ^ D76 D77 +error(0.00011199461596045396) D48 D80 ^ D77 +error(0.01094531334540550273) D49 +error(0.01538736176745019411) D49 D56 +error(0.0169485703355046792) D49 D56 ^ D53 +error(0.02209321612236390953) D49 D73 +error(0.002316639550606935157) D49 D73 ^ D77 +error(0.002146002416089138123) D49 D80 +error(0.002290705055193476176) D49 D80 ^ D53 +error(0.003445577716713628998) D49 D80 ^ D77 +error(0.0008214406114134374529) D49 D80 ^ D77 ^ D53 +error(0.008881637178845576755) D50 +error(0.01495585212186280669) D50 D51 +error(0.003695710743442946148) D50 D51 ^ D22 L0 +error(0.01799833116646069181) D50 D51 ^ D46 L0 +error(0.0004997383954729171145) D50 D51 ^ D54 L0 ^ D22 L0 +error(0.01987675887419782655) D50 D74 +error(0.0003296412873835849575) D50 ^ D18 ^ D22 L0 +error(0.0008096266067650861225) D50 ^ D46 L0 ^ D22 L0 +error(0.01506431211196329958) D51 D52 +error(0.0007457400519393364569) D51 D52 ^ D54 D55 +error(0.004363752286817622859) D51 D52 ^ D54 D78 +error(0.01385586789355772348) D51 D57 +error(0.01109776885461767094) D51 D57 ^ D54 L0 +error(0.005113701422269139804) D51 D74 +error(0.002144750650696250309) D51 D74 ^ D46 L0 +error(0.0005987071700741438676) D51 D74 ^ D78 L0 ^ D46 L0 +error(0.02694960105961625996) D51 D75 +error(0.0007380027204231738884) D51 D75 ^ D46 L0 +error(0.003721016964483825438) D51 D75 ^ D78 L0 +error(0.00189763058632084103) D51 D81 +error(0.002269670075562741068) D51 D81 ^ D54 L0 +error(0.003018302741455952676) D51 D81 ^ D78 L0 +error(0.0007595842134098546722) D51 D81 ^ D78 L0 ^ D54 L0 +error(0.01169871816276893753) D52 D53 +error(0.0004563423471117930195) D52 D53 ^ D54 D55 +error(0.0004944029476380669896) D52 D53 ^ D54 D79 +error(0.0004058715760627647413) D52 D53 ^ D55 D56 +error(0.00250279860763223715) D52 D53 ^ D55 D79 +error(0.01304884676936473968) D52 D58 +error(0.01084325194016807527) D52 D58 ^ D54 D55 +error(0.005038329940921605632) D52 D75 +error(0.0005822770362989852701) D52 D75 ^ D78 D79 +error(0.02718987902130082929) D52 D76 +error(0.001729643906341211826) D52 D76 ^ D78 D79 +error(0.002008286380084761159) D52 D81 +error(0.001184019355023896696) D52 D81 ^ D54 D78 +error(0.0001331019283698714549) D52 D81 ^ D54 D79 +error(0.0003174867051203577348) D52 D81 ^ D54 L0 +error(0.0005499328591647120778) D52 D81 ^ D78 D79 +error(0.0002857008089304124607) D52 D81 ^ D78 L0 +error(0.002378588767130583072) D52 D82 +error(0.001993144322145359512) D52 D82 ^ D54 D55 +error(0.0008444018024559791016) D52 D82 ^ D54 D78 +error(0.001376119481102591443) D52 D82 ^ D54 D79 +error(0.0007272918137137072275) D52 D82 ^ D55 D79 +error(0.001961341429606960809) D52 D82 ^ D78 D79 +error(0.01000000000000000021) D53 +error(0.003847026731771674424) D53 D76 +error(0.0007232425406817723831) D53 D76 ^ D79 D80 +error(0.021773936634121447) D53 D77 +error(0.001313798479028342953) D53 D77 ^ D79 D80 +error(0.003909402514313408024) D53 D82 +error(2.28104599996947481e-05) D53 D82 ^ D54 D79 +error(0.001083963797513874021) D53 D82 ^ D55 D79 +error(0.001120537449371218847) D53 ^ D21 ^ D25 +error(0.0008172106260104618561) D53 ^ D21 ^ D49 +error(0.0005108386865572231861) D53 ^ D25 +error(0.0001863077870320663395) D53 ^ D49 +error(0.006594162824587600225) D54 D55 +error(0.0005302971071338037764) D54 D55 ^ D57 D58 +error(0.002288777333365739179) D54 D55 ^ D58 D82 +error(0.0006884153111551963907) D54 D55 ^ D82 +error(0.03612550294212107937) D54 D78 +error(0.003986180069234413967) D54 D78 ^ D81 D82 +error(0.004298078915946801359) D54 D79 +error(0.0004818218312557076663) D54 D79 ^ D81 D82 +error(0.001625657018947900294) D54 D83 +error(0.0008012212761801838301) D54 D83 ^ D58 +error(0.001191671275737970267) D54 D83 ^ D58 D82 +error(0.000232923489534182565) D54 D83 ^ D82 +error(0.01000000000000000021) D54 L0 +error(0.01716894250448478682) D55 D56 +error(0.002238140370461111014) D55 D56 ^ D29 +error(0.01179623936683424357) D55 D56 ^ D53 +error(0.0005036757841566641674) D55 D56 ^ D58 +error(0.0002452144902547899984) D55 D56 ^ D58 ^ D29 +error(0.01685999773330407528) D55 D59 +error(0.01670462336830163749) D55 D59 ^ D58 +error(0.02173700185701750789) D55 D79 +error(0.001786549131622320371) D55 D79 ^ D53 +error(0.003912722710223686708) D55 D79 ^ D82 +error(0.002382500552628285216) D55 D80 +error(0.003284071404981582943) D55 D80 ^ D53 +error(0.0001814293687345641638) D55 D80 ^ D82 +error(0.0002952472760400955132) D55 D80 ^ D82 ^ D53 +error(0.003550633146921626862) D55 D83 +error(0.002950093029550475334) D55 D83 ^ D58 +error(0.004198020730678931646) D55 D83 ^ D82 +error(0.001191252727279817816) D55 D83 ^ D82 ^ D58 +error(0.02426465096103480254) D56 D80 +error(0.002887796181740957552) D56 D80 ^ D53 +error(0.007162167235623141323) D57 D58 +error(0.002013473804351892382) D57 D58 ^ D30 L0 +error(0.01188727626700753111) D57 D58 ^ D54 L0 +error(0.0006652180026593396264) D57 D58 ^ D59 L0 +error(0.0005288284790378269427) D57 D58 ^ D59 L0 ^ D30 L0 +error(0.03021538745065696641) D57 D81 +error(0.003655842737286960943) D57 D81 ^ D54 L0 +error(0.01000000000000000021) D58 +error(0.003072153014909577255) D58 D81 +error(0.002126355402752911228) D58 D81 ^ D54 L0 +error(0.0003891207497752700428) D58 D81 ^ D83 L0 +error(0.0004039352375315962947) D58 D81 ^ D83 L0 ^ D54 L0 +error(0.01966590043670931112) D58 D82 +error(0.00116697850444044183) D58 D82 ^ D54 L0 +error(0.002302712672173879219) D58 D82 ^ D83 L0 +error(0.00838775502972349471) D58 ^ D59 L0 +error(0.0008925839347452218337) D58 ^ D83 L0 +error(0.002919826675589398159) D59 D83 ^ D58 +error(0.01792671575261539293) D59 D83 +error(0.01159417794901059125) D59 L0 +error(0.005000000000000000104) D60 +error(0.01660438028321272949) D60 D64 +error(0.01779114294423248324) D60 D64 ^ D61 +error(0.02699148979780703964) D60 D84 +error(0.006834185536959506806) D60 D84 ^ D85 +error(0.007139333438785943654) D60 D88 +error(0.005071311220259624129) D60 D88 ^ D61 +error(0.003814151212458829175) D60 D88 ^ D85 +error(0.003241496548438547141) D60 D88 ^ D85 ^ D61 +error(0.003298463924975283609) D60 D89 +error(0.0005561199418532474046) D60 D89 ^ D61 +error(0.003357711680800872477) D60 D89 ^ D61 D85 +error(0.0001277368780254523777) D60 D89 ^ D85 +error(0.00612165296323359618) D60 ^ D61 +error(0.001411320666902509541) D60 ^ D85 +error(0.003813414387094213234) D61 D85 ^ D60 +error(0.01000000000000000021) D61 +error(0.007776687944794747655) D61 D62 +error(0.0002239251782426420899) D61 D62 ^ D60 +error(0.0006578014119039935111) D61 D62 ^ D64 D65 +error(9.807043003152089201e-05) D61 D62 ^ D64 D89 +error(0.01462632812957779041) D61 D62 ^ D65 +error(0.00451851992816860136) D61 D62 ^ D65 D89 +error(0.002686865629807736865) D61 D62 ^ D89 +error(0.0008975063743248118788) D61 D62 ^ D89 ^ D60 +error(0.02004352178629314682) D61 D67 +error(0.0126538281966155023) D61 D67 ^ D64 D65 +error(0.04091880631186525091) D61 D85 +error(0.002653181116343675261) D61 D85 ^ D88 D89 +error(0.003298283945553052033) D61 D85 ^ D89 +error(0.00339519176841894272) D61 D90 +error(0.001582986769424157402) D61 D90 ^ D64 D88 +error(0.0004380064685231338712) D61 D90 ^ D64 D89 +error(0.003113535398603530131) D61 D91 +error(0.00247782554596669884) D61 D91 ^ D64 D65 +error(0.001028637261928361376) D61 D91 ^ D64 D88 +error(0.00160650879303555344) D61 D91 ^ D64 D89 +error(0.002443953285749952357) D61 D91 ^ D88 D89 +error(0.01501988426115019766) D62 D68 +error(0.01690133780623802318) D62 D68 ^ D65 +error(0.006342401933687971671) D62 D85 +error(5.731474309590040581e-06) D62 D85 ^ D60 +error(0.004735574936250143592) D62 D85 ^ D89 +error(0.001109758085417464736) D62 D85 ^ D89 ^ D60 +error(0.02590702726501740299) D62 D86 +error(0.01055432121765075004) D62 D86 ^ D89 +error(0.002067699089454209764) D62 D91 +error(0.0004764857434993141063) D62 D91 ^ D64 D65 +error(0.00018791695239074924) D62 D91 ^ D64 D89 +error(0.000543812216206917675) D62 D91 ^ D65 +error(0.002265746668965656213) D62 D91 ^ D65 D89 +error(0.001367685511860447251) D62 D91 ^ D89 +error(0.003309490384053264886) D62 D92 +error(0.002654443592163411442) D62 D92 ^ D65 +error(0.00302472805964318402) D62 D92 ^ D89 +error(0.001061960255450209193) D62 D92 ^ D89 ^ D65 +error(0.008208999602450065339) D63 D64 +error(0.0002490393643702508214) D63 D64 ^ D61 +error(0.008432084388650621515) D63 D64 ^ D66 +error(0.0004018075719304165026) D63 D64 ^ D66 D67 +error(0.002531254512948871455) D63 D64 ^ D66 D90 +error(0.002283206907119589377) D63 D64 ^ D90 +error(0.0003647493962551453281) D63 D64 ^ D90 ^ D61 +error(0.01230414654041589451) D63 D70 +error(0.0105586013131753146) D63 D70 ^ D66 +error(0.02206797080950753318) D63 D87 +error(0.003109218220584021499) D63 D87 ^ D90 +error(0.001665473620494837799) D63 D88 +error(0.000751710629973935591) D63 D88 ^ D61 +error(0.002616716571845408533) D63 D88 ^ D90 +error(0.0002422723007377827135) D63 D88 ^ D90 ^ D61 +error(0.002331702848199883327) D63 D94 +error(0.003286376590100200615) D63 D94 ^ D66 +error(0.0016367579652731808) D63 D94 ^ D90 +error(0.0007603124886256211598) D63 D94 ^ D90 ^ D66 +error(0.002579757563572948522) D63 D95 +error(0.0001718132299533660715) D63 D95 ^ D66 +error(0.0001444887456803655346) D63 D95 ^ D66 D67 +error(0.001149196219717257958) D63 D95 ^ D66 D90 +error(1.120540756098161018e-05) D63 D95 ^ D67 D90 +error(0.0005057057902715079122) D63 D95 ^ D90 +error(0.00860417189101998249) D64 D65 +error(0.0008996636785346223512) D64 D65 ^ D37 +error(0.0007682366505013531362) D64 D65 ^ D66 D67 +error(0.0001543284317303631468) D64 D65 ^ D67 D68 +error(0.001413973100792486779) D64 D65 ^ D67 D91 +error(0.0001724825413106183519) D64 D65 ^ D68 D91 +error(0.01514009713272307031) D64 D71 +error(0.008955358603158896161) D64 D71 ^ D66 D67 +error(0.02572510637435859032) D64 D88 +error(0.007006310296506031501) D64 D88 ^ D61 +error(0.001316794376174020356) D64 D88 ^ D90 +error(0.002641791500945908124) D64 D88 ^ D90 D91 +error(0.003414039823895323716) D64 D89 +error(0.0006897576085226444272) D64 D89 ^ D90 D91 +error(0.001694614774715204851) D64 D95 +error(0.002644592536818960674) D64 D95 ^ D66 D67 +error(0.0009441644247071477548) D64 D95 ^ D66 D90 +error(0.001928777394211658768) D64 D95 ^ D67 D90 +error(0.00133008307762702495) D64 D95 ^ D67 D91 +error(0.001038771671501572628) D64 D95 ^ D90 D91 +error(0.0007323574101554897534) D64 D96 +error(0.0006847265269601655836) D64 D96 ^ D67 D68 +error(0.000653390831884755204) D64 D96 ^ D67 D90 +error(0.001523171598481931144) D64 D96 ^ D67 D91 +error(7.585149492345969401e-05) D64 D96 ^ D68 D91 +error(0.0003362069066020665037) D64 D96 ^ D90 D91 +error(0.01000000000000000021) D65 +error(0.02118071892183423163) D65 D72 +error(0.01736477246236184033) D65 D72 ^ D67 D68 +error(0.03300215916333530675) D65 D89 +error(0.00216592434550165339) D65 D89 ^ D91 D92 +error(0.004503622582071078496) D65 D96 +error(0.002318254759649248948) D65 D96 ^ D67 D68 +error(0.000376482607813980331) D65 D96 ^ D67 D91 +error(0.001747378805460943121) D65 D96 ^ D68 D91 +error(0.000593531763207356261) D65 D96 ^ D68 D92 +error(0.00215641765716670028) D65 D96 ^ D91 D92 +error(0.0005765516027016854509) D65 D97 ^ D68 D91 +error(0.0008586384286019724905) D65 D97 ^ D68 D92 +error(0.0004389250296211264098) D65 D97 ^ D91 D92 +error(0.01000000000000000021) D66 +error(0.009521520337646336568) D66 D67 +error(0.0008398031791907709142) D66 D67 ^ D70 D71 +error(0.0004021940016688471133) D66 D67 ^ D70 D95 +error(0.0005440209884140075275) D66 D67 ^ D71 D72 +error(0.002080156153275584171) D66 D67 ^ D71 D95 +error(0.01675364273324095668) D66 D75 +error(0.01174642302711653881) D66 D75 ^ D70 D71 +error(0.03443641348695664767) D66 D90 +error(0.002395055567470361167) D66 D90 ^ D94 D95 +error(0.002124958655053427441) D66 D98 +error(0.00220015674251626157) D66 D98 ^ D70 D94 +error(0.0004947019958325036496) D66 D98 ^ D70 D95 +error(0.000374511620403463689) D66 D98 ^ D94 D95 +error(0.004183529412601343783) D66 D99 +error(0.001754250315696467616) D66 D99 ^ D70 D71 +error(0.001890722784335428699) D66 D99 ^ D70 D94 +error(0.002250793337517553033) D66 D99 ^ D70 D95 +error(0.0007981997197410908157) D66 D99 ^ D71 D95 +error(0.001107907099724317985) D66 D99 ^ D94 D95 +error(0.0007396770146007538736) D66 ^ D94 L0 +error(0.00259721580293025044) D70 D94 ^ D66 +error(0.00729955180669228116) D67 D68 +error(5.062381541878982895e-05) D67 D68 ^ D41 +error(0.001030199975533826117) D67 D68 ^ D65 +error(0.0006584229463454448032) D67 D68 ^ D71 D72 +error(0.0001692053819037444857) D67 D68 ^ D71 D96 +error(0.0004254426911218613431) D67 D68 ^ D72 D73 +error(0.002214135018659018229) D67 D68 ^ D72 D96 +error(0.01623214291849352578) D67 D76 +error(0.01451260695679871225) D67 D76 ^ D71 D72 +error(0.003460367052192838376) D67 D90 +error(0.001095315529918634281) D67 D90 ^ D95 D96 +error(0.03984696727665810317) D67 D91 +error(0.001792163974324219007) D67 D91 ^ D95 D96 +error(0.001844556973055879161) D67 D99 +error(0.002352941691835960802) D67 D99 ^ D71 D95 +error(0.0004755448116354408215) D67 D99 ^ D71 D96 +error(0.0003335880933664818145) D67 D99 ^ D95 D96 +error(0.00299129553800945051) D67 D100 +error(0.001643907901120499624) D67 D100 ^ D71 D72 +error(0.0007920510235761922101) D67 D100 ^ D71 D95 +error(0.001755098518752947574) D67 D100 ^ D71 D96 +error(0.0006409651334938055956) D67 D100 ^ D72 D96 +error(0.002713297683053161272) D67 D100 ^ D95 D96 +error(0.009726903041435587885) D68 D69 +error(0.0003191744926083531198) D68 D69 ^ D65 +error(0.0006579173063691476581) D68 D69 ^ D72 D73 +error(0.0003869704899424970443) D68 D69 ^ D72 D97 +error(0.01220834273285227936) D68 D69 ^ D73 +error(0.00477129132198987789) D68 D69 ^ D73 D97 +error(0.002544666137518753445) D68 D69 ^ D97 +error(4.700906300686508247e-05) D68 D69 ^ D97 ^ D65 +error(0.01240604439279997979) D68 D77 +error(0.01094083605793164625) D68 D77 ^ D72 D73 +error(0.002545582488314489331) D68 D91 +error(0.0002826741056434087999) D68 D91 ^ D96 D97 +error(0.02075246121853630346) D68 D92 +error(0.004958470660349788284) D68 D92 ^ D65 +error(0.002257108386287591615) D68 D92 ^ D96 D97 +error(0.00124140148644221425) D68 D92 ^ D97 +error(0.002991512510671469512) D68 D100 +error(0.00177039048010369654) D68 D100 ^ D72 D96 +error(0.0003836293688450126611) D68 D100 ^ D72 D97 +error(0.0002262264940501502628) D68 D100 ^ D96 D97 +error(0.002041760540690738378) D68 D101 +error(0.002387441767965157308) D68 D101 ^ D72 D73 +error(0.0007494691992875175896) D68 D101 ^ D72 D96 +error(0.002474731958226495526) D68 D101 ^ D72 D97 +error(0.0009794943867816497014) D68 D101 ^ D73 D97 +error(0.002171252964640886084) D68 D101 ^ D96 D97 +error(0.01102841403074931829) D69 +error(0.001936390295073753699) D69 D92 +error(0.0003618605530372149084) D69 D92 ^ D65 +error(0.002183311663915940733) D69 D92 ^ D97 +error(3.448864583775733021e-05) D69 D92 ^ D97 ^ D65 +error(0.02852939423101608432) D69 D93 +error(0.004253581368126741966) D69 D93 ^ D97 +error(0.002900611666390966702) D69 D101 +error(0.003037154267016145548) D69 D101 ^ D73 D97 +error(0.01597507063807540942) D69 ^ D73 +error(0.001702405640180595101) D69 ^ D97 ^ D73 +error(0.01776770169544816466) D70 D71 +error(0.0001196824171128900416) D70 D71 ^ D42 +error(0.0006586128121373966554) D70 D71 ^ D74 D75 +error(0.002175366124230702306) D70 D71 ^ D75 D99 +error(0.0002506984111203783999) D70 D71 ^ D76 D99 +error(0.04739892754396989039) D70 D94 +error(0.003781829997311276104) D70 D94 ^ D98 D99 +error(0.002334841659936933052) D70 D95 +error(0.0009422456726712663197) D70 D95 ^ D98 D99 +error(0.0007049855875566741993) D70 D102 ^ D75 D76 +error(0.001934639851703026398) D70 D102 ^ D75 D99 +error(0.0002735044682239881077) D70 D102 ^ D76 D99 +error(0.01111336289536665051) D70 L0 +error(0.01173226287006574539) D70 L0 ^ D74 +error(0.003567715602164565989) D74 D98 ^ D70 L0 +error(0.0219173104120194244) D71 D72 +error(0.0006160258984500803633) D71 D72 ^ D75 D76 +error(6.315642213795687697e-05) D71 D72 ^ D76 D77 +error(0.002992427214964349901) D71 D72 ^ D76 D100 +error(0.0006609289947131321468) D71 D72 ^ D77 D100 +error(0.01946623581067056727) D71 D78 +error(0.01983614692690993664) D71 D78 ^ D75 D76 +error(0.02642383597330793393) D71 D95 +error(0.003024115804548305978) D71 D95 ^ D99 D100 +error(0.004707627181439803972) D71 D96 +error(0.0003746037177654245069) D71 D96 ^ D99 D100 +error(0.004350875619841032375) D71 D102 +error(0.005915511216720588557) D71 D102 ^ D75 D76 +error(0.001531588657764103561) D71 D102 ^ D75 D99 +error(0.008051354027943246824) D71 D102 ^ D76 D99 +error(0.001525927110233388445) D71 D102 ^ D76 D100 +error(0.003669458466892536359) D71 D102 ^ D99 D100 +error(0.002791113896069163328) D71 D103 +error(0.0006265920696080439726) D71 D103 ^ D76 D77 +error(4.779545894811885375e-05) D71 D103 ^ D76 D99 +error(0.0007337775853727664457) D71 D103 ^ D76 D100 +error(0.000542119306178530532) D71 D103 ^ D77 D100 +error(0.0003556315259281220406) D71 D103 ^ D99 D100 +error(0.007713185277822201882) D72 D73 +error(0.0002906218459867560932) D72 D73 ^ D77 +error(0.001951411826540530581) D72 D73 ^ D77 D101 +error(0.0001363990548493697222) D72 D73 ^ D101 +error(0.01427946177760987603) D72 D79 +error(0.009134401807325989373) D72 D79 ^ D76 D77 +error(0.02052822027627665413) D72 D96 +error(0.001984955007885169133) D72 D96 ^ D100 D101 +error(0.003128856462034781266) D72 D97 +error(0.0002188780272270664273) D72 D97 ^ D100 D101 +error(0.001173221145237272195) D72 D103 +error(0.00202756533973686608) D72 D103 ^ D76 D77 +error(0.0009147160160308196722) D72 D103 ^ D76 D100 +error(0.002478108585635494659) D72 D103 ^ D77 D100 +error(0.001252272042733494281) D72 D103 ^ D77 D101 +error(0.001947257464455566869) D72 D103 ^ D100 D101 +error(0.001123225366079328791) D72 D104 +error(6.005638908915711567e-05) D72 D104 ^ D77 +error(0.000421482864719889105) D72 D104 ^ D77 D100 +error(0.001261954426493605216) D72 D104 ^ D77 D101 +error(0.0001351826321506347569) D72 D104 ^ D100 D101 +error(0.00011199461596045396) D72 D104 ^ D101 +error(0.01094531334540550273) D73 +error(0.01538736176745019411) D73 D80 +error(0.0169485703355046792) D73 D80 ^ D77 +error(0.02209321612236390953) D73 D97 +error(0.002316639550606935157) D73 D97 ^ D101 +error(0.002146002416089138123) D73 D104 +error(0.002290705055193476176) D73 D104 ^ D77 +error(0.003445577716713628998) D73 D104 ^ D101 +error(0.0008214406114134374529) D73 D104 ^ D101 ^ D77 +error(0.008881637178845576755) D74 +error(0.01495585212186280669) D74 D75 +error(0.003695710743442946148) D74 D75 ^ D46 L0 +error(0.01799833116646069181) D74 D75 ^ D70 L0 +error(0.0004997383954729171145) D74 D75 ^ D78 L0 ^ D46 L0 +error(0.01987675887419782655) D74 D98 +error(0.0003296412873835849575) D74 ^ D42 ^ D46 L0 +error(0.0008096266067650861225) D74 ^ D70 L0 ^ D46 L0 +error(0.01506431211196329958) D75 D76 +error(0.0007457400519393364569) D75 D76 ^ D78 D79 +error(0.004363752286817622859) D75 D76 ^ D78 D102 +error(0.01385586789355772348) D75 D81 +error(0.01109776885461767094) D75 D81 ^ D78 L0 +error(0.005113701422269139804) D75 D98 +error(0.002144750650696250309) D75 D98 ^ D70 L0 +error(0.0005987071700741438676) D75 D98 ^ D102 L0 ^ D70 L0 +error(0.02694960105961625996) D75 D99 +error(0.0007380027204231738884) D75 D99 ^ D70 L0 +error(0.003721016964483825438) D75 D99 ^ D102 L0 +error(0.00189763058632084103) D75 D105 +error(0.002269670075562741068) D75 D105 ^ D78 L0 +error(0.003018302741455952676) D75 D105 ^ D102 L0 +error(0.0007595842134098546722) D75 D105 ^ D102 L0 ^ D78 L0 +error(0.01169871816276893753) D76 D77 +error(0.0004563423471117930195) D76 D77 ^ D78 D79 +error(0.0004944029476380669896) D76 D77 ^ D78 D103 +error(0.0004058715760627647413) D76 D77 ^ D79 D80 +error(0.00250279860763223715) D76 D77 ^ D79 D103 +error(0.01304884676936473968) D76 D82 +error(0.01084325194016807527) D76 D82 ^ D78 D79 +error(0.005038329940921605632) D76 D99 +error(0.0005822770362989852701) D76 D99 ^ D102 D103 +error(0.02718987902130082929) D76 D100 +error(0.001729643906341211826) D76 D100 ^ D102 D103 +error(0.002008286380084761159) D76 D105 +error(0.001184019355023896696) D76 D105 ^ D78 D102 +error(0.0001331019283698714549) D76 D105 ^ D78 D103 +error(0.0003174867051203577348) D76 D105 ^ D78 L0 +error(0.0005499328591647120778) D76 D105 ^ D102 D103 +error(0.0002857008089304124607) D76 D105 ^ D102 L0 +error(0.002378588767130583072) D76 D106 +error(0.001993144322145359512) D76 D106 ^ D78 D79 +error(0.0008444018024559791016) D76 D106 ^ D78 D102 +error(0.001376119481102591443) D76 D106 ^ D78 D103 +error(0.0007272918137137072275) D76 D106 ^ D79 D103 +error(0.001961341429606960809) D76 D106 ^ D102 D103 +error(0.01000000000000000021) D77 +error(0.003847026731771674424) D77 D100 +error(0.0007232425406817723831) D77 D100 ^ D103 D104 +error(0.021773936634121447) D77 D101 +error(0.001313798479028342953) D77 D101 ^ D103 D104 +error(0.003909402514313408024) D77 D106 +error(2.28104599996947481e-05) D77 D106 ^ D78 D103 +error(0.001083963797513874021) D77 D106 ^ D79 D103 +error(0.001120537449371218847) D77 ^ D45 ^ D49 +error(0.0008172106260104618561) D77 ^ D45 ^ D73 +error(0.0005108386865572231861) D77 ^ D49 +error(0.0001863077870320663395) D77 ^ D73 +error(0.006594162824587600225) D78 D79 +error(0.0005302971071338037764) D78 D79 ^ D81 D82 +error(0.002288777333365739179) D78 D79 ^ D82 D106 +error(0.0006884153111551963907) D78 D79 ^ D106 +error(0.03612550294212107937) D78 D102 +error(0.003986180069234413967) D78 D102 ^ D105 D106 +error(0.004298078915946801359) D78 D103 +error(0.0004818218312557076663) D78 D103 ^ D105 D106 +error(0.001625657018947900294) D78 D107 +error(0.0008012212761801838301) D78 D107 ^ D82 +error(0.001191671275737970267) D78 D107 ^ D82 D106 +error(0.000232923489534182565) D78 D107 ^ D106 +error(0.01000000000000000021) D78 L0 +error(0.01716894250448478682) D79 D80 +error(0.002238140370461111014) D79 D80 ^ D53 +error(0.01179623936683424357) D79 D80 ^ D77 +error(0.0005036757841566641674) D79 D80 ^ D82 +error(0.0002452144902547899984) D79 D80 ^ D82 ^ D53 +error(0.01685999773330407528) D79 D83 +error(0.01670462336830163749) D79 D83 ^ D82 +error(0.02173700185701750789) D79 D103 +error(0.001786549131622320371) D79 D103 ^ D77 +error(0.003912722710223686708) D79 D103 ^ D106 +error(0.002382500552628285216) D79 D104 +error(0.003284071404981582943) D79 D104 ^ D77 +error(0.0001814293687345641638) D79 D104 ^ D106 +error(0.0002952472760400955132) D79 D104 ^ D106 ^ D77 +error(0.003550633146921626862) D79 D107 +error(0.002950093029550475334) D79 D107 ^ D82 +error(0.004198020730678931646) D79 D107 ^ D106 +error(0.001191252727279817816) D79 D107 ^ D106 ^ D82 +error(0.02426465096103480254) D80 D104 +error(0.002887796181740957552) D80 D104 ^ D77 +error(0.007162167235623141323) D81 D82 +error(0.002013473804351892382) D81 D82 ^ D54 L0 +error(0.01188727626700753111) D81 D82 ^ D78 L0 +error(0.0006652180026593396264) D81 D82 ^ D83 L0 +error(0.0005288284790378269427) D81 D82 ^ D83 L0 ^ D54 L0 +error(0.03021538745065696641) D81 D105 +error(0.003655842737286960943) D81 D105 ^ D78 L0 +error(0.01000000000000000021) D82 +error(0.003072153014909577255) D82 D105 +error(0.002126355402752911228) D82 D105 ^ D78 L0 +error(0.0003891207497752700428) D82 D105 ^ D107 L0 +error(0.0004039352375315962947) D82 D105 ^ D107 L0 ^ D78 L0 +error(0.01966590043670931112) D82 D106 +error(0.00116697850444044183) D82 D106 ^ D78 L0 +error(0.002302712672173879219) D82 D106 ^ D107 L0 +error(0.00838775502972349471) D82 ^ D83 L0 +error(0.0008925839347452218337) D82 ^ D107 L0 +error(0.002919826675589398159) D83 D107 ^ D82 +error(0.01792671575261539293) D83 D107 +error(0.01159417794901059125) D83 L0 +error(0.005000000000000000104) D84 +error(0.01660438028321272949) D84 D88 +error(0.01779114294423248324) D84 D88 ^ D85 +error(0.02699148979780703964) D84 D108 +error(0.006834185536959506806) D84 D108 ^ D109 +error(0.007139333438785943654) D84 D112 +error(0.005071311220259624129) D84 D112 ^ D85 +error(0.003814151212458829175) D84 D112 ^ D109 +error(0.003241496548438547141) D84 D112 ^ D109 ^ D85 +error(0.003298463924975283609) D84 D113 +error(0.0005561199418532474046) D84 D113 ^ D85 +error(0.003357711680800872477) D84 D113 ^ D85 D109 +error(0.0001277368780254523777) D84 D113 ^ D109 +error(0.00612165296323359618) D84 ^ D85 +error(0.001411320666902509541) D84 ^ D109 +error(0.003813414387094213234) D85 D109 ^ D84 +error(0.01000000000000000021) D85 +error(0.007776687944794747655) D85 D86 +error(0.0002239251782426420899) D85 D86 ^ D84 +error(0.0006578014119039935111) D85 D86 ^ D88 D89 +error(9.807043003152089201e-05) D85 D86 ^ D88 D113 +error(0.01462632812957779041) D85 D86 ^ D89 +error(0.00451851992816860136) D85 D86 ^ D89 D113 +error(0.002686865629807736865) D85 D86 ^ D113 +error(0.0008975063743248118788) D85 D86 ^ D113 ^ D84 +error(0.02004352178629314682) D85 D91 +error(0.0126538281966155023) D85 D91 ^ D88 D89 +error(0.04091880631186525091) D85 D109 +error(0.002653181116343675261) D85 D109 ^ D112 D113 +error(0.003298283945553052033) D85 D109 ^ D113 +error(0.00339519176841894272) D85 D114 +error(0.001582986769424157402) D85 D114 ^ D88 D112 +error(0.0004380064685231338712) D85 D114 ^ D88 D113 +error(0.003113535398603530131) D85 D115 +error(0.00247782554596669884) D85 D115 ^ D88 D89 +error(0.001028637261928361376) D85 D115 ^ D88 D112 +error(0.00160650879303555344) D85 D115 ^ D88 D113 +error(0.002443953285749952357) D85 D115 ^ D112 D113 +error(0.01501988426115019766) D86 D92 +error(0.01690133780623802318) D86 D92 ^ D89 +error(0.006342401933687971671) D86 D109 +error(5.731474309590040581e-06) D86 D109 ^ D84 +error(0.004735574936250143592) D86 D109 ^ D113 +error(0.001109758085417464736) D86 D109 ^ D113 ^ D84 +error(0.02590702726501740299) D86 D110 +error(0.01055432121765075004) D86 D110 ^ D113 +error(0.002067699089454209764) D86 D115 +error(0.0004764857434993141063) D86 D115 ^ D88 D89 +error(0.00018791695239074924) D86 D115 ^ D88 D113 +error(0.000543812216206917675) D86 D115 ^ D89 +error(0.002265746668965656213) D86 D115 ^ D89 D113 +error(0.001367685511860447251) D86 D115 ^ D113 +error(0.003309490384053264886) D86 D116 +error(0.002654443592163411442) D86 D116 ^ D89 +error(0.00302472805964318402) D86 D116 ^ D113 +error(0.001061960255450209193) D86 D116 ^ D113 ^ D89 +error(0.008208999602450065339) D87 D88 +error(0.0002490393643702508214) D87 D88 ^ D85 +error(0.008432084388650621515) D87 D88 ^ D90 +error(0.0004018075719304165026) D87 D88 ^ D90 D91 +error(0.002531254512948871455) D87 D88 ^ D90 D114 +error(0.002283206907119589377) D87 D88 ^ D114 +error(0.0003647493962551453281) D87 D88 ^ D114 ^ D85 +error(0.01230414654041589451) D87 D94 +error(0.0105586013131753146) D87 D94 ^ D90 +error(0.02206797080950753318) D87 D111 +error(0.003109218220584021499) D87 D111 ^ D114 +error(0.001665473620494837799) D87 D112 +error(0.000751710629973935591) D87 D112 ^ D85 +error(0.002616716571845408533) D87 D112 ^ D114 +error(0.0002422723007377827135) D87 D112 ^ D114 ^ D85 +error(0.002331702848199883327) D87 D118 +error(0.003286376590100200615) D87 D118 ^ D90 +error(0.0016367579652731808) D87 D118 ^ D114 +error(0.0007603124886256211598) D87 D118 ^ D114 ^ D90 +error(0.002579757563572948522) D87 D119 +error(0.0001718132299533660715) D87 D119 ^ D90 +error(0.0001444887456803655346) D87 D119 ^ D90 D91 +error(0.001149196219717257958) D87 D119 ^ D90 D114 +error(1.120540756098161018e-05) D87 D119 ^ D91 D114 +error(0.0005057057902715079122) D87 D119 ^ D114 +error(0.00860417189101998249) D88 D89 +error(0.0008996636785346223512) D88 D89 ^ D61 +error(0.0007682366505013531362) D88 D89 ^ D90 D91 +error(0.0001543284317303631468) D88 D89 ^ D91 D92 +error(0.001413973100792486779) D88 D89 ^ D91 D115 +error(0.0001724825413106183519) D88 D89 ^ D92 D115 +error(0.01514009713272307031) D88 D95 +error(0.008955358603158896161) D88 D95 ^ D90 D91 +error(0.02572510637435859032) D88 D112 +error(0.007006310296506031501) D88 D112 ^ D85 +error(0.001316794376174020356) D88 D112 ^ D114 +error(0.002641791500945908124) D88 D112 ^ D114 D115 +error(0.003414039823895323716) D88 D113 +error(0.0006897576085226444272) D88 D113 ^ D114 D115 +error(0.001694614774715204851) D88 D119 +error(0.002644592536818960674) D88 D119 ^ D90 D91 +error(0.0009441644247071477548) D88 D119 ^ D90 D114 +error(0.001928777394211658768) D88 D119 ^ D91 D114 +error(0.00133008307762702495) D88 D119 ^ D91 D115 +error(0.001038771671501572628) D88 D119 ^ D114 D115 +error(0.0007323574101554897534) D88 D120 +error(0.0006847265269601655836) D88 D120 ^ D91 D92 +error(0.000653390831884755204) D88 D120 ^ D91 D114 +error(0.001523171598481931144) D88 D120 ^ D91 D115 +error(7.585149492345969401e-05) D88 D120 ^ D92 D115 +error(0.0003362069066020665037) D88 D120 ^ D114 D115 +error(0.01000000000000000021) D89 +error(0.02118071892183423163) D89 D96 +error(0.01736477246236184033) D89 D96 ^ D91 D92 +error(0.03300215916333530675) D89 D113 +error(0.00216592434550165339) D89 D113 ^ D115 D116 +error(0.004503622582071078496) D89 D120 +error(0.002318254759649248948) D89 D120 ^ D91 D92 +error(0.000376482607813980331) D89 D120 ^ D91 D115 +error(0.001747378805460943121) D89 D120 ^ D92 D115 +error(0.000593531763207356261) D89 D120 ^ D92 D116 +error(0.00215641765716670028) D89 D120 ^ D115 D116 +error(0.0005765516027016854509) D89 D121 ^ D92 D115 +error(0.0008586384286019724905) D89 D121 ^ D92 D116 +error(0.0004389250296211264098) D89 D121 ^ D115 D116 +error(0.01000000000000000021) D90 +error(0.009521520337646336568) D90 D91 +error(0.0008398031791907709142) D90 D91 ^ D94 D95 +error(0.0004021940016688471133) D90 D91 ^ D94 D119 +error(0.0005440209884140075275) D90 D91 ^ D95 D96 +error(0.002080156153275584171) D90 D91 ^ D95 D119 +error(0.01675364273324095668) D90 D99 +error(0.01174642302711653881) D90 D99 ^ D94 D95 +error(0.03443641348695664767) D90 D114 +error(0.002395055567470361167) D90 D114 ^ D118 D119 +error(0.002124958655053427441) D90 D122 +error(0.00220015674251626157) D90 D122 ^ D94 D118 +error(0.0004947019958325036496) D90 D122 ^ D94 D119 +error(0.000374511620403463689) D90 D122 ^ D118 D119 +error(0.004183529412601343783) D90 D123 +error(0.001754250315696467616) D90 D123 ^ D94 D95 +error(0.001890722784335428699) D90 D123 ^ D94 D118 +error(0.002250793337517553033) D90 D123 ^ D94 D119 +error(0.0007981997197410908157) D90 D123 ^ D95 D119 +error(0.001107907099724317985) D90 D123 ^ D118 D119 +error(0.0007396770146007538736) D90 ^ D118 L0 +error(0.00259721580293025044) D94 D118 ^ D90 +error(0.00729955180669228116) D91 D92 +error(5.062381541878982895e-05) D91 D92 ^ D65 +error(0.001030199975533826117) D91 D92 ^ D89 +error(0.0006584229463454448032) D91 D92 ^ D95 D96 +error(0.0001692053819037444857) D91 D92 ^ D95 D120 +error(0.0004254426911218613431) D91 D92 ^ D96 D97 +error(0.002214135018659018229) D91 D92 ^ D96 D120 +error(0.01623214291849352578) D91 D100 +error(0.01451260695679871225) D91 D100 ^ D95 D96 +error(0.003460367052192838376) D91 D114 +error(0.001095315529918634281) D91 D114 ^ D119 D120 +error(0.03984696727665810317) D91 D115 +error(0.001792163974324219007) D91 D115 ^ D119 D120 +error(0.001844556973055879161) D91 D123 +error(0.002352941691835960802) D91 D123 ^ D95 D119 +error(0.0004755448116354408215) D91 D123 ^ D95 D120 +error(0.0003335880933664818145) D91 D123 ^ D119 D120 +error(0.00299129553800945051) D91 D124 +error(0.001643907901120499624) D91 D124 ^ D95 D96 +error(0.0007920510235761922101) D91 D124 ^ D95 D119 +error(0.001755098518752947574) D91 D124 ^ D95 D120 +error(0.0006409651334938055956) D91 D124 ^ D96 D120 +error(0.002713297683053161272) D91 D124 ^ D119 D120 +error(0.009726903041435587885) D92 D93 +error(0.0003191744926083531198) D92 D93 ^ D89 +error(0.0006579173063691476581) D92 D93 ^ D96 D97 +error(0.0003869704899424970443) D92 D93 ^ D96 D121 +error(0.01220834273285227936) D92 D93 ^ D97 +error(0.00477129132198987789) D92 D93 ^ D97 D121 +error(0.002544666137518753445) D92 D93 ^ D121 +error(4.700906300686508247e-05) D92 D93 ^ D121 ^ D89 +error(0.01240604439279997979) D92 D101 +error(0.01094083605793164625) D92 D101 ^ D96 D97 +error(0.002545582488314489331) D92 D115 +error(0.0002826741056434087999) D92 D115 ^ D120 D121 +error(0.02075246121853630346) D92 D116 +error(0.004958470660349788284) D92 D116 ^ D89 +error(0.002257108386287591615) D92 D116 ^ D120 D121 +error(0.00124140148644221425) D92 D116 ^ D121 +error(0.002991512510671469512) D92 D124 +error(0.00177039048010369654) D92 D124 ^ D96 D120 +error(0.0003836293688450126611) D92 D124 ^ D96 D121 +error(0.0002262264940501502628) D92 D124 ^ D120 D121 +error(0.002041760540690738378) D92 D125 +error(0.002387441767965157308) D92 D125 ^ D96 D97 +error(0.0007494691992875175896) D92 D125 ^ D96 D120 +error(0.002474731958226495526) D92 D125 ^ D96 D121 +error(0.0009794943867816497014) D92 D125 ^ D97 D121 +error(0.002171252964640886084) D92 D125 ^ D120 D121 +error(0.01102841403074931829) D93 +error(0.001936390295073753699) D93 D116 +error(0.0003618605530372149084) D93 D116 ^ D89 +error(0.002183311663915940733) D93 D116 ^ D121 +error(3.448864583775733021e-05) D93 D116 ^ D121 ^ D89 +error(0.02852939423101608432) D93 D117 +error(0.004253581368126741966) D93 D117 ^ D121 +error(0.002900611666390966702) D93 D125 +error(0.003037154267016145548) D93 D125 ^ D97 D121 +error(0.01597507063807540942) D93 ^ D97 +error(0.001702405640180595101) D93 ^ D121 ^ D97 +error(0.01776770169544816466) D94 D95 +error(0.0001196824171128900416) D94 D95 ^ D66 +error(0.0006586128121373966554) D94 D95 ^ D98 D99 +error(0.002175366124230702306) D94 D95 ^ D99 D123 +error(0.0002506984111203783999) D94 D95 ^ D100 D123 +error(0.04739892754396989039) D94 D118 +error(0.003781829997311276104) D94 D118 ^ D122 D123 +error(0.002334841659936933052) D94 D119 +error(0.0009422456726712663197) D94 D119 ^ D122 D123 +error(0.0007049855875566741993) D94 D126 ^ D99 D100 +error(0.001934639851703026398) D94 D126 ^ D99 D123 +error(0.0002735044682239881077) D94 D126 ^ D100 D123 +error(0.01111336289536665051) D94 L0 +error(0.01173226287006574539) D94 L0 ^ D98 +error(0.003567715602164565989) D98 D122 ^ D94 L0 +error(0.0219173104120194244) D95 D96 +error(0.0006160258984500803633) D95 D96 ^ D99 D100 +error(6.315642213795687697e-05) D95 D96 ^ D100 D101 +error(0.002992427214964349901) D95 D96 ^ D100 D124 +error(0.0006609289947131321468) D95 D96 ^ D101 D124 +error(0.01946623581067056727) D95 D102 +error(0.01983614692690993664) D95 D102 ^ D99 D100 +error(0.02642383597330793393) D95 D119 +error(0.003024115804548305978) D95 D119 ^ D123 D124 +error(0.004707627181439803972) D95 D120 +error(0.0003746037177654245069) D95 D120 ^ D123 D124 +error(0.004350875619841032375) D95 D126 +error(0.005915511216720588557) D95 D126 ^ D99 D100 +error(0.001531588657764103561) D95 D126 ^ D99 D123 +error(0.008051354027943246824) D95 D126 ^ D100 D123 +error(0.001525927110233388445) D95 D126 ^ D100 D124 +error(0.003669458466892536359) D95 D126 ^ D123 D124 +error(0.002791113896069163328) D95 D127 +error(0.0006265920696080439726) D95 D127 ^ D100 D101 +error(4.779545894811885375e-05) D95 D127 ^ D100 D123 +error(0.0007337775853727664457) D95 D127 ^ D100 D124 +error(0.000542119306178530532) D95 D127 ^ D101 D124 +error(0.0003556315259281220406) D95 D127 ^ D123 D124 +error(0.007713185277822201882) D96 D97 +error(0.0002906218459867560932) D96 D97 ^ D101 +error(0.001951411826540530581) D96 D97 ^ D101 D125 +error(0.0001363990548493697222) D96 D97 ^ D125 +error(0.01427946177760987603) D96 D103 +error(0.009134401807325989373) D96 D103 ^ D100 D101 +error(0.02052822027627665413) D96 D120 +error(0.001984955007885169133) D96 D120 ^ D124 D125 +error(0.003128856462034781266) D96 D121 +error(0.0002188780272270664273) D96 D121 ^ D124 D125 +error(0.001173221145237272195) D96 D127 +error(0.00202756533973686608) D96 D127 ^ D100 D101 +error(0.0009147160160308196722) D96 D127 ^ D100 D124 +error(0.002478108585635494659) D96 D127 ^ D101 D124 +error(0.001252272042733494281) D96 D127 ^ D101 D125 +error(0.001947257464455566869) D96 D127 ^ D124 D125 +error(0.001123225366079328791) D96 D128 +error(6.005638908915711567e-05) D96 D128 ^ D101 +error(0.000421482864719889105) D96 D128 ^ D101 D124 +error(0.001261954426493605216) D96 D128 ^ D101 D125 +error(0.0001351826321506347569) D96 D128 ^ D124 D125 +error(0.00011199461596045396) D96 D128 ^ D125 +error(0.01094531334540550273) D97 +error(0.01538736176745019411) D97 D104 +error(0.0169485703355046792) D97 D104 ^ D101 +error(0.02209321612236390953) D97 D121 +error(0.002316639550606935157) D97 D121 ^ D125 +error(0.002146002416089138123) D97 D128 +error(0.002290705055193476176) D97 D128 ^ D101 +error(0.003445577716713628998) D97 D128 ^ D125 +error(0.0008214406114134374529) D97 D128 ^ D125 ^ D101 +error(0.008881637178845576755) D98 +error(0.01495585212186280669) D98 D99 +error(0.003695710743442946148) D98 D99 ^ D70 L0 +error(0.01799833116646069181) D98 D99 ^ D94 L0 +error(0.0004997383954729171145) D98 D99 ^ D102 L0 ^ D70 L0 +error(0.01987675887419782655) D98 D122 +error(0.0003296412873835849575) D98 ^ D66 ^ D70 L0 +error(0.0008096266067650861225) D98 ^ D94 L0 ^ D70 L0 +error(0.01506431211196329958) D99 D100 +error(0.0007457400519393364569) D99 D100 ^ D102 D103 +error(0.004363752286817622859) D99 D100 ^ D102 D126 +error(0.01385586789355772348) D99 D105 +error(0.01109776885461767094) D99 D105 ^ D102 L0 +error(0.005113701422269139804) D99 D122 +error(0.002144750650696250309) D99 D122 ^ D94 L0 +error(0.0005987071700741438676) D99 D122 ^ D126 L0 ^ D94 L0 +error(0.02694960105961625996) D99 D123 +error(0.0007380027204231738884) D99 D123 ^ D94 L0 +error(0.003721016964483825438) D99 D123 ^ D126 L0 +error(0.00189763058632084103) D99 D129 +error(0.002269670075562741068) D99 D129 ^ D102 L0 +error(0.003018302741455952676) D99 D129 ^ D126 L0 +error(0.0007595842134098546722) D99 D129 ^ D126 L0 ^ D102 L0 +error(0.01169871816276893753) D100 D101 +error(0.0004563423471117930195) D100 D101 ^ D102 D103 +error(0.0004944029476380669896) D100 D101 ^ D102 D127 +error(0.0004058715760627647413) D100 D101 ^ D103 D104 +error(0.00250279860763223715) D100 D101 ^ D103 D127 +error(0.01304884676936473968) D100 D106 +error(0.01084325194016807527) D100 D106 ^ D102 D103 +error(0.005038329940921605632) D100 D123 +error(0.0005822770362989852701) D100 D123 ^ D126 D127 +error(0.02718987902130082929) D100 D124 +error(0.001729643906341211826) D100 D124 ^ D126 D127 +error(0.002008286380084761159) D100 D129 +error(0.001184019355023896696) D100 D129 ^ D102 D126 +error(0.0001331019283698714549) D100 D129 ^ D102 D127 +error(0.0003174867051203577348) D100 D129 ^ D102 L0 +error(0.0005499328591647120778) D100 D129 ^ D126 D127 +error(0.0002857008089304124607) D100 D129 ^ D126 L0 +error(0.002378588767130583072) D100 D130 +error(0.001993144322145359512) D100 D130 ^ D102 D103 +error(0.0008444018024559791016) D100 D130 ^ D102 D126 +error(0.001376119481102591443) D100 D130 ^ D102 D127 +error(0.0007272918137137072275) D100 D130 ^ D103 D127 +error(0.001961341429606960809) D100 D130 ^ D126 D127 +error(0.01000000000000000021) D101 +error(0.003847026731771674424) D101 D124 +error(0.0007232425406817723831) D101 D124 ^ D127 D128 +error(0.021773936634121447) D101 D125 +error(0.001313798479028342953) D101 D125 ^ D127 D128 +error(0.003909402514313408024) D101 D130 +error(2.28104599996947481e-05) D101 D130 ^ D102 D127 +error(0.001083963797513874021) D101 D130 ^ D103 D127 +error(0.001120537449371218847) D101 ^ D69 ^ D73 +error(0.0008172106260104618561) D101 ^ D69 ^ D97 +error(0.0005108386865572231861) D101 ^ D73 +error(0.0001863077870320663395) D101 ^ D97 +error(0.006594162824587600225) D102 D103 +error(0.0005302971071338037764) D102 D103 ^ D105 D106 +error(0.002288777333365739179) D102 D103 ^ D106 D130 +error(0.0006884153111551963907) D102 D103 ^ D130 +error(0.03612550294212107937) D102 D126 +error(0.003986180069234413967) D102 D126 ^ D129 D130 +error(0.004298078915946801359) D102 D127 +error(0.0004818218312557076663) D102 D127 ^ D129 D130 +error(0.001625657018947900294) D102 D131 +error(0.0008012212761801838301) D102 D131 ^ D106 +error(0.001191671275737970267) D102 D131 ^ D106 D130 +error(0.000232923489534182565) D102 D131 ^ D130 +error(0.01000000000000000021) D102 L0 +error(0.01716894250448478682) D103 D104 +error(0.002238140370461111014) D103 D104 ^ D77 +error(0.01179623936683424357) D103 D104 ^ D101 +error(0.0005036757841566641674) D103 D104 ^ D106 +error(0.0002452144902547899984) D103 D104 ^ D106 ^ D77 +error(0.01685999773330407528) D103 D107 +error(0.01670462336830163749) D103 D107 ^ D106 +error(0.02173700185701750789) D103 D127 +error(0.001786549131622320371) D103 D127 ^ D101 +error(0.003912722710223686708) D103 D127 ^ D130 +error(0.002382500552628285216) D103 D128 +error(0.003284071404981582943) D103 D128 ^ D101 +error(0.0001814293687345641638) D103 D128 ^ D130 +error(0.0002952472760400955132) D103 D128 ^ D130 ^ D101 +error(0.003550633146921626862) D103 D131 +error(0.002950093029550475334) D103 D131 ^ D106 +error(0.004198020730678931646) D103 D131 ^ D130 +error(0.001191252727279817816) D103 D131 ^ D130 ^ D106 +error(0.02426465096103480254) D104 D128 +error(0.002887796181740957552) D104 D128 ^ D101 +error(0.007162167235623141323) D105 D106 +error(0.002013473804351892382) D105 D106 ^ D78 L0 +error(0.01188727626700753111) D105 D106 ^ D102 L0 +error(0.0006652180026593396264) D105 D106 ^ D107 L0 +error(0.0005288284790378269427) D105 D106 ^ D107 L0 ^ D78 L0 +error(0.03021538745065696641) D105 D129 +error(0.003655842737286960943) D105 D129 ^ D102 L0 +error(0.01000000000000000021) D106 +error(0.003072153014909577255) D106 D129 +error(0.002126355402752911228) D106 D129 ^ D102 L0 +error(0.0003891207497752700428) D106 D129 ^ D131 L0 +error(0.0004039352375315962947) D106 D129 ^ D131 L0 ^ D102 L0 +error(0.01966590043670931112) D106 D130 +error(0.00116697850444044183) D106 D130 ^ D102 L0 +error(0.002302712672173879219) D106 D130 ^ D131 L0 +error(0.00838775502972349471) D106 ^ D107 L0 +error(0.0008925839347452218337) D106 ^ D131 L0 +error(0.002919826675589398159) D107 D131 ^ D106 +error(0.01792671575261539293) D107 D131 +error(0.01159417794901059125) D107 L0 +error(0.005000000000000000104) D108 +error(0.01660438028321272949) D108 D112 +error(0.01779114294423248324) D108 D112 ^ D109 +error(0.02699148979780703964) D108 D132 +error(0.006834185536959506806) D108 D132 ^ D133 +error(0.007139333438785943654) D108 D136 +error(0.005071311220259624129) D108 D136 ^ D109 +error(0.003814151212458829175) D108 D136 ^ D133 +error(0.003241496548438547141) D108 D136 ^ D133 ^ D109 +error(0.003298463924975283609) D108 D137 +error(0.0005561199418532474046) D108 D137 ^ D109 +error(0.003357711680800872477) D108 D137 ^ D109 D133 +error(0.0001277368780254523777) D108 D137 ^ D133 +error(0.00612165296323359618) D108 ^ D109 +error(0.001411320666902509541) D108 ^ D133 +error(0.003813414387094213234) D109 D133 ^ D108 +error(0.01000000000000000021) D109 +error(0.007776687944794747655) D109 D110 +error(0.0002239251782426420899) D109 D110 ^ D108 +error(0.0006578014119039935111) D109 D110 ^ D112 D113 +error(9.807043003152089201e-05) D109 D110 ^ D112 D137 +error(0.01462632812957779041) D109 D110 ^ D113 +error(0.00451851992816860136) D109 D110 ^ D113 D137 +error(0.002686865629807736865) D109 D110 ^ D137 +error(0.0008975063743248118788) D109 D110 ^ D137 ^ D108 +error(0.02004352178629314682) D109 D115 +error(0.0126538281966155023) D109 D115 ^ D112 D113 +error(0.04091880631186525091) D109 D133 +error(0.002653181116343675261) D109 D133 ^ D136 D137 +error(0.003298283945553052033) D109 D133 ^ D137 +error(0.00339519176841894272) D109 D138 +error(0.001582986769424157402) D109 D138 ^ D112 D136 +error(0.0004380064685231338712) D109 D138 ^ D112 D137 +error(0.003113535398603530131) D109 D139 +error(0.00247782554596669884) D109 D139 ^ D112 D113 +error(0.001028637261928361376) D109 D139 ^ D112 D136 +error(0.00160650879303555344) D109 D139 ^ D112 D137 +error(0.002443953285749952357) D109 D139 ^ D136 D137 +error(0.01501988426115019766) D110 D116 +error(0.01690133780623802318) D110 D116 ^ D113 +error(0.006342401933687971671) D110 D133 +error(5.731474309590040581e-06) D110 D133 ^ D108 +error(0.004735574936250143592) D110 D133 ^ D137 +error(0.001109758085417464736) D110 D133 ^ D137 ^ D108 +error(0.02590702726501740299) D110 D134 +error(0.01055432121765075004) D110 D134 ^ D137 +error(0.002067699089454209764) D110 D139 +error(0.0004764857434993141063) D110 D139 ^ D112 D113 +error(0.00018791695239074924) D110 D139 ^ D112 D137 +error(0.000543812216206917675) D110 D139 ^ D113 +error(0.002265746668965656213) D110 D139 ^ D113 D137 +error(0.001367685511860447251) D110 D139 ^ D137 +error(0.003309490384053264886) D110 D140 +error(0.002654443592163411442) D110 D140 ^ D113 +error(0.00302472805964318402) D110 D140 ^ D137 +error(0.001061960255450209193) D110 D140 ^ D137 ^ D113 +error(0.008208999602450065339) D111 D112 +error(0.0002490393643702508214) D111 D112 ^ D109 +error(0.008432084388650621515) D111 D112 ^ D114 +error(0.0004018075719304165026) D111 D112 ^ D114 D115 +error(0.002531254512948871455) D111 D112 ^ D114 D138 +error(0.002283206907119589377) D111 D112 ^ D138 +error(0.0003647493962551453281) D111 D112 ^ D138 ^ D109 +error(0.01230414654041589451) D111 D118 +error(0.0105586013131753146) D111 D118 ^ D114 +error(0.02206797080950753318) D111 D135 +error(0.003109218220584021499) D111 D135 ^ D138 +error(0.001665473620494837799) D111 D136 +error(0.000751710629973935591) D111 D136 ^ D109 +error(0.002616716571845408533) D111 D136 ^ D138 +error(0.0002422723007377827135) D111 D136 ^ D138 ^ D109 +error(0.002331702848199883327) D111 D142 +error(0.003286376590100200615) D111 D142 ^ D114 +error(0.0016367579652731808) D111 D142 ^ D138 +error(0.0007603124886256211598) D111 D142 ^ D138 ^ D114 +error(0.002579757563572948522) D111 D143 +error(0.0001718132299533660715) D111 D143 ^ D114 +error(0.0001444887456803655346) D111 D143 ^ D114 D115 +error(0.001149196219717257958) D111 D143 ^ D114 D138 +error(1.120540756098161018e-05) D111 D143 ^ D115 D138 +error(0.0005057057902715079122) D111 D143 ^ D138 +error(0.00860417189101998249) D112 D113 +error(0.0008996636785346223512) D112 D113 ^ D85 +error(0.0007682366505013531362) D112 D113 ^ D114 D115 +error(0.0001543284317303631468) D112 D113 ^ D115 D116 +error(0.001413973100792486779) D112 D113 ^ D115 D139 +error(0.0001724825413106183519) D112 D113 ^ D116 D139 +error(0.01514009713272307031) D112 D119 +error(0.008955358603158896161) D112 D119 ^ D114 D115 +error(0.02572510637435859032) D112 D136 +error(0.007006310296506031501) D112 D136 ^ D109 +error(0.001316794376174020356) D112 D136 ^ D138 +error(0.002641791500945908124) D112 D136 ^ D138 D139 +error(0.003414039823895323716) D112 D137 +error(0.0006897576085226444272) D112 D137 ^ D138 D139 +error(0.001694614774715204851) D112 D143 +error(0.002644592536818960674) D112 D143 ^ D114 D115 +error(0.0009441644247071477548) D112 D143 ^ D114 D138 +error(0.001928777394211658768) D112 D143 ^ D115 D138 +error(0.00133008307762702495) D112 D143 ^ D115 D139 +error(0.001038771671501572628) D112 D143 ^ D138 D139 +error(0.0007323574101554897534) D112 D144 +error(0.0006847265269601655836) D112 D144 ^ D115 D116 +error(0.000653390831884755204) D112 D144 ^ D115 D138 +error(0.001523171598481931144) D112 D144 ^ D115 D139 +error(7.585149492345969401e-05) D112 D144 ^ D116 D139 +error(0.0003362069066020665037) D112 D144 ^ D138 D139 +error(0.01000000000000000021) D113 +error(0.02118071892183423163) D113 D120 +error(0.01736477246236184033) D113 D120 ^ D115 D116 +error(0.03300215916333530675) D113 D137 +error(0.00216592434550165339) D113 D137 ^ D139 D140 +error(0.004503622582071078496) D113 D144 +error(0.002318254759649248948) D113 D144 ^ D115 D116 +error(0.000376482607813980331) D113 D144 ^ D115 D139 +error(0.001747378805460943121) D113 D144 ^ D116 D139 +error(0.000593531763207356261) D113 D144 ^ D116 D140 +error(0.00215641765716670028) D113 D144 ^ D139 D140 +error(0.0005765516027016854509) D113 D145 ^ D116 D139 +error(0.0008586384286019724905) D113 D145 ^ D116 D140 +error(0.0004389250296211264098) D113 D145 ^ D139 D140 +error(0.01000000000000000021) D114 +error(0.009521520337646336568) D114 D115 +error(0.0008398031791907709142) D114 D115 ^ D118 D119 +error(0.0004021940016688471133) D114 D115 ^ D118 D143 +error(0.0005440209884140075275) D114 D115 ^ D119 D120 +error(0.002080156153275584171) D114 D115 ^ D119 D143 +error(0.01675364273324095668) D114 D123 +error(0.01174642302711653881) D114 D123 ^ D118 D119 +error(0.03443641348695664767) D114 D138 +error(0.002395055567470361167) D114 D138 ^ D142 D143 +error(0.002124958655053427441) D114 D146 +error(0.00220015674251626157) D114 D146 ^ D118 D142 +error(0.0004947019958325036496) D114 D146 ^ D118 D143 +error(0.000374511620403463689) D114 D146 ^ D142 D143 +error(0.004183529412601343783) D114 D147 +error(0.001754250315696467616) D114 D147 ^ D118 D119 +error(0.001890722784335428699) D114 D147 ^ D118 D142 +error(0.002250793337517553033) D114 D147 ^ D118 D143 +error(0.0007981997197410908157) D114 D147 ^ D119 D143 +error(0.001107907099724317985) D114 D147 ^ D142 D143 +error(0.0007396770146007538736) D114 ^ D142 L0 +error(0.00259721580293025044) D118 D142 ^ D114 +error(0.00729955180669228116) D115 D116 +error(5.062381541878982895e-05) D115 D116 ^ D89 +error(0.001030199975533826117) D115 D116 ^ D113 +error(0.0006584229463454448032) D115 D116 ^ D119 D120 +error(0.0001692053819037444857) D115 D116 ^ D119 D144 +error(0.0004254426911218613431) D115 D116 ^ D120 D121 +error(0.002214135018659018229) D115 D116 ^ D120 D144 +error(0.01623214291849352578) D115 D124 +error(0.01451260695679871225) D115 D124 ^ D119 D120 +error(0.003460367052192838376) D115 D138 +error(0.001095315529918634281) D115 D138 ^ D143 D144 +error(0.03984696727665810317) D115 D139 +error(0.001792163974324219007) D115 D139 ^ D143 D144 +error(0.001844556973055879161) D115 D147 +error(0.002352941691835960802) D115 D147 ^ D119 D143 +error(0.0004755448116354408215) D115 D147 ^ D119 D144 +error(0.0003335880933664818145) D115 D147 ^ D143 D144 +error(0.00299129553800945051) D115 D148 +error(0.001643907901120499624) D115 D148 ^ D119 D120 +error(0.0007920510235761922101) D115 D148 ^ D119 D143 +error(0.001755098518752947574) D115 D148 ^ D119 D144 +error(0.0006409651334938055956) D115 D148 ^ D120 D144 +error(0.002713297683053161272) D115 D148 ^ D143 D144 +error(0.009726903041435587885) D116 D117 +error(0.0003191744926083531198) D116 D117 ^ D113 +error(0.0006579173063691476581) D116 D117 ^ D120 D121 +error(0.0003869704899424970443) D116 D117 ^ D120 D145 +error(0.01220834273285227936) D116 D117 ^ D121 +error(0.00477129132198987789) D116 D117 ^ D121 D145 +error(0.002544666137518753445) D116 D117 ^ D145 +error(4.700906300686508247e-05) D116 D117 ^ D145 ^ D113 +error(0.01240604439279997979) D116 D125 +error(0.01094083605793164625) D116 D125 ^ D120 D121 +error(0.002545582488314489331) D116 D139 +error(0.0002826741056434087999) D116 D139 ^ D144 D145 +error(0.02075246121853630346) D116 D140 +error(0.004958470660349788284) D116 D140 ^ D113 +error(0.002257108386287591615) D116 D140 ^ D144 D145 +error(0.00124140148644221425) D116 D140 ^ D145 +error(0.002991512510671469512) D116 D148 +error(0.00177039048010369654) D116 D148 ^ D120 D144 +error(0.0003836293688450126611) D116 D148 ^ D120 D145 +error(0.0002262264940501502628) D116 D148 ^ D144 D145 +error(0.002041760540690738378) D116 D149 +error(0.002387441767965157308) D116 D149 ^ D120 D121 +error(0.0007494691992875175896) D116 D149 ^ D120 D144 +error(0.002474731958226495526) D116 D149 ^ D120 D145 +error(0.0009794943867816497014) D116 D149 ^ D121 D145 +error(0.002171252964640886084) D116 D149 ^ D144 D145 +error(0.01102841403074931829) D117 +error(0.001936390295073753699) D117 D140 +error(0.0003618605530372149084) D117 D140 ^ D113 +error(0.002183311663915940733) D117 D140 ^ D145 +error(3.448864583775733021e-05) D117 D140 ^ D145 ^ D113 +error(0.02852939423101608432) D117 D141 +error(0.004253581368126741966) D117 D141 ^ D145 +error(0.002900611666390966702) D117 D149 +error(0.003037154267016145548) D117 D149 ^ D121 D145 +error(0.01597507063807540942) D117 ^ D121 +error(0.001702405640180595101) D117 ^ D145 ^ D121 +error(0.01776770169544816466) D118 D119 +error(0.0001196824171128900416) D118 D119 ^ D90 +error(0.0006586128121373966554) D118 D119 ^ D122 D123 +error(0.002175366124230702306) D118 D119 ^ D123 D147 +error(0.0002506984111203783999) D118 D119 ^ D124 D147 +error(0.04739892754396989039) D118 D142 +error(0.003781829997311276104) D118 D142 ^ D146 D147 +error(0.002334841659936933052) D118 D143 +error(0.0009422456726712663197) D118 D143 ^ D146 D147 +error(0.0007049855875566741993) D118 D150 ^ D123 D124 +error(0.001934639851703026398) D118 D150 ^ D123 D147 +error(0.0002735044682239881077) D118 D150 ^ D124 D147 +error(0.01111336289536665051) D118 L0 +error(0.01173226287006574539) D118 L0 ^ D122 +error(0.003567715602164565989) D122 D146 ^ D118 L0 +error(0.0219173104120194244) D119 D120 +error(0.0006160258984500803633) D119 D120 ^ D123 D124 +error(6.315642213795687697e-05) D119 D120 ^ D124 D125 +error(0.002992427214964349901) D119 D120 ^ D124 D148 +error(0.0006609289947131321468) D119 D120 ^ D125 D148 +error(0.01946623581067056727) D119 D126 +error(0.01983614692690993664) D119 D126 ^ D123 D124 +error(0.02642383597330793393) D119 D143 +error(0.003024115804548305978) D119 D143 ^ D147 D148 +error(0.004707627181439803972) D119 D144 +error(0.0003746037177654245069) D119 D144 ^ D147 D148 +error(0.004350875619841032375) D119 D150 +error(0.005915511216720588557) D119 D150 ^ D123 D124 +error(0.001531588657764103561) D119 D150 ^ D123 D147 +error(0.008051354027943246824) D119 D150 ^ D124 D147 +error(0.001525927110233388445) D119 D150 ^ D124 D148 +error(0.003669458466892536359) D119 D150 ^ D147 D148 +error(0.002791113896069163328) D119 D151 +error(0.0006265920696080439726) D119 D151 ^ D124 D125 +error(4.779545894811885375e-05) D119 D151 ^ D124 D147 +error(0.0007337775853727664457) D119 D151 ^ D124 D148 +error(0.000542119306178530532) D119 D151 ^ D125 D148 +error(0.0003556315259281220406) D119 D151 ^ D147 D148 +error(0.007713185277822201882) D120 D121 +error(0.0002906218459867560932) D120 D121 ^ D125 +error(0.001951411826540530581) D120 D121 ^ D125 D149 +error(0.0001363990548493697222) D120 D121 ^ D149 +error(0.01427946177760987603) D120 D127 +error(0.009134401807325989373) D120 D127 ^ D124 D125 +error(0.02052822027627665413) D120 D144 +error(0.001984955007885169133) D120 D144 ^ D148 D149 +error(0.003128856462034781266) D120 D145 +error(0.0002188780272270664273) D120 D145 ^ D148 D149 +error(0.001173221145237272195) D120 D151 +error(0.00202756533973686608) D120 D151 ^ D124 D125 +error(0.0009147160160308196722) D120 D151 ^ D124 D148 +error(0.002478108585635494659) D120 D151 ^ D125 D148 +error(0.001252272042733494281) D120 D151 ^ D125 D149 +error(0.001947257464455566869) D120 D151 ^ D148 D149 +error(0.001123225366079328791) D120 D152 +error(6.005638908915711567e-05) D120 D152 ^ D125 +error(0.000421482864719889105) D120 D152 ^ D125 D148 +error(0.001261954426493605216) D120 D152 ^ D125 D149 +error(0.0001351826321506347569) D120 D152 ^ D148 D149 +error(0.00011199461596045396) D120 D152 ^ D149 +error(0.01094531334540550273) D121 +error(0.01538736176745019411) D121 D128 +error(0.0169485703355046792) D121 D128 ^ D125 +error(0.02209321612236390953) D121 D145 +error(0.002316639550606935157) D121 D145 ^ D149 +error(0.002146002416089138123) D121 D152 +error(0.002290705055193476176) D121 D152 ^ D125 +error(0.003445577716713628998) D121 D152 ^ D149 +error(0.0008214406114134374529) D121 D152 ^ D149 ^ D125 +error(0.008881637178845576755) D122 +error(0.01495585212186280669) D122 D123 +error(0.003695710743442946148) D122 D123 ^ D94 L0 +error(0.01799833116646069181) D122 D123 ^ D118 L0 +error(0.0004997383954729171145) D122 D123 ^ D126 L0 ^ D94 L0 +error(0.01987675887419782655) D122 D146 +error(0.0003296412873835849575) D122 ^ D90 ^ D94 L0 +error(0.0008096266067650861225) D122 ^ D118 L0 ^ D94 L0 +error(0.01506431211196329958) D123 D124 +error(0.0007457400519393364569) D123 D124 ^ D126 D127 +error(0.004363752286817622859) D123 D124 ^ D126 D150 +error(0.01385586789355772348) D123 D129 +error(0.01109776885461767094) D123 D129 ^ D126 L0 +error(0.005113701422269139804) D123 D146 +error(0.002144750650696250309) D123 D146 ^ D118 L0 +error(0.0005987071700741438676) D123 D146 ^ D150 L0 ^ D118 L0 +error(0.02694960105961625996) D123 D147 +error(0.0007380027204231738884) D123 D147 ^ D118 L0 +error(0.003721016964483825438) D123 D147 ^ D150 L0 +error(0.00189763058632084103) D123 D153 +error(0.002269670075562741068) D123 D153 ^ D126 L0 +error(0.003018302741455952676) D123 D153 ^ D150 L0 +error(0.0007595842134098546722) D123 D153 ^ D150 L0 ^ D126 L0 +error(0.01169871816276893753) D124 D125 +error(0.0004563423471117930195) D124 D125 ^ D126 D127 +error(0.0004944029476380669896) D124 D125 ^ D126 D151 +error(0.0004058715760627647413) D124 D125 ^ D127 D128 +error(0.00250279860763223715) D124 D125 ^ D127 D151 +error(0.01304884676936473968) D124 D130 +error(0.01084325194016807527) D124 D130 ^ D126 D127 +error(0.005038329940921605632) D124 D147 +error(0.0005822770362989852701) D124 D147 ^ D150 D151 +error(0.02718987902130082929) D124 D148 +error(0.001729643906341211826) D124 D148 ^ D150 D151 +error(0.002008286380084761159) D124 D153 +error(0.001184019355023896696) D124 D153 ^ D126 D150 +error(0.0001331019283698714549) D124 D153 ^ D126 D151 +error(0.0003174867051203577348) D124 D153 ^ D126 L0 +error(0.0005499328591647120778) D124 D153 ^ D150 D151 +error(0.0002857008089304124607) D124 D153 ^ D150 L0 +error(0.002378588767130583072) D124 D154 +error(0.001993144322145359512) D124 D154 ^ D126 D127 +error(0.0008444018024559791016) D124 D154 ^ D126 D150 +error(0.001376119481102591443) D124 D154 ^ D126 D151 +error(0.0007272918137137072275) D124 D154 ^ D127 D151 +error(0.001961341429606960809) D124 D154 ^ D150 D151 +error(0.01000000000000000021) D125 +error(0.003847026731771674424) D125 D148 +error(0.0007232425406817723831) D125 D148 ^ D151 D152 +error(0.021773936634121447) D125 D149 +error(0.001313798479028342953) D125 D149 ^ D151 D152 +error(0.003909402514313408024) D125 D154 +error(2.28104599996947481e-05) D125 D154 ^ D126 D151 +error(0.001083963797513874021) D125 D154 ^ D127 D151 +error(0.001120537449371218847) D125 ^ D93 ^ D97 +error(0.0008172106260104618561) D125 ^ D93 ^ D121 +error(0.0005108386865572231861) D125 ^ D97 +error(0.0001863077870320663395) D125 ^ D121 +error(0.006594162824587600225) D126 D127 +error(0.0005302971071338037764) D126 D127 ^ D129 D130 +error(0.002288777333365739179) D126 D127 ^ D130 D154 +error(0.0006884153111551963907) D126 D127 ^ D154 +error(0.03612550294212107937) D126 D150 +error(0.003986180069234413967) D126 D150 ^ D153 D154 +error(0.004298078915946801359) D126 D151 +error(0.0004818218312557076663) D126 D151 ^ D153 D154 +error(0.001625657018947900294) D126 D155 +error(0.0008012212761801838301) D126 D155 ^ D130 +error(0.001191671275737970267) D126 D155 ^ D130 D154 +error(0.000232923489534182565) D126 D155 ^ D154 +error(0.01000000000000000021) D126 L0 +error(0.01716894250448478682) D127 D128 +error(0.002238140370461111014) D127 D128 ^ D101 +error(0.01179623936683424357) D127 D128 ^ D125 +error(0.0005036757841566641674) D127 D128 ^ D130 +error(0.0002452144902547899984) D127 D128 ^ D130 ^ D101 +error(0.01685999773330407528) D127 D131 +error(0.01670462336830163749) D127 D131 ^ D130 +error(0.02173700185701750789) D127 D151 +error(0.001786549131622320371) D127 D151 ^ D125 +error(0.003912722710223686708) D127 D151 ^ D154 +error(0.002382500552628285216) D127 D152 +error(0.003284071404981582943) D127 D152 ^ D125 +error(0.0001814293687345641638) D127 D152 ^ D154 +error(0.0002952472760400955132) D127 D152 ^ D154 ^ D125 +error(0.003550633146921626862) D127 D155 +error(0.002950093029550475334) D127 D155 ^ D130 +error(0.004198020730678931646) D127 D155 ^ D154 +error(0.001191252727279817816) D127 D155 ^ D154 ^ D130 +error(0.02426465096103480254) D128 D152 +error(0.002887796181740957552) D128 D152 ^ D125 +error(0.007162167235623141323) D129 D130 +error(0.002013473804351892382) D129 D130 ^ D102 L0 +error(0.01188727626700753111) D129 D130 ^ D126 L0 +error(0.0006652180026593396264) D129 D130 ^ D131 L0 +error(0.0005288284790378269427) D129 D130 ^ D131 L0 ^ D102 L0 +error(0.03021538745065696641) D129 D153 +error(0.003655842737286960943) D129 D153 ^ D126 L0 +error(0.01000000000000000021) D130 +error(0.003072153014909577255) D130 D153 +error(0.002126355402752911228) D130 D153 ^ D126 L0 +error(0.0003891207497752700428) D130 D153 ^ D155 L0 +error(0.0004039352375315962947) D130 D153 ^ D155 L0 ^ D126 L0 +error(0.01966590043670931112) D130 D154 +error(0.00116697850444044183) D130 D154 ^ D126 L0 +error(0.002302712672173879219) D130 D154 ^ D155 L0 +error(0.00838775502972349471) D130 ^ D131 L0 +error(0.0008925839347452218337) D130 ^ D155 L0 +error(0.002919826675589398159) D131 D155 ^ D130 +error(0.01792671575261539293) D131 D155 +error(0.01159417794901059125) D131 L0 +error(0.005000000000000000104) D132 +error(0.01660438028321272949) D132 D136 +error(0.01779114294423248324) D132 D136 ^ D133 +error(0.02699148979780703964) D132 D156 +error(0.006834185536959506806) D132 D156 ^ D157 +error(0.007139333438785943654) D132 D160 +error(0.005071311220259624129) D132 D160 ^ D133 +error(0.003814151212458829175) D132 D160 ^ D157 +error(0.003241496548438547141) D132 D160 ^ D157 ^ D133 +error(0.003298463924975283609) D132 D161 +error(0.0005561199418532474046) D132 D161 ^ D133 +error(0.003357711680800872477) D132 D161 ^ D133 D157 +error(0.0001277368780254523777) D132 D161 ^ D157 +error(0.00612165296323359618) D132 ^ D133 +error(0.001411320666902509541) D132 ^ D157 +error(0.003813414387094213234) D133 D157 ^ D132 +error(0.01000000000000000021) D133 +error(0.007776687944794747655) D133 D134 +error(0.0002239251782426420899) D133 D134 ^ D132 +error(0.0006578014119039935111) D133 D134 ^ D136 D137 +error(9.807043003152089201e-05) D133 D134 ^ D136 D161 +error(0.01462632812957779041) D133 D134 ^ D137 +error(0.00451851992816860136) D133 D134 ^ D137 D161 +error(0.002686865629807736865) D133 D134 ^ D161 +error(0.0008975063743248118788) D133 D134 ^ D161 ^ D132 +error(0.02004352178629314682) D133 D139 +error(0.0126538281966155023) D133 D139 ^ D136 D137 +error(0.04091880631186525091) D133 D157 +error(0.002653181116343675261) D133 D157 ^ D160 D161 +error(0.003298283945553052033) D133 D157 ^ D161 +error(0.00339519176841894272) D133 D162 +error(0.001582986769424157402) D133 D162 ^ D136 D160 +error(0.0004380064685231338712) D133 D162 ^ D136 D161 +error(0.003113535398603530131) D133 D163 +error(0.00247782554596669884) D133 D163 ^ D136 D137 +error(0.001028637261928361376) D133 D163 ^ D136 D160 +error(0.00160650879303555344) D133 D163 ^ D136 D161 +error(0.002443953285749952357) D133 D163 ^ D160 D161 +error(0.01501988426115019766) D134 D140 +error(0.01690133780623802318) D134 D140 ^ D137 +error(0.006342401933687971671) D134 D157 +error(5.731474309590040581e-06) D134 D157 ^ D132 +error(0.004735574936250143592) D134 D157 ^ D161 +error(0.001109758085417464736) D134 D157 ^ D161 ^ D132 +error(0.02590702726501740299) D134 D158 +error(0.01055432121765075004) D134 D158 ^ D161 +error(0.002067699089454209764) D134 D163 +error(0.0004764857434993141063) D134 D163 ^ D136 D137 +error(0.00018791695239074924) D134 D163 ^ D136 D161 +error(0.000543812216206917675) D134 D163 ^ D137 +error(0.002265746668965656213) D134 D163 ^ D137 D161 +error(0.001367685511860447251) D134 D163 ^ D161 +error(0.003309490384053264886) D134 D164 +error(0.002654443592163411442) D134 D164 ^ D137 +error(0.00302472805964318402) D134 D164 ^ D161 +error(0.001061960255450209193) D134 D164 ^ D161 ^ D137 +error(0.008208999602450065339) D135 D136 +error(0.0002490393643702508214) D135 D136 ^ D133 +error(0.008432084388650621515) D135 D136 ^ D138 +error(0.0004018075719304165026) D135 D136 ^ D138 D139 +error(0.002531254512948871455) D135 D136 ^ D138 D162 +error(0.002283206907119589377) D135 D136 ^ D162 +error(0.0003647493962551453281) D135 D136 ^ D162 ^ D133 +error(0.01230414654041589451) D135 D142 +error(0.0105586013131753146) D135 D142 ^ D138 +error(0.02206797080950753318) D135 D159 +error(0.003109218220584021499) D135 D159 ^ D162 +error(0.001665473620494837799) D135 D160 +error(0.000751710629973935591) D135 D160 ^ D133 +error(0.002616716571845408533) D135 D160 ^ D162 +error(0.0002422723007377827135) D135 D160 ^ D162 ^ D133 +error(0.002331702848199883327) D135 D166 +error(0.003286376590100200615) D135 D166 ^ D138 +error(0.0016367579652731808) D135 D166 ^ D162 +error(0.0007603124886256211598) D135 D166 ^ D162 ^ D138 +error(0.002579757563572948522) D135 D167 +error(0.0001718132299533660715) D135 D167 ^ D138 +error(0.0001444887456803655346) D135 D167 ^ D138 D139 +error(0.001149196219717257958) D135 D167 ^ D138 D162 +error(1.120540756098161018e-05) D135 D167 ^ D139 D162 +error(0.0005057057902715079122) D135 D167 ^ D162 +error(0.00860417189101998249) D136 D137 +error(0.0008996636785346223512) D136 D137 ^ D109 +error(0.0007682366505013531362) D136 D137 ^ D138 D139 +error(0.0001543284317303631468) D136 D137 ^ D139 D140 +error(0.001413973100792486779) D136 D137 ^ D139 D163 +error(0.0001724825413106183519) D136 D137 ^ D140 D163 +error(0.01514009713272307031) D136 D143 +error(0.008955358603158896161) D136 D143 ^ D138 D139 +error(0.02572510637435859032) D136 D160 +error(0.007006310296506031501) D136 D160 ^ D133 +error(0.001316794376174020356) D136 D160 ^ D162 +error(0.002641791500945908124) D136 D160 ^ D162 D163 +error(0.003414039823895323716) D136 D161 +error(0.0006897576085226444272) D136 D161 ^ D162 D163 +error(0.001694614774715204851) D136 D167 +error(0.002644592536818960674) D136 D167 ^ D138 D139 +error(0.0009441644247071477548) D136 D167 ^ D138 D162 +error(0.001928777394211658768) D136 D167 ^ D139 D162 +error(0.00133008307762702495) D136 D167 ^ D139 D163 +error(0.001038771671501572628) D136 D167 ^ D162 D163 +error(0.0007323574101554897534) D136 D168 +error(0.0006847265269601655836) D136 D168 ^ D139 D140 +error(0.000653390831884755204) D136 D168 ^ D139 D162 +error(0.001523171598481931144) D136 D168 ^ D139 D163 +error(7.585149492345969401e-05) D136 D168 ^ D140 D163 +error(0.0003362069066020665037) D136 D168 ^ D162 D163 +error(0.01000000000000000021) D137 +error(0.02118071892183423163) D137 D144 +error(0.01736477246236184033) D137 D144 ^ D139 D140 +error(0.03300215916333530675) D137 D161 +error(0.00216592434550165339) D137 D161 ^ D163 D164 +error(0.004503622582071078496) D137 D168 +error(0.002318254759649248948) D137 D168 ^ D139 D140 +error(0.000376482607813980331) D137 D168 ^ D139 D163 +error(0.001747378805460943121) D137 D168 ^ D140 D163 +error(0.000593531763207356261) D137 D168 ^ D140 D164 +error(0.00215641765716670028) D137 D168 ^ D163 D164 +error(0.0005765516027016854509) D137 D169 ^ D140 D163 +error(0.0008586384286019724905) D137 D169 ^ D140 D164 +error(0.0004389250296211264098) D137 D169 ^ D163 D164 +error(0.01000000000000000021) D138 +error(0.009521520337646336568) D138 D139 +error(0.0008398031791907709142) D138 D139 ^ D142 D143 +error(0.0004021940016688471133) D138 D139 ^ D142 D167 +error(0.0005440209884140075275) D138 D139 ^ D143 D144 +error(0.002080156153275584171) D138 D139 ^ D143 D167 +error(0.01675364273324095668) D138 D147 +error(0.01174642302711653881) D138 D147 ^ D142 D143 +error(0.03443641348695664767) D138 D162 +error(0.002395055567470361167) D138 D162 ^ D166 D167 +error(0.002124958655053427441) D138 D170 +error(0.00220015674251626157) D138 D170 ^ D142 D166 +error(0.0004947019958325036496) D138 D170 ^ D142 D167 +error(0.000374511620403463689) D138 D170 ^ D166 D167 +error(0.004183529412601343783) D138 D171 +error(0.001754250315696467616) D138 D171 ^ D142 D143 +error(0.001890722784335428699) D138 D171 ^ D142 D166 +error(0.002250793337517553033) D138 D171 ^ D142 D167 +error(0.0007981997197410908157) D138 D171 ^ D143 D167 +error(0.001107907099724317985) D138 D171 ^ D166 D167 +error(0.0007396770146007538736) D138 ^ D166 L0 +error(0.00259721580293025044) D142 D166 ^ D138 +error(0.00729955180669228116) D139 D140 +error(5.062381541878982895e-05) D139 D140 ^ D113 +error(0.001030199975533826117) D139 D140 ^ D137 +error(0.0006584229463454448032) D139 D140 ^ D143 D144 +error(0.0001692053819037444857) D139 D140 ^ D143 D168 +error(0.0004254426911218613431) D139 D140 ^ D144 D145 +error(0.002214135018659018229) D139 D140 ^ D144 D168 +error(0.01623214291849352578) D139 D148 +error(0.01451260695679871225) D139 D148 ^ D143 D144 +error(0.003460367052192838376) D139 D162 +error(0.001095315529918634281) D139 D162 ^ D167 D168 +error(0.03984696727665810317) D139 D163 +error(0.001792163974324219007) D139 D163 ^ D167 D168 +error(0.001844556973055879161) D139 D171 +error(0.002352941691835960802) D139 D171 ^ D143 D167 +error(0.0004755448116354408215) D139 D171 ^ D143 D168 +error(0.0003335880933664818145) D139 D171 ^ D167 D168 +error(0.00299129553800945051) D139 D172 +error(0.001643907901120499624) D139 D172 ^ D143 D144 +error(0.0007920510235761922101) D139 D172 ^ D143 D167 +error(0.001755098518752947574) D139 D172 ^ D143 D168 +error(0.0006409651334938055956) D139 D172 ^ D144 D168 +error(0.002713297683053161272) D139 D172 ^ D167 D168 +error(0.009726903041435587885) D140 D141 +error(0.0003191744926083531198) D140 D141 ^ D137 +error(0.0006579173063691476581) D140 D141 ^ D144 D145 +error(0.0003869704899424970443) D140 D141 ^ D144 D169 +error(0.01220834273285227936) D140 D141 ^ D145 +error(0.00477129132198987789) D140 D141 ^ D145 D169 +error(0.002544666137518753445) D140 D141 ^ D169 +error(4.700906300686508247e-05) D140 D141 ^ D169 ^ D137 +error(0.01240604439279997979) D140 D149 +error(0.01094083605793164625) D140 D149 ^ D144 D145 +error(0.002545582488314489331) D140 D163 +error(0.0002826741056434087999) D140 D163 ^ D168 D169 +error(0.02075246121853630346) D140 D164 +error(0.004958470660349788284) D140 D164 ^ D137 +error(0.002257108386287591615) D140 D164 ^ D168 D169 +error(0.00124140148644221425) D140 D164 ^ D169 +error(0.002991512510671469512) D140 D172 +error(0.00177039048010369654) D140 D172 ^ D144 D168 +error(0.0003836293688450126611) D140 D172 ^ D144 D169 +error(0.0002262264940501502628) D140 D172 ^ D168 D169 +error(0.002041760540690738378) D140 D173 +error(0.002387441767965157308) D140 D173 ^ D144 D145 +error(0.0007494691992875175896) D140 D173 ^ D144 D168 +error(0.002474731958226495526) D140 D173 ^ D144 D169 +error(0.0009794943867816497014) D140 D173 ^ D145 D169 +error(0.002171252964640886084) D140 D173 ^ D168 D169 +error(0.01102841403074931829) D141 +error(0.001936390295073753699) D141 D164 +error(0.0003618605530372149084) D141 D164 ^ D137 +error(0.002183311663915940733) D141 D164 ^ D169 +error(3.448864583775733021e-05) D141 D164 ^ D169 ^ D137 +error(0.02852939423101608432) D141 D165 +error(0.004253581368126741966) D141 D165 ^ D169 +error(0.002900611666390966702) D141 D173 +error(0.003037154267016145548) D141 D173 ^ D145 D169 +error(0.01597507063807540942) D141 ^ D145 +error(0.001702405640180595101) D141 ^ D169 ^ D145 +error(0.01776770169544816466) D142 D143 +error(0.0001196824171128900416) D142 D143 ^ D114 +error(0.0006586128121373966554) D142 D143 ^ D146 D147 +error(0.002175366124230702306) D142 D143 ^ D147 D171 +error(0.0002506984111203783999) D142 D143 ^ D148 D171 +error(0.04739892754396989039) D142 D166 +error(0.003781829997311276104) D142 D166 ^ D170 D171 +error(0.002334841659936933052) D142 D167 +error(0.0009422456726712663197) D142 D167 ^ D170 D171 +error(0.0007049855875566741993) D142 D174 ^ D147 D148 +error(0.001934639851703026398) D142 D174 ^ D147 D171 +error(0.0002735044682239881077) D142 D174 ^ D148 D171 +error(0.01111336289536665051) D142 L0 +error(0.01173226287006574539) D142 L0 ^ D146 +error(0.003567715602164565989) D146 D170 ^ D142 L0 +error(0.0219173104120194244) D143 D144 +error(0.0006160258984500803633) D143 D144 ^ D147 D148 +error(6.315642213795687697e-05) D143 D144 ^ D148 D149 +error(0.002992427214964349901) D143 D144 ^ D148 D172 +error(0.0006609289947131321468) D143 D144 ^ D149 D172 +error(0.01946623581067056727) D143 D150 +error(0.01983614692690993664) D143 D150 ^ D147 D148 +error(0.02642383597330793393) D143 D167 +error(0.003024115804548305978) D143 D167 ^ D171 D172 +error(0.004707627181439803972) D143 D168 +error(0.0003746037177654245069) D143 D168 ^ D171 D172 +error(0.004350875619841032375) D143 D174 +error(0.005915511216720588557) D143 D174 ^ D147 D148 +error(0.001531588657764103561) D143 D174 ^ D147 D171 +error(0.008051354027943246824) D143 D174 ^ D148 D171 +error(0.001525927110233388445) D143 D174 ^ D148 D172 +error(0.003669458466892536359) D143 D174 ^ D171 D172 +error(0.002791113896069163328) D143 D175 +error(0.0006265920696080439726) D143 D175 ^ D148 D149 +error(4.779545894811885375e-05) D143 D175 ^ D148 D171 +error(0.0007337775853727664457) D143 D175 ^ D148 D172 +error(0.000542119306178530532) D143 D175 ^ D149 D172 +error(0.0003556315259281220406) D143 D175 ^ D171 D172 +error(0.007713185277822201882) D144 D145 +error(0.0002906218459867560932) D144 D145 ^ D149 +error(0.001951411826540530581) D144 D145 ^ D149 D173 +error(0.0001363990548493697222) D144 D145 ^ D173 +error(0.01427946177760987603) D144 D151 +error(0.009134401807325989373) D144 D151 ^ D148 D149 +error(0.02052822027627665413) D144 D168 +error(0.001984955007885169133) D144 D168 ^ D172 D173 +error(0.003128856462034781266) D144 D169 +error(0.0002188780272270664273) D144 D169 ^ D172 D173 +error(0.001173221145237272195) D144 D175 +error(0.00202756533973686608) D144 D175 ^ D148 D149 +error(0.0009147160160308196722) D144 D175 ^ D148 D172 +error(0.002478108585635494659) D144 D175 ^ D149 D172 +error(0.001252272042733494281) D144 D175 ^ D149 D173 +error(0.001947257464455566869) D144 D175 ^ D172 D173 +error(0.001123225366079328791) D144 D176 +error(6.005638908915711567e-05) D144 D176 ^ D149 +error(0.000421482864719889105) D144 D176 ^ D149 D172 +error(0.001261954426493605216) D144 D176 ^ D149 D173 +error(0.0001351826321506347569) D144 D176 ^ D172 D173 +error(0.00011199461596045396) D144 D176 ^ D173 +error(0.01094531334540550273) D145 +error(0.01538736176745019411) D145 D152 +error(0.0169485703355046792) D145 D152 ^ D149 +error(0.02209321612236390953) D145 D169 +error(0.002316639550606935157) D145 D169 ^ D173 +error(0.002146002416089138123) D145 D176 +error(0.002290705055193476176) D145 D176 ^ D149 +error(0.003445577716713628998) D145 D176 ^ D173 +error(0.0008214406114134374529) D145 D176 ^ D173 ^ D149 +error(0.008881637178845576755) D146 +error(0.01495585212186280669) D146 D147 +error(0.003695710743442946148) D146 D147 ^ D118 L0 +error(0.01799833116646069181) D146 D147 ^ D142 L0 +error(0.0004997383954729171145) D146 D147 ^ D150 L0 ^ D118 L0 +error(0.01987675887419782655) D146 D170 +error(0.0003296412873835849575) D146 ^ D114 ^ D118 L0 +error(0.0008096266067650861225) D146 ^ D142 L0 ^ D118 L0 +error(0.01506431211196329958) D147 D148 +error(0.0007457400519393364569) D147 D148 ^ D150 D151 +error(0.004363752286817622859) D147 D148 ^ D150 D174 +error(0.01385586789355772348) D147 D153 +error(0.01109776885461767094) D147 D153 ^ D150 L0 +error(0.005113701422269139804) D147 D170 +error(0.002144750650696250309) D147 D170 ^ D142 L0 +error(0.0005987071700741438676) D147 D170 ^ D174 L0 ^ D142 L0 +error(0.02694960105961625996) D147 D171 +error(0.0007380027204231738884) D147 D171 ^ D142 L0 +error(0.003721016964483825438) D147 D171 ^ D174 L0 +error(0.00189763058632084103) D147 D177 +error(0.002269670075562741068) D147 D177 ^ D150 L0 +error(0.003018302741455952676) D147 D177 ^ D174 L0 +error(0.0007595842134098546722) D147 D177 ^ D174 L0 ^ D150 L0 +error(0.01169871816276893753) D148 D149 +error(0.0004563423471117930195) D148 D149 ^ D150 D151 +error(0.0004944029476380669896) D148 D149 ^ D150 D175 +error(0.0004058715760627647413) D148 D149 ^ D151 D152 +error(0.00250279860763223715) D148 D149 ^ D151 D175 +error(0.01304884676936473968) D148 D154 +error(0.01084325194016807527) D148 D154 ^ D150 D151 +error(0.005038329940921605632) D148 D171 +error(0.0005822770362989852701) D148 D171 ^ D174 D175 +error(0.02718987902130082929) D148 D172 +error(0.001729643906341211826) D148 D172 ^ D174 D175 +error(0.002008286380084761159) D148 D177 +error(0.001184019355023896696) D148 D177 ^ D150 D174 +error(0.0001331019283698714549) D148 D177 ^ D150 D175 +error(0.0003174867051203577348) D148 D177 ^ D150 L0 +error(0.0005499328591647120778) D148 D177 ^ D174 D175 +error(0.0002857008089304124607) D148 D177 ^ D174 L0 +error(0.002378588767130583072) D148 D178 +error(0.001993144322145359512) D148 D178 ^ D150 D151 +error(0.0008444018024559791016) D148 D178 ^ D150 D174 +error(0.001376119481102591443) D148 D178 ^ D150 D175 +error(0.0007272918137137072275) D148 D178 ^ D151 D175 +error(0.001961341429606960809) D148 D178 ^ D174 D175 +error(0.01000000000000000021) D149 +error(0.003847026731771674424) D149 D172 +error(0.0007232425406817723831) D149 D172 ^ D175 D176 +error(0.021773936634121447) D149 D173 +error(0.001313798479028342953) D149 D173 ^ D175 D176 +error(0.003909402514313408024) D149 D178 +error(2.28104599996947481e-05) D149 D178 ^ D150 D175 +error(0.001083963797513874021) D149 D178 ^ D151 D175 +error(0.001120537449371218847) D149 ^ D117 ^ D121 +error(0.0008172106260104618561) D149 ^ D117 ^ D145 +error(0.0005108386865572231861) D149 ^ D121 +error(0.0001863077870320663395) D149 ^ D145 +error(0.006594162824587600225) D150 D151 +error(0.0005302971071338037764) D150 D151 ^ D153 D154 +error(0.002288777333365739179) D150 D151 ^ D154 D178 +error(0.0006884153111551963907) D150 D151 ^ D178 +error(0.03612550294212107937) D150 D174 +error(0.003986180069234413967) D150 D174 ^ D177 D178 +error(0.004298078915946801359) D150 D175 +error(0.0004818218312557076663) D150 D175 ^ D177 D178 +error(0.001625657018947900294) D150 D179 +error(0.0008012212761801838301) D150 D179 ^ D154 +error(0.001191671275737970267) D150 D179 ^ D154 D178 +error(0.000232923489534182565) D150 D179 ^ D178 +error(0.01000000000000000021) D150 L0 +error(0.01716894250448478682) D151 D152 +error(0.002238140370461111014) D151 D152 ^ D125 +error(0.01179623936683424357) D151 D152 ^ D149 +error(0.0005036757841566641674) D151 D152 ^ D154 +error(0.0002452144902547899984) D151 D152 ^ D154 ^ D125 +error(0.01685999773330407528) D151 D155 +error(0.01670462336830163749) D151 D155 ^ D154 +error(0.02173700185701750789) D151 D175 +error(0.001786549131622320371) D151 D175 ^ D149 +error(0.003912722710223686708) D151 D175 ^ D178 +error(0.002382500552628285216) D151 D176 +error(0.003284071404981582943) D151 D176 ^ D149 +error(0.0001814293687345641638) D151 D176 ^ D178 +error(0.0002952472760400955132) D151 D176 ^ D178 ^ D149 +error(0.003550633146921626862) D151 D179 +error(0.002950093029550475334) D151 D179 ^ D154 +error(0.004198020730678931646) D151 D179 ^ D178 +error(0.001191252727279817816) D151 D179 ^ D178 ^ D154 +error(0.02426465096103480254) D152 D176 +error(0.002887796181740957552) D152 D176 ^ D149 +error(0.007162167235623141323) D153 D154 +error(0.002013473804351892382) D153 D154 ^ D126 L0 +error(0.01188727626700753111) D153 D154 ^ D150 L0 +error(0.0006652180026593396264) D153 D154 ^ D155 L0 +error(0.0005288284790378269427) D153 D154 ^ D155 L0 ^ D126 L0 +error(0.03021538745065696641) D153 D177 +error(0.003655842737286960943) D153 D177 ^ D150 L0 +error(0.01000000000000000021) D154 +error(0.003072153014909577255) D154 D177 +error(0.002126355402752911228) D154 D177 ^ D150 L0 +error(0.0003891207497752700428) D154 D177 ^ D179 L0 +error(0.0004039352375315962947) D154 D177 ^ D179 L0 ^ D150 L0 +error(0.01966590043670931112) D154 D178 +error(0.00116697850444044183) D154 D178 ^ D150 L0 +error(0.002302712672173879219) D154 D178 ^ D179 L0 +error(0.00838775502972349471) D154 ^ D155 L0 +error(0.0008925839347452218337) D154 ^ D179 L0 +error(0.002919826675589398159) D155 D179 ^ D154 +error(0.01792671575261539293) D155 D179 +error(0.01159417794901059125) D155 L0 +error(0.005000000000000000104) D156 +error(0.01660438028321272949) D156 D160 +error(0.01779114294423248324) D156 D160 ^ D157 +error(0.02699148979780703964) D156 D180 +error(0.006834185536959506806) D156 D180 ^ D181 +error(0.007139333438785943654) D156 D184 +error(0.005071311220259624129) D156 D184 ^ D157 +error(0.003814151212458829175) D156 D184 ^ D181 +error(0.003241496548438547141) D156 D184 ^ D181 ^ D157 +error(0.003298463924975283609) D156 D185 +error(0.0005561199418532474046) D156 D185 ^ D157 +error(0.003357711680800872477) D156 D185 ^ D157 D181 +error(0.0001277368780254523777) D156 D185 ^ D181 +error(0.00612165296323359618) D156 ^ D157 +error(0.001411320666902509541) D156 ^ D181 +error(0.003813414387094213234) D157 D181 ^ D156 +error(0.01000000000000000021) D157 +error(0.007776687944794747655) D157 D158 +error(0.0002239251782426420899) D157 D158 ^ D156 +error(0.0006578014119039935111) D157 D158 ^ D160 D161 +error(9.807043003152089201e-05) D157 D158 ^ D160 D185 +error(0.01462632812957779041) D157 D158 ^ D161 +error(0.00451851992816860136) D157 D158 ^ D161 D185 +error(0.002686865629807736865) D157 D158 ^ D185 +error(0.0008975063743248118788) D157 D158 ^ D185 ^ D156 +error(0.02004352178629314682) D157 D163 +error(0.0126538281966155023) D157 D163 ^ D160 D161 +error(0.04091880631186525091) D157 D181 +error(0.002653181116343675261) D157 D181 ^ D184 D185 +error(0.003298283945553052033) D157 D181 ^ D185 +error(0.00339519176841894272) D157 D186 +error(0.001582986769424157402) D157 D186 ^ D160 D184 +error(0.0004380064685231338712) D157 D186 ^ D160 D185 +error(0.003113535398603530131) D157 D187 +error(0.00247782554596669884) D157 D187 ^ D160 D161 +error(0.001028637261928361376) D157 D187 ^ D160 D184 +error(0.00160650879303555344) D157 D187 ^ D160 D185 +error(0.002443953285749952357) D157 D187 ^ D184 D185 +error(0.01501988426115019766) D158 D164 +error(0.01690133780623802318) D158 D164 ^ D161 +error(0.006342401933687971671) D158 D181 +error(5.731474309590040581e-06) D158 D181 ^ D156 +error(0.004735574936250143592) D158 D181 ^ D185 +error(0.001109758085417464736) D158 D181 ^ D185 ^ D156 +error(0.02590702726501740299) D158 D182 +error(0.01055432121765075004) D158 D182 ^ D185 +error(0.002067699089454209764) D158 D187 +error(0.0004764857434993141063) D158 D187 ^ D160 D161 +error(0.00018791695239074924) D158 D187 ^ D160 D185 +error(0.000543812216206917675) D158 D187 ^ D161 +error(0.002265746668965656213) D158 D187 ^ D161 D185 +error(0.001367685511860447251) D158 D187 ^ D185 +error(0.003309490384053264886) D158 D188 +error(0.002654443592163411442) D158 D188 ^ D161 +error(0.00302472805964318402) D158 D188 ^ D185 +error(0.001061960255450209193) D158 D188 ^ D185 ^ D161 +error(0.008208999602450065339) D159 D160 +error(0.0002490393643702508214) D159 D160 ^ D157 +error(0.008432084388650621515) D159 D160 ^ D162 +error(0.0004018075719304165026) D159 D160 ^ D162 D163 +error(0.002531254512948871455) D159 D160 ^ D162 D186 +error(0.002283206907119589377) D159 D160 ^ D186 +error(0.0003647493962551453281) D159 D160 ^ D186 ^ D157 +error(0.01230414654041589451) D159 D166 +error(0.0105586013131753146) D159 D166 ^ D162 +error(0.02206797080950753318) D159 D183 +error(0.003109218220584021499) D159 D183 ^ D186 +error(0.001665473620494837799) D159 D184 +error(0.000751710629973935591) D159 D184 ^ D157 +error(0.002616716571845408533) D159 D184 ^ D186 +error(0.0002422723007377827135) D159 D184 ^ D186 ^ D157 +error(0.002331702848199883327) D159 D190 +error(0.003286376590100200615) D159 D190 ^ D162 +error(0.0016367579652731808) D159 D190 ^ D186 +error(0.0007603124886256211598) D159 D190 ^ D186 ^ D162 +error(0.002579757563572948522) D159 D191 +error(0.0001718132299533660715) D159 D191 ^ D162 +error(0.0001444887456803655346) D159 D191 ^ D162 D163 +error(0.001149196219717257958) D159 D191 ^ D162 D186 +error(1.120540756098161018e-05) D159 D191 ^ D163 D186 +error(0.0005057057902715079122) D159 D191 ^ D186 +error(0.00860417189101998249) D160 D161 +error(0.0008996636785346223512) D160 D161 ^ D133 +error(0.0007682366505013531362) D160 D161 ^ D162 D163 +error(0.0001543284317303631468) D160 D161 ^ D163 D164 +error(0.001413973100792486779) D160 D161 ^ D163 D187 +error(0.0001724825413106183519) D160 D161 ^ D164 D187 +error(0.01514009713272307031) D160 D167 +error(0.008955358603158896161) D160 D167 ^ D162 D163 +error(0.02572510637435859032) D160 D184 +error(0.007006310296506031501) D160 D184 ^ D157 +error(0.001316794376174020356) D160 D184 ^ D186 +error(0.002641791500945908124) D160 D184 ^ D186 D187 +error(0.003414039823895323716) D160 D185 +error(0.0006897576085226444272) D160 D185 ^ D186 D187 +error(0.001694614774715204851) D160 D191 +error(0.002644592536818960674) D160 D191 ^ D162 D163 +error(0.0009441644247071477548) D160 D191 ^ D162 D186 +error(0.001928777394211658768) D160 D191 ^ D163 D186 +error(0.00133008307762702495) D160 D191 ^ D163 D187 +error(0.001038771671501572628) D160 D191 ^ D186 D187 +error(0.0007323574101554897534) D160 D192 +error(0.0006847265269601655836) D160 D192 ^ D163 D164 +error(0.000653390831884755204) D160 D192 ^ D163 D186 +error(0.001523171598481931144) D160 D192 ^ D163 D187 +error(7.585149492345969401e-05) D160 D192 ^ D164 D187 +error(0.0003362069066020665037) D160 D192 ^ D186 D187 +error(0.01000000000000000021) D161 +error(0.02118071892183423163) D161 D168 +error(0.01736477246236184033) D161 D168 ^ D163 D164 +error(0.03300215916333530675) D161 D185 +error(0.00216592434550165339) D161 D185 ^ D187 D188 +error(0.004503622582071078496) D161 D192 +error(0.002318254759649248948) D161 D192 ^ D163 D164 +error(0.000376482607813980331) D161 D192 ^ D163 D187 +error(0.001747378805460943121) D161 D192 ^ D164 D187 +error(0.000593531763207356261) D161 D192 ^ D164 D188 +error(0.00215641765716670028) D161 D192 ^ D187 D188 +error(0.0005765516027016854509) D161 D193 ^ D164 D187 +error(0.0008586384286019724905) D161 D193 ^ D164 D188 +error(0.0004389250296211264098) D161 D193 ^ D187 D188 +error(0.01000000000000000021) D162 +error(0.009521520337646336568) D162 D163 +error(0.0008398031791907709142) D162 D163 ^ D166 D167 +error(0.0004021940016688471133) D162 D163 ^ D166 D191 +error(0.0005440209884140075275) D162 D163 ^ D167 D168 +error(0.002080156153275584171) D162 D163 ^ D167 D191 +error(0.01675364273324095668) D162 D171 +error(0.01174642302711653881) D162 D171 ^ D166 D167 +error(0.03443641348695664767) D162 D186 +error(0.002395055567470361167) D162 D186 ^ D190 D191 +error(0.002124958655053427441) D162 D194 +error(0.00220015674251626157) D162 D194 ^ D166 D190 +error(0.0004947019958325036496) D162 D194 ^ D166 D191 +error(0.000374511620403463689) D162 D194 ^ D190 D191 +error(0.004183529412601343783) D162 D195 +error(0.001754250315696467616) D162 D195 ^ D166 D167 +error(0.001890722784335428699) D162 D195 ^ D166 D190 +error(0.002250793337517553033) D162 D195 ^ D166 D191 +error(0.0007981997197410908157) D162 D195 ^ D167 D191 +error(0.001107907099724317985) D162 D195 ^ D190 D191 +error(0.0007396770146007538736) D162 ^ D190 L0 +error(0.00259721580293025044) D166 D190 ^ D162 +error(0.00729955180669228116) D163 D164 +error(5.062381541878982895e-05) D163 D164 ^ D137 +error(0.001030199975533826117) D163 D164 ^ D161 +error(0.0006584229463454448032) D163 D164 ^ D167 D168 +error(0.0001692053819037444857) D163 D164 ^ D167 D192 +error(0.0004254426911218613431) D163 D164 ^ D168 D169 +error(0.002214135018659018229) D163 D164 ^ D168 D192 +error(0.01623214291849352578) D163 D172 +error(0.01451260695679871225) D163 D172 ^ D167 D168 +error(0.003460367052192838376) D163 D186 +error(0.001095315529918634281) D163 D186 ^ D191 D192 +error(0.03984696727665810317) D163 D187 +error(0.001792163974324219007) D163 D187 ^ D191 D192 +error(0.001844556973055879161) D163 D195 +error(0.002352941691835960802) D163 D195 ^ D167 D191 +error(0.0004755448116354408215) D163 D195 ^ D167 D192 +error(0.0003335880933664818145) D163 D195 ^ D191 D192 +error(0.00299129553800945051) D163 D196 +error(0.001643907901120499624) D163 D196 ^ D167 D168 +error(0.0007920510235761922101) D163 D196 ^ D167 D191 +error(0.001755098518752947574) D163 D196 ^ D167 D192 +error(0.0006409651334938055956) D163 D196 ^ D168 D192 +error(0.002713297683053161272) D163 D196 ^ D191 D192 +error(0.009726903041435587885) D164 D165 +error(0.0003191744926083531198) D164 D165 ^ D161 +error(0.0006579173063691476581) D164 D165 ^ D168 D169 +error(0.0003869704899424970443) D164 D165 ^ D168 D193 +error(0.01220834273285227936) D164 D165 ^ D169 +error(0.00477129132198987789) D164 D165 ^ D169 D193 +error(0.002544666137518753445) D164 D165 ^ D193 +error(4.700906300686508247e-05) D164 D165 ^ D193 ^ D161 +error(0.01240604439279997979) D164 D173 +error(0.01094083605793164625) D164 D173 ^ D168 D169 +error(0.002545582488314489331) D164 D187 +error(0.0002826741056434087999) D164 D187 ^ D192 D193 +error(0.02075246121853630346) D164 D188 +error(0.004958470660349788284) D164 D188 ^ D161 +error(0.002257108386287591615) D164 D188 ^ D192 D193 +error(0.00124140148644221425) D164 D188 ^ D193 +error(0.002991512510671469512) D164 D196 +error(0.00177039048010369654) D164 D196 ^ D168 D192 +error(0.0003836293688450126611) D164 D196 ^ D168 D193 +error(0.0002262264940501502628) D164 D196 ^ D192 D193 +error(0.002041760540690738378) D164 D197 +error(0.002387441767965157308) D164 D197 ^ D168 D169 +error(0.0007494691992875175896) D164 D197 ^ D168 D192 +error(0.002474731958226495526) D164 D197 ^ D168 D193 +error(0.0009794943867816497014) D164 D197 ^ D169 D193 +error(0.002171252964640886084) D164 D197 ^ D192 D193 +error(0.01102841403074931829) D165 +error(0.001936390295073753699) D165 D188 +error(0.0003618605530372149084) D165 D188 ^ D161 +error(0.002183311663915940733) D165 D188 ^ D193 +error(3.448864583775733021e-05) D165 D188 ^ D193 ^ D161 +error(0.02852939423101608432) D165 D189 +error(0.004253581368126741966) D165 D189 ^ D193 +error(0.002900611666390966702) D165 D197 +error(0.003037154267016145548) D165 D197 ^ D169 D193 +error(0.01597507063807540942) D165 ^ D169 +error(0.001702405640180595101) D165 ^ D193 ^ D169 +error(0.01776770169544816466) D166 D167 +error(0.0001196824171128900416) D166 D167 ^ D138 +error(0.0006586128121373966554) D166 D167 ^ D170 D171 +error(0.002175366124230702306) D166 D167 ^ D171 D195 +error(0.0002506984111203783999) D166 D167 ^ D172 D195 +error(0.04739892754396989039) D166 D190 +error(0.003781829997311276104) D166 D190 ^ D194 D195 +error(0.002334841659936933052) D166 D191 +error(0.0009422456726712663197) D166 D191 ^ D194 D195 +error(0.0007049855875566741993) D166 D198 ^ D171 D172 +error(0.001934639851703026398) D166 D198 ^ D171 D195 +error(0.0002735044682239881077) D166 D198 ^ D172 D195 +error(0.01111336289536665051) D166 L0 +error(0.01173226287006574539) D166 L0 ^ D170 +error(0.003567715602164565989) D170 D194 ^ D166 L0 +error(0.0219173104120194244) D167 D168 +error(0.0006160258984500803633) D167 D168 ^ D171 D172 +error(6.315642213795687697e-05) D167 D168 ^ D172 D173 +error(0.002992427214964349901) D167 D168 ^ D172 D196 +error(0.0006609289947131321468) D167 D168 ^ D173 D196 +error(0.01946623581067056727) D167 D174 +error(0.01983614692690993664) D167 D174 ^ D171 D172 +error(0.02642383597330793393) D167 D191 +error(0.003024115804548305978) D167 D191 ^ D195 D196 +error(0.004707627181439803972) D167 D192 +error(0.0003746037177654245069) D167 D192 ^ D195 D196 +error(0.004350875619841032375) D167 D198 +error(0.005915511216720588557) D167 D198 ^ D171 D172 +error(0.001531588657764103561) D167 D198 ^ D171 D195 +error(0.008051354027943246824) D167 D198 ^ D172 D195 +error(0.001525927110233388445) D167 D198 ^ D172 D196 +error(0.003669458466892536359) D167 D198 ^ D195 D196 +error(0.002791113896069163328) D167 D199 +error(0.0006265920696080439726) D167 D199 ^ D172 D173 +error(4.779545894811885375e-05) D167 D199 ^ D172 D195 +error(0.0007337775853727664457) D167 D199 ^ D172 D196 +error(0.000542119306178530532) D167 D199 ^ D173 D196 +error(0.0003556315259281220406) D167 D199 ^ D195 D196 +error(0.007713185277822201882) D168 D169 +error(0.0002906218459867560932) D168 D169 ^ D173 +error(0.001951411826540530581) D168 D169 ^ D173 D197 +error(0.0001363990548493697222) D168 D169 ^ D197 +error(0.01427946177760987603) D168 D175 +error(0.009134401807325989373) D168 D175 ^ D172 D173 +error(0.02052822027627665413) D168 D192 +error(0.001984955007885169133) D168 D192 ^ D196 D197 +error(0.003128856462034781266) D168 D193 +error(0.0002188780272270664273) D168 D193 ^ D196 D197 +error(0.001173221145237272195) D168 D199 +error(0.00202756533973686608) D168 D199 ^ D172 D173 +error(0.0009147160160308196722) D168 D199 ^ D172 D196 +error(0.002478108585635494659) D168 D199 ^ D173 D196 +error(0.001252272042733494281) D168 D199 ^ D173 D197 +error(0.001947257464455566869) D168 D199 ^ D196 D197 +error(0.001123225366079328791) D168 D200 +error(6.005638908915711567e-05) D168 D200 ^ D173 +error(0.000421482864719889105) D168 D200 ^ D173 D196 +error(0.001261954426493605216) D168 D200 ^ D173 D197 +error(0.0001351826321506347569) D168 D200 ^ D196 D197 +error(0.00011199461596045396) D168 D200 ^ D197 +error(0.01094531334540550273) D169 +error(0.01538736176745019411) D169 D176 +error(0.0169485703355046792) D169 D176 ^ D173 +error(0.02209321612236390953) D169 D193 +error(0.002316639550606935157) D169 D193 ^ D197 +error(0.002146002416089138123) D169 D200 +error(0.002290705055193476176) D169 D200 ^ D173 +error(0.003445577716713628998) D169 D200 ^ D197 +error(0.0008214406114134374529) D169 D200 ^ D197 ^ D173 +error(0.008881637178845576755) D170 +error(0.01495585212186280669) D170 D171 +error(0.003695710743442946148) D170 D171 ^ D142 L0 +error(0.01799833116646069181) D170 D171 ^ D166 L0 +error(0.0004997383954729171145) D170 D171 ^ D174 L0 ^ D142 L0 +error(0.01987675887419782655) D170 D194 +error(0.0003296412873835849575) D170 ^ D138 ^ D142 L0 +error(0.0008096266067650861225) D170 ^ D166 L0 ^ D142 L0 +error(0.01506431211196329958) D171 D172 +error(0.0007457400519393364569) D171 D172 ^ D174 D175 +error(0.004363752286817622859) D171 D172 ^ D174 D198 +error(0.01385586789355772348) D171 D177 +error(0.01109776885461767094) D171 D177 ^ D174 L0 +error(0.005113701422269139804) D171 D194 +error(0.002144750650696250309) D171 D194 ^ D166 L0 +error(0.0005987071700741438676) D171 D194 ^ D198 L0 ^ D166 L0 +error(0.02694960105961625996) D171 D195 +error(0.0007380027204231738884) D171 D195 ^ D166 L0 +error(0.003721016964483825438) D171 D195 ^ D198 L0 +error(0.00189763058632084103) D171 D201 +error(0.002269670075562741068) D171 D201 ^ D174 L0 +error(0.003018302741455952676) D171 D201 ^ D198 L0 +error(0.0007595842134098546722) D171 D201 ^ D198 L0 ^ D174 L0 +error(0.01169871816276893753) D172 D173 +error(0.0004563423471117930195) D172 D173 ^ D174 D175 +error(0.0004944029476380669896) D172 D173 ^ D174 D199 +error(0.0004058715760627647413) D172 D173 ^ D175 D176 +error(0.00250279860763223715) D172 D173 ^ D175 D199 +error(0.01304884676936473968) D172 D178 +error(0.01084325194016807527) D172 D178 ^ D174 D175 +error(0.005038329940921605632) D172 D195 +error(0.0005822770362989852701) D172 D195 ^ D198 D199 +error(0.02718987902130082929) D172 D196 +error(0.001729643906341211826) D172 D196 ^ D198 D199 +error(0.002008286380084761159) D172 D201 +error(0.001184019355023896696) D172 D201 ^ D174 D198 +error(0.0001331019283698714549) D172 D201 ^ D174 D199 +error(0.0003174867051203577348) D172 D201 ^ D174 L0 +error(0.0005499328591647120778) D172 D201 ^ D198 D199 +error(0.0002857008089304124607) D172 D201 ^ D198 L0 +error(0.002378588767130583072) D172 D202 +error(0.001993144322145359512) D172 D202 ^ D174 D175 +error(0.0008444018024559791016) D172 D202 ^ D174 D198 +error(0.001376119481102591443) D172 D202 ^ D174 D199 +error(0.0007272918137137072275) D172 D202 ^ D175 D199 +error(0.001961341429606960809) D172 D202 ^ D198 D199 +error(0.01000000000000000021) D173 +error(0.003847026731771674424) D173 D196 +error(0.0007232425406817723831) D173 D196 ^ D199 D200 +error(0.021773936634121447) D173 D197 +error(0.001313798479028342953) D173 D197 ^ D199 D200 +error(0.003909402514313408024) D173 D202 +error(2.28104599996947481e-05) D173 D202 ^ D174 D199 +error(0.001083963797513874021) D173 D202 ^ D175 D199 +error(0.001120537449371218847) D173 ^ D141 ^ D145 +error(0.0008172106260104618561) D173 ^ D141 ^ D169 +error(0.0005108386865572231861) D173 ^ D145 +error(0.0001863077870320663395) D173 ^ D169 +error(0.006594162824587600225) D174 D175 +error(0.0005302971071338037764) D174 D175 ^ D177 D178 +error(0.002288777333365739179) D174 D175 ^ D178 D202 +error(0.0006884153111551963907) D174 D175 ^ D202 +error(0.03612550294212107937) D174 D198 +error(0.003986180069234413967) D174 D198 ^ D201 D202 +error(0.004298078915946801359) D174 D199 +error(0.0004818218312557076663) D174 D199 ^ D201 D202 +error(0.001625657018947900294) D174 D203 +error(0.0008012212761801838301) D174 D203 ^ D178 +error(0.001191671275737970267) D174 D203 ^ D178 D202 +error(0.000232923489534182565) D174 D203 ^ D202 +error(0.01000000000000000021) D174 L0 +error(0.01716894250448478682) D175 D176 +error(0.002238140370461111014) D175 D176 ^ D149 +error(0.01179623936683424357) D175 D176 ^ D173 +error(0.0005036757841566641674) D175 D176 ^ D178 +error(0.0002452144902547899984) D175 D176 ^ D178 ^ D149 +error(0.01685999773330407528) D175 D179 +error(0.01670462336830163749) D175 D179 ^ D178 +error(0.02173700185701750789) D175 D199 +error(0.001786549131622320371) D175 D199 ^ D173 +error(0.003912722710223686708) D175 D199 ^ D202 +error(0.002382500552628285216) D175 D200 +error(0.003284071404981582943) D175 D200 ^ D173 +error(0.0001814293687345641638) D175 D200 ^ D202 +error(0.0002952472760400955132) D175 D200 ^ D202 ^ D173 +error(0.003550633146921626862) D175 D203 +error(0.002950093029550475334) D175 D203 ^ D178 +error(0.004198020730678931646) D175 D203 ^ D202 +error(0.001191252727279817816) D175 D203 ^ D202 ^ D178 +error(0.02426465096103480254) D176 D200 +error(0.002887796181740957552) D176 D200 ^ D173 +error(0.007162167235623141323) D177 D178 +error(0.002013473804351892382) D177 D178 ^ D150 L0 +error(0.01188727626700753111) D177 D178 ^ D174 L0 +error(0.0006652180026593396264) D177 D178 ^ D179 L0 +error(0.0005288284790378269427) D177 D178 ^ D179 L0 ^ D150 L0 +error(0.03021538745065696641) D177 D201 +error(0.003655842737286960943) D177 D201 ^ D174 L0 +error(0.01000000000000000021) D178 +error(0.003072153014909577255) D178 D201 +error(0.002126355402752911228) D178 D201 ^ D174 L0 +error(0.0003891207497752700428) D178 D201 ^ D203 L0 +error(0.0004039352375315962947) D178 D201 ^ D203 L0 ^ D174 L0 +error(0.01966590043670931112) D178 D202 +error(0.00116697850444044183) D178 D202 ^ D174 L0 +error(0.002302712672173879219) D178 D202 ^ D203 L0 +error(0.00838775502972349471) D178 ^ D179 L0 +error(0.0008925839347452218337) D178 ^ D203 L0 +error(0.002919826675589398159) D179 D203 ^ D178 +error(0.01792671575261539293) D179 D203 +error(0.01159417794901059125) D179 L0 +error(0.005000000000000000104) D180 +error(0.01813420014568381533) D180 D184 +error(0.02152520083511488824) D180 D184 ^ D181 +error(0.04332452129202413182) D180 D204 +error(0.01050135378381584529) D180 D206 +error(0.009022255236648823659) D180 D206 ^ D181 +error(0.002043664645070478528) D180 D208 +error(0.004967601520801231442) D180 D208 ^ D181 +error(0.009252246309056747636) D180 ^ D181 +error(0.0003770872312219100166) D180 ^ D182 +error(0.03773975282804960252) D181 +error(0.009857909864105042497) D181 D182 +error(0.01343575001707989804) D181 D182 ^ D185 +error(0.007283164048771048789) D181 D182 ^ D185 D208 +error(0.001563313896790632191) D181 D182 ^ D208 +error(0.01942314113063272479) D181 D187 +error(0.0123328244086421384) D181 D187 ^ D184 D185 +error(0.001413806142303450798) D181 ^ D180 ^ D182 +error(0.0002282798942845835476) D181 ^ D208 +error(0.0250539247284288398) D182 +error(0.01606667479344649208) D182 D188 +error(0.01652250418428684309) D182 D188 ^ D185 +error(0.005000000000000000104) D182 ^ D185 +error(0.01268502051505343217) D182 ^ D208 +error(0.00766915363093727525) D185 D208 ^ D182 +error(0.01317562614249773167) D183 D184 +error(0.01087437625878419703) D183 D184 ^ D186 +error(0.01250004395524711293) D183 D190 +error(0.01184835932540525757) D183 D190 ^ D186 +error(0.02284694660177433168) D183 D205 +error(0.002928998057951773086) D183 D206 +error(0.004900619386687504221) D183 D207 +error(0.00549445583062870696) D183 D207 ^ D186 +error(0.001839248267879753027) D183 D209 +error(0.001287216529598661464) D183 D209 ^ D186 +error(0.0003625599515569454716) D183 D209 ^ D187 +error(0.009047806857755757298) D184 D185 +error(0.0008996636785346223512) D184 D185 ^ D157 +error(4.144438474411374352e-05) D184 D185 ^ D181 +error(0.001983433130879510946) D184 D185 ^ D182 ^ D181 +error(0.003298465236688749753) D184 D185 ^ D186 D187 +error(8.696148041633241729e-05) D184 D185 ^ D187 +error(0.0002604090149758089704) D184 D185 ^ D187 ^ D188 +error(0.01060521543090599782) D184 D191 +error(0.0111033893272936713) D184 D191 ^ D186 D187 +error(0.0312140366906134073) D184 D206 +error(0.01187642895259482731) D184 D206 ^ D181 +error(0.002992097465924747988) D184 D208 +error(0.001979836307214286138) D184 D208 ^ D181 +error(0.001381909353815971271) D184 D208 ^ D182 +error(0.001108242156464336664) D184 D208 ^ D182 ^ D181 +error(0.003423442907537046012) D184 D209 +error(0.002436492436572516157) D184 D209 ^ D186 +error(0.0006185787456216020573) D184 D209 ^ D186 D187 +error(0.003346619879902386959) D184 D209 ^ D187 +error(0.0009598200654627748584) D184 D210 +error(0.001237004106290559352) D184 D210 ^ D187 +error(8.441087826477104911e-05) D184 D210 ^ D187 ^ D188 +error(0.01000000000000000021) D185 +error(0.01847508556997588813) D185 D192 +error(0.02024439930847083194) D185 D192 ^ D187 D188 +error(0.03071327754468607812) D185 D208 +error(0.003125531678446842078) D185 D208 ^ D181 +error(0.009671726062149119466) D185 D210 +error(1.973393514017970064e-05) D185 D210 ^ D187 +error(0.002686067675749103691) D185 D210 ^ D187 D188 +error(0.0009812756326774911119) D185 D210 ^ D188 +error(0.001124810442365705657) D185 D212 +error(0.001590794520398883249) D185 D212 ^ D188 +error(0.0007640559349292666298) D185 ^ D189 +error(0.02924416631391687366) D186 +error(0.005000000000000000104) D186 D187 +error(0.001812958566527053715) D186 D187 ^ D191 D192 +error(0.0009582855077323802458) D186 D187 ^ D191 D209 +error(0.01608005329481685536) D186 D195 +error(0.01287362211402139252) D186 D195 ^ D190 D191 +error(0.003264376150886942086) D186 ^ D190 L0 +error(0.002016571877667939616) D186 ^ D207 L0 +error(0.00603640454931144918) D190 D207 ^ D186 +error(0.03295427500436359791) D187 +error(0.008050909049739126203) D187 D188 +error(5.062381541878982895e-05) D187 D188 ^ D161 +error(0.00201914747903085643) D187 D188 ^ D185 +error(0.001457260001417363558) D187 D188 ^ D192 D193 +error(0.0032519549048554185) D187 D188 ^ D192 D210 +error(0.01411259002460397288) D187 D196 +error(0.01433260514527600303) D187 D196 ^ D191 D192 +error(0.01788071566792796135) D188 +error(0.008248739226592928173) D188 D189 +error(0.01426920176915262226) D188 D189 ^ D193 +error(0.006109970222437825262) D188 D189 ^ D193 D212 +error(0.0001510446441183972092) D188 D189 ^ D212 +error(0.01480132022792932968) D188 D197 +error(0.009263497814211487172) D188 D197 ^ D192 D193 +error(0.00273188909747897838) D188 ^ D185 +error(0.0007376702355415592962) D188 ^ D185 ^ D189 +error(0.001277873185003415265) D188 ^ D212 ^ D185 ^ D189 +error(0.04672698799569671713) D189 +error(0.01711954704811850456) D189 ^ D193 +error(0.004757830649422457002) D189 ^ D212 +error(0.004558937987351329921) D193 D212 ^ D189 +error(0.01373602141655237349) D190 D191 +error(0.0001196824171128900416) D190 D191 ^ D162 +error(0.001568552469036159705) D190 D191 ^ D187 ^ D186 +error(0.002691086973725029512) D190 D191 ^ D194 D195 +error(0.0004896196293597669408) D190 D191 ^ D195 +error(0.002832533679073116241) D190 D191 ^ D195 ^ D196 +error(0.0009328024720530267043) D190 D191 ^ D196 +error(0.05385417449979442578) D190 D207 +error(0.0045311788727064959) D190 D209 +error(0.0001822104396345387129) D190 D209 ^ D186 +error(0.001388245304435162166) D190 D209 ^ D187 ^ D186 +error(0.004082183625431705203) D190 D211 +error(0.0004512067195962462542) D190 D211 ^ D195 +error(0.001512782033025491255) D190 D211 ^ D195 ^ D196 +error(0.0001828372420582476436) D190 D211 ^ D196 +error(0.01392466589347819) D190 L0 +error(0.01395600801625140538) D190 L0 ^ D194 +error(0.003288213559306295622) D190 L0 ^ D195 +error(0.02578840533363068246) D191 D192 +error(0.003069142333833545407) D191 D192 ^ D195 D196 +error(0.00131765783584516182) D191 D192 ^ D196 ^ D197 +error(0.02143701462235764188) D191 D198 +error(0.01928739264197079986) D191 D198 ^ D195 D196 +error(0.02580538062919279785) D191 D209 +error(0.003268915348204168899) D191 D209 ^ D186 +error(0.004853448116091559766) D191 D209 ^ D187 +error(0.004998140149158569051) D191 D210 +error(0.003234552437069274349) D191 D210 ^ D187 +error(0.0005673798617038052243) D191 D210 ^ D188 ^ D187 +error(0.01051710402569955641) D191 D211 +error(0.003495184168292670736) D191 D211 ^ D195 +error(0.006017335010566221901) D191 D211 ^ D195 D196 +error(0.009556655509356783151) D191 D211 ^ D196 +error(0.002247656687675866558) D191 D213 +error(0.001470351354469425333) D191 D213 ^ D196 ^ D197 +error(5.512233325992634019e-05) D191 D213 ^ D197 +error(0.007815349435267763753) D192 D193 +error(0.002926016073578682243) D192 D193 ^ D188 +error(0.0006858381834669199624) D192 D193 ^ D189 +error(0.0002912097901636812947) D192 D193 ^ D196 D197 +error(0.0009227751319534682533) D192 D193 ^ D197 +error(0.01389010560522843489) D192 D199 +error(0.01055792066776815689) D192 D199 ^ D196 D197 +error(0.02275559346888043552) D192 D210 +error(0.0008707626688727530513) D192 D210 ^ D187 +error(0.002286365562153776058) D192 D210 ^ D188 +error(0.002066742884413600833) D192 D212 +error(0.00374183671142356471) D192 D212 ^ D188 +error(0.0003625830029919788785) D192 D212 ^ D189 +error(0.0009821324966327086257) D192 D212 ^ D189 ^ D188 +error(0.005666051641243153268) D192 D213 +error(0.00124294949853053535) D192 D213 ^ D196 +error(0.002754324164357703063) D192 D213 ^ D196 D197 +error(0.003786176672404106391) D192 D213 ^ D197 +error(0.003314692118591604578) D192 D214 +error(0.0007501696129312794819) D192 D214 ^ D197 +error(0.01572710335455064501) D193 +error(0.0152859862393172341) D193 D200 +error(0.01834089284493831476) D193 D200 ^ D197 +error(0.02525233655988739015) D193 D212 +error(0.001858546422089600667) D193 D212 ^ D188 +error(0.00820361415790244429) D193 D214 +error(0.003126356020802332786) D193 D214 ^ D197 +error(0.03010602421387373329) D194 +error(0.01725576588987519713) D194 D195 +error(0.003695710743442946148) D194 D195 ^ D166 L0 +error(0.01655334018913276473) D194 D195 ^ D190 L0 +error(0.0004997383954729171145) D194 D195 ^ D198 L0 ^ D166 L0 +error(0.0003296412873835849575) D194 ^ D162 ^ D166 L0 +error(0.0008096266067650861225) D194 ^ D190 L0 ^ D166 L0 +error(0.01757673225171079573) D195 +error(0.01552231913562481143) D195 D196 +error(0.003067068510325397009) D195 D196 ^ D198 D211 +error(0.01052579338565800757) D195 D201 +error(0.01532974317868063437) D195 D201 ^ D198 L0 +error(0.003693402498889460268) D195 ^ D211 L0 +error(0.002235209832601358672) D195 ^ D211 L0 ^ D198 L0 +error(0.0126219640746224656) D196 +error(0.008723287765927826079) D196 D197 +error(0.004577985872127925994) D196 D197 ^ D199 D213 +error(0.01416432706431445046) D196 D202 +error(0.01101268745114474847) D196 D202 ^ D198 D199 +error(0.001906657433359759722) D196 ^ D198 L0 +error(0.003564053975191587825) D198 D211 ^ D196 +error(0.0371047534907456289) D197 +error(0.001120537449371218847) D197 ^ D165 ^ D169 +error(0.0008172106260104618561) D197 ^ D165 ^ D193 +error(0.0005108386865572231861) D197 ^ D169 +error(0.0005682599272647727729) D197 ^ D193 +error(0.006114191567305802752) D198 D199 +error(0.004269409689106182758) D198 D199 ^ D196 +error(4.711778803644671497e-05) D198 D199 ^ D197 +error(0.002130257788050823799) D198 D199 ^ D201 D202 +error(0.03618808176019967099) D198 D211 +error(0.003188482674992927299) D198 D213 +error(0.002110616412538960946) D198 D213 ^ D196 +error(0.0008176685906095302681) D198 D213 ^ D197 +error(0.002703837096720205363) D198 D215 +error(0.002462831207384448984) D198 D215 ^ D202 +error(0.01221820817056769488) D198 L0 +error(0.008332474825594972032) D198 L0 ^ D202 +error(0.01984028621700753212) D199 D200 +error(0.002238140370461111014) D199 D200 ^ D173 +error(0.01263580087296928105) D199 D200 ^ D197 +error(0.002668471610316381585) D199 D200 ^ D202 +error(0.0002452144902547899984) D199 D200 ^ D202 ^ D173 +error(0.01715552191800281956) D199 D203 +error(0.01601315760624249379) D199 D203 ^ D202 +error(0.02245904022993731528) D199 D213 +error(0.0007030871030758843341) D199 D213 ^ D196 +error(0.004054756524523253462) D199 D213 ^ D197 +error(0.003269125014996700392) D199 D214 +error(0.003098736720754494654) D199 D214 ^ D197 +error(0.005602668876985740856) D199 D215 +error(0.004276734971013905484) D199 D215 ^ D202 +error(0.02376800757480877768) D200 D214 +error(0.001644340331922584031) D200 D214 ^ D197 +error(0.02578382051951268877) D201 +error(0.007882473620893075753) D201 D202 +error(0.002013473804351892382) D201 D202 ^ D174 L0 +error(0.01112713216727603295) D201 D202 ^ D198 L0 +error(0.001796912614939645114) D201 D202 ^ D203 L0 +error(0.0005288284790378269427) D201 D202 ^ D203 L0 ^ D174 L0 +error(0.005000000000000000104) D201 ^ D198 L0 +error(0.02219584047988094194) D202 +error(0.007660773206234461861) D202 ^ D203 L0 +error(0.005191007554773234382) D202 ^ D215 L0 +error(0.004197550641849638955) D203 D215 ^ D202 +error(0.01757590014677821999) D203 D215 +error(0.01024230229616157617) D203 L0 +error(0.03685447096545516055) D204 +error(0.02502800347647199386) D204 D206 +error(0.01446802781292200191) D205 D206 +error(0.01142820403241545657) D205 D207 +error(0.01620637386945210021) D206 D208 +error(0.004649581950951360045) D206 D208 ^ D181 +error(0.01330672477871619463) D206 D209 +error(0.01233447862686133829) D207 D209 +error(0.004850509268011318244) D207 D209 ^ D186 +error(0.03881705010797127653) D207 L0 +error(0.02103115286948175136) D208 +error(0.01986665636820106329) D208 D210 +error(0.001281202966195335059) D208 ^ D180 ^ D182 +error(0.02103262144130370673) D209 D210 +error(0.002769079126527895611) D209 D210 ^ D187 +error(0.01486722815460678193) D209 D211 +error(0.01937675471217479087) D210 D212 +error(0.005282940876317059574) D210 D212 ^ D188 +error(0.01401947246640028455) D210 D213 +error(0.01459869435636241067) D211 D213 +error(0.003850055265005339952) D211 D213 ^ D196 +error(0.02996993106455891204) D211 L0 +error(0.03559833106930707786) D212 +error(0.01679988997082021429) D212 D214 +error(0.001598060272409944534) D212 ^ D185 ^ D189 +error(0.02022266000610214304) D213 D214 +error(0.003166288182346991848) D213 D214 ^ D197 +error(0.03184950487609622405) D213 D215 +error(0.01722760923336421821) D215 L0 +detector(1, 4, 0) D0 +detector(3, 2, 0) D1 +detector(3, 4, 0) D2 +detector(5, 2, 0) D3 +detector(3, 6, 0) D4 +detector(5, 4, 0) D5 +detector(5, 6, 0) D6 +detector(7, 4, 0) D7 +detector(5, 8, 0) D8 +detector(7, 6, 0) D9 +detector(7, 8, 0) D10 +detector(9, 6, 0) D11 +detector(1, 4, 1) D12 +detector(2, 5, 1) D13 +detector(2, 7, 1) D14 +detector(3, 2, 1) D15 +detector(3, 4, 1) D16 +detector(3, 6, 1) D17 +detector(4, 3, 1) D18 +detector(4, 5, 1) D19 +detector(4, 7, 1) D20 +detector(4, 9, 1) D21 +detector(5, 2, 1) D22 +detector(5, 4, 1) D23 +detector(5, 6, 1) D24 +detector(5, 8, 1) D25 +detector(6, 1, 1) D26 +detector(6, 3, 1) D27 +detector(6, 5, 1) D28 +detector(6, 7, 1) D29 +detector(7, 4, 1) D30 +detector(7, 6, 1) D31 +detector(7, 8, 1) D32 +detector(8, 3, 1) D33 +detector(8, 5, 1) D34 +detector(9, 6, 1) D35 +detector(1, 4, 2) D36 +detector(2, 5, 2) D37 +detector(2, 7, 2) D38 +detector(3, 2, 2) D39 +detector(3, 4, 2) D40 +detector(3, 6, 2) D41 +detector(4, 3, 2) D42 +detector(4, 5, 2) D43 +detector(4, 7, 2) D44 +detector(4, 9, 2) D45 +detector(5, 2, 2) D46 +detector(5, 4, 2) D47 +detector(5, 6, 2) D48 +detector(5, 8, 2) D49 +detector(6, 1, 2) D50 +detector(6, 3, 2) D51 +detector(6, 5, 2) D52 +detector(6, 7, 2) D53 +detector(7, 4, 2) D54 +detector(7, 6, 2) D55 +detector(7, 8, 2) D56 +detector(8, 3, 2) D57 +detector(8, 5, 2) D58 +detector(9, 6, 2) D59 +detector(1, 4, 3) D60 +detector(2, 5, 3) D61 +detector(2, 7, 3) D62 +detector(3, 2, 3) D63 +detector(3, 4, 3) D64 +detector(3, 6, 3) D65 +detector(4, 3, 3) D66 +detector(4, 5, 3) D67 +detector(4, 7, 3) D68 +detector(4, 9, 3) D69 +detector(5, 2, 3) D70 +detector(5, 4, 3) D71 +detector(5, 6, 3) D72 +detector(5, 8, 3) D73 +detector(6, 1, 3) D74 +detector(6, 3, 3) D75 +detector(6, 5, 3) D76 +detector(6, 7, 3) D77 +detector(7, 4, 3) D78 +detector(7, 6, 3) D79 +detector(7, 8, 3) D80 +detector(8, 3, 3) D81 +detector(8, 5, 3) D82 +detector(9, 6, 3) D83 +detector(1, 4, 4) D84 +detector(2, 5, 4) D85 +detector(2, 7, 4) D86 +detector(3, 2, 4) D87 +detector(3, 4, 4) D88 +detector(3, 6, 4) D89 +detector(4, 3, 4) D90 +detector(4, 5, 4) D91 +detector(4, 7, 4) D92 +detector(4, 9, 4) D93 +detector(5, 2, 4) D94 +detector(5, 4, 4) D95 +detector(5, 6, 4) D96 +detector(5, 8, 4) D97 +detector(6, 1, 4) D98 +detector(6, 3, 4) D99 +detector(6, 5, 4) D100 +detector(6, 7, 4) D101 +detector(7, 4, 4) D102 +detector(7, 6, 4) D103 +detector(7, 8, 4) D104 +detector(8, 3, 4) D105 +detector(8, 5, 4) D106 +detector(9, 6, 4) D107 +detector(1, 4, 5) D108 +detector(2, 5, 5) D109 +detector(2, 7, 5) D110 +detector(3, 2, 5) D111 +detector(3, 4, 5) D112 +detector(3, 6, 5) D113 +detector(4, 3, 5) D114 +detector(4, 5, 5) D115 +detector(4, 7, 5) D116 +detector(4, 9, 5) D117 +detector(5, 2, 5) D118 +detector(5, 4, 5) D119 +detector(5, 6, 5) D120 +detector(5, 8, 5) D121 +detector(6, 1, 5) D122 +detector(6, 3, 5) D123 +detector(6, 5, 5) D124 +detector(6, 7, 5) D125 +detector(7, 4, 5) D126 +detector(7, 6, 5) D127 +detector(7, 8, 5) D128 +detector(8, 3, 5) D129 +detector(8, 5, 5) D130 +detector(9, 6, 5) D131 +detector(1, 4, 6) D132 +detector(2, 5, 6) D133 +detector(2, 7, 6) D134 +detector(3, 2, 6) D135 +detector(3, 4, 6) D136 +detector(3, 6, 6) D137 +detector(4, 3, 6) D138 +detector(4, 5, 6) D139 +detector(4, 7, 6) D140 +detector(4, 9, 6) D141 +detector(5, 2, 6) D142 +detector(5, 4, 6) D143 +detector(5, 6, 6) D144 +detector(5, 8, 6) D145 +detector(6, 1, 6) D146 +detector(6, 3, 6) D147 +detector(6, 5, 6) D148 +detector(6, 7, 6) D149 +detector(7, 4, 6) D150 +detector(7, 6, 6) D151 +detector(7, 8, 6) D152 +detector(8, 3, 6) D153 +detector(8, 5, 6) D154 +detector(9, 6, 6) D155 +detector(1, 4, 7) D156 +detector(2, 5, 7) D157 +detector(2, 7, 7) D158 +detector(3, 2, 7) D159 +detector(3, 4, 7) D160 +detector(3, 6, 7) D161 +detector(4, 3, 7) D162 +detector(4, 5, 7) D163 +detector(4, 7, 7) D164 +detector(4, 9, 7) D165 +detector(5, 2, 7) D166 +detector(5, 4, 7) D167 +detector(5, 6, 7) D168 +detector(5, 8, 7) D169 +detector(6, 1, 7) D170 +detector(6, 3, 7) D171 +detector(6, 5, 7) D172 +detector(6, 7, 7) D173 +detector(7, 4, 7) D174 +detector(7, 6, 7) D175 +detector(7, 8, 7) D176 +detector(8, 3, 7) D177 +detector(8, 5, 7) D178 +detector(9, 6, 7) D179 +detector(1, 4, 8) D180 +detector(2, 5, 8) D181 +detector(2, 7, 8) D182 +detector(3, 2, 8) D183 +detector(3, 4, 8) D184 +detector(3, 6, 8) D185 +detector(4, 3, 8) D186 +detector(4, 5, 8) D187 +detector(4, 7, 8) D188 +detector(4, 9, 8) D189 +detector(5, 2, 8) D190 +detector(5, 4, 8) D191 +detector(5, 6, 8) D192 +detector(5, 8, 8) D193 +detector(6, 1, 8) D194 +detector(6, 3, 8) D195 +detector(6, 5, 8) D196 +detector(6, 7, 8) D197 +detector(7, 4, 8) D198 +detector(7, 6, 8) D199 +detector(7, 8, 8) D200 +detector(8, 3, 8) D201 +detector(8, 5, 8) D202 +detector(9, 6, 8) D203 +detector(1, 4, 9) D204 +detector(3, 2, 9) D205 +detector(3, 4, 9) D206 +detector(5, 2, 9) D207 +detector(3, 6, 9) D208 +detector(5, 4, 9) D209 +detector(5, 6, 9) D210 +detector(7, 4, 9) D211 +detector(5, 8, 9) D212 +detector(7, 6, 9) D213 +detector(7, 8, 9) D214 +detector(9, 6, 9) D215 diff --git a/shared/package-files/76/76beb30e98a911f72f97609a2373782573c17c88a5fb3537db338aa382979ffc/blob b/shared/package-files/76/76beb30e98a911f72f97609a2373782573c17c88a5fb3537db338aa382979ffc/blob new file mode 100644 index 0000000000000000000000000000000000000000..712aee6e93084760e88f729d42822c1ba5762e23 --- /dev/null +++ b/shared/package-files/76/76beb30e98a911f72f97609a2373782573c17c88a5fb3537db338aa382979ffc/blob @@ -0,0 +1,307 @@ +""" Python Character Mapping Codec kz1048 generated from 'MAPPINGS/VENDORS/MISC/KZ1048.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self, input, errors='strict'): + return codecs.charmap_encode(input, errors, encoding_table) + + def decode(self, input, errors='strict'): + return codecs.charmap_decode(input, errors, decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input, self.errors, encoding_table)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input, self.errors, decoding_table)[0] + +class StreamWriter(Codec, codecs.StreamWriter): + pass + +class StreamReader(Codec, codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='kz1048', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + + +### Decoding Table + +decoding_table = ( + '\x00' # 0x00 -> NULL + '\x01' # 0x01 -> START OF HEADING + '\x02' # 0x02 -> START OF TEXT + '\x03' # 0x03 -> END OF TEXT + '\x04' # 0x04 -> END OF TRANSMISSION + '\x05' # 0x05 -> ENQUIRY + '\x06' # 0x06 -> ACKNOWLEDGE + '\x07' # 0x07 -> BELL + '\x08' # 0x08 -> BACKSPACE + '\t' # 0x09 -> HORIZONTAL TABULATION + '\n' # 0x0A -> LINE FEED + '\x0b' # 0x0B -> VERTICAL TABULATION + '\x0c' # 0x0C -> FORM FEED + '\r' # 0x0D -> CARRIAGE RETURN + '\x0e' # 0x0E -> SHIFT OUT + '\x0f' # 0x0F -> SHIFT IN + '\x10' # 0x10 -> DATA LINK ESCAPE + '\x11' # 0x11 -> DEVICE CONTROL ONE + '\x12' # 0x12 -> DEVICE CONTROL TWO + '\x13' # 0x13 -> DEVICE CONTROL THREE + '\x14' # 0x14 -> DEVICE CONTROL FOUR + '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE + '\x16' # 0x16 -> SYNCHRONOUS IDLE + '\x17' # 0x17 -> END OF TRANSMISSION BLOCK + '\x18' # 0x18 -> CANCEL + '\x19' # 0x19 -> END OF MEDIUM + '\x1a' # 0x1A -> SUBSTITUTE + '\x1b' # 0x1B -> ESCAPE + '\x1c' # 0x1C -> FILE SEPARATOR + '\x1d' # 0x1D -> GROUP SEPARATOR + '\x1e' # 0x1E -> RECORD SEPARATOR + '\x1f' # 0x1F -> UNIT SEPARATOR + ' ' # 0x20 -> SPACE + '!' # 0x21 -> EXCLAMATION MARK + '"' # 0x22 -> QUOTATION MARK + '#' # 0x23 -> NUMBER SIGN + '$' # 0x24 -> DOLLAR SIGN + '%' # 0x25 -> PERCENT SIGN + '&' # 0x26 -> AMPERSAND + "'" # 0x27 -> APOSTROPHE + '(' # 0x28 -> LEFT PARENTHESIS + ')' # 0x29 -> RIGHT PARENTHESIS + '*' # 0x2A -> ASTERISK + '+' # 0x2B -> PLUS SIGN + ',' # 0x2C -> COMMA + '-' # 0x2D -> HYPHEN-MINUS + '.' # 0x2E -> FULL STOP + '/' # 0x2F -> SOLIDUS + '0' # 0x30 -> DIGIT ZERO + '1' # 0x31 -> DIGIT ONE + '2' # 0x32 -> DIGIT TWO + '3' # 0x33 -> DIGIT THREE + '4' # 0x34 -> DIGIT FOUR + '5' # 0x35 -> DIGIT FIVE + '6' # 0x36 -> DIGIT SIX + '7' # 0x37 -> DIGIT SEVEN + '8' # 0x38 -> DIGIT EIGHT + '9' # 0x39 -> DIGIT NINE + ':' # 0x3A -> COLON + ';' # 0x3B -> SEMICOLON + '<' # 0x3C -> LESS-THAN SIGN + '=' # 0x3D -> EQUALS SIGN + '>' # 0x3E -> GREATER-THAN SIGN + '?' # 0x3F -> QUESTION MARK + '@' # 0x40 -> COMMERCIAL AT + 'A' # 0x41 -> LATIN CAPITAL LETTER A + 'B' # 0x42 -> LATIN CAPITAL LETTER B + 'C' # 0x43 -> LATIN CAPITAL LETTER C + 'D' # 0x44 -> LATIN CAPITAL LETTER D + 'E' # 0x45 -> LATIN CAPITAL LETTER E + 'F' # 0x46 -> LATIN CAPITAL LETTER F + 'G' # 0x47 -> LATIN CAPITAL LETTER G + 'H' # 0x48 -> LATIN CAPITAL LETTER H + 'I' # 0x49 -> LATIN CAPITAL LETTER I + 'J' # 0x4A -> LATIN CAPITAL LETTER J + 'K' # 0x4B -> LATIN CAPITAL LETTER K + 'L' # 0x4C -> LATIN CAPITAL LETTER L + 'M' # 0x4D -> LATIN CAPITAL LETTER M + 'N' # 0x4E -> LATIN CAPITAL LETTER N + 'O' # 0x4F -> LATIN CAPITAL LETTER O + 'P' # 0x50 -> LATIN CAPITAL LETTER P + 'Q' # 0x51 -> LATIN CAPITAL LETTER Q + 'R' # 0x52 -> LATIN CAPITAL LETTER R + 'S' # 0x53 -> LATIN CAPITAL LETTER S + 'T' # 0x54 -> LATIN CAPITAL LETTER T + 'U' # 0x55 -> LATIN CAPITAL LETTER U + 'V' # 0x56 -> LATIN CAPITAL LETTER V + 'W' # 0x57 -> LATIN CAPITAL LETTER W + 'X' # 0x58 -> LATIN CAPITAL LETTER X + 'Y' # 0x59 -> LATIN CAPITAL LETTER Y + 'Z' # 0x5A -> LATIN CAPITAL LETTER Z + '[' # 0x5B -> LEFT SQUARE BRACKET + '\\' # 0x5C -> REVERSE SOLIDUS + ']' # 0x5D -> RIGHT SQUARE BRACKET + '^' # 0x5E -> CIRCUMFLEX ACCENT + '_' # 0x5F -> LOW LINE + '`' # 0x60 -> GRAVE ACCENT + 'a' # 0x61 -> LATIN SMALL LETTER A + 'b' # 0x62 -> LATIN SMALL LETTER B + 'c' # 0x63 -> LATIN SMALL LETTER C + 'd' # 0x64 -> LATIN SMALL LETTER D + 'e' # 0x65 -> LATIN SMALL LETTER E + 'f' # 0x66 -> LATIN SMALL LETTER F + 'g' # 0x67 -> LATIN SMALL LETTER G + 'h' # 0x68 -> LATIN SMALL LETTER H + 'i' # 0x69 -> LATIN SMALL LETTER I + 'j' # 0x6A -> LATIN SMALL LETTER J + 'k' # 0x6B -> LATIN SMALL LETTER K + 'l' # 0x6C -> LATIN SMALL LETTER L + 'm' # 0x6D -> LATIN SMALL LETTER M + 'n' # 0x6E -> LATIN SMALL LETTER N + 'o' # 0x6F -> LATIN SMALL LETTER O + 'p' # 0x70 -> LATIN SMALL LETTER P + 'q' # 0x71 -> LATIN SMALL LETTER Q + 'r' # 0x72 -> LATIN SMALL LETTER R + 's' # 0x73 -> LATIN SMALL LETTER S + 't' # 0x74 -> LATIN SMALL LETTER T + 'u' # 0x75 -> LATIN SMALL LETTER U + 'v' # 0x76 -> LATIN SMALL LETTER V + 'w' # 0x77 -> LATIN SMALL LETTER W + 'x' # 0x78 -> LATIN SMALL LETTER X + 'y' # 0x79 -> LATIN SMALL LETTER Y + 'z' # 0x7A -> LATIN SMALL LETTER Z + '{' # 0x7B -> LEFT CURLY BRACKET + '|' # 0x7C -> VERTICAL LINE + '}' # 0x7D -> RIGHT CURLY BRACKET + '~' # 0x7E -> TILDE + '\x7f' # 0x7F -> DELETE + '\u0402' # 0x80 -> CYRILLIC CAPITAL LETTER DJE + '\u0403' # 0x81 -> CYRILLIC CAPITAL LETTER GJE + '\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK + '\u0453' # 0x83 -> CYRILLIC SMALL LETTER GJE + '\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK + '\u2026' # 0x85 -> HORIZONTAL ELLIPSIS + '\u2020' # 0x86 -> DAGGER + '\u2021' # 0x87 -> DOUBLE DAGGER + '\u20ac' # 0x88 -> EURO SIGN + '\u2030' # 0x89 -> PER MILLE SIGN + '\u0409' # 0x8A -> CYRILLIC CAPITAL LETTER LJE + '\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK + '\u040a' # 0x8C -> CYRILLIC CAPITAL LETTER NJE + '\u049a' # 0x8D -> CYRILLIC CAPITAL LETTER KA WITH DESCENDER + '\u04ba' # 0x8E -> CYRILLIC CAPITAL LETTER SHHA + '\u040f' # 0x8F -> CYRILLIC CAPITAL LETTER DZHE + '\u0452' # 0x90 -> CYRILLIC SMALL LETTER DJE + '\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK + '\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK + '\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK + '\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK + '\u2022' # 0x95 -> BULLET + '\u2013' # 0x96 -> EN DASH + '\u2014' # 0x97 -> EM DASH + '\ufffe' # 0x98 -> UNDEFINED + '\u2122' # 0x99 -> TRADE MARK SIGN + '\u0459' # 0x9A -> CYRILLIC SMALL LETTER LJE + '\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + '\u045a' # 0x9C -> CYRILLIC SMALL LETTER NJE + '\u049b' # 0x9D -> CYRILLIC SMALL LETTER KA WITH DESCENDER + '\u04bb' # 0x9E -> CYRILLIC SMALL LETTER SHHA + '\u045f' # 0x9F -> CYRILLIC SMALL LETTER DZHE + '\xa0' # 0xA0 -> NO-BREAK SPACE + '\u04b0' # 0xA1 -> CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE + '\u04b1' # 0xA2 -> CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE + '\u04d8' # 0xA3 -> CYRILLIC CAPITAL LETTER SCHWA + '\xa4' # 0xA4 -> CURRENCY SIGN + '\u04e8' # 0xA5 -> CYRILLIC CAPITAL LETTER BARRED O + '\xa6' # 0xA6 -> BROKEN BAR + '\xa7' # 0xA7 -> SECTION SIGN + '\u0401' # 0xA8 -> CYRILLIC CAPITAL LETTER IO + '\xa9' # 0xA9 -> COPYRIGHT SIGN + '\u0492' # 0xAA -> CYRILLIC CAPITAL LETTER GHE WITH STROKE + '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xac' # 0xAC -> NOT SIGN + '\xad' # 0xAD -> SOFT HYPHEN + '\xae' # 0xAE -> REGISTERED SIGN + '\u04ae' # 0xAF -> CYRILLIC CAPITAL LETTER STRAIGHT U + '\xb0' # 0xB0 -> DEGREE SIGN + '\xb1' # 0xB1 -> PLUS-MINUS SIGN + '\u0406' # 0xB2 -> CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I + '\u0456' # 0xB3 -> CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + '\u04e9' # 0xB4 -> CYRILLIC SMALL LETTER BARRED O + '\xb5' # 0xB5 -> MICRO SIGN + '\xb6' # 0xB6 -> PILCROW SIGN + '\xb7' # 0xB7 -> MIDDLE DOT + '\u0451' # 0xB8 -> CYRILLIC SMALL LETTER IO + '\u2116' # 0xB9 -> NUMERO SIGN + '\u0493' # 0xBA -> CYRILLIC SMALL LETTER GHE WITH STROKE + '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\u04d9' # 0xBC -> CYRILLIC SMALL LETTER SCHWA + '\u04a2' # 0xBD -> CYRILLIC CAPITAL LETTER EN WITH DESCENDER + '\u04a3' # 0xBE -> CYRILLIC SMALL LETTER EN WITH DESCENDER + '\u04af' # 0xBF -> CYRILLIC SMALL LETTER STRAIGHT U + '\u0410' # 0xC0 -> CYRILLIC CAPITAL LETTER A + '\u0411' # 0xC1 -> CYRILLIC CAPITAL LETTER BE + '\u0412' # 0xC2 -> CYRILLIC CAPITAL LETTER VE + '\u0413' # 0xC3 -> CYRILLIC CAPITAL LETTER GHE + '\u0414' # 0xC4 -> CYRILLIC CAPITAL LETTER DE + '\u0415' # 0xC5 -> CYRILLIC CAPITAL LETTER IE + '\u0416' # 0xC6 -> CYRILLIC CAPITAL LETTER ZHE + '\u0417' # 0xC7 -> CYRILLIC CAPITAL LETTER ZE + '\u0418' # 0xC8 -> CYRILLIC CAPITAL LETTER I + '\u0419' # 0xC9 -> CYRILLIC CAPITAL LETTER SHORT I + '\u041a' # 0xCA -> CYRILLIC CAPITAL LETTER KA + '\u041b' # 0xCB -> CYRILLIC CAPITAL LETTER EL + '\u041c' # 0xCC -> CYRILLIC CAPITAL LETTER EM + '\u041d' # 0xCD -> CYRILLIC CAPITAL LETTER EN + '\u041e' # 0xCE -> CYRILLIC CAPITAL LETTER O + '\u041f' # 0xCF -> CYRILLIC CAPITAL LETTER PE + '\u0420' # 0xD0 -> CYRILLIC CAPITAL LETTER ER + '\u0421' # 0xD1 -> CYRILLIC CAPITAL LETTER ES + '\u0422' # 0xD2 -> CYRILLIC CAPITAL LETTER TE + '\u0423' # 0xD3 -> CYRILLIC CAPITAL LETTER U + '\u0424' # 0xD4 -> CYRILLIC CAPITAL LETTER EF + '\u0425' # 0xD5 -> CYRILLIC CAPITAL LETTER HA + '\u0426' # 0xD6 -> CYRILLIC CAPITAL LETTER TSE + '\u0427' # 0xD7 -> CYRILLIC CAPITAL LETTER CHE + '\u0428' # 0xD8 -> CYRILLIC CAPITAL LETTER SHA + '\u0429' # 0xD9 -> CYRILLIC CAPITAL LETTER SHCHA + '\u042a' # 0xDA -> CYRILLIC CAPITAL LETTER HARD SIGN + '\u042b' # 0xDB -> CYRILLIC CAPITAL LETTER YERU + '\u042c' # 0xDC -> CYRILLIC CAPITAL LETTER SOFT SIGN + '\u042d' # 0xDD -> CYRILLIC CAPITAL LETTER E + '\u042e' # 0xDE -> CYRILLIC CAPITAL LETTER YU + '\u042f' # 0xDF -> CYRILLIC CAPITAL LETTER YA + '\u0430' # 0xE0 -> CYRILLIC SMALL LETTER A + '\u0431' # 0xE1 -> CYRILLIC SMALL LETTER BE + '\u0432' # 0xE2 -> CYRILLIC SMALL LETTER VE + '\u0433' # 0xE3 -> CYRILLIC SMALL LETTER GHE + '\u0434' # 0xE4 -> CYRILLIC SMALL LETTER DE + '\u0435' # 0xE5 -> CYRILLIC SMALL LETTER IE + '\u0436' # 0xE6 -> CYRILLIC SMALL LETTER ZHE + '\u0437' # 0xE7 -> CYRILLIC SMALL LETTER ZE + '\u0438' # 0xE8 -> CYRILLIC SMALL LETTER I + '\u0439' # 0xE9 -> CYRILLIC SMALL LETTER SHORT I + '\u043a' # 0xEA -> CYRILLIC SMALL LETTER KA + '\u043b' # 0xEB -> CYRILLIC SMALL LETTER EL + '\u043c' # 0xEC -> CYRILLIC SMALL LETTER EM + '\u043d' # 0xED -> CYRILLIC SMALL LETTER EN + '\u043e' # 0xEE -> CYRILLIC SMALL LETTER O + '\u043f' # 0xEF -> CYRILLIC SMALL LETTER PE + '\u0440' # 0xF0 -> CYRILLIC SMALL LETTER ER + '\u0441' # 0xF1 -> CYRILLIC SMALL LETTER ES + '\u0442' # 0xF2 -> CYRILLIC SMALL LETTER TE + '\u0443' # 0xF3 -> CYRILLIC SMALL LETTER U + '\u0444' # 0xF4 -> CYRILLIC SMALL LETTER EF + '\u0445' # 0xF5 -> CYRILLIC SMALL LETTER HA + '\u0446' # 0xF6 -> CYRILLIC SMALL LETTER TSE + '\u0447' # 0xF7 -> CYRILLIC SMALL LETTER CHE + '\u0448' # 0xF8 -> CYRILLIC SMALL LETTER SHA + '\u0449' # 0xF9 -> CYRILLIC SMALL LETTER SHCHA + '\u044a' # 0xFA -> CYRILLIC SMALL LETTER HARD SIGN + '\u044b' # 0xFB -> CYRILLIC SMALL LETTER YERU + '\u044c' # 0xFC -> CYRILLIC SMALL LETTER SOFT SIGN + '\u044d' # 0xFD -> CYRILLIC SMALL LETTER E + '\u044e' # 0xFE -> CYRILLIC SMALL LETTER YU + '\u044f' # 0xFF -> CYRILLIC SMALL LETTER YA +) + +### Encoding table +encoding_table = codecs.charmap_build(decoding_table) diff --git a/shared/package-files/76/76bfeda63663068df7d5848f6947a5a7c0873fd64fa0d518deadadeb3e0aa6ea/blob b/shared/package-files/76/76bfeda63663068df7d5848f6947a5a7c0873fd64fa0d518deadadeb3e0aa6ea/blob new file mode 100644 index 0000000000000000000000000000000000000000..3ba2a43c059659a47c1fb25928dda8a142311b7f --- /dev/null +++ b/shared/package-files/76/76bfeda63663068df7d5848f6947a5a7c0873fd64fa0d518deadadeb3e0aa6ea/blob @@ -0,0 +1,364 @@ +import itertools +import warnings +from enum import auto, Enum +from typing import Dict, List, Optional, Tuple, Union + +import torch +import torch.distributed as dist +import torch.distributed.fsdp._traversal_utils as traversal_utils +import torch.nn as nn +from torch.distributed.fsdp._common_utils import _FSDPState, _get_param_to_fqns +from torch.distributed.fsdp._flat_param import FlatParamHandle + + +class _ExecOrderWarnStatus(Enum): + """Used internally for execution order validation.""" + + NONE = auto() # no deviation yet + WARNING = auto() # deviated this iteration; currently issuing warnings + WARNED = auto() # deviated in a previous iteration + + +class _ExecOrderData: + """ + This contains the data structures to track the execution order. We track + the pre-forward order on the *first* iteration for forward prefetching + (which thus assumes static graph) and the post-forward order on *every* + iteration for backward prefetching (which thus does not assume static + graph but may be provide an incorrect order). + """ + + def __init__( + self, + debug_level: dist.DebugLevel, + backward_prefetch_limit: int, + forward_prefetch_limit: int, + ) -> None: + # Tracks the (static) pre-forward order for execution order validation + # and forward prefetching + self.handles_pre_forward_order: List[FlatParamHandle] = [] + # Tracks the post-forward order for pre-backward prefetching + self.handles_post_forward_order: List[Optional[FlatParamHandle]] = [] + self._iter = 0 + + # Gives the max number of backward/forward prefetched all-gathers by a + # single module + self._backward_prefetch_limit = backward_prefetch_limit + self._forward_prefetch_limit = forward_prefetch_limit + + # Data structures for execution order validation + self._checking_order: bool = debug_level == dist.DebugLevel.DETAIL + self.process_group: Optional[dist.ProcessGroup] = None + self.world_size: Optional[int] = None + self.all_handles: List[FlatParamHandle] = [] + # Names are prefixed from the root module + self.param_to_fqn: Dict[nn.Parameter, List[str]] = {} + # Current index in the pre-forward execution order + self.current_order_index = 0 + self.warn_status = _ExecOrderWarnStatus.NONE + + def init( + self, + state: _FSDPState, + root_module: nn.Module, + process_group: dist.ProcessGroup, + ) -> None: + """ + Initializes the data structures needed for checking the forward order. + This should be called after a root FSDP instance has been set during + lazy initialization. + """ + self.process_group = process_group + self.rank = process_group.rank() + self.world_size = process_group.size() + # Fix an order over the handles, which should be the same across ranks + for handle in traversal_utils._get_fsdp_handles(root_module): + index = len(self.all_handles) + self.all_handles.append(handle) + handle._handle_index = index + self.param_to_fqn = _get_param_to_fqns(root_module) + # TODO (awgu): We can broadcast the metadata of rank 0's `all_handles` + # to check that all ranks have the same handles in the same order. + # https://github.com/pytorch/pytorch/issues/79620 + + @property + def is_first_iter(self) -> bool: + return self._iter == 0 + + def get_handle_to_backward_prefetch( + self, + current_handle: FlatParamHandle, + ) -> Optional[FlatParamHandle]: + """ + Returns a :class:`list` of the handles keys of the handles to backward + prefetch given the current handles key. If there are no valid handles + keys to prefetch, then this returns an empty :class:`list`. + """ + current_index = current_handle._post_forward_index + if current_index is None: + return None + target_index = current_index - 1 + target_handle: Optional[FlatParamHandle] = None + for _ in range(self._backward_prefetch_limit): + if target_index < 0: + break + target_handle = self.handles_post_forward_order[target_index] + target_index -= 1 + return target_handle + + def get_handle_to_forward_prefetch( + self, + current_handle: FlatParamHandle, + ) -> Optional[FlatParamHandle]: + """ + Returns a :class:`list` of the handles keys of the handles to forward + prefetch given the current handles key. If there are no valid handles + keys to prefetch, then this returns an empty :class:`list`. + """ + current_index = current_handle._pre_forward_order_index + if current_index is None: + return None + target_index = current_index + 1 + target_handle: Optional[FlatParamHandle] = None + for _ in range(self._forward_prefetch_limit): + if target_index >= len(self.handles_pre_forward_order): + break + target_handle = self.handles_pre_forward_order[target_index] + target_index += 1 + return target_handle + + def record_post_forward(self, handle: Optional[FlatParamHandle]) -> None: + """ + Records ``handles`` in the post-forward order, where ``handles`` should + be a group of handles used in the same module's forward. If ``handles`` + is empty, then it is omitted. + + Unlike :meth:`record_pre_forward`, this records the order *every* + iteration with the expectation that the recorded order is reset in + :meth:`next_iter`. + """ + if not handle: + return + # Only record the first usage of a handles key + if handle._post_forward_index: + self.handles_post_forward_order.append(handle) + return + index = len(self.handles_post_forward_order) + handle._post_forward_index = index + self.handles_post_forward_order.append(handle) + + def record_pre_forward( + self, handle: Optional[FlatParamHandle], is_training: bool + ) -> None: + """ + Records ``handles`` in the pre-forward order, where ``handles`` should + be a group of handles used in the same module's forward. If ``handles`` + is empty, then it is omitted. + + On the first iteration, this checks the execution order across ranks. + See :meth:`_check_order` for details. + """ + if not handle: + return + self._check_order(handle, is_training) + # Fix the order after the first iteration and only record the first + # usage of a handles key + if not self.is_first_iter or handle._pre_forward_order_index is not None: + return + index = len(self.handles_pre_forward_order) + handle._pre_forward_order_index = index + self.handles_pre_forward_order.append(handle) + + def _check_order(self, handle: FlatParamHandle, is_training: bool) -> None: + """ + Checks the forward execution order as long as ``is_training`` is + ``True`` since checking in eval mode is not supported. This only checks + if the distributed debug level is DETAIL. + + - On the first iteration, this uses all-gathers to check that all ranks + are all-gathering the same handles and hence ``FlatParameter`` s, + raising an error if not. + - On subsequent iterations, this checks that each rank is locally + consistent with its own forward order from the first iteration, issuing + a warning if not. This issues a warning on the first deviating + iteration and stops warning thereafter. + """ + # Do not check order in eval mode since the post-backward callback does + # not run so it cannot be used to mark the end of an iteration + if not is_training or not self._checking_order: + return + if self.is_first_iter: + msg_prefix = "Forward order differs across ranks:" + optional_local_indices: Tuple[ + Optional[int], ... + ] = self._get_handle_indices(handle) + device = handle.device # guaranteed to be non-CPU + num_valid_indices = sum( + (index is not None) for index in optional_local_indices + ) + tensor_kwargs: Dict[str, Union[torch.dtype, torch.device]] = { + "dtype": torch.int32, + "device": device, + } + world_num_valid_indices = torch.zeros(self.world_size, **tensor_kwargs) # type: ignore[arg-type, call-overload] + local_num_valid_indices = torch.tensor([num_valid_indices], **tensor_kwargs) # type: ignore[arg-type, call-overload] + dist.all_gather_into_tensor( + world_num_valid_indices, + local_num_valid_indices, + group=self.process_group, + ) + # Copy entire tensor from D2H once to avoid per element D2H copies + world_num_valid_indices = world_num_valid_indices.cpu() + # Check that all ranks plan to all-gather the same number of + # parameters + # TODO (awgu): Since every module has at most one handle in the + # current implementation, this should never raise the error. + assert self.world_size is not None # mypy + if not torch.distributed._functional_collectives.is_torchdynamo_compiling(): + # TODO(voz): Don't graph break on this - dynamo hates the n1 != n2 + # tensor comparison control flow. + # https://github.com/pytorch/pytorch/issues/107055 + for (r1, n1), (r2, n2) in itertools.combinations( + ( + (rank, world_num_valid_indices[rank]) + for rank in range(self.world_size) + ), + 2, + ): + if n1 != n2: + raise RuntimeError( + f"{msg_prefix} rank {r1} is all-gathering {n1} parameters " + f"while rank {r2} is all-gathering {n2} parameters" + ) + world_indices = torch.zeros( # type: ignore[call-overload] + self.world_size * num_valid_indices, **tensor_kwargs + ) + local_indices = torch.tensor(optional_local_indices, **tensor_kwargs) # type: ignore[arg-type] + dist.all_gather_into_tensor( + world_indices, local_indices, group=self.process_group + ) + # Copy entire tensor from D2H once to avoid per element D2H copies + world_indices = world_indices.cpu() + # Check that all ranks plan to all-gather the same index parameters + if not torch.distributed._functional_collectives.is_torchdynamo_compiling(): + # TODO(voz): Don't graph break on this - dynamo hates the i1 != i2 + # tensor comparison control flow. + # https://github.com/pytorch/pytorch/issues/107055 + for (r1, i1), (r2, i2) in itertools.combinations( + ( + ( + rank, + world_indices[ + rank + * num_valid_indices : (rank + 1) + * num_valid_indices + ], + ) + for rank in range(self.world_size) + ), + 2, + ): + if i1 != i2: + r1_param_names = self._get_names_from_handle_indices(i1) + r2_param_names = self._get_names_from_handle_indices(i2) + raise RuntimeError( + f"{msg_prefix} rank {r1} is all-gathering parameters " + f"for {r1_param_names} while rank {r2} is all-gathering " + f"parameters for {r2_param_names}" + ) + else: + # Only issue warnings on the first deviating iteration and stop + # checking thereafter to avoid flooding the console + if self.warn_status == _ExecOrderWarnStatus.WARNED: + return + msg_prefix = None # non-`None` means we should warn + if self.current_order_index >= len(self.handles_pre_forward_order): + # This iteration sees extra all-gather(s) compared to the first + msg_prefix = ( + "Expected to not all-gather any more parameters in the " + "forward but trying to all-gather parameters for " + ) + else: + expected_handle = self.handles_pre_forward_order[ + self.current_order_index + ] + if expected_handle != handle: + expected_param_names = self._get_names_from_handles(expected_handle) + msg_prefix = ( + f"Expected to all-gather for {expected_param_names} " + "but trying to all-gather parameters for " + ) + if msg_prefix is not None: + param_names = self._get_names_from_handles(handle) + msg_suffix = ( + f"{param_names}" + if param_names + else "a newly-added parameter since construction time" + ) + warnings.warn( + "Forward order differs from that of the first iteration " + f"on rank {self.rank}. Collectives are unchecked and may " + f"give incorrect results or hang.\n{msg_prefix}{msg_suffix}" + ) + self.warn_status = _ExecOrderWarnStatus.WARNING + self.current_order_index += 1 + + def _get_handle_indices( + self, + handle: FlatParamHandle, + ) -> Tuple[Optional[int], ...]: + """ + Returns the handle indices (i.e. indices into ``self.all_handles``) + corresponding to the handles in ``handle``. An entry in the + returned tuple is ``None`` if the handle is invalid. + """ + indices: List[Optional[int]] = [] + if handle: + indices.append(handle._handle_index) + return tuple(indices) + + def _get_names_from_handle_indices( + self, + handle_indices: Tuple[int, ...], + ) -> List[List[str]]: + """ + Returns a list of FQNs for each handle in ``handle_indices``. If a + handle index is invalid, then its FQNs are omitted from the returned + list. + """ + fqns: List[List[str]] = [] + for index in handle_indices: + if index is None or index < 0 or index >= len(self.all_handles): + continue + handle = self.all_handles[index] + flat_param = handle.flat_param + fqns.append(self.param_to_fqn[flat_param]) + return fqns + + def _get_names_from_handles( + self, + handle: FlatParamHandle, + ) -> List[List[str]]: + """ + Returns a list of FQNs for each handle in ``handles_key``. If a handle + is invalid, then its FQNs are omitted from the returned list. + """ + fqns: List[List[str]] = [] + if handle: + flat_param = handle.flat_param + if flat_param in self.param_to_fqn: + fqns.append(self.param_to_fqn[flat_param]) + return fqns + + def next_iter(self): + """ + Advances the internal data structures per iteration. This should be + called in the post-backward callback since that marks the true end of + an iteration. + """ + self._iter += 1 + self.handles_post_forward_order.clear() + if self._checking_order: + self.current_order_index = 0 + if self.warn_status == _ExecOrderWarnStatus.WARNING: + self.warn_status = _ExecOrderWarnStatus.WARNED diff --git a/shared/package-files/76/76c07c0d11be1ab3f305a67e6c86ae61a6da7aa5db7ea068f5220ff41a9c4d2b/blob b/shared/package-files/76/76c07c0d11be1ab3f305a67e6c86ae61a6da7aa5db7ea068f5220ff41a9c4d2b/blob new file mode 100644 index 0000000000000000000000000000000000000000..f577c7fa9f9734876b6767f6cc21144df305d82f --- /dev/null +++ b/shared/package-files/76/76c07c0d11be1ab3f305a67e6c86ae61a6da7aa5db7ea068f5220ff41a9c4d2b/blob @@ -0,0 +1,451 @@ +import mpmath +from mpmath import * +from mpmath.libmp import * +import random +import sys + +try: + long = long +except NameError: + long = int + +def test_type_compare(): + assert mpf(2) == mpc(2,0) + assert mpf(0) == mpc(0) + assert mpf(2) != mpc(2, 0.00001) + assert mpf(2) == 2.0 + assert mpf(2) != 3.0 + assert mpf(2) == 2 + assert mpf(2) != '2.0' + assert mpc(2) != '2.0' + +def test_add(): + assert mpf(2.5) + mpf(3) == 5.5 + assert mpf(2.5) + 3 == 5.5 + assert mpf(2.5) + 3.0 == 5.5 + assert 3 + mpf(2.5) == 5.5 + assert 3.0 + mpf(2.5) == 5.5 + assert (3+0j) + mpf(2.5) == 5.5 + assert mpc(2.5) + mpf(3) == 5.5 + assert mpc(2.5) + 3 == 5.5 + assert mpc(2.5) + 3.0 == 5.5 + assert mpc(2.5) + (3+0j) == 5.5 + assert 3 + mpc(2.5) == 5.5 + assert 3.0 + mpc(2.5) == 5.5 + assert (3+0j) + mpc(2.5) == 5.5 + +def test_sub(): + assert mpf(2.5) - mpf(3) == -0.5 + assert mpf(2.5) - 3 == -0.5 + assert mpf(2.5) - 3.0 == -0.5 + assert 3 - mpf(2.5) == 0.5 + assert 3.0 - mpf(2.5) == 0.5 + assert (3+0j) - mpf(2.5) == 0.5 + assert mpc(2.5) - mpf(3) == -0.5 + assert mpc(2.5) - 3 == -0.5 + assert mpc(2.5) - 3.0 == -0.5 + assert mpc(2.5) - (3+0j) == -0.5 + assert 3 - mpc(2.5) == 0.5 + assert 3.0 - mpc(2.5) == 0.5 + assert (3+0j) - mpc(2.5) == 0.5 + +def test_mul(): + assert mpf(2.5) * mpf(3) == 7.5 + assert mpf(2.5) * 3 == 7.5 + assert mpf(2.5) * 3.0 == 7.5 + assert 3 * mpf(2.5) == 7.5 + assert 3.0 * mpf(2.5) == 7.5 + assert (3+0j) * mpf(2.5) == 7.5 + assert mpc(2.5) * mpf(3) == 7.5 + assert mpc(2.5) * 3 == 7.5 + assert mpc(2.5) * 3.0 == 7.5 + assert mpc(2.5) * (3+0j) == 7.5 + assert 3 * mpc(2.5) == 7.5 + assert 3.0 * mpc(2.5) == 7.5 + assert (3+0j) * mpc(2.5) == 7.5 + +def test_div(): + assert mpf(6) / mpf(3) == 2.0 + assert mpf(6) / 3 == 2.0 + assert mpf(6) / 3.0 == 2.0 + assert 6 / mpf(3) == 2.0 + assert 6.0 / mpf(3) == 2.0 + assert (6+0j) / mpf(3.0) == 2.0 + assert mpc(6) / mpf(3) == 2.0 + assert mpc(6) / 3 == 2.0 + assert mpc(6) / 3.0 == 2.0 + assert mpc(6) / (3+0j) == 2.0 + assert 6 / mpc(3) == 2.0 + assert 6.0 / mpc(3) == 2.0 + assert (6+0j) / mpc(3) == 2.0 + +def test_pow(): + assert mpf(6) ** mpf(3) == 216.0 + assert mpf(6) ** 3 == 216.0 + assert mpf(6) ** 3.0 == 216.0 + assert 6 ** mpf(3) == 216.0 + assert 6.0 ** mpf(3) == 216.0 + assert (6+0j) ** mpf(3.0) == 216.0 + assert mpc(6) ** mpf(3) == 216.0 + assert mpc(6) ** 3 == 216.0 + assert mpc(6) ** 3.0 == 216.0 + assert mpc(6) ** (3+0j) == 216.0 + assert 6 ** mpc(3) == 216.0 + assert 6.0 ** mpc(3) == 216.0 + assert (6+0j) ** mpc(3) == 216.0 + +def test_mixed_misc(): + assert 1 + mpf(3) == mpf(3) + 1 == 4 + assert 1 - mpf(3) == -(mpf(3) - 1) == -2 + assert 3 * mpf(2) == mpf(2) * 3 == 6 + assert 6 / mpf(2) == mpf(6) / 2 == 3 + assert 1.0 + mpf(3) == mpf(3) + 1.0 == 4 + assert 1.0 - mpf(3) == -(mpf(3) - 1.0) == -2 + assert 3.0 * mpf(2) == mpf(2) * 3.0 == 6 + assert 6.0 / mpf(2) == mpf(6) / 2.0 == 3 + +def test_add_misc(): + mp.dps = 15 + assert mpf(4) + mpf(-70) == -66 + assert mpf(1) + mpf(1.1)/80 == 1 + 1.1/80 + assert mpf((1, 10000000000)) + mpf(3) == mpf((1, 10000000000)) + assert mpf(3) + mpf((1, 10000000000)) == mpf((1, 10000000000)) + assert mpf((1, -10000000000)) + mpf(3) == mpf(3) + assert mpf(3) + mpf((1, -10000000000)) == mpf(3) + assert mpf(1) + 1e-15 != 1 + assert mpf(1) + 1e-20 == 1 + assert mpf(1.07e-22) + 0 == mpf(1.07e-22) + assert mpf(0) + mpf(1.07e-22) == mpf(1.07e-22) + +def test_complex_misc(): + # many more tests needed + assert 1 + mpc(2) == 3 + assert not mpc(2).ae(2 + 1e-13) + assert mpc(2+1e-15j).ae(2) + +def test_complex_zeros(): + for a in [0,2]: + for b in [0,3]: + for c in [0,4]: + for d in [0,5]: + assert mpc(a,b)*mpc(c,d) == complex(a,b)*complex(c,d) + +def test_hash(): + for i in range(-256, 256): + assert hash(mpf(i)) == hash(i) + assert hash(mpf(0.5)) == hash(0.5) + assert hash(mpc(2,3)) == hash(2+3j) + # Check that this doesn't fail + assert hash(inf) + # Check that overflow doesn't assign equal hashes to large numbers + assert hash(mpf('1e1000')) != hash('1e10000') + assert hash(mpc(100,'1e1000')) != hash(mpc(200,'1e1000')) + from mpmath.rational import mpq + assert hash(mp.mpq(1,3)) + assert hash(mp.mpq(0,1)) == 0 + assert hash(mp.mpq(-1,1)) == hash(-1) + assert hash(mp.mpq(1,1)) == hash(1) + assert hash(mp.mpq(5,1)) == hash(5) + assert hash(mp.mpq(1,2)) == hash(0.5) + if sys.version_info >= (3, 2): + assert hash(mpf(1)*2**2000) == hash(2**2000) + assert hash(mpf(1)/2**2000) == hash(mpq(1,2**2000)) + +# Advanced rounding test +def test_add_rounding(): + mp.dps = 15 + a = from_float(1e-50) + assert mpf_sub(mpf_add(fone, a, 53, round_up), fone, 53, round_up) == from_float(2.2204460492503131e-16) + assert mpf_sub(fone, a, 53, round_up) == fone + assert mpf_sub(fone, mpf_sub(fone, a, 53, round_down), 53, round_down) == from_float(1.1102230246251565e-16) + assert mpf_add(fone, a, 53, round_down) == fone + +def test_almost_equal(): + assert mpf(1.2).ae(mpf(1.20000001), 1e-7) + assert not mpf(1.2).ae(mpf(1.20000001), 1e-9) + assert not mpf(-0.7818314824680298).ae(mpf(-0.774695868667929)) + +def test_arithmetic_functions(): + import operator + ops = [(operator.add, fadd), (operator.sub, fsub), (operator.mul, fmul), + (operator.truediv, fdiv)] + a = mpf(0.27) + b = mpf(1.13) + c = mpc(0.51+2.16j) + d = mpc(1.08-0.99j) + for x in [a,b,c,d]: + for y in [a,b,c,d]: + for op, fop in ops: + if fop is not fdiv: + mp.prec = 200 + z0 = op(x,y) + mp.prec = 60 + z1 = op(x,y) + mp.prec = 53 + z2 = op(x,y) + assert fop(x, y, prec=60) == z1 + assert fop(x, y) == z2 + if fop is not fdiv: + assert fop(x, y, prec=inf) == z0 + assert fop(x, y, dps=inf) == z0 + assert fop(x, y, exact=True) == z0 + assert fneg(fneg(z1, exact=True), prec=inf) == z1 + assert fneg(z1) == -(+z1) + mp.dps = 15 + +def test_exact_integer_arithmetic(): + # XXX: re-fix this so that all operations are tested with all rounding modes + random.seed(0) + for prec in [6, 10, 25, 40, 100, 250, 725]: + for rounding in ['d', 'u', 'f', 'c', 'n']: + mp.dps = prec + M = 10**(prec-2) + M2 = 10**(prec//2-2) + for i in range(10): + a = random.randint(-M, M) + b = random.randint(-M, M) + assert mpf(a, rounding=rounding) == a + assert int(mpf(a, rounding=rounding)) == a + assert int(mpf(str(a), rounding=rounding)) == a + assert mpf(a) + mpf(b) == a + b + assert mpf(a) - mpf(b) == a - b + assert -mpf(a) == -a + a = random.randint(-M2, M2) + b = random.randint(-M2, M2) + assert mpf(a) * mpf(b) == a*b + assert mpf_mul(from_int(a), from_int(b), mp.prec, rounding) == from_int(a*b) + mp.dps = 15 + +def test_odd_int_bug(): + assert to_int(from_int(3), round_nearest) == 3 + +def test_str_1000_digits(): + mp.dps = 1001 + # last digit may be wrong + assert str(mpf(2)**0.5)[-10:-1] == '9518488472'[:9] + assert str(pi)[-10:-1] == '2164201989'[:9] + mp.dps = 15 + +def test_str_10000_digits(): + mp.dps = 10001 + # last digit may be wrong + assert str(mpf(2)**0.5)[-10:-1] == '5873258351'[:9] + assert str(pi)[-10:-1] == '5256375678'[:9] + mp.dps = 15 + +def test_monitor(): + f = lambda x: x**2 + a = [] + b = [] + g = monitor(f, a.append, b.append) + assert g(3) == 9 + assert g(4) == 16 + assert a[0] == ((3,), {}) + assert b[0] == 9 + +def test_nint_distance(): + assert nint_distance(mpf(-3)) == (-3, -inf) + assert nint_distance(mpc(-3)) == (-3, -inf) + assert nint_distance(mpf(-3.1)) == (-3, -3) + assert nint_distance(mpf(-3.01)) == (-3, -6) + assert nint_distance(mpf(-3.001)) == (-3, -9) + assert nint_distance(mpf(-3.0001)) == (-3, -13) + assert nint_distance(mpf(-2.9)) == (-3, -3) + assert nint_distance(mpf(-2.99)) == (-3, -6) + assert nint_distance(mpf(-2.999)) == (-3, -9) + assert nint_distance(mpf(-2.9999)) == (-3, -13) + assert nint_distance(mpc(-3+0.1j)) == (-3, -3) + assert nint_distance(mpc(-3+0.01j)) == (-3, -6) + assert nint_distance(mpc(-3.1+0.1j)) == (-3, -3) + assert nint_distance(mpc(-3.01+0.01j)) == (-3, -6) + assert nint_distance(mpc(-3.001+0.001j)) == (-3, -9) + assert nint_distance(mpf(0)) == (0, -inf) + assert nint_distance(mpf(0.01)) == (0, -6) + assert nint_distance(mpf('1e-100')) == (0, -332) + +def test_floor_ceil_nint_frac(): + mp.dps = 15 + for n in range(-10,10): + assert floor(n) == n + assert floor(n+0.5) == n + assert ceil(n) == n + assert ceil(n+0.5) == n+1 + assert nint(n) == n + # nint rounds to even + if n % 2 == 1: + assert nint(n+0.5) == n+1 + else: + assert nint(n+0.5) == n + assert floor(inf) == inf + assert floor(ninf) == ninf + assert isnan(floor(nan)) + assert ceil(inf) == inf + assert ceil(ninf) == ninf + assert isnan(ceil(nan)) + assert nint(inf) == inf + assert nint(ninf) == ninf + assert isnan(nint(nan)) + assert floor(0.1) == 0 + assert floor(0.9) == 0 + assert floor(-0.1) == -1 + assert floor(-0.9) == -1 + assert floor(10000000000.1) == 10000000000 + assert floor(10000000000.9) == 10000000000 + assert floor(-10000000000.1) == -10000000000-1 + assert floor(-10000000000.9) == -10000000000-1 + assert floor(1e-100) == 0 + assert floor(-1e-100) == -1 + assert floor(1e100) == 1e100 + assert floor(-1e100) == -1e100 + assert ceil(0.1) == 1 + assert ceil(0.9) == 1 + assert ceil(-0.1) == 0 + assert ceil(-0.9) == 0 + assert ceil(10000000000.1) == 10000000000+1 + assert ceil(10000000000.9) == 10000000000+1 + assert ceil(-10000000000.1) == -10000000000 + assert ceil(-10000000000.9) == -10000000000 + assert ceil(1e-100) == 1 + assert ceil(-1e-100) == 0 + assert ceil(1e100) == 1e100 + assert ceil(-1e100) == -1e100 + assert nint(0.1) == 0 + assert nint(0.9) == 1 + assert nint(-0.1) == 0 + assert nint(-0.9) == -1 + assert nint(10000000000.1) == 10000000000 + assert nint(10000000000.9) == 10000000000+1 + assert nint(-10000000000.1) == -10000000000 + assert nint(-10000000000.9) == -10000000000-1 + assert nint(1e-100) == 0 + assert nint(-1e-100) == 0 + assert nint(1e100) == 1e100 + assert nint(-1e100) == -1e100 + assert floor(3.2+4.6j) == 3+4j + assert ceil(3.2+4.6j) == 4+5j + assert nint(3.2+4.6j) == 3+5j + for n in range(-10,10): + assert frac(n) == 0 + assert frac(0.25) == 0.25 + assert frac(1.25) == 0.25 + assert frac(2.25) == 0.25 + assert frac(-0.25) == 0.75 + assert frac(-1.25) == 0.75 + assert frac(-2.25) == 0.75 + assert frac('1e100000000000000') == 0 + u = mpf('1e-100000000000000') + assert frac(u) == u + assert frac(-u) == 1 # rounding! + u = mpf('1e-400') + assert frac(-u, prec=0) == fsub(1, u, exact=True) + assert frac(3.25+4.75j) == 0.25+0.75j + +def test_isnan_etc(): + from mpmath.rational import mpq + assert isnan(nan) == True + assert isnan(3) == False + assert isnan(mpf(3)) == False + assert isnan(inf) == False + assert isnan(mpc(2,nan)) == True + assert isnan(mpc(2,nan)) == True + assert isnan(mpc(nan,nan)) == True + assert isnan(mpc(2,2)) == False + assert isnan(mpc(nan,inf)) == True + assert isnan(mpc(inf,inf)) == False + assert isnan(mpq((3,2))) == False + assert isnan(mpq((0,1))) == False + assert isinf(inf) == True + assert isinf(-inf) == True + assert isinf(3) == False + assert isinf(nan) == False + assert isinf(3+4j) == False + assert isinf(mpc(inf)) == True + assert isinf(mpc(3,inf)) == True + assert isinf(mpc(inf,3)) == True + assert isinf(mpc(inf,inf)) == True + assert isinf(mpc(nan,inf)) == True + assert isinf(mpc(inf,nan)) == True + assert isinf(mpc(nan,nan)) == False + assert isinf(mpq((3,2))) == False + assert isinf(mpq((0,1))) == False + assert isnormal(3) == True + assert isnormal(3.5) == True + assert isnormal(mpf(3.5)) == True + assert isnormal(0) == False + assert isnormal(mpf(0)) == False + assert isnormal(0.0) == False + assert isnormal(inf) == False + assert isnormal(-inf) == False + assert isnormal(nan) == False + assert isnormal(float(inf)) == False + assert isnormal(mpc(0,0)) == False + assert isnormal(mpc(3,0)) == True + assert isnormal(mpc(0,3)) == True + assert isnormal(mpc(3,3)) == True + assert isnormal(mpc(0,nan)) == False + assert isnormal(mpc(0,inf)) == False + assert isnormal(mpc(3,nan)) == False + assert isnormal(mpc(3,inf)) == False + assert isnormal(mpc(3,-inf)) == False + assert isnormal(mpc(nan,0)) == False + assert isnormal(mpc(inf,0)) == False + assert isnormal(mpc(nan,3)) == False + assert isnormal(mpc(inf,3)) == False + assert isnormal(mpc(inf,nan)) == False + assert isnormal(mpc(nan,inf)) == False + assert isnormal(mpc(nan,nan)) == False + assert isnormal(mpc(inf,inf)) == False + assert isnormal(mpq((3,2))) == True + assert isnormal(mpq((0,1))) == False + assert isint(3) == True + assert isint(0) == True + assert isint(long(3)) == True + assert isint(long(0)) == True + assert isint(mpf(3)) == True + assert isint(mpf(0)) == True + assert isint(mpf(-3)) == True + assert isint(mpf(3.2)) == False + assert isint(3.2) == False + assert isint(nan) == False + assert isint(inf) == False + assert isint(-inf) == False + assert isint(mpc(0)) == True + assert isint(mpc(3)) == True + assert isint(mpc(3.2)) == False + assert isint(mpc(3,inf)) == False + assert isint(mpc(inf)) == False + assert isint(mpc(3,2)) == False + assert isint(mpc(0,2)) == False + assert isint(mpc(3,2),gaussian=True) == True + assert isint(mpc(3,0),gaussian=True) == True + assert isint(mpc(0,3),gaussian=True) == True + assert isint(3+4j) == False + assert isint(3+4j, gaussian=True) == True + assert isint(3+0j) == True + assert isint(mpq((3,2))) == False + assert isint(mpq((3,9))) == False + assert isint(mpq((9,3))) == True + assert isint(mpq((0,4))) == True + assert isint(mpq((1,1))) == True + assert isint(mpq((-1,1))) == True + assert mp.isnpint(0) == True + assert mp.isnpint(1) == False + assert mp.isnpint(-1) == True + assert mp.isnpint(-1.1) == False + assert mp.isnpint(-1.0) == True + assert mp.isnpint(mp.mpq(1,2)) == False + assert mp.isnpint(mp.mpq(-1,2)) == False + assert mp.isnpint(mp.mpq(-3,1)) == True + assert mp.isnpint(mp.mpq(0,1)) == True + assert mp.isnpint(mp.mpq(1,1)) == False + assert mp.isnpint(0+0j) == True + assert mp.isnpint(-1+0j) == True + assert mp.isnpint(-1.1+0j) == False + assert mp.isnpint(-1+0.1j) == False + assert mp.isnpint(0+0.1j) == False + + +def test_issue_438(): + assert mpf(finf) == mpf('inf') + assert mpf(fninf) == mpf('-inf') + assert mpf(fnan)._mpf_ == mpf('nan')._mpf_ diff --git a/shared/package-files/76/76c1eac1684e3a6250541eff1def8c157aa083725efcd1e4d7ea04c1c6889909/blob b/shared/package-files/76/76c1eac1684e3a6250541eff1def8c157aa083725efcd1e4d7ea04c1c6889909/blob new file mode 100644 index 0000000000000000000000000000000000000000..3c06cb2ca0849804337b848ed07ce882341dba3b --- /dev/null +++ b/shared/package-files/76/76c1eac1684e3a6250541eff1def8c157aa083725efcd1e4d7ea04c1c6889909/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor +inline at::Tensor affine_grid_generator(const at::Tensor & theta, at::IntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator::call(theta, c10::fromIntArrayRefSlow(size), align_corners); +} +namespace symint { + template ::value>> + at::Tensor affine_grid_generator(const at::Tensor & theta, at::IntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator::call(theta, c10::fromIntArrayRefSlow(size), align_corners); + } +} + +// aten::affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor +inline at::Tensor affine_grid_generator_symint(const at::Tensor & theta, c10::SymIntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator::call(theta, size, align_corners); +} +namespace symint { + template ::value>> + at::Tensor affine_grid_generator(const at::Tensor & theta, c10::SymIntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator::call(theta, size, align_corners); + } +} + +// aten::affine_grid_generator.out(Tensor theta, SymInt[] size, bool align_corners, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & affine_grid_generator_out(at::Tensor & out, const at::Tensor & theta, at::IntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator_out::call(theta, c10::fromIntArrayRefSlow(size), align_corners, out); +} +namespace symint { + template ::value>> + at::Tensor & affine_grid_generator_out(at::Tensor & out, const at::Tensor & theta, at::IntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator_out::call(theta, c10::fromIntArrayRefSlow(size), align_corners, out); + } +} + +// aten::affine_grid_generator.out(Tensor theta, SymInt[] size, bool align_corners, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & affine_grid_generator_outf(const at::Tensor & theta, at::IntArrayRef size, bool align_corners, at::Tensor & out) { + return at::_ops::affine_grid_generator_out::call(theta, c10::fromIntArrayRefSlow(size), align_corners, out); +} +namespace symint { + template ::value>> + at::Tensor & affine_grid_generator_outf(const at::Tensor & theta, at::IntArrayRef size, bool align_corners, at::Tensor & out) { + return at::_ops::affine_grid_generator_out::call(theta, c10::fromIntArrayRefSlow(size), align_corners, out); + } +} + +// aten::affine_grid_generator.out(Tensor theta, SymInt[] size, bool align_corners, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & affine_grid_generator_symint_out(at::Tensor & out, const at::Tensor & theta, c10::SymIntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator_out::call(theta, size, align_corners, out); +} +namespace symint { + template ::value>> + at::Tensor & affine_grid_generator_out(at::Tensor & out, const at::Tensor & theta, c10::SymIntArrayRef size, bool align_corners) { + return at::_ops::affine_grid_generator_out::call(theta, size, align_corners, out); + } +} + +// aten::affine_grid_generator.out(Tensor theta, SymInt[] size, bool align_corners, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & affine_grid_generator_symint_outf(const at::Tensor & theta, c10::SymIntArrayRef size, bool align_corners, at::Tensor & out) { + return at::_ops::affine_grid_generator_out::call(theta, size, align_corners, out); +} +namespace symint { + template ::value>> + at::Tensor & affine_grid_generator_outf(const at::Tensor & theta, c10::SymIntArrayRef size, bool align_corners, at::Tensor & out) { + return at::_ops::affine_grid_generator_out::call(theta, size, align_corners, out); + } +} + +} diff --git a/shared/package-files/76/76c8ed5d0a015dc14369c29ce790db6524f52faf5718a3744ccb420671cde616/blob b/shared/package-files/76/76c8ed5d0a015dc14369c29ce790db6524f52faf5718a3744ccb420671cde616/blob new file mode 100644 index 0000000000000000000000000000000000000000..addd6ce022e0931c57a51874af4fd6c0a3ba7b3c --- /dev/null +++ b/shared/package-files/76/76c8ed5d0a015dc14369c29ce790db6524f52faf5718a3744ccb420671cde616/blob @@ -0,0 +1,108 @@ +from sympy.core.symbol import Symbol, symbols +from sympy.physics.continuum_mechanics.truss import Truss +from sympy import sqrt + + +def test_truss(): + A = Symbol('A') + B = Symbol('B') + C = Symbol('C') + AB, BC, AC = symbols('AB, BC, AC') + P = Symbol('P') + + t = Truss() + assert t.nodes == [] + assert t.node_labels == [] + assert t.node_positions == [] + assert t.members == {} + assert t.loads == {} + assert t.supports == {} + assert t.reaction_loads == {} + assert t.internal_forces == {} + + # testing the add_node method + t.add_node(A, 0, 0) + t.add_node(B, 2, 2) + t.add_node(C, 3, 0) + assert t.nodes == [(A, 0, 0), (B, 2, 2), (C, 3, 0)] + assert t.node_labels == [A, B, C] + assert t.node_positions == [(0, 0), (2, 2), (3, 0)] + assert t.loads == {} + assert t.supports == {} + assert t.reaction_loads == {} + + # testing the remove_node method + t.remove_node(C) + assert t.nodes == [(A, 0, 0), (B, 2, 2)] + assert t.node_labels == [A, B] + assert t.node_positions == [(0, 0), (2, 2)] + assert t.loads == {} + assert t.supports == {} + + t.add_node(C, 3, 0) + + # testing the add_member method + t.add_member(AB, A, B) + t.add_member(BC, B, C) + t.add_member(AC, A, C) + assert t.members == {AB: [A, B], BC: [B, C], AC: [A, C]} + assert t.internal_forces == {AB: 0, BC: 0, AC: 0} + + # testing the remove_member method + t.remove_member(BC) + assert t.members == {AB: [A, B], AC: [A, C]} + assert t.internal_forces == {AB: 0, AC: 0} + + t.add_member(BC, B, C) + + D, CD = symbols('D, CD') + + # testing the change_label methods + t.change_node_label(B, D) + assert t.nodes == [(A, 0, 0), (D, 2, 2), (C, 3, 0)] + assert t.node_labels == [A, D, C] + assert t.loads == {} + assert t.supports == {} + assert t.members == {AB: [A, D], BC: [D, C], AC: [A, C]} + + t.change_member_label(BC, CD) + assert t.members == {AB: [A, D], CD: [D, C], AC: [A, C]} + assert t.internal_forces == {AB: 0, CD: 0, AC: 0} + + + # testing the apply_load method + t.apply_load(A, P, 90) + t.apply_load(A, P/4, 90) + t.apply_load(A, 2*P,45) + t.apply_load(D, P/2, 90) + assert t.loads == {A: [[P, 90], [P/4, 90], [2*P, 45]], D: [[P/2, 90]]} + assert t.loads[A] == [[P, 90], [P/4, 90], [2*P, 45]] + + # testing the remove_load method + t.remove_load(A, P/4, 90) + assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90]]} + assert t.loads[A] == [[P, 90], [2*P, 45]] + + # testing the apply_support method + t.apply_support(A, "pinned") + t.apply_support(D, "roller") + assert t.supports == {A: 'pinned', D: 'roller'} + assert t.reaction_loads == {} + assert t.loads == {A: [[P, 90], [2*P, 45], [Symbol('R_A_x'), 0], [Symbol('R_A_y'), 90]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]} + + # testing the remove_support method + t.remove_support(A) + assert t.supports == {D: 'roller'} + assert t.reaction_loads == {} + assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]} + + t.apply_support(A, "pinned") + + # testing the solve method + t.solve() + assert t.reaction_loads['R_A_x'] == -sqrt(2)*P + assert t.reaction_loads['R_A_y'] == -sqrt(2)*P - P + assert t.reaction_loads['R_D_y'] == -P/2 + assert t.internal_forces[AB]/P == 0 + assert t.internal_forces[CD] == 0 + assert t.internal_forces[AC] == 0 diff --git a/shared/package-files/76/76c96373dfb4f4f3cad97a473f1738a9aee54b71e425f54caf97d1388db50e12/blob b/shared/package-files/76/76c96373dfb4f4f3cad97a473f1738a9aee54b71e425f54caf97d1388db50e12/blob new file mode 100644 index 0000000000000000000000000000000000000000..1676684bfcec6af767097830496c707e060d4015 --- /dev/null +++ b/shared/package-files/76/76c96373dfb4f4f3cad97a473f1738a9aee54b71e425f54caf97d1388db50e12/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & mkldnn_reorder_conv3d_weight_out_symint(const at::Tensor & self, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out); +TORCH_API at::Tensor mkldnn_reorder_conv3d_weight(const at::Tensor & self, at::IntArrayRef padding=0, at::IntArrayRef stride=1, at::IntArrayRef dilation=1, int64_t groups=1); +} // namespace native +} // namespace at diff --git a/shared/package-files/76/76ca9e7b0caac9d530604f6c36c708daabd813587986e5de650f628318d00fc2/blob b/shared/package-files/76/76ca9e7b0caac9d530604f6c36c708daabd813587986e5de650f628318d00fc2/blob new file mode 100644 index 0000000000000000000000000000000000000000..f1ade5261afa71b93550aea025431ad21d0e4de3 --- /dev/null +++ b/shared/package-files/76/76ca9e7b0caac9d530604f6c36c708daabd813587986e5de650f628318d00fc2/blob @@ -0,0 +1,18 @@ +from typing import Any, Optional + +class DescriptorPool: + def __new__(cls, descriptor_db: Optional[Any] = ...): ... + def __init__(self, descriptor_db: Optional[Any] = ...) -> None: ... + def Add(self, file_desc_proto): ... + def AddSerializedFile(self, serialized_file_desc_proto): ... + def AddDescriptor(self, desc): ... + def AddEnumDescriptor(self, enum_desc): ... + def AddFileDescriptor(self, file_desc): ... + def FindFileByName(self, file_name): ... + def FindFileContainingSymbol(self, symbol): ... + def FindMessageTypeByName(self, full_name): ... + def FindEnumTypeByName(self, full_name): ... + def FindFieldByName(self, full_name): ... + def FindExtensionByName(self, full_name): ... + +def Default(): ... diff --git a/shared/package-files/76/76cf4818157b882c4cf84258aaebdeb63d15498d503da1ec8541beaba06d3c22/blob b/shared/package-files/76/76cf4818157b882c4cf84258aaebdeb63d15498d503da1ec8541beaba06d3c22/blob new file mode 100644 index 0000000000000000000000000000000000000000..6b6a6c20063cf034685f0f5cff51febb0de50aa4 --- /dev/null +++ b/shared/package-files/76/76cf4818157b882c4cf84258aaebdeb63d15498d503da1ec8541beaba06d3c22/blob @@ -0,0 +1,101 @@ +""" +assert functions from numpy and pandas testing + +""" +from statsmodels.compat.pandas import testing as pdt + +import numpy.testing as npt +import pandas as pd + +from statsmodels.tools.tools import Bunch + +# Standard list for parsing tables +PARAM_LIST = ["params", "bse", "tvalues", "pvalues"] + + +def bunch_factory(attribute, columns): + """ + Generates a special purpose Bunch class + + Parameters + ---------- + attribute : str + Attribute to access when splitting + columns : list of str + List of names to use when splitting the columns of attribute + + Notes + ----- + After the class is initialized as a Bunch, the columns of attribute + are split so that Bunch has the keys in columns and + bunch[column[i]] = bunch[attribute][:, i] + + """ + class FactoryBunch(Bunch): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not hasattr(self, attribute): + raise AttributeError(f"{attribute} is required and must be passed to " + "the constructor") + for i, att in enumerate(columns): + self[att] = getattr(self, attribute)[:, i] + + return FactoryBunch + + +ParamsTableTestBunch = bunch_factory("params_table", PARAM_LIST) + +MarginTableTestBunch = bunch_factory("margins_table", PARAM_LIST) + + +class Holder: + """Test-focused class to simplify accessing values by attribute""" + + def __init__(self, **kwds): + self.__dict__.update(kwds) + + def __str__(self): + ss = "\n".join(str(k) + " = " + str(v).replace("\n", "\n ") + for k, v in vars(self).items()) + return ss + + def __repr__(self): + # use repr for values including nested cases as in tost + ss = "\n".join(str(k) + " = " + repr(v).replace("\n", "\n ") + for k, v in vars(self).items()) + ss = str(self.__class__) + "\n" + ss + return ss + + +# adjusted functions + +def assert_equal(actual, desired, err_msg="", verbose=True, **kwds): + """ + Dispatch to the appropriate pandas or numpy testing assert function + + Parameters + ---------- + actual : array_like + The value to test. + desired : array_like + The expected value. If a pandas Index, Series, or DataFrame, the + matching pandas assert function is used. + err_msg : str, optional + The error message to use on failure when neither `desired` is a + pandas Index, Series, or DataFrame. + verbose : bool, optional + Whether to include the actual and desired values in the error + message when neither `desired` is a pandas Index, Series, or + DataFrame. + **kwds + Additional keyword arguments passed to the pandas assert function + when `desired` is a pandas Index, Series, or DataFrame. + """ + if isinstance(desired, pd.Index): + pdt.assert_index_equal(actual, desired, **kwds) + elif isinstance(desired, pd.Series): + pdt.assert_series_equal(actual, desired, **kwds) + elif isinstance(desired, pd.DataFrame): + pdt.assert_frame_equal(actual, desired, **kwds) + else: + npt.assert_equal(actual, desired, err_msg=err_msg, verbose=verbose) diff --git a/shared/package-files/76/76d0a427b74fe82bdabfca723b718921a5eaf4e20fb927726918160a629e15a8/blob b/shared/package-files/76/76d0a427b74fe82bdabfca723b718921a5eaf4e20fb927726918160a629e15a8/blob new file mode 100644 index 0000000000000000000000000000000000000000..a5331f109b8ce9606bb9b99f59819e5dcb7f3402 --- /dev/null +++ b/shared/package-files/76/76d0a427b74fe82bdabfca723b718921a5eaf4e20fb927726918160a629e15a8/blob @@ -0,0 +1,124 @@ +from fontTools.varLib.models import normalizeValue + + +def _denormalize(v, triplet): + if v >= 0: + return triplet[1] + v * (triplet[2] - triplet[1]) + else: + return triplet[1] + v * (triplet[1] - triplet[0]) + + +def map( + font, location, *, inputNormalized=False, outputNormalized=False, dropZeroes=False +): + if "fvar" not in font: + return None + + fvar = font["fvar"] + axes = {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes} + unknownAxes = sorted(tag for tag in location if tag not in axes) + if unknownAxes: + raise ValueError(f"Unknown axis tag(s): {', '.join(unknownAxes)}") + + if not inputNormalized: + location = { + tag: normalizeValue(value, axes[tag]) for tag, value in location.items() + } + + if "avar" in font: + location = font["avar"].renormalizeLocation(location, font, dropZeroes) + + if not outputNormalized: + location = { + tag: _denormalize(value, axes[tag]) for tag, value in location.items() + } + + return location + + +def main(args=None): + """Map variation coordinates through the `avar` table.""" + + from fontTools.ttLib import TTFont + import argparse + + if args is None: + import sys + + args = sys.argv[1:] + + parser = argparse.ArgumentParser( + "fonttools varLib.avar.map", + description="Map variation coordinates through the `avar` table.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "coords", + metavar="[AXIS=value...]", + help="Coordinates to map, e.g. 'wght=700 wdth=75'.", + nargs="*", + default=None, + ) + parser.add_argument( + "-f", action="store_true", help="Do not omit axes at default location." + ) + parser.add_argument( + "-i", action="store_true", help="Input coordinates are normalized (-1..1)." + ) + parser.add_argument( + "-o", action="store_true", help="Output coordinates as normalized (-1..1)." + ) + + options = parser.parse_args(args) + + if not options.coords: + parser.error( + "No coordinates provided. Please specify at least one axis coordinate (e.g., wght=500)" + ) + + if options.font.endswith(".designspace"): + from .build import build + + font = TTFont() + build(font, options.font) + else: + font = TTFont(options.font) + if "fvar" not in font: + parser.error(f"Font '{options.font}' does not contain an 'fvar' table.") + + location = {} + for item in options.coords: + tag, sep, value = item.partition("=") + if not sep or not tag or not value: + parser.error( + f"Invalid coordinate {item!r}. Expected AXIS=value, e.g. wght=500" + ) + try: + location[tag] = float(value) + except ValueError: + parser.error( + f"Invalid coordinate value in {item!r}. Expected a number after '='" + ) + + try: + mapped = map( + font, + location, + inputNormalized=options.i, + outputNormalized=options.o, + dropZeroes=not options.f, + ) + except ValueError as e: + parser.error(str(e)) + assert mapped is not None + + for tag in mapped: + v = mapped[tag] + v = int(v) if v == int(v) else v + print(f"{tag}={v:g}") + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/shared/package-files/76/76d1e06e5c7d2617f2acac75f89ec9971c3f7fbb3c65b3c54228b65163136696/blob b/shared/package-files/76/76d1e06e5c7d2617f2acac75f89ec9971c3f7fbb3c65b3c54228b65163136696/blob new file mode 100644 index 0000000000000000000000000000000000000000..2171abd6969f6823454d704c5eea3e278bbe8005 --- /dev/null +++ b/shared/package-files/76/76d1e06e5c7d2617f2acac75f89ec9971c3f7fbb3c65b3c54228b65163136696/blob @@ -0,0 +1,130 @@ +"""distutils.pypirc + +Provides the PyPIRCCommand class, the base class for the command classes +that uses .pypirc in the distutils.command package. +""" +import os +from configparser import RawConfigParser + +from distutils.cmd import Command + +DEFAULT_PYPIRC = """\ +[distutils] +index-servers = + pypi + +[pypi] +username:%s +password:%s +""" + +class PyPIRCCommand(Command): + """Base command that knows how to handle the .pypirc file + """ + DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/' + DEFAULT_REALM = 'pypi' + repository = None + realm = None + + user_options = [ + ('repository=', 'r', + "url of repository [default: %s]" % \ + DEFAULT_REPOSITORY), + ('show-response', None, + 'display full response text from server')] + + boolean_options = ['show-response'] + + def _get_rc_file(self): + """Returns rc file path.""" + return os.path.join(os.path.expanduser('~'), '.pypirc') + + def _store_pypirc(self, username, password): + """Creates a default .pypirc file.""" + rc = self._get_rc_file() + with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f: + f.write(DEFAULT_PYPIRC % (username, password)) + + def _read_pypirc(self): + """Reads the .pypirc file.""" + rc = self._get_rc_file() + if os.path.exists(rc): + self.announce('Using PyPI login from %s' % rc) + repository = self.repository or self.DEFAULT_REPOSITORY + + config = RawConfigParser() + config.read(rc) + sections = config.sections() + if 'distutils' in sections: + # let's get the list of servers + index_servers = config.get('distutils', 'index-servers') + _servers = [server.strip() for server in + index_servers.split('\n') + if server.strip() != ''] + if _servers == []: + # nothing set, let's try to get the default pypi + if 'pypi' in sections: + _servers = ['pypi'] + else: + # the file is not properly defined, returning + # an empty dict + return {} + for server in _servers: + current = {'server': server} + current['username'] = config.get(server, 'username') + + # optional params + for key, default in (('repository', + self.DEFAULT_REPOSITORY), + ('realm', self.DEFAULT_REALM), + ('password', None)): + if config.has_option(server, key): + current[key] = config.get(server, key) + else: + current[key] = default + + # work around people having "repository" for the "pypi" + # section of their config set to the HTTP (rather than + # HTTPS) URL + if (server == 'pypi' and + repository in (self.DEFAULT_REPOSITORY, 'pypi')): + current['repository'] = self.DEFAULT_REPOSITORY + return current + + if (current['server'] == repository or + current['repository'] == repository): + return current + elif 'server-login' in sections: + # old format + server = 'server-login' + if config.has_option(server, 'repository'): + repository = config.get(server, 'repository') + else: + repository = self.DEFAULT_REPOSITORY + return {'username': config.get(server, 'username'), + 'password': config.get(server, 'password'), + 'repository': repository, + 'server': server, + 'realm': self.DEFAULT_REALM} + + return {} + + def _read_pypi_response(self, response): + """Read and decode a PyPI HTTP response.""" + import cgi + content_type = response.getheader('content-type', 'text/plain') + encoding = cgi.parse_header(content_type)[1].get('charset', 'ascii') + return response.read().decode(encoding) + + def initialize_options(self): + """Initialize options.""" + self.repository = None + self.realm = None + self.show_response = 0 + + def finalize_options(self): + """Finalizes options.""" + if self.repository is None: + self.repository = self.DEFAULT_REPOSITORY + if self.realm is None: + self.realm = self.DEFAULT_REALM diff --git a/shared/package-files/76/76d20048d84b2952d00c8f979e6d6b0c1baa81829fb0988c717143aa2f8b191e/blob b/shared/package-files/76/76d20048d84b2952d00c8f979e6d6b0c1baa81829fb0988c717143aa2f8b191e/blob new file mode 100644 index 0000000000000000000000000000000000000000..8da31886ae5e94c8da571bf2de4a096dab400078 --- /dev/null +++ b/shared/package-files/76/76d20048d84b2952d00c8f979e6d6b0c1baa81829fb0988c717143aa2f8b191e/blob @@ -0,0 +1,160 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API set__source_Storage { + using schema = at::Tensor & (at::Tensor &, at::Storage); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Storage") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set_.source_Storage(Tensor(a!) self, Storage source) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, at::Storage source); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, at::Storage source); +}; + +struct TORCH_API set__source_Storage_storage_offset { + using schema = at::Tensor & (at::Tensor &, at::Storage, c10::SymInt, c10::SymIntArrayRef, c10::SymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Storage_storage_offset") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); +}; + +struct TORCH_API set__source_Tensor_storage_offset { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, c10::SymInt, c10::SymIntArrayRef, c10::SymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Tensor_storage_offset") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); +}; + +struct TORCH_API set__source_Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & source); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & source); +}; + +struct TORCH_API set_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API set_source_Storage_out { + using schema = at::Tensor & (const at::Tensor &, at::Storage, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Storage_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.source_Storage_out(Tensor self, Storage source, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Storage source, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Storage source, at::Tensor & out); +}; + +struct TORCH_API set_source_Storage { + using schema = at::Tensor (const at::Tensor &, at::Storage); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Storage") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.source_Storage(Tensor self, Storage source) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::Storage source); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Storage source); +}; + +struct TORCH_API set_source_Storage_storage_offset_out { + using schema = at::Tensor & (const at::Tensor &, at::Storage, c10::SymInt, c10::SymIntArrayRef, c10::SymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Storage_storage_offset_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.source_Storage_storage_offset_out(Tensor self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[], *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::Tensor & out); +}; + +struct TORCH_API set_source_Storage_storage_offset { + using schema = at::Tensor (const at::Tensor &, at::Storage, c10::SymInt, c10::SymIntArrayRef, c10::SymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Storage_storage_offset") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.source_Storage_storage_offset(Tensor self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride); +}; + +struct TORCH_API set_source_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.source_Tensor_out(Tensor self, Tensor source, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & source, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & source, at::Tensor & out); +}; + +struct TORCH_API set_source_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "source_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.source_Tensor(Tensor self, Tensor source) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & source); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & source); +}; + +struct TORCH_API set_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +struct TORCH_API set { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::set") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "set(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/76/76d2ad46c254995c2226ed3267e221d26f0fbd6fccc66a2e1bb99284472c4ad7/blob b/shared/package-files/76/76d2ad46c254995c2226ed3267e221d26f0fbd6fccc66a2e1bb99284472c4ad7/blob new file mode 100644 index 0000000000000000000000000000000000000000..aea0e56c25d0d74e04788493058549a1399f8342 --- /dev/null +++ b/shared/package-files/76/76d2ad46c254995c2226ed3267e221d26f0fbd6fccc66a2e1bb99284472c4ad7/blob @@ -0,0 +1,80 @@ +import warnings + + +def _viztracer_init(init_kwargs): + """Initialize viztracer's profiler in worker processes""" + from viztracer import VizTracer + + tracer = VizTracer(**init_kwargs) + tracer.register_exit() + tracer.start() + + +def _make_viztracer_initializer_and_initargs(): + try: + import viztracer + + tracer = viztracer.get_tracer() + if tracer is not None and getattr(tracer, "enable", False): + # Profiler is active: introspect its configuration to + # initialize the workers with the same configuration. + return _viztracer_init, (tracer.init_kwargs,) + except ImportError: + # viztracer is not installed: nothing to do + pass + except Exception as e: + # In case viztracer's API evolve, we do not want to crash loky but + # we want to know about it to be able to update loky. + warnings.warn(f"Unable to introspect viztracer state: {e}") + return None, () + + +class _ChainedInitializer: + """Compound worker initializer + + This is meant to be used in conjunction with _chain_initializers to + produce the necessary chained_args list to be passed to __call__. + """ + + def __init__(self, initializers): + self._initializers = initializers + + def __call__(self, *chained_args): + for initializer, args in zip(self._initializers, chained_args): + initializer(*args) + + +def _chain_initializers(initializer_and_args): + """Convenience helper to combine a sequence of initializers. + + If some initializers are None, they are filtered out. + """ + filtered_initializers = [] + filtered_initargs = [] + for initializer, initargs in initializer_and_args: + if initializer is not None: + filtered_initializers.append(initializer) + filtered_initargs.append(initargs) + + if not filtered_initializers: + return None, () + elif len(filtered_initializers) == 1: + return filtered_initializers[0], filtered_initargs[0] + else: + return _ChainedInitializer(filtered_initializers), filtered_initargs + + +def _prepare_initializer(initializer, initargs): + if initializer is not None and not callable(initializer): + raise TypeError( + f"initializer must be a callable, got: {initializer!r}" + ) + + # Introspect runtime to determine if we need to propagate the viztracer + # profiler information to the workers: + return _chain_initializers( + [ + (initializer, initargs), + _make_viztracer_initializer_and_initargs(), + ] + ) diff --git a/shared/package-files/76/76d43a3cf3f2a501bfca5afdefaa1dfafac8d1fb54ec22da723dd9057c0b948a/blob b/shared/package-files/76/76d43a3cf3f2a501bfca5afdefaa1dfafac8d1fb54ec22da723dd9057c0b948a/blob new file mode 100644 index 0000000000000000000000000000000000000000..066c2b6581540652693120fb9d8bb0729f1dddc4 --- /dev/null +++ b/shared/package-files/76/76d43a3cf3f2a501bfca5afdefaa1dfafac8d1fb54ec22da723dd9057c0b948a/blob @@ -0,0 +1,200 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +import sys +import threading +from inspect import signature +from typing import TYPE_CHECKING, Callable, Dict + +import attr + +from hypothesis.internal.cache import LRUReusedCache +from hypothesis.internal.compat import dataclass_asdict +from hypothesis.internal.conjecture.junkdrawer import clamp +from hypothesis.internal.floats import float_to_int +from hypothesis.internal.reflection import proxies +from hypothesis.vendor.pretty import pretty + +if TYPE_CHECKING: + from hypothesis.strategies._internal.strategies import SearchStrategy, T + +_strategies: Dict[str, Callable[..., "SearchStrategy"]] = {} + + +class FloatKey: + def __init__(self, f): + self.value = float_to_int(f) + + def __eq__(self, other): + return isinstance(other, FloatKey) and (other.value == self.value) + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.value) + + +def convert_value(v): + if isinstance(v, float): + return FloatKey(v) + return (type(v), v) + + +_CACHE = threading.local() + + +def get_cache() -> LRUReusedCache: + try: + return _CACHE.STRATEGY_CACHE + except AttributeError: + _CACHE.STRATEGY_CACHE = LRUReusedCache(1024) + return _CACHE.STRATEGY_CACHE + + +def clear_cache() -> None: + cache = get_cache() + cache.clear() + + +def cacheable(fn: "T") -> "T": + from hypothesis.strategies._internal.strategies import SearchStrategy + + @proxies(fn) + def cached_strategy(*args, **kwargs): + try: + kwargs_cache_key = {(k, convert_value(v)) for k, v in kwargs.items()} + except TypeError: + return fn(*args, **kwargs) + cache_key = (fn, tuple(map(convert_value, args)), frozenset(kwargs_cache_key)) + cache = get_cache() + try: + if cache_key in cache: + return cache[cache_key] + except TypeError: + return fn(*args, **kwargs) + else: + result = fn(*args, **kwargs) + if not isinstance(result, SearchStrategy) or result.is_cacheable: + cache[cache_key] = result + return result + + cached_strategy.__clear_cache = clear_cache # type: ignore + return cached_strategy + + +def defines_strategy( + *, + force_reusable_values: bool = False, + try_non_lazy: bool = False, + never_lazy: bool = False, +) -> Callable[["T"], "T"]: + """Returns a decorator for strategy functions. + + If ``force_reusable_values`` is True, the returned strategy will be marked + with ``.has_reusable_values == True`` even if it uses maps/filters or + non-reusable strategies internally. This tells our numpy/pandas strategies + that they can implicitly use such strategies as background values. + + If ``try_non_lazy`` is True, attempt to execute the strategy definition + function immediately, so that a LazyStrategy is only returned if this + raises an exception. + + If ``never_lazy`` is True, the decorator performs no lazy-wrapping at all, + and instead returns the original function. + """ + + def decorator(strategy_definition): + """A decorator that registers the function as a strategy and makes it + lazily evaluated.""" + _strategies[strategy_definition.__name__] = signature(strategy_definition) + + if never_lazy: + assert not try_non_lazy + # We could potentially support never_lazy + force_reusable_values + # with a suitable wrapper, but currently there are no callers that + # request this combination. + assert not force_reusable_values + return strategy_definition + + from hypothesis.strategies._internal.lazy import LazyStrategy + + @proxies(strategy_definition) + def accept(*args, **kwargs): + if try_non_lazy: + # Why not try this unconditionally? Because we'd end up with very + # deep nesting of recursive strategies - better to be lazy unless we + # *know* that eager evaluation is the right choice. + try: + return strategy_definition(*args, **kwargs) + except Exception: + # If invoking the strategy definition raises an exception, + # wrap that up in a LazyStrategy so it happens again later. + pass + result = LazyStrategy(strategy_definition, args, kwargs) + if force_reusable_values: + # Setting `force_has_reusable_values` here causes the recursive + # property code to set `.has_reusable_values == True`. + result.force_has_reusable_values = True + assert result.has_reusable_values + return result + + accept.is_hypothesis_strategy_function = True + return accept + + return decorator + + +def to_jsonable(obj: object) -> object: + """Recursively convert an object to json-encodable form. + + This is not intended to round-trip, but rather provide an analysis-ready + format for observability. To avoid side affects, we pretty-print all but + known types. + """ + if isinstance(obj, (str, int, float, bool, type(None))): + if isinstance(obj, int) and abs(obj) >= 2**63: + # Silently clamp very large ints to max_float, to avoid + # OverflowError when casting to float. + obj = clamp(-sys.float_info.max, obj, sys.float_info.max) + return float(obj) + return obj + if isinstance(obj, (list, tuple, set, frozenset)): + if isinstance(obj, tuple) and hasattr(obj, "_asdict"): + return to_jsonable(obj._asdict()) # treat namedtuples as dicts + return [to_jsonable(x) for x in obj] + if isinstance(obj, dict): + return { + k if isinstance(k, str) else pretty(k): to_jsonable(v) + for k, v in obj.items() + } + + # Hey, might as well try calling a .to_json() method - it works for Pandas! + # We try this before the below general-purpose handlers to give folks a + # chance to control this behavior on their custom classes. + try: + return to_jsonable(obj.to_json()) # type: ignore + except Exception: + pass + + # Special handling for dataclasses, attrs, and pydantic classes + if ( + (dcs := sys.modules.get("dataclasses")) + and dcs.is_dataclass(obj) + and not isinstance(obj, type) + ): + return to_jsonable(dataclass_asdict(obj)) + if attr.has(type(obj)): + return to_jsonable(attr.asdict(obj, recurse=False)) # type: ignore + if (pyd := sys.modules.get("pydantic")) and isinstance(obj, pyd.BaseModel): + return to_jsonable(obj.model_dump()) + + # If all else fails, we'll just pretty-print as a string. + return pretty(obj) diff --git a/shared/package-files/76/76d521ae26b8db3b51f76b3a21dbf8683ef145c719fbb551097eddc9d06fff7e/blob b/shared/package-files/76/76d521ae26b8db3b51f76b3a21dbf8683ef145c719fbb551097eddc9d06fff7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..d98e603b1dd175d5e6129a57c7a5d761abea0fb1 --- /dev/null +++ b/shared/package-files/76/76d521ae26b8db3b51f76b3a21dbf8683ef145c719fbb551097eddc9d06fff7e/blob @@ -0,0 +1,1968 @@ +import collections +import functools +import math +import multiprocessing +import os +import random +import subprocess +import sys +import threading +import itertools +from textwrap import dedent + +import numpy as np + +import unittest + +import numba +from numba import jit, _helperlib, njit +from numba.core import types +from numba.tests.support import TestCase, compile_function, tag +from numba.core.errors import TypingError + + +# State size of the Mersenne Twister +N = 624 + + +def get_py_state_ptr(): + return _helperlib.rnd_get_py_state_ptr() + +def get_np_state_ptr(): + return _helperlib.rnd_get_np_state_ptr() + + +def numpy_randint1(a): + return np.random.randint(a) + +def numpy_randint2(a, b): + return np.random.randint(a, b) + +def random_randint(a, b): + return random.randint(a, b) + +def random_randrange1(a): + return random.randrange(a) + +def random_randrange2(a, b): + return random.randrange(a, b) + +def random_randrange3(a, b, c): + return random.randrange(a, b, c) + +def numpy_choice1(a): + return np.random.choice(a) + +def numpy_choice2(a, size): + return np.random.choice(a, size=size) + +def numpy_choice3(a, size, replace): + return np.random.choice(a, size=size, replace=replace) + +def numpy_multinomial2(n, pvals): + return np.random.multinomial(n, pvals) + +def numpy_multinomial3(n, pvals, size): + return np.random.multinomial(n, pvals=pvals, size=size) + +def numpy_dirichlet(alpha, size): + return np.random.dirichlet(alpha, size=size) + +def numpy_dirichlet_default(alpha): + return np.random.dirichlet(alpha) + +def numpy_noncentral_chisquare(df, nonc, size): + return np.random.noncentral_chisquare(df, nonc, size=size) + +def numpy_noncentral_chisquare_default(df, nonc): + return np.random.noncentral_chisquare(df, nonc) + +def numpy_check_rand(seed, a, b): + np.random.seed(seed) + expected = np.random.random((a, b)) + np.random.seed(seed) + got = np.random.rand(a, b) + return expected, got + +def numpy_check_randn(seed, a, b): + np.random.seed(seed) + expected = np.random.standard_normal((a, b)) + np.random.seed(seed) + got = np.random.randn(a, b) + return expected, got + +def jit_with_args(name, argstring): + code = """def func(%(argstring)s): + return %(name)s(%(argstring)s) +""" % locals() + pyfunc = compile_function("func", code, globals()) + return jit(nopython=True)(pyfunc) + +def jit_with_kwargs(name, kwarg_list): + # Similar to jit_with_args, but uses keyword arguments + call_args_with_kwargs = ','.join([f'{kw}={kw}' for kw in kwarg_list]) + signature = ','.join(kwarg_list) + code = f"""def func({signature}): + return {name}({call_args_with_kwargs}) +""" + pyfunc = compile_function("func", code, globals()) + return jit(nopython=True)(pyfunc) + +def jit_nullary(name): + return jit_with_args(name, "") + +def jit_unary(name): + return jit_with_args(name, "a") + +def jit_binary(name): + return jit_with_args(name, "a, b") + +def jit_ternary(name): + return jit_with_args(name, "a, b, c") + + +random_gauss = jit_binary("random.gauss") +random_random = jit_nullary("random.random") +random_seed = jit_unary("random.seed") + +numpy_normal = jit_binary("np.random.normal") +numpy_random = jit_nullary("np.random.random") +numpy_seed = jit_unary("np.random.seed") + + +def _copy_py_state(r, ptr): + """ + Copy state of Python random *r* to Numba state *ptr*. + """ + mt = r.getstate()[1] + ints, index = mt[:-1], mt[-1] + _helperlib.rnd_set_state(ptr, (index, list(ints))) + return ints, index + +def _copy_np_state(r, ptr): + """ + Copy state of Numpy random *r* to Numba state *ptr*. + """ + ints, index = r.get_state()[1:3] + _helperlib.rnd_set_state(ptr, (index, [int(x) for x in ints])) + return ints, index + +def sync_to_numpy(r): + _ver, mt_st, _gauss_next = r.getstate() + mt_pos = mt_st[-1] + mt_ints = mt_st[:-1] + assert len(mt_ints) == 624 + + np_st = ('MT19937', np.array(mt_ints, dtype='uint32'), mt_pos) + if _gauss_next is None: + np_st += (0, 0.0) + else: + np_st += (1, _gauss_next) + + np.random.set_state(np_st) + +# Pure Python equivalents of some of the Numpy distributions, using +# Python's basic generators. + +def py_chisquare(r, df): + return 2.0 * r.gammavariate(df / 2.0, 1.0) + +def py_f(r, num, denom): + return ((py_chisquare(r, num) * denom) / + (py_chisquare(r, denom) * num)) + + +class BaseTest(TestCase): + + def _follow_cpython(self, ptr, seed=2): + r = random.Random(seed) + _copy_py_state(r, ptr) + return r + + def _follow_numpy(self, ptr, seed=2): + r = np.random.RandomState(seed) + _copy_np_state(r, ptr) + return r + + +class TestInternals(BaseTest): + """ + Test low-level internals of the implementation. + """ + + def _check_get_set_state(self, ptr): + state = _helperlib.rnd_get_state(ptr) + i, ints = state + self.assertIsInstance(i, int) + self.assertIsInstance(ints, list) + self.assertEqual(len(ints), N) + j = (i * 100007) % N + ints = [i * 3 for i in range(N)] + # Roundtrip + _helperlib.rnd_set_state(ptr, (j, ints)) + self.assertEqual(_helperlib.rnd_get_state(ptr), (j, ints)) + + def _check_shuffle(self, ptr): + # We test shuffling against CPython + r = random.Random() + ints, index = _copy_py_state(r, ptr) + # Force shuffling in CPython generator + for i in range(index, N + 1, 2): + r.random() + _helperlib.rnd_shuffle(ptr) + # Check new integer keys + mt = r.getstate()[1] + ints, index = mt[:-1], mt[-1] + self.assertEqual(_helperlib.rnd_get_state(ptr)[1], list(ints)) + + def _check_init(self, ptr): + # We use the same integer seeding as Numpy + # (CPython is different: it treats the integer as a byte array) + r = np.random.RandomState() + for i in [0, 1, 125, 2**32 - 5]: + # Need to cast to a C-sized int (for Numpy <= 1.7) + r.seed(np.uint32(i)) + st = r.get_state() + ints = list(st[1]) + index = st[2] + assert index == N # sanity check + _helperlib.rnd_seed(ptr, i) + self.assertEqual(_helperlib.rnd_get_state(ptr), (index, ints)) + + def _check_perturb(self, ptr): + states = [] + for i in range(10): + # Initialize with known state + _helperlib.rnd_seed(ptr, 0) + # Perturb with entropy + _helperlib.rnd_seed(ptr, os.urandom(512)) + states.append(tuple(_helperlib.rnd_get_state(ptr)[1])) + # No two identical states + self.assertEqual(len(set(states)), len(states)) + + def test_get_set_state(self): + self._check_get_set_state(get_py_state_ptr()) + + def test_shuffle(self): + self._check_shuffle(get_py_state_ptr()) + + def test_init(self): + self._check_init(get_py_state_ptr()) + + def test_perturb(self): + self._check_perturb(get_py_state_ptr()) + + +class TestRandom(BaseTest): + + # NOTE: there may be cascading imprecision issues (e.g. between x87-using + # C code and SSE-using LLVM code), which is especially brutal for some + # iterative algorithms with sensitive exit conditions. + # Therefore we stick to hardcoded integers for seed values. + + def _check_random_seed(self, seedfunc, randomfunc): + """ + Check seed()- and random()-like functions. + """ + # Our seed() mimics NumPy's. + r = np.random.RandomState() + for i in [0, 1, 125, 2**32 - 1]: + # Need to cast to a C-sized int (for Numpy <= 1.7) + r.seed(np.uint32(i)) + seedfunc(i) + # Be sure to trigger a reshuffle + for j in range(N + 10): + self.assertPreciseEqual(randomfunc(), r.uniform(0.0, 1.0)) + + def test_random_random(self): + self._check_random_seed(random_seed, random_random) + + def test_numpy_random(self): + self._check_random_seed(numpy_seed, numpy_random) + # Test aliases + self._check_random_seed(numpy_seed, jit_nullary("np.random.random_sample")) + self._check_random_seed(numpy_seed, jit_nullary("np.random.ranf")) + self._check_random_seed(numpy_seed, jit_nullary("np.random.sample")) + self._check_random_seed(numpy_seed, jit_nullary("np.random.rand")) + + def _check_random_sized(self, seedfunc, randomfunc): + # Our seed() mimics NumPy's. + r = np.random.RandomState() + for i in [0, 1, 125, 2**32 - 1]: + # Need to cast to a C-sized int (for Numpy <= 1.7) + r.seed(np.uint32(i)) + seedfunc(i) + for n in range(10): + self.assertPreciseEqual(randomfunc(n), r.uniform(0.0, 1.0, n)) + + def test_numpy_random_sized(self): + self._check_random_sized(numpy_seed, jit_unary("np.random.random_sample")) + self._check_random_sized(numpy_seed, jit_unary("np.random.ranf")) + self._check_random_sized(numpy_seed, jit_unary("np.random.sample")) + self._check_random_sized(numpy_seed, jit_unary("np.random.rand")) + + def test_independent_generators(self): + # PRNGs for Numpy and Python are independent. + N = 10 + random_seed(1) + py_numbers = [random_random() for i in range(N)] + numpy_seed(2) + np_numbers = [numpy_random() for i in range(N)] + random_seed(1) + numpy_seed(2) + pairs = [(random_random(), numpy_random()) for i in range(N)] + self.assertPreciseEqual([p[0] for p in pairs], py_numbers) + self.assertPreciseEqual([p[1] for p in pairs], np_numbers) + + def _check_getrandbits(self, func, ptr): + """ + Check a getrandbits()-like function. + """ + # Our implementation follows CPython's for bits <= 64. + r = self._follow_cpython(ptr) + for nbits in range(1, 65): + expected = r.getrandbits(nbits) + got = func(nbits) + self.assertPreciseEqual(expected, got) + self.assertRaises(OverflowError, func, 65) + self.assertRaises(OverflowError, func, 9999999) + self.assertRaises(OverflowError, func, -1) + + def test_random_getrandbits(self): + self._check_getrandbits(jit_unary("random.getrandbits"), get_py_state_ptr()) + + # Explanation for the large ulps value: on 32-bit platforms, our + # LLVM-compiled functions use SSE but they are compared against + # C functions which use x87. + # On some distributions, the errors seem to accumulate dramatically. + + def _check_dist(self, func, pyfunc, argslist, niters=3, + prec='double', ulps=12, pydtype=None): + assert len(argslist) + for args in argslist: + results = [func(*args) for i in range(niters)] + pyresults = [(pyfunc(*args, dtype=pydtype) if pydtype else pyfunc(*args)) + for i in range(niters)] + self.assertPreciseEqual(results, pyresults, prec=prec, ulps=ulps, + msg="for arguments %s" % (args,)) + + def _check_dist_kwargs(self, func, pyfunc, kwargslist, niters=3, + prec='double', ulps=12, pydtype=None): + assert len(kwargslist) + for kwargs in kwargslist: + results = [func(**kwargs) for i in range(niters)] + pyresults = [(pyfunc(**kwargs, dtype=pydtype) if pydtype else pyfunc(**kwargs)) + for i in range(niters)] + self.assertPreciseEqual(results, pyresults, prec=prec, ulps=ulps, + msg="for arguments %s" % (kwargs,)) + + def _check_gauss(self, func2, func1, func0, ptr): + """ + Check a gauss()-like function. + """ + # Our implementation follows Numpy's. + r = self._follow_numpy(ptr) + if func2 is not None: + self._check_dist(func2, r.normal, + [(1.0, 1.0), (2.0, 0.5), (-2.0, 0.5)], + niters=N // 2 + 10) + if func1 is not None: + self._check_dist(func1, r.normal, [(0.5,)]) + if func0 is not None: + self._check_dist(func0, r.normal, [()]) + + def test_random_gauss(self): + self._check_gauss(jit_binary("random.gauss"), None, None, get_py_state_ptr()) + + def test_random_normalvariate(self): + # normalvariate() is really an alias to gauss() in Numba + # (not in Python, though - they use different algorithms) + self._check_gauss(jit_binary("random.normalvariate"), None, None, + get_py_state_ptr()) + + def test_numpy_normal(self): + self._check_gauss(jit_binary("np.random.normal"), + jit_unary("np.random.normal"), + jit_nullary("np.random.normal"), + get_np_state_ptr()) + + def test_numpy_standard_normal(self): + self._check_gauss(None, None, jit_nullary("np.random.standard_normal"), + get_np_state_ptr()) + + def test_numpy_randn(self): + self._check_gauss(None, None, jit_nullary("np.random.randn"), + get_np_state_ptr()) + + def _check_lognormvariate(self, func2, func1, func0, ptr): + """ + Check a lognormvariate()-like function. + """ + # Our implementation follows Numpy's. + r = self._follow_numpy(ptr) + if func2 is not None: + self._check_dist(func2, r.lognormal, + [(1.0, 1.0), (2.0, 0.5), (-2.0, 0.5)], + niters=N // 2 + 10) + if func1 is not None: + self._check_dist(func1, r.lognormal, [(0.5,)]) + if func0 is not None: + self._check_dist(func0, r.lognormal, [()]) + + def test_random_lognormvariate(self): + self._check_lognormvariate(jit_binary("random.lognormvariate"), + None, None, get_py_state_ptr()) + + def test_numpy_lognormal(self): + self._check_lognormvariate(jit_binary("np.random.lognormal"), + jit_unary("np.random.lognormal"), + jit_nullary("np.random.lognormal"), + get_np_state_ptr()) + + def _check_randrange(self, func1, func2, func3, ptr, max_width, is_numpy, tp=None): + """ + Check a randrange()-like function. + """ + # Sanity check + ints = [] + for i in range(10): + ints.append(func1(500000000)) + ints.append(func2(5, 500000000)) + if func3 is not None: + ints.append(func3(5, 500000000, 3)) + if is_numpy: + rr = self._follow_numpy(ptr).randint + else: + rr = self._follow_cpython(ptr).randrange + widths = [w for w in [1, 5, 8, 5000, 2**40, 2**62 + 2**61] if w < max_width] + pydtype = tp if is_numpy else None + for width in widths: + self._check_dist(func1, rr, [(width,)], niters=10, + pydtype=pydtype) + self._check_dist(func2, rr, [(-2, 2 +width)], niters=10, + pydtype=pydtype) + if func3 is not None: + self.assertPreciseEqual(func3(-2, 2 + width, 6), + rr(-2, 2 + width, 6)) + self.assertPreciseEqual(func3(2 + width, 2, -3), + rr(2 + width, 2, -3)) + # Empty ranges + self.assertRaises(ValueError, func1, 0) + self.assertRaises(ValueError, func1, -5) + self.assertRaises(ValueError, func2, 5, 5) + self.assertRaises(ValueError, func2, 5, 2) + if func3 is not None: + self.assertRaises(ValueError, func3, 5, 7, -1) + self.assertRaises(ValueError, func3, 7, 5, 1) + + def test_random_randrange(self): + for tp, max_width in [(types.int64, 2**63), (types.int32, 2**31)]: + cf1 = njit((tp,))(random_randrange1) + cf2 = njit((tp, tp,),)(random_randrange2) + cf3 = njit((tp, tp, tp,))(random_randrange3) + self._check_randrange(cf1, cf2, cf3, get_py_state_ptr(), + max_width, False) + + def test_numpy_randint(self): + for tp, np_tp, max_width in [(types.int64, np.int64, 2**63), + (types.int32, np.int32, 2**31)]: + cf1 = njit((tp,))(numpy_randint1) + cf2 = njit((tp, tp,))(numpy_randint2) + self._check_randrange(cf1, cf2, None, get_np_state_ptr(), max_width, + True, np_tp) + + def _check_randint(self, func, ptr, max_width): + """ + Check a randint()-like function. + """ + # Sanity check + ints = [] + for i in range(10): + ints.append(func(5, 500000000)) + self.assertEqual(len(ints), len(set(ints)), ints) + + r = self._follow_cpython(ptr) + for args in [(1, 5), (13, 5000), (20, 2**62 + 2**61)]: + if args[1] > max_width: + continue + self._check_dist(func, r.randint, [args], niters=10) + # Empty ranges + self.assertRaises(ValueError, func, 5, 4) + self.assertRaises(ValueError, func, 5, 2) + + def test_random_randint(self): + for tp, max_width in [(types.int64, 2**63), (types.int32, 2**31)]: + cf = njit((tp, tp,))(random_randint) + self._check_randint(cf, get_py_state_ptr(), max_width) + + def _check_uniform(self, func, ptr): + """ + Check a uniform()-like function. + """ + # Our implementation follows Python's. + r = self._follow_cpython(ptr) + self._check_dist(func, r.uniform, + [(1.5, 1e6), (-2.5, 1e3), (1.5, -2.5)]) + + def _check_any_distrib_kwargs(self, func, ptr, distrib, paramlist): + """ + Check any numpy distribution function. Does Numba use the same keyword + argument names as Numpy? + And given a fixed seed, do they both return the same samples? + """ + # Our implementation follows Numpy's (not Python's) + r = self._follow_numpy(ptr) + distrib_method_of_numpy = getattr(r, distrib) + self._check_dist_kwargs(func, distrib_method_of_numpy, paramlist) + + + def test_random_uniform(self): + self._check_uniform(jit_binary("random.uniform"), get_py_state_ptr()) + + def test_numpy_uniform(self): + self._check_uniform(jit_binary("np.random.uniform"), get_np_state_ptr()) + + def test_numpy_uniform_kwargs(self): + self._check_any_distrib_kwargs( + jit_with_kwargs("np.random.uniform", ['low', 'high']), + get_np_state_ptr(), + 'uniform', + paramlist=[{'low': 1.5, 'high': 1e6}, + {'low': -2.5, 'high': 1e3}, + {'low': 1.5, 'high': -2.5}]) + + def test_numpy_uniform_empty_size(self): + self._check_any_distrib_kwargs( + jit_with_kwargs("np.random.uniform", ['low', 'high', 'size']), + get_np_state_ptr(), + 'uniform', + paramlist=[{'low': 1.5, 'high': 1e6, 'size': ()}, + {'low': -2.5, 'high': 1e3, 'size': ()}, + {'low': 1.5, 'high': -2.5, 'size': ()}, + {'low': 1.5, 'high': 1e6, 'size': None}, + {'low': -2.5, 'high': 1e3, 'size': None}, + {'low': 1.5, 'high': -2.5, 'size': None},]) + + def _check_triangular(self, func2, func3, ptr): + """ + Check a triangular()-like function. + """ + # Our implementation follows Python's. + r = self._follow_cpython(ptr) + if func2 is not None: + self._check_dist(func2, r.triangular, + [(1.5, 3.5), (-2.5, 1.5), (1.5, 1.5)]) + self._check_dist(func3, r.triangular, [(1.5, 3.5, 2.2)]) + + def test_random_triangular(self): + self._check_triangular(jit_binary("random.triangular"), + jit_ternary("random.triangular"), + get_py_state_ptr()) + + def test_numpy_triangular(self): + triangular = jit_ternary("np.random.triangular") + fixed_triangular = lambda l, r, m: triangular(l, m, r) + self._check_triangular(None, fixed_triangular, get_np_state_ptr()) + + def _check_gammavariate(self, func2, func1, ptr): + """ + Check a gammavariate()-like function. + """ + # Our implementation follows Python's. + r = self._follow_cpython(ptr) + if func2 is not None: + self._check_dist(func2, r.gammavariate, + [(0.5, 2.5), (1.0, 1.5), (1.5, 3.5)]) + if func1 is not None: + self.assertPreciseEqual(func1(1.5), r.gammavariate(1.5, 1.0)) + # Invalid inputs + if func2 is not None: + self.assertRaises(ValueError, func2, 0.0, 1.0) + self.assertRaises(ValueError, func2, 1.0, 0.0) + self.assertRaises(ValueError, func2, -0.5, 1.0) + self.assertRaises(ValueError, func2, 1.0, -0.5) + if func1 is not None: + self.assertRaises(ValueError, func1, 0.0) + self.assertRaises(ValueError, func1, -0.5) + + def test_random_gammavariate(self): + self._check_gammavariate(jit_binary("random.gammavariate"), None, + get_py_state_ptr()) + + def test_numpy_gamma(self): + self._check_gammavariate(jit_binary("np.random.gamma"), + jit_unary("np.random.gamma"), + get_np_state_ptr()) + self._check_gammavariate(None, + jit_unary("np.random.standard_gamma"), + get_np_state_ptr()) + + def _check_betavariate(self, func, ptr): + """ + Check a betavariate()-like function. + """ + # Our implementation follows Python's. + r = self._follow_cpython(ptr) + self._check_dist(func, r.betavariate, [(0.5, 2.5)]) + # Invalid inputs + self.assertRaises(ValueError, func, 0.0, 1.0) + self.assertRaises(ValueError, func, 1.0, 0.0) + self.assertRaises(ValueError, func, -0.5, 1.0) + self.assertRaises(ValueError, func, 1.0, -0.5) + + def test_random_betavariate(self): + self._check_betavariate(jit_binary("random.betavariate"), get_py_state_ptr()) + + def test_numpy_beta(self): + self._check_betavariate(jit_binary("np.random.beta"), get_np_state_ptr()) + + def _check_vonmisesvariate(self, func, ptr): + """ + Check a vonmisesvariate()-like function. + """ + r = self._follow_cpython(ptr) + self._check_dist(func, r.vonmisesvariate, [(0.5, 2.5)]) + + def test_random_vonmisesvariate(self): + self._check_vonmisesvariate(jit_binary("random.vonmisesvariate"), + get_py_state_ptr()) + + def test_numpy_vonmises(self): + self._check_vonmisesvariate(jit_binary("np.random.vonmises"), + get_np_state_ptr()) + + def _check_expovariate(self, func, ptr): + """ + Check a expovariate()-like function. Note the second argument + is inversed compared to np.random.exponential(). + """ + r = self._follow_numpy(ptr) + for lambd in (0.2, 0.5, 1.5): + for i in range(3): + self.assertPreciseEqual(func(lambd), r.exponential(1 / lambd), + prec='double') + + def test_random_expovariate(self): + self._check_expovariate(jit_unary("random.expovariate"), get_py_state_ptr()) + + def _check_exponential(self, func1, func0, ptr): + """ + Check a exponential()-like function. + """ + r = self._follow_numpy(ptr) + if func1 is not None: + self._check_dist(func1, r.exponential, [(0.5,), (1.0,), (1.5,)]) + if func0 is not None: + self._check_dist(func0, r.exponential, [()]) + + def test_numpy_exponential(self): + self._check_exponential(jit_unary("np.random.exponential"), + jit_nullary("np.random.exponential"), + get_np_state_ptr()) + + def test_numpy_standard_exponential(self): + self._check_exponential(None, + jit_nullary("np.random.standard_exponential"), + get_np_state_ptr()) + + def _check_paretovariate(self, func, ptr): + """ + Check a paretovariate()-like function. + """ + # Our implementation follows Python's. + r = self._follow_cpython(ptr) + self._check_dist(func, r.paretovariate, [(0.5,), (3.5,)]) + + def test_random_paretovariate(self): + self._check_paretovariate(jit_unary("random.paretovariate"), get_py_state_ptr()) + + def test_numpy_pareto(self): + pareto = jit_unary("np.random.pareto") + fixed_pareto = lambda a: pareto(a) + 1.0 + self._check_paretovariate(fixed_pareto, get_np_state_ptr()) + + def _check_weibullvariate(self, func2, func1, ptr): + """ + Check a weibullvariate()-like function. + """ + # Our implementation follows Python's. + r = self._follow_cpython(ptr) + if func2 is not None: + self._check_dist(func2, r.weibullvariate, [(0.5, 2.5)]) + if func1 is not None: + for i in range(3): + self.assertPreciseEqual(func1(2.5), + r.weibullvariate(1.0, 2.5)) + + def test_random_weibullvariate(self): + self._check_weibullvariate(jit_binary("random.weibullvariate"), + None, get_py_state_ptr()) + + def test_numpy_weibull(self): + self._check_weibullvariate(None, jit_unary("np.random.weibull"), + get_np_state_ptr()) + + def test_numpy_binomial(self): + binomial = jit_binary("np.random.binomial") + r = self._follow_numpy(get_np_state_ptr(), 0) + self._check_dist(binomial, r.binomial, [(18, 0.25), (60, 0.5), + (61, 0.5), (100, 0.4), + (100, 0.6)]) + # Sanity check many values + for n in (100, 1000, 10000): + self.assertEqual(binomial(n, 0.0), 0) + self.assertEqual(binomial(n, 1.0), n) + for p in (0.0001, 0.1, 0.4, 0.49999, 0.5, 0.50001, 0.8, 0.9, 0.9999): + r = binomial(n, p) + if p > 0.5: + r = n - r + p = 1 - p + self.assertGreaterEqual(r, 0) + self.assertLessEqual(r, n) + expected = p * n + tol = 3 * n / math.sqrt(n) + self.assertGreaterEqual(r, expected - tol, (p, n, r)) + self.assertLessEqual(r, expected + tol, (p, n, r)) + # Invalid values + self.assertRaises(ValueError, binomial, -1, 0.5) + self.assertRaises(ValueError, binomial, 10, -0.1) + self.assertRaises(ValueError, binomial, 10, 1.1) + + def test_numpy_chisquare(self): + chisquare = jit_unary("np.random.chisquare") + r = self._follow_cpython(get_np_state_ptr()) + self._check_dist(chisquare, + functools.partial(py_chisquare, r), + [(1.5,), (2.5,)]) + + def test_numpy_f(self): + f = jit_binary("np.random.f") + r = self._follow_cpython(get_np_state_ptr()) + self._check_dist(f, functools.partial(py_f, r), + [(0.5, 1.5), (1.5, 0.8)]) + + def test_numpy_geometric(self): + geom = jit_unary("np.random.geometric") + # p out of domain + self.assertRaises(ValueError, geom, -1.0) + self.assertRaises(ValueError, geom, 0.0) + self.assertRaises(ValueError, geom, 1.001) + # Some basic checks + N = 200 + r = [geom(1.0) for i in range(N)] + self.assertPreciseEqual(r, [1] * N) + r = [geom(0.9) for i in range(N)] + n = r.count(1) + self.assertGreaterEqual(n, N // 2) + self.assertLess(n, N) + self.assertFalse([i for i in r if i > 1000]) # unlikely + r = [geom(0.4) for i in range(N)] + self.assertTrue([i for i in r if i > 4]) # likely + r = [geom(0.01) for i in range(N)] + self.assertTrue([i for i in r if i > 50]) # likely + r = [geom(1e-15) for i in range(N)] + self.assertTrue([i for i in r if i > 2**32]) # likely + + def test_numpy_gumbel(self): + gumbel = jit_binary("np.random.gumbel") + r = self._follow_numpy(get_np_state_ptr()) + self._check_dist(gumbel, r.gumbel, [(0.0, 1.0), (-1.5, 3.5)]) + + def test_numpy_gumbel_kwargs(self): + self._check_any_distrib_kwargs( + jit_with_kwargs("np.random.gumbel", ['loc', 'scale']), + get_np_state_ptr(), + distrib="gumbel", + paramlist=[{'loc': 0.0, 'scale': 1.0}, + {'loc': -1.5, 'scale': 3.5}]) + + + def test_numpy_hypergeometric(self): + # Our implementation follows Numpy's up to nsamples = 10. + hg = jit_ternary("np.random.hypergeometric") + r = self._follow_numpy(get_np_state_ptr()) + self._check_dist(hg, r.hypergeometric, + [(1000, 5000, 10), (5000, 1000, 10)], + niters=30) + # Sanity checks + r = [hg(1000, 1000, 100) for i in range(100)] + self.assertTrue(all(x >= 0 and x <= 100 for x in r), r) + self.assertGreaterEqual(np.mean(r), 40.0) + self.assertLessEqual(np.mean(r), 60.0) + r = [hg(1000, 100000, 100) for i in range(100)] + self.assertTrue(all(x >= 0 and x <= 100 for x in r), r) + self.assertLessEqual(np.mean(r), 10.0) + r = [hg(100000, 1000, 100) for i in range(100)] + self.assertTrue(all(x >= 0 and x <= 100 for x in r), r) + self.assertGreaterEqual(np.mean(r), 90.0) + + def test_numpy_laplace(self): + r = self._follow_numpy(get_np_state_ptr()) + self._check_dist(jit_binary("np.random.laplace"), r.laplace, + [(0.0, 1.0), (-1.5, 3.5)]) + self._check_dist(jit_unary("np.random.laplace"), r.laplace, + [(0.0,), (-1.5,)]) + self._check_dist(jit_nullary("np.random.laplace"), r.laplace, [()]) + + def test_numpy_logistic(self): + r = self._follow_numpy(get_np_state_ptr()) + self._check_dist(jit_binary("np.random.logistic"), r.logistic, + [(0.0, 1.0), (-1.5, 3.5)]) + self._check_dist(jit_unary("np.random.logistic"), r.logistic, + [(0.0,), (-1.5,)]) + self._check_dist(jit_nullary("np.random.logistic"), r.logistic, [()]) + + def test_numpy_logseries(self): + r = self._follow_numpy(get_np_state_ptr()) + logseries = jit_unary("np.random.logseries") + self._check_dist(logseries, r.logseries, + [(0.1,), (0.99,), (0.9999,)], + niters=50) + # Numpy's logseries overflows on 32-bit builds, so instead + # hardcode Numpy's (correct) output on 64-bit builds. + r = self._follow_numpy(get_np_state_ptr(), seed=1) + self.assertEqual([logseries(0.9999999999999) for i in range(10)], + [2022733531, 77296, 30, 52204, 9341294, 703057324, + 413147702918, 1870715907, 16009330, 738]) + self.assertRaises(ValueError, logseries, 0.0) + self.assertRaises(ValueError, logseries, -0.1) + self.assertRaises(ValueError, logseries, 1.1) + + def test_numpy_poisson(self): + r = self._follow_numpy(get_np_state_ptr()) + poisson = jit_unary("np.random.poisson") + # Our implementation follows Numpy's. + self._check_dist(poisson, r.poisson, + [(0.0,), (0.5,), (2.0,), (10.0,), (900.5,)], + niters=50) + self.assertRaises(ValueError, poisson, -0.1) + + def test_numpy_negative_binomial(self): + self._follow_numpy(get_np_state_ptr(), 0) + negbin = jit_binary("np.random.negative_binomial") + self.assertEqual([negbin(10, 0.9) for i in range(10)], + [2, 3, 1, 5, 2, 1, 0, 1, 0, 0]) + self.assertEqual([negbin(10, 0.1) for i in range(10)], + [55, 71, 56, 57, 56, 56, 34, 55, 101, 67]) + self.assertEqual([negbin(1000, 0.1) for i in range(10)], + [9203, 8640, 9081, 9292, 8938, + 9165, 9149, 8774, 8886, 9117]) + self.assertEqual([negbin(0.3, 0.1) for i in range(10)], + [0, 2, 15, 4, 4, 0, 0, 0, 1, 0]) + m = np.mean([negbin(1000000000, 0.1) + for i in range(50)]) + self.assertGreater(m, 9e9 * 0.99) + self.assertLess(m, 9e9 * 1.01) + self.assertRaises(ValueError, negbin, 0, 0.5) + self.assertRaises(ValueError, negbin, -1, 0.5) + self.assertRaises(ValueError, negbin, 10, -0.1) + self.assertRaises(ValueError, negbin, 10, 1.1) + + def test_numpy_power(self): + r = self._follow_numpy(get_np_state_ptr()) + power = jit_unary("np.random.power") + self._check_dist(power, r.power, + [(0.1,), (0.5,), (0.9,), (6.0,)]) + self.assertRaises(ValueError, power, 0.0) + self.assertRaises(ValueError, power, -0.1) + + def test_numpy_rayleigh(self): + r = self._follow_numpy(get_np_state_ptr()) + rayleigh1 = jit_unary("np.random.rayleigh") + rayleigh0 = jit_nullary("np.random.rayleigh") + self._check_dist(rayleigh1, r.rayleigh, + [(0.1,), (0.8,), (25.,), (1e3,)]) + self._check_dist(rayleigh0, r.rayleigh, [()]) + self.assertRaises(ValueError, rayleigh1, 0.0) + self.assertRaises(ValueError, rayleigh1, -0.1) + + def test_numpy_standard_cauchy(self): + r = self._follow_numpy(get_np_state_ptr()) + cauchy = jit_nullary("np.random.standard_cauchy") + self._check_dist(cauchy, r.standard_cauchy, [()]) + + def test_numpy_standard_t(self): + # We use CPython's algorithm for the gamma dist and numpy's + # for the normal dist. Standard T calls both so we can't check + # against either generator's output. + r = self._follow_cpython(get_np_state_ptr()) + standard_t = jit_unary("np.random.standard_t") + avg = np.mean([standard_t(5) for i in range(5000)]) + # Sanity check + self.assertLess(abs(avg), 0.5) + + def test_numpy_wald(self): + r = self._follow_numpy(get_np_state_ptr()) + wald = jit_binary("np.random.wald") + self._check_dist(wald, r.wald, [(1.0, 1.0), (2.0, 5.0)]) + self.assertRaises(ValueError, wald, 0.0, 1.0) + self.assertRaises(ValueError, wald, -0.1, 1.0) + self.assertRaises(ValueError, wald, 1.0, 0.0) + self.assertRaises(ValueError, wald, 1.0, -0.1) + + def test_numpy_wald_kwargs(self): + numba_version = jit_with_kwargs("np.random.wald", ['mean', 'scale']) + self._check_any_distrib_kwargs(numba_version, + get_np_state_ptr(), + distrib="wald", + paramlist=[{'mean': 1.0, 'scale': 1.0}, + {'mean': 2.0, 'scale': 5.0}]) + self.assertRaises(ValueError, numba_version, 0.0, 1.0) + self.assertRaises(ValueError, numba_version, -0.1, 1.0) + self.assertRaises(ValueError, numba_version, 1.0, 0.0) + self.assertRaises(ValueError, numba_version, 1.0, -0.1) + + def test_numpy_zipf(self): + r = self._follow_numpy(get_np_state_ptr()) + zipf = jit_unary("np.random.zipf") + self._check_dist(zipf, r.zipf, [(1.5,), (2.5,)], niters=100) + for val in (1.0, 0.5, 0.0, -0.1): + self.assertRaises(ValueError, zipf, val) + + def _check_shuffle(self, func, ptr, is_numpy): + """ + Check a shuffle()-like function for arrays. + """ + arrs = [np.arange(20), np.arange(32).reshape((8, 4))] + if is_numpy: + r = self._follow_numpy(ptr) + else: + r = self._follow_cpython(ptr) + for a in arrs: + for i in range(3): + got = a.copy() + expected = a.copy() + func(got) + if is_numpy or len(a.shape) == 1: + r.shuffle(expected) + self.assertPreciseEqual(got, expected) + # Test with an arbitrary buffer-providing object + a = arrs[0] + b = a.copy() + func(memoryview(b)) + self.assertNotEqual(list(a), list(b)) + self.assertEqual(sorted(a), sorted(b)) + # Read-only object + with self.assertTypingError(): + func(memoryview(b"xyz")) + + def test_random_shuffle(self): + self._check_shuffle(jit_unary("random.shuffle"), get_py_state_ptr(), False) + + def test_numpy_shuffle(self): + self._check_shuffle(jit_unary("np.random.shuffle"), get_np_state_ptr(), True) + + def _check_startup_randomness(self, func_name, func_args): + """ + Check that the state is properly randomized at startup. + """ + code = """if 1: + from numba.tests import test_random + func = getattr(test_random, %(func_name)r) + print(func(*%(func_args)r)) + """ % (locals()) + numbers = set() + for i in range(3): + popen = subprocess.Popen([sys.executable, "-c", code], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = popen.communicate() + if popen.returncode != 0: + raise AssertionError("process failed with code %s: stderr follows\n%s\n" + % (popen.returncode, err.decode())) + numbers.add(float(out.strip())) + self.assertEqual(len(numbers), 3, numbers) + + def test_random_random_startup(self): + self._check_startup_randomness("random_random", ()) + + def test_random_gauss_startup(self): + self._check_startup_randomness("random_gauss", (1.0, 1.0)) + + def test_numpy_random_startup(self): + self._check_startup_randomness("numpy_random", ()) + + def test_numpy_gauss_startup(self): + self._check_startup_randomness("numpy_normal", (1.0, 1.0)) + + def test_numpy_random_permutation(self): + func = jit_unary("np.random.permutation") + r = self._follow_numpy(get_np_state_ptr()) + for s in [5, 10, 15, 20]: + a = np.arange(s) + b = a.copy() + # Test array version + self.assertPreciseEqual(func(a), r.permutation(a)) + # Test int version + self.assertPreciseEqual(func(s), r.permutation(s)) + # Permutation should not modify its argument + self.assertPreciseEqual(a, b) + # Check multi-dimensional arrays + arrs = [np.arange(10).reshape(2, 5), + np.arange(27).reshape(3, 3, 3), + np.arange(36).reshape(2, 3, 3, 2)] + for a in arrs: + b = a.copy() + self.assertPreciseEqual(func(a), r.permutation(a)) + self.assertPreciseEqual(a, b) + + +class TestRandomArrays(BaseTest): + """ + Test array-producing variants of np.random.* functions. + """ + + def _compile_array_dist(self, funcname, nargs): + qualname = "np.random.%s" % (funcname,) + argstring = ', '.join('abcd'[:nargs]) + return jit_with_args(qualname, argstring) + + def _check_array_dist(self, funcname, scalar_args): + """ + Check returning an array according to a given distribution. + """ + cfunc = self._compile_array_dist(funcname, len(scalar_args) + 1) + r = self._follow_numpy(get_np_state_ptr()) + pyfunc = getattr(r, funcname) + for size in (8, (2, 3)): + args = scalar_args + (size,) + expected = pyfunc(*args) + got = cfunc(*args) + # Numpy may return int32s where we return int64s, adjust + if (expected.dtype == np.dtype('int32') + and got.dtype == np.dtype('int64')): + expected = expected.astype(got.dtype) + self.assertPreciseEqual(expected, got, prec='double', ulps=5) + args = scalar_args + (None,) + expected = pyfunc(*args) + got = cfunc(*args) + self.assertPreciseEqual(expected, got, prec='double', ulps=5) + + def _check_array_dist_gamma(self, funcname, scalar_args, extra_pyfunc_args): + """ + Check returning an array according to a given gamma distribution, + where we use CPython's implementation rather than NumPy's. + """ + cfunc = self._compile_array_dist(funcname, len(scalar_args) + 1) + r = self._follow_cpython(get_np_state_ptr()) + pyfunc = getattr(r, "gammavariate") + pyfunc_args = scalar_args + extra_pyfunc_args + pyrandom = lambda *_args: pyfunc(*pyfunc_args) + + args = scalar_args + (None,) + expected = pyrandom() + got = cfunc(*args) + self.assertPreciseEqual(expected, got, prec='double', ulps=5) + for size in (8, (2, 3)): + args = scalar_args + (size,) + expected = np.empty(size) + expected_flat = expected.flat + for idx in range(expected.size): + expected_flat[idx] = pyrandom() + got = cfunc(*args) + self.assertPreciseEqual(expected, got, prec='double', ulps=5) + + def _check_array_dist_self(self, funcname, scalar_args): + """ + Check function returning an array against its scalar implementation. + Because we use the CPython gamma distribution rather than the NumPy one, + distributions which use the gamma distribution vary in ways that are + difficult to compare. Instead, we compile both the array and scalar + versions and check that the array is filled with the same values as + we would expect from the scalar version. + """ + @numba.njit + def reset(): + np.random.seed(1234) + + array_func = self._compile_array_dist(funcname, len(scalar_args) + 1) + + qualname = "np.random.%s" % (funcname,) + argstring = ', '.join('abcd'[:len(scalar_args)]) + scalar_func = jit_with_args(qualname, argstring) + + for size in (8, (2, 3)): + args = scalar_args + (size,) + reset() + got = array_func(*args) + reset() + # We're just going to go with whatever type the array version + # gives us and hope it's not Boolean or something useless. + expected = np.empty(size, dtype=got.dtype) + flat = expected.flat + for idx in range(expected.size): + flat[idx] = scalar_func(*scalar_args) + self.assertPreciseEqual(expected, got, prec='double', ulps=5) + + reset() + args = scalar_args + (None,) + expected = scalar_func(*scalar_args) + reset() + got = array_func(*args) + self.assertPreciseEqual(expected, got, prec='double', ulps=5) + + def test_numpy_randint(self): + cfunc = self._compile_array_dist("randint", 3) + low, high = 1000, 10000 + size = (30, 30) + res = cfunc(low, high, size) + self.assertIsInstance(res, np.ndarray) + self.assertEqual(res.shape, size) + self.assertIn(res.dtype, (np.dtype('int32'), np.dtype('int64'))) + self.assertTrue(np.all(res >= low)) + self.assertTrue(np.all(res < high)) + # Crude statistical tests + mean = (low + high) / 2 + tol = (high - low) / 20 + self.assertGreaterEqual(res.mean(), mean - tol) + self.assertLessEqual(res.mean(), mean + tol) + + def test_numpy_random_random(self): + cfunc = self._compile_array_dist("random", 1) + size = (30, 30) + res = cfunc(size) + self.assertIsInstance(res, np.ndarray) + self.assertEqual(res.shape, size) + self.assertEqual(res.dtype, np.dtype('float64')) + # Results are within expected bounds + self.assertTrue(np.all(res >= 0.0)) + self.assertTrue(np.all(res < 1.0)) + # Crude statistical tests + self.assertTrue(np.any(res <= 0.1)) + self.assertTrue(np.any(res >= 0.9)) + mean = res.mean() + self.assertGreaterEqual(mean, 0.45) + self.assertLessEqual(mean, 0.55) + + # Sanity-check various distributions. For convenience, we only check + # those distributions that produce the exact same values as Numpy's. + + def test_numpy_beta(self): + self._check_array_dist_self("beta", (0.5, 2.5)) + + def test_numpy_binomial(self): + self._check_array_dist("binomial", (20, 0.5)) + + def test_numpy_chisquare(self): + self._check_array_dist_self("chisquare", (1.5,)) + + def test_numpy_exponential(self): + self._check_array_dist("exponential", (1.5,)) + + def test_numpy_f(self): + self._check_array_dist_self("f", (0.5, 1.5)) + + def test_numpy_gamma(self): + self._check_array_dist_gamma("gamma", (2.0, 1.0), ()) + + def test_numpy_geometric(self): + self._check_array_dist("geometric", (1.0,)) + + def test_numpy_gumbel(self): + self._check_array_dist("gumbel", (1.5, 0.5)) + + def test_numpy_hypergeometric(self): + self._check_array_dist("hypergeometric", (1000, 5000, 10)) + + def test_numpy_laplace(self): + self._check_array_dist("laplace", (1.5, 0.5)) + + def test_numpy_logistic(self): + self._check_array_dist("logistic", (1.5, 0.5)) + + def test_numpy_lognormal(self): + self._check_array_dist("lognormal", (1.5, 2.0)) + + def test_numpy_logseries(self): + self._check_array_dist("logseries", (0.8,)) + + def test_numpy_normal(self): + self._check_array_dist("normal", (0.5, 2.0)) + + def test_numpy_pareto(self): + self._check_array_dist("pareto", (0.5,)) + + def test_numpy_poisson(self): + self._check_array_dist("poisson", (0.8,)) + + def test_numpy_power(self): + self._check_array_dist("power", (0.8,)) + + def test_numpy_rand(self): + cfunc = jit(nopython=True)(numpy_check_rand) + expected, got = cfunc(42, 2, 3) + self.assertEqual(got.shape, (2, 3)) + self.assertPreciseEqual(expected, got) + + def test_numpy_randn(self): + cfunc = jit(nopython=True)(numpy_check_randn) + expected, got = cfunc(42, 2, 3) + self.assertEqual(got.shape, (2, 3)) + self.assertPreciseEqual(expected, got) + + def test_numpy_rayleigh(self): + self._check_array_dist("rayleigh", (0.8,)) + + def test_numpy_standard_cauchy(self): + self._check_array_dist("standard_cauchy", ()) + + def test_numpy_standard_exponential(self): + self._check_array_dist("standard_exponential", ()) + + def test_numpy_standard_gamma(self): + self._check_array_dist_gamma("standard_gamma", (2.0,), (1.0,)) + + def test_numpy_standard_normal(self): + self._check_array_dist("standard_normal", ()) + + def test_numpy_triangular(self): + self._check_array_dist("triangular", (1.5, 2.2, 3.5)) + + def test_numpy_uniform(self): + self._check_array_dist("uniform", (0.1, 0.4)) + + def test_numpy_wald(self): + self._check_array_dist("wald", (0.1, 0.4)) + + def test_numpy_vonmises(self): + self._check_array_dist_self("vonmises", (0.5, 2.5)) + + def test_numpy_zipf(self): + self._check_array_dist("zipf", (2.5,)) + + +class TestRandomChoice(BaseTest): + """ + Test np.random.choice. + """ + + def _check_results(self, pop, res, replace=True): + """ + Check basic expectations about a batch of samples. + """ + spop = set(pop) + sres = set(res) + # All results are in the population + self.assertLessEqual(sres, spop) + # Sorted results are unlikely + self.assertNotEqual(sorted(res), list(res)) + if replace: + # Duplicates are likely + self.assertLess(len(sres), len(res), res) + else: + # No duplicates + self.assertEqual(len(sres), len(res), res) + + def _check_dist(self, pop, samples): + """ + Check distribution of some samples. + """ + # Sanity check that we have enough samples + self.assertGreaterEqual(len(samples), len(pop) * 100) + # Check equidistribution of samples + expected_frequency = len(samples) / len(pop) + c = collections.Counter(samples) + for value in pop: + n = c[value] + self.assertGreaterEqual(n, expected_frequency * 0.5) + self.assertLessEqual(n, expected_frequency * 2.0) + + def _accumulate_array_results(self, func, nresults): + """ + Accumulate array results produced by *func* until they reach + *nresults* elements. + """ + res = [] + while len(res) < nresults: + res += list(func().flat) + return res[:nresults] + + def _check_choice_1(self, a, pop): + """ + Check choice(a) against pop. + """ + cfunc = jit(nopython=True)(numpy_choice1) + n = len(pop) + res = [cfunc(a) for i in range(n)] + self._check_results(pop, res) + dist = [cfunc(a) for i in range(n * 100)] + self._check_dist(pop, dist) + + def test_choice_scalar_1(self): + """ + Test choice(int) + """ + n = 50 + pop = list(range(n)) + self._check_choice_1(n, pop) + + def test_choice_array_1(self): + """ + Test choice(array) + """ + pop = np.arange(50) * 2 + 100 + self._check_choice_1(pop, pop) + + def _check_array_results(self, func, pop, replace=True): + """ + Check array results produced by *func* and their distribution. + """ + n = len(pop) + res = list(func().flat) + self._check_results(pop, res, replace) + dist = self._accumulate_array_results(func, n * 100) + self._check_dist(pop, dist) + + def _check_choice_2(self, a, pop): + """ + Check choice(a, size) against pop. + """ + cfunc = jit(nopython=True)(numpy_choice2) + n = len(pop) + # Final sizes should be large enough, so as to stress + # replacement + sizes = [n - 10, (3, (n - 1) // 3), n * 10] + + for size in sizes: + # Check result shape + res = cfunc(a, size) + expected_shape = size if isinstance(size, tuple) else (size,) + self.assertEqual(res.shape, expected_shape) + # Check results and their distribution + self._check_array_results(lambda: cfunc(a, size), pop) + + def test_choice_scalar_2(self): + """ + Test choice(int, size) + """ + n = 50 + pop = np.arange(n) + self._check_choice_2(n, pop) + + def test_choice_array_2(self): + """ + Test choice(array, size) + """ + pop = np.arange(50) * 2 + 100 + self._check_choice_2(pop, pop) + + def _check_choice_3(self, a, pop): + """ + Check choice(a, size, replace) against pop. + """ + cfunc = jit(nopython=True)(numpy_choice3) + n = len(pop) + # Final sizes should be close but slightly <= n, so as to stress + # replacement (or not) + sizes = [n - 10, (3, (n - 1) // 3)] + replaces = [True, False] + + # Check result shapes + for size in sizes: + for replace in [True, False]: + res = cfunc(a, size, replace) + expected_shape = size if isinstance(size, tuple) else (size,) + self.assertEqual(res.shape, expected_shape) + + # Check results for replace=True + for size in sizes: + self._check_array_results(lambda: cfunc(a, size, True), pop) + # Check results for replace=False + for size in sizes: + self._check_array_results(lambda: cfunc(a, size, False), pop, False) + + # Can't ask for more samples than population size with replace=False + for size in [n + 1, (3, n // 3 + 1)]: + with self.assertRaises(ValueError): + cfunc(a, size, False) + + def test_choice_scalar_3(self): + """ + Test choice(int, size, replace) + """ + n = 50 + pop = np.arange(n) + self._check_choice_3(n, pop) + + def test_choice_array_3(self): + """ + Test choice(array, size, replace) + """ + pop = np.arange(50) * 2 + 100 + self._check_choice_3(pop, pop) + + def test_choice_follows_seed(self): + # See issue #3888, np.random.choice must acknowledge the seed + + @jit(nopython=True) + def numba_rands(n_to_return, choice_array): + np.random.seed(1337) + out = np.empty((n_to_return, 2), np.int32) + for i in range(n_to_return): + out[i] = np.random.choice(choice_array, 2, False) + return out + + choice_array = np.random.randint(300, size=1000).astype(np.int32) + tmp_np = choice_array.copy() + expected = numba_rands.py_func(5, tmp_np) + tmp_nb = choice_array.copy() + got = numba_rands(5, tmp_nb) + np.testing.assert_allclose(expected, got) + # check no mutation + np.testing.assert_allclose(choice_array, tmp_np) + np.testing.assert_allclose(choice_array, tmp_nb) + + +class TestRandomMultinomial(BaseTest): + """ + Test np.random.multinomial. + """ + # A biased dice + pvals = np.array([1, 1, 1, 2, 3, 1], dtype=np.float64) + pvals /= pvals.sum() + + def _check_sample(self, n, pvals, sample): + """ + Check distribution of some samples. + """ + self.assertIsInstance(sample, np.ndarray) + self.assertEqual(sample.shape, (len(pvals),)) + self.assertIn(sample.dtype, (np.dtype('int32'), np.dtype('int64'))) + # Statistical properties + self.assertEqual(sample.sum(), n) + for p, nexp in zip(pvals, sample): + self.assertGreaterEqual(nexp, 0) + self.assertLessEqual(nexp, n) + pexp = float(nexp) / n + self.assertGreaterEqual(pexp, p * 0.5) + self.assertLessEqual(pexp, p * 2.0) + + def test_multinomial_2(self): + """ + Test multinomial(n, pvals) + """ + cfunc = jit(nopython=True)(numpy_multinomial2) + n, pvals = 1000, self.pvals + res = cfunc(n, pvals) + self._check_sample(n, pvals, res) + # pvals as list + pvals = list(pvals) + res = cfunc(n, pvals) + self._check_sample(n, pvals, res) + # A case with extreme probabilities + n = 1000000 + pvals = np.array([1, 0, n // 100, 1], dtype=np.float64) + pvals /= pvals.sum() + res = cfunc(n, pvals) + self._check_sample(n, pvals, res) + + def test_multinomial_3_int(self): + """ + Test multinomial(n, pvals, size: int) + """ + cfunc = jit(nopython=True)(numpy_multinomial3) + n, pvals = 1000, self.pvals + k = 10 + res = cfunc(n, pvals, k) + self.assertEqual(res.shape[0], k) + for sample in res: + self._check_sample(n, pvals, sample) + + def test_multinomial_3_tuple(self): + """ + Test multinomial(n, pvals, size: tuple) + """ + cfunc = jit(nopython=True)(numpy_multinomial3) + n, pvals = 1000, self.pvals + k = (3, 4) + res = cfunc(n, pvals, k) + self.assertEqual(res.shape[:-1], k) + for sample in res.reshape((-1, res.shape[-1])): + self._check_sample(n, pvals, sample) + + +class TestRandomDirichlet(BaseTest): + alpha = np.array([1, 1, 1, 2], dtype=np.float64) + + def _check_sample(self, alpha, size, sample): + + """Check output structure""" + self.assertIsInstance(sample, np.ndarray) + self.assertEqual(sample.dtype, np.float64) + if size is None: + self.assertEqual(sample.size, len(alpha)) + elif type(size) is int: + self.assertEqual(sample.shape, (size, len(alpha))) + else: + self.assertEqual(sample.shape, size + (len(alpha),)) + + """Check statistical properties""" + for val in np.nditer(sample): + self.assertGreaterEqual(val, 0) + self.assertLessEqual(val, 1) + if size is None: + self.assertAlmostEqual(sample.sum(), 1, places=5) + else: + for totals in np.nditer(sample.sum(axis=-1)): + self.assertAlmostEqual(totals, 1, places=5) + + def test_dirichlet_default(self): + """ + Test dirichlet(alpha, size=None) + """ + cfunc = jit(nopython=True)(numpy_dirichlet_default) + alphas = ( + self.alpha, + tuple(self.alpha), + np.array([1, 1, 10000, 1], dtype=np.float64), + np.array([1, 1, 1.5, 1], dtype=np.float64), + ) + for alpha in alphas: + res = cfunc(alpha) + self._check_sample(alpha, None, res) + + def test_dirichlet(self): + """ + Test dirichlet(alpha, size=None) + """ + cfunc = jit(nopython=True)(numpy_dirichlet) + sizes = (None, (10,), (10, 10)) + alphas = ( + self.alpha, + tuple(self.alpha), + np.array([1, 1, 10000, 1], dtype=np.float64), + np.array([1, 1, 1.5, 1], dtype=np.float64), + ) + + for alpha, size in itertools.product(alphas, sizes): + res = cfunc(alpha, size) + self._check_sample(alpha, size, res) + + def test_dirichlet_exceptions(self): + cfunc = jit(nopython=True)(numpy_dirichlet) + alpha = tuple((0, 1, 1)) + with self.assertRaises(ValueError) as raises: + cfunc(alpha, 1) + self.assertIn("dirichlet: alpha must be > 0.0", str(raises.exception)) + + alpha = self.alpha + sizes = (True, 3j, 1.5, (1.5, 1), (3j, 1), (3j, 3j), (np.int8(3), np.int64(7))) + for size in sizes: + with self.assertRaises(TypingError) as raises: + cfunc(alpha, size) + self.assertIn( + "np.random.dirichlet(): size should be int or " + "tuple of ints or None, got", + str(raises.exception), + ) + +class TestRandomNoncentralChiSquare(BaseTest): + + def _check_sample(self, size, sample): + + # Check output structure + if size is not None: + self.assertIsInstance(sample, np.ndarray) + self.assertEqual(sample.dtype, np.float64) + + if isinstance(size, int): + self.assertEqual(sample.shape, (size,)) + else: + self.assertEqual(sample.shape, size) + else: + self.assertIsInstance(sample, float) + + # Check statistical properties + for val in np.nditer(sample): + self.assertGreaterEqual(val, 0) + + def test_noncentral_chisquare_default(self): + """ + Test noncentral_chisquare(df, nonc, size=None) + """ + cfunc = jit(nopython=True)(numpy_noncentral_chisquare_default) + inputs = ( + (0.5, 1), # test branch when df < 1 + (1, 5), + (5, 1), + (100000, 1), + (1, 10000), + ) + for df, nonc in inputs: + res = cfunc(df, nonc) + self._check_sample(None, res) + res = cfunc(df, np.nan) # test branch when nonc is nan + self.assertTrue(np.isnan(res)) + + + def test_noncentral_chisquare(self): + """ + Test noncentral_chisquare(df, nonc, size) + """ + cfunc = jit(nopython=True)(numpy_noncentral_chisquare) + sizes = (None, 10, (10,), (10, 10)) + inputs = ( + (0.5, 1), + (1, 5), + (5, 1), + (100000, 1), + (1, 10000), + ) + + for (df, nonc), size in itertools.product(inputs, sizes): + res = cfunc(df, nonc, size) + self._check_sample(size, res) + res = cfunc(df, np.nan, size) # test branch when nonc is nan + self.assertTrue(np.isnan(res).all()) + + def test_noncentral_chisquare_exceptions(self): + cfunc = jit(nopython=True)(numpy_noncentral_chisquare) + df, nonc = 0, 1 + with self.assertRaises(ValueError) as raises: + cfunc(df, nonc, 1) + self.assertIn("df <= 0", str(raises.exception)) + + df, nonc = 1, -1 + with self.assertRaises(ValueError) as raises: + cfunc(df, nonc, 1) + self.assertIn("nonc < 0", str(raises.exception)) + + df, nonc = 1, 1 + sizes = (True, 3j, 1.5, (1.5, 1), (3j, 1), (3j, 3j), (np.int8(3), np.int64(7))) + for size in sizes: + with self.assertRaises(TypingError) as raises: + cfunc(df, nonc, size) + self.assertIn( + "np.random.noncentral_chisquare(): size should be int or " + "tuple of ints or None, got", + str(raises.exception), + ) + +@jit(nopython=True, nogil=True) +def py_extract_randomness(seed, out): + if seed != 0: + random.seed(seed) + for i in range(out.size): + out[i] = random.getrandbits(32) + +_randint_limit = 1 << 32 + +@jit(nopython=True, nogil=True) +def np_extract_randomness(seed, out): + if seed != 0: + np.random.seed(seed) + s = 0 + for i in range(out.size): + out[i] = np.random.randint(_randint_limit) + + + +class ConcurrencyBaseTest(TestCase): + + # Enough iterations for: + # 1. Mersenne-Twister state shuffles to occur (once every 624) + # 2. Race conditions to be plausible + # 3. Nice statistical properties to emerge + _extract_iterations = 100000 + + def setUp(self): + # Warm up, to avoid compiling in the threads + args = (42, self._get_output(1)) + py_extract_randomness(*args) + np_extract_randomness(*args) + + def _get_output(self, size): + return np.zeros(size, dtype=np.uint32) + + def check_output(self, out): + """ + Check statistical properties of output. + """ + # Output should follow a uniform distribution in [0, 1<<32) + expected_avg = 1 << 31 + expected_std = (1 << 32) / np.sqrt(12) + rtol = 0.05 # given enough iterations + np.testing.assert_allclose(out.mean(), expected_avg, rtol=rtol) + np.testing.assert_allclose(out.std(), expected_std, rtol=rtol) + + def check_several_outputs(self, results, same_expected): + # Outputs should have the expected statistical properties + # (an uninitialized PRNG or a PRNG whose internal state was + # corrupted by a race condition could produce bogus randomness) + for out in results: + self.check_output(out) + + # Check all threads gave either the same sequence or + # distinct sequences + if same_expected: + expected_distinct = 1 + else: + expected_distinct = len(results) + + heads = {tuple(out[:5]) for out in results} + tails = {tuple(out[-5:]) for out in results} + sums = {out.sum() for out in results} + self.assertEqual(len(heads), expected_distinct, heads) + self.assertEqual(len(tails), expected_distinct, tails) + self.assertEqual(len(sums), expected_distinct, sums) + + +class TestThreads(ConcurrencyBaseTest): + """ + Check the PRNG behaves well with threads. + """ + + def extract_in_threads(self, nthreads, extract_randomness, seed): + """ + Run *nthreads* threads extracting randomness with the given *seed* + (no seeding if 0). + """ + results = [self._get_output(self._extract_iterations) + for i in range(nthreads + 1)] + + def target(i): + # The PRNG will be seeded in thread + extract_randomness(seed=seed, out=results[i]) + + threads = [threading.Thread(target=target, args=(i,)) + for i in range(nthreads)] + + for th in threads: + th.start() + # Exercise main thread as well + target(nthreads) + for th in threads: + th.join() + + return results + + def check_thread_safety(self, extract_randomness): + """ + When initializing the PRNG the same way, each thread + should produce the same sequence of random numbers, + using independent states, regardless of parallel + execution. + """ + # Note the seed value doesn't matter, as long as it's + # the same for all threads + results = self.extract_in_threads(15, extract_randomness, seed=42) + + # All threads gave the same sequence + self.check_several_outputs(results, same_expected=True) + + def check_implicit_initialization(self, extract_randomness): + """ + The PRNG in new threads should be implicitly initialized with + system entropy, if seed() wasn't called. + """ + results = self.extract_in_threads(4, extract_randomness, seed=0) + + # All threads gave a different, valid random sequence + self.check_several_outputs(results, same_expected=False) + + def test_py_thread_safety(self): + self.check_thread_safety(py_extract_randomness) + + def test_np_thread_safety(self): + self.check_thread_safety(np_extract_randomness) + + def test_py_implicit_initialization(self): + self.check_implicit_initialization(py_extract_randomness) + + def test_np_implicit_initialization(self): + self.check_implicit_initialization(np_extract_randomness) + + +@unittest.skipIf(os.name == 'nt', "Windows is not affected by fork() issues") +class TestProcesses(ConcurrencyBaseTest): + """ + Check the PRNG behaves well in child processes. + """ + + # Avoid nested multiprocessing AssertionError + # ("daemonic processes are not allowed to have children") + _numba_parallel_test_ = False + + + def extract_in_processes(self, nprocs, extract_randomness): + """ + Run *nprocs* processes extracting randomness + without explicit seeding. + """ + q = multiprocessing.Queue() + results = [] + + def target_inner(): + out = self._get_output(self._extract_iterations) + extract_randomness(seed=0, out=out) + return out + + def target(): + try: + out = target_inner() + q.put(out) + except Exception as e: + # Ensure an exception in a child gets reported + # in the parent. + q.put(e) + raise + + if hasattr(multiprocessing, 'get_context'): + # The test works only in fork context. + mpc = multiprocessing.get_context('fork') + else: + mpc = multiprocessing + procs = [mpc.Process(target=target) + for i in range(nprocs)] + for p in procs: + p.start() + # Need to dequeue before joining, otherwise the large size of the + # enqueued objects will lead to deadlock. + for i in range(nprocs): + results.append(q.get(timeout=5)) + for p in procs: + p.join() + + # Exercise parent process as well; this will detect if the + # same state was reused for one of the children. + results.append(target_inner()) + for res in results: + if isinstance(res, Exception): + self.fail("Exception in child: %s" % (res,)) + + return results + + def check_implicit_initialization(self, extract_randomness): + """ + The PRNG in new processes should be implicitly initialized + with system entropy, to avoid reproducing the same sequences. + """ + results = self.extract_in_processes(2, extract_randomness) + + # All processes gave a different, valid random sequence + self.check_several_outputs(results, same_expected=False) + + def test_py_implicit_initialization(self): + self.check_implicit_initialization(py_extract_randomness) + + def test_np_implicit_initialization(self): + self.check_implicit_initialization(np_extract_randomness) + + +class TestNumPyRandomAPI(TestCase): + API_CALL_TESTS = {"np.random.beta": {'a': 1., 'b': 2., 'size': 3}, + "np.random.binomial": {'n': 1, 'p': 0.3, 'size': 3}, + "np.random.chisquare": {'df': 2., 'size': 3}, + "np.random.choice": {'a': 2, 'size': 3}, + "np.random.dirichlet": {'alpha': (2,), 'size': 3}, + "np.random.exponential": {'scale': 1., 'size': 3}, + "np.random.f": {'dfnum': 1., 'dfden': 2., 'size': 3}, + "np.random.gamma": {'shape': 2, 'scale': 2.0, 'size': 3}, + "np.random.geometric": {'p': 1., 'size': 3}, + "np.random.gumbel": {'loc': 0., 'scale': 1., 'size': 3}, + "np.random.hypergeometric": {'ngood': 1, 'nbad': 1, + 'nsample': 1, 'size': 3}, + "np.random.laplace": {'loc': 0., 'scale': 1., 'size': 3}, + "np.random.logistic": {'loc': 0., 'scale': 1., 'size': 3}, + "np.random.lognormal": {'mean': 0., 'sigma': 1., 'size': 3}, + "np.random.logseries": {'p': 0.5, 'size': 3}, + "np.random.multinomial": {'n': 1, 'pvals': (1,), 'size': 3}, + "np.random.negative_binomial": {'n': 1, 'p': 0.5}, + "np.random.noncentral_chisquare": {'df': 1., 'nonc': 1., + 'size': 3}, + "np.random.normal": {'loc': 0., 'scale': 1., 'size': 3}, + "np.random.pareto": {'a': 2., 'size': 3}, + # NOTE: The NumPy impl of permutation "takes no keyword + # arguments". + # "np.random.permutation": {'x': (1, 2, 3)}, + "np.random.poisson": {'lam': 1., 'size': 3}, + "np.random.power": {'a': 2., 'size': 3}, + # NOTE: The NumPy impl of rand essentially takes *args so kwargs + # are unsupported. + # "np.random.rand": {'d0': 1, 'd1': 2, ...}} + "np.random.randint": {'low': 1, 'high': 2, 'size': 3}, + # NOTE: The NumPy impl of randn essentially takes *args so + # kwargs are unsupported. + # "np.random.randn": {'d0': 1, 'd1': 2, ...}} + "np.random.random": {'size': 3}, + "np.random.random_sample": {'size': 3}, + "np.random.ranf": {'size': 3}, + "np.random.rayleigh": {'scale': 1., 'size': 3}, + "np.random.sample": {'size': 3}, + "np.random.seed": {'seed': 4}, + # NOTE: The NumPy impl of shuffle "takes no keyword arguments". + # "np.random.shuffle" + "np.random.standard_cauchy": {'size': 3}, + "np.random.standard_exponential": {'size': 3}, + "np.random.standard_gamma": {'shape': 2., 'size': 3}, + "np.random.standard_normal": {'size': 3}, + "np.random.standard_t": {'df': 2., 'size': 3}, + "np.random.triangular": {'left': 1., 'mode': 2., 'right': 3., + 'size': 3}, + "np.random.uniform": {'low': 1., 'high': 2., 'size': 3}, + "np.random.vonmises": {'mu': 1., 'kappa': 2., 'size': 3}, + "np.random.wald": {'mean': 1., 'scale': 2., 'size': 3}, + "np.random.weibull": {'a': 1., 'size': 3}, + "np.random.zipf": {'a': 2., 'size': 3},} + + def test_call_by_name(self): + # Checks that the NumPy impls in Numba can be used via call-by-name + # args, see issue numba#9053. + # + # Checking call-by-name has to be done somewhat manually as the NumPy + # numpy.random.* functions do not have signatures, see numpy#8734. + + # Herein, it doesn't matter what the values are, the names and types + # just have to make sense. + + for fn, args in self.API_CALL_TESTS.items(): + argstr = ', '.join([f'{k}={v}' for k, v in args.items()]) + template = dedent(f""" + def foo(): + return {fn}({argstr}) + """) + l = {} + exec(template, {'np': np}, l) + # The answer doesn't matter, these are tested in the tests above, + # the purpose of this test is to ensure that the code compiles with + # the args presented via name, i.e. the overloads are defined + # correctly with respect to the public API of the function. + func = l['foo'] + func() + njit(func).compile(()) + + def test_call_distributions_with_empty_size(self): + # Check that the distributions can be called with size=() as per the + # NumPy API, see issue numba#8975. + for fn, args in self.API_CALL_TESTS.items(): + if 'size' not in args: + continue + + args['size'] = () + argstr = ', '.join([f'{k}={v}' for k, v in args.items()]) + template = dedent(f""" + def foo(): + return {fn}({argstr}) + """) + l = {} + exec(template, {'np': np}, l) + + # Store result obtained by calling the np and nb functions. + # We are not interested by the values, they were tested above + # but we want to ensure that the function compiles, and that + # the shapes and types are the same between numpy and numba. + func = l['foo'] + np_val = func() + + nb_func = njit(func).compile(()) + nb_val = nb_func() + + if isinstance(nb_val, np.ndarray): + self.assertEqual(nb_val.shape, np_val.shape) + else: + self.assertIsInstance(nb_val, np_val.__class__) + + + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/package-files/76/76d9c651a021436ceb5a2d387523266c65f5aa5cde9fb947c1dcbbc20625fe91/blob b/shared/package-files/76/76d9c651a021436ceb5a2d387523266c65f5aa5cde9fb947c1dcbbc20625fe91/blob new file mode 100644 index 0000000000000000000000000000000000000000..763c65eadc98156fde7ae315c5353dd9737fdb67 --- /dev/null +++ b/shared/package-files/76/76d9c651a021436ceb5a2d387523266c65f5aa5cde9fb947c1dcbbc20625fe91/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_special_i0e_out : public at::meta::structured_special_i0e { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/76/76da903790e8872892959ffb6cb8c4b321181658e534f50bb231953734de74ab/blob b/shared/package-files/76/76da903790e8872892959ffb6cb8c4b321181658e534f50bb231953734de74ab/blob new file mode 100644 index 0000000000000000000000000000000000000000..96058f8f09f9c31b5448ee8ee32db0c8c6b12c55 --- /dev/null +++ b/shared/package-files/76/76da903790e8872892959ffb6cb8c4b321181658e534f50bb231953734de74ab/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::mm(Tensor self, Tensor mat2) -> Tensor +inline at::Tensor mm(const at::Tensor & self, const at::Tensor & mat2) { + return at::_ops::mm::call(self, mat2); +} + +// aten::mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat2) { + return at::_ops::mm_out::call(self, mat2, out); +} +// aten::mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & mm_outf(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out) { + return at::_ops::mm_out::call(self, mat2, out); +} + +} diff --git a/shared/package-files/76/76daebae82b90670034751968c2675f5a674b45b0c7ef141b4b410535b29fda8/blob b/shared/package-files/76/76daebae82b90670034751968c2675f5a674b45b0c7ef141b4b410535b29fda8/blob new file mode 100644 index 0000000000000000000000000000000000000000..24ff469ff98baf5a4457ba6a34330be310058cb4 --- /dev/null +++ b/shared/package-files/76/76daebae82b90670034751968c2675f5a674b45b0c7ef141b4b410535b29fda8/blob @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 + +from pip._vendor.cachecontrol.caches.file_cache import FileCache, SeparateBodyFileCache +from pip._vendor.cachecontrol.caches.redis_cache import RedisCache + +__all__ = ["FileCache", "SeparateBodyFileCache", "RedisCache"] diff --git a/shared/package-files/76/76dbd4b72ff3a0399c17055f969a620f37a562478e8423bbe2e445ea2cd04b39/blob b/shared/package-files/76/76dbd4b72ff3a0399c17055f969a620f37a562478e8423bbe2e445ea2cd04b39/blob new file mode 100644 index 0000000000000000000000000000000000000000..1e6f6efb2c751a97e3f0cd9de3eb55c0bb87772c --- /dev/null +++ b/shared/package-files/76/76dbd4b72ff3a0399c17055f969a620f37a562478e8423bbe2e445ea2cd04b39/blob @@ -0,0 +1,135 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// This API is EXPERIMENTAL. + +#pragma once + +#include +#include +#include + +#include "arrow/acero/exec_plan.h" +#include "arrow/acero/options.h" +#include "arrow/compute/type_fwd.h" +#include "arrow/engine/substrait/type_fwd.h" +#include "arrow/engine/substrait/visibility.h" +#include "arrow/type_fwd.h" + +namespace arrow { +namespace engine { + +/// How strictly to adhere to the input structure when converting between Substrait and +/// Acero representations of a plan. This allows the user to trade conversion accuracy +/// for performance and lenience. +enum class ARROW_ENGINE_EXPORT ConversionStrictness { + /// When a primitive is used at the input that doesn't have an exact match at the + /// output, reject the conversion. This effectively asserts that there is no (known) + /// information loss in the conversion, and that plans should either round-trip back and + /// forth exactly or not at all. This option is primarily intended for testing and + /// debugging. + EXACT_ROUNDTRIP, + + /// When a primitive is used at the input that doesn't have an exact match at the + /// output, attempt to model it with some collection of primitives at the output. This + /// means that even if the incoming plan is completely optimal by some metric, the + /// returned plan is fairly likely to not be optimal anymore, and round-trips back and + /// forth may make the plan increasingly suboptimal. However, every primitive at the + /// output can be (manually) traced back to exactly one primitive at the input, which + /// may be useful when debugging. + PRESERVE_STRUCTURE, + + /// Behaves like PRESERVE_STRUCTURE, but prefers performance over structural accuracy. + /// Basic optimizations *may* be applied, in order to attempt to not regress in terms of + /// plan performance: if the incoming plan was already aggressively optimized, the goal + /// is for the output plan to not be less performant. In practical use cases, this is + /// probably the option you want. + /// + /// Note that no guarantees are made on top of PRESERVE_STRUCTURE. Past and future + /// versions of Arrow may even ignore this option entirely and treat it exactly like + /// PRESERVE_STRUCTURE. + BEST_EFFORT, +}; + +using NamedTableProvider = std::function( + const std::vector&, const Schema&)>; +static NamedTableProvider kDefaultNamedTableProvider; + +using NamedTapProvider = std::function( + const std::string&, std::vector, const std::string&, + std::shared_ptr)>; + +class ARROW_ENGINE_EXPORT ExtensionDetails { + public: + virtual ~ExtensionDetails() = default; +}; + +class ARROW_ENGINE_EXPORT ExtensionProvider { + public: + virtual ~ExtensionProvider() = default; + virtual Result MakeRel(const ConversionOptions& conv_opts, + const std::vector& inputs, + const ExtensionDetails& ext_details, + const ExtensionSet& ext_set) = 0; +}; + +/// \brief Get the default extension provider +ARROW_ENGINE_EXPORT std::shared_ptr default_extension_provider(); +/// \brief Set the default extension provider +/// +/// \param[in] provider the new provider to be set as default +ARROW_ENGINE_EXPORT void set_default_extension_provider( + const std::shared_ptr& provider); + +ARROW_ENGINE_EXPORT NamedTapProvider default_named_tap_provider(); + +ARROW_ENGINE_EXPORT void set_default_named_tap_provider(NamedTapProvider provider); + +/// Options that control the conversion between Substrait and Acero representations of a +/// plan. +struct ARROW_ENGINE_EXPORT ConversionOptions { + ConversionOptions() + : strictness(ConversionStrictness::BEST_EFFORT), + named_table_provider(kDefaultNamedTableProvider), + named_tap_provider(default_named_tap_provider()), + extension_provider(default_extension_provider()), + allow_arrow_extensions(false) {} + + /// \brief How strictly the converter should adhere to the structure of the input. + ConversionStrictness strictness; + /// \brief A custom strategy to be used for providing named tables + /// + /// The default behavior will return an invalid status if the plan has any + /// named table relations. + NamedTableProvider named_table_provider; + /// \brief A custom strategy to be used for obtaining a tap declaration + /// + /// The default provider returns an error + NamedTapProvider named_tap_provider; + /// \brief A custom strategy to be used for providing relation infos. + /// + /// The default behavior will provide for relations known to Arrow. + std::shared_ptr extension_provider; + /// \brief If true then Arrow-specific types and functions will be allowed + /// + /// Set to false to create plans that are more likely to be compatible with non-Arrow + /// engines + bool allow_arrow_extensions; +}; + +} // namespace engine +} // namespace arrow diff --git a/shared/package-files/76/76dbdbf9216678d48d1640f8fd1e278e7140482e1cac7680127a9a425cc61dee/blob b/shared/package-files/76/76dbdbf9216678d48d1640f8fd1e278e7140482e1cac7680127a9a425cc61dee/blob new file mode 100644 index 0000000000000000000000000000000000000000..7cfdaa021f3d4a780e12aa3899f9b14efec45fa1 --- /dev/null +++ b/shared/package-files/76/76dbdbf9216678d48d1640f8fd1e278e7140482e1cac7680127a9a425cc61dee/blob @@ -0,0 +1,43 @@ +# optMenu.tcl -- +# +# This file defines the procedure tk_optionMenu, which creates +# an option button and its associated menu. +# +# Copyright (c) 1994 The Regents of the University of California. +# Copyright (c) 1994 Sun Microsystems, Inc. +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +# ::tk_optionMenu -- +# This procedure creates an option button named $w and an associated +# menu. Together they provide the functionality of Motif option menus: +# they can be used to select one of many values, and the current value +# appears in the global variable varName, as well as in the text of +# the option menubutton. The name of the menu is returned as the +# procedure's result, so that the caller can use it to change configuration +# options on the menu or otherwise manipulate it. +# +# Arguments: +# w - The name to use for the menubutton. +# varName - Global variable to hold the currently selected value. +# firstValue - First of legal values for option (must be >= 1). +# args - Any number of additional values. + +proc ::tk_optionMenu {w varName firstValue args} { + upvar #0 $varName var + + if {![info exists var]} { + set var $firstValue + } + menubutton $w -textvariable $varName -indicatoron 1 -menu $w.menu \ + -relief raised -highlightthickness 1 -anchor c \ + -direction flush + menu $w.menu -tearoff 0 + $w.menu add radiobutton -label $firstValue -variable $varName + foreach i $args { + $w.menu add radiobutton -label $i -variable $varName + } + return $w.menu +} diff --git a/shared/package-files/76/76de09700f183b048bbc910cc209501c38ee9f9c47e1c459dcd53a450536a4a9/blob b/shared/package-files/76/76de09700f183b048bbc910cc209501c38ee9f9c47e1c459dcd53a450536a4a9/blob new file mode 100644 index 0000000000000000000000000000000000000000..db51362ce03907ee7c86c0995836e6d5d18160c6 --- /dev/null +++ b/shared/package-files/76/76de09700f183b048bbc910cc209501c38ee9f9c47e1c459dcd53a450536a4a9/blob @@ -0,0 +1,205 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * Original header comment appears below. + */ + +/* An implementation of the digamma function for complex arguments. + * + * Author: Josh Wilson + * + * Distributed under the same license as Scipy. + * + * Sources: + * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov + * + * [2] mpmath (version 0.19), http://mpmath.org + */ + +#pragma once + +#include "cephes/psi.h" +#include "cephes/zeta.h" +#include "config.h" +#include "error.h" +#include "trig.h" + +namespace xsf { +namespace detail { + // All of the following were computed with mpmath + // Location of the positive root + constexpr double digamma_posroot = 1.4616321449683623; + // Value of the positive root + constexpr double digamma_posrootval = -9.2412655217294275e-17; + // Location of the negative root + constexpr double digamma_negroot = -0.504083008264455409; + // Value of the negative root + constexpr double digamma_negrootval = 7.2897639029768949e-17; + + template + XSF_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) { + T res = rootval; + T coeff = -1.0; + + z = z - root; + T term; + for (int n = 1; n < 100; n++) { + coeff *= -z; + term = coeff * cephes::zeta(n + 1, root); + res += term; + if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) { + break; + } + } + return res; + } + + XSF_HOST_DEVICE inline std::complex + digamma_forward_recurrence(std::complex z, std::complex psiz, int n) { + /* Compute digamma(z + n) using digamma(z) using the recurrence + * relation + * + * digamma(z + 1) = digamma(z) + 1/z. + * + * See https://dlmf.nist.gov/5.5#E2 */ + std::complex res = psiz; + + for (int k = 0; k < n; k++) { + res += 1.0 / (z + static_cast(k)); + } + return res; + } + + XSF_HOST_DEVICE inline std::complex + digamma_backward_recurrence(std::complex z, std::complex psiz, int n) { + /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */ + std::complex res = psiz; + + for (int k = 1; k < n + 1; k++) { + res -= 1.0 / (z - static_cast(k)); + } + return res; + } + + XSF_HOST_DEVICE inline std::complex digamma_asymptotic_series(std::complex z) { + /* Evaluate digamma using an asymptotic series. See + * + * https://dlmf.nist.gov/5.11#E2 */ + double bernoulli2k[] = {0.166666666666666667, -0.0333333333333333333, 0.0238095238095238095, + -0.0333333333333333333, 0.0757575757575757576, -0.253113553113553114, + 1.16666666666666667, -7.09215686274509804, 54.9711779448621554, + -529.124242424242424, 6192.12318840579710, -86580.2531135531136, + 1425517.16666666667, -27298231.0678160920, 601580873.900642368, + -15116315767.0921569}; + std::complex rzz = 1.0 / z / z; + std::complex zfac = 1.0; + std::complex term; + std::complex res; + + if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) { + /* Check for infinity (or nan) and return early. + * Result of division by complex infinity is implementation dependent. + * and has been observed to vary between C++ stdlib and CUDA stdlib. + */ + return std::log(z); + } + + res = std::log(z) - 0.5 / z; + + for (int k = 1; k < 17; k++) { + zfac *= rzz; + term = -bernoulli2k[k - 1] * zfac / (2 * static_cast(k)); + res += term; + if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) { + break; + } + } + return res; + } + +} // namespace detail + +XSF_HOST_DEVICE inline double digamma(double z) { + /* Wrap Cephes' psi to take advantage of the series expansion around + * the smallest negative zero. + */ + if (std::abs(z - detail::digamma_negroot) < 0.3) { + return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval); + } + return cephes::psi(z); +} + +XSF_HOST_DEVICE inline float digamma(float z) { return static_cast(digamma(static_cast(z))); } + +XSF_HOST_DEVICE inline std::complex digamma(std::complex z) { + /* + * Compute the digamma function for complex arguments. The strategy + * is: + * + * - Around the two zeros closest to the origin (posroot and negroot) + * use a Taylor series with precomputed zero order coefficient. + * - If close to the origin, use a recurrence relation to step away + * from the origin. + * - If close to the negative real axis, use the reflection formula + * to move to the right halfplane. + * - If |z| is large (> 16), use the asymptotic series. + * - If |z| is small, use a recurrence relation to make |z| large + * enough to use the asymptotic series. + */ + double absz = std::abs(z); + std::complex res = 0; + /* Use the asymptotic series for z away from the negative real axis + * with abs(z) > smallabsz. */ + int smallabsz = 16; + /* Use the reflection principle for z with z.real < 0 that are within + * smallimag of the negative real axis. + * int smallimag = 6 # unused below except in a comment */ + + if (z.real() <= 0.0 && std::ceil(z.real()) == z) { + // Poles + set_error("digamma", SF_ERROR_SINGULAR, NULL); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (std::abs(z - detail::digamma_negroot) < 0.3) { + // First negative root. + return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval); + } + + if (z.real() < 0 and std::abs(z.imag()) < smallabsz) { + /* Reflection formula for digamma. See + * + *https://dlmf.nist.gov/5.5#E4 + */ + res = -M_PI * cospi(z) / sinpi(z); + z = 1.0 - z; + absz = std::abs(z); + } + + if (absz < 0.5) { + /* Use one step of the recurrence relation to step away from + * the pole. */ + res = -1.0 / z; + z += 1.0; + absz = std::abs(z); + } + + if (std::abs(z - detail::digamma_posroot) < 0.5) { + res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval); + } else if (absz > smallabsz) { + res += detail::digamma_asymptotic_series(z); + } else if (z.real() >= 0.0) { + double n = std::trunc(smallabsz - absz) + 1; + std::complex init = detail::digamma_asymptotic_series(z + n); + res += detail::digamma_backward_recurrence(z + n, init, n); + } else { + // z.real() < 0, absz < smallabsz, and z.imag() > smallimag + double n = std::trunc(smallabsz - absz) - 1; + std::complex init = detail::digamma_asymptotic_series(z - n); + res += detail::digamma_forward_recurrence(z - n, init, n); + } + return res; +} + +XSF_HOST_DEVICE inline std::complex digamma(std::complex z) { + return static_cast>(digamma(static_cast>(z))); +} + +} // namespace xsf diff --git a/shared/package-files/76/76de4327fa9b0d9944334488b8df3b254e372477d595bf0e7a9a7be8a0efe6dc/blob b/shared/package-files/76/76de4327fa9b0d9944334488b8df3b254e372477d595bf0e7a9a7be8a0efe6dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..70bced70fd37c3c681915492cea0c68c87cf0a7e --- /dev/null +++ b/shared/package-files/76/76de4327fa9b0d9944334488b8df3b254e372477d595bf0e7a9a7be8a0efe6dc/blob @@ -0,0 +1,178 @@ +from collections import OrderedDict +from functools import partial +from typing import Any, Dict, Optional + +from torch import nn, Tensor +from torch.nn import functional as F + +from ...transforms._presets import SemanticSegmentation +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights, MobileNetV3 + + +__all__ = ["LRASPP", "LRASPP_MobileNet_V3_Large_Weights", "lraspp_mobilenet_v3_large"] + + +class LRASPP(nn.Module): + """ + Implements a Lite R-ASPP Network for semantic segmentation from + `"Searching for MobileNetV3" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "high" for the high level feature map and "low" for the low level feature map. + low_channels (int): the number of channels of the low level features. + high_channels (int): the number of channels of the high level features. + num_classes (int, optional): number of output classes of the model (including the background). + inter_channels (int, optional): the number of channels for intermediate computations. + """ + + def __init__( + self, backbone: nn.Module, low_channels: int, high_channels: int, num_classes: int, inter_channels: int = 128 + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.backbone = backbone + self.classifier = LRASPPHead(low_channels, high_channels, num_classes, inter_channels) + + def forward(self, input: Tensor) -> Dict[str, Tensor]: + features = self.backbone(input) + out = self.classifier(features) + out = F.interpolate(out, size=input.shape[-2:], mode="bilinear", align_corners=False) + + result = OrderedDict() + result["out"] = out + + return result + + +class LRASPPHead(nn.Module): + def __init__(self, low_channels: int, high_channels: int, num_classes: int, inter_channels: int) -> None: + super().__init__() + self.cbr = nn.Sequential( + nn.Conv2d(high_channels, inter_channels, 1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU(inplace=True), + ) + self.scale = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(high_channels, inter_channels, 1, bias=False), + nn.Sigmoid(), + ) + self.low_classifier = nn.Conv2d(low_channels, num_classes, 1) + self.high_classifier = nn.Conv2d(inter_channels, num_classes, 1) + + def forward(self, input: Dict[str, Tensor]) -> Tensor: + low = input["low"] + high = input["high"] + + x = self.cbr(high) + s = self.scale(high) + x = x * s + x = F.interpolate(x, size=low.shape[-2:], mode="bilinear", align_corners=False) + + return self.low_classifier(low) + self.high_classifier(x) + + +def _lraspp_mobilenetv3(backbone: MobileNetV3, num_classes: int) -> LRASPP: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + low_pos = stage_indices[-4] # use C2 here which has output_stride = 8 + high_pos = stage_indices[-1] # use C5 which has output_stride = 16 + low_channels = backbone[low_pos].out_channels + high_channels = backbone[high_pos].out_channels + backbone = IntermediateLayerGetter(backbone, return_layers={str(low_pos): "low", str(high_pos): "high"}) + + return LRASPP(backbone, low_channels, high_channels, num_classes) + + +class LRASPP_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/lraspp_mobilenet_v3_large-d234d4ea.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + "num_params": 3221538, + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#lraspp_mobilenet_v3_large", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 57.9, + "pixel_acc": 91.2, + } + }, + "_ops": 2.086, + "_file_size": 12.49, + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the + Pascal VOC dataset. + """, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", LRASPP_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def lraspp_mobilenet_v3_large( + *, + weights: Optional[LRASPP_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> LRASPP: + """Constructs a Lite R-ASPP Network model with a MobileNetV3-Large backbone from + `Searching for MobileNetV3 `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.LRASPP`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights + :members: + """ + if kwargs.pop("aux_loss", False): + raise NotImplementedError("This model does not use auxiliary loss") + + weights = LRASPP_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 21 + + backbone = mobilenet_v3_large(weights=weights_backbone, dilated=True) + model = _lraspp_mobilenetv3(backbone, num_classes) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/shared/package-files/76/76dee4ef39b8542e1dfca0837758a69e0afc1e66f33b0b278ece0fb129a93d8d/blob b/shared/package-files/76/76dee4ef39b8542e1dfca0837758a69e0afc1e66f33b0b278ece0fb129a93d8d/blob new file mode 100644 index 0000000000000000000000000000000000000000..42e5c98120c1fee01334a70d4a1b74409be58b1b Binary files /dev/null and b/shared/package-files/76/76dee4ef39b8542e1dfca0837758a69e0afc1e66f33b0b278ece0fb129a93d8d/blob differ diff --git a/shared/package-files/76/76df3f0d32e75c754bfef6e19ee204e4aee48c870ed76ec4d849f899e16a80a0/predict.py b/shared/package-files/76/76df3f0d32e75c754bfef6e19ee204e4aee48c870ed76ec4d849f899e16a80a0/predict.py new file mode 100644 index 0000000000000000000000000000000000000000..473ddbb5e454ffe580b2ee388108b84b1fb82e40 --- /dev/null +++ b/shared/package-files/76/76df3f0d32e75c754bfef6e19ee204e4aee48c870ed76ec4d849f899e16a80a0/predict.py @@ -0,0 +1,134 @@ +"""Fixed cross-radius candidate-score ensemble; all features derive from public input.""" +import argparse,hashlib,json,os +from collections import defaultdict +from concurrent.futures import ProcessPoolExecutor +from contextlib import nullcontext +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F +from model import PeakTransformer +from metric_transform import normalized_covariance_shrink +from features import features,candidate_features,mass_likelihood +from prior_features import descriptors,standardized_score as descriptor_standardized_score +from information_features import prior_multiplier +from property_features import public_features as conditional_public_features +from prior_features import transformed as descriptor_transformed + +def candidate_features_with_descriptors(smiles): + return candidate_features(smiles),descriptors(smiles) + +def digest(path): + h=hashlib.sha256() + with path.open('rb')as f: + for block in iter(lambda:f.read(1<<20),b''):h.update(block) + return h.hexdigest() + +def main(): + parser=argparse.ArgumentParser();parser.add_argument('input_root',type=Path);parser.add_argument('output_root',type=Path);parser.add_argument('--scores-output',type=Path);parser.add_argument('--base-scores-output',type=Path);args=parser.parse_args() + torch.set_num_threads(4);root=Path(__file__).resolve().parent;manifest=json.loads((root/'model_manifest.json').read_text());path=root/manifest['checkpoint']['path'];assert path.resolve().is_relative_to(root) and digest(path)==manifest['checkpoint']['sha256'] + state=torch.load(path,map_location='cpu',weights_only=True);cfg=json.loads((root/manifest['model_config']).read_text());assert cfg==state['model_config'];assert len(state['state_dicts'])==len(cfg['members']) + device='cuda' if torch.cuda.is_available() else 'cpu';models=[] + for weights,member in zip(state['state_dicts'],cfg['members']): + model=PeakTransformer(**member).to(device).eval();model.load_state_dict(weights);models.append(model) + molecular_prior_weight=state['molecular_prior_weight'].cpu().numpy();prior_config=cfg['molecular_prior'] + assert molecular_prior_weight.shape==(4096,) and prior_config['scale']>0 + secondary_prior_weight=state['secondary_molecular_prior_weight'].cpu().numpy();secondary_config=prior_config['secondary'] + assert secondary_prior_weight.shape==(4096,) and secondary_config['scale']>0 + sodium_config=prior_config['sodium'];sodium_weights=[state['sodium_radius'+str(radius)+'_prior_weight'].cpu().numpy() for radius in [2,3]] + assert all(v.shape==(4096,) for v in sodium_weights) + descriptor_config=prior_config['descriptor'];descriptor_parameters={} + for domain in ['global','sodium']: + descriptor_parameters[domain]={k:v.cpu().numpy() for k,v in state['descriptor_prior_states'][domain].items()} + descriptor_parameters[domain].update({k:descriptor_config[domain][k] for k in ['center','scale','clip']}) + conditional_config=cfg['conditional_descriptor'];conditional_state={k:v.cpu().numpy() for k,v in state['conditional_descriptor_state'].items()} + rank_weights=[v.to(device).sqrt() for v in state['group_fingerprint_weights']] + covariance=cfg['fingerprint_covariance_transform'];assert covariance['score_group_index']==0 and covariance['rank']==256 and covariance['damping']==.75 + covariance_basis=state['fingerprint_covariance_basis'].to(device);assert covariance_basis.shape==(4096,256) and covariance_basis.dtype==torch.float32 + assert cfg['score_groups'][0]['radius']==2 and not cfg['score_groups'][0]['allow_tf32'];del state + queries=[json.loads(line) for line in(args.input_root/'queries.jsonl').open() if line.strip()];pools={p['candidate_pool_id']:p['candidates'] for p in map(json.loads,(args.input_root/'candidate_pools.jsonl').open())} + args.output_root.mkdir(parents=True,exist_ok=True) + if any(args.output_root.iterdir()):raise ValueError('output must start empty') + if not queries: + (args.output_root/'rankings.jsonl').touch() + if args.scores_output:args.scores_output.write_text('') + if args.base_scores_output:args.base_scores_output.write_text('') + return + grouped=defaultdict(list) + for i,q in enumerate(queries):grouped[q['candidate_pool_id']].append(i) + smiles=sorted({c['smiles'] for pid in grouped for c in pools[pid]});sidx={s:i for i,s in enumerate(smiles)} + with ProcessPoolExecutor(cfg['inference_workers'])as workers:combined=list(workers.map(candidate_features_with_descriptors,smiles,chunksize=128)) + cf=[v[0] for v in combined];descriptor_features=np.stack([v[1][0] for v in combined]);descriptor_valid=np.asarray([v[1][1] for v in combined],dtype=bool);del combined + fingerprints=[np.stack([v[i] for v in cf]) for i in range(2)];masses=np.asarray([v[2] for v in cf],dtype=np.float64);del cf + molecular_prior=np.empty(len(smiles),dtype=np.float32) + for st in range(0,len(smiles),8192): + block=fingerprints[0][st:st+8192];linear=block.astype(np.float32)@molecular_prior_weight + molecular_prior[st:st+len(block)]=np.where(block.any(axis=1),np.clip((linear-prior_config['center'])/prior_config['scale'],-prior_config['clip'],prior_config['clip']),0.) + secondary_prior=np.empty(len(smiles),dtype=np.float32) + for st in range(0,len(smiles),8192): + block=fingerprints[1][st:st+8192];linear=block.astype(np.float32)@secondary_prior_weight + secondary_prior[st:st+len(block)]=np.where(block.any(axis=1),np.clip((linear-secondary_config['center'])/secondary_config['scale'],-secondary_config['clip'],secondary_config['clip']),0.) + molecular_prior=prior_config['primary_fraction']*molecular_prior+(1.-prior_config['primary_fraction'])*secondary_prior + sodium_components=[] + for fi,radius in enumerate([2,3]): + config=sodium_config['radius'+str(radius)];values=np.empty(len(smiles),dtype=np.float32);assert config['scale']>0 + for st in range(0,len(smiles),8192): + block=fingerprints[fi][st:st+8192];linear=block.astype(np.float32)@sodium_weights[fi] + values[st:st+len(block)]=np.where(block.any(axis=1),np.clip((linear-config['center'])/config['scale'],-config['clip'],config['clip']),0.) + sodium_components.append(values) + sodium_prior=sodium_config['radius2_fraction']*sodium_components[0]+(1.-sodium_config['radius2_fraction'])*sodium_components[1] + descriptor_values={domain:np.where(descriptor_valid,descriptor_standardized_score(descriptor_features,descriptor_parameters[domain]),0.).astype(np.float32) for domain in ['global','sodium']} + fraction=descriptor_config['fraction'];molecular_prior=(1.-fraction)*molecular_prior+fraction*descriptor_values['global'];sodium_prior=(1.-fraction)*sodium_prior+fraction*descriptor_values['sodium'] + conditional_descriptors=np.clip((descriptor_transformed(descriptor_features)-conditional_state['descriptor_center'])/conditional_state['descriptor_scale'],-5.,5.) + conditional_valid=descriptor_valid + del descriptor_features,descriptor_valid + conditional_features=[] + for q in queries: + value,names=conditional_public_features(q);assert names==conditional_config['public_feature_names'];conditional_features.append(value) + conditional_X=np.clip((np.stack(conditional_features)-conditional_state['spectrum_center'])/conditional_state['spectrum_scale'],-5.,5.) + conditional_projection=conditional_X@conditional_state['weight'] + del conditional_features,conditional_X + predictions=[[] for _ in cfg['score_groups']] + with torch.inference_mode(): + for st in range(0,len(queries),512): + raw,meta=zip(*(features(q) for q in queries[st:st+512]));tensors=[torch.from_numpy(np.stack(v)).to(device) for v in(raw,meta)];probabilities=[] + for model in models: + with torch.autocast(device_type=device,dtype=torch.bfloat16,enabled=device=='cuda'):logits=model(*tensors) + probabilities.append(logits.float().sigmoid()) + for gi,group in enumerate(cfg['score_groups']): + mean=torch.stack([probabilities[i] for i in group['member_indices']]).mean(0);value=F.normalize(mean*rank_weights[gi],dim=-1) + if gi==covariance['score_group_index']: + torch.backends.cuda.matmul.allow_tf32=False;value=normalized_covariance_shrink(value,covariance_basis,covariance['damping']) + predictions[gi].append(value.cpu()) + predictions=[torch.cat(parts) for parts in predictions] + partial=args.output_root/'rankings.jsonl.tmp' + with partial.open('w')as output,(args.scores_output.open('w') if args.scores_output else nullcontext(None))as scores_output,(args.base_scores_output.open('w') if args.base_scores_output else nullcontext(None))as base_scores_output: + for pool_id in sorted(grouped): + candidates=sorted(pools[pool_id],key=lambda c:c['candidate_id']);mi=[sidx[c['smiles']] for c in candidates];fps=[F.normalize(torch.from_numpy(fp[mi]).to(device).float()*wt,dim=-1) for fp,wt in zip(fingerprints,rank_weights)] + torch.backends.cuda.matmul.allow_tf32=False;gi=covariance['score_group_index'];fps[gi]=normalized_covariance_shrink(fps[gi],covariance_basis,covariance['damping']) + strength=float(cfg['candidate_pool_centering']['strength']);assert strength==1. + centers=[fp.mean(dim=0,keepdim=True)*strength for fp in fps] + centered_fps=[F.normalize(fp-center,dim=-1) for fp,center in zip(fps,centers)] if len(candidates)>1 else fps + for st in range(0,len(grouped[pool_id]),512): + indices=grouped[pool_id][st:st+512];scores=np.zeros((len(indices),len(candidates)),dtype=np.float32) + for gi,group in enumerate(cfg['score_groups']): + torch.backends.cuda.matmul.allow_tf32=group['allow_tf32'];query=predictions[gi][indices].to(device) + if len(candidates)>1:query=F.normalize(query-centers[gi],dim=-1) + score=(query@centered_fps[gi].T).cpu().numpy();scores+=group['coefficient']*score + scores+=cfg['mass_coefficient']*mass_likelihood([queries[i] for i in indices],masses[mi],cfg) + is_sodium=np.asarray([queries[i]['adduct']==sodium_config['adduct'] for i in indices],dtype=bool) + selected_prior=np.where(is_sodium[:,None],sodium_prior[mi][None,:],molecular_prior[mi][None,:]) + information=prior_config['information_scaling'];factors=np.asarray([prior_multiplier(queries[i],information['TRAIN_median_effective_fragment_peaks'],information['exponent']) for i in indices],dtype=np.float32)[:,None] + scores+=prior_config['coefficient']*factors*selected_prior + if base_scores_output is not None: + for i,values in zip(indices,scores): + base_scores_output.write(json.dumps({'query_id':queries[i]['query_id'],'candidate_ids':[c['candidate_id'] for c in candidates],'scores':values.tolist()},separators=(',',':'))+'\n') + extra=np.clip((conditional_projection[indices]@conditional_descriptors[mi].T-float(conditional_state['score_center']))/float(conditional_state['score_scale']),-float(conditional_state['score_clip']),float(conditional_state['score_clip'])) + extra[:,~conditional_valid[mi]]=0. + scores=scores.astype(np.float64)+conditional_config['coefficient']*extra + for i,values in zip(indices,scores): + cids=[c['candidate_id'] for c in candidates];order=np.argsort(-values,kind='stable');output.write(json.dumps({'query_id':queries[i]['query_id'],'ranking':[cids[j] for j in order]},separators=(',',':'))+'\n') + if scores_output is not None:scores_output.write(json.dumps({'query_id':queries[i]['query_id'],'candidate_ids':cids,'scores':values.tolist()},separators=(',',':'))+'\n') + os.replace(partial,args.output_root/'rankings.jsonl') + +if __name__=='__main__':main() diff --git a/shared/package-files/76/76e47d0d02d4a51bb2f5bbf464a40fb7d832f56c625ff2b4f8154c96717e5876/blob b/shared/package-files/76/76e47d0d02d4a51bb2f5bbf464a40fb7d832f56c625ff2b4f8154c96717e5876/blob new file mode 100644 index 0000000000000000000000000000000000000000..cffa8bb22c186bd05ee2bf67b066263997f9fb69 --- /dev/null +++ b/shared/package-files/76/76e47d0d02d4a51bb2f5bbf464a40fb7d832f56c625ff2b4f8154c96717e5876/blob @@ -0,0 +1,657 @@ +import pytest + +import networkx as nx +from networkx.generators import directed + +# Unit tests for the :func:`~networkx.weisfeiler_lehman_graph_hash` function + + +def test_empty_graph_hash(): + """ + empty graphs should give hashes regardless of other params + """ + G1 = nx.empty_graph() + G2 = nx.empty_graph() + + h1 = nx.weisfeiler_lehman_graph_hash(G1) + h2 = nx.weisfeiler_lehman_graph_hash(G2) + h3 = nx.weisfeiler_lehman_graph_hash(G2, edge_attr="edge_attr1") + h4 = nx.weisfeiler_lehman_graph_hash(G2, node_attr="node_attr1") + h5 = nx.weisfeiler_lehman_graph_hash( + G2, edge_attr="edge_attr1", node_attr="node_attr1" + ) + h6 = nx.weisfeiler_lehman_graph_hash(G2, iterations=10) + + assert h1 == h2 + assert h1 == h3 + assert h1 == h4 + assert h1 == h5 + assert h1 == h6 + + +def test_directed(): + """ + A directed graph with no bi-directional edges should yield different a graph hash + to the same graph taken as undirected if there are no hash collisions. + """ + r = 10 + for i in range(r): + G_directed = nx.gn_graph(10 + r, seed=100 + i) + G_undirected = nx.to_undirected(G_directed) + + h_directed = nx.weisfeiler_lehman_graph_hash(G_directed) + h_undirected = nx.weisfeiler_lehman_graph_hash(G_undirected) + + assert h_directed != h_undirected + + +def test_reversed(): + """ + A directed graph with no bi-directional edges should yield different a graph hash + to the same graph taken with edge directions reversed if there are no hash collisions. + Here we test a cycle graph which is the minimal counterexample + """ + G = nx.cycle_graph(5, create_using=nx.DiGraph) + nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label") + + G_reversed = G.reverse() + + h = nx.weisfeiler_lehman_graph_hash(G, node_attr="label") + h_reversed = nx.weisfeiler_lehman_graph_hash(G_reversed, node_attr="label") + + assert h != h_reversed + + +def test_isomorphic(): + """ + graph hashes should be invariant to node-relabeling (when the output is reindexed + by the same mapping) + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i) + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g1_hash = nx.weisfeiler_lehman_graph_hash(G1) + g2_hash = nx.weisfeiler_lehman_graph_hash(G2) + + assert g1_hash == g2_hash + + +def test_isomorphic_edge_attr(): + """ + Isomorphic graphs with differing edge attributes should yield different graph + hashes if the 'edge_attr' argument is supplied and populated in the graph, + and there are no hash collisions. + The output should still be invariant to node-relabeling + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i) + + for a, b in G1.edges: + G1[a][b]["edge_attr1"] = f"{a}-{b}-1" + G1[a][b]["edge_attr2"] = f"{a}-{b}-2" + + g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash( + G1, edge_attr="edge_attr1" + ) + g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash( + G1, edge_attr="edge_attr2" + ) + g1_hash_no_edge_attr = nx.weisfeiler_lehman_graph_hash(G1, edge_attr=None) + + assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr + assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr + assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2 + + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_graph_hash( + G2, edge_attr="edge_attr1" + ) + g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_graph_hash( + G2, edge_attr="edge_attr2" + ) + + assert g1_hash_with_edge_attr1 == g2_hash_with_edge_attr1 + assert g1_hash_with_edge_attr2 == g2_hash_with_edge_attr2 + + +def test_missing_edge_attr(): + """ + If the 'edge_attr' argument is supplied but is missing from an edge in the graph, + we should raise a KeyError + """ + G = nx.Graph() + G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})]) + pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, edge_attr="edge_attr1") + + +def test_isomorphic_node_attr(): + """ + Isomorphic graphs with differing node attributes should yield different graph + hashes if the 'node_attr' argument is supplied and populated in the graph, and + there are no hash collisions. + The output should still be invariant to node-relabeling + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i) + + for u in G1.nodes(): + G1.nodes[u]["node_attr1"] = f"{u}-1" + G1.nodes[u]["node_attr2"] = f"{u}-2" + + g1_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash( + G1, node_attr="node_attr1" + ) + g1_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash( + G1, node_attr="node_attr2" + ) + g1_hash_no_node_attr = nx.weisfeiler_lehman_graph_hash(G1, node_attr=None) + + assert g1_hash_with_node_attr1 != g1_hash_no_node_attr + assert g1_hash_with_node_attr2 != g1_hash_no_node_attr + assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2 + + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g2_hash_with_node_attr1 = nx.weisfeiler_lehman_graph_hash( + G2, node_attr="node_attr1" + ) + g2_hash_with_node_attr2 = nx.weisfeiler_lehman_graph_hash( + G2, node_attr="node_attr2" + ) + + assert g1_hash_with_node_attr1 == g2_hash_with_node_attr1 + assert g1_hash_with_node_attr2 == g2_hash_with_node_attr2 + + +def test_missing_node_attr(): + """ + If the 'node_attr' argument is supplied but is missing from a node in the graph, + we should raise a KeyError + """ + G = nx.Graph() + G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})]) + G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)]) + pytest.raises(KeyError, nx.weisfeiler_lehman_graph_hash, G, node_attr="node_attr1") + + +def test_isomorphic_edge_attr_and_node_attr(): + """ + Isomorphic graphs with differing node attributes should yield different graph + hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in + the graph, and there are no hash collisions. + The output should still be invariant to node-relabeling + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i) + + for u in G1.nodes(): + G1.nodes[u]["node_attr1"] = f"{u}-1" + G1.nodes[u]["node_attr2"] = f"{u}-2" + + for a, b in G1.edges: + G1[a][b]["edge_attr1"] = f"{a}-{b}-1" + G1[a][b]["edge_attr2"] = f"{a}-{b}-2" + + g1_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash( + G1, edge_attr="edge_attr1", node_attr="node_attr1" + ) + g1_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash( + G1, edge_attr="edge_attr2", node_attr="node_attr2" + ) + g1_hash_edge1_node2 = nx.weisfeiler_lehman_graph_hash( + G1, edge_attr="edge_attr1", node_attr="node_attr2" + ) + g1_hash_no_attr = nx.weisfeiler_lehman_graph_hash(G1) + + assert g1_hash_edge1_node1 != g1_hash_no_attr + assert g1_hash_edge2_node2 != g1_hash_no_attr + assert g1_hash_edge1_node1 != g1_hash_edge2_node2 + assert g1_hash_edge1_node2 != g1_hash_edge2_node2 + assert g1_hash_edge1_node2 != g1_hash_edge1_node1 + + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g2_hash_edge1_node1 = nx.weisfeiler_lehman_graph_hash( + G2, edge_attr="edge_attr1", node_attr="node_attr1" + ) + g2_hash_edge2_node2 = nx.weisfeiler_lehman_graph_hash( + G2, edge_attr="edge_attr2", node_attr="node_attr2" + ) + + assert g1_hash_edge1_node1 == g2_hash_edge1_node1 + assert g1_hash_edge2_node2 == g2_hash_edge2_node2 + + +def test_digest_size(): + """ + The hash string lengths should be as expected for a variety of graphs and + digest sizes + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i) + + h16 = nx.weisfeiler_lehman_graph_hash(G) + h32 = nx.weisfeiler_lehman_graph_hash(G, digest_size=32) + + assert h16 != h32 + assert len(h16) == 16 * 2 + assert len(h32) == 32 * 2 + + +# Unit tests for the :func:`~networkx.weisfeiler_lehman_hash_subgraphs` function + + +def is_subiteration(a, b): + """ + returns True if that each hash sequence in 'a' is a prefix for + the corresponding sequence indexed by the same node in 'b'. + """ + return all(b[node][: len(hashes)] == hashes for node, hashes in a.items()) + + +def hexdigest_sizes_correct(a, digest_size): + """ + returns True if all hex digest sizes are the expected length in a node:subgraph-hashes + dictionary. Hex digest string length == 2 * bytes digest length since each pair of hex + digits encodes 1 byte (https://docs.python.org/3/library/hashlib.html) + """ + hexdigest_size = digest_size * 2 + list_digest_sizes_correct = lambda l: all(len(x) == hexdigest_size for x in l) + return all(list_digest_sizes_correct(hashes) for hashes in a.values()) + + +def test_empty_graph_subgraph_hash(): + """ " + empty graphs should give empty dict subgraph hashes regardless of other params + """ + G = nx.empty_graph() + + subgraph_hashes1 = nx.weisfeiler_lehman_subgraph_hashes(G) + subgraph_hashes2 = nx.weisfeiler_lehman_subgraph_hashes(G, edge_attr="edge_attr") + subgraph_hashes3 = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="edge_attr") + subgraph_hashes4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=2) + subgraph_hashes5 = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=64) + + assert subgraph_hashes1 == {} + assert subgraph_hashes2 == {} + assert subgraph_hashes3 == {} + assert subgraph_hashes4 == {} + assert subgraph_hashes5 == {} + + +def test_directed_subgraph_hash(): + """ + A directed graph with no bi-directional edges should yield different subgraph hashes + to the same graph taken as undirected, if all hashes don't collide. + """ + r = 10 + for i in range(r): + G_directed = nx.gn_graph(10 + r, seed=100 + i) + G_undirected = nx.to_undirected(G_directed) + + directed_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_directed) + undirected_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G_undirected) + + assert directed_subgraph_hashes != undirected_subgraph_hashes + + +def test_reversed_subgraph_hash(): + """ + A directed graph with no bi-directional edges should yield different subgraph hashes + to the same graph taken with edge directions reversed if there are no hash collisions. + Here we test a cycle graph which is the minimal counterexample + """ + G = nx.cycle_graph(5, create_using=nx.DiGraph) + nx.set_node_attributes(G, {n: str(n) for n in G.nodes()}, name="label") + + G_reversed = G.reverse() + + h = nx.weisfeiler_lehman_subgraph_hashes(G, node_attr="label") + h_reversed = nx.weisfeiler_lehman_subgraph_hashes(G_reversed, node_attr="label") + + assert h != h_reversed + + +def test_isomorphic_subgraph_hash(): + """ + the subgraph hashes should be invariant to node-relabeling when the output is reindexed + by the same mapping and all hashes don't collide. + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=200 + i) + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g1_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G1) + g2_subgraph_hashes = nx.weisfeiler_lehman_subgraph_hashes(G2) + + assert g1_subgraph_hashes == {-1 * k: v for k, v in g2_subgraph_hashes.items()} + + +def test_isomorphic_edge_attr_subgraph_hash(): + """ + Isomorphic graphs with differing edge attributes should yield different subgraph + hashes if the 'edge_attr' argument is supplied and populated in the graph, and + all hashes don't collide. + The output should still be invariant to node-relabeling + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=300 + i) + + for a, b in G1.edges: + G1[a][b]["edge_attr1"] = f"{a}-{b}-1" + G1[a][b]["edge_attr2"] = f"{a}-{b}-2" + + g1_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes( + G1, edge_attr="edge_attr1" + ) + g1_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes( + G1, edge_attr="edge_attr2" + ) + g1_hash_no_edge_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, edge_attr=None) + + assert g1_hash_with_edge_attr1 != g1_hash_no_edge_attr + assert g1_hash_with_edge_attr2 != g1_hash_no_edge_attr + assert g1_hash_with_edge_attr1 != g1_hash_with_edge_attr2 + + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g2_hash_with_edge_attr1 = nx.weisfeiler_lehman_subgraph_hashes( + G2, edge_attr="edge_attr1" + ) + g2_hash_with_edge_attr2 = nx.weisfeiler_lehman_subgraph_hashes( + G2, edge_attr="edge_attr2" + ) + + assert g1_hash_with_edge_attr1 == { + -1 * k: v for k, v in g2_hash_with_edge_attr1.items() + } + assert g1_hash_with_edge_attr2 == { + -1 * k: v for k, v in g2_hash_with_edge_attr2.items() + } + + +def test_missing_edge_attr_subgraph_hash(): + """ + If the 'edge_attr' argument is supplied but is missing from an edge in the graph, + we should raise a KeyError + """ + G = nx.Graph() + G.add_edges_from([(1, 2, {"edge_attr1": "a"}), (1, 3, {})]) + pytest.raises( + KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, edge_attr="edge_attr1" + ) + + +def test_isomorphic_node_attr_subgraph_hash(): + """ + Isomorphic graphs with differing node attributes should yield different subgraph + hashes if the 'node_attr' argument is supplied and populated in the graph, and + all hashes don't collide. + The output should still be invariant to node-relabeling + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=400 + i) + + for u in G1.nodes(): + G1.nodes[u]["node_attr1"] = f"{u}-1" + G1.nodes[u]["node_attr2"] = f"{u}-2" + + g1_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes( + G1, node_attr="node_attr1" + ) + g1_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes( + G1, node_attr="node_attr2" + ) + g1_hash_no_node_attr = nx.weisfeiler_lehman_subgraph_hashes(G1, node_attr=None) + + assert g1_hash_with_node_attr1 != g1_hash_no_node_attr + assert g1_hash_with_node_attr2 != g1_hash_no_node_attr + assert g1_hash_with_node_attr1 != g1_hash_with_node_attr2 + + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g2_hash_with_node_attr1 = nx.weisfeiler_lehman_subgraph_hashes( + G2, node_attr="node_attr1" + ) + g2_hash_with_node_attr2 = nx.weisfeiler_lehman_subgraph_hashes( + G2, node_attr="node_attr2" + ) + + assert g1_hash_with_node_attr1 == { + -1 * k: v for k, v in g2_hash_with_node_attr1.items() + } + assert g1_hash_with_node_attr2 == { + -1 * k: v for k, v in g2_hash_with_node_attr2.items() + } + + +def test_missing_node_attr_subgraph_hash(): + """ + If the 'node_attr' argument is supplied but is missing from a node in the graph, + we should raise a KeyError + """ + G = nx.Graph() + G.add_nodes_from([(1, {"node_attr1": "a"}), (2, {})]) + G.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 4)]) + pytest.raises( + KeyError, nx.weisfeiler_lehman_subgraph_hashes, G, node_attr="node_attr1" + ) + + +def test_isomorphic_edge_attr_and_node_attr_subgraph_hash(): + """ + Isomorphic graphs with differing node attributes should yield different subgraph + hashes if the 'node_attr' and 'edge_attr' argument is supplied and populated in + the graph, and all hashes don't collide + The output should still be invariant to node-relabeling + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G1 = nx.erdos_renyi_graph(n, p * i, seed=500 + i) + + for u in G1.nodes(): + G1.nodes[u]["node_attr1"] = f"{u}-1" + G1.nodes[u]["node_attr2"] = f"{u}-2" + + for a, b in G1.edges: + G1[a][b]["edge_attr1"] = f"{a}-{b}-1" + G1[a][b]["edge_attr2"] = f"{a}-{b}-2" + + g1_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes( + G1, edge_attr="edge_attr1", node_attr="node_attr1" + ) + g1_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes( + G1, edge_attr="edge_attr2", node_attr="node_attr2" + ) + g1_hash_edge1_node2 = nx.weisfeiler_lehman_subgraph_hashes( + G1, edge_attr="edge_attr1", node_attr="node_attr2" + ) + g1_hash_no_attr = nx.weisfeiler_lehman_subgraph_hashes(G1) + + assert g1_hash_edge1_node1 != g1_hash_no_attr + assert g1_hash_edge2_node2 != g1_hash_no_attr + assert g1_hash_edge1_node1 != g1_hash_edge2_node2 + assert g1_hash_edge1_node2 != g1_hash_edge2_node2 + assert g1_hash_edge1_node2 != g1_hash_edge1_node1 + + G2 = nx.relabel_nodes(G1, {u: -1 * u for u in G1.nodes()}) + + g2_hash_edge1_node1 = nx.weisfeiler_lehman_subgraph_hashes( + G2, edge_attr="edge_attr1", node_attr="node_attr1" + ) + g2_hash_edge2_node2 = nx.weisfeiler_lehman_subgraph_hashes( + G2, edge_attr="edge_attr2", node_attr="node_attr2" + ) + + assert g1_hash_edge1_node1 == { + -1 * k: v for k, v in g2_hash_edge1_node1.items() + } + assert g1_hash_edge2_node2 == { + -1 * k: v for k, v in g2_hash_edge2_node2.items() + } + + +def test_iteration_depth(): + """ + All nodes should have the correct number of subgraph hashes in the output when + using degree as initial node labels + Subsequent iteration depths for the same graph should be additive for each node + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G = nx.erdos_renyi_graph(n, p * i, seed=600 + i) + + depth3 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=3) + depth4 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=4) + depth5 = nx.weisfeiler_lehman_subgraph_hashes(G, iterations=5) + + assert all(len(hashes) == 3 for hashes in depth3.values()) + assert all(len(hashes) == 4 for hashes in depth4.values()) + assert all(len(hashes) == 5 for hashes in depth5.values()) + + assert is_subiteration(depth3, depth4) + assert is_subiteration(depth4, depth5) + assert is_subiteration(depth3, depth5) + + +def test_iteration_depth_edge_attr(): + """ + All nodes should have the correct number of subgraph hashes in the output when + setting initial node labels empty and using an edge attribute when aggregating + neighborhoods. + Subsequent iteration depths for the same graph should be additive for each node + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G = nx.erdos_renyi_graph(n, p * i, seed=700 + i) + + for a, b in G.edges: + G[a][b]["edge_attr1"] = f"{a}-{b}-1" + + depth3 = nx.weisfeiler_lehman_subgraph_hashes( + G, edge_attr="edge_attr1", iterations=3 + ) + depth4 = nx.weisfeiler_lehman_subgraph_hashes( + G, edge_attr="edge_attr1", iterations=4 + ) + depth5 = nx.weisfeiler_lehman_subgraph_hashes( + G, edge_attr="edge_attr1", iterations=5 + ) + + assert all(len(hashes) == 3 for hashes in depth3.values()) + assert all(len(hashes) == 4 for hashes in depth4.values()) + assert all(len(hashes) == 5 for hashes in depth5.values()) + + assert is_subiteration(depth3, depth4) + assert is_subiteration(depth4, depth5) + assert is_subiteration(depth3, depth5) + + +def test_iteration_depth_node_attr(): + """ + All nodes should have the correct number of subgraph hashes in the output when + setting initial node labels to an attribute. + Subsequent iteration depths for the same graph should be additive for each node + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G = nx.erdos_renyi_graph(n, p * i, seed=800 + i) + + for u in G.nodes(): + G.nodes[u]["node_attr1"] = f"{u}-1" + + depth3 = nx.weisfeiler_lehman_subgraph_hashes( + G, node_attr="node_attr1", iterations=3 + ) + depth4 = nx.weisfeiler_lehman_subgraph_hashes( + G, node_attr="node_attr1", iterations=4 + ) + depth5 = nx.weisfeiler_lehman_subgraph_hashes( + G, node_attr="node_attr1", iterations=5 + ) + + assert all(len(hashes) == 3 for hashes in depth3.values()) + assert all(len(hashes) == 4 for hashes in depth4.values()) + assert all(len(hashes) == 5 for hashes in depth5.values()) + + assert is_subiteration(depth3, depth4) + assert is_subiteration(depth4, depth5) + assert is_subiteration(depth3, depth5) + + +def test_iteration_depth_node_edge_attr(): + """ + All nodes should have the correct number of subgraph hashes in the output when + setting initial node labels to an attribute and also using an edge attribute when + aggregating neighborhoods. + Subsequent iteration depths for the same graph should be additive for each node + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G = nx.erdos_renyi_graph(n, p * i, seed=900 + i) + + for u in G.nodes(): + G.nodes[u]["node_attr1"] = f"{u}-1" + + for a, b in G.edges: + G[a][b]["edge_attr1"] = f"{a}-{b}-1" + + depth3 = nx.weisfeiler_lehman_subgraph_hashes( + G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=3 + ) + depth4 = nx.weisfeiler_lehman_subgraph_hashes( + G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=4 + ) + depth5 = nx.weisfeiler_lehman_subgraph_hashes( + G, edge_attr="edge_attr1", node_attr="node_attr1", iterations=5 + ) + + assert all(len(hashes) == 3 for hashes in depth3.values()) + assert all(len(hashes) == 4 for hashes in depth4.values()) + assert all(len(hashes) == 5 for hashes in depth5.values()) + + assert is_subiteration(depth3, depth4) + assert is_subiteration(depth4, depth5) + assert is_subiteration(depth3, depth5) + + +def test_digest_size_subgraph_hash(): + """ + The hash string lengths should be as expected for a variety of graphs and + digest sizes + """ + n, r = 100, 10 + p = 1.0 / r + for i in range(1, r + 1): + G = nx.erdos_renyi_graph(n, p * i, seed=1000 + i) + + digest_size16_hashes = nx.weisfeiler_lehman_subgraph_hashes(G) + digest_size32_hashes = nx.weisfeiler_lehman_subgraph_hashes(G, digest_size=32) + + assert digest_size16_hashes != digest_size32_hashes + + assert hexdigest_sizes_correct(digest_size16_hashes, 16) + assert hexdigest_sizes_correct(digest_size32_hashes, 32) diff --git a/shared/package-files/76/76e491e373a360988c3878edee52d5ad274165aef819046ac09cf944f75b4393/blob b/shared/package-files/76/76e491e373a360988c3878edee52d5ad274165aef819046ac09cf944f75b4393/blob new file mode 100644 index 0000000000000000000000000000000000000000..57f57e56201c872e54e91c4e6da2c2154a07a6d5 --- /dev/null +++ b/shared/package-files/76/76e491e373a360988c3878edee52d5ad274165aef819046ac09cf944f75b4393/blob @@ -0,0 +1,81 @@ +from datetime import ( + datetime, + timedelta, +) + +import pytz + +from pandas._libs.tslibs.timezones import dateutil_gettz as gettz +import pandas.util._test_decorators as td + +from pandas import Timestamp +import pandas._testing as tm + + +class TestTimestampToPyDatetime: + def test_to_pydatetime_fold(self): + # GH#45087 + tzstr = "dateutil/usr/share/zoneinfo/America/Chicago" + ts = Timestamp(year=2013, month=11, day=3, hour=1, minute=0, fold=1, tz=tzstr) + dt = ts.to_pydatetime() + assert dt.fold == 1 + + def test_to_pydatetime_nonzero_nano(self): + ts = Timestamp("2011-01-01 9:00:00.123456789") + + # Warn the user of data loss (nanoseconds). + with tm.assert_produces_warning(UserWarning): + expected = datetime(2011, 1, 1, 9, 0, 0, 123456) + result = ts.to_pydatetime() + assert result == expected + + def test_timestamp_to_datetime(self): + stamp = Timestamp("20090415", tz="US/Eastern") + dtval = stamp.to_pydatetime() + assert stamp == dtval + assert stamp.tzinfo == dtval.tzinfo + + def test_timestamp_to_pydatetime_dateutil(self): + stamp = Timestamp("20090415", tz="dateutil/US/Eastern") + dtval = stamp.to_pydatetime() + assert stamp == dtval + assert stamp.tzinfo == dtval.tzinfo + + def test_timestamp_to_pydatetime_explicit_pytz(self): + stamp = Timestamp("20090415", tz=pytz.timezone("US/Eastern")) + dtval = stamp.to_pydatetime() + assert stamp == dtval + assert stamp.tzinfo == dtval.tzinfo + + @td.skip_if_windows + def test_timestamp_to_pydatetime_explicit_dateutil(self): + stamp = Timestamp("20090415", tz=gettz("US/Eastern")) + dtval = stamp.to_pydatetime() + assert stamp == dtval + assert stamp.tzinfo == dtval.tzinfo + + def test_to_pydatetime_bijective(self): + # Ensure that converting to datetime and back only loses precision + # by going from nanoseconds to microseconds. + exp_warning = None if Timestamp.max.nanosecond == 0 else UserWarning + with tm.assert_produces_warning(exp_warning): + pydt_max = Timestamp.max.to_pydatetime() + + assert ( + Timestamp(pydt_max).as_unit("ns")._value / 1000 + == Timestamp.max._value / 1000 + ) + + exp_warning = None if Timestamp.min.nanosecond == 0 else UserWarning + with tm.assert_produces_warning(exp_warning): + pydt_min = Timestamp.min.to_pydatetime() + + # The next assertion can be enabled once GH#39221 is merged + # assert pydt_min < Timestamp.min # this is bc nanos are dropped + tdus = timedelta(microseconds=1) + assert pydt_min + tdus > Timestamp.min + + assert ( + Timestamp(pydt_min + tdus).as_unit("ns")._value / 1000 + == Timestamp.min._value / 1000 + ) diff --git a/shared/package-files/76/76e6562f11b6af6d42d7fbb198731b144ab3ad5e79525d573f510df4f2916790/blob b/shared/package-files/76/76e6562f11b6af6d42d7fbb198731b144ab3ad5e79525d573f510df4f2916790/blob new file mode 100644 index 0000000000000000000000000000000000000000..f8c5e536184989c77c912f0f9570826685cfe697 Binary files /dev/null and b/shared/package-files/76/76e6562f11b6af6d42d7fbb198731b144ab3ad5e79525d573f510df4f2916790/blob differ diff --git a/shared/package-files/76/76e81480277a418e76c87907b943f88d15b3a39c78dfd2108a06980af105e3a4/blob b/shared/package-files/76/76e81480277a418e76c87907b943f88d15b3a39c78dfd2108a06980af105e3a4/blob new file mode 100644 index 0000000000000000000000000000000000000000..407138caf94e467b52d925f96ad80b506e16d9ec Binary files /dev/null and b/shared/package-files/76/76e81480277a418e76c87907b943f88d15b3a39c78dfd2108a06980af105e3a4/blob differ diff --git a/shared/package-files/76/76e96d837d75527e90e0cd8a4002bd04c3801c9e8c86091d2622af2847cf6a2b/blob b/shared/package-files/76/76e96d837d75527e90e0cd8a4002bd04c3801c9e8c86091d2622af2847cf6a2b/blob new file mode 100644 index 0000000000000000000000000000000000000000..d2b8eac109b20804ffb200e3322910ceb4e080d4 --- /dev/null +++ b/shared/package-files/76/76e96d837d75527e90e0cd8a4002bd04c3801c9e8c86091d2622af2847cf6a2b/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API lstm_cell { + using schema = ::std::tuple (const at::Tensor &, at::TensorList, const at::Tensor &, const at::Tensor &, const c10::optional &, const c10::optional &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::lstm_cell") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & input, at::TensorList hx, const at::Tensor & w_ih, const at::Tensor & w_hh, const c10::optional & b_ih, const c10::optional & b_hh); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::TensorList hx, const at::Tensor & w_ih, const at::Tensor & w_hh, const c10::optional & b_ih, const c10::optional & b_hh); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/76/76e9e750be2cc760b9d026e4655ecfa335f34a868ba0f9fb4d1f18cb7e649a62/blob b/shared/package-files/76/76e9e750be2cc760b9d026e4655ecfa335f34a868ba0f9fb4d1f18cb7e649a62/blob new file mode 100644 index 0000000000000000000000000000000000000000..66b8b82bfe77734dfd0ac224a01cd2fbdbd06717 --- /dev/null +++ b/shared/package-files/76/76e9e750be2cc760b9d026e4655ecfa335f34a868ba0f9fb4d1f18cb7e649a62/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void _validate_compressed_sparse_indices_cpu(bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz); +TORCH_API void _validate_compressed_sparse_indices_cuda(bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz); +} // namespace native +} // namespace at diff --git a/shared/package-files/76/76eaac111b9c65c12fce35941e3cef4497a337d1afac8731848dbd49ceefae04/blob b/shared/package-files/76/76eaac111b9c65c12fce35941e3cef4497a337d1afac8731848dbd49ceefae04/blob new file mode 100644 index 0000000000000000000000000000000000000000..81fa1cb708d38382e05048942671c451bf4e04e3 --- /dev/null +++ b/shared/package-files/76/76eaac111b9c65c12fce35941e3cef4497a337d1afac8731848dbd49ceefae04/blob @@ -0,0 +1,98 @@ +#pragma once + +namespace torch { +namespace autograd { +namespace generated { + +PyTypeObject* get__fake_quantize_per_tensor_affine_cachemask_tensor_qparams_structseq(); +PyTypeObject* get__fused_moving_avg_obs_fq_helper_structseq(); +PyTypeObject* get__linalg_det_structseq(); +PyTypeObject* get__linalg_det_out_structseq(); +PyTypeObject* get__linalg_eigh_structseq(); +PyTypeObject* get__linalg_eigh_out_structseq(); +PyTypeObject* get__linalg_slogdet_structseq(); +PyTypeObject* get__linalg_slogdet_out_structseq(); +PyTypeObject* get__linalg_solve_ex_structseq(); +PyTypeObject* get__linalg_solve_ex_out_structseq(); +PyTypeObject* get__linalg_svd_structseq(); +PyTypeObject* get__linalg_svd_out_structseq(); +PyTypeObject* get__lu_with_info_structseq(); +PyTypeObject* get__scaled_dot_product_cudnn_attention_structseq(); +PyTypeObject* get__scaled_dot_product_efficient_attention_structseq(); +PyTypeObject* get__scaled_dot_product_flash_attention_structseq(); +PyTypeObject* get__scaled_dot_product_flash_attention_for_cpu_structseq(); +PyTypeObject* get__unpack_dual_structseq(); +PyTypeObject* get_aminmax_structseq(); +PyTypeObject* get_aminmax_out_structseq(); +PyTypeObject* get_cummax_structseq(); +PyTypeObject* get_cummax_out_structseq(); +PyTypeObject* get_cummin_structseq(); +PyTypeObject* get_cummin_out_structseq(); +PyTypeObject* get_frexp_structseq(); +PyTypeObject* get_frexp_out_structseq(); +PyTypeObject* get_geqrf_out_structseq(); +PyTypeObject* get_geqrf_structseq(); +PyTypeObject* get_histogram_out_structseq(); +PyTypeObject* get_histogram_structseq(); +PyTypeObject* get_histogramdd_structseq(); +PyTypeObject* get_kthvalue_structseq(); +PyTypeObject* get_kthvalue_out_structseq(); +PyTypeObject* get_linalg_cholesky_ex_structseq(); +PyTypeObject* get_linalg_cholesky_ex_out_structseq(); +PyTypeObject* get_linalg_eig_structseq(); +PyTypeObject* get_linalg_eig_out_structseq(); +PyTypeObject* get_linalg_eigh_structseq(); +PyTypeObject* get_linalg_eigh_out_structseq(); +PyTypeObject* get_linalg_inv_ex_structseq(); +PyTypeObject* get_linalg_inv_ex_out_structseq(); +PyTypeObject* get_linalg_ldl_factor_structseq(); +PyTypeObject* get_linalg_ldl_factor_out_structseq(); +PyTypeObject* get_linalg_ldl_factor_ex_structseq(); +PyTypeObject* get_linalg_ldl_factor_ex_out_structseq(); +PyTypeObject* get_linalg_lstsq_structseq(); +PyTypeObject* get_linalg_lstsq_out_structseq(); +PyTypeObject* get_linalg_lu_structseq(); +PyTypeObject* get_linalg_lu_out_structseq(); +PyTypeObject* get_linalg_lu_factor_structseq(); +PyTypeObject* get_linalg_lu_factor_out_structseq(); +PyTypeObject* get_linalg_lu_factor_ex_structseq(); +PyTypeObject* get_linalg_lu_factor_ex_out_structseq(); +PyTypeObject* get_linalg_qr_structseq(); +PyTypeObject* get_linalg_qr_out_structseq(); +PyTypeObject* get_linalg_slogdet_structseq(); +PyTypeObject* get_linalg_slogdet_out_structseq(); +PyTypeObject* get_linalg_solve_ex_structseq(); +PyTypeObject* get_linalg_solve_ex_out_structseq(); +PyTypeObject* get_linalg_svd_structseq(); +PyTypeObject* get_linalg_svd_out_structseq(); +PyTypeObject* get_lu_unpack_structseq(); +PyTypeObject* get_lu_unpack_out_structseq(); +PyTypeObject* get_max_structseq(); +PyTypeObject* get_max_out_structseq(); +PyTypeObject* get_median_structseq(); +PyTypeObject* get_median_out_structseq(); +PyTypeObject* get_min_structseq(); +PyTypeObject* get_min_out_structseq(); +PyTypeObject* get_mode_structseq(); +PyTypeObject* get_mode_out_structseq(); +PyTypeObject* get_nanmedian_structseq(); +PyTypeObject* get_nanmedian_out_structseq(); +PyTypeObject* get_qr_out_structseq(); +PyTypeObject* get_qr_structseq(); +PyTypeObject* get_slogdet_structseq(); +PyTypeObject* get_slogdet_out_structseq(); +PyTypeObject* get_sort_out_structseq(); +PyTypeObject* get_sort_structseq(); +PyTypeObject* get_svd_out_structseq(); +PyTypeObject* get_svd_structseq(); +PyTypeObject* get_topk_out_structseq(); +PyTypeObject* get_topk_structseq(); +PyTypeObject* get_triangular_solve_out_structseq(); +PyTypeObject* get_triangular_solve_structseq(); + +} + +void initReturnTypes(PyObject* module); + +} // namespace autograd +} // namespace torch diff --git a/shared/package-files/76/76ed8cf9c612d299a04c2f9ca21e2594ee43e2ff2e6f75dda3fac4c5ca67bf6d/blob b/shared/package-files/76/76ed8cf9c612d299a04c2f9ca21e2594ee43e2ff2e6f75dda3fac4c5ca67bf6d/blob new file mode 100644 index 0000000000000000000000000000000000000000..cc6e1655423c65c9e39389ae3e2ae43fb7da583c Binary files /dev/null and b/shared/package-files/76/76ed8cf9c612d299a04c2f9ca21e2594ee43e2ff2e6f75dda3fac4c5ca67bf6d/blob differ diff --git a/shared/package-files/76/76edd7f3e3689162131c58ba0dbcd89cc3b8b9b6b9b874aa588678666ffd1e10/blob b/shared/package-files/76/76edd7f3e3689162131c58ba0dbcd89cc3b8b9b6b9b874aa588678666ffd1e10/blob new file mode 100644 index 0000000000000000000000000000000000000000..e5c1fe9daee2c5a955dd71de3e82f33e3dc02179 --- /dev/null +++ b/shared/package-files/76/76edd7f3e3689162131c58ba0dbcd89cc3b8b9b6b9b874aa588678666ffd1e10/blob @@ -0,0 +1,503 @@ +# Copyright (C) 2015, Pauli Virtanen +# Distributed under the same license as SciPy. + +import numpy as np +from numpy.linalg import LinAlgError +from scipy.linalg import (get_blas_funcs, qr, solve, svd, qr_insert, lstsq) +from .iterative import _get_atol_rtol +from scipy.sparse.linalg._isolve.utils import make_system + + +__all__ = ['gcrotmk'] + + +def _fgmres(matvec, v0, m, atol, lpsolve=None, rpsolve=None, cs=(), outer_v=(), + prepend_outer_v=False): + """ + FGMRES Arnoldi process, with optional projection or augmentation + + Parameters + ---------- + matvec : callable + Operation A*x + v0 : ndarray + Initial vector, normalized to nrm2(v0) == 1 + m : int + Number of GMRES rounds + atol : float + Absolute tolerance for early exit + lpsolve : callable + Left preconditioner L + rpsolve : callable + Right preconditioner R + cs : list of (ndarray, ndarray) + Columns of matrices C and U in GCROT + outer_v : list of ndarrays + Augmentation vectors in LGMRES + prepend_outer_v : bool, optional + Whether augmentation vectors come before or after + Krylov iterates + + Raises + ------ + LinAlgError + If nans encountered + + Returns + ------- + Q, R : ndarray + QR decomposition of the upper Hessenberg H=QR + B : ndarray + Projections corresponding to matrix C + vs : list of ndarray + Columns of matrix V + zs : list of ndarray + Columns of matrix Z + y : ndarray + Solution to ||H y - e_1||_2 = min! + res : float + The final (preconditioned) residual norm + + """ + + if lpsolve is None: + def lpsolve(x): + return x + if rpsolve is None: + def rpsolve(x): + return x + + axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (v0,)) + + vs = [v0] + zs = [] + y = None + res = np.nan + + m = m + len(outer_v) + + # Orthogonal projection coefficients + B = np.zeros((len(cs), m), dtype=v0.dtype) + + # H is stored in QR factorized form + Q = np.ones((1, 1), dtype=v0.dtype) + R = np.zeros((1, 0), dtype=v0.dtype) + + eps = np.finfo(v0.dtype).eps + + breakdown = False + + # FGMRES Arnoldi process + for j in range(m): + # L A Z = C B + V H + + if prepend_outer_v and j < len(outer_v): + z, w = outer_v[j] + elif prepend_outer_v and j == len(outer_v): + z = rpsolve(v0) + w = None + elif not prepend_outer_v and j >= m - len(outer_v): + z, w = outer_v[j - (m - len(outer_v))] + else: + z = rpsolve(vs[-1]) + w = None + + if w is None: + w = lpsolve(matvec(z)) + else: + # w is clobbered below + w = w.copy() + + w_norm = nrm2(w) + + # GCROT projection: L A -> (1 - C C^H) L A + # i.e. orthogonalize against C + for i, c in enumerate(cs): + alpha = dot(c, w) + B[i,j] = alpha + w = axpy(c, w, c.shape[0], -alpha) # w -= alpha*c + + # Orthogonalize against V + hcur = np.zeros(j+2, dtype=Q.dtype) + for i, v in enumerate(vs): + alpha = dot(v, w) + hcur[i] = alpha + w = axpy(v, w, v.shape[0], -alpha) # w -= alpha*v + hcur[i+1] = nrm2(w) + + with np.errstate(over='ignore', divide='ignore'): + # Careful with denormals + alpha = 1/hcur[-1] + + if np.isfinite(alpha): + w = scal(alpha, w) + + if not (hcur[-1] > eps * w_norm): + # w essentially in the span of previous vectors, + # or we have nans. Bail out after updating the QR + # solution. + breakdown = True + + vs.append(w) + zs.append(z) + + # Arnoldi LSQ problem + + # Add new column to H=Q@R, padding other columns with zeros + Q2 = np.zeros((j+2, j+2), dtype=Q.dtype, order='F') + Q2[:j+1,:j+1] = Q + Q2[j+1,j+1] = 1 + + R2 = np.zeros((j+2, j), dtype=R.dtype, order='F') + R2[:j+1,:] = R + + Q, R = qr_insert(Q2, R2, hcur, j, which='col', + overwrite_qru=True, check_finite=False) + + # Transformed least squares problem + # || Q R y - inner_res_0 * e_1 ||_2 = min! + # Since R = [R'; 0], solution is y = inner_res_0 (R')^{-1} (Q^H)[:j,0] + + # Residual is immediately known + res = abs(Q[0,-1]) + + # Check for termination + if res < atol or breakdown: + break + + if not np.isfinite(R[j,j]): + # nans encountered, bail out + raise LinAlgError() + + # -- Get the LSQ problem solution + + # The problem is triangular, but the condition number may be + # bad (or in case of breakdown the last diagonal entry may be + # zero), so use lstsq instead of trtrs. + y, _, _, _, = lstsq(R[:j+1,:j+1], Q[0,:j+1].conj()) + + B = B[:,:j+1] + + return Q, R, B, vs, zs, y, res + + +def gcrotmk(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=1000, M=None, callback=None, + m=20, k=None, CU=None, discard_C=False, truncate='oldest'): + """ + Solve a matrix equation using flexible GCROT(m,k) algorithm. + + Parameters + ---------- + A : {sparse array, ndarray, LinearOperator} + The real or complex N-by-N matrix of the linear system. + Alternatively, `A` can be a linear operator which can + produce ``Ax`` using, e.g., + `LinearOperator`. + b : ndarray + Right hand side of the linear system. Has shape (N,) or (N,1). + x0 : ndarray + Starting guess for the solution. + rtol, atol : float, optional + Parameters for the convergence test. For convergence, + ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied. + The default is ``rtol=1e-5`` and ``atol=0.0``. + maxiter : int, optional + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. The + default is ``1000``. + M : {sparse array, ndarray, LinearOperator}, optional + Preconditioner for `A`. The preconditioner should approximate the + inverse of `A`. gcrotmk is a 'flexible' algorithm and the preconditioner + can vary from iteration to iteration. Effective preconditioning + dramatically improves the rate of convergence, which implies that + fewer iterations are needed to reach a given error tolerance. + callback : function, optional + User-supplied function to call after each iteration. It is called + as ``callback(xk)``, where ``xk`` is the current solution vector. + m : int, optional + Number of inner FGMRES iterations per each outer iteration. + Default: 20 + k : int, optional + Number of vectors to carry between inner FGMRES iterations. + According to [2]_, good values are around `m`. + Default: `m` + CU : list of tuples, optional + List of tuples ``(c, u)`` which contain the columns of the matrices + C and U in the GCROT(m,k) algorithm. For details, see [2]_. + The list given and vectors contained in it are modified in-place. + If not given, start from empty matrices. The ``c`` elements in the + tuples can be ``None``, in which case the vectors are recomputed + via ``c = A u`` on start and orthogonalized as described in [3]_. + discard_C : bool, optional + Discard the C-vectors at the end. Useful if recycling Krylov subspaces + for different linear systems. + truncate : {'oldest', 'smallest'}, optional + Truncation scheme to use. Drop: oldest vectors, or vectors with + smallest singular values using the scheme discussed in [1,2]. + See [2]_ for detailed comparison. + Default: 'oldest' + + Returns + ------- + x : ndarray + The solution found. + info : int + Provides convergence information: + + * 0 : successful exit + * >0 : convergence to tolerance not achieved, number of iterations + + References + ---------- + .. [1] E. de Sturler, ''Truncation strategies for optimal Krylov subspace + methods'', SIAM J. Numer. Anal. 36, 864 (1999). + .. [2] J.E. Hicken and D.W. Zingg, ''A simplified and flexible variant + of GCROT for solving nonsymmetric linear systems'', + SIAM J. Sci. Comput. 32, 172 (2010). + .. [3] M.L. Parks, E. de Sturler, G. Mackey, D.D. Johnson, S. Maiti, + ''Recycling Krylov subspaces for sequences of linear systems'', + SIAM J. Sci. Comput. 28, 1651 (2006). + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csc_array + >>> from scipy.sparse.linalg import gcrotmk + >>> R = np.random.randn(5, 5) + >>> A = csc_array(R) + >>> b = np.random.randn(5) + >>> x, exit_code = gcrotmk(A, b, atol=1e-5) + >>> print(exit_code) + 0 + >>> np.allclose(A.dot(x), b) + True + + """ + A,M,x,b,postprocess = make_system(A,M,x0,b) + + if not np.isfinite(b).all(): + raise ValueError("RHS must contain only finite numbers") + + if truncate not in ('oldest', 'smallest'): + raise ValueError(f"Invalid value for 'truncate': {truncate!r}") + + matvec = A.matvec + psolve = M.matvec + + if CU is None: + CU = [] + + if k is None: + k = m + + axpy, dot, scal = None, None, None + + if x0 is None: + r = b.copy() + else: + r = b - matvec(x) + + axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (x, r)) + + b_norm = nrm2(b) + + # we call this to get the right atol/rtol and raise errors as necessary + atol, rtol = _get_atol_rtol('gcrotmk', b_norm, atol, rtol) + + if b_norm == 0: + x = b + return (postprocess(x), 0) + + if discard_C: + CU[:] = [(None, u) for c, u in CU] + + # Reorthogonalize old vectors + if CU: + # Sort already existing vectors to the front + CU.sort(key=lambda cu: cu[0] is not None) + + # Fill-in missing ones + C = np.empty((A.shape[0], len(CU)), dtype=r.dtype, order='F') + us = [] + j = 0 + while CU: + # More memory-efficient: throw away old vectors as we go + c, u = CU.pop(0) + if c is None: + c = matvec(u) + C[:,j] = c + j += 1 + us.append(u) + + # Orthogonalize + Q, R, P = qr(C, overwrite_a=True, mode='economic', pivoting=True) + del C + + # C := Q + cs = list(Q.T) + + # U := U P R^-1, back-substitution + new_us = [] + for j in range(len(cs)): + u = us[P[j]] + for i in range(j): + u = axpy(us[P[i]], u, u.shape[0], -R[i,j]) + if abs(R[j,j]) < 1e-12 * abs(R[0,0]): + # discard rest of the vectors + break + u = scal(1.0/R[j,j], u) + new_us.append(u) + + # Form the new CU lists + CU[:] = list(zip(cs, new_us))[::-1] + + if CU: + axpy, dot = get_blas_funcs(['axpy', 'dot'], (r,)) + + # Solve first the projection operation with respect to the CU + # vectors. This corresponds to modifying the initial guess to + # be + # + # x' = x + U y + # y = argmin_y || b - A (x + U y) ||^2 + # + # The solution is y = C^H (b - A x) + for c, u in CU: + yc = dot(c, r) + x = axpy(u, x, x.shape[0], yc) + r = axpy(c, r, r.shape[0], -yc) + + # GCROT main iteration + for j_outer in range(maxiter): + # -- callback + if callback is not None: + callback(x) + + beta = nrm2(r) + + # -- check stopping condition + beta_tol = max(atol, rtol * b_norm) + + if beta <= beta_tol and (j_outer > 0 or CU): + # recompute residual to avoid rounding error + r = b - matvec(x) + beta = nrm2(r) + + if beta <= beta_tol: + j_outer = -1 + break + + ml = m + max(k - len(CU), 0) + + cs = [c for c, u in CU] + + try: + Q, R, B, vs, zs, y, pres = _fgmres(matvec, + r/beta, + ml, + rpsolve=psolve, + atol=max(atol, rtol*b_norm)/beta, + cs=cs) + y *= beta + except LinAlgError: + # Floating point over/underflow, non-finite result from + # matmul etc. -- report failure. + break + + # + # At this point, + # + # [A U, A Z] = [C, V] G; G = [ I B ] + # [ 0 H ] + # + # where [C, V] has orthonormal columns, and r = beta v_0. Moreover, + # + # || b - A (x + Z y + U q) ||_2 = || r - C B y - V H y - C q ||_2 = min! + # + # from which y = argmin_y || beta e_1 - H y ||_2, and q = -B y + # + + # + # GCROT(m,k) update + # + + # Define new outer vectors + + # ux := (Z - U B) y + ux = zs[0]*y[0] + for z, yc in zip(zs[1:], y[1:]): + ux = axpy(z, ux, ux.shape[0], yc) # ux += z*yc + by = B.dot(y) + for cu, byc in zip(CU, by): + c, u = cu + ux = axpy(u, ux, ux.shape[0], -byc) # ux -= u*byc + + # cx := V H y + with np.errstate(invalid="ignore"): + hy = Q.dot(R.dot(y)) + cx = vs[0] * hy[0] + for v, hyc in zip(vs[1:], hy[1:]): + cx = axpy(v, cx, cx.shape[0], hyc) # cx += v*hyc + + # Normalize cx, maintaining cx = A ux + # This new cx is orthogonal to the previous C, by construction + try: + alpha = 1/nrm2(cx) + if not np.isfinite(alpha): + raise FloatingPointError() + except (FloatingPointError, ZeroDivisionError): + # Cannot update, so skip it + continue + + cx = scal(alpha, cx) + ux = scal(alpha, ux) + + # Update residual and solution + gamma = dot(cx, r) + r = axpy(cx, r, r.shape[0], -gamma) # r -= gamma*cx + x = axpy(ux, x, x.shape[0], gamma) # x += gamma*ux + + # Truncate CU + if truncate == 'oldest': + while len(CU) >= k and CU: + del CU[0] + elif truncate == 'smallest': + if len(CU) >= k and CU: + # cf. [1,2] + D = solve(R[:-1,:].T, B.T).T + W, sigma, V = svd(D) + + # C := C W[:,:k-1], U := U W[:,:k-1] + new_CU = [] + for j, w in enumerate(W[:,:k-1].T): + c, u = CU[0] + c = c * w[0] + u = u * w[0] + for cup, wp in zip(CU[1:], w[1:]): + cp, up = cup + c = axpy(cp, c, c.shape[0], wp) + u = axpy(up, u, u.shape[0], wp) + + # Reorthogonalize at the same time; not necessary + # in exact arithmetic, but floating point error + # tends to accumulate here + for cp, up in new_CU: + alpha = dot(cp, c) + c = axpy(cp, c, c.shape[0], -alpha) + u = axpy(up, u, u.shape[0], -alpha) + alpha = nrm2(c) + c = scal(1.0/alpha, c) + u = scal(1.0/alpha, u) + + new_CU.append((c, u)) + CU[:] = new_CU + + # Add new vector to CU + CU.append((cx, ux)) + + # Include the solution vector to the span + CU.append((None, x.copy())) + if discard_C: + CU[:] = [(None, uz) for cz, uz in CU] + + return postprocess(x), j_outer + 1 diff --git a/shared/package-files/76/76efd0f880acd182ceaa3d64af9a5e4af840a5932b08e08801d636d4ca4e2e1a/blob b/shared/package-files/76/76efd0f880acd182ceaa3d64af9a5e4af840a5932b08e08801d636d4ca4e2e1a/blob new file mode 100644 index 0000000000000000000000000000000000000000..b5b05288aef27f70e8f136858a1b721251da8b47 --- /dev/null +++ b/shared/package-files/76/76efd0f880acd182ceaa3d64af9a5e4af840a5932b08e08801d636d4ca4e2e1a/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API cumulative_trapezoid_x { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cumulative_trapezoid") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "x") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cumulative_trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor") + static at::Tensor call(const at::Tensor & y, const at::Tensor & x, int64_t dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & y, const at::Tensor & x, int64_t dim); +}; + +struct TORCH_API cumulative_trapezoid_dx { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cumulative_trapezoid") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dx") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cumulative_trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor") + static at::Tensor call(const at::Tensor & y, const at::Scalar & dx, int64_t dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & y, const at::Scalar & dx, int64_t dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/76/76f0592d51fad133931c234d9168344c52edb89e46861ff15cdef7af7572ab9f/blob b/shared/package-files/76/76f0592d51fad133931c234d9168344c52edb89e46861ff15cdef7af7572ab9f/blob new file mode 100644 index 0000000000000000000000000000000000000000..f85acbeb2148d2aa8f289808e61aa61e2d68e2f9 --- /dev/null +++ b/shared/package-files/76/76f0592d51fad133931c234d9168344c52edb89e46861ff15cdef7af7572ab9f/blob @@ -0,0 +1,119 @@ +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["AlexNet", "AlexNet_Weights", "alexnet"] + + +class AlexNet(nn.Module): + def __init__(self, num_classes: int = 1000, dropout: float = 0.5) -> None: + super().__init__() + _log_api_usage_once(self) + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + nn.Conv2d(64, 192, kernel_size=5, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + nn.Conv2d(192, 384, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(384, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(256, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + ) + self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Linear(256 * 6 * 6, 4096), + nn.ReLU(inplace=True), + nn.Dropout(p=dropout), + nn.Linear(4096, 4096), + nn.ReLU(inplace=True), + nn.Linear(4096, num_classes), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + +class AlexNet_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/alexnet-owt-7be5be79.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 61100840, + "min_size": (63, 63), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#alexnet-and-vgg", + "_metrics": { + "ImageNet-1K": { + "acc@1": 56.522, + "acc@5": 79.066, + } + }, + "_ops": 0.714, + "_file_size": 233.087, + "_docs": """ + These weights reproduce closely the results of the paper using a simplified training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", AlexNet_Weights.IMAGENET1K_V1)) +def alexnet(*, weights: Optional[AlexNet_Weights] = None, progress: bool = True, **kwargs: Any) -> AlexNet: + """AlexNet model architecture from `One weird trick for parallelizing convolutional neural networks `__. + + .. note:: + AlexNet was originally introduced in the `ImageNet Classification with + Deep Convolutional Neural Networks + `__ + paper. Our implementation is based instead on the "One weird trick" + paper above. + + Args: + weights (:class:`~torchvision.models.AlexNet_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.AlexNet_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.AlexNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.AlexNet_Weights + :members: + """ + + weights = AlexNet_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = AlexNet(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/shared/package-files/76/76f365f5399f3f3355c622a4e560c58a112b679efdea0d940bdf8a186c9f5e69/blob b/shared/package-files/76/76f365f5399f3f3355c622a4e560c58a112b679efdea0d940bdf8a186c9f5e69/blob new file mode 100644 index 0000000000000000000000000000000000000000..10fc0d7e9f398dd550a42c6b8c0637684882ee60 --- /dev/null +++ b/shared/package-files/76/76f365f5399f3f3355c622a4e560c58a112b679efdea0d940bdf8a186c9f5e69/blob @@ -0,0 +1,72 @@ +import sys +from dataclasses import dataclass + + +@dataclass +class WindowsConsoleFeatures: + """Windows features available.""" + + vt: bool = False + """The console supports VT codes.""" + truecolor: bool = False + """The console supports truecolor.""" + + +try: + import ctypes + from ctypes import LibraryLoader + + if sys.platform == "win32": + windll = LibraryLoader(ctypes.WinDLL) + else: + windll = None + raise ImportError("Not windows") + + from pip._vendor.rich._win32_console import ( + ENABLE_VIRTUAL_TERMINAL_PROCESSING, + GetConsoleMode, + GetStdHandle, + LegacyWindowsError, + ) + +except (AttributeError, ImportError, ValueError): + + # Fallback if we can't load the Windows DLL + def get_windows_console_features() -> WindowsConsoleFeatures: + features = WindowsConsoleFeatures() + return features + +else: + + def get_windows_console_features() -> WindowsConsoleFeatures: + """Get windows console features. + + Returns: + WindowsConsoleFeatures: An instance of WindowsConsoleFeatures. + """ + handle = GetStdHandle() + try: + console_mode = GetConsoleMode(handle) + success = True + except LegacyWindowsError: + console_mode = 0 + success = False + vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) + truecolor = False + if vt: + win_version = sys.getwindowsversion() + truecolor = win_version.major > 10 or ( + win_version.major == 10 and win_version.build >= 15063 + ) + features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor) + return features + + +if __name__ == "__main__": + import platform + + features = get_windows_console_features() + from pip._vendor.rich import print + + print(f'platform="{platform.system()}"') + print(repr(features)) diff --git a/shared/package-files/76/76f69fb6007d8e0911ffc113ca1cf254bb5fd5926eff0402f996e94d83176461/blob b/shared/package-files/76/76f69fb6007d8e0911ffc113ca1cf254bb5fd5926eff0402f996e94d83176461/blob new file mode 100644 index 0000000000000000000000000000000000000000..5fa9222c2a9b218f42636267235d5dd44c25f8bb --- /dev/null +++ b/shared/package-files/76/76f69fb6007d8e0911ffc113ca1cf254bb5fd5926eff0402f996e94d83176461/blob @@ -0,0 +1,91 @@ +from sympy.core.sympify import _sympify +from sympy.matrices.expressions import MatrixExpr +from sympy.core.numbers import I +from sympy.core.singleton import S +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt + + +class DFT(MatrixExpr): + r""" + Returns a discrete Fourier transform matrix. The matrix is scaled + with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. + + Parameters + ========== + + n : integer or Symbol + Size of the transform. + + Examples + ======== + + >>> from sympy.abc import n + >>> from sympy.matrices.expressions.fourier import DFT + >>> DFT(3) + DFT(3) + >>> DFT(3).as_explicit() + Matrix([ + [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3], + [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(2*I*pi/3)/3], + [sqrt(3)/3, sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]]) + >>> DFT(n).shape + (n, n) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/DFT_matrix + + """ + + def __new__(cls, n): + n = _sympify(n) + cls._check_dim(n) + + obj = super().__new__(cls, n) + return obj + + n = property(lambda self: self.args[0]) # type: ignore + shape = property(lambda self: (self.n, self.n)) # type: ignore + + def _entry(self, i, j, **kwargs): + w = exp(-2*S.Pi*I/self.n) + return w**(i*j) / sqrt(self.n) + + def _eval_inverse(self): + return IDFT(self.n) + + +class IDFT(DFT): + r""" + Returns an inverse discrete Fourier transform matrix. The matrix is scaled + with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. + + Parameters + ========== + + n : integer or Symbol + Size of the transform + + Examples + ======== + + >>> from sympy.matrices.expressions.fourier import DFT, IDFT + >>> IDFT(3) + IDFT(3) + >>> IDFT(4)*DFT(4) + I + + See Also + ======== + + DFT + + """ + def _entry(self, i, j, **kwargs): + w = exp(-2*S.Pi*I/self.n) + return w**(-i*j) / sqrt(self.n) + + def _eval_inverse(self): + return DFT(self.n) diff --git a/shared/package-files/76/76f8f6265f666d322de3ba56e6579318589af3dc57c8588ae4df0f9480e4900e/blob b/shared/package-files/76/76f8f6265f666d322de3ba56e6579318589af3dc57c8588ae4df0f9480e4900e/blob new file mode 100644 index 0000000000000000000000000000000000000000..e3621f7c22fb8c7e28d708217db550269bb9d068 Binary files /dev/null and b/shared/package-files/76/76f8f6265f666d322de3ba56e6579318589af3dc57c8588ae4df0f9480e4900e/blob differ diff --git a/shared/package-files/77/7705041c23b0553fa59d95daa95d0fd17adfdab3ee0a4b1748f455cc69abaa9b/blob b/shared/package-files/77/7705041c23b0553fa59d95daa95d0fd17adfdab3ee0a4b1748f455cc69abaa9b/blob new file mode 100644 index 0000000000000000000000000000000000000000..a89e9c8863b37c42c7cc470125017dd9af64ad12 --- /dev/null +++ b/shared/package-files/77/7705041c23b0553fa59d95daa95d0fd17adfdab3ee0a4b1748f455cc69abaa9b/blob @@ -0,0 +1,461 @@ +from parso.python import tree + +from jedi import debug +from jedi.inference.cache import inference_state_method_cache, CachedMetaClass +from jedi.inference import compiled +from jedi.inference import recursion +from jedi.inference import docstrings +from jedi.inference import flow_analysis +from jedi.inference.signature import TreeSignature +from jedi.inference.filters import ParserTreeFilter, FunctionExecutionFilter, \ + AnonymousFunctionExecutionFilter +from jedi.inference.names import ValueName, AbstractNameDefinition, \ + AnonymousParamName, ParamName, NameWrapper +from jedi.inference.base_value import ContextualizedNode, NO_VALUES, \ + ValueSet, TreeValue, ValueWrapper +from jedi.inference.lazy_value import LazyKnownValues, LazyKnownValue, \ + LazyTreeValue +from jedi.inference.context import ValueContext, TreeContextMixin +from jedi.inference.value import iterable +from jedi import parser_utils +from jedi.inference.parser_cache import get_yield_exprs +from jedi.inference.helpers import values_from_qualified_names +from jedi.inference.gradual.generics import TupleGenericManager + + +class LambdaName(AbstractNameDefinition): + string_name = '' + api_type = 'function' + + def __init__(self, lambda_value): + self._lambda_value = lambda_value + self.parent_context = lambda_value.parent_context + + @property + def start_pos(self): + return self._lambda_value.tree_node.start_pos + + def infer(self): + return ValueSet([self._lambda_value]) + + +class FunctionAndClassBase(TreeValue): + def get_qualified_names(self): + if self.parent_context.is_class(): + n = self.parent_context.get_qualified_names() + if n is None: + # This means that the parent class lives within a function. + return None + return n + (self.py__name__(),) + elif self.parent_context.is_module(): + return (self.py__name__(),) + else: + return None + + +class FunctionMixin: + api_type = 'function' + + def get_filters(self, origin_scope=None): + cls = self.py__class__() + for instance in cls.execute_with_values(): + yield from instance.get_filters(origin_scope=origin_scope) + + def py__get__(self, instance, class_value): + from jedi.inference.value.instance import BoundMethod + if instance is None: + # Calling the Foo.bar results in the original bar function. + return ValueSet([self]) + return ValueSet([BoundMethod(instance, class_value.as_context(), self)]) + + def get_param_names(self): + return [AnonymousParamName(self, param.name) + for param in self.tree_node.get_params()] + + @property + def name(self): + if self.tree_node.type == 'lambdef': + return LambdaName(self) + return ValueName(self, self.tree_node.name) + + def is_function(self): + return True + + def py__name__(self): + return self.name.string_name + + def get_type_hint(self, add_class_info=True): + return_annotation = self.tree_node.annotation + if return_annotation is None: + def param_name_to_str(n): + s = n.string_name + annotation = n.infer().get_type_hint() + if annotation is not None: + s += ': ' + annotation + if n.default_node is not None: + s += '=' + n.default_node.get_code(include_prefix=False) + return s + + function_execution = self.as_context() + result = function_execution.infer() + return_hint = result.get_type_hint() + body = self.py__name__() + '(%s)' % ', '.join([ + param_name_to_str(n) + for n in function_execution.get_param_names() + ]) + if return_hint is None: + return body + else: + return_hint = return_annotation.get_code(include_prefix=False) + body = self.py__name__() + self.tree_node.children[2].get_code(include_prefix=False) + + return body + ' -> ' + return_hint + + def py__call__(self, arguments): + function_execution = self.as_context(arguments) + return function_execution.infer() + + def _as_context(self, arguments=None): + if arguments is None: + return AnonymousFunctionExecution(self) + return FunctionExecutionContext(self, arguments) + + def get_signatures(self): + return [TreeSignature(f) for f in self.get_signature_functions()] + + +class FunctionValue(FunctionMixin, FunctionAndClassBase, metaclass=CachedMetaClass): + @classmethod + def from_context(cls, context, tree_node): + def create(tree_node): + if context.is_class(): + return MethodValue( + context.inference_state, + context, + parent_context=parent_context, + tree_node=tree_node + ) + else: + return cls( + context.inference_state, + parent_context=parent_context, + tree_node=tree_node + ) + + overloaded_funcs = list(_find_overload_functions(context, tree_node)) + + parent_context = context + while parent_context.is_class() or parent_context.is_instance(): + parent_context = parent_context.parent_context + + function = create(tree_node) + + if overloaded_funcs: + return OverloadedFunctionValue( + function, + # Get them into the correct order: lower line first. + list(reversed([create(f) for f in overloaded_funcs])) + ) + return function + + def py__class__(self): + c, = values_from_qualified_names(self.inference_state, 'types', 'FunctionType') + return c + + def get_default_param_context(self): + return self.parent_context + + def get_signature_functions(self): + return [self] + + +class FunctionNameInClass(NameWrapper): + def __init__(self, class_context, name): + super().__init__(name) + self._class_context = class_context + + def get_defining_qualified_value(self): + return self._class_context.get_value() # Might be None. + + +class MethodValue(FunctionValue): + def __init__(self, inference_state, class_context, *args, **kwargs): + super().__init__(inference_state, *args, **kwargs) + self.class_context = class_context + + def get_default_param_context(self): + return self.class_context + + def get_qualified_names(self): + # Need to implement this, because the parent value of a method + # value is not the class value but the module. + names = self.class_context.get_qualified_names() + if names is None: + return None + return names + (self.py__name__(),) + + @property + def name(self): + return FunctionNameInClass(self.class_context, super().name) + + +class BaseFunctionExecutionContext(ValueContext, TreeContextMixin): + def infer_annotations(self): + raise NotImplementedError + + @inference_state_method_cache(default=NO_VALUES) + @recursion.execution_recursion_decorator() + def get_return_values(self, check_yields=False): + funcdef = self.tree_node + if funcdef.type == 'lambdef': + return self.infer_node(funcdef.children[-1]) + + if check_yields: + value_set = NO_VALUES + returns = get_yield_exprs(self.inference_state, funcdef) + else: + value_set = self.infer_annotations() + if value_set: + # If there are annotations, prefer them over anything else. + # This will make it faster. + return value_set + value_set |= docstrings.infer_return_types(self._value) + returns = funcdef.iter_return_stmts() + + for r in returns: + if check_yields: + value_set |= ValueSet.from_sets( + lazy_value.infer() + for lazy_value in self._get_yield_lazy_value(r) + ) + else: + check = flow_analysis.reachability_check(self, funcdef, r) + if check is flow_analysis.UNREACHABLE: + debug.dbg('Return unreachable: %s', r) + else: + try: + children = r.children + except AttributeError: + ctx = compiled.builtin_from_name(self.inference_state, 'None') + value_set |= ValueSet([ctx]) + else: + value_set |= self.infer_node(children[1]) + if check is flow_analysis.REACHABLE: + debug.dbg('Return reachable: %s', r) + break + return value_set + + def _get_yield_lazy_value(self, yield_expr): + if yield_expr.type == 'keyword': + # `yield` just yields None. + ctx = compiled.builtin_from_name(self.inference_state, 'None') + yield LazyKnownValue(ctx) + return + + node = yield_expr.children[1] + if node.type == 'yield_arg': # It must be a yield from. + cn = ContextualizedNode(self, node.children[1]) + yield from cn.infer().iterate(cn) + else: + yield LazyTreeValue(self, node) + + @recursion.execution_recursion_decorator(default=iter([])) + def get_yield_lazy_values(self, is_async=False): + # TODO: if is_async, wrap yield statements in Awaitable/async_generator_asend + for_parents = [(y, tree.search_ancestor(y, 'for_stmt', 'funcdef', + 'while_stmt', 'if_stmt')) + for y in get_yield_exprs(self.inference_state, self.tree_node)] + + # Calculate if the yields are placed within the same for loop. + yields_order = [] + last_for_stmt = None + for yield_, for_stmt in for_parents: + # For really simple for loops we can predict the order. Otherwise + # we just ignore it. + parent = for_stmt.parent + if parent.type == 'suite': + parent = parent.parent + if for_stmt.type == 'for_stmt' and parent == self.tree_node \ + and parser_utils.for_stmt_defines_one_name(for_stmt): # Simplicity for now. + if for_stmt == last_for_stmt: + yields_order[-1][1].append(yield_) + else: + yields_order.append((for_stmt, [yield_])) + elif for_stmt == self.tree_node: + yields_order.append((None, [yield_])) + else: + types = self.get_return_values(check_yields=True) + if types: + yield LazyKnownValues(types, min=0, max=float('inf')) + return + last_for_stmt = for_stmt + + for for_stmt, yields in yields_order: + if for_stmt is None: + # No for_stmt, just normal yields. + for yield_ in yields: + yield from self._get_yield_lazy_value(yield_) + else: + input_node = for_stmt.get_testlist() + cn = ContextualizedNode(self, input_node) + ordered = cn.infer().iterate(cn) + ordered = list(ordered) + for lazy_value in ordered: + dct = {str(for_stmt.children[1].value): lazy_value.infer()} + with self.predefine_names(for_stmt, dct): + for yield_in_same_for_stmt in yields: + yield from self._get_yield_lazy_value(yield_in_same_for_stmt) + + def merge_yield_values(self, is_async=False): + return ValueSet.from_sets( + lazy_value.infer() + for lazy_value in self.get_yield_lazy_values() + ) + + def is_generator(self): + return bool(get_yield_exprs(self.inference_state, self.tree_node)) + + def infer(self): + """ + Created to be used by inheritance. + """ + inference_state = self.inference_state + is_coroutine = self.tree_node.parent.type in ('async_stmt', 'async_funcdef') + from jedi.inference.gradual.base import GenericClass + + if is_coroutine: + if self.is_generator(): + async_generator_classes = inference_state.typing_module \ + .py__getattribute__('AsyncGenerator') + + yield_values = self.merge_yield_values(is_async=True) + # The contravariant doesn't seem to be defined. + generics = (yield_values.py__class__(), NO_VALUES) + return ValueSet( + GenericClass(c, TupleGenericManager(generics)) + for c in async_generator_classes + ).execute_annotation() + else: + async_classes = inference_state.typing_module.py__getattribute__('Coroutine') + return_values = self.get_return_values() + # Only the first generic is relevant. + generics = (return_values.py__class__(), NO_VALUES, NO_VALUES) + return ValueSet( + GenericClass(c, TupleGenericManager(generics)) for c in async_classes + ).execute_annotation() + else: + # If there are annotations, prefer them over anything else. + if self.is_generator() and not self.infer_annotations(): + return ValueSet([iterable.Generator(inference_state, self)]) + else: + return self.get_return_values() + + +class FunctionExecutionContext(BaseFunctionExecutionContext): + def __init__(self, function_value, arguments): + super().__init__(function_value) + self._arguments = arguments + + def get_filters(self, until_position=None, origin_scope=None): + yield FunctionExecutionFilter( + self, self._value, + until_position=until_position, + origin_scope=origin_scope, + arguments=self._arguments + ) + + def infer_annotations(self): + from jedi.inference.gradual.annotation import infer_return_types + return infer_return_types(self._value, self._arguments) + + def get_param_names(self): + return [ + ParamName(self._value, param.name, self._arguments) + for param in self._value.tree_node.get_params() + ] + + +class AnonymousFunctionExecution(BaseFunctionExecutionContext): + def infer_annotations(self): + # I don't think inferring anonymous executions is a big thing. + # Anonymous contexts are mostly there for the user to work in. ~ dave + return NO_VALUES + + def get_filters(self, until_position=None, origin_scope=None): + yield AnonymousFunctionExecutionFilter( + self, self._value, + until_position=until_position, + origin_scope=origin_scope, + ) + + def get_param_names(self): + return self._value.get_param_names() + + +class OverloadedFunctionValue(FunctionMixin, ValueWrapper): + def __init__(self, function, overloaded_functions): + super().__init__(function) + self._overloaded_functions = overloaded_functions + + def py__call__(self, arguments): + debug.dbg("Execute overloaded function %s", self._wrapped_value, color='BLUE') + function_executions = [] + for signature in self.get_signatures(): + function_execution = signature.value.as_context(arguments) + function_executions.append(function_execution) + if signature.matches_signature(arguments): + return function_execution.infer() + + if self.inference_state.is_analysis: + # In this case we want precision. + return NO_VALUES + return ValueSet.from_sets(fe.infer() for fe in function_executions) + + def get_signature_functions(self): + return self._overloaded_functions + + def get_type_hint(self, add_class_info=True): + return 'Union[%s]' % ', '.join(f.get_type_hint() for f in self._overloaded_functions) + + +def _find_overload_functions(context, tree_node): + def _is_overload_decorated(funcdef): + if funcdef.parent.type == 'decorated': + decorators = funcdef.parent.children[0] + if decorators.type == 'decorator': + decorators = [decorators] + else: + decorators = decorators.children + for decorator in decorators: + dotted_name = decorator.children[1] + if dotted_name.type == 'name' and dotted_name.value == 'overload': + # TODO check with values if it's the right overload + return True + return False + + if tree_node.type == 'lambdef': + return + + if _is_overload_decorated(tree_node): + yield tree_node + + while True: + filter = ParserTreeFilter( + context, + until_position=tree_node.start_pos + ) + names = filter.get(tree_node.name.value) + assert isinstance(names, list) + if not names: + break + + found = False + for name in names: + funcdef = name.tree_name.parent + if funcdef.type == 'funcdef' and _is_overload_decorated(funcdef): + tree_node = funcdef + found = True + yield funcdef + + if not found: + break diff --git a/shared/package-files/77/77086deae3fa05d1d38d3237b512051c3bb5f1eae07de08ee1dd68731dd4cf2a/blob b/shared/package-files/77/77086deae3fa05d1d38d3237b512051c3bb5f1eae07de08ee1dd68731dd4cf2a/blob new file mode 100644 index 0000000000000000000000000000000000000000..05a252db2f8a6757d90676596e2ac12aa9962d13 --- /dev/null +++ b/shared/package-files/77/77086deae3fa05d1d38d3237b512051c3bb5f1eae07de08ee1dd68731dd4cf2a/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor multinomial(const at::Tensor & self, int64_t num_samples, bool replacement=false, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & multinomial_out(const at::Tensor & self, int64_t num_samples, bool replacement, c10::optional generator, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/770e8f3ccbde69f5a54199844a28ca3dca5eef350fc838307a05ee8823291b07/blob b/shared/package-files/77/770e8f3ccbde69f5a54199844a28ca3dca5eef350fc838307a05ee8823291b07/blob new file mode 100644 index 0000000000000000000000000000000000000000..546524d900e81aa930c8e847c36c0013e0d39f26 --- /dev/null +++ b/shared/package-files/77/770e8f3ccbde69f5a54199844a28ca3dca5eef350fc838307a05ee8823291b07/blob @@ -0,0 +1,53 @@ +import contextlib +import tempfile +import unittest + +from torch._dynamo.test_case import ( + run_tests as dynamo_run_tests, + TestCase as DynamoTestCase, +) + +from torch._inductor import config + + +def run_tests(needs=()): + dynamo_run_tests(needs) + + +class TestCase(DynamoTestCase): + """ + A base TestCase for inductor tests. Enables FX graph caching and isolates + the cache directory for each test. + """ + + _stack: contextlib.ExitStack + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls._stack = contextlib.ExitStack() + cls._stack.enter_context(config.patch({"fx_graph_cache": True})) + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + cls._stack.close() + + def setUp(self): + super().setUp() + + # For all tests, mock the tmp directory populated by the inductor + # FxGraphCache, both for test isolation and to avoid filling disk. + self._inductor_cache_tmp_dir = tempfile.TemporaryDirectory() + self._inductor_cache_get_tmp_dir_patch = unittest.mock.patch( + "torch._inductor.codecache.FxGraphCache._get_tmp_dir" + ) + mock_get_dir = self._inductor_cache_get_tmp_dir_patch.start() + mock_get_dir.return_value = self._inductor_cache_tmp_dir.name + + def tearDown(self): + super().tearDown() + + # Clean up the FxGraphCache tmp dir. + self._inductor_cache_get_tmp_dir_patch.stop() + self._inductor_cache_tmp_dir.cleanup() diff --git a/shared/package-files/77/771005f2d4b2b84d6048937ebfb0f79a0db56ff5b9ef3ee62ccc923411059c14/blob b/shared/package-files/77/771005f2d4b2b84d6048937ebfb0f79a0db56ff5b9ef3ee62ccc923411059c14/blob new file mode 100644 index 0000000000000000000000000000000000000000..9cfa645e2313b97d38e2595627611a68cd9930e5 --- /dev/null +++ b/shared/package-files/77/771005f2d4b2b84d6048937ebfb0f79a0db56ff5b9ef3ee62ccc923411059c14/blob @@ -0,0 +1,743 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + from narwhals.typing import TimeUnit + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprDateTimeNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def date(self) -> ExprT: + """Extract the date from underlying DateTime representation. + + Raises: + NotImplementedError: If pandas default backend is being used. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [datetime(2012, 1, 7, 10), datetime(2027, 12, 13)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.date()).to_native() + shape: (2, 1) + ┌────────────┐ + │ a │ + │ --- │ + │ date │ + ╞════════════╡ + │ 2012-01-07 │ + │ 2027-12-13 │ + └────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.date")) + + def year(self) -> ExprT: + """Extract year from underlying DateTime representation. + + Returns the year number in the calendar date. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.year().alias("year")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a year| + |0 1978-06-01 1978| + |1 2065-01-01 2065| + └──────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.year")) + + def month(self) -> ExprT: + """Extract month from underlying DateTime representation. + + Returns the month number starting from 1. The return value ranges from 1 to 12. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.month().alias("month")).to_native() + pyarrow.Table + a: timestamp[us] + month: int64 + ---- + a: [[1978-06-01 00:00:00.000000,2065-01-01 00:00:00.000000]] + month: [[6,1]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.month")) + + def day(self) -> ExprT: + """Extract day from underlying DateTime representation. + + Returns the day of month starting from 1. The return value ranges from 1 to 31. (The last day of month differs by months.) + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.day().alias("day")).to_native() + pyarrow.Table + a: timestamp[us] + day: int64 + ---- + a: [[1978-06-01 00:00:00.000000,2065-01-01 00:00:00.000000]] + day: [[1,1]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.day")) + + def hour(self) -> ExprT: + """Extract hour from underlying DateTime representation. + + Returns the hour number from 0 to 23. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [datetime(1978, 1, 1, 1), datetime(2065, 1, 1, 10)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.hour().alias("hour")) + ┌──────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------| + |shape: (2, 2) | + |┌─────────────────────┬──────┐| + |│ a ┆ hour │| + |│ --- ┆ --- │| + |│ datetime[μs] ┆ i8 │| + |╞═════════════════════╪══════╡| + |│ 1978-01-01 01:00:00 ┆ 1 │| + |│ 2065-01-01 10:00:00 ┆ 10 │| + |└─────────────────────┴──────┘| + └──────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.hour")) + + def minute(self) -> ExprT: + """Extract minutes from underlying DateTime representation. + + Returns the minute number from 0 to 59. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(1978, 1, 1, 1, 1), datetime(2065, 1, 1, 10, 20)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.minute().alias("minute")).to_native() + a minute + 0 1978-01-01 01:01:00 1 + 1 2065-01-01 10:20:00 20 + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.minute")) + + def second(self) -> ExprT: + """Extract seconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1), + ... datetime(2065, 1, 1, 10, 20, 30), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.second().alias("second")).to_native() + pyarrow.Table + a: timestamp[us] + second: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.000000]] + second: [[1,30]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.second")) + + def millisecond(self) -> ExprT: + """Extract milliseconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1, 0), + ... datetime(2065, 1, 1, 10, 20, 30, 67000), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").dt.millisecond().alias("millisecond") + ... ).to_native() + pyarrow.Table + a: timestamp[us] + millisecond: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]] + millisecond: [[0,67]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.millisecond")) + + def microsecond(self) -> ExprT: + """Extract microseconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1, 0), + ... datetime(2065, 1, 1, 10, 20, 30, 67000), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").dt.microsecond().alias("microsecond") + ... ).to_native() + pyarrow.Table + a: timestamp[us] + microsecond: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]] + microsecond: [[0,67000]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.microsecond")) + + def nanosecond(self) -> ExprT: + """Extract Nanoseconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1, 0), + ... datetime(2065, 1, 1, 10, 20, 30, 67000), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").dt.nanosecond().alias("nanosecond") + ... ).to_native() + pyarrow.Table + a: timestamp[us] + nanosecond: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]] + nanosecond: [[0,67000000]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.nanosecond")) + + def ordinal_day(self) -> ExprT: + """Get ordinal day. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(2020, 1, 1), datetime(2020, 8, 3)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_ordinal_day=nw.col("a").dt.ordinal_day()) + ┌───────────────────────────┐ + | Narwhals DataFrame | + |---------------------------| + | a a_ordinal_day| + |0 2020-01-01 1| + |1 2020-08-03 216| + └───────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.ordinal_day")) + + def weekday(self) -> ExprT: + """Extract the week day from the underlying Date representation. + + Note that Monday = 1 and Sunday = 7. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(2020, 1, 1), datetime(2020, 8, 3)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_week_day=nw.col("a").dt.weekday()) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + | a a_week_day| + |0 2020-01-01 3| + |1 2020-08-03 1| + └────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.weekday")) + + def total_minutes(self) -> ExprT: + """Get total minutes. + + Notes: + The function outputs the total minutes in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [timedelta(minutes=10), timedelta(minutes=20, seconds=40)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_minutes=nw.col("a").dt.total_minutes() + ... ).to_native() + shape: (2, 2) + ┌──────────────┬─────────────────┐ + │ a ┆ a_total_minutes │ + │ --- ┆ --- │ + │ duration[μs] ┆ i64 │ + ╞══════════════╪═════════════════╡ + │ 10m ┆ 10 │ + │ 20m 40s ┆ 20 │ + └──────────────┴─────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.total_minutes")) + + def total_seconds(self) -> ExprT: + """Get total seconds. + + Notes: + The function outputs the total seconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [timedelta(seconds=10), timedelta(seconds=20, milliseconds=40)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_seconds=nw.col("a").dt.total_seconds() + ... ).to_native() + shape: (2, 2) + ┌──────────────┬─────────────────┐ + │ a ┆ a_total_seconds │ + │ --- ┆ --- │ + │ duration[μs] ┆ i64 │ + ╞══════════════╪═════════════════╡ + │ 10s ┆ 10 │ + │ 20s 40ms ┆ 20 │ + └──────────────┴─────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.total_seconds")) + + def total_milliseconds(self) -> ExprT: + """Get total milliseconds. + + Notes: + The function outputs the total milliseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... { + ... "a": [ + ... timedelta(milliseconds=10), + ... timedelta(milliseconds=20, microseconds=40), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_milliseconds=nw.col("a").dt.total_milliseconds() + ... ).to_native() + shape: (2, 2) + ┌──────────────┬──────────────────────┐ + │ a ┆ a_total_milliseconds │ + │ --- ┆ --- │ + │ duration[μs] ┆ i64 │ + ╞══════════════╪══════════════════════╡ + │ 10ms ┆ 10 │ + │ 20040µs ┆ 20 │ + └──────────────┴──────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.total_milliseconds") + ) + + def total_microseconds(self) -> ExprT: + """Get total microseconds. + + Notes: + The function outputs the total microseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... timedelta(microseconds=10), + ... timedelta(milliseconds=1, microseconds=200), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_microseconds=nw.col("a").dt.total_microseconds() + ... ).to_native() + pyarrow.Table + a: duration[us] + a_total_microseconds: int64 + ---- + a: [[10,1200]] + a_total_microseconds: [[10,1200]] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.total_microseconds") + ) + + def total_nanoseconds(self) -> ExprT: + """Get total nanoseconds. + + Notes: + The function outputs the total nanoseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": pd.to_datetime( + ... [ + ... "2024-01-01 00:00:00.000000001", + ... "2024-01-01 00:00:00.000000002", + ... ] + ... ) + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_diff_total_nanoseconds=nw.col("a").diff().dt.total_nanoseconds() + ... ).to_native() + a a_diff_total_nanoseconds + 0 2024-01-01 00:00:00.000000001 NaN + 1 2024-01-01 00:00:00.000000002 1.0 + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.total_nanoseconds") + ) + + def to_string(self, format: str) -> ExprT: + """Convert a Date/Time/Datetime column into a String column with the given format. + + Arguments: + format: Format to format temporal column with. + + Notes: + Unfortunately, different libraries interpret format directives a bit + differently. + + - Chrono, the library used by Polars, uses `"%.f"` for fractional seconds, + whereas pandas and Python stdlib use `".%f"`. + - PyArrow interprets `"%S"` as "seconds, including fractional seconds" + whereas most other tools interpret it as "just seconds, as 2 digits". + --- + Therefore, we make the following adjustments. + + - for pandas-like libraries, we replace `"%S.%f"` with `"%S%.f"`. + - for PyArrow, we replace `"%S.%f"` with `"%S"`. + --- + Workarounds like these don't make us happy, and we try to avoid them as + much as possible, but here we feel like it's the best compromise. + + If you just want to format a date/datetime Series as a local datetime + string, and have it work as consistently as possible across libraries, + we suggest using: + + - `"%Y-%m-%dT%H:%M:%S%.f"` for datetimes + - `"%Y-%m-%d"` for dates + --- + Though note that, even then, different tools may return a different number + of trailing zeros. Nonetheless, this is probably consistent enough for + most applications. + + If you have an application where this is not enough, please open an issue + and let us know. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [datetime(2020, 3, 1), datetime(2020, 5, 1)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.to_string("%Y/%m/%d %H:%M:%S")) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + |shape: (2, 1) | + |┌─────────────────────┐| + |│ a │| + |│ --- │| + |│ str │| + |╞═════════════════════╡| + |│ 2020/03/01 00:00:00 │| + |│ 2020/05/01 00:00:00 │| + |└─────────────────────┘| + └───────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.to_string", format=format) + ) + + def replace_time_zone(self, time_zone: str | None) -> ExprT: + """Replace time zone. + + Arguments: + time_zone: Target time zone. + + Examples: + >>> from datetime import datetime, timezone + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": [ + ... datetime(2024, 1, 1, tzinfo=timezone.utc), + ... datetime(2024, 1, 2, tzinfo=timezone.utc), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.replace_time_zone("Asia/Kathmandu")).to_native() + a + 0 2024-01-01 00:00:00+05:45 + 1 2024-01-02 00:00:00+05:45 + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.replace_time_zone", time_zone=time_zone) + ) + + def convert_time_zone(self, time_zone: str) -> ExprT: + """Convert to a new time zone. + + If converting from a time-zone-naive column, then conversion happens + as if converting from UTC. + + Arguments: + time_zone: Target time zone. + + Examples: + >>> from datetime import datetime, timezone + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": [ + ... datetime(2024, 1, 1, tzinfo=timezone.utc), + ... datetime(2024, 1, 2, tzinfo=timezone.utc), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.convert_time_zone("Asia/Kathmandu")).to_native() + a + 0 2024-01-01 05:45:00+05:45 + 1 2024-01-02 05:45:00+05:45 + """ + if time_zone is None: + msg = "Target `time_zone` cannot be `None` in `convert_time_zone`. Please use `replace_time_zone(None)` if you want to remove the time zone." + raise TypeError(msg) + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.convert_time_zone", time_zone=time_zone) + ) + + def timestamp(self, time_unit: TimeUnit = "us") -> ExprT: + """Return a timestamp in the given time unit. + + Arguments: + time_unit: One of + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + + Examples: + >>> from datetime import date + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"date": [date(2001, 1, 1), None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("date").dt.timestamp("ms").alias("timestamp_ms")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + |shape: (2, 2) | + |┌────────────┬──────────────┐| + |│ date ┆ timestamp_ms │| + |│ --- ┆ --- │| + |│ date ┆ i64 │| + |╞════════════╪══════════════╡| + |│ 2001-01-01 ┆ 978307200000 │| + |│ null ┆ null │| + |└────────────┴──────────────┘| + └─────────────────────────────┘ + """ + if time_unit not in {"ns", "us", "ms"}: + msg = ( + "invalid `time_unit`" + f"\n\nExpected one of {{'ns', 'us', 'ms'}}, got {time_unit!r}." + ) + raise ValueError(msg) + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.timestamp", time_unit=time_unit) + ) + + def truncate(self, every: str) -> ExprT: + """Divide the date/datetime range into buckets. + + Arguments: + every: Length of bucket. Must be of form ``, + where `multiple` is a positive integer and `unit` is one of + + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + - 's': second. + - 'm': minute. + - 'h': hour. + - 'd': day. + - 'mo': month. + - 'q': quarter. + - 'y': year. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"datetime": [datetime(2021, 3, 1, 12, 34)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("datetime").dt.truncate("1h").alias("datetime_trunc") + ... ) + ┌─────────────────────────────────────────────┐ + | Narwhals DataFrame | + |---------------------------------------------| + |shape: (1, 2) | + |┌─────────────────────┬─────────────────────┐| + |│ datetime ┆ datetime_trunc │| + |│ --- ┆ --- │| + |│ datetime[μs] ┆ datetime[μs] │| + |╞═════════════════════╪═════════════════════╡| + |│ 2021-03-01 12:34:00 ┆ 2021-03-01 12:00:00 │| + |└─────────────────────┴─────────────────────┘| + └─────────────────────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.truncate", every=every) + ) + + def offset_by(self, by: str) -> ExprT: + """Offset this date by a relative time offset. + + Arguments: + by: The offset. Must be of form ``, + where `multiple` is a positive integer and `unit` is one of + + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + - 's': second. + - 'm': minute. + - 'h': hour. + - 'd': day. + - 'mo': month. + - 'q': quarter. + - 'y': year. + + Notes: + For the Ibis backend, offsetting timezone-aware data by a calendar + unit ('d', 'mo', 'q' or 'y') raises: Ibis stores such values as UTC, + so the result would diverge from other backends across DST transitions. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"datetime": [datetime(2021, 3, 1, 12, 34)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("datetime").dt.offset_by("1h").alias("datetime_offset_by_1h") + ... ) + ┌───────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------------| + |shape: (1, 2) | + |┌─────────────────────┬───────────────────────┐| + |│ datetime ┆ datetime_offset_by_1h │| + |│ --- ┆ --- │| + |│ datetime[μs] ┆ datetime[μs] │| + |╞═════════════════════╪═══════════════════════╡| + |│ 2021-03-01 12:34:00 ┆ 2021-03-01 13:34:00 │| + |└─────────────────────┴───────────────────────┘| + └───────────────────────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.offset_by", by=by) + ) diff --git a/shared/package-files/77/7712b741869f92e057a1b1a42f4c01ad9de624fcfb67053e005cb6fb541a5622/blob b/shared/package-files/77/7712b741869f92e057a1b1a42f4c01ad9de624fcfb67053e005cb6fb541a5622/blob new file mode 100644 index 0000000000000000000000000000000000000000..404017e4198322d7e8a5b8ab5d54e4da7f456cf0 --- /dev/null +++ b/shared/package-files/77/7712b741869f92e057a1b1a42f4c01ad9de624fcfb67053e005cb6fb541a5622/blob @@ -0,0 +1,52 @@ +import sys +from logging import Logger, LogRecord +from types import TracebackType +from typing import IO, AnyStr, Callable, Generic, List, Optional, Protocol, Text, Type, TypeVar, Union + +from paramiko.config import SSHConfig, SSHConfigDict +from paramiko.hostkeys import HostKeys + +if sys.version_info < (3, 0): + from hashlib import _hash as _Hash +else: + from hashlib import _Hash + +class SupportsClose(Protocol): + def close(self) -> None: ... + +_T = TypeVar("_T") +_TC = TypeVar("_TC", bound=SupportsClose) + +def inflate_long(s: bytes, always_positive: bool = ...) -> int: ... + +deflate_zero: int +deflate_ff: int + +def deflate_long(n: int, add_sign_padding: bool = ...) -> bytes: ... +def format_binary(data: bytes, prefix: str = ...) -> List[str]: ... +def format_binary_line(data: bytes) -> str: ... +def safe_string(s: bytes) -> bytes: ... +def bit_length(n: int) -> int: ... +def tb_strings() -> List[str]: ... +def generate_key_bytes(hash_alg: Type[_Hash], salt: bytes, key: Union[bytes, str], nbytes: int) -> bytes: ... +def load_host_keys(filename: str) -> HostKeys: ... +def parse_ssh_config(file_obj: IO[str]) -> SSHConfig: ... +def lookup_ssh_host_config(hostname: str, config: SSHConfig) -> SSHConfigDict: ... +def mod_inverse(x: int, m: int) -> int: ... +def get_thread_id() -> int: ... +def log_to_file(filename: str, level: int = ...) -> None: ... + +class PFilter: + def filter(self, record: LogRecord) -> bool: ... + +def get_logger(name: str) -> Logger: ... +def retry_on_signal(function: Callable[[], _T]) -> _T: ... +def constant_time_bytes_eq(a: AnyStr, b: AnyStr) -> bool: ... + +class ClosingContextManager: + def __enter__(self: _TC) -> _TC: ... + def __exit__( + self: _TC, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> None: ... + +def clamp_value(minimum: int, val: int, maximum: int) -> int: ... diff --git a/shared/package-files/77/7714f261af4881a00d0d133857b8b4a9c69147ec1d37ac8ce98eaa85c65a7d04/blob b/shared/package-files/77/7714f261af4881a00d0d133857b8b4a9c69147ec1d37ac8ce98eaa85c65a7d04/blob new file mode 100644 index 0000000000000000000000000000000000000000..eec3b2bd3e1a2a765af57fe2a3147295a19d842d --- /dev/null +++ b/shared/package-files/77/7714f261af4881a00d0d133857b8b4a9c69147ec1d37ac8ce98eaa85c65a7d04/blob @@ -0,0 +1,221 @@ +/* + * This C file is compiled and linked into pycc-generated shared objects. + * It provides the Numba helper functions for runtime use in pycc-compiled + * functions. + */ + +#include "../_numba_common.h" +#include "../_pymodule.h" + +/* Define all runtime-required symbols in this C module, but do not + export them outside the shared library if possible. */ + +#define NUMBA_EXPORT_FUNC(_rettype) VISIBILITY_HIDDEN _rettype +#define NUMBA_EXPORT_DATA(_vartype) VISIBILITY_HIDDEN _vartype + +#define PYCC_COMPILING + +#include "../_helperlib.c" +#include "../_dynfunc.c" + +#if PYCC_USE_NRT +#include "../core/runtime/_nrt_python.c" +#include "../core/runtime/nrt.h" +#endif + +#if (PY_MAJOR_VERSION == 3) && (PY_MINOR_VERSION >= 12) + #define Py_BUILD_CORE 1 + #include "internal/pycore_pyhash.h" + #undef Py_BUILD_CORE +#endif + +/* Defines hashsecret variables (see issue #6386) */ +int64_t _numba_hashsecret_siphash_k0; +int64_t _numba_hashsecret_siphash_k1; +int64_t _numba_hashsecret_djbx33a_suffix; + +/* NOTE: import_array() is macro, not a function. It returns NULL on + failure */ +static void * +wrap_import_array(void) { + import_array(); + return (void *) 1; +} + + +static int +init_numpy(void) { + return wrap_import_array() != NULL; +} + + +#ifndef PYCC_MODULE_NAME +#error PYCC_MODULE_NAME must be defined +#endif + +/* Preprocessor trick: need to use two levels of macros otherwise + PYCC_MODULE_NAME would not get expanded */ +#define __PYCC(prefix, modname) prefix ## modname +#define _PYCC(prefix, modname) __PYCC(prefix, modname) +#define PYCC(prefix) _PYCC(prefix, PYCC_MODULE_NAME) + +/* Silence warnings about unused functions */ +VISIBILITY_HIDDEN void **PYCC(_unused_) = { + (void *) Numba_make_generator, +}; + +/* The structure type constructed by PythonAPI.serialize_uncached() */ +typedef struct { + const char *data; + int len; + const char *hashbuf; + const char *func_ptr; // pointer to unwrap dyn args function + int alloc_flag; +} env_def_t; + +/* Environment GlobalVariable address type */ +typedef void **env_gv_t; + +/* + * Recreate an environment object from a env_def_t structure. + */ +static EnvironmentObject * +recreate_environment(PyObject *module, env_def_t env) +{ + EnvironmentObject *envobj; + PyObject *env_consts; + + env_consts = numba_unpickle(env.data, env.len, env.hashbuf); + if (env_consts == NULL) + return NULL; + if (!PyList_Check(env_consts)) { + PyErr_Format(PyExc_TypeError, + "environment constants should be a list, got '%s'", + Py_TYPE(env_consts)->tp_name); + Py_DECREF(env_consts); + return NULL; + } + + envobj = env_new_empty(&EnvironmentType); + if (envobj == NULL) { + Py_DECREF(env_consts); + return NULL; + } + envobj->consts = env_consts; + envobj->globals = PyModule_GetDict(module); + if (envobj->globals == NULL) { + Py_DECREF(envobj); + return NULL; + } + Py_INCREF(envobj->globals); + return envobj; +} + +/* + * Subroutine to initialize all resources required for running the + * pycc-compiled functions. + */ + +int +PYCC(pycc_init_) (PyObject *module, PyMethodDef *defs, + env_def_t *envs, + env_gv_t *envgvs) +{ + /* Aligns hashsecret with values in current python process so that + * hashes computed inside the pycc module are correct if imported + * by the current process. Imports in a new process get the right + * hash secret through: + * `numba.cpython.hashing._load_hashsecret`. + */ + _numba_hashsecret_siphash_k0 = _Py_HashSecret.siphash.k0; + _numba_hashsecret_siphash_k1 = _Py_HashSecret.siphash.k1; + _numba_hashsecret_djbx33a_suffix = _Py_HashSecret.djbx33a.suffix; + + PyMethodDef *fdef; + PyObject *modname = NULL; + PyObject *docobj = NULL; + int i; + + if (!init_numpy()) { + goto error; + } + if (init_dynfunc_module(module)) { + goto error; + } + /* Initialize random generation. */ + numba_rnd_ensure_global_init(); + +#if PYCC_USE_NRT + NRT_MemSys_init(); + if (init_nrt_python_module(module)) { + goto error; + } +#endif + + modname = PyObject_GetAttrString(module, "__name__"); + if (modname == NULL) { + goto error; + } + + /* Empty docstring for all compiled functions */ + docobj = PyString_FromString(""); + if (docobj == NULL) { + goto error; + } + + /* Overwrite C method objects with our own Closure objects, in order + * to make their environments available to the compiled functions. + */ + for (i = 0, fdef = defs; fdef->ml_name != NULL; i++, fdef++) { + PyObject *func; + PyObject *nameobj; + EnvironmentObject *envobj; + + envobj = recreate_environment(module, envs[i]); + if (envobj == NULL) { + goto error; + } + nameobj = PyString_FromString(fdef->ml_name); + if (nameobj == NULL) { + Py_DECREF(envobj); + goto error; + } + // Store the environment pointer into the global + *envgvs[i] = envobj; + + func = pycfunction_new(module, nameobj, docobj, + fdef->ml_meth, envobj, NULL); + Py_DECREF(envobj); + Py_DECREF(nameobj); + + if (func == NULL) { + goto error; + } + if (PyObject_SetAttrString(module, fdef->ml_name, func)) { + Py_DECREF(func); + goto error; + } + Py_DECREF(func); + } + /* Recreate other environment objects + envgvs is expected to end with a NULL pointer. + */ + for (; envgvs[i]; ++i) { + EnvironmentObject *envobj; + envobj = recreate_environment(module, envs[i]); + if (envobj == NULL) { + goto error; + } + // Store the environment pointer into the global + *envgvs[i] = envobj; + Py_DECREF(envobj); + } + Py_DECREF(docobj); + Py_DECREF(modname); + return 0; + +error: + Py_XDECREF(docobj); + Py_XDECREF(modname); + return -1; +} diff --git a/shared/package-files/77/7716ea5f9fcf0ff244012666654e92578d1679bf5dd762a439b9f9a5be21467f/blob b/shared/package-files/77/7716ea5f9fcf0ff244012666654e92578d1679bf5dd762a439b9f9a5be21467f/blob new file mode 100644 index 0000000000000000000000000000000000000000..a1a3d7fe497897748054de4b2e954b13fd66a78e --- /dev/null +++ b/shared/package-files/77/7716ea5f9fcf0ff244012666654e92578d1679bf5dd762a439b9f9a5be21467f/blob @@ -0,0 +1,139 @@ +# search.tcl -- +# +# This demonstration script creates a collection of widgets that +# allow you to load a file into a text widget, then perform searches +# on that file. + +if {![info exists widgetDemo]} { + error "This script should be run from the \"widget\" demo." +} + +package require Tk + +# textLoadFile -- +# This procedure below loads a file into a text widget, discarding +# the previous contents of the widget. Tags for the old widget are +# not affected, however. +# +# Arguments: +# w - The window into which to load the file. Must be a +# text widget. +# file - The name of the file to load. Must be readable. + +proc textLoadFile {w file} { + set f [open $file] + $w delete 1.0 end + while {![eof $f]} { + $w insert end [read $f 10000] + } + close $f +} + +# textSearch -- +# Search for all instances of a given string in a text widget and +# apply a given tag to each instance found. +# +# Arguments: +# w - The window in which to search. Must be a text widget. +# string - The string to search for. The search is done using +# exact matching only; no special characters. +# tag - Tag to apply to each instance of a matching string. + +proc textSearch {w string tag} { + $w tag remove search 0.0 end + if {$string == ""} { + return + } + set cur 1.0 + while 1 { + set cur [$w search -count length $string $cur end] + if {$cur == ""} { + break + } + $w tag add $tag $cur "$cur + $length char" + set cur [$w index "$cur + $length char"] + } +} + +# textToggle -- +# This procedure is invoked repeatedly to invoke two commands at +# periodic intervals. It normally reschedules itself after each +# execution but if an error occurs (e.g. because the window was +# deleted) then it doesn't reschedule itself. +# +# Arguments: +# cmd1 - Command to execute when procedure is called. +# sleep1 - Ms to sleep after executing cmd1 before executing cmd2. +# cmd2 - Command to execute in the *next* invocation of this +# procedure. +# sleep2 - Ms to sleep after executing cmd2 before executing cmd1 again. + +proc textToggle {cmd1 sleep1 cmd2 sleep2} { + catch { + eval $cmd1 + after $sleep1 [list textToggle $cmd2 $sleep2 $cmd1 $sleep1] + } +} + +set w .search +catch {destroy $w} +toplevel $w +wm title $w "Text Demonstration - Search and Highlight" +wm iconname $w "search" +positionWindow $w + +## See Code / Dismiss buttons +set btns [addSeeDismiss $w.buttons $w] +pack $btns -side bottom -fill x + +frame $w.file +label $w.file.label -text "File name:" -width 13 -anchor w +entry $w.file.entry -width 40 -textvariable fileName +button $w.file.button -text "Load File" \ + -command "textLoadFile $w.text \$fileName" +pack $w.file.label $w.file.entry -side left +pack $w.file.button -side left -pady 5 -padx 10 +bind $w.file.entry " + textLoadFile $w.text \$fileName + focus $w.string.entry +" +focus $w.file.entry + +frame $w.string +label $w.string.label -text "Search string:" -width 13 -anchor w +entry $w.string.entry -width 40 -textvariable searchString +button $w.string.button -text "Highlight" \ + -command "textSearch $w.text \$searchString search" +pack $w.string.label $w.string.entry -side left +pack $w.string.button -side left -pady 5 -padx 10 +bind $w.string.entry "textSearch $w.text \$searchString search" + +text $w.text -yscrollcommand "$w.scroll set" -setgrid true +ttk::scrollbar $w.scroll -command "$w.text yview" +pack $w.file $w.string -side top -fill x +pack $w.scroll -side right -fill y +pack $w.text -expand yes -fill both + +# Set up display styles for text highlighting. + +if {[winfo depth $w] > 1} { + textToggle "$w.text tag configure search -background \ + #ce5555 -foreground white" 800 "$w.text tag configure \ + search -background {} -foreground {}" 200 +} else { + textToggle "$w.text tag configure search -background \ + black -foreground white" 800 "$w.text tag configure \ + search -background {} -foreground {}" 200 +} +$w.text insert 1.0 \ +{This window demonstrates how to use the tagging facilities in text +widgets to implement a searching mechanism. First, type a file name +in the top entry, then type or click on "Load File". Then +type a string in the lower entry and type or click on +"Load File". This will cause all of the instances of the string to +be tagged with the tag "search", and it will arrange for the tag's +display attributes to change to make all of the strings blink.} +$w.text mark set insert 0.0 + +set fileName "" +set searchString "" diff --git a/shared/package-files/77/771baa4e2d41cbfb53d6e4f1cff3974b97e11bdad3f067eff43afe4b1f201469/blob b/shared/package-files/77/771baa4e2d41cbfb53d6e4f1cff3974b97e11bdad3f067eff43afe4b1f201469/blob new file mode 100644 index 0000000000000000000000000000000000000000..589a0c39e514a17119c508cdb6bc24b9da58eda7 --- /dev/null +++ b/shared/package-files/77/771baa4e2d41cbfb53d6e4f1cff3974b97e11bdad3f067eff43afe4b1f201469/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:771baa4e2d41cbfb53d6e4f1cff3974b97e11bdad3f067eff43afe4b1f201469 +size 5131024 diff --git a/shared/package-files/77/771dd9fbce787c68ecd4eba92b650fa3330c31889cdde42bbe0a05f05fae8c25/blob b/shared/package-files/77/771dd9fbce787c68ecd4eba92b650fa3330c31889cdde42bbe0a05f05fae8c25/blob new file mode 100644 index 0000000000000000000000000000000000000000..c92b1a55d55400e254adc47a2978f46b9cf46a58 Binary files /dev/null and b/shared/package-files/77/771dd9fbce787c68ecd4eba92b650fa3330c31889cdde42bbe0a05f05fae8c25/blob differ diff --git a/shared/package-files/77/772062fa52af8a61f5bbf93aa7b6742492bbd9086a56d541b2a072be910f2af7/blob b/shared/package-files/77/772062fa52af8a61f5bbf93aa7b6742492bbd9086a56d541b2a072be910f2af7/blob new file mode 100644 index 0000000000000000000000000000000000000000..f74d1f7442473997245ac683b8a269a3574d1ba4 --- /dev/null +++ b/shared/package-files/77/772062fa52af8a61f5bbf93aa7b6742492bbd9086a56d541b2a072be910f2af7/blob @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +""" +This module offers a generic Easter computing method for any given year, using +Western, Orthodox or Julian algorithms. +""" + +import datetime + +__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] + +EASTER_JULIAN = 1 +EASTER_ORTHODOX = 2 +EASTER_WESTERN = 3 + + +def easter(year, method=EASTER_WESTERN): + """ + This method was ported from the work done by GM Arts, + on top of the algorithm by Claus Tondering, which was + based in part on the algorithm of Ouding (1940), as + quoted in "Explanatory Supplement to the Astronomical + Almanac", P. Kenneth Seidelmann, editor. + + This algorithm implements three different Easter + calculation methods: + + 1. Original calculation in Julian calendar, valid in + dates after 326 AD + 2. Original method, with date converted to Gregorian + calendar, valid in years 1583 to 4099 + 3. Revised method, in Gregorian calendar, valid in + years 1583 to 4099 as well + + These methods are represented by the constants: + + * ``EASTER_JULIAN = 1`` + * ``EASTER_ORTHODOX = 2`` + * ``EASTER_WESTERN = 3`` + + The default method is method 3. + + More about the algorithm may be found at: + + `GM Arts: Easter Algorithms `_ + + and + + `The Calendar FAQ: Easter `_ + + """ + + if not (1 <= method <= 3): + raise ValueError("invalid method") + + # g - Golden year - 1 + # c - Century + # h - (23 - Epact) mod 30 + # i - Number of days from March 21 to Paschal Full Moon + # j - Weekday for PFM (0=Sunday, etc) + # p - Number of days from March 21 to Sunday on or before PFM + # (-6 to 28 methods 1 & 3, to 56 for method 2) + # e - Extra days to add for method 2 (converting Julian + # date to Gregorian date) + + y = year + g = y % 19 + e = 0 + if method < 3: + # Old method + i = (19*g + 15) % 30 + j = (y + y//4 + i) % 7 + if method == 2: + # Extra dates to convert Julian to Gregorian date + e = 10 + if y > 1600: + e = e + y//100 - 16 - (y//100 - 16)//4 + else: + # New method + c = y//100 + h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 + i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) + j = (y + y//4 + i + 2 - c + c//4) % 7 + + # p can be from -6 to 56 corresponding to dates 22 March to 23 May + # (later dates apply to method 2, although 23 May never actually occurs) + p = i - j + e + d = 1 + (p + 27 + (p + 6)//40) % 31 + m = 3 + (p + 26)//30 + return datetime.date(int(y), int(m), int(d)) diff --git a/shared/package-files/77/77236d0eb9da6ef0a94159bb8bc4d54290cc22f58aa0aff6a2d260778d615182/blob b/shared/package-files/77/77236d0eb9da6ef0a94159bb8bc4d54290cc22f58aa0aff6a2d260778d615182/blob new file mode 100644 index 0000000000000000000000000000000000000000..5101a6f87487f845c8e3dc37e692af8aa247e95c --- /dev/null +++ b/shared/package-files/77/77236d0eb9da6ef0a94159bb8bc4d54290cc22f58aa0aff6a2d260778d615182/blob @@ -0,0 +1,27 @@ +from typing import Any, Iterable, List, Optional, TextIO, Tuple, TypeVar, Union + +_T = TypeVar("_T") + +class Popen3: + sts: int + cmd: Iterable[Any] + pid: int + tochild: TextIO + fromchild: TextIO + childerr: Optional[TextIO] + def __init__(self, cmd: Iterable[Any] = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ... + def __del__(self) -> None: ... + def poll(self, _deadstate: _T = ...) -> Union[int, _T]: ... + def wait(self) -> int: ... + +class Popen4(Popen3): + childerr: None + cmd: Iterable[Any] + pid: int + tochild: TextIO + fromchild: TextIO + def __init__(self, cmd: Iterable[Any] = ..., bufsize: int = ...) -> None: ... + +def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... +def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... +def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... diff --git a/shared/package-files/77/7724ba8e0f210871e45d6bec7dc20c3bcae396ffdb773031884d25924cc9e619/blob b/shared/package-files/77/7724ba8e0f210871e45d6bec7dc20c3bcae396ffdb773031884d25924cc9e619/blob new file mode 100644 index 0000000000000000000000000000000000000000..bc30e96adc75f793da4efdd21e3aff9b501659ed --- /dev/null +++ b/shared/package-files/77/7724ba8e0f210871e45d6bec7dc20c3bcae396ffdb773031884d25924cc9e619/blob @@ -0,0 +1 @@ +lark diff --git a/shared/package-files/77/77274880b0a7d929d0e8769057df6b4813165e7c87d379e153198a55bb1ed3dc/blob b/shared/package-files/77/77274880b0a7d929d0e8769057df6b4813165e7c87d379e153198a55bb1ed3dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..91f8c9649d8ac0f2e5172c969bf48a6eefcddca3 --- /dev/null +++ b/shared/package-files/77/77274880b0a7d929d0e8769057df6b4813165e7c87d379e153198a55bb1ed3dc/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API relu { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::relu") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "relu(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API relu_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::relu_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "relu_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API relu_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::relu") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "relu.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/77/772812daa01cb13d124f87456089e0be6626a6915a86b8d3a27b41ab309d5c7a/blob b/shared/package-files/77/772812daa01cb13d124f87456089e0be6626a6915a86b8d3a27b41ab309d5c7a/blob new file mode 100644 index 0000000000000000000000000000000000000000..abbc6e075821bbe903c673efd10f5fc1e50b3197 --- /dev/null +++ b/shared/package-files/77/772812daa01cb13d124f87456089e0be6626a6915a86b8d3a27b41ab309d5c7a/blob @@ -0,0 +1,36 @@ +IV1,IV2,IV3,DUM1,DUM2,DV +144.6,-0.02036,0.03699,0,0,0.01291 +30,-0.09591,-0.25186,0,0,-0.04267 +-293.1,-0.2668,0.93698,0,0,-0.25406 +-166,-0.11855,0.73074,1,0,0.34175 +-43.5,0.14966,-0.29941,0,0,0.10051 +43.7,0.14612,-0.25366,0,0,0.13155 +182.4,0.05158,-0.2597,0,0,0.09492 +114.6,0.0553,-0.01949,0,0,0.03839 +207.5,-0.12244,-0.11013,0,0,0.0188 +169.1,0.10412,0.67668,0,0,0.01934 +172.5,0.10573,-0.28238,0,0,0.10318 +8.2,0.05749,-0.28363,0,0,0.06143 +222.5,-0.00469,0.24894,0,0,0.00608 +126.2,-0.17023,-0.22687,0,0,-0.00281 +198.2,0.10886,1.11175,0,0,0.01905 +188.6,0.11647,-0.05312,0,0,0.06962 +148,-0.03671,-0.49461,0,1,0.21069 +106,0.05481,0.16064,0,0,0.06319 +69.4,-0.00402,-0.23218,0,0,0.03645 +178.1,0.10007,0.10992,0,0,0.0444 +66,0.02262,-0.16417,0,0,0.02033 +207.9,0.05493,0.07899,0,0,0.06044 +250.6,0.09136,-0.16984,0,0,0.06762 +31.4,0.01524,0.19577,0,0,0.03301 +289.6,0.04258,0.05408,0,0,0.01857 +301.4,-0.00535,-0.20569,0,0,0.06799 +113.6,0.04613,0,0,0,0.01813 +138.8,0.01312,0.5414,0,0,0.02022 +218.5,-0.00354,-0.14705,0,0,0.01317 +134.5,-0.08043,-0.15811,0,0,-0.00628 +59.5,0.05562,1.16127,0,0,0.02035 +38,0.00371,-0.40133,0,0,-0.04564 +212.8,0.02066,0.15375,0,0,0.04537 +191.1,0.03843,-0.08458,0,0,0.07685 +176.4,0.03534,-0.29581,0,0,0.03299 diff --git a/shared/package-files/77/772acd85bd84c5637b1cef3e0c695ba1e8aea5ece6358d49a6c37793c9db6358/blob b/shared/package-files/77/772acd85bd84c5637b1cef3e0c695ba1e8aea5ece6358d49a6c37793c9db6358/blob new file mode 100644 index 0000000000000000000000000000000000000000..a4f3b86ade0e60b6c8c72439ed3a39d6be0710e4 --- /dev/null +++ b/shared/package-files/77/772acd85bd84c5637b1cef3e0c695ba1e8aea5ece6358d49a6c37793c9db6358/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_cdist_backward(Tensor grad, Tensor x1, Tensor x2, float p, Tensor cdist) -> Tensor +inline at::Tensor _cdist_backward(const at::Tensor & grad, const at::Tensor & x1, const at::Tensor & x2, double p, const at::Tensor & cdist) { + return at::_ops::_cdist_backward::call(grad, x1, x2, p, cdist); +} + +// aten::_cdist_backward.out(Tensor grad, Tensor x1, Tensor x2, float p, Tensor cdist, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _cdist_backward_out(at::Tensor & out, const at::Tensor & grad, const at::Tensor & x1, const at::Tensor & x2, double p, const at::Tensor & cdist) { + return at::_ops::_cdist_backward_out::call(grad, x1, x2, p, cdist, out); +} +// aten::_cdist_backward.out(Tensor grad, Tensor x1, Tensor x2, float p, Tensor cdist, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _cdist_backward_outf(const at::Tensor & grad, const at::Tensor & x1, const at::Tensor & x2, double p, const at::Tensor & cdist, at::Tensor & out) { + return at::_ops::_cdist_backward_out::call(grad, x1, x2, p, cdist, out); +} + +} diff --git a/shared/package-files/77/772c1718faebf9eb1ced75fb0a47be4132a1ccbf72d868294adb4f0d678e6fda/blob b/shared/package-files/77/772c1718faebf9eb1ced75fb0a47be4132a1ccbf72d868294adb4f0d678e6fda/blob new file mode 100644 index 0000000000000000000000000000000000000000..d29b25a54f9c19f9cce2d73d5f85a0f9cac1a043 Binary files /dev/null and b/shared/package-files/77/772c1718faebf9eb1ced75fb0a47be4132a1ccbf72d868294adb4f0d678e6fda/blob differ diff --git a/shared/package-files/77/772d6693d5e1ddb6cae4a380affe29654502acc11175afb2f34401fd0194556b/blob b/shared/package-files/77/772d6693d5e1ddb6cae4a380affe29654502acc11175afb2f34401fd0194556b/blob new file mode 100644 index 0000000000000000000000000000000000000000..5c6d4e7c1e84d9f967a80b2d84061ab1b8ce0aa9 --- /dev/null +++ b/shared/package-files/77/772d6693d5e1ddb6cae4a380affe29654502acc11175afb2f34401fd0194556b/blob @@ -0,0 +1,920 @@ +import gc +import pickle +import platform +import weakref + +import pytest + +import networkx as nx +from networkx.utils import edges_equal, graphs_equal, nodes_equal + + +class BaseGraphTester: + """Tests for data-structure independent graph class features.""" + + def test_contains(self): + G = self.K3 + assert 1 in G + assert 4 not in G + assert "b" not in G + assert [] not in G # no exception for nonhashable + assert {1: 1} not in G # no exception for nonhashable + + def test_order(self): + G = self.K3 + assert len(G) == 3 + assert G.order() == 3 + assert G.number_of_nodes() == 3 + + def test_nodes(self): + G = self.K3 + assert isinstance(G._node, G.node_dict_factory) + assert isinstance(G._adj, G.adjlist_outer_dict_factory) + assert all( + isinstance(adj, G.adjlist_inner_dict_factory) for adj in G._adj.values() + ) + assert sorted(G.nodes()) == self.k3nodes + assert sorted(G.nodes(data=True)) == [(0, {}), (1, {}), (2, {})] + + def test_none_node(self): + G = self.Graph() + with pytest.raises(ValueError): + G.add_node(None) + with pytest.raises(ValueError): + G.add_nodes_from([None]) + with pytest.raises(ValueError): + G.add_edge(0, None) + with pytest.raises(ValueError): + G.add_edges_from([(0, None)]) + + def test_has_node(self): + G = self.K3 + assert G.has_node(1) + assert not G.has_node(4) + assert not G.has_node([]) # no exception for nonhashable + assert not G.has_node({1: 1}) # no exception for nonhashable + + def test_has_edge(self): + G = self.K3 + assert G.has_edge(0, 1) + assert not G.has_edge(0, -1) + + def test_neighbors(self): + G = self.K3 + assert sorted(G.neighbors(0)) == [1, 2] + with pytest.raises(nx.NetworkXError): + G.neighbors(-1) + + @pytest.mark.skipif( + platform.python_implementation() == "PyPy", reason="PyPy gc is different" + ) + def test_memory_leak(self): + G = self.Graph() + + def count_objects_of_type(_type): + # Iterating over all objects tracked by gc can include weak references + # whose weakly-referenced objects may no longer exist. Calling `isinstance` + # on such a weak reference will raise ReferenceError. There are at least + # three workarounds for this: one is to compare type names instead of using + # `isinstance` such as `type(obj).__name__ == typename`, another is to use + # `type(obj) == _type`, and the last is to ignore ProxyTypes as we do below. + # NOTE: even if this safeguard is deemed unnecessary to pass NetworkX tests, + # we should still keep it for maximum safety for other NetworkX backends. + return sum( + 1 + for obj in gc.get_objects() + if not isinstance(obj, weakref.ProxyTypes) and isinstance(obj, _type) + ) + + gc.collect() + before = count_objects_of_type(self.Graph) + G.copy() + gc.collect() + after = count_objects_of_type(self.Graph) + assert before == after + + # test a subgraph of the base class + class MyGraph(self.Graph): + pass + + gc.collect() + G = MyGraph() + before = count_objects_of_type(MyGraph) + G.copy() + gc.collect() + after = count_objects_of_type(MyGraph) + assert before == after + + def test_edges(self): + G = self.K3 + assert isinstance(G._adj, G.adjlist_outer_dict_factory) + assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)]) + assert edges_equal(G.edges(0), [(0, 1), (0, 2)]) + assert edges_equal(G.edges([0, 1]), [(0, 1), (0, 2), (1, 2)]) + with pytest.raises(nx.NetworkXError): + G.edges(-1) + + def test_degree(self): + G = self.K3 + assert sorted(G.degree()) == [(0, 2), (1, 2), (2, 2)] + assert dict(G.degree()) == {0: 2, 1: 2, 2: 2} + assert G.degree(0) == 2 + with pytest.raises(nx.NetworkXError): + G.degree(-1) # node not in graph + + def test_size(self): + G = self.K3 + assert G.size() == 3 + assert G.number_of_edges() == 3 + + def test_nbunch_iter(self): + G = self.K3 + assert nodes_equal(G.nbunch_iter(), self.k3nodes) # all nodes + assert nodes_equal(G.nbunch_iter(0), [0]) # single node + assert nodes_equal(G.nbunch_iter([0, 1]), [0, 1]) # sequence + # sequence with none in graph + assert nodes_equal(G.nbunch_iter([-1]), []) + # string sequence with none in graph + assert nodes_equal(G.nbunch_iter("foo"), []) + # node not in graph doesn't get caught upon creation of iterator + bunch = G.nbunch_iter(-1) + # but gets caught when iterator used + with pytest.raises(nx.NetworkXError, match="is not a node or a sequence"): + list(bunch) + # unhashable doesn't get caught upon creation of iterator + bunch = G.nbunch_iter([0, 1, 2, {}]) + # but gets caught when iterator hits the unhashable + with pytest.raises( + nx.NetworkXError, match="in sequence nbunch is not a valid node" + ): + list(bunch) + + def test_nbunch_iter_node_format_raise(self): + # Tests that a node that would have failed string formatting + # doesn't cause an error when attempting to raise a + # :exc:`nx.NetworkXError`. + + # For more information, see pull request #1813. + G = self.Graph() + nbunch = [("x", set())] + with pytest.raises(nx.NetworkXError): + list(G.nbunch_iter(nbunch)) + + def test_selfloop_degree(self): + G = self.Graph() + G.add_edge(1, 1) + assert sorted(G.degree()) == [(1, 2)] + assert dict(G.degree()) == {1: 2} + assert G.degree(1) == 2 + assert sorted(G.degree([1])) == [(1, 2)] + assert G.degree(1, weight="weight") == 2 + + def test_selfloops(self): + G = self.K3.copy() + G.add_edge(0, 0) + assert nodes_equal(nx.nodes_with_selfloops(G), [0]) + assert edges_equal(nx.selfloop_edges(G), [(0, 0)]) + assert nx.number_of_selfloops(G) == 1 + G.remove_edge(0, 0) + G.add_edge(0, 0) + G.remove_edges_from([(0, 0)]) + G.add_edge(1, 1) + G.remove_node(1) + G.add_edge(0, 0) + G.add_edge(1, 1) + G.remove_nodes_from([0, 1]) + + def test_cache_reset(self): + G = self.K3.copy() + old_adj = G.adj + assert id(G.adj) == id(old_adj) + G._adj = {} + assert id(G.adj) != id(old_adj) + + old_nodes = G.nodes + assert id(G.nodes) == id(old_nodes) + G._node = {} + assert id(G.nodes) != id(old_nodes) + + def test_attributes_cached(self): + G = self.K3.copy() + assert id(G.nodes) == id(G.nodes) + assert id(G.edges) == id(G.edges) + assert id(G.degree) == id(G.degree) + assert id(G.adj) == id(G.adj) + + +class BaseAttrGraphTester(BaseGraphTester): + """Tests of graph class attribute features.""" + + def test_weighted_degree(self): + G = self.Graph() + G.add_edge(1, 2, weight=2, other=3) + G.add_edge(2, 3, weight=3, other=4) + assert sorted(d for n, d in G.degree(weight="weight")) == [2, 3, 5] + assert dict(G.degree(weight="weight")) == {1: 2, 2: 5, 3: 3} + assert G.degree(1, weight="weight") == 2 + assert nodes_equal((G.degree([1], weight="weight")), [(1, 2)]) + + assert nodes_equal((d for n, d in G.degree(weight="other")), [3, 7, 4]) + assert dict(G.degree(weight="other")) == {1: 3, 2: 7, 3: 4} + assert G.degree(1, weight="other") == 3 + assert edges_equal((G.degree([1], weight="other")), [(1, 3)]) + + def add_attributes(self, G): + G.graph["foo"] = [] + G.nodes[0]["foo"] = [] + G.remove_edge(1, 2) + ll = [] + G.add_edge(1, 2, foo=ll) + G.add_edge(2, 1, foo=ll) + + def test_name(self): + G = self.Graph(name="") + assert G.name == "" + G = self.Graph(name="test") + assert G.name == "test" + + def test_str_unnamed(self): + G = self.Graph() + G.add_edges_from([(1, 2), (2, 3)]) + assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges" + + def test_str_named(self): + G = self.Graph(name="foo") + G.add_edges_from([(1, 2), (2, 3)]) + assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges" + + def test_graph_chain(self): + G = self.Graph([(0, 1), (1, 2)]) + DG = G.to_directed(as_view=True) + SDG = DG.subgraph([0, 1]) + RSDG = SDG.reverse(copy=False) + assert G is DG._graph + assert DG is SDG._graph + assert SDG is RSDG._graph + + def test_copy(self): + G = self.Graph() + G.add_node(0) + G.add_edge(1, 2) + self.add_attributes(G) + # copy edge datadict but any container attr are same + H = G.copy() + self.graphs_equal(H, G) + self.different_attrdict(H, G) + self.shallow_copy_attrdict(H, G) + + def test_class_copy(self): + G = self.Graph() + G.add_node(0) + G.add_edge(1, 2) + self.add_attributes(G) + # copy edge datadict but any container attr are same + H = G.__class__(G) + self.graphs_equal(H, G) + self.different_attrdict(H, G) + self.shallow_copy_attrdict(H, G) + + def test_fresh_copy(self): + G = self.Graph() + G.add_node(0) + G.add_edge(1, 2) + self.add_attributes(G) + # copy graph structure but use fresh datadict + H = G.__class__() + H.add_nodes_from(G) + H.add_edges_from(G.edges()) + assert len(G.nodes[0]) == 1 + ddict = G.adj[1][2][0] if G.is_multigraph() else G.adj[1][2] + assert len(ddict) == 1 + assert len(H.nodes[0]) == 0 + ddict = H.adj[1][2][0] if H.is_multigraph() else H.adj[1][2] + assert len(ddict) == 0 + + def is_deepcopy(self, H, G): + self.graphs_equal(H, G) + self.different_attrdict(H, G) + self.deep_copy_attrdict(H, G) + + def deep_copy_attrdict(self, H, G): + self.deepcopy_graph_attr(H, G) + self.deepcopy_node_attr(H, G) + self.deepcopy_edge_attr(H, G) + + def deepcopy_graph_attr(self, H, G): + assert G.graph["foo"] == H.graph["foo"] + G.graph["foo"].append(1) + assert G.graph["foo"] != H.graph["foo"] + + def deepcopy_node_attr(self, H, G): + assert G.nodes[0]["foo"] == H.nodes[0]["foo"] + G.nodes[0]["foo"].append(1) + assert G.nodes[0]["foo"] != H.nodes[0]["foo"] + + def deepcopy_edge_attr(self, H, G): + assert G[1][2]["foo"] == H[1][2]["foo"] + G[1][2]["foo"].append(1) + assert G[1][2]["foo"] != H[1][2]["foo"] + + def is_shallow_copy(self, H, G): + self.graphs_equal(H, G) + self.shallow_copy_attrdict(H, G) + + def shallow_copy_attrdict(self, H, G): + self.shallow_copy_graph_attr(H, G) + self.shallow_copy_node_attr(H, G) + self.shallow_copy_edge_attr(H, G) + + def shallow_copy_graph_attr(self, H, G): + assert G.graph["foo"] == H.graph["foo"] + G.graph["foo"].append(1) + assert G.graph["foo"] == H.graph["foo"] + + def shallow_copy_node_attr(self, H, G): + assert G.nodes[0]["foo"] == H.nodes[0]["foo"] + G.nodes[0]["foo"].append(1) + assert G.nodes[0]["foo"] == H.nodes[0]["foo"] + + def shallow_copy_edge_attr(self, H, G): + assert G[1][2]["foo"] == H[1][2]["foo"] + G[1][2]["foo"].append(1) + assert G[1][2]["foo"] == H[1][2]["foo"] + + def same_attrdict(self, H, G): + old_foo = H[1][2]["foo"] + H.adj[1][2]["foo"] = "baz" + assert G.edges == H.edges + H.adj[1][2]["foo"] = old_foo + assert G.edges == H.edges + + old_foo = H.nodes[0]["foo"] + H.nodes[0]["foo"] = "baz" + assert G.nodes == H.nodes + H.nodes[0]["foo"] = old_foo + assert G.nodes == H.nodes + + def different_attrdict(self, H, G): + old_foo = H[1][2]["foo"] + H.adj[1][2]["foo"] = "baz" + assert G._adj != H._adj + H.adj[1][2]["foo"] = old_foo + assert G._adj == H._adj + + old_foo = H.nodes[0]["foo"] + H.nodes[0]["foo"] = "baz" + assert G._node != H._node + H.nodes[0]["foo"] = old_foo + assert G._node == H._node + + def graphs_equal(self, H, G): + assert G._adj == H._adj + assert G._node == H._node + assert G.graph == H.graph + assert G.name == H.name + if not G.is_directed() and not H.is_directed(): + assert H._adj[1][2] is H._adj[2][1] + assert G._adj[1][2] is G._adj[2][1] + else: # at least one is directed + if not G.is_directed(): + G._pred = G._adj + G._succ = G._adj + if not H.is_directed(): + H._pred = H._adj + H._succ = H._adj + assert G._pred == H._pred + assert G._succ == H._succ + assert H._succ[1][2] is H._pred[2][1] + assert G._succ[1][2] is G._pred[2][1] + + def test_graph_attr(self): + G = self.K3.copy() + G.graph["foo"] = "bar" + assert isinstance(G.graph, G.graph_attr_dict_factory) + assert G.graph["foo"] == "bar" + del G.graph["foo"] + assert G.graph == {} + H = self.Graph(foo="bar") + assert H.graph["foo"] == "bar" + + def test_node_attr(self): + G = self.K3.copy() + G.add_node(1, foo="bar") + assert all( + isinstance(d, G.node_attr_dict_factory) for u, d in G.nodes(data=True) + ) + assert nodes_equal(G.nodes(), [0, 1, 2]) + assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "bar"}), (2, {})]) + G.nodes[1]["foo"] = "baz" + assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "baz"}), (2, {})]) + assert nodes_equal(G.nodes(data="foo"), [(0, None), (1, "baz"), (2, None)]) + assert nodes_equal( + G.nodes(data="foo", default="bar"), [(0, "bar"), (1, "baz"), (2, "bar")] + ) + + def test_node_attr2(self): + G = self.K3.copy() + a = {"foo": "bar"} + G.add_node(3, **a) + assert nodes_equal(G.nodes(), [0, 1, 2, 3]) + assert nodes_equal( + G.nodes(data=True), [(0, {}), (1, {}), (2, {}), (3, {"foo": "bar"})] + ) + + def test_edge_lookup(self): + G = self.Graph() + G.add_edge(1, 2, foo="bar") + assert edges_equal(G.edges[1, 2], {"foo": "bar"}) + + def test_edge_attr(self): + G = self.Graph() + G.add_edge(1, 2, foo="bar") + assert all( + isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True) + ) + assert edges_equal(G.edges(data=True), [(1, 2, {"foo": "bar"})]) + assert edges_equal(G.edges(data="foo"), [(1, 2, "bar")]) + + def test_edge_attr2(self): + G = self.Graph() + G.add_edges_from([(1, 2), (3, 4)], foo="foo") + assert edges_equal( + G.edges(data=True), [(1, 2, {"foo": "foo"}), (3, 4, {"foo": "foo"})] + ) + assert edges_equal(G.edges(data="foo"), [(1, 2, "foo"), (3, 4, "foo")]) + + def test_edge_attr3(self): + G = self.Graph() + G.add_edges_from([(1, 2, {"weight": 32}), (3, 4, {"weight": 64})], foo="foo") + assert edges_equal( + G.edges(data=True), + [ + (1, 2, {"foo": "foo", "weight": 32}), + (3, 4, {"foo": "foo", "weight": 64}), + ], + ) + + G.remove_edges_from([(1, 2), (3, 4)]) + G.add_edge(1, 2, data=7, spam="bar", bar="foo") + assert edges_equal( + G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})] + ) + + def test_edge_attr4(self): + G = self.Graph() + G.add_edge(1, 2, data=7, spam="bar", bar="foo") + assert edges_equal( + G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})] + ) + G[1][2]["data"] = 10 # OK to set data like this + assert edges_equal( + G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})] + ) + + G.adj[1][2]["data"] = 20 + assert edges_equal( + G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})] + ) + G.edges[1, 2]["data"] = 21 # another spelling, "edge" + assert edges_equal( + G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})] + ) + G.adj[1][2]["listdata"] = [20, 200] + G.adj[1][2]["weight"] = 20 + dd = { + "data": 21, + "spam": "bar", + "bar": "foo", + "listdata": [20, 200], + "weight": 20, + } + assert edges_equal(G.edges(data=True), [(1, 2, dd)]) + + def test_to_undirected(self): + G = self.K3 + self.add_attributes(G) + H = nx.Graph(G) + self.is_shallow_copy(H, G) + self.different_attrdict(H, G) + H = G.to_undirected() + self.is_deepcopy(H, G) + + def test_to_directed_as_view(self): + H = nx.path_graph(2, create_using=self.Graph) + H2 = H.to_directed(as_view=True) + assert H is H2._graph + assert H2.has_edge(0, 1) + assert H2.has_edge(1, 0) or H.is_directed() + pytest.raises(nx.NetworkXError, H2.add_node, -1) + pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2) + H.add_edge(1, 2) + assert H2.has_edge(1, 2) + assert H2.has_edge(2, 1) or H.is_directed() + + def test_to_undirected_as_view(self): + H = nx.path_graph(2, create_using=self.Graph) + H2 = H.to_undirected(as_view=True) + assert H is H2._graph + assert H2.has_edge(0, 1) + assert H2.has_edge(1, 0) + pytest.raises(nx.NetworkXError, H2.add_node, -1) + pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2) + H.add_edge(1, 2) + assert H2.has_edge(1, 2) + assert H2.has_edge(2, 1) + + def test_directed_class(self): + G = self.Graph() + + class newGraph(G.to_undirected_class()): + def to_directed_class(self): + return newDiGraph + + def to_undirected_class(self): + return newGraph + + class newDiGraph(G.to_directed_class()): + def to_directed_class(self): + return newDiGraph + + def to_undirected_class(self): + return newGraph + + G = newDiGraph() if G.is_directed() else newGraph() + H = G.to_directed() + assert isinstance(H, newDiGraph) + H = G.to_undirected() + assert isinstance(H, newGraph) + + def test_to_directed(self): + G = self.K3 + self.add_attributes(G) + H = nx.DiGraph(G) + self.is_shallow_copy(H, G) + self.different_attrdict(H, G) + H = G.to_directed() + self.is_deepcopy(H, G) + + def test_subgraph(self): + G = self.K3 + self.add_attributes(G) + H = G.subgraph([0, 1, 2, 5]) + self.graphs_equal(H, G) + self.same_attrdict(H, G) + self.shallow_copy_attrdict(H, G) + + H = G.subgraph(0) + assert H.adj == {0: {}} + H = G.subgraph([]) + assert H.adj == {} + assert G.adj != {} + + def test_selfloops_attr(self): + G = self.K3.copy() + G.add_edge(0, 0) + G.add_edge(1, 1, weight=2) + assert edges_equal( + nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})] + ) + assert edges_equal( + nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)] + ) + + +class TestGraph(BaseAttrGraphTester): + """Tests specific to dict-of-dict-of-dict graph data structure""" + + def setup_method(self): + self.Graph = nx.Graph + # build dict-of-dict-of-dict K3 + ed1, ed2, ed3 = ({}, {}, {}) + self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}} + self.k3edges = [(0, 1), (0, 2), (1, 2)] + self.k3nodes = [0, 1, 2] + self.K3 = self.Graph() + self.K3._adj = self.k3adj + self.K3._node = {} + self.K3._node[0] = {} + self.K3._node[1] = {} + self.K3._node[2] = {} + + def test_pickle(self): + G = self.K3 + pg = pickle.loads(pickle.dumps(G, -1)) + self.graphs_equal(pg, G) + pg = pickle.loads(pickle.dumps(G)) + self.graphs_equal(pg, G) + + def test_data_input(self): + G = self.Graph({1: [2], 2: [1]}, name="test") + assert G.name == "test" + assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})] + + def test_adjacency(self): + G = self.K3 + assert dict(G.adjacency()) == { + 0: {1: {}, 2: {}}, + 1: {0: {}, 2: {}}, + 2: {0: {}, 1: {}}, + } + + def test_getitem(self): + G = self.K3 + assert G.adj[0] == {1: {}, 2: {}} + assert G[0] == {1: {}, 2: {}} + with pytest.raises(KeyError): + G.__getitem__("j") + with pytest.raises(TypeError): + G.__getitem__(["A"]) + + def test_add_node(self): + G = self.Graph() + G.add_node(0) + assert G.adj == {0: {}} + # test add attributes + G.add_node(1, c="red") + G.add_node(2, c="blue") + G.add_node(3, c="red") + assert G.nodes[1]["c"] == "red" + assert G.nodes[2]["c"] == "blue" + assert G.nodes[3]["c"] == "red" + # test updating attributes + G.add_node(1, c="blue") + G.add_node(2, c="red") + G.add_node(3, c="blue") + assert G.nodes[1]["c"] == "blue" + assert G.nodes[2]["c"] == "red" + assert G.nodes[3]["c"] == "blue" + + def test_add_nodes_from(self): + G = self.Graph() + G.add_nodes_from([0, 1, 2]) + assert G.adj == {0: {}, 1: {}, 2: {}} + # test add attributes + G.add_nodes_from([0, 1, 2], c="red") + assert G.nodes[0]["c"] == "red" + assert G.nodes[2]["c"] == "red" + # test that attribute dicts are not the same + assert G.nodes[0] is not G.nodes[1] + # test updating attributes + G.add_nodes_from([0, 1, 2], c="blue") + assert G.nodes[0]["c"] == "blue" + assert G.nodes[2]["c"] == "blue" + assert G.nodes[0] is not G.nodes[1] + # test tuple input + H = self.Graph() + H.add_nodes_from(G.nodes(data=True)) + assert H.nodes[0]["c"] == "blue" + assert H.nodes[2]["c"] == "blue" + assert H.nodes[0] is not H.nodes[1] + # specific overrides general + H.add_nodes_from([0, (1, {"c": "green"}), (3, {"c": "cyan"})], c="red") + assert H.nodes[0]["c"] == "red" + assert H.nodes[1]["c"] == "green" + assert H.nodes[2]["c"] == "blue" + assert H.nodes[3]["c"] == "cyan" + + def test_remove_node(self): + G = self.K3.copy() + G.remove_node(0) + assert G.adj == {1: {2: {}}, 2: {1: {}}} + with pytest.raises(nx.NetworkXError): + G.remove_node(-1) + + # generator here to implement list,set,string... + + def test_remove_nodes_from(self): + G = self.K3.copy() + G.remove_nodes_from([0, 1]) + assert G.adj == {2: {}} + G.remove_nodes_from([-1]) # silent fail + + def test_add_edge(self): + G = self.Graph() + G.add_edge(0, 1) + assert G.adj == {0: {1: {}}, 1: {0: {}}} + G = self.Graph() + G.add_edge(*(0, 1)) + assert G.adj == {0: {1: {}}, 1: {0: {}}} + G = self.Graph() + with pytest.raises(ValueError): + G.add_edge(None, "anything") + + def test_add_edges_from(self): + G = self.Graph() + G.add_edges_from([(0, 1), (0, 2, {"weight": 3})]) + assert G.adj == { + 0: {1: {}, 2: {"weight": 3}}, + 1: {0: {}}, + 2: {0: {"weight": 3}}, + } + G = self.Graph() + G.add_edges_from([(0, 1), (0, 2, {"weight": 3}), (1, 2, {"data": 4})], data=2) + assert G.adj == { + 0: {1: {"data": 2}, 2: {"weight": 3, "data": 2}}, + 1: {0: {"data": 2}, 2: {"data": 4}}, + 2: {0: {"weight": 3, "data": 2}, 1: {"data": 4}}, + } + + with pytest.raises(nx.NetworkXError): + G.add_edges_from([(0,)]) # too few in tuple + with pytest.raises(nx.NetworkXError): + G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple + with pytest.raises(TypeError): + G.add_edges_from([0]) # not a tuple + with pytest.raises(ValueError): + G.add_edges_from([(None, 3), (3, 2)]) # None cannot be a node + + def test_remove_edge(self): + G = self.K3.copy() + G.remove_edge(0, 1) + assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}} + with pytest.raises(nx.NetworkXError): + G.remove_edge(-1, 0) + + def test_remove_edges_from(self): + G = self.K3.copy() + G.remove_edges_from([(0, 1)]) + assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}} + G.remove_edges_from([(0, 0)]) # silent fail + + def test_clear(self): + G = self.K3.copy() + G.graph["name"] = "K3" + G.clear() + assert list(G.nodes) == [] + assert G.adj == {} + assert G.graph == {} + + def test_clear_edges(self): + G = self.K3.copy() + G.graph["name"] = "K3" + nodes = list(G.nodes) + G.clear_edges() + assert list(G.nodes) == nodes + assert G.adj == {0: {}, 1: {}, 2: {}} + assert list(G.edges) == [] + assert G.graph["name"] == "K3" + + def test_edges_data(self): + G = self.K3 + all_edges = [(0, 1, {}), (0, 2, {}), (1, 2, {})] + assert edges_equal(G.edges(data=True), all_edges) + assert edges_equal(G.edges(0, data=True), [(0, 1, {}), (0, 2, {})]) + assert edges_equal(G.edges([0, 1], data=True), all_edges) + with pytest.raises(nx.NetworkXError): + G.edges(-1, True) + + def test_get_edge_data(self): + G = self.K3.copy() + assert G.get_edge_data(0, 1) == {} + assert G[0][1] == {} + assert G.get_edge_data(10, 20) is None + assert G.get_edge_data(-1, 0) is None + assert G.get_edge_data(-1, 0, default=1) == 1 + + def test_update(self): + # specify both edgees and nodes + G = self.K3.copy() + G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})]) + nlist = [ + (0, {}), + (1, {}), + (2, {}), + (3, {}), + (4, {"size": 2}), + (5, {}), + (6, {}), + (7, {}), + ] + assert sorted(G.nodes.data()) == nlist + if G.is_directed(): + elist = [ + (0, 1, {}), + (0, 2, {}), + (1, 0, {}), + (1, 2, {}), + (2, 0, {}), + (2, 1, {}), + (4, 5, {}), + (6, 7, {"weight": 2}), + ] + else: + elist = [ + (0, 1, {}), + (0, 2, {}), + (1, 2, {}), + (4, 5, {}), + (6, 7, {"weight": 2}), + ] + assert sorted(G.edges.data()) == elist + assert G.graph == {} + + # no keywords -- order is edges, nodes + G = self.K3.copy() + G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})]) + assert sorted(G.nodes.data()) == nlist + assert sorted(G.edges.data()) == elist + assert G.graph == {} + + # update using only a graph + G = self.Graph() + G.graph["foo"] = "bar" + G.add_node(2, data=4) + G.add_edge(0, 1, weight=0.5) + GG = G.copy() + H = self.Graph() + GG.update(H) + assert graphs_equal(G, GG) + H.update(G) + assert graphs_equal(H, G) + + # update nodes only + H = self.Graph() + H.update(nodes=[3, 4]) + assert H.nodes ^ {3, 4} == set() + assert H.size() == 0 + + # update edges only + H = self.Graph() + H.update(edges=[(3, 4)]) + assert sorted(H.edges.data()) == [(3, 4, {})] + assert H.size() == 1 + + # No inputs -> exception + with pytest.raises(nx.NetworkXError): + nx.Graph().update() + + +class TestEdgeSubgraph: + """Unit tests for the :meth:`Graph.edge_subgraph` method.""" + + def setup_method(self): + # Create a path graph on five nodes. + G = nx.path_graph(5) + # Add some node, edge, and graph attributes. + for i in range(5): + G.nodes[i]["name"] = f"node{i}" + G.edges[0, 1]["name"] = "edge01" + G.edges[3, 4]["name"] = "edge34" + G.graph["name"] = "graph" + # Get the subgraph induced by the first and last edges. + self.G = G + self.H = G.edge_subgraph([(0, 1), (3, 4)]) + + def test_correct_nodes(self): + """Tests that the subgraph has the correct nodes.""" + assert [0, 1, 3, 4] == sorted(self.H.nodes()) + + def test_correct_edges(self): + """Tests that the subgraph has the correct edges.""" + assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name")) + + def test_add_node(self): + """Tests that adding a node to the original graph does not + affect the nodes of the subgraph. + + """ + self.G.add_node(5) + assert [0, 1, 3, 4] == sorted(self.H.nodes()) + + def test_remove_node(self): + """Tests that removing a node in the original graph does + affect the nodes of the subgraph. + + """ + self.G.remove_node(0) + assert [1, 3, 4] == sorted(self.H.nodes()) + + def test_node_attr_dict(self): + """Tests that the node attribute dictionary of the two graphs is + the same object. + + """ + for v in self.H: + assert self.G.nodes[v] == self.H.nodes[v] + # Making a change to G should make a change in H and vice versa. + self.G.nodes[0]["name"] = "foo" + assert self.G.nodes[0] == self.H.nodes[0] + self.H.nodes[1]["name"] = "bar" + assert self.G.nodes[1] == self.H.nodes[1] + + def test_edge_attr_dict(self): + """Tests that the edge attribute dictionary of the two graphs is + the same object. + + """ + for u, v in self.H.edges(): + assert self.G.edges[u, v] == self.H.edges[u, v] + # Making a change to G should make a change in H and vice versa. + self.G.edges[0, 1]["name"] = "foo" + assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"] + self.H.edges[3, 4]["name"] = "bar" + assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"] + + def test_graph_attr_dict(self): + """Tests that the graph attribute dictionary of the two graphs + is the same object. + + """ + assert self.G.graph is self.H.graph diff --git a/shared/package-files/77/772d6a5d11c35165ae78c58a4ae73dad57332b2b134f7199d9f1c5efb61e8a03/blob b/shared/package-files/77/772d6a5d11c35165ae78c58a4ae73dad57332b2b134f7199d9f1c5efb61e8a03/blob new file mode 100644 index 0000000000000000000000000000000000000000..4c38ad0839b6f2a11c2b61004f4c7096a8fa56fb --- /dev/null +++ b/shared/package-files/77/772d6a5d11c35165ae78c58a4ae73dad57332b2b134f7199d9f1c5efb61e8a03/blob @@ -0,0 +1,104 @@ +from itertools import combinations + +__all__ = ["dispersion"] + + +def dispersion(G, u=None, v=None, normalized=True, alpha=1.0, b=0.0, c=0.0): + r"""Calculate dispersion between `u` and `v` in `G`. + + A link between two actors (`u` and `v`) has a high dispersion when their + mutual ties (`s` and `t`) are not well connected with each other. + + Parameters + ---------- + G : graph + A NetworkX graph. + u : node, optional + The source for the dispersion score (e.g. ego node of the network). + v : node, optional + The target of the dispersion score if specified. + normalized : bool + If True (default) normalize by the embededness of the nodes (u and v). + alpha, b, c : float + Parameters for the normalization procedure. When `normalized` is True, + the dispersion value is normalized by:: + + result = ((dispersion + b) ** alpha) / (embeddedness + c) + + as long as the denominator is nonzero. + + Returns + ------- + nodes : dictionary + If u (v) is specified, returns a dictionary of nodes with dispersion + score for all "target" ("source") nodes. If neither u nor v is + specified, returns a dictionary of dictionaries for all nodes 'u' in the + graph with a dispersion score for each node 'v'. + + Notes + ----- + This implementation follows Lars Backstrom and Jon Kleinberg [1]_. Typical + usage would be to run dispersion on the ego network $G_u$ if $u$ were + specified. Running :func:`dispersion` with neither $u$ nor $v$ specified + can take some time to complete. + + References + ---------- + .. [1] Romantic Partnerships and the Dispersion of Social Ties: + A Network Analysis of Relationship Status on Facebook. + Lars Backstrom, Jon Kleinberg. + https://arxiv.org/pdf/1310.6753v1.pdf + + """ + + def _dispersion(G_u, u, v): + """dispersion for all nodes 'v' in a ego network G_u of node 'u'""" + u_nbrs = set(G_u[u]) + ST = {n for n in G_u[v] if n in u_nbrs} + set_uv = {u, v} + # all possible ties of connections that u and b share + possib = combinations(ST, 2) + total = 0 + for s, t in possib: + # neighbors of s that are in G_u, not including u and v + nbrs_s = u_nbrs.intersection(G_u[s]) - set_uv + # s and t are not directly connected + if t not in nbrs_s: + # s and t do not share a connection + if nbrs_s.isdisjoint(G_u[t]): + # tick for disp(u, v) + total += 1 + # neighbors that u and v share + embededness = len(ST) + + dispersion_val = total + if normalized: + dispersion_val = (total + b) ** alpha + if embededness + c != 0: + dispersion_val /= embededness + c + + return dispersion_val + + if u is None: + # v and u are not specified + if v is None: + results = {n: {} for n in G} + for u in G: + for v in G[u]: + results[u][v] = _dispersion(G, u, v) + # u is not specified, but v is + else: + results = dict.fromkeys(G[v], {}) + for u in G[v]: + results[u] = _dispersion(G, v, u) + else: + # u is specified with no target v + if v is None: + results = dict.fromkeys(G[u], {}) + for v in G[u]: + results[v] = _dispersion(G, u, v) + # both u and v are specified + else: + results = _dispersion(G, u, v) + + return results diff --git a/shared/package-files/77/772f60ef4cf277cd0aa5ac1f7d22a059b75db0a53034d785e6c6f131f09393ac/blob b/shared/package-files/77/772f60ef4cf277cd0aa5ac1f7d22a059b75db0a53034d785e6c6f131f09393ac/blob new file mode 100644 index 0000000000000000000000000000000000000000..82021775c294c7b881b9458b57d16deaac483cc7 --- /dev/null +++ b/shared/package-files/77/772f60ef4cf277cd0aa5ac1f7d22a059b75db0a53034d785e6c6f131f09393ac/blob @@ -0,0 +1,204 @@ +from numpy.testing import assert_equal, assert_ +from pytest import raises as assert_raises + +import time +import pytest +import ctypes +import threading +from scipy._lib import _ccallback_c as _test_ccallback_cython +from scipy._lib import _test_ccallback +from scipy._lib._ccallback import LowLevelCallable + +try: + import cffi + HAVE_CFFI = True +except ImportError: + HAVE_CFFI = False + + +ERROR_VALUE = 2.0 + + +def callback_python(a, user_data=None): + if a == ERROR_VALUE: + raise ValueError("bad value") + + if user_data is None: + return a + 1 + else: + return a + user_data + +def _get_cffi_func(base, signature): + if not HAVE_CFFI: + pytest.skip("cffi not installed") + + # Get function address + voidp = ctypes.cast(base, ctypes.c_void_p) + address = voidp.value + + # Create corresponding cffi handle + ffi = cffi.FFI() + func = ffi.cast(signature, address) + return func + + +def _get_ctypes_data(): + value = ctypes.c_double(2.0) + return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp) + + +def _get_cffi_data(): + if not HAVE_CFFI: + pytest.skip("cffi not installed") + ffi = cffi.FFI() + return ffi.new('double *', 2.0) + + +CALLERS = { + 'simple': _test_ccallback.test_call_simple, + 'nodata': _test_ccallback.test_call_nodata, + 'nonlocal': _test_ccallback.test_call_nonlocal, + 'cython': _test_ccallback_cython.test_call_cython, +} + +# These functions have signatures known to the callers +FUNCS = { + 'python': lambda: callback_python, + 'capsule': lambda: _test_ccallback.test_get_plus1_capsule(), + 'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython, + "plus1_cython"), + 'ctypes': lambda: _test_ccallback_cython.plus1_ctypes, + 'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes, + 'double (*)(double, int *, void *)'), + 'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(), + 'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython, + "plus1b_cython"), + 'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes, + 'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes, + 'double (*)(double, double, int *, void *)'), +} + +# These functions have signatures the callers don't know +BAD_FUNCS = { + 'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(), + 'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython, + "plus1bc_cython"), + 'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes, + 'cffi_bc': lambda: _get_cffi_func( + _test_ccallback_cython.plus1bc_ctypes, + 'double (*)(double, double, double, int *, void *)' + ), +} + +USER_DATAS = { + 'ctypes': _get_ctypes_data, + 'cffi': _get_cffi_data, + 'capsule': _test_ccallback.test_get_data_capsule, +} + + +def test_callbacks(): + def check(caller, func, user_data): + caller = CALLERS[caller] + func = FUNCS[func]() + user_data = USER_DATAS[user_data]() + + if func is callback_python: + def func2(x): + return func(x, 2.0) + else: + func2 = LowLevelCallable(func, user_data) + func = LowLevelCallable(func) + + # Test basic call + assert_equal(caller(func, 1.0), 2.0) + + # Test 'bad' value resulting to an error + assert_raises(ValueError, caller, func, ERROR_VALUE) + + # Test passing in user_data + assert_equal(caller(func2, 1.0), 3.0) + + for caller in sorted(CALLERS.keys()): + for func in sorted(FUNCS.keys()): + for user_data in sorted(USER_DATAS.keys()): + check(caller, func, user_data) + + +def test_bad_callbacks(): + def check(caller, func, user_data): + caller = CALLERS[caller] + user_data = USER_DATAS[user_data]() + func = BAD_FUNCS[func]() + + if func is callback_python: + def func2(x): + return func(x, 2.0) + else: + func2 = LowLevelCallable(func, user_data) + func = LowLevelCallable(func) + + # Test that basic call fails + assert_raises(ValueError, caller, LowLevelCallable(func), 1.0) + + # Test that passing in user_data also fails + assert_raises(ValueError, caller, func2, 1.0) + + # Test error message + llfunc = LowLevelCallable(func) + try: + caller(llfunc, 1.0) + except ValueError as err: + msg = str(err) + assert_(llfunc.signature in msg, msg) + assert_('double (double, double, int *, void *)' in msg, msg) + + for caller in sorted(CALLERS.keys()): + for func in sorted(BAD_FUNCS.keys()): + for user_data in sorted(USER_DATAS.keys()): + check(caller, func, user_data) + + +def test_signature_override(): + caller = _test_ccallback.test_call_simple + func = _test_ccallback.test_get_plus1_capsule() + + llcallable = LowLevelCallable(func, signature="bad signature") + assert_equal(llcallable.signature, "bad signature") + assert_raises(ValueError, caller, llcallable, 3) + + llcallable = LowLevelCallable(func, signature="double (double, int *, void *)") + assert_equal(llcallable.signature, "double (double, int *, void *)") + assert_equal(caller(llcallable, 3), 4) + + +def test_threadsafety(): + def callback(a, caller): + if a <= 0: + return 1 + else: + res = caller(lambda x: callback(x, caller), a - 1) + return 2*res + + def check(caller): + caller = CALLERS[caller] + + results = [] + + count = 10 + + def run(): + time.sleep(0.01) + r = caller(lambda x: callback(x, caller), count) + results.append(r) + + threads = [threading.Thread(target=run) for j in range(20)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert_equal(results, [2.0**count]*len(threads)) + + for caller in CALLERS.keys(): + check(caller) diff --git a/shared/package-files/77/7734b91f93baa6b12434b8689458012d639f169e2ed0cc3ad660c1405879299e/blob b/shared/package-files/77/7734b91f93baa6b12434b8689458012d639f169e2ed0cc3ad660c1405879299e/blob new file mode 100644 index 0000000000000000000000000000000000000000..8e7550b09be2cc0ba395fde424d137ad5b2156b0 --- /dev/null +++ b/shared/package-files/77/7734b91f93baa6b12434b8689458012d639f169e2ed0cc3ad660c1405879299e/blob @@ -0,0 +1,57 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import timeit +from contextlib import contextmanager + + +def _message_with_time(source, message, time): + """Create one line message for logging purposes. + + Parameters + ---------- + source : str + String indicating the source or the reference of the message. + + message : str + Short message. + + time : int + Time in seconds. + """ + start_message = "[%s] " % source + + # adapted from joblib.logger.short_format_time without the Windows -.1s + # adjustment + if time > 60: + time_str = "%4.1fmin" % (time / 60) + else: + time_str = " %5.1fs" % time + end_message = " %s, total=%s" % (message, time_str) + dots_len = 70 - len(start_message) - len(end_message) + return "%s%s%s" % (start_message, dots_len * ".", end_message) + + +@contextmanager +def _print_elapsed_time(source, message=None): + """Log elapsed time to stdout when the context is exited. + + Parameters + ---------- + source : str + String indicating the source or the reference of the message. + + message : str, default=None + Short message. If None, nothing will be printed. + + Returns + ------- + context_manager + Prints elapsed time upon exit if verbose. + """ + if message is None: + yield + else: + start = timeit.default_timer() + yield + print(_message_with_time(source, message, timeit.default_timer() - start)) diff --git a/shared/package-files/77/7734d1c412a76e5d704882e1620ac08f7f95d22d09bcaf9485a58fd3127b3692/blob b/shared/package-files/77/7734d1c412a76e5d704882e1620ac08f7f95d22d09bcaf9485a58fd3127b3692/blob new file mode 100644 index 0000000000000000000000000000000000000000..538b83c482caba1d4a8a2f64e1ad56da1862e286 --- /dev/null +++ b/shared/package-files/77/7734d1c412a76e5d704882e1620ac08f7f95d22d09bcaf9485a58fd3127b3692/blob @@ -0,0 +1,372 @@ +"""Utilities to allow inserting docstring fragments for common +parameters into function and method docstrings.""" + +from collections.abc import Callable, Iterable, Mapping +from typing import Protocol, TypeVar +import sys + +__all__ = [ + "docformat", + "inherit_docstring_from", + "indentcount_lines", + "filldoc", + "unindent_dict", + "unindent_string", + "extend_notes_in_docstring", + "replace_notes_in_docstring", + "doc_replace", +] + +_F = TypeVar("_F", bound=Callable[..., object]) + + +class Decorator(Protocol): + """A decorator of a function.""" + + def __call__(self, func: _F, /) -> _F: ... + + +def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str: + """Fill a function docstring from variables in dictionary. + + Adapt the indent of the inserted docs + + Parameters + ---------- + docstring : str + A docstring from a function, possibly with dict formatting strings. + docdict : dict[str, str], optional + A dictionary with keys that match the dict formatting strings + and values that are docstring fragments to be inserted. The + indentation of the inserted docstrings is set to match the + minimum indentation of the ``docstring`` by adding this + indentation to all lines of the inserted string, except the + first. + + Returns + ------- + docstring : str + string with requested ``docdict`` strings inserted. + + Examples + -------- + >>> docformat(' Test string with %(value)s', {'value':'inserted value'}) + ' Test string with inserted value' + >>> docstring = 'First line\\n Second line\\n %(value)s' + >>> inserted_string = "indented\\nstring" + >>> docdict = {'value': inserted_string} + >>> docformat(docstring, docdict) + 'First line\\n Second line\\n indented\\n string' + """ + if not docstring: + return docstring + if docdict is None: + docdict = {} + if not docdict: + return docstring + lines = docstring.expandtabs().splitlines() + # Find the minimum indent of the main docstring, after first line + if len(lines) < 2: + icount = 0 + else: + icount = indentcount_lines(lines[1:]) + indent = " " * icount + # Insert this indent to dictionary docstrings + indented = {} + for name, dstr in docdict.items(): + lines = dstr.expandtabs().splitlines() + try: + newlines = [lines[0]] + for line in lines[1:]: + newlines.append(indent + line) + indented[name] = "\n".join(newlines) + except IndexError: + indented[name] = dstr + return docstring % indented + + +def inherit_docstring_from(cls: object) -> Decorator: + """This decorator modifies the decorated function's docstring by + replacing occurrences of '%(super)s' with the docstring of the + method of the same name from the class `cls`. + + If the decorated method has no docstring, it is simply given the + docstring of `cls`s method. + + Parameters + ---------- + cls : type or object + A class with a method with the same name as the decorated method. + The docstring of the method in this class replaces '%(super)s' in the + docstring of the decorated method. + + Returns + ------- + decfunc : function + The decorator function that modifies the __doc__ attribute + of its argument. + + Examples + -------- + In the following, the docstring for Bar.func created using the + docstring of `Foo.func`. + + >>> class Foo: + ... def func(self): + ... '''Do something useful.''' + ... return + ... + >>> class Bar(Foo): + ... @inherit_docstring_from(Foo) + ... def func(self): + ... '''%(super)s + ... Do it fast. + ... ''' + ... return + ... + >>> b = Bar() + >>> b.func.__doc__ + 'Do something useful.\n Do it fast.\n ' + """ + + def _doc(func: _F) -> _F: + cls_docstring = getattr(cls, func.__name__).__doc__ + func_docstring = func.__doc__ + if func_docstring is None: + func.__doc__ = cls_docstring + else: + new_docstring = func_docstring % dict(super=cls_docstring) + func.__doc__ = new_docstring + return func + + return _doc + + +def extend_notes_in_docstring(cls: object, notes: str) -> Decorator: + """This decorator replaces the decorated function's docstring + with the docstring from corresponding method in `cls`. + It extends the 'Notes' section of that docstring to include + the given `notes`. + + Parameters + ---------- + cls : type or object + A class with a method with the same name as the decorated method. + The docstring of the method in this class replaces the docstring of the + decorated method. + notes : str + Additional notes to append to the 'Notes' section of the docstring. + + Returns + ------- + decfunc : function + The decorator function that modifies the __doc__ attribute + of its argument. + """ + + def _doc(func: _F) -> _F: + cls_docstring = getattr(cls, func.__name__).__doc__ + # If python is called with -OO option, + # there is no docstring + if cls_docstring is None: + return func + end_of_notes = cls_docstring.find(" References\n") + if end_of_notes == -1: + end_of_notes = cls_docstring.find(" Examples\n") + if end_of_notes == -1: + end_of_notes = len(cls_docstring) + func.__doc__ = ( + cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:] + ) + return func + + return _doc + + +def replace_notes_in_docstring(cls: object, notes: str) -> Decorator: + """This decorator replaces the decorated function's docstring + with the docstring from corresponding method in `cls`. + It replaces the 'Notes' section of that docstring with + the given `notes`. + + Parameters + ---------- + cls : type or object + A class with a method with the same name as the decorated method. + The docstring of the method in this class replaces the docstring of the + decorated method. + notes : str + The notes to replace the existing 'Notes' section with. + + Returns + ------- + decfunc : function + The decorator function that modifies the __doc__ attribute + of its argument. + """ + + def _doc(func: _F) -> _F: + cls_docstring = getattr(cls, func.__name__).__doc__ + notes_header = " Notes\n -----\n" + # If python is called with -OO option, + # there is no docstring + if cls_docstring is None: + return func + start_of_notes = cls_docstring.find(notes_header) + end_of_notes = cls_docstring.find(" References\n") + if end_of_notes == -1: + end_of_notes = cls_docstring.find(" Examples\n") + if end_of_notes == -1: + end_of_notes = len(cls_docstring) + func.__doc__ = ( + cls_docstring[: start_of_notes + len(notes_header)] + + notes + + cls_docstring[end_of_notes:] + ) + return func + + return _doc + + +def indentcount_lines(lines: Iterable[str]) -> int: + """Minimum indent for all lines in line list + + Parameters + ---------- + lines : Iterable[str] + The lines to find the minimum indent of. + + Returns + ------- + indent : int + The minimum indent. + + + Examples + -------- + >>> lines = [' one', ' two', ' three'] + >>> indentcount_lines(lines) + 1 + >>> lines = [] + >>> indentcount_lines(lines) + 0 + >>> lines = [' one'] + >>> indentcount_lines(lines) + 1 + >>> indentcount_lines([' ']) + 0 + """ + indentno = sys.maxsize + for line in lines: + stripped = line.lstrip() + if stripped: + indentno = min(indentno, len(line) - len(stripped)) + if indentno == sys.maxsize: + return 0 + return indentno + + +def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator: + """Return docstring decorator using docdict variable dictionary. + + Parameters + ---------- + docdict : dict[str, str] + A dictionary containing name, docstring fragment pairs. + unindent_params : bool, optional + If True, strip common indentation from all parameters in docdict. + Default is False. + + Returns + ------- + decfunc : function + The decorator function that applies dictionary to its + argument's __doc__ attribute. + """ + if unindent_params: + docdict = unindent_dict(docdict) + + def decorate(func: _F) -> _F: + # __doc__ may be None for optimized Python (-OO) + doc = func.__doc__ or "" + func.__doc__ = docformat(doc, docdict) + return func + + return decorate + + +def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]: + """Unindent all strings in a docdict. + + Parameters + ---------- + docdict : dict[str, str] + A dictionary with string values to unindent. + + Returns + ------- + docdict : dict[str, str] + The `docdict` dictionary but each of its string values are unindented. + """ + can_dict: dict[str, str] = {} + for name, dstr in docdict.items(): + can_dict[name] = unindent_string(dstr) + return can_dict + + +def unindent_string(docstring: str) -> str: + """Set docstring to minimum indent for all lines, including first. + + Parameters + ---------- + docstring : str + The input docstring to unindent. + + Returns + ------- + docstring : str + The unindented docstring. + + Examples + -------- + >>> unindent_string(' two') + 'two' + >>> unindent_string(' two\\n three') + 'two\\n three' + """ + lines = docstring.expandtabs().splitlines() + icount = indentcount_lines(lines) + if icount == 0: + return docstring + return "\n".join([line[icount:] for line in lines]) + + +def doc_replace(obj: object, oldval: str, newval: str) -> Decorator: + """Decorator to take the docstring from obj, with oldval replaced by newval + + Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)`` + + Parameters + ---------- + obj : object + A class or object whose docstring will be used as the basis for the + replacement operation. + oldval : str + The string to search for in the docstring. + newval : str + The string to replace `oldval` with in the docstring. + + Returns + ------- + decfunc : function + A decorator function that replaces occurrences of `oldval` with `newval` + in the docstring of the decorated function. + """ + # __doc__ may be None for optimized Python (-OO) + doc = (obj.__doc__ or "").replace(oldval, newval) + + def inner(func: _F) -> _F: + func.__doc__ = doc + return func + + return inner diff --git a/shared/package-files/77/773568e1567c3a40fd6126c111842e769707704755306ecb7e72114cc7782f38/blob b/shared/package-files/77/773568e1567c3a40fd6126c111842e769707704755306ecb7e72114cc7782f38/blob new file mode 100644 index 0000000000000000000000000000000000000000..298a83634da8392eded68236994b239a6a389328 --- /dev/null +++ b/shared/package-files/77/773568e1567c3a40fd6126c111842e769707704755306ecb7e72114cc7782f38/blob @@ -0,0 +1,808 @@ +"""Fourier Series""" + +from sympy.core.numbers import (oo, pi) +from sympy.core.symbol import Wild +from sympy.core.expr import Expr +from sympy.core.add import Add +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.core.symbol import Dummy, Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.trigonometric import sin, cos, sinc +from sympy.series.series_class import SeriesBase +from sympy.series.sequences import SeqFormula +from sympy.sets.sets import Interval +from sympy.utilities.iterables import is_sequence + + +def fourier_cos_seq(func, limits, n): + """Returns the cos sequence in a Fourier series""" + from sympy.integrals import integrate + x, L = limits[0], limits[2] - limits[1] + cos_term = cos(2*n*pi*x / L) + formula = 2 * cos_term * integrate(func * cos_term, limits) / L + a0 = formula.subs(n, S.Zero) / 2 + return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits) + / L, (n, 1, oo)) + + +def fourier_sin_seq(func, limits, n): + """Returns the sin sequence in a Fourier series""" + from sympy.integrals import integrate + x, L = limits[0], limits[2] - limits[1] + sin_term = sin(2*n*pi*x / L) + return SeqFormula(2 * sin_term * integrate(func * sin_term, limits) + / L, (n, 1, oo)) + + +def _process_limits(func, limits): + """ + Limits should be of the form (x, start, stop). + x should be a symbol. Both start and stop should be bounded. + + Explanation + =========== + + * If x is not given, x is determined from func. + * If limits is None. Limit of the form (x, -pi, pi) is returned. + + Examples + ======== + + >>> from sympy.series.fourier import _process_limits as pari + >>> from sympy.abc import x + >>> pari(x**2, (x, -2, 2)) + (x, -2, 2) + >>> pari(x**2, (-2, 2)) + (x, -2, 2) + >>> pari(x**2, None) + (x, -pi, pi) + """ + def _find_x(func): + free = func.free_symbols + if len(free) == 1: + return free.pop() + elif not free: + return Dummy('k') + else: + raise ValueError( + " specify dummy variables for %s. If the function contains" + " more than one free symbol, a dummy variable should be" + " supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))" + % func) + + x, start, stop = None, None, None + if limits is None: + x, start, stop = _find_x(func), -pi, pi + if is_sequence(limits, Tuple): + if len(limits) == 3: + x, start, stop = limits + elif len(limits) == 2: + x = _find_x(func) + start, stop = limits + + if not isinstance(x, Symbol) or start is None or stop is None: + raise ValueError('Invalid limits given: %s' % str(limits)) + + unbounded = [S.NegativeInfinity, S.Infinity] + if start in unbounded or stop in unbounded: + raise ValueError("Both the start and end value should be bounded") + + return sympify((x, start, stop)) + + +def finite_check(f, x, L): + + def check_fx(exprs, x): + return x not in exprs.free_symbols + + def check_sincos(_expr, x, L): + if isinstance(_expr, (sin, cos)): + sincos_args = _expr.args[0] + + if sincos_args.match(a*(pi/L)*x + b) is not None: + return True + else: + return False + + from sympy.simplify.fu import TR2, TR1, sincos_to_sum + _expr = sincos_to_sum(TR2(TR1(f))) + add_coeff = _expr.as_coeff_add() + + a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ]) + b = Wild('b', properties=[lambda k: x not in k.free_symbols, ]) + + for s in add_coeff[1]: + mul_coeffs = s.as_coeff_mul()[1] + for t in mul_coeffs: + if not (check_fx(t, x) or check_sincos(t, x, L)): + return False, f + + return True, _expr + + +class FourierSeries(SeriesBase): + r"""Represents Fourier sine/cosine series. + + Explanation + =========== + + This class only represents a fourier series. + No computation is performed. + + For how to compute Fourier series, see the :func:`fourier_series` + docstring. + + See Also + ======== + + sympy.series.fourier.fourier_series + """ + def __new__(cls, *args): + args = map(sympify, args) + return Expr.__new__(cls, *args) + + @property + def function(self): + return self.args[0] + + @property + def x(self): + return self.args[1][0] + + @property + def period(self): + return (self.args[1][1], self.args[1][2]) + + @property + def a0(self): + return self.args[2][0] + + @property + def an(self): + return self.args[2][1] + + @property + def bn(self): + return self.args[2][2] + + @property + def interval(self): + return Interval(0, oo) + + @property + def start(self): + return self.interval.inf + + @property + def stop(self): + return self.interval.sup + + @property + def length(self): + return oo + + @property + def L(self): + return abs(self.period[1] - self.period[0]) / 2 + + def _eval_subs(self, old, new): + x = self.x + if old.has(x): + return self + + def truncate(self, n=3): + """ + Return the first n nonzero terms of the series. + + If ``n`` is None return an iterator. + + Parameters + ========== + + n : int or None + Amount of non-zero terms in approximation or None. + + Returns + ======= + + Expr or iterator : + Approximation of function expanded into Fourier series. + + Examples + ======== + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> s = fourier_series(x, (x, -pi, pi)) + >>> s.truncate(4) + 2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2 + + See Also + ======== + + sympy.series.fourier.FourierSeries.sigma_approximation + """ + if n is None: + return iter(self) + + terms = [] + for t in self: + if len(terms) == n: + break + if t is not S.Zero: + terms.append(t) + + return Add(*terms) + + def sigma_approximation(self, n=3): + r""" + Return :math:`\sigma`-approximation of Fourier series with respect + to order n. + + Explanation + =========== + + Sigma approximation adjusts a Fourier summation to eliminate the Gibbs + phenomenon which would otherwise occur at discontinuities. + A sigma-approximated summation for a Fourier series of a T-periodical + function can be written as + + .. math:: + s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1} + \operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot + \left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr) + + b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right], + + where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier + series coefficients and + :math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos + :math:`\sigma` factor (expressed in terms of normalized + :math:`\operatorname{sinc}` function). + + Parameters + ========== + + n : int + Highest order of the terms taken into account in approximation. + + Returns + ======= + + Expr : + Sigma approximation of function expanded into Fourier series. + + Examples + ======== + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> s = fourier_series(x, (x, -pi, pi)) + >>> s.sigma_approximation(4) + 2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3 + + See Also + ======== + + sympy.series.fourier.FourierSeries.truncate + + Notes + ===== + + The behaviour of + :meth:`~sympy.series.fourier.FourierSeries.sigma_approximation` + is different from :meth:`~sympy.series.fourier.FourierSeries.truncate` + - it takes all nonzero terms of degree smaller than n, rather than + first n nonzero ones. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon + .. [2] https://en.wikipedia.org/wiki/Sigma_approximation + """ + terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n]) + if t is not S.Zero] + return Add(*terms) + + def shift(self, s): + """ + Shift the function by a term independent of x. + + Explanation + =========== + + f(x) -> f(x) + s + + This is fast, if Fourier series of f(x) is already + computed. + + Examples + ======== + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> s = fourier_series(x**2, (x, -pi, pi)) + >>> s.shift(1).truncate() + -4*cos(x) + cos(2*x) + 1 + pi**2/3 + """ + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + a0 = self.a0 + s + sfunc = self.function + s + + return self.func(sfunc, self.args[1], (a0, self.an, self.bn)) + + def shiftx(self, s): + """ + Shift x by a term independent of x. + + Explanation + =========== + + f(x) -> f(x + s) + + This is fast, if Fourier series of f(x) is already + computed. + + Examples + ======== + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> s = fourier_series(x**2, (x, -pi, pi)) + >>> s.shiftx(1).truncate() + -4*cos(x + 1) + cos(2*x + 2) + pi**2/3 + """ + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + an = self.an.subs(x, x + s) + bn = self.bn.subs(x, x + s) + sfunc = self.function.subs(x, x + s) + + return self.func(sfunc, self.args[1], (self.a0, an, bn)) + + def scale(self, s): + """ + Scale the function by a term independent of x. + + Explanation + =========== + + f(x) -> s * f(x) + + This is fast, if Fourier series of f(x) is already + computed. + + Examples + ======== + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> s = fourier_series(x**2, (x, -pi, pi)) + >>> s.scale(2).truncate() + -8*cos(x) + 2*cos(2*x) + 2*pi**2/3 + """ + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + an = self.an.coeff_mul(s) + bn = self.bn.coeff_mul(s) + a0 = self.a0 * s + sfunc = self.args[0] * s + + return self.func(sfunc, self.args[1], (a0, an, bn)) + + def scalex(self, s): + """ + Scale x by a term independent of x. + + Explanation + =========== + + f(x) -> f(s*x) + + This is fast, if Fourier series of f(x) is already + computed. + + Examples + ======== + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> s = fourier_series(x**2, (x, -pi, pi)) + >>> s.scalex(2).truncate() + -4*cos(2*x) + cos(4*x) + pi**2/3 + """ + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + an = self.an.subs(x, x * s) + bn = self.bn.subs(x, x * s) + sfunc = self.function.subs(x, x * s) + + return self.func(sfunc, self.args[1], (self.a0, an, bn)) + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + for t in self: + if t is not S.Zero: + return t + + def _eval_term(self, pt): + if pt == 0: + return self.a0 + return self.an.coeff(pt) + self.bn.coeff(pt) + + def __neg__(self): + return self.scale(-1) + + def __add__(self, other): + if isinstance(other, FourierSeries): + if self.period != other.period: + raise ValueError("Both the series should have same periods") + + x, y = self.x, other.x + function = self.function + other.function.subs(y, x) + + if self.x not in function.free_symbols: + return function + + an = self.an + other.an + bn = self.bn + other.bn + a0 = self.a0 + other.a0 + + return self.func(function, self.args[1], (a0, an, bn)) + + return Add(self, other) + + def __sub__(self, other): + return self.__add__(-other) + + +class FiniteFourierSeries(FourierSeries): + r"""Represents Finite Fourier sine/cosine series. + + For how to compute Fourier series, see the :func:`fourier_series` + docstring. + + Parameters + ========== + + f : Expr + Expression for finding fourier_series + + limits : ( x, start, stop) + x is the independent variable for the expression f + (start, stop) is the period of the fourier series + + exprs: (a0, an, bn) or Expr + a0 is the constant term a0 of the fourier series + an is a dictionary of coefficients of cos terms + an[k] = coefficient of cos(pi*(k/L)*x) + bn is a dictionary of coefficients of sin terms + bn[k] = coefficient of sin(pi*(k/L)*x) + + or exprs can be an expression to be converted to fourier form + + Methods + ======= + + This class is an extension of FourierSeries class. + Please refer to sympy.series.fourier.FourierSeries for + further information. + + See Also + ======== + + sympy.series.fourier.FourierSeries + sympy.series.fourier.fourier_series + """ + + def __new__(cls, f, limits, exprs): + f = sympify(f) + limits = sympify(limits) + exprs = sympify(exprs) + + if not (isinstance(exprs, Tuple) and len(exprs) == 3): # exprs is not of form (a0, an, bn) + # Converts the expression to fourier form + c, e = exprs.as_coeff_add() + from sympy.simplify.fu import TR10 + rexpr = c + Add(*[TR10(i) for i in e]) + a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add() + + x = limits[0] + L = abs(limits[2] - limits[1]) / 2 + + a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ]) + b = Wild('b', properties=[lambda k: x not in k.free_symbols, ]) + + an = {} + bn = {} + + # separates the coefficients of sin and cos terms in dictionaries an, and bn + for p in exp_ls: + t = p.match(b * cos(a * (pi / L) * x)) + q = p.match(b * sin(a * (pi / L) * x)) + if t: + an[t[a]] = t[b] + an.get(t[a], S.Zero) + elif q: + bn[q[a]] = q[b] + bn.get(q[a], S.Zero) + else: + a0 += p + + exprs = Tuple(a0, an, bn) + + return Expr.__new__(cls, f, limits, exprs) + + @property + def interval(self): + _length = 1 if self.a0 else 0 + _length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1 + return Interval(0, _length) + + @property + def length(self): + return self.stop - self.start + + def shiftx(self, s): + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + _expr = self.truncate().subs(x, x + s) + sfunc = self.function.subs(x, x + s) + + return self.func(sfunc, self.args[1], _expr) + + def scale(self, s): + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + _expr = self.truncate() * s + sfunc = self.function * s + + return self.func(sfunc, self.args[1], _expr) + + def scalex(self, s): + s, x = sympify(s), self.x + + if x in s.free_symbols: + raise ValueError("'%s' should be independent of %s" % (s, x)) + + _expr = self.truncate().subs(x, x * s) + sfunc = self.function.subs(x, x * s) + + return self.func(sfunc, self.args[1], _expr) + + def _eval_term(self, pt): + if pt == 0: + return self.a0 + + _term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \ + + self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x) + return _term + + def __add__(self, other): + if isinstance(other, FourierSeries): + return other.__add__(fourier_series(self.function, self.args[1],\ + finite=False)) + elif isinstance(other, FiniteFourierSeries): + if self.period != other.period: + raise ValueError("Both the series should have same periods") + + x, y = self.x, other.x + function = self.function + other.function.subs(y, x) + + if self.x not in function.free_symbols: + return function + + return fourier_series(function, limits=self.args[1]) + + +def fourier_series(f, limits=None, finite=True): + r"""Computes the Fourier trigonometric series expansion. + + Explanation + =========== + + Fourier trigonometric series of $f(x)$ over the interval $(a, b)$ + is defined as: + + .. math:: + \frac{a_0}{2} + \sum_{n=1}^{\infty} + (a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L})) + + where the coefficients are: + + .. math:: + L = b - a + + .. math:: + a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx} + + .. math:: + a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx} + + .. math:: + b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx} + + The condition whether the function $f(x)$ given should be periodic + or not is more than necessary, because it is sufficient to consider + the series to be converging to $f(x)$ only in the given interval, + not throughout the whole real line. + + This also brings a lot of ease for the computation because + you do not have to make $f(x)$ artificially periodic by + wrapping it with piecewise, modulo operations, + but you can shape the function to look like the desired periodic + function only in the interval $(a, b)$, and the computed series will + automatically become the series of the periodic version of $f(x)$. + + This property is illustrated in the examples section below. + + Parameters + ========== + + limits : (sym, start, end), optional + *sym* denotes the symbol the series is computed with respect to. + + *start* and *end* denotes the start and the end of the interval + where the fourier series converges to the given function. + + Default range is specified as $-\pi$ and $\pi$. + + Returns + ======= + + FourierSeries + A symbolic object representing the Fourier trigonometric series. + + Examples + ======== + + Computing the Fourier series of $f(x) = x^2$: + + >>> from sympy import fourier_series, pi + >>> from sympy.abc import x + >>> f = x**2 + >>> s = fourier_series(f, (x, -pi, pi)) + >>> s1 = s.truncate(n=3) + >>> s1 + -4*cos(x) + cos(2*x) + pi**2/3 + + Shifting of the Fourier series: + + >>> s.shift(1).truncate() + -4*cos(x) + cos(2*x) + 1 + pi**2/3 + >>> s.shiftx(1).truncate() + -4*cos(x + 1) + cos(2*x + 2) + pi**2/3 + + Scaling of the Fourier series: + + >>> s.scale(2).truncate() + -8*cos(x) + 2*cos(2*x) + 2*pi**2/3 + >>> s.scalex(2).truncate() + -4*cos(2*x) + cos(4*x) + pi**2/3 + + Computing the Fourier series of $f(x) = x$: + + This illustrates how truncating to the higher order gives better + convergence. + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import fourier_series, pi, plot + >>> from sympy.abc import x + >>> f = x + >>> s = fourier_series(f, (x, -pi, pi)) + >>> s1 = s.truncate(n = 3) + >>> s2 = s.truncate(n = 5) + >>> s3 = s.truncate(n = 7) + >>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True) + + >>> p[0].line_color = (0, 0, 0) + >>> p[0].label = 'x' + >>> p[1].line_color = (0.7, 0.7, 0.7) + >>> p[1].label = 'n=3' + >>> p[2].line_color = (0.5, 0.5, 0.5) + >>> p[2].label = 'n=5' + >>> p[3].line_color = (0.3, 0.3, 0.3) + >>> p[3].label = 'n=7' + + >>> p.show() + + This illustrates how the series converges to different sawtooth + waves if the different ranges are specified. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> s1 = fourier_series(x, (x, -1, 1)).truncate(10) + >>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10) + >>> s3 = fourier_series(x, (x, 0, 1)).truncate(10) + >>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True) + + >>> p[0].line_color = (0, 0, 0) + >>> p[0].label = 'x' + >>> p[1].line_color = (0.7, 0.7, 0.7) + >>> p[1].label = '[-1, 1]' + >>> p[2].line_color = (0.5, 0.5, 0.5) + >>> p[2].label = '[-pi, pi]' + >>> p[3].line_color = (0.3, 0.3, 0.3) + >>> p[3].label = '[0, 1]' + + >>> p.show() + + Notes + ===== + + Computing Fourier series can be slow + due to the integration required in computing + an, bn. + + It is faster to compute Fourier series of a function + by using shifting and scaling on an already + computed Fourier series rather than computing + again. + + e.g. If the Fourier series of ``x**2`` is known + the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``. + + See Also + ======== + + sympy.series.fourier.FourierSeries + + References + ========== + + .. [1] https://mathworld.wolfram.com/FourierSeries.html + """ + f = sympify(f) + + limits = _process_limits(f, limits) + x = limits[0] + + if x not in f.free_symbols: + return f + + if finite: + L = abs(limits[2] - limits[1]) / 2 + is_finite, res_f = finite_check(f, x, L) + if is_finite: + return FiniteFourierSeries(f, limits, res_f) + + n = Dummy('n') + center = (limits[1] + limits[2]) / 2 + if center.is_zero: + neg_f = f.subs(x, -x) + if f == neg_f: + a0, an = fourier_cos_seq(f, limits, n) + bn = SeqFormula(0, (1, oo)) + return FourierSeries(f, limits, (a0, an, bn)) + elif f == -neg_f: + a0 = S.Zero + an = SeqFormula(0, (1, oo)) + bn = fourier_sin_seq(f, limits, n) + return FourierSeries(f, limits, (a0, an, bn)) + a0, an = fourier_cos_seq(f, limits, n) + bn = fourier_sin_seq(f, limits, n) + return FourierSeries(f, limits, (a0, an, bn)) diff --git a/shared/package-files/77/7735c63451dfa4c0d67f12ad11ad3c41724d501ab31ef7a1e79064f2feffd700/blob b/shared/package-files/77/7735c63451dfa4c0d67f12ad11ad3c41724d501ab31ef7a1e79064f2feffd700/blob new file mode 100644 index 0000000000000000000000000000000000000000..cbba19f9530a4d070f824315fa02bfafc8ba1123 --- /dev/null +++ b/shared/package-files/77/7735c63451dfa4c0d67f12ad11ad3c41724d501ab31ef7a1e79064f2feffd700/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor & logical_and_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_and_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/77/77373452513ceb3fe276100def7783b3d036d6b178bfa0643a99841db15896c5/blob b/shared/package-files/77/77373452513ceb3fe276100def7783b3d036d6b178bfa0643a99841db15896c5/blob new file mode 100644 index 0000000000000000000000000000000000000000..cd3e2d171ada1273e25ea895f6d0e38eb30d3a9c --- /dev/null +++ b/shared/package-files/77/77373452513ceb3fe276100def7783b3d036d6b178bfa0643a99841db15896c5/blob @@ -0,0 +1,79 @@ +""" +This file provides internal compiler utilities that support certain special +operations with numpy. +""" +from numba.core import types, typing +from numba.core.cgutils import unpack_tuple +from numba.core.extending import intrinsic +from numba.core.imputils import impl_ret_new_ref +from numba.core.errors import RequireLiteralValue, TypingError + +from numba.cpython.unsafe.tuple import tuple_setitem + + +@intrinsic +def empty_inferred(typingctx, shape): + """A version of numpy.empty whose dtype is inferred by the type system. + + Expects `shape` to be a int-tuple. + + There is special logic in the type-inferencer to handle the "refine"-ing + of undefined dtype. + """ + from numba.np.arrayobj import _empty_nd_impl + + def codegen(context, builder, signature, args): + # check that the return type is now defined + arrty = signature.return_type + assert arrty.is_precise() + shapes = unpack_tuple(builder, args[0]) + # redirect implementation to np.empty + res = _empty_nd_impl(context, builder, arrty, shapes) + return impl_ret_new_ref(context, builder, arrty, res._getvalue()) + + # make function signature + nd = len(shape) + array_ty = types.Array(ndim=nd, layout='C', dtype=types.undefined) + sig = array_ty(shape) + return sig, codegen + + +@intrinsic +def to_fixed_tuple(typingctx, array, length): + """Convert *array* into a tuple of *length* + + Returns ``UniTuple(array.dtype, length)`` + + ** Warning ** + - No boundchecking. + If *length* is longer than *array.size*, the behavior is undefined. + """ + if not isinstance(length, types.IntegerLiteral): + raise RequireLiteralValue('*length* argument must be a constant') + + if array.ndim != 1: + raise TypingError("Not supported on array.ndim={}".format(array.ndim)) + + # Determine types + tuple_size = int(length.literal_value) + tuple_type = types.UniTuple(dtype=array.dtype, count=tuple_size) + sig = tuple_type(array, length) + + def codegen(context, builder, signature, args): + def impl(array, length, empty_tuple): + out = empty_tuple + for i in range(length): + out = tuple_setitem(out, i, array[i]) + return out + + inner_argtypes = [signature.args[0], types.intp, tuple_type] + inner_sig = typing.signature(tuple_type, *inner_argtypes) + ll_idx_type = context.get_value_type(types.intp) + # Allocate an empty tuple + empty_tuple = context.get_constant_undef(tuple_type) + inner_args = [args[0], ll_idx_type(tuple_size), empty_tuple] + + res = context.compile_internal(builder, impl, inner_sig, inner_args) + return res + + return sig, codegen diff --git a/shared/package-files/77/7737adbd731d7cf9a8c77841ec9684d68d912bccccb8b29e3c9f852e943d4ff8/blob b/shared/package-files/77/7737adbd731d7cf9a8c77841ec9684d68d912bccccb8b29e3c9f852e943d4ff8/blob new file mode 100644 index 0000000000000000000000000000000000000000..42594d4d43e70033649abdaa598b0f8bf4befae4 --- /dev/null +++ b/shared/package-files/77/7737adbd731d7cf9a8c77841ec9684d68d912bccccb8b29e3c9f852e943d4ff8/blob @@ -0,0 +1,34 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options={}) { + return at::_ops::_sparse_csc_tensor_unsafe::call(ccol_indices, row_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::_sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::_sparse_csc_tensor_unsafe::call(ccol_indices, row_indices, values, size, dtype, layout, device, pin_memory); +} + +} diff --git a/shared/package-files/77/77393d2ef180ff1452b670088c016e4c9f14c33feceea1961909a25cf803b0b6/blob b/shared/package-files/77/77393d2ef180ff1452b670088c016e4c9f14c33feceea1961909a25cf803b0b6/blob new file mode 100644 index 0000000000000000000000000000000000000000..947b50995f4045ee6562cae21120dc8a05687653 Binary files /dev/null and b/shared/package-files/77/77393d2ef180ff1452b670088c016e4c9f14c33feceea1961909a25cf803b0b6/blob differ diff --git a/shared/package-files/77/773c07497f1d2f1ccf76352bff3ddf2508f1cf94c731f59355de01a8aac31f31/blob b/shared/package-files/77/773c07497f1d2f1ccf76352bff3ddf2508f1cf94c731f59355de01a8aac31f31/blob new file mode 100644 index 0000000000000000000000000000000000000000..8d88d064e8fb69454c5f0d572bad09a93960a6aa --- /dev/null +++ b/shared/package-files/77/773c07497f1d2f1ccf76352bff3ddf2508f1cf94c731f59355de01a8aac31f31/blob @@ -0,0 +1,620 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates + +from dataclasses import dataclass +from typing import Any, cast, List, NamedTuple, Optional, Tuple + +import torch +import torch.distributed._functional_collectives as funcol +import torch.distributed.distributed_c10d as c10d + +from torch.distributed._tensor._collective_utils import mesh_broadcast, mesh_scatter +from torch.distributed.device_mesh import DeviceMesh + + +class Placement: + # base class Placement type + + # convenient utils to check for placement types + def is_shard(self, dim: Optional[int] = None) -> bool: + is_shard_instance = isinstance(self, Shard) + if dim is not None and is_shard_instance: + return cast(Shard, self).dim == dim + else: + return is_shard_instance + + def is_replicate(self) -> bool: + return isinstance(self, Replicate) + + def is_partial(self) -> bool: + return isinstance(self, _Partial) + + +@dataclass(frozen=True) +class Shard(Placement): + # shard placement, shard on a dim + dim: int + + def _split_tensor( + self, + tensor: torch.Tensor, + num_chunks: int, + *, + with_padding: bool = True, + contiguous: bool = True, + ) -> Tuple[List[torch.Tensor], List[int]]: + """ + This function uses torch.chunk to split a tensor into num_chunks shards along + the Shard placement dimension, and return a list of shards with their pad sizes. + + Keyword args: + with_padding (bool, optional): when True, we pad the tensor on the last + few ranks before calling the collectives (i.e. scatter/all_gather, etc.). + This is because collectives usually require equal size tensor inputs + """ + assert ( + self.dim <= tensor.ndim + ), f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}" + + # chunk tensor over dimension `dim` into n slices with padding if necessary + tensor_list = list(torch.chunk(tensor, num_chunks, dim=self.dim)) + # compute the chunk size inline with ``torch.chunk`` + full_chunk_size = (tensor.size(self.dim) + num_chunks - 1) // num_chunks + + # Compute chunk size for each chunk for ``self.dim`` + chunk_sizes = [ + tensor_list[idx].size(self.dim) if idx < len(tensor_list) else 0 + for idx in range(num_chunks) + ] + # Compute pad size on each chunk + pad_sizes = [full_chunk_size - chunk_size for chunk_size in chunk_sizes] + + # Reuse tensor to fill empty chunk with empty tensor + num_empty_tensors = num_chunks - len(tensor_list) + tensor_size = list(tensor_list[0].size()) + tensor_size = [ + size if idx != self.dim else 0 for idx, size in enumerate(tensor_size) + ] + tensor = tensor.new_zeros(tensor_size) + for _ in range(num_empty_tensors): + tensor_list.append(tensor) + + if with_padding or contiguous: + shard_list = [] + for shard, pad_size in zip(tensor_list, pad_sizes): + # Fill the empty tensor with zeroes with padding. + if with_padding and pad_size > 0: + shard = self._pad_tensor(shard, pad_size) + shard = shard.contiguous() if contiguous else shard + shard_list.append(shard) + return shard_list, pad_sizes + else: + return tensor_list, pad_sizes + + def _pad_tensor( + self, + tensor: torch.Tensor, + pad_size: int, + ) -> torch.Tensor: + if pad_size == 0: + return tensor + pad = [0, 0] * (tensor.ndim - self.dim) + pad[-1] = pad_size + return torch.nn.functional.pad(tensor, pad) + + def _unpad_tensor( + self, + tensor: torch.Tensor, + pad_size: int, + ) -> torch.Tensor: + if pad_size == 0: + return tensor + return tensor.narrow( + self.dim, + start=0, + length=tensor.size(self.dim) - pad_size, + ) + + @staticmethod + def _local_shard_size_on_dim( + size_on_dim: int, + num_chunks: int, + rank: int, + return_offset: bool = False, + ) -> Tuple[int, int]: + """ + returns the local shard size and offset on a given tensor dim + """ + # Compute the chunk size inline with ``torch.chunk`` + if size_on_dim % num_chunks == 0: + full_chunk_size = size_on_dim // num_chunks + return full_chunk_size, full_chunk_size * rank if return_offset else -1 + + # uneven sharding case + full_chunk_size = (size_on_dim + num_chunks - 1) // num_chunks + shard_starting_idx = full_chunk_size * rank + + if size_on_dim < shard_starting_idx: + return 0, size_on_dim if return_offset else -1 + else: + local_shard_size = ( + min(size_on_dim, shard_starting_idx + full_chunk_size) + - shard_starting_idx + ) + return local_shard_size, shard_starting_idx if return_offset else -1 + + def _shard_tensor( + self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int + ) -> torch.Tensor: + """ + shard and scatter a tensor on a mesh dimension (use coordinate + 0 on the mesh dimension as source of truth) + """ + my_coordinate = mesh.get_coordinate() + num_chunks = mesh.size(mesh_dim=mesh_dim) + + if my_coordinate is None: + # if rank is not part of mesh, we simply return an empty tensor + return tensor.new_empty(0, requires_grad=tensor.requires_grad) + + scatter_list, pad_sizes = self._split_tensor( + tensor, num_chunks, with_padding=True, contiguous=True + ) + + output = torch.empty_like(scatter_list[my_coordinate[mesh_dim]]) + mesh_scatter(output, scatter_list, mesh, mesh_dim=mesh_dim) + + # Only unpad if the local_tensor was padded on the dimension. + pad_size = pad_sizes[my_coordinate[mesh_dim]] + if pad_size > 0: + output = self._unpad_tensor(output, pad_size) + return output + + def _reduce_shard_tensor( + self, + tensor: torch.Tensor, + mesh: DeviceMesh, + reduce_op: c10d.ReduceOp.RedOpType, + mesh_dim: int, + ) -> torch.Tensor: + """ + reduce and scatter a tensor on a mesh dimension + """ + my_coordinate = mesh.get_coordinate() + num_chunks = mesh.size(mesh_dim=mesh_dim) + + if my_coordinate is None: + # if rank is not part of mesh, we simply return local_tensor, + # which should be an empty tensor + return tensor + + is_padded = tensor.size(self.dim) % num_chunks != 0 + if is_padded: + scattered_list, pad_sizes = self._split_tensor( + tensor, num_chunks, with_padding=True, contiguous=True + ) + tensor = torch.cat(scattered_list, dim=self.dim) + elif not tensor.is_contiguous(): + tensor = tensor.contiguous() + + output = funcol.reduce_scatter_tensor( + tensor, reduce_op.name, scatter_dim=self.dim, group=(mesh, mesh_dim) + ) + + if is_padded: + output = self._unpad_tensor(output, pad_sizes[my_coordinate[mesh_dim]]) # type: ignore[possibly-undefined] + return output + + def _to_replicate_tensor( + self, + local_tensor: torch.Tensor, + mesh: DeviceMesh, + mesh_dim: int, + current_logical_shape: List[int], + ) -> torch.Tensor: + """ + This function all_gather all shards and return a tensor that + is replicated on the previously sharded mesh dimension + """ + num_chunks = mesh.size(mesh_dim=mesh_dim) + # check if it's uneven, so we need to pad input tensor before all_gather + local_shape = list(local_tensor.size()) + + logical_dim_size = current_logical_shape[self.dim] + is_padded = logical_dim_size % num_chunks != 0 + + if is_padded: + full_chunk_size = (logical_dim_size + num_chunks - 1) // num_chunks + pad_size = full_chunk_size - local_shape[self.dim] + local_tensor = self._pad_tensor(local_tensor, pad_size) + + if not local_tensor.is_contiguous(): + local_tensor = local_tensor.contiguous() + + result = funcol.all_gather_tensor( + local_tensor, + gather_dim=self.dim, + group=(mesh, mesh_dim), + ) + if is_padded: + unpad_size = full_chunk_size * num_chunks - logical_dim_size # type: ignore[possibly-undefined] + result = self._unpad_tensor(result, unpad_size) + return result + + def _replicate_to_shard( + self, + local_tensor: torch.Tensor, + mesh: DeviceMesh, + mesh_dim: int, + shard_index: int, + ) -> torch.Tensor: + """ + transform from replicated tensor to a sharded tensor on + the current rank, which would perform a local chunk + """ + num_chunks = mesh.size(mesh_dim=mesh_dim) + shards, _ = self._split_tensor( + local_tensor, + num_chunks, + with_padding=False, + contiguous=False, + ) + return shards[shard_index].clone() + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Shard): + return False + return self.dim == other.dim + + def __hash__(self) -> int: + return hash(self.dim) + + def __repr__(self) -> str: + """ + machine readable representation of the Shard placement + """ + return f"Shard(dim={self.dim})" + + def __str__(self) -> str: + """human readable representation of the Shard placement""" + return f"S({self.dim})" + + +@dataclass(frozen=True) +class Replicate(Placement): + # replicate placement + def __eq__(self, other: object) -> bool: + if not isinstance(other, Replicate): + return False + return True + + def __hash__(self) -> int: + # every replicate placement is the same + return -1 + + def __repr__(self) -> str: + """ + machine readable representation of the Replicate placement + """ + return "Replicate()" + + def __str__(self) -> str: + """ + human readable representation of the Replicate placement + """ + return "R" + + def _replicate_tensor( + self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int + ) -> torch.Tensor: + """ + Replicate (broadcast) a torch.Tensor on a mesh dimension (use + the first coordinate on the mesh dimension as source of truth) + """ + my_coordinate = mesh.get_coordinate() + if my_coordinate is None: + # if rank is not part of mesh, we simply return an empty tensor + return tensor.new_empty(0, requires_grad=tensor.requires_grad) + + tensor = tensor.contiguous() + mesh_broadcast(tensor, mesh, mesh_dim=mesh_dim) + return tensor + + +@dataclass(frozen=True) +class _Partial(Placement): + # This is a default _Partial placement with element-wise reduce op + # _Partial define three contracts: + # 1. _reduce_value: reduce the value of the tensor on the mesh dimension + # 2. _reduce_shard_value: reduce_scatter the value of the tensor on the mesh dimension + # 3. _partition_value: partition the value of a replicated tensor on the mesh dimension + # We can implement custom reductions as needed by subclassing this + # class and override those contracts. + reduce_op: c10d.ReduceOp.RedOpType = c10d.ReduceOp.SUM + + def _reduce_value( + self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int + ) -> torch.Tensor: + return funcol.all_reduce( + tensor, reduceOp=self.reduce_op.name, group=(mesh, mesh_dim) + ) + + def _reduce_shard_value( + self, + tensor: torch.Tensor, + mesh: DeviceMesh, + mesh_dim: int, + shard_spec: Placement, + ) -> torch.Tensor: + # by default call reduce_shard_tensor of the shard_spec. + shard_spec = cast(Shard, shard_spec) + return shard_spec._reduce_shard_tensor(tensor, mesh, self.reduce_op, mesh_dim) + + def _partition_value( + self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int + ) -> torch.Tensor: + # _partition_value is the conjugate operation of _reduce_value + # - i.e. _partition_value on a sum reduce op is just a divison operation + # - the _reduce_value on a sum reduce op would just be a sum(allreduce) operation + # TODO: if the reduce_op is min/max, etc. the _partition_value should be a + # different operation + assert ( + self.reduce_op == c10d.ReduceOp.SUM + ), "only support replicate to PartialSUM for now!" + num_chunks = mesh.size(mesh_dim=mesh_dim) + return tensor / num_chunks + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _Partial): + return False + return self.reduce_op == other.reduce_op + + def __hash__(self) -> int: + return 1 + hash(self.reduce_op) + + def __repr__(self) -> str: + """ + machine readable representation of the Partial placement + """ + return f"_Partial(reduce_op={self.reduce_op})" + + def __str__(self) -> str: + """ + human readable representation of the Partial placement + """ + return "P" + + +class TensorMeta(NamedTuple): + # simple named tuple to represent tensor metadata + # intentionally to stay simple only for sharding + # propagation purposes. + shape: torch.Size + stride: Tuple[int, ...] + dtype: torch.dtype + + +# used internally to propagate the placements +@dataclass +class DTensorSpec: + mesh: DeviceMesh + placements: Tuple[Placement, ...] + + # tensor meta will only be set during sharding propagation + tensor_meta: Optional[TensorMeta] = None + + def __post_init__(self): + if not isinstance(self.placements, tuple): + self.placements = tuple(self.placements) + self._hash: Optional[int] = None + + def __setattr__(self, attr: str, value: Any): + super().__setattr__(attr, value) + # Make sure to recompute the hash in case any of the hashed attributes + # change (though we do not expect `mesh` or `placements` to change) + if hasattr(self, "_hash") and attr in ("mesh", "placements", "tensor_meta"): + self._hash = None + + def _hash_impl(self) -> int: + # hashing and equality check for DTensorSpec are used to cache the sharding + # propagation results. We only need to consider the mesh, placements, shape + # dtype and stride. + # Caveat: we need to keep this in mind and sync hash and eq if we add more + # fields to them. + if self.tensor_meta is not None: + return hash( + ( + self.mesh, + self.placements, + self.tensor_meta.shape, + self.tensor_meta.stride, + self.tensor_meta.dtype, + ) + ) + return hash((self.mesh, self.placements)) + + def __hash__(self) -> int: + # We lazily cache the spec to avoid recomputing the hash upon each + # use, where we make sure to update the hash when the `tensor_meta` + # changes by overriding `__setattr__`. This must be lazy so that Dynamo + # does not try to hash non-singleton `SymInt`s for the stride. + if self._hash is None: + self._hash = self._hash_impl() + return self._hash + + def __eq__(self, __o: object) -> bool: + if not ( + isinstance(__o, DTensorSpec) + and self.mesh == __o.mesh + and self.placements == __o.placements + ): + return False + if self.tensor_meta is None or __o.tensor_meta is None: + return self.tensor_meta == __o.tensor_meta + + return ( + self.tensor_meta.shape == __o.tensor_meta.shape # type: ignore[union-attr] + and self.tensor_meta.stride == __o.tensor_meta.stride # type: ignore[union-attr] + and self.tensor_meta.dtype == __o.tensor_meta.dtype # type: ignore[union-attr] + ) + + def __str__(self) -> str: + """ + human readable representation of the DTensorSpec + """ + if len(self.placements) == 1: + placement_str = str(self.placements[0]) + else: + placement_str = str(self.placements) + + if self.tensor_meta is not None: + tensor_shape = str(tuple(self.tensor_meta.shape)) + else: + tensor_shape = "unknown shape" + + return f"Spec({placement_str} on {tensor_shape})" + + @property + def shape(self) -> torch.Size: + if self.tensor_meta is None: + raise ValueError("tensor_meta is not set") + return self.tensor_meta.shape + + @property + def stride(self) -> Tuple[int, ...]: + if self.tensor_meta is None: + raise ValueError("tensor_meta is not set") + return self.tensor_meta.stride + + @property + def ndim(self) -> int: + if self.tensor_meta is None: + raise ValueError("tensor_meta is not set") + return len(self.tensor_meta.shape) + + @property + def num_shards(self) -> int: + num_shards = 1 + for i, placement in enumerate(self.placements): + if placement.is_shard(): + num_shards *= self.mesh.size(i) + return num_shards + + @property + def device_mesh(self) -> DeviceMesh: + # simple aliasing for the mesh field, make some + # checks that mixes DTensor/DTensorSpec easier + return self.mesh + + @property + def dim_map(self) -> List[int]: + """ + dim_map is a property we derive from `placements` of + the distributed tensor. It simply return a list of ints + where dim_map[i] denotes the sharding mapping to the mesh + dimension, and len(dim_map) == dist_tensor.ndim + dim_map[i] = -1: means tensor dim i replicate on mesh + dim_map[i] = j: means tensor dim i shard on mesh dim j + + For example, we have a dist tensor that have the shape of + [18, 20, 30], and device_mesh([0, 1, 2, 3]), placements: + [Shard(1)], the dim_map of this placement would be: + [-1, 0, -1]. This representation is pretty helpful during + sharding propagation where we could know exactly each + tensor dimension is sharded or not. + + Note that if placements contains `_Partial`, we have to + explicitly deal with it, so that when we create a DTensorSpec + with dim_map, we could properly record the pending sums. + """ + # dims mapping of dist tensor sharding + # return size of tensor ndim, -1 represent replicate + # and int >=0 represent shard on that device mesh dim + r = [-1] * self.ndim + for i, placement in enumerate(self.placements): + if placement.is_shard(): + shard_dim = cast(Shard, placement).dim + if r[shard_dim] > -1: + raise ValueError( + f"Tensor dim {shard_dim} is already sharded on mesh dim {r[shard_dim]}," + " DTensor operator implementation does not support things like hybrid" + " sharding strategies yet (i.e. [Shard(0), Shard(0)])" + ) + r[shard_dim] = i + return r + + @property + def sums(self) -> List[int]: + """ + sums is a property we derive from `placements` of the + distributed tensor. It simply return a list of ints where + sums[i] denotes the pending sum (partial) on mesh dim i + """ + return [ + idx + for idx, placement in enumerate(self.placements) + if placement.is_partial() + ] + + @classmethod + def from_dim_map( + cls, + mesh: DeviceMesh, + dim_map: List[int], + sums: List[int], + tensor_meta: Optional[TensorMeta] = None, + ) -> "DTensorSpec": + """ + Construct a DTensorSpec from dim_map list and pending sum. + + Args: + mesh (class:`DeviceMesh`): device mesh to be used in the DTensorSpec + dim_map (List[int]): a list of integer that represents sharding on each + tensor dimension, see `dim_map` property doc for details + sums (List[int]): a list of integer that represents the dist tensor have + pending sum on which device mesh dimension. + tensor meta (TensorMeta): DTensor metadata + + Return: + a class:`DTensorSpec` object + """ + # by default replicate on device mesh dims + placements: List[Placement] = [Replicate() for _ in range(mesh.ndim)] + + # find all mesh dims that need pending reductions + for s in sums: + placements[s] = _Partial() + + for i, m in enumerate(dim_map): + if m >= 0: + placement = placements[m] + if placement.is_shard(): + placement = cast(Shard, placement) + raise RuntimeError( + f"DeviceMesh dimension cann't be mapped to two dimension of the same tensor: {i} and {placement.dim}" + ) + elif placement.is_partial(): + raise RuntimeError( + f"DeviceMesh dimension {m} cannot be both shard and partial!" + ) + placements[m] = Shard(i) + + return cls(mesh, tuple(placements), tensor_meta=tensor_meta) + + def is_replicated(self): + """ + return True if the current DTensorSpec replicates on all mesh dims (devices) + """ + return all(placement.is_replicate() for placement in self.placements) + + def shallow_copy_with_tensor_meta( + self, tensor_meta: Optional[TensorMeta] + ) -> "DTensorSpec": + """ + Shallow copy the DTensorSpec with a new tensor_meta. + """ + assert tensor_meta is not None, "shallow copy with no tensor_meta!" + return DTensorSpec( + self.mesh, + self.placements, + tensor_meta=tensor_meta, + ) diff --git a/shared/package-files/77/773c97407b6c756d962f9aee569ffe32ca9241dfe7fadbb2ab6da892bcd7946c/blob b/shared/package-files/77/773c97407b6c756d962f9aee569ffe32ca9241dfe7fadbb2ab6da892bcd7946c/blob new file mode 100644 index 0000000000000000000000000000000000000000..e71aec9bd07cd4ef486b7e74b9589b6f1634d629 --- /dev/null +++ b/shared/package-files/77/773c97407b6c756d962f9aee569ffe32ca9241dfe7fadbb2ab6da892bcd7946c/blob @@ -0,0 +1,33 @@ +"""Test possibility of patching fftpack with pyfftw. + +No module source outside of scipy.fftpack should contain an import of +the form `from scipy.fftpack import ...`, so that a simple replacement +of scipy.fftpack by the corresponding fftw interface completely swaps +the two FFT implementations. + +Because this simply inspects source files, we only need to run the test +on one version of Python. +""" + + +from pathlib import Path +import re +import tokenize +import pytest +from numpy.testing import assert_ +import scipy + +class TestFFTPackImport: + @pytest.mark.slow + def test_fftpack_import(self): + base = Path(scipy.__file__).parent + regexp = r"\s*from.+\.fftpack import .*\n" + for path in base.rglob("*.py"): + if base / "fftpack" in path.parents: + continue + # use tokenize to auto-detect encoding on systems where no + # default encoding is defined (e.g., LANG='C') + with tokenize.open(str(path)) as file: + assert_(all(not re.fullmatch(regexp, line) + for line in file), + f"{path} contains an import from fftpack") diff --git a/shared/package-files/77/773d1f787b978edbbe6160e7b2a7372360ede804071865e5a008688bce20be44/blob b/shared/package-files/77/773d1f787b978edbbe6160e7b2a7372360ede804071865e5a008688bce20be44/blob new file mode 100644 index 0000000000000000000000000000000000000000..8494b79b937501438a71b6151c1d91d844ed8a92 --- /dev/null +++ b/shared/package-files/77/773d1f787b978edbbe6160e7b2a7372360ede804071865e5a008688bce20be44/blob @@ -0,0 +1,208 @@ +""" +Label propagation community detection algorithms. +""" +from collections import Counter, defaultdict + +import networkx as nx +from networkx.utils import groups, not_implemented_for, py_random_state + +__all__ = ["label_propagation_communities", "asyn_lpa_communities"] + + +@py_random_state(2) +def asyn_lpa_communities(G, weight=None, seed=None): + """Returns communities in `G` as detected by asynchronous label + propagation. + + The asynchronous label propagation algorithm is described in + [1]_. The algorithm is probabilistic and the found communities may + vary on different executions. + + The algorithm proceeds as follows. After initializing each node with + a unique label, the algorithm repeatedly sets the label of a node to + be the label that appears most frequently among that nodes + neighbors. The algorithm halts when each node has the label that + appears most frequently among its neighbors. The algorithm is + asynchronous because each node is updated without waiting for + updates on the remaining nodes. + + This generalized version of the algorithm in [1]_ accepts edge + weights. + + Parameters + ---------- + G : Graph + + weight : string + The edge attribute representing the weight of an edge. + If None, each edge is assumed to have weight one. In this + algorithm, the weight of an edge is used in determining the + frequency with which a label appears among the neighbors of a + node: a higher weight means the label appears more often. + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + communities : iterable + Iterable of communities given as sets of nodes. + + Notes + ----- + Edge weight attributes must be numerical. + + References + ---------- + .. [1] Raghavan, Usha Nandini, Réka Albert, and Soundar Kumara. "Near + linear time algorithm to detect community structures in large-scale + networks." Physical Review E 76.3 (2007): 036106. + """ + + labels = {n: i for i, n in enumerate(G)} + cont = True + + while cont: + cont = False + nodes = list(G) + seed.shuffle(nodes) + + for node in nodes: + if not G[node]: + continue + + # Get label frequencies among adjacent nodes. + # Depending on the order they are processed in, + # some nodes will be in iteration t and others in t-1, + # making the algorithm asynchronous. + if weight is None: + # initialising a Counter from an iterator of labels is + # faster for getting unweighted label frequencies + label_freq = Counter(map(labels.get, G[node])) + else: + # updating a defaultdict is substantially faster + # for getting weighted label frequencies + label_freq = defaultdict(float) + for _, v, wt in G.edges(node, data=weight, default=1): + label_freq[labels[v]] += wt + + # Get the labels that appear with maximum frequency. + max_freq = max(label_freq.values()) + best_labels = [ + label for label, freq in label_freq.items() if freq == max_freq + ] + + # If the node does not have one of the maximum frequency labels, + # randomly choose one of them and update the node's label. + # Continue the iteration as long as at least one node + # doesn't have a maximum frequency label. + if labels[node] not in best_labels: + labels[node] = seed.choice(best_labels) + cont = True + + yield from groups(labels).values() + + +@not_implemented_for("directed") +def label_propagation_communities(G): + """Generates community sets determined by label propagation + + Finds communities in `G` using a semi-synchronous label propagation + method [1]_. This method combines the advantages of both the synchronous + and asynchronous models. Not implemented for directed graphs. + + Parameters + ---------- + G : graph + An undirected NetworkX graph. + + Returns + ------- + communities : iterable + A dict_values object that contains a set of nodes for each community. + + Raises + ------ + NetworkXNotImplemented + If the graph is directed + + References + ---------- + .. [1] Cordasco, G., & Gargano, L. (2010, December). Community detection + via semi-synchronous label propagation algorithms. In Business + Applications of Social Network Analysis (BASNA), 2010 IEEE International + Workshop on (pp. 1-8). IEEE. + """ + coloring = _color_network(G) + # Create a unique label for each node in the graph + labeling = {v: k for k, v in enumerate(G)} + while not _labeling_complete(labeling, G): + # Update the labels of every node with the same color. + for color, nodes in coloring.items(): + for n in nodes: + _update_label(n, labeling, G) + + clusters = defaultdict(set) + for node, label in labeling.items(): + clusters[label].add(node) + return clusters.values() + + +def _color_network(G): + """Colors the network so that neighboring nodes all have distinct colors. + + Returns a dict keyed by color to a set of nodes with that color. + """ + coloring = {} # color => set(node) + colors = nx.coloring.greedy_color(G) + for node, color in colors.items(): + if color in coloring: + coloring[color].add(node) + else: + coloring[color] = {node} + return coloring + + +def _labeling_complete(labeling, G): + """Determines whether or not LPA is done. + + Label propagation is complete when all nodes have a label that is + in the set of highest frequency labels amongst its neighbors. + + Nodes with no neighbors are considered complete. + """ + return all( + labeling[v] in _most_frequent_labels(v, labeling, G) for v in G if len(G[v]) > 0 + ) + + +def _most_frequent_labels(node, labeling, G): + """Returns a set of all labels with maximum frequency in `labeling`. + + Input `labeling` should be a dict keyed by node to labels. + """ + if not G[node]: + # Nodes with no neighbors are themselves a community and are labeled + # accordingly, hence the immediate if statement. + return {labeling[node]} + + # Compute the frequencies of all neighbours of node + freqs = Counter(labeling[q] for q in G[node]) + max_freq = max(freqs.values()) + return {label for label, freq in freqs.items() if freq == max_freq} + + +def _update_label(node, labeling, G): + """Updates the label of a node using the Prec-Max tie breaking algorithm + + The algorithm is explained in: 'Community Detection via Semi-Synchronous + Label Propagation Algorithms' Cordasco and Gargano, 2011 + """ + high_labels = _most_frequent_labels(node, labeling, G) + if len(high_labels) == 1: + labeling[node] = high_labels.pop() + elif len(high_labels) > 1: + # Prec-Max + if labeling[node] not in high_labels: + labeling[node] = max(high_labels) diff --git a/shared/package-files/77/7744d0aca61198121f11674e2e1a1f71031155ef51dab2ff822a30418a7fe9f6/blob b/shared/package-files/77/7744d0aca61198121f11674e2e1a1f71031155ef51dab2ff822a30418a7fe9f6/blob new file mode 100644 index 0000000000000000000000000000000000000000..a6c35897a0486812a5c58d3cd2491667f972f343 Binary files /dev/null and b/shared/package-files/77/7744d0aca61198121f11674e2e1a1f71031155ef51dab2ff822a30418a7fe9f6/blob differ diff --git a/shared/package-files/77/774590de44d144e2d0a21b05a9c6d199c20146dd32bf888701bb008182597c8b/blob b/shared/package-files/77/774590de44d144e2d0a21b05a9c6d199c20146dd32bf888701bb008182597c8b/blob new file mode 100644 index 0000000000000000000000000000000000000000..dddeab1e2675fd791b678eb1da9c81713b8440e1 --- /dev/null +++ b/shared/package-files/77/774590de44d144e2d0a21b05a9c6d199c20146dd32bf888701bb008182597c8b/blob @@ -0,0 +1,54 @@ +#pragma once + +#include + +#include +#include + +// TODO: No need to have this whole header, we can just put it all in +// the cpp file + +namespace at::cuda::detail { + +// Set the callback to initialize Magma, which is set by +// torch_cuda_cu. This indirection is required so magma_init is called +// in the same library where Magma will be used. +TORCH_CUDA_CPP_API void set_magma_init_fn(void (*magma_init_fn)()); + + +// The real implementation of CUDAHooksInterface +struct CUDAHooks : public at::CUDAHooksInterface { + CUDAHooks(at::CUDAHooksArgs) {} + void initCUDA() const override; + Device getDeviceFromPtr(void* data) const override; + bool isPinnedPtr(const void* data) const override; + const Generator& getDefaultCUDAGenerator(DeviceIndex device_index = -1) const override; + bool hasCUDA() const override; + bool hasMAGMA() const override; + bool hasCuDNN() const override; + bool hasCuSOLVER() const override; + bool hasROCM() const override; + const at::cuda::NVRTC& nvrtc() const override; + DeviceIndex current_device() const override; + bool hasPrimaryContext(DeviceIndex device_index) const override; + Allocator* getCUDADeviceAllocator() const override; + Allocator* getPinnedMemoryAllocator() const override; + bool compiledWithCuDNN() const override; + bool compiledWithMIOpen() const override; + bool supportsDilatedConvolutionWithCuDNN() const override; + bool supportsDepthwiseConvolutionWithCuDNN() const override; + bool supportsBFloat16ConvolutionWithCuDNNv8() const override; + bool hasCUDART() const override; + long versionCUDART() const override; + long versionCuDNN() const override; + std::string showConfig() const override; + double batchnormMinEpsilonCuDNN() const override; + int64_t cuFFTGetPlanCacheMaxSize(DeviceIndex device_index) const override; + void cuFFTSetPlanCacheMaxSize(DeviceIndex device_index, int64_t max_size) const override; + int64_t cuFFTGetPlanCacheSize(DeviceIndex device_index) const override; + void cuFFTClearPlanCache(DeviceIndex device_index) const override; + int getNumGPUs() const override; + void deviceSynchronize(DeviceIndex device_index) const override; +}; + +} // at::cuda::detail diff --git a/shared/package-files/77/774676bc6b24a1c144ee4e81e9710560517abc45a73fcf0ad69c0774774749ef/blob b/shared/package-files/77/774676bc6b24a1c144ee4e81e9710560517abc45a73fcf0ad69c0774774749ef/blob new file mode 100644 index 0000000000000000000000000000000000000000..003ec71f62360b5a1e24f28ee7b34adbca164db6 --- /dev/null +++ b/shared/package-files/77/774676bc6b24a1c144ee4e81e9710560517abc45a73fcf0ad69c0774774749ef/blob @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor normal_functional(const at::Tensor & self, double mean=0, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(const at::Tensor & self, double mean, double std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor & normal_(at::Tensor & self, double mean=0, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_nested_(at::Tensor & self, double mean=0, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_sparse_csr_(at::Tensor & self, double mean=0, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_meta_(at::Tensor & self, double mean=0, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor normal(const at::Tensor & mean, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(const at::Tensor & mean, double std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal_meta(const at::Tensor & mean, double std=1, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out_meta(const at::Tensor & mean, double std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal(double mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(double mean, const at::Tensor & std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal_meta(double mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out_meta(double mean, const at::Tensor & std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal(const at::Tensor & mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out(const at::Tensor & mean, const at::Tensor & std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal_meta(const at::Tensor & mean, const at::Tensor & std, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & normal_out_meta(const at::Tensor & mean, const at::Tensor & std, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal(double mean, double std, at::IntArrayRef size, c10::optional generator=c10::nullopt, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & normal_out(double mean, double std, at::IntArrayRef size, c10::optional generator, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77493fd965eb908bb824e1a42109738a39a0b26ed7f975b65e6a1b68dff743fb/blob b/shared/package-files/77/77493fd965eb908bb824e1a42109738a39a0b26ed7f975b65e6a1b68dff743fb/blob new file mode 100644 index 0000000000000000000000000000000000000000..e954cecba417afd71059a35f7506c650eb780373 --- /dev/null +++ b/shared/package-files/77/77493fd965eb908bb824e1a42109738a39a0b26ed7f975b65e6a1b68dff743fb/blob @@ -0,0 +1,132 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import FloatingArray + + +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy(box): + con = pd.Series if box else pd.array + + # default (with or without missing values) -> object dtype + arr = con([0.1, 0.2, 0.3], dtype="Float64") + result = arr.to_numpy() + expected = np.array([0.1, 0.2, 0.3], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + arr = con([0.1, 0.2, None], dtype="Float64") + result = arr.to_numpy() + expected = np.array([0.1, 0.2, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy_float(box): + con = pd.Series if box else pd.array + + # no missing values -> can convert to float, otherwise raises + arr = con([0.1, 0.2, 0.3], dtype="Float64") + result = arr.to_numpy(dtype="float64") + expected = np.array([0.1, 0.2, 0.3], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + arr = con([0.1, 0.2, None], dtype="Float64") + result = arr.to_numpy(dtype="float64") + expected = np.array([0.1, 0.2, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + result = arr.to_numpy(dtype="float64", na_value=np.nan) + expected = np.array([0.1, 0.2, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy_int(box): + con = pd.Series if box else pd.array + + # no missing values -> can convert to int, otherwise raises + arr = con([1.0, 2.0, 3.0], dtype="Float64") + result = arr.to_numpy(dtype="int64") + expected = np.array([1, 2, 3], dtype="int64") + tm.assert_numpy_array_equal(result, expected) + + arr = con([1.0, 2.0, None], dtype="Float64") + with pytest.raises(ValueError, match="cannot convert to 'int64'-dtype"): + result = arr.to_numpy(dtype="int64") + + # automatic casting (floors the values) + arr = con([0.1, 0.9, 1.1], dtype="Float64") + result = arr.to_numpy(dtype="int64") + expected = np.array([0, 0, 1], dtype="int64") + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy_na_value(box): + con = pd.Series if box else pd.array + + arr = con([0.0, 1.0, None], dtype="Float64") + result = arr.to_numpy(dtype=object, na_value=None) + expected = np.array([0.0, 1.0, None], dtype="object") + tm.assert_numpy_array_equal(result, expected) + + result = arr.to_numpy(dtype=bool, na_value=False) + expected = np.array([False, True, False], dtype="bool") + tm.assert_numpy_array_equal(result, expected) + + result = arr.to_numpy(dtype="int64", na_value=-99) + expected = np.array([0, 1, -99], dtype="int64") + tm.assert_numpy_array_equal(result, expected) + + +def test_to_numpy_na_value_with_nan(): + # array with both NaN and NA -> only fill NA with `na_value` + arr = FloatingArray(np.array([0.0, np.nan, 0.0]), np.array([False, False, True])) + result = arr.to_numpy(dtype="float64", na_value=-1) + expected = np.array([0.0, np.nan, -1.0], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["float64", "float32", "int32", "int64", "bool"]) +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy_dtype(box, dtype): + con = pd.Series if box else pd.array + arr = con([0.0, 1.0], dtype="Float64") + + result = arr.to_numpy(dtype=dtype) + expected = np.array([0, 1], dtype=dtype) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["int32", "int64", "bool"]) +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy_na_raises(box, dtype): + con = pd.Series if box else pd.array + arr = con([0.0, 1.0, None], dtype="Float64") + with pytest.raises(ValueError, match=dtype): + arr.to_numpy(dtype=dtype) + + +@pytest.mark.parametrize("box", [True, False], ids=["series", "array"]) +def test_to_numpy_string(box, dtype): + con = pd.Series if box else pd.array + arr = con([0.0, 1.0, None], dtype="Float64") + + result = arr.to_numpy(dtype="str") + expected = np.array([0.0, 1.0, pd.NA], dtype=f"{tm.ENDIAN}U32") + tm.assert_numpy_array_equal(result, expected) + + +def test_to_numpy_copy(): + # to_numpy can be zero-copy if no missing values + arr = pd.array([0.1, 0.2, 0.3], dtype="Float64") + result = arr.to_numpy(dtype="float64") + result[0] = 10 + tm.assert_extension_array_equal(arr, pd.array([10, 0.2, 0.3], dtype="Float64")) + + arr = pd.array([0.1, 0.2, 0.3], dtype="Float64") + result = arr.to_numpy(dtype="float64", copy=True) + result[0] = 10 + tm.assert_extension_array_equal(arr, pd.array([0.1, 0.2, 0.3], dtype="Float64")) diff --git a/shared/package-files/77/77494c45d9a5437d3d4e1ddaf782ea955ff8dc12777a964f61ca0b08f7d62edf/blob b/shared/package-files/77/77494c45d9a5437d3d4e1ddaf782ea955ff8dc12777a964f61ca0b08f7d62edf/blob new file mode 100644 index 0000000000000000000000000000000000000000..dc384954c3f7335b3b8032850419269e67ce0730 --- /dev/null +++ b/shared/package-files/77/77494c45d9a5437d3d4e1ddaf782ea955ff8dc12777a964f61ca0b08f7d62edf/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77494c45d9a5437d3d4e1ddaf782ea955ff8dc12777a964f61ca0b08f7d62edf +size 406513 diff --git a/shared/package-files/77/774b1399439fab933d14c96220a2be7e526447afbbafaf4d8d4d93a7185fa96a/blob b/shared/package-files/77/774b1399439fab933d14c96220a2be7e526447afbbafaf4d8d4d93a7185fa96a/blob new file mode 100644 index 0000000000000000000000000000000000000000..3a8b665ed6c0f0021abedea1917a4b4501157179 --- /dev/null +++ b/shared/package-files/77/774b1399439fab933d14c96220a2be7e526447afbbafaf4d8d4d93a7185fa96a/blob @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Middleware implementation for propagating OpenTelemetry spans. + +#pragma once + +#include + +#include "arrow/flight/client_middleware.h" + +namespace arrow { +namespace flight { + +/// \brief Returns a ClientMiddlewareFactory that handles sending OpenTelemetry spans. +ARROW_FLIGHT_EXPORT std::shared_ptr +MakeTracingClientMiddlewareFactory(); + +} // namespace flight +} // namespace arrow diff --git a/shared/package-files/77/774d744f7e070636dff08d4fa02894da60cf42530b8411bcf9e15b0082eacbb4/blob b/shared/package-files/77/774d744f7e070636dff08d4fa02894da60cf42530b8411bcf9e15b0082eacbb4/blob new file mode 100644 index 0000000000000000000000000000000000000000..33c71d8391f9e36a6ffdcfdfb085b2fec57b7e26 --- /dev/null +++ b/shared/package-files/77/774d744f7e070636dff08d4fa02894da60cf42530b8411bcf9e15b0082eacbb4/blob @@ -0,0 +1,304 @@ +""" + pygments.lexers.prolog + ~~~~~~~~~~~~~~~~~~~~~~ + + Lexers for Prolog and Prolog-like languages. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.lexer import RegexLexer, bygroups +from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ + Number, Punctuation + +__all__ = ['PrologLexer', 'LogtalkLexer'] + + +class PrologLexer(RegexLexer): + """ + Lexer for Prolog files. + """ + name = 'Prolog' + aliases = ['prolog'] + filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl'] + mimetypes = ['text/x-prolog'] + + tokens = { + 'root': [ + (r'/\*', Comment.Multiline, 'nested-comment'), + (r'%.*', Comment.Single), + # character literal + (r'0\'.', String.Char), + (r'0b[01]+', Number.Bin), + (r'0o[0-7]+', Number.Oct), + (r'0x[0-9a-fA-F]+', Number.Hex), + # literal with prepended base + (r'\d\d?\'[a-zA-Z0-9]+', Number.Integer), + (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), + (r'\d+', Number.Integer), + (r'[\[\](){}|.,;!]', Punctuation), + (r':-|-->', Punctuation), + (r'"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|' + r'\\[0-7]+\\|\\["\\abcefnrstv]|[^\\"])*"', String.Double), + (r"'(?:''|[^'])*'", String.Atom), # quoted atom + # Needs to not be followed by an atom. + # (r'=(?=\s|[a-zA-Z\[])', Operator), + (r'is\b', Operator), + (r'(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])', + Operator), + (r'(mod|div|not)\b', Operator), + (r'_', Keyword), # The don't-care variable + (r'([a-z]+)(:)', bygroups(Name.Namespace, Punctuation)), + (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' + r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' + r'(\s*)(:-|-->)', + bygroups(Name.Function, Text, Operator)), # function defn + (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' + r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' + r'(\s*)(\()', + bygroups(Name.Function, Text, Punctuation)), + (r'[a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' + r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*', + String.Atom), # atom, characters + # This one includes ! + (r'[#&*+\-./:<=>?@\\^~\u00a1-\u00bf\u2010-\u303f]+', + String.Atom), # atom, graphics + (r'[A-Z_]\w*', Name.Variable), + (r'\s+|[\u2000-\u200f\ufff0-\ufffe\uffef]', Text), + ], + 'nested-comment': [ + (r'\*/', Comment.Multiline, '#pop'), + (r'/\*', Comment.Multiline, '#push'), + (r'[^*/]+', Comment.Multiline), + (r'[*/]', Comment.Multiline), + ], + } + + def analyse_text(text): + return ':-' in text + + +class LogtalkLexer(RegexLexer): + """ + For Logtalk source code. + + .. versionadded:: 0.10 + """ + + name = 'Logtalk' + url = 'http://logtalk.org/' + aliases = ['logtalk'] + filenames = ['*.lgt', '*.logtalk'] + mimetypes = ['text/x-logtalk'] + + tokens = { + 'root': [ + # Directives + (r'^\s*:-\s', Punctuation, 'directive'), + # Comments + (r'%.*?\n', Comment), + (r'/\*(.|\n)*?\*/', Comment), + # Whitespace + (r'\n', Text), + (r'\s+', Text), + # Numbers + (r"0'[\\]?.", Number), + (r'0b[01]+', Number.Bin), + (r'0o[0-7]+', Number.Oct), + (r'0x[0-9a-fA-F]+', Number.Hex), + (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number), + # Variables + (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable), + # Event handlers + (r'(after|before)(?=[(])', Keyword), + # Message forwarding handler + (r'forward(?=[(])', Keyword), + # Execution-context methods + (r'(context|parameter|this|se(lf|nder))(?=[(])', Keyword), + # Reflection + (r'(current_predicate|predicate_property)(?=[(])', Keyword), + # DCGs and term expansion + (r'(expand_(goal|term)|(goal|term)_expansion|phrase)(?=[(])', Keyword), + # Entity + (r'(abolish|c(reate|urrent))_(object|protocol|category)(?=[(])', Keyword), + (r'(object|protocol|category)_property(?=[(])', Keyword), + # Entity relations + (r'co(mplements_object|nforms_to_protocol)(?=[(])', Keyword), + (r'extends_(object|protocol|category)(?=[(])', Keyword), + (r'imp(lements_protocol|orts_category)(?=[(])', Keyword), + (r'(instantiat|specializ)es_class(?=[(])', Keyword), + # Events + (r'(current_event|(abolish|define)_events)(?=[(])', Keyword), + # Flags + (r'(create|current|set)_logtalk_flag(?=[(])', Keyword), + # Compiling, loading, and library paths + (r'logtalk_(compile|l(ibrary_path|oad|oad_context)|make(_target_action)?)(?=[(])', Keyword), + (r'\blogtalk_make\b', Keyword), + # Database + (r'(clause|retract(all)?)(?=[(])', Keyword), + (r'a(bolish|ssert(a|z))(?=[(])', Keyword), + # Control constructs + (r'(ca(ll|tch)|throw)(?=[(])', Keyword), + (r'(fa(il|lse)|true|(instantiation|system)_error)\b', Keyword), + (r'(type|domain|existence|permission|representation|evaluation|resource|syntax)_error(?=[(])', Keyword), + # All solutions + (r'((bag|set)of|f(ind|or)all)(?=[(])', Keyword), + # Multi-threading predicates + (r'threaded(_(ca(ll|ncel)|once|ignore|exit|peek|wait|notify))?(?=[(])', Keyword), + # Engine predicates + (r'threaded_engine(_(create|destroy|self|next|next_reified|yield|post|fetch))?(?=[(])', Keyword), + # Term unification + (r'(subsumes_term|unify_with_occurs_check)(?=[(])', Keyword), + # Term creation and decomposition + (r'(functor|arg|copy_term|numbervars|term_variables)(?=[(])', Keyword), + # Evaluable functors + (r'(div|rem|m(ax|in|od)|abs|sign)(?=[(])', Keyword), + (r'float(_(integer|fractional)_part)?(?=[(])', Keyword), + (r'(floor|t(an|runcate)|round|ceiling)(?=[(])', Keyword), + # Other arithmetic functors + (r'(cos|a(cos|sin|tan|tan2)|exp|log|s(in|qrt)|xor)(?=[(])', Keyword), + # Term testing + (r'(var|atom(ic)?|integer|float|c(allable|ompound)|n(onvar|umber)|ground|acyclic_term)(?=[(])', Keyword), + # Term comparison + (r'compare(?=[(])', Keyword), + # Stream selection and control + (r'(curren|se)t_(in|out)put(?=[(])', Keyword), + (r'(open|close)(?=[(])', Keyword), + (r'flush_output(?=[(])', Keyword), + (r'(at_end_of_stream|flush_output)\b', Keyword), + (r'(stream_property|at_end_of_stream|set_stream_position)(?=[(])', Keyword), + # Character and byte input/output + (r'(nl|(get|peek|put)_(byte|c(har|ode)))(?=[(])', Keyword), + (r'\bnl\b', Keyword), + # Term input/output + (r'read(_term)?(?=[(])', Keyword), + (r'write(q|_(canonical|term))?(?=[(])', Keyword), + (r'(current_)?op(?=[(])', Keyword), + (r'(current_)?char_conversion(?=[(])', Keyword), + # Atomic term processing + (r'atom_(length|c(hars|o(ncat|des)))(?=[(])', Keyword), + (r'(char_code|sub_atom)(?=[(])', Keyword), + (r'number_c(har|ode)s(?=[(])', Keyword), + # Implementation defined hooks functions + (r'(se|curren)t_prolog_flag(?=[(])', Keyword), + (r'\bhalt\b', Keyword), + (r'halt(?=[(])', Keyword), + # Message sending operators + (r'(::|:|\^\^)', Operator), + # External call + (r'[{}]', Keyword), + # Logic and control + (r'(ignore|once)(?=[(])', Keyword), + (r'\brepeat\b', Keyword), + # Sorting + (r'(key)?sort(?=[(])', Keyword), + # Bitwise functors + (r'(>>|<<|/\\|\\\\|\\)', Operator), + # Predicate aliases + (r'\bas\b', Operator), + # Arithmetic evaluation + (r'\bis\b', Keyword), + # Arithmetic comparison + (r'(=:=|=\\=|<|=<|>=|>)', Operator), + # Term creation and decomposition + (r'=\.\.', Operator), + # Term unification + (r'(=|\\=)', Operator), + # Term comparison + (r'(==|\\==|@=<|@<|@>=|@>)', Operator), + # Evaluable functors + (r'(//|[-+*/])', Operator), + (r'\b(e|pi|div|mod|rem)\b', Operator), + # Other arithmetic functors + (r'\b\*\*\b', Operator), + # DCG rules + (r'-->', Operator), + # Control constructs + (r'([!;]|->)', Operator), + # Logic and control + (r'\\+', Operator), + # Mode operators + (r'[?@]', Operator), + # Existential quantifier + (r'\^', Operator), + # Strings + (r'"(\\\\|\\[^\\]|[^"\\])*"', String), + # Punctuation + (r'[()\[\],.|]', Text), + # Atoms + (r"[a-z][a-zA-Z0-9_]*", Text), + (r"'", String, 'quoted_atom'), + ], + + 'quoted_atom': [ + (r"''", String), + (r"'", String, '#pop'), + (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape), + (r"[^\\'\n]+", String), + (r'\\', String), + ], + + 'directive': [ + # Conditional compilation directives + (r'(el)?if(?=[(])', Keyword, 'root'), + (r'(e(lse|ndif))(?=[.])', Keyword, 'root'), + # Entity directives + (r'(category|object|protocol)(?=[(])', Keyword, 'entityrelations'), + (r'(end_(category|object|protocol))(?=[.])', Keyword, 'root'), + # Predicate scope directives + (r'(public|protected|private)(?=[(])', Keyword, 'root'), + # Other directives + (r'e(n(coding|sure_loaded)|xport)(?=[(])', Keyword, 'root'), + (r'in(clude|itialization|fo)(?=[(])', Keyword, 'root'), + (r'(built_in|dynamic|synchronized|threaded)(?=[.])', Keyword, 'root'), + (r'(alias|d(ynamic|iscontiguous)|m(eta_(non_terminal|predicate)|ode|ultifile)|s(et_(logtalk|prolog)_flag|ynchronized))(?=[(])', Keyword, 'root'), + (r'op(?=[(])', Keyword, 'root'), + (r'(c(alls|oinductive)|module|reexport|use(s|_module))(?=[(])', Keyword, 'root'), + (r'[a-z][a-zA-Z0-9_]*(?=[(])', Text, 'root'), + (r'[a-z][a-zA-Z0-9_]*(?=[.])', Text, 'root'), + ], + + 'entityrelations': [ + (r'(complements|extends|i(nstantiates|mp(lements|orts))|specializes)(?=[(])', Keyword), + # Numbers + (r"0'[\\]?.", Number), + (r'0b[01]+', Number.Bin), + (r'0o[0-7]+', Number.Oct), + (r'0x[0-9a-fA-F]+', Number.Hex), + (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number), + # Variables + (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable), + # Atoms + (r"[a-z][a-zA-Z0-9_]*", Text), + (r"'", String, 'quoted_atom'), + # Strings + (r'"(\\\\|\\[^\\]|[^"\\])*"', String), + # End of entity-opening directive + (r'([)]\.)', Text, 'root'), + # Scope operator + (r'(::)', Operator), + # Punctuation + (r'[()\[\],.|]', Text), + # Comments + (r'%.*?\n', Comment), + (r'/\*(.|\n)*?\*/', Comment), + # Whitespace + (r'\n', Text), + (r'\s+', Text), + ] + } + + def analyse_text(text): + if ':- object(' in text: + return 1.0 + elif ':- protocol(' in text: + return 1.0 + elif ':- category(' in text: + return 1.0 + elif re.search(r'^:-\s[a-z]', text, re.M): + return 0.9 + else: + return 0.0 diff --git a/shared/package-files/77/774e381c67ffd3e52acec9a27ec00a0b0d9b3db40b4c3d7ebc81493a1c5b4e4b/blob b/shared/package-files/77/774e381c67ffd3e52acec9a27ec00a0b0d9b3db40b4c3d7ebc81493a1c5b4e4b/blob new file mode 100644 index 0000000000000000000000000000000000000000..f483976badb771d777c9dba0eecfbeb94d2e76fd --- /dev/null +++ b/shared/package-files/77/774e381c67ffd3e52acec9a27ec00a0b0d9b3db40b4c3d7ebc81493a1c5b4e4b/blob @@ -0,0 +1,1402 @@ +"""Functions to construct sparse matrices and arrays +""" + +__docformat__ = "restructuredtext en" + +__all__ = ['spdiags', 'eye', 'identity', 'kron', 'kronsum', + 'hstack', 'vstack', 'bmat', 'rand', 'random', 'diags', 'block_diag', + 'diags_array', 'block_array', 'eye_array', 'random_array'] + +import numbers +import math +import numpy as np + +from scipy._lib._util import check_random_state, rng_integers, _transition_to_rng +from ._sputils import upcast, get_index_dtype, isscalarlike + +from ._sparsetools import csr_hstack +from ._bsr import bsr_matrix, bsr_array +from ._coo import coo_matrix, coo_array +from ._csc import csc_matrix, csc_array +from ._csr import csr_matrix, csr_array +from ._dia import dia_matrix, dia_array + +from ._base import issparse, sparray + + +def spdiags(data, diags, m=None, n=None, format=None): + """ + Return a sparse matrix from diagonals. + + Parameters + ---------- + data : array_like + Matrix diagonals stored row-wise + diags : sequence of int or an int + Diagonals to set: + + * k = 0 the main diagonal + * k > 0 the kth upper diagonal + * k < 0 the kth lower diagonal + m, n : int, tuple, optional + Shape of the result. If `n` is None and `m` is a given tuple, + the shape is this tuple. If omitted, the matrix is square and + its shape is len(data[0]). + format : str, optional + Format of the result. By default (format=None) an appropriate sparse + matrix format is returned. This choice is subject to change. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``dia_array`` to take advantage + of the sparse array functionality. + + Notes + ----- + This function can be replaced by an equivalent call to ``dia_matrix`` + as:: + + dia_matrix((data, diags), shape=(m, n)).asformat(format) + + See Also + -------- + diags_array : more convenient form of this function + diags : matrix version of diags_array + dia_matrix : the sparse DIAgonal format. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import spdiags + >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) + >>> diags = np.array([0, -1, 2]) + >>> spdiags(data, diags, 4, 4).toarray() + array([[1, 0, 3, 0], + [1, 2, 0, 4], + [0, 2, 3, 0], + [0, 0, 3, 4]]) + + """ + if m is None and n is None: + m = n = len(data[0]) + elif n is None: + m, n = m + return dia_matrix((data, diags), shape=(m, n)).asformat(format) + + +def diags_array(diagonals, /, *, offsets=0, shape=None, format=None, dtype=None): + """ + Construct a sparse array from diagonals. + + Parameters + ---------- + diagonals : sequence of array_like + Sequence of arrays containing the array diagonals, + corresponding to `offsets`. + offsets : sequence of int or an int, optional + Diagonals to set (repeated offsets are not allowed): + - k = 0 the main diagonal (default) + - k > 0 the kth upper diagonal + - k < 0 the kth lower diagonal + shape : tuple of int, optional + Shape of the result. If omitted, a square array large enough + to contain the diagonals is returned. + format : {"dia", "csr", "csc", "lil", ...}, optional + Matrix format of the result. By default (format=None) an + appropriate sparse array format is returned. This choice is + subject to change. + dtype : dtype, optional + Data type of the array. + + Notes + ----- + Repeated diagonal offsets are disallowed. + + The result from `diags_array` is the sparse equivalent of:: + + np.diag(diagonals[0], offsets[0]) + + ... + + np.diag(diagonals[k], offsets[k]) + + ``diags_array`` differs from `dia_array` in the way it handles off-diagonals. + Specifically, `dia_array` assumes the data input includes padding + (ignored values) at the start/end of the rows for positive/negative + offset, while ``diags_array` assumes the input data has no padding. + Each value in the input ``diagonals`` is used. + + .. versionadded:: 1.11 + + Examples + -------- + >>> from scipy.sparse import diags_array + >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]] + >>> diags_array(diagonals, offsets=[0, -1, 2]).toarray() + array([[1., 0., 1., 0.], + [1., 2., 0., 2.], + [0., 2., 3., 0.], + [0., 0., 3., 4.]]) + + Broadcasting of scalars is supported (but shape needs to be + specified): + + >>> diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)).toarray() + array([[-2., 1., 0., 0.], + [ 1., -2., 1., 0.], + [ 0., 1., -2., 1.], + [ 0., 0., 1., -2.]]) + + + If only one diagonal is wanted (as in `numpy.diag`), the following + works as well: + + >>> diags_array([1, 2, 3], offsets=1).toarray() + array([[ 0., 1., 0., 0.], + [ 0., 0., 2., 0.], + [ 0., 0., 0., 3.], + [ 0., 0., 0., 0.]]) + + """ + # if offsets is not a sequence, assume that there's only one diagonal + if isscalarlike(offsets): + # now check that there's actually only one diagonal + if len(diagonals) == 0 or isscalarlike(diagonals[0]): + diagonals = [np.atleast_1d(diagonals)] + else: + raise ValueError("Different number of diagonals and offsets.") + else: + diagonals = list(map(np.atleast_1d, diagonals)) + + offsets = np.atleast_1d(offsets) + + # Basic check + if len(diagonals) != len(offsets): + raise ValueError("Different number of diagonals and offsets.") + + # Determine shape, if omitted + if shape is None: + m = len(diagonals[0]) + abs(int(offsets[0])) + shape = (m, m) + + # Determine data type, if omitted + if dtype is None: + dtype = np.common_type(*diagonals) + + # Construct data array + m, n = shape + + M = max([min(m + offset, n - offset) + max(0, offset) + for offset in offsets]) + M = max(0, M) + data_arr = np.zeros((len(offsets), M), dtype=dtype) + + K = min(m, n) + + for j, diagonal in enumerate(diagonals): + offset = offsets[j] + k = max(0, offset) + length = min(m + offset, n - offset, K) + if length < 0: + raise ValueError(f"Offset {offset} (index {j}) out of bounds") + try: + data_arr[j, k:k+length] = diagonal[...,:length] + except ValueError as e: + if len(diagonal) != length and len(diagonal) != 1: + raise ValueError( + f"Diagonal length (index {j}: {len(diagonal)} at" + f" offset {offset}) does not agree with array size ({m}, {n})." + ) from e + raise + + return dia_array((data_arr, offsets), shape=(m, n)).asformat(format) + + +def diags(diagonals, offsets=0, shape=None, format=None, dtype=None): + """ + Construct a sparse matrix from diagonals. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``diags_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + diagonals : sequence of array_like + Sequence of arrays containing the matrix diagonals, + corresponding to `offsets`. + offsets : sequence of int or an int, optional + Diagonals to set (repeated offsets are not allowed): + - k = 0 the main diagonal (default) + - k > 0 the kth upper diagonal + - k < 0 the kth lower diagonal + shape : tuple of int, optional + Shape of the result. If omitted, a square matrix large enough + to contain the diagonals is returned. + format : {"dia", "csr", "csc", "lil", ...}, optional + Matrix format of the result. By default (format=None) an + appropriate sparse matrix format is returned. This choice is + subject to change. + dtype : dtype, optional + Data type of the matrix. + + See Also + -------- + spdiags : construct matrix from diagonals + diags_array : construct sparse array instead of sparse matrix + + Notes + ----- + Repeated diagonal offsets are disallowed. + + The result from `diags` is the sparse equivalent of:: + + np.diag(diagonals[0], offsets[0]) + + ... + + np.diag(diagonals[k], offsets[k]) + + ``diags`` differs from ``dia_matrix`` in the way it handles off-diagonals. + Specifically, `dia_matrix` assumes the data input includes padding + (ignored values) at the start/end of the rows for positive/negative + offset, while ``diags` assumes the input data has no padding. + Each value in the input ``diagonals`` is used. + + .. versionadded:: 0.11 + + Examples + -------- + >>> from scipy.sparse import diags + >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]] + >>> diags(diagonals, [0, -1, 2]).toarray() + array([[1., 0., 1., 0.], + [1., 2., 0., 2.], + [0., 2., 3., 0.], + [0., 0., 3., 4.]]) + + Broadcasting of scalars is supported (but shape needs to be + specified): + + >>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray() + array([[-2., 1., 0., 0.], + [ 1., -2., 1., 0.], + [ 0., 1., -2., 1.], + [ 0., 0., 1., -2.]]) + + + If only one diagonal is wanted (as in `numpy.diag`), the following + works as well: + + >>> diags([1, 2, 3], 1).toarray() + array([[ 0., 1., 0., 0.], + [ 0., 0., 2., 0.], + [ 0., 0., 0., 3.], + [ 0., 0., 0., 0.]]) + + """ + A = diags_array(diagonals, offsets=offsets, shape=shape, dtype=dtype) + return dia_matrix(A).asformat(format) + + +def identity(n, dtype='d', format=None): + """Identity matrix in sparse format + + Returns an identity matrix with shape (n,n) using a given + sparse format and dtype. This differs from `eye_array` in + that it has a square shape with ones only on the main diagonal. + It is thus the multiplicative identity. `eye_array` allows + rectangular shapes and the diagonal can be offset from the main one. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``eye_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + n : int + Shape of the identity matrix. + dtype : dtype, optional + Data type of the matrix + format : str, optional + Sparse format of the result, e.g., format="csr", etc. + + Examples + -------- + >>> import scipy as sp + >>> sp.sparse.identity(3).toarray() + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> sp.sparse.identity(3, dtype='int8', format='dia') + + >>> sp.sparse.eye_array(3, dtype='int8', format='dia') + + + """ + return eye(n, n, dtype=dtype, format=format) + + +def eye_array(m, n=None, *, k=0, dtype=float, format=None): + """Identity matrix in sparse array format + + Return a sparse array with ones on diagonal. + Specifically a sparse array (m x n) where the kth diagonal + is all ones and everything else is zeros. + + Parameters + ---------- + m : int + Number of rows requested. + n : int, optional + Number of columns. Default: `m`. + k : int, optional + Diagonal to place ones on. Default: 0 (main diagonal). + dtype : dtype, optional + Data type of the array + format : str, optional (default: "dia") + Sparse format of the result, e.g., format="csr", etc. + + Examples + -------- + >>> import numpy as np + >>> import scipy as sp + >>> sp.sparse.eye_array(3).toarray() + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> sp.sparse.eye_array(3, dtype=np.int8) + + + """ + # TODO: delete next 15 lines [combine with _eye()] once spmatrix removed + return _eye(m, n, k, dtype, format) + + +def _eye(m, n, k, dtype, format, as_sparray=True): + if as_sparray: + csr_sparse = csr_array + csc_sparse = csc_array + coo_sparse = coo_array + diags_sparse = diags_array + else: + csr_sparse = csr_matrix + csc_sparse = csc_matrix + coo_sparse = coo_matrix + diags_sparse = diags + + if n is None: + n = m + m, n = int(m), int(n) + + if m == n and k == 0: + # fast branch for special formats + if format in ['csr', 'csc']: + idx_dtype = get_index_dtype(maxval=n) + indptr = np.arange(n+1, dtype=idx_dtype) + indices = np.arange(n, dtype=idx_dtype) + data = np.ones(n, dtype=dtype) + cls = {'csr': csr_sparse, 'csc': csc_sparse}[format] + return cls((data, indices, indptr), (n, n)) + + elif format == 'coo': + idx_dtype = get_index_dtype(maxval=n) + row = np.arange(n, dtype=idx_dtype) + col = np.arange(n, dtype=idx_dtype) + data = np.ones(n, dtype=dtype) + return coo_sparse((data, (row, col)), (n, n)) + + data = np.ones((1, max(0, min(m + k, n))), dtype=dtype) + return diags_sparse(data, offsets=[k], shape=(m, n), dtype=dtype).asformat(format) + + +def eye(m, n=None, k=0, dtype=float, format=None): + """Sparse matrix with ones on diagonal + + Returns a sparse matrix (m x n) where the kth diagonal + is all ones and everything else is zeros. + + Parameters + ---------- + m : int + Number of rows in the matrix. + n : int, optional + Number of columns. Default: `m`. + k : int, optional + Diagonal to place ones on. Default: 0 (main diagonal). + dtype : dtype, optional + Data type of the matrix. + format : str, optional + Sparse format of the result, e.g., format="csr", etc. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``eye_array`` to take advantage + of the sparse array functionality. + + Examples + -------- + >>> import numpy as np + >>> import scipy as sp + >>> sp.sparse.eye(3).toarray() + array([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + >>> sp.sparse.eye(3, dtype=np.int8) + + + """ + return _eye(m, n, k, dtype, format, False) + + +def kron(A, B, format=None): + """kronecker product of sparse matrices A and B + + Parameters + ---------- + A : sparse or dense matrix + first matrix of the product + B : sparse or dense matrix + second matrix of the product + format : str, optional (default: 'bsr' or 'coo') + format of the result (e.g. "csr") + If None, choose 'bsr' for relatively dense array and 'coo' for others + + Returns + ------- + kronecker product in a sparse format. + Returns a sparse matrix unless either A or B is a + sparse array in which case returns a sparse array. + + Examples + -------- + >>> import numpy as np + >>> import scipy as sp + >>> A = sp.sparse.csr_array(np.array([[0, 2], [5, 0]])) + >>> B = sp.sparse.csr_array(np.array([[1, 2], [3, 4]])) + >>> sp.sparse.kron(A, B).toarray() + array([[ 0, 0, 2, 4], + [ 0, 0, 6, 8], + [ 5, 10, 0, 0], + [15, 20, 0, 0]]) + + >>> sp.sparse.kron(A, [[1, 2], [3, 4]]).toarray() + array([[ 0, 0, 2, 4], + [ 0, 0, 6, 8], + [ 5, 10, 0, 0], + [15, 20, 0, 0]]) + + """ + # TODO: delete next 10 lines and replace _sparse with _array when spmatrix removed + if isinstance(A, sparray) or isinstance(B, sparray): + # convert to local variables + bsr_sparse = bsr_array + csr_sparse = csr_array + coo_sparse = coo_array + else: # use spmatrix + bsr_sparse = bsr_matrix + csr_sparse = csr_matrix + coo_sparse = coo_matrix + + B = coo_sparse(B) + if B.ndim != 2: + raise ValueError(f"kron requires 2D input arrays. `B` is {B.ndim}D.") + + # B is fairly dense, use BSR + if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: + A = csr_sparse(A,copy=True) + if A.ndim != 2: + raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.") + output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) + + if A.nnz == 0 or B.nnz == 0: + # kronecker product is the zero matrix + return coo_sparse(output_shape).asformat(format) + + B = B.toarray() + data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) + data = data * B + + return bsr_sparse((data,A.indices,A.indptr), shape=output_shape) + else: + # use COO + A = coo_sparse(A) + if A.ndim != 2: + raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.") + output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) + + if A.nnz == 0 or B.nnz == 0: + # kronecker product is the zero matrix + return coo_sparse(output_shape).asformat(format) + + # expand entries of a into blocks + idx_dtype = get_index_dtype(A.coords, maxval=max(output_shape)) + row = np.asarray(A.row, dtype=idx_dtype).repeat(B.nnz) + col = np.asarray(A.col, dtype=idx_dtype).repeat(B.nnz) + data = A.data.repeat(B.nnz) + + row *= B.shape[0] + col *= B.shape[1] + + # increment block indices + row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) + row += B.row + col += B.col + row,col = row.reshape(-1),col.reshape(-1) + + # compute block entries + data = data.reshape(-1,B.nnz) * B.data + data = data.reshape(-1) + + return coo_sparse((data,(row,col)), shape=output_shape).asformat(format) + + +def kronsum(A, B, format=None): + """kronecker sum of square sparse matrices A and B + + Kronecker sum of two sparse matrices is a sum of two Kronecker + products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) + and B has shape (n,n) and I_m and I_n are identity matrices + of shape (m,m) and (n,n), respectively. + + Parameters + ---------- + A + square matrix + B + square matrix + format : str + format of the result (e.g. "csr") + + Returns + ------- + kronecker sum in a sparse matrix format + + """ + # TODO: delete next 8 lines and replace _sparse with _array when spmatrix removed + if isinstance(A, sparray) or isinstance(B, sparray): + # convert to local variables + coo_sparse = coo_array + identity_sparse = eye_array + else: + coo_sparse = coo_matrix + identity_sparse = identity + + A = coo_sparse(A) + B = coo_sparse(B) + + if A.ndim != 2: + raise ValueError(f"kronsum requires 2D inputs. `A` is {A.ndim}D.") + if B.ndim != 2: + raise ValueError(f"kronsum requires 2D inputs. `B` is {B.ndim}D.") + if A.shape[0] != A.shape[1]: + raise ValueError('A is not square') + if B.shape[0] != B.shape[1]: + raise ValueError('B is not square') + + dtype = upcast(A.dtype, B.dtype) + + I_n = identity_sparse(A.shape[0], dtype=dtype) + I_m = identity_sparse(B.shape[0], dtype=dtype) + L = kron(I_m, A, format='coo') + R = kron(B, I_n, format='coo') + + return (L + R).asformat(format) + + +def _compressed_sparse_stack(blocks, axis, return_spmatrix): + """ + Stacking fast path for CSR/CSC matrices or arrays + (i) vstack for CSR, (ii) hstack for CSC. + """ + other_axis = 1 if axis == 0 else 0 + data = np.concatenate([b.data for b in blocks]) + constant_dim = blocks[0]._shape_as_2d[other_axis] + idx_dtype = get_index_dtype(arrays=[b.indptr for b in blocks], + maxval=max(data.size, constant_dim)) + indices = np.empty(data.size, dtype=idx_dtype) + indptr = np.empty(sum(b._shape_as_2d[axis] for b in blocks) + 1, dtype=idx_dtype) + last_indptr = idx_dtype(0) + sum_dim = 0 + sum_indices = 0 + for b in blocks: + if b._shape_as_2d[other_axis] != constant_dim: + raise ValueError(f'incompatible dimensions for axis {other_axis}') + indices[sum_indices:sum_indices+b.indices.size] = b.indices + sum_indices += b.indices.size + idxs = slice(sum_dim, sum_dim + b._shape_as_2d[axis]) + indptr[idxs] = b.indptr[:-1] + indptr[idxs] += last_indptr + sum_dim += b._shape_as_2d[axis] + last_indptr += b.indptr[-1] + indptr[-1] = last_indptr + # TODO remove this if-structure when sparse matrices removed + if return_spmatrix: + if axis == 0: + return csr_matrix((data, indices, indptr), + shape=(sum_dim, constant_dim)) + else: + return csc_matrix((data, indices, indptr), + shape=(constant_dim, sum_dim)) + + if axis == 0: + return csr_array((data, indices, indptr), + shape=(sum_dim, constant_dim)) + else: + return csc_array((data, indices, indptr), + shape=(constant_dim, sum_dim)) + + +def _stack_along_minor_axis(blocks, axis): + """ + Stacking fast path for CSR/CSC matrices along the minor axis + (i) hstack for CSR, (ii) vstack for CSC. + """ + n_blocks = len(blocks) + if n_blocks == 0: + raise ValueError('Missing block matrices') + + if n_blocks == 1: + return blocks[0] + + # check for incompatible dimensions + other_axis = 1 if axis == 0 else 0 + other_axis_dims = {b._shape_as_2d[other_axis] for b in blocks} + if len(other_axis_dims) > 1: + raise ValueError(f'Mismatching dimensions along axis {other_axis}: ' + f'{other_axis_dims}') + constant_dim, = other_axis_dims + + # Do the stacking + indptr_list = [b.indptr for b in blocks] + data_cat = np.concatenate([b.data for b in blocks]) + + # Need to check if any indices/indptr, would be too large post- + # concatenation for np.int32: + # - The max value of indices is the output array's stacking-axis length - 1 + # - The max value in indptr is the number of non-zero entries. This is + # exceedingly unlikely to require int64, but is checked out of an + # abundance of caution. + sum_dim = sum(b._shape_as_2d[axis] for b in blocks) + nnz = sum(len(b.indices) for b in blocks) + idx_dtype = get_index_dtype(indptr_list, maxval=max(sum_dim - 1, nnz)) + stack_dim_cat = np.array([b._shape_as_2d[axis] for b in blocks], dtype=idx_dtype) + if data_cat.size > 0: + indptr_cat = np.concatenate(indptr_list, dtype=idx_dtype) + indices_cat = np.concatenate([b.indices for b in blocks], dtype=idx_dtype) + indptr = np.empty(constant_dim + 1, dtype=idx_dtype) + indices = np.empty_like(indices_cat) + data = np.empty_like(data_cat) + csr_hstack(n_blocks, constant_dim, stack_dim_cat, + indptr_cat, indices_cat, data_cat, + indptr, indices, data) + else: + indptr = np.zeros(constant_dim + 1, dtype=idx_dtype) + indices = np.empty(0, dtype=idx_dtype) + data = np.empty(0, dtype=data_cat.dtype) + + if axis == 0: + return blocks[0]._csc_container((data, indices, indptr), + shape=(sum_dim, constant_dim)) + else: + return blocks[0]._csr_container((data, indices, indptr), + shape=(constant_dim, sum_dim)) + + +def hstack(blocks, format=None, dtype=None): + """ + Stack sparse matrices horizontally (column wise) + + Parameters + ---------- + blocks + sequence of sparse matrices with compatible shapes + format : str + sparse format of the result (e.g., "csr") + by default an appropriate sparse matrix format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output matrix. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + new_array : sparse matrix or array + If any block in blocks is a sparse array, return a sparse array. + Otherwise return a sparse matrix. + + If you want a sparse array built from blocks that are not sparse + arrays, use ``block(hstack(blocks))`` or convert one block + e.g. ``blocks[0] = csr_array(blocks[0])``. + + See Also + -------- + vstack : stack sparse matrices vertically (row wise) + + Examples + -------- + >>> from scipy.sparse import coo_matrix, hstack + >>> A = coo_matrix([[1, 2], [3, 4]]) + >>> B = coo_matrix([[5], [6]]) + >>> hstack([A,B]).toarray() + array([[1, 2, 5], + [3, 4, 6]]) + + """ + blocks = np.asarray(blocks, dtype='object') + if any(isinstance(b, sparray) for b in blocks.flat): + return _block([blocks], format, dtype) + else: + return _block([blocks], format, dtype, return_spmatrix=True) + + +def vstack(blocks, format=None, dtype=None): + """ + Stack sparse arrays vertically (row wise) + + Parameters + ---------- + blocks + sequence of sparse arrays with compatible shapes + format : str, optional + sparse format of the result (e.g., "csr") + by default an appropriate sparse array format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output array. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + new_array : sparse matrix or array + If any block in blocks is a sparse array, return a sparse array. + Otherwise return a sparse matrix. + + If you want a sparse array built from blocks that are not sparse + arrays, use ``block(vstack(blocks))`` or convert one block + e.g. `blocks[0] = csr_array(blocks[0])`. + + See Also + -------- + hstack : stack sparse matrices horizontally (column wise) + + Examples + -------- + >>> from scipy.sparse import coo_array, vstack + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5, 6]]) + >>> vstack([A, B]).toarray() + array([[1, 2], + [3, 4], + [5, 6]]) + + """ + blocks = np.asarray(blocks, dtype='object') + if any(isinstance(b, sparray) for b in blocks.flat): + return _block([[b] for b in blocks], format, dtype) + else: + return _block([[b] for b in blocks], format, dtype, return_spmatrix=True) + + +def bmat(blocks, format=None, dtype=None): + """ + Build a sparse array or matrix from sparse sub-blocks + + Note: `block_array` is preferred over `bmat`. They are the same function + except that `bmat` can return a deprecated sparse matrix. + `bmat` returns a coo_matrix if none of the inputs are a sparse array. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``block_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + blocks : array_like + Grid of sparse matrices with compatible shapes. + An entry of None implies an all-zero matrix. + format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional + The sparse format of the result (e.g. "csr"). By default an + appropriate sparse matrix format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output matrix. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + bmat : sparse matrix or array + If any block in blocks is a sparse array, return a sparse array. + Otherwise return a sparse matrix. + + If you want a sparse array built from blocks that are not sparse + arrays, use ``block_array()``. + + See Also + -------- + block_array + + Examples + -------- + >>> from scipy.sparse import coo_array, bmat + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5], [6]]) + >>> C = coo_array([[7]]) + >>> bmat([[A, B], [None, C]]).toarray() + array([[1, 2, 5], + [3, 4, 6], + [0, 0, 7]]) + + >>> bmat([[A, None], [None, C]]).toarray() + array([[1, 2, 0], + [3, 4, 0], + [0, 0, 7]]) + + """ + blocks = np.asarray(blocks, dtype='object') + if any(isinstance(b, sparray) for b in blocks.flat): + return _block(blocks, format, dtype) + else: + return _block(blocks, format, dtype, return_spmatrix=True) + + +def block_array(blocks, *, format=None, dtype=None): + """ + Build a sparse array from sparse sub-blocks + + Parameters + ---------- + blocks : array_like + Grid of sparse arrays with compatible shapes. + An entry of None implies an all-zero array. + format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional + The sparse format of the result (e.g. "csr"). By default an + appropriate sparse array format is returned. + This choice is subject to change. + dtype : dtype, optional + The data-type of the output array. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + block : sparse array + + See Also + -------- + block_diag : specify blocks along the main diagonals + diags : specify (possibly offset) diagonals + + Examples + -------- + >>> from scipy.sparse import coo_array, block_array + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5], [6]]) + >>> C = coo_array([[7]]) + >>> block_array([[A, B], [None, C]]).toarray() + array([[1, 2, 5], + [3, 4, 6], + [0, 0, 7]]) + + >>> block_array([[A, None], [None, C]]).toarray() + array([[1, 2, 0], + [3, 4, 0], + [0, 0, 7]]) + + """ + return _block(blocks, format, dtype) + + +def _block(blocks, format, dtype, return_spmatrix=False): + blocks = np.asarray(blocks, dtype='object') + + if blocks.ndim != 2: + raise ValueError('blocks must be 2-D') + + M,N = blocks.shape + + # check for fast path cases + if (format in (None, 'csr') and + all(issparse(b) and b.format == 'csr' for b in blocks.flat) + ): + if N > 1: + # stack along columns (axis 1): must have shape (M, 1) + blocks = [[_stack_along_minor_axis(blocks[b, :], 1)] for b in range(M)] + blocks = np.asarray(blocks, dtype='object') + + # stack along rows (axis 0): + A = _compressed_sparse_stack(blocks[:, 0], 0, return_spmatrix) + if dtype is not None: + A = A.astype(dtype, copy=False) + return A + elif (format in (None, 'csc') and + all(issparse(b) and b.format == 'csc' for b in blocks.flat) + ): + if M > 1: + # stack along rows (axis 0): must have shape (1, N) + blocks = [[_stack_along_minor_axis(blocks[:, b], 0) for b in range(N)]] + blocks = np.asarray(blocks, dtype='object') + + # stack along columns (axis 1): + A = _compressed_sparse_stack(blocks[0, :], 1, return_spmatrix) + if dtype is not None: + A = A.astype(dtype, copy=False) + return A + + block_mask = np.zeros(blocks.shape, dtype=bool) + brow_lengths = np.zeros(M, dtype=np.int64) + bcol_lengths = np.zeros(N, dtype=np.int64) + + # convert everything to COO format + for i in range(M): + for j in range(N): + if blocks[i,j] is not None: + A = coo_array(blocks[i,j]) + blocks[i,j] = A + block_mask[i,j] = True + + if brow_lengths[i] == 0: + brow_lengths[i] = A._shape_as_2d[0] + elif brow_lengths[i] != A._shape_as_2d[0]: + msg = (f'blocks[{i},:] has incompatible row dimensions. ' + f'Got blocks[{i},{j}].shape[0] == {A._shape_as_2d[0]}, ' + f'expected {brow_lengths[i]}.') + raise ValueError(msg) + + if bcol_lengths[j] == 0: + bcol_lengths[j] = A._shape_as_2d[1] + elif bcol_lengths[j] != A._shape_as_2d[1]: + msg = (f'blocks[:,{j}] has incompatible column ' + f'dimensions. ' + f'Got blocks[{i},{j}].shape[1] == {A._shape_as_2d[1]}, ' + f'expected {bcol_lengths[j]}.') + raise ValueError(msg) + + nnz = sum(block.nnz for block in blocks[block_mask]) + if dtype is None: + all_dtypes = [blk.dtype for blk in blocks[block_mask]] + dtype = upcast(*all_dtypes) if all_dtypes else None + + row_offsets = np.append(0, np.cumsum(brow_lengths)) + col_offsets = np.append(0, np.cumsum(bcol_lengths)) + + shape = (row_offsets[-1], col_offsets[-1]) + + data = np.empty(nnz, dtype=dtype) + idx_dtype = get_index_dtype([b.coords[0] for b in blocks[block_mask]], + maxval=max(shape)) + row = np.empty(nnz, dtype=idx_dtype) + col = np.empty(nnz, dtype=idx_dtype) + + nnz = 0 + ii, jj = np.nonzero(block_mask) + for i, j in zip(ii, jj): + B = blocks[i, j] + idx = slice(nnz, nnz + B.nnz) + data[idx] = B.data + np.add(B.row, row_offsets[i], out=row[idx], dtype=idx_dtype) + np.add(B.col, col_offsets[j], out=col[idx], dtype=idx_dtype) + nnz += B.nnz + + if return_spmatrix: + return coo_matrix((data, (row, col)), shape=shape).asformat(format) + return coo_array((data, (row, col)), shape=shape).asformat(format) + + +def block_diag(mats, format=None, dtype=None): + """ + Build a block diagonal sparse matrix or array from provided matrices. + + Parameters + ---------- + mats : sequence of matrices or arrays + Input matrices or arrays. + format : str, optional + The sparse format of the result (e.g., "csr"). If not given, the result + is returned in "coo" format. + dtype : dtype specifier, optional + The data-type of the output. If not given, the dtype is + determined from that of `blocks`. + + Returns + ------- + res : sparse matrix or array + If at least one input is a sparse array, the output is a sparse array. + Otherwise the output is a sparse matrix. + + Notes + ----- + + .. versionadded:: 0.11.0 + + See Also + -------- + block_array + diags_array + + Examples + -------- + >>> from scipy.sparse import coo_array, block_diag + >>> A = coo_array([[1, 2], [3, 4]]) + >>> B = coo_array([[5], [6]]) + >>> C = coo_array([[7]]) + >>> block_diag((A, B, C)).toarray() + array([[1, 2, 0, 0], + [3, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 6, 0], + [0, 0, 0, 7]]) + + """ + if any(isinstance(a, sparray) for a in mats): + container = coo_array + else: + container = coo_matrix + + row = [] + col = [] + data = [] + idx_arrays = [] # track idx_dtype of incoming sparse arrays + r_idx = 0 + c_idx = 0 + for a in mats: + if isinstance(a, (list | numbers.Number)): + a = coo_array(np.atleast_2d(a)) + if issparse(a): + a = a.tocoo() + if not idx_arrays and a.coords[0].dtype == np.int64: + idx_arrays.append(a.coords[0]) + nrows, ncols = a._shape_as_2d + row.append(a.row + r_idx) + col.append(a.col + c_idx) + data.append(a.data) + else: + nrows, ncols = a.shape + a_row, a_col = np.divmod(np.arange(nrows*ncols), ncols) + row.append(a_row + r_idx) + col.append(a_col + c_idx) + data.append(a.ravel()) + r_idx += nrows + c_idx += ncols + idx_dtype = get_index_dtype(idx_arrays, maxval=max(r_idx, c_idx)) + row = np.concatenate(row, dtype=idx_dtype) + col = np.concatenate(col, dtype=idx_dtype) + data = np.concatenate(data) + new_shape = (r_idx, c_idx) + + return container((data, (row, col)), shape=new_shape, dtype=dtype).asformat(format) + + +@_transition_to_rng("random_state") +def random_array(shape, *, density=0.01, format='coo', dtype=None, + rng=None, data_sampler=None): + """Return a sparse array of uniformly random numbers in [0, 1) + + Returns a sparse array with the given shape and density + where values are generated uniformly randomly in the range [0, 1). + + Parameters + ---------- + shape : int or tuple of ints + shape of the array + density : real, optional (default: 0.01) + density of the generated matrix: density equal to one means a full + matrix, density of 0 means a matrix with no non-zero items. + format : str, optional (default: 'coo') + sparse matrix format. + dtype : dtype, optional (default: np.float64) + type of the returned matrix values. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + This random state will be used for sampling `indices` (the sparsity + structure), and by default for the data values too (see `data_sampler`). + data_sampler : callable, optional (default depends on dtype) + Sampler of random data values with keyword arg `size`. + This function should take a single keyword argument `size` specifying + the length of its returned ndarray. It is used to generate the nonzero + values in the matrix after the locations of those values are chosen. + By default, uniform [0, 1) random values are used unless `dtype` is + an integer (default uniform integers from that dtype) or + complex (default uniform over the unit square in the complex plane). + For these, the `rng` is used e.g. ``rng.uniform(size=size)``. + + Returns + ------- + res : sparse array + + Examples + -------- + + Passing a ``np.random.Generator`` instance for better performance: + + >>> import numpy as np + >>> import scipy as sp + >>> rng = np.random.default_rng() + + Default sampling uniformly from [0, 1): + + >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng) + + Providing a sampler for the values: + + >>> rvs = sp.stats.poisson(25, loc=10).rvs + >>> S = sp.sparse.random_array((3, 4), density=0.25, + ... rng=rng, data_sampler=rvs) + >>> S.toarray() + array([[ 36., 0., 33., 0.], # random + [ 0., 0., 0., 0.], + [ 0., 0., 36., 0.]]) + + Building a custom distribution. + This example builds a squared normal from np.random: + + >>> def np_normal_squared(size=None, rng=rng): + ... return rng.standard_normal(size) ** 2 + >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, + ... data_sampler=np_normal_squared) + + Or we can build it from sp.stats style rvs functions: + + >>> def sp_stats_normal_squared(size=None, rng=rng): + ... std_normal = sp.stats.distributions.norm_gen().rvs + ... return std_normal(size=size, random_state=rng) ** 2 + >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng, + ... data_sampler=sp_stats_normal_squared) + + Or we can subclass sp.stats rv_continuous or rv_discrete: + + >>> class NormalSquared(sp.stats.rv_continuous): + ... def _rvs(self, size=None, random_state=rng): + ... return rng.standard_normal(size) ** 2 + >>> X = NormalSquared() + >>> Y = X().rvs + >>> S = sp.sparse.random_array((3, 4), density=0.25, + ... rng=rng, data_sampler=Y) + """ + data, ind = _random(shape, density, format, dtype, rng, data_sampler) + + # downcast, if safe, before calling coo_constructor + idx_dtype = get_index_dtype(maxval=max(shape)) + ind = tuple(np.asarray(co, dtype=idx_dtype) for co in ind) + return coo_array((data, ind), shape=shape).asformat(format) + + +def _random(shape, density=0.01, format=None, dtype=None, + rng=None, data_sampler=None): + if density < 0 or density > 1: + raise ValueError("density expected to be 0 <= density <= 1") + + tot_prod = math.prod(shape) # use `math` for when prod is >= 2**64 + + # Number of non zero values + size = int(round(density * tot_prod)) + + rng = check_random_state(rng) + + if data_sampler is None: + if np.issubdtype(dtype, np.integer): + def data_sampler(size): + return rng_integers(rng, + np.iinfo(dtype).min, + np.iinfo(dtype).max, + size, + dtype=dtype) + elif np.issubdtype(dtype, np.complexfloating): + def data_sampler(size): + return (rng.uniform(size=size) + + rng.uniform(size=size) * 1j) + else: + data_sampler = rng.uniform + + idx_dtype = get_index_dtype(maxval=max(shape)) + # rng.choice uses int64 if first arg is an int + if tot_prod <= np.iinfo(np.int64).max: + raveled_ind = rng.choice(tot_prod, size=size, replace=False) + ind = np.unravel_index(raveled_ind, shape=shape, order='F') + ind = tuple(np.asarray(co, idx_dtype) for co in ind) + else: + # for ravel indices bigger than dtype max, use sets to remove duplicates + ndim = len(shape) + seen = set() + while len(seen) < size: + dsize = size - len(seen) + seen.update(map(tuple, rng_integers(rng, shape, size=(dsize, ndim)))) + ind = tuple(np.array(list(seen), dtype=idx_dtype).T) + + # size kwarg allows eg data_sampler=partial(np.random.poisson, lam=5) + vals = data_sampler(size=size).astype(dtype, copy=False) + return vals, ind + + +@_transition_to_rng("random_state", position_num=5) +def random(m, n, density=0.01, format='coo', dtype=None, + rng=None, data_rvs=None): + """Generate a sparse matrix of the given shape and density with randomly + distributed values. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``random_array`` to take advantage of the + sparse array functionality. + + Parameters + ---------- + m, n : int + shape of the matrix + density : real, optional + density of the generated matrix: density equal to one means a full + matrix, density of 0 means a matrix with no non-zero items. + format : str, optional + sparse matrix format. + dtype : dtype, optional + type of the returned matrix values. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + This random state will be used for sampling the sparsity structure, but + not necessarily for sampling the values of the structurally nonzero + entries of the matrix. + data_rvs : callable, optional + Samples a requested number of random values. + This function should take a single argument specifying the length + of the ndarray that it will return. The structurally nonzero entries + of the sparse random matrix will be taken from the array sampled + by this function. By default, uniform [0, 1) random values will be + sampled using the same random state as is used for sampling + the sparsity structure. + + Returns + ------- + res : sparse matrix + + See Also + -------- + random_array : constructs sparse arrays instead of sparse matrices + + Examples + -------- + + Passing a ``np.random.Generator`` instance for better performance: + + >>> import scipy as sp + >>> import numpy as np + >>> rng = np.random.default_rng() + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng) + + Providing a sampler for the values: + + >>> rvs = sp.stats.poisson(25, loc=10).rvs + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=rvs) + >>> S.toarray() + array([[ 36., 0., 33., 0.], # random + [ 0., 0., 0., 0.], + [ 0., 0., 36., 0.]]) + + Building a custom distribution. + This example builds a squared normal from np.random: + + >>> def np_normal_squared(size=None, rng=rng): + ... return rng.standard_normal(size) ** 2 + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, + ... data_rvs=np_normal_squared) + + Or we can build it from sp.stats style rvs functions: + + >>> def sp_stats_normal_squared(size=None, rng=rng): + ... std_normal = sp.stats.distributions.norm_gen().rvs + ... return std_normal(size=size, random_state=rng) ** 2 + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, + ... data_rvs=sp_stats_normal_squared) + + Or we can subclass sp.stats rv_continuous or rv_discrete: + + >>> class NormalSquared(sp.stats.rv_continuous): + ... def _rvs(self, size=None, random_state=rng): + ... return rng.standard_normal(size) ** 2 + >>> X = NormalSquared() + >>> Y = X() # get a frozen version of the distribution + >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=Y.rvs) + """ + if n is None: + n = m + m, n = int(m), int(n) + # make keyword syntax work for data_rvs e.g. data_rvs(size=7) + if data_rvs is not None: + def data_rvs_kw(size): + return data_rvs(size) + else: + data_rvs_kw = None + vals, ind = _random((m, n), density, format, dtype, rng, data_rvs_kw) + return coo_matrix((vals, ind), shape=(m, n)).asformat(format) + + +@_transition_to_rng("random_state", position_num=5) +def rand(m, n, density=0.01, format="coo", dtype=None, rng=None): + """Generate a sparse matrix of the given shape and density with uniformly + distributed values. + + .. warning:: + + This function returns a sparse matrix -- not a sparse array. + You are encouraged to use ``random_array`` to take advantage + of the sparse array functionality. + + Parameters + ---------- + m, n : int + shape of the matrix + density : real, optional + density of the generated matrix: density equal to one means a full + matrix, density of 0 means a matrix with no non-zero items. + format : str, optional + sparse matrix format. + dtype : dtype, optional + type of the returned matrix values. + rng : `numpy.random.Generator`, optional + Pseudorandom number generator state. When `rng` is None, a new + `numpy.random.Generator` is created using entropy from the + operating system. Types other than `numpy.random.Generator` are + passed to `numpy.random.default_rng` to instantiate a ``Generator``. + + Returns + ------- + res : sparse matrix + + Notes + ----- + Only float types are supported for now. + + See Also + -------- + random : Similar function allowing a custom random data sampler + random_array : Similar to random() but returns a sparse array + + Examples + -------- + >>> from scipy.sparse import rand + >>> matrix = rand(3, 4, density=0.25, format="csr", rng=42) + >>> matrix + + >>> matrix.toarray() + array([[0.05641158, 0. , 0. , 0.65088847], # random + [0. , 0. , 0. , 0.14286682], + [0. , 0. , 0. , 0. ]]) + + """ + return random(m, n, density, format, dtype, rng) diff --git a/shared/package-files/77/774fb4748790323db4343a02373d12646fa9642b30ed8b1707d04e516fc2ed97/blob b/shared/package-files/77/774fb4748790323db4343a02373d12646fa9642b30ed8b1707d04e516fc2ed97/blob new file mode 100644 index 0000000000000000000000000000000000000000..2f43c5f8f71ae3562729a0d6533ea5fa8c35ed07 --- /dev/null +++ b/shared/package-files/77/774fb4748790323db4343a02373d12646fa9642b30ed8b1707d04e516fc2ed97/blob @@ -0,0 +1,154 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import os +import sys +from collections import namedtuple +from logging import getLogger +from os.path import abspath +from subprocess import PIPE, CalledProcessError, Popen + +from conda.auxlib.compat import shlex_split_unicode + +from .. import ACTIVE_SUBPROCESSES +from ..auxlib.ish import dals +from ..base.context import context +from ..common.compat import encode_arguments, encode_environment, isiterable +from ..gateways.disk.delete import rm_rf +from ..utils import wrap_subprocess_call +from .logging import TRACE + +log = getLogger(__name__) +Response = namedtuple("Response", ("stdout", "stderr", "rc")) + + +def _format_output(command_str, cwd, rc, stdout, stderr): + return ( + dals( + """ + $ %s + ==> cwd: %s <== + ==> exit code: %d <== + ==> stdout <== + %s + ==> stderr <== + %s + """ + ) + % (command_str, cwd, rc, stdout, stderr) + ) + + +def any_subprocess(args, prefix, env=None, cwd=None): + script_caller, command_args = wrap_subprocess_call( + context.root_prefix, + prefix, + context.dev, + context.verbosity >= 2, + args, + ) + process = Popen( + command_args, + cwd=cwd or prefix, + universal_newlines=False, + stdout=PIPE, + stderr=PIPE, + env=env, + ) + stdout, stderr = process.communicate() + if script_caller is not None: + if "CONDA_TEST_SAVE_TEMPS" not in os.environ: + rm_rf(script_caller) + else: + log.warning( + "CONDA_TEST_SAVE_TEMPS :: retaining pip run_script {}".format( + script_caller + ) + ) + if hasattr(stdout, "decode"): + stdout = stdout.decode("utf-8", errors="replace") + if hasattr(stderr, "decode"): + stderr = stderr.decode("utf-8", errors="replace") + return stdout, stderr, process.returncode + + +def subprocess_call( + command, env=None, path=None, stdin=None, raise_on_error=True, capture_output=True +): + """This utility function should be preferred for all conda subprocessing. + It handles multiple tricky details. + """ + env = encode_environment(env or os.environ) + cwd = sys.prefix if path is None else abspath(path) + if not isiterable(command): + command = shlex_split_unicode(command) + command_str = command if isinstance(command, str) else " ".join(command) + log.debug("executing>> %s", command_str) + + pipe = None + if capture_output: + pipe = PIPE + elif stdin: + raise ValueError("When passing stdin, output needs to be captured") + else: + stdin = None + + # spawn subprocess + process = Popen( + encode_arguments(command), + cwd=cwd, + stdin=pipe, + stdout=pipe, + stderr=pipe, + env=env, + ) + ACTIVE_SUBPROCESSES.add(process) + + # decode output, if not PIPE, stdout/stderr will be None + stdout, stderr = process.communicate(input=stdin) + if hasattr(stdout, "decode"): + stdout = stdout.decode("utf-8", errors="replace") + if hasattr(stderr, "decode"): + stderr = stderr.decode("utf-8", errors="replace") + rc = process.returncode + ACTIVE_SUBPROCESSES.remove(process) + + if (raise_on_error and rc != 0) or log.isEnabledFor(TRACE): + formatted_output = _format_output(command_str, cwd, rc, stdout, stderr) + if raise_on_error and rc != 0: + log.info(formatted_output) + raise CalledProcessError(rc, command, output=formatted_output) + if log.isEnabledFor(TRACE): + log.trace(formatted_output) + + return Response(stdout, stderr, int(rc)) + + +def _subprocess_clean_env(env, clean_python=True, clean_conda=True): + dels = [] + if clean_python: + dels.extend(("PYTHONPATH", "PYTHONHOME")) + if clean_conda: + dels.extend( + ("CONDA_ROOT", "CONDA_PROMPT_MODIFIER", "CONDA_EXE", "CONDA_DEFAULT_ENV") + ) + for key in dels: + if key in env: + del env[key] + + +def subprocess_call_with_clean_env( + command, + path=None, + stdin=None, + raise_on_error=True, + clean_python=True, + clean_conda=True, +): + # Any of these env vars are likely to mess the whole thing up. + # This has been seen to be the case with PYTHONPATH. + env = os.environ.copy() + _subprocess_clean_env(env, clean_python, clean_conda) + # env['CONDA_DLL_SEARCH_MODIFICATION_ENABLE'] = '1' + return subprocess_call( + command, env=env, path=path, stdin=stdin, raise_on_error=raise_on_error + ) diff --git a/shared/package-files/77/7758d7c62b28b5c45547988741a7159579bccfd01e895eaf04ee6ce2ecbaff60/blob b/shared/package-files/77/7758d7c62b28b5c45547988741a7159579bccfd01e895eaf04ee6ce2ecbaff60/blob new file mode 100644 index 0000000000000000000000000000000000000000..3cc997c784c63a61f71860f5684266e122028ed6 --- /dev/null +++ b/shared/package-files/77/7758d7c62b28b5c45547988741a7159579bccfd01e895eaf04ee6ce2ecbaff60/blob @@ -0,0 +1,63 @@ +# Since bitmap glyph metrics are shared between EBLC and EBDT +# this class gets its own python file. +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +import logging + +log = logging.getLogger(__name__) + +bigGlyphMetricsFormat = """ + > # big endian + height: B + width: B + horiBearingX: b + horiBearingY: b + horiAdvance: B + vertBearingX: b + vertBearingY: b + vertAdvance: B +""" + +smallGlyphMetricsFormat = """ + > # big endian + height: B + width: B + BearingX: b + BearingY: b + Advance: B +""" + + +class BitmapGlyphMetrics(object): + def toXML(self, writer, ttFont): + writer.begintag(self.__class__.__name__) + writer.newline() + for metricName in sstruct.getformat(self.__class__.binaryFormat)[1]: + writer.simpletag(metricName, value=getattr(self, metricName)) + writer.newline() + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + # Make sure this is a metric that is needed by GlyphMetrics. + if name in metricNames: + vars(self)[name] = safeEval(attrs["value"]) + else: + log.warning( + "unknown name '%s' being ignored in %s.", + name, + self.__class__.__name__, + ) + + +class BigGlyphMetrics(BitmapGlyphMetrics): + binaryFormat = bigGlyphMetricsFormat + + +class SmallGlyphMetrics(BitmapGlyphMetrics): + binaryFormat = smallGlyphMetricsFormat diff --git a/shared/package-files/77/775d67558aafd5da82fc7d80f8f5f3d681d860200e9e42bfb3cef2b66e2dc0c0/blob b/shared/package-files/77/775d67558aafd5da82fc7d80f8f5f3d681d860200e9e42bfb3cef2b66e2dc0c0/blob new file mode 100644 index 0000000000000000000000000000000000000000..b38aab8b98dc0695675feb9e94868f0dc93d67d0 --- /dev/null +++ b/shared/package-files/77/775d67558aafd5da82fc7d80f8f5f3d681d860200e9e42bfb3cef2b66e2dc0c0/blob @@ -0,0 +1,10 @@ +from __future__ import annotations # pragma: no cover + +from typing import TYPE_CHECKING # pragma: no cover + +if TYPE_CHECKING: + from typing import TypeVar + + from narwhals._polars.dataframe import PolarsDataFrame, PolarsLazyFrame + + FrameT = TypeVar("FrameT", PolarsDataFrame, PolarsLazyFrame) diff --git a/shared/package-files/77/776078e89fd7dadbce41678f8bacd3b493135e6d610911c867489415420de383/blob b/shared/package-files/77/776078e89fd7dadbce41678f8bacd3b493135e6d610911c867489415420de383/blob new file mode 100644 index 0000000000000000000000000000000000000000..ce77632516c646ecc11e231a1d855e3a48670a71 --- /dev/null +++ b/shared/package-files/77/776078e89fd7dadbce41678f8bacd3b493135e6d610911c867489415420de383/blob @@ -0,0 +1,206 @@ +import contextlib +import os +import pathlib +import shutil +import stat +import sys +import zipfile + +__all__ = ['ZipAppError', 'create_archive', 'get_interpreter'] + + +# The __main__.py used if the users specifies "-m module:fn". +# Note that this will always be written as UTF-8 (module and +# function names can be non-ASCII in Python 3). +# We add a coding cookie even though UTF-8 is the default in Python 3 +# because the resulting archive may be intended to be run under Python 2. +MAIN_TEMPLATE = """\ +# -*- coding: utf-8 -*- +import {module} +{module}.{fn}() +""" + + +# The Windows launcher defaults to UTF-8 when parsing shebang lines if the +# file has no BOM. So use UTF-8 on Windows. +# On Unix, use the filesystem encoding. +if sys.platform.startswith('win'): + shebang_encoding = 'utf-8' +else: + shebang_encoding = sys.getfilesystemencoding() + + +class ZipAppError(ValueError): + pass + + +@contextlib.contextmanager +def _maybe_open(archive, mode): + if isinstance(archive, (str, os.PathLike)): + with open(archive, mode) as f: + yield f + else: + yield archive + + +def _write_file_prefix(f, interpreter): + """Write a shebang line.""" + if interpreter: + shebang = b'#!' + interpreter.encode(shebang_encoding) + b'\n' + f.write(shebang) + + +def _copy_archive(archive, new_archive, interpreter=None): + """Copy an application archive, modifying the shebang line.""" + with _maybe_open(archive, 'rb') as src: + # Skip the shebang line from the source. + # Read 2 bytes of the source and check if they are #!. + first_2 = src.read(2) + if first_2 == b'#!': + # Discard the initial 2 bytes and the rest of the shebang line. + first_2 = b'' + src.readline() + + with _maybe_open(new_archive, 'wb') as dst: + _write_file_prefix(dst, interpreter) + # If there was no shebang, "first_2" contains the first 2 bytes + # of the source file, so write them before copying the rest + # of the file. + dst.write(first_2) + shutil.copyfileobj(src, dst) + + if interpreter and isinstance(new_archive, str): + os.chmod(new_archive, os.stat(new_archive).st_mode | stat.S_IEXEC) + + +def create_archive(source, target=None, interpreter=None, main=None, + filter=None, compressed=False): + """Create an application archive from SOURCE. + + The SOURCE can be the name of a directory, or a filename or a file-like + object referring to an existing archive. + + The content of SOURCE is packed into an application archive in TARGET, + which can be a filename or a file-like object. If SOURCE is a directory, + TARGET can be omitted and will default to the name of SOURCE with .pyz + appended. + + The created application archive will have a shebang line specifying + that it should run with INTERPRETER (there will be no shebang line if + INTERPRETER is None), and a __main__.py which runs MAIN (if MAIN is + not specified, an existing __main__.py will be used). It is an error + to specify MAIN for anything other than a directory source with no + __main__.py, and it is an error to omit MAIN if the directory has no + __main__.py. + """ + # Are we copying an existing archive? + source_is_file = False + if hasattr(source, 'read') and hasattr(source, 'readline'): + source_is_file = True + else: + source = pathlib.Path(source) + if source.is_file(): + source_is_file = True + + if source_is_file: + _copy_archive(source, target, interpreter) + return + + # We are creating a new archive from a directory. + if not source.exists(): + raise ZipAppError("Source does not exist") + has_main = (source / '__main__.py').is_file() + if main and has_main: + raise ZipAppError( + "Cannot specify entry point if the source has __main__.py") + if not (main or has_main): + raise ZipAppError("Archive has no entry point") + + main_py = None + if main: + # Check that main has the right format. + mod, sep, fn = main.partition(':') + mod_ok = all(part.isidentifier() for part in mod.split('.')) + fn_ok = all(part.isidentifier() for part in fn.split('.')) + if not (sep == ':' and mod_ok and fn_ok): + raise ZipAppError("Invalid entry point: " + main) + main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) + + if target is None: + target = source.with_suffix('.pyz') + elif not hasattr(target, 'write'): + target = pathlib.Path(target) + + with _maybe_open(target, 'wb') as fd: + _write_file_prefix(fd, interpreter) + compression = (zipfile.ZIP_DEFLATED if compressed else + zipfile.ZIP_STORED) + with zipfile.ZipFile(fd, 'w', compression=compression) as z: + for child in source.rglob('*'): + arcname = child.relative_to(source) + if filter is None or filter(arcname): + z.write(child, arcname.as_posix()) + if main_py: + z.writestr('__main__.py', main_py.encode('utf-8')) + + if interpreter and not hasattr(target, 'write'): + target.chmod(target.stat().st_mode | stat.S_IEXEC) + + +def get_interpreter(archive): + with _maybe_open(archive, 'rb') as f: + if f.read(2) == b'#!': + return f.readline().strip().decode(shebang_encoding) + + +def main(args=None): + """Run the zipapp command line interface. + + The ARGS parameter lets you specify the argument list directly. + Omitting ARGS (or setting it to None) works as for argparse, using + sys.argv[1:] as the argument list. + """ + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument('--output', '-o', default=None, + help="The name of the output archive. " + "Required if SOURCE is an archive.") + parser.add_argument('--python', '-p', default=None, + help="The name of the Python interpreter to use " + "(default: no shebang line).") + parser.add_argument('--main', '-m', default=None, + help="The main function of the application " + "(default: use an existing __main__.py).") + parser.add_argument('--compress', '-c', action='store_true', + help="Compress files with the deflate method. " + "Files are stored uncompressed by default.") + parser.add_argument('--info', default=False, action='store_true', + help="Display the interpreter from the archive.") + parser.add_argument('source', + help="Source directory (or existing archive).") + + args = parser.parse_args(args) + + # Handle `python -m zipapp archive.pyz --info`. + if args.info: + if not os.path.isfile(args.source): + raise SystemExit("Can only get info for an archive file") + interpreter = get_interpreter(args.source) + print("Interpreter: {}".format(interpreter or "")) + sys.exit(0) + + if os.path.isfile(args.source): + if args.output is None or (os.path.exists(args.output) and + os.path.samefile(args.source, args.output)): + raise SystemExit("In-place editing of archives is not supported") + if args.main: + raise SystemExit("Cannot change the main function when copying") + + create_archive(args.source, args.output, + interpreter=args.python, main=args.main, + compressed=args.compress) + + +if __name__ == '__main__': + main() diff --git a/shared/package-files/77/7764a770c14210b42fd28c7d9e83a517fccfcca1baafd0848998205f4272a68d/blob b/shared/package-files/77/7764a770c14210b42fd28c7d9e83a517fccfcca1baafd0848998205f4272a68d/blob new file mode 100644 index 0000000000000000000000000000000000000000..bac85bab6270a84bf79ccb987d90bab53cc86bf4 --- /dev/null +++ b/shared/package-files/77/7764a770c14210b42fd28c7d9e83a517fccfcca1baafd0848998205f4272a68d/blob @@ -0,0 +1,41 @@ +from __future__ import annotations + +from .base import Always, Filter, FilterOrBool, Never + +__all__ = [ + "to_filter", + "is_true", +] + + +_always = Always() +_never = Never() + + +_bool_to_filter: dict[bool, Filter] = { + True: _always, + False: _never, +} + + +def to_filter(bool_or_filter: FilterOrBool) -> Filter: + """ + Accept both booleans and Filters as input and + turn it into a Filter. + """ + if isinstance(bool_or_filter, bool): + return _bool_to_filter[bool_or_filter] + + if isinstance(bool_or_filter, Filter): + return bool_or_filter + + raise TypeError("Expecting a bool or a Filter instance. Got %r" % bool_or_filter) + + +def is_true(value: FilterOrBool) -> bool: + """ + Test whether `value` is True. In case of a Filter, call it. + + :param value: Boolean or `Filter` instance. + """ + return to_filter(value)() diff --git a/shared/package-files/77/7767e625af6ee46aeb01a493f0981d7e916c0712aea6f28b6f6887f5580fed68/blob b/shared/package-files/77/7767e625af6ee46aeb01a493f0981d7e916c0712aea6f28b6f6887f5580fed68/blob new file mode 100644 index 0000000000000000000000000000000000000000..e0cd08a83c5bb81d45fa3794168026bbc5455107 --- /dev/null +++ b/shared/package-files/77/7767e625af6ee46aeb01a493f0981d7e916c0712aea6f28b6f6887f5580fed68/blob @@ -0,0 +1,17 @@ +class RedisError(Exception): ... + +def __unicode__(self): ... + +class AuthenticationError(RedisError): ... +class ConnectionError(RedisError): ... +class TimeoutError(RedisError): ... +class BusyLoadingError(ConnectionError): ... +class InvalidResponse(RedisError): ... +class ResponseError(RedisError): ... +class DataError(RedisError): ... +class PubSubError(RedisError): ... +class WatchError(RedisError): ... +class NoScriptError(ResponseError): ... +class ExecAbortError(ResponseError): ... +class ReadOnlyError(ResponseError): ... +class LockError(RedisError, ValueError): ... diff --git a/shared/package-files/77/776af8dd8b1ebe22a803d3b25fa26f0f25ef63c94545f57ffe3e618a9a64618d/blob b/shared/package-files/77/776af8dd8b1ebe22a803d3b25fa26f0f25ef63c94545f57ffe3e618a9a64618d/blob new file mode 100644 index 0000000000000000000000000000000000000000..e5d6c853aa454ff31dd1edfccee4993c1e133c4d --- /dev/null +++ b/shared/package-files/77/776af8dd8b1ebe22a803d3b25fa26f0f25ef63c94545f57ffe3e618a9a64618d/blob @@ -0,0 +1,26 @@ +"""Test Olivetti faces fetcher, if the data is available, +or if specifically requested via environment variable +(e.g. for CI jobs).""" + +import numpy as np + +from sklearn.datasets.tests.test_common import check_return_X_y +from sklearn.utils import Bunch +from sklearn.utils._testing import assert_array_equal + + +def test_olivetti_faces(fetch_olivetti_faces_fxt): + data = fetch_olivetti_faces_fxt(shuffle=True, random_state=0) + + assert isinstance(data, Bunch) + for expected_keys in ("data", "images", "target", "DESCR"): + assert expected_keys in data.keys() + + assert data.data.shape == (400, 4096) + assert data.images.shape == (400, 64, 64) + assert data.target.shape == (400,) + assert_array_equal(np.unique(np.sort(data.target)), np.arange(40)) + assert data.DESCR.startswith(".. _olivetti_faces_dataset:") + + # test the return_X_y option + check_return_X_y(data, fetch_olivetti_faces_fxt) diff --git a/shared/package-files/77/776e7b1f86c9e821bc8ce03afc3f8ce935f653d966200f6ffadd424addb066ff/blob b/shared/package-files/77/776e7b1f86c9e821bc8ce03afc3f8ce935f653d966200f6ffadd424addb066ff/blob new file mode 100644 index 0000000000000000000000000000000000000000..71b55d18a23e49c239c8221343a32078b53b667b --- /dev/null +++ b/shared/package-files/77/776e7b1f86c9e821bc8ce03afc3f8ce935f653d966200f6ffadd424addb066ff/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::logical_or(Tensor self, Tensor other) -> Tensor +inline at::Tensor logical_or(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::logical_or::call(self, other); +} + +// aten::logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logical_or_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::logical_or_out::call(self, other, out); +} +// aten::logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & logical_or_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::logical_or_out::call(self, other, out); +} + +} diff --git a/shared/package-files/77/7770155e40b821a49cc7a1d2e4bcf76374905e4cc0f117bdb904fdb37d8e3ad7/blob b/shared/package-files/77/7770155e40b821a49cc7a1d2e4bcf76374905e4cc0f117bdb904fdb37d8e3ad7/blob new file mode 100644 index 0000000000000000000000000000000000000000..4690ba81b360a8354d837d9e8db29bff231e06f9 --- /dev/null +++ b/shared/package-files/77/7770155e40b821a49cc7a1d2e4bcf76374905e4cc0f117bdb904fdb37d8e3ad7/blob @@ -0,0 +1,408 @@ +import torch.fx as fx +from torch.fx.node import Argument, Target +from torch.nn.utils.fusion import fuse_conv_bn_eval +from typing import Type, Dict, Any, Tuple, Iterable, Optional, List, cast +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.fx.passes.shape_prop import ShapeProp +import copy +from collections import defaultdict +import torch.utils.mkldnn as th_mkldnn +import operator +import time +import logging +from enum import Enum + +def _parent_name(target : str) -> Tuple[str, str]: + """ + Splits a qualname into parent path and last atom. + For example, `foo.bar.baz` -> (`foo.bar`, `baz`) + """ + *parent, name = target.rsplit('.', 1) + return parent[0] if parent else '', name + +# Works for length 2 patterns with 2 modules +def matches_module_pattern(pattern: Iterable[Type], node: fx.Node, modules: Dict[str, Any]): + if len(node.args) == 0: + return False + nodes: Tuple[Any, fx.Node] = (node.args[0], node) + for expected_type, current_node in zip(pattern, nodes): + if not isinstance(current_node, fx.Node): + return False + if current_node.op != 'call_module': + return False + if not isinstance(current_node.target, str): + return False + if current_node.target not in modules: + return False + if type(modules[current_node.target]) is not expected_type: + return False + return True + + +def replace_node_module(node: fx.Node, modules: Dict[str, Any], new_module: torch.nn.Module): + assert isinstance(node.target, str) + parent_name, name = _parent_name(node.target) + modules[node.target] = new_module + setattr(modules[parent_name], name, new_module) + +def fuse(model: torch.nn.Module, inplace=False, no_trace=False) -> torch.nn.Module: + """ + Fuses convolution/BN layers for inference purposes. Will deepcopy your + model by default, but can modify the model inplace as well. + """ + patterns = [(nn.Conv1d, nn.BatchNorm1d), + (nn.Conv2d, nn.BatchNorm2d), + (nn.Conv3d, nn.BatchNorm3d)] + if not inplace: + model = copy.deepcopy(model) + if not no_trace or not isinstance(model, torch.fx.GraphModule): + fx_model = fx.symbolic_trace(model) + else: + fx_model = model + modules = dict(fx_model.named_modules()) + new_graph = copy.deepcopy(fx_model.graph) + + for pattern in patterns: + for node in new_graph.nodes: + if matches_module_pattern(pattern, node, modules): + if len(node.args[0].users) > 1: # Output of conv is used by other nodes + continue + conv = modules[node.args[0].target] + bn = modules[node.target] + if not bn.track_running_stats: + continue + fused_conv = fuse_conv_bn_eval(conv, bn) + replace_node_module(node.args[0], modules, fused_conv) + node.replace_all_uses_with(node.args[0]) + new_graph.erase_node(node) + return fx.GraphModule(fx_model, new_graph) + +def remove_dropout(model: nn.Module) -> nn.Module: + """ + Removes all dropout layers from the module. + """ + fx_model = fx.symbolic_trace(model) + + class DropoutRemover(torch.fx.Transformer): + def call_module(self, target : Target, args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any: + if isinstance(self.submodules[target], nn.Dropout): + assert len(args) == 1 + return args[0] + else: + return super().call_module(target, args, kwargs) + return DropoutRemover(fx_model).transform() + +def extract_subgraph(orig_module: nn.Module, nodes: List[fx.Node], inputs: List[fx.Node], outputs: List[fx.Node]): + """ + Given lists of nodes from an existing graph that represent a subgraph, returns a submodule that executes that subgraph. + """ + new_graph = fx.Graph() + env: Dict[fx.Node, fx.Node] = {} + for input in inputs: + new_node = new_graph.placeholder(input.name) + env[input] = new_node + for node in nodes: + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + new_graph.output([env[output] for output in outputs]) + new_graph.lint() + return fx.GraphModule(orig_module, new_graph) + +mkldnn_supported = [ + nn.Conv2d, nn.Linear, nn.BatchNorm2d, nn.ReLU, nn.MaxPool2d, nn.AvgPool2d, nn.AdaptiveAvgPool2d, + torch.relu, torch.transpose, torch.sigmoid, + F.relu, F.avg_pool2d, F.adaptive_avg_pool2d +] +# These are operators that may not be convertible into MKLDNN ops (e.g. the +# args are scalar values). Thus, we only include them in the subgraph if their +# arguments are already in MKLDNN. +# TODO: Determine whether this can be removed after type inference. +mkldnn_supported_unknown = [operator.add, operator.mul] +mkldnn_map = { + nn.Conv2d: th_mkldnn.MkldnnConv2d, + nn.Linear: th_mkldnn.MkldnnLinear, + nn.BatchNorm2d: lambda a, _: th_mkldnn.MkldnnBatchNorm(a) +} + + +def modules_to_mkldnn(nodes: List[fx.Node], modules: Dict[str, nn.Module]): + """ + For each node, if it's a module that can be preconverted into MKLDNN, + then we do so and create a mapping to allow us to convert from the MKLDNN + version of the module to the original. + """ + old_modules: Dict[nn.Module, nn.Module] = {} + for node in nodes: + if node.op == 'call_module': + assert isinstance(node.target, str) + cur_module = modules[node.target] + if type(cur_module) in mkldnn_map: + new_module = mkldnn_map[type(cur_module)](cur_module, torch.float) + assert isinstance(new_module, nn.Module) + old_modules[new_module] = copy.deepcopy(cur_module) + replace_node_module(node, modules, new_module) + return old_modules + +def reset_modules(nodes: List[fx.Node], modules: Dict[str, nn.Module], old_modules: Dict[nn.Module, nn.Module]): + """ + Maps each module that's been changed with `modules_to_mkldnn` back to its + original. + """ + for node in nodes: + if node.op == 'call_module': + assert (isinstance(node.target, str)) + cur_module = modules[node.target] + if cur_module in old_modules: + replace_node_module(node, modules, old_modules[cur_module]) + +class MklSubgraph: + def __init__(self, fx_graph: fx.Graph): + self.fx_graph = fx_graph + self.nodes: List[fx.Node] = [] + self.start_nodes: List[fx.Node] = [] + self.end_nodes: List[fx.Node] = [] + +def gen_mkl_autotuner(example_inputs, iters=10, warmup=1): + """ + This generates a heuristic that can be passed into `optimize_for_inference` that + determines whether a subgraph should be run in MKL by running it with the example_inputs. + + Example usage: + heuristic = gen_mkl_autotuner(example_inputs, iters=10) + fast_model = optimization.optimize_for_inference(model, heuristic) + """ + fx_model = None + old_modules = None + + def use_mkl_heuristic(graph: MklSubgraph) -> bool: + nonlocal fx_model, old_modules + input_nodes = graph.start_nodes + if fx_model is None: + fx_model = graph.fx_graph.owning_module + old_modules = graph.fx_graph.old_modules # type: ignore[attr-defined] + ShapeProp(fx_model).propagate(example_inputs) + sample_inputs = [torch.randn(node.shape) for node in input_nodes] # type: ignore[attr-defined] + output_args = cast(List[fx.Node], [node.args[0] for node in graph.end_nodes]) + submodule = extract_subgraph(fx_model, graph.nodes, input_nodes, output_args) + + def benchmark(f): + for _ in range(warmup): + f() + begin = time.time() + for _ in range(iters): + out = f() + return time.time() - begin + + mkl_time = benchmark(lambda: [i.to_dense() for i in submodule(*[i.to_mkldnn() for i in sample_inputs])]) + + reset_modules(submodule.graph.nodes, dict(submodule.named_modules()), old_modules) + no_mkl_time = benchmark(lambda: submodule(*sample_inputs)) + return mkl_time < no_mkl_time + return use_mkl_heuristic + +def use_mkl_length(graph: MklSubgraph) -> bool: + """ + This is a heuristic that can be passed into `optimize_for_inference` that + determines whether a subgraph should be run in MKL by checking if there + are more than 2 nodes in it + """ + return len(graph.nodes) > 2 + +class UnionFind: + def __init__(self, n): + self.parent: List[Optional[int]] = [None] * n + self.size: List[int] = [0] * n + + def make_set(self, v: int): + self.parent[v] = v + self.size[v] = 1 + + def find(self, v: int) -> int: + par = self.parent[v] + if v == par: + return v + assert par is not None + self.parent[v] = self.find(par) + return cast(int, self.parent[v]) + + def join(self, a: int, b: int): + a, b = self.find(a), self.find(b) + if a == b: + return a + if self.size[a] < self.size[b]: + a, b = b, a + self.parent[b] = a + self.size[a] += self.size[b] + +def optimize_for_inference( + model: torch.nn.Module, + pass_config: Optional[Dict[str, Any]] = None, + tracer: Type[fx.Tracer] = fx.Tracer +) -> torch.nn.Module: + """ + Performs a set of optimization passes to optimize a model for the + purposes of inference. Specifically, the passes that are run are: + 1. Conv/BN fusion + 2. Dropout removal + 3. MKL layout optimizations + + The third optimization takes a function `use_mkl_heuristic` that's used + to determine whether a subgraph should be explicitly run in MKL layout. + + Note: As FX does not currently handle aliasing, this pass currently + assumes nothing aliases. If that isn't true, use at your own risk. + """ + default_pass_config = { + "conv_bn_fuse": True, + "remove_dropout": True, + "mkldnn_layout_optimize": {'heuristic': use_mkl_length}, + } + if pass_config is None: + pass_config = {} + default_pass_config.update(pass_config) + + if default_pass_config["conv_bn_fuse"]: + model = fuse(model) + if default_pass_config["remove_dropout"]: + model = remove_dropout(model) + if default_pass_config["mkldnn_layout_optimize"] is False: + return model + if not isinstance(default_pass_config["mkldnn_layout_optimize"], dict): + raise RuntimeError("mkldnn_layout_optimize config is not a dict") + if "heuristic" not in default_pass_config["mkldnn_layout_optimize"]: + raise RuntimeError("Heuristic not found in mkldnn_layout_optimize config") + use_mkl_heuristic = default_pass_config["mkldnn_layout_optimize"]["heuristic"] + + cur_tracer = tracer() + fx_graph = cur_tracer.trace(copy.deepcopy(model)) + fx_model = fx.GraphModule(cur_tracer.root, fx_graph) + modules: Dict[str, nn.Module] = dict(model.named_modules()) + + class MklSupport(Enum): + NO = 1 + YES = 2 + UNKNOWN = 3 + + # Inserts to_mkldnn and to_dense around every node we want to be a MKLDNN node. + # If the op is in `mkldnn_supported` then we always treat it as a MKLDNN node. + # However, if it's in `mkldnn_supported_unknown`, then we only treat it as + # a MKLDNN node if its inputs are MKLDNN nodes. + for node in list(fx_graph.nodes): + supports_mkldnn = MklSupport.NO + if node.op == 'call_module': + cur_module = modules[node.target] + if type(cur_module) in mkldnn_supported: + supports_mkldnn = MklSupport.YES + sample_parameter = next(cur_module.parameters(), None) + if sample_parameter is not None: + assert sample_parameter.dtype == torch.float, "this pass is only for torch.float modules" + assert sample_parameter.device == torch.device('cpu'), "this pass is only for CPU modules" + elif node.op == 'call_function': + if node.target in mkldnn_supported: + supports_mkldnn = MklSupport.YES + elif node.target in mkldnn_supported_unknown: + supports_mkldnn = MklSupport.UNKNOWN + + if supports_mkldnn != MklSupport.NO: + if supports_mkldnn == MklSupport.UNKNOWN: + if not any(arg.target == 'to_dense' for arg in node.args): + continue + with fx_graph.inserting_before(node): + mkldnn_args = fx.map_arg(node.args, lambda n: fx_graph.call_method('to_mkldnn', (n, ))) + + node.args = cast(Tuple[fx.node.Argument], mkldnn_args) + + with fx_graph.inserting_after(node): + dense_x = fx_graph.create_node('call_method', 'to_dense', (node,)) + node.replace_all_uses_with(dense_x) + dense_x.args = (node,) + + # Does pre-conversion of all modules into MKLDNN (when possible) + old_modules = modules_to_mkldnn(list(fx_graph.nodes), modules) + fx_graph.old_modules = old_modules # type: ignore[attr-defined] + + # optimizes all a -> to_dense -> to_mkldnn -> b patterns into a -> b + for node in fx_graph.nodes: + if node.op == 'call_method' and node.target == 'to_dense': + prv_node = node.args[0] + users = list(node.users) + for user in users: + if user.op == 'call_method' and user.target == 'to_mkldnn': + user.replace_all_uses_with(prv_node) + fx_graph.erase_node(user) + if len(node.users) == 0: + fx_graph.erase_node(node) + + + num_nodes = len(fx_graph.nodes) + uf = UnionFind(num_nodes) + + def get_color(n): + if hasattr(n, 'color'): # Current node is part of a MKL subgraph + return uf.find(n.color) + if hasattr(n, 'start_color'): # Current node is input to MKL subgraph + return uf.find(n.start_color) + return None + + + # This code is to find each MKLDNN subgraph. Each MKLDNN subgraph consists + # of input nodes (which are only `to_mkldnn` calls), output nodes + # (`to_dense` calls), and intermediate nodes, which are run entirely on + # MKLDNN layout tensors. + # + # Specifically, this code does a flood fill on a directed acyclic graph + # (DAG), starting from each possible "start node" (i.e: `to_mkldnn` nodes). + # If every node only had one input, this would be sufficient. However, in + # the case that a node has multiple inputs coming from different start + # nodes (i.e. colors), we need to join these 2 colors into 1. That's done + # using a Disjoint Set Union. + for cur_idx, node in enumerate(fx_graph.nodes): + if node.op == 'call_method' and node.target == 'to_mkldnn': + node.start_color = cur_idx + uf.make_set(cur_idx) + elif node.op == 'call_method' and node.target == 'to_dense': + assert get_color(node.args[0]) is not None + node.end_color = get_color(node.args[0]) + else: + cur_colors = [get_color(i) for i in node.all_input_nodes if isinstance(i, fx.Node) if get_color(i) is not None] + + if len(cur_colors) == 0: + continue + assert not any(i is None for i in cur_colors) + cur_colors = sorted(cur_colors) + node.color = cur_colors[0] + for other_color in cur_colors[1:]: + uf.join(cur_colors[0], other_color) + + + mkldnn_graphs: Dict[int, MklSubgraph] = defaultdict(lambda: MklSubgraph(fx_graph)) + for node in fx_graph.nodes: + if hasattr(node, 'color'): + mkldnn_graphs[uf.find(node.color)].nodes.append(node) + if hasattr(node, 'start_color'): + mkldnn_graphs[uf.find(node.start_color)].start_nodes.append(node) + if hasattr(node, 'end_color'): + mkldnn_graphs[uf.find(node.end_color)].end_nodes.append(node) + + + # Now that we have all the subgraphs, we need to decide which MKLDNN + # subgraphs we actually want to keep in MKLDNN. + for graph in mkldnn_graphs.values(): + if not use_mkl_heuristic(graph): + for node in graph.start_nodes + graph.end_nodes: + prv = node.args[0] + node.replace_all_uses_with(prv) + fx_graph.erase_node(node) + reset_modules(graph.nodes, modules, old_modules) + + mkldnn_conversions = 0 + for node in fx_graph.nodes: + if node.target == 'to_mkldnn' or node.target == 'to_dense': + mkldnn_conversions += 1 + + logging.getLogger(__name__).info(f"mkldnn conversions: {mkldnn_conversions}") + fx_graph.lint() + result = fx.GraphModule(model, fx_graph) + return result diff --git a/shared/package-files/77/777030202bd4d8ca5236387668f22c74978664b9438c03401754a86bab8cd0fa/blob b/shared/package-files/77/777030202bd4d8ca5236387668f22c74978664b9438c03401754a86bab8cd0fa/blob new file mode 100644 index 0000000000000000000000000000000000000000..669602e0a880d308cbea22eed2fda74cea225a9f Binary files /dev/null and b/shared/package-files/77/777030202bd4d8ca5236387668f22c74978664b9438c03401754a86bab8cd0fa/blob differ diff --git a/shared/package-files/77/7770488b936d481a8fb21da0c82b1f4f4dcbbd198edaf33f5e0a178a9fc7b8a0/blob b/shared/package-files/77/7770488b936d481a8fb21da0c82b1f4f4dcbbd198edaf33f5e0a178a9fc7b8a0/blob new file mode 100644 index 0000000000000000000000000000000000000000..0d4f9d6ff436de470801f061b4e66a5e58876286 --- /dev/null +++ b/shared/package-files/77/7770488b936d481a8fb21da0c82b1f4f4dcbbd198edaf33f5e0a178a9fc7b8a0/blob @@ -0,0 +1,772 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/compute/exec.h" +#include "arrow/datum.h" +#include "arrow/device_allocation_type_set.h" +#include "arrow/memory_pool.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +// macOS defines PREALLOCATE as a preprocessor macro in the header sys/vnode.h. +// No other BSD seems to do so. The name is used as an identifier in MemAllocation enum. +#if defined(__APPLE__) && defined(PREALLOCATE) +# undef PREALLOCATE +#endif + +namespace arrow { +namespace compute { + +class FunctionOptions; + +/// \brief Base class for opaque kernel-specific state. For example, if there +/// is some kind of initialization required. +struct ARROW_EXPORT KernelState { + virtual ~KernelState() = default; +}; + +/// \brief Context/state for the execution of a particular kernel. +class ARROW_EXPORT KernelContext { + public: + // Can pass optional backreference; not used consistently for the + // moment but will be made so in the future + explicit KernelContext(ExecContext* exec_ctx, const Kernel* kernel = NULLPTR) + : exec_ctx_(exec_ctx), kernel_(kernel) {} + + /// \brief Allocate buffer from the context's memory pool. The contents are + /// not initialized. + Result> Allocate(int64_t nbytes); + + /// \brief Allocate buffer for bitmap from the context's memory pool. Like + /// Allocate, the contents of the buffer are not initialized but the last + /// byte is preemptively zeroed to help avoid ASAN or valgrind issues. + Result> AllocateBitmap(int64_t num_bits); + + /// \brief Assign the active KernelState to be utilized for each stage of + /// kernel execution. Ownership and memory lifetime of the KernelState must + /// be minded separately. + void SetState(KernelState* state) { state_ = state; } + + // Set kernel that is being invoked since some kernel + // implementations will examine the kernel state. + void SetKernel(const Kernel* kernel) { kernel_ = kernel; } + + KernelState* state() { return state_; } + + /// \brief Configuration related to function execution that is to be shared + /// across multiple kernels. + ExecContext* exec_context() { return exec_ctx_; } + + /// \brief The memory pool to use for allocations. For now, it uses the + /// MemoryPool contained in the ExecContext used to create the KernelContext. + MemoryPool* memory_pool() { return exec_ctx_->memory_pool(); } + + const Kernel* kernel() const { return kernel_; } + + private: + ExecContext* exec_ctx_; + KernelState* state_ = NULLPTR; + const Kernel* kernel_ = NULLPTR; +}; + +/// \brief An type-checking interface to permit customizable validation rules +/// for use with InputType and KernelSignature. This is for scenarios where the +/// acceptance is not an exact type instance, such as a TIMESTAMP type for a +/// specific TimeUnit, but permitting any time zone. +struct ARROW_EXPORT TypeMatcher { + virtual ~TypeMatcher() = default; + + /// \brief Return true if this matcher accepts the data type. + virtual bool Matches(const DataType& type) const = 0; + + /// \brief A human-interpretable string representation of what the type + /// matcher checks for, usable when printing KernelSignature or formatting + /// error messages. + virtual std::string ToString() const = 0; + + /// \brief Return true if this TypeMatcher contains the same matching rule as + /// the other. Currently depends on RTTI. + virtual bool Equals(const TypeMatcher& other) const = 0; +}; + +namespace match { + +/// \brief Match any DataType instance having the same DataType::id. +ARROW_EXPORT std::shared_ptr SameTypeId(Type::type type_id); + +/// \brief Match any TimestampType instance having the same unit, but the time +/// zones can be different. +ARROW_EXPORT std::shared_ptr TimestampTypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr Time32TypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr Time64TypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr DurationTypeUnit(TimeUnit::type unit); + +// \brief Match any integer type +ARROW_EXPORT std::shared_ptr Integer(); + +// Match types using 32-bit varbinary representation +ARROW_EXPORT std::shared_ptr BinaryLike(); + +// Match types using 64-bit varbinary representation +ARROW_EXPORT std::shared_ptr LargeBinaryLike(); + +// Match any fixed binary type +ARROW_EXPORT std::shared_ptr FixedSizeBinaryLike(); + +// \brief Match any primitive type (boolean or any type representable as a C +// Type) +ARROW_EXPORT std::shared_ptr Primitive(); + +// \brief Match any integer type that can be used as run-end in run-end encoded +// arrays +ARROW_EXPORT std::shared_ptr RunEndInteger(); + +/// \brief Match run-end encoded types that use any valid run-end type and +/// encode specific value types +/// +/// @param[in] value_type_matcher a matcher that is applied to the values field +ARROW_EXPORT std::shared_ptr RunEndEncoded( + std::shared_ptr value_type_matcher); + +/// \brief Match run-end encoded types that use any valid run-end type and +/// encode specific value types +/// +/// @param[in] value_type_id a type id that the type of the values field should match +ARROW_EXPORT std::shared_ptr RunEndEncoded(Type::type value_type_id); + +/// \brief Match run-end encoded types that encode specific run-end and value types +/// +/// @param[in] run_end_type_matcher a matcher that is applied to the run_ends field +/// @param[in] value_type_matcher a matcher that is applied to the values field +ARROW_EXPORT std::shared_ptr RunEndEncoded( + std::shared_ptr run_end_type_matcher, + std::shared_ptr value_type_matcher); + +} // namespace match + +/// \brief An object used for type-checking arguments to be passed to a kernel +/// and stored in a KernelSignature. The type-checking rule can be supplied +/// either with an exact DataType instance or a custom TypeMatcher. +class ARROW_EXPORT InputType { + public: + /// \brief The kind of type-checking rule that the InputType contains. + enum Kind { + /// \brief Accept any value type. + ANY_TYPE, + + /// \brief A fixed arrow::DataType and will only exact match having this + /// exact type (e.g. same TimestampType unit, same decimal scale and + /// precision, or same nested child types). + EXACT_TYPE, + + /// \brief Uses a TypeMatcher implementation to check the type. + USE_TYPE_MATCHER + }; + + /// \brief Accept any value type + InputType() : kind_(ANY_TYPE) {} + + /// \brief Accept an exact value type. + InputType(std::shared_ptr type) // NOLINT implicit construction + : kind_(EXACT_TYPE), type_(std::move(type)) {} + + /// \brief Use the passed TypeMatcher to type check. + InputType(std::shared_ptr type_matcher) // NOLINT implicit construction + : kind_(USE_TYPE_MATCHER), type_matcher_(std::move(type_matcher)) {} + + /// \brief Match any type with the given Type::type. Uses a TypeMatcher for + /// its implementation. + InputType(Type::type type_id) // NOLINT implicit construction + : InputType(match::SameTypeId(type_id)) {} + + InputType(const InputType& other) { CopyInto(other); } + + void operator=(const InputType& other) { CopyInto(other); } + + InputType(InputType&& other) { MoveInto(std::forward(other)); } + + void operator=(InputType&& other) { MoveInto(std::forward(other)); } + + // \brief Match any input (array, scalar of any type) + static InputType Any() { return InputType(); } + + /// \brief Return true if this input type matches the same type cases as the + /// other. + bool Equals(const InputType& other) const; + + bool operator==(const InputType& other) const { return this->Equals(other); } + + bool operator!=(const InputType& other) const { return !(*this == other); } + + /// \brief Return hash code. + size_t Hash() const; + + /// \brief Render a human-readable string representation. + std::string ToString() const; + + /// \brief Return true if the Datum matches this argument kind in + /// type (and only allows scalar or array-like Datums). + bool Matches(const Datum& value) const; + + /// \brief Return true if the type matches this InputType + bool Matches(const DataType& type) const; + + /// \brief The type matching rule that this InputType uses. + Kind kind() const { return kind_; } + + /// \brief For InputType::EXACT_TYPE kind, the exact type that this InputType + /// must match. Otherwise this function should not be used and will assert in + /// debug builds. + const std::shared_ptr& type() const; + + /// \brief For InputType::USE_TYPE_MATCHER, the TypeMatcher to be used for + /// checking the type of a value. Otherwise this function should not be used + /// and will assert in debug builds. + const TypeMatcher& type_matcher() const; + + private: + void CopyInto(const InputType& other) { + this->kind_ = other.kind_; + this->type_ = other.type_; + this->type_matcher_ = other.type_matcher_; + } + + void MoveInto(InputType&& other) { + this->kind_ = other.kind_; + this->type_ = std::move(other.type_); + this->type_matcher_ = std::move(other.type_matcher_); + } + + Kind kind_; + + // For EXACT_TYPE Kind + std::shared_ptr type_; + + // For USE_TYPE_MATCHER Kind + std::shared_ptr type_matcher_; +}; + +/// \brief Container to capture both exact and input-dependent output types. +class ARROW_EXPORT OutputType { + public: + /// \brief An enum indicating whether the value type is an invariant fixed + /// value or one that's computed by a kernel-defined resolver function. + enum ResolveKind { FIXED, COMPUTED }; + + /// Type resolution function. Given input types, return output type. This + /// function MAY may use the kernel state to decide the output type based on + /// the FunctionOptions. + /// + /// This function SHOULD _not_ be used to check for arity, that is to be + /// performed one or more layers above. + using Resolver = + std::function(KernelContext*, const std::vector&)>; + + /// \brief Output an exact type + OutputType(std::shared_ptr type) // NOLINT implicit construction + : kind_(FIXED), type_(std::move(type)) {} + + /// \brief Output a computed type depending on actual input types + template + OutputType(Fn resolver) // NOLINT implicit construction + : kind_(COMPUTED), resolver_(std::move(resolver)) {} + + OutputType(const OutputType& other) { + this->kind_ = other.kind_; + this->type_ = other.type_; + this->resolver_ = other.resolver_; + } + + OutputType(OutputType&& other) { + this->kind_ = other.kind_; + this->type_ = std::move(other.type_); + this->resolver_ = other.resolver_; + } + + OutputType& operator=(const OutputType&) = default; + OutputType& operator=(OutputType&&) = default; + + /// \brief Return the type of the expected output value of the kernel given + /// the input argument types. The resolver may make use of state information + /// kept in the KernelContext. + Result Resolve(KernelContext* ctx, + const std::vector& args) const; + + /// \brief The exact output value type for the FIXED kind. + const std::shared_ptr& type() const; + + /// \brief For use with COMPUTED resolution strategy. It may be more + /// convenient to invoke this with OutputType::Resolve returned from this + /// method. + const Resolver& resolver() const; + + /// \brief Render a human-readable string representation. + std::string ToString() const; + + /// \brief Return the kind of type resolution of this output type, whether + /// fixed/invariant or computed by a resolver. + ResolveKind kind() const { return kind_; } + + private: + ResolveKind kind_; + + // For FIXED resolution + std::shared_ptr type_; + + // For COMPUTED resolution + Resolver resolver_ = NULLPTR; +}; + +/// \brief Additional constraints to apply to the input types of a kernel when matching a +/// specific kernel signature. +class ARROW_EXPORT MatchConstraint { + public: + virtual ~MatchConstraint() = default; + + /// \brief Return true if the input types satisfy the constraint. + virtual bool Matches(const std::vector& types) const = 0; + + /// \brief Convenience function to create a MatchConstraint from a match function. + static std::shared_ptr Make( + std::function&)> matches); +}; + +/// \brief Constraint that all input types are decimal types and have the same scale. +ARROW_EXPORT std::shared_ptr DecimalsHaveSameScale(); + +/// \brief Holds the input types, optional match constraint and output type of the kernel. +/// +/// VarArgs functions with minimum N arguments should pass up to N input types to be +/// used to validate the input types of a function invocation. The first N-1 types +/// will be matched against the first N-1 arguments, and the last type will be +/// matched against the remaining arguments. +class ARROW_EXPORT KernelSignature { + public: + KernelSignature(std::vector in_types, OutputType out_type, + bool is_varargs = false, + std::shared_ptr constraint = NULLPTR); + + /// \brief Convenience ctor since make_shared can be awkward + static std::shared_ptr Make( + std::vector in_types, OutputType out_type, bool is_varargs = false, + std::shared_ptr constraint = NULLPTR); + + /// \brief Return true if the signature is compatible with the list of input + /// value descriptors and satisfies the match constraint, if any. + bool MatchesInputs(const std::vector& types) const; + + /// \brief Returns true if the input types of each signature are + /// equal. Well-formed functions should have a deterministic output type + /// given input types, but currently it is the responsibility of the + /// developer to ensure this. + bool Equals(const KernelSignature& other) const; + + bool operator==(const KernelSignature& other) const { return this->Equals(other); } + + bool operator!=(const KernelSignature& other) const { return !(*this == other); } + + /// \brief Compute a hash code for the signature + size_t Hash() const; + + /// \brief The input types for the kernel. For VarArgs functions, this should + /// generally contain a single validator to use for validating all of the + /// function arguments. + const std::vector& in_types() const { return in_types_; } + + /// \brief The output type for the kernel. Use Resolve to return the + /// exact output given input argument types, since many kernels' + /// output types depend on their input types (or their type + /// metadata). + const OutputType& out_type() const { return out_type_; } + + /// \brief Render a human-readable string representation + std::string ToString() const; + + bool is_varargs() const { return is_varargs_; } + + private: + std::vector in_types_; + OutputType out_type_; + bool is_varargs_; + std::shared_ptr constraint_; + + // For caching the hash code after it's computed the first time + mutable uint64_t hash_code_; +}; + +/// \brief A function may contain multiple variants of a kernel for a given +/// type combination for different SIMD levels. Based on the active system's +/// CPU info or the user's preferences, we can elect to use one over the other. +struct SimdLevel { + enum type { NONE = 0, SSE4_2, AVX, AVX2, AVX512, NEON, MAX }; +}; + +/// \brief The strategy to use for propagating or otherwise populating the +/// validity bitmap of a kernel output. +struct NullHandling { + enum type { + /// Compute the output validity bitmap by intersecting the validity bitmaps + /// of the arguments using bitwise-and operations. This means that values + /// in the output are valid/non-null only if the corresponding values in + /// all input arguments were valid/non-null. Kernel generally need not + /// touch the bitmap thereafter, but a kernel's exec function is permitted + /// to alter the bitmap after the null intersection is computed if it needs + /// to. + INTERSECTION, + + /// Kernel expects a pre-allocated buffer to write the result bitmap + /// into. The preallocated memory is not zeroed (except for the last byte), + /// so the kernel should ensure to completely populate the bitmap. + COMPUTED_PREALLOCATE, + + /// Kernel allocates and sets the validity bitmap of the output. + COMPUTED_NO_PREALLOCATE, + + /// Kernel output is never null and a validity bitmap does not need to be + /// allocated. + OUTPUT_NOT_NULL + }; +}; + +/// \brief The preference for memory preallocation of fixed-width type outputs +/// in kernel execution. +struct MemAllocation { + enum type { + // For data types that support pre-allocation (i.e. fixed-width), the + // kernel expects to be provided a pre-allocated data buffer to write + // into. Non-fixed-width types must always allocate their own data + // buffers. The allocation made for the same length as the execution batch, + // so vector kernels yielding differently sized output should not use this. + // + // It is valid for the data to not be preallocated but the validity bitmap + // is (or is computed using the intersection/bitwise-and method). + // + // For variable-size output types like BinaryType or StringType, or for + // nested types, this option has no effect. + PREALLOCATE, + + // The kernel is responsible for allocating its own data buffer for + // fixed-width type outputs. + NO_PREALLOCATE + }; +}; + +struct Kernel; + +/// \brief Arguments to pass to an KernelInit function. A struct is used to help +/// avoid API breakage should the arguments passed need to be expanded. +struct KernelInitArgs { + /// \brief A pointer to the kernel being initialized. The init function may + /// depend on the kernel's KernelSignature or other data contained there. + const Kernel* kernel; + + /// \brief The types of the input arguments that the kernel is + /// about to be executed against. + const std::vector& inputs; + + /// \brief Opaque options specific to this kernel. May be nullptr for functions + /// that do not require options. + const FunctionOptions* options; +}; + +/// \brief Common initializer function for all kernel types. +using KernelInit = std::function>( + KernelContext*, const KernelInitArgs&)>; + +/// \brief Base type for kernels. Contains the function signature and +/// optionally the state initialization function, along with some common +/// attributes +struct ARROW_EXPORT Kernel { + Kernel() = default; + + Kernel(std::shared_ptr sig, KernelInit init) + : signature(std::move(sig)), init(std::move(init)) {} + + Kernel(std::vector in_types, OutputType out_type, KernelInit init) + : Kernel(KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init)) {} + + /// \brief The "signature" of the kernel containing the InputType input + /// argument validators and OutputType output type resolver. + std::shared_ptr signature; + + /// \brief Create a new KernelState for invocations of this kernel, e.g. to + /// set up any options or state relevant for execution. + KernelInit init; + + /// \brief Create a vector of new KernelState for invocations of this kernel. + static Status InitAll(KernelContext*, const KernelInitArgs&, + std::vector>*); + + /// \brief Indicates whether execution can benefit from parallelization + /// (splitting large chunks into smaller chunks and using multiple + /// threads). Some kernels may not support parallel execution at + /// all. Synchronization and concurrency-related issues are currently the + /// responsibility of the Kernel's implementation. + bool parallelizable = true; + + /// \brief Indicates the level of SIMD instruction support in the host CPU is + /// required to use the function. The intention is for functions to be able to + /// contain multiple kernels with the same signature but different levels of SIMD, + /// so that the most optimized kernel supported on a host's processor can be chosen. + SimdLevel::type simd_level = SimdLevel::NONE; + + // Additional kernel-specific data + std::shared_ptr data; +}; + +/// \brief The scalar kernel execution API that must be implemented for SCALAR +/// kernel types. This includes both stateless and stateful kernels. Kernels +/// depending on some execution state access that state via subclasses of +/// KernelState set on the KernelContext object. Implementations should +/// endeavor to write into pre-allocated memory if they are able, though for +/// some kernels (e.g. in cases when a builder like StringBuilder) must be +/// employed this may not be possible. +using ArrayKernelExec = Status (*)(KernelContext*, const ExecSpan&, ExecResult*); + +/// \brief Kernel data structure for implementations of ScalarFunction. In +/// addition to the members found in Kernel, contains the null handling +/// and memory pre-allocation preferences. +struct ARROW_EXPORT ScalarKernel : public Kernel { + ScalarKernel() = default; + + ScalarKernel(std::shared_ptr sig, ArrayKernelExec exec, + KernelInit init = NULLPTR) + : Kernel(std::move(sig), init), exec(exec) {} + + ScalarKernel(std::vector in_types, OutputType out_type, ArrayKernelExec exec, + KernelInit init = NULLPTR) + : Kernel(std::move(in_types), std::move(out_type), std::move(init)), exec(exec) {} + + /// \brief Perform a single invocation of this kernel. Depending on the + /// implementation, it may only write into preallocated memory, while in some + /// cases it will allocate its own memory. Any required state is managed + /// through the KernelContext. + ArrayKernelExec exec; + + /// \brief Writing execution results into larger contiguous allocations + /// requires that the kernel be able to write into sliced output ArrayData*, + /// including sliced output validity bitmaps. Some kernel implementations may + /// not be able to do this, so setting this to false disables this + /// functionality. + bool can_write_into_slices = true; + + // For scalar functions preallocated data and intersecting arg validity + // bitmaps is a reasonable default + NullHandling::type null_handling = NullHandling::INTERSECTION; + MemAllocation::type mem_allocation = MemAllocation::PREALLOCATE; +}; + +// ---------------------------------------------------------------------- +// VectorKernel (for VectorFunction) + +/// \brief Kernel data structure for implementations of VectorFunction. In +/// contains an optional finalizer function, the null handling and memory +/// pre-allocation preferences (which have different defaults from +/// ScalarKernel), and some other execution-related options. +struct ARROW_EXPORT VectorKernel : public Kernel { + /// \brief See VectorKernel::finalize member for usage + using FinalizeFunc = std::function*)>; + + /// \brief Function for executing a stateful VectorKernel against a + /// ChunkedArray input. Does not need to be defined for all VectorKernels + using ChunkedExec = Status (*)(KernelContext*, const ExecBatch&, Datum* out); + + VectorKernel() = default; + + VectorKernel(std::vector in_types, OutputType out_type, ArrayKernelExec exec, + KernelInit init = NULLPTR, FinalizeFunc finalize = NULLPTR) + : Kernel(std::move(in_types), std::move(out_type), std::move(init)), + exec(exec), + finalize(std::move(finalize)) {} + + VectorKernel(std::shared_ptr sig, ArrayKernelExec exec, + KernelInit init = NULLPTR, FinalizeFunc finalize = NULLPTR) + : Kernel(std::move(sig), std::move(init)), + exec(exec), + finalize(std::move(finalize)) {} + + /// \brief Perform a single invocation of this kernel. Any required state is + /// managed through the KernelContext. + ArrayKernelExec exec; + + /// \brief Execute the kernel on a ChunkedArray. Does not need to be defined + ChunkedExec exec_chunked = NULLPTR; + + /// \brief For VectorKernel, convert intermediate results into finalized + /// results. Mutates input argument. Some kernels may accumulate state + /// (example: hashing-related functions) through processing chunked inputs, and + /// then need to attach some accumulated state to each of the outputs of + /// processing each chunk of data. + FinalizeFunc finalize; + + /// Since vector kernels generally are implemented rather differently from + /// scalar/elementwise kernels (and they may not even yield arrays of the same + /// size), so we make the developer opt-in to any memory preallocation rather + /// than having to turn it off. + NullHandling::type null_handling = NullHandling::COMPUTED_NO_PREALLOCATE; + MemAllocation::type mem_allocation = MemAllocation::NO_PREALLOCATE; + + /// \brief Writing execution results into larger contiguous allocations + /// requires that the kernel be able to write into sliced output ArrayData*, + /// including sliced output validity bitmaps. Some kernel implementations may + /// not be able to do this, so setting this to false disables this + /// functionality. + bool can_write_into_slices = true; + + /// Some vector kernels can do chunkwise execution using ExecSpanIterator, + /// in some cases accumulating some state. Other kernels (like Take) need to + /// be passed whole arrays and don't work on ChunkedArray inputs + bool can_execute_chunkwise = true; + + /// Some kernels (like unique and value_counts) yield non-chunked output from + /// chunked-array inputs. This option controls how the results are boxed when + /// returned from ExecVectorFunction + /// + /// true -> ChunkedArray + /// false -> Array + bool output_chunked = true; +}; + +// ---------------------------------------------------------------------- +// ScalarAggregateKernel (for ScalarAggregateFunction) + +using ScalarAggregateConsume = Status (*)(KernelContext*, const ExecSpan&); +using ScalarAggregateMerge = Status (*)(KernelContext*, KernelState&&, KernelState*); +// Finalize returns Datum to permit multiple return values +using ScalarAggregateFinalize = Status (*)(KernelContext*, Datum*); + +/// \brief Kernel data structure for implementations of +/// ScalarAggregateFunction. The four necessary components of an aggregation +/// kernel are the init, consume, merge, and finalize functions. +/// +/// * init: creates a new KernelState for a kernel. +/// * consume: processes an ExecSpan and updates the KernelState found in the +/// KernelContext. +/// * merge: combines one KernelState with another. +/// * finalize: produces the end result of the aggregation using the +/// KernelState in the KernelContext. +struct ARROW_EXPORT ScalarAggregateKernel : public Kernel { + ScalarAggregateKernel(std::shared_ptr sig, KernelInit init, + ScalarAggregateConsume consume, ScalarAggregateMerge merge, + ScalarAggregateFinalize finalize, const bool ordered) + : Kernel(std::move(sig), std::move(init)), + consume(consume), + merge(merge), + finalize(finalize), + ordered(ordered) {} + + ScalarAggregateKernel(std::vector in_types, OutputType out_type, + KernelInit init, ScalarAggregateConsume consume, + ScalarAggregateMerge merge, ScalarAggregateFinalize finalize, + const bool ordered) + : ScalarAggregateKernel( + KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init), consume, merge, finalize, ordered) {} + + /// \brief Merge a vector of KernelStates into a single KernelState. + /// The merged state will be returned and will be set on the KernelContext. + static Result> MergeAll( + const ScalarAggregateKernel* kernel, KernelContext* ctx, + std::vector> states); + + ScalarAggregateConsume consume; + ScalarAggregateMerge merge; + ScalarAggregateFinalize finalize; + /// \brief Whether this kernel requires ordering + /// Some aggregations, such as, "first", requires some kind of input order. The + /// order can be implicit, e.g., the order of the input data, or explicit, e.g. + /// the ordering specified with a window aggregation. + /// The caller of the aggregate kernel is responsible for passing data in some + /// defined order to the kernel. The flag here is a way for the kernel to tell + /// the caller that data passed to the kernel must be defined in some order. + bool ordered = false; +}; + +// ---------------------------------------------------------------------- +// HashAggregateKernel (for HashAggregateFunction) + +using HashAggregateResize = Status (*)(KernelContext*, int64_t); +using HashAggregateConsume = Status (*)(KernelContext*, const ExecSpan&); +using HashAggregateMerge = Status (*)(KernelContext*, KernelState&&, const ArrayData&); + +// Finalize returns Datum to permit multiple return values +using HashAggregateFinalize = Status (*)(KernelContext*, Datum*); + +/// \brief Kernel data structure for implementations of +/// HashAggregateFunction. The four necessary components of an aggregation +/// kernel are the init, consume, merge, and finalize functions. +/// +/// * init: creates a new KernelState for a kernel. +/// * resize: ensure that the KernelState can accommodate the specified number of groups. +/// * consume: processes an ExecSpan (which includes the argument as well +/// as an array of group identifiers) and updates the KernelState found in the +/// KernelContext. +/// * merge: combines one KernelState with another. +/// * finalize: produces the end result of the aggregation using the +/// KernelState in the KernelContext. +struct ARROW_EXPORT HashAggregateKernel : public Kernel { + HashAggregateKernel() = default; + + HashAggregateKernel(std::shared_ptr sig, KernelInit init, + HashAggregateResize resize, HashAggregateConsume consume, + HashAggregateMerge merge, HashAggregateFinalize finalize, + const bool ordered) + : Kernel(std::move(sig), std::move(init)), + resize(resize), + consume(consume), + merge(merge), + finalize(finalize), + ordered(ordered) {} + + HashAggregateKernel(std::vector in_types, OutputType out_type, + KernelInit init, HashAggregateConsume consume, + HashAggregateResize resize, HashAggregateMerge merge, + HashAggregateFinalize finalize, const bool ordered) + : HashAggregateKernel( + KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init), resize, consume, merge, finalize, ordered) {} + + HashAggregateResize resize; + HashAggregateConsume consume; + HashAggregateMerge merge; + HashAggregateFinalize finalize; + /// @brief whether the summarizer requires ordering + /// This is similar to ScalarAggregateKernel. See ScalarAggregateKernel + /// for detailed doc of this variable. + bool ordered = false; +}; + +} // namespace compute +} // namespace arrow diff --git a/shared/package-files/77/777252ed9df30423461e4a3ba8d49e1390812ae3e3f0a62d6aed6a123fad924b/blob b/shared/package-files/77/777252ed9df30423461e4a3ba8d49e1390812ae3e3f0a62d6aed6a123fad924b/blob new file mode 100644 index 0000000000000000000000000000000000000000..c3465e6b605aa3da6028e32fc513e32e25c052c8 --- /dev/null +++ b/shared/package-files/77/777252ed9df30423461e4a3ba8d49e1390812ae3e3f0a62d6aed6a123fad924b/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_sparse_log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor +inline at::Tensor _sparse_log_softmax_backward_data(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, const at::Tensor & self) { + return at::_ops::_sparse_log_softmax_backward_data::call(grad_output, output, dim, self); +} + +// aten::_sparse_log_softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _sparse_log_softmax_backward_data_out(at::Tensor & out, const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, const at::Tensor & self) { + return at::_ops::_sparse_log_softmax_backward_data_out::call(grad_output, output, dim, self, out); +} +// aten::_sparse_log_softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _sparse_log_softmax_backward_data_outf(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, const at::Tensor & self, at::Tensor & out) { + return at::_ops::_sparse_log_softmax_backward_data_out::call(grad_output, output, dim, self, out); +} + +} diff --git a/shared/package-files/77/7772bac2cccf8682045c3290aa09c79301e197edf4555e0dffbc28f197772d7e/blob b/shared/package-files/77/7772bac2cccf8682045c3290aa09c79301e197edf4555e0dffbc28f197772d7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..509c03ef71d81e871fe6ce9c8383382c124222e8 --- /dev/null +++ b/shared/package-files/77/7772bac2cccf8682045c3290aa09c79301e197edf4555e0dffbc28f197772d7e/blob @@ -0,0 +1,359 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +import enum +import hashlib +import heapq +import sys +from collections import OrderedDict, abc +from functools import lru_cache +from typing import TYPE_CHECKING, List, Optional, Sequence, Tuple, Type, TypeVar, Union + +from hypothesis.errors import InvalidArgument +from hypothesis.internal.compat import int_from_bytes +from hypothesis.internal.floats import next_up + +if TYPE_CHECKING: + from hypothesis.internal.conjecture.data import ConjectureData + + +LABEL_MASK = 2**64 - 1 + + +def calc_label_from_name(name: str) -> int: + hashed = hashlib.sha384(name.encode()).digest() + return int_from_bytes(hashed[:8]) + + +def calc_label_from_cls(cls: type) -> int: + return calc_label_from_name(cls.__qualname__) + + +def combine_labels(*labels: int) -> int: + label = 0 + for l in labels: + label = (label << 1) & LABEL_MASK + label ^= l + return label + + +SAMPLE_IN_SAMPLER_LABEL = calc_label_from_name("a sample() in Sampler") +ONE_FROM_MANY_LABEL = calc_label_from_name("one more from many()") + + +T = TypeVar("T") + + +def check_sample( + values: Union[Type[enum.Enum], Sequence[T]], strategy_name: str +) -> Sequence[T]: + if "numpy" in sys.modules and isinstance(values, sys.modules["numpy"].ndarray): + if values.ndim != 1: + raise InvalidArgument( + "Only one-dimensional arrays are supported for sampling, " + f"and the given value has {values.ndim} dimensions (shape " + f"{values.shape}). This array would give samples of array slices " + "instead of elements! Use np.ravel(values) to convert " + "to a one-dimensional array, or tuple(values) if you " + "want to sample slices." + ) + elif not isinstance(values, (OrderedDict, abc.Sequence, enum.EnumMeta)): + raise InvalidArgument( + f"Cannot sample from {values!r}, not an ordered collection. " + f"Hypothesis goes to some length to ensure that the {strategy_name} " + "strategy has stable results between runs. To replay a saved " + "example, the sampled values must have the same iteration order " + "on every run - ruling out sets, dicts, etc due to hash " + "randomization. Most cases can simply use `sorted(values)`, but " + "mixed types or special values such as math.nan require careful " + "handling - and note that when simplifying an example, " + "Hypothesis treats earlier values as simpler." + ) + if isinstance(values, range): + return values + return tuple(values) + + +class Sampler: + """Sampler based on Vose's algorithm for the alias method. See + http://www.keithschwarz.com/darts-dice-coins/ for a good explanation. + + The general idea is that we store a table of triples (base, alternate, p). + base. We then pick a triple uniformly at random, and choose its alternate + value with probability p and else choose its base value. The triples are + chosen so that the resulting mixture has the right distribution. + + We maintain the following invariants to try to produce good shrinks: + + 1. The table is in lexicographic (base, alternate) order, so that choosing + an earlier value in the list always lowers (or at least leaves + unchanged) the value. + 2. base[i] < alternate[i], so that shrinking the draw always results in + shrinking the chosen element. + """ + + table: List[Tuple[int, int, float]] # (base_idx, alt_idx, alt_chance) + + def __init__(self, weights: Sequence[float], *, observe: bool = True): + self.observe = observe + + n = len(weights) + table: "list[list[int | float | None]]" = [[i, None, None] for i in range(n)] + total = sum(weights) + num_type = type(total) + + zero = num_type(0) # type: ignore + one = num_type(1) # type: ignore + + small: "List[int]" = [] + large: "List[int]" = [] + + probabilities = [w / total for w in weights] + scaled_probabilities: "List[float]" = [] + + for i, alternate_chance in enumerate(probabilities): + scaled = alternate_chance * n + scaled_probabilities.append(scaled) + if scaled == 1: + table[i][2] = zero + elif scaled < 1: + small.append(i) + else: + large.append(i) + heapq.heapify(small) + heapq.heapify(large) + + while small and large: + lo = heapq.heappop(small) + hi = heapq.heappop(large) + + assert lo != hi + assert scaled_probabilities[hi] > one + assert table[lo][1] is None + table[lo][1] = hi + table[lo][2] = one - scaled_probabilities[lo] + scaled_probabilities[hi] = ( + scaled_probabilities[hi] + scaled_probabilities[lo] + ) - one + + if scaled_probabilities[hi] < 1: + heapq.heappush(small, hi) + elif scaled_probabilities[hi] == 1: + table[hi][2] = zero + else: + heapq.heappush(large, hi) + while large: + table[large.pop()][2] = zero + while small: + table[small.pop()][2] = zero + + self.table: "List[Tuple[int, int, float]]" = [] + for base, alternate, alternate_chance in table: # type: ignore + assert isinstance(base, int) + assert isinstance(alternate, int) or alternate is None + if alternate is None: + self.table.append((base, base, alternate_chance)) + elif alternate < base: + self.table.append((alternate, base, one - alternate_chance)) + else: + self.table.append((base, alternate, alternate_chance)) + self.table.sort() + + def sample( + self, + data: "ConjectureData", + *, + forced: Optional[int] = None, + fake_forced: bool = False, + ) -> int: + data.start_example(SAMPLE_IN_SAMPLER_LABEL) + forced_choice = ( # pragma: no branch # https://github.com/nedbat/coveragepy/issues/1617 + None + if forced is None + else next( + (base, alternate, alternate_chance) + for (base, alternate, alternate_chance) in self.table + if forced == base or (forced == alternate and alternate_chance > 0) + ) + ) + base, alternate, alternate_chance = data.choice( + self.table, + forced=forced_choice, + fake_forced=fake_forced, + observe=self.observe, + ) + forced_use_alternate = None + if forced is not None: + # we maintain this invariant when picking forced_choice above. + # This song and dance about alternate_chance > 0 is to avoid forcing + # e.g. draw_boolean(p=0, forced=True), which is an error. + forced_use_alternate = forced == alternate and alternate_chance > 0 + assert forced == base or forced_use_alternate + + use_alternate = data.draw_boolean( + alternate_chance, + forced=forced_use_alternate, + fake_forced=fake_forced, + observe=self.observe, + ) + data.stop_example() + if use_alternate: + assert forced is None or alternate == forced, (forced, alternate) + return alternate + else: + assert forced is None or base == forced, (forced, base) + return base + + +INT_SIZES = (8, 16, 32, 64, 128) +INT_SIZES_SAMPLER = Sampler((4.0, 8.0, 1.0, 1.0, 0.5), observe=False) + + +class many: + """Utility class for collections. Bundles up the logic we use for "should I + keep drawing more values?" and handles starting and stopping examples in + the right place. + + Intended usage is something like: + + elements = many(data, ...) + while elements.more(): + add_stuff_to_result() + """ + + def __init__( + self, + data: "ConjectureData", + min_size: int, + max_size: Union[int, float], + average_size: Union[int, float], + *, + forced: Optional[int] = None, + fake_forced: bool = False, + observe: bool = True, + ) -> None: + assert 0 <= min_size <= average_size <= max_size + assert forced is None or min_size <= forced <= max_size + self.min_size = min_size + self.max_size = max_size + self.data = data + self.forced_size = forced + self.fake_forced = fake_forced + self.p_continue = _calc_p_continue(average_size - min_size, max_size - min_size) + self.count = 0 + self.rejections = 0 + self.drawn = False + self.force_stop = False + self.rejected = False + self.observe = observe + + def more(self) -> bool: + """Should I draw another element to add to the collection?""" + if self.drawn: + self.data.stop_example() + + self.drawn = True + self.rejected = False + + self.data.start_example(ONE_FROM_MANY_LABEL) + if self.min_size == self.max_size: + # if we have to hit an exact size, draw unconditionally until that + # point, and no further. + should_continue = self.count < self.min_size + else: + forced_result = None + if self.force_stop: + # if our size is forced, we can't reject in a way that would + # cause us to differ from the forced size. + assert self.forced_size is None or self.count == self.forced_size + forced_result = False + elif self.count < self.min_size: + forced_result = True + elif self.count >= self.max_size: + forced_result = False + elif self.forced_size is not None: + forced_result = self.count < self.forced_size + should_continue = self.data.draw_boolean( + self.p_continue, + forced=forced_result, + fake_forced=self.fake_forced, + observe=self.observe, + ) + + if should_continue: + self.count += 1 + return True + else: + self.data.stop_example() + return False + + def reject(self, why: Optional[str] = None) -> None: + """Reject the last example (i.e. don't count it towards our budget of + elements because it's not going to go in the final collection).""" + assert self.count > 0 + self.count -= 1 + self.rejections += 1 + self.rejected = True + # We set a minimum number of rejections before we give up to avoid + # failing too fast when we reject the first draw. + if self.rejections > max(3, 2 * self.count): + if self.count < self.min_size: + self.data.mark_invalid(why) + else: + self.force_stop = True + + +SMALLEST_POSITIVE_FLOAT: float = next_up(0.0) or sys.float_info.min + + +@lru_cache +def _calc_p_continue(desired_avg: float, max_size: int) -> float: + """Return the p_continue which will generate the desired average size.""" + assert desired_avg <= max_size, (desired_avg, max_size) + if desired_avg == max_size: + return 1.0 + p_continue = 1 - 1.0 / (1 + desired_avg) + if p_continue == 0 or max_size == float("inf"): + assert 0 <= p_continue < 1, p_continue + return p_continue + assert 0 < p_continue < 1, p_continue + # For small max_size, the infinite-series p_continue is a poor approximation, + # and while we can't solve the polynomial a few rounds of iteration quickly + # gets us a good approximate solution in almost all cases (sometimes exact!). + while _p_continue_to_avg(p_continue, max_size) > desired_avg: + # This is impossible over the reals, but *can* happen with floats. + p_continue -= 0.0001 + # If we've reached zero or gone negative, we want to break out of this loop, + # and do so even if we're on a system with the unsafe denormals-are-zero flag. + # We make that an explicit error in st.floats(), but here we'd prefer to + # just get somewhat worse precision on collection lengths. + if p_continue < SMALLEST_POSITIVE_FLOAT: + p_continue = SMALLEST_POSITIVE_FLOAT + break + # Let's binary-search our way to a better estimate! We tried fancier options + # like gradient descent, but this is numerically stable and works better. + hi = 1.0 + while desired_avg - _p_continue_to_avg(p_continue, max_size) > 0.01: + assert 0 < p_continue < hi, (p_continue, hi) + mid = (p_continue + hi) / 2 + if _p_continue_to_avg(mid, max_size) <= desired_avg: + p_continue = mid + else: + hi = mid + assert 0 < p_continue < 1, p_continue + assert _p_continue_to_avg(p_continue, max_size) <= desired_avg + return p_continue + + +def _p_continue_to_avg(p_continue: float, max_size: int) -> float: + """Return the average_size generated by this p_continue and max_size.""" + if p_continue >= 1: + return max_size + return (1.0 / (1 - p_continue) - 1) * (1 - p_continue**max_size) diff --git a/shared/package-files/77/7772e1b01ca6bc9bef27435aa768bd090aeb51c6eee183081721a914ca4b02e5/blob b/shared/package-files/77/7772e1b01ca6bc9bef27435aa768bd090aeb51c6eee183081721a914ca4b02e5/blob new file mode 100644 index 0000000000000000000000000000000000000000..3e5e29169a90e8adedf4d82546efa282d05d85f6 --- /dev/null +++ b/shared/package-files/77/7772e1b01ca6bc9bef27435aa768bd090aeb51c6eee183081721a914ca4b02e5/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7772e1b01ca6bc9bef27435aa768bd090aeb51c6eee183081721a914ca4b02e5 +size 258384 diff --git a/shared/package-files/77/77743b2a902cdefd0bf71514a9221881fbdeb66c25e4d2a6a5d0303409067643/blob b/shared/package-files/77/77743b2a902cdefd0bf71514a9221881fbdeb66c25e4d2a6a5d0303409067643/blob new file mode 100644 index 0000000000000000000000000000000000000000..1260767ddc95300521a72c1f2df93de3751c2039 --- /dev/null +++ b/shared/package-files/77/77743b2a902cdefd0bf71514a9221881fbdeb66c25e4d2a6a5d0303409067643/blob @@ -0,0 +1,16 @@ +zstandard-0.19.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +zstandard-0.19.0.dist-info/LICENSE,sha256=eI_oXlNySkCymQUcSryc901Csn55aDJbgIkcJfea20s,1484 +zstandard-0.19.0.dist-info/METADATA,sha256=nnzOQO3CJE93MLJ6VIg9Wacq-HFnqvjND8YKb1f45xE,2962 +zstandard-0.19.0.dist-info/RECORD,, +zstandard-0.19.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +zstandard-0.19.0.dist-info/WHEEL,sha256=Qde73y9i2oDu_CV3UfJjbD0-upkMJblIn_RvcIzi-D4,105 +zstandard-0.19.0.dist-info/direct_url.json,sha256=VXaffrH7wSsH46ytZpdljGyus59kdWIgODnwd4_3cc8,69 +zstandard-0.19.0.dist-info/top_level.txt,sha256=J-wj94pPadY4ipFaanrYBlrMblOSegEYS8o_LdogrpU,10 +zstandard/__init__.py,sha256=imXNSrRBEuFDOgl9rufOhgAEeZXzKJ8T11i7ABwGpVM,7102 +zstandard/__init__.pyi,sha256=w7AmWAOu39_YMBFwHqZsJ1eIr6YrVkUq40sC4HPm8p4,13890 +zstandard/__pycache__/__init__.cpython-310.pyc,, +zstandard/__pycache__/backend_cffi.cpython-310.pyc,, +zstandard/_cffi.cpython-310-x86_64-linux-gnu.so,sha256=T3-SZiDZ9P2osJE9D4stNDZF3Ruqo71qAIZeJZkt9PI,893416 +zstandard/backend_c.cpython-310-x86_64-linux-gnu.so,sha256=1QjTDI5CtQqPaGB9rlk8mkfhPFsMiEyfJ5FA06rgb5g,762712 +zstandard/backend_cffi.py,sha256=nDdvVF6eAt84S4rSfPGd5ZAZb2xrAB0uRUFykDR4498,151371 +zstandard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/shared/package-files/77/7774870daf949cdcb5eccbf46a2a3b91011feaab11cc4a60037d7e3305ae048a/blob b/shared/package-files/77/7774870daf949cdcb5eccbf46a2a3b91011feaab11cc4a60037d7e3305ae048a/blob new file mode 100644 index 0000000000000000000000000000000000000000..3e798351874a376455673768e382de38cf9ed5eb --- /dev/null +++ b/shared/package-files/77/7774870daf949cdcb5eccbf46a2a3b91011feaab11cc4a60037d7e3305ae048a/blob @@ -0,0 +1,3 @@ +import collections + +OrderedDict = collections.OrderedDict diff --git a/shared/package-files/77/777606509a5c6c09c6d87024c9a07df0435d69399b8ef9c1581e816ba85030d1/blob b/shared/package-files/77/777606509a5c6c09c6d87024c9a07df0435d69399b8ef9c1581e816ba85030d1/blob new file mode 100644 index 0000000000000000000000000000000000000000..4a807a605571979fd50d96a70a3b25f1ee507a99 --- /dev/null +++ b/shared/package-files/77/777606509a5c6c09c6d87024c9a07df0435d69399b8ef9c1581e816ba85030d1/blob @@ -0,0 +1,160 @@ +from typing import Dict, List, Optional + +import torch +import torch.optim._functional as F + +from torch import Tensor + +__all__: List[str] = [] + +# Define a TorchScript compatible Functional SGD Optimizer +# where we use these optimizer in a functional way. +# Instead of using the `param.grad` when updating parameters, +# we explicitly allow the distributed optimizer pass gradients to +# the `step` function. In this way, we could separate the gradients +# and parameters and allow multithreaded trainer to update the +# parameters without data traces on accumulating to the same .grad. +# NOTE: This should be only used by distributed optimizer internals +# and not meant to expose to the user. +@torch.jit.script +class _FunctionalSGD: + def __init__( + self, + params: List[Tensor], + lr: float = 1e-2, + momentum: float = 0.0, + dampening: float = 0.0, + weight_decay: float = 0.0, + nesterov: bool = False, + maximize: bool = False, + foreach: bool = False, + fused: bool = False, + _allow_empty_param_list: bool = False, + ): + self.defaults = { + "lr": lr, + "momentum": momentum, + "dampening": dampening, + "weight_decay": weight_decay, + } + self.nesterov = nesterov + self.maximize = maximize + self.foreach = foreach + self.fused = fused + self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {}) + + if len(params) == 0 and not _allow_empty_param_list: + raise ValueError("optimizer got an empty parameter list") + + # NOTE: we only have one param_group and don't allow user to add additional + # param group as it's not a common use case. + self.param_group = {"params": params} + + def step_param(self, param: Tensor, grad: Optional[Tensor]): + """Similar to self.step, but operates on a single parameter and + its gradient. + """ + # TODO: Once step_param interface is robust, refactor step to call + # step param on each param. + weight_decay = self.defaults["weight_decay"] + momentum = self.defaults["momentum"] + dampening = self.defaults["dampening"] + lr = self.defaults["lr"] + params = [param] + momentum_buffer_list: List[Optional[Tensor]] = [] + grads = [] + + has_sparse_grad = False + if grad is not None: + grads.append(grad) + if grad.is_sparse: + has_sparse_grad = True + if param not in self.state: + self.state[param] = {} + state = self.state[param] + if "momentum_buffer" not in state: + momentum_buffer_list.append(None) + else: + momentum_buffer_list.append(state["momentum_buffer"]) + + with torch.no_grad(): + F.sgd( + params, + grads, + momentum_buffer_list, + weight_decay=weight_decay, + momentum=momentum, + lr=lr, + dampening=dampening, + nesterov=self.nesterov, + maximize=self.maximize, + has_sparse_grad=has_sparse_grad, + foreach=self.foreach, + fused=self.fused, + grad_scale=None, + found_inf=None, + ) + # update momentum_buffer in state + state = self.state[param] + momentum_buffer = momentum_buffer_list[0] + if momentum_buffer is not None: + state["momentum_buffer"] = momentum_buffer + + def step(self, gradients: List[Optional[Tensor]]): + params = self.param_group["params"] + params_with_grad = [] + grads = [] + momentum_buffer_list: List[Optional[Tensor]] = [] + lr = self.defaults["lr"] + weight_decay = self.defaults["weight_decay"] + momentum = self.defaults["momentum"] + dampening = self.defaults["dampening"] + + if len(params) != len(gradients): + raise ValueError( + "the gradients passed in does not equal to the size of the parameters!" + + f"Params length: {len(params)}. " + + f"Gradients length: {len(gradients)}" + ) + + has_sparse_grad = False + for param, gradient in zip(params, gradients): + if gradient is not None: + params_with_grad.append(param) + grads.append(gradient) + if gradient.is_sparse: + has_sparse_grad = True + + if param not in self.state: + self.state[param] = {} + + state = self.state[param] + if "momentum_buffer" not in state: + momentum_buffer_list.append(None) + else: + momentum_buffer_list.append(state["momentum_buffer"]) + + with torch.no_grad(): + F.sgd( + params_with_grad, + grads, + momentum_buffer_list, + weight_decay=weight_decay, + momentum=momentum, + lr=lr, + dampening=dampening, + nesterov=self.nesterov, + maximize=self.maximize, + has_sparse_grad=has_sparse_grad, + foreach=self.foreach, + fused=self.fused, + grad_scale=None, + found_inf=None, + ) + + # update momentum_buffers in state + for i, p in enumerate(params_with_grad): + state = self.state[p] + momentum_buffer = momentum_buffer_list[i] + if momentum_buffer is not None: + state["momentum_buffer"] = momentum_buffer diff --git a/shared/package-files/77/77766f78b11a5ccf2cc8449f60ed44425d3cdaa450e9243bc70cf48e2653ffb2/blob b/shared/package-files/77/77766f78b11a5ccf2cc8449f60ed44425d3cdaa450e9243bc70cf48e2653ffb2/blob new file mode 100644 index 0000000000000000000000000000000000000000..8be0ab6f54451f2304eaf37dee1f05901caf7022 Binary files /dev/null and b/shared/package-files/77/77766f78b11a5ccf2cc8449f60ed44425d3cdaa450e9243bc70cf48e2653ffb2/blob differ diff --git a/shared/package-files/77/77768b4b9ab8f752156647cac7c1d37388e4813b6e37448e69455f9320532261/blob b/shared/package-files/77/77768b4b9ab8f752156647cac7c1d37388e4813b6e37448e69455f9320532261/blob new file mode 100644 index 0000000000000000000000000000000000000000..edf3839c2cebb6f51d0bb21b06ea8a1c47dec0fe --- /dev/null +++ b/shared/package-files/77/77768b4b9ab8f752156647cac7c1d37388e4813b6e37448e69455f9320532261/blob @@ -0,0 +1,40 @@ +import numpy as np +import pytest + +from pandas import Series + + +@pytest.mark.parametrize( + "data, expected", + [ + (np.random.default_rng(2).integers(0, 10, size=1000), False), + (np.arange(1000), True), + ([], True), + ([np.nan], True), + (["foo", "bar", np.nan], True), + (["foo", "foo", np.nan], False), + (["foo", "bar", np.nan, np.nan], False), + ], +) +def test_is_unique(data, expected): + # GH#11946 / GH#25180 + ser = Series(data) + assert ser.is_unique is expected + + +def test_is_unique_class_ne(capsys): + # GH#20661 + class Foo: + def __init__(self, val) -> None: + self._value = val + + def __ne__(self, other): + raise Exception("NEQ not supported") + + with capsys.disabled(): + li = [Foo(i) for i in range(5)] + ser = Series(li, index=list(range(5))) + + ser.is_unique + captured = capsys.readouterr() + assert len(captured.err) == 0 diff --git a/shared/package-files/77/77772922eeb421b2ab2f2c0f9e2d7b45411063b32f92aa8a89fcb32791f7cd15/blob b/shared/package-files/77/77772922eeb421b2ab2f2c0f9e2d7b45411063b32f92aa8a89fcb32791f7cd15/blob new file mode 100644 index 0000000000000000000000000000000000000000..c3bf5e33ba4f9eeff3e41d9516fd847ecea4deb8 --- /dev/null +++ b/shared/package-files/77/77772922eeb421b2ab2f2c0f9e2d7b45411063b32f92aa8a89fcb32791f7cd15/blob @@ -0,0 +1,185 @@ +# SPDX-License-Identifier: MIT + + +import inspect +import platform +import sys +import threading +import types +import warnings + +from collections.abc import Mapping, Sequence # noqa +from typing import _GenericAlias + + +PYPY = platform.python_implementation() == "PyPy" +PY_3_9_PLUS = sys.version_info[:2] >= (3, 9) +PY310 = sys.version_info[:2] >= (3, 10) +PY_3_12_PLUS = sys.version_info[:2] >= (3, 12) + + +def just_warn(*args, **kw): + warnings.warn( + "Running interpreter doesn't sufficiently support code object " + "introspection. Some features like bare super() or accessing " + "__class__ will not work with slotted classes.", + RuntimeWarning, + stacklevel=2, + ) + + +class _AnnotationExtractor: + """ + Extract type annotations from a callable, returning None whenever there + is none. + """ + + __slots__ = ["sig"] + + def __init__(self, callable): + try: + self.sig = inspect.signature(callable) + except (ValueError, TypeError): # inspect failed + self.sig = None + + def get_first_param_type(self): + """ + Return the type annotation of the first argument if it's not empty. + """ + if not self.sig: + return None + + params = list(self.sig.parameters.values()) + if params and params[0].annotation is not inspect.Parameter.empty: + return params[0].annotation + + return None + + def get_return_type(self): + """ + Return the return type if it's not empty. + """ + if ( + self.sig + and self.sig.return_annotation is not inspect.Signature.empty + ): + return self.sig.return_annotation + + return None + + +def make_set_closure_cell(): + """Return a function of two arguments (cell, value) which sets + the value stored in the closure cell `cell` to `value`. + """ + # pypy makes this easy. (It also supports the logic below, but + # why not do the easy/fast thing?) + if PYPY: + + def set_closure_cell(cell, value): + cell.__setstate__((value,)) + + return set_closure_cell + + # Otherwise gotta do it the hard way. + + try: + if sys.version_info >= (3, 8): + + def set_closure_cell(cell, value): + cell.cell_contents = value + + else: + # Create a function that will set its first cellvar to `value`. + def set_first_cellvar_to(value): + x = value + return + + # This function will be eliminated as dead code, but + # not before its reference to `x` forces `x` to be + # represented as a closure cell rather than a local. + def force_x_to_be_a_cell(): # pragma: no cover + return x + + # Extract the code object and make sure our assumptions about + # the closure behavior are correct. + co = set_first_cellvar_to.__code__ + if co.co_cellvars != ("x",) or co.co_freevars != (): + raise AssertionError # pragma: no cover + + # Convert this code object to a code object that sets the + # function's first _freevar_ (not cellvar) to the argument. + args = [co.co_argcount] + args.append(co.co_kwonlyargcount) + args.extend( + [ + co.co_nlocals, + co.co_stacksize, + co.co_flags, + co.co_code, + co.co_consts, + co.co_names, + co.co_varnames, + co.co_filename, + co.co_name, + co.co_firstlineno, + co.co_lnotab, + # These two arguments are reversed: + co.co_cellvars, + co.co_freevars, + ] + ) + set_first_freevar_code = types.CodeType(*args) + + def set_closure_cell(cell, value): + # Create a function using the set_first_freevar_code, + # whose first closure cell is `cell`. Calling it will + # change the value of that cell. + setter = types.FunctionType( + set_first_freevar_code, {}, "setter", (), (cell,) + ) + # And call it to set the cell. + setter(value) + + # Make sure it works on this interpreter: + def make_func_with_cell(): + x = None + + def func(): + return x # pragma: no cover + + return func + + cell = make_func_with_cell().__closure__[0] + set_closure_cell(cell, 100) + if cell.cell_contents != 100: + raise AssertionError # pragma: no cover + + except Exception: + return just_warn + else: + return set_closure_cell + + +set_closure_cell = make_set_closure_cell() + +# Thread-local global to track attrs instances which are already being repr'd. +# This is needed because there is no other (thread-safe) way to pass info +# about the instances that are already being repr'd through the call stack +# in order to ensure we don't perform infinite recursion. +# +# For instance, if an instance contains a dict which contains that instance, +# we need to know that we're already repr'ing the outside instance from within +# the dict's repr() call. +# +# This lives here rather than in _make.py so that the functions in _make.py +# don't have a direct reference to the thread-local in their globals dict. +# If they have such a reference, it breaks cloudpickle. +repr_context = threading.local() + + +def get_generic_base(cl): + """If this is a generic class (A[str]), return the generic base for it.""" + if cl.__class__ is _GenericAlias: + return cl.__origin__ + return None diff --git a/shared/package-files/77/777963c901498b99e9b33f8aeabf6fe32088676105b96c687c5be1044b7cc65a/blob b/shared/package-files/77/777963c901498b99e9b33f8aeabf6fe32088676105b96c687c5be1044b7cc65a/blob new file mode 100644 index 0000000000000000000000000000000000000000..fbafe2935f91ab4c6831982184b379e3028eb690 --- /dev/null +++ b/shared/package-files/77/777963c901498b99e9b33f8aeabf6fe32088676105b96c687c5be1044b7cc65a/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor rand(at::IntArrayRef size, c10::optional names, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & rand_names_out_symint(c10::SymIntArrayRef size, c10::optional names, at::Tensor & out); +TORCH_API at::Tensor rand(at::IntArrayRef size, c10::optional generator, c10::optional names, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & rand_generator_with_names_out_symint(c10::SymIntArrayRef size, c10::optional generator, c10::optional names, at::Tensor & out); +TORCH_API at::Tensor rand(at::IntArrayRef size, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +TORCH_API at::Tensor & rand_out(at::IntArrayRef size, at::Tensor & out); +TORCH_API at::Tensor & rand_out(at::IntArrayRef size, c10::optional generator, at::Tensor & out); +TORCH_API at::Tensor rand(at::IntArrayRef size, c10::optional generator, c10::optional dtype={}, c10::optional layout={}, c10::optional device={}, c10::optional pin_memory={}); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/7779b574263ab57110a09f1f8f8c5ed6790fa167488a6b780efe4a097b24feed/blob b/shared/package-files/77/7779b574263ab57110a09f1f8f8c5ed6790fa167488a6b780efe4a097b24feed/blob new file mode 100644 index 0000000000000000000000000000000000000000..fe78e3a05dce7a97b4ece22777afc5c1212bda50 --- /dev/null +++ b/shared/package-files/77/7779b574263ab57110a09f1f8f8c5ed6790fa167488a6b780efe4a097b24feed/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _nested_view_from_buffer_copy_out(const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets, at::Tensor & out); +TORCH_API at::Tensor _nested_view_from_buffer_copy(const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/777a5a1d3a9479b7b1e327e03e3ee9ce90a47ace273a7b8ba2369446af5accc1/blob b/shared/package-files/77/777a5a1d3a9479b7b1e327e03e3ee9ce90a47ace273a7b8ba2369446af5accc1/blob new file mode 100644 index 0000000000000000000000000000000000000000..08d2fb3ac8e8762df227246612607b1602026c72 --- /dev/null +++ b/shared/package-files/77/777a5a1d3a9479b7b1e327e03e3ee9ce90a47ace273a7b8ba2369446af5accc1/blob @@ -0,0 +1,155 @@ +import torch +from torch import nan +from torch.distributions import constraints +from torch.distributions.distribution import Distribution +from torch.distributions.utils import lazy_property, logits_to_probs, probs_to_logits + +__all__ = ["Categorical"] + + +class Categorical(Distribution): + r""" + Creates a categorical distribution parameterized by either :attr:`probs` or + :attr:`logits` (but not both). + + .. note:: + It is equivalent to the distribution that :func:`torch.multinomial` + samples from. + + Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``. + + If `probs` is 1-dimensional with length-`K`, each element is the relative probability + of sampling the class at that index. + + If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of + relative probability vectors. + + .. note:: The `probs` argument must be non-negative, finite and have a non-zero sum, + and it will be normalized to sum to 1 along the last dimension. :attr:`probs` + will return this normalized value. + The `logits` argument will be interpreted as unnormalized log probabilities + and can therefore be any real number. It will likewise be normalized so that + the resulting probabilities sum to 1 along the last dimension. :attr:`logits` + will return this normalized value. + + See also: :func:`torch.multinomial` + + Example:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ])) + >>> m.sample() # equal probability of 0, 1, 2, 3 + tensor(3) + + Args: + probs (Tensor): event probabilities + logits (Tensor): event log probabilities (unnormalized) + """ + arg_constraints = {"probs": constraints.simplex, "logits": constraints.real_vector} + has_enumerate_support = True + + def __init__(self, probs=None, logits=None, validate_args=None): + if (probs is None) == (logits is None): + raise ValueError( + "Either `probs` or `logits` must be specified, but not both." + ) + if probs is not None: + if probs.dim() < 1: + raise ValueError("`probs` parameter must be at least one-dimensional.") + self.probs = probs / probs.sum(-1, keepdim=True) + else: + if logits.dim() < 1: + raise ValueError("`logits` parameter must be at least one-dimensional.") + # Normalize + self.logits = logits - logits.logsumexp(dim=-1, keepdim=True) + self._param = self.probs if probs is not None else self.logits + self._num_events = self._param.size()[-1] + batch_shape = ( + self._param.size()[:-1] if self._param.ndimension() > 1 else torch.Size() + ) + super().__init__(batch_shape, validate_args=validate_args) + + def expand(self, batch_shape, _instance=None): + new = self._get_checked_instance(Categorical, _instance) + batch_shape = torch.Size(batch_shape) + param_shape = batch_shape + torch.Size((self._num_events,)) + if "probs" in self.__dict__: + new.probs = self.probs.expand(param_shape) + new._param = new.probs + if "logits" in self.__dict__: + new.logits = self.logits.expand(param_shape) + new._param = new.logits + new._num_events = self._num_events + super(Categorical, new).__init__(batch_shape, validate_args=False) + new._validate_args = self._validate_args + return new + + def _new(self, *args, **kwargs): + return self._param.new(*args, **kwargs) + + @constraints.dependent_property(is_discrete=True, event_dim=0) + def support(self): + return constraints.integer_interval(0, self._num_events - 1) + + @lazy_property + def logits(self): + return probs_to_logits(self.probs) + + @lazy_property + def probs(self): + return logits_to_probs(self.logits) + + @property + def param_shape(self): + return self._param.size() + + @property + def mean(self): + return torch.full( + self._extended_shape(), + nan, + dtype=self.probs.dtype, + device=self.probs.device, + ) + + @property + def mode(self): + return self.probs.argmax(axis=-1) + + @property + def variance(self): + return torch.full( + self._extended_shape(), + nan, + dtype=self.probs.dtype, + device=self.probs.device, + ) + + def sample(self, sample_shape=torch.Size()): + if not isinstance(sample_shape, torch.Size): + sample_shape = torch.Size(sample_shape) + probs_2d = self.probs.reshape(-1, self._num_events) + samples_2d = torch.multinomial(probs_2d, sample_shape.numel(), True).T + return samples_2d.reshape(self._extended_shape(sample_shape)) + + def log_prob(self, value): + if self._validate_args: + self._validate_sample(value) + value = value.long().unsqueeze(-1) + value, log_pmf = torch.broadcast_tensors(value, self.logits) + value = value[..., :1] + return log_pmf.gather(-1, value).squeeze(-1) + + def entropy(self): + min_real = torch.finfo(self.logits.dtype).min + logits = torch.clamp(self.logits, min=min_real) + p_log_p = logits * self.probs + return -p_log_p.sum(-1) + + def enumerate_support(self, expand=True): + num_events = self._num_events + values = torch.arange(num_events, dtype=torch.long, device=self._param.device) + values = values.view((-1,) + (1,) * len(self._batch_shape)) + if expand: + values = values.expand((-1,) + self._batch_shape) + return values diff --git a/shared/package-files/77/777a5abed68cb8820a8eea562f014bb7b5ab7eabed4f5f2eef072c05d9ee393b/blob b/shared/package-files/77/777a5abed68cb8820a8eea562f014bb7b5ab7eabed4f5f2eef072c05d9ee393b/blob new file mode 100644 index 0000000000000000000000000000000000000000..189381cb06fbe2992123e0facae18101ee7f1927 --- /dev/null +++ b/shared/package-files/77/777a5abed68cb8820a8eea562f014bb7b5ab7eabed4f5f2eef072c05d9ee393b/blob @@ -0,0 +1,238 @@ +__all__ = ['geometric_slerp'] + +import warnings +from typing import TYPE_CHECKING + +import numpy as np +from scipy.spatial.distance import euclidean + +if TYPE_CHECKING: + import numpy.typing as npt + + +def _geometric_slerp(start, end, t): + # create an orthogonal basis using QR decomposition + basis = np.vstack([start, end]) + Q, R = np.linalg.qr(basis.T) + signs = 2 * (np.diag(R) >= 0) - 1 + Q = Q.T * signs.T[:, np.newaxis] + R = R.T * signs.T[:, np.newaxis] + + # calculate the angle between `start` and `end` + c = np.dot(start, end) + s = np.linalg.det(R) + omega = np.arctan2(s, c) + + # interpolate + start, end = Q + s = np.sin(t * omega) + c = np.cos(t * omega) + return start * c[:, np.newaxis] + end * s[:, np.newaxis] + + +def geometric_slerp( + start: "npt.ArrayLike", + end: "npt.ArrayLike", + t: "npt.ArrayLike", + tol: float = 1e-7, +) -> np.ndarray: + """ + Geometric spherical linear interpolation. + + The interpolation occurs along a unit-radius + great circle arc in arbitrary dimensional space. + + Parameters + ---------- + start : (n_dimensions, ) array-like + Single n-dimensional input coordinate in a 1-D array-like + object. `n` must be greater than 1. + end : (n_dimensions, ) array-like + Single n-dimensional input coordinate in a 1-D array-like + object. `n` must be greater than 1. + t : float or (n_points,) 1D array-like + A float or 1D array-like of doubles representing interpolation + parameters, with values required in the inclusive interval + between 0 and 1. A common approach is to generate the array + with ``np.linspace(0, 1, n_pts)`` for linearly spaced points. + Ascending, descending, and scrambled orders are permitted. + tol : float + The absolute tolerance for determining if the start and end + coordinates are antipodes. + + Returns + ------- + result : (t.size, D) + An array of doubles containing the interpolated + spherical path and including start and + end when 0 and 1 t are used. The + interpolated values should correspond to the + same sort order provided in the t array. The result + may be 1-dimensional if ``t`` is a float. + + Raises + ------ + ValueError + If ``start`` and ``end`` are antipodes, not on the + unit n-sphere, or for a variety of degenerate conditions. + + See Also + -------- + scipy.spatial.transform.Slerp : 3-D Slerp that works with quaternions + + Notes + ----- + The implementation is based on the mathematical formula provided in [1]_, + and the first known presentation of this algorithm, derived from study of + 4-D geometry, is credited to Glenn Davis in a footnote of the original + quaternion Slerp publication by Ken Shoemake [2]_. + + .. versionadded:: 1.5.0 + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Slerp#Geometric_Slerp + .. [2] Ken Shoemake (1985) Animating rotation with quaternion curves. + ACM SIGGRAPH Computer Graphics, 19(3): 245-254. + + Examples + -------- + Interpolate four linearly-spaced values on the circumference of + a circle spanning 90 degrees: + + >>> import numpy as np + >>> from scipy.spatial import geometric_slerp + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> start = np.array([1, 0]) + >>> end = np.array([0, 1]) + >>> t_vals = np.linspace(0, 1, 4) + >>> result = geometric_slerp(start, + ... end, + ... t_vals) + + The interpolated results should be at 30 degree intervals + recognizable on the unit circle: + + >>> ax.scatter(result[...,0], result[...,1], c='k') + >>> circle = plt.Circle((0, 0), 1, color='grey') + >>> ax.add_artist(circle) + >>> ax.set_aspect('equal') + >>> plt.show() + + Attempting to interpolate between antipodes on a circle is + ambiguous because there are two possible paths, and on a + sphere there are infinite possible paths on the geodesic surface. + Nonetheless, one of the ambiguous paths is returned along + with a warning: + + >>> opposite_pole = np.array([-1, 0]) + >>> with np.testing.suppress_warnings() as sup: + ... sup.filter(UserWarning) + ... geometric_slerp(start, + ... opposite_pole, + ... t_vals) + array([[ 1.00000000e+00, 0.00000000e+00], + [ 5.00000000e-01, 8.66025404e-01], + [-5.00000000e-01, 8.66025404e-01], + [-1.00000000e+00, 1.22464680e-16]]) + + Extend the original example to a sphere and plot interpolation + points in 3D: + + >>> from mpl_toolkits.mplot3d import proj3d + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111, projection='3d') + + Plot the unit sphere for reference (optional): + + >>> u = np.linspace(0, 2 * np.pi, 100) + >>> v = np.linspace(0, np.pi, 100) + >>> x = np.outer(np.cos(u), np.sin(v)) + >>> y = np.outer(np.sin(u), np.sin(v)) + >>> z = np.outer(np.ones(np.size(u)), np.cos(v)) + >>> ax.plot_surface(x, y, z, color='y', alpha=0.1) + + Interpolating over a larger number of points + may provide the appearance of a smooth curve on + the surface of the sphere, which is also useful + for discretized integration calculations on a + sphere surface: + + >>> start = np.array([1, 0, 0]) + >>> end = np.array([0, 0, 1]) + >>> t_vals = np.linspace(0, 1, 200) + >>> result = geometric_slerp(start, + ... end, + ... t_vals) + >>> ax.plot(result[...,0], + ... result[...,1], + ... result[...,2], + ... c='k') + >>> plt.show() + """ + + start = np.asarray(start, dtype=np.float64) + end = np.asarray(end, dtype=np.float64) + t = np.asarray(t) + + if t.ndim > 1: + raise ValueError("The interpolation parameter " + "value must be one dimensional.") + + if start.ndim != 1 or end.ndim != 1: + raise ValueError("Start and end coordinates " + "must be one-dimensional") + + if start.size != end.size: + raise ValueError("The dimensions of start and " + "end must match (have same size)") + + if start.size < 2 or end.size < 2: + raise ValueError("The start and end coordinates must " + "both be in at least two-dimensional " + "space") + + if np.array_equal(start, end): + return np.linspace(start, start, t.size) + + # for points that violate equation for n-sphere + for coord in [start, end]: + if not np.allclose(np.linalg.norm(coord), 1.0, + rtol=1e-9, + atol=0): + raise ValueError("start and end are not" + " on a unit n-sphere") + + if not isinstance(tol, float): + raise ValueError("tol must be a float") + else: + tol = np.fabs(tol) + + coord_dist = euclidean(start, end) + + # diameter of 2 within tolerance means antipodes, which is a problem + # for all unit n-spheres (even the 0-sphere would have an ambiguous path) + if np.allclose(coord_dist, 2.0, rtol=0, atol=tol): + warnings.warn("start and end are antipodes " + "using the specified tolerance; " + "this may cause ambiguous slerp paths", + stacklevel=2) + + t = np.asarray(t, dtype=np.float64) + + if t.size == 0: + return np.empty((0, start.size)) + + if t.min() < 0 or t.max() > 1: + raise ValueError("interpolation parameter must be in [0, 1]") + + if t.ndim == 0: + return _geometric_slerp(start, + end, + np.atleast_1d(t)).ravel() + else: + return _geometric_slerp(start, + end, + t) diff --git a/shared/package-files/77/777af1b518f952ed7d0cd2cfd3275017fb04ff859e1d682df2e0e2e4d5c30d17/blob b/shared/package-files/77/777af1b518f952ed7d0cd2cfd3275017fb04ff859e1d682df2e0e2e4d5c30d17/blob new file mode 100644 index 0000000000000000000000000000000000000000..a59e4bdce00a283e01fad6d46f8ec3115cd93f1d --- /dev/null +++ b/shared/package-files/77/777af1b518f952ed7d0cd2cfd3275017fb04ff859e1d682df2e0e2e4d5c30d17/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple _lstm_mps_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, at::Tensor & out5, const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first); +TORCH_API ::std::tuple _lstm_mps_outf(const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, at::Tensor & out5); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/77/777af8b7bc4736a485b66aac03d06dab5369cb759333ea5c336fe3782c840b16/blob b/shared/package-files/77/777af8b7bc4736a485b66aac03d06dab5369cb759333ea5c336fe3782c840b16/blob new file mode 100644 index 0000000000000000000000000000000000000000..93594dd44474a415c74e4b0beb83bd7012666c9d --- /dev/null +++ b/shared/package-files/77/777af8b7bc4736a485b66aac03d06dab5369cb759333ea5c336fe3782c840b16/blob @@ -0,0 +1,1339 @@ +""" +This module defines the mpf, mpc classes, and standard functions for +operating with them. +""" +__docformat__ = 'plaintext' + +import functools + +import re + +from .ctx_base import StandardBaseContext + +from .libmp.backend import basestring, BACKEND + +from . import libmp + +from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps, + round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps, + ComplexResult, to_pickable, from_pickable, normalize, + from_int, from_float, from_str, to_int, to_float, to_str, + from_rational, from_man_exp, + fone, fzero, finf, fninf, fnan, + mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int, + mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod, + mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge, + mpf_hash, mpf_rand, + mpf_sum, + bitcount, to_fixed, + mpc_to_str, + mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate, + mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf, + mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int, + mpc_mpf_div, + mpf_pow, + mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10, + mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin, + mpf_glaisher, mpf_twinprime, mpf_mertens, + int_types) + +from . import function_docs +from . import rational + +new = object.__new__ + +get_complex = re.compile(r'^\(?(?P[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?)??' + r'(?P[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?j)?\)?$') + +if BACKEND == 'sage': + from sage.libs.mpmath.ext_main import Context as BaseMPContext + # pickle hack + import sage.libs.mpmath.ext_main as _mpf_module +else: + from .ctx_mp_python import PythonMPContext as BaseMPContext + from . import ctx_mp_python as _mpf_module + +from .ctx_mp_python import _mpf, _mpc, mpnumeric + +class MPContext(BaseMPContext, StandardBaseContext): + """ + Context for multiprecision arithmetic with a global precision. + """ + + def __init__(ctx): + BaseMPContext.__init__(ctx) + ctx.trap_complex = False + ctx.pretty = False + ctx.types = [ctx.mpf, ctx.mpc, ctx.constant] + ctx._mpq = rational.mpq + ctx.default() + StandardBaseContext.__init__(ctx) + + ctx.mpq = rational.mpq + ctx.init_builtins() + + ctx.hyp_summators = {} + + ctx._init_aliases() + + # XXX: automate + try: + ctx.bernoulli.im_func.func_doc = function_docs.bernoulli + ctx.primepi.im_func.func_doc = function_docs.primepi + ctx.psi.im_func.func_doc = function_docs.psi + ctx.atan2.im_func.func_doc = function_docs.atan2 + except AttributeError: + # python 3 + ctx.bernoulli.__func__.func_doc = function_docs.bernoulli + ctx.primepi.__func__.func_doc = function_docs.primepi + ctx.psi.__func__.func_doc = function_docs.psi + ctx.atan2.__func__.func_doc = function_docs.atan2 + + ctx.digamma.func_doc = function_docs.digamma + ctx.cospi.func_doc = function_docs.cospi + ctx.sinpi.func_doc = function_docs.sinpi + + def init_builtins(ctx): + + mpf = ctx.mpf + mpc = ctx.mpc + + # Exact constants + ctx.one = ctx.make_mpf(fone) + ctx.zero = ctx.make_mpf(fzero) + ctx.j = ctx.make_mpc((fzero,fone)) + ctx.inf = ctx.make_mpf(finf) + ctx.ninf = ctx.make_mpf(fninf) + ctx.nan = ctx.make_mpf(fnan) + + eps = ctx.constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1), + "epsilon of working precision", "eps") + ctx.eps = eps + + # Approximate constants + ctx.pi = ctx.constant(mpf_pi, "pi", "pi") + ctx.ln2 = ctx.constant(mpf_ln2, "ln(2)", "ln2") + ctx.ln10 = ctx.constant(mpf_ln10, "ln(10)", "ln10") + ctx.phi = ctx.constant(mpf_phi, "Golden ratio phi", "phi") + ctx.e = ctx.constant(mpf_e, "e = exp(1)", "e") + ctx.euler = ctx.constant(mpf_euler, "Euler's constant", "euler") + ctx.catalan = ctx.constant(mpf_catalan, "Catalan's constant", "catalan") + ctx.khinchin = ctx.constant(mpf_khinchin, "Khinchin's constant", "khinchin") + ctx.glaisher = ctx.constant(mpf_glaisher, "Glaisher's constant", "glaisher") + ctx.apery = ctx.constant(mpf_apery, "Apery's constant", "apery") + ctx.degree = ctx.constant(mpf_degree, "1 deg = pi / 180", "degree") + ctx.twinprime = ctx.constant(mpf_twinprime, "Twin prime constant", "twinprime") + ctx.mertens = ctx.constant(mpf_mertens, "Mertens' constant", "mertens") + + # Standard functions + ctx.sqrt = ctx._wrap_libmp_function(libmp.mpf_sqrt, libmp.mpc_sqrt) + ctx.cbrt = ctx._wrap_libmp_function(libmp.mpf_cbrt, libmp.mpc_cbrt) + ctx.ln = ctx._wrap_libmp_function(libmp.mpf_log, libmp.mpc_log) + ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan) + ctx.exp = ctx._wrap_libmp_function(libmp.mpf_exp, libmp.mpc_exp) + ctx.expj = ctx._wrap_libmp_function(libmp.mpf_expj, libmp.mpc_expj) + ctx.expjpi = ctx._wrap_libmp_function(libmp.mpf_expjpi, libmp.mpc_expjpi) + ctx.sin = ctx._wrap_libmp_function(libmp.mpf_sin, libmp.mpc_sin) + ctx.cos = ctx._wrap_libmp_function(libmp.mpf_cos, libmp.mpc_cos) + ctx.tan = ctx._wrap_libmp_function(libmp.mpf_tan, libmp.mpc_tan) + ctx.sinh = ctx._wrap_libmp_function(libmp.mpf_sinh, libmp.mpc_sinh) + ctx.cosh = ctx._wrap_libmp_function(libmp.mpf_cosh, libmp.mpc_cosh) + ctx.tanh = ctx._wrap_libmp_function(libmp.mpf_tanh, libmp.mpc_tanh) + ctx.asin = ctx._wrap_libmp_function(libmp.mpf_asin, libmp.mpc_asin) + ctx.acos = ctx._wrap_libmp_function(libmp.mpf_acos, libmp.mpc_acos) + ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan) + ctx.asinh = ctx._wrap_libmp_function(libmp.mpf_asinh, libmp.mpc_asinh) + ctx.acosh = ctx._wrap_libmp_function(libmp.mpf_acosh, libmp.mpc_acosh) + ctx.atanh = ctx._wrap_libmp_function(libmp.mpf_atanh, libmp.mpc_atanh) + ctx.sinpi = ctx._wrap_libmp_function(libmp.mpf_sin_pi, libmp.mpc_sin_pi) + ctx.cospi = ctx._wrap_libmp_function(libmp.mpf_cos_pi, libmp.mpc_cos_pi) + ctx.floor = ctx._wrap_libmp_function(libmp.mpf_floor, libmp.mpc_floor) + ctx.ceil = ctx._wrap_libmp_function(libmp.mpf_ceil, libmp.mpc_ceil) + ctx.nint = ctx._wrap_libmp_function(libmp.mpf_nint, libmp.mpc_nint) + ctx.frac = ctx._wrap_libmp_function(libmp.mpf_frac, libmp.mpc_frac) + ctx.fib = ctx.fibonacci = ctx._wrap_libmp_function(libmp.mpf_fibonacci, libmp.mpc_fibonacci) + + ctx.gamma = ctx._wrap_libmp_function(libmp.mpf_gamma, libmp.mpc_gamma) + ctx.rgamma = ctx._wrap_libmp_function(libmp.mpf_rgamma, libmp.mpc_rgamma) + ctx.loggamma = ctx._wrap_libmp_function(libmp.mpf_loggamma, libmp.mpc_loggamma) + ctx.fac = ctx.factorial = ctx._wrap_libmp_function(libmp.mpf_factorial, libmp.mpc_factorial) + + ctx.digamma = ctx._wrap_libmp_function(libmp.mpf_psi0, libmp.mpc_psi0) + ctx.harmonic = ctx._wrap_libmp_function(libmp.mpf_harmonic, libmp.mpc_harmonic) + ctx.ei = ctx._wrap_libmp_function(libmp.mpf_ei, libmp.mpc_ei) + ctx.e1 = ctx._wrap_libmp_function(libmp.mpf_e1, libmp.mpc_e1) + ctx._ci = ctx._wrap_libmp_function(libmp.mpf_ci, libmp.mpc_ci) + ctx._si = ctx._wrap_libmp_function(libmp.mpf_si, libmp.mpc_si) + ctx.ellipk = ctx._wrap_libmp_function(libmp.mpf_ellipk, libmp.mpc_ellipk) + ctx._ellipe = ctx._wrap_libmp_function(libmp.mpf_ellipe, libmp.mpc_ellipe) + ctx.agm1 = ctx._wrap_libmp_function(libmp.mpf_agm1, libmp.mpc_agm1) + ctx._erf = ctx._wrap_libmp_function(libmp.mpf_erf, None) + ctx._erfc = ctx._wrap_libmp_function(libmp.mpf_erfc, None) + ctx._zeta = ctx._wrap_libmp_function(libmp.mpf_zeta, libmp.mpc_zeta) + ctx._altzeta = ctx._wrap_libmp_function(libmp.mpf_altzeta, libmp.mpc_altzeta) + + # Faster versions + ctx.sqrt = getattr(ctx, "_sage_sqrt", ctx.sqrt) + ctx.exp = getattr(ctx, "_sage_exp", ctx.exp) + ctx.ln = getattr(ctx, "_sage_ln", ctx.ln) + ctx.cos = getattr(ctx, "_sage_cos", ctx.cos) + ctx.sin = getattr(ctx, "_sage_sin", ctx.sin) + + def to_fixed(ctx, x, prec): + return x.to_fixed(prec) + + def hypot(ctx, x, y): + r""" + Computes the Euclidean norm of the vector `(x, y)`, equal + to `\sqrt{x^2 + y^2}`. Both `x` and `y` must be real.""" + x = ctx.convert(x) + y = ctx.convert(y) + return ctx.make_mpf(libmp.mpf_hypot(x._mpf_, y._mpf_, *ctx._prec_rounding)) + + def _gamma_upper_int(ctx, n, z): + n = int(ctx._re(n)) + if n == 0: + return ctx.e1(z) + if not hasattr(z, '_mpf_'): + raise NotImplementedError + prec, rounding = ctx._prec_rounding + real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding, gamma=True) + if imag is None: + return ctx.make_mpf(real) + else: + return ctx.make_mpc((real, imag)) + + def _expint_int(ctx, n, z): + n = int(n) + if n == 1: + return ctx.e1(z) + if not hasattr(z, '_mpf_'): + raise NotImplementedError + prec, rounding = ctx._prec_rounding + real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding) + if imag is None: + return ctx.make_mpf(real) + else: + return ctx.make_mpc((real, imag)) + + def _nthroot(ctx, x, n): + if hasattr(x, '_mpf_'): + try: + return ctx.make_mpf(libmp.mpf_nthroot(x._mpf_, n, *ctx._prec_rounding)) + except ComplexResult: + if ctx.trap_complex: + raise + x = (x._mpf_, libmp.fzero) + else: + x = x._mpc_ + return ctx.make_mpc(libmp.mpc_nthroot(x, n, *ctx._prec_rounding)) + + def _besselj(ctx, n, z): + prec, rounding = ctx._prec_rounding + if hasattr(z, '_mpf_'): + return ctx.make_mpf(libmp.mpf_besseljn(n, z._mpf_, prec, rounding)) + elif hasattr(z, '_mpc_'): + return ctx.make_mpc(libmp.mpc_besseljn(n, z._mpc_, prec, rounding)) + + def _agm(ctx, a, b=1): + prec, rounding = ctx._prec_rounding + if hasattr(a, '_mpf_') and hasattr(b, '_mpf_'): + try: + v = libmp.mpf_agm(a._mpf_, b._mpf_, prec, rounding) + return ctx.make_mpf(v) + except ComplexResult: + pass + if hasattr(a, '_mpf_'): a = (a._mpf_, libmp.fzero) + else: a = a._mpc_ + if hasattr(b, '_mpf_'): b = (b._mpf_, libmp.fzero) + else: b = b._mpc_ + return ctx.make_mpc(libmp.mpc_agm(a, b, prec, rounding)) + + def bernoulli(ctx, n): + return ctx.make_mpf(libmp.mpf_bernoulli(int(n), *ctx._prec_rounding)) + + def _zeta_int(ctx, n): + return ctx.make_mpf(libmp.mpf_zeta_int(int(n), *ctx._prec_rounding)) + + def atan2(ctx, y, x): + x = ctx.convert(x) + y = ctx.convert(y) + return ctx.make_mpf(libmp.mpf_atan2(y._mpf_, x._mpf_, *ctx._prec_rounding)) + + def psi(ctx, m, z): + z = ctx.convert(z) + m = int(m) + if ctx._is_real_type(z): + return ctx.make_mpf(libmp.mpf_psi(m, z._mpf_, *ctx._prec_rounding)) + else: + return ctx.make_mpc(libmp.mpc_psi(m, z._mpc_, *ctx._prec_rounding)) + + def cos_sin(ctx, x, **kwargs): + if type(x) not in ctx.types: + x = ctx.convert(x) + prec, rounding = ctx._parse_prec(kwargs) + if hasattr(x, '_mpf_'): + c, s = libmp.mpf_cos_sin(x._mpf_, prec, rounding) + return ctx.make_mpf(c), ctx.make_mpf(s) + elif hasattr(x, '_mpc_'): + c, s = libmp.mpc_cos_sin(x._mpc_, prec, rounding) + return ctx.make_mpc(c), ctx.make_mpc(s) + else: + return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs) + + def cospi_sinpi(ctx, x, **kwargs): + if type(x) not in ctx.types: + x = ctx.convert(x) + prec, rounding = ctx._parse_prec(kwargs) + if hasattr(x, '_mpf_'): + c, s = libmp.mpf_cos_sin_pi(x._mpf_, prec, rounding) + return ctx.make_mpf(c), ctx.make_mpf(s) + elif hasattr(x, '_mpc_'): + c, s = libmp.mpc_cos_sin_pi(x._mpc_, prec, rounding) + return ctx.make_mpc(c), ctx.make_mpc(s) + else: + return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs) + + def clone(ctx): + """ + Create a copy of the context, with the same working precision. + """ + a = ctx.__class__() + a.prec = ctx.prec + return a + + # Several helper methods + # TODO: add more of these, make consistent, write docstrings, ... + + def _is_real_type(ctx, x): + if hasattr(x, '_mpc_') or type(x) is complex: + return False + return True + + def _is_complex_type(ctx, x): + if hasattr(x, '_mpc_') or type(x) is complex: + return True + return False + + def isnan(ctx, x): + """ + Return *True* if *x* is a NaN (not-a-number), or for a complex + number, whether either the real or complex part is NaN; + otherwise return *False*:: + + >>> from mpmath import * + >>> isnan(3.14) + False + >>> isnan(nan) + True + >>> isnan(mpc(3.14,2.72)) + False + >>> isnan(mpc(3.14,nan)) + True + + """ + if hasattr(x, "_mpf_"): + return x._mpf_ == fnan + if hasattr(x, "_mpc_"): + return fnan in x._mpc_ + if isinstance(x, int_types) or isinstance(x, rational.mpq): + return False + x = ctx.convert(x) + if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'): + return ctx.isnan(x) + raise TypeError("isnan() needs a number as input") + + def isfinite(ctx, x): + """ + Return *True* if *x* is a finite number, i.e. neither + an infinity or a NaN. + + >>> from mpmath import * + >>> isfinite(inf) + False + >>> isfinite(-inf) + False + >>> isfinite(3) + True + >>> isfinite(nan) + False + >>> isfinite(3+4j) + True + >>> isfinite(mpc(3,inf)) + False + >>> isfinite(mpc(nan,3)) + False + + """ + if ctx.isinf(x) or ctx.isnan(x): + return False + return True + + def isnpint(ctx, x): + """ + Determine if *x* is a nonpositive integer. + """ + if not x: + return True + if hasattr(x, '_mpf_'): + sign, man, exp, bc = x._mpf_ + return sign and exp >= 0 + if hasattr(x, '_mpc_'): + return not x.imag and ctx.isnpint(x.real) + if type(x) in int_types: + return x <= 0 + if isinstance(x, ctx.mpq): + p, q = x._mpq_ + if not p: + return True + return q == 1 and p <= 0 + return ctx.isnpint(ctx.convert(x)) + + def __str__(ctx): + lines = ["Mpmath settings:", + (" mp.prec = %s" % ctx.prec).ljust(30) + "[default: 53]", + (" mp.dps = %s" % ctx.dps).ljust(30) + "[default: 15]", + (" mp.trap_complex = %s" % ctx.trap_complex).ljust(30) + "[default: False]", + ] + return "\n".join(lines) + + @property + def _repr_digits(ctx): + return repr_dps(ctx._prec) + + @property + def _str_digits(ctx): + return ctx._dps + + def extraprec(ctx, n, normalize_output=False): + """ + The block + + with extraprec(n): + + + increases the precision n bits, executes , and then + restores the precision. + + extraprec(n)(f) returns a decorated version of the function f + that increases the working precision by n bits before execution, + and restores the parent precision afterwards. With + normalize_output=True, it rounds the return value to the parent + precision. + """ + return PrecisionManager(ctx, lambda p: p + n, None, normalize_output) + + def extradps(ctx, n, normalize_output=False): + """ + This function is analogous to extraprec (see documentation) + but changes the decimal precision instead of the number of bits. + """ + return PrecisionManager(ctx, None, lambda d: d + n, normalize_output) + + def workprec(ctx, n, normalize_output=False): + """ + The block + + with workprec(n): + + + sets the precision to n bits, executes , and then restores + the precision. + + workprec(n)(f) returns a decorated version of the function f + that sets the precision to n bits before execution, + and restores the precision afterwards. With normalize_output=True, + it rounds the return value to the parent precision. + """ + return PrecisionManager(ctx, lambda p: n, None, normalize_output) + + def workdps(ctx, n, normalize_output=False): + """ + This function is analogous to workprec (see documentation) + but changes the decimal precision instead of the number of bits. + """ + return PrecisionManager(ctx, None, lambda d: n, normalize_output) + + def autoprec(ctx, f, maxprec=None, catch=(), verbose=False): + r""" + Return a wrapped copy of *f* that repeatedly evaluates *f* + with increasing precision until the result converges to the + full precision used at the point of the call. + + This heuristically protects against rounding errors, at the cost of + roughly a 2x slowdown compared to manually setting the optimal + precision. This method can, however, easily be fooled if the results + from *f* depend "discontinuously" on the precision, for instance + if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec` + should be used judiciously. + + **Examples** + + Many functions are sensitive to perturbations of the input arguments. + If the arguments are decimal numbers, they may have to be converted + to binary at a much higher precision. If the amount of required + extra precision is unknown, :func:`~mpmath.autoprec` is convenient:: + + >>> from mpmath import * + >>> mp.dps = 15 + >>> mp.pretty = True + >>> besselj(5, 125 * 10**28) # Exact input + -8.03284785591801e-17 + >>> besselj(5, '1.25e30') # Bad + 7.12954868316652e-16 + >>> autoprec(besselj)(5, '1.25e30') # Good + -8.03284785591801e-17 + + The following fails to converge because `\sin(\pi) = 0` whereas all + finite-precision approximations of `\pi` give nonzero values:: + + >>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + NoConvergence: autoprec: prec increased to 2910 without convergence + + As the following example shows, :func:`~mpmath.autoprec` can protect against + cancellation, but is fooled by too severe cancellation:: + + >>> x = 1e-10 + >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x) + 1.00000008274037e-10 + 1.00000000005e-10 + 1.00000000005e-10 + >>> x = 1e-50 + >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x) + 0.0 + 1.0e-50 + 0.0 + + With *catch*, an exception or list of exceptions to intercept + may be specified. The raised exception is interpreted + as signaling insufficient precision. This permits, for example, + evaluating a function where a too low precision results in a + division by zero:: + + >>> f = lambda x: 1/(exp(x)-1) + >>> f(1e-30) + Traceback (most recent call last): + ... + ZeroDivisionError + >>> autoprec(f, catch=ZeroDivisionError)(1e-30) + 1.0e+30 + + + """ + def f_autoprec_wrapped(*args, **kwargs): + prec = ctx.prec + if maxprec is None: + maxprec2 = ctx._default_hyper_maxprec(prec) + else: + maxprec2 = maxprec + try: + ctx.prec = prec + 10 + try: + v1 = f(*args, **kwargs) + except catch: + v1 = ctx.nan + prec2 = prec + 20 + while 1: + ctx.prec = prec2 + try: + v2 = f(*args, **kwargs) + except catch: + v2 = ctx.nan + if v1 == v2: + break + err = ctx.mag(v2-v1) - ctx.mag(v2) + if err < (-prec): + break + if verbose: + print("autoprec: target=%s, prec=%s, accuracy=%s" \ + % (prec, prec2, -err)) + v1 = v2 + if prec2 >= maxprec2: + raise ctx.NoConvergence(\ + "autoprec: prec increased to %i without convergence"\ + % prec2) + prec2 += int(prec2*2) + prec2 = min(prec2, maxprec2) + finally: + ctx.prec = prec + return +v2 + return f_autoprec_wrapped + + def nstr(ctx, x, n=6, **kwargs): + """ + Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n* + significant digits. The small default value for *n* is chosen to + make this function useful for printing collections of numbers + (lists, matrices, etc). + + If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively + to each element. For unrecognized classes, :func:`~mpmath.nstr` + simply returns ``str(x)``. + + The companion function :func:`~mpmath.nprint` prints the result + instead of returning it. + + The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed* + and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`. + + The number will be printed in fixed-point format if the position + of the leading digit is strictly between min_fixed + (default = min(-dps/3,-5)) and max_fixed (default = dps). + + To force fixed-point format always, set min_fixed = -inf, + max_fixed = +inf. To force floating-point format, set + min_fixed >= max_fixed. + + >>> from mpmath import * + >>> nstr([+pi, ldexp(1,-500)]) + '[3.14159, 3.05494e-151]' + >>> nprint([+pi, ldexp(1,-500)]) + [3.14159, 3.05494e-151] + >>> nstr(mpf("5e-10"), 5) + '5.0e-10' + >>> nstr(mpf("5e-10"), 5, strip_zeros=False) + '5.0000e-10' + >>> nstr(mpf("5e-10"), 5, strip_zeros=False, min_fixed=-11) + '0.00000000050000' + >>> nstr(mpf(0), 5, show_zero_exponent=True) + '0.0e+0' + + """ + if isinstance(x, list): + return "[%s]" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x)) + if isinstance(x, tuple): + return "(%s)" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x)) + if hasattr(x, '_mpf_'): + return to_str(x._mpf_, n, **kwargs) + if hasattr(x, '_mpc_'): + return "(" + mpc_to_str(x._mpc_, n, **kwargs) + ")" + if isinstance(x, basestring): + return repr(x) + if isinstance(x, ctx.matrix): + return x.__nstr__(n, **kwargs) + return str(x) + + def _convert_fallback(ctx, x, strings): + if strings and isinstance(x, basestring): + if 'j' in x.lower(): + x = x.lower().replace(' ', '') + match = get_complex.match(x) + re = match.group('re') + if not re: + re = 0 + im = match.group('im').rstrip('j') + return ctx.mpc(ctx.convert(re), ctx.convert(im)) + if hasattr(x, "_mpi_"): + a, b = x._mpi_ + if a == b: + return ctx.make_mpf(a) + else: + raise ValueError("can only create mpf from zero-width interval") + raise TypeError("cannot create mpf from " + repr(x)) + + def mpmathify(ctx, *args, **kwargs): + return ctx.convert(*args, **kwargs) + + def _parse_prec(ctx, kwargs): + if kwargs: + if kwargs.get('exact'): + return 0, 'f' + prec, rounding = ctx._prec_rounding + if 'rounding' in kwargs: + rounding = kwargs['rounding'] + if 'prec' in kwargs: + prec = kwargs['prec'] + if prec == ctx.inf: + return 0, 'f' + else: + prec = int(prec) + elif 'dps' in kwargs: + dps = kwargs['dps'] + if dps == ctx.inf: + return 0, 'f' + prec = dps_to_prec(dps) + return prec, rounding + return ctx._prec_rounding + + _exact_overflow_msg = "the exact result does not fit in memory" + + _hypsum_msg = """hypsum() failed to converge to the requested %i bits of accuracy +using a working precision of %i bits. Try with a higher maxprec, +maxterms, or set zeroprec.""" + + def hypsum(ctx, p, q, flags, coeffs, z, accurate_small=True, **kwargs): + if hasattr(z, "_mpf_"): + key = p, q, flags, 'R' + v = z._mpf_ + elif hasattr(z, "_mpc_"): + key = p, q, flags, 'C' + v = z._mpc_ + if key not in ctx.hyp_summators: + ctx.hyp_summators[key] = libmp.make_hyp_summator(key)[1] + summator = ctx.hyp_summators[key] + prec = ctx.prec + maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(prec)) + extraprec = 50 + epsshift = 25 + # Jumps in magnitude occur when parameters are close to negative + # integers. We must ensure that these terms are included in + # the sum and added accurately + magnitude_check = {} + max_total_jump = 0 + for i, c in enumerate(coeffs): + if flags[i] == 'Z': + if i >= p and c <= 0: + ok = False + for ii, cc in enumerate(coeffs[:p]): + # Note: c <= cc or c < cc, depending on convention + if flags[ii] == 'Z' and cc <= 0 and c <= cc: + ok = True + if not ok: + raise ZeroDivisionError("pole in hypergeometric series") + continue + n, d = ctx.nint_distance(c) + n = -int(n) + d = -d + if i >= p and n >= 0 and d > 4: + if n in magnitude_check: + magnitude_check[n] += d + else: + magnitude_check[n] = d + extraprec = max(extraprec, d - prec + 60) + max_total_jump += abs(d) + while 1: + if extraprec > maxprec: + raise ValueError(ctx._hypsum_msg % (prec, prec+extraprec)) + wp = prec + extraprec + if magnitude_check: + mag_dict = dict((n,None) for n in magnitude_check) + else: + mag_dict = {} + zv, have_complex, magnitude = summator(coeffs, v, prec, wp, \ + epsshift, mag_dict, **kwargs) + cancel = -magnitude + jumps_resolved = True + if extraprec < max_total_jump: + for n in mag_dict.values(): + if (n is None) or (n < prec): + jumps_resolved = False + break + accurate = (cancel < extraprec-25-5 or not accurate_small) + if jumps_resolved: + if accurate: + break + # zero? + zeroprec = kwargs.get('zeroprec') + if zeroprec is not None: + if cancel > zeroprec: + if have_complex: + return ctx.mpc(0) + else: + return ctx.zero + + # Some near-singularities were not included, so increase + # precision and repeat until they are + extraprec *= 2 + # Possible workaround for bad roundoff in fixed-point arithmetic + epsshift += 5 + extraprec += 5 + + if type(zv) is tuple: + if have_complex: + return ctx.make_mpc(zv) + else: + return ctx.make_mpf(zv) + else: + return zv + + def ldexp(ctx, x, n): + r""" + Computes `x 2^n` efficiently. No rounding is performed. + The argument `x` must be a real floating-point number (or + possible to convert into one) and `n` must be a Python ``int``. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> ldexp(1, 10) + mpf('1024.0') + >>> ldexp(1, -3) + mpf('0.125') + + """ + x = ctx.convert(x) + return ctx.make_mpf(libmp.mpf_shift(x._mpf_, n)) + + def frexp(ctx, x): + r""" + Given a real number `x`, returns `(y, n)` with `y \in [0.5, 1)`, + `n` a Python integer, and such that `x = y 2^n`. No rounding is + performed. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> frexp(7.5) + (mpf('0.9375'), 3) + + """ + x = ctx.convert(x) + y, n = libmp.mpf_frexp(x._mpf_) + return ctx.make_mpf(y), n + + def fneg(ctx, x, **kwargs): + """ + Negates the number *x*, giving a floating-point result, optionally + using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + An mpmath number is returned:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fneg(2.5) + mpf('-2.5') + >>> fneg(-5+2j) + mpc(real='5.0', imag='-2.0') + + Precise control over rounding is possible:: + + >>> x = fadd(2, 1e-100, exact=True) + >>> fneg(x) + mpf('-2.0') + >>> fneg(x, rounding='f') + mpf('-2.0000000000000004') + + Negating with and without roundoff:: + + >>> n = 200000000000000000000001 + >>> print(int(-mpf(n))) + -200000000000000016777216 + >>> print(int(fneg(n))) + -200000000000000016777216 + >>> print(int(fneg(n, prec=log(n,2)+1))) + -200000000000000000000001 + >>> print(int(fneg(n, dps=log(n,10)+1))) + -200000000000000000000001 + >>> print(int(fneg(n, prec=inf))) + -200000000000000000000001 + >>> print(int(fneg(n, dps=inf))) + -200000000000000000000001 + >>> print(int(fneg(n, exact=True))) + -200000000000000000000001 + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + if hasattr(x, '_mpf_'): + return ctx.make_mpf(mpf_neg(x._mpf_, prec, rounding)) + if hasattr(x, '_mpc_'): + return ctx.make_mpc(mpc_neg(x._mpc_, prec, rounding)) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fadd(ctx, x, y, **kwargs): + """ + Adds the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + The default precision is the working precision of the context. + You can specify a custom precision in bits by passing the *prec* keyword + argument, or by providing an equivalent decimal precision with the *dps* + keyword argument. If the precision is set to ``+inf``, or if the flag + *exact=True* is passed, an exact addition with no rounding is performed. + + When the precision is finite, the optional *rounding* keyword argument + specifies the direction of rounding. Valid options are ``'n'`` for + nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'`` + for down, ``'u'`` for up. + + **Examples** + + Using :func:`~mpmath.fadd` with precision and rounding control:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fadd(2, 1e-20) + mpf('2.0') + >>> fadd(2, 1e-20, rounding='u') + mpf('2.0000000000000004') + >>> nprint(fadd(2, 1e-20, prec=100), 25) + 2.00000000000000000001 + >>> nprint(fadd(2, 1e-20, dps=15), 25) + 2.0 + >>> nprint(fadd(2, 1e-20, dps=25), 25) + 2.00000000000000000001 + >>> nprint(fadd(2, 1e-20, exact=True), 25) + 2.00000000000000000001 + + Exact addition avoids cancellation errors, enforcing familiar laws + of numbers such as `x+y-x = y`, which don't hold in floating-point + arithmetic with finite precision:: + + >>> x, y = mpf(2), mpf('1e-1000') + >>> print(x + y - x) + 0.0 + >>> print(fadd(x, y, prec=inf) - x) + 1.0e-1000 + >>> print(fadd(x, y, exact=True) - x) + 1.0e-1000 + + Exact addition can be inefficient and may be impossible to perform + with large magnitude differences:: + + >>> fadd(1, '1e-100000000000000000000', prec=inf) + Traceback (most recent call last): + ... + OverflowError: the exact result does not fit in memory + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + y = ctx.convert(y) + try: + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_add(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_add_mpf(y._mpc_, x._mpf_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_add_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_add(x._mpc_, y._mpc_, prec, rounding)) + except (ValueError, OverflowError): + raise OverflowError(ctx._exact_overflow_msg) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fsub(ctx, x, y, **kwargs): + """ + Subtracts the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + Using :func:`~mpmath.fsub` with precision and rounding control:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fsub(2, 1e-20) + mpf('2.0') + >>> fsub(2, 1e-20, rounding='d') + mpf('1.9999999999999998') + >>> nprint(fsub(2, 1e-20, prec=100), 25) + 1.99999999999999999999 + >>> nprint(fsub(2, 1e-20, dps=15), 25) + 2.0 + >>> nprint(fsub(2, 1e-20, dps=25), 25) + 1.99999999999999999999 + >>> nprint(fsub(2, 1e-20, exact=True), 25) + 1.99999999999999999999 + + Exact subtraction avoids cancellation errors, enforcing familiar laws + of numbers such as `x-y+y = x`, which don't hold in floating-point + arithmetic with finite precision:: + + >>> x, y = mpf(2), mpf('1e1000') + >>> print(x - y + y) + 0.0 + >>> print(fsub(x, y, prec=inf) + y) + 2.0 + >>> print(fsub(x, y, exact=True) + y) + 2.0 + + Exact addition can be inefficient and may be impossible to perform + with large magnitude differences:: + + >>> fsub(1, '1e-100000000000000000000', prec=inf) + Traceback (most recent call last): + ... + OverflowError: the exact result does not fit in memory + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + y = ctx.convert(y) + try: + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_sub(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_sub((x._mpf_, fzero), y._mpc_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_sub_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_sub(x._mpc_, y._mpc_, prec, rounding)) + except (ValueError, OverflowError): + raise OverflowError(ctx._exact_overflow_msg) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fmul(ctx, x, y, **kwargs): + """ + Multiplies the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + The result is an mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fmul(2, 5.0) + mpf('10.0') + >>> fmul(0.5j, 0.5) + mpc(real='0.0', imag='0.25') + + Avoiding roundoff:: + + >>> x, y = 10**10+1, 10**15+1 + >>> print(x*y) + 10000000001000010000000001 + >>> print(mpf(x) * mpf(y)) + 1.0000000001e+25 + >>> print(int(mpf(x) * mpf(y))) + 10000000001000011026399232 + >>> print(int(fmul(x, y))) + 10000000001000011026399232 + >>> print(int(fmul(x, y, dps=25))) + 10000000001000010000000001 + >>> print(int(fmul(x, y, exact=True))) + 10000000001000010000000001 + + Exact multiplication with complex numbers can be inefficient and may + be impossible to perform with large magnitude differences between + real and imaginary parts:: + + >>> x = 1+2j + >>> y = mpc(2, '1e-100000000000000000000') + >>> fmul(x, y) + mpc(real='2.0', imag='4.0') + >>> fmul(x, y, rounding='u') + mpc(real='2.0', imag='4.0000000000000009') + >>> fmul(x, y, exact=True) + Traceback (most recent call last): + ... + OverflowError: the exact result does not fit in memory + + """ + prec, rounding = ctx._parse_prec(kwargs) + x = ctx.convert(x) + y = ctx.convert(y) + try: + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_mul(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_mul_mpf(y._mpc_, x._mpf_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_mul_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_mul(x._mpc_, y._mpc_, prec, rounding)) + except (ValueError, OverflowError): + raise OverflowError(ctx._exact_overflow_msg) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def fdiv(ctx, x, y, **kwargs): + """ + Divides the numbers *x* and *y*, giving a floating-point result, + optionally using a custom precision and rounding mode. + + See the documentation of :func:`~mpmath.fadd` for a detailed description + of how to specify precision and rounding. + + **Examples** + + The result is an mpmath number:: + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fdiv(3, 2) + mpf('1.5') + >>> fdiv(2, 3) + mpf('0.66666666666666663') + >>> fdiv(2+4j, 0.5) + mpc(real='4.0', imag='8.0') + + The rounding direction and precision can be controlled:: + + >>> fdiv(2, 3, dps=3) # Should be accurate to at least 3 digits + mpf('0.6666259765625') + >>> fdiv(2, 3, rounding='d') + mpf('0.66666666666666663') + >>> fdiv(2, 3, prec=60) + mpf('0.66666666666666667') + >>> fdiv(2, 3, rounding='u') + mpf('0.66666666666666674') + + Checking the error of a division by performing it at higher precision:: + + >>> fdiv(2, 3) - fdiv(2, 3, prec=100) + mpf('-3.7007434154172148e-17') + + Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not + allowed since the quotient of two floating-point numbers generally + does not have an exact floating-point representation. (In the + future this might be changed to allow the case where the division + is actually exact.) + + >>> fdiv(2, 3, exact=True) + Traceback (most recent call last): + ... + ValueError: division is not an exact operation + + """ + prec, rounding = ctx._parse_prec(kwargs) + if not prec: + raise ValueError("division is not an exact operation") + x = ctx.convert(x) + y = ctx.convert(y) + if hasattr(x, '_mpf_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpf(mpf_div(x._mpf_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_div((x._mpf_, fzero), y._mpc_, prec, rounding)) + if hasattr(x, '_mpc_'): + if hasattr(y, '_mpf_'): + return ctx.make_mpc(mpc_div_mpf(x._mpc_, y._mpf_, prec, rounding)) + if hasattr(y, '_mpc_'): + return ctx.make_mpc(mpc_div(x._mpc_, y._mpc_, prec, rounding)) + raise ValueError("Arguments need to be mpf or mpc compatible numbers") + + def nint_distance(ctx, x): + r""" + Return `(n,d)` where `n` is the nearest integer to `x` and `d` is + an estimate of `\log_2(|x-n|)`. If `d < 0`, `-d` gives the precision + (measured in bits) lost to cancellation when computing `x-n`. + + >>> from mpmath import * + >>> n, d = nint_distance(5) + >>> print(n); print(d) + 5 + -inf + >>> n, d = nint_distance(mpf(5)) + >>> print(n); print(d) + 5 + -inf + >>> n, d = nint_distance(mpf(5.00000001)) + >>> print(n); print(d) + 5 + -26 + >>> n, d = nint_distance(mpf(4.99999999)) + >>> print(n); print(d) + 5 + -26 + >>> n, d = nint_distance(mpc(5,10)) + >>> print(n); print(d) + 5 + 4 + >>> n, d = nint_distance(mpc(5,0.000001)) + >>> print(n); print(d) + 5 + -19 + + """ + typx = type(x) + if typx in int_types: + return int(x), ctx.ninf + elif typx is rational.mpq: + p, q = x._mpq_ + n, r = divmod(p, q) + if 2*r >= q: + n += 1 + elif not r: + return n, ctx.ninf + # log(p/q-n) = log((p-nq)/q) = log(p-nq) - log(q) + d = bitcount(abs(p-n*q)) - bitcount(q) + return n, d + if hasattr(x, "_mpf_"): + re = x._mpf_ + im_dist = ctx.ninf + elif hasattr(x, "_mpc_"): + re, im = x._mpc_ + isign, iman, iexp, ibc = im + if iman: + im_dist = iexp + ibc + elif im == fzero: + im_dist = ctx.ninf + else: + raise ValueError("requires a finite number") + else: + x = ctx.convert(x) + if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"): + return ctx.nint_distance(x) + else: + raise TypeError("requires an mpf/mpc") + sign, man, exp, bc = re + mag = exp+bc + # |x| < 0.5 + if mag < 0: + n = 0 + re_dist = mag + elif man: + # exact integer + if exp >= 0: + n = man << exp + re_dist = ctx.ninf + # exact half-integer + elif exp == -1: + n = (man>>1)+1 + re_dist = 0 + else: + d = (-exp-1) + t = man >> d + if t & 1: + t += 1 + man = (t<>1 # int(t)>>1 + re_dist = exp+bitcount(man) + if sign: + n = -n + elif re == fzero: + re_dist = ctx.ninf + n = 0 + else: + raise ValueError("requires a finite number") + return n, max(re_dist, im_dist) + + def fprod(ctx, factors): + r""" + Calculates a product containing a finite number of factors (for + infinite products, see :func:`~mpmath.nprod`). The factors will be + converted to mpmath numbers. + + >>> from mpmath import * + >>> mp.dps = 15; mp.pretty = False + >>> fprod([1, 2, 0.5, 7]) + mpf('7.0') + + """ + orig = ctx.prec + try: + v = ctx.one + for p in factors: + v *= p + finally: + ctx.prec = orig + return +v + + def rand(ctx): + """ + Returns an ``mpf`` with value chosen randomly from `[0, 1)`. + The number of randomly generated bits in the mantissa is equal + to the working precision. + """ + return ctx.make_mpf(mpf_rand(ctx._prec)) + + def fraction(ctx, p, q): + """ + Given Python integers `(p, q)`, returns a lazy ``mpf`` representing + the fraction `p/q`. The value is updated with the precision. + + >>> from mpmath import * + >>> mp.dps = 15 + >>> a = fraction(1,100) + >>> b = mpf(1)/100 + >>> print(a); print(b) + 0.01 + 0.01 + >>> mp.dps = 30 + >>> print(a); print(b) # a will be accurate + 0.01 + 0.0100000000000000002081668171172 + >>> mp.dps = 15 + """ + return ctx.constant(lambda prec, rnd: from_rational(p, q, prec, rnd), + '%s/%s' % (p, q)) + + def absmin(ctx, x): + return abs(ctx.convert(x)) + + def absmax(ctx, x): + return abs(ctx.convert(x)) + + def _as_points(ctx, x): + # XXX: remove this? + if hasattr(x, '_mpi_'): + a, b = x._mpi_ + return [ctx.make_mpf(a), ctx.make_mpf(b)] + return x + + ''' + def _zetasum(ctx, s, a, b): + """ + Computes sum of k^(-s) for k = a, a+1, ..., b with a, b both small + integers. + """ + a = int(a) + b = int(b) + s = ctx.convert(s) + prec, rounding = ctx._prec_rounding + if hasattr(s, '_mpf_'): + v = ctx.make_mpf(libmp.mpf_zetasum(s._mpf_, a, b, prec)) + elif hasattr(s, '_mpc_'): + v = ctx.make_mpc(libmp.mpc_zetasum(s._mpc_, a, b, prec)) + return v + ''' + + def _zetasum_fast(ctx, s, a, n, derivatives=[0], reflect=False): + if not (ctx.isint(a) and hasattr(s, "_mpc_")): + raise NotImplementedError + a = int(a) + prec = ctx._prec + xs, ys = libmp.mpc_zetasum(s._mpc_, a, n, derivatives, reflect, prec) + xs = [ctx.make_mpc(x) for x in xs] + ys = [ctx.make_mpc(y) for y in ys] + return xs, ys + +class PrecisionManager: + def __init__(self, ctx, precfun, dpsfun, normalize_output=False): + self.ctx = ctx + self.precfun = precfun + self.dpsfun = dpsfun + self.normalize_output = normalize_output + def __call__(self, f): + @functools.wraps(f) + def g(*args, **kwargs): + orig = self.ctx.prec + try: + if self.precfun: + self.ctx.prec = self.precfun(self.ctx.prec) + else: + self.ctx.dps = self.dpsfun(self.ctx.dps) + if self.normalize_output: + v = f(*args, **kwargs) + if type(v) is tuple: + return tuple([+a for a in v]) + return +v + else: + return f(*args, **kwargs) + finally: + self.ctx.prec = orig + return g + def __enter__(self): + self.origp = self.ctx.prec + if self.precfun: + self.ctx.prec = self.precfun(self.ctx.prec) + else: + self.ctx.dps = self.dpsfun(self.ctx.dps) + def __exit__(self, exc_type, exc_val, exc_tb): + self.ctx.prec = self.origp + return False + + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/shared/package-files/77/777c8b07f4a46ab0ec688d1e0ad39fe0fee2292fcf0510fbdeadb122d3dd9953/blob b/shared/package-files/77/777c8b07f4a46ab0ec688d1e0ad39fe0fee2292fcf0510fbdeadb122d3dd9953/blob new file mode 100644 index 0000000000000000000000000000000000000000..dc8353d6172990b5be63f27dfb798605095f425e --- /dev/null +++ b/shared/package-files/77/777c8b07f4a46ab0ec688d1e0ad39fe0fee2292fcf0510fbdeadb122d3dd9953/blob @@ -0,0 +1,560 @@ +from collections import namedtuple +from typing import Optional, Any, Union, Type + +import torch +import torch.nn as nn +from torch.ao.quantization.fake_quantize import ( + FakeQuantize, + FakeQuantizeBase, + default_fake_quant, + default_dynamic_fake_quant, + default_per_channel_weight_fake_quant, + default_weight_fake_quant, + default_fused_act_fake_quant, + default_fused_wt_fake_quant, + FusedMovingAvgObsFakeQuantize, + default_fused_per_channel_wt_fake_quant, + default_embedding_fake_quant, + default_embedding_fake_quant_4bit, + fused_wt_fake_quant_range_neg_127_to_127, + fused_per_channel_wt_fake_quant_range_neg_127_to_127, +) + +from .observer import ( + _PartialWrapper, + MinMaxObserver, + HistogramObserver, + MovingAverageMinMaxObserver, + NoopObserver, + PlaceholderObserver, + ReuseInputObserver, + default_debug_observer, + default_dynamic_quant_observer, + default_float_qparams_observer, + default_float_qparams_observer_4bit, + default_observer, + default_per_channel_weight_observer, + default_placeholder_observer, + default_weight_observer, + weight_observer_range_neg_127_to_127, + per_channel_weight_observer_range_neg_127_to_127, + default_reuse_input_observer, + ObserverBase, +) +import warnings +import copy + +__all__ = [ + "QConfig", + # TODO: deprecated, remove + "QConfigDynamic", + "default_qconfig", + "default_debug_qconfig", + "default_per_channel_qconfig", + "default_dynamic_qconfig", + "float16_dynamic_qconfig", + "float16_static_qconfig", + "per_channel_dynamic_qconfig", + "float_qparams_weight_only_qconfig", + "float_qparams_weight_only_qconfig_4bit", + "default_quint8_weight_qconfig", + "default_qat_qconfig", + "default_dynamic_qat_qconfig", + "default_weight_only_qconfig", + "default_activation_only_qconfig", + "default_qat_qconfig_v2", + "default_reuse_input_qconfig", + "default_symmetric_qnnpack_qconfig", + "default_per_channel_symmetric_qnnpack_qconfig", + "default_symmetric_qnnpack_qat_qconfig", + "default_per_channel_symmetric_qnnpack_qat_qconfig", + "default_embedding_qat_qconfig", + "default_embedding_qat_qconfig_4bit", + "get_default_qconfig", + "get_default_qat_qconfig", + "get_default_qconfig_dict", + "get_default_qat_qconfig_dict", + "QConfigAny", + "qconfig_equals", + +] + +class QConfig(namedtuple('QConfig', ['activation', 'weight'])): + """ + Describes how to quantize a layer or a part of the network by providing + settings (observer classes) for activations and weights respectively. + + + Note that QConfig needs to contain observer **classes** (like MinMaxObserver) or a callable that returns + instances on invocation, not the concrete observer instances themselves. + Quantization preparation function will instantiate observers multiple times for each of the layers. + + + Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args` + method (that behaves like functools.partial):: + + my_qconfig = QConfig( + activation=MinMaxObserver.with_args(dtype=torch.qint8), + weight=default_observer.with_args(dtype=torch.qint8)) + + """ + def __new__(cls, activation, weight): + # catch common mistakes + if isinstance(activation, nn.Module) or isinstance(weight, nn.Module): + raise ValueError("QConfig received observer instance, please pass observer class instead. " + + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed") + return super().__new__(cls, activation, weight) + + +class QConfigDynamic(namedtuple('QConfigDynamic', ['activation', 'weight'])): + """ + Describes how to dynamically quantize a layer or a part of the network by providing + settings (observer classes) for weights. + + It's like QConfig, but for dynamic quantization. + + Note that QConfigDynamic needs to contain observer **classes** (like MinMaxObserver) or a callable that returns + instances on invocation, not the concrete observer instances themselves. + Quantization function will instantiate observers multiple times for each of the layers. + + Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args` + method (that behaves like functools.partial):: + + my_qconfig = QConfigDynamic(weight=default_observer.with_args(dtype=torch.qint8)) + """ + def __new__(cls, activation=torch.nn.Identity, weight=torch.nn.Identity): + # catch common mistakes + if isinstance(weight, nn.Module): + raise ValueError("QConfigDynamic received observer instance, please pass observer class instead. " + + "Use MyObserver.with_args(x=1) to override arguments to constructor if needed") + warnings.warn("QConfigDynamic is going to be deprecated in PyTorch 1.12, please use QConfig instead") + return super().__new__(cls, activation, weight) + + +default_qconfig = QConfig(activation=default_observer, + weight=default_weight_observer) +""" +Default qconfig configuration. +""" + +default_debug_qconfig = QConfig(weight=default_weight_observer, + activation=default_debug_observer) +""" +Default qconfig configuration for debugging. +""" + +default_per_channel_qconfig = QConfig(activation=default_observer, + weight=default_per_channel_weight_observer) +""" +Default qconfig configuration for per channel weight quantization. +""" + +default_dynamic_qconfig = QConfig(activation=default_dynamic_quant_observer, + weight=default_weight_observer) +""" +Default dynamic qconfig. +""" + +float16_dynamic_qconfig = QConfig(activation=PlaceholderObserver.with_args(dtype=torch.float16, is_dynamic=True), + weight=PlaceholderObserver.with_args(dtype=torch.float16)) +""" +Dynamic qconfig with weights quantized to `torch.float16`. +""" + +float16_static_qconfig = QConfig(activation=PlaceholderObserver.with_args(dtype=torch.float16), + weight=PlaceholderObserver.with_args(dtype=torch.float16)) +""" +Dynamic qconfig with both activations and weights quantized to `torch.float16`. +""" + +per_channel_dynamic_qconfig = QConfig(activation=default_dynamic_quant_observer, + weight=default_per_channel_weight_observer) +""" +Dynamic qconfig with weights quantized per channel. +""" + +float_qparams_weight_only_qconfig = QConfig( + activation=default_placeholder_observer, + weight=default_float_qparams_observer) +""" +Dynamic qconfig with weights quantized with a floating point zero_point. +""" + +float_qparams_weight_only_qconfig_4bit = QConfig( + activation=default_placeholder_observer, + weight=default_float_qparams_observer_4bit) + +default_qat_qconfig = QConfig(activation=default_fake_quant, + weight=default_weight_fake_quant) +""" +Default qconfig for QAT. +""" + +default_dynamic_qat_qconfig = QConfig(activation=default_dynamic_fake_quant, + weight=default_weight_fake_quant) +""" +Default qconfig for dynamic QAT. +""" + +default_weight_only_qconfig = QConfig(activation=torch.nn.Identity, + weight=default_weight_fake_quant) +""" +Default qconfig for quantizing weights only. +""" + +default_activation_only_qconfig = QConfig(activation=default_fake_quant, + weight=torch.nn.Identity) +""" +Default qconfig for quantizing activations only. +""" + +# QAT config that uses a fused observer + fake quant modules for optimized training performance. +# to modify the activation/weight observers, the default entries in fake_quantize.py can be modified. +default_qat_qconfig_v2 = QConfig(activation=default_fused_act_fake_quant, weight=default_fused_wt_fake_quant) +""" +Fused version of `default_qat_config`, has performance benefits. +""" + +default_reuse_input_qconfig = QConfig(activation=default_reuse_input_observer, + weight=NoopObserver) +""" +Default qconfig for operators that reuse the observers from input Tensor, e.g. reshape +""" + +def get_default_qconfig(backend='x86', version=0): + """ + Returns the default PTQ qconfig for the specified backend. + + Args: + * `backend` (str): a string representing the target backend. Currently supports + `x86` (default), `fbgemm`, `qnnpack` and `onednn`. + + Return: + qconfig + """ + supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"] + if backend not in supported_backends: + raise AssertionError( + "backend: " + str(backend) + + f" not supported. backend must be one of {supported_backends}" + ) + + if version == 0: + if backend == 'fbgemm': + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=True), + weight=default_per_channel_weight_observer) + elif backend == 'qnnpack': + # TODO: make this compatible with xnnpack constraints + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=False), + weight=default_weight_observer) + elif backend == 'onednn': + if not torch.cpu._is_cpu_support_vnni(): + warnings.warn( + "Default qconfig of oneDNN backend with reduce_range of false may have accuracy issues " + "on CPU without Vector Neural Network Instruction support.") + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=False), + weight=default_per_channel_weight_observer) + elif backend == 'x86': + qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=True), + weight=default_per_channel_weight_observer) + else: + # won't reach + qconfig = default_qconfig + else: + raise AssertionError("Version number: " + str(version) + + " in get_default_qconfig is not supported. Version number must be 0") + + return qconfig + +""" +Default, symmetric PTQ qconfig for the specified backend. And a per_channel +variant of the same. + +Symmetric here applies to signed weights with zero point = 0, and additional +value restrictions. The activations are also signed 8-bit integers with this +qconfig. + + * Once this change is merged [as of 3/17/22], with backend or qengine = + 'qnnpack', some quantized operators with this symmetric qconfig may use + operators from xnnpack library. + + ** Support to use xnnpack ops with `qnnpack` backed for asymmetric + qconfig (returned by get_default_qconfig()) is not available yet. + + * This qconfig uses signed activations and weights. Weights have added + restrictions such as zero point is forced to be 0, making the weights + symmetric, hence the name. And the 8-bit quantized values are + restricting to to [-127, +127], excluding -128. + + * xnnpack has a requantization scale value restriction, 0x1p-32 <= + requantization_scale < 256.0 where, `requantization_scale = (input_scale + * kernel_scale) / (output_scale)`. Using this eps (w/ assumed max value + of 256) is to prevent requantization_scale to go below xnnpack lower + threshold. +""" +default_symmetric_qnnpack_qconfig = QConfig(activation=HistogramObserver.with_args(dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=weight_observer_range_neg_127_to_127) + +default_per_channel_symmetric_qnnpack_qconfig = QConfig(activation=HistogramObserver.with_args(dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=per_channel_weight_observer_range_neg_127_to_127) + +default_embedding_qat_qconfig = QConfig(activation=NoopObserver.with_args(dtype=torch.float32), + weight=default_embedding_fake_quant) + +default_embedding_qat_qconfig_4bit = QConfig(activation=NoopObserver.with_args(dtype=torch.float32), + weight=default_embedding_fake_quant_4bit) + +default_quint8_weight_qconfig = QConfig(activation=HistogramObserver, weight=MinMaxObserver) + +def get_default_qat_qconfig(backend='x86', version=1): + """ + Returns the default QAT qconfig for the specified backend. + + Args: + * `backend` (str): a string representing the target backend. Currently supports + `x86` (default), `fbgemm`, `qnnpack` and `onednn`. + * `version`: version, for backwards compatibility. Can be `None` or `1`. + + Return: + qconfig + """ + supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"] + if backend not in supported_backends: + raise AssertionError( + "backend: " + str(backend) + + f" not supported. backend must be one of {supported_backends}" + ) + + # Histogram observer is too slow for quantization aware training + if version == 0: + if backend == 'fbgemm': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_per_channel_weight_fake_quant) + elif backend == 'qnnpack': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=False), + weight=default_weight_fake_quant) + elif backend == 'onednn': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255), + weight=default_per_channel_weight_fake_quant) + elif backend == 'x86': + qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_per_channel_weight_fake_quant) + else: + qconfig = default_qat_qconfig + # Use the fused observe + fake_quant modules for doing QAT. + elif version == 1: + if backend == 'fbgemm': + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_fused_per_channel_wt_fake_quant) + elif backend == 'qnnpack': + # TODO: make this compatible with xnnpack constraints + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=False), + weight=default_fused_wt_fake_quant) + elif backend == 'onednn': + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255), + weight=default_fused_per_channel_wt_fake_quant) + elif backend == 'x86': + qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=0, + quant_max=255, + reduce_range=True), + weight=default_fused_per_channel_wt_fake_quant) + else: + qconfig = default_qat_qconfig_v2 + else: + raise AssertionError("Version number: " + str(version) + + "in get_default_qat_qconfig is not supported. Version number must be 0 or 1") + + return qconfig + +""" +Default symmetric QAT qconfig for qnnpack. And its per channel weight variant. +""" +default_symmetric_qnnpack_qat_qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=fused_wt_fake_quant_range_neg_127_to_127) + +default_per_channel_symmetric_qnnpack_qat_qconfig = QConfig( + activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver, + quant_min=-128, + quant_max=127, + dtype=torch.qint8, + reduce_range=False, + eps=2 ** -12), + weight=fused_per_channel_wt_fake_quant_range_neg_127_to_127) + +_default_fp32_placeholder_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.float32), + weight=PlaceholderObserver.with_args(dtype=torch.float32) +) + +_default_quint8_placeholder_qconfig = QConfig( + activation=PlaceholderObserver.with_args(dtype=torch.quint8), + # operators using this qconfig doesn't have weights + weight=None, +) + +def get_default_qconfig_dict(backend='x86', version=0): + warnings.warn( + "torch.ao.quantization.get_default_qconfig_dict is deprecated and will be removed in " + "a future version. Please use torch.ao.quantization.get_default_qconfig_mapping instead.") + return torch.ao.quantization.get_default_qconfig_mapping(backend, version).to_dict() + +def get_default_qat_qconfig_dict(backend='x86', version=1): + warnings.warn( + "torch.ao.quantization.get_default_qat_qconfig_dict is deprecated and will be removed in " + "a future version. Please use torch.ao.quantization.get_default_qat_qconfig_mapping instead.") + return torch.ao.quantization.get_default_qat_qconfig_mapping(backend, version).to_dict() + +def _assert_valid_qconfig(qconfig: Optional[QConfig], + mod: torch.nn.Module) -> None: + """ + Verifies that this `qconfig` is valid. + """ + if qconfig is None: + return + is_conv_transpose_mod = ( + isinstance(mod, (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d))) + if is_conv_transpose_mod: + if qconfig.weight is None: + # for now, we assume that any qconfig for ConvTranspose without a weight is valid + return + example_observer = qconfig.weight() + is_per_channel = ( + isinstance(example_observer, (torch.ao.quantization.PerChannelMinMaxObserver, + torch.ao.quantization.MovingAveragePerChannelMinMaxObserver)) + ) + assert not is_per_channel, \ + 'Per channel weight observer is not supported yet for ConvTranspose{n}d.' + +QConfigAny = Optional[QConfig] +QConfigAny.__module__ = "torch.ao.quantization.qconfig" + +def _add_module_to_qconfig_obs_ctr( + qconfig: QConfigAny, + module: Optional[nn.Module]) -> Any: + r"""This is a helper function for use in quantization prepare that updates a qconfig so that + the constructors stored in the qconfig will create observers on the same device that + 'module' is on. This is intended to be used when the qconfigs are propagated to each + module in order to avoid potential device alignment issues. + + Args: + qconfig: QConfig with obs constructors stored in activation and weight + module: module which the qconfig is related to + + Return: + qconfig: configured so that obs constructors set to construct on the same device as module + """ + + if module is None or qconfig is None or qconfig._fields != ('activation', 'weight'): + return qconfig + + def get_factory_kwargs_based_on_module_device(): + assert isinstance(module, torch.nn.Module) + devices = {p.device for p in module.parameters()} | \ + {p.device for p in module.buffers()} + device = next(iter(devices)) if len(devices) > 0 else None + return None if device is None else {'device': device} + + def configure_constructor_to_put_obs_on_module_device(original_constructor): + try: + # check if constructor can accept factory_kwargs + check = original_constructor.with_args(factory_kwargs=None) + check() + return original_constructor.with_callable_args(factory_kwargs=get_factory_kwargs_based_on_module_device) + except AttributeError: # qconfig doesn't have activation or weight + return original_constructor + except TypeError: # the class doesn't accept factory_kwargs argument + return original_constructor + + activation = configure_constructor_to_put_obs_on_module_device(qconfig.activation) + weight = configure_constructor_to_put_obs_on_module_device(qconfig.weight) + + return QConfig(activation, weight) + +_ObserverOrFakeQuantizeConstructor = Union[_PartialWrapper, Type[ObserverBase], Type[FakeQuantizeBase]] + +def _obs_or_fq_ctr_equals(obs_or_fq1: _ObserverOrFakeQuantizeConstructor, obs_or_fq2: _ObserverOrFakeQuantizeConstructor): + if isinstance(obs_or_fq1, _PartialWrapper) and isinstance(obs_or_fq2, _PartialWrapper): + return _partial_wrapper_equals(obs_or_fq1, obs_or_fq2) + return obs_or_fq1 == obs_or_fq2 + +def _partial_wrapper_equals(obs_or_fq1: _PartialWrapper, obs_or_fq2: _PartialWrapper): + """ + Return whether the two partial wrappers are equal, + """ + # functools.partial has no __eq__ operator defined so '==' defaults to 'is' + obs_or_fq1_keywords = copy.copy(obs_or_fq1.p.keywords) + obs_or_fq2_keywords = copy.copy(obs_or_fq2.p.keywords) + keywords_equal = True + # compare observer constructor with _obs_or_fq_ctr_equals since direct compare would fail + if "observer" in obs_or_fq1_keywords and "observer" in obs_or_fq2_keywords: + keywords_equal = keywords_equal and _obs_or_fq_ctr_equals(obs_or_fq1_keywords["observer"], obs_or_fq2_keywords["observer"]) + obs_or_fq1_keywords.pop("observer") + obs_or_fq2_keywords.pop("observer") + keywords_equal = keywords_equal and obs_or_fq1_keywords == obs_or_fq2_keywords + return obs_or_fq1.p.func == obs_or_fq2.p.func and obs_or_fq1.p.args == obs_or_fq2.p.args and keywords_equal + +def qconfig_equals(q1: QConfigAny, q2: QConfigAny): + """ + Returns `True` if `q1` equals `q2`, and `False` otherwise. + """ + if q1 is None or q2 is None: + return q1 == q2 + else: + assert q1 is not None and q2 is not None + try: + # Qconfig weight and activation can be either a partial wrapper, + # or an observer class. Special handling is required (above) for + # comparing partial wrappers. + activation_same = _obs_or_fq_ctr_equals(q1.activation, q2.activation) + weight_same = _obs_or_fq_ctr_equals(q1.weight, q2.weight) + return activation_same and weight_same + except AttributeError: + return q1 == q2 + +def _activation_is_memoryless(qconfig: QConfig): + """ + Return whether the observer for activations defined in the given QConfig is memoryless. + This means a MovingAverage observer with averaging constant equal to 1. + """ + def _is_memoryless(observer): + return hasattr(observer, "averaging_constant") and observer.averaging_constant == 1 + act = qconfig.activation() + if isinstance(act, FakeQuantizeBase) and hasattr(act, "activation_post_process"): + return _is_memoryless(act.activation_post_process) + else: + return _is_memoryless(act) + +def _is_reuse_input_qconfig(qconfig: Optional[QConfig]): + return qconfig is not None and \ + isinstance(qconfig.activation(), ReuseInputObserver) and \ + isinstance(qconfig.weight(), NoopObserver) diff --git a/shared/package-files/77/777ddd197d779ba07ec20f249de659606bf34ef58887059f7fe962eed7ea1548/nn_utils.py b/shared/package-files/77/777ddd197d779ba07ec20f249de659606bf34ef58887059f7fe962eed7ea1548/nn_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bf465838f6a85751d75875886a815c810b849271 --- /dev/null +++ b/shared/package-files/77/777ddd197d779ba07ec20f249de659606bf34ef58887059f7fe962eed7ea1548/nn_utils.py @@ -0,0 +1,1205 @@ +""" nn_utils.py +""" +from __future__ import annotations +import copy +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import einsum, nn +from torch.nn import init +import torch_scatter +import dgl + + +from einops import rearrange, repeat, pack, unpack +from einops.layers.torch import Rearrange +from packaging.version import Version + + +if Version(torch.__version__) > Version('2.0.0'): + _TORCH_SP_SUPPORT = True # use torch built-in sparse +else: + try: + import torch_sparse + _TORCH_SP_SUPPORT = False # use torch_sparse package + except: + raise ModuleNotFoundError("Please either install torch_sparse or upgrade to a PyTorch version that supports " + "sparse-sparse matrix multiply") + +from dgl.backend import pytorch as dgl_F +import ms_pred.nn_utils.dgl_modules as dgl_mods + + +def get_clones(module, N): + return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) + + +def build_lr_scheduler( + optimizer, lr_decay_rate: float, decay_steps: int = 5000, warmup: int = 1000 +): + """build_lr_scheduler. + + Args: + optimizer: + lr_decay_rate (float): lr_decay_rate + decay_steps (int): decay_steps + warmup_steps (int): warmup_steps + """ + + def lr_lambda(step): + if step >= warmup: + # Adjust + step = step - warmup + rate = lr_decay_rate ** (step // decay_steps) + else: + rate = 1 - math.exp(-step / warmup) + return rate + + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda) + return scheduler + + +class MoleculeGNN(nn.Module): + """MoleculeGNN Module""" + + def __init__( + self, + hidden_size: int, + num_step_message_passing: int = 4, + gnn_node_feats: int = 74, + gnn_edge_feats: int = 4, # 12, + mpnn_type: str = "GGNN", + node_feat_symbol="h", + set_transform_layers: int = 2, + dropout: float = 0, + **kwargs + ): + """__init__. + Args: + hidden_size (int): Hidden size + num_mol_layers (int): Number of layers to encode for the molecule + """ + super().__init__() + self.hidden_size = hidden_size + self.gnn_edge_feats = gnn_edge_feats + self.gnn_node_feats = gnn_node_feats + self.node_feat_symbol = node_feat_symbol + self.dropout = dropout + + self.mpnn_type = mpnn_type + self.hidden_size = hidden_size + self.num_step_message_passing = num_step_message_passing + self.input_project = nn.Linear(self.gnn_node_feats, self.hidden_size) + + if self.mpnn_type == "GGNN": + self.gnn = GGNN( + hidden_size=self.hidden_size, + edge_feats=self.gnn_edge_feats, + node_feats=self.gnn_node_feats, + num_step_message_passing=num_step_message_passing, + ) + elif self.mpnn_type == "PNA": + self.gnn = PNA( + hidden_size=self.hidden_size, + edge_feats=self.gnn_edge_feats, + node_feats=self.gnn_node_feats, + num_step_message_passing=num_step_message_passing, + dropout=self.dropout, + ) + elif self.mpnn_type == "GINE": + self.gnn = GINE( + hidden_size=self.hidden_size, + edge_feats=self.gnn_edge_feats, + node_feats=self.gnn_node_feats, + num_step_message_passing=num_step_message_passing, + dropout=self.dropout, + ) + else: + raise ValueError() + + # Keeping d_head only to 2x increase in size to avoid memory. Orig + # transformer uses 4x + self.set_transformer = SetTransformerEncoder( + d_model=self.hidden_size, + n_heads=4, + d_head=self.hidden_size // 4, + d_ff=hidden_size, + n_layers=set_transform_layers, + ) + + def forward(self, g): + """encode batch of molecule graph""" + with g.local_scope(): + # Set initial hidden + ndata = g.ndata[self.node_feat_symbol] + edata = g.edata["e"] + h_init = self.input_project(ndata) + g.ndata.update({"_h": h_init}) + g.edata.update({"_e": edata}) + + if self.mpnn_type == "GGNN": + # Get graph output + output = self.gnn(g, "_h", "_e") + elif self.mpnn_type == "PNA": + # Get graph output + output = self.gnn(g, "_h", "_e") + elif self.mpnn_type == "GINE": + # Get graph output + output = self.gnn(g, "_h", "_e") + else: + raise NotImplementedError() + + output = self.set_transformer(g, output) + return output + + +class GINE(nn.Module): + def __init__( + self, + hidden_size=64, + edge_feats=4, + num_step_message_passing=4, + dropout=0, + **kwargs + ): + """GINE. + + Args: + input_size (int): Size of edge features into the graph + hidden_size (int): Hidden size + edge_feats (int): Number of edge feats. Must be onehot! + node_feats (int): Num of node feats (default 74) + num_step_message_passing (int): Number of message passing steps + dropout + """ + super().__init__() + + self.edge_transform = nn.Linear(edge_feats, hidden_size) + + self.layers = [] + for i in range(num_step_message_passing): + apply_fn = nn.Sequential( + nn.Linear(hidden_size, hidden_size), + nn.ReLU(), + nn.Linear(hidden_size, hidden_size), + ) + temp_layer = dgl_mods.GINEConv(apply_func=apply_fn, init_eps=0) + self.layers.append(temp_layer) + + self.layers = nn.ModuleList(self.layers) + self.bnorms = get_clones(nn.BatchNorm1d(hidden_size), num_step_message_passing) + self.dropouts = get_clones(nn.Dropout(dropout), num_step_message_passing) + + def forward(self, graph, nfeat_name="_h", efeat_name="_e"): + """forward. + + Args: + graph (dgl graph): Graph object + nfeat_name (str): Name of node feat data + efeat_name (str): Name of e feat + + Return: + h: Hidden state at each node + + + """ + node_feat, edge_feat = graph.ndata[nfeat_name], graph.edata[efeat_name] + edge_feat = self.edge_transform(edge_feat) + + for dropout, layer, norm in zip(self.dropouts, self.layers, self.bnorms): + layer_out = layer(graph, node_feat, edge_feat) + node_feat = F.relu(dropout(norm(layer_out))) + node_feat + + return node_feat + + +class GGNN(nn.Module): + def __init__( + self, hidden_size=64, edge_feats=4, num_step_message_passing=4, **kwargs + ): + """GGNN. + + Define a gated graph neural network + + This is very similar to the NNConv models. + + Args: + input_size (int): Size of edge features into the graph + hidden_size (int): Hidden size + edge_feats (int): Number of edge feats. Must be onehot! + node_feats (int): Num of node feats (default 74) + num_step_message_passing (int): Number of message passing steps + """ + super().__init__() + self.model = dgl_mods.GatedGraphConv( + in_feats=hidden_size, + out_feats=hidden_size, + n_steps=num_step_message_passing, + n_etypes=edge_feats, + ) + + def forward(self, graph, nfeat_name="_h", efeat_name="_e"): + """forward. + + Args: + graph (dgl graph): Graph object + nfeat_name (str): Name of node feat data + efeat_name (str): Name of e feat + + Return: + h: Hidden state at each node + + """ + if "e_ind" in graph.edata: + etypes = graph.edata["e_ind"] + else: + etypes = graph.edata[efeat_name].argmax(1) + return self.model(graph, graph.ndata[nfeat_name], etypes=etypes) + + +class PNA(nn.Module): + def __init__( + self, + hidden_size=64, + edge_feats=4, + num_step_message_passing=4, + dropout=0, + **kwargs + ): + """PNA. + + Define a PNA network + + Args: + input_size (int): Size of edge features into the graph + hidden_size (int): Hidden size + edge_feats (int): Number of edge feats. Must be onehot! + node_feats (int): Num of node feats (default 74) + num_step_message_passing (int): Number of message passing steps + """ + super().__init__() + self.layer = dgl_mods.PNAConv( + in_size=hidden_size, + out_size=hidden_size, + aggregators=["mean", "max", "min", "std", "var", "sum"], + scalers=["identity", "amplification", "attenuation"], + delta=2.5, + dropout=dropout, + ) + + self.layers = get_clones(self.layer, num_step_message_passing) + self.bnorms = get_clones(nn.BatchNorm1d(hidden_size), num_step_message_passing) + + def forward(self, graph, nfeat_name="_h", efeat_name="_e"): + """forward. + + Args: + graph (dgl graph): Graph object + nfeat_name (str): Name of node feat data + efeat_name (str): Name of e feat + + Return: + h: Hidden state at each node + + """ + node_feat, edge_feat = graph.ndata[nfeat_name], graph.edata[efeat_name] + for layer, norm in zip(self.layers, self.bnorms): + node_feat = F.relu(norm(layer(graph, node_feat, edge_feat))) + node_feat + + return node_feat + + +class MLPBlocks(nn.Module): + def __init__( + self, + input_size: int, + hidden_size: int, + dropout: float, + num_layers: int, + output_size: int = None, + use_residuals: bool = False, + use_batchnorm: bool = False, + ): + super().__init__() + self.activation = nn.ReLU() + self.dropout_layer = nn.Dropout(p=dropout) if dropout > 0 else nn.Identity() + self.input_layer = nn.Linear(input_size, hidden_size) + middle_layer = nn.Linear(hidden_size, hidden_size) + self.layers = get_clones(middle_layer, num_layers - 1) + + self.output_layer = None + self.output_size = output_size + if self.output_size is not None: + self.output_layer = nn.Linear(hidden_size, self.output_size) + + self.use_residuals = use_residuals + self.use_batchnorm = use_batchnorm + if self.use_batchnorm: + self.bn_input = nn.BatchNorm1d(hidden_size) + bn = nn.BatchNorm1d(hidden_size) + self.bn_mids = get_clones(bn, num_layers - 1) + + def safe_apply_bn(self, x, bn): + """transpose and untranspose after linear for 3 dim items to us + batchnorm""" + temp_shape = x.shape + if len(x.shape) == 2: + return bn(x) + elif len(x.shape) == 3: + return bn(x.transpose(-1, -2)).transpose(-1, -2) + else: + raise NotImplementedError() + + def forward(self, x): + output = x + output = self.input_layer(x) + output = self.activation(output) + output = self.dropout_layer(output) + + if self.use_batchnorm: + output = self.safe_apply_bn(output, self.bn_input) + + old_op = output + for layer_index, layer in enumerate(self.layers): + output = layer(output) + output = self.activation(output) + output = self.dropout_layer(output) + + if self.use_batchnorm: + output = self.safe_apply_bn(output, self.bn_mids[layer_index]) + + if self.use_residuals: + # avoid in-place addition which can break autograd when + # tensors required for gradient computation are modified + output = output + old_op + old_op = output + + if self.output_layer is not None: + output = self.output_layer(output) + + return output + + +# DGL Models +# https://docs.dgl.ai/en/0.6.x/_modules/dgl/nn/pytorch/glob.html#SetTransformerDecoder + + +class MultiHeadAttention(nn.Module): + r"""Multi-Head Attention block, used in Transformer, Set Transformer and so on. + + Parameters + ---------- + d_model : int + The feature size (input and output) in Multi-Head Attention layer. + num_heads : int + The number of heads. + d_head : int + The hidden size per head. + d_ff : int + The inner hidden size in the Feed-Forward Neural Network. + dropouth : float + The dropout rate of each sublayer. + dropouta : float + The dropout rate of attention heads. + + Notes + ----- + This module was used in SetTransformer layer. + """ + + def __init__(self, d_model, num_heads, d_head, d_ff, dropouth=0.0, dropouta=0.0): + super(MultiHeadAttention, self).__init__() + self.d_model = d_model + self.num_heads = num_heads + self.d_head = d_head + self.d_ff = d_ff + self.proj_q = nn.Linear(d_model, num_heads * d_head, bias=False) + self.proj_k = nn.Linear(d_model, num_heads * d_head, bias=False) + self.proj_v = nn.Linear(d_model, num_heads * d_head, bias=False) + self.proj_o = nn.Linear(num_heads * d_head, d_model, bias=False) + self.ffn = nn.Sequential( + nn.Linear(d_model, d_ff), + nn.ReLU(), + nn.Dropout(dropouth), + nn.Linear(d_ff, d_model), + ) + self.droph = nn.Dropout(dropouth) + self.dropa = nn.Dropout(dropouta) + self.norm_in = nn.LayerNorm(d_model) + self.norm_inter = nn.LayerNorm(d_model) + self.reset_parameters() + + def reset_parameters(self): + """Reinitialize learnable parameters.""" + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def self_attention(self, x, mem, lengths_x, lengths_mem): + batch_size = len(lengths_x) + max_len_x = max(lengths_x) + max_len_mem = max(lengths_mem) + device = x.device + + lengths_x = lengths_x.clone().detach().long().to(device) + lengths_mem = lengths_mem.clone().detach().long().to(device) + + queries = self.proj_q(x).view(-1, self.num_heads, self.d_head) + keys = self.proj_k(mem).view(-1, self.num_heads, self.d_head) + values = self.proj_v(mem).view(-1, self.num_heads, self.d_head) + + # padding to (B, max_len_x/mem, num_heads, d_head) + queries = dgl_F.pad_packed_tensor(queries, lengths_x, 0) + keys = dgl_F.pad_packed_tensor(keys, lengths_mem, 0) + values = dgl_F.pad_packed_tensor(values, lengths_mem, 0) + + # attention score with shape (B, num_heads, max_len_x, max_len_mem) + e = torch.einsum("bxhd,byhd->bhxy", queries, keys) + # normalize + e = e / np.sqrt(self.d_head) + + # generate mask + mask = _gen_mask(lengths_x, lengths_mem, max_len_x, max_len_mem) + e = e.masked_fill(mask == 0, -float("inf")) + + # apply softmax + alpha = torch.softmax(e, dim=-1) + # the following line addresses the NaN issue, see + # https://github.com/dmlc/dgl/issues/2657 + alpha = alpha.masked_fill(mask == 0, 0.0) + + # sum of value weighted by alpha + out = torch.einsum("bhxy,byhd->bxhd", alpha, values) + # project to output + out = self.proj_o( + out.contiguous().view(batch_size, max_len_x, self.num_heads * self.d_head) + ) + # pack tensor + out = dgl_F.pack_padded_tensor(out, lengths_x) + return out + + def forward(self, x, mem, lengths_x, lengths_mem): + """ + Compute multi-head self-attention. + + Parameters + ---------- + x : torch.Tensor + The input tensor used to compute queries. + mem : torch.Tensor + The memory tensor used to compute keys and values. + lengths_x : list + The array of node numbers, used to segment x. + lengths_mem : list + The array of node numbers, used to segment mem. + """ + + ### Following a _pre_ transformer + + # intra norm + x = x + self.self_attention(self.norm_in(x), mem, lengths_x, lengths_mem) + + # inter norm + x = x + self.ffn(self.norm_inter(x)) + + ## intra norm + # x = self.norm_in(x + out) + + ## inter norm + # x = self.norm_inter(x + self.ffn(x)) + return x + + +class SetAttentionBlock(nn.Module): + r"""SAB block introduced in Set-Transformer paper. + + Parameters + ---------- + d_model : int + The feature size (input and output) in Multi-Head Attention layer. + num_heads : int + The number of heads. + d_head : int + The hidden size per head. + d_ff : int + The inner hidden size in the Feed-Forward Neural Network. + dropouth : float + The dropout rate of each sublayer. + dropouta : float + The dropout rate of attention heads. + + Notes + ----- + This module was used in SetTransformer layer. + """ + + def __init__(self, d_model, num_heads, d_head, d_ff, dropouth=0.0, dropouta=0.0): + super(SetAttentionBlock, self).__init__() + self.mha = MultiHeadAttention( + d_model, num_heads, d_head, d_ff, dropouth=dropouth, dropouta=dropouta + ) + + def forward(self, feat, lengths): + """ + Compute a Set Attention Block. + + Parameters + ---------- + feat : torch.Tensor + The input feature. + lengths : list + The array of node numbers, used to segment feat tensor. + """ + return self.mha(feat, feat, lengths, lengths) + + +class SetTransformerEncoder(nn.Module): + r""" + + Description + ----------- + The Encoder module in `Set Transformer: A Framework for Attention-based + Permutation-Invariant Neural Networks `__. + + Parameters + ---------- + d_model : int + The hidden size of the model. + n_heads : int + The number of heads. + d_head : int + The hidden size of each head. + d_ff : int + The kernel size in FFN (Positionwise Feed-Forward Network) layer. + n_layers : int + The number of layers. + block_type : str + Building block type: 'sab' (Set Attention Block) or 'isab' (Induced + Set Attention Block). + m : int or None + The number of induced vectors in ISAB Block. Set to None if block type + is 'sab'. + dropouth : float + The dropout rate of each sublayer. + dropouta : float + The dropout rate of attention heads. + + Examples + -------- + >>> import dgl + >>> import torch as th + >>> from dgl.nn import SetTransformerEncoder + >>> + >>> g1 = dgl.rand_graph(3, 4) # g1 is a random graph with 3 nodes and 4 edges + >>> g1_node_feats = torch.rand(3, 5) # feature size is 5 + >>> g1_node_feats + tensor([[0.8948, 0.0699, 0.9137, 0.7567, 0.3637], + [0.8137, 0.8938, 0.8377, 0.4249, 0.6118], + [0.5197, 0.9030, 0.6825, 0.5725, 0.4755]]) + >>> + >>> g2 = dgl.rand_graph(4, 6) # g2 is a random graph with 4 nodes and 6 edges + >>> g2_node_feats = torch.rand(4, 5) # feature size is 5 + >>> g2_node_feats + tensor([[0.2053, 0.2426, 0.4111, 0.9028, 0.5658], + [0.5278, 0.6365, 0.9990, 0.2351, 0.8945], + [0.3134, 0.0580, 0.4349, 0.7949, 0.3891], + [0.0142, 0.2709, 0.3330, 0.8521, 0.6925]]) + >>> + >>> set_trans_enc = SetTransformerEncoder(5, 4, 4, 20) # create a settrans encoder. + + Case 1: Input a single graph + + >>> set_trans_enc(g1, g1_node_feats) + tensor([[ 0.1262, -1.9081, 0.7287, 0.1678, 0.8854], + [-0.0634, -1.1996, 0.6955, -0.9230, 1.4904], + [-0.9972, -0.7924, 0.6907, -0.5221, 1.6211]], + grad_fn=) + + Case 2: Input a batch of graphs + + Build a batch of DGL graphs and concatenate all graphs' node features into one tensor. + + >>> batch_g = dgl.batch([g1, g2]) + >>> batch_f = torch.cat([g1_node_feats, g2_node_feats]) + >>> + >>> set_trans_enc(batch_g, batch_f) + tensor([[ 0.1262, -1.9081, 0.7287, 0.1678, 0.8854], + [-0.0634, -1.1996, 0.6955, -0.9230, 1.4904], + [-0.9972, -0.7924, 0.6907, -0.5221, 1.6211], + [-0.7973, -1.3203, 0.0634, 0.5237, 1.5306], + [-0.4497, -1.0920, 0.8470, -08030, 1.4977], + [-0.4940, -1.6045, 0.2363, 0.4885, 1.3737], + [-0.9840, -1.0913, -0.0099, 0.4653, 1.6199]], + grad_fn=) + + See Also + -------- + SetTransformerDecoder + + Notes + ----- + SetTransformerEncoder is not a readout layer, the tensor it returned is nodewise + representation instead out graphwise representation, and the SetTransformerDecoder + would return a graph readout tensor. + """ + + def __init__( + self, + d_model, + n_heads, + d_head, + d_ff, + n_layers=1, + block_type="sab", + m=None, + dropouth=0.0, + dropouta=0.0, + ): + super(SetTransformerEncoder, self).__init__() + self.n_layers = n_layers + self.block_type = block_type + self.m = m + layers = [] + if block_type == "isab" and m is None: + raise KeyError( + "The number of inducing points is not specified in ISAB block." + ) + + for _ in range(n_layers): + if block_type == "sab": + layers.append( + SetAttentionBlock( + d_model, + n_heads, + d_head, + d_ff, + dropouth=dropouth, + dropouta=dropouta, + ) + ) + elif block_type == "isab": + # layers.append( + # InducedSetAttentionBlock(m, d_model, n_heads, d_head, d_ff, + # dropouth=dropouth, dropouta=dropouta)) + raise NotImplementedError() + else: + raise KeyError("Unrecognized block type {}: we only support sab/isab") + + self.layers = nn.ModuleList(layers) + + def forward(self, graph, feat): + """ + Compute the Encoder part of Set Transformer. + + Parameters + ---------- + graph : DGLGraph + The input graph. + feat : torch.Tensor + The input feature with shape :math:`(N, D)`, where :math:`N` is the + number of nodes in the graph. + + Returns + ------- + torch.Tensor + The output feature with shape :math:`(N, D)`. + """ + lengths = graph.batch_num_nodes() + for layer in self.layers: + feat = layer(feat, lengths) + return feat + +class SlotDecoder(nn.Module): + def __init__(self, hidden_dim=256, num_slots=40, nhead=8, num_layers=3, dropout=0.1, enable_norm=False): + super().__init__() + self.num_slots = num_slots + + # Learnable slot embeddings + self.slots = nn.Parameter(torch.empty(num_slots, hidden_dim)) + # init.xavier_uniform_(self.slots) + + init.orthogonal_(self.slots, gain=0.02) + self.dropout = dropout + + # Transformer decoder layers + decoder_layer = nn.TransformerDecoderLayer( + d_model=hidden_dim, + nhead=nhead, + dim_feedforward=hidden_dim * 4, + batch_first=True, + dropout=self.dropout + ) + self.hidden_dim=hidden_dim + self.num_layers = num_layers + self.enable_norm = enable_norm + self.decoder_norm = nn.LayerNorm(hidden_dim) if self.enable_norm else None + self.decoder_layers = get_clones(decoder_layer, self.num_layers) + # self.decoder = nn.TransformerDecoder(decoder_layer, num_layers=num_layers) + + def forward(self, graph_tokens, node_embeddings, memory_key_padding_mask=None): + """ + graph_tokens: [B, 1, d] + node_embeddings: [B, N, d] + """ + B, N, d = node_embeddings.size() + slots = self.slots.unsqueeze(0).expand(B, self.num_slots, self.hidden_dim) + # # Use both graph token and nodes as memory for decoder + memory = torch.cat([graph_tokens, node_embeddings], dim=1) # [B, 1+N, d] + outs = [] + for decoder_layer in self.decoder_layers: + slots = decoder_layer(tgt=slots, memory=memory, memory_key_padding_mask=memory_key_padding_mask) # [B, K, d] + if self.enable_norm: + outs.append(self.decoder_norm(slots)) + else: + outs.append(slots) + return torch.stack(outs, dim=0) + +class SlotAttention(nn.Module): + def __init__(self, num_slots, dim, iters = 3, eps = 1e-8, hidden_dim = 128): + super().__init__() + self.num_slots = num_slots + self.iters = iters + self.eps = eps + self.scale = dim ** -0.5 + + self.slots_mu = nn.Parameter(torch.randn(1, 1, dim)) + self.slots_sigma = nn.Parameter(torch.rand(1, 1, dim)) + + self.to_q = nn.Linear(dim, dim) + self.to_k = nn.Linear(dim, dim) + self.to_v = nn.Linear(dim, dim) + + self.gru = nn.GRUCell(dim, dim) + + hidden_dim = max(dim, hidden_dim) + + self.fc1 = nn.Linear(dim, hidden_dim) + self.fc2 = nn.Linear(hidden_dim, dim) + + self.norm_input = nn.LayerNorm(dim) + self.norm_slots = nn.LayerNorm(dim) + self.norm_pre_ff = nn.LayerNorm(dim) + + def forward(self, inputs, num_slots = None, key_padding_mask=None): + """ + inputs: [B, N, D] + key_padding_mask: [B, N] (bool), True for positions to ignore (masked) + """ + b, n, d = inputs.shape + n_s = num_slots if num_slots is not None else self.num_slots + + mu = self.slots_mu.expand(b, n_s, -1) + sigma = self.slots_sigma.expand(b, n_s, -1) + slots = torch.normal(mu, sigma) + + inputs = self.norm_input(inputs) + k, v = self.to_k(inputs), self.to_v(inputs) + + if key_padding_mask is not None: + # key_padding_mask: [B, N], True for masked positions + # We'll use this to mask attention logits later + mask = key_padding_mask.unsqueeze(1) # [B, 1, N] + else: + mask = None + + for _ in range(self.iters): + slots_prev = slots + + slots = self.norm_slots(slots) + q = self.to_q(slots) + + dots = torch.einsum('bid,bjd->bij', q, k) * self.scale # [B, num_slots, N] + if mask is not None: + dots = dots.masked_fill(mask, float('-inf')) + + attn = dots.softmax(dim=-1) + self.eps + attn = attn / attn.sum(dim=-1, keepdim=True) + + updates = torch.einsum('bjd,bij->bid', v, attn) + + slots = self.gru( + updates.reshape(-1, d), + slots_prev.reshape(-1, d) + ) + + slots = slots.reshape(b, -1, d) + slots = slots + self.fc2(F.relu(self.fc1(self.norm_pre_ff(slots)))) + + return slots + +class MultiHeadSlotAttention(nn.Module): + def __init__( + self, + num_slots, + dim, + heads = 4, + dim_head = 64, + iters = 3, + eps = 1e-8, + hidden_dim = 128 + ): + super().__init__() + self.dim = dim + self.num_slots = num_slots + self.iters = iters + self.eps = eps + self.scale = dim ** -0.5 + + self.slots_mu = nn.Parameter(torch.randn(1, 1, dim)) + + self.slots_logsigma = nn.Parameter(torch.zeros(1, 1, dim)) + init.xavier_uniform_(self.slots_logsigma) + + self.norm_input = nn.LayerNorm(dim) + self.norm_slots = nn.LayerNorm(dim) + + dim_inner = dim_head * heads + + self.split_heads = Rearrange('b n (h d) -> b h n d', h = heads) + + self.to_q = nn.Linear(dim, dim_inner) + self.to_k = nn.Linear(dim, dim_inner) + self.to_v = nn.Linear(dim, dim_inner) + + self.merge_heads = Rearrange('b h n d -> b n (h d)') + self.combine_heads = nn.Linear(dim_inner, dim) + + self.gru = nn.GRUCell(dim, dim) + + hidden_dim = max(dim, hidden_dim) + + self.norm_pre_ff = nn.LayerNorm(dim) + + self.mlp = nn.Sequential( + nn.Linear(dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, dim) + ) + + def forward( + self, + inputs, + num_slots: int | None = None, + key_padding_mask=None + ): + b, n, d, device, dtype = *inputs.shape, inputs.device, inputs.dtype + n_s = num_slots if num_slots is not None else self.num_slots + + mu = repeat(self.slots_mu, '1 1 d -> b s d', b = b, s = n_s) + sigma = repeat(self.slots_logsigma.exp(), '1 1 d -> b s d', b = b, s = n_s) + + slots = mu + sigma * torch.randn(mu.shape, device = device, dtype = dtype) + + inputs = self.norm_input(inputs) + + k, v = self.to_k(inputs), self.to_v(inputs) + k, v = map(self.split_heads, (k, v)) + + # Apply key_padding_mask to attention logits if provided + if key_padding_mask is not None: + # key_padding_mask: [B, N], True for masked positions + # We need to expand to [B, 1, N] for broadcasting with dots + mask = key_padding_mask + else: + mask = None + + for _ in range(self.iters): + slots_prev = slots + + slots = self.norm_slots(slots) + + q = self.to_q(slots) + q = self.split_heads(q) + + dots = einsum('... i d, ... j d -> ... i j', q, k) * self.scale # [B, heads, num_slots, N] + + if mask is not None: + # mask: [B, 1, N], dots: [B, heads, num_slots, N] + # Broadcast mask to all heads and slots + # dots = dots.masked_fill(mask.unsqueeze(1).unsqueeze(2), float('-inf')) + dots = dots.masked_fill(mask.unsqueeze(1).unsqueeze(2), -99999) + + attn = dots.softmax(dim = -2) + attn = F.normalize(attn + self.eps, p = 1, dim = -1) + + updates = einsum('... j d, ... i j -> ... i d', v, attn) + assert updates.ndim == 4, f"Expected 4D tensor, got {updates.shape}" + updates = self.merge_heads(updates) + updates = self.combine_heads(updates) + + updates, packed_shape = pack([updates], '* d') + slots_prev, _ = pack([slots_prev], '* d') + + slots = self.gru(updates, slots_prev) + + slots, = unpack(slots, packed_shape, '* d') + slots = slots + self.mlp(self.norm_pre_ff(slots)) + + return slots + +class SlotAttentionDecoder(nn.Module): + """ + SlotAttentionDecoder: SlotAttention with self-attention on slots before cross-attention to inputs. + Now supports multi-head attention for both self-attention and cross-attention. + """ + def __init__(self, num_slots, dim, iters=3, eps=1e-8, hidden_dim=128, attn_heads=1): + super().__init__() + self.num_slots = num_slots + self.iters = iters + self.eps = eps + self.scale = dim ** -0.5 + self.attn_heads = attn_heads + + self.slots_mu = nn.Parameter(torch.randn(1, 1, dim)) + self.slots_sigma = nn.Parameter(torch.rand(1, 1, dim)) + + self.to_q = nn.Linear(dim, dim) + self.to_k = nn.Linear(dim, dim) + self.to_v = nn.Linear(dim, dim) + + self.gru = nn.GRUCell(dim, dim) + + hidden_dim = max(dim, hidden_dim) + self.fc1 = nn.Linear(dim, hidden_dim) + self.fc2 = nn.Linear(hidden_dim, dim) + + self.norm_input = nn.LayerNorm(dim) + self.norm_slots = nn.LayerNorm(dim) + self.norm_pre_ff = nn.LayerNorm(dim) + + # Self-attention for slots + self.self_attn = nn.MultiheadAttention(embed_dim=dim, num_heads=self.attn_heads, batch_first=True) + # Cross-attention for slots-to-inputs + self.cross_attn = nn.MultiheadAttention(embed_dim=dim, num_heads=self.attn_heads, batch_first=True) + + def forward(self, inputs, num_slots=None, key_padding_mask=None): + """ + inputs: [B, N, D] + key_padding_mask: [B, N] (bool), True for positions to ignore (masked) + """ + b, n, d = inputs.shape + n_s = num_slots if num_slots is not None else self.num_slots + + mu = self.slots_mu.expand(b, n_s, -1) + sigma = self.slots_sigma.expand(b, n_s, -1) + slots = torch.normal(mu, sigma) + + inputs = self.norm_input(inputs) + k, v = self.to_k(inputs), self.to_v(inputs) + + for _ in range(self.iters): + slots_prev = slots + + # Self-attention on slots + slots_norm = self.norm_slots(slots) + slots_sa, _ = self.self_attn(slots_norm, slots_norm, slots_norm) + slots = slots + slots_sa + + # Cross-attention: slots as queries, inputs as keys/values + # MultiheadAttention expects [B, num_slots, D] for query, [B, N, D] for key/value + # key_padding_mask: [B, N] (True for masked) + cross_attn_out, _ = self.cross_attn( + query=slots, key=k, value=v, key_padding_mask=key_padding_mask + ) + slots = slots + cross_attn_out + + # Feedforward and GRU update + + slots = self.gru( + slots.reshape(-1, d), + slots_prev.reshape(-1, d) + ) + + slots = slots.reshape(b, -1, d) + slots = slots + self.fc2(F.relu(self.fc1(self.norm_pre_ff(slots)))) + + return slots + + + +def _gen_mask(lengths_x, lengths_y, max_len_x, max_len_y): + """Generate binary mask array for given x and y input pairs. + + Parameters + ---------- + lengths_x : Tensor + The int tensor indicates the segment information of x. + lengths_y : Tensor + The int tensor indicates the segment information of y. + max_len_x : int + The maximum element in lengths_x. + max_len_y : int + The maximum element in lengths_y. + + Returns + ------- + Tensor + the mask tensor with shape (batch_size, 1, max_len_x, max_len_y) + """ + device = lengths_x.device + # x_mask: (batch_size, max_len_x) + x_mask = torch.arange(max_len_x, device=device).unsqueeze(0) < lengths_x.unsqueeze( + 1 + ) + # y_mask: (batch_size, max_len_y) + y_mask = torch.arange(max_len_y, device=device).unsqueeze(0) < lengths_y.unsqueeze( + 1 + ) + # mask: (batch_size, 1, max_len_x, max_len_y) + mask = (x_mask.unsqueeze(-1) & y_mask.unsqueeze(-2)).unsqueeze(1) + return mask + + +def pad_packed_tensor(input, lengths, value): + """pad_packed_tensor""" + old_shape = input.shape + device = input.device + if not isinstance(lengths, torch.Tensor): + lengths = lengths.clone().detach().long().to(device) + else: + lengths = lengths.to(device) + max_len = (lengths.max()).item() + + batch_size = len(lengths) + x = input.new(batch_size * max_len, *old_shape[1:]) + x.fill_(value) + + # Initialize a tensor with an index for every value in the array + index = torch.ones(len(input), dtype=torch.int64, device=device) + + # Row shifts + row_shifts = torch.cumsum(max_len - lengths, 0) + + # Calculate shifts for second row, third row... nth row (not the n+1th row) + # Expand this out to match the shape of all entries after the first row + row_shifts_expanded = row_shifts[:-1].repeat_interleave(lengths[1:]) + + # Add this to the list of inds _after_ the first row + cumsum_inds = torch.cumsum(index, 0) - 1 + cumsum_inds[lengths[0] :] += row_shifts_expanded + x[cumsum_inds] = input + return x.view(batch_size, max_len, *old_shape[1:]) + +def pack_padded_tensor(input, lengths): + """pack_padded_tensor""" + device = input.device + if not isinstance(lengths, torch.Tensor): + lengths = lengths.clone().detach().long().to(device) + else: + lengths = lengths.to(device) + max_len = (lengths.max()).item() + + batch_size = len(lengths) + packed_tensors = [] + for i in range(batch_size): + packed_tensors.append(input[i, :lengths[i].item()]) + packed_tensors = torch.cat(packed_tensors) + return packed_tensors + + + +def random_walk_pe(g, k, eweight_name=None): + """Random Walk Positional Encoding, as introduced in + `Graph Neural Networks with Learnable Structural and Positional Representations + `__ + + This function computes the random walk positional encodings as landing probabilities + from 1-step to k-step, starting from each node to itself. + + Parameters + ---------- + g : DGLGraph + The input graph. Must be homogeneous. + k : int + The number of random walk steps. The paper found the best value to be 16 and 20 + for two experiments. + eweight_name : str, optional + The name to retrieve the edge weights. Default: None, not using the edge weights. + + Returns + ------- + Tensor + The random walk positional encodings of shape :math:`(N, k)`, where :math:`N` is the + number of nodes in the input graph. + + Example + ------- + >>> import dgl + >>> g = dgl.graph(([0,1,1], [1,1,0])) + >>> dgl.random_walk_pe(g, 2) + tensor([[0.0000, 0.5000], + [0.5000, 0.7500]]) + """ + device = g.device + N = g.num_nodes() # number of nodes + M = g.num_edges() # number of edges + + row, col = g.edges() + + if eweight_name is None: + value = torch.ones(M, device=device) + else: + value = g.edata[eweight_name].squeeze().to(device) + # value_norm = torch_scatter.scatter(value, col, dim_size=N, reduce='sum').clamp(min=1)[col] + value_norm = torch_scatter.scatter(value, row, dim_size=N, reduce='sum')[row] + 1e-30 + value = value / value_norm + + if N <= 2_000: # Dense code path for faster computation: + adj = torch.zeros((N, N), device=row.device) + adj[row, col] = value + loop_index = torch.arange(N, device=row.device) + elif _TORCH_SP_SUPPORT: + adj = torch.sparse_coo_tensor(indices=torch.stack((row, col)), values=value, size=(N, N)) + else: + adj = torch_sparse.SparseTensor(row=row, col=col, value=value, sparse_sizes=(N, N)) + + def get_pe(out: torch.Tensor) -> torch.Tensor: + if not _TORCH_SP_SUPPORT and isinstance(out, torch_sparse.SparseTensor): + return out.get_diag() + elif _TORCH_SP_SUPPORT and out.is_sparse: + out = out.coalesce() + row, col = out.indices() + value = out.values() + select = row == col + ret_val = torch.zeros(N, dtype=out.dtype, device=out.device) + ret_val[row[select]] = value[select] + return ret_val + return out[loop_index, loop_index] + + out = adj + pe_list = [get_pe(out)] + for _ in range(k - 1): + out = out @ adj + pe_list.append(get_pe(out)) + + pe = torch.stack(pe_list, dim=-1) + + return pe + + +def split_dgl_batch(batch: dgl.DGLGraph, max_dgl_edges, frag_hashes, rev_idx, frag_form_vecs): + if batch.num_edges() > max_dgl_edges and batch.batch_size > 1: + split = batch.batch_size // 2 + list_of_graphs = dgl.unbatch(batch) + new_batch1 = split_dgl_batch(dgl.batch(list_of_graphs[:split]), max_dgl_edges, + frag_hashes[:split], rev_idx[:split], frag_form_vecs[:split]) + new_batch2 = split_dgl_batch(dgl.batch(list_of_graphs[split:]), max_dgl_edges, + frag_hashes[split:], rev_idx[split:], frag_form_vecs[split:]) + return new_batch1 + new_batch2 + else: + return [(batch, frag_hashes, rev_idx, frag_form_vecs)] + + +def dict_to_device(data_dict, device): + sent_dict = {} + for key, value in data_dict.items(): + if torch.is_tensor(value): + sent_dict[key] = value.to(device) + else: + sent_dict[key] = value + return sent_dict + + diff --git a/shared/package-files/77/777e5313f3cd6b0a920cb5ab1786340a0e662d5b30b3b9a77e6c10a8205d3e6b/blob b/shared/package-files/77/777e5313f3cd6b0a920cb5ab1786340a0e662d5b30b3b9a77e6c10a8205d3e6b/blob new file mode 100644 index 0000000000000000000000000000000000000000..a511e8ab6cc7f19c1a148e5ee72b6c38e0ea9d1d --- /dev/null +++ b/shared/package-files/77/777e5313f3cd6b0a920cb5ab1786340a0e662d5b30b3b9a77e6c10a8205d3e6b/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_lgamma { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_lgamma") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_lgamma(Tensor[] self) -> Tensor[]") + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_lgamma_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_lgamma_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_lgamma_(Tensor(a!)[] self) -> ()") + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_lgamma_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_lgamma") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_lgamma.out(Tensor[] self, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/77/777f6cc26e680d1135b3af63f341cb514da279a2d4456bccae596b3acfb8276b/blob b/shared/package-files/77/777f6cc26e680d1135b3af63f341cb514da279a2d4456bccae596b3acfb8276b/blob new file mode 100644 index 0000000000000000000000000000000000000000..2b30018b4a8881718a5b419ae44dd86910065eca --- /dev/null +++ b/shared/package-files/77/777f6cc26e680d1135b3af63f341cb514da279a2d4456bccae596b3acfb8276b/blob @@ -0,0 +1,130 @@ +#pragma once + +#include + +// Use of c10::hip namespace here makes hipification easier, because +// I don't have to also fix namespaces. Sorry! +namespace c10 { namespace hip { + +// See Note [Masquerading as CUDA] for motivation + +class HIPStreamMasqueradingAsCUDA { +public: + + enum Unchecked { UNCHECKED }; + + explicit HIPStreamMasqueradingAsCUDA(Stream stream) + : HIPStreamMasqueradingAsCUDA(UNCHECKED, stream) { + // We did the coercion unchecked; check that it was right. + TORCH_CHECK(stream.device().is_cuda() /* !!! */); + } + + explicit HIPStreamMasqueradingAsCUDA(Unchecked, Stream stream) + // Unsafely coerce the "CUDA" stream into a HIP stream + : stream_( + HIPStream( + Stream( + Stream::UNSAFE, + Device(c10::DeviceType::HIP, stream.device_index()), + stream.id()) + ) + ) {} + + // New constructor, just for this. Does NOT coerce. + explicit HIPStreamMasqueradingAsCUDA(HIPStream stream) : stream_(stream) {} + + bool operator==(const HIPStreamMasqueradingAsCUDA& other) const noexcept { + return stream_ == other.stream_; + } + + bool operator!=(const HIPStreamMasqueradingAsCUDA& other) const noexcept { + return stream_ != other.stream_; + } + + operator hipStream_t() const { return stream_.stream(); } + + operator Stream() const { + // Unsafely coerce HIP stream into a "CUDA" stream + return Stream(Stream::UNSAFE, device(), id()); + } + + DeviceIndex device_index() const { return stream_.device_index(); } + + // Unsafely coerce HIP device into CUDA device + c10::DeviceType device_type() const { return c10::DeviceType::CUDA; } + + Device device() const { + // Unsafely coerce HIP device into CUDA device + return Device(c10::DeviceType::CUDA, stream_.device_index()); + } + + StreamId id() const { return stream_.id(); } + bool query() const { return stream_.query(); } + void synchronize() const { stream_.synchronize(); } + int priority() const { return stream_.priority(); } + hipStream_t stream() const { return stream_.stream(); } + + Stream unwrap() const { + // Unsafely coerce HIP stream into "CUDA" stream + return Stream(Stream::UNSAFE, device(), id()); + } + + c10::StreamData3 pack3() const noexcept { + // Unsafely coerce HIP stream into "CUDA" stream before packing + return unwrap().pack3(); + } + + static HIPStreamMasqueradingAsCUDA unpack3(StreamId stream_id, + DeviceIndex device_index, + c10::DeviceType device_type) { + // NB: constructor manages CUDA->HIP translation for us + return HIPStreamMasqueradingAsCUDA(Stream::unpack3( + stream_id, device_index, device_type)); + } + + static std::tuple priority_range() { return HIPStream::priority_range(); } + + // New method, gets the underlying HIPStream + HIPStream hip_stream() const { return stream_; } + +private: + HIPStream stream_; +}; + +HIPStreamMasqueradingAsCUDA +inline getStreamFromPoolMasqueradingAsCUDA(const bool isHighPriority = false, DeviceIndex device = -1) { + return HIPStreamMasqueradingAsCUDA(getStreamFromPool(isHighPriority, device)); +} + +HIPStreamMasqueradingAsCUDA +inline getStreamFromExternalMasqueradingAsCUDA(hipStream_t ext_stream, DeviceIndex device) { + return HIPStreamMasqueradingAsCUDA(getStreamFromExternal(ext_stream, device)); +} + +inline HIPStreamMasqueradingAsCUDA getDefaultHIPStreamMasqueradingAsCUDA(DeviceIndex device_index = -1) { + return HIPStreamMasqueradingAsCUDA(getDefaultHIPStream(device_index)); +} + +inline HIPStreamMasqueradingAsCUDA getCurrentHIPStreamMasqueradingAsCUDA(DeviceIndex device_index = -1) { + return HIPStreamMasqueradingAsCUDA(getCurrentHIPStream(device_index)); +} + +inline void setCurrentHIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA stream) { + setCurrentHIPStream(stream.hip_stream()); +} + +inline std::ostream& operator<<(std::ostream& stream, const HIPStreamMasqueradingAsCUDA& s) { + stream << s.hip_stream() << " (masquerading as CUDA)"; + return stream; +} + +}} // namespace c10::hip + +namespace std { + template <> + struct hash { + size_t operator()(c10::hip::HIPStreamMasqueradingAsCUDA s) const noexcept { + return std::hash{}(s.unwrap()); + } + }; +} // namespace std diff --git a/shared/package-files/77/77849cc3837826e64319b0c839841f84b5da3dadbf9915334608ba07d5c72bc4/blob b/shared/package-files/77/77849cc3837826e64319b0c839841f84b5da3dadbf9915334608ba07d5c72bc4/blob new file mode 100644 index 0000000000000000000000000000000000000000..b8d4e34756a48e5f0cf81b80d6c1b8d18871ab09 --- /dev/null +++ b/shared/package-files/77/77849cc3837826e64319b0c839841f84b5da3dadbf9915334608ba07d5c72bc4/blob @@ -0,0 +1,48 @@ +# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29, +# with extension for dataclasses and type annotation. + +from __future__ import annotations + +import dataclasses +from typing import Any, Optional + +from torch.onnx._internal.diagnostics.infra.sarif import ( + _artifact_content, + _property_bag, +) + + +@dataclasses.dataclass +class WebRequest(object): + """Describes an HTTP request.""" + + body: Optional[_artifact_content.ArtifactContent] = dataclasses.field( + default=None, metadata={"schema_property_name": "body"} + ) + headers: Any = dataclasses.field( + default=None, metadata={"schema_property_name": "headers"} + ) + index: int = dataclasses.field( + default=-1, metadata={"schema_property_name": "index"} + ) + method: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "method"} + ) + parameters: Any = dataclasses.field( + default=None, metadata={"schema_property_name": "parameters"} + ) + properties: Optional[_property_bag.PropertyBag] = dataclasses.field( + default=None, metadata={"schema_property_name": "properties"} + ) + protocol: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "protocol"} + ) + target: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "target"} + ) + version: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "version"} + ) + + +# flake8: noqa diff --git a/shared/package-files/77/77863c93b4f32217da5d68bff3d5976dedd9b53dbcdda73f3a22edcc57291ee6/blob b/shared/package-files/77/77863c93b4f32217da5d68bff3d5976dedd9b53dbcdda73f3a22edcc57291ee6/blob new file mode 100644 index 0000000000000000000000000000000000000000..2bbc8f92d4266025df959183e0da273a866ab703 --- /dev/null +++ b/shared/package-files/77/77863c93b4f32217da5d68bff3d5976dedd9b53dbcdda73f3a22edcc57291ee6/blob @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace torch::autograd { + +struct TORCH_API SavedVariableHooks { + virtual void call_pack_hook(const at::Tensor& tensor) = 0; + virtual at::Tensor call_unpack_hook() = 0; + virtual ~SavedVariableHooks() = default; +}; + +} // namespace torch::autograd diff --git a/shared/package-files/77/778758ef0d3e2d60e5c6035f067b8a2efa26634027eddbfc7ac1c9c03214821b/blob b/shared/package-files/77/778758ef0d3e2d60e5c6035f067b8a2efa26634027eddbfc7ac1c9c03214821b/blob new file mode 100644 index 0000000000000000000000000000000000000000..2b98c4b61e7347580b7c4e722af53cc2282fdd9f --- /dev/null +++ b/shared/package-files/77/778758ef0d3e2d60e5c6035f067b8a2efa26634027eddbfc7ac1c9c03214821b/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor conv_transpose3d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & 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)); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/7787f6d901b0a5bd59b4393ed529fbd9fb6fa388a7702e44d890229268f37c92/blob b/shared/package-files/77/7787f6d901b0a5bd59b4393ed529fbd9fb6fa388a7702e44d890229268f37c92/blob new file mode 100644 index 0000000000000000000000000000000000000000..7e7363e797f3f5a33f66efd0349814c562e349e6 --- /dev/null +++ b/shared/package-files/77/7787f6d901b0a5bd59b4393ed529fbd9fb6fa388a7702e44d890229268f37c92/blob @@ -0,0 +1 @@ +def main() -> None: ... diff --git a/shared/package-files/77/7789fedfb3e086d51713955b1bd38a802a5b9304323d5bffccb5feb46a7b0c77/blob b/shared/package-files/77/7789fedfb3e086d51713955b1bd38a802a5b9304323d5bffccb5feb46a7b0c77/blob new file mode 100644 index 0000000000000000000000000000000000000000..c4d99b4af816a7cf2c8c607bad2177b8e28558ac --- /dev/null +++ b/shared/package-files/77/7789fedfb3e086d51713955b1bd38a802a5b9304323d5bffccb5feb46a7b0c77/blob @@ -0,0 +1,105 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API bitwise_xor_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API bitwise_xor_Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +struct TORCH_API bitwise_xor_Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API bitwise_xor_Scalar_Tensor { + using schema = at::Tensor (const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar_Tensor(Scalar self, Tensor other) -> Tensor") + static at::Tensor call(const at::Scalar & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_xor_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_xor__Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API bitwise_xor__Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_xor_Scalar_Tensor_out { + using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_xor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_xor.Scalar_Tensor_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/77/778a8cca881314caef951644a43b3b4a38529a60a705430d8125f66c953a7839/blob b/shared/package-files/77/778a8cca881314caef951644a43b3b4a38529a60a705430d8125f66c953a7839/blob new file mode 100644 index 0000000000000000000000000000000000000000..3b0d2529b5f10fb68fd8a634fab4615f78fe3520 --- /dev/null +++ b/shared/package-files/77/778a8cca881314caef951644a43b3b4a38529a60a705430d8125f66c953a7839/blob @@ -0,0 +1,1022 @@ +from numpy.testing import (assert_allclose, assert_almost_equal, + assert_array_equal, assert_array_almost_equal_nulp) +import numpy as np +import pytest + +from matplotlib import mlab + + +def test_window(): + np.random.seed(0) + n = 1000 + rand = np.random.standard_normal(n) + 100 + ones = np.ones(n) + assert_array_equal(mlab.window_none(ones), ones) + assert_array_equal(mlab.window_none(rand), rand) + assert_array_equal(np.hanning(len(rand)) * rand, mlab.window_hanning(rand)) + assert_array_equal(np.hanning(len(ones)), mlab.window_hanning(ones)) + + +class TestDetrend: + def setup_method(self): + np.random.seed(0) + n = 1000 + x = np.linspace(0., 100, n) + + self.sig_zeros = np.zeros(n) + + self.sig_off = self.sig_zeros + 100. + self.sig_slope = np.linspace(-10., 90., n) + self.sig_slope_mean = x - x.mean() + + self.sig_base = ( + np.random.standard_normal(n) + np.sin(x*2*np.pi/(n/100))) + self.sig_base -= self.sig_base.mean() + + def allclose(self, *args): + assert_allclose(*args, atol=1e-8) + + def test_detrend_none(self): + assert mlab.detrend_none(0.) == 0. + assert mlab.detrend_none(0., axis=1) == 0. + assert mlab.detrend(0., key="none") == 0. + assert mlab.detrend(0., key=mlab.detrend_none) == 0. + for sig in [ + 5.5, self.sig_off, self.sig_slope, self.sig_base, + (self.sig_base + self.sig_slope + self.sig_off).tolist(), + np.vstack([self.sig_base, # 2D case. + self.sig_base + self.sig_off, + self.sig_base + self.sig_slope, + self.sig_base + self.sig_off + self.sig_slope]), + np.vstack([self.sig_base, # 2D transposed case. + self.sig_base + self.sig_off, + self.sig_base + self.sig_slope, + self.sig_base + self.sig_off + self.sig_slope]).T, + ]: + if isinstance(sig, np.ndarray): + assert_array_equal(mlab.detrend_none(sig), sig) + else: + assert mlab.detrend_none(sig) == sig + + def test_detrend_mean(self): + for sig in [0., 5.5]: # 0D. + assert mlab.detrend_mean(sig) == 0. + assert mlab.detrend(sig, key="mean") == 0. + assert mlab.detrend(sig, key=mlab.detrend_mean) == 0. + # 1D. + self.allclose(mlab.detrend_mean(self.sig_zeros), self.sig_zeros) + self.allclose(mlab.detrend_mean(self.sig_base), self.sig_base) + self.allclose(mlab.detrend_mean(self.sig_base + self.sig_off), + self.sig_base) + self.allclose(mlab.detrend_mean(self.sig_base + self.sig_slope), + self.sig_base + self.sig_slope_mean) + self.allclose( + mlab.detrend_mean(self.sig_base + self.sig_slope + self.sig_off), + self.sig_base + self.sig_slope_mean) + + def test_detrend_mean_1d_base_slope_off_list_andor_axis0(self): + input = self.sig_base + self.sig_slope + self.sig_off + target = self.sig_base + self.sig_slope_mean + self.allclose(mlab.detrend_mean(input, axis=0), target) + self.allclose(mlab.detrend_mean(input.tolist()), target) + self.allclose(mlab.detrend_mean(input.tolist(), axis=0), target) + + def test_detrend_mean_2d(self): + input = np.vstack([self.sig_off, + self.sig_base + self.sig_off]) + target = np.vstack([self.sig_zeros, + self.sig_base]) + self.allclose(mlab.detrend_mean(input), target) + self.allclose(mlab.detrend_mean(input, axis=None), target) + self.allclose(mlab.detrend_mean(input.T, axis=None).T, target) + self.allclose(mlab.detrend(input), target) + self.allclose(mlab.detrend(input, axis=None), target) + self.allclose( + mlab.detrend(input.T, key="constant", axis=None), target.T) + + input = np.vstack([self.sig_base, + self.sig_base + self.sig_off, + self.sig_base + self.sig_slope, + self.sig_base + self.sig_off + self.sig_slope]) + target = np.vstack([self.sig_base, + self.sig_base, + self.sig_base + self.sig_slope_mean, + self.sig_base + self.sig_slope_mean]) + self.allclose(mlab.detrend_mean(input.T, axis=0), target.T) + self.allclose(mlab.detrend_mean(input, axis=1), target) + self.allclose(mlab.detrend_mean(input, axis=-1), target) + self.allclose(mlab.detrend(input, key="default", axis=1), target) + self.allclose(mlab.detrend(input.T, key="mean", axis=0), target.T) + self.allclose( + mlab.detrend(input.T, key=mlab.detrend_mean, axis=0), target.T) + + def test_detrend_ValueError(self): + for signal, kwargs in [ + (self.sig_slope[np.newaxis], {"key": "spam"}), + (self.sig_slope[np.newaxis], {"key": 5}), + (5.5, {"axis": 0}), + (self.sig_slope, {"axis": 1}), + (self.sig_slope[np.newaxis], {"axis": 2}), + ]: + with pytest.raises(ValueError): + mlab.detrend(signal, **kwargs) + + def test_detrend_mean_ValueError(self): + for signal, kwargs in [ + (5.5, {"axis": 0}), + (self.sig_slope, {"axis": 1}), + (self.sig_slope[np.newaxis], {"axis": 2}), + ]: + with pytest.raises(ValueError): + mlab.detrend_mean(signal, **kwargs) + + def test_detrend_linear(self): + # 0D. + assert mlab.detrend_linear(0.) == 0. + assert mlab.detrend_linear(5.5) == 0. + assert mlab.detrend(5.5, key="linear") == 0. + assert mlab.detrend(5.5, key=mlab.detrend_linear) == 0. + for sig in [ # 1D. + self.sig_off, + self.sig_slope, + self.sig_slope + self.sig_off, + ]: + self.allclose(mlab.detrend_linear(sig), self.sig_zeros) + + def test_detrend_str_linear_1d(self): + input = self.sig_slope + self.sig_off + target = self.sig_zeros + self.allclose(mlab.detrend(input, key="linear"), target) + self.allclose(mlab.detrend(input, key=mlab.detrend_linear), target) + self.allclose(mlab.detrend_linear(input.tolist()), target) + + def test_detrend_linear_2d(self): + input = np.vstack([self.sig_off, + self.sig_slope, + self.sig_slope + self.sig_off]) + target = np.vstack([self.sig_zeros, + self.sig_zeros, + self.sig_zeros]) + self.allclose( + mlab.detrend(input.T, key="linear", axis=0), target.T) + self.allclose( + mlab.detrend(input.T, key=mlab.detrend_linear, axis=0), target.T) + self.allclose( + mlab.detrend(input, key="linear", axis=1), target) + self.allclose( + mlab.detrend(input, key=mlab.detrend_linear, axis=1), target) + + with pytest.raises(ValueError): + mlab.detrend_linear(self.sig_slope[np.newaxis]) + + +@pytest.mark.parametrize('iscomplex', [False, True], + ids=['real', 'complex'], scope='class') +@pytest.mark.parametrize('sides', ['onesided', 'twosided', 'default'], + scope='class') +@pytest.mark.parametrize( + 'fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum', + [ + ([], None, -1, -1, -1, -1), + ([4], None, -1, -1, -1, -1), + ([4, 5, 10], None, -1, -1, -1, -1), + ([], None, None, -1, -1, None), + ([], None, -1, -1, None, None), + ([], None, None, -1, None, None), + ([], 1024, 512, -1, -1, 128), + ([], 256, -1, -1, 33, 257), + ([], 255, 33, -1, -1, None), + ([], 256, 128, -1, 256, 256), + ([], None, -1, 32, -1, -1), + ], + ids=[ + 'nosig', + 'Fs4', + 'FsAll', + 'nosig_noNFFT', + 'nosig_nopad_to', + 'nosig_noNFFT_no_pad_to', + 'nosig_trim', + 'nosig_odd', + 'nosig_oddlen', + 'nosig_stretch', + 'nosig_overlap', + ], + scope='class') +class TestSpectral: + @pytest.fixture(scope='class', autouse=True) + def stim(self, request, fstims, iscomplex, sides, len_x, NFFT_density, + nover_density, pad_to_density, pad_to_spectrum): + Fs = 100. + + x = np.arange(0, 10, 1 / Fs) + if len_x is not None: + x = x[:len_x] + + # get the stimulus frequencies, defaulting to None + fstims = [Fs / fstim for fstim in fstims] + + # get the constants, default to calculated values + if NFFT_density is None: + NFFT_density_real = 256 + elif NFFT_density < 0: + NFFT_density_real = NFFT_density = 100 + else: + NFFT_density_real = NFFT_density + + if nover_density is None: + nover_density_real = 0 + elif nover_density < 0: + nover_density_real = nover_density = NFFT_density_real // 2 + else: + nover_density_real = nover_density + + if pad_to_density is None: + pad_to_density_real = NFFT_density_real + elif pad_to_density < 0: + pad_to_density = int(2**np.ceil(np.log2(NFFT_density_real))) + pad_to_density_real = pad_to_density + else: + pad_to_density_real = pad_to_density + + if pad_to_spectrum is None: + pad_to_spectrum_real = len(x) + elif pad_to_spectrum < 0: + pad_to_spectrum_real = pad_to_spectrum = len(x) + else: + pad_to_spectrum_real = pad_to_spectrum + + if pad_to_spectrum is None: + NFFT_spectrum_real = NFFT_spectrum = pad_to_spectrum_real + else: + NFFT_spectrum_real = NFFT_spectrum = len(x) + nover_spectrum = 0 + + NFFT_specgram = NFFT_density + nover_specgram = nover_density + pad_to_specgram = pad_to_density + NFFT_specgram_real = NFFT_density_real + nover_specgram_real = nover_density_real + + if sides == 'onesided' or (sides == 'default' and not iscomplex): + # frequencies for specgram, psd, and csd + # need to handle even and odd differently + if pad_to_density_real % 2: + freqs_density = np.linspace(0, Fs / 2, + num=pad_to_density_real, + endpoint=False)[::2] + else: + freqs_density = np.linspace(0, Fs / 2, + num=pad_to_density_real // 2 + 1) + + # frequencies for complex, magnitude, angle, and phase spectrums + # need to handle even and odd differently + if pad_to_spectrum_real % 2: + freqs_spectrum = np.linspace(0, Fs / 2, + num=pad_to_spectrum_real, + endpoint=False)[::2] + else: + freqs_spectrum = np.linspace(0, Fs / 2, + num=pad_to_spectrum_real // 2 + 1) + else: + # frequencies for specgram, psd, and csd + # need to handle even and odd differently + if pad_to_density_real % 2: + freqs_density = np.linspace(-Fs / 2, Fs / 2, + num=2 * pad_to_density_real, + endpoint=False)[1::2] + else: + freqs_density = np.linspace(-Fs / 2, Fs / 2, + num=pad_to_density_real, + endpoint=False) + + # frequencies for complex, magnitude, angle, and phase spectrums + # need to handle even and odd differently + if pad_to_spectrum_real % 2: + freqs_spectrum = np.linspace(-Fs / 2, Fs / 2, + num=2 * pad_to_spectrum_real, + endpoint=False)[1::2] + else: + freqs_spectrum = np.linspace(-Fs / 2, Fs / 2, + num=pad_to_spectrum_real, + endpoint=False) + + freqs_specgram = freqs_density + # time points for specgram + t_start = NFFT_specgram_real // 2 + t_stop = len(x) - NFFT_specgram_real // 2 + 1 + t_step = NFFT_specgram_real - nover_specgram_real + t_specgram = x[t_start:t_stop:t_step] + if NFFT_specgram_real % 2: + t_specgram += 1 / Fs / 2 + if len(t_specgram) == 0: + t_specgram = np.array([NFFT_specgram_real / (2 * Fs)]) + t_spectrum = np.array([NFFT_spectrum_real / (2 * Fs)]) + t_density = t_specgram + + y = np.zeros_like(x) + for i, fstim in enumerate(fstims): + y += np.sin(fstim * x * np.pi * 2) * 10**i + + if iscomplex: + y = y.astype('complex') + + # Interestingly, the instance on which this fixture is called is not + # the same as the one on which a test is run. So we need to modify the + # class itself when using a class-scoped fixture. + cls = request.cls + + cls.Fs = Fs + cls.sides = sides + cls.fstims = fstims + + cls.NFFT_density = NFFT_density + cls.nover_density = nover_density + cls.pad_to_density = pad_to_density + + cls.NFFT_spectrum = NFFT_spectrum + cls.nover_spectrum = nover_spectrum + cls.pad_to_spectrum = pad_to_spectrum + + cls.NFFT_specgram = NFFT_specgram + cls.nover_specgram = nover_specgram + cls.pad_to_specgram = pad_to_specgram + + cls.t_specgram = t_specgram + cls.t_density = t_density + cls.t_spectrum = t_spectrum + cls.y = y + + cls.freqs_density = freqs_density + cls.freqs_spectrum = freqs_spectrum + cls.freqs_specgram = freqs_specgram + + cls.NFFT_density_real = NFFT_density_real + + def check_freqs(self, vals, targfreqs, resfreqs, fstims): + assert resfreqs.argmin() == 0 + assert resfreqs.argmax() == len(resfreqs)-1 + assert_allclose(resfreqs, targfreqs, atol=1e-06) + for fstim in fstims: + i = np.abs(resfreqs - fstim).argmin() + assert vals[i] > vals[i+2] + assert vals[i] > vals[i-2] + + def check_maxfreq(self, spec, fsp, fstims): + # skip the test if there are no frequencies + if len(fstims) == 0: + return + + # if twosided, do the test for each side + if fsp.min() < 0: + fspa = np.abs(fsp) + zeroind = fspa.argmin() + self.check_maxfreq(spec[:zeroind], fspa[:zeroind], fstims) + self.check_maxfreq(spec[zeroind:], fspa[zeroind:], fstims) + return + + fstimst = fstims[:] + spect = spec.copy() + + # go through each peak and make sure it is correctly the maximum peak + while fstimst: + maxind = spect.argmax() + maxfreq = fsp[maxind] + assert_almost_equal(maxfreq, fstimst[-1]) + del fstimst[-1] + spect[maxind-5:maxind+5] = 0 + + def test_spectral_helper_raises(self): + # We don't use parametrize here to handle ``y = self.y``. + for kwargs in [ # Various error conditions: + {"y": self.y+1, "mode": "complex"}, # Modes requiring ``x is y``. + {"y": self.y+1, "mode": "magnitude"}, + {"y": self.y+1, "mode": "angle"}, + {"y": self.y+1, "mode": "phase"}, + {"mode": "spam"}, # Bad mode. + {"y": self.y, "sides": "eggs"}, # Bad sides. + {"y": self.y, "NFFT": 10, "noverlap": 20}, # noverlap > NFFT. + {"NFFT": 10, "noverlap": 10}, # noverlap == NFFT. + {"y": self.y, "NFFT": 10, + "window": np.ones(9)}, # len(win) != NFFT. + ]: + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, **kwargs) + + @pytest.mark.parametrize('mode', ['default', 'psd']) + def test_single_spectrum_helper_unsupported_modes(self, mode): + with pytest.raises(ValueError): + mlab._single_spectrum_helper(x=self.y, mode=mode) + + @pytest.mark.parametrize("mode, case", [ + ("psd", "density"), + ("magnitude", "specgram"), + ("magnitude", "spectrum"), + ]) + def test_spectral_helper_psd(self, mode, case): + freqs = getattr(self, f"freqs_{case}") + spec, fsp, t = mlab._spectral_helper( + x=self.y, y=self.y, + NFFT=getattr(self, f"NFFT_{case}"), + Fs=self.Fs, + noverlap=getattr(self, f"nover_{case}"), + pad_to=getattr(self, f"pad_to_{case}"), + sides=self.sides, + mode=mode) + + assert_allclose(fsp, freqs, atol=1e-06) + assert_allclose(t, getattr(self, f"t_{case}"), atol=1e-06) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == getattr(self, f"t_{case}").shape[0] + + def test_csd(self): + freqs = self.freqs_density + spec, fsp = mlab.csd(x=self.y, y=self.y+1, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides) + assert_allclose(fsp, freqs, atol=1e-06) + assert spec.shape == freqs.shape + + def test_csd_padding(self): + """Test zero padding of csd().""" + if self.NFFT_density is None: # for derived classes + return + sargs = dict(x=self.y, y=self.y+1, Fs=self.Fs, window=mlab.window_none, + sides=self.sides) + + spec0, _ = mlab.csd(NFFT=self.NFFT_density, **sargs) + spec1, _ = mlab.csd(NFFT=self.NFFT_density*2, **sargs) + assert_almost_equal(np.sum(np.conjugate(spec0)*spec0).real, + np.sum(np.conjugate(spec1/2)*spec1/2).real) + + def test_psd(self): + freqs = self.freqs_density + spec, fsp = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides) + assert spec.shape == freqs.shape + self.check_freqs(spec, freqs, fsp, self.fstims) + + @pytest.mark.parametrize( + 'make_data, detrend', + [(np.zeros, mlab.detrend_mean), (np.zeros, 'mean'), + (np.arange, mlab.detrend_linear), (np.arange, 'linear')]) + def test_psd_detrend(self, make_data, detrend): + if self.NFFT_density is None: + return + ydata = make_data(self.NFFT_density) + ydata1 = ydata+5 + ydata2 = ydata+3.3 + ydata = np.vstack([ydata1, ydata2]) + ydata = np.tile(ydata, (20, 1)) + ydatab = ydata.T.flatten() + ydata = ydata.flatten() + ycontrol = np.zeros_like(ydata) + spec_g, fsp_g = mlab.psd(x=ydata, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + detrend=detrend) + spec_b, fsp_b = mlab.psd(x=ydatab, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + detrend=detrend) + spec_c, fsp_c = mlab.psd(x=ycontrol, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides) + assert_array_equal(fsp_g, fsp_c) + assert_array_equal(fsp_b, fsp_c) + assert_allclose(spec_g, spec_c, atol=1e-08) + # these should not be almost equal + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) + + def test_psd_window_hanning(self): + if self.NFFT_density is None: + return + ydata = np.arange(self.NFFT_density) + ydata1 = ydata+5 + ydata2 = ydata+3.3 + windowVals = mlab.window_hanning(np.ones_like(ydata1)) + ycontrol1 = ydata1 * windowVals + ycontrol2 = mlab.window_hanning(ydata2) + ydata = np.vstack([ydata1, ydata2]) + ycontrol = np.vstack([ycontrol1, ycontrol2]) + ydata = np.tile(ydata, (20, 1)) + ycontrol = np.tile(ycontrol, (20, 1)) + ydatab = ydata.T.flatten() + ydataf = ydata.flatten() + ycontrol = ycontrol.flatten() + spec_g, fsp_g = mlab.psd(x=ydataf, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + window=mlab.window_hanning) + spec_b, fsp_b = mlab.psd(x=ydatab, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + window=mlab.window_hanning) + spec_c, fsp_c = mlab.psd(x=ycontrol, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + window=mlab.window_none) + spec_c *= len(ycontrol1)/(windowVals**2).sum() + assert_array_equal(fsp_g, fsp_c) + assert_array_equal(fsp_b, fsp_c) + assert_allclose(spec_g, spec_c, atol=1e-08) + # these should not be almost equal + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) + + def test_psd_window_hanning_detrend_linear(self): + if self.NFFT_density is None: + return + ydata = np.arange(self.NFFT_density) + ycontrol = np.zeros(self.NFFT_density) + ydata1 = ydata+5 + ydata2 = ydata+3.3 + ycontrol1 = ycontrol + ycontrol2 = ycontrol + windowVals = mlab.window_hanning(np.ones_like(ycontrol1)) + ycontrol1 = ycontrol1 * windowVals + ycontrol2 = mlab.window_hanning(ycontrol2) + ydata = np.vstack([ydata1, ydata2]) + ycontrol = np.vstack([ycontrol1, ycontrol2]) + ydata = np.tile(ydata, (20, 1)) + ycontrol = np.tile(ycontrol, (20, 1)) + ydatab = ydata.T.flatten() + ydataf = ydata.flatten() + ycontrol = ycontrol.flatten() + spec_g, fsp_g = mlab.psd(x=ydataf, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + detrend=mlab.detrend_linear, + window=mlab.window_hanning) + spec_b, fsp_b = mlab.psd(x=ydatab, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + detrend=mlab.detrend_linear, + window=mlab.window_hanning) + spec_c, fsp_c = mlab.psd(x=ycontrol, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + window=mlab.window_none) + spec_c *= len(ycontrol1)/(windowVals**2).sum() + assert_array_equal(fsp_g, fsp_c) + assert_array_equal(fsp_b, fsp_c) + assert_allclose(spec_g, spec_c, atol=1e-08) + # these should not be almost equal + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) + + def test_psd_window_flattop(self): + # flattop window + # adaption from https://github.com/scipy/scipy/blob\ + # /v1.10.0/scipy/signal/windows/_windows.py#L562-L622 + a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368] + fac = np.linspace(-np.pi, np.pi, self.NFFT_density_real) + win = np.zeros(self.NFFT_density_real) + for k in range(len(a)): + win += a[k] * np.cos(k * fac) + + spec, fsp = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + window=win, + scale_by_freq=False) + spec_a, fsp_a = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=0, + sides=self.sides, + window=win) + assert_allclose(spec*win.sum()**2, + spec_a*self.Fs*(win**2).sum(), + atol=1e-08) + + def test_psd_windowarray(self): + freqs = self.freqs_density + spec, fsp = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides, + window=np.ones(self.NFFT_density_real)) + assert_allclose(fsp, freqs, atol=1e-06) + assert spec.shape == freqs.shape + + def test_psd_windowarray_scale_by_freq(self): + win = mlab.window_hanning(np.ones(self.NFFT_density_real)) + + spec, fsp = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides, + window=mlab.window_hanning) + spec_s, fsp_s = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides, + window=mlab.window_hanning, + scale_by_freq=True) + spec_n, fsp_n = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides, + window=mlab.window_hanning, + scale_by_freq=False) + assert_array_equal(fsp, fsp_s) + assert_array_equal(fsp, fsp_n) + assert_array_equal(spec, spec_s) + assert_allclose(spec_s*(win**2).sum(), + spec_n/self.Fs*win.sum()**2, + atol=1e-08) + + @pytest.mark.parametrize( + "kind", ["complex", "magnitude", "angle", "phase"]) + def test_spectrum(self, kind): + freqs = self.freqs_spectrum + spec, fsp = getattr(mlab, f"{kind}_spectrum")( + x=self.y, + Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum) + assert_allclose(fsp, freqs, atol=1e-06) + assert spec.shape == freqs.shape + if kind == "magnitude": + self.check_maxfreq(spec, fsp, self.fstims) + self.check_freqs(spec, freqs, fsp, self.fstims) + + @pytest.mark.parametrize( + 'kwargs', + [{}, {'mode': 'default'}, {'mode': 'psd'}, {'mode': 'magnitude'}, + {'mode': 'complex'}, {'mode': 'angle'}, {'mode': 'phase'}]) + def test_specgram(self, kwargs): + freqs = self.freqs_specgram + spec, fsp, t = mlab.specgram(x=self.y, + NFFT=self.NFFT_specgram, + Fs=self.Fs, + noverlap=self.nover_specgram, + pad_to=self.pad_to_specgram, + sides=self.sides, + **kwargs) + if kwargs.get('mode') == 'complex': + spec = np.abs(spec) + specm = np.mean(spec, axis=1) + + assert_allclose(fsp, freqs, atol=1e-06) + assert_allclose(t, self.t_specgram, atol=1e-06) + + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] + + if kwargs.get('mode') not in ['complex', 'angle', 'phase']: + # using a single freq, so all time slices should be about the same + if np.abs(spec.max()) != 0: + assert_allclose( + np.diff(spec, axis=1).max() / np.abs(spec.max()), 0, + atol=1e-02) + if kwargs.get('mode') not in ['angle', 'phase']: + self.check_freqs(specm, freqs, fsp, self.fstims) + + def test_specgram_warn_only1seg(self): + """Warning should be raised if len(x) <= NFFT.""" + with pytest.warns(UserWarning, match="Only one segment is calculated"): + mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs) + + def test_psd_csd_equal(self): + Pxx, freqsxx = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides) + Pxy, freqsxy = mlab.csd(x=self.y, y=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides) + assert_array_almost_equal_nulp(Pxx, Pxy) + assert_array_equal(freqsxx, freqsxy) + + @pytest.mark.parametrize("mode", ["default", "psd"]) + def test_specgram_auto_default_psd_equal(self, mode): + """ + Test that mlab.specgram without mode and with mode 'default' and 'psd' + are all the same. + """ + speca, freqspeca, ta = mlab.specgram(x=self.y, + NFFT=self.NFFT_specgram, + Fs=self.Fs, + noverlap=self.nover_specgram, + pad_to=self.pad_to_specgram, + sides=self.sides) + specb, freqspecb, tb = mlab.specgram(x=self.y, + NFFT=self.NFFT_specgram, + Fs=self.Fs, + noverlap=self.nover_specgram, + pad_to=self.pad_to_specgram, + sides=self.sides, + mode=mode) + assert_array_equal(speca, specb) + assert_array_equal(freqspeca, freqspecb) + assert_array_equal(ta, tb) + + @pytest.mark.parametrize( + "mode, conv", [ + ("magnitude", np.abs), + ("angle", np.angle), + ("phase", lambda x: np.unwrap(np.angle(x), axis=0)) + ]) + def test_specgram_complex_equivalent(self, mode, conv): + specc, freqspecc, tc = mlab.specgram(x=self.y, + NFFT=self.NFFT_specgram, + Fs=self.Fs, + noverlap=self.nover_specgram, + pad_to=self.pad_to_specgram, + sides=self.sides, + mode='complex') + specm, freqspecm, tm = mlab.specgram(x=self.y, + NFFT=self.NFFT_specgram, + Fs=self.Fs, + noverlap=self.nover_specgram, + pad_to=self.pad_to_specgram, + sides=self.sides, + mode=mode) + + assert_array_equal(freqspecc, freqspecm) + assert_array_equal(tc, tm) + assert_allclose(conv(specc), specm, atol=1e-06) + + def test_psd_windowarray_equal(self): + win = mlab.window_hanning(np.ones(self.NFFT_density_real)) + speca, fspa = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides, + window=win) + specb, fspb = mlab.psd(x=self.y, + NFFT=self.NFFT_density, + Fs=self.Fs, + noverlap=self.nover_density, + pad_to=self.pad_to_density, + sides=self.sides) + assert_array_equal(fspa, fspb) + assert_allclose(speca, specb, atol=1e-08) + + +# extra test for cohere... +def test_cohere(): + N = 1024 + np.random.seed(19680801) + x = np.random.randn(N) + # phase offset + y = np.roll(x, 20) + # high-freq roll-off + y = np.convolve(y, np.ones(20) / 20., mode='same') + cohsq, f = mlab.cohere(x, y, NFFT=256, Fs=2, noverlap=128) + assert_allclose(np.mean(cohsq), 0.837, atol=1.e-3) + assert np.isreal(np.mean(cohsq)) + + +# ***************************************************************** +# These Tests were taken from SCIPY with some minor modifications +# this can be retrieved from: +# https://github.com/scipy/scipy/blob/master/scipy/stats/tests/test_kdeoth.py +# ***************************************************************** + +class TestGaussianKDE: + + def test_kde_integer_input(self): + """Regression test for #1181.""" + x1 = np.arange(5) + kde = mlab.GaussianKDE(x1) + y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869, + 0.13480721] + np.testing.assert_array_almost_equal(kde(x1), y_expected, decimal=6) + + def test_gaussian_kde_covariance_caching(self): + x1 = np.array([-7, -5, 1, 4, 5], dtype=float) + xs = np.linspace(-10, 10, num=5) + # These expected values are from scipy 0.10, before some changes to + # gaussian_kde. They were not compared with any external reference. + y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754, + 0.01664475] + + # set it to the default bandwidth. + kde2 = mlab.GaussianKDE(x1, 'scott') + y2 = kde2(xs) + + np.testing.assert_array_almost_equal(y_expected, y2, decimal=7) + + def test_kde_bandwidth_method(self): + + np.random.seed(8765678) + n_basesample = 50 + xn = np.random.randn(n_basesample) + + # Default + gkde = mlab.GaussianKDE(xn) + # Supply a callable + gkde2 = mlab.GaussianKDE(xn, 'scott') + # Supply a scalar + gkde3 = mlab.GaussianKDE(xn, bw_method=gkde.factor) + + xs = np.linspace(-7, 7, 51) + kdepdf = gkde.evaluate(xs) + kdepdf2 = gkde2.evaluate(xs) + assert kdepdf.all() == kdepdf2.all() + kdepdf3 = gkde3.evaluate(xs) + assert kdepdf.all() == kdepdf3.all() + + +class TestGaussianKDECustom: + def test_no_data(self): + """Pass no data into the GaussianKDE class.""" + with pytest.raises(ValueError): + mlab.GaussianKDE([]) + + def test_single_dataset_element(self): + """Pass a single dataset element into the GaussianKDE class.""" + with pytest.raises(ValueError): + mlab.GaussianKDE([42]) + + def test_silverman_multidim_dataset(self): + """Test silverman's for a multi-dimensional array.""" + x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + with pytest.raises(np.linalg.LinAlgError): + mlab.GaussianKDE(x1, "silverman") + + def test_silverman_singledim_dataset(self): + """Test silverman's output for a single dimension list.""" + x1 = np.array([-7, -5, 1, 4, 5]) + mygauss = mlab.GaussianKDE(x1, "silverman") + y_expected = 0.76770389927475502 + assert_almost_equal(mygauss.covariance_factor(), y_expected, 7) + + def test_scott_multidim_dataset(self): + """Test scott's output for a multi-dimensional array.""" + x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + with pytest.raises(np.linalg.LinAlgError): + mlab.GaussianKDE(x1, "scott") + + def test_scott_singledim_dataset(self): + """Test scott's output a single-dimensional array.""" + x1 = np.array([-7, -5, 1, 4, 5]) + mygauss = mlab.GaussianKDE(x1, "scott") + y_expected = 0.72477966367769553 + assert_almost_equal(mygauss.covariance_factor(), y_expected, 7) + + def test_scalar_empty_dataset(self): + """Test the scalar's cov factor for an empty array.""" + with pytest.raises(ValueError): + mlab.GaussianKDE([], bw_method=5) + + def test_scalar_covariance_dataset(self): + """Test a scalar's cov factor.""" + np.random.seed(8765678) + n_basesample = 50 + multidim_data = [np.random.randn(n_basesample) for i in range(5)] + + kde = mlab.GaussianKDE(multidim_data, bw_method=0.5) + assert kde.covariance_factor() == 0.5 + + def test_callable_covariance_dataset(self): + """Test the callable's cov factor for a multi-dimensional array.""" + np.random.seed(8765678) + n_basesample = 50 + multidim_data = [np.random.randn(n_basesample) for i in range(5)] + + def callable_fun(x): + return 0.55 + kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun) + assert kde.covariance_factor() == 0.55 + + def test_callable_singledim_dataset(self): + """Test the callable's cov factor for a single-dimensional array.""" + np.random.seed(8765678) + n_basesample = 50 + multidim_data = np.random.randn(n_basesample) + + kde = mlab.GaussianKDE(multidim_data, bw_method='silverman') + y_expected = 0.48438841363348911 + assert_almost_equal(kde.covariance_factor(), y_expected, 7) + + def test_wrong_bw_method(self): + """Test the error message that should be called when bw is invalid.""" + np.random.seed(8765678) + n_basesample = 50 + data = np.random.randn(n_basesample) + with pytest.raises(ValueError): + mlab.GaussianKDE(data, bw_method="invalid") + + +class TestGaussianKDEEvaluate: + + def test_evaluate_diff_dim(self): + """ + Test the evaluate method when the dim's of dataset and points have + different dimensions. + """ + x1 = np.arange(3, 10, 2) + kde = mlab.GaussianKDE(x1) + x2 = np.arange(3, 12, 2) + y_expected = [ + 0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153 + ] + y = kde.evaluate(x2) + np.testing.assert_array_almost_equal(y, y_expected, 7) + + def test_evaluate_inv_dim(self): + """ + Invert the dimensions; i.e., for a dataset of dimension 1 [3, 2, 4], + the points should have a dimension of 3 [[3], [2], [4]]. + """ + np.random.seed(8765678) + n_basesample = 50 + multidim_data = np.random.randn(n_basesample) + kde = mlab.GaussianKDE(multidim_data) + x2 = [[1], [2], [3]] + with pytest.raises(ValueError): + kde.evaluate(x2) + + def test_evaluate_dim_and_num(self): + """Tests if evaluated against a one by one array""" + x1 = np.arange(3, 10, 2) + x2 = np.array([3]) + kde = mlab.GaussianKDE(x1) + y_expected = [0.08797252] + y = kde.evaluate(x2) + np.testing.assert_array_almost_equal(y, y_expected, 7) + + def test_evaluate_point_dim_not_one(self): + x1 = np.arange(3, 10, 2) + x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)] + kde = mlab.GaussianKDE(x1) + with pytest.raises(ValueError): + kde.evaluate(x2) + + def test_evaluate_equal_dim_and_num_lt(self): + x1 = np.arange(3, 10, 2) + x2 = np.arange(3, 8, 2) + kde = mlab.GaussianKDE(x1) + y_expected = [0.08797252, 0.11774109, 0.11774109] + y = kde.evaluate(x2) + np.testing.assert_array_almost_equal(y, y_expected, 7) + + +def test_psd_onesided_norm(): + u = np.array([0, 1, 2, 3, 1, 2, 1]) + dt = 1.0 + Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size) + P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none, + detrend=mlab.detrend_none, noverlap=0, pad_to=None, + scale_by_freq=None, + sides='onesided') + Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) + assert_allclose(P, Su_1side, atol=1e-06) + + +def test_psd_oversampling(): + """Test the case len(x) < NFFT for psd().""" + u = np.array([0, 1, 2, 3, 1, 2, 1]) + dt = 1.0 + Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size) + P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none, + detrend=mlab.detrend_none, noverlap=0, pad_to=None, + scale_by_freq=None, + sides='onesided') + Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) + assert_almost_equal(np.sum(P), np.sum(Su_1side)) # same energy diff --git a/shared/package-files/77/778ea214b1bd8f78cdec7664c04bbdf56b7db2fcee3fec2666da59125ee0e5c8/blob b/shared/package-files/77/778ea214b1bd8f78cdec7664c04bbdf56b7db2fcee3fec2666da59125ee0e5c8/blob new file mode 100644 index 0000000000000000000000000000000000000000..eda274b5724f0f5f0a3f94b9beb5821ae06a6dd4 --- /dev/null +++ b/shared/package-files/77/778ea214b1bd8f78cdec7664c04bbdf56b7db2fcee3fec2666da59125ee0e5c8/blob @@ -0,0 +1 @@ +from .memory_tracker import MemoryTracker diff --git a/shared/package-files/77/77903a40396482740cf3ccac3e9903cae169197df3bd9cd37c26f9aa17a85c50/blob b/shared/package-files/77/77903a40396482740cf3ccac3e9903cae169197df3bd9cd37c26f9aa17a85c50/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ffac3c418a0d85af12755b63168830838847c24 --- /dev/null +++ b/shared/package-files/77/77903a40396482740cf3ccac3e9903cae169197df3bd9cd37c26f9aa17a85c50/blob @@ -0,0 +1,157 @@ +# This module provides a LALR interactive parser, which is used for debugging and error handling + +from typing import Iterator, List +from copy import copy +import warnings + +from lark.exceptions import UnexpectedToken +from lark.lexer import Token, LexerThread + +###{standalone + +class InteractiveParser: + """InteractiveParser gives you advanced control over parsing and error handling when parsing with LALR. + + For a simpler interface, see the ``on_error`` argument to ``Lark.parse()``. + """ + def __init__(self, parser, parser_state, lexer_thread: LexerThread): + self.parser = parser + self.parser_state = parser_state + self.lexer_thread = lexer_thread + self.result = None + + @property + def lexer_state(self) -> LexerThread: + warnings.warn("lexer_state will be removed in subsequent releases. Use lexer_thread instead.", DeprecationWarning) + return self.lexer_thread + + def feed_token(self, token: Token): + """Feed the parser with a token, and advance it to the next state, as if it received it from the lexer. + + Note that ``token`` has to be an instance of ``Token``. + """ + return self.parser_state.feed_token(token, token.type == '$END') + + def iter_parse(self) -> Iterator[Token]: + """Step through the different stages of the parse, by reading tokens from the lexer + and feeding them to the parser, one per iteration. + + Returns an iterator of the tokens it encounters. + + When the parse is over, the resulting tree can be found in ``InteractiveParser.result``. + """ + for token in self.lexer_thread.lex(self.parser_state): + yield token + self.result = self.feed_token(token) + + def exhaust_lexer(self) -> List[Token]: + """Try to feed the rest of the lexer state into the interactive parser. + + Note that this modifies the instance in place and does not feed an '$END' Token + """ + return list(self.iter_parse()) + + + def feed_eof(self, last_token=None): + """Feed a '$END' Token. Borrows from 'last_token' if given.""" + eof = Token.new_borrow_pos('$END', '', last_token) if last_token is not None else self.lexer_thread._Token('$END', '', 0, 1, 1) + return self.feed_token(eof) + + + def __copy__(self): + """Create a new interactive parser with a separate state. + + Calls to feed_token() won't affect the old instance, and vice-versa. + """ + return type(self)( + self.parser, + copy(self.parser_state), + copy(self.lexer_thread), + ) + + def copy(self): + return copy(self) + + def __eq__(self, other): + if not isinstance(other, InteractiveParser): + return False + + return self.parser_state == other.parser_state and self.lexer_thread == other.lexer_thread + + def as_immutable(self): + """Convert to an ``ImmutableInteractiveParser``.""" + p = copy(self) + return ImmutableInteractiveParser(p.parser, p.parser_state, p.lexer_thread) + + def pretty(self): + """Print the output of ``choices()`` in a way that's easier to read.""" + out = ["Parser choices:"] + for k, v in self.choices().items(): + out.append('\t- %s -> %r' % (k, v)) + out.append('stack size: %s' % len(self.parser_state.state_stack)) + return '\n'.join(out) + + def choices(self): + """Returns a dictionary of token types, matched to their action in the parser. + + Only returns token types that are accepted by the current state. + + Updated by ``feed_token()``. + """ + return self.parser_state.parse_conf.parse_table.states[self.parser_state.position] + + def accepts(self): + """Returns the set of possible tokens that will advance the parser into a new valid state.""" + accepts = set() + conf_no_callbacks = copy(self.parser_state.parse_conf) + # We don't want to call callbacks here since those might have arbitrary side effects + # and are unnecessarily slow. + conf_no_callbacks.callbacks = {} + for t in self.choices(): + if t.isupper(): # is terminal? + new_cursor = copy(self) + new_cursor.parser_state.parse_conf = conf_no_callbacks + try: + new_cursor.feed_token(self.lexer_thread._Token(t, '')) + except UnexpectedToken: + pass + else: + accepts.add(t) + return accepts + + def resume_parse(self): + """Resume automated parsing from the current state. + """ + return self.parser.parse_from_state(self.parser_state, last_token=self.lexer_thread.state.last_token) + + + +class ImmutableInteractiveParser(InteractiveParser): + """Same as ``InteractiveParser``, but operations create a new instance instead + of changing it in-place. + """ + + result = None + + def __hash__(self): + return hash((self.parser_state, self.lexer_thread)) + + def feed_token(self, token): + c = copy(self) + c.result = InteractiveParser.feed_token(c, token) + return c + + def exhaust_lexer(self): + """Try to feed the rest of the lexer state into the parser. + + Note that this returns a new ImmutableInteractiveParser and does not feed an '$END' Token""" + cursor = self.as_mutable() + cursor.exhaust_lexer() + return cursor.as_immutable() + + def as_mutable(self): + """Convert to an ``InteractiveParser``.""" + p = copy(self) + return InteractiveParser(p.parser, p.parser_state, p.lexer_thread) + +###} diff --git a/shared/package-files/77/77906c38a434dc70b4386628a9e8e35fb3cbcd0409891e34432a92a246b345b3/blob b/shared/package-files/77/77906c38a434dc70b4386628a9e8e35fb3cbcd0409891e34432a92a246b345b3/blob new file mode 100644 index 0000000000000000000000000000000000000000..04274472631245e54db90cb3cc7cc1330e556568 --- /dev/null +++ b/shared/package-files/77/77906c38a434dc70b4386628a9e8e35fb3cbcd0409891e34432a92a246b345b3/blob @@ -0,0 +1,376 @@ +""" +Univariate lowess function, like in R. + +References +---------- +Hastie, Tibshirani, Friedman. (2009) The Elements of Statistical Learning: Data Mining, Inference, and Prediction, Second Edition: Chapter 6. + +Cleveland, W.S. (1979) "Robust Locally Weighted Regression and Smoothing Scatterplots". Journal of the American Statistical Association 74 (368): 829-836. +""" +from statsmodels.compat.numpy import inplace_reshape + +import warnings + +import numpy as np +from numpy.linalg import lstsq + + +def lowess(endog, exog, frac=2.0 / 3, it=3): + """ + LOWESS (Locally Weighted Scatterplot Smoothing) + + A lowess function that outputs smoothed estimates of endog + at the given exog values from points (exog, endog) + + Parameters + ---------- + endog : ndarray + The 1-D y-values of the observed points + exog : ndarray + The 1-D x-values of the observed points + frac : float, optional + Between 0 and 1. The fraction of the data used + when estimating each y-value. + it : int, optional + The number of residual-based reweightings + to perform. + + Returns + ------- + out : ndarray + An array with two columns. The first column + is the sorted x values and the second column the + associated estimated y-values. + + Notes + ----- + This lowess function implements the algorithm given in the + reference below using local linear estimates. + + Suppose the input data has N points. The algorithm works by + estimating the true ``y_i`` by taking the frac*N closest points + to ``(x_i,y_i)`` based on their x values and estimating ``y_i`` + using a weighted linear regression. The weight for ``(x_j,y_j)`` + is `_lowess_tricube` function applied to ``|x_i-x_j|``. + + If ``iter > 0``, then further weighted local linear regressions + are performed, where the weights are the same as above + times the `_lowess_bisquare` function of the residuals. Each iteration + takes approximately the same amount of time as the original fit, + so these iterations are expensive. They are most useful when + the noise has extremely heavy tails, such as Cauchy noise. + Noise with less heavy-tails, such as t-distributions with ``df > 2``, + are less problematic. The weights downgrade the influence of + points with large residuals. In the extreme case, points whose + residuals are larger than 6 times the median absolute residual + are given weight 0. + + Some experimentation is likely required to find a good + choice of frac and iter for a particular dataset. + + References + ---------- + Cleveland, W.S. (1979) "Robust Locally Weighted Regression + and Smoothing Scatterplots". Journal of the American Statistical + Association 74 (368): 829-836. + + Examples + -------- + The below allows a comparison between how different the fits from + `lowess` for different values of frac can be. + + >>> import numpy as np + >>> import statsmodels.api as sm + >>> lowess = sm.nonparametric.lowess + >>> x = np.random.uniform(low=-2*np.pi, high=2*np.pi, size=500) + >>> y = np.sin(x) + np.random.normal(size=len(x)) + >>> z = lowess(y, x) + >>> w = lowess(y, x, frac=1./3) + + This gives a similar comparison for when it is 0 vs not. + + >>> from scipy import stats + >>> x = np.random.uniform(low=-2*np.pi, high=2*np.pi, size=500) + >>> y = np.sin(x) + stats.cauchy.rvs(size=len(x)) + >>> z = lowess(y, x, frac= 1./3, it=0) + >>> w = lowess(y, x, frac=1./3) + """ + warnings.warn( + "statsmodels.nonparametric.smoothers_lowess_old.lowess is " + "deprecated and is not exported from any public statsmodels API; " + "it has had no test coverage and has been superseded by the " + "actively maintained statsmodels.nonparametric.lowess (used in " + "this very function's own docstring examples). It will be " + "removed after statsmodels 0.16 is released. If you rely on this " + "function, please open an issue at " + "https://github.com/statsmodels/statsmodels/issues.", + FutureWarning, + stacklevel=2, + ) + x = exog + + if exog.ndim != 1: + raise ValueError("exog must be a vector") + if endog.ndim != 1: + raise ValueError("endog must be a vector") + if endog.shape[0] != x.shape[0]: + raise ValueError("exog and endog must have same length") + + n = exog.shape[0] + fitted = np.zeros(n) + + k = int(frac * n) + + index_array = np.argsort(exog) + x_copy = np.array(exog[index_array]) # , dtype ='float32') + y_copy = endog[index_array] + + fitted, weights = _lowess_initial_fit(x_copy, y_copy, k, n) + + for _ in range(it): + _lowess_robustify_fit(x_copy, y_copy, fitted, weights, k, n) + + out = np.array([x_copy, fitted]).T + out = inplace_reshape(out, (n, 2)) + + return out + + +def _lowess_initial_fit(x_copy, y_copy, k, n): + """ + The initial weighted local linear regression for lowess + + Parameters + ---------- + x_copy : 1-d ndarray + The x-values/exogenous part of the data being smoothed + y_copy : 1-d ndarray + The y-values/ endogenous part of the data being smoothed + k : int + The number of data points which affect the linear fit for + each estimated point + n : int + The total number of points + + Returns + ------- + fitted : 1-d ndarray + The fitted y-values + weights : 2-d ndarray + An n by k array. The contribution to the weights in the + local linear fit coming from the distances between the + x-values + """ + weights = np.zeros((n, k), dtype=x_copy.dtype) + nn_indices = [0, k] + + X = np.ones((k, 2)) + fitted = np.zeros(n) + + for i in range(n): + # note: all _lowess functions are inplace, no return + + left_width = x_copy[i] - x_copy[nn_indices[0]] + right_width = x_copy[nn_indices[1] - 1] - x_copy[i] + width = max(left_width, right_width) + _lowess_wt_standardize( + weights[i, :], x_copy[nn_indices[0] : nn_indices[1]], x_copy[i], width + ) + _lowess_tricube(weights[i, :]) + weights[i, :] = np.sqrt(weights[i, :]) + + X[:, 1] = x_copy[nn_indices[0] : nn_indices[1]] + y_i = weights[i, :] * y_copy[nn_indices[0] : nn_indices[1]] + + beta = lstsq(weights[i, :].reshape(k, 1) * X, y_i, rcond=-1)[0] + fitted[i] = beta[0] + beta[1] * x_copy[i] + + _lowess_update_nn(x_copy, nn_indices, i + 1) + return fitted, weights + + +def _lowess_wt_standardize(weights, new_entries, x_copy_i, width): + """ + The initial phase of creating the weights + + Subtract the current x_i and divide by the width. + + Parameters + ---------- + weights : ndarray + The memory where (new_entries - x_copy_i)/width will be placed + new_entries : ndarray + The x-values of the k closest points to x[i] + x_copy_i : float + x[i], the i'th point in the (sorted) x values + width : float + The maximum distance between x[i] and any point in new_entries + + Returns + ------- + None + The modifications are made to `weights` in place. + """ + weights[:] = new_entries + weights -= x_copy_i + weights /= width + + +def _lowess_robustify_fit(x_copy, y_copy, fitted, weights, k, n): + """ + Additional weighted local linear regressions, performed if iter>0 + + They take into account the sizes of the residuals, to eliminate the + effect of extreme outliers. + + Parameters + ---------- + x_copy : 1-d ndarray + The x-values/exogenous part of the data being smoothed + y_copy : 1-d ndarray + The y-values/ endogenous part of the data being smoothed + fitted : 1-d ndarray + The fitted y-values from the previous iteration + weights : 2-d ndarray + An n by k array. The contribution to the weights in the + local linear fit coming from the distances between the + x-values + k : int + The number of data points which affect the linear fit for + each estimated point + n : int + The total number of points + + Returns + ------- + None + The modifications are made to `fitted` in place. + """ + nn_indices = [0, k] + X = np.ones((k, 2)) + + residual_weights = np.copy(y_copy) + residual_weights = inplace_reshape(residual_weights, (n,)) + residual_weights -= fitted + residual_weights = np.absolute(residual_weights) # , out=residual_weights) + s = np.median(residual_weights) + residual_weights /= 6 * s + too_big = residual_weights >= 1 + _lowess_bisquare(residual_weights) + residual_weights[too_big] = 0 + + for i in range(n): + total_weights = weights[i, :] * np.sqrt( + residual_weights[nn_indices[0] : nn_indices[1]] + ) + + X[:, 1] = x_copy[nn_indices[0] : nn_indices[1]] + y_i = total_weights * y_copy[nn_indices[0] : nn_indices[1]] + total_weights = inplace_reshape(total_weights, (k, 1)) + + beta = lstsq(total_weights * X, y_i, rcond=-1)[0] + + fitted[i] = beta[0] + beta[1] * x_copy[i] + + _lowess_update_nn(x_copy, nn_indices, i + 1) + + +def _lowess_update_nn(x, cur_nn, i): + """ + Update the endpoints of the nearest neighbors to the ith point + + Parameters + ---------- + x : ndarray + The sorted points of x-values + cur_nn : list of int + Two-element list giving the current indices between which are the + k closest points to x[i]. (The actual value of + k is irrelevant for the algorithm.) + i : int + The index of the current value in x for which + the k closest points are desired. + + Returns + ------- + None + The modifications are made to `cur_nn` in place. + """ + while True: + if cur_nn[1] < x.size: + left_dist = x[i] - x[cur_nn[0]] + new_right_dist = x[cur_nn[1]] - x[i] + if new_right_dist < left_dist: + cur_nn[0] = cur_nn[0] + 1 + cur_nn[1] = cur_nn[1] + 1 + else: + break + else: + break + + +def _lowess_tricube(t): + """ + The _tricube function applied to a numpy array + + The tricube function is (1-abs(t)**3)**3. + + Parameters + ---------- + t : ndarray + Array the tricube function is applied to elementwise and + in-place. + + Returns + ------- + None + The modifications are made to `t` in place. + """ + # t = (1-np.abs(t)**3)**3 + t[:] = np.absolute(t) # , out=t) # numpy version? + _lowess_mycube(t) + t[:] = np.negative(t) # , out = t) + t += 1 + _lowess_mycube(t) + + +def _lowess_mycube(t): + """ + Fast matrix cube + + Parameters + ---------- + t : ndarray + Array that is cubed, elementwise and in-place + + Returns + ------- + None + The modifications are made to `t` in place. + """ + # t **= 3 + t2 = t * t + t *= t2 + + +def _lowess_bisquare(t): + """ + The bisquare function applied to a numpy array + + The bisquare function is (1-t**2)**2. + + Parameters + ---------- + t : ndarray + array bisquare function is applied to, element-wise and in-place. + + Returns + ------- + None + The modifications are made to `t` in place. + """ + # t = (1-t**2)**2 + t *= t + t[:] = np.negative(t) # , out=t) + t += 1 + t *= t diff --git a/shared/package-files/77/7791171ad2a175e81cb60ebc52050d038c90d6e7b3798bbfef80d8202392029f/blob b/shared/package-files/77/7791171ad2a175e81cb60ebc52050d038c90d6e7b3798bbfef80d8202392029f/blob new file mode 100644 index 0000000000000000000000000000000000000000..9505b19d03e8d0891cd0b53cf71d2ed16ee06c0f Binary files /dev/null and b/shared/package-files/77/7791171ad2a175e81cb60ebc52050d038c90d6e7b3798bbfef80d8202392029f/blob differ diff --git a/shared/package-files/77/7792c874706c987afa07f023e0e322f745eebf5d90f685644c051bb552ee7e52/blob b/shared/package-files/77/7792c874706c987afa07f023e0e322f745eebf5d90f685644c051bb552ee7e52/blob new file mode 100644 index 0000000000000000000000000000000000000000..c6457f54b925ba4bef8006fe56c4d46ab3f85ff3 Binary files /dev/null and b/shared/package-files/77/7792c874706c987afa07f023e0e322f745eebf5d90f685644c051bb552ee7e52/blob differ diff --git a/shared/package-files/77/7794cb496b6f585ab3320b1c25b5acadcd8bfb02b56c67dff1c1d7db52c1a74e/blob b/shared/package-files/77/7794cb496b6f585ab3320b1c25b5acadcd8bfb02b56c67dff1c1d7db52c1a74e/blob new file mode 100644 index 0000000000000000000000000000000000000000..548d1d3852b022d5c589dae53aa3556517ab112b --- /dev/null +++ b/shared/package-files/77/7794cb496b6f585ab3320b1c25b5acadcd8bfb02b56c67dff1c1d7db52c1a74e/blob @@ -0,0 +1,289 @@ +import re +from typing import Callable, Dict, Optional, Set, Union + +import torch.fx +from torch.fx.node import map_arg +from torch.fx.passes.split_module import split_module + + +__all__ = ['FoldedGraphModule', 'get_unique_attr_name_in_module', 'split_const_subgraphs'] + +class FoldedGraphModule(torch.fx.GraphModule): + """ + FoldedGraphModule is a GraphModule which also contains another + `const_subgraph_module` representing a subgraph which has all const attr + inputs and which can be run once before running the main standard + `graph`. The `const_output_names` are the ordered list names of attrs which + represent what each respective output from the const_subgraph should be set + on which attrs. + """ + + def __init__( + self, + root: torch.nn.Module, + graph: torch.fx.Graph, + const_subgraph: Optional[torch.fx.Graph] = None, + fx_const_folded_attrs_name: Optional[str] = None, + device_for_folded_attrs: str = "cuda", + ): + super().__init__(root, graph) + self.const_subgraph_module = ( + None + if const_subgraph is None + else torch.fx.GraphModule(root, const_subgraph) + ) + self.has_folding_been_run = False + self.fx_const_folded_attrs_name = fx_const_folded_attrs_name + self.device_for_folded_attrs = device_for_folded_attrs + + def __call__(self, *args, **kwargs): + if not self.has_folding_been_run: + self.run_folding() + return super().__call__(*args) + + def run_folding(self): + # If there's no const subgraph module or attr output names to use, return + # early as there is no const folding to perform. + if ( + self.const_subgraph_module is None + or self.fx_const_folded_attrs_name is None + ): + return + + assert not self.has_folding_been_run + self.has_folding_been_run = True + + # Actually run const folding subgraph. Note that single attr const fold + # subgraphs output a single Tensor while multiple outputs are returned as + # Tuple[Tensor,]. + folded_attrs = self.const_subgraph_module() + + def _create_param(i): + return torch.nn.Parameter( + i + if not isinstance(i, int) + else torch.Tensor([i]).to(device=self.device_for_folded_attrs), + requires_grad=i.requires_grad if isinstance(i, torch.Tensor) else False, + ) + + params = ( + torch.nn.ParameterList([_create_param(i) for i in folded_attrs]) + if isinstance(folded_attrs, tuple) + else _create_param(folded_attrs) + ) + setattr(self, self.fx_const_folded_attrs_name, params) + + +def _inline_module(gm: torch.fx.GraphModule, inline_mod_name: str): + """ + Given `gm` and some graph module which is called with target name `inline_mod_name`, + this helper will inline all of the nodes from that called graph module into `gm`. + """ + # Fetch the inner graph module that we want to inline inside `gm`. + inline_mod = dict(gm.named_modules())[inline_mod_name] + assert isinstance(inline_mod, torch.fx.GraphModule) + call_mod_node_to_replace = None + for node in gm.graph.nodes: + if node.op == "call_module" and node.target == inline_mod_name: + call_mod_node_to_replace = node + break + assert call_mod_node_to_replace is not None + + # Now actually do the swap. Note that we have to keep track of new nodes that are + # copied into `gm` -- we do this via replacement_mapping. + call_mod_args = call_mod_node_to_replace.args + replacement_mapping: Dict[torch.fx.Node, torch.fx.Node] = {} + ph_count = 0 + + def replacement_fn(node): + new_node = replacement_mapping[node] + new_node.meta = node.meta.copy() + return new_node + + for inline_node in inline_mod.graph.nodes: + if inline_node.op == "placeholder": + replacement_mapping[inline_node] = call_mod_args[ph_count] + ph_count += 1 + continue + + if inline_node.op == "output": + outputs = inline_node.args[0] + output_replacements = map_arg(outputs, replacement_fn) + call_mod_node_to_replace.replace_all_uses_with(output_replacements) + continue + + with gm.graph.inserting_before(call_mod_node_to_replace): + new_node = gm.graph.node_copy(inline_node, replacement_fn) + replacement_mapping[inline_node] = new_node + + gm.graph.eliminate_dead_code() + + +def get_unique_attr_name_in_module(mod_traced: torch.fx.GraphModule, name: str) -> str: + """ + Make sure the name is unique (in a module) and can represents an attr. + """ + # Delete all characters that are illegal in a Python identifier. + name = re.sub("[^0-9a-zA-Z_]+", "_", name) + if name[0].isdigit(): + name = f"_{name}" + # Now make sure it is in fact unique to the module by incrementing suffix value. + while hasattr(mod_traced, name): + match = re.match(r"(.*)_(\d+)$", name) + if match is None: + name = name + "_1" + else: + base, num = match.group(1, 2) + name = f"{base}_{int(num) + 1}" + + return name + + +def split_const_subgraphs( + module: Union[torch.nn.Module, torch.fx.GraphModule], + skip_folding_node_fn: Optional[Callable[[torch.fx.Node], bool]] = None, + device_for_folded_attrs: str = "cpu", +) -> FoldedGraphModule: + """ + Looks through `module` for any nodes that have all constant attribute inputs + and separates them out into their own constant subgraph, and returns a + FoldedGraphModule which runs that constant subgraph on the first run to set + attributes on the module prior to running the non-constant portion of the + graph. + """ + if not isinstance(module, torch.fx.GraphModule): + mod_traced = torch.fx.symbolic_trace(module) + else: + mod_traced = module + + # Build up a list of const_nodes, defined as nodes that are themselves + # get_attrs, or have all get_attr or other constant node inputs. + const_nodes: Set[torch.fx.Node] = set() + found_const_folding = False + for node in mod_traced.graph.nodes: + # Skip over placeholders/outputs because they can't be const folded and + # we don't want to add tags to them. + if node.op in {"placeholder", "output"}: + continue + + # If the node itself is constant, or all of its inputs are constant, + # then tag it as constant. + if node.op != "get_attr" and not set(node.all_input_nodes).issubset( + const_nodes + ): + continue + + # If provided skip folding function says to skip, then skip. + if skip_folding_node_fn and skip_folding_node_fn(node): + continue + + # Skip folding side-effectful functions + if node.is_impure(): + continue + + # Must be a constant foldable node at this point. + const_nodes.add(node) + if node.op != "get_attr": + found_const_folding = True + + # If we did not find any const folding then return early without a const fold subgraph. + if not found_const_folding: + return FoldedGraphModule(mod_traced, mod_traced.graph) + + # Partition the module into two: submod_0 for constant folding subgraph, and + # submod_1 for the rest. + def mod_partition(node: torch.fx.Node): + return 0 if node in const_nodes else 1 + + split = split_module(mod_traced, module, mod_partition) + + const_gm, non_const_gm = split.submod_0, split.submod_1 + const_mod_name, non_const_mod_name = "submod_0", "submod_1" + + # The module that a call_module node refers to gets copied to submodules during split. + # The path to the module also gets inlined, i.e. mod.a.b -> mod_a_b. Here we need to + # attach inlined modules to `split` as it's the owning module now. + for node in non_const_gm.graph.nodes: + if node.op == "call_module": + setattr(split, node.target, getattr(non_const_gm, node.target)) + for node in const_gm.graph.nodes: + if node.op == "call_module": + setattr(split, node.target, getattr(const_gm, node.target)) + + # split_module currently does not use get_attrs for attrs. Instead it passes + # them in as args from the parent module, which used get_attrs. Here we set + # them as get_attrs inside const_gm, allowing for running folding without + # somehow a priori knowing the attrs that should be passed as args. We can + # unconditionally do this for all placeholders because we know all + # placeholders to const_gm must be constants accessible via get_attr. + call_const_gm_args = None + for node in split.graph.nodes: + if node.op == "call_module": + if node.target == const_mod_name: + call_const_gm_args = node.args + break + assert call_const_gm_args is not None + + # Here we do the actual replacement of placeholders to get_attrs. Note that here we + # set the const_gm.graph into a new root_const_gm with split as the root module, + # because we are fetching attributes directly from the root module, instead of + # fetching them from const_gm. Example: The const_gm must have some format like: + # graph(): + # %inp : [num_users=1] = placeholder[target=const_inp] + # %add : [num_users=1] = call_function[target=operator.add](args = (%inp, %inp), kwargs = {}) + # return add + # We replace that with the following, which does not have any placeholders: + # graph(): + # %inp_1 : [num_users=1] = get_attr[target=const_inp] + # %add : [num_users=1] = call_function[target=operator.add](args = (%inp_1, %inp_1), kwargs = {}) + # return add + root_const_gm = torch.fx.GraphModule(split, const_gm.graph) + for node in root_const_gm.graph.nodes: + if node.op == "output": + multiple_outputs = isinstance(node.args[0], tuple) + continue + if node.op != "placeholder": + continue + in_node = next(n for n in call_const_gm_args if n.name == node.target) + assert in_node.op == "get_attr" + with root_const_gm.graph.inserting_before(node): + new_node = root_const_gm.graph.get_attr(in_node.target) + new_node.meta = node.meta.copy() + node.replace_all_uses_with(new_node) + root_const_gm.graph.erase_node(node) + assert "multiple_outputs" in locals() + + # Now find the call to const_gm inside split, and replace it with a getattr to the + # folded tensor(s) that result from constant folding. Note that we don't need to + # worry about whether this is one or more tensors because the original graph + # correctly uses getitem to extract individual tensors if there are multiple folded. + fx_const_folded_attrs_name = get_unique_attr_name_in_module( + split, "_FX_CONST_FOLDED_ATTRS" + ) + setattr( + split, + fx_const_folded_attrs_name, + torch.nn.ParameterList() if multiple_outputs else torch.nn.Parameter(), # type: ignore[possibly-undefined] + ) + for node in split.graph.nodes: + if node.op == "call_module" and node.target == const_mod_name: + with node.graph.inserting_before(node): + folded_attrs = node.graph.get_attr(fx_const_folded_attrs_name) + folded_attrs.meta = node.meta.copy() + node.replace_all_uses_with(folded_attrs) + break + + split.graph.eliminate_dead_code() + + # Finally, inline the non-constant submod into the split submod. This is so that the + # original caller who may have passed in a graph module will get back out a graph + # module whose graph is traced to the same granularity. + _inline_module(split, non_const_mod_name) + + return FoldedGraphModule( + split, + split.graph, + root_const_gm.graph, + fx_const_folded_attrs_name, + device_for_folded_attrs, + ) diff --git a/shared/package-files/77/779a0d53e1786234e84ca4a2344ec8411a14a6149e43ce0fb6c0e67c6ff512cd/blob b/shared/package-files/77/779a0d53e1786234e84ca4a2344ec8411a14a6149e43ce0fb6c0e67c6ff512cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..9ee59ae2ddb310d6b61583a37eb6f664dc333bbd --- /dev/null +++ b/shared/package-files/77/779a0d53e1786234e84ca4a2344ec8411a14a6149e43ce0fb6c0e67c6ff512cd/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor cov(const at::Tensor & self, int64_t correction=1, const c10::optional & fweights={}, const c10::optional & aweights={}); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/779a219d6ed2ed282f9416ee04fe65f92a1c90606cf6e93a61cebfc3aa96c982/blob b/shared/package-files/77/779a219d6ed2ed282f9416ee04fe65f92a1c90606cf6e93a61cebfc3aa96c982/blob new file mode 100644 index 0000000000000000000000000000000000000000..b4ee9b08a2312a66c23a23957f295ec831ece9aa Binary files /dev/null and b/shared/package-files/77/779a219d6ed2ed282f9416ee04fe65f92a1c90606cf6e93a61cebfc3aa96c982/blob differ diff --git a/shared/package-files/77/779a6a6c0255729d337fb2c69637fb7977882a05b27818195397443c13832736/blob b/shared/package-files/77/779a6a6c0255729d337fb2c69637fb7977882a05b27818195397443c13832736/blob new file mode 100644 index 0000000000000000000000000000000000000000..9a3112bf9823fa74617d108dc427012e5ccc1f33 --- /dev/null +++ b/shared/package-files/77/779a6a6c0255729d337fb2c69637fb7977882a05b27818195397443c13832736/blob @@ -0,0 +1,13 @@ +*** Mon, 25 Jul 2016 13:50:44 *** +TEST FOR GRANGER-CAUSALITY: +H0: "Dp" do not Granger-cause "R" + +Test statistic l = 0.4480 +pval-F( l; 4, 174) = 0.7738 + +TEST FOR INSTANTANEOUS CAUSALITY: +H0: No instantaneous causality between "Dp" and "R" + +Test statistic: c = 0.6101 +pval-Chi( c; 1) = 0.4348 + diff --git a/shared/package-files/77/779af4c08360cf6ef80504d7bd09a70b74b7a80a4276a66cfb7c705cb64e4766/blob b/shared/package-files/77/779af4c08360cf6ef80504d7bd09a70b74b7a80a4276a66cfb7c705cb64e4766/blob new file mode 100644 index 0000000000000000000000000000000000000000..2c8456c6c06803d1f1bc6f51845014847fc6b034 --- /dev/null +++ b/shared/package-files/77/779af4c08360cf6ef80504d7bd09a70b74b7a80a4276a66cfb7c705cb64e4766/blob @@ -0,0 +1,1526 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas.errors import SettingWithCopyWarning +import pandas.util._test_decorators as td + +from pandas.core.dtypes.base import _registry as ea_registry +from pandas.core.dtypes.common import is_object_dtype +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + DatetimeTZDtype, + IntervalDtype, + PeriodDtype, +) + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + Index, + Interval, + IntervalIndex, + MultiIndex, + NaT, + Period, + PeriodIndex, + Series, + Timestamp, + cut, + date_range, + notna, + period_range, +) +import pandas._testing as tm +from pandas.core.arrays import SparseArray + +from pandas.tseries.offsets import BDay + + +class TestDataFrameSetItem: + def test_setitem_str_subclass(self): + # GH#37366 + class mystring(str): + pass + + data = ["2020-10-22 01:21:00+00:00"] + index = DatetimeIndex(data) + df = DataFrame({"a": [1]}, index=index) + df["b"] = 2 + df[mystring("c")] = 3 + expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index) + tm.assert_equal(df, expected) + + @pytest.mark.parametrize( + "dtype", ["int32", "int64", "uint32", "uint64", "float32", "float64"] + ) + def test_setitem_dtype(self, dtype, float_frame): + # Use integers since casting negative floats to uints is undefined + arr = np.random.default_rng(2).integers(1, 10, len(float_frame)) + + float_frame[dtype] = np.array(arr, dtype=dtype) + assert float_frame[dtype].dtype.name == dtype + + def test_setitem_list_not_dataframe(self, float_frame): + data = np.random.default_rng(2).standard_normal((len(float_frame), 2)) + float_frame[["A", "B"]] = data + tm.assert_almost_equal(float_frame[["A", "B"]].values, data) + + def test_setitem_error_msmgs(self): + # GH 7432 + df = DataFrame( + {"bar": [1, 2, 3], "baz": ["d", "e", "f"]}, + index=Index(["a", "b", "c"], name="foo"), + ) + ser = Series( + ["g", "h", "i", "j"], + index=Index(["a", "b", "c", "a"], name="foo"), + name="fiz", + ) + msg = "cannot reindex on an axis with duplicate labels" + with pytest.raises(ValueError, match=msg): + df["newcol"] = ser + + # GH 4107, more descriptive error message + df = DataFrame( + np.random.default_rng(2).integers(0, 2, (4, 4)), + columns=["a", "b", "c", "d"], + ) + + msg = "Cannot set a DataFrame with multiple columns to the single column gr" + with pytest.raises(ValueError, match=msg): + df["gr"] = df.groupby(["b", "c"]).count() + + # GH 55956, specific message for zero columns + msg = "Cannot set a DataFrame without columns to the column gr" + with pytest.raises(ValueError, match=msg): + df["gr"] = DataFrame() + + def test_setitem_benchmark(self): + # from the vb_suite/frame_methods/frame_insert_columns + N = 10 + K = 5 + df = DataFrame(index=range(N)) + new_col = np.random.default_rng(2).standard_normal(N) + for i in range(K): + df[i] = new_col + expected = DataFrame(np.repeat(new_col, K).reshape(N, K), index=range(N)) + tm.assert_frame_equal(df, expected) + + def test_setitem_different_dtype(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), + index=np.arange(5), + columns=["c", "b", "a"], + ) + df.insert(0, "foo", df["a"]) + df.insert(2, "bar", df["c"]) + + # diff dtype + + # new item + df["x"] = df["a"].astype("float32") + result = df.dtypes + expected = Series( + [np.dtype("float64")] * 5 + [np.dtype("float32")], + index=["foo", "c", "bar", "b", "a", "x"], + ) + tm.assert_series_equal(result, expected) + + # replacing current (in different block) + df["a"] = df["a"].astype("float32") + result = df.dtypes + expected = Series( + [np.dtype("float64")] * 4 + [np.dtype("float32")] * 2, + index=["foo", "c", "bar", "b", "a", "x"], + ) + tm.assert_series_equal(result, expected) + + df["y"] = df["a"].astype("int32") + result = df.dtypes + expected = Series( + [np.dtype("float64")] * 4 + [np.dtype("float32")] * 2 + [np.dtype("int32")], + index=["foo", "c", "bar", "b", "a", "x", "y"], + ) + tm.assert_series_equal(result, expected) + + def test_setitem_overwrite_index(self): + # GH 13522 - assign the index as a column and then overwrite the values + # -> should not affect the index + df = DataFrame(index=["A", "B", "C"]) + df["X"] = df.index + df["X"] = ["x", "y", "z"] + exp = DataFrame( + data={"X": ["x", "y", "z"]}, index=["A", "B", "C"], columns=["X"] + ) + tm.assert_frame_equal(df, exp) + + def test_setitem_empty_columns(self): + # Starting from an empty DataFrame and setting a column should result + # in a default string dtype for the columns' Index + # https://github.com/pandas-dev/pandas/issues/60338 + + df = DataFrame() + df["foo"] = [1, 2, 3] + expected = DataFrame({"foo": [1, 2, 3]}) + tm.assert_frame_equal(df, expected) + + df = DataFrame(columns=Index([])) + df["foo"] = [1, 2, 3] + expected = DataFrame({"foo": [1, 2, 3]}) + tm.assert_frame_equal(df, expected) + + def test_setitem_dt64_index_empty_columns(self): + rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") + df = DataFrame(index=np.arange(len(rng))) + + df["A"] = rng + assert df["A"].dtype == np.dtype("M8[ns]") + + def test_setitem_timestamp_empty_columns(self): + # GH#19843 + df = DataFrame(index=range(3)) + df["now"] = Timestamp("20130101", tz="UTC").as_unit("ns") + + expected = DataFrame( + [[Timestamp("20130101", tz="UTC")]] * 3, index=range(3), columns=["now"] + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_wrong_length_categorical_dtype_raises(self): + # GH#29523 + cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) + df = DataFrame(range(10), columns=["bar"]) + + msg = ( + rf"Length of values \({len(cat)}\) " + rf"does not match length of index \({len(df)}\)" + ) + with pytest.raises(ValueError, match=msg): + df["foo"] = cat + + def test_setitem_with_sparse_value(self): + # GH#8131 + df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) + sp_array = SparseArray([0, 0, 1]) + df["new_column"] = sp_array + + expected = Series(sp_array, name="new_column") + tm.assert_series_equal(df["new_column"], expected) + + def test_setitem_with_unaligned_sparse_value(self): + df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) + sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0]) + + df["new_column"] = sp_series + expected = Series(SparseArray([1, 0, 0]), name="new_column") + tm.assert_series_equal(df["new_column"], expected) + + def test_setitem_period_preserves_dtype(self): + # GH: 26861 + data = [Period("2003-12", "D")] + result = DataFrame([]) + result["a"] = data + + expected = DataFrame({"a": data}, columns=["a"]) + + tm.assert_frame_equal(result, expected) + + def test_setitem_dict_preserves_dtypes(self): + # https://github.com/pandas-dev/pandas/issues/34573 + expected = DataFrame( + { + "a": Series([0, 1, 2], dtype="int64"), + "b": Series([1, 2, 3], dtype=float), + "c": Series([1, 2, 3], dtype=float), + "d": Series([1, 2, 3], dtype="uint32"), + } + ) + df = DataFrame( + { + "a": Series([], dtype="int64"), + "b": Series([], dtype=float), + "c": Series([], dtype=float), + "d": Series([], dtype="uint32"), + } + ) + for idx, b in enumerate([1, 2, 3]): + df.loc[df.shape[0]] = { + "a": int(idx), + "b": float(b), + "c": float(b), + "d": np.uint32(b), + } + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "obj,dtype", + [ + (Period("2020-01"), PeriodDtype("M")), + (Interval(left=0, right=5), IntervalDtype("int64", "right")), + ( + Timestamp("2011-01-01", tz="US/Eastern"), + DatetimeTZDtype(unit="s", tz="US/Eastern"), + ), + ], + ) + def test_setitem_extension_types(self, obj, dtype): + # GH: 34832 + expected = DataFrame({"idx": [1, 2, 3], "obj": Series([obj] * 3, dtype=dtype)}) + + df = DataFrame({"idx": [1, 2, 3]}) + df["obj"] = obj + + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "ea_name", + [ + dtype.name + for dtype in ea_registry.dtypes + # property would require instantiation + if not isinstance(dtype.name, property) + ] + + ["datetime64[ns, UTC]", "period[D]"], + ) + def test_setitem_with_ea_name(self, ea_name): + # GH 38386 + result = DataFrame([0]) + result[ea_name] = [1] + expected = DataFrame({0: [0], ea_name: [1]}) + tm.assert_frame_equal(result, expected) + + def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self): + # GH#7492 + data_ns = np.array([1, "nat"], dtype="datetime64[ns]") + result = Series(data_ns).to_frame() + result["new"] = data_ns + expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + # OutOfBoundsDatetime error shouldn't occur; as of 2.0 we preserve "M8[s]" + data_s = np.array([1, "nat"], dtype="datetime64[s]") + result["new"] = data_s + tm.assert_series_equal(result[0], expected[0]) + tm.assert_numpy_array_equal(result["new"].to_numpy(), data_s) + + @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) + def test_frame_setitem_datetime64_col_other_units(self, unit): + # Check that non-nano dt64 values get cast to dt64 on setitem + # into a not-yet-existing column + n = 100 + + dtype = np.dtype(f"M8[{unit}]") + vals = np.arange(n, dtype=np.int64).view(dtype) + if unit in ["s", "ms"]: + # supported unit + ex_vals = vals + else: + # we get the nearest supported units, i.e. "s" + ex_vals = vals.astype("datetime64[s]") + + df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) + df[unit] = vals + + assert df[unit].dtype == ex_vals.dtype + assert (df[unit].values == ex_vals).all() + + @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) + def test_frame_setitem_existing_datetime64_col_other_units(self, unit): + # Check that non-nano dt64 values get cast to dt64 on setitem + # into an already-existing dt64 column + n = 100 + + dtype = np.dtype(f"M8[{unit}]") + vals = np.arange(n, dtype=np.int64).view(dtype) + ex_vals = vals.astype("datetime64[ns]") + + df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) + df["dates"] = np.arange(n, dtype=np.int64).view("M8[ns]") + + # We overwrite existing dt64 column with new, non-nano dt64 vals + df["dates"] = vals + assert (df["dates"].values == ex_vals).all() + + def test_setitem_dt64tz(self, timezone_frame, using_copy_on_write): + df = timezone_frame + idx = df["B"].rename("foo") + + # setitem + df["C"] = idx + tm.assert_series_equal(df["C"], Series(idx, name="C")) + + df["D"] = "foo" + df["D"] = idx + tm.assert_series_equal(df["D"], Series(idx, name="D")) + del df["D"] + + # assert that A & C are not sharing the same base (e.g. they + # are copies) + # Note: This does not hold with Copy on Write (because of lazy copying) + v1 = df._mgr.arrays[1] + v2 = df._mgr.arrays[2] + tm.assert_extension_array_equal(v1, v2) + v1base = v1._ndarray.base + v2base = v2._ndarray.base + if not using_copy_on_write: + assert v1base is None or (id(v1base) != id(v2base)) + else: + assert id(v1base) == id(v2base) + + # with nan + df2 = df.copy() + df2.iloc[1, 1] = NaT + df2.iloc[1, 2] = NaT + result = df2["B"] + tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) + tm.assert_series_equal(df2.dtypes, df.dtypes) + + def test_setitem_periodindex(self): + rng = period_range("1/1/2000", periods=5, name="index") + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), index=rng) + + df["Index"] = rng + rs = Index(df["Index"]) + tm.assert_index_equal(rs, rng, check_names=False) + assert rs.name == "Index" + assert rng.name == "index" + + rs = df.reset_index().set_index("index") + assert isinstance(rs.index, PeriodIndex) + tm.assert_index_equal(rs.index, rng) + + def test_setitem_complete_column_with_array(self): + # GH#37954 + df = DataFrame({"a": ["one", "two", "three"], "b": [1, 2, 3]}) + arr = np.array([[1, 1], [3, 1], [5, 1]]) + df[["c", "d"]] = arr + expected = DataFrame( + { + "a": ["one", "two", "three"], + "b": [1, 2, 3], + "c": [1, 3, 5], + "d": [1, 1, 1], + } + ) + expected["c"] = expected["c"].astype(arr.dtype) + expected["d"] = expected["d"].astype(arr.dtype) + assert expected["c"].dtype == arr.dtype + assert expected["d"].dtype == arr.dtype + tm.assert_frame_equal(df, expected) + + def test_setitem_period_d_dtype(self): + # GH 39763 + rng = period_range("2016-01-01", periods=9, freq="D", name="A") + result = DataFrame(rng) + expected = DataFrame( + {"A": ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT"]}, + dtype="period[D]", + ) + result.iloc[:] = rng._na_value + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["f8", "i8", "u8"]) + def test_setitem_bool_with_numeric_index(self, dtype): + # GH#36319 + cols = Index([1, 2, 3], dtype=dtype) + df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)), columns=cols) + + df[False] = ["a", "b", "c"] + + expected_cols = Index([1, 2, 3, False], dtype=object) + if dtype == "f8": + expected_cols = Index([1.0, 2.0, 3.0, False], dtype=object) + + tm.assert_index_equal(df.columns, expected_cols) + + @pytest.mark.parametrize("indexer", ["B", ["B"]]) + def test_setitem_frame_length_0_str_key(self, indexer): + # GH#38831 + df = DataFrame(columns=["A", "B"]) + other = DataFrame({"B": [1, 2]}) + df[indexer] = other + expected = DataFrame({"A": [np.nan] * 2, "B": [1, 2]}) + expected["A"] = expected["A"].astype("object") + tm.assert_frame_equal(df, expected) + + def test_setitem_frame_duplicate_columns(self): + # GH#15695 + cols = ["A", "B", "C"] * 2 + df = DataFrame(index=range(3), columns=cols) + df.loc[0, "A"] = (0, 3) + df.loc[:, "B"] = (1, 4) + df["C"] = (2, 5) + expected = DataFrame( + [ + [0, 1, 2, 3, 4, 5], + [np.nan, 1, 2, np.nan, 4, 5], + [np.nan, 1, 2, np.nan, 4, 5], + ], + dtype="object", + ) + + # set these with unique columns to be extra-unambiguous + expected[2] = expected[2].astype(np.int64) + expected[5] = expected[5].astype(np.int64) + expected.columns = cols + + tm.assert_frame_equal(df, expected) + + def test_setitem_frame_duplicate_columns_size_mismatch(self): + # GH#39510 + cols = ["A", "B", "C"] * 2 + df = DataFrame(index=range(3), columns=cols) + with pytest.raises(ValueError, match="Columns must be same length as key"): + df[["A"]] = (0, 3, 5) + + df2 = df.iloc[:, :3] # unique columns + with pytest.raises(ValueError, match="Columns must be same length as key"): + df2[["A"]] = (0, 3, 5) + + @pytest.mark.parametrize("cols", [["a", "b", "c"], ["a", "a", "a"]]) + def test_setitem_df_wrong_column_number(self, cols): + # GH#38604 + df = DataFrame([[1, 2, 3]], columns=cols) + rhs = DataFrame([[10, 11]], columns=["d", "e"]) + msg = "Columns must be same length as key" + with pytest.raises(ValueError, match=msg): + df["a"] = rhs + + def test_setitem_listlike_indexer_duplicate_columns(self): + # GH#38604 + df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"]) + rhs = DataFrame([[10, 11, 12]], columns=["a", "b", "b"]) + df[["a", "b"]] = rhs + expected = DataFrame([[10, 11, 12]], columns=["a", "b", "b"]) + tm.assert_frame_equal(df, expected) + + df[["c", "b"]] = rhs + expected = DataFrame([[10, 11, 12, 10]], columns=["a", "b", "b", "c"]) + tm.assert_frame_equal(df, expected) + + def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self): + # GH#39403 + df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"]) + rhs = DataFrame([[10, 11]], columns=["a", "b"]) + msg = "Columns must be same length as key" + with pytest.raises(ValueError, match=msg): + df[["a", "b"]] = rhs + + def test_setitem_intervals(self): + df = DataFrame({"A": range(10)}) + ser = cut(df["A"], 5) + assert isinstance(ser.cat.categories, IntervalIndex) + + # B & D end up as Categoricals + # the remainder are converted to in-line objects + # containing an IntervalIndex.values + df["B"] = ser + df["C"] = np.array(ser) + df["D"] = ser.values + df["E"] = np.array(ser.values) + df["F"] = ser.astype(object) + + assert isinstance(df["B"].dtype, CategoricalDtype) + assert isinstance(df["B"].cat.categories.dtype, IntervalDtype) + assert isinstance(df["D"].dtype, CategoricalDtype) + assert isinstance(df["D"].cat.categories.dtype, IntervalDtype) + + # These go through the Series constructor and so get inferred back + # to IntervalDtype + assert isinstance(df["C"].dtype, IntervalDtype) + assert isinstance(df["E"].dtype, IntervalDtype) + + # But the Series constructor doesn't do inference on Series objects, + # so setting df["F"] doesn't get cast back to IntervalDtype + assert is_object_dtype(df["F"]) + + # they compare equal as Index + # when converted to numpy objects + c = lambda x: Index(np.array(x)) + tm.assert_index_equal(c(df.B), c(df.B)) + tm.assert_index_equal(c(df.B), c(df.C), check_names=False) + tm.assert_index_equal(c(df.B), c(df.D), check_names=False) + tm.assert_index_equal(c(df.C), c(df.D), check_names=False) + + # B & D are the same Series + tm.assert_series_equal(df["B"], df["B"]) + tm.assert_series_equal(df["B"], df["D"], check_names=False) + + # C & E are the same Series + tm.assert_series_equal(df["C"], df["C"]) + tm.assert_series_equal(df["C"], df["E"], check_names=False) + + def test_setitem_categorical(self): + # GH#35369 + df = DataFrame({"h": Series(list("mn")).astype("category")}) + df.h = df.h.cat.reorder_categories(["n", "m"]) + expected = DataFrame( + {"h": Categorical(["m", "n"]).reorder_categories(["n", "m"])} + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_with_empty_listlike(self): + # GH#17101 + index = Index([], name="idx") + result = DataFrame(columns=["A"], index=index) + result["A"] = [] + expected = DataFrame(columns=["A"], index=index) + tm.assert_index_equal(result.index, expected.index) + + @pytest.mark.parametrize( + "cols, values, expected", + [ + (["C", "D", "D", "a"], [1, 2, 3, 4], 4), # with duplicates + (["D", "C", "D", "a"], [1, 2, 3, 4], 4), # mixed order + (["C", "B", "B", "a"], [1, 2, 3, 4], 4), # other duplicate cols + (["C", "B", "a"], [1, 2, 3], 3), # no duplicates + (["B", "C", "a"], [3, 2, 1], 1), # alphabetical order + (["C", "a", "B"], [3, 2, 1], 2), # in the middle + ], + ) + def test_setitem_same_column(self, cols, values, expected): + # GH#23239 + df = DataFrame([values], columns=cols) + df["a"] = df["a"] + result = df["a"].values[0] + assert result == expected + + def test_setitem_multi_index(self): + # GH#7655, test that assigning to a sub-frame of a frame + # with multi-index columns aligns both rows and columns + it = ["jim", "joe", "jolie"], ["first", "last"], ["left", "center", "right"] + + cols = MultiIndex.from_product(it) + index = date_range("20141006", periods=20) + vals = np.random.default_rng(2).integers(1, 1000, (len(index), len(cols))) + df = DataFrame(vals, columns=cols, index=index) + + i, j = df.index.values.copy(), it[-1][:] + + np.random.default_rng(2).shuffle(i) + df["jim"] = df["jolie"].loc[i, ::-1] + tm.assert_frame_equal(df["jim"], df["jolie"]) + + np.random.default_rng(2).shuffle(j) + df[("joe", "first")] = df[("jolie", "last")].loc[i, j] + tm.assert_frame_equal(df[("joe", "first")], df[("jolie", "last")]) + + np.random.default_rng(2).shuffle(j) + df[("joe", "last")] = df[("jolie", "first")].loc[i, j] + tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")]) + + @pytest.mark.parametrize( + "columns,box,expected", + [ + ( + ["A", "B", "C", "D"], + 7, + DataFrame( + [[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["C", "D"], + [7, 8], + DataFrame( + [[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["A", "B", "C"], + np.array([7, 8, 9], dtype=np.int64), + DataFrame([[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"]), + ), + ( + ["B", "C", "D"], + [[7, 8, 9], [10, 11, 12], [13, 14, 15]], + DataFrame( + [[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["C", "A", "D"], + np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64), + DataFrame( + [[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["A", "C"], + DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]), + DataFrame( + [[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"] + ), + ), + ], + ) + def test_setitem_list_missing_columns(self, columns, box, expected): + # GH#29334 + df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"]) + df[columns] = box + tm.assert_frame_equal(df, expected) + + def test_setitem_list_of_tuples(self, float_frame): + tuples = list(zip(float_frame["A"], float_frame["B"])) + float_frame["tuples"] = tuples + + result = float_frame["tuples"] + expected = Series(tuples, index=float_frame.index, name="tuples") + tm.assert_series_equal(result, expected) + + def test_setitem_iloc_generator(self): + # GH#39614 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + indexer = (x for x in [1, 2]) + df.iloc[indexer] = 1 + expected = DataFrame({"a": [1, 1, 1], "b": [4, 1, 1]}) + tm.assert_frame_equal(df, expected) + + def test_setitem_iloc_two_dimensional_generator(self): + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + indexer = (x for x in [1, 2]) + df.iloc[indexer, 1] = 1 + expected = DataFrame({"a": [1, 2, 3], "b": [4, 1, 1]}) + tm.assert_frame_equal(df, expected) + + def test_setitem_dtypes_bytes_type_to_object(self): + # GH 20734 + index = Series(name="id", dtype="S24") + df = DataFrame(index=index, columns=Index([], dtype="str")) + df["a"] = Series(name="a", index=index, dtype=np.uint32) + df["b"] = Series(name="b", index=index, dtype="S64") + df["c"] = Series(name="c", index=index, dtype="S64") + df["d"] = Series(name="d", index=index, dtype=np.uint8) + result = df.dtypes + expected = Series([np.uint32, object, object, np.uint8], index=list("abcd")) + tm.assert_series_equal(result, expected) + + def test_boolean_mask_nullable_int64(self): + # GH 28928 + result = DataFrame({"a": [3, 4], "b": [5, 6]}).astype( + {"a": "int64", "b": "Int64"} + ) + mask = Series(False, index=result.index) + result.loc[mask, "a"] = result["a"] + result.loc[mask, "b"] = result["b"] + expected = DataFrame({"a": [3, 4], "b": [5, 6]}).astype( + {"a": "int64", "b": "Int64"} + ) + tm.assert_frame_equal(result, expected) + + def test_setitem_ea_dtype_rhs_series(self): + # GH#47425 + df = DataFrame({"a": [1, 2]}) + df["a"] = Series([1, 2], dtype="Int64") + expected = DataFrame({"a": [1, 2]}, dtype="Int64") + tm.assert_frame_equal(df, expected) + + # TODO(ArrayManager) set column with 2d column array, see #44788 + @td.skip_array_manager_not_yet_implemented + def test_setitem_npmatrix_2d(self): + # GH#42376 + # for use-case df["x"] = sparse.random((10, 10)).mean(axis=1) + expected = DataFrame( + {"np-array": np.ones(10), "np-matrix": np.ones(10)}, index=np.arange(10) + ) + + a = np.ones((10, 1)) + df = DataFrame(index=np.arange(10), columns=Index([], dtype="str")) + df["np-array"] = a + + # Instantiation of `np.matrix` gives PendingDeprecationWarning + with tm.assert_produces_warning(PendingDeprecationWarning): + df["np-matrix"] = np.matrix(a) + + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("vals", [{}, {"d": "a"}]) + def test_setitem_aligning_dict_with_index(self, vals): + # GH#47216 + df = DataFrame({"a": [1, 2], "b": [3, 4], **vals}) + df.loc[:, "a"] = {1: 100, 0: 200} + df.loc[:, "c"] = {0: 5, 1: 6} + df.loc[:, "e"] = {1: 5} + expected = DataFrame( + {"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6], "e": [np.nan, 5]} + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_rhs_dataframe(self): + # GH#47578 + df = DataFrame({"a": [1, 2]}) + df["a"] = DataFrame({"a": [10, 11]}, index=[1, 2]) + expected = DataFrame({"a": [np.nan, 10]}) + tm.assert_frame_equal(df, expected) + + df = DataFrame({"a": [1, 2]}) + df.isetitem(0, DataFrame({"a": [10, 11]}, index=[1, 2])) + tm.assert_frame_equal(df, expected) + + def test_setitem_frame_overwrite_with_ea_dtype(self, any_numeric_ea_dtype): + # GH#46896 + df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]]) + df["a"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype) + expected = DataFrame( + { + "a": Series([10, 11], dtype=any_numeric_ea_dtype), + "b": [2, 4], + } + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_string_option_object_index(self): + # GH#55638 + pytest.importorskip("pyarrow") + df = DataFrame({"a": [1, 2]}) + with pd.option_context("future.infer_string", True): + df["b"] = Index(["a", "b"], dtype=object) + expected = DataFrame({"a": [1, 2], "b": Series(["a", "b"], dtype=object)}) + tm.assert_frame_equal(df, expected) + + def test_setitem_frame_midx_columns(self): + # GH#49121 + df = DataFrame({("a", "b"): [10]}) + expected = df.copy() + col_name = ("a", "b") + df[col_name] = df[[col_name]] + tm.assert_frame_equal(df, expected) + + def test_loc_setitem_ea_dtype(self): + # GH#55604 + df = DataFrame({"a": np.array([10], dtype="i8")}) + df.loc[:, "a"] = Series([11], dtype="Int64") + expected = DataFrame({"a": np.array([11], dtype="i8")}) + tm.assert_frame_equal(df, expected) + + df = DataFrame({"a": np.array([10], dtype="i8")}) + df.iloc[:, 0] = Series([11], dtype="Int64") + tm.assert_frame_equal(df, expected) + + def test_setitem_object_inferring(self): + # GH#56102 + idx = Index([Timestamp("2019-12-31")], dtype=object) + df = DataFrame({"a": [1]}) + with tm.assert_produces_warning(FutureWarning, match="infer"): + df.loc[:, "b"] = idx + with tm.assert_produces_warning(FutureWarning, match="infer"): + df["c"] = idx + + expected = DataFrame( + { + "a": [1], + "b": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"), + "c": Series([Timestamp("2019-12-31")], dtype="datetime64[ns]"), + } + ) + tm.assert_frame_equal(df, expected) + + +class TestSetitemTZAwareValues: + @pytest.fixture + def idx(self): + naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") + idx = naive.tz_localize("US/Pacific") + return idx + + @pytest.fixture + def expected(self, idx): + expected = Series(np.array(idx.tolist(), dtype="object"), name="B") + assert expected.dtype == idx.dtype + return expected + + def test_setitem_dt64series(self, idx, expected): + # convert to utc + df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"]) + df["B"] = idx + df["B"] = idx.to_series(index=[0, 1]).dt.tz_convert(None) + + result = df["B"] + comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B") + tm.assert_series_equal(result, comp) + + def test_setitem_datetimeindex(self, idx, expected): + # setting a DataFrame column with a tzaware DTI retains the dtype + df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"]) + + # assign to frame + df["B"] = idx + result = df["B"] + tm.assert_series_equal(result, expected) + + def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected): + # setting a DataFrame column with a tzaware DTI retains the dtype + df = DataFrame(np.random.default_rng(2).standard_normal((2, 1)), columns=["A"]) + + # object array of datetimes with a tz + df["B"] = idx.to_pydatetime() + result = df["B"] + tm.assert_series_equal(result, expected) + + +class TestDataFrameSetItemWithExpansion: + def test_setitem_listlike_views(self, using_copy_on_write, warn_copy_on_write): + # GH#38148 + df = DataFrame({"a": [1, 2, 3], "b": [4, 4, 6]}) + + # get one column as a view of df + ser = df["a"] + + # add columns with list-like indexer + df[["c", "d"]] = np.array([[0.1, 0.2], [0.3, 0.4], [0.4, 0.5]]) + + # edit in place the first column to check view semantics + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 + + if using_copy_on_write: + expected = Series([1, 2, 3], name="a") + else: + expected = Series([100, 2, 3], name="a") + tm.assert_series_equal(ser, expected) + + def test_setitem_string_column_numpy_dtype_raising(self): + # GH#39010 + df = DataFrame([[1, 2], [3, 4]]) + df["0 - Name"] = [5, 6] + expected = DataFrame([[1, 2, 5], [3, 4, 6]], columns=[0, 1, "0 - Name"]) + tm.assert_frame_equal(df, expected) + + def test_setitem_empty_df_duplicate_columns(self, using_copy_on_write): + # GH#38521 + df = DataFrame(columns=["a", "b", "b"], dtype="float64") + df.loc[:, "a"] = list(range(2)) + expected = DataFrame( + [[0, np.nan, np.nan], [1, np.nan, np.nan]], columns=["a", "b", "b"] + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_with_expansion_categorical_dtype(self): + # assignment + df = DataFrame( + { + "value": np.array( + np.random.default_rng(2).integers(0, 10000, 100), dtype="int32" + ) + } + ) + labels = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + + df = df.sort_values(by=["value"], ascending=True) + ser = cut(df.value, range(0, 10500, 500), right=False, labels=labels) + cat = ser.values + + # setting with a Categorical + df["D"] = cat + result = df.dtypes + expected = Series( + [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], + index=["value", "D"], + ) + tm.assert_series_equal(result, expected) + + # setting with a Series + df["E"] = ser + result = df.dtypes + expected = Series( + [ + np.dtype("int32"), + CategoricalDtype(categories=labels, ordered=False), + CategoricalDtype(categories=labels, ordered=False), + ], + index=["value", "D", "E"], + ) + tm.assert_series_equal(result, expected) + + result1 = df["D"] + result2 = df["E"] + tm.assert_categorical_equal(result1._mgr.array, cat) + + # sorting + ser.name = "E" + tm.assert_series_equal(result2.sort_index(), ser.sort_index()) + + def test_setitem_scalars_no_index(self): + # GH#16823 / GH#17894 + df = DataFrame() + df["foo"] = 1 + expected = DataFrame(columns=["foo"]).astype(np.int64) + tm.assert_frame_equal(df, expected) + + def test_setitem_newcol_tuple_key(self, float_frame): + assert ( + "A", + "B", + ) not in float_frame.columns + float_frame["A", "B"] = float_frame["A"] + assert ("A", "B") in float_frame.columns + + result = float_frame["A", "B"] + expected = float_frame["A"] + tm.assert_series_equal(result, expected, check_names=False) + + def test_frame_setitem_newcol_timestamp(self): + # GH#2155 + columns = date_range(start="1/1/2012", end="2/1/2012", freq=BDay()) + data = DataFrame(columns=columns, index=range(10)) + t = datetime(2012, 11, 1) + ts = Timestamp(t) + data[ts] = np.nan # works, mostly a smoke-test + assert np.isnan(data[ts]).all() + + def test_frame_setitem_rangeindex_into_new_col(self): + # GH#47128 + df = DataFrame({"a": ["a", "b"]}) + df["b"] = df.index + df.loc[[False, True], "b"] = 100 + result = df.loc[[1], :] + expected = DataFrame({"a": ["b"], "b": [100]}, index=[1]) + tm.assert_frame_equal(result, expected) + + def test_setitem_frame_keep_ea_dtype(self, any_numeric_ea_dtype): + # GH#46896 + df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]]) + df["c"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype) + expected = DataFrame( + { + "a": [1, 3], + "b": [2, 4], + "c": Series([10, 11], dtype=any_numeric_ea_dtype), + } + ) + tm.assert_frame_equal(df, expected) + + def test_loc_expansion_with_timedelta_type(self): + result = DataFrame(columns=list("abc")) + result.loc[0] = { + "a": pd.to_timedelta(5, unit="s"), + "b": pd.to_timedelta(72, unit="s"), + "c": "23", + } + expected = DataFrame( + [[pd.Timedelta("0 days 00:00:05"), pd.Timedelta("0 days 00:01:12"), "23"]], + index=Index([0]), + columns=(["a", "b", "c"]), + ) + tm.assert_frame_equal(result, expected) + + +class TestDataFrameSetItemSlicing: + def test_setitem_slice_position(self): + # GH#31469 + df = DataFrame(np.zeros((100, 1))) + df[-4:] = 1 + arr = np.zeros((100, 1)) + arr[-4:] = 1 + expected = DataFrame(arr) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc]) + @pytest.mark.parametrize("box", [Series, np.array, list, pd.array]) + @pytest.mark.parametrize("n", [1, 2, 3]) + def test_setitem_slice_indexer_broadcasting_rhs(self, n, box, indexer): + # GH#40440 + df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]) + indexer(df)[1:] = box([10, 11, 12]) + expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"]) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("box", [Series, np.array, list, pd.array]) + @pytest.mark.parametrize("n", [1, 2, 3]) + def test_setitem_list_indexer_broadcasting_rhs(self, n, box): + # GH#40440 + df = DataFrame([[1, 3, 5]] + [[2, 4, 6]] * n, columns=["a", "b", "c"]) + df.iloc[list(range(1, n + 1))] = box([10, 11, 12]) + expected = DataFrame([[1, 3, 5]] + [[10, 11, 12]] * n, columns=["a", "b", "c"]) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", [tm.setitem, tm.iloc]) + @pytest.mark.parametrize("box", [Series, np.array, list, pd.array]) + @pytest.mark.parametrize("n", [1, 2, 3]) + def test_setitem_slice_broadcasting_rhs_mixed_dtypes(self, n, box, indexer): + # GH#40440 + df = DataFrame( + [[1, 3, 5], ["x", "y", "z"]] + [[2, 4, 6]] * n, columns=["a", "b", "c"] + ) + indexer(df)[1:] = box([10, 11, 12]) + expected = DataFrame( + [[1, 3, 5]] + [[10, 11, 12]] * (n + 1), + columns=["a", "b", "c"], + dtype="object", + ) + tm.assert_frame_equal(df, expected) + + +class TestDataFrameSetItemCallable: + def test_setitem_callable(self): + # GH#12533 + df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}) + df[lambda x: "A"] = [11, 12, 13, 14] + + exp = DataFrame({"A": [11, 12, 13, 14], "B": [5, 6, 7, 8]}) + tm.assert_frame_equal(df, exp) + + def test_setitem_other_callable(self): + # GH#13299 + def inc(x): + return x + 1 + + # Set dtype object straight away to avoid upcast when setting inc below + df = DataFrame([[-1, 1], [1, -1]], dtype=object) + df[df > 0] = inc + + expected = DataFrame([[-1, inc], [inc, -1]]) + tm.assert_frame_equal(df, expected) + + +class TestDataFrameSetItemBooleanMask: + @td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite not using .values + @pytest.mark.parametrize( + "mask_type", + [lambda df: df > np.abs(df) / 2, lambda df: (df > np.abs(df) / 2).values], + ids=["dataframe", "array"], + ) + def test_setitem_boolean_mask(self, mask_type, float_frame): + # Test for issue #18582 + df = float_frame.copy() + mask = mask_type(df) + + # index with boolean mask + result = df.copy() + result[mask] = np.nan + + expected = df.values.copy() + expected[np.array(mask)] = np.nan + expected = DataFrame(expected, index=df.index, columns=df.columns) + tm.assert_frame_equal(result, expected) + + @pytest.mark.xfail(reason="Currently empty indexers are treated as all False") + @pytest.mark.parametrize("box", [list, np.array, Series]) + def test_setitem_loc_empty_indexer_raises_with_non_empty_value(self, box): + # GH#37672 + df = DataFrame({"a": ["a"], "b": [1], "c": [1]}) + if box == Series: + indexer = box([], dtype="object") + else: + indexer = box([]) + msg = "Must have equal len keys and value when setting with an iterable" + with pytest.raises(ValueError, match=msg): + df.loc[indexer, ["b"]] = [1] + + @pytest.mark.parametrize("box", [list, np.array, Series]) + def test_setitem_loc_only_false_indexer_dtype_changed(self, box): + # GH#37550 + # Dtype is only changed when value to set is a Series and indexer is + # empty/bool all False + df = DataFrame({"a": ["a"], "b": [1], "c": [1]}) + indexer = box([False]) + df.loc[indexer, ["b"]] = 10 - df["c"] + expected = DataFrame({"a": ["a"], "b": [1], "c": [1]}) + tm.assert_frame_equal(df, expected) + + df.loc[indexer, ["b"]] = 9 + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc]) + def test_setitem_boolean_mask_aligning(self, indexer): + # GH#39931 + df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]}) + expected = df.copy() + mask = df["a"] >= 3 + indexer(df)[mask] = indexer(df)[mask].sort_values("a") + tm.assert_frame_equal(df, expected) + + def test_setitem_mask_categorical(self): + # assign multiple rows (mixed values) (-> array) -> exp_multi_row + # changed multiple rows + cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) + idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values2 = [1, 1, 2, 2, 1, 1, 1] + exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) + + catsf = Categorical( + ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] + ) + idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) + valuesf = [1, 1, 3, 3, 1, 1, 1] + df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) + + exp_fancy = exp_multi_row.copy() + exp_fancy["cats"] = exp_fancy["cats"].cat.set_categories(["a", "b", "c"]) + + mask = df["cats"] == "c" + df[mask] = ["b", 2] + # category c is kept in .categories + tm.assert_frame_equal(df, exp_fancy) + + @pytest.mark.parametrize("dtype", ["float", "int64"]) + @pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}]) + def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): + # see GH#10126 + kwargs["dtype"] = dtype + df = DataFrame(**kwargs) + + df2 = df.copy() + df[df > df2] = 47 + tm.assert_frame_equal(df, df2) + + def test_setitem_boolean_indexing(self): + idx = list(range(3)) + cols = ["A", "B", "C"] + df1 = DataFrame( + index=idx, + columns=cols, + data=np.array( + [[0.0, 0.5, 1.0], [1.5, 2.0, 2.5], [3.0, 3.5, 4.0]], dtype=float + ), + ) + df2 = DataFrame(index=idx, columns=cols, data=np.ones((len(idx), len(cols)))) + + expected = DataFrame( + index=idx, + columns=cols, + data=np.array([[0.0, 0.5, 1.0], [1.5, 2.0, -1], [-1, -1, -1]], dtype=float), + ) + + df1[df1 > 2.0 * df2] = -1 + tm.assert_frame_equal(df1, expected) + with pytest.raises(ValueError, match="Item wrong length"): + df1[df1.index[:-1] > 2] = -1 + + def test_loc_setitem_all_false_boolean_two_blocks(self): + # GH#40885 + df = DataFrame({"a": [1, 2], "b": [3, 4], "c": "a"}) + expected = df.copy() + indexer = Series([False, False], name="c") + df.loc[indexer, ["b"]] = DataFrame({"b": [5, 6]}, index=[0, 1]) + tm.assert_frame_equal(df, expected) + + def test_setitem_ea_boolean_mask(self): + # GH#47125 + df = DataFrame([[-1, 2], [3, -4]]) + expected = DataFrame([[0, 2], [3, 0]]) + boolean_indexer = DataFrame( + { + 0: Series([True, False], dtype="boolean"), + 1: Series([pd.NA, True], dtype="boolean"), + } + ) + df[boolean_indexer] = 0 + tm.assert_frame_equal(df, expected) + + +class TestDataFrameSetitemCopyViewSemantics: + def test_setitem_always_copy(self, float_frame): + assert "E" not in float_frame.columns + s = float_frame["A"].copy() + float_frame["E"] = s + + float_frame.iloc[5:10, float_frame.columns.get_loc("E")] = np.nan + assert notna(s[5:10]).all() + + @pytest.mark.parametrize("consolidate", [True, False]) + def test_setitem_partial_column_inplace( + self, consolidate, using_array_manager, using_copy_on_write + ): + # This setting should be in-place, regardless of whether frame is + # single-block or multi-block + # GH#304 this used to be incorrectly not-inplace, in which case + # we needed to ensure _item_cache was cleared. + + df = DataFrame( + {"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3] + ) + df.insert(2, "z", np.nan) + if not using_array_manager: + if consolidate: + df._consolidate_inplace() + assert len(df._mgr.blocks) == 1 + else: + assert len(df._mgr.blocks) == 2 + + zvals = df["z"]._values + + df.loc[2:, "z"] = 42 + + expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z") + tm.assert_series_equal(df["z"], expected) + + # check setting occurred in-place + if not using_copy_on_write: + tm.assert_numpy_array_equal(zvals, expected.values) + assert np.shares_memory(zvals, df["z"]._values) + + def test_setitem_duplicate_columns_not_inplace(self): + # GH#39510 + cols = ["A", "B"] * 2 + df = DataFrame(0.0, index=[0], columns=cols) + df_copy = df.copy() + df_view = df[:] + df["B"] = (2, 5) + + expected = DataFrame([[0.0, 2, 0.0, 5]], columns=cols) + tm.assert_frame_equal(df_view, df_copy) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "value", [1, np.array([[1], [1]], dtype="int64"), [[1], [1]]] + ) + def test_setitem_same_dtype_not_inplace(self, value, using_array_manager): + # GH#39510 + cols = ["A", "B"] + df = DataFrame(0, index=[0, 1], columns=cols) + df_copy = df.copy() + df_view = df[:] + df[["B"]] = value + + expected = DataFrame([[0, 1], [0, 1]], columns=cols) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(df_view, df_copy) + + @pytest.mark.parametrize("value", [1.0, np.array([[1.0], [1.0]]), [[1.0], [1.0]]]) + def test_setitem_listlike_key_scalar_value_not_inplace(self, value): + # GH#39510 + cols = ["A", "B"] + df = DataFrame(0, index=[0, 1], columns=cols) + df_copy = df.copy() + df_view = df[:] + df[["B"]] = value + + expected = DataFrame([[0, 1.0], [0, 1.0]], columns=cols) + tm.assert_frame_equal(df_view, df_copy) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "indexer", + [ + "a", + ["a"], + pytest.param( + [True, False], + marks=pytest.mark.xfail( + reason="Boolean indexer incorrectly setting inplace", + strict=False, # passing on some builds, no obvious pattern + ), + ), + ], + ) + @pytest.mark.parametrize( + "value, set_value", + [ + (1, 5), + (1.0, 5.0), + (Timestamp("2020-12-31"), Timestamp("2021-12-31")), + ("a", "b"), + ], + ) + def test_setitem_not_operating_inplace(self, value, set_value, indexer): + # GH#43406 + df = DataFrame({"a": value}, index=[0, 1]) + expected = df.copy() + view = df[:] + df[indexer] = set_value + tm.assert_frame_equal(view, expected) + + @td.skip_array_manager_invalid_test + def test_setitem_column_update_inplace( + self, using_copy_on_write, warn_copy_on_write + ): + # https://github.com/pandas-dev/pandas/issues/47172 + + labels = [f"c{i}" for i in range(10)] + df = DataFrame({col: np.zeros(len(labels)) for col in labels}, index=labels) + values = df._mgr.blocks[0].values + + with tm.raises_chained_assignment_error(): + for label in df.columns: + df[label][label] = 1 + if not using_copy_on_write: + # diagonal values all updated + assert np.all(values[np.arange(10), np.arange(10)] == 1) + else: + # original dataframe not updated + assert np.all(values[np.arange(10), np.arange(10)] == 0) + + def test_setitem_column_frame_as_category(self): + # GH31581 + df = DataFrame([1, 2, 3]) + df["col1"] = DataFrame([1, 2, 3], dtype="category") + df["col2"] = Series([1, 2, 3], dtype="category") + + expected_types = Series( + ["int64", "category", "category"], index=[0, "col1", "col2"], dtype=object + ) + tm.assert_series_equal(df.dtypes, expected_types) + + @pytest.mark.parametrize("dtype", ["int64", "Int64"]) + def test_setitem_iloc_with_numpy_array(self, dtype): + # GH-33828 + df = DataFrame({"a": np.ones(3)}, dtype=dtype) + df.iloc[np.array([0]), np.array([0])] = np.array([[2]]) + + expected = DataFrame({"a": [2, 1, 1]}, dtype=dtype) + tm.assert_frame_equal(df, expected) + + def test_setitem_frame_dup_cols_dtype(self): + # GH#53143 + df = DataFrame([[1, 2, 3, 4], [4, 5, 6, 7]], columns=["a", "b", "a", "c"]) + rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"]) + df["a"] = rhs + expected = DataFrame( + [[0, 2, 1.5, 4], [2, 5, 2.5, 7]], columns=["a", "b", "a", "c"] + ) + tm.assert_frame_equal(df, expected) + + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) + rhs = DataFrame([[0, 1.5], [2, 2.5]], columns=["a", "a"]) + df["a"] = rhs + expected = DataFrame([[0, 1.5, 3], [2, 2.5, 6]], columns=["a", "a", "b"]) + tm.assert_frame_equal(df, expected) + + def test_frame_setitem_empty_dataframe(self): + # GH#28871 + dti = DatetimeIndex(["2000-01-01"], dtype="M8[ns]", name="date") + df = DataFrame({"date": dti}).set_index("date") + df = df[0:0].copy() + + df["3010"] = None + df["2010"] = None + + expected = DataFrame( + [], + columns=["3010", "2010"], + index=dti[:0], + ) + tm.assert_frame_equal(df, expected) + + def test_iloc_setitem_view_2dblock(self, using_copy_on_write, warn_copy_on_write): + # https://github.com/pandas-dev/pandas/issues/60309 + df_parent = DataFrame( + { + "A": [1, 4, 1, 5], + "B": [2, 5, 2, 6], + "C": [3, 6, 1, 7], + "D": [8, 9, 10, 11], + } + ) + df_orig = df_parent.copy() + df = df_parent[["B", "C"]] + + # Perform the iloc operation + if using_copy_on_write: + df.iloc[[1, 3], :] = [[2, 2], [2, 2]] + + # Check that original DataFrame is unchanged + tm.assert_frame_equal(df_parent, df_orig) + elif warn_copy_on_write: + # TODO(COW): should this warn? + # with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[[1, 3], :] = [[2, 2], [2, 2]] + else: + with pd.option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(SettingWithCopyWarning): + df.iloc[[1, 3], :] = [[2, 2], [2, 2]] + + # Check that df is modified correctly + expected = DataFrame({"B": [2, 2, 2, 2], "C": [3, 2, 1, 2]}, index=df.index) + tm.assert_frame_equal(df, expected) + + # with setting to subset of columns + df = df_parent[["B", "C", "D"]] + if using_copy_on_write or warn_copy_on_write: + df.iloc[[1, 3], 0:3:2] = [[2, 2], [2, 2]] + tm.assert_frame_equal(df_parent, df_orig) + else: + with pd.option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(SettingWithCopyWarning): + df.iloc[[1, 3], 0:3:2] = [[2, 2], [2, 2]] + + expected = DataFrame( + {"B": [2, 2, 2, 2], "C": [3, 6, 1, 7], "D": [8, 2, 10, 2]}, index=df.index + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "indexer, value", + [ + (([0, 2], slice(None)), [[2, 2, 2, 2], [2, 2, 2, 2]]), + ((slice(None), slice(None)), 2), + ((0, [1, 3]), [2, 2]), + (([0], 1), [2]), + (([0], np.int64(1)), [2]), + ((slice(None), np.int64(1)), [2, 2, 2]), + ((slice(None, 2), np.int64(1)), [2, 2]), + ( + (np.array([False, True, False]), np.array([False, True, False, True])), + [2, 2], + ), + ], + ) + def test_setitem_2dblock_with_ref( + self, indexer, value, using_copy_on_write, warn_copy_on_write + ): + # https://github.com/pandas-dev/pandas/issues/60309 + arr = np.arange(12).reshape(3, 4) + + df_parent = DataFrame(arr.copy(), columns=list("ABCD")) + # the test is specifically for the case where the df is backed by a single + # block (taking the non-split path) + assert df_parent._mgr.is_single_block + df_orig = df_parent.copy() + df = df_parent[:] + + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[indexer] = value + + # Check that original DataFrame is unchanged + if using_copy_on_write: + tm.assert_frame_equal(df_parent, df_orig) + + # Check that df is modified correctly + arr[indexer] = value + expected = DataFrame(arr, columns=list("ABCD")) + tm.assert_frame_equal(df, expected) + + +def test_full_setter_loc_incompatible_dtype(): + # https://github.com/pandas-dev/pandas/issues/55791 + df = DataFrame({"a": [1, 2]}) + with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): + df.loc[:, "a"] = True + expected = DataFrame({"a": [True, True]}) + tm.assert_frame_equal(df, expected) + + df = DataFrame({"a": [1, 2]}) + with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): + df.loc[:, "a"] = {0: 3.5, 1: 4.5} + expected = DataFrame({"a": [3.5, 4.5]}) + tm.assert_frame_equal(df, expected) + + df = DataFrame({"a": [1, 2]}) + df.loc[:, "a"] = {0: 3, 1: 4} + expected = DataFrame({"a": [3, 4]}) + tm.assert_frame_equal(df, expected) + + +def test_setitem_partial_row_multiple_columns(): + # https://github.com/pandas-dev/pandas/issues/56503 + df = DataFrame({"A": [1, 2, 3], "B": [4.0, 5, 6]}) + # should not warn + df.loc[df.index <= 1, ["F", "G"]] = (1, "abc") + expected = DataFrame( + { + "A": [1, 2, 3], + "B": [4.0, 5, 6], + "F": [1.0, 1, float("nan")], + "G": ["abc", "abc", float("nan")], + } + ) + tm.assert_frame_equal(df, expected) diff --git a/shared/package-files/77/779d5743717192d31f42d40a6938e4574c6fb7319eb0a5ef5a7ec45c469d553b/blob b/shared/package-files/77/779d5743717192d31f42d40a6938e4574c6fb7319eb0a5ef5a7ec45c469d553b/blob new file mode 100644 index 0000000000000000000000000000000000000000..fc297929d072ea34f603f8ea68e4ab7312df04d1 --- /dev/null +++ b/shared/package-files/77/779d5743717192d31f42d40a6938e4574c6fb7319eb0a5ef5a7ec45c469d553b/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor & empty_out(at::Tensor & out, at::IntArrayRef size, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor & empty_outf(at::IntArrayRef size, c10::optional memory_format, at::Tensor & out); +TORCH_API at::Tensor & empty_symint_out(at::Tensor & out, c10::SymIntArrayRef size, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor & empty_symint_outf(c10::SymIntArrayRef size, c10::optional memory_format, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/77/779fb81371ce417bccb21b6b28e52decd230c2a7bbf9e927c3cc28b97fd8e931/blob b/shared/package-files/77/779fb81371ce417bccb21b6b28e52decd230c2a7bbf9e927c3cc28b97fd8e931/blob new file mode 100644 index 0000000000000000000000000000000000000000..022a5fbf28a914e4e27b6679b0d572d5a356ca82 --- /dev/null +++ b/shared/package-files/77/779fb81371ce417bccb21b6b28e52decd230c2a7bbf9e927c3cc28b97fd8e931/blob @@ -0,0 +1,382 @@ +from collections import Counter + +import numpy as np +import pytest +from scipy.integrate import trapezoid + +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_breast_cancer, make_classification +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import ( + PrecisionRecallDisplay, + average_precision_score, + precision_recall_curve, +) +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.utils import shuffle + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +@pytest.mark.parametrize("drop_intermediate", [True, False]) +def test_precision_recall_display_plotting( + pyplot, constructor_name, response_method, drop_intermediate +): + """Check the overall plotting rendering.""" + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + pos_label = 1 + + classifier = LogisticRegression().fit(X, y) + classifier.fit(X, y) + + y_pred = getattr(classifier, response_method)(X) + y_pred = y_pred if y_pred.ndim == 1 else y_pred[:, pos_label] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X, + y, + response_method=response_method, + drop_intermediate=drop_intermediate, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=pos_label, drop_intermediate=drop_intermediate + ) + + precision, recall, _ = precision_recall_curve( + y, y_pred, pos_label=pos_label, drop_intermediate=drop_intermediate + ) + average_precision = average_precision_score(y, y_pred, pos_label=pos_label) + + np.testing.assert_allclose(display.precision, precision) + np.testing.assert_allclose(display.recall, recall) + assert display.average_precision == pytest.approx(average_precision) + + import matplotlib as mpl + + assert isinstance(display.line_, mpl.lines.Line2D) + assert isinstance(display.ax_, mpl.axes.Axes) + assert isinstance(display.figure_, mpl.figure.Figure) + + assert display.ax_.get_xlabel() == "Recall (Positive label: 1)" + assert display.ax_.get_ylabel() == "Precision (Positive label: 1)" + assert display.ax_.get_adjustable() == "box" + assert display.ax_.get_aspect() in ("equal", 1.0) + assert display.ax_.get_xlim() == display.ax_.get_ylim() == (-0.01, 1.01) + + # plotting passing some new parameters + display.plot(alpha=0.8, name="MySpecialEstimator") + expected_label = f"MySpecialEstimator (AP = {average_precision:0.2f})" + assert display.line_.get_label() == expected_label + assert display.line_.get_alpha() == pytest.approx(0.8) + + # Check that the chance level line is not plotted by default + assert display.chance_level_ is None + + +@pytest.mark.parametrize("chance_level_kw", [None, {"color": "r"}, {"c": "r"}]) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_precision_recall_chance_level_line( + pyplot, + chance_level_kw, + constructor_name, +): + """Check the chance level line plotting behavior.""" + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + pos_prevalence = Counter(y)[1] / len(y) + + lr = LogisticRegression() + y_pred = lr.fit(X, y).predict_proba(X)[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + lr, + X, + y, + plot_chance_level=True, + chance_level_kw=chance_level_kw, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, + y_pred, + plot_chance_level=True, + chance_level_kw=chance_level_kw, + ) + + import matplotlib as mpl + + assert isinstance(display.chance_level_, mpl.lines.Line2D) + assert tuple(display.chance_level_.get_xdata()) == (0, 1) + assert tuple(display.chance_level_.get_ydata()) == (pos_prevalence, pos_prevalence) + + # Checking for chance level line styles + if chance_level_kw is None: + assert display.chance_level_.get_color() == "k" + else: + assert display.chance_level_.get_color() == "r" + + +@pytest.mark.parametrize( + "constructor_name, default_label", + [ + ("from_estimator", "LogisticRegression (AP = {:.2f})"), + ("from_predictions", "Classifier (AP = {:.2f})"), + ], +) +def test_precision_recall_display_name(pyplot, constructor_name, default_label): + """Check the behaviour of the name parameters""" + X, y = make_classification(n_classes=2, n_samples=100, random_state=0) + pos_label = 1 + + classifier = LogisticRegression().fit(X, y) + classifier.fit(X, y) + + y_pred = classifier.predict_proba(X)[:, pos_label] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator(classifier, X, y) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=pos_label + ) + + average_precision = average_precision_score(y, y_pred, pos_label=pos_label) + + # check that the default name is used + assert display.line_.get_label() == default_label.format(average_precision) + + # check that the name can be set + display.plot(name="MySpecialEstimator") + assert ( + display.line_.get_label() + == f"MySpecialEstimator (AP = {average_precision:.2f})" + ) + + +@pytest.mark.parametrize( + "clf", + [ + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +def test_precision_recall_display_pipeline(pyplot, clf): + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + with pytest.raises(NotFittedError): + PrecisionRecallDisplay.from_estimator(clf, X, y) + clf.fit(X, y) + display = PrecisionRecallDisplay.from_estimator(clf, X, y) + assert display.estimator_name == clf.__class__.__name__ + + +def test_precision_recall_display_string_labels(pyplot): + # regression test #15738 + cancer = load_breast_cancer() + X, y = cancer.data, cancer.target_names[cancer.target] + + lr = make_pipeline(StandardScaler(), LogisticRegression()) + lr.fit(X, y) + for klass in cancer.target_names: + assert klass in lr.classes_ + display = PrecisionRecallDisplay.from_estimator(lr, X, y) + + y_pred = lr.predict_proba(X)[:, 1] + avg_prec = average_precision_score(y, y_pred, pos_label=lr.classes_[1]) + + assert display.average_precision == pytest.approx(avg_prec) + assert display.estimator_name == lr.__class__.__name__ + + err_msg = r"y_true takes value in {'benign', 'malignant'}" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_predictions(y, y_pred) + + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=lr.classes_[1] + ) + assert display.average_precision == pytest.approx(avg_prec) + + +@pytest.mark.parametrize( + "average_precision, estimator_name, expected_label", + [ + (0.9, None, "AP = 0.90"), + (None, "my_est", "my_est"), + (0.8, "my_est2", "my_est2 (AP = 0.80)"), + ], +) +def test_default_labels(pyplot, average_precision, estimator_name, expected_label): + """Check the default labels used in the display.""" + precision = np.array([1, 0.5, 0]) + recall = np.array([0, 0.5, 1]) + display = PrecisionRecallDisplay( + precision, + recall, + average_precision=average_precision, + estimator_name=estimator_name, + ) + display.plot() + assert display.line_.get_label() == expected_label + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_plot_precision_recall_pos_label(pyplot, constructor_name, response_method): + # check that we can provide the positive label and display the proper + # statistics + X, y = load_breast_cancer(return_X_y=True) + # create an highly imbalanced version of the breast cancer dataset + idx_positive = np.flatnonzero(y == 1) + idx_negative = np.flatnonzero(y == 0) + idx_selected = np.hstack([idx_negative, idx_positive[:25]]) + X, y = X[idx_selected], y[idx_selected] + X, y = shuffle(X, y, random_state=42) + # only use 2 features to make the problem even harder + X = X[:, :2] + y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object) + X_train, X_test, y_train, y_test = train_test_split( + X, + y, + stratify=y, + random_state=0, + ) + + classifier = LogisticRegression() + classifier.fit(X_train, y_train) + + # sanity check to be sure the positive class is classes_[0] and that we + # are betrayed by the class imbalance + assert classifier.classes_.tolist() == ["cancer", "not cancer"] + + y_pred = getattr(classifier, response_method)(X_test) + # we select the corresponding probability columns or reverse the decision + # function otherwise + y_pred_cancer = -1 * y_pred if y_pred.ndim == 1 else y_pred[:, 0] + y_pred_not_cancer = y_pred if y_pred.ndim == 1 else y_pred[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X_test, + y_test, + pos_label="cancer", + response_method=response_method, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y_test, + y_pred_cancer, + pos_label="cancer", + ) + # we should obtain the statistics of the "cancer" class + avg_prec_limit = 0.65 + assert display.average_precision < avg_prec_limit + assert -trapezoid(display.precision, display.recall) < avg_prec_limit + + # otherwise we should obtain the statistics of the "not cancer" class + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X_test, + y_test, + response_method=response_method, + pos_label="not cancer", + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y_test, + y_pred_not_cancer, + pos_label="not cancer", + ) + avg_prec_limit = 0.95 + assert display.average_precision > avg_prec_limit + assert -trapezoid(display.precision, display.recall) > avg_prec_limit + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_precision_recall_prevalence_pos_label_reusable(pyplot, constructor_name): + # Check that even if one passes plot_chance_level=False the first time + # one can still call disp.plot with plot_chance_level=True and get the + # chance level line + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + lr = LogisticRegression() + y_pred = lr.fit(X, y).predict_proba(X)[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + lr, X, y, plot_chance_level=False + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, plot_chance_level=False + ) + assert display.chance_level_ is None + + import matplotlib as mpl + + # When calling from_estimator or from_predictions, + # prevalence_pos_label should have been set, so that directly + # calling plot_chance_level=True should plot the chance level line + display.plot(plot_chance_level=True) + assert isinstance(display.chance_level_, mpl.lines.Line2D) + + +def test_precision_recall_raise_no_prevalence(pyplot): + # Check that raises correctly when plotting chance level with + # no prvelance_pos_label is provided + precision = np.array([1, 0.5, 0]) + recall = np.array([0, 0.5, 1]) + display = PrecisionRecallDisplay(precision, recall) + + msg = ( + "You must provide prevalence_pos_label when constructing the " + "PrecisionRecallDisplay object in order to plot the chance " + "level line. Alternatively, you may use " + "PrecisionRecallDisplay.from_estimator or " + "PrecisionRecallDisplay.from_predictions " + "to automatically set prevalence_pos_label" + ) + + with pytest.raises(ValueError, match=msg): + display.plot(plot_chance_level=True) + + +@pytest.mark.parametrize("despine", [True, False]) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_plot_precision_recall_despine(pyplot, despine, constructor_name): + # Check that the despine keyword is working correctly + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + clf = LogisticRegression().fit(X, y) + clf.fit(X, y) + + y_pred = clf.decision_function(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator(clf, X, y, despine=despine) + else: + display = PrecisionRecallDisplay.from_predictions(y, y_pred, despine=despine) + + for s in ["top", "right"]: + assert display.ax_.spines[s].get_visible() is not despine + + if despine: + for s in ["bottom", "left"]: + assert display.ax_.spines[s].get_bounds() == (0, 1) diff --git a/shared/package-files/77/77a17fc6bf0f558cd4e2a31c9e8bf19ce6f00b928e647c9da5f0478c67f89dc5/blob b/shared/package-files/77/77a17fc6bf0f558cd4e2a31c9e8bf19ce6f00b928e647c9da5f0478c67f89dc5/blob new file mode 100644 index 0000000000000000000000000000000000000000..f4ff4576f6b8302dabc9a08ccf3d7f51b676f82d --- /dev/null +++ b/shared/package-files/77/77a17fc6bf0f558cd4e2a31c9e8bf19ce6f00b928e647c9da5f0478c67f89dc5/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77a17fc6bf0f558cd4e2a31c9e8bf19ce6f00b928e647c9da5f0478c67f89dc5 +size 187349634 diff --git a/shared/package-files/77/77a7409f089e8f2148da7ec0cc59455b4685013eb360d123048106d2ebb4b1b4/blob b/shared/package-files/77/77a7409f089e8f2148da7ec0cc59455b4685013eb360d123048106d2ebb4b1b4/blob new file mode 100644 index 0000000000000000000000000000000000000000..06e777d57e0267a0635b6b284729fddcfe6221dd Binary files /dev/null and b/shared/package-files/77/77a7409f089e8f2148da7ec0cc59455b4685013eb360d123048106d2ebb4b1b4/blob differ diff --git a/shared/package-files/77/77a7a130572c2f0351f1f0dec0db4e7ac9e71970b74dfcb6c2d93b66da869df6/blob b/shared/package-files/77/77a7a130572c2f0351f1f0dec0db4e7ac9e71970b74dfcb6c2d93b66da869df6/blob new file mode 100644 index 0000000000000000000000000000000000000000..600d0bd49fe2cf6095511a889db6477ad3bfa321 --- /dev/null +++ b/shared/package-files/77/77a7a130572c2f0351f1f0dec0db4e7ac9e71970b74dfcb6c2d93b66da869df6/blob @@ -0,0 +1,493 @@ +"""File selection dialog classes. + +Classes: + +- FileDialog +- LoadFileDialog +- SaveFileDialog + +This module also presents tk common file dialogues, it provides interfaces +to the native file dialogues available in Tk 4.2 and newer, and the +directory dialogue available in Tk 8.3 and newer. +These interfaces were written by Fredrik Lundh, May 1997. +""" +__all__ = ["FileDialog", "LoadFileDialog", "SaveFileDialog", + "Open", "SaveAs", "Directory", + "askopenfilename", "asksaveasfilename", "askopenfilenames", + "askopenfile", "askopenfiles", "asksaveasfile", "askdirectory"] + +import fnmatch +import os +from tkinter import ( + Frame, LEFT, YES, BOTTOM, Entry, TOP, Button, Tk, X, + Toplevel, RIGHT, Y, END, Listbox, BOTH, Scrollbar, +) +from tkinter.dialog import Dialog +from tkinter import commondialog +from tkinter.simpledialog import _setup_dialog + + +dialogstates = {} + + +class FileDialog: + + """Standard file selection dialog -- no checks on selected file. + + Usage: + + d = FileDialog(master) + fname = d.go(dir_or_file, pattern, default, key) + if fname is None: ...canceled... + else: ...open file... + + All arguments to go() are optional. + + The 'key' argument specifies a key in the global dictionary + 'dialogstates', which keeps track of the values for the directory + and pattern arguments, overriding the values passed in (it does + not keep track of the default argument!). If no key is specified, + the dialog keeps no memory of previous state. Note that memory is + kept even when the dialog is canceled. (All this emulates the + behavior of the Macintosh file selection dialogs.) + + """ + + title = "File Selection Dialog" + + def __init__(self, master, title=None): + if title is None: title = self.title + self.master = master + self.directory = None + + self.top = Toplevel(master) + self.top.title(title) + self.top.iconname(title) + _setup_dialog(self.top) + + self.botframe = Frame(self.top) + self.botframe.pack(side=BOTTOM, fill=X) + + self.selection = Entry(self.top) + self.selection.pack(side=BOTTOM, fill=X) + self.selection.bind('', self.ok_event) + + self.filter = Entry(self.top) + self.filter.pack(side=TOP, fill=X) + self.filter.bind('', self.filter_command) + + self.midframe = Frame(self.top) + self.midframe.pack(expand=YES, fill=BOTH) + + self.filesbar = Scrollbar(self.midframe) + self.filesbar.pack(side=RIGHT, fill=Y) + self.files = Listbox(self.midframe, exportselection=0, + yscrollcommand=(self.filesbar, 'set')) + self.files.pack(side=RIGHT, expand=YES, fill=BOTH) + btags = self.files.bindtags() + self.files.bindtags(btags[1:] + btags[:1]) + self.files.bind('', self.files_select_event) + self.files.bind('', self.files_double_event) + self.filesbar.config(command=(self.files, 'yview')) + + self.dirsbar = Scrollbar(self.midframe) + self.dirsbar.pack(side=LEFT, fill=Y) + self.dirs = Listbox(self.midframe, exportselection=0, + yscrollcommand=(self.dirsbar, 'set')) + self.dirs.pack(side=LEFT, expand=YES, fill=BOTH) + self.dirsbar.config(command=(self.dirs, 'yview')) + btags = self.dirs.bindtags() + self.dirs.bindtags(btags[1:] + btags[:1]) + self.dirs.bind('', self.dirs_select_event) + self.dirs.bind('', self.dirs_double_event) + + self.ok_button = Button(self.botframe, + text="OK", + command=self.ok_command) + self.ok_button.pack(side=LEFT) + self.filter_button = Button(self.botframe, + text="Filter", + command=self.filter_command) + self.filter_button.pack(side=LEFT, expand=YES) + self.cancel_button = Button(self.botframe, + text="Cancel", + command=self.cancel_command) + self.cancel_button.pack(side=RIGHT) + + self.top.protocol('WM_DELETE_WINDOW', self.cancel_command) + # XXX Are the following okay for a general audience? + self.top.bind('', self.cancel_command) + self.top.bind('', self.cancel_command) + + def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): + if key and key in dialogstates: + self.directory, pattern = dialogstates[key] + else: + dir_or_file = os.path.expanduser(dir_or_file) + if os.path.isdir(dir_or_file): + self.directory = dir_or_file + else: + self.directory, default = os.path.split(dir_or_file) + self.set_filter(self.directory, pattern) + self.set_selection(default) + self.filter_command() + self.selection.focus_set() + self.top.wait_visibility() # window needs to be visible for the grab + self.top.grab_set() + self.how = None + self.master.mainloop() # Exited by self.quit(how) + if key: + directory, pattern = self.get_filter() + if self.how: + directory = os.path.dirname(self.how) + dialogstates[key] = directory, pattern + self.top.destroy() + return self.how + + def quit(self, how=None): + self.how = how + self.master.quit() # Exit mainloop() + + def dirs_double_event(self, event): + self.filter_command() + + def dirs_select_event(self, event): + dir, pat = self.get_filter() + subdir = self.dirs.get('active') + dir = os.path.normpath(os.path.join(self.directory, subdir)) + self.set_filter(dir, pat) + + def files_double_event(self, event): + self.ok_command() + + def files_select_event(self, event): + file = self.files.get('active') + self.set_selection(file) + + def ok_event(self, event): + self.ok_command() + + def ok_command(self): + self.quit(self.get_selection()) + + def filter_command(self, event=None): + dir, pat = self.get_filter() + try: + names = os.listdir(dir) + except OSError: + self.master.bell() + return + self.directory = dir + self.set_filter(dir, pat) + names.sort() + subdirs = [os.pardir] + matchingfiles = [] + for name in names: + fullname = os.path.join(dir, name) + if os.path.isdir(fullname): + subdirs.append(name) + elif fnmatch.fnmatch(name, pat): + matchingfiles.append(name) + self.dirs.delete(0, END) + for name in subdirs: + self.dirs.insert(END, name) + self.files.delete(0, END) + for name in matchingfiles: + self.files.insert(END, name) + head, tail = os.path.split(self.get_selection()) + if tail == os.curdir: tail = '' + self.set_selection(tail) + + def get_filter(self): + filter = self.filter.get() + filter = os.path.expanduser(filter) + if filter[-1:] == os.sep or os.path.isdir(filter): + filter = os.path.join(filter, "*") + return os.path.split(filter) + + def get_selection(self): + file = self.selection.get() + file = os.path.expanduser(file) + return file + + def cancel_command(self, event=None): + self.quit() + + def set_filter(self, dir, pat): + if not os.path.isabs(dir): + try: + pwd = os.getcwd() + except OSError: + pwd = None + if pwd: + dir = os.path.join(pwd, dir) + dir = os.path.normpath(dir) + self.filter.delete(0, END) + self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) + + def set_selection(self, file): + self.selection.delete(0, END) + self.selection.insert(END, os.path.join(self.directory, file)) + + +class LoadFileDialog(FileDialog): + + """File selection dialog which checks that the file exists.""" + + title = "Load File Selection Dialog" + + def ok_command(self): + file = self.get_selection() + if not os.path.isfile(file): + self.master.bell() + else: + self.quit(file) + + +class SaveFileDialog(FileDialog): + + """File selection dialog which checks that the file may be created.""" + + title = "Save File Selection Dialog" + + def ok_command(self): + file = self.get_selection() + if os.path.exists(file): + if os.path.isdir(file): + self.master.bell() + return + d = Dialog(self.top, + title="Overwrite Existing File Question", + text="Overwrite existing file %r?" % (file,), + bitmap='questhead', + default=1, + strings=("Yes", "Cancel")) + if d.num != 0: + return + else: + head, tail = os.path.split(file) + if not os.path.isdir(head): + self.master.bell() + return + self.quit(file) + + +# For the following classes and modules: +# +# options (all have default values): +# +# - defaultextension: added to filename if not explicitly given +# +# - filetypes: sequence of (label, pattern) tuples. the same pattern +# may occur with several patterns. use "*" as pattern to indicate +# all files. +# +# - initialdir: initial directory. preserved by dialog instance. +# +# - initialfile: initial file (ignored by the open dialog). preserved +# by dialog instance. +# +# - parent: which window to place the dialog on top of +# +# - title: dialog title +# +# - multiple: if true user may select more than one file +# +# options for the directory chooser: +# +# - initialdir, parent, title: see above +# +# - mustexist: if true, user must pick an existing directory +# + + +class _Dialog(commondialog.Dialog): + + def _fixoptions(self): + try: + # make sure "filetypes" is a tuple + self.options["filetypes"] = tuple(self.options["filetypes"]) + except KeyError: + pass + + def _fixresult(self, widget, result): + if result: + # keep directory and filename until next time + # convert Tcl path objects to strings + try: + result = result.string + except AttributeError: + # it already is a string + pass + path, file = os.path.split(result) + self.options["initialdir"] = path + self.options["initialfile"] = file + self.filename = result # compatibility + return result + + +# +# file dialogs + +class Open(_Dialog): + "Ask for a filename to open" + + command = "tk_getOpenFile" + + def _fixresult(self, widget, result): + if isinstance(result, tuple): + # multiple results: + result = tuple([getattr(r, "string", r) for r in result]) + if result: + path, file = os.path.split(result[0]) + self.options["initialdir"] = path + # don't set initialfile or filename, as we have multiple of these + return result + if not widget.tk.wantobjects() and "multiple" in self.options: + # Need to split result explicitly + return self._fixresult(widget, widget.tk.splitlist(result)) + return _Dialog._fixresult(self, widget, result) + + +class SaveAs(_Dialog): + "Ask for a filename to save as" + + command = "tk_getSaveFile" + + +# the directory dialog has its own _fix routines. +class Directory(commondialog.Dialog): + "Ask for a directory" + + command = "tk_chooseDirectory" + + def _fixresult(self, widget, result): + if result: + # convert Tcl path objects to strings + try: + result = result.string + except AttributeError: + # it already is a string + pass + # keep directory until next time + self.options["initialdir"] = result + self.directory = result # compatibility + return result + +# +# convenience stuff + + +def askopenfilename(**options): + "Ask for a filename to open" + + return Open(**options).show() + + +def asksaveasfilename(**options): + "Ask for a filename to save as" + + return SaveAs(**options).show() + + +def askopenfilenames(**options): + """Ask for multiple filenames to open + + Returns a list of filenames or empty list if + cancel button selected + """ + options["multiple"]=1 + return Open(**options).show() + +# FIXME: are the following perhaps a bit too convenient? + + +def askopenfile(mode = "r", **options): + "Ask for a filename to open, and returned the opened file" + + filename = Open(**options).show() + if filename: + return open(filename, mode) + return None + + +def askopenfiles(mode = "r", **options): + """Ask for multiple filenames and return the open file + objects + + returns a list of open file objects or an empty list if + cancel selected + """ + + files = askopenfilenames(**options) + if files: + ofiles=[] + for filename in files: + ofiles.append(open(filename, mode)) + files=ofiles + return files + + +def asksaveasfile(mode = "w", **options): + "Ask for a filename to save as, and returned the opened file" + + filename = SaveAs(**options).show() + if filename: + return open(filename, mode) + return None + + +def askdirectory (**options): + "Ask for a directory, and return the file name" + return Directory(**options).show() + + +# -------------------------------------------------------------------- +# test stuff + +def test(): + """Simple test program.""" + root = Tk() + root.withdraw() + fd = LoadFileDialog(root) + loadfile = fd.go(key="test") + fd = SaveFileDialog(root) + savefile = fd.go(key="test") + print(loadfile, savefile) + + # Since the file name may contain non-ASCII characters, we need + # to find an encoding that likely supports the file name, and + # displays correctly on the terminal. + + # Start off with UTF-8 + enc = "utf-8" + import sys + + # See whether CODESET is defined + try: + import locale + locale.setlocale(locale.LC_ALL,'') + enc = locale.nl_langinfo(locale.CODESET) + except (ImportError, AttributeError): + pass + + # dialog for opening files + + openfilename=askopenfilename(filetypes=[("all files", "*")]) + try: + fp=open(openfilename,"r") + fp.close() + except: + print("Could not open File: ") + print(sys.exc_info()[1]) + + print("open", openfilename.encode(enc)) + + # dialog for saving files + + saveasfilename=asksaveasfilename() + print("saveas", saveasfilename.encode(enc)) + + +if __name__ == '__main__': + test() diff --git a/shared/package-files/77/77a8034e26996faffd4c5c45b7861ecc9149b525071593b49e36f2e074e8ead7/blob b/shared/package-files/77/77a8034e26996faffd4c5c45b7861ecc9149b525071593b49e36f2e074e8ead7/blob new file mode 100644 index 0000000000000000000000000000000000000000..efd813335eaf2ab7064006d5842e6a6f1f66909d --- /dev/null +++ b/shared/package-files/77/77a8034e26996faffd4c5c45b7861ecc9149b525071593b49e36f2e074e8ead7/blob @@ -0,0 +1,13 @@ +*** Fri, 26 Aug 2016 11:41:45 *** +TEST FOR GRANGER-CAUSALITY: +H0: "Dp" do not Granger-cause "R" + +Test statistic l = 1.4258 +pval-F( l; 3, 180) = 0.2368 + +TEST FOR INSTANTANEOUS CAUSALITY: +H0: No instantaneous causality between "Dp" and "R" + +Test statistic: c = 0.9332 +pval-Chi( c; 1) = 0.3340 + diff --git a/shared/package-files/77/77aa69bfd503ca88a17e36032607b2d27a9ccb0746c1cc86dc74c158078dfab3/blob b/shared/package-files/77/77aa69bfd503ca88a17e36032607b2d27a9ccb0746c1cc86dc74c158078dfab3/blob new file mode 100644 index 0000000000000000000000000000000000000000..03961d4b89644a45fb66c90c752d1dca72443cec --- /dev/null +++ b/shared/package-files/77/77aa69bfd503ca88a17e36032607b2d27a9ccb0746c1cc86dc74c158078dfab3/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_get_jagged_dummy { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_get_jagged_dummy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_get_jagged_dummy(Tensor any) -> Tensor") + static at::Tensor call(const at::Tensor & any); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & any); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/77/77abba52453bd53e942f10d549d324213dc25002f8e9d12e0ee36b9e365ee411/blob b/shared/package-files/77/77abba52453bd53e942f10d549d324213dc25002f8e9d12e0ee36b9e365ee411/blob new file mode 100644 index 0000000000000000000000000000000000000000..9208c31df2bf7181ab003ee860543ebbf2975b52 --- /dev/null +++ b/shared/package-files/77/77abba52453bd53e942f10d549d324213dc25002f8e9d12e0ee36b9e365ee411/blob @@ -0,0 +1,53 @@ +from io import BytesIO +from pathlib import Path + +import pytest + +from matplotlib.testing.decorators import image_comparison +from matplotlib import cm, pyplot as plt + + +@image_comparison(['pngsuite.png'], tol=0.04) +def test_pngsuite(): + files = sorted( + (Path(__file__).parent / "baseline_images/pngsuite").glob("basn*.png")) + + plt.figure(figsize=(len(files), 2)) + + for i, fname in enumerate(files): + data = plt.imread(fname) + cmap = None # use default colormap + if data.ndim == 2: + # keep grayscale images gray + cmap = cm.gray + # Using the old default data interpolation stage lets us + # continue to use the existing reference image + plt.imshow(data, extent=(i, i + 1, 0, 1), cmap=cmap, + interpolation_stage='data') + + plt.gca().patch.set_facecolor("#ddffff") + plt.gca().set_xlim(0, len(files)) + + +def test_truncated_file(tmp_path): + path = tmp_path / 'test.png' + path_t = tmp_path / 'test_truncated.png' + plt.savefig(path) + with open(path, 'rb') as fin: + buf = fin.read() + with open(path_t, 'wb') as fout: + fout.write(buf[:20]) + + with pytest.raises(Exception): + plt.imread(path_t) + + +def test_truncated_buffer(): + b = BytesIO() + plt.savefig(b) + b.seek(0) + b2 = BytesIO(b.read(20)) + b2.seek(0) + + with pytest.raises(Exception): + plt.imread(b2) diff --git a/shared/package-files/77/77ade75ce7cb17b5aa1ab363f7d3dc2e4bcb222090dc975997949ff5aec84c69/blob b/shared/package-files/77/77ade75ce7cb17b5aa1ab363f7d3dc2e4bcb222090dc975997949ff5aec84c69/blob new file mode 100644 index 0000000000000000000000000000000000000000..3aa5f3f61ce694c10175c4d3a1d71b4bf96686f7 --- /dev/null +++ b/shared/package-files/77/77ade75ce7cb17b5aa1ab363f7d3dc2e4bcb222090dc975997949ff5aec84c69/blob @@ -0,0 +1,12 @@ +"""IFT - Incremental Font Transfer table.""" + +# Reference: https://github.com/googlefonts/fontations/blob/main/read-fonts/src/tables/ift.rs + + +from .otBase import BaseTTXConverter + + +class table_I_F_T_(BaseTTXConverter): + """Incremental Font Transfer table.""" + + pass diff --git a/shared/package-files/77/77aedacf799dc0bf0325a392460baf0c8db007ed1141e0a6f79688ba5f3f00bc/blob b/shared/package-files/77/77aedacf799dc0bf0325a392460baf0c8db007ed1141e0a6f79688ba5f3f00bc/blob new file mode 100644 index 0000000000000000000000000000000000000000..1fcc7fbb9cab145dc8c53fc1d325bcd1b7aa6bce --- /dev/null +++ b/shared/package-files/77/77aedacf799dc0bf0325a392460baf0c8db007ed1141e0a6f79688ba5f3f00bc/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor nll_loss2d_symint(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100); +TORCH_API at::Tensor & nll_loss2d_out(const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77b495047630289f441481540a1793aec357f103744aaa93dc27bb376838a036/blob b/shared/package-files/77/77b495047630289f441481540a1793aec357f103744aaa93dc27bb376838a036/blob new file mode 100644 index 0000000000000000000000000000000000000000..2093403a27fab41ec990bd46a7506b8f3b281107 --- /dev/null +++ b/shared/package-files/77/77b495047630289f441481540a1793aec357f103744aaa93dc27bb376838a036/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_neg : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77b4c064ae584164fb76c1edf38cbed8af50d7b154c62ea29697e077418f677d/blob b/shared/package-files/77/77b4c064ae584164fb76c1edf38cbed8af50d7b154c62ea29697e077418f677d/blob new file mode 100644 index 0000000000000000000000000000000000000000..c488b518ed5936f814d4fffa2f4a12e0a3a8805b --- /dev/null +++ b/shared/package-files/77/77b4c064ae584164fb76c1edf38cbed8af50d7b154c62ea29697e077418f677d/blob @@ -0,0 +1,2195 @@ +from typing import Tuple as tTuple +from collections import defaultdict +from functools import cmp_to_key, reduce +from itertools import product +import operator + +from .sympify import sympify +from .basic import Basic +from .singleton import S +from .operations import AssocOp, AssocOpDispatcher +from .cache import cacheit +from .logic import fuzzy_not, _fuzzy_group +from .expr import Expr +from .parameters import global_parameters +from .kind import KindDispatcher +from .traversal import bottom_up + +from sympy.utilities.iterables import sift + +# internal marker to indicate: +# "there are still non-commutative objects -- don't forget to process them" +class NC_Marker: + is_Order = False + is_Mul = False + is_Number = False + is_Poly = False + + is_commutative = False + + +# Key for sorting commutative args in canonical order +_args_sortkey = cmp_to_key(Basic.compare) +def _mulsort(args): + # in-place sorting of args + args.sort(key=_args_sortkey) + + +def _unevaluated_Mul(*args): + """Return a well-formed unevaluated Mul: Numbers are collected and + put in slot 0, any arguments that are Muls will be flattened, and args + are sorted. Use this when args have changed but you still want to return + an unevaluated Mul. + + Examples + ======== + + >>> from sympy.core.mul import _unevaluated_Mul as uMul + >>> from sympy import S, sqrt, Mul + >>> from sympy.abc import x + >>> a = uMul(*[S(3.0), x, S(2)]) + >>> a.args[0] + 6.00000000000000 + >>> a.args[1] + x + + Two unevaluated Muls with the same arguments will + always compare as equal during testing: + + >>> m = uMul(sqrt(2), sqrt(3)) + >>> m == uMul(sqrt(3), sqrt(2)) + True + >>> u = Mul(sqrt(3), sqrt(2), evaluate=False) + >>> m == uMul(u) + True + >>> m == Mul(*m.args) + False + + """ + args = list(args) + newargs = [] + ncargs = [] + co = S.One + while args: + a = args.pop() + if a.is_Mul: + c, nc = a.args_cnc() + args.extend(c) + if nc: + ncargs.append(Mul._from_args(nc)) + elif a.is_Number: + co *= a + else: + newargs.append(a) + _mulsort(newargs) + if co is not S.One: + newargs.insert(0, co) + if ncargs: + newargs.append(Mul._from_args(ncargs)) + return Mul._from_args(newargs) + + +class Mul(Expr, AssocOp): + """ + Expression representing multiplication operation for algebraic field. + + .. deprecated:: 1.7 + + Using arguments that aren't subclasses of :class:`~.Expr` in core + operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is + deprecated. See :ref:`non-expr-args-deprecated` for details. + + Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*`` + on most scalar objects in SymPy calls this class. + + Another use of ``Mul()`` is to represent the structure of abstract + multiplication so that its arguments can be substituted to return + different class. Refer to examples section for this. + + ``Mul()`` evaluates the argument unless ``evaluate=False`` is passed. + The evaluation logic includes: + + 1. Flattening + ``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)`` + + 2. Identity removing + ``Mul(x, 1, y)`` -> ``Mul(x, y)`` + + 3. Exponent collecting by ``.as_base_exp()`` + ``Mul(x, x**2)`` -> ``Pow(x, 3)`` + + 4. Term sorting + ``Mul(y, x, 2)`` -> ``Mul(2, x, y)`` + + Since multiplication can be vector space operation, arguments may + have the different :obj:`sympy.core.kind.Kind()`. Kind of the + resulting object is automatically inferred. + + Examples + ======== + + >>> from sympy import Mul + >>> from sympy.abc import x, y + >>> Mul(x, 1) + x + >>> Mul(x, x) + x**2 + + If ``evaluate=False`` is passed, result is not evaluated. + + >>> Mul(1, 2, evaluate=False) + 1*2 + >>> Mul(x, x, evaluate=False) + x*x + + ``Mul()`` also represents the general structure of multiplication + operation. + + >>> from sympy import MatrixSymbol + >>> A = MatrixSymbol('A', 2,2) + >>> expr = Mul(x,y).subs({y:A}) + >>> expr + x*A + >>> type(expr) + + + See Also + ======== + + MatMul + + """ + __slots__ = () + + args: tTuple[Expr] + + is_Mul = True + + _args_type = Expr + _kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True) + + @property + def kind(self): + arg_kinds = (a.kind for a in self.args) + return self._kind_dispatcher(*arg_kinds) + + def could_extract_minus_sign(self): + if self == (-self): + return False # e.g. zoo*x == -zoo*x + c = self.args[0] + return c.is_Number and c.is_extended_negative + + def __neg__(self): + c, args = self.as_coeff_mul() + if args[0] is not S.ComplexInfinity: + c = -c + if c is not S.One: + if args[0].is_Number: + args = list(args) + if c is S.NegativeOne: + args[0] = -args[0] + else: + args[0] *= c + else: + args = (c,) + args + return self._from_args(args, self.is_commutative) + + @classmethod + def flatten(cls, seq): + """Return commutative, noncommutative and order arguments by + combining related terms. + + Notes + ===== + * In an expression like ``a*b*c``, Python process this through SymPy + as ``Mul(Mul(a, b), c)``. This can have undesirable consequences. + + - Sometimes terms are not combined as one would like: + {c.f. https://github.com/sympy/sympy/issues/4596} + + >>> from sympy import Mul, sqrt + >>> from sympy.abc import x, y, z + >>> 2*(x + 1) # this is the 2-arg Mul behavior + 2*x + 2 + >>> y*(x + 1)*2 + 2*y*(x + 1) + >>> 2*(x + 1)*y # 2-arg result will be obtained first + y*(2*x + 2) + >>> Mul(2, x + 1, y) # all 3 args simultaneously processed + 2*y*(x + 1) + >>> 2*((x + 1)*y) # parentheses can control this behavior + 2*y*(x + 1) + + Powers with compound bases may not find a single base to + combine with unless all arguments are processed at once. + Post-processing may be necessary in such cases. + {c.f. https://github.com/sympy/sympy/issues/5728} + + >>> a = sqrt(x*sqrt(y)) + >>> a**3 + (x*sqrt(y))**(3/2) + >>> Mul(a,a,a) + (x*sqrt(y))**(3/2) + >>> a*a*a + x*sqrt(y)*sqrt(x*sqrt(y)) + >>> _.subs(a.base, z).subs(z, a.base) + (x*sqrt(y))**(3/2) + + - If more than two terms are being multiplied then all the + previous terms will be re-processed for each new argument. + So if each of ``a``, ``b`` and ``c`` were :class:`Mul` + expression, then ``a*b*c`` (or building up the product + with ``*=``) will process all the arguments of ``a`` and + ``b`` twice: once when ``a*b`` is computed and again when + ``c`` is multiplied. + + Using ``Mul(a, b, c)`` will process all arguments once. + + * The results of Mul are cached according to arguments, so flatten + will only be called once for ``Mul(a, b, c)``. If you can + structure a calculation so the arguments are most likely to be + repeats then this can save time in computing the answer. For + example, say you had a Mul, M, that you wished to divide by ``d[i]`` + and multiply by ``n[i]`` and you suspect there are many repeats + in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather + than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the + product, ``M*n[i]`` will be returned without flattening -- the + cached value will be returned. If you divide by the ``d[i]`` + first (and those are more unique than the ``n[i]``) then that will + create a new Mul, ``M/d[i]`` the args of which will be traversed + again when it is multiplied by ``n[i]``. + + {c.f. https://github.com/sympy/sympy/issues/5706} + + This consideration is moot if the cache is turned off. + + NB + -- + The validity of the above notes depends on the implementation + details of Mul and flatten which may change at any time. Therefore, + you should only consider them when your code is highly performance + sensitive. + + Removal of 1 from the sequence is already handled by AssocOp.__new__. + """ + + from sympy.calculus.accumulationbounds import AccumBounds + from sympy.matrices.expressions import MatrixExpr + rv = None + if len(seq) == 2: + a, b = seq + if b.is_Rational: + a, b = b, a + seq = [a, b] + assert a is not S.One + if not a.is_zero and a.is_Rational: + r, b = b.as_coeff_Mul() + if b.is_Add: + if r is not S.One: # 2-arg hack + # leave the Mul as a Mul? + ar = a*r + if ar is S.One: + arb = b + else: + arb = cls(a*r, b, evaluate=False) + rv = [arb], [], None + elif global_parameters.distribute and b.is_commutative: + newb = Add(*[_keep_coeff(a, bi) for bi in b.args]) + rv = [newb], [], None + if rv: + return rv + + # apply associativity, separate commutative part of seq + c_part = [] # out: commutative factors + nc_part = [] # out: non-commutative factors + + nc_seq = [] + + coeff = S.One # standalone term + # e.g. 3 * ... + + c_powers = [] # (base,exp) n + # e.g. (x,n) for x + + num_exp = [] # (num-base, exp) y + # e.g. (3, y) for ... * 3 * ... + + neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I + + pnum_rat = {} # (num-base, Rat-exp) 1/2 + # e.g. (3, 1/2) for ... * 3 * ... + + order_symbols = None + + # --- PART 1 --- + # + # "collect powers and coeff": + # + # o coeff + # o c_powers + # o num_exp + # o neg1e + # o pnum_rat + # + # NOTE: this is optimized for all-objects-are-commutative case + for o in seq: + # O(x) + if o.is_Order: + o, order_symbols = o.as_expr_variables(order_symbols) + + # Mul([...]) + if o.is_Mul: + if o.is_commutative: + seq.extend(o.args) # XXX zerocopy? + + else: + # NCMul can have commutative parts as well + for q in o.args: + if q.is_commutative: + seq.append(q) + else: + nc_seq.append(q) + + # append non-commutative marker, so we don't forget to + # process scheduled non-commutative objects + seq.append(NC_Marker) + + continue + + # 3 + elif o.is_Number: + if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero: + # we know for sure the result will be nan + return [S.NaN], [], None + elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo + coeff *= o + if coeff is S.NaN: + # we know for sure the result will be nan + return [S.NaN], [], None + continue + + elif isinstance(o, AccumBounds): + coeff = o.__mul__(coeff) + continue + + elif o is S.ComplexInfinity: + if not coeff: + # 0 * zoo = NaN + return [S.NaN], [], None + coeff = S.ComplexInfinity + continue + + elif o is S.ImaginaryUnit: + neg1e += S.Half + continue + + elif o.is_commutative: + # e + # o = b + b, e = o.as_base_exp() + + # y + # 3 + if o.is_Pow: + if b.is_Number: + + # get all the factors with numeric base so they can be + # combined below, but don't combine negatives unless + # the exponent is an integer + if e.is_Rational: + if e.is_Integer: + coeff *= Pow(b, e) # it is an unevaluated power + continue + elif e.is_negative: # also a sign of an unevaluated power + seq.append(Pow(b, e)) + continue + elif b.is_negative: + neg1e += e + b = -b + if b is not S.One: + pnum_rat.setdefault(b, []).append(e) + continue + elif b.is_positive or e.is_integer: + num_exp.append((b, e)) + continue + + c_powers.append((b, e)) + + # NON-COMMUTATIVE + # TODO: Make non-commutative exponents not combine automatically + else: + if o is not NC_Marker: + nc_seq.append(o) + + # process nc_seq (if any) + while nc_seq: + o = nc_seq.pop(0) + if not nc_part: + nc_part.append(o) + continue + + # b c b+c + # try to combine last terms: a * a -> a + o1 = nc_part.pop() + b1, e1 = o1.as_base_exp() + b2, e2 = o.as_base_exp() + new_exp = e1 + e2 + # Only allow powers to combine if the new exponent is + # not an Add. This allow things like a**2*b**3 == a**5 + # if a.is_commutative == False, but prohibits + # a**x*a**y and x**a*x**b from combining (x,y commute). + if b1 == b2 and (not new_exp.is_Add): + o12 = b1 ** new_exp + + # now o12 could be a commutative object + if o12.is_commutative: + seq.append(o12) + continue + else: + nc_seq.insert(0, o12) + + else: + nc_part.extend([o1, o]) + + # We do want a combined exponent if it would not be an Add, such as + # y 2y 3y + # x * x -> x + # We determine if two exponents have the same term by using + # as_coeff_Mul. + # + # Unfortunately, this isn't smart enough to consider combining into + # exponents that might already be adds, so things like: + # z - y y + # x * x will be left alone. This is because checking every possible + # combination can slow things down. + + # gather exponents of common bases... + def _gather(c_powers): + common_b = {} # b:e + for b, e in c_powers: + co = e.as_coeff_Mul() + common_b.setdefault(b, {}).setdefault( + co[1], []).append(co[0]) + for b, d in common_b.items(): + for di, li in d.items(): + d[di] = Add(*li) + new_c_powers = [] + for b, e in common_b.items(): + new_c_powers.extend([(b, c*t) for t, c in e.items()]) + return new_c_powers + + # in c_powers + c_powers = _gather(c_powers) + + # and in num_exp + num_exp = _gather(num_exp) + + # --- PART 2 --- + # + # o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow) + # o combine collected powers (2**x * 3**x -> 6**x) + # with numeric base + + # ................................ + # now we have: + # - coeff: + # - c_powers: (b, e) + # - num_exp: (2, e) + # - pnum_rat: {(1/3, [1/3, 2/3, 1/4])} + + # 0 1 + # x -> 1 x -> x + + # this should only need to run twice; if it fails because + # it needs to be run more times, perhaps this should be + # changed to a "while True" loop -- the only reason it + # isn't such now is to allow a less-than-perfect result to + # be obtained rather than raising an error or entering an + # infinite loop + for i in range(2): + new_c_powers = [] + changed = False + for b, e in c_powers: + if e.is_zero: + # canceling out infinities yields NaN + if (b.is_Add or b.is_Mul) and any(infty in b.args + for infty in (S.ComplexInfinity, S.Infinity, + S.NegativeInfinity)): + return [S.NaN], [], None + continue + if e is S.One: + if b.is_Number: + coeff *= b + continue + p = b + if e is not S.One: + p = Pow(b, e) + # check to make sure that the base doesn't change + # after exponentiation; to allow for unevaluated + # Pow, we only do so if b is not already a Pow + if p.is_Pow and not b.is_Pow: + bi = b + b, e = p.as_base_exp() + if b != bi: + changed = True + c_part.append(p) + new_c_powers.append((b, e)) + # there might have been a change, but unless the base + # matches some other base, there is nothing to do + if changed and len({ + b for b, e in new_c_powers}) != len(new_c_powers): + # start over again + c_part = [] + c_powers = _gather(new_c_powers) + else: + break + + # x x x + # 2 * 3 -> 6 + inv_exp_dict = {} # exp:Mul(num-bases) x x + # e.g. x:6 for ... * 2 * 3 * ... + for b, e in num_exp: + inv_exp_dict.setdefault(e, []).append(b) + for e, b in inv_exp_dict.items(): + inv_exp_dict[e] = cls(*b) + c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e]) + + # b, e -> e' = sum(e), b + # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])} + comb_e = {} + for b, e in pnum_rat.items(): + comb_e.setdefault(Add(*e), []).append(b) + del pnum_rat + # process them, reducing exponents to values less than 1 + # and updating coeff if necessary else adding them to + # num_rat for further processing + num_rat = [] + for e, b in comb_e.items(): + b = cls(*b) + if e.q == 1: + coeff *= Pow(b, e) + continue + if e.p > e.q: + e_i, ep = divmod(e.p, e.q) + coeff *= Pow(b, e_i) + e = Rational(ep, e.q) + num_rat.append((b, e)) + del comb_e + + # extract gcd of bases in num_rat + # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4) + pnew = defaultdict(list) + i = 0 # steps through num_rat which may grow + while i < len(num_rat): + bi, ei = num_rat[i] + grow = [] + for j in range(i + 1, len(num_rat)): + bj, ej = num_rat[j] + g = bi.gcd(bj) + if g is not S.One: + # 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2 + # this might have a gcd with something else + e = ei + ej + if e.q == 1: + coeff *= Pow(g, e) + else: + if e.p > e.q: + e_i, ep = divmod(e.p, e.q) # change e in place + coeff *= Pow(g, e_i) + e = Rational(ep, e.q) + grow.append((g, e)) + # update the jth item + num_rat[j] = (bj/g, ej) + # update bi that we are checking with + bi = bi/g + if bi is S.One: + break + if bi is not S.One: + obj = Pow(bi, ei) + if obj.is_Number: + coeff *= obj + else: + # changes like sqrt(12) -> 2*sqrt(3) + for obj in Mul.make_args(obj): + if obj.is_Number: + coeff *= obj + else: + assert obj.is_Pow + bi, ei = obj.args + pnew[ei].append(bi) + + num_rat.extend(grow) + i += 1 + + # combine bases of the new powers + for e, b in pnew.items(): + pnew[e] = cls(*b) + + # handle -1 and I + if neg1e: + # treat I as (-1)**(1/2) and compute -1's total exponent + p, q = neg1e.as_numer_denom() + # if the integer part is odd, extract -1 + n, p = divmod(p, q) + if n % 2: + coeff = -coeff + # if it's a multiple of 1/2 extract I + if q == 2: + c_part.append(S.ImaginaryUnit) + elif p: + # see if there is any positive base this power of + # -1 can join + neg1e = Rational(p, q) + for e, b in pnew.items(): + if e == neg1e and b.is_positive: + pnew[e] = -b + break + else: + # keep it separate; we've already evaluated it as + # much as possible so evaluate=False + c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False)) + + # add all the pnew powers + c_part.extend([Pow(b, e) for e, b in pnew.items()]) + + # oo, -oo + if coeff in (S.Infinity, S.NegativeInfinity): + def _handle_for_oo(c_part, coeff_sign): + new_c_part = [] + for t in c_part: + if t.is_extended_positive: + continue + if t.is_extended_negative: + coeff_sign *= -1 + continue + new_c_part.append(t) + return new_c_part, coeff_sign + c_part, coeff_sign = _handle_for_oo(c_part, 1) + nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign) + coeff *= coeff_sign + + # zoo + if coeff is S.ComplexInfinity: + # zoo might be + # infinite_real + bounded_im + # bounded_real + infinite_im + # infinite_real + infinite_im + # and non-zero real or imaginary will not change that status. + c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and + c.is_extended_real is not None)] + nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and + c.is_extended_real is not None)] + + # 0 + elif coeff.is_zero: + # we know for sure the result will be 0 except the multiplicand + # is infinity or a matrix + if any(isinstance(c, MatrixExpr) for c in nc_part): + return [coeff], nc_part, order_symbols + if any(c.is_finite == False for c in c_part): + return [S.NaN], [], order_symbols + return [coeff], [], order_symbols + + # check for straggling Numbers that were produced + _new = [] + for i in c_part: + if i.is_Number: + coeff *= i + else: + _new.append(i) + c_part = _new + + # order commutative part canonically + _mulsort(c_part) + + # current code expects coeff to be always in slot-0 + if coeff is not S.One: + c_part.insert(0, coeff) + + # we are done + if (global_parameters.distribute and not nc_part and len(c_part) == 2 and + c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add): + # 2*(1+a) -> 2 + 2 * a + coeff = c_part[0] + c_part = [Add(*[coeff*f for f in c_part[1].args])] + + return c_part, nc_part, order_symbols + + def _eval_power(self, e): + + # don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B + cargs, nc = self.args_cnc(split_1=False) + + if e.is_Integer: + return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \ + Pow(Mul._from_args(nc), e, evaluate=False) + if e.is_Rational and e.q == 2: + if self.is_imaginary: + a = self.as_real_imag()[1] + if a.is_Rational: + from .power import integer_nthroot + n, d = abs(a/2).as_numer_denom() + n, t = integer_nthroot(n, 2) + if t: + d, t = integer_nthroot(d, 2) + if t: + from sympy.functions.elementary.complexes import sign + r = sympify(n)/d + return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p) + + p = Pow(self, e, evaluate=False) + + if e.is_Rational or e.is_Float: + return p._eval_expand_power_base() + + return p + + @classmethod + def class_key(cls): + return 3, 0, cls.__name__ + + def _eval_evalf(self, prec): + c, m = self.as_coeff_Mul() + if c is S.NegativeOne: + if m.is_Mul: + rv = -AssocOp._eval_evalf(m, prec) + else: + mnew = m._eval_evalf(prec) + if mnew is not None: + m = mnew + rv = -m + else: + rv = AssocOp._eval_evalf(self, prec) + if rv.is_number: + return rv.expand() + return rv + + @property + def _mpc_(self): + """ + Convert self to an mpmath mpc if possible + """ + from .numbers import Float + im_part, imag_unit = self.as_coeff_Mul() + if imag_unit is not S.ImaginaryUnit: + # ValueError may seem more reasonable but since it's a @property, + # we need to use AttributeError to keep from confusing things like + # hasattr. + raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I") + + return (Float(0)._mpf_, Float(im_part)._mpf_) + + @cacheit + def as_two_terms(self): + """Return head and tail of self. + + This is the most efficient way to get the head and tail of an + expression. + + - if you want only the head, use self.args[0]; + - if you want to process the arguments of the tail then use + self.as_coef_mul() which gives the head and a tuple containing + the arguments of the tail when treated as a Mul. + - if you want the coefficient when self is treated as an Add + then use self.as_coeff_add()[0] + + Examples + ======== + + >>> from sympy.abc import x, y + >>> (3*x*y).as_two_terms() + (3, x*y) + """ + args = self.args + + if len(args) == 1: + return S.One, self + elif len(args) == 2: + return args + + else: + return args[0], self._new_rawargs(*args[1:]) + + @cacheit + def as_coeff_mul(self, *deps, rational=True, **kwargs): + if deps: + l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True) + return self._new_rawargs(*l2), tuple(l1) + args = self.args + if args[0].is_Number: + if not rational or args[0].is_Rational: + return args[0], args[1:] + elif args[0].is_extended_negative: + return S.NegativeOne, (-args[0],) + args[1:] + return S.One, args + + def as_coeff_Mul(self, rational=False): + """ + Efficiently extract the coefficient of a product. + """ + coeff, args = self.args[0], self.args[1:] + + if coeff.is_Number: + if not rational or coeff.is_Rational: + if len(args) == 1: + return coeff, args[0] + else: + return coeff, self._new_rawargs(*args) + elif coeff.is_extended_negative: + return S.NegativeOne, self._new_rawargs(*((-coeff,) + args)) + return S.One, self + + def as_real_imag(self, deep=True, **hints): + from sympy.functions.elementary.complexes import Abs, im, re + other = [] + coeffr = [] + coeffi = [] + addterms = S.One + for a in self.args: + r, i = a.as_real_imag() + if i.is_zero: + coeffr.append(r) + elif r.is_zero: + coeffi.append(i*S.ImaginaryUnit) + elif a.is_commutative: + aconj = a.conjugate() if other else None + # search for complex conjugate pairs: + for i, x in enumerate(other): + if x == aconj: + coeffr.append(Abs(x)**2) + del other[i] + break + else: + if a.is_Add: + addterms *= a + else: + other.append(a) + else: + other.append(a) + m = self.func(*other) + if hints.get('ignore') == m: + return + if len(coeffi) % 2: + imco = im(coeffi.pop(0)) + # all other pairs make a real factor; they will be + # put into reco below + else: + imco = S.Zero + reco = self.func(*(coeffr + coeffi)) + r, i = (reco*re(m), reco*im(m)) + if addterms == 1: + if m == 1: + if imco.is_zero: + return (reco, S.Zero) + else: + return (S.Zero, reco*imco) + if imco is S.Zero: + return (r, i) + return (-imco*i, imco*r) + from .function import expand_mul + addre, addim = expand_mul(addterms, deep=False).as_real_imag() + if imco is S.Zero: + return (r*addre - i*addim, i*addre + r*addim) + else: + r, i = -imco*i, imco*r + return (r*addre - i*addim, r*addim + i*addre) + + @staticmethod + def _expandsums(sums): + """ + Helper function for _eval_expand_mul. + + sums must be a list of instances of Basic. + """ + + L = len(sums) + if L == 1: + return sums[0].args + terms = [] + left = Mul._expandsums(sums[:L//2]) + right = Mul._expandsums(sums[L//2:]) + + terms = [Mul(a, b) for a in left for b in right] + added = Add(*terms) + return Add.make_args(added) # it may have collapsed down to one term + + def _eval_expand_mul(self, **hints): + from sympy.simplify.radsimp import fraction + + # Handle things like 1/(x*(x + 1)), which are automatically converted + # to 1/x*1/(x + 1) + expr = self + n, d = fraction(expr) + if d.is_Mul: + n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i + for i in (n, d)] + expr = n/d + if not expr.is_Mul: + return expr + + plain, sums, rewrite = [], [], False + for factor in expr.args: + if factor.is_Add: + sums.append(factor) + rewrite = True + else: + if factor.is_commutative: + plain.append(factor) + else: + sums.append(Basic(factor)) # Wrapper + + if not rewrite: + return expr + else: + plain = self.func(*plain) + if sums: + deep = hints.get("deep", False) + terms = self.func._expandsums(sums) + args = [] + for term in terms: + t = self.func(plain, term) + if t.is_Mul and any(a.is_Add for a in t.args) and deep: + t = t._eval_expand_mul() + args.append(t) + return Add(*args) + else: + return plain + + @cacheit + def _eval_derivative(self, s): + args = list(self.args) + terms = [] + for i in range(len(args)): + d = args[i].diff(s) + if d: + # Note: reduce is used in step of Mul as Mul is unable to + # handle subtypes and operation priority: + terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One)) + return Add.fromiter(terms) + + @cacheit + def _eval_derivative_n_times(self, s, n): + from .function import AppliedUndef + from .symbol import Symbol, symbols, Dummy + if not isinstance(s, (AppliedUndef, Symbol)): + # other types of s may not be well behaved, e.g. + # (cos(x)*sin(y)).diff([[x, y, z]]) + return super()._eval_derivative_n_times(s, n) + from .numbers import Integer + args = self.args + m = len(args) + if isinstance(n, (int, Integer)): + # https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors + terms = [] + from sympy.ntheory.multinomial import multinomial_coefficients_iterator + for kvals, c in multinomial_coefficients_iterator(m, n): + p = Mul(*[arg.diff((s, k)) for k, arg in zip(kvals, args)]) + terms.append(c * p) + return Add(*terms) + from sympy.concrete.summations import Sum + from sympy.functions.combinatorial.factorials import factorial + from sympy.functions.elementary.miscellaneous import Max + kvals = symbols("k1:%i" % m, cls=Dummy) + klast = n - sum(kvals) + nfact = factorial(n) + e, l = (# better to use the multinomial? + nfact/prod(map(factorial, kvals))/factorial(klast)*\ + Mul(*[args[t].diff((s, kvals[t])) for t in range(m-1)])*\ + args[-1].diff((s, Max(0, klast))), + [(k, 0, n) for k in kvals]) + return Sum(e, *l) + + def _eval_difference_delta(self, n, step): + from sympy.series.limitseq import difference_delta as dd + arg0 = self.args[0] + rest = Mul(*self.args[1:]) + return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) * + rest) + + def _matches_simple(self, expr, repl_dict): + # handle (w*3).matches('x*5') -> {w: x*5/3} + coeff, terms = self.as_coeff_Mul() + terms = Mul.make_args(terms) + if len(terms) == 1: + newexpr = self.__class__._combine_inverse(expr, coeff) + return terms[0].matches(newexpr, repl_dict) + return + + def matches(self, expr, repl_dict=None, old=False): + expr = sympify(expr) + if self.is_commutative and expr.is_commutative: + return self._matches_commutative(expr, repl_dict, old) + elif self.is_commutative is not expr.is_commutative: + return None + + # Proceed only if both both expressions are non-commutative + c1, nc1 = self.args_cnc() + c2, nc2 = expr.args_cnc() + c1, c2 = [c or [1] for c in [c1, c2]] + + # TODO: Should these be self.func? + comm_mul_self = Mul(*c1) + comm_mul_expr = Mul(*c2) + + repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old) + + # If the commutative arguments didn't match and aren't equal, then + # then the expression as a whole doesn't match + if not repl_dict and c1 != c2: + return None + + # Now match the non-commutative arguments, expanding powers to + # multiplications + nc1 = Mul._matches_expand_pows(nc1) + nc2 = Mul._matches_expand_pows(nc2) + + repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict) + + return repl_dict or None + + @staticmethod + def _matches_expand_pows(arg_list): + new_args = [] + for arg in arg_list: + if arg.is_Pow and arg.exp > 0: + new_args.extend([arg.base] * arg.exp) + else: + new_args.append(arg) + return new_args + + @staticmethod + def _matches_noncomm(nodes, targets, repl_dict=None): + """Non-commutative multiplication matcher. + + `nodes` is a list of symbols within the matcher multiplication + expression, while `targets` is a list of arguments in the + multiplication expression being matched against. + """ + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + # List of possible future states to be considered + agenda = [] + # The current matching state, storing index in nodes and targets + state = (0, 0) + node_ind, target_ind = state + # Mapping between wildcard indices and the index ranges they match + wildcard_dict = {} + + while target_ind < len(targets) and node_ind < len(nodes): + node = nodes[node_ind] + + if node.is_Wild: + Mul._matches_add_wildcard(wildcard_dict, state) + + states_matches = Mul._matches_new_states(wildcard_dict, state, + nodes, targets) + if states_matches: + new_states, new_matches = states_matches + agenda.extend(new_states) + if new_matches: + for match in new_matches: + repl_dict[match] = new_matches[match] + if not agenda: + return None + else: + state = agenda.pop() + node_ind, target_ind = state + + return repl_dict + + @staticmethod + def _matches_add_wildcard(dictionary, state): + node_ind, target_ind = state + if node_ind in dictionary: + begin, end = dictionary[node_ind] + dictionary[node_ind] = (begin, target_ind) + else: + dictionary[node_ind] = (target_ind, target_ind) + + @staticmethod + def _matches_new_states(dictionary, state, nodes, targets): + node_ind, target_ind = state + node = nodes[node_ind] + target = targets[target_ind] + + # Don't advance at all if we've exhausted the targets but not the nodes + if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1: + return None + + if node.is_Wild: + match_attempt = Mul._matches_match_wilds(dictionary, node_ind, + nodes, targets) + if match_attempt: + # If the same node has been matched before, don't return + # anything if the current match is diverging from the previous + # match + other_node_inds = Mul._matches_get_other_nodes(dictionary, + nodes, node_ind) + for ind in other_node_inds: + other_begin, other_end = dictionary[ind] + curr_begin, curr_end = dictionary[node_ind] + + other_targets = targets[other_begin:other_end + 1] + current_targets = targets[curr_begin:curr_end + 1] + + for curr, other in zip(current_targets, other_targets): + if curr != other: + return None + + # A wildcard node can match more than one target, so only the + # target index is advanced + new_state = [(node_ind, target_ind + 1)] + # Only move on to the next node if there is one + if node_ind < len(nodes) - 1: + new_state.append((node_ind + 1, target_ind + 1)) + return new_state, match_attempt + else: + # If we're not at a wildcard, then make sure we haven't exhausted + # nodes but not targets, since in this case one node can only match + # one target + if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1: + return None + + match_attempt = node.matches(target) + + if match_attempt: + return [(node_ind + 1, target_ind + 1)], match_attempt + elif node == target: + return [(node_ind + 1, target_ind + 1)], None + else: + return None + + @staticmethod + def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets): + """Determine matches of a wildcard with sub-expression in `target`.""" + wildcard = nodes[wildcard_ind] + begin, end = dictionary[wildcard_ind] + terms = targets[begin:end + 1] + # TODO: Should this be self.func? + mult = Mul(*terms) if len(terms) > 1 else terms[0] + return wildcard.matches(mult) + + @staticmethod + def _matches_get_other_nodes(dictionary, nodes, node_ind): + """Find other wildcards that may have already been matched.""" + ind_node = nodes[node_ind] + return [ind for ind in dictionary if nodes[ind] == ind_node] + + @staticmethod + def _combine_inverse(lhs, rhs): + """ + Returns lhs/rhs, but treats arguments like symbols, so things + like oo/oo return 1 (instead of a nan) and ``I`` behaves like + a symbol instead of sqrt(-1). + """ + from sympy.simplify.simplify import signsimp + from .symbol import Dummy + if lhs == rhs: + return S.One + + def check(l, r): + if l.is_Float and r.is_comparable: + # if both objects are added to 0 they will share the same "normalization" + # and are more likely to compare the same. Since Add(foo, 0) will not allow + # the 0 to pass, we use __add__ directly. + return l.__add__(0) == r.evalf().__add__(0) + return False + if check(lhs, rhs) or check(rhs, lhs): + return S.One + if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)): + # gruntz and limit wants a literal I to not combine + # with a power of -1 + d = Dummy('I') + _i = {S.ImaginaryUnit: d} + i_ = {d: S.ImaginaryUnit} + a = lhs.xreplace(_i).as_powers_dict() + b = rhs.xreplace(_i).as_powers_dict() + blen = len(b) + for bi in tuple(b.keys()): + if bi in a: + a[bi] -= b.pop(bi) + if not a[bi]: + a.pop(bi) + if len(b) != blen: + lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_) + rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_) + rv = lhs/rhs + srv = signsimp(rv) + return srv if srv.is_Number else rv + + def as_powers_dict(self): + d = defaultdict(int) + for term in self.args: + for b, e in term.as_powers_dict().items(): + d[b] += e + return d + + def as_numer_denom(self): + # don't use _from_args to rebuild the numerators and denominators + # as the order is not guaranteed to be the same once they have + # been separated from each other + numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args])) + return self.func(*numers), self.func(*denoms) + + def as_base_exp(self): + e1 = None + bases = [] + nc = 0 + for m in self.args: + b, e = m.as_base_exp() + if not b.is_commutative: + nc += 1 + if e1 is None: + e1 = e + elif e != e1 or nc > 1: + return self, S.One + bases.append(b) + return self.func(*bases), e1 + + def _eval_is_polynomial(self, syms): + return all(term._eval_is_polynomial(syms) for term in self.args) + + def _eval_is_rational_function(self, syms): + return all(term._eval_is_rational_function(syms) for term in self.args) + + def _eval_is_meromorphic(self, x, a): + return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args), + quick_exit=True) + + def _eval_is_algebraic_expr(self, syms): + return all(term._eval_is_algebraic_expr(syms) for term in self.args) + + _eval_is_commutative = lambda self: _fuzzy_group( + a.is_commutative for a in self.args) + + def _eval_is_complex(self): + comp = _fuzzy_group(a.is_complex for a in self.args) + if comp is False: + if any(a.is_infinite for a in self.args): + if any(a.is_zero is not False for a in self.args): + return None + return False + return comp + + def _eval_is_zero_infinite_helper(self): + # + # Helper used by _eval_is_zero and _eval_is_infinite. + # + # Three-valued logic is tricky so let us reason this carefully. It + # would be nice to say that we just check is_zero/is_infinite in all + # args but we need to be careful about the case that one arg is zero + # and another is infinite like Mul(0, oo) or more importantly a case + # where it is not known if the arguments are zero or infinite like + # Mul(y, 1/x). If either y or x could be zero then there is a + # *possibility* that we have Mul(0, oo) which should give None for both + # is_zero and is_infinite. + # + # We keep track of whether we have seen a zero or infinity but we also + # need to keep track of whether we have *possibly* seen one which + # would be indicated by None. + # + # For each argument there is the possibility that is_zero might give + # True, False or None and likewise that is_infinite might give True, + # False or None, giving 9 combinations. The True cases for is_zero and + # is_infinite are mutually exclusive though so there are 3 main cases: + # + # - is_zero = True + # - is_infinite = True + # - is_zero and is_infinite are both either False or None + # + # At the end seen_zero and seen_infinite can be any of 9 combinations + # of True/False/None. Unless one is False though we cannot return + # anything except None: + # + # - is_zero=True needs seen_zero=True and seen_infinite=False + # - is_zero=False needs seen_zero=False + # - is_infinite=True needs seen_infinite=True and seen_zero=False + # - is_infinite=False needs seen_infinite=False + # - anything else gives both is_zero=None and is_infinite=None + # + # The loop only sets the flags to True or None and never back to False. + # Hence as soon as neither flag is False we exit early returning None. + # In particular as soon as we encounter a single arg that has + # is_zero=is_infinite=None we exit. This is a common case since it is + # the default assumptions for a Symbol and also the case for most + # expressions containing such a symbol. The early exit gives a big + # speedup for something like Mul(*symbols('x:1000')).is_zero. + # + seen_zero = seen_infinite = False + + for a in self.args: + if a.is_zero: + if seen_infinite is not False: + return None, None + seen_zero = True + elif a.is_infinite: + if seen_zero is not False: + return None, None + seen_infinite = True + else: + if seen_zero is False and a.is_zero is None: + if seen_infinite is not False: + return None, None + seen_zero = None + if seen_infinite is False and a.is_infinite is None: + if seen_zero is not False: + return None, None + seen_infinite = None + + return seen_zero, seen_infinite + + def _eval_is_zero(self): + # True iff any arg is zero and no arg is infinite but need to handle + # three valued logic carefully. + seen_zero, seen_infinite = self._eval_is_zero_infinite_helper() + + if seen_zero is False: + return False + elif seen_zero is True and seen_infinite is False: + return True + else: + return None + + def _eval_is_infinite(self): + # True iff any arg is infinite and no arg is zero but need to handle + # three valued logic carefully. + seen_zero, seen_infinite = self._eval_is_zero_infinite_helper() + + if seen_infinite is True and seen_zero is False: + return True + elif seen_infinite is False: + return False + else: + return None + + # We do not need to implement _eval_is_finite because the assumptions + # system can infer it from finite = not infinite. + + def _eval_is_rational(self): + r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True) + if r: + return r + elif r is False: + # All args except one are rational + if all(a.is_zero is False for a in self.args): + return False + + def _eval_is_algebraic(self): + r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True) + if r: + return r + elif r is False: + # All args except one are algebraic + if all(a.is_zero is False for a in self.args): + return False + + # without involving odd/even checks this code would suffice: + #_eval_is_integer = lambda self: _fuzzy_group( + # (a.is_integer for a in self.args), quick_exit=True) + def _eval_is_integer(self): + from sympy.ntheory.factor_ import trailing + is_rational = self._eval_is_rational() + if is_rational is False: + return False + + numerators = [] + denominators = [] + unknown = False + for a in self.args: + hit = False + if a.is_integer: + if abs(a) is not S.One: + numerators.append(a) + elif a.is_Rational: + n, d = a.as_numer_denom() + if abs(n) is not S.One: + numerators.append(n) + if d is not S.One: + denominators.append(d) + elif a.is_Pow: + b, e = a.as_base_exp() + if not b.is_integer or not e.is_integer: + hit = unknown = True + if e.is_negative: + denominators.append(2 if a is S.Half else + Pow(a, S.NegativeOne)) + elif not hit: + # int b and pos int e: a = b**e is integer + assert not e.is_positive + # for rational self and e equal to zero: a = b**e is 1 + assert not e.is_zero + return # sign of e unknown -> self.is_integer unknown + else: + # x**2, 2**x, or x**y with x and y int-unknown -> unknown + return + else: + return + + if not denominators and not unknown: + return True + + allodd = lambda x: all(i.is_odd for i in x) + alleven = lambda x: all(i.is_even for i in x) + anyeven = lambda x: any(i.is_even for i in x) + + from .relational import is_gt + if not numerators and denominators and all( + is_gt(_, S.One) for _ in denominators): + return False + elif unknown: + return + elif allodd(numerators) and anyeven(denominators): + return False + elif anyeven(numerators) and denominators == [2]: + return True + elif alleven(numerators) and allodd(denominators + ) and (Mul(*denominators, evaluate=False) - 1 + ).is_positive: + return False + if len(denominators) == 1: + d = denominators[0] + if d.is_Integer and d.is_even: + # if minimal power of 2 in num vs den is not + # negative then we have an integer + if (Add(*[i.as_base_exp()[1] for i in + numerators if i.is_even]) - trailing(d.p) + ).is_nonnegative: + return True + if len(numerators) == 1: + n = numerators[0] + if n.is_Integer and n.is_even: + # if minimal power of 2 in den vs num is positive + # then we have have a non-integer + if (Add(*[i.as_base_exp()[1] for i in + denominators if i.is_even]) - trailing(n.p) + ).is_positive: + return False + + def _eval_is_polar(self): + has_polar = any(arg.is_polar for arg in self.args) + return has_polar and \ + all(arg.is_polar or arg.is_positive for arg in self.args) + + def _eval_is_extended_real(self): + return self._eval_real_imag(True) + + def _eval_real_imag(self, real): + zero = False + t_not_re_im = None + + for t in self.args: + if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False: + return False + elif t.is_imaginary: # I + real = not real + elif t.is_extended_real: # 2 + if not zero: + z = t.is_zero + if not z and zero is False: + zero = z + elif z: + if all(a.is_finite for a in self.args): + return True + return + elif t.is_extended_real is False: + # symbolic or literal like `2 + I` or symbolic imaginary + if t_not_re_im: + return # complex terms might cancel + t_not_re_im = t + elif t.is_imaginary is False: # symbolic like `2` or `2 + I` + if t_not_re_im: + return # complex terms might cancel + t_not_re_im = t + else: + return + + if t_not_re_im: + if t_not_re_im.is_extended_real is False: + if real: # like 3 + return zero # 3*(smthng like 2 + I or i) is not real + if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I + if not real: # like I + return zero # I*(smthng like 2 or 2 + I) is not real + elif zero is False: + return real # can't be trumped by 0 + elif real: + return real # doesn't matter what zero is + + def _eval_is_imaginary(self): + if all(a.is_zero is False and a.is_finite for a in self.args): + return self._eval_real_imag(False) + + def _eval_is_hermitian(self): + return self._eval_herm_antiherm(True) + + def _eval_is_antihermitian(self): + return self._eval_herm_antiherm(False) + + def _eval_herm_antiherm(self, herm): + for t in self.args: + if t.is_hermitian is None or t.is_antihermitian is None: + return + if t.is_hermitian: + continue + elif t.is_antihermitian: + herm = not herm + else: + return + + if herm is not False: + return herm + + is_zero = self._eval_is_zero() + if is_zero: + return True + elif is_zero is False: + return herm + + def _eval_is_irrational(self): + for t in self.args: + a = t.is_irrational + if a: + others = list(self.args) + others.remove(t) + if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others): + return True + return + if a is None: + return + if all(x.is_real for x in self.args): + return False + + def _eval_is_extended_positive(self): + """Return True if self is positive, False if not, and None if it + cannot be determined. + + Explanation + =========== + + This algorithm is non-recursive and works by keeping track of the + sign which changes when a negative or nonpositive is encountered. + Whether a nonpositive or nonnegative is seen is also tracked since + the presence of these makes it impossible to return True, but + possible to return False if the end result is nonpositive. e.g. + + pos * neg * nonpositive -> pos or zero -> None is returned + pos * neg * nonnegative -> neg or zero -> False is returned + """ + return self._eval_pos_neg(1) + + def _eval_pos_neg(self, sign): + saw_NON = saw_NOT = False + for t in self.args: + if t.is_extended_positive: + continue + elif t.is_extended_negative: + sign = -sign + elif t.is_zero: + if all(a.is_finite for a in self.args): + return False + return + elif t.is_extended_nonpositive: + sign = -sign + saw_NON = True + elif t.is_extended_nonnegative: + saw_NON = True + # FIXME: is_positive/is_negative is False doesn't take account of + # Symbol('x', infinite=True, extended_real=True) which has + # e.g. is_positive is False but has uncertain sign. + elif t.is_positive is False: + sign = -sign + if saw_NOT: + return + saw_NOT = True + elif t.is_negative is False: + if saw_NOT: + return + saw_NOT = True + else: + return + if sign == 1 and saw_NON is False and saw_NOT is False: + return True + if sign < 0: + return False + + def _eval_is_extended_negative(self): + return self._eval_pos_neg(-1) + + def _eval_is_odd(self): + is_integer = self._eval_is_integer() + if is_integer is not True: + return is_integer + + from sympy.simplify.radsimp import fraction + n, d = fraction(self) + if d.is_Integer and d.is_even: + from sympy.ntheory.factor_ import trailing + # if minimal power of 2 in num vs den is + # positive then we have an even number + if (Add(*[i.as_base_exp()[1] for i in + Mul.make_args(n) if i.is_even]) - trailing(d.p) + ).is_positive: + return False + return + r, acc = True, 1 + for t in self.args: + if abs(t) is S.One: + continue + if t.is_even: + return False + if r is False: + pass + elif acc != 1 and (acc + t).is_odd: + r = False + elif t.is_even is None: + r = None + acc = t + return r + + def _eval_is_even(self): + from sympy.simplify.radsimp import fraction + n, d = fraction(self) + if n.is_Integer and n.is_even: + # if minimal power of 2 in den vs num is not + # negative then this is not an integer and + # can't be even + from sympy.ntheory.factor_ import trailing + if (Add(*[i.as_base_exp()[1] for i in + Mul.make_args(d) if i.is_even]) - trailing(n.p) + ).is_nonnegative: + return False + + def _eval_is_composite(self): + """ + Here we count the number of arguments that have a minimum value + greater than two. + If there are more than one of such a symbol then the result is composite. + Else, the result cannot be determined. + """ + number_of_args = 0 # count of symbols with minimum value greater than one + for arg in self.args: + if not (arg.is_integer and arg.is_positive): + return None + if (arg-1).is_positive: + number_of_args += 1 + + if number_of_args > 1: + return True + + def _eval_subs(self, old, new): + from sympy.functions.elementary.complexes import sign + from sympy.ntheory.factor_ import multiplicity + from sympy.simplify.powsimp import powdenest + from sympy.simplify.radsimp import fraction + + if not old.is_Mul: + return None + + # try keep replacement literal so -2*x doesn't replace 4*x + if old.args[0].is_Number and old.args[0] < 0: + if self.args[0].is_Number: + if self.args[0] < 0: + return self._subs(-old, -new) + return None + + def base_exp(a): + # if I and -1 are in a Mul, they get both end up with + # a -1 base (see issue 6421); all we want here are the + # true Pow or exp separated into base and exponent + from sympy.functions.elementary.exponential import exp + if a.is_Pow or isinstance(a, exp): + return a.as_base_exp() + return a, S.One + + def breakup(eq): + """break up powers of eq when treated as a Mul: + b**(Rational*e) -> b**e, Rational + commutatives come back as a dictionary {b**e: Rational} + noncommutatives come back as a list [(b**e, Rational)] + """ + + (c, nc) = (defaultdict(int), []) + for a in Mul.make_args(eq): + a = powdenest(a) + (b, e) = base_exp(a) + if e is not S.One: + (co, _) = e.as_coeff_mul() + b = Pow(b, e/co) + e = co + if a.is_commutative: + c[b] += e + else: + nc.append([b, e]) + return (c, nc) + + def rejoin(b, co): + """ + Put rational back with exponent; in general this is not ok, but + since we took it from the exponent for analysis, it's ok to put + it back. + """ + + (b, e) = base_exp(b) + return Pow(b, e*co) + + def ndiv(a, b): + """if b divides a in an extractive way (like 1/4 divides 1/2 + but not vice versa, and 2/5 does not divide 1/3) then return + the integer number of times it divides, else return 0. + """ + if not b.q % a.q or not a.q % b.q: + return int(a/b) + return 0 + + # give Muls in the denominator a chance to be changed (see issue 5651) + # rv will be the default return value + rv = None + n, d = fraction(self) + self2 = self + if d is not S.One: + self2 = n._subs(old, new)/d._subs(old, new) + if not self2.is_Mul: + return self2._subs(old, new) + if self2 != self: + rv = self2 + + # Now continue with regular substitution. + + # handle the leading coefficient and use it to decide if anything + # should even be started; we always know where to find the Rational + # so it's a quick test + + co_self = self2.args[0] + co_old = old.args[0] + co_xmul = None + if co_old.is_Rational and co_self.is_Rational: + # if coeffs are the same there will be no updating to do + # below after breakup() step; so skip (and keep co_xmul=None) + if co_old != co_self: + co_xmul = co_self.extract_multiplicatively(co_old) + elif co_old.is_Rational: + return rv + + # break self and old into factors + + (c, nc) = breakup(self2) + (old_c, old_nc) = breakup(old) + + # update the coefficients if we had an extraction + # e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5 + # then co_self in c is replaced by (3/5)**2 and co_residual + # is 2*(1/7)**2 + + if co_xmul and co_xmul.is_Rational and abs(co_old) != 1: + mult = S(multiplicity(abs(co_old), co_self)) + c.pop(co_self) + if co_old in c: + c[co_old] += mult + else: + c[co_old] = mult + co_residual = co_self/co_old**mult + else: + co_residual = 1 + + # do quick tests to see if we can't succeed + + ok = True + if len(old_nc) > len(nc): + # more non-commutative terms + ok = False + elif len(old_c) > len(c): + # more commutative terms + ok = False + elif {i[0] for i in old_nc}.difference({i[0] for i in nc}): + # unmatched non-commutative bases + ok = False + elif set(old_c).difference(set(c)): + # unmatched commutative terms + ok = False + elif any(sign(c[b]) != sign(old_c[b]) for b in old_c): + # differences in sign + ok = False + if not ok: + return rv + + if not old_c: + cdid = None + else: + rat = [] + for (b, old_e) in old_c.items(): + c_e = c[b] + rat.append(ndiv(c_e, old_e)) + if not rat[-1]: + return rv + cdid = min(rat) + + if not old_nc: + ncdid = None + for i in range(len(nc)): + nc[i] = rejoin(*nc[i]) + else: + ncdid = 0 # number of nc replacements we did + take = len(old_nc) # how much to look at each time + limit = cdid or S.Infinity # max number that we can take + failed = [] # failed terms will need subs if other terms pass + i = 0 + while limit and i + take <= len(nc): + hit = False + + # the bases must be equivalent in succession, and + # the powers must be extractively compatible on the + # first and last factor but equal in between. + + rat = [] + for j in range(take): + if nc[i + j][0] != old_nc[j][0]: + break + elif j == 0: + rat.append(ndiv(nc[i + j][1], old_nc[j][1])) + elif j == take - 1: + rat.append(ndiv(nc[i + j][1], old_nc[j][1])) + elif nc[i + j][1] != old_nc[j][1]: + break + else: + rat.append(1) + j += 1 + else: + ndo = min(rat) + if ndo: + if take == 1: + if cdid: + ndo = min(cdid, ndo) + nc[i] = Pow(new, ndo)*rejoin(nc[i][0], + nc[i][1] - ndo*old_nc[0][1]) + else: + ndo = 1 + + # the left residual + + l = rejoin(nc[i][0], nc[i][1] - ndo* + old_nc[0][1]) + + # eliminate all middle terms + + mid = new + + # the right residual (which may be the same as the middle if take == 2) + + ir = i + take - 1 + r = (nc[ir][0], nc[ir][1] - ndo* + old_nc[-1][1]) + if r[1]: + if i + take < len(nc): + nc[i:i + take] = [l*mid, r] + else: + r = rejoin(*r) + nc[i:i + take] = [l*mid*r] + else: + + # there was nothing left on the right + + nc[i:i + take] = [l*mid] + + limit -= ndo + ncdid += ndo + hit = True + if not hit: + + # do the subs on this failing factor + + failed.append(i) + i += 1 + else: + + if not ncdid: + return rv + + # although we didn't fail, certain nc terms may have + # failed so we rebuild them after attempting a partial + # subs on them + + failed.extend(range(i, len(nc))) + for i in failed: + nc[i] = rejoin(*nc[i]).subs(old, new) + + # rebuild the expression + + if cdid is None: + do = ncdid + elif ncdid is None: + do = cdid + else: + do = min(ncdid, cdid) + + margs = [] + for b in c: + if b in old_c: + + # calculate the new exponent + + e = c[b] - old_c[b]*do + margs.append(rejoin(b, e)) + else: + margs.append(rejoin(b.subs(old, new), c[b])) + if cdid and not ncdid: + + # in case we are replacing commutative with non-commutative, + # we want the new term to come at the front just like the + # rest of this routine + + margs = [Pow(new, cdid)] + margs + return co_residual*self2.func(*margs)*self2.func(*nc) + + def _eval_nseries(self, x, n, logx, cdir=0): + from .function import PoleError + from sympy.functions.elementary.integers import ceiling + from sympy.series.order import Order + + def coeff_exp(term, x): + lt = term.as_coeff_exponent(x) + if lt[0].has(x): + try: + lt = term.leadterm(x) + except ValueError: + return term, S.Zero + return lt + + ords = [] + + try: + for t in self.args: + coeff, exp = t.leadterm(x) + if not coeff.has(x): + ords.append((t, exp)) + else: + raise ValueError + + n0 = sum(t[1] for t in ords if t[1].is_number) + facs = [] + for t, m in ords: + n1 = ceiling(n - n0 + (m if m.is_number else 0)) + s = t.nseries(x, n=n1, logx=logx, cdir=cdir) + ns = s.getn() + if ns is not None: + if ns < n1: # less than expected + n -= n1 - ns # reduce n + facs.append(s) + + except (ValueError, NotImplementedError, TypeError, AttributeError, PoleError): + n0 = sympify(sum(t[1] for t in ords if t[1].is_number)) + if n0.is_nonnegative: + n0 = S.Zero + facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args] + from sympy.simplify.powsimp import powsimp + res = powsimp(self.func(*facs).expand(), combine='exp', deep=True) + if res.has(Order): + res += Order(x**n, x) + return res + + res = S.Zero + ords2 = [Add.make_args(factor) for factor in facs] + + for fac in product(*ords2): + ords3 = [coeff_exp(term, x) for term in fac] + coeffs, powers = zip(*ords3) + power = sum(powers) + if (power - n).is_negative: + res += Mul(*coeffs)*(x**power) + + def max_degree(e, x): + if e is x: + return S.One + if e.is_Atom: + return S.Zero + if e.is_Add: + return max(max_degree(a, x) for a in e.args) + if e.is_Mul: + return Add(*[max_degree(a, x) for a in e.args]) + if e.is_Pow: + return max_degree(e.base, x)*e.exp + return S.Zero + + if self.is_polynomial(x): + from sympy.polys.polyerrors import PolynomialError + from sympy.polys.polytools import degree + try: + if max_degree(self, x) >= n or degree(self, x) != degree(res, x): + res += Order(x**n, x) + except PolynomialError: + pass + else: + return res + + if res != self: + if (self - res).subs(x, 0) == S.Zero and n > 0: + lt = self._eval_as_leading_term(x, logx=logx, cdir=cdir) + if lt == S.Zero: + return res + res += Order(x**n, x) + return res + + def _eval_as_leading_term(self, x, logx=None, cdir=0): + return self.func(*[t.as_leading_term(x, logx=logx, cdir=cdir) for t in self.args]) + + def _eval_conjugate(self): + return self.func(*[t.conjugate() for t in self.args]) + + def _eval_transpose(self): + return self.func(*[t.transpose() for t in self.args[::-1]]) + + def _eval_adjoint(self): + return self.func(*[t.adjoint() for t in self.args[::-1]]) + + def as_content_primitive(self, radical=False, clear=True): + """Return the tuple (R, self/R) where R is the positive Rational + extracted from self. + + Examples + ======== + + >>> from sympy import sqrt + >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive() + (6, -sqrt(2)*(1 - sqrt(2))) + + See docstring of Expr.as_content_primitive for more examples. + """ + + coef = S.One + args = [] + for a in self.args: + c, p = a.as_content_primitive(radical=radical, clear=clear) + coef *= c + if p is not S.One: + args.append(p) + # don't use self._from_args here to reconstruct args + # since there may be identical args now that should be combined + # e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x)) + return coef, self.func(*args) + + def as_ordered_factors(self, order=None): + """Transform an expression into an ordered list of factors. + + Examples + ======== + + >>> from sympy import sin, cos + >>> from sympy.abc import x, y + + >>> (2*x*y*sin(x)*cos(x)).as_ordered_factors() + [2, x, y, sin(x), cos(x)] + + """ + cpart, ncpart = self.args_cnc() + cpart.sort(key=lambda expr: expr.sort_key(order=order)) + return cpart + ncpart + + @property + def _sorted_args(self): + return tuple(self.as_ordered_factors()) + +mul = AssocOpDispatcher('mul') + + +def prod(a, start=1): + """Return product of elements of a. Start with int 1 so if only + ints are included then an int result is returned. + + Examples + ======== + + >>> from sympy import prod, S + >>> prod(range(3)) + 0 + >>> type(_) is int + True + >>> prod([S(2), 3]) + 6 + >>> _.is_Integer + True + + You can start the product at something other than 1: + + >>> prod([1, 2], 3) + 6 + + """ + return reduce(operator.mul, a, start) + + +def _keep_coeff(coeff, factors, clear=True, sign=False): + """Return ``coeff*factors`` unevaluated if necessary. + + If ``clear`` is False, do not keep the coefficient as a factor + if it can be distributed on a single factor such that one or + more terms will still have integer coefficients. + + If ``sign`` is True, allow a coefficient of -1 to remain factored out. + + Examples + ======== + + >>> from sympy.core.mul import _keep_coeff + >>> from sympy.abc import x, y + >>> from sympy import S + + >>> _keep_coeff(S.Half, x + 2) + (x + 2)/2 + >>> _keep_coeff(S.Half, x + 2, clear=False) + x/2 + 1 + >>> _keep_coeff(S.Half, (x + 2)*y, clear=False) + y*(x + 2)/2 + >>> _keep_coeff(S(-1), x + y) + -x - y + >>> _keep_coeff(S(-1), x + y, sign=True) + -(x + y) + """ + if not coeff.is_Number: + if factors.is_Number: + factors, coeff = coeff, factors + else: + return coeff*factors + if factors is S.One: + return coeff + if coeff is S.One: + return factors + elif coeff is S.NegativeOne and not sign: + return -factors + elif factors.is_Add: + if not clear and coeff.is_Rational and coeff.q != 1: + args = [i.as_coeff_Mul() for i in factors.args] + args = [(_keep_coeff(c, coeff), m) for c, m in args] + if any(c.is_Integer for c, _ in args): + return Add._from_args([Mul._from_args( + i[1:] if i[0] == 1 else i) for i in args]) + return Mul(coeff, factors, evaluate=False) + elif factors.is_Mul: + margs = list(factors.args) + if margs[0].is_Number: + margs[0] *= coeff + if margs[0] == 1: + margs.pop(0) + else: + margs.insert(0, coeff) + return Mul._from_args(margs) + else: + m = coeff*factors + if m.is_Number and not factors.is_Number: + m = Mul._from_args((coeff, factors)) + return m + +def expand_2arg(e): + def do(e): + if e.is_Mul: + c, r = e.as_coeff_Mul() + if c.is_Number and r.is_Add: + return _unevaluated_Add(*[c*ri for ri in r.args]) + return e + return bottom_up(e, do) + + +from .numbers import Rational +from .power import Pow +from .add import Add, _unevaluated_Add diff --git a/shared/package-files/77/77bd8e4b9ac248ac9a0ba5eefc2ab268515bf2d1cbbb841ec75612516d46a4e0/blob b/shared/package-files/77/77bd8e4b9ac248ac9a0ba5eefc2ab268515bf2d1cbbb841ec75612516d46a4e0/blob new file mode 100644 index 0000000000000000000000000000000000000000..7a5524deafac2050bb073a931fa1d0b945415b97 --- /dev/null +++ b/shared/package-files/77/77bd8e4b9ac248ac9a0ba5eefc2ab268515bf2d1cbbb841ec75612516d46a4e0/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor erfc(const at::Tensor & self); +TORCH_API at::Tensor & erfc_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & erfc_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & erfc_(at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/77/77bf5c9a0af6303cfbf54432e8286829fe0c49c282b43bed38154621b575eb8e/blob b/shared/package-files/77/77bf5c9a0af6303cfbf54432e8286829fe0c49c282b43bed38154621b575eb8e/blob new file mode 100644 index 0000000000000000000000000000000000000000..ab4e5d1b992a8069433af01937ea8f9df4fccc6f --- /dev/null +++ b/shared/package-files/77/77bf5c9a0af6303cfbf54432e8286829fe0c49c282b43bed38154621b575eb8e/blob @@ -0,0 +1,406 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Tools for dealing with Arrow type metadata in Python + + +from enum import IntEnum + +from pyarrow.lib import (is_boolean_value, # noqa + is_integer_value, + is_float_value) + +import pyarrow.lib as lib +from pyarrow.util import doc + + +_SIGNED_INTEGER_TYPES = {lib.Type_INT8, lib.Type_INT16, lib.Type_INT32, + lib.Type_INT64} +_UNSIGNED_INTEGER_TYPES = {lib.Type_UINT8, lib.Type_UINT16, lib.Type_UINT32, + lib.Type_UINT64} +_INTEGER_TYPES = _SIGNED_INTEGER_TYPES | _UNSIGNED_INTEGER_TYPES +_FLOATING_TYPES = {lib.Type_HALF_FLOAT, lib.Type_FLOAT, lib.Type_DOUBLE} +_DECIMAL_TYPES = {lib.Type_DECIMAL32, lib.Type_DECIMAL64, lib.Type_DECIMAL128, + lib.Type_DECIMAL256} +_DATE_TYPES = {lib.Type_DATE32, lib.Type_DATE64} +_TIME_TYPES = {lib.Type_TIME32, lib.Type_TIME64} +_INTERVAL_TYPES = {lib.Type_INTERVAL_MONTH_DAY_NANO} +_TEMPORAL_TYPES = ({lib.Type_TIMESTAMP, + lib.Type_DURATION} | _TIME_TYPES | _DATE_TYPES | + _INTERVAL_TYPES) +_UNION_TYPES = {lib.Type_SPARSE_UNION, lib.Type_DENSE_UNION} +_NESTED_TYPES = {lib.Type_LIST, lib.Type_FIXED_SIZE_LIST, lib.Type_LARGE_LIST, + lib.Type_LIST_VIEW, lib.Type_LARGE_LIST_VIEW, + lib.Type_STRUCT, lib.Type_MAP} | _UNION_TYPES + + +class TypesEnum(IntEnum): + """ + An Enum that maps constant values to data types. + Exposes the underlying data types representation for type checking purposes. + Note that some of the types listed here are not supported by PyArrow yet: + INTERVAL_MONTHS and INTERVAL_DAY_TIME. + + Examples + -------- + >>> import pyarrow as pa + >>> from pyarrow.types import TypesEnum + >>> int8_field = pa.field('int8_field', pa.int8()) + >>> int8_field.type.id == TypesEnum.INT8 + True + + >>> fixed_size_list = pa.list_(pa.uint16(), 3) + >>> fixed_size_list.id == TypesEnum.LIST + False + + >>> fixed_size_list.id == TypesEnum.FIXED_SIZE_LIST + True + """ + + NA = lib.Type_NA + BOOL = lib.Type_BOOL + + INT8 = lib.Type_INT8 + INT16 = lib.Type_INT16 + INT32 = lib.Type_INT32 + INT64 = lib.Type_INT64 + + UINT8 = lib.Type_UINT8 + UINT16 = lib.Type_UINT16 + UINT32 = lib.Type_UINT32 + UINT64 = lib.Type_UINT64 + + HALF_FLOAT = lib.Type_HALF_FLOAT + FLOAT = lib.Type_FLOAT + DOUBLE = lib.Type_DOUBLE + + BINARY = lib.Type_BINARY + BINARY_VIEW = lib.Type_BINARY_VIEW + LARGE_BINARY = lib.Type_LARGE_BINARY + STRING = lib.Type_STRING + STRING_VIEW = lib.Type_STRING_VIEW + LARGE_STRING = lib.Type_LARGE_STRING + FIXED_SIZE_BINARY = lib.Type_FIXED_SIZE_BINARY + + DECIMAL32 = lib.Type_DECIMAL32 + DECIMAL64 = lib.Type_DECIMAL64 + DECIMAL128 = lib.Type_DECIMAL128 + DECIMAL256 = lib.Type_DECIMAL256 + + LIST = lib.Type_LIST + LARGE_LIST = lib.Type_LARGE_LIST + LIST_VIEW = lib.Type_LIST_VIEW + LARGE_LIST_VIEW = lib.Type_LARGE_LIST_VIEW + MAP = lib.Type_MAP + FIXED_SIZE_LIST = lib.Type_FIXED_SIZE_LIST + + STRUCT = lib.Type_STRUCT + SPARSE_UNION = lib.Type_SPARSE_UNION + DENSE_UNION = lib.Type_DENSE_UNION + RUN_END_ENCODED = lib.Type_RUN_END_ENCODED + + DATE32 = lib.Type_DATE32 + DATE64 = lib.Type_DATE64 + TIME32 = lib.Type_TIME32 + TIME64 = lib.Type_TIME64 + TIMESTAMP = lib.Type_TIMESTAMP + + INTERVAL_MONTHS = lib.Type_INTERVAL_MONTHS + INTERVAL_DAY_TIME = lib.Type_INTERVAL_DAY_TIME + INTERVAL_MONTH_DAY_NANO = lib.Type_INTERVAL_MONTH_DAY_NANO + + DURATION = lib.Type_DURATION + DICTIONARY = lib.Type_DICTIONARY + + +@doc(datatype="null") +def is_null(t): + """ + Return True if value is an instance of type: {datatype}. + + Parameters + ---------- + t : DataType + """ + return t.id == lib.Type_NA + + +@doc(is_null, datatype="boolean") +def is_boolean(t): + return t.id == lib.Type_BOOL + + +@doc(is_null, datatype="any integer") +def is_integer(t): + return t.id in _INTEGER_TYPES + + +@doc(is_null, datatype="signed integer") +def is_signed_integer(t): + return t.id in _SIGNED_INTEGER_TYPES + + +@doc(is_null, datatype="unsigned integer") +def is_unsigned_integer(t): + return t.id in _UNSIGNED_INTEGER_TYPES + + +@doc(is_null, datatype="int8") +def is_int8(t): + return t.id == lib.Type_INT8 + + +@doc(is_null, datatype="int16") +def is_int16(t): + return t.id == lib.Type_INT16 + + +@doc(is_null, datatype="int32") +def is_int32(t): + return t.id == lib.Type_INT32 + + +@doc(is_null, datatype="int64") +def is_int64(t): + return t.id == lib.Type_INT64 + + +@doc(is_null, datatype="uint8") +def is_uint8(t): + return t.id == lib.Type_UINT8 + + +@doc(is_null, datatype="uint16") +def is_uint16(t): + return t.id == lib.Type_UINT16 + + +@doc(is_null, datatype="uint32") +def is_uint32(t): + return t.id == lib.Type_UINT32 + + +@doc(is_null, datatype="uint64") +def is_uint64(t): + return t.id == lib.Type_UINT64 + + +@doc(is_null, datatype="floating point numeric") +def is_floating(t): + return t.id in _FLOATING_TYPES + + +@doc(is_null, datatype="float16 (half-precision)") +def is_float16(t): + return t.id == lib.Type_HALF_FLOAT + + +@doc(is_null, datatype="float32 (single precision)") +def is_float32(t): + return t.id == lib.Type_FLOAT + + +@doc(is_null, datatype="float64 (double precision)") +def is_float64(t): + return t.id == lib.Type_DOUBLE + + +@doc(is_null, datatype="list") +def is_list(t): + return t.id == lib.Type_LIST + + +@doc(is_null, datatype="large list") +def is_large_list(t): + return t.id == lib.Type_LARGE_LIST + + +@doc(is_null, datatype="fixed size list") +def is_fixed_size_list(t): + return t.id == lib.Type_FIXED_SIZE_LIST + + +@doc(is_null, datatype="list view") +def is_list_view(t): + return t.id == lib.Type_LIST_VIEW + + +@doc(is_null, datatype="large list view") +def is_large_list_view(t): + return t.id == lib.Type_LARGE_LIST_VIEW + + +@doc(is_null, datatype="struct") +def is_struct(t): + return t.id == lib.Type_STRUCT + + +@doc(is_null, datatype="union") +def is_union(t): + return t.id in _UNION_TYPES + + +@doc(is_null, datatype="nested type") +def is_nested(t): + return t.id in _NESTED_TYPES + + +@doc(is_null, datatype="run-end encoded") +def is_run_end_encoded(t): + return t.id == lib.Type_RUN_END_ENCODED + + +@doc(is_null, datatype="date, time, timestamp or duration") +def is_temporal(t): + return t.id in _TEMPORAL_TYPES + + +@doc(is_null, datatype="timestamp") +def is_timestamp(t): + return t.id == lib.Type_TIMESTAMP + + +@doc(is_null, datatype="duration") +def is_duration(t): + return t.id == lib.Type_DURATION + + +@doc(is_null, datatype="time") +def is_time(t): + return t.id in _TIME_TYPES + + +@doc(is_null, datatype="time32") +def is_time32(t): + return t.id == lib.Type_TIME32 + + +@doc(is_null, datatype="time64") +def is_time64(t): + return t.id == lib.Type_TIME64 + + +@doc(is_null, datatype="variable-length binary") +def is_binary(t): + return t.id == lib.Type_BINARY + + +@doc(is_null, datatype="large variable-length binary") +def is_large_binary(t): + return t.id == lib.Type_LARGE_BINARY + + +@doc(method="is_string") +def is_unicode(t): + """ + Alias for {method}. + + Parameters + ---------- + t : DataType + """ + return is_string(t) + + +@doc(is_null, datatype="string (utf8 unicode)") +def is_string(t): + return t.id == lib.Type_STRING + + +@doc(is_unicode, method="is_large_string") +def is_large_unicode(t): + return is_large_string(t) + + +@doc(is_null, datatype="large string (utf8 unicode)") +def is_large_string(t): + return t.id == lib.Type_LARGE_STRING + + +@doc(is_null, datatype="fixed size binary") +def is_fixed_size_binary(t): + return t.id == lib.Type_FIXED_SIZE_BINARY + + +@doc(is_null, datatype="variable-length binary view") +def is_binary_view(t): + return t.id == lib.Type_BINARY_VIEW + + +@doc(is_null, datatype="variable-length string (utf-8) view") +def is_string_view(t): + return t.id == lib.Type_STRING_VIEW + + +@doc(is_null, datatype="date") +def is_date(t): + return t.id in _DATE_TYPES + + +@doc(is_null, datatype="date32 (days)") +def is_date32(t): + return t.id == lib.Type_DATE32 + + +@doc(is_null, datatype="date64 (milliseconds)") +def is_date64(t): + return t.id == lib.Type_DATE64 + + +@doc(is_null, datatype="map") +def is_map(t): + return t.id == lib.Type_MAP + + +@doc(is_null, datatype="decimal") +def is_decimal(t): + return t.id in _DECIMAL_TYPES + + +@doc(is_null, datatype="decimal32") +def is_decimal32(t): + return t.id == lib.Type_DECIMAL32 + + +@doc(is_null, datatype="decimal64") +def is_decimal64(t): + return t.id == lib.Type_DECIMAL64 + + +@doc(is_null, datatype="decimal128") +def is_decimal128(t): + return t.id == lib.Type_DECIMAL128 + + +@doc(is_null, datatype="decimal256") +def is_decimal256(t): + return t.id == lib.Type_DECIMAL256 + + +@doc(is_null, datatype="dictionary-encoded") +def is_dictionary(t): + return t.id == lib.Type_DICTIONARY + + +@doc(is_null, datatype="interval") +def is_interval(t): + return t.id == lib.Type_INTERVAL_MONTH_DAY_NANO + + +@doc(is_null, datatype="primitive type") +def is_primitive(t): + return lib._is_primitive(t.id) diff --git a/shared/package-files/77/77c41686645deaa95a19f3beb58ea20d066df57522c9f25f29d8e81a3bf0394e/blob b/shared/package-files/77/77c41686645deaa95a19f3beb58ea20d066df57522c9f25f29d8e81a3bf0394e/blob new file mode 100644 index 0000000000000000000000000000000000000000..776e5eeba7b725ea68e2a1f3ffc7099b7797b709 --- /dev/null +++ b/shared/package-files/77/77c41686645deaa95a19f3beb58ea20d066df57522c9f25f29d8e81a3bf0394e/blob @@ -0,0 +1,516 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2009-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""EDNS Options""" + +import binascii +import math +import socket +import struct +from typing import Any, Dict, Optional, Union + +import dns.enum +import dns.inet +import dns.rdata +import dns.wire + + +class OptionType(dns.enum.IntEnum): + #: NSID + NSID = 3 + #: DAU + DAU = 5 + #: DHU + DHU = 6 + #: N3U + N3U = 7 + #: ECS (client-subnet) + ECS = 8 + #: EXPIRE + EXPIRE = 9 + #: COOKIE + COOKIE = 10 + #: KEEPALIVE + KEEPALIVE = 11 + #: PADDING + PADDING = 12 + #: CHAIN + CHAIN = 13 + #: EDE (extended-dns-error) + EDE = 15 + + @classmethod + def _maximum(cls): + return 65535 + + +class Option: + """Base class for all EDNS option types.""" + + def __init__(self, otype: Union[OptionType, str]): + """Initialize an option. + + *otype*, a ``dns.edns.OptionType``, is the option type. + """ + self.otype = OptionType.make(otype) + + def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]: + """Convert an option to wire format. + + Returns a ``bytes`` or ``None``. + + """ + raise NotImplementedError # pragma: no cover + + def to_text(self) -> str: + raise NotImplementedError # pragma: no cover + + @classmethod + def from_wire_parser(cls, otype: OptionType, parser: "dns.wire.Parser") -> "Option": + """Build an EDNS option object from wire format. + + *otype*, a ``dns.edns.OptionType``, is the option type. + + *parser*, a ``dns.wire.Parser``, the parser, which should be + restructed to the option length. + + Returns a ``dns.edns.Option``. + """ + raise NotImplementedError # pragma: no cover + + def _cmp(self, other): + """Compare an EDNS option with another option of the same type. + + Returns < 0 if < *other*, 0 if == *other*, and > 0 if > *other*. + """ + wire = self.to_wire() + owire = other.to_wire() + if wire == owire: + return 0 + if wire > owire: + return 1 + return -1 + + def __eq__(self, other): + if not isinstance(other, Option): + return False + if self.otype != other.otype: + return False + return self._cmp(other) == 0 + + def __ne__(self, other): + if not isinstance(other, Option): + return True + if self.otype != other.otype: + return True + return self._cmp(other) != 0 + + def __lt__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) < 0 + + def __le__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) <= 0 + + def __ge__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) >= 0 + + def __gt__(self, other): + if not isinstance(other, Option) or self.otype != other.otype: + return NotImplemented + return self._cmp(other) > 0 + + def __str__(self): + return self.to_text() + + +class GenericOption(Option): # lgtm[py/missing-equals] + """Generic Option Class + + This class is used for EDNS option types for which we have no better + implementation. + """ + + def __init__(self, otype: Union[OptionType, str], data: Union[bytes, str]): + super().__init__(otype) + self.data = dns.rdata.Rdata._as_bytes(data, True) + + def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]: + if file: + file.write(self.data) + return None + else: + return self.data + + def to_text(self) -> str: + return "Generic %d" % self.otype + + @classmethod + def from_wire_parser( + cls, otype: Union[OptionType, str], parser: "dns.wire.Parser" + ) -> Option: + return cls(otype, parser.get_remaining()) + + +class ECSOption(Option): # lgtm[py/missing-equals] + """EDNS Client Subnet (ECS, RFC7871)""" + + def __init__(self, address: str, srclen: Optional[int] = None, scopelen: int = 0): + """*address*, a ``str``, is the client address information. + + *srclen*, an ``int``, the source prefix length, which is the + leftmost number of bits of the address to be used for the + lookup. The default is 24 for IPv4 and 56 for IPv6. + + *scopelen*, an ``int``, the scope prefix length. This value + must be 0 in queries, and should be set in responses. + """ + + super().__init__(OptionType.ECS) + af = dns.inet.af_for_address(address) + + if af == socket.AF_INET6: + self.family = 2 + if srclen is None: + srclen = 56 + address = dns.rdata.Rdata._as_ipv6_address(address) + srclen = dns.rdata.Rdata._as_int(srclen, 0, 128) + scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 128) + elif af == socket.AF_INET: + self.family = 1 + if srclen is None: + srclen = 24 + address = dns.rdata.Rdata._as_ipv4_address(address) + srclen = dns.rdata.Rdata._as_int(srclen, 0, 32) + scopelen = dns.rdata.Rdata._as_int(scopelen, 0, 32) + else: # pragma: no cover (this will never happen) + raise ValueError("Bad address family") + + assert srclen is not None + self.address = address + self.srclen = srclen + self.scopelen = scopelen + + addrdata = dns.inet.inet_pton(af, address) + nbytes = int(math.ceil(srclen / 8.0)) + + # Truncate to srclen and pad to the end of the last octet needed + # See RFC section 6 + self.addrdata = addrdata[:nbytes] + nbits = srclen % 8 + if nbits != 0: + last = struct.pack("B", ord(self.addrdata[-1:]) & (0xFF << (8 - nbits))) + self.addrdata = self.addrdata[:-1] + last + + def to_text(self) -> str: + return "ECS {}/{} scope/{}".format(self.address, self.srclen, self.scopelen) + + @staticmethod + def from_text(text: str) -> Option: + """Convert a string into a `dns.edns.ECSOption` + + *text*, a `str`, the text form of the option. + + Returns a `dns.edns.ECSOption`. + + Examples: + + >>> import dns.edns + >>> + >>> # basic example + >>> dns.edns.ECSOption.from_text('1.2.3.4/24') + >>> + >>> # also understands scope + >>> dns.edns.ECSOption.from_text('1.2.3.4/24/32') + >>> + >>> # IPv6 + >>> dns.edns.ECSOption.from_text('2001:4b98::1/64/64') + >>> + >>> # it understands results from `dns.edns.ECSOption.to_text()` + >>> dns.edns.ECSOption.from_text('ECS 1.2.3.4/24/32') + """ + optional_prefix = "ECS" + tokens = text.split() + ecs_text = None + if len(tokens) == 1: + ecs_text = tokens[0] + elif len(tokens) == 2: + if tokens[0] != optional_prefix: + raise ValueError('could not parse ECS from "{}"'.format(text)) + ecs_text = tokens[1] + else: + raise ValueError('could not parse ECS from "{}"'.format(text)) + n_slashes = ecs_text.count("/") + if n_slashes == 1: + address, tsrclen = ecs_text.split("/") + tscope = "0" + elif n_slashes == 2: + address, tsrclen, tscope = ecs_text.split("/") + else: + raise ValueError('could not parse ECS from "{}"'.format(text)) + try: + scope = int(tscope) + except ValueError: + raise ValueError( + "invalid scope " + '"{}": scope must be an integer'.format(tscope) + ) + try: + srclen = int(tsrclen) + except ValueError: + raise ValueError( + "invalid srclen " + '"{}": srclen must be an integer'.format(tsrclen) + ) + return ECSOption(address, srclen, scope) + + def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]: + value = ( + struct.pack("!HBB", self.family, self.srclen, self.scopelen) + self.addrdata + ) + if file: + file.write(value) + return None + else: + return value + + @classmethod + def from_wire_parser( + cls, otype: Union[OptionType, str], parser: "dns.wire.Parser" + ) -> Option: + family, src, scope = parser.get_struct("!HBB") + addrlen = int(math.ceil(src / 8.0)) + prefix = parser.get_bytes(addrlen) + if family == 1: + pad = 4 - addrlen + addr = dns.ipv4.inet_ntoa(prefix + b"\x00" * pad) + elif family == 2: + pad = 16 - addrlen + addr = dns.ipv6.inet_ntoa(prefix + b"\x00" * pad) + else: + raise ValueError("unsupported family") + + return cls(addr, src, scope) + + +class EDECode(dns.enum.IntEnum): + OTHER = 0 + UNSUPPORTED_DNSKEY_ALGORITHM = 1 + UNSUPPORTED_DS_DIGEST_TYPE = 2 + STALE_ANSWER = 3 + FORGED_ANSWER = 4 + DNSSEC_INDETERMINATE = 5 + DNSSEC_BOGUS = 6 + SIGNATURE_EXPIRED = 7 + SIGNATURE_NOT_YET_VALID = 8 + DNSKEY_MISSING = 9 + RRSIGS_MISSING = 10 + NO_ZONE_KEY_BIT_SET = 11 + NSEC_MISSING = 12 + CACHED_ERROR = 13 + NOT_READY = 14 + BLOCKED = 15 + CENSORED = 16 + FILTERED = 17 + PROHIBITED = 18 + STALE_NXDOMAIN_ANSWER = 19 + NOT_AUTHORITATIVE = 20 + NOT_SUPPORTED = 21 + NO_REACHABLE_AUTHORITY = 22 + NETWORK_ERROR = 23 + INVALID_DATA = 24 + + @classmethod + def _maximum(cls): + return 65535 + + +class EDEOption(Option): # lgtm[py/missing-equals] + """Extended DNS Error (EDE, RFC8914)""" + + _preserve_case = {"DNSKEY", "DS", "DNSSEC", "RRSIGs", "NSEC", "NXDOMAIN"} + + def __init__(self, code: Union[EDECode, str], text: Optional[str] = None): + """*code*, a ``dns.edns.EDECode`` or ``str``, the info code of the + extended error. + + *text*, a ``str`` or ``None``, specifying additional information about + the error. + """ + + super().__init__(OptionType.EDE) + + self.code = EDECode.make(code) + if text is not None and not isinstance(text, str): + raise ValueError("text must be string or None") + self.text = text + + def to_text(self) -> str: + output = f"EDE {self.code}" + if self.code in EDECode: + desc = EDECode.to_text(self.code) + desc = " ".join( + word if word in self._preserve_case else word.title() + for word in desc.split("_") + ) + output += f" ({desc})" + if self.text is not None: + output += f": {self.text}" + return output + + def to_wire(self, file: Optional[Any] = None) -> Optional[bytes]: + value = struct.pack("!H", self.code) + if self.text is not None: + value += self.text.encode("utf8") + + if file: + file.write(value) + return None + else: + return value + + @classmethod + def from_wire_parser( + cls, otype: Union[OptionType, str], parser: "dns.wire.Parser" + ) -> Option: + code = EDECode.make(parser.get_uint16()) + text = parser.get_remaining() + + if text: + if text[-1] == 0: # text MAY be null-terminated + text = text[:-1] + btext = text.decode("utf8") + else: + btext = None + + return cls(code, btext) + + +class NSIDOption(Option): + def __init__(self, nsid: bytes): + super().__init__(OptionType.NSID) + self.nsid = nsid + + def to_wire(self, file: Any = None) -> Optional[bytes]: + if file: + file.write(self.nsid) + return None + else: + return self.nsid + + def to_text(self) -> str: + if all(c >= 0x20 and c <= 0x7E for c in self.nsid): + # All ASCII printable, so it's probably a string. + value = self.nsid.decode() + else: + value = binascii.hexlify(self.nsid).decode() + return f"NSID {value}" + + @classmethod + def from_wire_parser( + cls, otype: Union[OptionType, str], parser: dns.wire.Parser + ) -> Option: + return cls(parser.get_remaining()) + + +_type_to_class: Dict[OptionType, Any] = { + OptionType.ECS: ECSOption, + OptionType.EDE: EDEOption, + OptionType.NSID: NSIDOption, +} + + +def get_option_class(otype: OptionType) -> Any: + """Return the class for the specified option type. + + The GenericOption class is used if a more specific class is not + known. + """ + + cls = _type_to_class.get(otype) + if cls is None: + cls = GenericOption + return cls + + +def option_from_wire_parser( + otype: Union[OptionType, str], parser: "dns.wire.Parser" +) -> Option: + """Build an EDNS option object from wire format. + + *otype*, an ``int``, is the option type. + + *parser*, a ``dns.wire.Parser``, the parser, which should be + restricted to the option length. + + Returns an instance of a subclass of ``dns.edns.Option``. + """ + otype = OptionType.make(otype) + cls = get_option_class(otype) + return cls.from_wire_parser(otype, parser) + + +def option_from_wire( + otype: Union[OptionType, str], wire: bytes, current: int, olen: int +) -> Option: + """Build an EDNS option object from wire format. + + *otype*, an ``int``, is the option type. + + *wire*, a ``bytes``, is the wire-format message. + + *current*, an ``int``, is the offset in *wire* of the beginning + of the rdata. + + *olen*, an ``int``, is the length of the wire-format option data + + Returns an instance of a subclass of ``dns.edns.Option``. + """ + parser = dns.wire.Parser(wire, current) + with parser.restrict_to(olen): + return option_from_wire_parser(otype, parser) + + +def register_type(implementation: Any, otype: OptionType) -> None: + """Register the implementation of an option type. + + *implementation*, a ``class``, is a subclass of ``dns.edns.Option``. + + *otype*, an ``int``, is the option type. + """ + + _type_to_class[otype] = implementation + + +### BEGIN generated OptionType constants + +NSID = OptionType.NSID +DAU = OptionType.DAU +DHU = OptionType.DHU +N3U = OptionType.N3U +ECS = OptionType.ECS +EXPIRE = OptionType.EXPIRE +COOKIE = OptionType.COOKIE +KEEPALIVE = OptionType.KEEPALIVE +PADDING = OptionType.PADDING +CHAIN = OptionType.CHAIN +EDE = OptionType.EDE + +### END generated OptionType constants diff --git a/shared/package-files/77/77c68196b1252b399b4fb4322a1d0a731cab9e300b00a2ad46bf13369ae7e323/blob b/shared/package-files/77/77c68196b1252b399b4fb4322a1d0a731cab9e300b00a2ad46bf13369ae7e323/blob new file mode 100644 index 0000000000000000000000000000000000000000..e9546d2f9deeeb04c0f3720b3667877da89227b8 --- /dev/null +++ b/shared/package-files/77/77c68196b1252b399b4fb4322a1d0a731cab9e300b00a2ad46bf13369ae7e323/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API detach_copy { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::detach_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "detach_copy(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API detach_copy_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::detach_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "detach_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/77/77c7483a784b28e1545eb9dc35d1101abbecdff77f6904ef98d8f35e74a13485/blob b/shared/package-files/77/77c7483a784b28e1545eb9dc35d1101abbecdff77f6904ef98d8f35e74a13485/blob new file mode 100644 index 0000000000000000000000000000000000000000..38cfa189b5d2dfabc4da4b19489ccb108e8fa5ba --- /dev/null +++ b/shared/package-files/77/77c7483a784b28e1545eb9dc35d1101abbecdff77f6904ef98d8f35e74a13485/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor linalg_eigvalsh(const at::Tensor & self, c10::string_view UPLO="L"); +TORCH_API at::Tensor & linalg_eigvalsh_out(at::Tensor & out, const at::Tensor & self, c10::string_view UPLO="L"); +TORCH_API at::Tensor & linalg_eigvalsh_outf(const at::Tensor & self, c10::string_view UPLO, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/77/77c9bbd2de4635ca0b1c0b5583757685f62317725314883d5f4bbd3ceb178186/blob b/shared/package-files/77/77c9bbd2de4635ca0b1c0b5583757685f62317725314883d5f4bbd3ceb178186/blob new file mode 100644 index 0000000000000000000000000000000000000000..8c2078e5a9c44223082be7984efda7d2194c5297 --- /dev/null +++ b/shared/package-files/77/77c9bbd2de4635ca0b1c0b5583757685f62317725314883d5f4bbd3ceb178186/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _test_check_tensor(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77ca0c22962f06998bce5e48d81cb865a14466c83ff5dc607eaa483344058bf6/blob b/shared/package-files/77/77ca0c22962f06998bce5e48d81cb865a14466c83ff5dc607eaa483344058bf6/blob new file mode 100644 index 0000000000000000000000000000000000000000..cdf0572be31d3052a98494e3d01802b83737f23c Binary files /dev/null and b/shared/package-files/77/77ca0c22962f06998bce5e48d81cb865a14466c83ff5dc607eaa483344058bf6/blob differ diff --git a/shared/package-files/77/77cac82ad51ea97b793b9d5d37078b729fc9eb8e3929d0bd69626718a47bcdd2/blob b/shared/package-files/77/77cac82ad51ea97b793b9d5d37078b729fc9eb8e3929d0bd69626718a47bcdd2/blob new file mode 100644 index 0000000000000000000000000000000000000000..bb9e9c6db132e07a0fcfabebd38a3a78e17c3e17 --- /dev/null +++ b/shared/package-files/77/77cac82ad51ea97b793b9d5d37078b729fc9eb8e3929d0bd69626718a47bcdd2/blob @@ -0,0 +1,172 @@ +import subprocess +import sys +import time +from socket import socket as _socket +from ssl import SSLContext, SSLSocket +from types import TracebackType +from typing import IO, Any, Callable, Dict, List, Optional, Pattern, Text, Tuple, Type, Union +from typing_extensions import Literal + +# TODO: Commands should use their actual return types, not this type alias. +# E.g. Tuple[Literal["OK"], List[bytes]] +_CommandResults = Tuple[str, List[Any]] + +_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] + +class IMAP4: + error: Type[Exception] = ... + abort: Type[Exception] = ... + readonly: Type[Exception] = ... + mustquote: Pattern[Text] = ... + debug: int = ... + state: str = ... + literal: Optional[Text] = ... + tagged_commands: Dict[bytes, Optional[List[bytes]]] + untagged_responses: Dict[str, List[Union[bytes, Tuple[bytes, bytes]]]] + continuation_response: str = ... + is_readonly: bool = ... + tagnum: int = ... + tagpre: str = ... + tagre: Pattern[Text] = ... + welcome: bytes = ... + capabilities: Tuple[str] = ... + PROTOCOL_VERSION: str = ... + if sys.version_info >= (3, 9): + def __init__(self, host: str = ..., port: int = ..., timeout: Optional[float] = ...) -> None: ... + def open(self, host: str = ..., port: int = ..., timeout: Optional[float] = ...) -> None: ... + else: + def __init__(self, host: str = ..., port: int = ...) -> None: ... + def open(self, host: str = ..., port: int = ...) -> None: ... + def __getattr__(self, attr: str) -> Any: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: Union[IO[Text], IO[bytes]] = ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def recent(self) -> _CommandResults: ... + def response(self, code: str) -> _CommandResults: ... + def append(self, mailbox: str, flags: str, date_time: str, message: str) -> str: ... + def authenticate(self, mechanism: str, authobject: Callable[[bytes], Optional[bytes]]) -> Tuple[str, str]: ... + def capability(self) -> _CommandResults: ... + def check(self) -> _CommandResults: ... + def close(self) -> _CommandResults: ... + def copy(self, message_set: str, new_mailbox: str) -> _CommandResults: ... + def create(self, mailbox: str) -> _CommandResults: ... + def delete(self, mailbox: str) -> _CommandResults: ... + def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... + if sys.version_info >= (3, 5): + def enable(self, capability: str) -> _CommandResults: ... + def __enter__(self) -> IMAP4: ... + def __exit__(self, t: Optional[Type[BaseException]], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... + def expunge(self) -> _CommandResults: ... + def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... + def getacl(self, mailbox: str) -> _CommandResults: ... + def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ... + def getquota(self, root: str) -> _CommandResults: ... + def getquotaroot(self, mailbox: str) -> _CommandResults: ... + def list(self, directory: str = ..., pattern: str = ...) -> Tuple[str, _AnyResponseData]: ... + def login(self, user: str, password: str) -> Tuple[Literal["OK"], List[bytes]]: ... + def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... + def logout(self) -> Tuple[str, _AnyResponseData]: ... + def lsub(self, directory: str = ..., pattern: str = ...) -> _CommandResults: ... + def myrights(self, mailbox: str) -> _CommandResults: ... + def namespace(self) -> _CommandResults: ... + def noop(self) -> Tuple[str, List[bytes]]: ... + def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: ... + def proxyauth(self, user: str) -> _CommandResults: ... + def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ... + def search(self, charset: Optional[str], *criteria: str) -> _CommandResults: ... + def select(self, mailbox: str = ..., readonly: bool = ...) -> Tuple[str, List[Optional[bytes]]]: ... + def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... + def setannotation(self, *args: str) -> _CommandResults: ... + def setquota(self, root: str, limits: str) -> _CommandResults: ... + def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... + if sys.version_info >= (3,): + def starttls(self, ssl_context: Optional[Any] = ...) -> Tuple[Literal["OK"], List[None]]: ... + def status(self, mailbox: str, names: str) -> _CommandResults: ... + def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ... + def subscribe(self, mailbox: str) -> _CommandResults: ... + def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ... + def uid(self, command: str, *args: str) -> _CommandResults: ... + def unsubscribe(self, mailbox: str) -> _CommandResults: ... + if sys.version_info >= (3, 9): + def unselect(self) -> _CommandResults: ... + def xatom(self, name: str, *args: str) -> _CommandResults: ... + def print_log(self) -> None: ... + +class IMAP4_SSL(IMAP4): + keyfile: str = ... + certfile: str = ... + if sys.version_info >= (3, 9): + def __init__( + self, + host: str = ..., + port: int = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + ssl_context: Optional[SSLContext] = ..., + timeout: Optional[float] = ..., + ) -> None: ... + elif sys.version_info >= (3, 3): + def __init__( + self, + host: str = ..., + port: int = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + ssl_context: Optional[SSLContext] = ..., + ) -> None: ... + else: + def __init__( + self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ... + ) -> None: ... + host: str = ... + port: int = ... + sock: _socket = ... + sslobj: SSLSocket = ... + file: IO[Any] = ... + if sys.version_info >= (3, 9): + def open(self, host: str = ..., port: Optional[int] = ..., timeout: Optional[float] = ...) -> None: ... + else: + def open(self, host: str = ..., port: Optional[int] = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def ssl(self) -> SSLSocket: ... + +class IMAP4_stream(IMAP4): + command: str = ... + def __init__(self, command: str) -> None: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: IO[Any] = ... + process: subprocess.Popen[bytes] = ... + writefile: IO[Any] = ... + readfile: IO[Any] = ... + if sys.version_info >= (3, 9): + def open(self, host: Optional[str] = ..., port: Optional[int] = ..., timeout: Optional[float] = ...) -> None: ... + else: + def open(self, host: Optional[str] = ..., port: Optional[int] = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + +class _Authenticator: + mech: Callable[[bytes], bytes] = ... + def __init__(self, mechinst: Callable[[bytes], bytes]) -> None: ... + def process(self, data: str) -> str: ... + def encode(self, inp: bytes) -> str: ... + def decode(self, inp: str) -> bytes: ... + +def Internaldate2tuple(resp: str) -> time.struct_time: ... +def Int2AP(num: int) -> str: ... +def ParseFlags(resp: str) -> Tuple[str]: ... +def Time2Internaldate(date_time: Union[float, time.struct_time, str]) -> str: ... diff --git a/shared/package-files/77/77cc215c5333161333f95c34a57eceaee1b1ba2071be80695653c147b3021e01/blob b/shared/package-files/77/77cc215c5333161333f95c34a57eceaee1b1ba2071be80695653c147b3021e01/blob new file mode 100644 index 0000000000000000000000000000000000000000..01f1fef192ad850e60b8a360a7ae01addd947687 --- /dev/null +++ b/shared/package-files/77/77cc215c5333161333f95c34a57eceaee1b1ba2071be80695653c147b3021e01/blob @@ -0,0 +1,19 @@ +#---------------------------------------------------------------- +# Generated CMake target import file for configuration "Release". +#---------------------------------------------------------------- + +# Commands may need to know the format version. +set(CMAKE_IMPORT_FILE_VERSION 1) + +# Import target "libmamba" for configuration "Release" +set_property(TARGET libmamba APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) +set_target_properties(libmamba PROPERTIES + IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libmamba.so.2.0.0" + IMPORTED_SONAME_RELEASE "libmamba.so.2" + ) + +list(APPEND _cmake_import_check_targets libmamba ) +list(APPEND _cmake_import_check_files_for_libmamba "${_IMPORT_PREFIX}/lib/libmamba.so.2.0.0" ) + +# Commands beyond this point should not need to know the version. +set(CMAKE_IMPORT_FILE_VERSION) diff --git a/shared/package-files/77/77cde5d50a42095a8c576936f4d3242f72ddd6a363882ea1cce3d66408af1234/blob b/shared/package-files/77/77cde5d50a42095a8c576936f4d3242f72ddd6a363882ea1cce3d66408af1234/blob new file mode 100644 index 0000000000000000000000000000000000000000..cea5b0d4678346249233435061e094297dea1979 --- /dev/null +++ b/shared/package-files/77/77cde5d50a42095a8c576936f4d3242f72ddd6a363882ea1cce3d66408af1234/blob @@ -0,0 +1,211 @@ +#ifndef NUMPY_CORE_INCLUDE_NUMPY_NOPREFIX_H_ +#define NUMPY_CORE_INCLUDE_NUMPY_NOPREFIX_H_ + +/* + * You can directly include noprefix.h as a backward + * compatibility measure + */ +#ifndef NPY_NO_PREFIX +#include "ndarrayobject.h" +#include "npy_interrupt.h" +#endif + +#define SIGSETJMP NPY_SIGSETJMP +#define SIGLONGJMP NPY_SIGLONGJMP +#define SIGJMP_BUF NPY_SIGJMP_BUF + +#define MAX_DIMS NPY_MAXDIMS + +#define longlong npy_longlong +#define ulonglong npy_ulonglong +#define Bool npy_bool +#define longdouble npy_longdouble +#define byte npy_byte + +#ifndef _BSD_SOURCE +#define ushort npy_ushort +#define uint npy_uint +#define ulong npy_ulong +#endif + +#define ubyte npy_ubyte +#define ushort npy_ushort +#define uint npy_uint +#define ulong npy_ulong +#define cfloat npy_cfloat +#define cdouble npy_cdouble +#define clongdouble npy_clongdouble +#define Int8 npy_int8 +#define UInt8 npy_uint8 +#define Int16 npy_int16 +#define UInt16 npy_uint16 +#define Int32 npy_int32 +#define UInt32 npy_uint32 +#define Int64 npy_int64 +#define UInt64 npy_uint64 +#define Int128 npy_int128 +#define UInt128 npy_uint128 +#define Int256 npy_int256 +#define UInt256 npy_uint256 +#define Float16 npy_float16 +#define Complex32 npy_complex32 +#define Float32 npy_float32 +#define Complex64 npy_complex64 +#define Float64 npy_float64 +#define Complex128 npy_complex128 +#define Float80 npy_float80 +#define Complex160 npy_complex160 +#define Float96 npy_float96 +#define Complex192 npy_complex192 +#define Float128 npy_float128 +#define Complex256 npy_complex256 +#define intp npy_intp +#define uintp npy_uintp +#define datetime npy_datetime +#define timedelta npy_timedelta + +#define SIZEOF_LONGLONG NPY_SIZEOF_LONGLONG +#define SIZEOF_INTP NPY_SIZEOF_INTP +#define SIZEOF_UINTP NPY_SIZEOF_UINTP +#define SIZEOF_HALF NPY_SIZEOF_HALF +#define SIZEOF_LONGDOUBLE NPY_SIZEOF_LONGDOUBLE +#define SIZEOF_DATETIME NPY_SIZEOF_DATETIME +#define SIZEOF_TIMEDELTA NPY_SIZEOF_TIMEDELTA + +#define LONGLONG_FMT NPY_LONGLONG_FMT +#define ULONGLONG_FMT NPY_ULONGLONG_FMT +#define LONGLONG_SUFFIX NPY_LONGLONG_SUFFIX +#define ULONGLONG_SUFFIX NPY_ULONGLONG_SUFFIX + +#define MAX_INT8 127 +#define MIN_INT8 -128 +#define MAX_UINT8 255 +#define MAX_INT16 32767 +#define MIN_INT16 -32768 +#define MAX_UINT16 65535 +#define MAX_INT32 2147483647 +#define MIN_INT32 (-MAX_INT32 - 1) +#define MAX_UINT32 4294967295U +#define MAX_INT64 LONGLONG_SUFFIX(9223372036854775807) +#define MIN_INT64 (-MAX_INT64 - LONGLONG_SUFFIX(1)) +#define MAX_UINT64 ULONGLONG_SUFFIX(18446744073709551615) +#define MAX_INT128 LONGLONG_SUFFIX(85070591730234615865843651857942052864) +#define MIN_INT128 (-MAX_INT128 - LONGLONG_SUFFIX(1)) +#define MAX_UINT128 ULONGLONG_SUFFIX(170141183460469231731687303715884105728) +#define MAX_INT256 LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) +#define MIN_INT256 (-MAX_INT256 - LONGLONG_SUFFIX(1)) +#define MAX_UINT256 ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) + +#define MAX_BYTE NPY_MAX_BYTE +#define MIN_BYTE NPY_MIN_BYTE +#define MAX_UBYTE NPY_MAX_UBYTE +#define MAX_SHORT NPY_MAX_SHORT +#define MIN_SHORT NPY_MIN_SHORT +#define MAX_USHORT NPY_MAX_USHORT +#define MAX_INT NPY_MAX_INT +#define MIN_INT NPY_MIN_INT +#define MAX_UINT NPY_MAX_UINT +#define MAX_LONG NPY_MAX_LONG +#define MIN_LONG NPY_MIN_LONG +#define MAX_ULONG NPY_MAX_ULONG +#define MAX_LONGLONG NPY_MAX_LONGLONG +#define MIN_LONGLONG NPY_MIN_LONGLONG +#define MAX_ULONGLONG NPY_MAX_ULONGLONG +#define MIN_DATETIME NPY_MIN_DATETIME +#define MAX_DATETIME NPY_MAX_DATETIME +#define MIN_TIMEDELTA NPY_MIN_TIMEDELTA +#define MAX_TIMEDELTA NPY_MAX_TIMEDELTA + +#define BITSOF_BOOL NPY_BITSOF_BOOL +#define BITSOF_CHAR NPY_BITSOF_CHAR +#define BITSOF_SHORT NPY_BITSOF_SHORT +#define BITSOF_INT NPY_BITSOF_INT +#define BITSOF_LONG NPY_BITSOF_LONG +#define BITSOF_LONGLONG NPY_BITSOF_LONGLONG +#define BITSOF_HALF NPY_BITSOF_HALF +#define BITSOF_FLOAT NPY_BITSOF_FLOAT +#define BITSOF_DOUBLE NPY_BITSOF_DOUBLE +#define BITSOF_LONGDOUBLE NPY_BITSOF_LONGDOUBLE +#define BITSOF_DATETIME NPY_BITSOF_DATETIME +#define BITSOF_TIMEDELTA NPY_BITSOF_TIMEDELTA + +#define _pya_malloc PyArray_malloc +#define _pya_free PyArray_free +#define _pya_realloc PyArray_realloc + +#define BEGIN_THREADS_DEF NPY_BEGIN_THREADS_DEF +#define BEGIN_THREADS NPY_BEGIN_THREADS +#define END_THREADS NPY_END_THREADS +#define ALLOW_C_API_DEF NPY_ALLOW_C_API_DEF +#define ALLOW_C_API NPY_ALLOW_C_API +#define DISABLE_C_API NPY_DISABLE_C_API + +#define PY_FAIL NPY_FAIL +#define PY_SUCCEED NPY_SUCCEED + +#ifndef TRUE +#define TRUE NPY_TRUE +#endif + +#ifndef FALSE +#define FALSE NPY_FALSE +#endif + +#define LONGDOUBLE_FMT NPY_LONGDOUBLE_FMT + +#define CONTIGUOUS NPY_CONTIGUOUS +#define C_CONTIGUOUS NPY_C_CONTIGUOUS +#define FORTRAN NPY_FORTRAN +#define F_CONTIGUOUS NPY_F_CONTIGUOUS +#define OWNDATA NPY_OWNDATA +#define FORCECAST NPY_FORCECAST +#define ENSURECOPY NPY_ENSURECOPY +#define ENSUREARRAY NPY_ENSUREARRAY +#define ELEMENTSTRIDES NPY_ELEMENTSTRIDES +#define ALIGNED NPY_ALIGNED +#define NOTSWAPPED NPY_NOTSWAPPED +#define WRITEABLE NPY_WRITEABLE +#define WRITEBACKIFCOPY NPY_ARRAY_WRITEBACKIFCOPY +#define ARR_HAS_DESCR NPY_ARR_HAS_DESCR +#define BEHAVED NPY_BEHAVED +#define BEHAVED_NS NPY_BEHAVED_NS +#define CARRAY NPY_CARRAY +#define CARRAY_RO NPY_CARRAY_RO +#define FARRAY NPY_FARRAY +#define FARRAY_RO NPY_FARRAY_RO +#define DEFAULT NPY_DEFAULT +#define IN_ARRAY NPY_IN_ARRAY +#define OUT_ARRAY NPY_OUT_ARRAY +#define INOUT_ARRAY NPY_INOUT_ARRAY +#define IN_FARRAY NPY_IN_FARRAY +#define OUT_FARRAY NPY_OUT_FARRAY +#define INOUT_FARRAY NPY_INOUT_FARRAY +#define UPDATE_ALL NPY_UPDATE_ALL + +#define OWN_DATA NPY_OWNDATA +#define BEHAVED_FLAGS NPY_BEHAVED +#define BEHAVED_FLAGS_NS NPY_BEHAVED_NS +#define CARRAY_FLAGS_RO NPY_CARRAY_RO +#define CARRAY_FLAGS NPY_CARRAY +#define FARRAY_FLAGS NPY_FARRAY +#define FARRAY_FLAGS_RO NPY_FARRAY_RO +#define DEFAULT_FLAGS NPY_DEFAULT +#define UPDATE_ALL_FLAGS NPY_UPDATE_ALL_FLAGS + +#ifndef MIN +#define MIN PyArray_MIN +#endif +#ifndef MAX +#define MAX PyArray_MAX +#endif +#define MAX_INTP NPY_MAX_INTP +#define MIN_INTP NPY_MIN_INTP +#define MAX_UINTP NPY_MAX_UINTP +#define INTP_FMT NPY_INTP_FMT + +#ifndef PYPY_VERSION +#define REFCOUNT PyArray_REFCOUNT +#define MAX_ELSIZE NPY_MAX_ELSIZE +#endif + +#endif /* NUMPY_CORE_INCLUDE_NUMPY_NOPREFIX_H_ */ diff --git a/shared/package-files/77/77cf355620db638b49c372aad449d7ef656858ebb14a097c8f7c6a5f4da15a98/blob b/shared/package-files/77/77cf355620db638b49c372aad449d7ef656858ebb14a097c8f7c6a5f4da15a98/blob new file mode 100644 index 0000000000000000000000000000000000000000..8a329425e71a07f75025d632c0833e8dc9186295 --- /dev/null +++ b/shared/package-files/77/77cf355620db638b49c372aad449d7ef656858ebb14a097c8f7c6a5f4da15a98/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _test_autograd_multiple_dispatch_view_copy_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor _test_autograd_multiple_dispatch_view_copy(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77cff2842710c1b783e915781dd1cd7bb9fa6b1e1a88f4116e4ca278dc448483/blob b/shared/package-files/77/77cff2842710c1b783e915781dd1cd7bb9fa6b1e1a88f4116e4ca278dc448483/blob new file mode 100644 index 0000000000000000000000000000000000000000..392a22bee62aec834674623e25ef25e3b5262a0e --- /dev/null +++ b/shared/package-files/77/77cff2842710c1b783e915781dd1cd7bb9fa6b1e1a88f4116e4ca278dc448483/blob @@ -0,0 +1,1586 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { + +#ifdef CPU_CAPABILITY_AVX2 + +struct Vectorizedi { +protected: + __m256i values; + + static inline __m256i invert(const __m256i& v) { + const auto ones = _mm256_set1_epi64x(-1); + return _mm256_xor_si256(ones, v); + } +public: + Vectorizedi() {} + Vectorizedi(__m256i v) : values(v) {} + operator __m256i() const { + return values; + } +}; + +#else + +struct Vectorizedi {}; // dummy definition to make Vectorizedi always defined + +#endif // CPU_CAPABILITY_AVX2 + +#ifdef CPU_CAPABILITY_AVX2 + +template <> +class Vectorized : public Vectorizedi { +private: + static const Vectorized ones; +public: + using value_type = int64_t; + using size_type = int; + static constexpr size_type size() { + return 4; + } + using Vectorizedi::Vectorizedi; + Vectorized() {} + Vectorized(int64_t v) { values = _mm256_set1_epi64x(v); } + Vectorized(int64_t val1, int64_t val2, int64_t val3, int64_t val4) { + values = _mm256_setr_epi64x(val1, val2, val3, val4); + } + template + static Vectorized blend(Vectorized a, Vectorized b) { + __at_align__ int64_t tmp_values[size()]; + a.store(tmp_values); + if (mask & 0x01) + tmp_values[0] = _mm256_extract_epi64(b.values, 0); + if (mask & 0x02) + tmp_values[1] = _mm256_extract_epi64(b.values, 1); + if (mask & 0x04) + tmp_values[2] = _mm256_extract_epi64(b.values, 2); + if (mask & 0x08) + tmp_values[3] = _mm256_extract_epi64(b.values, 3); + return loadu(tmp_values); + } + static Vectorized blendv(const Vectorized& a, const Vectorized& b, + const Vectorized& mask) { + return _mm256_blendv_epi8(a.values, b.values, mask.values); + } + template + static Vectorized arange(int64_t base = 0, step_t step = static_cast(1)) { + return Vectorized(base, base + step, base + 2 * step, base + 3 * step); + } + static Vectorized + set(Vectorized a, Vectorized b, int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm256_loadu_si256(reinterpret_cast(ptr)); + } + static Vectorized loadu(const void* ptr, int64_t count) { + __at_align__ int64_t tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, ptr, count * sizeof(int64_t)); + return loadu(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm256-storeu-si256.html + _mm256_storeu_si256(reinterpret_cast<__m256i*>(ptr), values); + } else if (count > 0) { + __at_align__ int64_t tmp_values[size()]; + _mm256_storeu_si256(reinterpret_cast<__m256i*>(tmp_values), values); + std::memcpy(ptr, tmp_values, count * sizeof(int64_t)); + } + } + const int64_t& operator[](int idx) const = delete; + int64_t& operator[](int idx) = delete; + Vectorized abs() const { + auto zero = _mm256_set1_epi64x(0); + auto is_larger = _mm256_cmpgt_epi64(zero, values); + auto inverse = _mm256_xor_si256(values, is_larger); + return _mm256_sub_epi64(inverse, is_larger); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm256_set1_epi64x(0); + } + Vectorized conj() const { + return *this; + } + Vectorized neg() const; + Vectorized operator==(const Vectorized& other) const { + return _mm256_cmpeq_epi64(values, other.values); + } + Vectorized operator!=(const Vectorized& other) const { + return invert(_mm256_cmpeq_epi64(values, other.values)); + } + Vectorized operator<(const Vectorized& other) const { + return _mm256_cmpgt_epi64(other.values, values); + } + Vectorized operator<=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi64(values, other.values)); + } + Vectorized operator>(const Vectorized& other) const { + return _mm256_cmpgt_epi64(values, other.values); + } + Vectorized operator>=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi64(other.values, values)); + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +class Vectorized : public Vectorizedi { +private: + static const Vectorized ones; +public: + using value_type = int32_t; + static constexpr int size() { + return 8; + } + using Vectorizedi::Vectorizedi; + Vectorized() {} + Vectorized(int32_t v) { values = _mm256_set1_epi32(v); } + Vectorized(int32_t val1, int32_t val2, int32_t val3, int32_t val4, + int32_t val5, int32_t val6, int32_t val7, int32_t val8) { + values = _mm256_setr_epi32(val1, val2, val3, val4, val5, val6, val7, val8); + } + template + static Vectorized blend(Vectorized a, Vectorized b) { + return _mm256_blend_epi32(a, b, mask); + } + static Vectorized blendv(const Vectorized& a, const Vectorized& b, + const Vectorized& mask) { + return _mm256_blendv_epi8(a.values, b.values, mask.values); + } + template + static Vectorized arange(int32_t base = 0, step_t step = static_cast(1)) { + return Vectorized( + base, base + step, base + 2 * step, base + 3 * step, + base + 4 * step, base + 5 * step, base + 6 * step, base + 7 * step); + } + static Vectorized + set(Vectorized a, Vectorized b, int32_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm256_loadu_si256(reinterpret_cast(ptr)); + } + static Vectorized loadu(const void* ptr, int32_t count) { + __at_align__ int32_t tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, ptr, count * sizeof(int32_t)); + return loadu(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm256-storeu-si256.html + _mm256_storeu_si256(reinterpret_cast<__m256i*>(ptr), values); + } else if (count > 0) { + __at_align__ int32_t tmp_values[size()]; + _mm256_storeu_si256(reinterpret_cast<__m256i*>(tmp_values), values); + std::memcpy(ptr, tmp_values, count * sizeof(int32_t)); + } + } + const int32_t& operator[](int idx) const = delete; + int32_t& operator[](int idx) = delete; + Vectorized abs() const { + return _mm256_abs_epi32(values); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm256_set1_epi32(0); + } + Vectorized conj() const { + return *this; + } + Vectorized neg() const; + Vectorized operator==(const Vectorized& other) const { + return _mm256_cmpeq_epi32(values, other.values); + } + Vectorized operator!=(const Vectorized& other) const { + return invert(_mm256_cmpeq_epi32(values, other.values)); + } + Vectorized operator<(const Vectorized& other) const { + return _mm256_cmpgt_epi32(other.values, values); + } + Vectorized operator<=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi32(values, other.values)); + } + Vectorized operator>(const Vectorized& other) const { + return _mm256_cmpgt_epi32(values, other.values); + } + Vectorized operator>=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi32(other.values, values)); + } + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +inline void convert(const int32_t *src, float *dst, int64_t n) { + int64_t i; + // int32_t and float have same size +#ifndef _MSC_VER +# pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); i += Vectorized::size()) { + auto input_vec = _mm256_loadu_si256(reinterpret_cast(src + i)); + auto output_vec = _mm256_cvtepi32_ps(input_vec); + _mm256_storeu_ps(reinterpret_cast(dst + i), output_vec); + } +#ifndef _MSC_VER +# pragma unroll +#endif + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +template <> +inline void convert(const int32_t *src, double *dst, int64_t n) { + int64_t i; + // int32_t has half the size of double +#ifndef _MSC_VER +# pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); i += Vectorized::size()) { + auto input_128_vec = _mm_loadu_si128(reinterpret_cast(src + i)); + auto output_vec = _mm256_cvtepi32_pd(input_128_vec); + _mm256_storeu_pd(reinterpret_cast(dst + i), output_vec); + } +#ifndef _MSC_VER +# pragma unroll +#endif + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +template <> +class Vectorized : public Vectorizedi { +private: + static const Vectorized ones; +public: + using value_type = int16_t; + static constexpr int size() { + return 16; + } + using Vectorizedi::Vectorizedi; + Vectorized() {} + Vectorized(int16_t v) { values = _mm256_set1_epi16(v); } + Vectorized(int16_t val1, int16_t val2, int16_t val3, int16_t val4, + int16_t val5, int16_t val6, int16_t val7, int16_t val8, + int16_t val9, int16_t val10, int16_t val11, int16_t val12, + int16_t val13, int16_t val14, int16_t val15, int16_t val16) { + values = _mm256_setr_epi16(val1, val2, val3, val4, val5, val6, val7, val8, + val9, val10, val11, val12, val13, val14, val15, val16); + } + template + static Vectorized blend(Vectorized a, Vectorized b) { + __at_align__ int16_t tmp_values[size()]; + a.store(tmp_values); + if (mask & 0x01) + tmp_values[0] = _mm256_extract_epi16(b.values, 0); + if (mask & 0x02) + tmp_values[1] = _mm256_extract_epi16(b.values, 1); + if (mask & 0x04) + tmp_values[2] = _mm256_extract_epi16(b.values, 2); + if (mask & 0x08) + tmp_values[3] = _mm256_extract_epi16(b.values, 3); + if (mask & 0x10) + tmp_values[4] = _mm256_extract_epi16(b.values, 4); + if (mask & 0x20) + tmp_values[5] = _mm256_extract_epi16(b.values, 5); + if (mask & 0x40) + tmp_values[6] = _mm256_extract_epi16(b.values, 6); + if (mask & 0x80) + tmp_values[7] = _mm256_extract_epi16(b.values, 7); + if (mask & 0x100) + tmp_values[8] = _mm256_extract_epi16(b.values, 8); + if (mask & 0x200) + tmp_values[9] = _mm256_extract_epi16(b.values, 9); + if (mask & 0x400) + tmp_values[10] = _mm256_extract_epi16(b.values, 10); + if (mask & 0x800) + tmp_values[11] = _mm256_extract_epi16(b.values, 11); + if (mask & 0x1000) + tmp_values[12] = _mm256_extract_epi16(b.values, 12); + if (mask & 0x2000) + tmp_values[13] = _mm256_extract_epi16(b.values, 13); + if (mask & 0x4000) + tmp_values[14] = _mm256_extract_epi16(b.values, 14); + if (mask & 0x8000) + tmp_values[15] = _mm256_extract_epi16(b.values, 15); + return loadu(tmp_values); + } + static Vectorized blendv(const Vectorized& a, const Vectorized& b, + const Vectorized& mask) { + return _mm256_blendv_epi8(a.values, b.values, mask.values); + } + template + static Vectorized arange(int16_t base = 0, step_t step = static_cast(1)) { + return Vectorized( + base, base + step, base + 2 * step, base + 3 * step, + base + 4 * step, base + 5 * step, base + 6 * step, base + 7 * step, + base + 8 * step, base + 9 * step, base + 10 * step, base + 11 * step, + base + 12 * step, base + 13 * step, base + 14 * step, base + 15 * step); + } + static Vectorized + set(Vectorized a, Vectorized b, int16_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + case 8: + return blend<255>(a, b); + case 9: + return blend<511>(a, b); + case 10: + return blend<1023>(a, b); + case 11: + return blend<2047>(a, b); + case 12: + return blend<4095>(a, b); + case 13: + return blend<8191>(a, b); + case 14: + return blend<16383>(a, b); + case 15: + return blend<32767>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm256_loadu_si256(reinterpret_cast(ptr)); + } + static Vectorized loadu(const void* ptr, int16_t count) { + __at_align__ int16_t tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, ptr, count * sizeof(int16_t)); + return loadu(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm256-storeu-si256.html + _mm256_storeu_si256(reinterpret_cast<__m256i*>(ptr), values); + } else if (count > 0) { + __at_align__ int16_t tmp_values[size()]; + _mm256_storeu_si256(reinterpret_cast<__m256i*>(tmp_values), values); + std::memcpy(ptr, tmp_values, count * sizeof(int16_t)); + } + } + const int16_t& operator[](int idx) const = delete; + int16_t& operator[](int idx) = delete; + Vectorized abs() const { + return _mm256_abs_epi16(values); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm256_set1_epi16(0); + } + Vectorized conj() const { + return *this; + } + Vectorized neg() const; + Vectorized operator==(const Vectorized& other) const { + return _mm256_cmpeq_epi16(values, other.values); + } + Vectorized operator!=(const Vectorized& other) const { + return invert(_mm256_cmpeq_epi16(values, other.values)); + } + Vectorized operator<(const Vectorized& other) const { + return _mm256_cmpgt_epi16(other.values, values); + } + Vectorized operator<=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi16(values, other.values)); + } + Vectorized operator>(const Vectorized& other) const { + return _mm256_cmpgt_epi16(values, other.values); + } + Vectorized operator>=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi16(other.values, values)); + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template +class Vectorized8 : public Vectorizedi { + static_assert( + std::is_same::value || std::is_same::value, + "Only int8_t/uint8_t are supported"); +protected: + static const Vectorized ones; +public: + using value_type = T; + static constexpr int size() { + return 32; + } + using Vectorizedi::Vectorizedi; + Vectorized8() {} + Vectorized8(T v) { values = _mm256_set1_epi8(v); } + Vectorized8(T val1, T val2, T val3, T val4, + T val5, T val6, T val7, T val8, + T val9, T val10, T val11, T val12, + T val13, T val14, T val15, T val16, + T val17, T val18, T val19, T val20, + T val21, T val22, T val23, T val24, + T val25, T val26, T val27, T val28, + T val29, T val30, T val31, T val32) { + values = _mm256_setr_epi8(val1, val2, val3, val4, val5, val6, val7, val8, + val9, val10, val11, val12, val13, val14, val15, val16, + val17, val18, val19, val20, val21, val22, val23, val24, + val25, val26, val27, val28, val29, val30, val31, val32); + } + template + static Vectorized blend(Vectorized a, Vectorized b) { + __at_align__ T tmp_values[size()]; + a.store(tmp_values); + if (mask & 0x01) + tmp_values[0] = _mm256_extract_epi8(b.values, 0); + if (mask & 0x02) + tmp_values[1] = _mm256_extract_epi8(b.values, 1); + if (mask & 0x04) + tmp_values[2] = _mm256_extract_epi8(b.values, 2); + if (mask & 0x08) + tmp_values[3] = _mm256_extract_epi8(b.values, 3); + if (mask & 0x10) + tmp_values[4] = _mm256_extract_epi8(b.values, 4); + if (mask & 0x20) + tmp_values[5] = _mm256_extract_epi8(b.values, 5); + if (mask & 0x40) + tmp_values[6] = _mm256_extract_epi8(b.values, 6); + if (mask & 0x80) + tmp_values[7] = _mm256_extract_epi8(b.values, 7); + if (mask & 0x100) + tmp_values[8] = _mm256_extract_epi8(b.values, 8); + if (mask & 0x200) + tmp_values[9] = _mm256_extract_epi8(b.values, 9); + if (mask & 0x400) + tmp_values[10] = _mm256_extract_epi8(b.values, 10); + if (mask & 0x800) + tmp_values[11] = _mm256_extract_epi8(b.values, 11); + if (mask & 0x1000) + tmp_values[12] = _mm256_extract_epi8(b.values, 12); + if (mask & 0x2000) + tmp_values[13] = _mm256_extract_epi8(b.values, 13); + if (mask & 0x4000) + tmp_values[14] = _mm256_extract_epi8(b.values, 14); + if (mask & 0x8000) + tmp_values[15] = _mm256_extract_epi8(b.values, 15); + if (mask & 0x010000) + tmp_values[16] = _mm256_extract_epi8(b.values, 16); + if (mask & 0x020000) + tmp_values[17] = _mm256_extract_epi8(b.values, 17); + if (mask & 0x040000) + tmp_values[18] = _mm256_extract_epi8(b.values, 18); + if (mask & 0x080000) + tmp_values[19] = _mm256_extract_epi8(b.values, 19); + if (mask & 0x100000) + tmp_values[20] = _mm256_extract_epi8(b.values, 20); + if (mask & 0x200000) + tmp_values[21] = _mm256_extract_epi8(b.values, 21); + if (mask & 0x400000) + tmp_values[22] = _mm256_extract_epi8(b.values, 22); + if (mask & 0x800000) + tmp_values[23] = _mm256_extract_epi8(b.values, 23); + if (mask & 0x1000000) + tmp_values[24] = _mm256_extract_epi8(b.values, 24); + if (mask & 0x2000000) + tmp_values[25] = _mm256_extract_epi8(b.values, 25); + if (mask & 0x4000000) + tmp_values[26] = _mm256_extract_epi8(b.values, 26); + if (mask & 0x8000000) + tmp_values[27] = _mm256_extract_epi8(b.values, 27); + if (mask & 0x10000000) + tmp_values[28] = _mm256_extract_epi8(b.values, 28); + if (mask & 0x20000000) + tmp_values[29] = _mm256_extract_epi8(b.values, 29); + if (mask & 0x40000000) + tmp_values[30] = _mm256_extract_epi8(b.values, 30); + if (mask & 0x80000000) + tmp_values[31] = _mm256_extract_epi8(b.values, 31); + return loadu(tmp_values); + } + static Vectorized blendv(const Vectorized& a, const Vectorized& b, + const Vectorized& mask) { + return _mm256_blendv_epi8(a.values, b.values, mask.values); + } + template + static Vectorized arange(T base = 0, step_t step = static_cast(1)) { + return Vectorized( + base, base + step, base + 2 * step, base + 3 * step, + base + 4 * step, base + 5 * step, base + 6 * step, base + 7 * step, + base + 8 * step, base + 9 * step, base + 10 * step, base + 11 * step, + base + 12 * step, base + 13 * step, base + 14 * step, base + 15 * step, + base + 16 * step, base + 17 * step, base + 18 * step, base + 19 * step, + base + 20 * step, base + 21 * step, base + 22 * step, base + 23 * step, + base + 24 * step, base + 25 * step, base + 26 * step, base + 27 * step, + base + 28 * step, base + 29 * step, base + 30 * step, base + 31 * step); + } + static Vectorized + set(Vectorized a, Vectorized b, T count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<0x1>(a, b); + case 2: + return blend<0x3>(a, b); + case 3: + return blend<0x7>(a, b); + case 4: + return blend<0xF>(a, b); + case 5: + return blend<0x1F>(a, b); + case 6: + return blend<0x3F>(a, b); + case 7: + return blend<0x7F>(a, b); + case 8: + return blend<0xFF>(a, b); + case 9: + return blend<0x1FF>(a, b); + case 10: + return blend<0x3FF>(a, b); + case 11: + return blend<0x7FF>(a, b); + case 12: + return blend<0xFFF>(a, b); + case 13: + return blend<0x1FFF>(a, b); + case 14: + return blend<0x3FFF>(a, b); + case 15: + return blend<0x7FFF>(a, b); + case 16: + return blend<0xFFFF>(a, b); + case 17: + return blend<0x1FFFF>(a, b); + case 18: + return blend<0x3FFFF>(a, b); + case 19: + return blend<0x7FFFF>(a, b); + case 20: + return blend<0xFFFFF>(a, b); + case 21: + return blend<0x1FFFFF>(a, b); + case 22: + return blend<0x3FFFFF>(a, b); + case 23: + return blend<0x7FFFFF>(a, b); + case 24: + return blend<0xFFFFFF>(a, b); + case 25: + return blend<0x1FFFFFF>(a, b); + case 26: + return blend<0x3FFFFFF>(a, b); + case 27: + return blend<0x7FFFFFF>(a, b); + case 28: + return blend<0xFFFFFFF>(a, b); + case 29: + return blend<0x1FFFFFFF>(a, b); + case 30: + return blend<0x3FFFFFFF>(a, b); + case 31: + return blend<0x7FFFFFFF>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm256_loadu_si256(reinterpret_cast(ptr)); + } + static Vectorized loadu_one_fourth(const void* ptr) { + // Fast path if only load element number of 8. + // Note: We didn't merge it as fast path of loadu(const void* ptr, T count), + // Because loadu(const void* ptr, T count) requires zero initialization for upper 128 bits. + // However, by using _mm256_castsi128_si256, the upper 128 bits of the result are undefined. + // TODO We can use _mm256_zextsi128_si256 in the furture, + // since gcc 9.3 doesn't support it now. + __m128i input_128 = _mm_loadl_epi64(reinterpret_cast(ptr)); + return _mm256_castsi128_si256(input_128); + } + static Vectorized loadu(const void* ptr, T count) { + __at_align__ T tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, ptr, count * sizeof(T)); + return loadu(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm256-storeu-si256.html + _mm256_storeu_si256(reinterpret_cast<__m256i*>(ptr), values); + } else if (count > 0) { + if (count == 8) { + // Fast path if only store element number of 8 + _mm_storel_epi64(reinterpret_cast<__m128i*>(ptr), _mm256_castsi256_si128(values)); + } else { + __at_align__ T tmp_values[size()]; + _mm256_storeu_si256(reinterpret_cast<__m256i*>(tmp_values), values); + std::memcpy(ptr, tmp_values, count * sizeof(T)); + } + } + } + const T& operator[](int idx) const = delete; + T& operator[](int idx) = delete; + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm256_set1_epi8(0); + } + Vectorized conj() const { + return *this; + } +}; + +template<> +class Vectorized: public Vectorized8 { +public: + using Vectorized8::Vectorized8; + + Vectorized neg() const; + + Vectorized abs() const { + return _mm256_abs_epi8(values); + } + + Vectorized operator==(const Vectorized& other) const { + return _mm256_cmpeq_epi8(values, other.values); + } + Vectorized operator!=(const Vectorized& other) const { + return invert(_mm256_cmpeq_epi8(values, other.values)); + } + Vectorized operator<(const Vectorized& other) const { + return _mm256_cmpgt_epi8(other.values, values); + } + Vectorized operator<=(const Vectorized& other) const { + return invert(_mm256_cmpgt_epi8(values, other.values)); + } + Vectorized operator>(const Vectorized& other) const { + return other < *this; + } + Vectorized operator>=(const Vectorized& other) const { + return other <= *this; + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template<> +class Vectorized: public Vectorized8 { +public: + using Vectorized8::Vectorized8; + + Vectorized neg() const; + + Vectorized abs() const { + return *this; + } + + Vectorized operator==(const Vectorized& other) const { + return _mm256_cmpeq_epi8(values, other.values); + } + Vectorized operator!=(const Vectorized& other) const { + return invert(_mm256_cmpeq_epi8(values, other.values)); + } + Vectorized operator<(const Vectorized& other) const { + __m256i max = _mm256_max_epu8(values, other.values); + return invert(_mm256_cmpeq_epi8(max, values)); + } + Vectorized operator<=(const Vectorized& other) const { + __m256i max = _mm256_max_epu8(values, other.values); + return _mm256_cmpeq_epi8(max, other.values); + } + Vectorized operator>(const Vectorized& other) const { + return other < *this; + } + Vectorized operator>=(const Vectorized& other) const { + return other <= *this; + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return _mm256_add_epi64(a, b); +} + +template <> +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return _mm256_add_epi32(a, b); +} + +template <> +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return _mm256_add_epi16(a, b); +} + +template <> +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return _mm256_add_epi8(a, b); +} + +template <> +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return _mm256_add_epi8(a, b); +} + +template <> +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return _mm256_sub_epi64(a, b); +} + +template <> +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return _mm256_sub_epi32(a, b); +} + +template <> +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return _mm256_sub_epi16(a, b); +} + +template <> +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return _mm256_sub_epi8(a, b); +} + +template <> +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return _mm256_sub_epi8(a, b); +} + +// Negation. Defined here so we can utilize operator- +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +// Emulate operations with no native 64-bit support in avx, +// by extracting each element, performing the operation pointwise, +// then combining the results into a vector. +template +Vectorized inline emulate(const Vectorized& a, const Vectorized& b, const op_t& op) { + int64_t a0 = _mm256_extract_epi64(a, 0); + int64_t a1 = _mm256_extract_epi64(a, 1); + int64_t a2 = _mm256_extract_epi64(a, 2); + int64_t a3 = _mm256_extract_epi64(a, 3); + + int64_t b0 = _mm256_extract_epi64(b, 0); + int64_t b1 = _mm256_extract_epi64(b, 1); + int64_t b2 = _mm256_extract_epi64(b, 2); + int64_t b3 = _mm256_extract_epi64(b, 3); + + int64_t c0 = op(a0, b0); + int64_t c1 = op(a1, b1); + int64_t c2 = op(a2, b2); + int64_t c3 = op(a3, b3); + + return _mm256_set_epi64x(c3, c2, c1, c0); +} + +template +Vectorized inline emulate(const Vectorized& a, const Vectorized& b, const Vectorized& c, const op_t& op) { + int64_t a0 = _mm256_extract_epi64(a, 0); + int64_t a1 = _mm256_extract_epi64(a, 1); + int64_t a2 = _mm256_extract_epi64(a, 2); + int64_t a3 = _mm256_extract_epi64(a, 3); + + int64_t b0 = _mm256_extract_epi64(b, 0); + int64_t b1 = _mm256_extract_epi64(b, 1); + int64_t b2 = _mm256_extract_epi64(b, 2); + int64_t b3 = _mm256_extract_epi64(b, 3); + + int64_t c0 = _mm256_extract_epi64(c, 0); + int64_t c1 = _mm256_extract_epi64(c, 1); + int64_t c2 = _mm256_extract_epi64(c, 2); + int64_t c3 = _mm256_extract_epi64(c, 3); + + int64_t d0 = op(a0, b0, c0); + int64_t d1 = op(a1, b1, c1); + int64_t d2 = op(a2, b2, c2); + int64_t d3 = op(a3, b3, c3); + + return _mm256_set_epi64x(d3, d2, d1, d0); +} + +// AVX2 has no intrinsic for int64_t multiply so it needs to be emulated +// This could be implemented more efficiently using epi32 instructions +// This is also technically avx compatible, but then we'll need AVX +// code for add as well. +// Note: intentionally ignores undefined behavior like (-lowest * -1). +template <> +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + return emulate(a, b, [](int64_t a_point, int64_t b_point) __ubsan_ignore_undefined__ {return a_point * b_point;}); +} + +template <> +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + return _mm256_mullo_epi32(a, b); +} + +template <> +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + return _mm256_mullo_epi16(a, b); +} + +template +Vectorized inline int_elementwise_binary_256(const Vectorized& a, const Vectorized& b, Op op) { + T values_a[Vectorized::size()]; + T values_b[Vectorized::size()]; + a.store(values_a); + b.store(values_b); + for (int i = 0; i != Vectorized::size(); i++) { + values_a[i] = op(values_a[i], values_b[i]); + } + return Vectorized::loadu(values_a); +} + +template <> +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + // We don't have an instruction for multiplying int8_t +#ifndef CPU_CAPABILITY_AVX2 + return int_elementwise_binary_256(a, b, std::multiplies()); +#else + __m256i mask00FF = _mm256_set1_epi16(0x00FF); + __m256i a_lo = _mm256_srai_epi16(_mm256_slli_epi16(a, 8), 8); + __m256i b_lo = _mm256_srai_epi16(_mm256_slli_epi16(b, 8), 8); + __m256i a_hi = _mm256_srai_epi16(a, 8); + __m256i b_hi = _mm256_srai_epi16(b, 8); + __m256i res_lo = _mm256_and_si256(_mm256_mullo_epi16(a_lo, b_lo), mask00FF); + __m256i res_hi = _mm256_slli_epi16(_mm256_mullo_epi16(a_hi, b_hi), 8); + __m256i res = _mm256_or_si256(res_hi, res_lo); + return res; +#endif +} + +template <> +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + // We don't have an instruction for multiplying uint8_t +#ifndef CPU_CAPABILITY_AVX2 + return int_elementwise_binary_256(a, b, std::multiplies()); +#else + __m256i mask00FF = _mm256_set1_epi16(0x00FF); + __m256i a_lo = _mm256_and_si256 (a, mask00FF); + __m256i b_lo = _mm256_and_si256 (b, mask00FF); + __m256i a_hi = _mm256_srli_epi16(a, 8); + __m256i b_hi = _mm256_srli_epi16(b, 8); + __m256i res_lo = _mm256_and_si256(_mm256_mullo_epi16(a_lo, b_lo), mask00FF); + __m256i res_hi = _mm256_slli_epi16(_mm256_mullo_epi16(a_hi, b_hi), 8); + __m256i res = _mm256_or_si256(res_hi, res_lo); + return res; +#endif +} + +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { +#ifndef CPU_CAPABILITY_AVX2 + return emulate(a, b, [](int64_t a_point, int64_t b_point) {return std::min(a_point, b_point);}); +#else + __m256i cmp = _mm256_cmpgt_epi64(a, b); + return _mm256_blendv_epi8(a, b, cmp); +#endif +} + +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + return _mm256_min_epi32(a, b); +} + +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + return _mm256_min_epi16(a, b); +} + +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + return _mm256_min_epi8(a, b); +} + +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + return _mm256_min_epu8(a, b); +} + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { +#ifndef CPU_CAPABILITY_AVX2 + return emulate(a, b, [](int64_t a_point, int64_t b_point) {return std::max(a_point, b_point);}); +#else + __m256i cmp = _mm256_cmpgt_epi64(a, b); + return _mm256_blendv_epi8(b, a, cmp); +#endif +} + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return _mm256_max_epi32(a, b); +} + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return _mm256_max_epi16(a, b); +} + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return _mm256_max_epi8(a, b); +} + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return _mm256_max_epu8(a, b); +} + +template <> +Vectorized inline clamp(const Vectorized& a, const Vectorized& min_val, const Vectorized& max_val) { +#ifndef CPU_CAPABILITY_AVX2 + return emulate(a, min_val, max_val, [](int64_t a_point, int64_t min_point, int64_t max_point) {return std::min(max_point, std::max(a_point, min_point));}); +#else + return minimum(maximum(a, min_val), max_val); +#endif +} + +template <> +Vectorized inline clamp(const Vectorized& a, const Vectorized& min_val, const Vectorized& max_val) { + return _mm256_min_epi32(max_val, _mm256_max_epi32(a, min_val)); +} + +template <> +Vectorized inline clamp(const Vectorized& a, const Vectorized& min_val, const Vectorized& max_val) { + return _mm256_min_epi16(max_val, _mm256_max_epi16(a, min_val)); +} + +template <> +Vectorized inline clamp(const Vectorized& a, const Vectorized& min_val, const Vectorized& max_val) { + return _mm256_min_epi8(max_val, _mm256_max_epi8(a, min_val)); +} + +template <> +Vectorized inline clamp(const Vectorized& a, const Vectorized& min_val, const Vectorized& max_val) { + return _mm256_min_epu8(max_val, _mm256_max_epu8(a, min_val)); +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max_val) { +#ifndef CPU_CAPABILITY_AVX2 + return emulate(a, max_val, [](int64_t a_point, int64_t max_point) {return std::min(max_point, a_point);}); +#else + return minimum(max_val, a); +#endif +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max_val) { + return _mm256_min_epi32(max_val, a); +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max_val) { + return _mm256_min_epi16(max_val, a); +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max_val) { + return _mm256_min_epi8(max_val, a); +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max_val) { + return _mm256_min_epu8(max_val, a); +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min_val) { +#ifndef CPU_CAPABILITY_AVX2 + return emulate(a, min_val, [](int64_t a_point, int64_t min_point) {return std::max(min_point, a_point);}); +#else + return maximum(min_val, a); +#endif +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min_val) { + return _mm256_max_epi32(min_val, a); +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min_val) { + return _mm256_max_epi16(min_val, a); +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min_val) { + return _mm256_max_epi8(min_val, a); +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min_val) { + return _mm256_max_epu8(min_val, a); +} + +template +Vectorized inline convert_to_int32(const T* ptr) { + return Vectorized::loadu(ptr); +} + +template<> +Vectorized inline convert_to_int32(const int8_t* ptr) { + return _mm256_cvtepi8_epi32(_mm_loadl_epi64(reinterpret_cast(ptr))); +} + +template<> +Vectorized inline convert_to_int32(const uint8_t* ptr) { + return _mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cast(ptr))); +} + +template <> +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return int_elementwise_binary_256(a, b, std::divides()); +} +template <> +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return int_elementwise_binary_256(a, b, std::divides()); +} +template <> +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return int_elementwise_binary_256(a, b, std::divides()); +} +template <> +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return int_elementwise_binary_256(a, b, std::divides()); +} +template <> +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return int_elementwise_binary_256(a, b, std::divides()); +} + +template>::value, int> = 0> +inline Vectorized operator&(const Vectorized& a, const Vectorized& b) { + return _mm256_and_si256(a, b); +} +template>::value, int> = 0> +inline Vectorized operator|(const Vectorized& a, const Vectorized& b) { + return _mm256_or_si256(a, b); +} +template>::value, int> = 0> +inline Vectorized operator^(const Vectorized& a, const Vectorized& b) { + return _mm256_xor_si256(a, b); +} +template>::value, int> = 0> +inline Vectorized operator~(const Vectorized& a) { + return _mm256_xor_si256(a, _mm256_set1_epi32(-1)); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +template +Vectorized inline shift_256_16(const Vectorized& a, const Vectorized& b) { + // No vector instruction for shifting int16_t, so emulating it instead. + + // Control masks for shuffle operation, treating 256 bits as an + // array of 16-bit elements, and considering pairs of neighboring + // elements. Specifially, a mask named "ctl_M_N" (M,N in [0,1], and + // M!=N) is set so that shuffle will move element with index M from + // input pair into element with index N in output pair, and element + // with index M in output pair will be set to all 0s. + __m256i ctl_0_1 = _mm256_set_epi8(29, 28, 0x80, 0x80, 25, 24, 0x80, 0x80, + 21, 20, 0x80, 0x80, 17, 16, 0x80, 0x80, + 13, 12, 0x80, 0x80, 9, 8, 0x80, 0x80, + 5, 4, 0x80, 0x80, 1, 0, 0x80, 0x80); + __m256i ctl_1_0 = _mm256_set_epi8(0x80, 0x80, 31, 30, 0x80, 0x80, 27, 26, + 0x80, 0x80, 23, 22, 0x80, 0x80, 19, 18, + 0x80, 0x80, 15, 14, 0x80, 0x80, 11, 10, + 0x80, 0x80, 7, 6, 0x80, 0x80, 3, 2); + + // Masks for bitwise and operation, treating 256 bits as an array of + // 16-bit elements, and considering them in pairs of neighboring + // elements. A mask named "keep_M" (M in [0,1]) is set so that + // bitwise and will copy element with index M from input pair into + // element with the same index in output pair, while the other + // element in output pair will be set to all 0s. + __m256i keep_0 = _mm256_set1_epi32(0xFFFF); + __m256i keep_1 = _mm256_set1_epi32(0xFFFF0000); + + // Take each 16-bit element with idx%2==0 from input array to be + // shifted and extend it to 32 bits so that 0s are added to the + // right. Then, perform shifting on this 32-bit number. Upper 16 + // bits will be proper result of shifting original 16-bit number, so + // write them to result array, into the same position from which + // corresponding input element is taken. Also, make sure that + // result array elements with idx%2!=0 are set to all 0s. + // + // Note that number of bits to shift for is extended to 32 bits by + // adding 0s to the left. That means this number is not properly + // sign-extended for negative values. However, number of bits to + // shift is treated as an unsigned integer by respective shift + // intrinsics anyway so if negative then either with or without + // proper sign extension, it will be interpreted as a number greater + // than 32, and the shifting result will be the same. + __m256i a0 = _mm256_shuffle_epi8(a, ctl_0_1); + __m256i b0 = _mm256_and_si256(b, keep_0); + __m256i c0; + if (left_shift) + c0 = _mm256_sllv_epi32(a0, b0); + else + c0 = _mm256_srav_epi32(a0, b0); + c0 = _mm256_shuffle_epi8(c0, ctl_1_0); + + // Peform shifting the same way for input array elements with + // idx%2==1. + __m256i a1 = _mm256_and_si256(a, keep_1); + __m256i b1 = _mm256_shuffle_epi8(b, ctl_1_0); + __m256i c1; + if (left_shift) + c1 = _mm256_sllv_epi32(a1, b1); + else + c1 = _mm256_srav_epi32(a1, b1); + c1 = _mm256_and_si256(c1, keep_1); + + // Merge partial results into the final result. + __m256i c = _mm256_or_si256(c0, c1); + + return c; +} + +template ::value || std::is_same::value, int> = 0> +Vectorized inline shift_256_8(const Vectorized& a, const Vectorized& b) { + // No vector instruction for shifting int8_t/uint8_t, so emulating + // it instead. + + // Control masks for shuffle operation, treating 256 bits as an + // array of 8-bit elements, and considering quadruples of + // neighboring elements. Specifially, a mask named "ctl_M_N" (M,N + // in [0,1,2,3], and M!=N) is set so that shuffle will move element + // with index M from input quadruple into element with index N in + // output quadruple, and other elements in output quadruple will be + // set to all 0s. + __m256i ctl_0_3 = _mm256_set_epi8(28, 0x80, 0x80, 0x80, 24, 0x80, 0x80, 0x80, + 20, 0x80, 0x80, 0x80, 16, 0x80, 0x80, 0x80, + 12, 0x80, 0x80, 0x80, 8, 0x80, 0x80, 0x80, + 4, 0x80, 0x80, 0x80, 0, 0x80, 0x80, 0x80); + __m256i ctl_1_0 = _mm256_set_epi8(0x80, 0x80, 0x80, 29, 0x80, 0x80, 0x80, 25, + 0x80, 0x80, 0x80, 21, 0x80, 0x80, 0x80, 17, + 0x80, 0x80, 0x80, 13, 0x80, 0x80, 0x80, 9, + 0x80, 0x80, 0x80, 5, 0x80, 0x80, 0x80, 1); + __m256i ctl_1_3 = _mm256_set_epi8(29, 0x80, 0x80, 0x80, 25, 0x80, 0x80, 0x80, + 21, 0x80, 0x80, 0x80, 17, 0x80, 0x80, 0x80, + 13, 0x80, 0x80, 0x80, 9, 0x80, 0x80, 0x80, + 5, 0x80, 0x80, 0x80, 1, 0x80, 0x80, 0x80); + __m256i ctl_2_0 = _mm256_set_epi8(0x80, 0x80, 0x80, 30, 0x80, 0x80, 0x80, 26, + 0x80, 0x80, 0x80, 22, 0x80, 0x80, 0x80, 18, + 0x80, 0x80, 0x80, 14, 0x80, 0x80, 0x80, 10, + 0x80, 0x80, 0x80, 6, 0x80, 0x80, 0x80, 2); + __m256i ctl_2_3 = _mm256_set_epi8(30, 0x80, 0x80, 0x80, 26, 0x80, 0x80, 0x80, + 22, 0x80, 0x80, 0x80, 18, 0x80, 0x80, 0x80, + 14, 0x80, 0x80, 0x80, 10, 0x80, 0x80, 0x80, + 6, 0x80, 0x80, 0x80, 2, 0x80, 0x80, 0x80); + __m256i ctl_3_0 = _mm256_set_epi8(0x80, 0x80, 0x80, 31, 0x80, 0x80, 0x80, 27, + 0x80, 0x80, 0x80, 23, 0x80, 0x80, 0x80, 19, + 0x80, 0x80, 0x80, 15, 0x80, 0x80, 0x80, 11, + 0x80, 0x80, 0x80, 7, 0x80, 0x80, 0x80, 3); + __m256i ctl_3_1 = _mm256_set_epi8(0x80, 0x80, 31, 0x80, 0x80, 0x80, 27, 0x80, + 0x80, 0x80, 23, 0x80, 0x80, 0x80, 19, 0x80, + 0x80, 0x80, 15, 0x80, 0x80, 0x80, 11, 0x80, + 0x80, 0x80, 7, 0x80, 0x80, 0x80, 3, 0x80); + __m256i ctl_3_2 = _mm256_set_epi8(0x80, 31, 0x80, 0x80, 0x80, 27, 0x80, 0x80, + 0x80, 23, 0x80, 0x80, 0x80, 19, 0x80, 0x80, + 0x80, 15, 0x80, 0x80, 0x80, 11, 0x80, 0x80, + 0x80, 7, 0x80, 0x80, 0x80, 3, 0x80, 0x80); + + // Masks for bitwise and operation, treating 256 bits as an array of + // 8-bit elements, and considering them in quadruples of neighboring + // elements. A mask named "keep_M" (M in [0,1,2,3]) is set so that + // bitwise and will copy element with index M from input quadruple + // into element with the same index in output quadruple, while the + // other elements in output quadruple will be set to all 0s. + __m256i keep_0 = _mm256_set1_epi32(0xFF); + __m256i keep_3 = _mm256_set1_epi32(0xFF000000); + + // Take each 8-bit element with idx%4==0 from input array to be + // shifted and extend it to 32 bits so that 0s are added to the + // right. Then, perform shifting on this 32-bit number. Upper 8 + // bits will be proper result of shifting original 8-bit number, so + // write them to result array, into the same position from which + // corresponding input element is taken. Also, make sure that + // result array elements with idx%4!=0 are set to all 0s. + // + // Note that number of bits to shift for is extended to 32 bits by + // adding 0s to the left. That means this number is not properly + // sign-extended for negative values. However, number of bits to + // shift is treated as an unsigned integer by respective shift + // intrinsics anyway so if negative then either with or without + // proper sign extension, it will be interpreted as a number greater + // than 32, and the shifting result will be the same. + __m256i a0 = _mm256_shuffle_epi8(a, ctl_0_3); + __m256i b0 = _mm256_and_si256(b, keep_0); + __m256i c0; + if (left_shift) + c0 = _mm256_sllv_epi32(a0, b0); + else + if constexpr (std::is_same_v) + c0 = _mm256_srav_epi32(a0, b0); + else + c0 = _mm256_srlv_epi32(a0, b0); + c0 = _mm256_shuffle_epi8(c0, ctl_3_0); + + // Peform shifting the same way for input array elements with + // idx%4==1. + __m256i a1 = _mm256_shuffle_epi8(a, ctl_1_3); + __m256i b1 = _mm256_shuffle_epi8(b, ctl_1_0); + __m256i c1; + if (left_shift) + c1 = _mm256_sllv_epi32(a1, b1); + else + if constexpr (std::is_same_v) + c1 = _mm256_srav_epi32(a1, b1); + else + c1 = _mm256_srlv_epi32(a1, b1); + c1 = _mm256_shuffle_epi8(c1, ctl_3_1); + + // Peform shifting the same way for input array elements with + // idx%4==2. + __m256i a2 = _mm256_shuffle_epi8(a, ctl_2_3); + __m256i b2 = _mm256_shuffle_epi8(b, ctl_2_0); + __m256i c2; + if (left_shift) + c2 = _mm256_sllv_epi32(a2, b2); + else + if constexpr (std::is_same_v) + c2 = _mm256_srav_epi32(a2, b2); + else + c2 = _mm256_srlv_epi32(a2, b2); + c2 = _mm256_shuffle_epi8(c2, ctl_3_2); + + // Peform shifting the same way for input array elements with + // idx%4==3. + __m256i a3 = _mm256_and_si256(a, keep_3); + __m256i b3 = _mm256_shuffle_epi8(b, ctl_3_0); + __m256i c3; + if (left_shift) + c3 = _mm256_sllv_epi32(a3, b3); + else + if constexpr (std::is_same_v) + c3 = _mm256_srav_epi32(a3, b3); + else + c3 = _mm256_srlv_epi32(a3, b3); + c3 = _mm256_and_si256(c3, keep_3); + + // Merge partial results into the final result. + __m256i c01 = _mm256_or_si256(c0, c1); + __m256i c23 = _mm256_or_si256(c2, c3); + __m256i c = _mm256_or_si256(c01, c23); + + return c; +} + +template <> +Vectorized inline operator<<(const Vectorized& a, const Vectorized& b) { + return _mm256_sllv_epi64(a, b); +} + +template <> +Vectorized inline operator<<(const Vectorized& a, const Vectorized& b) { + return _mm256_sllv_epi32(a, b); +} + +template <> +Vectorized inline operator<<(const Vectorized& a, const Vectorized& b) { + return shift_256_16(a, b); +} + +template <> +Vectorized inline operator<<(const Vectorized& a, const Vectorized& b) { + return shift_256_8(a, b); +} + +template <> +Vectorized inline operator<<(const Vectorized& a, const Vectorized& b) { + return shift_256_8(a, b); +} + +template <> +Vectorized inline operator>>(const Vectorized& a, const Vectorized& b) { + // No vector instruction for right arithmetic shifting int64_t, so emulating it + // instead. + + // Clamp the shift values such that shift values < 0 and > 64 are changed to 64 + // which results in -1 for negative input and 0 for non-negative input. + __m256i zero = _mm256_set1_epi64x(0); + __m256i max_shift = _mm256_set1_epi64x(64); + __m256i mask = _mm256_or_si256(_mm256_cmpgt_epi64(zero, b), _mm256_cmpgt_epi64(b, max_shift)); + __m256i shift = _mm256_blendv_epi8(b, max_shift, mask); + // Shift the number logically to the right, thus filling the most + // significant bits with 0s. Then, replace these bits with the sign + // bit. + __m256i sign_bits = _mm256_cmpgt_epi64(zero, a); + __m256i sign_shift = _mm256_sub_epi64(max_shift, shift); + __m256i sign_ext = _mm256_sllv_epi64(sign_bits, sign_shift); + __m256i c = _mm256_srlv_epi64(a, shift); + c = _mm256_or_si256(c, sign_ext); + + return c; +} + +template <> +Vectorized inline operator>>(const Vectorized& a, const Vectorized& b) { + return _mm256_srav_epi32(a, b); +} + +template <> +Vectorized inline operator>>(const Vectorized& a, const Vectorized& b) { + return shift_256_16(a, b); +} + +template <> +Vectorized inline operator>>(const Vectorized& a, const Vectorized& b) { + return shift_256_8(a, b); +} + +template <> +Vectorized inline operator>>(const Vectorized& a, const Vectorized& b) { + return shift_256_8(a, b); +} + +#endif + +}} // namespace at::vec::CPU_CAPABILITY diff --git a/shared/package-files/77/77d345b3281c286b69fa9c3e6693af231321a6c46a775b8f05596a7a31e43665/blob b/shared/package-files/77/77d345b3281c286b69fa9c3e6693af231321a6c46a775b8f05596a7a31e43665/blob new file mode 100644 index 0000000000000000000000000000000000000000..6d05dc79fbb2cf52688547b672365802463ce6f2 --- /dev/null +++ b/shared/package-files/77/77d345b3281c286b69fa9c3e6693af231321a6c46a775b8f05596a7a31e43665/blob @@ -0,0 +1,27 @@ +import numpy as np + +from pandas._libs.tslibs.dtypes import abbrev_to_npy_unit +from pandas._libs.tslibs.vectorized import is_date_array_normalized + +# a datetime64 ndarray which *is* normalized +day_arr = np.arange(10, dtype="i8").view("M8[D]") + + +class TestIsDateArrayNormalized: + def test_is_date_array_normalized_day(self): + arr = day_arr + abbrev = "D" + unit = abbrev_to_npy_unit(abbrev) + result = is_date_array_normalized(arr.view("i8"), None, unit) + assert result is True + + def test_is_date_array_normalized_seconds(self): + abbrev = "s" + arr = day_arr.astype(f"M8[{abbrev}]") + unit = abbrev_to_npy_unit(abbrev) + result = is_date_array_normalized(arr.view("i8"), None, unit) + assert result is True + + arr[0] += np.timedelta64(1, abbrev) + result2 = is_date_array_normalized(arr.view("i8"), None, unit) + assert result2 is False diff --git a/shared/package-files/77/77d533b6a834ba8c4e8f40590949ab2aff566012369e0662ee3d1f83a6b31625/blob b/shared/package-files/77/77d533b6a834ba8c4e8f40590949ab2aff566012369e0662ee3d1f83a6b31625/blob new file mode 100644 index 0000000000000000000000000000000000000000..d71cead30026011843335a53e342f8f736e1098b Binary files /dev/null and b/shared/package-files/77/77d533b6a834ba8c4e8f40590949ab2aff566012369e0662ee3d1f83a6b31625/blob differ diff --git a/shared/package-files/77/77d92cad39c94bce78f4eab9d221b4f2ee69121b8c6e1437a126144aad2dc0d4/blob b/shared/package-files/77/77d92cad39c94bce78f4eab9d221b4f2ee69121b8c6e1437a126144aad2dc0d4/blob new file mode 100644 index 0000000000000000000000000000000000000000..faf604c21d3cbeb8fabe14e64d4f94ec1bfd6a94 --- /dev/null +++ b/shared/package-files/77/77d92cad39c94bce78f4eab9d221b4f2ee69121b8c6e1437a126144aad2dc0d4/blob @@ -0,0 +1,294 @@ +############################################################################### +# Reusable ProcessPoolExecutor +# +# author: Thomas Moreau and Olivier Grisel +# +import time +import warnings +import threading +import multiprocessing as mp + +from .process_executor import ProcessPoolExecutor, EXTRA_QUEUED_CALLS +from .backend.context import cpu_count +from .backend import get_context + +__all__ = ["get_reusable_executor"] + +# Singleton executor and id management +_executor_lock = threading.RLock() +_next_executor_id = 0 +_executor = None +_executor_kwargs = None + + +def _get_next_executor_id(): + """Ensure that each successive executor instance has a unique, monotonic id. + + The purpose of this monotonic id is to help debug and test automated + instance creation. + """ + global _next_executor_id + with _executor_lock: + executor_id = _next_executor_id + _next_executor_id += 1 + return executor_id + + +def get_reusable_executor( + max_workers=None, + context=None, + timeout=10, + kill_workers=False, + reuse="auto", + job_reducers=None, + result_reducers=None, + initializer=None, + initargs=(), + env=None, +): + """Return the current ReusableExectutor instance. + + Start a new instance if it has not been started already or if the previous + instance was left in a broken state. + + If the previous instance does not have the requested number of workers, the + executor is dynamically resized to adjust the number of workers prior to + returning. + + Reusing a singleton instance spares the overhead of starting new worker + processes and importing common python packages each time. + + ``max_workers`` controls the maximum number of tasks that can be running in + parallel in worker processes. By default this is set to the number of + CPUs on the host. + + Setting ``timeout`` (in seconds) makes idle workers automatically shutdown + so as to release system resources. New workers are respawn upon submission + of new tasks so that ``max_workers`` are available to accept the newly + submitted tasks. Setting ``timeout`` to around 100 times the time required + to spawn new processes and import packages in them (on the order of 100ms) + ensures that the overhead of spawning workers is negligible. + + Setting ``kill_workers=True`` makes it possible to forcibly interrupt + previously spawned jobs to get a new instance of the reusable executor + with new constructor argument values. + + The ``job_reducers`` and ``result_reducers`` are used to customize the + pickling of tasks and results send to the executor. + + When provided, the ``initializer`` is run first in newly spawned + processes with argument ``initargs``. + + The environment variable in the child process are a copy of the values in + the main process. One can provide a dict ``{ENV: VAL}`` where ``ENV`` and + ``VAL`` are string literals to overwrite the environment variable ``ENV`` + in the child processes to value ``VAL``. The environment variables are set + in the children before any module is loaded. This only works with the + ``loky`` context. + """ + _executor, _ = _ReusablePoolExecutor.get_reusable_executor( + max_workers=max_workers, + context=context, + timeout=timeout, + kill_workers=kill_workers, + reuse=reuse, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, + initargs=initargs, + env=env, + ) + return _executor + + +class _ReusablePoolExecutor(ProcessPoolExecutor): + def __init__( + self, + submit_resize_lock, + max_workers=None, + context=None, + timeout=None, + executor_id=0, + job_reducers=None, + result_reducers=None, + initializer=None, + initargs=(), + env=None, + ): + super().__init__( + max_workers=max_workers, + context=context, + timeout=timeout, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, + initargs=initargs, + env=env, + ) + self.executor_id = executor_id + self._submit_resize_lock = submit_resize_lock + + @classmethod + def get_reusable_executor( + cls, + max_workers=None, + context=None, + timeout=10, + kill_workers=False, + reuse="auto", + job_reducers=None, + result_reducers=None, + initializer=None, + initargs=(), + env=None, + ): + with _executor_lock: + global _executor, _executor_kwargs + executor = _executor + + if max_workers is None: + if reuse is True and executor is not None: + max_workers = executor._max_workers + else: + max_workers = cpu_count() + elif max_workers <= 0: + raise ValueError( + f"max_workers must be greater than 0, got {max_workers}." + ) + + if isinstance(context, str): + context = get_context(context) + if context is not None and context.get_start_method() == "fork": + raise ValueError( + "Cannot use reusable executor with the 'fork' context" + ) + + kwargs = dict( + context=context, + timeout=timeout, + job_reducers=job_reducers, + result_reducers=result_reducers, + initializer=initializer, + initargs=initargs, + env=env, + ) + if executor is None: + is_reused = False + mp.util.debug( + f"Create a executor with max_workers={max_workers}." + ) + executor_id = _get_next_executor_id() + _executor_kwargs = kwargs + _executor = executor = cls( + _executor_lock, + max_workers=max_workers, + executor_id=executor_id, + **kwargs, + ) + else: + if reuse == "auto": + reuse = kwargs == _executor_kwargs + if ( + executor._flags.broken + or executor._flags.shutdown + or not reuse + or executor.queue_size < max_workers + ): + if executor._flags.broken: + reason = "broken" + elif executor._flags.shutdown: + reason = "shutdown" + elif executor.queue_size < max_workers: + # Do not reuse the executor if the queue size is too + # small as this would lead to limited parallelism. + reason = "queue size is too small" + else: + reason = "arguments have changed" + mp.util.debug( + "Creating a new executor with max_workers=" + f"{max_workers} as the previous instance cannot be " + f"reused ({reason})." + ) + executor.shutdown(wait=True, kill_workers=kill_workers) + _executor = executor = _executor_kwargs = None + # Recursive call to build a new instance + return cls.get_reusable_executor( + max_workers=max_workers, **kwargs + ) + else: + mp.util.debug( + "Reusing existing executor with " + f"max_workers={executor._max_workers}." + ) + is_reused = True + executor._resize(max_workers) + + return executor, is_reused + + def submit(self, fn, *args, **kwargs): + with self._submit_resize_lock: + return super().submit(fn, *args, **kwargs) + + def _resize(self, max_workers): + with self._submit_resize_lock: + if max_workers is None: + raise ValueError("Trying to resize with max_workers=None") + elif max_workers == self._max_workers: + return + + if self._executor_manager_thread is None: + # If the executor_manager_thread has not been started + # then no processes have been spawned and we can just + # update _max_workers and return + self._max_workers = max_workers + return + + self._wait_job_completion() + + # Some process might have returned due to timeout so check how many + # children are still alive. Use the _process_management_lock to + # ensure that no process are spawned or timeout during the resize. + with self._processes_management_lock: + processes = list(self._processes.values()) + nb_children_alive = sum(p.is_alive() for p in processes) + self._max_workers = max_workers + for _ in range(max_workers, nb_children_alive): + self._call_queue.put(None) + while ( + len(self._processes) > max_workers and not self._flags.broken + ): + time.sleep(1e-3) + + self._adjust_process_count() + processes = list(self._processes.values()) + while not all(p.is_alive() for p in processes): + time.sleep(1e-3) + + def _wait_job_completion(self): + """Wait for the cache to be empty before resizing the pool.""" + # Issue a warning to the user about the bad effect of this usage. + if self._pending_work_items: + warnings.warn( + "Trying to resize an executor with running jobs: " + "waiting for jobs completion before resizing.", + UserWarning, + ) + mp.util.debug( + f"Executor {self.executor_id} waiting for jobs completion " + "before resizing" + ) + # Wait for the completion of the jobs + while self._pending_work_items: + time.sleep(1e-3) + + def _setup_queues(self, job_reducers, result_reducers): + # As this executor can be resized, use a large queue size to avoid + # underestimating capacity and introducing overhead + # Also handle the case where the user set max_workers to a value larger + # than cpu_count(), to avoid limiting the number of parallel jobs. + + min_queue_size = max(cpu_count(), self._max_workers) + self.queue_size = 2 * min_queue_size + EXTRA_QUEUED_CALLS + super()._setup_queues( + job_reducers, result_reducers, queue_size=self.queue_size + ) diff --git a/shared/package-files/77/77db1404767d0b05312d4b7bfc54e9853b5b895a8d6e00750c20053db9521123/blob b/shared/package-files/77/77db1404767d0b05312d4b7bfc54e9853b5b895a8d6e00750c20053db9521123/blob new file mode 100644 index 0000000000000000000000000000000000000000..3d97041ea300c50beeb801edcd40188587e155fd --- /dev/null +++ b/shared/package-files/77/77db1404767d0b05312d4b7bfc54e9853b5b895a8d6e00750c20053db9521123/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor celu(const at::Tensor & self, const at::Scalar & alpha=1.0); +TORCH_API at::Tensor & celu_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & alpha=1.0); +TORCH_API at::Tensor & celu_outf(const at::Tensor & self, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & celu_(at::Tensor & self, const at::Scalar & alpha=1.0); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/77/77dc8bdfdbff5bbaa62830d21fab13e1b1348ff2ecd4cdcfd7ad4e1a076c9b88/blob b/shared/package-files/77/77dc8bdfdbff5bbaa62830d21fab13e1b1348ff2ecd4cdcfd7ad4e1a076c9b88/blob new file mode 100644 index 0000000000000000000000000000000000000000..b5ac1070294b478b7cc2ce677207ee08813bfa37 --- /dev/null +++ b/shared/package-files/77/77dc8bdfdbff5bbaa62830d21fab13e1b1348ff2ecd4cdcfd7ad4e1a076c9b88/blob @@ -0,0 +1,3 @@ +_distutils_hack +pkg_resources +setuptools diff --git a/shared/package-files/77/77de6f1fe0e9718ae35c5b09d3d4494277df05adddf50884c5b20c53866b39db/blob b/shared/package-files/77/77de6f1fe0e9718ae35c5b09d3d4494277df05adddf50884c5b20c53866b39db/blob new file mode 100644 index 0000000000000000000000000000000000000000..8a71485a6d4599d998247083bf6d076547eb6077 --- /dev/null +++ b/shared/package-files/77/77de6f1fe0e9718ae35c5b09d3d4494277df05adddf50884c5b20c53866b39db/blob @@ -0,0 +1,46 @@ +## Generate PCCF reference values via OLS regression +## +## The partial cross-correlation at lag h between x and y is defined as +## the Pearson correlation between the residuals from regressing x[t] +## and y[t+h] on all intervening observations {x[t+j], y[t+j]: j=1..h-1} +## plus intercept. At lag 1 there are no intervening observations, +## so pccf(1) = cor(x[1:(n-1)], y[2:n]). +## +## Data: macrodata realgdp and realcons from statsmodels. +## To export: python -c "from statsmodels.datasets import macrodata; \ +## macrodata.load_pandas().data.to_csv('macrodata.csv', index=False)" + +options(digits = 17, scipen = 999) + +macro <- read.csv("macrodata.csv") +x <- macro$realgdp +y <- macro$realcons +n <- length(x) +nlags <- 20 + +pccf_vals <- numeric(nlags) + +for (h in 1:nlags) { + if (h == 1) { + rx <- x[1:(n - 1)] + ry <- y[2:n] + } else { + idx <- 1:(n - h) + carriers <- matrix(1, nrow = length(idx), ncol = 1) + for (j in 1:(h - 1)) { + carriers <- cbind(carriers, x[idx + j], y[idx + j]) + } + targets_x <- x[idx] + targets_y <- y[idx + h] + fit_x <- lm.fit(carriers, targets_x) + fit_y <- lm.fit(carriers, targets_y) + rx <- fit_x$residuals + ry <- fit_y$residuals + } + pccf_vals[h] <- cor(rx, ry) +} + +out <- data.frame(pccf = pccf_vals) +write.csv(out, "results_pccf.csv", row.names = FALSE) +cat("PCCF values:\n") +print(pccf_vals) diff --git a/shared/package-files/77/77decd45c6c986aa6f5119f0ef3c86d133ae1228ca5ef534838a8e4d61dbc316/blob b/shared/package-files/77/77decd45c6c986aa6f5119f0ef3c86d133ae1228ca5ef534838a8e4d61dbc316/blob new file mode 100644 index 0000000000000000000000000000000000000000..d0eb7b1ad5c63995a995c8fe80f59fd8131538d1 --- /dev/null +++ b/shared/package-files/77/77decd45c6c986aa6f5119f0ef3c86d133ae1228ca5ef534838a8e4d61dbc316/blob @@ -0,0 +1,20 @@ +#if defined(DETECT_FEATURES) && defined(__INTEL_COMPILER) + /* + * Unlike GCC and CLANG, Intel Compiler exposes all supported intrinsics, + * whether or not the build options for those features are specified. + * Therefore, we must test #definitions of CPU features when option native/host + * is enabled via `--cpu-baseline` or through env var `CFLAGS` otherwise + * the test will be broken and leads to enable all possible features. + */ + #ifndef __AVX512F__ + #error "HOST/ARCH doesn't support AVX512F" + #endif +#endif + +#include + +int main(int argc, char **argv) +{ + __m512i a = _mm512_abs_epi32(_mm512_loadu_si512((const __m512i*)argv[argc-1])); + return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); +} diff --git a/shared/package-files/77/77deedaca7b86c0fa2d615d43a3c65a9174568b00157c6ef6e04155005f8cd9b/blob b/shared/package-files/77/77deedaca7b86c0fa2d615d43a3c65a9174568b00157c6ef6e04155005f8cd9b/blob new file mode 100644 index 0000000000000000000000000000000000000000..bd8a8fdc80f317078059ac54379861c1b706f26d --- /dev/null +++ b/shared/package-files/77/77deedaca7b86c0fa2d615d43a3c65a9174568b00157c6ef6e04155005f8cd9b/blob @@ -0,0 +1,230 @@ +"""Functions for computing eigenvector centrality.""" +import math + +import networkx as nx +from networkx.utils import not_implemented_for + +__all__ = ["eigenvector_centrality", "eigenvector_centrality_numpy"] + + +@nx._dispatch +@not_implemented_for("multigraph") +def eigenvector_centrality(G, max_iter=100, tol=1.0e-6, nstart=None, weight=None): + r"""Compute the eigenvector centrality for the graph `G`. + + Eigenvector centrality computes the centrality for a node based on the + centrality of its neighbors. The eigenvector centrality for node $i$ is + the $i$-th element of the vector $x$ defined by the equation + + .. math:: + + Ax = \lambda x + + where $A$ is the adjacency matrix of the graph `G` with eigenvalue + $\lambda$. By virtue of the Perron–Frobenius theorem, there is a unique + solution $x$, all of whose entries are positive, if $\lambda$ is the + largest eigenvalue of the adjacency matrix $A$ ([2]_). + + Parameters + ---------- + G : graph + A networkx graph + + max_iter : integer, optional (default=100) + Maximum number of iterations in power method. + + tol : float, optional (default=1.0e-6) + Error tolerance used to check convergence in power method iteration. + + nstart : dictionary, optional (default=None) + Starting value of eigenvector iteration for each node. + + weight : None or string, optional (default=None) + If None, all edge weights are considered equal. + Otherwise holds the name of the edge attribute used as weight. + In this measure the weight is interpreted as the connection strength. + + Returns + ------- + nodes : dictionary + Dictionary of nodes with eigenvector centrality as the value. + + Examples + -------- + >>> G = nx.path_graph(4) + >>> centrality = nx.eigenvector_centrality(G) + >>> sorted((v, f"{c:0.2f}") for v, c in centrality.items()) + [(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')] + + Raises + ------ + NetworkXPointlessConcept + If the graph `G` is the null graph. + + NetworkXError + If each value in `nstart` is zero. + + PowerIterationFailedConvergence + If the algorithm fails to converge to the specified tolerance + within the specified number of iterations of the power iteration + method. + + See Also + -------- + eigenvector_centrality_numpy + pagerank + hits + + Notes + ----- + The measure was introduced by [1]_ and is discussed in [2]_. + + The power iteration method is used to compute the eigenvector and + convergence is **not** guaranteed. Our method stops after ``max_iter`` + iterations or when the change in the computed vector between two + iterations is smaller than an error tolerance of + ``G.number_of_nodes() * tol``. This implementation uses ($A + I$) + rather than the adjacency matrix $A$ because it shifts the spectrum + to enable discerning the correct eigenvector even for networks with + multiple dominant eigenvalues. + + For directed graphs this is "left" eigenvector centrality which corresponds + to the in-edges in the graph. For out-edges eigenvector centrality + first reverse the graph with ``G.reverse()``. + + References + ---------- + .. [1] Phillip Bonacich. + "Power and Centrality: A Family of Measures." + *American Journal of Sociology* 92(5):1170–1182, 1986 + + .. [2] Mark E. J. Newman. + *Networks: An Introduction.* + Oxford University Press, USA, 2010, pp. 169. + + """ + if len(G) == 0: + raise nx.NetworkXPointlessConcept( + "cannot compute centrality for the null graph" + ) + # If no initial vector is provided, start with the all-ones vector. + if nstart is None: + nstart = {v: 1 for v in G} + if all(v == 0 for v in nstart.values()): + raise nx.NetworkXError("initial vector cannot have all zero values") + # Normalize the initial vector so that each entry is in [0, 1]. This is + # guaranteed to never have a divide-by-zero error by the previous line. + nstart_sum = sum(nstart.values()) + x = {k: v / nstart_sum for k, v in nstart.items()} + nnodes = G.number_of_nodes() + # make up to max_iter iterations + for _ in range(max_iter): + xlast = x + x = xlast.copy() # Start with xlast times I to iterate with (A+I) + # do the multiplication y^T = x^T A (left eigenvector) + for n in x: + for nbr in G[n]: + w = G[n][nbr].get(weight, 1) if weight else 1 + x[nbr] += xlast[n] * w + # Normalize the vector. The normalization denominator `norm` + # should never be zero by the Perron--Frobenius + # theorem. However, in case it is due to numerical error, we + # assume the norm to be one instead. + norm = math.hypot(*x.values()) or 1 + x = {k: v / norm for k, v in x.items()} + # Check for convergence (in the L_1 norm). + if sum(abs(x[n] - xlast[n]) for n in x) < nnodes * tol: + return x + raise nx.PowerIterationFailedConvergence(max_iter) + + +def eigenvector_centrality_numpy(G, weight=None, max_iter=50, tol=0): + r"""Compute the eigenvector centrality for the graph G. + + Eigenvector centrality computes the centrality for a node based on the + centrality of its neighbors. The eigenvector centrality for node $i$ is + + .. math:: + + Ax = \lambda x + + where $A$ is the adjacency matrix of the graph G with eigenvalue $\lambda$. + By virtue of the Perron–Frobenius theorem, there is a unique and positive + solution if $\lambda$ is the largest eigenvalue associated with the + eigenvector of the adjacency matrix $A$ ([2]_). + + Parameters + ---------- + G : graph + A networkx graph + + weight : None or string, optional (default=None) + The name of the edge attribute used as weight. + If None, all edge weights are considered equal. + In this measure the weight is interpreted as the connection strength. + max_iter : integer, optional (default=100) + Maximum number of iterations in power method. + + tol : float, optional (default=1.0e-6) + Relative accuracy for eigenvalues (stopping criterion). + The default value of 0 implies machine precision. + + Returns + ------- + nodes : dictionary + Dictionary of nodes with eigenvector centrality as the value. + + Examples + -------- + >>> G = nx.path_graph(4) + >>> centrality = nx.eigenvector_centrality_numpy(G) + >>> print([f"{node} {centrality[node]:0.2f}" for node in centrality]) + ['0 0.37', '1 0.60', '2 0.60', '3 0.37'] + + See Also + -------- + eigenvector_centrality + pagerank + hits + + Notes + ----- + The measure was introduced by [1]_. + + This algorithm uses the SciPy sparse eigenvalue solver (ARPACK) to + find the largest eigenvalue/eigenvector pair. + + For directed graphs this is "left" eigenvector centrality which corresponds + to the in-edges in the graph. For out-edges eigenvector centrality + first reverse the graph with ``G.reverse()``. + + Raises + ------ + NetworkXPointlessConcept + If the graph ``G`` is the null graph. + + References + ---------- + .. [1] Phillip Bonacich: + Power and Centrality: A Family of Measures. + American Journal of Sociology 92(5):1170–1182, 1986 + http://www.leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf + .. [2] Mark E. J. Newman: + Networks: An Introduction. + Oxford University Press, USA, 2010, pp. 169. + """ + import numpy as np + import scipy as sp + import scipy.sparse.linalg # call as sp.sparse.linalg + + if len(G) == 0: + raise nx.NetworkXPointlessConcept( + "cannot compute centrality for the null graph" + ) + M = nx.to_scipy_sparse_array(G, nodelist=list(G), weight=weight, dtype=float) + _, eigenvector = sp.sparse.linalg.eigs( + M.T, k=1, which="LR", maxiter=max_iter, tol=tol + ) + largest = eigenvector.flatten().real + norm = np.sign(largest.sum()) * sp.linalg.norm(largest) + return dict(zip(G, largest / norm)) diff --git a/shared/package-files/77/77dfb3a28fa310c453d4f84264dd5f17ae1d05c6398252ebe4622ecd420d7ec9/blob b/shared/package-files/77/77dfb3a28fa310c453d4f84264dd5f17ae1d05c6398252ebe4622ecd420d7ec9/blob new file mode 100644 index 0000000000000000000000000000000000000000..842c9a89b458d95e9953f490b49e6d69bc43ed6f --- /dev/null +++ b/shared/package-files/77/77dfb3a28fa310c453d4f84264dd5f17ae1d05c6398252ebe4622ecd420d7ec9/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _scaled_dot_product_flash_attention_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, c10::optional scale=c10::nullopt); +TORCH_API ::std::tuple _scaled_dot_product_flash_attention_nestedtensor_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, c10::optional scale=c10::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77e1ce95cb49f0ccf4885d5e19f55f3e07f93c2f5842d071e12222e41555ca3f/blob b/shared/package-files/77/77e1ce95cb49f0ccf4885d5e19f55f3e07f93c2f5842d071e12222e41555ca3f/blob new file mode 100644 index 0000000000000000000000000000000000000000..750551ba51d5871d03f737b54bd9656da83c0116 --- /dev/null +++ b/shared/package-files/77/77e1ce95cb49f0ccf4885d5e19f55f3e07f93c2f5842d071e12222e41555ca3f/blob @@ -0,0 +1,14 @@ +from setuptools import distutils + +from nested.source_module import cc + + +setup = distutils.core.setup + + +def run_setup(): + setup(ext_modules=[cc.distutils_extension()]) + + +if __name__ == '__main__': + run_setup() diff --git a/shared/package-files/77/77e1f09a746b65ea6624c2fb17461358ef93b910cfd85d76fbe01f34e8d93563/blob b/shared/package-files/77/77e1f09a746b65ea6624c2fb17461358ef93b910cfd85d76fbe01f34e8d93563/blob new file mode 100644 index 0000000000000000000000000000000000000000..ad31e9a0b8f95eb987a9a3eb68bc54ddca749452 Binary files /dev/null and b/shared/package-files/77/77e1f09a746b65ea6624c2fb17461358ef93b910cfd85d76fbe01f34e8d93563/blob differ diff --git a/shared/package-files/77/77e4233e95b4973ba0686060f05ea90e5ff9b191ce47f10327c12f58b733e056/blob b/shared/package-files/77/77e4233e95b4973ba0686060f05ea90e5ff9b191ce47f10327c12f58b733e056/blob new file mode 100644 index 0000000000000000000000000000000000000000..17937e58bd20a9fb82f44ccd05f0c081a1aa6c9b --- /dev/null +++ b/shared/package-files/77/77e4233e95b4973ba0686060f05ea90e5ff9b191ce47f10327c12f58b733e056/blob @@ -0,0 +1,12 @@ +% ruletest2.al +VARIABLES X1,X2 +SPECIFIED F1 = X1*X2 + 3*X1^2 +SPECIFIED F2=X1*T+X2*T^2 +VARIABLE X', Y'' +MOTIONVARIABLES Q{3}, U{2} +VARIABLES P{2}' +VARIABLE W{3}', R{2}'' +VARIABLES C{1:2, 1:2} +VARIABLES D{1,3} +VARIABLES J{1:2} +IMAGINARY N diff --git a/shared/package-files/77/77e7a538194052b0abbde6046229f726a04681cb3aad945616e629f3c9f2a978/blob b/shared/package-files/77/77e7a538194052b0abbde6046229f726a04681cb3aad945616e629f3c9f2a978/blob new file mode 100644 index 0000000000000000000000000000000000000000..b3ece0328fe35f5b32faae79d8a66020f5045b1e --- /dev/null +++ b/shared/package-files/77/77e7a538194052b0abbde6046229f726a04681cb3aad945616e629f3c9f2a978/blob @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace at { +class Tensor; +} + +namespace at::native { + +using reduce_all_fn = void (*)(Tensor & result, const Tensor & self); +using reduce_min_max_fn = void (*)(Tensor & max_result, Tensor & min_result, const Tensor & self); +DECLARE_DISPATCH(reduce_all_fn, min_all_stub); +DECLARE_DISPATCH(reduce_all_fn, max_all_stub); + +} // namespace at::native diff --git a/shared/package-files/77/77e833ab3caf478e4541ead1609adb0730961670ec656488f6982003941644ee/blob b/shared/package-files/77/77e833ab3caf478e4541ead1609adb0730961670ec656488f6982003941644ee/blob new file mode 100644 index 0000000000000000000000000000000000000000..baf23f7f0b6982115500fa95360d0ca4d2a1caf8 --- /dev/null +++ b/shared/package-files/77/77e833ab3caf478e4541ead1609adb0730961670ec656488f6982003941644ee/blob @@ -0,0 +1,20 @@ +from __future__ import annotations + +from ._array_object import Array +from ._dtypes import _integer_dtypes + +import numpy as np + +def take(x: Array, indices: Array, /, *, axis: Optional[int] = None) -> Array: + """ + Array API compatible wrapper for :py:func:`np.take `. + + See its docstring for more information. + """ + if axis is None and x.ndim != 1: + raise ValueError("axis must be specified when ndim > 1") + if indices.dtype not in _integer_dtypes: + raise TypeError("Only integer dtypes are allowed in indexing") + if indices.ndim != 1: + raise ValueError("Only 1-dim indices array is supported") + return Array._new(np.take(x._array, indices._array, axis=axis)) diff --git a/shared/package-files/77/77eb02a955f0fc036cbe85299621fb76594c6d3cbb4dcc919b6215f7b2e5d273/blob b/shared/package-files/77/77eb02a955f0fc036cbe85299621fb76594c6d3cbb4dcc919b6215f7b2e5d273/blob new file mode 100644 index 0000000000000000000000000000000000000000..0645479ee5e75de2279a0d619b8860d7abe4bd32 --- /dev/null +++ b/shared/package-files/77/77eb02a955f0fc036cbe85299621fb76594c6d3cbb4dcc919b6215f7b2e5d273/blob @@ -0,0 +1,757 @@ +from . import artist +from .axes import Axes +from .backend_bases import RendererBase, MouseEvent +from .path import Path +from .transforms import Transform, Bbox + +from typing import Any, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike +from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType + +class Patch(artist.Artist): + zorder: float + def __init__( + self, + *, + edgecolor: ColorType | None = ..., + facecolor: ColorType | None = ..., + color: ColorType | None = ..., + linewidth: float | None = ..., + linestyle: LineStyleType | None = ..., + antialiased: bool | None = ..., + hatch: str | None = ..., + fill: bool = ..., + capstyle: CapStyleType | None = ..., + joinstyle: JoinStyleType | None = ..., + **kwargs, + ) -> None: ... + def get_verts(self) -> ArrayLike: ... + def contains(self, mouseevent: MouseEvent, radius: float | None = None) -> tuple[bool, dict[Any, Any]]: ... + def contains_point( + self, point: tuple[float, float], radius: float | None = ... + ) -> bool: ... + def contains_points( + self, points: ArrayLike, radius: float | None = ... + ) -> np.ndarray: ... + def get_extents(self) -> Bbox: ... + def get_transform(self) -> Transform: ... + def get_data_transform(self) -> Transform: ... + def get_patch_transform(self) -> Transform: ... + def get_antialiased(self) -> bool: ... + def get_edgecolor(self) -> ColorType: ... + def get_facecolor(self) -> ColorType: ... + def get_linewidth(self) -> float: ... + def get_linestyle(self) -> LineStyleType: ... + def set_antialiased(self, aa: bool | None) -> None: ... + def set_edgecolor(self, color: ColorType | None) -> None: ... + def set_facecolor(self, color: ColorType | None) -> None: ... + def set_color(self, c: ColorType | None) -> None: ... + def set_alpha(self, alpha: float | None) -> None: ... + def set_linewidth(self, w: float | None) -> None: ... + def set_linestyle(self, ls: LineStyleType | None) -> None: ... + def set_fill(self, b: bool) -> None: ... + def get_fill(self) -> bool: ... + fill = property(get_fill, set_fill) + def set_capstyle(self, s: CapStyleType) -> None: ... + def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def set_joinstyle(self, s: JoinStyleType) -> None: ... + def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def set_hatch(self, hatch: str) -> None: ... + def set_hatch_linewidth(self, lw: float) -> None: ... + def get_hatch_linewidth(self) -> float: ... + def get_hatch(self) -> str: ... + def get_path(self) -> Path: ... + +class Shadow(Patch): + patch: Patch + def __init__(self, patch: Patch, ox: float, oy: float, *, shade: float = ..., **kwargs) -> None: ... + +class Rectangle(Patch): + angle: float + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + *, + angle: float = ..., + rotation_point: Literal["xy", "center"] | tuple[float, float] = ..., + **kwargs, + ) -> None: ... + @property + def rotation_point(self) -> Literal["xy", "center"] | tuple[float, float]: ... + @rotation_point.setter + def rotation_point( + self, value: Literal["xy", "center"] | tuple[float, float] + ) -> None: ... + def get_x(self) -> float: ... + def get_y(self) -> float: ... + def get_xy(self) -> tuple[float, float]: ... + def get_corners(self) -> np.ndarray: ... + def get_center(self) -> np.ndarray: ... + def get_width(self) -> float: ... + def get_height(self) -> float: ... + def get_angle(self) -> float: ... + def set_x(self, x: float) -> None: ... + def set_y(self, y: float) -> None: ... + def set_angle(self, angle: float) -> None: ... + def set_xy(self, xy: tuple[float, float]) -> None: ... + def set_width(self, w: float) -> None: ... + def set_height(self, h: float) -> None: ... + @overload + def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ... + @overload + def set_bounds( + self, left: float, bottom: float, width: float, height: float, / + ) -> None: ... + def get_bbox(self) -> Bbox: ... + xy = property(get_xy, set_xy) + +class RegularPolygon(Patch): + xy: tuple[float, float] + numvertices: int + orientation: float + radius: float + def __init__( + self, + xy: tuple[float, float], + numVertices: int, + *, + radius: float = ..., + orientation: float = ..., + **kwargs, + ) -> None: ... + +class PathPatch(Patch): + def __init__(self, path: Path, **kwargs) -> None: ... + def set_path(self, path: Path) -> None: ... + +class StepPatch(PathPatch): + orientation: Literal["vertical", "horizontal"] + def __init__( + self, + values: ArrayLike, + edges: ArrayLike, + *, + orientation: Literal["vertical", "horizontal"] = ..., + baseline: float = ..., + **kwargs, + ) -> None: ... + + # NamedTuple StairData, defined in body of method + def get_data(self) -> tuple[np.ndarray, np.ndarray, float]: ... + def set_data( + self, + values: ArrayLike | None = ..., + edges: ArrayLike | None = ..., + baseline: float | None = ..., + ) -> None: ... + +class Polygon(Patch): + def __init__(self, xy: ArrayLike, *, closed: bool = ..., **kwargs) -> None: ... + def get_closed(self) -> bool: ... + def set_closed(self, closed: bool) -> None: ... + def get_xy(self) -> np.ndarray: ... + def set_xy(self, xy: ArrayLike) -> None: ... + xy = property(get_xy, set_xy) + +class Wedge(Patch): + center: tuple[float, float] + r: float + theta1: float + theta2: float + width: float | None + def __init__( + self, + center: tuple[float, float], + r: float, + theta1: float, + theta2: float, + *, + width: float | None = ..., + **kwargs, + ) -> None: ... + def set_center(self, center: tuple[float, float]) -> None: ... + def set_radius(self, radius: float) -> None: ... + def set_theta1(self, theta1: float) -> None: ... + def set_theta2(self, theta2: float) -> None: ... + def set_width(self, width: float | None) -> None: ... + +class Arrow(Patch): + def __init__( + self, x: float, y: float, dx: float, dy: float, *, width: float = ..., **kwargs + ) -> None: ... + def set_data( + self, + x: float | None = ..., + y: float | None = ..., + dx: float | None = ..., + dy: float | None = ..., + width: float | None = ..., + ) -> None: ... +class FancyArrow(Polygon): + def __init__( + self, + x: float, + y: float, + dx: float, + dy: float, + *, + width: float = ..., + length_includes_head: bool = ..., + head_width: float | None = ..., + head_length: float | None = ..., + shape: Literal["full", "left", "right"] = ..., + overhang: float = ..., + head_starts_at_zero: bool = ..., + **kwargs, + ) -> None: ... + def set_data( + self, + *, + x: float | None = ..., + y: float | None = ..., + dx: float | None = ..., + dy: float | None = ..., + width: float | None = ..., + head_width: float | None = ..., + head_length: float | None = ..., + ) -> None: ... + +class CirclePolygon(RegularPolygon): + def __init__( + self, + xy: tuple[float, float], + radius: float = ..., + *, + resolution: int = ..., + **kwargs, + ) -> None: ... + +class Ellipse(Patch): + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + *, + angle: float = ..., + **kwargs, + ) -> None: ... + def set_center(self, xy: tuple[float, float]) -> None: ... + def get_center(self) -> float: ... + center = property(get_center, set_center) + + def set_width(self, width: float) -> None: ... + def get_width(self) -> float: ... + width = property(get_width, set_width) + + def set_height(self, height: float) -> None: ... + def get_height(self) -> float: ... + height = property(get_height, set_height) + + def set_angle(self, angle: float) -> None: ... + def get_angle(self) -> float: ... + angle = property(get_angle, set_angle) + + def get_corners(self) -> np.ndarray: ... + + def get_vertices(self) -> list[tuple[float, float]]: ... + def get_co_vertices(self) -> list[tuple[float, float]]: ... + + +class Annulus(Patch): + a: float + b: float + def __init__( + self, + xy: tuple[float, float], + r: float | tuple[float, float], + width: float, + angle: float = ..., + **kwargs, + ) -> None: ... + def set_center(self, xy: tuple[float, float]) -> None: ... + def get_center(self) -> tuple[float, float]: ... + center = property(get_center, set_center) + + def set_width(self, width: float) -> None: ... + def get_width(self) -> float: ... + width = property(get_width, set_width) + + def set_angle(self, angle: float) -> None: ... + def get_angle(self) -> float: ... + angle = property(get_angle, set_angle) + + def set_semimajor(self, a: float) -> None: ... + def set_semiminor(self, b: float) -> None: ... + def set_radii(self, r: float | tuple[float, float]) -> None: ... + def get_radii(self) -> tuple[float, float]: ... + radii = property(get_radii, set_radii) + +class Circle(Ellipse): + def __init__( + self, xy: tuple[float, float], radius: float = ..., **kwargs + ) -> None: ... + def set_radius(self, radius: float) -> None: ... + def get_radius(self) -> float: ... + radius = property(get_radius, set_radius) + +class Arc(Ellipse): + theta1: float + theta2: float + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + *, + angle: float = ..., + theta1: float = ..., + theta2: float = ..., + **kwargs, + ) -> None: ... + +def bbox_artist( + artist: artist.Artist, + renderer: RendererBase, + props: dict[str, Any] | None = ..., + fill: bool = ..., +) -> None: ... +def draw_bbox( + bbox: Bbox, + renderer: RendererBase, + color: ColorType = ..., + trans: Transform | None = ..., +) -> None: ... + +class _Style: + def __new__(cls, stylename, **kwargs): ... + @classmethod + def get_styles(cls) -> dict[str, type]: ... + @classmethod + def pprint_styles(cls) -> str: ... + @classmethod + def register(cls, name: str, style: type) -> None: ... + +class BoxStyle(_Style): + class Square(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Circle(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Ellipse(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class LArrow(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class RArrow(LArrow): + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class DArrow(BoxStyle): + pad: float + def __init__(self, pad: float = ...) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Round(BoxStyle): + pad: float + rounding_size: float | None + def __init__( + self, pad: float = ..., rounding_size: float | None = ... + ) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Round4(BoxStyle): + pad: float + rounding_size: float | None + def __init__( + self, pad: float = ..., rounding_size: float | None = ... + ) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Sawtooth(BoxStyle): + pad: float + tooth_size: float | None + def __init__( + self, pad: float = ..., tooth_size: float | None = ... + ) -> None: ... + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + + class Roundtooth(Sawtooth): + def __call__( + self, + x0: float, + y0: float, + width: float, + height: float, + mutation_size: float, + ) -> Path: ... + +class ConnectionStyle(_Style): + class _Base(ConnectionStyle): + def __call__( + self, + posA: tuple[float, float], + posB: tuple[float, float], + shrinkA: float = ..., + shrinkB: float = ..., + patchA: Patch | None = ..., + patchB: Patch | None = ..., + ) -> Path: ... + + class Arc3(_Base): + rad: float + def __init__(self, rad: float = ...) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Angle3(_Base): + angleA: float + angleB: float + def __init__(self, angleA: float = ..., angleB: float = ...) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Angle(_Base): + angleA: float + angleB: float + rad: float + def __init__( + self, angleA: float = ..., angleB: float = ..., rad: float = ... + ) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Arc(_Base): + angleA: float + angleB: float + armA: float | None + armB: float | None + rad: float + def __init__( + self, + angleA: float = ..., + angleB: float = ..., + armA: float | None = ..., + armB: float | None = ..., + rad: float = ..., + ) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + + class Bar(_Base): + armA: float + armB: float + fraction: float + angle: float | None + def __init__( + self, + armA: float = ..., + armB: float = ..., + fraction: float = ..., + angle: float | None = ..., + ) -> None: ... + def connect( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> Path: ... + +class ArrowStyle(_Style): + class _Base(ArrowStyle): + @staticmethod + def ensure_quadratic_bezier(path: Path) -> list[float]: ... + def transmute( + self, path: Path, mutation_size: float, linewidth: float + ) -> tuple[Path, bool]: ... + def __call__( + self, + path: Path, + mutation_size: float, + linewidth: float, + aspect_ratio: float = ..., + ) -> tuple[Path, bool]: ... + + class _Curve(_Base): + arrow: str + fillbegin: bool + fillend: bool + def __init__( + self, + head_length: float = ..., + head_width: float = ..., + widthA: float = ..., + widthB: float = ..., + lengthA: float = ..., + lengthB: float = ..., + angleA: float | None = ..., + angleB: float | None = ..., + scaleA: float | None = ..., + scaleB: float | None = ..., + ) -> None: ... + + class Curve(_Curve): + def __init__(self) -> None: ... + + class CurveA(_Curve): + arrow: str + + class CurveB(_Curve): + arrow: str + + class CurveAB(_Curve): + arrow: str + + class CurveFilledA(_Curve): + arrow: str + + class CurveFilledB(_Curve): + arrow: str + + class CurveFilledAB(_Curve): + arrow: str + + class BracketA(_Curve): + arrow: str + def __init__( + self, widthA: float = ..., lengthA: float = ..., angleA: float = ... + ) -> None: ... + + class BracketB(_Curve): + arrow: str + def __init__( + self, widthB: float = ..., lengthB: float = ..., angleB: float = ... + ) -> None: ... + + class BracketAB(_Curve): + arrow: str + def __init__( + self, + widthA: float = ..., + lengthA: float = ..., + angleA: float = ..., + widthB: float = ..., + lengthB: float = ..., + angleB: float = ..., + ) -> None: ... + + class BarAB(_Curve): + arrow: str + def __init__( + self, + widthA: float = ..., + angleA: float = ..., + widthB: float = ..., + angleB: float = ..., + ) -> None: ... + + class BracketCurve(_Curve): + arrow: str + def __init__( + self, widthA: float = ..., lengthA: float = ..., angleA: float | None = ... + ) -> None: ... + + class CurveBracket(_Curve): + arrow: str + def __init__( + self, widthB: float = ..., lengthB: float = ..., angleB: float | None = ... + ) -> None: ... + + class Simple(_Base): + def __init__( + self, + head_length: float = ..., + head_width: float = ..., + tail_width: float = ..., + ) -> None: ... + + class Fancy(_Base): + def __init__( + self, + head_length: float = ..., + head_width: float = ..., + tail_width: float = ..., + ) -> None: ... + + class Wedge(_Base): + tail_width: float + shrink_factor: float + def __init__( + self, tail_width: float = ..., shrink_factor: float = ... + ) -> None: ... + +class FancyBboxPatch(Patch): + def __init__( + self, + xy: tuple[float, float], + width: float, + height: float, + boxstyle: str | BoxStyle = ..., + *, + mutation_scale: float = ..., + mutation_aspect: float = ..., + **kwargs, + ) -> None: ... + def set_boxstyle(self, boxstyle: str | BoxStyle | None = ..., **kwargs) -> None: ... + def get_boxstyle(self) -> BoxStyle: ... + def set_mutation_scale(self, scale: float) -> None: ... + def get_mutation_scale(self) -> float: ... + def set_mutation_aspect(self, aspect: float) -> None: ... + def get_mutation_aspect(self) -> float: ... + def get_x(self) -> float: ... + def get_y(self) -> float: ... + def get_width(self) -> float: ... + def get_height(self) -> float: ... + def set_x(self, x: float) -> None: ... + def set_y(self, y: float) -> None: ... + def set_width(self, w: float) -> None: ... + def set_height(self, h: float) -> None: ... + @overload + def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ... + @overload + def set_bounds( + self, left: float, bottom: float, width: float, height: float, / + ) -> None: ... + def get_bbox(self) -> Bbox: ... + +class FancyArrowPatch(Patch): + patchA: Patch + patchB: Patch + shrinkA: float + shrinkB: float + def __init__( + self, + posA: tuple[float, float] | None = ..., + posB: tuple[float, float] | None = ..., + *, + path: Path | None = ..., + arrowstyle: str | ArrowStyle = ..., + connectionstyle: str | ConnectionStyle = ..., + patchA: Patch | None = ..., + patchB: Patch | None = ..., + shrinkA: float = ..., + shrinkB: float = ..., + mutation_scale: float = ..., + mutation_aspect: float | None = ..., + **kwargs, + ) -> None: ... + def set_positions( + self, posA: tuple[float, float], posB: tuple[float, float] + ) -> None: ... + def set_patchA(self, patchA: Patch) -> None: ... + def set_patchB(self, patchB: Patch) -> None: ... + def set_connectionstyle(self, connectionstyle: str | ConnectionStyle | None = ..., **kwargs) -> None: ... + def get_connectionstyle(self) -> ConnectionStyle: ... + def set_arrowstyle(self, arrowstyle: str | ArrowStyle | None = ..., **kwargs) -> None: ... + def get_arrowstyle(self) -> ArrowStyle: ... + def set_mutation_scale(self, scale: float) -> None: ... + def get_mutation_scale(self) -> float: ... + def set_mutation_aspect(self, aspect: float | None) -> None: ... + def get_mutation_aspect(self) -> float: ... + +class ConnectionPatch(FancyArrowPatch): + xy1: tuple[float, float] + xy2: tuple[float, float] + coords1: str | Transform + coords2: str | Transform | None + axesA: Axes | None + axesB: Axes | None + def __init__( + self, + xyA: tuple[float, float], + xyB: tuple[float, float], + coordsA: str | Transform, + coordsB: str | Transform | None = ..., + *, + axesA: Axes | None = ..., + axesB: Axes | None = ..., + arrowstyle: str | ArrowStyle = ..., + connectionstyle: str | ConnectionStyle = ..., + patchA: Patch | None = ..., + patchB: Patch | None = ..., + shrinkA: float = ..., + shrinkB: float = ..., + mutation_scale: float = ..., + mutation_aspect: float | None = ..., + clip_on: bool = ..., + **kwargs, + ) -> None: ... + def set_annotation_clip(self, b: bool | None) -> None: ... + def get_annotation_clip(self) -> bool | None: ... diff --git a/shared/package-files/77/77ed36b72ad723e09219b5c115815c9ccff24fc5921800477e9362171c9a74bd/blob b/shared/package-files/77/77ed36b72ad723e09219b5c115815c9ccff24fc5921800477e9362171c9a74bd/blob new file mode 100644 index 0000000000000000000000000000000000000000..bd518cf2b69094728f8693fe2cb8a2a535bd7d3c --- /dev/null +++ b/shared/package-files/77/77ed36b72ad723e09219b5c115815c9ccff24fc5921800477e9362171c9a74bd/blob @@ -0,0 +1,189 @@ +import os +from pathlib import Path +from typing import List, Tuple, Union + +from torch import Tensor +from torch.utils.data import Dataset +from torchaudio._internal import download_url_to_file +from torchaudio.datasets.utils import _extract_tar, _load_waveform + +URL = "train-clean-100" +FOLDER_IN_ARCHIVE = "LibriSpeech" +SAMPLE_RATE = 16000 +_DATA_SUBSETS = [ + "dev-clean", + "dev-other", + "test-clean", + "test-other", + "train-clean-100", + "train-clean-360", + "train-other-500", +] +_CHECKSUMS = { + "http://www.openslr.org/resources/12/dev-clean.tar.gz": "76f87d090650617fca0cac8f88b9416e0ebf80350acb97b343a85fa903728ab3", # noqa: E501 + "http://www.openslr.org/resources/12/dev-other.tar.gz": "12661c48e8c3fe1de2c1caa4c3e135193bfb1811584f11f569dd12645aa84365", # noqa: E501 + "http://www.openslr.org/resources/12/test-clean.tar.gz": "39fde525e59672dc6d1551919b1478f724438a95aa55f874b576be21967e6c23", # noqa: E501 + "http://www.openslr.org/resources/12/test-other.tar.gz": "d09c181bba5cf717b3dee7d4d592af11a3ee3a09e08ae025c5506f6ebe961c29", # noqa: E501 + "http://www.openslr.org/resources/12/train-clean-100.tar.gz": "d4ddd1d5a6ab303066f14971d768ee43278a5f2a0aa43dc716b0e64ecbbbf6e2", # noqa: E501 + "http://www.openslr.org/resources/12/train-clean-360.tar.gz": "146a56496217e96c14334a160df97fffedd6e0a04e66b9c5af0d40be3c792ecf", # noqa: E501 + "http://www.openslr.org/resources/12/train-other-500.tar.gz": "ddb22f27f96ec163645d53215559df6aa36515f26e01dd70798188350adcb6d2", # noqa: E501 +} + + +def _download_librispeech(root, url): + base_url = "http://www.openslr.org/resources/12/" + ext_archive = ".tar.gz" + + filename = url + ext_archive + archive = os.path.join(root, filename) + download_url = os.path.join(base_url, filename) + if not os.path.isfile(archive): + checksum = _CHECKSUMS.get(download_url, None) + download_url_to_file(download_url, archive, hash_prefix=checksum) + _extract_tar(archive) + + +def _get_librispeech_metadata( + fileid: str, root: str, folder: str, ext_audio: str, ext_txt: str, blist: List[str] +) -> Tuple[str, int, str, int, int, int]: + blist = blist or [] + speaker_id, chapter_id, utterance_id = fileid.split("-") + + # Get audio path and sample rate + fileid_audio = f"{speaker_id}-{chapter_id}-{utterance_id}" + filepath = os.path.join(folder, speaker_id, chapter_id, f"{fileid_audio}{ext_audio}") + + # Load text + file_text = f"{speaker_id}-{chapter_id}{ext_txt}" + file_text = os.path.join(root, folder, speaker_id, chapter_id, file_text) + uttblist = [] + with open(file_text) as ft: + for line in ft: + fileid_text, transcript = line.strip().split(" ", 1) + if fileid_audio == fileid_text: + # get utterance biasing list + for word in transcript.split(): + if word in blist and word not in uttblist: + uttblist.append(word) + break + else: + # Translation not found + raise FileNotFoundError(f"Translation not found for {fileid_audio}") + + return ( + filepath, + SAMPLE_RATE, + transcript, + int(speaker_id), + int(chapter_id), + int(utterance_id), + uttblist, + ) + + +class LibriSpeechBiasing(Dataset): + """*LibriSpeech* :cite:`7178964` dataset with prefix-tree construction and biasing support. + + Args: + root (str or Path): Path to the directory where the dataset is found or downloaded. + url (str, optional): The URL to download the dataset from, + or the type of the dataset to dowload. + Allowed type values are ``"dev-clean"``, ``"dev-other"``, ``"test-clean"``, + ``"test-other"``, ``"train-clean-100"``, ``"train-clean-360"`` and + ``"train-other-500"``. (default: ``"train-clean-100"``) + folder_in_archive (str, optional): + The top-level directory of the dataset. (default: ``"LibriSpeech"``) + download (bool, optional): + Whether to download the dataset if it is not found at root path. (default: ``False``). + blist (list, optional): + The list of biasing words (default: ``[]``). + """ + + _ext_txt = ".trans.txt" + _ext_audio = ".flac" + + def __init__( + self, + root: Union[str, Path], + url: str = URL, + folder_in_archive: str = FOLDER_IN_ARCHIVE, + download: bool = False, + blist: List[str] = None, + ) -> None: + self._url = url + if url not in _DATA_SUBSETS: + raise ValueError(f"Invalid url '{url}' given; please provide one of {_DATA_SUBSETS}.") + + root = os.fspath(root) + self._archive = os.path.join(root, folder_in_archive) + self._path = os.path.join(root, folder_in_archive, url) + + if not os.path.isdir(self._path): + if download: + _download_librispeech(root, url) + else: + raise RuntimeError( + f"Dataset not found at {self._path}. Please set `download=True` to download the dataset." + ) + + self._walker = sorted(str(p.stem) for p in Path(self._path).glob("*/*/*" + self._ext_audio)) + self.blist = blist + + def get_metadata(self, n: int) -> Tuple[str, int, str, int, int, int]: + """Get metadata for the n-th sample from the dataset. Returns filepath instead of waveform, + but otherwise returns the same fields as :py:func:`__getitem__`. + + Args: + n (int): The index of the sample to be loaded + + Returns: + Tuple of the following items; + + str: + Path to audio + int: + Sample rate + str: + Transcript + int: + Speaker ID + int: + Chapter ID + int: + Utterance ID + list: + List of biasing words in the utterance + """ + fileid = self._walker[n] + return _get_librispeech_metadata(fileid, self._archive, self._url, self._ext_audio, self._ext_txt, self.blist) + + def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]: + """Load the n-th sample from the dataset. + + Args: + n (int): The index of the sample to be loaded + + Returns: + Tuple of the following items; + + Tensor: + Waveform + int: + Sample rate + str: + Transcript + int: + Speaker ID + int: + Chapter ID + int: + Utterance ID + list: + List of biasing words in the utterance + """ + metadata = self.get_metadata(n) + waveform = _load_waveform(self._archive, metadata[0], metadata[1]) + return (waveform,) + metadata[1:] + + def __len__(self) -> int: + return len(self._walker) diff --git a/shared/package-files/77/77ef522912474652490b7df523112858e51721e63dcf109b8567a35ce9b31b0d/blob b/shared/package-files/77/77ef522912474652490b7df523112858e51721e63dcf109b8567a35ce9b31b0d/blob new file mode 100644 index 0000000000000000000000000000000000000000..6071707027bea46dccfc4d92fb3195060faf07ce --- /dev/null +++ b/shared/package-files/77/77ef522912474652490b7df523112858e51721e63dcf109b8567a35ce9b31b0d/blob @@ -0,0 +1,240 @@ +# +# Module which supports allocation of ctypes objects from shared memory +# +# multiprocessing/sharedctypes.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# + +import ctypes +import weakref + +from . import heap +from . import get_context + +from .context import reduction, assert_spawning +_ForkingPickler = reduction.ForkingPickler + +__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized'] + +# +# +# + +typecode_to_type = { + 'c': ctypes.c_char, 'u': ctypes.c_wchar, + 'b': ctypes.c_byte, 'B': ctypes.c_ubyte, + 'h': ctypes.c_short, 'H': ctypes.c_ushort, + 'i': ctypes.c_int, 'I': ctypes.c_uint, + 'l': ctypes.c_long, 'L': ctypes.c_ulong, + 'q': ctypes.c_longlong, 'Q': ctypes.c_ulonglong, + 'f': ctypes.c_float, 'd': ctypes.c_double + } + +# +# +# + +def _new_value(type_): + size = ctypes.sizeof(type_) + wrapper = heap.BufferWrapper(size) + return rebuild_ctype(type_, wrapper, None) + +def RawValue(typecode_or_type, *args): + ''' + Returns a ctypes object allocated from shared memory + ''' + type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) + obj = _new_value(type_) + ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) + obj.__init__(*args) + return obj + +def RawArray(typecode_or_type, size_or_initializer): + ''' + Returns a ctypes array allocated from shared memory + ''' + type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) + if isinstance(size_or_initializer, int): + type_ = type_ * size_or_initializer + obj = _new_value(type_) + ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) + return obj + else: + type_ = type_ * len(size_or_initializer) + result = _new_value(type_) + result.__init__(*size_or_initializer) + return result + +def Value(typecode_or_type, *args, lock=True, ctx=None): + ''' + Return a synchronization wrapper for a Value + ''' + obj = RawValue(typecode_or_type, *args) + if lock is False: + return obj + if lock in (True, None): + ctx = ctx or get_context() + lock = ctx.RLock() + if not hasattr(lock, 'acquire'): + raise AttributeError("%r has no method 'acquire'" % lock) + return synchronized(obj, lock, ctx=ctx) + +def Array(typecode_or_type, size_or_initializer, *, lock=True, ctx=None): + ''' + Return a synchronization wrapper for a RawArray + ''' + obj = RawArray(typecode_or_type, size_or_initializer) + if lock is False: + return obj + if lock in (True, None): + ctx = ctx or get_context() + lock = ctx.RLock() + if not hasattr(lock, 'acquire'): + raise AttributeError("%r has no method 'acquire'" % lock) + return synchronized(obj, lock, ctx=ctx) + +def copy(obj): + new_obj = _new_value(type(obj)) + ctypes.pointer(new_obj)[0] = obj + return new_obj + +def synchronized(obj, lock=None, ctx=None): + assert not isinstance(obj, SynchronizedBase), 'object already synchronized' + ctx = ctx or get_context() + + if isinstance(obj, ctypes._SimpleCData): + return Synchronized(obj, lock, ctx) + elif isinstance(obj, ctypes.Array): + if obj._type_ is ctypes.c_char: + return SynchronizedString(obj, lock, ctx) + return SynchronizedArray(obj, lock, ctx) + else: + cls = type(obj) + try: + scls = class_cache[cls] + except KeyError: + names = [field[0] for field in cls._fields_] + d = {name: make_property(name) for name in names} + classname = 'Synchronized' + cls.__name__ + scls = class_cache[cls] = type(classname, (SynchronizedBase,), d) + return scls(obj, lock, ctx) + +# +# Functions for pickling/unpickling +# + +def reduce_ctype(obj): + assert_spawning(obj) + if isinstance(obj, ctypes.Array): + return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_) + else: + return rebuild_ctype, (type(obj), obj._wrapper, None) + +def rebuild_ctype(type_, wrapper, length): + if length is not None: + type_ = type_ * length + _ForkingPickler.register(type_, reduce_ctype) + buf = wrapper.create_memoryview() + obj = type_.from_buffer(buf) + obj._wrapper = wrapper + return obj + +# +# Function to create properties +# + +def make_property(name): + try: + return prop_cache[name] + except KeyError: + d = {} + exec(template % ((name,)*7), d) + prop_cache[name] = d[name] + return d[name] + +template = ''' +def get%s(self): + self.acquire() + try: + return self._obj.%s + finally: + self.release() +def set%s(self, value): + self.acquire() + try: + self._obj.%s = value + finally: + self.release() +%s = property(get%s, set%s) +''' + +prop_cache = {} +class_cache = weakref.WeakKeyDictionary() + +# +# Synchronized wrappers +# + +class SynchronizedBase(object): + + def __init__(self, obj, lock=None, ctx=None): + self._obj = obj + if lock: + self._lock = lock + else: + ctx = ctx or get_context(force=True) + self._lock = ctx.RLock() + self.acquire = self._lock.acquire + self.release = self._lock.release + + def __enter__(self): + return self._lock.__enter__() + + def __exit__(self, *args): + return self._lock.__exit__(*args) + + def __reduce__(self): + assert_spawning(self) + return synchronized, (self._obj, self._lock) + + def get_obj(self): + return self._obj + + def get_lock(self): + return self._lock + + def __repr__(self): + return '<%s wrapper for %s>' % (type(self).__name__, self._obj) + + +class Synchronized(SynchronizedBase): + value = make_property('value') + + +class SynchronizedArray(SynchronizedBase): + + def __len__(self): + return len(self._obj) + + def __getitem__(self, i): + with self: + return self._obj[i] + + def __setitem__(self, i, value): + with self: + self._obj[i] = value + + def __getslice__(self, start, stop): + with self: + return self._obj[start:stop] + + def __setslice__(self, start, stop, values): + with self: + self._obj[start:stop] = values + + +class SynchronizedString(SynchronizedArray): + value = make_property('value') + raw = make_property('raw') diff --git a/shared/package-files/77/77f0078770835015f867ac48fabbc6207df59d5d4c1d12d8f2a5c22001083f52/blob b/shared/package-files/77/77f0078770835015f867ac48fabbc6207df59d5d4c1d12d8f2a5c22001083f52/blob new file mode 100644 index 0000000000000000000000000000000000000000..628c62691e07802581d8dd42c59cc851810a94f7 --- /dev/null +++ b/shared/package-files/77/77f0078770835015f867ac48fabbc6207df59d5d4c1d12d8f2a5c22001083f52/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _convert_indices_from_csr_to_coo(const at::Tensor & crow_indices, const at::Tensor & col_indices, bool out_int32=false, bool transpose=false); +TORCH_API at::Tensor & _convert_indices_from_csr_to_coo_out(at::Tensor & out, const at::Tensor & crow_indices, const at::Tensor & col_indices, bool out_int32=false, bool transpose=false); +TORCH_API at::Tensor & _convert_indices_from_csr_to_coo_outf(const at::Tensor & crow_indices, const at::Tensor & col_indices, bool out_int32, bool transpose, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/77/77f10f0d409e2d5bd3f9c976d4cbb8e5d46eb19882140504ef4396616a956df5/blob b/shared/package-files/77/77f10f0d409e2d5bd3f9c976d4cbb8e5d46eb19882140504ef4396616a956df5/blob new file mode 100644 index 0000000000000000000000000000000000000000..b388a3d663227234abdbbdc0a9db6416c3986c55 --- /dev/null +++ b/shared/package-files/77/77f10f0d409e2d5bd3f9c976d4cbb8e5d46eb19882140504ef4396616a956df5/blob @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor __and__(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & __iand__(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor __and__(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & __iand__(at::Tensor & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/77/77f5dc311010f6bfbec8800059274930be8a796824b32e6a44d157698d413100/blob b/shared/package-files/77/77f5dc311010f6bfbec8800059274930be8a796824b32e6a44d157698d413100/blob new file mode 100644 index 0000000000000000000000000000000000000000..215026d648471c04cb8751506c03626fda73fc68 --- /dev/null +++ b/shared/package-files/77/77f5dc311010f6bfbec8800059274930be8a796824b32e6a44d157698d413100/blob @@ -0,0 +1,84 @@ +import pytest + +from pandas.util._validators import validate_args_and_kwargs + + +@pytest.fixture +def _fname(): + return "func" + + +def test_invalid_total_length_max_length_one(_fname): + compat_args = ("foo",) + kwargs = {"foo": "FOO"} + args = ("FoO", "BaZ") + + min_fname_arg_count = 0 + max_length = len(compat_args) + min_fname_arg_count + actual_length = len(kwargs) + len(args) + min_fname_arg_count + + msg = ( + rf"{_fname}\(\) takes at most {max_length} " + rf"argument \({actual_length} given\)" + ) + + with pytest.raises(TypeError, match=msg): + validate_args_and_kwargs(_fname, args, kwargs, min_fname_arg_count, compat_args) + + +def test_invalid_total_length_max_length_multiple(_fname): + compat_args = ("foo", "bar", "baz") + kwargs = {"foo": "FOO", "bar": "BAR"} + args = ("FoO", "BaZ") + + min_fname_arg_count = 2 + max_length = len(compat_args) + min_fname_arg_count + actual_length = len(kwargs) + len(args) + min_fname_arg_count + + msg = ( + rf"{_fname}\(\) takes at most {max_length} " + rf"arguments \({actual_length} given\)" + ) + + with pytest.raises(TypeError, match=msg): + validate_args_and_kwargs(_fname, args, kwargs, min_fname_arg_count, compat_args) + + +@pytest.mark.parametrize("args,kwargs", [((), {"foo": -5, "bar": 2}), ((-5, 2), {})]) +def test_missing_args_or_kwargs(args, kwargs, _fname): + bad_arg = "bar" + min_fname_arg_count = 2 + + compat_args = {"foo": -5, bad_arg: 1} + + msg = ( + rf"the '{bad_arg}' parameter is not supported " + rf"in the pandas implementation of {_fname}\(\)" + ) + + with pytest.raises(ValueError, match=msg): + validate_args_and_kwargs(_fname, args, kwargs, min_fname_arg_count, compat_args) + + +def test_duplicate_argument(_fname): + min_fname_arg_count = 2 + + compat_args = {"foo": None, "bar": None, "baz": None} + kwargs = {"foo": None, "bar": None} + args = (None,) # duplicate value for "foo" + + msg = rf"{_fname}\(\) got multiple values for keyword argument 'foo'" + + with pytest.raises(TypeError, match=msg): + validate_args_and_kwargs(_fname, args, kwargs, min_fname_arg_count, compat_args) + + +def test_validation(_fname): + # No exceptions should be raised. + compat_args = {"foo": 1, "bar": None, "baz": -2} + kwargs = {"baz": -2} + + args = (1, None) + min_fname_arg_count = 2 + + validate_args_and_kwargs(_fname, args, kwargs, min_fname_arg_count, compat_args) diff --git a/shared/package-files/77/77f802a10e2127334114d73686f44e379875174e767a9810f3387f44a4e52e52/blob b/shared/package-files/77/77f802a10e2127334114d73686f44e379875174e767a9810f3387f44a4e52e52/blob new file mode 100644 index 0000000000000000000000000000000000000000..c22deb56470e553407c07d3820af0f31a584823b --- /dev/null +++ b/shared/package-files/77/77f802a10e2127334114d73686f44e379875174e767a9810f3387f44a4e52e52/blob @@ -0,0 +1,448 @@ +import math +import operator +from llvmlite import ir +from numba.core import types, typing, cgutils, targetconfig +from numba.core.imputils import Registry +from numba.types import float32, float64, int64, uint64 +from numba.cuda import libdevice +from numba import cuda + +registry = Registry() +lower = registry.lower + + +booleans = [] +booleans += [('isnand', 'isnanf', math.isnan)] +booleans += [('isinfd', 'isinff', math.isinf)] +booleans += [('isfinited', 'finitef', math.isfinite)] + +unarys = [] +unarys += [('ceil', 'ceilf', math.ceil)] +unarys += [('floor', 'floorf', math.floor)] +unarys += [('fabs', 'fabsf', math.fabs)] +unarys += [('exp', 'expf', math.exp)] +unarys += [('expm1', 'expm1f', math.expm1)] +unarys += [('erf', 'erff', math.erf)] +unarys += [('erfc', 'erfcf', math.erfc)] +unarys += [('tgamma', 'tgammaf', math.gamma)] +unarys += [('lgamma', 'lgammaf', math.lgamma)] +unarys += [('sqrt', 'sqrtf', math.sqrt)] +unarys += [('log', 'logf', math.log)] +unarys += [('log2', 'log2f', math.log2)] +unarys += [('log10', 'log10f', math.log10)] +unarys += [('log1p', 'log1pf', math.log1p)] +unarys += [('acosh', 'acoshf', math.acosh)] +unarys += [('acos', 'acosf', math.acos)] +unarys += [('cos', 'cosf', math.cos)] +unarys += [('cosh', 'coshf', math.cosh)] +unarys += [('asinh', 'asinhf', math.asinh)] +unarys += [('asin', 'asinf', math.asin)] +unarys += [('sin', 'sinf', math.sin)] +unarys += [('sinh', 'sinhf', math.sinh)] +unarys += [('atan', 'atanf', math.atan)] +unarys += [('atanh', 'atanhf', math.atanh)] +unarys += [('tan', 'tanf', math.tan)] +unarys += [('trunc', 'truncf', math.trunc)] + +unarys_fastmath = {} +unarys_fastmath['cosf'] = 'fast_cosf' +unarys_fastmath['sinf'] = 'fast_sinf' +unarys_fastmath['tanf'] = 'fast_tanf' +unarys_fastmath['expf'] = 'fast_expf' +unarys_fastmath['log2f'] = 'fast_log2f' +unarys_fastmath['log10f'] = 'fast_log10f' +unarys_fastmath['logf'] = 'fast_logf' + +binarys = [] +binarys += [('copysign', 'copysignf', math.copysign)] +binarys += [('atan2', 'atan2f', math.atan2)] +binarys += [('pow', 'powf', math.pow)] +binarys += [('fmod', 'fmodf', math.fmod)] +binarys += [('hypot', 'hypotf', math.hypot)] +binarys += [('remainder', 'remainderf', math.remainder)] + +binarys_fastmath = {} +binarys_fastmath['powf'] = 'fast_powf' + + +@lower(math.isinf, types.Integer) +@lower(math.isnan, types.Integer) +def math_isinf_isnan_int(context, builder, sig, args): + return context.get_constant(types.boolean, 0) + + +@lower(operator.truediv, types.float32, types.float32) +def maybe_fast_truediv(context, builder, sig, args): + if context.fastmath: + sig = typing.signature(float32, float32, float32) + impl = context.get_function(libdevice.fast_fdividef, sig) + return impl(builder, args) + else: + with cgutils.if_zero(builder, args[1]): + context.error_model.fp_zero_division(builder, ("division by zero",)) + res = builder.fdiv(*args) + return res + + +@lower(math.isfinite, types.Integer) +def math_isfinite_int(context, builder, sig, args): + return context.get_constant(types.boolean, 1) + + +@lower(math.sin, types.float16) +def fp16_sin_impl(context, builder, sig, args): + def fp16_sin(x): + return cuda.fp16.hsin(x) + + return context.compile_internal(builder, fp16_sin, sig, args) + + +@lower(math.cos, types.float16) +def fp16_cos_impl(context, builder, sig, args): + def fp16_cos(x): + return cuda.fp16.hcos(x) + + return context.compile_internal(builder, fp16_cos, sig, args) + + +@lower(math.log, types.float16) +def fp16_log_impl(context, builder, sig, args): + def fp16_log(x): + return cuda.fp16.hlog(x) + + return context.compile_internal(builder, fp16_log, sig, args) + + +@lower(math.log10, types.float16) +def fp16_log10_impl(context, builder, sig, args): + def fp16_log10(x): + return cuda.fp16.hlog10(x) + + return context.compile_internal(builder, fp16_log10, sig, args) + + +@lower(math.log2, types.float16) +def fp16_log2_impl(context, builder, sig, args): + def fp16_log2(x): + return cuda.fp16.hlog2(x) + + return context.compile_internal(builder, fp16_log2, sig, args) + + +@lower(math.exp, types.float16) +def fp16_exp_impl(context, builder, sig, args): + def fp16_exp(x): + return cuda.fp16.hexp(x) + + return context.compile_internal(builder, fp16_exp, sig, args) + + +@lower(math.floor, types.float16) +def fp16_floor_impl(context, builder, sig, args): + def fp16_floor(x): + return cuda.fp16.hfloor(x) + + return context.compile_internal(builder, fp16_floor, sig, args) + + +@lower(math.ceil, types.float16) +def fp16_ceil_impl(context, builder, sig, args): + def fp16_ceil(x): + return cuda.fp16.hceil(x) + + return context.compile_internal(builder, fp16_ceil, sig, args) + + +@lower(math.sqrt, types.float16) +def fp16_sqrt_impl(context, builder, sig, args): + def fp16_sqrt(x): + return cuda.fp16.hsqrt(x) + + return context.compile_internal(builder, fp16_sqrt, sig, args) + + +@lower(math.fabs, types.float16) +def fp16_fabs_impl(context, builder, sig, args): + def fp16_fabs(x): + return cuda.fp16.habs(x) + + return context.compile_internal(builder, fp16_fabs, sig, args) + + +@lower(math.trunc, types.float16) +def fp16_trunc_impl(context, builder, sig, args): + def fp16_trunc(x): + return cuda.fp16.htrunc(x) + + return context.compile_internal(builder, fp16_trunc, sig, args) + + +def impl_boolean(key, ty, libfunc): + def lower_boolean_impl(context, builder, sig, args): + libfunc_impl = context.get_function(libfunc, + typing.signature(types.int32, ty)) + result = libfunc_impl(builder, args) + return context.cast(builder, result, types.int32, types.boolean) + + lower(key, ty)(lower_boolean_impl) + + +def get_lower_unary_impl(key, ty, libfunc): + def lower_unary_impl(context, builder, sig, args): + actual_libfunc = libfunc + fast_replacement = None + if ty == float32 and context.fastmath: + fast_replacement = unarys_fastmath.get(libfunc.__name__) + + if fast_replacement is not None: + actual_libfunc = getattr(libdevice, fast_replacement) + + libfunc_impl = context.get_function(actual_libfunc, + typing.signature(ty, ty)) + return libfunc_impl(builder, args) + return lower_unary_impl + + +def get_unary_impl_for_fn_and_ty(fn, ty): + # tanh is a special case - because it is not registered like the other + # unary implementations, it does not appear in the unarys list. However, + # its implementation can be looked up by key like the other + # implementations, so we add it to the list we search here. + tanh_impls = ('tanh', 'tanhf', math.tanh) + for fname64, fname32, key in unarys + [tanh_impls]: + if fn == key: + if ty == float32: + impl = getattr(libdevice, fname32) + elif ty == float64: + impl = getattr(libdevice, fname64) + + return get_lower_unary_impl(key, ty, impl) + + raise RuntimeError(f"Implementation of {fn} for {ty} not found") + + +def impl_unary(key, ty, libfunc): + lower_unary_impl = get_lower_unary_impl(key, ty, libfunc) + lower(key, ty)(lower_unary_impl) + + +def impl_unary_int(key, ty, libfunc): + def lower_unary_int_impl(context, builder, sig, args): + if sig.args[0] == int64: + convert = builder.sitofp + elif sig.args[0] == uint64: + convert = builder.uitofp + else: + m = 'Only 64-bit integers are supported for generic unary int ops' + raise TypeError(m) + + arg = convert(args[0], ir.DoubleType()) + sig = typing.signature(float64, float64) + libfunc_impl = context.get_function(libfunc, sig) + return libfunc_impl(builder, [arg]) + + lower(key, ty)(lower_unary_int_impl) + + +def get_lower_binary_impl(key, ty, libfunc): + def lower_binary_impl(context, builder, sig, args): + actual_libfunc = libfunc + fast_replacement = None + if ty == float32 and context.fastmath: + fast_replacement = binarys_fastmath.get(libfunc.__name__) + + if fast_replacement is not None: + actual_libfunc = getattr(libdevice, fast_replacement) + + libfunc_impl = context.get_function(actual_libfunc, + typing.signature(ty, ty, ty)) + return libfunc_impl(builder, args) + return lower_binary_impl + + +def get_binary_impl_for_fn_and_ty(fn, ty): + for fname64, fname32, key in binarys: + if fn == key: + if ty == float32: + impl = getattr(libdevice, fname32) + elif ty == float64: + impl = getattr(libdevice, fname64) + + return get_lower_binary_impl(key, ty, impl) + + raise RuntimeError(f"Implementation of {fn} for {ty} not found") + + +def impl_binary(key, ty, libfunc): + lower_binary_impl = get_lower_binary_impl(key, ty, libfunc) + lower(key, ty, ty)(lower_binary_impl) + + +def impl_binary_int(key, ty, libfunc): + def lower_binary_int_impl(context, builder, sig, args): + if sig.args[0] == int64: + convert = builder.sitofp + elif sig.args[0] == uint64: + convert = builder.uitofp + else: + m = 'Only 64-bit integers are supported for generic binary int ops' + raise TypeError(m) + + args = [convert(arg, ir.DoubleType()) for arg in args] + sig = typing.signature(float64, float64, float64) + libfunc_impl = context.get_function(libfunc, sig) + return libfunc_impl(builder, args) + + lower(key, ty, ty)(lower_binary_int_impl) + + +for fname64, fname32, key in booleans: + impl32 = getattr(libdevice, fname32) + impl64 = getattr(libdevice, fname64) + impl_boolean(key, float32, impl32) + impl_boolean(key, float64, impl64) + + +for fname64, fname32, key in unarys: + impl32 = getattr(libdevice, fname32) + impl64 = getattr(libdevice, fname64) + impl_unary(key, float32, impl32) + impl_unary(key, float64, impl64) + impl_unary_int(key, int64, impl64) + impl_unary_int(key, uint64, impl64) + + +for fname64, fname32, key in binarys: + impl32 = getattr(libdevice, fname32) + impl64 = getattr(libdevice, fname64) + impl_binary(key, float32, impl32) + impl_binary(key, float64, impl64) + impl_binary_int(key, int64, impl64) + impl_binary_int(key, uint64, impl64) + + +def impl_pow_int(ty, libfunc): + def lower_pow_impl_int(context, builder, sig, args): + powi_sig = typing.signature(ty, ty, types.int32) + libfunc_impl = context.get_function(libfunc, powi_sig) + return libfunc_impl(builder, args) + + lower(math.pow, ty, types.int32)(lower_pow_impl_int) + + +impl_pow_int(types.float32, libdevice.powif) +impl_pow_int(types.float64, libdevice.powi) + + +def impl_modf(ty, libfunc): + retty = types.UniTuple(ty, 2) + + def lower_modf_impl(context, builder, sig, args): + modf_sig = typing.signature(retty, ty) + libfunc_impl = context.get_function(libfunc, modf_sig) + return libfunc_impl(builder, args) + + lower(math.modf, ty)(lower_modf_impl) + + +impl_modf(types.float32, libdevice.modff) +impl_modf(types.float64, libdevice.modf) + + +def impl_frexp(ty, libfunc): + retty = types.Tuple((ty, types.int32)) + + def lower_frexp_impl(context, builder, sig, args): + frexp_sig = typing.signature(retty, ty) + libfunc_impl = context.get_function(libfunc, frexp_sig) + return libfunc_impl(builder, args) + + lower(math.frexp, ty)(lower_frexp_impl) + + +impl_frexp(types.float32, libdevice.frexpf) +impl_frexp(types.float64, libdevice.frexp) + + +def impl_ldexp(ty, libfunc): + def lower_ldexp_impl(context, builder, sig, args): + ldexp_sig = typing.signature(ty, ty, types.int32) + libfunc_impl = context.get_function(libfunc, ldexp_sig) + return libfunc_impl(builder, args) + + lower(math.ldexp, ty, types.int32)(lower_ldexp_impl) + + +impl_ldexp(types.float32, libdevice.ldexpf) +impl_ldexp(types.float64, libdevice.ldexp) + + +def impl_tanh(ty, libfunc): + def lower_tanh_impl(context, builder, sig, args): + def get_compute_capability(): + flags = targetconfig.ConfigStack().top() + return flags.compute_capability + + def tanh_impl_libdevice(): + tanh_sig = typing.signature(ty, ty) + libfunc_impl = context.get_function(libfunc, tanh_sig) + return libfunc_impl(builder, args) + + def tanhf_impl_fastmath(): + fnty = ir.FunctionType(ir.FloatType(), [ir.FloatType()]) + asm = ir.InlineAsm(fnty, 'tanh.approx.f32 $0, $1;', '=f,f') + return builder.call(asm, args) + + if ty == float32 and context.fastmath: + cc = get_compute_capability() + if cc >= (7,5): + return tanhf_impl_fastmath() + + return tanh_impl_libdevice() + + lower(math.tanh, ty)(lower_tanh_impl) + + +impl_tanh(types.float32, libdevice.tanhf) +impl_tanh(types.float64, libdevice.tanh) + +impl_unary_int(math.tanh, int64, libdevice.tanh) +impl_unary_int(math.tanh, uint64, libdevice.tanh) + +# Complex power implementations - translations of _Py_c_pow from CPython +# https://github.com/python/cpython/blob/a755410e054e1e2390de5830befc08fe80706c66/Objects/complexobject.c#L123-L151 +# +# The complex64 variant casts all constants and some variables to ensure that +# as much computation is done in single precision as possible. A small number +# of operations are still done in 64-bit, but these come from libdevice code. + + +def cpow_implement(fty, cty): + def core(context, builder, sig, args): + def cpow_internal(a, b): + + if b.real == fty(0.0) and b.imag == fty(0.0): + return cty(1.0) + cty(0.0j) + elif a.real == fty(0.0) and b.real == fty(0.0): + return cty(0.0) + cty(0.0j) + + vabs = math.hypot(a.real, a.imag) + len = math.pow(vabs, b.real) + at = math.atan2(a.imag, a.real) + phase = at * b.real + if b.imag != fty(0.0): + len /= math.exp(at * b.imag) + phase += b.imag * math.log(vabs) + + return len * (cty(math.cos(phase)) + + cty(math.sin(phase) * cty(1.0j))) + + return context.compile_internal(builder, cpow_internal, sig, args) + + lower(operator.pow, cty, cty)(core) + lower(operator.ipow, cty, cty)(core) + lower(pow, cty, cty)(core) + + +cpow_implement(types.float32, types.complex64) +cpow_implement(types.float64, types.complex128) diff --git a/shared/package-files/77/77fa371b06bcb9b3945c6425488a7777c958c916cf4b56d9886f8f2b47b64f29/blob b/shared/package-files/77/77fa371b06bcb9b3945c6425488a7777c958c916cf4b56d9886f8f2b47b64f29/blob new file mode 100644 index 0000000000000000000000000000000000000000..1fd01786a47bd079b49297ee8461b7e37a0b5e68 --- /dev/null +++ b/shared/package-files/77/77fa371b06bcb9b3945c6425488a7777c958c916cf4b56d9886f8f2b47b64f29/blob @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import abc +import time +import warnings +from collections import namedtuple +from functools import wraps +from typing import Dict, Optional + + +MetricData = namedtuple("MetricData", ["timestamp", "group_name", "name", "value"]) + + +class MetricsConfig: + __slots__ = ["params"] + + def __init__(self, params: Optional[Dict[str, str]] = None): + self.params = params + if self.params is None: + self.params = {} + + +class MetricHandler(abc.ABC): + @abc.abstractmethod + def emit(self, metric_data: MetricData): + pass + + +class ConsoleMetricHandler(MetricHandler): + def emit(self, metric_data: MetricData): + print( + "[{}][{}]: {}={}".format( + metric_data.timestamp, + metric_data.group_name, + metric_data.name, + metric_data.value, + ) + ) + + +class NullMetricHandler(MetricHandler): + def emit(self, metric_data: MetricData): + pass + + +class MetricStream: + def __init__(self, group_name: str, handler: MetricHandler): + self.group_name = group_name + self.handler = handler + + def add_value(self, metric_name: str, metric_value: int): + self.handler.emit( + MetricData(time.time(), self.group_name, metric_name, metric_value) + ) + + +_metrics_map = {} +_default_metrics_handler = NullMetricHandler() + + +# pyre-fixme[9]: group has type `str`; used as `None`. +def configure(handler: MetricHandler, group: str = None): + if group is None: + global _default_metrics_handler + # pyre-fixme[9]: _default_metrics_handler has type `NullMetricHandler`; used + # as `MetricHandler`. + _default_metrics_handler = handler + else: + _metrics_map[group] = handler + + +def getStream(group: str): + if group in _metrics_map: + handler = _metrics_map[group] + else: + handler = _default_metrics_handler + return MetricStream(group, handler) + + +def _get_metric_name(fn): + qualname = fn.__qualname__ + split = qualname.split(".") + if len(split) == 1: + module = fn.__module__ + if module: + return module.split(".")[-1] + "." + split[0] + else: + return split[0] + else: + return qualname + + +def prof(fn=None, group: str = "torchelastic"): + r""" + @profile decorator publishes duration.ms, count, success, failure + metrics for the function that it decorates. The metric name defaults + to the qualified name (``class_name.def_name``) of the function. + If the function does not belong to a class, it uses the leaf module name + instead. + + Usage + + :: + + @metrics.prof + def x(): + pass + + @metrics.prof(group="agent") + def y(): + pass + """ + + def wrap(f): + @wraps(f) + def wrapper(*args, **kwargs): + key = _get_metric_name(f) + try: + start = time.time() + result = f(*args, **kwargs) + put_metric(f"{key}.success", 1, group) + except Exception: + put_metric(f"{key}.failure", 1, group) + raise + finally: + put_metric(f"{key}.duration.ms", get_elapsed_time_ms(start), group) + return result + + return wrapper + + if fn: + return wrap(fn) + else: + return wrap + + +def profile(group=None): + """ + @profile decorator adds latency and success/failure metrics to any given function. + + Usage + + :: + + @metrics.profile("my_metric_group") + def some_function(): + """ + warnings.warn("Deprecated, use @prof instead", DeprecationWarning) + + def wrap(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + start_time = time.time() + result = func(*args, **kwargs) + publish_metric(group, "{}.success".format(func.__name__), 1) + except Exception: + publish_metric(group, "{}.failure".format(func.__name__), 1) + raise + finally: + publish_metric( + group, + "{}.duration.ms".format(func.__name__), + get_elapsed_time_ms(start_time), + ) + return result + + return wrapper + + return wrap + + +def put_metric(metric_name: str, metric_value: int, metric_group: str = "torchelastic"): + """ + Publishes a metric data point. + + Usage + + :: + + put_metric("metric_name", 1) + put_metric("metric_name", 1, "metric_group_name") + """ + + getStream(metric_group).add_value(metric_name, metric_value) + + +def publish_metric(metric_group: str, metric_name: str, metric_value: int): + warnings.warn( + "Deprecated, use put_metric(metric_group)(metric_name, metric_value) instead" + ) + metric_stream = getStream(metric_group) + metric_stream.add_value(metric_name, metric_value) + + +def get_elapsed_time_ms(start_time_in_seconds: float): + """ + Returns the elapsed time in millis from the given start time. + """ + end_time = time.time() + return int((end_time - start_time_in_seconds) * 1000) diff --git a/shared/package-files/77/77facb92a74e6c10c3e050694ce620cf0cac4ea06d623815e6fd480cb872afef/blob b/shared/package-files/77/77facb92a74e6c10c3e050694ce620cf0cac4ea06d623815e6fd480cb872afef/blob new file mode 100644 index 0000000000000000000000000000000000000000..cae169e14f0306b195bca73ce86547391851aab6 --- /dev/null +++ b/shared/package-files/77/77facb92a74e6c10c3e050694ce620cf0cac4ea06d623815e6fd480cb872afef/blob @@ -0,0 +1,97 @@ +import numpy as np +from numpy.linalg import norm +from numpy.testing import assert_equal, assert_allclose, assert_ +from scipy.sparse.linalg._isolve import minres + +from pytest import raises as assert_raises + + +def get_sample_problem(): + # A random 10 x 10 symmetric matrix + rng = np.random.RandomState(1234) + matrix = rng.rand(10, 10) + matrix = matrix + matrix.T + # A random vector of length 10 + vector = rng.rand(10) + return matrix, vector + + +def test_singular(): + A, b = get_sample_problem() + A[0, ] = 0 + b[0] = 0 + xp, info = minres(A, b) + assert_equal(info, 0) + assert norm(A @ xp - b) <= 1e-5 * norm(b) + + +def test_x0_is_used_by(): + A, b = get_sample_problem() + # Random x0 to feed minres + rng = np.random.RandomState(12345) + x0 = rng.rand(10) + trace = [] + + def trace_iterates(xk): + trace.append(xk) + minres(A, b, x0=x0, callback=trace_iterates) + trace_with_x0 = trace + + trace = [] + minres(A, b, callback=trace_iterates) + assert_(not np.array_equal(trace_with_x0[0], trace[0])) + + +def test_shift(): + A, b = get_sample_problem() + shift = 0.5 + shifted_A = A - shift * np.eye(10) + x1, info1 = minres(A, b, shift=shift) + x2, info2 = minres(shifted_A, b) + assert_equal(info1, 0) + assert_allclose(x1, x2, rtol=1e-5) + + +def test_asymmetric_fail(): + """Asymmetric matrix should raise `ValueError` when check=True""" + A, b = get_sample_problem() + A[1, 2] = 1 + A[2, 1] = 2 + with assert_raises(ValueError): + xp, info = minres(A, b, check=True) + + +def test_minres_non_default_x0(): + rng = np.random.RandomState(1234) + rtol = 1e-6 + a = rng.randn(5, 5) + a = np.dot(a, a.T) + b = rng.randn(5) + c = rng.randn(5) + x = minres(a, b, x0=c, rtol=rtol)[0] + assert norm(a @ x - b) <= rtol * norm(b) + + +def test_minres_precond_non_default_x0(): + rng = np.random.RandomState(12345) + rtol = 1e-6 + a = rng.randn(5, 5) + a = np.dot(a, a.T) + b = rng.randn(5) + c = rng.randn(5) + m = rng.randn(5, 5) + m = np.dot(m, m.T) + x = minres(a, b, M=m, x0=c, rtol=rtol)[0] + assert norm(a @ x - b) <= rtol * norm(b) + + +def test_minres_precond_exact_x0(): + rng = np.random.RandomState(1234) + rtol = 1e-6 + a = np.eye(10) + b = np.ones(10) + c = np.ones(10) + m = rng.randn(10, 10) + m = np.dot(m, m.T) + x = minres(a, b, M=m, x0=c, rtol=rtol)[0] + assert norm(a @ x - b) <= rtol * norm(b) diff --git a/shared/package-files/77/77fdf53be9855158956a68880ea1f46206317249f45518e3d4a9d5142f70dd8b/blob b/shared/package-files/77/77fdf53be9855158956a68880ea1f46206317249f45518e3d4a9d5142f70dd8b/blob new file mode 100644 index 0000000000000000000000000000000000000000..abbdc0345f568934375180b13c7e8bf1bdee46c2 Binary files /dev/null and b/shared/package-files/77/77fdf53be9855158956a68880ea1f46206317249f45518e3d4a9d5142f70dd8b/blob differ diff --git a/shared/package-files/78/7800e9e307be1247e681246d8f3b56ae406189a7742ca7d2e33085e522eab61f/blob b/shared/package-files/78/7800e9e307be1247e681246d8f3b56ae406189a7742ca7d2e33085e522eab61f/blob new file mode 100644 index 0000000000000000000000000000000000000000..0a97def6d00baa18eaffaca73c92d7b6dd2b5e32 --- /dev/null +++ b/shared/package-files/78/7800e9e307be1247e681246d8f3b56ae406189a7742ca7d2e33085e522eab61f/blob @@ -0,0 +1,193 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* chdtr.c + * + * Chi-square distribution + * + * + * + * SYNOPSIS: + * + * double df, x, y, chdtr(); + * + * y = chdtr( df, x ); + * + * + * + * DESCRIPTION: + * + * Returns the area under the left hand tail (from 0 to x) + * of the Chi square probability density function with + * v degrees of freedom. + * + * + * inf. + * - + * 1 | | v/2-1 -t/2 + * P( x | v ) = ----------- | t e dt + * v/2 - | | + * 2 | (v/2) - + * x + * + * where x is the Chi-square variable. + * + * The incomplete Gamma integral is used, according to the + * formula + * + * y = chdtr( v, x ) = igam( v/2.0, x/2.0 ). + * + * + * The arguments must both be positive. + * + * + * + * ACCURACY: + * + * See igam(). + * + * ERROR MESSAGES: + * + * message condition value returned + * chdtr domain x < 0 or v < 1 0.0 + */ +/* chdtrc() + * + * Complemented Chi-square distribution + * + * + * + * SYNOPSIS: + * + * double v, x, y, chdtrc(); + * + * y = chdtrc( v, x ); + * + * + * + * DESCRIPTION: + * + * Returns the area under the right hand tail (from x to + * infinity) of the Chi square probability density function + * with v degrees of freedom: + * + * + * inf. + * - + * 1 | | v/2-1 -t/2 + * P( x | v ) = ----------- | t e dt + * v/2 - | | + * 2 | (v/2) - + * x + * + * where x is the Chi-square variable. + * + * The incomplete Gamma integral is used, according to the + * formula + * + * y = chdtr( v, x ) = igamc( v/2.0, x/2.0 ). + * + * + * The arguments must both be positive. + * + * + * + * ACCURACY: + * + * See igamc(). + * + * ERROR MESSAGES: + * + * message condition value returned + * chdtrc domain x < 0 or v < 1 0.0 + */ +/* chdtri() + * + * Inverse of complemented Chi-square distribution + * + * + * + * SYNOPSIS: + * + * double df, x, y, chdtri(); + * + * x = chdtri( df, y ); + * + * + * + * + * DESCRIPTION: + * + * Finds the Chi-square argument x such that the integral + * from x to infinity of the Chi-square density is equal + * to the given cumulative probability y. + * + * This is accomplished using the inverse Gamma integral + * function and the relation + * + * x/2 = igamci( df/2, y ); + * + * + * + * + * ACCURACY: + * + * See igami.c. + * + * ERROR MESSAGES: + * + * message condition value returned + * chdtri domain y < 0 or y > 1 0.0 + * v < 1 + * + */ + +/* chdtr() */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" + +#include "igam.h" +#include "igami.h" + +namespace xsf { +namespace cephes { + + XSF_HOST_DEVICE inline double chdtrc(double df, double x) { + + if (x < 0.0) + return 1.0; /* modified by T. Oliphant */ + return (igamc(df / 2.0, x / 2.0)); + } + + XSF_HOST_DEVICE inline double chdtr(double df, double x) { + + if ((x < 0.0)) { /* || (df < 1.0) ) */ + set_error("chdtr", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + return (igam(df / 2.0, x / 2.0)); + } + + XSF_HOST_DEVICE double chdtri(double df, double y) { + double x; + + if ((y < 0.0) || (y > 1.0)) { /* || (df < 1.0) ) */ + set_error("chdtri", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + + x = igamci(0.5 * df, y); + return (2.0 * x); + } + +} // namespace cephes +} // namespace xsf diff --git a/shared/package-files/78/7804a7ee9d73950002ac3c94557e77fa82e20bb060946287c17a4eeec1b8f2c4/blob b/shared/package-files/78/7804a7ee9d73950002ac3c94557e77fa82e20bb060946287c17a4eeec1b8f2c4/blob new file mode 100644 index 0000000000000000000000000000000000000000..16b500a5529eacdd272b7e3c38b5f04d9aa678be --- /dev/null +++ b/shared/package-files/78/7804a7ee9d73950002ac3c94557e77fa82e20bb060946287c17a4eeec1b8f2c4/blob @@ -0,0 +1,3243 @@ +import ctypes +import threading +from ctypes import CFUNCTYPE, c_int, c_int32 +from ctypes.util import find_library +import gc +import locale +import os +import platform +import re +import subprocess +import sys +import unittest +from contextlib import contextmanager +from tempfile import mkstemp + +from llvmlite import ir +from llvmlite import binding as llvm +from llvmlite.binding import ffi +from llvmlite.tests import TestCase + +# arvm7l needs extra ABI symbols to link successfully +if platform.machine() == 'armv7l': + llvm.load_library_permanently('libgcc_s.so.1') + + +is_conda_package = unittest.skipUnless(llvm.package_format == "conda", + ("conda package test only, have " + f"{llvm.package_format}")) +is_wheel_package = unittest.skipUnless(llvm.package_format == "wheel", + ("wheel package test only, have " + f"{llvm.package_format}")) + +_HAVE_LIEF = False +try: + import lief # noqa: F401 + _HAVE_LIEF = True +except ImportError: + pass + + +needs_lief = unittest.skipUnless(_HAVE_LIEF, "test needs py-lief package") + + +def no_de_locale(): + cur = locale.setlocale(locale.LC_ALL) + try: + locale.setlocale(locale.LC_ALL, 'de_DE') + except locale.Error: + return True + else: + return False + finally: + locale.setlocale(locale.LC_ALL, cur) + + +asm_sum = r""" + ; ModuleID = '' + source_filename = "asm_sum.c" + target triple = "{triple}" + %struct.glob_type = type {{ i64, [2 x i64]}} + %struct.glob_type_vec = type {{ i64, <2 x i64>}} + + @glob = global i32 0 + @glob_b = global i8 0 + @glob_f = global float 1.5 + @glob_struct = global %struct.glob_type {{i64 0, [2 x i64] [i64 0, i64 0]}} + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + %.4 = add i32 0, %.3 + ret i32 %.4 + }} + """ + +asm_sum2 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + ret i32 %.3 + }} + """ + +asm_sum3 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i64 @sum(i64 %.1, i64 %.2) {{ + %.3 = add i64 %.1, %.2 + %.4 = add i64 5, %.3 + %.5 = add i64 -5, %.4 + ret i64 %.5 + }} + """ + +asm_sum4 = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = add i32 %.1, %.2 + ret i32 0 + }} + """ + +asm_mul = r""" + ; ModuleID = '' + target triple = "{triple}" + @mul_glob = global i32 0 + + define i32 @mul(i32 %.1, i32 %.2) {{ + %.3 = mul i32 %.1, %.2 + ret i32 %.3 + }} + """ + +asm_square_sum = r""" + ; ModuleID = '' + target triple = "{triple}" + @mul_glob = global i32 0 + + declare i32 @sum(i32, i32) + define i32 @square_sum(i32 %.1, i32 %.2) {{ + %.3 = call i32 @sum(i32 %.1, i32 %.2) + %.4 = mul i32 %.3, %.3 + ret i32 %.4 + }} + """ + +asm_getversion = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i8* @Py_GetVersion() + + define void @getversion(i32 %.1, i32 %.2) {{ + %1 = call i8* @Py_GetVersion() + ret void + }} + """ + +if platform.python_implementation() == 'PyPy': + asm_getversion = asm_getversion.replace('Py_GetVersion', 'PyPy_GetVersion') + +# `fadd` used on integer inputs +asm_parse_error = r""" + ; ModuleID = '' + target triple = "{triple}" + + define i32 @sum(i32 %.1, i32 %.2) {{ + %.3 = fadd i32 %.1, %.2 + ret i32 %.3 + }} + """ + +# "%.bug" definition references itself +asm_verification_fail = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @sum() {{ + %.bug = add i32 1, %.bug + ret void + }} + """ + +asm_sum_declare = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i32 @sum(i32 %.1, i32 %.2) + """ + +asm_vararg_declare = r""" + ; ModuleID = '' + target triple = "{triple}" + + declare i32 @vararg(i32 %.1, ...) + """ + +asm_double_inaccurate = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + %const = fadd fp128 0xLF3CB1CCF26FBC178452FB4EC7F91DEAD, 0xL00000000000000000000000000000001 + ret void + }} + """ # noqa E501 + +asm_double_locale = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + %const = fadd double 0.0, 3.14 + ret void + }} + """ + + +asm_inlineasm = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo() {{ + call void asm sideeffect "nop", ""() + ret void + }} + """ + +asm_inlineasm2 = """ + ; ModuleID = '' + target triple = "{triple}" + + define void @inlineme() {{ + ret void + }} + + define i32 @caller(i32 %.1, i32 %.2) {{ + entry: + %stack = alloca i32 + store i32 %.1, i32* %stack + br label %main + main: + %loaded = load i32, i32* %stack + %.3 = add i32 %loaded, %.2 + %.4 = add i32 0, %.3 + call void @inlineme() + ret i32 %.4 + }} +""" + +asm_inlineasm3 = """ +; ModuleID = 'test.c' +source_filename = "test.c" +target triple = "{triple}" + +; Function Attrs: noinline nounwind optnone ssp uwtable +define void @inlineme() noinline !dbg !15 {{ + ret void, !dbg !18 +}} + +; Function Attrs: noinline nounwind optnone ssp uwtable +define i32 @foo(i32 %0, i32 %1) !dbg !19 {{ + %3 = alloca i32, align 4 + %4 = alloca i32, align 4 + store i32 %0, i32* %3, align 4 + call void @llvm.dbg.declare(metadata i32* %3, metadata !23, metadata !DIExpression()), !dbg !24 + store i32 %1, i32* %4, align 4 + call void @llvm.dbg.declare(metadata i32* %4, metadata !25, metadata !DIExpression()), !dbg !26 + call void @inlineme(), !dbg !27 + %5 = load i32, i32* %3, align 4, !dbg !28 + %6 = load i32, i32* %4, align 4, !dbg !29 + %7 = add nsw i32 %5, %6, !dbg !30 + ret i32 %7, !dbg !31 +}} + +; Function Attrs: nofree nosync nounwind readnone speculatable willreturn +declare void @llvm.dbg.declare(metadata, metadata, metadata) #1 + +attributes #1 = {{ nofree nosync nounwind readnone speculatable willreturn }} + +!llvm.module.flags = !{{!1, !2, !3, !4, !5, !6, !7, !8, !9, !10}} +!llvm.dbg.cu = !{{!11}} +!llvm.ident = !{{!14}} + +!0 = !{{i32 2, !"SDK Version", [2 x i32] [i32 12, i32 3]}} +!1 = !{{i32 7, !"Dwarf Version", i32 4}} +!2 = !{{i32 2, !"Debug Info Version", i32 3}} +!3 = !{{i32 1, !"wchar_size", i32 4}} +!4 = !{{i32 1, !"branch-target-enforcement", i32 0}} +!5 = !{{i32 1, !"sign-return-address", i32 0}} +!6 = !{{i32 1, !"sign-return-address-all", i32 0}} +!7 = !{{i32 1, !"sign-return-address-with-bkey", i32 0}} +!8 = !{{i32 7, !"PIC Level", i32 2}} +!9 = !{{i32 7, !"uwtable", i32 1}} +!10 = !{{i32 7, !"frame-pointer", i32 1}} +!11 = distinct !DICompileUnit(language: DW_LANG_C99, file: !12, producer: "Apple clang version 13.1.6 (clang-1316.0.21.2.3)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !13, splitDebugInlining: false, nameTableKind: None, sysroot: "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk", sdk: "MacOSX.sdk") +!12 = !DIFile(filename: "test.c", directory: "/") +!13 = !{{}} +!14 = !{{!"Apple clang version 13.1.6 (clang-1316.0.21.2.3)"}} +!15 = distinct !DISubprogram(name: "inlineme", scope: !12, file: !12, line: 1, type: !16, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13) +!16 = !DISubroutineType(types: !17) +!17 = !{{null}} +!18 = !DILocation(line: 1, column: 22, scope: !15) +!19 = distinct !DISubprogram(name: "foo", scope: !12, file: !12, line: 3, type: !20, scopeLine: 3, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13) +!20 = !DISubroutineType(types: !21) +!21 = !{{!22, !22, !22}} +!22 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) +!23 = !DILocalVariable(name: "a", arg: 1, scope: !19, file: !12, line: 3, type: !22) +!24 = !DILocation(line: 3, column: 13, scope: !19) +!25 = !DILocalVariable(name: "b", arg: 2, scope: !19, file: !12, line: 3, type: !22) +!26 = !DILocation(line: 3, column: 20, scope: !19) +!27 = !DILocation(line: 4, column: 5, scope: !19) +!28 = !DILocation(line: 5, column: 12, scope: !19) +!29 = !DILocation(line: 5, column: 16, scope: !19) +!30 = !DILocation(line: 5, column: 14, scope: !19) +!31 = !DILocation(line: 5, column: 5, scope: !19) +""" # noqa E501 + +licm_asm = r""" +; ModuleID = "" +target triple = "{triple}" + +define double @licm(i32 %0) {{ + %2 = alloca i32, align 4 + %3 = alloca double, align 8 + %4 = alloca i32, align 4 + %5 = alloca double, align 8 + store i32 %0, i32* %2, align 4 + store double 0.000000e+00, double* %3, align 8 + store i32 0, i32* %4, align 4 + br label %6 + +6: ; preds = %14, %1 + %7 = load i32, i32* %4, align 4 + %8 = load i32, i32* %2, align 4 + %9 = icmp slt i32 %7, %8 + br i1 %9, label %10, label %17 + +10: ; preds = %6 + store double 7.000000e+00, double* %5, align 8 + %11 = load double, double* %5, align 8 + %12 = load double, double* %3, align 8 + %13 = fadd double %12, %11 + store double %13, double* %3, align 8 + br label %14 + +14: ; preds = %10 + %15 = load i32, i32* %4, align 4 + %16 = add nsw i32 %15, 1 + store i32 %16, i32* %4, align 4 + br label %6 + +17: ; preds = %6 + %18 = load double, double* %3, align 8 + ret double %18 +}} +""" # noqa E501 + +asm_global_ctors = r""" + ; ModuleID = "" + target triple = "{triple}" + + @A = global i32 undef + + define void @ctor_A() + {{ + store i32 10, i32* @A + ret void + }} + + define void @dtor_A() + {{ + store i32 20, i32* @A + ret void + }} + + define i32 @foo() + {{ + %.2 = load i32, i32* @A + %.3 = add i32 %.2, 2 + ret i32 %.3 + }} + + @llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}] + @llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}] + """ # noqa E501 + +asm_ext_ctors = r""" + ; ModuleID = "" + target triple = "{triple}" + + @A = external global i32 + + define void @ctor_A() + {{ + store i32 10, i32* @A + ret void + }} + + define void @dtor_A() + {{ + store i32 20, i32* @A + ret void + }} + + define i32 @foo() + {{ + %.2 = load i32, i32* @A + %.3 = add i32 %.2, 2 + ret i32 %.3 + }} + + @llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}] + @llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}] + """ # noqa E501 + + +asm_nonalphanum_blocklabel = """; ModuleID = "" +target triple = "unknown-unknown-unknown" +target datalayout = "" + +define i32 @"foo"() +{ +"<>!*''#": + ret i32 12345 +} +""" # noqa W291 # trailing space needed for match later + + +asm_null_constant = r""" + ; ModuleID = '' + target triple = "{triple}" + + define void @foo(i64* %.1) {{ + ret void + }} + + define void @bar() {{ + call void @foo(i64* null) + ret void + }} +""" + + +riscv_asm_ilp32 = [ + 'addi\tsp, sp, -16', + 'sw\ta1, 8(sp)', + 'sw\ta2, 12(sp)', + 'fld\tfa5, 8(sp)', + 'fmv.w.x\tfa4, a0', + 'fcvt.d.s\tfa4, fa4', + 'fadd.d\tfa5, fa4, fa5', + 'fsd\tfa5, 8(sp)', + 'lw\ta0, 8(sp)', + 'lw\ta1, 12(sp)', + 'addi\tsp, sp, 16', + 'ret' +] + + +riscv_asm_ilp32f = [ + 'addi\tsp, sp, -16', + 'sw\ta0, 8(sp)', + 'sw\ta1, 12(sp)', + 'fld\tfa5, 8(sp)', + 'fcvt.d.s\tfa4, fa0', + 'fadd.d\tfa5, fa4, fa5', + 'fsd\tfa5, 8(sp)', + 'lw\ta0, 8(sp)', + 'lw\ta1, 12(sp)', + 'addi\tsp, sp, 16', + 'ret' +] + + +riscv_asm_ilp32d = [ + 'fcvt.d.s\tfa5, fa0', + 'fadd.d\tfa0, fa5, fa1', + 'ret' +] + + +asm_attributes = r""" +declare void @a_readonly_func(i8 *) readonly + +declare i8* @a_arg0_return_func(i8* returned, i32*) +""" + +asm_alloca_optnone = r""" +define double @foo(i32 %i, double %j) optnone noinline { + %I = alloca i32 ; [#uses=4] + %J = alloca double ; [#uses=2] + store i32 %i, i32* %I + store double %j, double* %J + %t1 = load i32, i32* %I ; [#uses=1] + %t2 = add i32 %t1, 1 ; [#uses=1] + store i32 %t2, i32* %I + %t3 = load i32, i32* %I ; [#uses=1] + %t4 = sitofp i32 %t3 to double ; [#uses=1] + %t5 = load double, double* %J ; [#uses=1] + %t6 = fmul double %t4, %t5 ; [#uses=1] + ret double %t6 +} +""" + +# A strided store loop: at O3 LLVM emits a "vector.body" block; optsize/minsize +# inhibit the vectoriser so no "vector.body" is created. +asm_vectorize = r""" + ; ModuleID = '' + + define void @stride1(ptr noalias %B, i32 %BStride) {{ + entry: + br label %for.body + + for.body: + %iv = phi i32 [ %iv.next, %for.body ], [ 0, %entry ] + %mulB = mul nsw i32 %iv, %BStride + %gepOfB = getelementptr inbounds i16, ptr %B, i32 %mulB + store i16 42, ptr %gepOfB, align 4 + %iv.next = add nuw nsw i32 %iv, 1 + %exitcond = icmp eq i32 %iv.next, 1025 + br i1 %exitcond, label %for.end, label %for.body + + for.end: + ret void + }} + """ + +asm_declaration = r""" +declare void @test_declare(i32* ) +""" + +# This produces the following output from objdump: +# +# $ objdump -D 632.elf +# +# 632.elf: file format elf64-x86-64 +# +# +# Disassembly of section .text: +# +# 0000000000000000 <__arybo>: +# 0: 48 c1 e2 20 shl $0x20,%rdx +# 4: 48 09 c2 or %rax,%rdx +# 7: 48 89 d0 mov %rdx,%rax +# a: 48 c1 c0 3d rol $0x3d,%rax +# e: 48 31 d0 xor %rdx,%rax +# 11: 48 b9 01 20 00 04 80 movabs $0x7010008004002001,%rcx +# 18: 00 10 70 +# 1b: 48 0f af c8 imul %rax,%rcx + +issue_632_elf = \ + "7f454c4602010100000000000000000001003e00010000000000000000000000000000" \ + "0000000000e0000000000000000000000040000000000040000500010048c1e2204809" \ + "c24889d048c1c03d4831d048b90120000480001070480fafc800000000000000000000" \ + "0000000000000000000000000000002f0000000400f1ff000000000000000000000000" \ + "00000000070000001200020000000000000000001f00000000000000002e7465787400" \ + "5f5f617279626f002e6e6f74652e474e552d737461636b002e737472746162002e7379" \ + "6d746162003c737472696e673e00000000000000000000000000000000000000000000" \ + "0000000000000000000000000000000000000000000000000000000000000000000000" \ + "00000000000000001f0000000300000000000000000000000000000000000000a80000" \ + "0000000000380000000000000000000000000000000100000000000000000000000000" \ + "000001000000010000000600000000000000000000000000000040000000000000001f" \ + "000000000000000000000000000000100000000000000000000000000000000f000000" \ + "01000000000000000000000000000000000000005f0000000000000000000000000000" \ + "0000000000000000000100000000000000000000000000000027000000020000000000" \ + "0000000000000000000000000000600000000000000048000000000000000100000002" \ + "00000008000000000000001800000000000000" + + +issue_632_text = \ + "48c1e2204809c24889d048c1c03d4831d048b90120000480001070480fafc8" + + +asm_tli_exp2 = r""" +; ModuleID = '' +source_filename = "" +target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-pc-windows-msvc" + +declare float @llvm.exp2.f32(float %casted) + +define float @foo(i16 %arg) { +entry: + %casted = sitofp i16 %arg to float + %ret = call float @llvm.exp2.f32(float %casted) + ret float %ret +} +""" # noqa E501 + +asm_phi_blocks = r""" +; ModuleID = '' +target triple = "{triple}" + +define void @foo(i32 %N) {{ + ; unnamed block for testing + %cmp4 = icmp sgt i32 %N, 0 + br i1 %cmp4, label %for.body, label %for.cond.cleanup + +for.cond.cleanup: + ret void + +for.body: + %i.05 = phi i32 [ %inc, %for.body ], [ 0, %0 ] + %inc = add nuw nsw i32 %i.05, 1 + %exitcond.not = icmp eq i32 %inc, %N + br i1 %exitcond.not, label %for.cond.cleanup, label %for.body +}} +""" + +asm_cpp_class = r""" +; Source C++ +;----------------------------------------- +; class MyClass; +; +; class MyClassDefined{ +; MyClass *member; +; MyClass *m2; +; MyClass *m3; +; }; +; +; void foo(MyClass *c, MyClassDefined){ } +;----------------------------------------- +; LLVM-IR by: clang -arch arm64 -S -emit-llvm file.cpp +; ModuleID = 'file.cpp' +source_filename = "class.cpp" +target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128" +target triple = "arm64-apple-macosx13.3.0" + +%class.MyClass = type opaque +%class.MyClassDefined = type { %class.MyClass*, %class.MyClass*, %class.MyClass* } + +; Function Attrs: noinline nounwind optnone ssp uwtable(sync) +define void @_Z3fooP7MyClass14MyClassDefined(%class.MyClass* noundef %0, %class.MyClassDefined* noundef %1) { + %3 = alloca %class.MyClass*, align 8 + store %class.MyClass* %0, %class.MyClass** %3, align 8 + ret void +} + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!llvm.ident = !{!9} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 13, i32 3]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 8, !"branch-target-enforcement", i32 0} +!3 = !{i32 8, !"sign-return-address", i32 0} +!4 = !{i32 8, !"sign-return-address-all", i32 0} +!5 = !{i32 8, !"sign-return-address-with-bkey", i32 0} +!6 = !{i32 7, !"PIC Level", i32 2} +!7 = !{i32 7, !"uwtable", i32 1} +!8 = !{i32 7, !"frame-pointer", i32 1} +!9 = !{!"Apple clang version 14.0.3 (clang-1403.0.22.14.1)"} + +""" # noqa + +asm_cpp_vector = r"""; Source C++ +;----------------------------------------- + +; struct Vector2D{ +; float x, y; +; }; +; +; void foo(Vector2D vec, Vector2D *out) { +; *out = vec; +; } +;----------------------------------------- +; LLVM-IR by: clang -arch x86_64 -S -emit-llvm file.cpp +; ModuleID = 'file.cpp' +source_filename = "class.cpp" +target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-apple-macosx13.3.0" + +%struct.Vector2D = type { float, float } + +; Function Attrs: noinline nounwind optnone ssp uwtable +define void @_Z3foo8Vector2DPS_(<2 x float> %0, %struct.Vector2D* noundef %1) #0 { + %3 = alloca %struct.Vector2D, align 4 + %4 = alloca %struct.Vector2D*, align 8 + %5 = bitcast %struct.Vector2D* %3 to <2 x float>* + store <2 x float> %0, <2 x float>* %5, align 4 + store %struct.Vector2D* %1, %struct.Vector2D** %4, align 8 + %6 = load %struct.Vector2D*, %struct.Vector2D** %4, align 8 + %7 = bitcast %struct.Vector2D* %6 to i8* + %8 = bitcast %struct.Vector2D* %3 to i8* + call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 %7, i8* align 4 %8, i64 8, i1 false) + ret void +} + +; Function Attrs: argmemonly nofree nounwind willreturn +declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture writeonly, i8* noalias nocapture readonly, i64, i1 immarg) #1 + +attributes #0 = { noinline nounwind optnone ssp uwtable "darwin-stkchk-strong-link" "frame-pointer"="all" "min-legal-vector-width"="64" "no-trapping-math"="true" "probe-stack"="___chkstk_darwin" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "tune-cpu"="generic" } +attributes #1 = { argmemonly nofree nounwind willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4} +!llvm.ident = !{!5} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 13, i32 3]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"PIC Level", i32 2} +!3 = !{i32 7, !"uwtable", i32 2} +!4 = !{i32 7, !"frame-pointer", i32 2} +!5 = !{!"Apple clang version 14.0.3 (clang-1403.0.22.14.1)"} + +""" # noqa + + +class BaseTest(TestCase): + + def setUp(self): + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + gc.collect() + self.old_garbage = gc.garbage[:] + gc.garbage[:] = [] + + def tearDown(self): + # Test that no uncollectable objects were created + # (llvmlite objects have a __del__ so a reference cycle could + # create some). + gc.collect() + self.assertEqual(gc.garbage, []) + # This will probably put any existing garbage in gc.garbage again + del self.old_garbage + + def module(self, asm=asm_sum, context=None): + asm = asm.format(triple=llvm.get_default_triple()) + mod = llvm.parse_assembly(asm, context) + return mod + + def glob(self, name='glob', mod=None): + if mod is None: + mod = self.module() + return mod.get_global_variable(name) + + def target_machine(self, *, jit): + target = llvm.Target.from_default_triple() + return target.create_target_machine(jit=jit) + + +class TestDependencies(BaseTest): + """ + Test DLL dependencies are within a certain expected set. + """ + + @unittest.skipUnless(sys.platform.startswith('linux'), + "Linux-specific test") + @unittest.skipUnless(os.environ.get('LLVMLITE_DIST_TEST'), + "Distribution-specific test") + def test_linux(self): + lib_path = ffi.lib._name + env = os.environ.copy() + env['LANG'] = 'C' + p = subprocess.Popen(["objdump", "-p", lib_path], + stdout=subprocess.PIPE, env=env) + out, _ = p.communicate() + self.assertEqual(0, p.returncode) + # Parse library dependencies + lib_pat = re.compile(r'^([+-_a-zA-Z0-9]+)\.so(?:\.\d+){0,3}$') + deps = set() + for line in out.decode().splitlines(): + parts = line.split() + if parts and parts[0] == 'NEEDED': + dep = parts[1] + m = lib_pat.match(dep) + if len(parts) != 2 or not m: + self.fail("invalid NEEDED line: %r" % (line,)) + deps.add(m.group(1)) + # Sanity check that our dependencies were parsed ok + if 'libc' not in deps or 'libpthread' not in deps: + self.fail("failed parsing dependencies? got %r" % (deps,)) + # Ensure all dependencies are expected + allowed = set(['librt', 'libdl', 'libpthread', 'libz', 'libm', + 'libgcc_s', 'libc', 'ld-linux', 'ld64', 'libzstd', + 'libstdc++']) + if platform.python_implementation() == 'PyPy': + allowed.add('libtinfo') + + fails = [] + for dep in deps: + if not dep.startswith('ld-linux-') and dep not in allowed: + fails.append(dep) + if len(fails) == 1: + self.fail("unexpected dependency %r in %r" % (fails[0], deps)) + elif len(fails) > 1: + self.fail("unexpected dependencies %r in %r" % (fails, deps)) + else: + pass # test passes + + +class TestRISCVABI(BaseTest): + """ + Test calling convention of floating point arguments of RISC-V + using different ABI. + """ + triple = "riscv32-unknown-linux" + + def setUp(self): + super().setUp() + llvm.initialize_all_targets() + llvm.initialize_all_asmprinters() + + def check_riscv_target(self): + try: + llvm.Target.from_triple(self.triple) + except RuntimeError as e: + if "No available targets are compatible with triple" in str(e): + self.skipTest("RISCV target unsupported by linked LLVM.") + else: + raise e + + def riscv_target_machine(self, **kwarg): + lltarget = llvm.Target.from_triple(self.triple) + return lltarget.create_target_machine(**kwarg) + + def fpadd_ll_module(self): + f64 = ir.DoubleType() + f32 = ir.FloatType() + fnty = ir.FunctionType(f64, (f32, f64)) + module = ir.Module() + func = ir.Function(module, fnty, name="fpadd") + block = func.append_basic_block() + builder = ir.IRBuilder(block) + a, b = func.args + arg0 = builder.fpext(a, f64) + result = builder.fadd(arg0, b) + builder.ret(result) + + llmod = llvm.parse_assembly(str(module)) + llmod.verify() + return llmod + + def break_up_asm(self, asm): + asm_list = [] + for line in asm.splitlines(): + s_line = line.strip() + if not (s_line.startswith(".") or s_line.startswith("fpadd") + or s_line == ""): + asm_list.append(s_line) + return asm_list + + def test_rv32d_ilp32(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32) + + def test_rv32d_ilp32f(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32f") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32f) + + def test_rv32d_ilp32d(self): + self.check_riscv_target() + llmod = self.fpadd_ll_module() + target = self.riscv_target_machine(features="+f,+d", abiname="ilp32d") + self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)), + riscv_asm_ilp32d) + + +class TestMisc(BaseTest): + """ + Test miscellaneous functions in llvm.binding. + """ + + def test_parse_assembly(self): + self.module(asm_sum) + + def test_parse_assembly_error(self): + with self.assertRaises(RuntimeError) as cm: + self.module(asm_parse_error) + s = str(cm.exception) + self.assertIn("parsing error", s) + self.assertIn("invalid operand type", s) + + def test_nonalphanum_block_name(self): + mod = ir.Module() + ft = ir.FunctionType(ir.IntType(32), []) + fn = ir.Function(mod, ft, "foo") + bd = ir.IRBuilder(fn.append_basic_block(name="<>!*''#")) + bd.ret(ir.Constant(ir.IntType(32), 12345)) + asm = str(mod) + self.assertEqual(asm, asm_nonalphanum_blocklabel) + + def test_global_context(self): + gcontext1 = llvm.context.get_global_context() + gcontext2 = llvm.context.get_global_context() + assert gcontext1 == gcontext2 + + def test_dylib_symbols(self): + llvm.add_symbol("__xyzzy", 1234) + llvm.add_symbol("__xyzzy", 5678) + addr = llvm.address_of_symbol("__xyzzy") + self.assertEqual(addr, 5678) + addr = llvm.address_of_symbol("__foobar") + self.assertIs(addr, None) + + def test_get_default_triple(self): + triple = llvm.get_default_triple() + self.assertIsInstance(triple, str) + self.assertTrue(triple) + + def test_get_process_triple(self): + # Sometimes we get synonyms for PPC + def normalize_ppc(arch): + if arch == 'powerpc64le': + return 'ppc64le' + else: + return arch + + triple = llvm.get_process_triple() + default = llvm.get_default_triple() + self.assertIsInstance(triple, str) + self.assertTrue(triple) + + default_arch = normalize_ppc(default.split('-')[0]) + triple_arch = normalize_ppc(triple.split('-')[0]) + # Arch must be equal + self.assertEqual(default_arch, triple_arch) + + def test_get_host_cpu_features(self): + features = llvm.get_host_cpu_features() + # Check the content of `features` + self.assertIsInstance(features, dict) + self.assertIsInstance(features, llvm.FeatureMap) + for k, v in features.items(): + self.assertIsInstance(k, str) + self.assertTrue(k) # single feature string cannot be empty + self.assertIsInstance(v, bool) + self.assertIsInstance(features.flatten(), str) + + re_term = r"[+\-][a-zA-Z0-9\._-]+" + regex = r"^({0}|{0}(,{0})*)?$".format(re_term) + # quick check for our regex + self.assertIsNotNone(re.match(regex, "")) + self.assertIsNotNone(re.match(regex, "+aa")) + self.assertIsNotNone(re.match(regex, "+a,-bb")) + # check CpuFeature.flatten() + if len(features) == 0: + self.assertEqual(features.flatten(), "") + else: + self.assertIsNotNone(re.match(regex, features.flatten())) + + def test_get_host_cpu_name(self): + cpu = llvm.get_host_cpu_name() + self.assertIsInstance(cpu, str) + self.assertTrue(cpu) + + def test_initfini(self): + code = """if 1: + from llvmlite import binding as llvm + + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + llvm.initialize_all_targets() + llvm.initialize_all_asmprinters() + llvm.shutdown() + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_deprecated_init(self): + regex = r"llvmlite.binding.initialize\(\) is deprecated" + with self.assertRaisesRegex(RuntimeError, expected_regex=regex): + llvm.initialize() + + def test_set_option(self): + # We cannot set an option multiple times (LLVM would exit() the + # process), so run the code in a subprocess. + code = """if 1: + from llvmlite import binding as llvm + + llvm.set_option("progname", "-debug-pass=Disabled") + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_version(self): + major, minor, patch = llvm.llvm_version_info + # one of these can be valid + valid = (22,) + self.assertIn(major, valid) + self.assertIn(patch, range(9)) + + def test_check_jit_execution(self): + llvm.check_jit_execution() + + @unittest.skipIf(no_de_locale(), "Locale not available") + def test_print_double_locale(self): + m = self.module(asm_double_locale) + expect = str(m) + # Change the locale so that comma is used as decimal-point + # to trigger the LLVM bug (llvmlite issue #80) + locale.setlocale(locale.LC_ALL, 'de_DE') + # The LLVM bug is trigged by print the module with double constant + got = str(m) + # Changing the locale should not affect the LLVM IR + self.assertEqual(expect, got) + + def test_no_accidental_warnings(self): + code = "from llvmlite import binding" + flags = "-Werror" + cmdargs = [sys.executable, flags, "-c", code] + subprocess.check_call(cmdargs) + + +class TestModuleRef(BaseTest): + + def test_str(self): + mod = self.module() + s = str(mod).strip() + self.assertTrue(s.startswith('; ModuleID ='), s) + + def test_close(self): + mod = self.module() + str(mod) + mod.close() + with self.assertRaises(ctypes.ArgumentError): + str(mod) + mod.close() + + def test_with(self): + mod = self.module() + str(mod) + with mod: + str(mod) + with self.assertRaises(ctypes.ArgumentError): + str(mod) + with self.assertRaises(RuntimeError): + with mod: + pass + + def test_name(self): + mod = self.module() + mod.name = "foo" + self.assertEqual(mod.name, "foo") + mod.name = "bar" + self.assertEqual(mod.name, "bar") + + def test_source_file(self): + mod = self.module() + self.assertEqual(mod.source_file, "asm_sum.c") + + def test_data_layout(self): + mod = self.module() + s = mod.data_layout + self.assertIsInstance(s, str) + mod.data_layout = s + self.assertEqual(s, mod.data_layout) + + def test_triple(self): + mod = self.module() + s = mod.triple + self.assertEqual(s, llvm.get_default_triple()) + mod.triple = '' + self.assertEqual(mod.triple, '') + + def test_verify(self): + # Verify successful + mod = self.module() + self.assertIs(mod.verify(), None) + # Verify failed + mod = self.module(asm_verification_fail) + with self.assertRaises(RuntimeError) as cm: + mod.verify() + s = str(cm.exception) + self.assertIn("%.bug = add i32 1, %.bug", s) + + def test_get_function(self): + mod = self.module() + fn = mod.get_function("sum") + self.assertIsInstance(fn, llvm.ValueRef) + self.assertEqual(fn.name, "sum") + + with self.assertRaises(NameError): + mod.get_function("foo") + + # Check that fn keeps the module instance alive + del mod + str(fn.module) + + def test_get_struct_type(self): + mod = self.module() + st_ty = mod.get_struct_type("struct.glob_type") + self.assertEqual(st_ty.name, "struct.glob_type") + # also match struct names of form "%struct.glob_type.{some_index}" + self.assertIsNotNone(re.match( + r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }', + str(st_ty))) + + with self.assertRaises(NameError): + mod.get_struct_type("struct.doesnt_exist") + + def test_get_global_variable(self): + mod = self.module() + gv = mod.get_global_variable("glob") + self.assertIsInstance(gv, llvm.ValueRef) + self.assertEqual(gv.name, "glob") + + with self.assertRaises(NameError): + mod.get_global_variable("bar") + + # Check that gv keeps the module instance alive + del mod + str(gv.module) + + def test_global_variables(self): + mod = self.module() + it = mod.global_variables + del mod + globs = sorted(it, key=lambda value: value.name) + self.assertEqual(len(globs), 4) + self.assertEqual([g.name for g in globs], + ["glob", "glob_b", "glob_f", "glob_struct"]) + + def test_functions(self): + mod = self.module() + it = mod.functions + del mod + funcs = list(it) + self.assertEqual(len(funcs), 1) + self.assertEqual(funcs[0].name, "sum") + + def test_structs(self): + mod = self.module() + it = mod.struct_types + del mod + structs = list(it) + self.assertEqual(len(structs), 1) + self.assertIsNotNone(re.match(r'struct\.glob_type(\.[\d]+)?', + structs[0].name)) + self.assertIsNotNone(re.match( + r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }', + str(structs[0]))) + + def test_link_in(self): + dest = self.module() + src = self.module(asm_mul) + dest.link_in(src) + self.assertEqual( + sorted(f.name for f in dest.functions), ["mul", "sum"]) + dest.get_function("mul") + dest.close() + with self.assertRaises(ctypes.ArgumentError): + src.get_function("mul") + + def test_link_in_preserve(self): + dest = self.module() + src2 = self.module(asm_mul) + dest.link_in(src2, preserve=True) + self.assertEqual( + sorted(f.name for f in dest.functions), ["mul", "sum"]) + dest.close() + self.assertEqual(sorted(f.name for f in src2.functions), ["mul"]) + src2.get_function("mul") + + def test_link_in_error(self): + # Raise an error by trying to link two modules with the same global + # definition "sum". + dest = self.module() + src = self.module(asm_sum2) + with self.assertRaises(RuntimeError) as cm: + dest.link_in(src) + self.assertIn("symbol multiply defined", str(cm.exception)) + + def test_as_bitcode(self): + mod = self.module() + bc = mod.as_bitcode() + # Refer to http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00064 # noqa E501 + # and http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00092 # noqa E501 + bitcode_wrapper_magic = b'\xde\xc0\x17\x0b' + bitcode_magic = b'BC' + self.assertTrue(bc.startswith(bitcode_magic) or + bc.startswith(bitcode_wrapper_magic)) + + def test_parse_bitcode_error(self): + with self.assertRaises(RuntimeError) as cm: + llvm.parse_bitcode(b"") + self.assertIn("LLVM bitcode parsing error", str(cm.exception)) + self.assertIn( + "file too small to contain bitcode header", str(cm.exception), + ) + + def test_bitcode_roundtrip(self): + # create a new context to avoid struct renaming + context1 = llvm.create_context() + bc = self.module(context=context1).as_bitcode() + context2 = llvm.create_context() + mod = llvm.parse_bitcode(bc, context2) + self.assertEqual(mod.as_bitcode(), bc) + + mod.get_function("sum") + mod.get_global_variable("glob") + + def test_cloning(self): + m = self.module() + cloned = m.clone() + self.assertIsNot(cloned, m) + self.assertEqual(cloned.as_bitcode(), m.as_bitcode()) + + +class JITTestMixin(object): + """ + Mixin for ExecutionEngine tests. + """ + + def get_sum(self, ee, func_name="sum"): + ee.finalize_object() + cfptr = ee.get_function_address(func_name) + self.assertTrue(cfptr) + return CFUNCTYPE(c_int, c_int, c_int)(cfptr) + + def test_run_code(self): + mod = self.module() + with self.jit(mod) as ee: + cfunc = self.get_sum(ee) + res = cfunc(2, -5) + self.assertEqual(-3, res) + + def test_close(self): + ee = self.jit(self.module()) + ee.close() + ee.close() + with self.assertRaises(ctypes.ArgumentError): + ee.finalize_object() + + def test_with(self): + ee = self.jit(self.module()) + with ee: + pass + with self.assertRaises(RuntimeError): + with ee: + pass + with self.assertRaises(ctypes.ArgumentError): + ee.finalize_object() + + def test_module_lifetime(self): + mod = self.module() + ee = self.jit(mod) + ee.close() + mod.close() + + def test_module_lifetime2(self): + mod = self.module() + ee = self.jit(mod) + mod.close() + ee.close() + + def test_add_module(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + with self.assertRaises(KeyError): + ee.add_module(mod) + self.assertFalse(mod.closed) + ee.close() + self.assertTrue(mod.closed) + + def test_add_module_lifetime(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + mod.close() + ee.close() + + def test_add_module_lifetime2(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + ee.close() + mod.close() + + def test_remove_module(self): + ee = self.jit(self.module()) + mod = self.module(asm_mul) + ee.add_module(mod) + ee.remove_module(mod) + with self.assertRaises(KeyError): + ee.remove_module(mod) + self.assertFalse(mod.closed) + ee.close() + self.assertFalse(mod.closed) + + def test_target_data(self): + mod = self.module() + ee = self.jit(mod) + td = ee.target_data + # A singleton is returned + self.assertIs(ee.target_data, td) + str(td) + del mod, ee + str(td) + + def test_target_data_abi_enquiries(self): + mod = self.module() + ee = self.jit(mod) + td = ee.target_data + gv_i32 = mod.get_global_variable("glob") + gv_i8 = mod.get_global_variable("glob_b") + gv_struct = mod.get_global_variable("glob_struct") + # A global is a pointer, it has the ABI size of a pointer + pointer_size = 4 if sys.maxsize < 2 ** 32 else 8 + for g in (gv_i32, gv_i8, gv_struct): + self.assertEqual(td.get_abi_size(g.type), pointer_size) + + self.assertEqual(td.get_abi_size(gv_i32.global_value_type), 4) + self.assertEqual(td.get_abi_alignment(gv_i32.global_value_type), 4) + + self.assertEqual(td.get_abi_size(gv_i8.global_value_type), 1) + self.assertIn(td.get_abi_alignment(gv_i8.global_value_type), (1, 2, 4)) + + self.assertEqual(td.get_abi_size(gv_struct.global_value_type), 24) + self.assertIn(td.get_abi_alignment(gv_struct.global_value_type), (4, 8)) + + def test_object_cache_notify(self): + notifies = [] + + def notify(mod, buf): + notifies.append((mod, buf)) + + mod = self.module() + ee = self.jit(mod) + ee.set_object_cache(notify) + + self.assertEqual(len(notifies), 0) + cfunc = self.get_sum(ee) + cfunc(2, -5) + self.assertEqual(len(notifies), 1) + # The right module object was found + self.assertIs(notifies[0][0], mod) + self.assertIsInstance(notifies[0][1], bytes) + + notifies[:] = [] + mod2 = self.module(asm_mul) + ee.add_module(mod2) + cfunc = self.get_sum(ee, "mul") + self.assertEqual(len(notifies), 1) + # The right module object was found + self.assertIs(notifies[0][0], mod2) + self.assertIsInstance(notifies[0][1], bytes) + + def test_object_cache_getbuffer(self): + notifies = [] + getbuffers = [] + + def notify(mod, buf): + notifies.append((mod, buf)) + + def getbuffer(mod): + getbuffers.append(mod) + + mod = self.module() + ee = self.jit(mod) + ee.set_object_cache(notify, getbuffer) + + # First return None from getbuffer(): the object is compiled normally + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 0) + cfunc = self.get_sum(ee) + self.assertEqual(len(notifies), 1) + self.assertEqual(len(getbuffers), 1) + self.assertIs(getbuffers[0], mod) + sum_buffer = notifies[0][1] + + # Recreate a new EE, and use getbuffer() to return the previously + # compiled object. + + def getbuffer_successful(mod): + getbuffers.append(mod) + return sum_buffer + + notifies[:] = [] + getbuffers[:] = [] + # Use another source module to make sure it is ignored + mod = self.module(asm_mul) + ee = self.jit(mod) + ee.set_object_cache(notify, getbuffer_successful) + + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 0) + cfunc = self.get_sum(ee) + self.assertEqual(cfunc(2, -5), -3) + self.assertEqual(len(notifies), 0) + self.assertEqual(len(getbuffers), 1) + + +class JITWithTMTestMixin(JITTestMixin): + + def test_emit_assembly(self): + """Test TargetMachineRef.emit_assembly()""" + target_machine = self.target_machine(jit=True) + mod = self.module() + ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive + raw_asm = target_machine.emit_assembly(mod) + self.assertIn("sum", raw_asm) + target_machine.set_asm_verbosity(True) + raw_asm_verbose = target_machine.emit_assembly(mod) + self.assertIn("sum", raw_asm) + self.assertNotEqual(raw_asm, raw_asm_verbose) + + def test_emit_object(self): + """Test TargetMachineRef.emit_object()""" + target_machine = self.target_machine(jit=True) + mod = self.module() + ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive + code_object = target_machine.emit_object(mod) + self.assertIsInstance(code_object, bytes) + if sys.platform.startswith('linux'): + # Sanity check + self.assertIn(b"ELF", code_object[:10]) + + +class TestMCJit(BaseTest, JITWithTMTestMixin): + """ + Test JIT engines created with create_mcjit_compiler(). + """ + + def jit(self, mod, target_machine=None): + if target_machine is None: + target_machine = self.target_machine(jit=True) + return llvm.create_mcjit_compiler(mod, target_machine) + + +# There are some memory corruption issues with OrcJIT on AArch64 - see Issue +# #1000. Since OrcJIT is experimental, and we don't test regularly during +# llvmlite development on non-x86 platforms, it seems safest to skip these +# tests on non-x86 platforms. +# After LLVM20 upgrades skip on X86 too as ORCJit complains about missing +# JITDyLib symbol. +# TODO: Investigate this further. +@unittest.skip("OrcJIT support is experimental") +class TestOrcLLJIT(BaseTest): + + def jit(self, asm=asm_sum, func_name="sum", target_machine=None, + add_process=False, func_type=CFUNCTYPE(c_int, c_int, c_int), + suppress_errors=False): + lljit = llvm.create_lljit_compiler(target_machine, + use_jit_link=False, + suppress_errors=suppress_errors) + builder = llvm.JITLibraryBuilder() + if add_process: + builder.add_current_process() + rt = builder\ + .add_ir(asm.format(triple=llvm.get_default_triple()))\ + .export_symbol(func_name)\ + .link(lljit, func_name) + cfptr = rt[func_name] + self.assertTrue(cfptr) + self.assertEqual(func_name, rt.name) + return lljit, rt, func_type(cfptr) + + # From test_dylib_symbols + def test_define_symbol(self): + lljit = llvm.create_lljit_compiler() + rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\ + .export_symbol("__xyzzy").link(lljit, "foo") + self.assertEqual(rt["__xyzzy"], 1234) + + def test_lookup_undefined_symbol_fails(self): + lljit = llvm.create_lljit_compiler() + with self.assertRaisesRegex(RuntimeError, 'No such library'): + lljit.lookup("foo", "__foobar") + rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\ + .export_symbol("__xyzzy").link(lljit, "foo") + self.assertNotEqual(rt["__xyzzy"], 0) + with self.assertRaisesRegex(RuntimeError, + 'Symbols not found.*__foobar'): + lljit.lookup("foo", "__foobar") + + def test_jit_link(self): + if sys.platform == "win32": + with self.assertRaisesRegex(RuntimeError, + 'JITLink .* Windows'): + llvm.create_lljit_compiler(use_jit_link=True) + else: + self.assertIsNotNone(llvm.create_lljit_compiler(use_jit_link=True)) + + def test_run_code(self): + (lljit, rt, cfunc) = self.jit() + with lljit: + res = cfunc(2, -5) + self.assertEqual(-3, res) + + def test_close(self): + (lljit, rt, cfunc) = self.jit() + lljit.close() + lljit.close() + with self.assertRaises(AssertionError): + lljit.lookup("foo", "fn") + + def test_with(self): + (lljit, rt, cfunc) = self.jit() + with lljit: + pass + with self.assertRaises(RuntimeError): + with lljit: + pass + with self.assertRaises(AssertionError): + lljit.lookup("foo", "fn") + + def test_add_ir_module(self): + (lljit, rt_sum, cfunc_sum) = self.jit() + rt_mul = llvm.JITLibraryBuilder() \ + .add_ir(asm_mul.format(triple=llvm.get_default_triple())) \ + .export_symbol("mul") \ + .link(lljit, "mul") + res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["mul"])(2, -5) + self.assertEqual(-10, res) + self.assertNotEqual(lljit.lookup("sum", "sum")["sum"], 0) + self.assertNotEqual(lljit.lookup("mul", "mul")["mul"], 0) + with self.assertRaises(RuntimeError): + lljit.lookup("sum", "mul") + with self.assertRaises(RuntimeError): + lljit.lookup("mul", "sum") + + def test_remove_module(self): + (lljit, rt_sum, _) = self.jit() + del rt_sum + gc.collect() + with self.assertRaises(RuntimeError): + lljit.lookup("sum", "sum") + lljit.close() + + def test_lib_depends(self): + (lljit, rt_sum, cfunc_sum) = self.jit() + rt_mul = llvm.JITLibraryBuilder() \ + .add_ir(asm_square_sum.format(triple=llvm.get_default_triple())) \ + .export_symbol("square_sum") \ + .add_jit_library("sum") \ + .link(lljit, "square_sum") + res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["square_sum"])(2, -5) + self.assertEqual(9, res) + + def test_target_data(self): + (lljit, rt, _) = self.jit() + td = lljit.target_data + # A singleton is returned + self.assertIs(lljit.target_data, td) + str(td) + del lljit + str(td) + + def test_global_ctors_dtors(self): + # test issue #303 + # (https://github.com/numba/llvmlite/issues/303) + shared_value = c_int32(0) + lljit = llvm.create_lljit_compiler() + builder = llvm.JITLibraryBuilder() + rt = builder \ + .add_ir(asm_ext_ctors.format(triple=llvm.get_default_triple())) \ + .import_symbol("A", ctypes.addressof(shared_value)) \ + .export_symbol("foo") \ + .link(lljit, "foo") + foo = rt["foo"] + self.assertTrue(foo) + self.assertEqual(CFUNCTYPE(c_int)(foo)(), 12) + del rt + self.assertNotEqual(shared_value.value, 20) + + def test_lookup_current_process_symbol_fails(self): + # An attempt to lookup a symbol in the current process (Py_GetVersion, + # in this case) should fail with an appropriate error if we have not + # enabled searching the current process for symbols. + msg = 'Failed to materialize symbols:.*getversion' + with self.assertRaisesRegex(RuntimeError, msg): + self.jit(asm_getversion, "getversion", suppress_errors=True) + + def test_lookup_current_process_symbol(self): + self.jit(asm_getversion, "getversion", None, True) + + def test_thread_safe(self): + lljit = llvm.create_lljit_compiler() + llvm_ir = asm_sum.format(triple=llvm.get_default_triple()) + + def compile_many(i): + def do_work(): + tracking = [] + for c in range(50): + tracking.append(llvm.JITLibraryBuilder() + .add_ir(llvm_ir) + .export_symbol("sum") + .link(lljit, f"sum_{i}_{c}")) + + return do_work + + ths = [threading.Thread(target=compile_many(i)) + for i in range(os.cpu_count())] + for th in ths: + th.start() + for th in ths: + th.join() + + def test_add_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + lljit = llvm.create_lljit_compiler(target_machine) + rt = llvm.JITLibraryBuilder()\ + .add_object_img(target_machine.emit_object(mod))\ + .export_symbol("sum")\ + .link(lljit, "sum") + sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"]) + self.assertEqual(sum(2, 3), 5) + + def test_add_object_file_from_filesystem(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + temp_desc, temp_path = mkstemp() + + try: + with os.fdopen(temp_desc, "wb") as f: + f.write(obj_bin) + lljit = llvm.create_lljit_compiler(target_machine) + rt = llvm.JITLibraryBuilder() \ + .add_object_file(temp_path) \ + .export_symbol("sum") \ + .link(lljit, "sum") + sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"]) + self.assertEqual(sum(2, 3), 5) + finally: + os.unlink(temp_path) + + +class TestValueRef(BaseTest): + + def test_str(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(str(glob), "@glob = global i32 0") + + def test_name(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(glob.name, "glob") + glob.name = "foobar" + self.assertEqual(glob.name, "foobar") + + def test_linkage(self): + mod = self.module() + glob = mod.get_global_variable("glob") + linkage = glob.linkage + self.assertIsInstance(glob.linkage, llvm.Linkage) + glob.linkage = linkage + self.assertEqual(glob.linkage, linkage) + for linkage in ("internal", "external"): + glob.linkage = linkage + self.assertIsInstance(glob.linkage, llvm.Linkage) + self.assertEqual(glob.linkage.name, linkage) + + def test_visibility(self): + mod = self.module() + glob = mod.get_global_variable("glob") + visibility = glob.visibility + self.assertIsInstance(glob.visibility, llvm.Visibility) + glob.visibility = visibility + self.assertEqual(glob.visibility, visibility) + for visibility in ("hidden", "protected", "default"): + glob.visibility = visibility + self.assertIsInstance(glob.visibility, llvm.Visibility) + self.assertEqual(glob.visibility.name, visibility) + + def test_storage_class(self): + mod = self.module() + glob = mod.get_global_variable("glob") + storage_class = glob.storage_class + self.assertIsInstance(glob.storage_class, llvm.StorageClass) + glob.storage_class = storage_class + self.assertEqual(glob.storage_class, storage_class) + for storage_class in ("dllimport", "dllexport", "default"): + glob.storage_class = storage_class + self.assertIsInstance(glob.storage_class, llvm.StorageClass) + self.assertEqual(glob.storage_class.name, storage_class) + + def test_add_function_attribute(self): + mod = self.module() + fn = mod.get_function("sum") + fn.add_function_attribute("noinline") + with self.assertRaises(ValueError) as raises: + fn.add_function_attribute("zext") + self.assertEqual(str(raises.exception), "no such attribute 'zext'") + + def test_add_function_attribute_optsize(self): + mod = self.module() + fn = mod.get_function("sum") + fn.add_function_attribute("optsize") + self.assertIn(b"optsize", list(fn.attributes)) + + def test_add_function_attribute_minsize(self): + mod = self.module() + fn = mod.get_function("sum") + fn.add_function_attribute("minsize") + self.assertIn(b"minsize", list(fn.attributes)) + + def test_module(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertIs(glob.module, mod) + + def test_type(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.type + self.assertIsInstance(tp, llvm.TypeRef) + + def test_type_name(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.type + self.assertEqual(tp.name, "") + st = mod.get_global_variable("glob_struct") + self.assertIsNotNone(re.match(r"struct\.glob_type(\.[\d]+)?", + st.global_value_type.name)) + + def test_type_printing_variable(self): + mod = self.module() + glob = mod.get_global_variable("glob") + tp = glob.global_value_type + self.assertEqual(str(tp), 'i32') + + def test_type_printing_function(self): + mod = self.module() + fn = mod.get_function("sum") + self.assertEqual(str(fn.global_value_type), "i32 (i32, i32)") + + def test_type_printing_struct(self): + mod = self.module() + st = mod.get_global_variable("glob_struct") + self.assertTrue(st.type.is_pointer) + self.assertIsNotNone(re.match(r'ptr', str(st.type))) + self.assertIsNotNone(re.match( + r"%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }", + str(st.global_value_type))) + + def test_close(self): + glob = self.glob() + glob.close() + glob.close() + + def test_is_declaration(self): + defined = self.module().get_function('sum') + declared = self.module(asm_sum_declare).get_function('sum') + self.assertFalse(defined.is_declaration) + self.assertTrue(declared.is_declaration) + + def test_module_global_variables(self): + mod = self.module(asm_sum) + gvars = list(mod.global_variables) + self.assertEqual(len(gvars), 4) + for v in gvars: + self.assertTrue(v.is_global) + + def test_module_functions(self): + mod = self.module() + funcs = list(mod.functions) + self.assertEqual(len(funcs), 1) + func = funcs[0] + self.assertTrue(func.is_function) + self.assertEqual(func.name, 'sum') + + with self.assertRaises(ValueError): + func.instructions + with self.assertRaises(ValueError): + func.operands + with self.assertRaises(ValueError): + func.opcode + + def test_function_arguments(self): + mod = self.module() + func = mod.get_function('sum') + self.assertTrue(func.is_function) + args = list(func.arguments) + self.assertEqual(len(args), 2) + self.assertTrue(args[0].is_argument) + self.assertTrue(args[1].is_argument) + self.assertEqual(args[0].name, '.1') + self.assertEqual(str(args[0].type), 'i32') + self.assertEqual(args[1].name, '.2') + self.assertEqual(str(args[1].type), 'i32') + + with self.assertRaises(ValueError): + args[0].blocks + with self.assertRaises(ValueError): + args[0].arguments + + def test_function_blocks(self): + func = self.module().get_function('sum') + blocks = list(func.blocks) + self.assertEqual(len(blocks), 1) + block = blocks[0] + self.assertTrue(block.is_block) + + def test_block_instructions(self): + func = self.module().get_function('sum') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(len(insts), 3) + self.assertTrue(insts[0].is_instruction) + self.assertTrue(insts[1].is_instruction) + self.assertTrue(insts[2].is_instruction) + self.assertEqual(insts[0].opcode, 'add') + self.assertEqual(insts[1].opcode, 'add') + self.assertEqual(insts[2].opcode, 'ret') + + def test_instruction_operands(self): + func = self.module().get_function('sum') + add = list(list(func.blocks)[0].instructions)[0] + self.assertEqual(add.opcode, 'add') + operands = list(add.operands) + self.assertEqual(len(operands), 2) + self.assertTrue(operands[0].is_operand) + self.assertTrue(operands[1].is_operand) + self.assertEqual(operands[0].name, '.1') + self.assertEqual(str(operands[0].type), 'i32') + self.assertEqual(operands[1].name, '.2') + self.assertEqual(str(operands[1].type), 'i32') + + def test_function_attributes(self): + ver = llvm.llvm_version_info[0] + readonly_attrs = [b'memory(read)' if ver > 15 else b'readonly'] + mod = self.module(asm_attributes) + for func in mod.functions: + attrs = list(func.attributes) + if func.name == 'a_readonly_func': + self.assertEqual(attrs, readonly_attrs) + elif func.name == 'a_arg0_return_func': + self.assertEqual(attrs, []) + args = list(func.arguments) + self.assertEqual(list(args[0].attributes), [b'returned']) + self.assertEqual(list(args[1].attributes), []) + + def test_value_kind(self): + mod = self.module() + self.assertEqual(mod.get_global_variable('glob').value_kind, + llvm.ValueKind.global_variable) + func = mod.get_function('sum') + self.assertEqual(func.value_kind, llvm.ValueKind.function) + block = list(func.blocks)[0] + self.assertEqual(block.value_kind, llvm.ValueKind.basic_block) + inst = list(block.instructions)[1] + self.assertEqual(inst.value_kind, llvm.ValueKind.instruction) + self.assertEqual(list(inst.operands)[0].value_kind, + llvm.ValueKind.constant_int) + self.assertEqual(list(inst.operands)[1].value_kind, + llvm.ValueKind.instruction) + + iasm_func = self.module(asm_inlineasm).get_function('foo') + iasm_inst = list(list(iasm_func.blocks)[0].instructions)[0] + self.assertEqual(list(iasm_inst.operands)[0].value_kind, + llvm.ValueKind.inline_asm) + + def test_is_constant(self): + mod = self.module() + self.assertTrue(mod.get_global_variable('glob').is_constant) + constant_operands = 0 + for func in mod.functions: + self.assertTrue(func.is_constant) + for block in func.blocks: + self.assertFalse(block.is_constant) + for inst in block.instructions: + self.assertFalse(inst.is_constant) + for op in inst.operands: + if op.is_constant: + constant_operands += 1 + + self.assertEqual(constant_operands, 1) + + def test_constant_int(self): + mod = self.module() + func = mod.get_function('sum') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(insts[1].opcode, 'add') + operands = list(insts[1].operands) + self.assertTrue(operands[0].is_constant) + self.assertFalse(operands[1].is_constant) + self.assertEqual(operands[0].get_constant_value(), 0) + with self.assertRaises(ValueError): + operands[1].get_constant_value() + + mod = self.module(asm_sum3) + func = mod.get_function('sum') + insts = list(list(func.blocks)[0].instructions) + posint64 = list(insts[1].operands)[0] + negint64 = list(insts[2].operands)[0] + self.assertEqual(posint64.get_constant_value(), 5) + self.assertEqual(negint64.get_constant_value(signed_int=True), -5) + + # Convert from unsigned arbitrary-precision integer to signed i64 + as_u64 = negint64.get_constant_value(signed_int=False) + as_i64 = int.from_bytes(as_u64.to_bytes(8, 'little'), 'little', + signed=True) + self.assertEqual(as_i64, -5) + + def test_constant_fp(self): + mod = self.module(asm_double_locale) + func = mod.get_function('foo') + insts = list(list(func.blocks)[0].instructions) + self.assertEqual(len(insts), 2) + self.assertEqual(insts[0].opcode, 'fadd') + operands = list(insts[0].operands) + self.assertTrue(operands[0].is_constant) + self.assertAlmostEqual(operands[0].get_constant_value(), 0.0) + self.assertTrue(operands[1].is_constant) + self.assertAlmostEqual(operands[1].get_constant_value(), 3.14) + + mod = self.module(asm_double_inaccurate) + func = mod.get_function('foo') + inst = list(list(func.blocks)[0].instructions)[0] + operands = list(inst.operands) + with self.assertRaises(ValueError): + operands[0].get_constant_value() + self.assertAlmostEqual(operands[1].get_constant_value(round_fp=True), 0) + + def test_constant_as_string(self): + mod = self.module(asm_null_constant) + func = mod.get_function('bar') + inst = list(list(func.blocks)[0].instructions)[0] + arg = list(inst.operands)[0] + self.assertTrue(arg.is_constant) + self.assertEqual(arg.get_constant_value(), 'ptr null') + + def test_incoming_phi_blocks(self): + mod = self.module(asm_phi_blocks) + func = mod.get_function('foo') + blocks = list(func.blocks) + instructions = list(blocks[-1].instructions) + self.assertTrue(instructions[0].is_instruction) + self.assertEqual(instructions[0].opcode, 'phi') + + incoming_blocks = list(instructions[0].incoming_blocks) + self.assertEqual(len(incoming_blocks), 2) + self.assertTrue(incoming_blocks[0].is_block) + self.assertTrue(incoming_blocks[1].is_block) + # Test reference to blocks (named or unnamed) + self.assertEqual(incoming_blocks[0], blocks[-1]) + self.assertEqual(incoming_blocks[1], blocks[0]) + + # Test case that should fail + self.assertNotEqual(instructions[1].opcode, 'phi') + with self.assertRaises(ValueError): + instructions[1].incoming_blocks + + +class TestTypeRef(BaseTest): + + def test_str(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(str(glob.global_value_type), "i32") + glob_struct_type = mod.get_struct_type("struct.glob_type") + self.assertEqual(str(glob_struct_type), + "%struct.glob_type = type { i64, [2 x i64] }") + + elements = list(glob_struct_type.elements) + self.assertEqual(len(elements), 2) + self.assertEqual(str(elements[0]), "i64") + self.assertEqual(str(elements[1]), "[2 x i64]") + + def test_type_kind(self): + mod = self.module() + glob = mod.get_global_variable("glob") + self.assertEqual(glob.type.type_kind, llvm.TypeKind.pointer) + self.assertTrue(glob.type.is_pointer) + + glob_struct = mod.get_global_variable("glob_struct") + self.assertEqual(glob_struct.type.type_kind, llvm.TypeKind.pointer) + self.assertTrue(glob_struct.type.is_pointer) + + stype = glob_struct.global_value_type + self.assertEqual(stype.type_kind, llvm.TypeKind.struct) + self.assertTrue(stype.is_struct) + + stype_a, stype_b = stype.elements + self.assertEqual(stype_a.type_kind, llvm.TypeKind.integer) + self.assertEqual(stype_b.type_kind, llvm.TypeKind.array) + self.assertTrue(stype_b.is_array) + + glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec") + _, vector_type = glob_vec_struct_type.elements + self.assertEqual(vector_type.type_kind, llvm.TypeKind.vector) + self.assertTrue(vector_type.is_vector) + + funcptr = mod.get_function("sum").type + self.assertEqual(funcptr.type_kind, llvm.TypeKind.pointer) + functype = mod.get_function("sum").global_value_type + self.assertEqual(functype.type_kind, llvm.TypeKind.function) + + def test_element_count(self): + mod = self.module() + glob_struct_type = mod.get_struct_type("struct.glob_type") + _, array_type = glob_struct_type.elements + self.assertEqual(array_type.element_count, 2) + with self.assertRaises(ValueError): + glob_struct_type.element_count + + def test_type_width(self): + mod = self.module() + glob_struct_type = mod.get_struct_type("struct.glob_type") + glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec") + integer_type, array_type = glob_struct_type.elements + _, vector_type = glob_vec_struct_type.elements + self.assertEqual(integer_type.type_width, 64) + self.assertEqual(vector_type.type_width, 64 * 2) + + # Structs and arrays are not primitive types + self.assertEqual(glob_struct_type.type_width, 0) + self.assertEqual(array_type.type_width, 0) + + def test_vararg_function(self): + # Variadic function + mod = self.module(asm_vararg_declare) + func = mod.get_function('vararg') + decltype = func.global_value_type + self.assertTrue(decltype.is_function_vararg) + + mod = self.module(asm_sum_declare) + func = mod.get_function('sum') + decltype = func.global_value_type + self.assertFalse(decltype.is_function_vararg) + + # test that the function pointer type cannot use is_function_vararg + self.assertTrue(func.type.is_pointer) + with self.assertRaises(ValueError) as raises: + func.type.is_function_vararg + self.assertIn("Type ptr is not a function", str(raises.exception)) + + def test_function_typeref_as_ir(self): + mod = self.module() + + [fn] = list(mod.functions) + # .type gives a pointer type, a problem if it's opaque (llvm15+) + self.assertEqual(fn.type.type_kind, llvm.TypeKind.pointer) + self.assertFalse(fn.type.is_function) + # Use .global_value_type instead + fnty = fn.global_value_type + self.assertEqual(fnty.type_kind, llvm.TypeKind.function) + self.assertTrue(fnty.is_function) + # Run .as_ir() to get llvmlite.ir.FunctionType + tyir = fnty.as_ir(ir.global_context) + self.assertIsInstance(tyir, ir.FunctionType) + self.assertEqual(tyir.args, (ir.IntType(32), ir.IntType(32))) + self.assertEqual(tyir.return_type ,ir.IntType(32)) + + def test_void_typeref_as_ir(self): + # Void type can only be used as return-type of llvmlite.ir.FunctionType. + fnty = ir.FunctionType(ir.VoidType(), ()) + irmod = ir.Module() + fn = ir.Function(irmod, fnty, "foo") + mod = self.module(str(irmod)) + fn = mod.get_function("foo") + gvty = fn.global_value_type + self.assertEqual(fnty.return_type, + gvty.as_ir(ir.global_context).return_type) + + def test_global_typeref_as_ir(self): + from llvmlite.binding.typeref import _TypeKindToIRType + ctx = ir.Context() + + skipped = { + "function", # tested in test_function_typeref_as_ir + "void", # tested in test_void_typeref_as_ir + } + + makers = {} + + def maker_half(): + yield ir.HalfType() + + makers['half'] = maker_half + + def maker_float(): + yield ir.FloatType() + + makers['float'] = maker_float + + def maker_double(): + yield ir.DoubleType() + + makers['double'] = maker_double + + def maker_integer(): + yield ir.IntType(32) + + makers['integer'] = maker_integer + + def maker_pointer(): + yield ir.PointerType(ir.IntType(8)) + # opaque struct ptr + yield ctx.get_identified_type("myclass").as_pointer() + # named struct with defined body + myclass2 = ctx.get_identified_type("myclass2") + myclass2.set_body(ir.IntType(8)) + yield myclass2.as_pointer() + + makers['pointer'] = maker_pointer + + def maker_array(): + yield ir.ArrayType(ir.IntType(8), 123) + + makers['array'] = maker_array + + def maker_vector(): + yield ir.VectorType(ir.FloatType(), 2) + + makers['vector'] = maker_vector + + def maker_struct(): + yield ir.LiteralStructType([ir.FloatType(), ir.IntType(64)]) + yield ir.LiteralStructType([ir.FloatType(), ir.IntType(64)], + packed=True) + + makers['struct'] = maker_struct + + # Ensure that number of supported TypeKind matches number of makers + self.assertEqual({x.name for x in _TypeKindToIRType.keys()}, + set(makers.keys()) | set(skipped)) + + # Test each type-kind + for type_kind, irtype in _TypeKindToIRType.items(): + if type_kind.name in skipped: + continue + for ty in makers[type_kind.name](): + with self.subTest(f"{type_kind!s} -> {ty}"): + irmod = ir.Module(context=ctx) + ir.GlobalVariable(irmod, ty, name='gv') + asm = str(irmod) + mod = llvm.parse_assembly(asm) + gv = mod.get_global_variable("gv") + gvty = gv.global_value_type + got = gvty.as_ir(ir.Context()) # fresh context + self.assertEqual(got, ty) + self.assertIsInstance(got, irtype) + + def _check_typeref_as_ir_for_wrappers(self, asm, target_symbol): + # Get a clang++ defined function from a llvm ir + mod = llvm.parse_assembly(asm) + cppfn = mod.get_function(target_symbol) + cppfntype = cppfn.global_value_type + + # Get the function type into a new context + my_context = ir.Context() # don't populate global context + ty = cppfntype.as_ir(ir_ctx=my_context) + + # Build a wrapper module for the cpp function + wrapper_mod = ir.Module(context=my_context) + # declare the original function + declfn = ir.Function(wrapper_mod, ty, name=cppfn.name) + # populate the wrapper function + wrapfn = ir.Function(wrapper_mod, ty, name="wrapper") + builder = ir.IRBuilder(wrapfn.append_basic_block()) + # just call the original function + builder.call(declfn, wrapfn.args) + builder.ret_void() + # Create a new LLVM module with the wrapper + new_mod = llvm.parse_assembly(str(wrapper_mod)) + self.assertTrue(new_mod.get_function(declfn.name).is_declaration, + msg="declfn must not have a body") + # Merge/link the original module into the new module + new_mod.link_in(mod, preserve=True) + self.assertEqual(len(list(new_mod.functions)), + len(list(mod.functions)) + 1, + msg="the only new function is the wrapper") + self.assertFalse(new_mod.get_function(declfn.name).is_declaration, + msg="declfn must have a body now") + self.assertEqual(new_mod.get_function(declfn.name).global_value_type, + new_mod.get_function(wrapfn.name).global_value_type, + msg="declfn and wrapfn must have the same llvm Type") + + def test_typeref_as_ir_for_wrappers_of_cpp_class(self): + """Exercise extracting C++ defined class types. + Contains both opaque and non-opaque class definitions. + """ + self._check_typeref_as_ir_for_wrappers( + asm_cpp_class, + "_Z3fooP7MyClass14MyClassDefined", + ) + + def test_typeref_as_ir_for_wrappers_of_cpp_vector_struct(self): + """Exercise extracting C++ struct types that are passed as vectors. + + IA64 ABI on x86_64 will put struct with two floats as + a vector of two floats. + """ + self._check_typeref_as_ir_for_wrappers( + asm_cpp_vector, + "_Z3foo8Vector2DPS_", + ) + + +class TestTarget(BaseTest): + + def test_from_triple(self): + f = llvm.Target.from_triple + with self.assertRaises(RuntimeError) as cm: + f("foobar") + self.assertIn("No available targets are compatible with", + str(cm.exception)) + triple = llvm.get_default_triple() + target = f(triple) + self.assertEqual(target.triple, triple) + target.close() + + def test_create_target_machine(self): + target = llvm.Target.from_triple(llvm.get_default_triple()) + # With the default settings + target.create_target_machine('', '', 1, 'default', 'default') + # With the host's CPU + cpu = llvm.get_host_cpu_name() + target.create_target_machine(cpu, '', 1, 'default', 'default') + + def test_name(self): + t = llvm.Target.from_triple(llvm.get_default_triple()) + u = llvm.Target.from_default_triple() + self.assertIsInstance(t.name, str) + self.assertEqual(t.name, u.name) + + def test_description(self): + t = llvm.Target.from_triple(llvm.get_default_triple()) + u = llvm.Target.from_default_triple() + self.assertIsInstance(t.description, str) + self.assertEqual(t.description, u.description) + + def test_str(self): + target = llvm.Target.from_triple(llvm.get_default_triple()) + s = str(target) + self.assertIn(target.name, s) + self.assertIn(target.description, s) + + def test_get_parts_from_triple(self): + # Tests adapted from llvm-14::llvm/unittests/ADT/TripleTest.cpp + cases = [ + ("x86_64-scei-ps4", + llvm.targets.Triple(Arch="x86_64", SubArch='', + Vendor="scei", OS="ps4", + Env="unknown", ObjectFormat="ELF")), + ("x86_64-sie-ps4", + llvm.targets.Triple(Arch="x86_64", SubArch='', + Vendor="scei", OS="ps4", + Env="unknown", ObjectFormat="ELF")), + ("powerpc-dunno-notsure", + llvm.targets.Triple(Arch="powerpc", SubArch='', + Vendor="unknown", OS="unknown", + Env="unknown", ObjectFormat="ELF")), + ("powerpcspe-unknown-freebsd", + llvm.targets.Triple(Arch="powerpc", SubArch='spe', + Vendor="unknown", OS="freebsd", + Env="unknown", ObjectFormat="ELF")), + ("armv6hl-none-linux-gnueabi", + llvm.targets.Triple(Arch="arm", SubArch='v6hl', + Vendor="unknown", OS="linux", + Env="gnueabi", ObjectFormat="ELF")), + ("i686-unknown-linux-gnu", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="unknown", OS="linux", + Env="gnu", ObjectFormat="ELF")), + ("i686-apple-macosx", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="apple", OS="macosx", + Env="unknown", ObjectFormat="MachO")), + ("i686-dunno-win32", + llvm.targets.Triple(Arch="i386", SubArch='', + Vendor="unknown", OS="windows", + Env="msvc", ObjectFormat="COFF")), + ("s390x-ibm-zos", + llvm.targets.Triple(Arch="s390x", SubArch='', + Vendor="ibm", OS="zos", + Env="unknown", ObjectFormat="GOFF")), + ("wasm64-wasi", + llvm.targets.Triple(Arch="wasm64", SubArch='', + Vendor="unknown", OS="wasi", + Env="unknown", ObjectFormat="Wasm")), + ("aarch64-pc-windows-msvc", + llvm.targets.Triple(Arch="aarch64", SubArch='', + Vendor="pc", OS="windows", + Env="msvc", ObjectFormat="COFF")), + ] + + for case in cases: + triple_str, triple_obj = case + res = llvm.get_triple_parts(triple_str) + + self.assertEqual(res, triple_obj) + + +class TestTargetData(BaseTest): + + def target_data(self): + return llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128") + + def test_get_abi_size(self): + td = self.target_data() + glob = self.glob() + self.assertEqual(td.get_abi_size(glob.type), 8) + + def test_get_pointee_abi_size(self): + td = self.target_data() + + glob = self.glob() + self.assertEqual(td.get_abi_size(glob.global_value_type), 4) + + glob = self.glob("glob_struct") + self.assertEqual(td.get_abi_size(glob.global_value_type), 24) + + def test_get_struct_element_offset(self): + td = self.target_data() + glob = self.glob("glob_struct") + + with self.assertRaises(ValueError): + td.get_element_offset(glob.type, 0) + + struct_type = glob.global_value_type + self.assertEqual(td.get_element_offset(struct_type, 0), 0) + self.assertEqual(td.get_element_offset(struct_type, 1), 8) + + +class TestTargetMachine(BaseTest): + + def test_target_data_from_tm(self): + tm = self.target_machine(jit=False) + td = tm.target_data + mod = self.module() + gv_i32 = mod.get_global_variable("glob") + # A global is a pointer, it has the ABI size of a pointer + pointer_size = 4 if sys.maxsize < 2 ** 32 else 8 + self.assertEqual(td.get_abi_size(gv_i32.type), pointer_size) + + +class TestDylib(BaseTest): + + def test_bad_library(self): + with self.assertRaises(RuntimeError): + llvm.load_library_permanently("zzzasdkf;jasd;l") + + @unittest.skipUnless(platform.system() in ["Linux"], + "test only works on Linux") + def test_libm(self): + libm = find_library("m") + llvm.load_library_permanently(libm) + + +class TestAnalysis(BaseTest): + def build_ir_module(self): + m = ir.Module() + ft = ir.FunctionType(ir.IntType(32), [ir.IntType(32), ir.IntType(32)]) + fn = ir.Function(m, ft, "foo") + bd = ir.IRBuilder(fn.append_basic_block()) + x, y = fn.args + z = bd.add(x, y) + bd.ret(z) + return m + + def test_get_function_cfg_on_ir(self): + mod = self.build_ir_module() + foo = mod.get_global('foo') + dot_showing_inst = llvm.get_function_cfg(foo) + dot_without_inst = llvm.get_function_cfg(foo, show_inst=False) + inst = "%.5 = add i32 %.1, %.2" + self.assertIn(inst, dot_showing_inst) + self.assertNotIn(inst, dot_without_inst) + + def test_function_cfg_on_llvm_value(self): + defined = self.module().get_function('sum') + dot_showing_inst = llvm.get_function_cfg(defined, show_inst=True) + dot_without_inst = llvm.get_function_cfg(defined, show_inst=False) + # Check "digraph" + prefix = 'digraph' + self.assertIn(prefix, dot_showing_inst) + self.assertIn(prefix, dot_without_inst) + # Check function name + fname = "CFG for 'sum' function" + self.assertIn(fname, dot_showing_inst) + self.assertIn(fname, dot_without_inst) + # Check instruction + inst = "%.3 = add i32 %.1, %.2" + self.assertIn(inst, dot_showing_inst) + self.assertNotIn(inst, dot_without_inst) + + +class TestTypeParsing(BaseTest): + @contextmanager + def check_parsing(self): + mod = ir.Module() + # Yield to caller and provide the module for adding + # new GV. + yield mod + # Caller yield back and continue with testing + asm = str(mod) + llvm.parse_assembly(asm) + + def test_literal_struct(self): + # Natural layout + with self.check_parsing() as mod: + typ = ir.LiteralStructType([ir.IntType(32)]) + gv = ir.GlobalVariable(mod, typ, "foo") + # Also test constant text repr + gv.initializer = ir.Constant(typ, [1]) + + # Packed layout + with self.check_parsing() as mod: + typ = ir.LiteralStructType([ir.IntType(32)], + packed=True) + gv = ir.GlobalVariable(mod, typ, "foo") + # Also test constant text repr + gv.initializer = ir.Constant(typ, [1]) + + # Packed layout created from Constant.literal_struct + with self.check_parsing() as mod: + const = ir.Constant.literal_struct([ir.IntType(32)(1), + ir.IntType(32)(2)], + packed=True) + gv = ir.GlobalVariable(mod, const.type, "foo") + gv.initializer = const + + +class TestGlobalConstructors(TestMCJit): + @unittest.skipIf(platform.system() == "Darwin", + "__cxa_atexit is broken on OSX in MCJIT") + def test_global_ctors_dtors(self): + # test issue #303 + # (https://github.com/numba/llvmlite/issues/303) + mod = self.module(asm_global_ctors) + ee = self.jit(mod) + ee.finalize_object() + + ee.run_static_constructors() + + # global variable should have been initialized + ptr_addr = ee.get_global_value_address("A") + ptr_t = ctypes.POINTER(ctypes.c_int32) + ptr = ctypes.cast(ptr_addr, ptr_t) + self.assertEqual(ptr.contents.value, 10) + + foo_addr = ee.get_function_address("foo") + foo = ctypes.CFUNCTYPE(ctypes.c_int32)(foo_addr) + self.assertEqual(foo(), 12) + + ee.run_static_destructors() + + # destructor should have run + self.assertEqual(ptr.contents.value, 20) + + +class TestGlobalVariables(BaseTest): + def check_global_variable_linkage(self, linkage, has_undef=True): + # This test default initializer on global variables with different + # linkages. Some linkages requires an initializer be present, while + # it is optional for others. This test uses ``parse_assembly()`` + # to verify that we are adding an `undef` automatically if user didn't + # specific one for certain linkages. It is a IR syntax error if the + # initializer is not present for certain linkages e.g. "external". + mod = ir.Module() + typ = ir.IntType(32) + gv = ir.GlobalVariable(mod, typ, "foo") + gv.linkage = linkage + asm = str(mod) + # check if 'undef' is present + if has_undef: + self.assertIn('undef', asm) + else: + self.assertNotIn('undef', asm) + # parse assembly to ensure correctness + self.module(asm) + + def test_internal_linkage(self): + self.check_global_variable_linkage('internal') + + def test_common_linkage(self): + self.check_global_variable_linkage('common') + + def test_external_linkage(self): + self.check_global_variable_linkage('external', has_undef=False) + + def test_available_externally_linkage(self): + self.check_global_variable_linkage('available_externally') + + def test_private_linkage(self): + self.check_global_variable_linkage('private') + + def test_linkonce_linkage(self): + self.check_global_variable_linkage('linkonce') + + def test_weak_linkage(self): + self.check_global_variable_linkage('weak') + + def test_appending_linkage(self): + self.check_global_variable_linkage('appending') + + def test_extern_weak_linkage(self): + self.check_global_variable_linkage('extern_weak', has_undef=False) + + def test_linkonce_odr_linkage(self): + self.check_global_variable_linkage('linkonce_odr') + + def test_weak_odr_linkage(self): + self.check_global_variable_linkage('weak_odr') + + +@unittest.skipUnless(platform.machine().startswith('x86'), "only on x86") +class TestInlineAsm(BaseTest): + def test_inlineasm(self): + llvm.initialize_native_asmparser() + m = self.module(asm=asm_inlineasm) + tm = self.target_machine(jit=False) + asm = tm.emit_assembly(m) + self.assertIn('nop', asm) + + +class TestObjectFile(BaseTest): + + mod_asm = """ + ;ModuleID = + target triple = "{triple}" + + declare i32 @sum(i32 %.1, i32 %.2) + + define i32 @sum_twice(i32 %.1, i32 %.2) {{ + %.3 = call i32 @sum(i32 %.1, i32 %.2) + %.4 = call i32 @sum(i32 %.3, i32 %.3) + ret i32 %.4 + }} + """ + + def test_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + obj = llvm.ObjectFileRef.from_data(obj_bin) + # Check that we have a text section, and that she has a name and data + has_text_and_data = False + last_address = -1 + for s in obj.sections(): + if ( + s.is_text() + and len(s.data()) > 0 + and s.address() is not None + and last_address < s.address() + ): + has_text_and_data = True + last_address = s.address() + break + self.assertTrue(has_text_and_data) + + def test_add_object_file(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + obj = llvm.ObjectFileRef.from_data(obj_bin) + + jit = llvm.create_mcjit_compiler(self.module(self.mod_asm), + target_machine) + + jit.add_object_file(obj) + + sum_twice = CFUNCTYPE(c_int, c_int, c_int)( + jit.get_function_address("sum_twice")) + + self.assertEqual(sum_twice(2, 3), 10) + + def test_add_object_file_from_filesystem(self): + target_machine = self.target_machine(jit=False) + mod = self.module() + obj_bin = target_machine.emit_object(mod) + temp_desc, temp_path = mkstemp() + + try: + try: + f = os.fdopen(temp_desc, "wb") + f.write(obj_bin) + f.flush() + finally: + f.close() + + jit = llvm.create_mcjit_compiler(self.module(self.mod_asm), + target_machine) + + jit.add_object_file(temp_path) + finally: + os.unlink(temp_path) + + sum_twice = CFUNCTYPE(c_int, c_int, c_int)( + jit.get_function_address("sum_twice")) + + self.assertEqual(sum_twice(2, 3), 10) + + def test_get_section_content(self): + # See Issue #632 - section contents were getting truncated at null + # bytes. + elf = bytes.fromhex(issue_632_elf) + obj = llvm.ObjectFileRef.from_data(elf) + for s in obj.sections(): + if s.is_text(): + self.assertEqual(len(s.data()), 31) + self.assertEqual(s.data().hex(), issue_632_text) + + +class TestLLVMLockCallbacks(BaseTest): + def test_lock_callbacks(self): + events = [] + + def acq(): + events.append('acq') + + def rel(): + events.append('rel') + + # register callback + llvm.ffi.register_lock_callback(acq, rel) + + # Check: events are initially empty + self.assertFalse(events) + # Call LLVM functions + llvm.create_new_module_pass_manager() + # Check: there must be at least one acq and one rel + self.assertIn("acq", events) + self.assertIn("rel", events) + + # unregister callback + llvm.ffi.unregister_lock_callback(acq, rel) + + # Check: removing non-existent callbacks will trigger a ValueError + with self.assertRaises(ValueError): + llvm.ffi.unregister_lock_callback(acq, rel) + + +class TestPipelineTuningOptions(BaseTest): + + def pto(self): + return llvm.create_pipeline_tuning_options() + + def test_close(self): + pto = self.pto() + pto.close() + + def test_speed_level(self): + pto = self.pto() + self.assertIsInstance(pto.speed_level, int) + for i in range(4): + pto.speed_level = i + self.assertEqual(pto.speed_level, i) + + def test_inlining_threshold(self): + pto = self.pto() + self.assertIsInstance(pto.inlining_threshold, int) + for i in (25, 80, 350): + pto.inlining_threshold = i + + def test_loop_interleaving(self): + pto = self.pto() + self.assertIsInstance(pto.loop_interleaving, bool) + for b in (True, False): + pto.loop_interleaving = b + self.assertEqual(pto.loop_interleaving, b) + + def test_loop_vectorization(self): + pto = self.pto() + self.assertIsInstance(pto.loop_vectorization, bool) + for b in (True, False): + pto.loop_vectorization = b + self.assertEqual(pto.loop_vectorization, b) + + def test_slp_vectorization(self): + pto = self.pto() + self.assertIsInstance(pto.slp_vectorization, bool) + for b in (True, False): + pto.slp_vectorization = b + self.assertEqual(pto.slp_vectorization, b) + + def test_loop_unrolling(self): + pto = self.pto() + self.assertIsInstance(pto.loop_unrolling, bool) + for b in (True, False): + pto.loop_unrolling = b + self.assertEqual(pto.loop_unrolling, b) + + def test_speed_level_constraints(self): + pto = self.pto() + with self.assertRaises(ValueError): + pto.speed_level = 4 + with self.assertRaises(ValueError): + pto.speed_level = -1 + + +class NewPassManagerMixin(object): + + def pb(self, speed_level=0): + tm = self.target_machine(jit=False) + pto = llvm.create_pipeline_tuning_options(speed_level) + pb = llvm.create_pass_builder(tm, pto) + return pb + + +class TestPassBuilder(BaseTest, NewPassManagerMixin): + + def test_close(self): + pb = self.pb() + pb.close() + + def test_pto(self): + tm = self.target_machine(jit=False) + pto = llvm.create_pipeline_tuning_options(3) + pto.inlining_threshold = 2 + pto.loop_interleaving = True + pto.loop_vectorization = True + pto.slp_vectorization = True + pto.loop_unrolling = False + pb = llvm.create_pass_builder(tm, pto) + pb.close() + + def test_get_module_pass_manager(self): + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(self.module(), pb) + pb.close() + + def test_get_function_pass_manager(self): + pb = self.pb() + fpm = pb.getFunctionPassManager() + fpm.run(self.module().get_function("sum"), pb) + pb.close() + + def test_time_passes(self): + """Test pass timing reports for O3 and O0 optimization levels""" + def run_with_timing(speed_level): + mod = self.module() + pb = self.pb(speed_level=speed_level) + pb.start_pass_timing() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + report = pb.finish_pass_timing() + pb.close() + return report + + report_O3 = run_with_timing(3) + report_O0 = run_with_timing(0) + + self.assertIsInstance(report_O3, str) + self.assertIsInstance(report_O0, str) + self.assertEqual(report_O3.count("Pass execution timing report"), 1) + self.assertEqual(report_O0.count("Pass execution timing report"), 1) + + def test_empty_report(self): + mod = self.module() + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + pb.start_pass_timing() + report = pb.finish_pass_timing() + pb.close() + self.assertFalse(report) + + def test_multiple_timers_error(self): + mod = self.module() + pb = self.pb() + pb.start_pass_timing() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + pb.finish_pass_timing() + with self.assertRaisesRegex(RuntimeError, "only be done once"): + pb.start_pass_timing() + pb.close() + + def test_empty_report_error(self): + mod = self.module() + pb = self.pb() + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + with self.assertRaisesRegex(RuntimeError, "not enabled"): + pb.finish_pass_timing() + pb.close() + + +class TestNewModulePassManager(BaseTest, NewPassManagerMixin): + def pm(self): + return llvm.create_new_module_pass_manager() + + def run_o_n(self, level): + mod = self.module() + orig_asm = str(mod) + pb = self.pb(speed_level=level) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized_asm = str(mod) + return orig_asm, optimized_asm + + def test_close(self): + mpm = self.pm() + mpm.close() + + def test_run_o3(self): + orig_asm, optimized_asm = self.run_o_n(3) + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", optimized_asm) + + def test_run_o0(self): + orig_asm, optimized_asm = self.run_o_n(0) + self.assertIn("%.4", orig_asm) + self.assertIn("%.4", optimized_asm) + + def test_instcombine(self): + pb = self.pb() + mpm = self.pm() + mpm.add_instruction_combine_pass() + mod = self.module(asm_sum4) + orig_asm = str(mod) + mpm.run(mod, pb) + optimized_asm = str(mod) + self.assertIn("%.3", orig_asm) + self.assertNotIn("%.3", optimized_asm) + + def test_optnone(self): + pb = self.pb(speed_level=3) + orig_asm = str(asm_alloca_optnone.replace("optnone ", "")) + mod = llvm.parse_assembly(orig_asm) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized_asm = str(mod) + self.assertIn("alloca", orig_asm) + self.assertNotIn("alloca", optimized_asm) + + # Module shouldn't be optimized if the function has `optnone` attached + orig_asm_optnone = str(asm_alloca_optnone) + mpm = pb.getModulePassManager() + mod = llvm.parse_assembly(orig_asm_optnone) + mpm.run(mod, pb) + optimized_asm_optnone = str(mod) + self.assertIn("alloca", orig_asm_optnone) + self.assertIn("alloca", optimized_asm_optnone) + + def test_optsize_minsize(self): + pb = self.pb(speed_level=3) + + # Without optsize: O3 vectorises the loop + mod = self.module(asm_vectorize) + mpm = pb.getModulePassManager() + mpm.run(mod, pb) + optimized = str(mod) + self.assertIn("vector.body", optimized) + + # With optsize: vectorisation is suppressed + mod_optsize = self.module(asm_vectorize) + fn = mod_optsize.get_function("stride1") + fn.add_function_attribute("optsize") + self.assertIn(b"optsize", list(fn.attributes)) + mpm2 = pb.getModulePassManager() + mpm2.run(mod_optsize, pb) + optimized_optsize = str(mod_optsize) + self.assertIn("optsize", optimized_optsize) + self.assertNotIn("vector.body", optimized_optsize) + + # With minsize: vectorisation is suppressed + mod_minsize = self.module(asm_vectorize) + fn = mod_minsize.get_function("stride1") + fn.add_function_attribute("minsize") + self.assertIn(b"minsize", list(fn.attributes)) + mpm3 = pb.getModulePassManager() + mpm3.run(mod_minsize, pb) + optimized_minsize = str(mod_minsize) + self.assertIn("minsize", optimized_minsize) + self.assertNotIn("vector.body", optimized_minsize) + + def test_add_passes(self): + mpm = self.pm() + mpm.add_argument_promotion_pass() + mpm.add_post_order_function_attributes_pass() + mpm.add_verifier() + mpm.add_constant_merge_pass() + mpm.add_dead_arg_elimination_pass() + mpm.add_dot_call_graph_printer_pass() + mpm.add_always_inliner_pass() + mpm.add_rpo_function_attrs_pass() + mpm.add_global_dead_code_eliminate_pass() + mpm.add_global_opt_pass() + mpm.add_ipsccp_pass() + mpm.add_internalize_pass() + mpm.add_loop_extract_pass() + mpm.add_merge_functions_pass() + mpm.add_partial_inliner_pass() + mpm.add_strip_symbols_pass() + mpm.add_strip_dead_debug_info_pass() + mpm.add_strip_dead_prototype_pass() + mpm.add_strip_debug_declare_pass() + mpm.add_strip_non_debug_symbols_pass() + mpm.add_aa_eval_pass() + mpm.add_simplify_cfg_pass() + mpm.add_loop_unroll_pass() + mpm.add_instruction_combine_pass() + mpm.add_jump_threading_pass() + mpm.add_cfg_printer_pass() + mpm.add_cfg_only_printer_pass() + mpm.add_dom_printer_pass() + mpm.add_dom_only_printer_pass() + mpm.add_post_dom_printer_pass() + mpm.add_post_dom_only_printer_pass() + mpm.add_dom_viewer_pass() + mpm.add_dom_only_printer_pass() + mpm.add_post_dom_viewer_pass() + mpm.add_post_dom_only_viewer_pass() + mpm.add_aggressive_dce_pass() + mpm.add_break_critical_edges_pass() + mpm.add_dead_store_elimination_pass() + mpm.add_dead_code_elimination_pass() + mpm.add_aggressive_instcombine_pass() + mpm.add_lcssa_pass() + mpm.add_new_gvn_pass() + mpm.add_loop_simplify_pass() + mpm.add_loop_unroll_and_jam_pass() + mpm.add_sccp_pass() + mpm.add_lower_atomic_pass() + mpm.add_lower_invoke_pass() + mpm.add_lower_switch_pass() + mpm.add_mem_copy_opt_pass() + mpm.add_unify_function_exit_nodes_pass() + mpm.add_reassociate_pass() + mpm.add_register_to_memory_pass() + mpm.add_sroa_pass() + mpm.add_sinking_pass() + mpm.add_tail_call_elimination_pass() + mpm.add_instruction_namer_pass() + mpm.add_loop_deletion_pass() + mpm.add_loop_strength_reduce_pass() + mpm.add_loop_rotate_pass() + mpm.add_refprune_pass() + + +class TestNewFunctionPassManager(BaseTest, NewPassManagerMixin): + def pm(self): + return llvm.create_new_function_pass_manager() + + def test_close(self): + fpm = self.pm() + fpm.close() + + def run_o_n(self, level): + mod = self.module() + fun = mod.get_function("sum") + orig_asm = str(fun) + pb = self.pb(speed_level=level) + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm = str(fun) + return orig_asm, optimized_asm + + def test_run_o3(self): + orig_asm, optimized_asm = self.run_o_n(3) + self.assertIn("%.4", orig_asm) + self.assertNotIn("%.4", optimized_asm) + + def test_run_o0(self): + orig_asm, optimized_asm = self.run_o_n(0) + self.assertIn("%.4", orig_asm) + self.assertIn("%.4", optimized_asm) + + def test_optnone(self): + pb = self.pb(speed_level=3) + orig_asm = str(asm_alloca_optnone.replace("optnone ", "")) + fun = llvm.parse_assembly(orig_asm).get_function("foo") + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm = str(fun) + self.assertIn("alloca", orig_asm) + self.assertNotIn("alloca", optimized_asm) + + # Function shouldn't be optimized if the function has `optnone` attached + orig_asm_optnone = str(asm_alloca_optnone) + fun = llvm.parse_assembly(orig_asm_optnone).get_function("foo") + fpm = pb.getFunctionPassManager() + fpm.run(fun, pb) + optimized_asm_optnone = str(fun) + self.assertIn("alloca", orig_asm_optnone) + self.assertIn("alloca", optimized_asm_optnone) + + def test_instcombine(self): + pb = self.pb() + fpm = self.pm() + fun = self.module(asm_sum4).get_function("sum") + fpm.add_instruction_combine_pass() + orig_asm = str(fun) + fpm.run(fun, pb) + optimized_asm = str(fun) + self.assertIn("%.3", orig_asm) + self.assertNotIn("%.3", optimized_asm) + + # This should not crash + def test_declarations(self): + pb = self.pb(3) + fpm = pb.getFunctionPassManager() + for fun in llvm.parse_assembly(asm_declaration).functions: + fpm.run(fun, pb) + + def test_add_passes(self): + fpm = self.pm() + fpm.add_aa_eval_pass() + fpm.add_simplify_cfg_pass() + fpm.add_loop_unroll_pass() + fpm.add_instruction_combine_pass() + fpm.add_jump_threading_pass() + fpm.add_cfg_printer_pass() + fpm.add_cfg_only_printer_pass() + fpm.add_dom_printer_pass() + fpm.add_dom_only_printer_pass() + fpm.add_post_dom_printer_pass() + fpm.add_post_dom_only_printer_pass() + fpm.add_dom_viewer_pass() + fpm.add_dom_only_printer_pass() + fpm.add_post_dom_viewer_pass() + fpm.add_post_dom_only_viewer_pass() + fpm.add_aggressive_dce_pass() + fpm.add_break_critical_edges_pass() + fpm.add_dead_store_elimination_pass() + fpm.add_dead_code_elimination_pass() + fpm.add_aggressive_instcombine_pass() + fpm.add_lcssa_pass() + fpm.add_new_gvn_pass() + fpm.add_loop_simplify_pass() + fpm.add_loop_unroll_and_jam_pass() + fpm.add_sccp_pass() + fpm.add_lower_atomic_pass() + fpm.add_lower_invoke_pass() + fpm.add_lower_switch_pass() + fpm.add_mem_copy_opt_pass() + fpm.add_unify_function_exit_nodes_pass() + fpm.add_reassociate_pass() + fpm.add_register_to_memory_pass() + fpm.add_sroa_pass() + fpm.add_sinking_pass() + fpm.add_tail_call_elimination_pass() + fpm.add_instruction_namer_pass() + fpm.add_loop_deletion_pass() + fpm.add_loop_strength_reduce_pass() + fpm.add_loop_rotate_pass() + fpm.add_refprune_pass() + + +@unittest.skipUnless(os.environ.get('LLVMLITE_DIST_TEST'), + "Distribution-specific test") +@needs_lief +class TestBuild(TestCase): + # These tests are for use by the Numba project maintainers to check that + # package builds for which they are responsible are producing artifacts in + # the expected way. If you are a package maintainer and these tests are + # running, they shouldn't be by default. The only way they will run is if + # the environment variable LLVMLITE_DIST_TEST is set. The things they are + # checking are based on how the Numba project maintainers want to ship the + # packages, this may be entirely different to how other maintainers wish to + # ship. Basically, don't enable these tests unless you are sure they are + # suitable for your use case. + # + # The llvmlite DSO is the foundation of Numba's JIT compiler stack and is + # also used by other similar projects. It has to link against LLVM as that + # is what provides the tooling to do e.g. IR generation and JIT compilation. + # There are various options surrounding how to build LLVM and then how to + # link it into llvmlite. There have been many occurences of surprising + # linkages, symbol collisions and various other issues. + # + # The following tests are designed to try and test out some of the more + # common combinations of package type and linkage. + # + # NOTE: For Numba project maintainers on packaging formats and expected + # linkage. The following dictionaries capture the state of linkage as of + # llvmlite release 0.44. This is not an indication that it is correct, just + # that this is what is present in practice and clearly "works" to a large + # degree by virtue of having fixed the few reported issues. If you need to + # modify these dictionaries based on new information, that's fine, just make + # sure that it is an understood action opposed to just capturing what + # happened! + + wheel_expected = {"linux": {"x86_64": set(["pthread", + "z", + "dl", + "m", + "gcc_s", + "c", + "rt", + "stdc++", + "ld-linux-x86-64",]), + "aarch64": set(["pthread", + "z", + "dl", + "m", + "gcc_s", + "c", + "rt", + "stdc++",]), + }, # end linux + # NOTE: on windows, this includes a "capture what is + # present and known to work and make sure it doesn"t + # change" approach. + "windows": {"amd64": set(["advapi32", + "kernel32", + "ntdll", + "msvcp140", + "vcruntime140", + "vcruntime140_1", + "api-ms-win-crt-convert-l1-1-0", + "api-ms-win-crt-environment-l1-1-0", # noqa: E501 + "api-ms-win-crt-heap-l1-1-0", + "api-ms-win-crt-locale-l1-1-0", + "api-ms-win-crt-math-l1-1-0", + "api-ms-win-crt-runtime-l1-1-0", + "api-ms-win-crt-stdio-l1-1-0", + "api-ms-win-crt-string-l1-1-0", + "api-ms-win-crt-time-l1-1-0", + "api-ms-win-crt-utility-l1-1-0", + "shell32", # this is delayed + "ole32",]), # also delayed + "arm64": set(["advapi32", + "kernel32", + "ntdll", + "msvcp140", + "vcruntime140", + "api-ms-win-crt-convert-l1-1-0", + "api-ms-win-crt-environment-l1-1-0", # noqa: E501 + "api-ms-win-crt-heap-l1-1-0", + "api-ms-win-crt-locale-l1-1-0", + "api-ms-win-crt-math-l1-1-0", + "api-ms-win-crt-runtime-l1-1-0", + "api-ms-win-crt-stdio-l1-1-0", + "api-ms-win-crt-string-l1-1-0", + "api-ms-win-crt-time-l1-1-0", + "api-ms-win-crt-utility-l1-1-0", + "shell32", # this is delayed + "ole32",]), # also delayed + }, # end windows + "darwin": {"x86_64": set(["llvmlite", + "system", + "z", + "corefoundation", + "c++",]), + "arm64": set(["llvmlite", + "system", + "z", + "c++",]), + },# end darwin + } # end wheel_expected + + conda_expected = {"linux": {"x86_64": set(["pthread", + "z", + "zstd", + "dl", + "m", + "gcc_s", + "c", + # "stdc++", conda has static c++ + "ld-linux-x86-64",]), + "aarch64": set(["pthread", + "z", + "zstd", + "dl", + "m", + "gcc_s", + "c", + # "stdc++", conda has static c++ # noqa: E501 + "ld-linux-aarch64",]), + }, # end linux + # NOTE: on windows, this includes a "capture what is + # present and known to work and make sure it doesn"t + # change" approach. + "windows": {"amd64": set(["z", + "zstd", + "advapi32", + "kernel32", + "ntdll", + "msvcp140", + "vcruntime140", + "vcruntime140_1", + "api-ms-win-crt-convert-l1-1-0", + "api-ms-win-crt-environment-l1-1-0", # noqa: E501 + "api-ms-win-crt-heap-l1-1-0", + "api-ms-win-crt-locale-l1-1-0", + "api-ms-win-crt-math-l1-1-0", + "api-ms-win-crt-runtime-l1-1-0", + "api-ms-win-crt-stdio-l1-1-0", + "api-ms-win-crt-string-l1-1-0", + "api-ms-win-crt-time-l1-1-0", + "api-ms-win-crt-utility-l1-1-0", + "shell32", # this is delayed + "ole32",]), # also delayed + "arm64": set(["z", + "zstd", + "advapi32", + "kernel32", + "ntdll", + "msvcp140", + "vcruntime140", + "api-ms-win-crt-convert-l1-1-0", + "api-ms-win-crt-environment-l1-1-0", # noqa: E501 + "api-ms-win-crt-heap-l1-1-0", + "api-ms-win-crt-locale-l1-1-0", + "api-ms-win-crt-math-l1-1-0", + "api-ms-win-crt-runtime-l1-1-0", + "api-ms-win-crt-stdio-l1-1-0", + "api-ms-win-crt-string-l1-1-0", + "api-ms-win-crt-time-l1-1-0", + "api-ms-win-crt-utility-l1-1-0", + "shell32", # this is delayed + "ole32",]), # also delayed + }, # end windows + "darwin": {"x86_64": set(["llvmlite", + "system", + "z", + "zstd", + "corefoundation", + "c++",]), + "arm64": set(["llvmlite", + "system", + "z", + "zstd", + "c++",]), + },# end darwin + } # end conda_expected + + def check_linkage(self, info, package_type): + machine = platform.machine().lower() + os_name = platform.system().lower() + + if package_type == "wheel": + expected = self.wheel_expected[os_name][machine] + elif package_type == "conda": + expected = self.conda_expected[os_name][machine] + else: + raise ValueError(f"Unexpected package type: {package_type}") + + got = set(info["canonicalised_linked_libraries"]) + # Normalize delvewheel-bundled MSVCP hashed name (e.g. msvcp140-) + got = { + ("msvcp140" if lib.startswith("msvcp140") else lib) + for lib in got + } + + try: + self.assertEqual(expected, got) + except AssertionError as e: + msg = ("Unexpected linkage encountered for libllvmlite:\n" + f"Expected: {sorted(expected)}\n" + f" Got: {sorted(got)}\n\n" + f"Difference: {set.symmetric_difference(expected, got)}\n" + f"Only in Expected: {set.difference(expected, got)}\n" + f"Only in Got: {set.difference(got, expected)}\n") + raise AssertionError(msg) from e + + @is_wheel_package + def test_wheel_build(self): + info = llvm.config.get_sysinfo() + self.assertEqual(info['llvm_linkage_type'], "static") + self.assertEqual(info['llvm_assertions_state'], "on") + self.check_linkage(info, "wheel") + + @is_conda_package + def test_conda_build(self): + info = llvm.config.get_sysinfo() + self.assertEqual(info['llvm_linkage_type'], "static") + self.assertEqual(info['llvm_assertions_state'], "on") + + self.check_linkage(info, "conda") + if platform.system().lower() == "linux": + self.assertEqual(info['libstdcxx_linkage_type'], "static") + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/package-files/78/7804c60e8590851a7c6094fa7586b0b865932814a9c0f850ac41400493169b64/blob b/shared/package-files/78/7804c60e8590851a7c6094fa7586b0b865932814a9c0f850ac41400493169b64/blob new file mode 100644 index 0000000000000000000000000000000000000000..271653aaf39d3bd99580a78423adc41e42912f82 Binary files /dev/null and b/shared/package-files/78/7804c60e8590851a7c6094fa7586b0b865932814a9c0f850ac41400493169b64/blob differ diff --git a/shared/package-files/78/78056cbb55d47a890b87b2a8d3e6c335442a995ac60323afbfdbc97560908f43/blob b/shared/package-files/78/78056cbb55d47a890b87b2a8d3e6c335442a995ac60323afbfdbc97560908f43/blob new file mode 100644 index 0000000000000000000000000000000000000000..2b3f3d3d16ac6c49d231ac526fa89570975e4bfb --- /dev/null +++ b/shared/package-files/78/78056cbb55d47a890b87b2a8d3e6c335442a995ac60323afbfdbc97560908f43/blob @@ -0,0 +1,126 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize( + "ufunc", [np.add, np.logical_or, np.logical_and, np.logical_xor] +) +def test_ufuncs_binary(ufunc): + # two BooleanArrays + a = pd.array([True, False, None], dtype="boolean") + result = ufunc(a, a) + expected = pd.array(ufunc(a._data, a._data), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_extension_array_equal(result, expected) + + s = pd.Series(a) + result = ufunc(s, a) + expected = pd.Series(ufunc(a._data, a._data), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_series_equal(result, expected) + + # Boolean with numpy array + arr = np.array([True, True, False]) + result = ufunc(a, arr) + expected = pd.array(ufunc(a._data, arr), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_extension_array_equal(result, expected) + + result = ufunc(arr, a) + expected = pd.array(ufunc(arr, a._data), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_extension_array_equal(result, expected) + + # BooleanArray with scalar + result = ufunc(a, True) + expected = pd.array(ufunc(a._data, True), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_extension_array_equal(result, expected) + + result = ufunc(True, a) + expected = pd.array(ufunc(True, a._data), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_extension_array_equal(result, expected) + + # not handled types + msg = r"operand type\(s\) all returned NotImplemented from __array_ufunc__" + with pytest.raises(TypeError, match=msg): + ufunc(a, "test") + + +@pytest.mark.parametrize("ufunc", [np.logical_not]) +def test_ufuncs_unary(ufunc): + a = pd.array([True, False, None], dtype="boolean") + result = ufunc(a) + expected = pd.array(ufunc(a._data), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_extension_array_equal(result, expected) + + ser = pd.Series(a) + result = ufunc(ser) + expected = pd.Series(ufunc(a._data), dtype="boolean") + expected[a._mask] = np.nan + tm.assert_series_equal(result, expected) + + +def test_ufunc_numeric(): + # np.sqrt on np.bool_ returns float16, which we upcast to Float32 + # bc we do not have Float16 + arr = pd.array([True, False, None], dtype="boolean") + + res = np.sqrt(arr) + + expected = pd.array([1, 0, None], dtype="Float32") + tm.assert_extension_array_equal(res, expected) + + +@pytest.mark.parametrize("values", [[True, False], [True, None]]) +def test_ufunc_reduce_raises(values): + arr = pd.array(values, dtype="boolean") + + res = np.add.reduce(arr) + if arr[-1] is pd.NA: + expected = pd.NA + else: + expected = arr._data.sum() + tm.assert_almost_equal(res, expected) + + +def test_value_counts_na(): + arr = pd.array([True, False, pd.NA], dtype="boolean") + result = arr.value_counts(dropna=False) + expected = pd.Series([1, 1, 1], index=arr, dtype="Int64", name="count") + assert expected.index.dtype == arr.dtype + tm.assert_series_equal(result, expected) + + result = arr.value_counts(dropna=True) + expected = pd.Series([1, 1], index=arr[:-1], dtype="Int64", name="count") + assert expected.index.dtype == arr.dtype + tm.assert_series_equal(result, expected) + + +def test_value_counts_with_normalize(): + ser = pd.Series([True, False, pd.NA], dtype="boolean") + result = ser.value_counts(normalize=True) + expected = pd.Series([1, 1], index=ser[:-1], dtype="Float64", name="proportion") / 2 + assert expected.index.dtype == "boolean" + tm.assert_series_equal(result, expected) + + +def test_diff(): + a = pd.array( + [True, True, False, False, True, None, True, None, False], dtype="boolean" + ) + result = pd.core.algorithms.diff(a, 1) + expected = pd.array( + [None, False, True, False, True, None, None, None, None], dtype="boolean" + ) + tm.assert_extension_array_equal(result, expected) + + ser = pd.Series(a) + result = ser.diff() + expected = pd.Series(expected) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/78/78089cf4cffcf52f176e4d61117d31c887815b61ab0303ce4e936e3686f74da5/blob b/shared/package-files/78/78089cf4cffcf52f176e4d61117d31c887815b61ab0303ce4e936e3686f74da5/blob new file mode 100644 index 0000000000000000000000000000000000000000..a0420bbd406ec873022ee3a6e511c51fafd82f11 --- /dev/null +++ b/shared/package-files/78/78089cf4cffcf52f176e4d61117d31c887815b61ab0303ce4e936e3686f74da5/blob @@ -0,0 +1,413 @@ +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy.sparse import issparse + +from sklearn import datasets +from sklearn.metrics import pairwise_distances +from sklearn.metrics.cluster import ( + calinski_harabasz_score, + davies_bouldin_score, + silhouette_samples, + silhouette_score, +) +from sklearn.metrics.cluster._unsupervised import _silhouette_reduce +from sklearn.utils._testing import assert_array_equal +from sklearn.utils.fixes import ( + CSC_CONTAINERS, + CSR_CONTAINERS, + DOK_CONTAINERS, + LIL_CONTAINERS, +) + + +@pytest.mark.parametrize( + "sparse_container", + [None] + CSR_CONTAINERS + CSC_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +@pytest.mark.parametrize("sample_size", [None, "half"]) +def test_silhouette(sparse_container, sample_size): + # Tests the Silhouette Coefficient. + dataset = datasets.load_iris() + X, y = dataset.data, dataset.target + if sparse_container is not None: + X = sparse_container(X) + sample_size = int(X.shape[0] / 2) if sample_size == "half" else sample_size + + D = pairwise_distances(X, metric="euclidean") + # Given that the actual labels are used, we can assume that S would be positive. + score_precomputed = silhouette_score( + D, y, metric="precomputed", sample_size=sample_size, random_state=0 + ) + score_euclidean = silhouette_score( + X, y, metric="euclidean", sample_size=sample_size, random_state=0 + ) + assert score_precomputed > 0 + assert score_euclidean > 0 + assert score_precomputed == pytest.approx(score_euclidean) + + +def test_cluster_size_1(): + # Assert Silhouette Coefficient == 0 when there is 1 sample in a cluster + # (cluster 0). We also test the case where there are identical samples + # as the only members of a cluster (cluster 2). To our knowledge, this case + # is not discussed in reference material, and we choose for it a sample + # score of 1. + X = [[0.0], [1.0], [1.0], [2.0], [3.0], [3.0]] + labels = np.array([0, 1, 1, 1, 2, 2]) + + # Cluster 0: 1 sample -> score of 0 by Rousseeuw's convention + # Cluster 1: intra-cluster = [.5, .5, 1] + # inter-cluster = [1, 1, 1] + # silhouette = [.5, .5, 0] + # Cluster 2: intra-cluster = [0, 0] + # inter-cluster = [arbitrary, arbitrary] + # silhouette = [1., 1.] + + silhouette = silhouette_score(X, labels) + assert not np.isnan(silhouette) + ss = silhouette_samples(X, labels) + assert_array_equal(ss, [0, 0.5, 0.5, 0, 1, 1]) + + +def test_silhouette_paper_example(): + # Explicitly check per-sample results against Rousseeuw (1987) + # Data from Table 1 + lower = [ + 5.58, + 7.00, + 6.50, + 7.08, + 7.00, + 3.83, + 4.83, + 5.08, + 8.17, + 5.83, + 2.17, + 5.75, + 6.67, + 6.92, + 4.92, + 6.42, + 5.00, + 5.58, + 6.00, + 4.67, + 6.42, + 3.42, + 5.50, + 6.42, + 6.42, + 5.00, + 3.92, + 6.17, + 2.50, + 4.92, + 6.25, + 7.33, + 4.50, + 2.25, + 6.33, + 2.75, + 6.08, + 6.67, + 4.25, + 2.67, + 6.00, + 6.17, + 6.17, + 6.92, + 6.17, + 5.25, + 6.83, + 4.50, + 3.75, + 5.75, + 5.42, + 6.08, + 5.83, + 6.67, + 3.67, + 4.75, + 3.00, + 6.08, + 6.67, + 5.00, + 5.58, + 4.83, + 6.17, + 5.67, + 6.50, + 6.92, + ] + D = np.zeros((12, 12)) + D[np.tril_indices(12, -1)] = lower + D += D.T + + names = [ + "BEL", + "BRA", + "CHI", + "CUB", + "EGY", + "FRA", + "IND", + "ISR", + "USA", + "USS", + "YUG", + "ZAI", + ] + + # Data from Figure 2 + labels1 = [1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1] + expected1 = { + "USA": 0.43, + "BEL": 0.39, + "FRA": 0.35, + "ISR": 0.30, + "BRA": 0.22, + "EGY": 0.20, + "ZAI": 0.19, + "CUB": 0.40, + "USS": 0.34, + "CHI": 0.33, + "YUG": 0.26, + "IND": -0.04, + } + score1 = 0.28 + + # Data from Figure 3 + labels2 = [1, 2, 3, 3, 1, 1, 2, 1, 1, 3, 3, 2] + expected2 = { + "USA": 0.47, + "FRA": 0.44, + "BEL": 0.42, + "ISR": 0.37, + "EGY": 0.02, + "ZAI": 0.28, + "BRA": 0.25, + "IND": 0.17, + "CUB": 0.48, + "USS": 0.44, + "YUG": 0.31, + "CHI": 0.31, + } + score2 = 0.33 + + for labels, expected, score in [ + (labels1, expected1, score1), + (labels2, expected2, score2), + ]: + expected = [expected[name] for name in names] + # we check to 2dp because that's what's in the paper + pytest.approx( + expected, + silhouette_samples(D, np.array(labels), metric="precomputed"), + abs=1e-2, + ) + pytest.approx( + score, silhouette_score(D, np.array(labels), metric="precomputed"), abs=1e-2 + ) + + +def test_correct_labelsize(): + # Assert 1 < n_labels < n_samples + dataset = datasets.load_iris() + X = dataset.data + + # n_labels = n_samples + y = np.arange(X.shape[0]) + err_msg = ( + r"Number of labels is %d\. Valid values are 2 " + r"to n_samples - 1 \(inclusive\)" % len(np.unique(y)) + ) + with pytest.raises(ValueError, match=err_msg): + silhouette_score(X, y) + + # n_labels = 1 + y = np.zeros(X.shape[0]) + err_msg = ( + r"Number of labels is %d\. Valid values are 2 " + r"to n_samples - 1 \(inclusive\)" % len(np.unique(y)) + ) + with pytest.raises(ValueError, match=err_msg): + silhouette_score(X, y) + + +def test_non_encoded_labels(): + dataset = datasets.load_iris() + X = dataset.data + labels = dataset.target + assert silhouette_score(X, labels * 2 + 10) == silhouette_score(X, labels) + assert_array_equal( + silhouette_samples(X, labels * 2 + 10), silhouette_samples(X, labels) + ) + + +def test_non_numpy_labels(): + dataset = datasets.load_iris() + X = dataset.data + y = dataset.target + assert silhouette_score(list(X), list(y)) == silhouette_score(X, y) + + +@pytest.mark.parametrize("dtype", (np.float32, np.float64)) +def test_silhouette_nonzero_diag(dtype): + # Make sure silhouette_samples requires diagonal to be zero. + # Non-regression test for #12178 + + # Construct a zero-diagonal matrix + dists = pairwise_distances( + np.array([[0.2, 0.1, 0.12, 1.34, 1.11, 1.6]], dtype=dtype).T + ) + labels = [0, 0, 0, 1, 1, 1] + + # small values on the diagonal are OK + dists[2][2] = np.finfo(dists.dtype).eps * 10 + silhouette_samples(dists, labels, metric="precomputed") + + # values bigger than eps * 100 are not + dists[2][2] = np.finfo(dists.dtype).eps * 1000 + with pytest.raises(ValueError, match="contains non-zero"): + silhouette_samples(dists, labels, metric="precomputed") + + +@pytest.mark.parametrize( + "sparse_container", + CSC_CONTAINERS + CSR_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +def test_silhouette_samples_precomputed_sparse(sparse_container): + """Check that silhouette_samples works for sparse matrices correctly.""" + X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T + y = [0, 0, 0, 0, 1, 1, 1, 1] + pdist_dense = pairwise_distances(X) + pdist_sparse = sparse_container(pdist_dense) + assert issparse(pdist_sparse) + output_with_sparse_input = silhouette_samples(pdist_sparse, y, metric="precomputed") + output_with_dense_input = silhouette_samples(pdist_dense, y, metric="precomputed") + assert_allclose(output_with_sparse_input, output_with_dense_input) + + +@pytest.mark.parametrize( + "sparse_container", + CSC_CONTAINERS + CSR_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +def test_silhouette_samples_euclidean_sparse(sparse_container): + """Check that silhouette_samples works for sparse matrices correctly.""" + X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T + y = [0, 0, 0, 0, 1, 1, 1, 1] + pdist_dense = pairwise_distances(X) + pdist_sparse = sparse_container(pdist_dense) + assert issparse(pdist_sparse) + output_with_sparse_input = silhouette_samples(pdist_sparse, y) + output_with_dense_input = silhouette_samples(pdist_dense, y) + assert_allclose(output_with_sparse_input, output_with_dense_input) + + +@pytest.mark.parametrize( + "sparse_container", CSC_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS +) +def test_silhouette_reduce(sparse_container): + """Check for non-CSR input to private method `_silhouette_reduce`.""" + X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T + pdist_dense = pairwise_distances(X) + pdist_sparse = sparse_container(pdist_dense) + y = [0, 0, 0, 0, 1, 1, 1, 1] + label_freqs = np.bincount(y) + with pytest.raises( + TypeError, + match="Expected CSR matrix. Please pass sparse matrix in CSR format.", + ): + _silhouette_reduce(pdist_sparse, start=0, labels=y, label_freqs=label_freqs) + + +def assert_raises_on_only_one_label(func): + """Assert message when there is only one label""" + rng = np.random.RandomState(seed=0) + with pytest.raises(ValueError, match="Number of labels is"): + func(rng.rand(10, 2), np.zeros(10)) + + +def assert_raises_on_all_points_same_cluster(func): + """Assert message when all point are in different clusters""" + rng = np.random.RandomState(seed=0) + with pytest.raises(ValueError, match="Number of labels is"): + func(rng.rand(10, 2), np.arange(10)) + + +def test_calinski_harabasz_score(): + assert_raises_on_only_one_label(calinski_harabasz_score) + + assert_raises_on_all_points_same_cluster(calinski_harabasz_score) + + # Assert the value is 1. when all samples are equals + assert 1.0 == calinski_harabasz_score(np.ones((10, 2)), [0] * 5 + [1] * 5) + + # Assert the value is 0. when all the mean cluster are equal + assert 0.0 == calinski_harabasz_score([[-1, -1], [1, 1]] * 10, [0] * 10 + [1] * 10) + + # General case (with non numpy arrays) + X = ( + [[0, 0], [1, 1]] * 5 + + [[3, 3], [4, 4]] * 5 + + [[0, 4], [1, 3]] * 5 + + [[3, 1], [4, 0]] * 5 + ) + labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10 + pytest.approx(calinski_harabasz_score(X, labels), 45 * (40 - 4) / (5 * (4 - 1))) + + +def test_davies_bouldin_score(): + assert_raises_on_only_one_label(davies_bouldin_score) + assert_raises_on_all_points_same_cluster(davies_bouldin_score) + + # Assert the value is 0. when all samples are equals + assert davies_bouldin_score(np.ones((10, 2)), [0] * 5 + [1] * 5) == pytest.approx( + 0.0 + ) + + # Assert the value is 0. when all the mean cluster are equal + assert davies_bouldin_score( + [[-1, -1], [1, 1]] * 10, [0] * 10 + [1] * 10 + ) == pytest.approx(0.0) + + # General case (with non numpy arrays) + X = ( + [[0, 0], [1, 1]] * 5 + + [[3, 3], [4, 4]] * 5 + + [[0, 4], [1, 3]] * 5 + + [[3, 1], [4, 0]] * 5 + ) + labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10 + pytest.approx(davies_bouldin_score(X, labels), 2 * np.sqrt(0.5) / 3) + + # Ensure divide by zero warning is not raised in general case + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + davies_bouldin_score(X, labels) + + # General case - cluster have one sample + X = [[0, 0], [2, 2], [3, 3], [5, 5]] + labels = [0, 0, 1, 2] + pytest.approx(davies_bouldin_score(X, labels), (5.0 / 4) / 3) + + +def test_silhouette_score_integer_precomputed(): + """Check that silhouette_score works for precomputed metrics that are integers. + + Non-regression test for #22107. + """ + result = silhouette_score( + [[0, 1, 2], [1, 0, 1], [2, 1, 0]], [0, 0, 1], metric="precomputed" + ) + assert result == pytest.approx(1 / 6) + + # non-zero on diagonal for ints raises an error + with pytest.raises(ValueError, match="contains non-zero"): + silhouette_score( + [[1, 1, 2], [1, 0, 1], [2, 1, 0]], [0, 0, 1], metric="precomputed" + ) diff --git a/shared/package-files/78/780a7c6d575ce5560eefe2da913401125f0192ef88d7172cb64a7ec27dac6e6f/blob b/shared/package-files/78/780a7c6d575ce5560eefe2da913401125f0192ef88d7172cb64a7ec27dac6e6f/blob new file mode 100644 index 0000000000000000000000000000000000000000..9c55012c158e19df20e4c4770867fc19398213d0 --- /dev/null +++ b/shared/package-files/78/780a7c6d575ce5560eefe2da913401125f0192ef88d7172cb64a7ec27dac6e6f/blob @@ -0,0 +1,374 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +import pytest + +from sklearn import datasets +from sklearn.covariance import ( + OAS, + EmpiricalCovariance, + LedoitWolf, + ShrunkCovariance, + empirical_covariance, + ledoit_wolf, + ledoit_wolf_shrinkage, + oas, + shrunk_covariance, +) +from sklearn.covariance._shrunk_covariance import _ledoit_wolf +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) + +from .._shrunk_covariance import _oas + +X, _ = datasets.load_diabetes(return_X_y=True) +X_1d = X[:, 0] +n_samples, n_features = X.shape + + +def test_covariance(): + # Tests Covariance module on a simple dataset. + # test covariance fit from data + cov = EmpiricalCovariance() + cov.fit(X) + emp_cov = empirical_covariance(X) + assert_array_almost_equal(emp_cov, cov.covariance_, 4) + assert_almost_equal(cov.error_norm(emp_cov), 0) + assert_almost_equal(cov.error_norm(emp_cov, norm="spectral"), 0) + assert_almost_equal(cov.error_norm(emp_cov, norm="frobenius"), 0) + assert_almost_equal(cov.error_norm(emp_cov, scaling=False), 0) + assert_almost_equal(cov.error_norm(emp_cov, squared=False), 0) + with pytest.raises(NotImplementedError): + cov.error_norm(emp_cov, norm="foo") + # Mahalanobis distances computation test + mahal_dist = cov.mahalanobis(X) + assert np.amin(mahal_dist) > 0 + + # test with n_features = 1 + X_1d = X[:, 0].reshape((-1, 1)) + cov = EmpiricalCovariance() + cov.fit(X_1d) + assert_array_almost_equal(empirical_covariance(X_1d), cov.covariance_, 4) + assert_almost_equal(cov.error_norm(empirical_covariance(X_1d)), 0) + assert_almost_equal(cov.error_norm(empirical_covariance(X_1d), norm="spectral"), 0) + + # test with one sample + # Create X with 1 sample and 5 features + X_1sample = np.arange(5).reshape(1, 5) + cov = EmpiricalCovariance() + warn_msg = "Only one sample available. You may want to reshape your data array" + with pytest.warns(UserWarning, match=warn_msg): + cov.fit(X_1sample) + + assert_array_almost_equal(cov.covariance_, np.zeros(shape=(5, 5), dtype=np.float64)) + + # test integer type + X_integer = np.asarray([[0, 1], [1, 0]]) + result = np.asarray([[0.25, -0.25], [-0.25, 0.25]]) + assert_array_almost_equal(empirical_covariance(X_integer), result) + + # test centered case + cov = EmpiricalCovariance(assume_centered=True) + cov.fit(X) + assert_array_equal(cov.location_, np.zeros(X.shape[1])) + + +@pytest.mark.parametrize("n_matrices", [1, 3]) +def test_shrunk_covariance_func(n_matrices): + """Check `shrunk_covariance` function.""" + + n_features = 2 + cov = np.ones((n_features, n_features)) + cov_target = np.array([[1, 0.5], [0.5, 1]]) + + if n_matrices > 1: + cov = np.repeat(cov[np.newaxis, ...], n_matrices, axis=0) + cov_target = np.repeat(cov_target[np.newaxis, ...], n_matrices, axis=0) + + cov_shrunk = shrunk_covariance(cov, 0.5) + assert_allclose(cov_shrunk, cov_target) + + +def test_shrunk_covariance(): + """Check consistency between `ShrunkCovariance` and `shrunk_covariance`.""" + + # Tests ShrunkCovariance module on a simple dataset. + # compare shrunk covariance obtained from data and from MLE estimate + cov = ShrunkCovariance(shrinkage=0.5) + cov.fit(X) + assert_array_almost_equal( + shrunk_covariance(empirical_covariance(X), shrinkage=0.5), cov.covariance_, 4 + ) + + # same test with shrinkage not provided + cov = ShrunkCovariance() + cov.fit(X) + assert_array_almost_equal( + shrunk_covariance(empirical_covariance(X)), cov.covariance_, 4 + ) + + # same test with shrinkage = 0 (<==> empirical_covariance) + cov = ShrunkCovariance(shrinkage=0.0) + cov.fit(X) + assert_array_almost_equal(empirical_covariance(X), cov.covariance_, 4) + + # test with n_features = 1 + X_1d = X[:, 0].reshape((-1, 1)) + cov = ShrunkCovariance(shrinkage=0.3) + cov.fit(X_1d) + assert_array_almost_equal(empirical_covariance(X_1d), cov.covariance_, 4) + + # test shrinkage coeff on a simple data set (without saving precision) + cov = ShrunkCovariance(shrinkage=0.5, store_precision=False) + cov.fit(X) + assert cov.precision_ is None + + +def test_ledoit_wolf(): + # Tests LedoitWolf module on a simple dataset. + # test shrinkage coeff on a simple data set + X_centered = X - X.mean(axis=0) + lw = LedoitWolf(assume_centered=True) + lw.fit(X_centered) + shrinkage_ = lw.shrinkage_ + + score_ = lw.score(X_centered) + assert_almost_equal( + ledoit_wolf_shrinkage(X_centered, assume_centered=True), shrinkage_ + ) + assert_almost_equal( + ledoit_wolf_shrinkage(X_centered, assume_centered=True, block_size=6), + shrinkage_, + ) + # compare shrunk covariance obtained from data and from MLE estimate + lw_cov_from_mle, lw_shrinkage_from_mle = ledoit_wolf( + X_centered, assume_centered=True + ) + assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4) + assert_almost_equal(lw_shrinkage_from_mle, lw.shrinkage_) + # compare estimates given by LW and ShrunkCovariance + scov = ShrunkCovariance(shrinkage=lw.shrinkage_, assume_centered=True) + scov.fit(X_centered) + assert_array_almost_equal(scov.covariance_, lw.covariance_, 4) + + # test with n_features = 1 + X_1d = X[:, 0].reshape((-1, 1)) + lw = LedoitWolf(assume_centered=True) + lw.fit(X_1d) + lw_cov_from_mle, lw_shrinkage_from_mle = ledoit_wolf(X_1d, assume_centered=True) + assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4) + assert_almost_equal(lw_shrinkage_from_mle, lw.shrinkage_) + assert_array_almost_equal((X_1d**2).sum() / n_samples, lw.covariance_, 4) + + # test shrinkage coeff on a simple data set (without saving precision) + lw = LedoitWolf(store_precision=False, assume_centered=True) + lw.fit(X_centered) + assert_almost_equal(lw.score(X_centered), score_, 4) + assert lw.precision_ is None + + # Same tests without assuming centered data + # test shrinkage coeff on a simple data set + lw = LedoitWolf() + lw.fit(X) + assert_almost_equal(lw.shrinkage_, shrinkage_, 4) + assert_almost_equal(lw.shrinkage_, ledoit_wolf_shrinkage(X)) + assert_almost_equal(lw.shrinkage_, ledoit_wolf(X)[1]) + assert_almost_equal( + lw.shrinkage_, _ledoit_wolf(X=X, assume_centered=False, block_size=10000)[1] + ) + assert_almost_equal(lw.score(X), score_, 4) + # compare shrunk covariance obtained from data and from MLE estimate + lw_cov_from_mle, lw_shrinkage_from_mle = ledoit_wolf(X) + assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4) + assert_almost_equal(lw_shrinkage_from_mle, lw.shrinkage_) + # compare estimates given by LW and ShrunkCovariance + scov = ShrunkCovariance(shrinkage=lw.shrinkage_) + scov.fit(X) + assert_array_almost_equal(scov.covariance_, lw.covariance_, 4) + + # test with n_features = 1 + X_1d = X[:, 0].reshape((-1, 1)) + lw = LedoitWolf() + lw.fit(X_1d) + assert_allclose( + X_1d.var(ddof=0), + _ledoit_wolf(X=X_1d, assume_centered=False, block_size=10000)[0], + ) + lw_cov_from_mle, lw_shrinkage_from_mle = ledoit_wolf(X_1d) + assert_array_almost_equal(lw_cov_from_mle, lw.covariance_, 4) + assert_almost_equal(lw_shrinkage_from_mle, lw.shrinkage_) + assert_array_almost_equal(empirical_covariance(X_1d), lw.covariance_, 4) + + # test with one sample + # warning should be raised when using only 1 sample + X_1sample = np.arange(5).reshape(1, 5) + lw = LedoitWolf() + + warn_msg = "Only one sample available. You may want to reshape your data array" + with pytest.warns(UserWarning, match=warn_msg): + lw.fit(X_1sample) + + assert_array_almost_equal(lw.covariance_, np.zeros(shape=(5, 5), dtype=np.float64)) + + # test shrinkage coeff on a simple data set (without saving precision) + lw = LedoitWolf(store_precision=False) + lw.fit(X) + assert_almost_equal(lw.score(X), score_, 4) + assert lw.precision_ is None + + +def _naive_ledoit_wolf_shrinkage(X): + # A simple implementation of the formulas from Ledoit & Wolf + + # The computation below achieves the following computations of the + # "O. Ledoit and M. Wolf, A Well-Conditioned Estimator for + # Large-Dimensional Covariance Matrices" + # beta and delta are given in the beginning of section 3.2 + n_samples, n_features = X.shape + emp_cov = empirical_covariance(X, assume_centered=False) + mu = np.trace(emp_cov) / n_features + delta_ = emp_cov.copy() + delta_.flat[:: n_features + 1] -= mu + delta = (delta_**2).sum() / n_features + X2 = X**2 + beta_ = ( + 1.0 + / (n_features * n_samples) + * np.sum(np.dot(X2.T, X2) / n_samples - emp_cov**2) + ) + + beta = min(beta_, delta) + shrinkage = beta / delta + return shrinkage + + +def test_ledoit_wolf_small(): + # Compare our blocked implementation to the naive implementation + X_small = X[:, :4] + lw = LedoitWolf() + lw.fit(X_small) + shrinkage_ = lw.shrinkage_ + + assert_almost_equal(shrinkage_, _naive_ledoit_wolf_shrinkage(X_small)) + + +def test_ledoit_wolf_large(): + # test that ledoit_wolf doesn't error on data that is wider than block_size + rng = np.random.RandomState(0) + # use a number of features that is larger than the block-size + X = rng.normal(size=(10, 20)) + lw = LedoitWolf(block_size=10).fit(X) + # check that covariance is about diagonal (random normal noise) + assert_almost_equal(lw.covariance_, np.eye(20), 0) + cov = lw.covariance_ + + # check that the result is consistent with not splitting data into blocks. + lw = LedoitWolf(block_size=25).fit(X) + assert_almost_equal(lw.covariance_, cov) + + +@pytest.mark.parametrize( + "ledoit_wolf_fitting_function", [LedoitWolf().fit, ledoit_wolf_shrinkage] +) +def test_ledoit_wolf_empty_array(ledoit_wolf_fitting_function): + """Check that we validate X and raise proper error with 0-sample array.""" + X_empty = np.zeros((0, 2)) + with pytest.raises(ValueError, match="Found array with 0 sample"): + ledoit_wolf_fitting_function(X_empty) + + +def test_oas(): + # Tests OAS module on a simple dataset. + # test shrinkage coeff on a simple data set + X_centered = X - X.mean(axis=0) + oa = OAS(assume_centered=True) + oa.fit(X_centered) + shrinkage_ = oa.shrinkage_ + score_ = oa.score(X_centered) + # compare shrunk covariance obtained from data and from MLE estimate + oa_cov_from_mle, oa_shrinkage_from_mle = oas(X_centered, assume_centered=True) + assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4) + assert_almost_equal(oa_shrinkage_from_mle, oa.shrinkage_) + # compare estimates given by OAS and ShrunkCovariance + scov = ShrunkCovariance(shrinkage=oa.shrinkage_, assume_centered=True) + scov.fit(X_centered) + assert_array_almost_equal(scov.covariance_, oa.covariance_, 4) + + # test with n_features = 1 + X_1d = X[:, 0:1] + oa = OAS(assume_centered=True) + oa.fit(X_1d) + oa_cov_from_mle, oa_shrinkage_from_mle = oas(X_1d, assume_centered=True) + assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4) + assert_almost_equal(oa_shrinkage_from_mle, oa.shrinkage_) + assert_array_almost_equal((X_1d**2).sum() / n_samples, oa.covariance_, 4) + + # test shrinkage coeff on a simple data set (without saving precision) + oa = OAS(store_precision=False, assume_centered=True) + oa.fit(X_centered) + assert_almost_equal(oa.score(X_centered), score_, 4) + assert oa.precision_ is None + + # Same tests without assuming centered data-------------------------------- + # test shrinkage coeff on a simple data set + oa = OAS() + oa.fit(X) + assert_almost_equal(oa.shrinkage_, shrinkage_, 4) + assert_almost_equal(oa.score(X), score_, 4) + # compare shrunk covariance obtained from data and from MLE estimate + oa_cov_from_mle, oa_shrinkage_from_mle = oas(X) + assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4) + assert_almost_equal(oa_shrinkage_from_mle, oa.shrinkage_) + # compare estimates given by OAS and ShrunkCovariance + scov = ShrunkCovariance(shrinkage=oa.shrinkage_) + scov.fit(X) + assert_array_almost_equal(scov.covariance_, oa.covariance_, 4) + + # test with n_features = 1 + X_1d = X[:, 0].reshape((-1, 1)) + oa = OAS() + oa.fit(X_1d) + oa_cov_from_mle, oa_shrinkage_from_mle = oas(X_1d) + assert_array_almost_equal(oa_cov_from_mle, oa.covariance_, 4) + assert_almost_equal(oa_shrinkage_from_mle, oa.shrinkage_) + assert_array_almost_equal(empirical_covariance(X_1d), oa.covariance_, 4) + + # test with one sample + # warning should be raised when using only 1 sample + X_1sample = np.arange(5).reshape(1, 5) + oa = OAS() + warn_msg = "Only one sample available. You may want to reshape your data array" + with pytest.warns(UserWarning, match=warn_msg): + oa.fit(X_1sample) + + assert_array_almost_equal(oa.covariance_, np.zeros(shape=(5, 5), dtype=np.float64)) + + # test shrinkage coeff on a simple data set (without saving precision) + oa = OAS(store_precision=False) + oa.fit(X) + assert_almost_equal(oa.score(X), score_, 4) + assert oa.precision_ is None + + # test function _oas without assuming centered data + X_1f = X[:, 0:1] + oa = OAS() + oa.fit(X_1f) + # compare shrunk covariance obtained from data and from MLE estimate + _oa_cov_from_mle, _oa_shrinkage_from_mle = _oas(X_1f) + assert_array_almost_equal(_oa_cov_from_mle, oa.covariance_, 4) + assert_almost_equal(_oa_shrinkage_from_mle, oa.shrinkage_) + assert_array_almost_equal((X_1f**2).sum() / n_samples, oa.covariance_, 4) + + +def test_EmpiricalCovariance_validates_mahalanobis(): + """Checks that EmpiricalCovariance validates data with mahalanobis.""" + cov = EmpiricalCovariance().fit(X) + + msg = f"X has 2 features, but \\w+ is expecting {X.shape[1]} features as input" + with pytest.raises(ValueError, match=msg): + cov.mahalanobis(X[:, :2]) diff --git a/shared/package-files/78/780e9d69c47544c55ee76615e053cb9a1c17028619949ab4b7d134990dd2b6df/blob b/shared/package-files/78/780e9d69c47544c55ee76615e053cb9a1c17028619949ab4b7d134990dd2b6df/blob new file mode 100644 index 0000000000000000000000000000000000000000..cf7e868f609fc5c3d4de9af5f168bb063114bd2c --- /dev/null +++ b/shared/package-files/78/780e9d69c47544c55ee76615e053cb9a1c17028619949ab4b7d134990dd2b6df/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API void set_data(at::Tensor & self, const at::Tensor & new_data); +} // namespace native +} // namespace at diff --git a/shared/package-files/78/780eee61766bd29d1a6b3e6b056f84ca92f1f51721aefa8362d4a7904250b18c/blob b/shared/package-files/78/780eee61766bd29d1a6b3e6b056f84ca92f1f51721aefa8362d4a7904250b18c/blob new file mode 100644 index 0000000000000000000000000000000000000000..81b6a24f39ec37ba45055d8fefa819e816a61b8d --- /dev/null +++ b/shared/package-files/78/780eee61766bd29d1a6b3e6b056f84ca92f1f51721aefa8362d4a7904250b18c/blob @@ -0,0 +1,42 @@ +import os +import subprocess +from collections.abc import Iterable +from typing import Literal as L, Any, overload, TypedDict + +from numpy._pytesttester import PytestTester + +class _F2PyDictBase(TypedDict): + csrc: list[str] + h: list[str] + +class _F2PyDict(_F2PyDictBase, total=False): + fsrc: list[str] + ltx: list[str] + +__all__: list[str] +test: PytestTester + +def run_main(comline_list: Iterable[str]) -> dict[str, _F2PyDict]: ... + +@overload +def compile( # type: ignore[misc] + source: str | bytes, + modulename: str = ..., + extra_args: str | list[str] = ..., + verbose: bool = ..., + source_fn: None | str | bytes | os.PathLike[Any] = ..., + extension: L[".f", ".f90"] = ..., + full_output: L[False] = ..., +) -> int: ... +@overload +def compile( + source: str | bytes, + modulename: str = ..., + extra_args: str | list[str] = ..., + verbose: bool = ..., + source_fn: None | str | bytes | os.PathLike[Any] = ..., + extension: L[".f", ".f90"] = ..., + full_output: L[True] = ..., +) -> subprocess.CompletedProcess[bytes]: ... + +def get_include() -> str: ... diff --git a/shared/package-files/78/78104888d4c3c451362c953270c78099119f9bc54cdefcea0937ee82c6555568/blob b/shared/package-files/78/78104888d4c3c451362c953270c78099119f9bc54cdefcea0937ee82c6555568/blob new file mode 100644 index 0000000000000000000000000000000000000000..a01ca7ad0b17792d927e071ba92ec5e3f113992c --- /dev/null +++ b/shared/package-files/78/78104888d4c3c451362c953270c78099119f9bc54cdefcea0937ee82c6555568/blob @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch { +namespace jit { + +TORCH_API std::variant parseSchemaOrName( + const std::string& schemaOrName); +TORCH_API c10::FunctionSchema parseSchema(const std::string& schema); +TORCH_API c10::OperatorName parseName(const std::string& name); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/78/78116e7e706c7d1e3e7446094709819fb39a50c2a2302f92d6a498e06ed4a31b/blob b/shared/package-files/78/78116e7e706c7d1e3e7446094709819fb39a50c2a2302f92d6a498e06ed4a31b/blob new file mode 100644 index 0000000000000000000000000000000000000000..0f5e26975e8eaf3f6e097403ead544f8da63a00e --- /dev/null +++ b/shared/package-files/78/78116e7e706c7d1e3e7446094709819fb39a50c2a2302f92d6a498e06ed4a31b/blob @@ -0,0 +1,39 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset ar_JO DAYS_OF_WEEK_ABBREV [list \ + "\u0627\u0644\u0623\u062d\u062f"\ + "\u0627\u0644\u0627\u062b\u0646\u064a\u0646"\ + "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621"\ + "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621"\ + "\u0627\u0644\u062e\u0645\u064a\u0633"\ + "\u0627\u0644\u062c\u0645\u0639\u0629"\ + "\u0627\u0644\u0633\u0628\u062a"] + ::msgcat::mcset ar_JO MONTHS_ABBREV [list \ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0634\u0628\u0627\u0637"\ + "\u0622\u0630\u0627\u0631"\ + "\u0646\u064a\u0633\u0627\u0646"\ + "\u0646\u0648\u0627\u0631"\ + "\u062d\u0632\u064a\u0631\u0627\u0646"\ + "\u062a\u0645\u0648\u0632"\ + "\u0622\u0628"\ + "\u0623\u064a\u0644\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u0623\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u0623\u0648\u0644"\ + ""] + ::msgcat::mcset ar_JO MONTHS_FULL [list \ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0634\u0628\u0627\u0637"\ + "\u0622\u0630\u0627\u0631"\ + "\u0646\u064a\u0633\u0627\u0646"\ + "\u0646\u0648\u0627\u0631"\ + "\u062d\u0632\u064a\u0631\u0627\u0646"\ + "\u062a\u0645\u0648\u0632"\ + "\u0622\u0628"\ + "\u0623\u064a\u0644\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u0623\u0648\u0644"\ + "\u062a\u0634\u0631\u064a\u0646 \u0627\u0644\u062b\u0627\u0646\u064a"\ + "\u0643\u0627\u0646\u0648\u0646 \u0627\u0644\u0623\u0648\u0644"\ + ""] +} diff --git a/shared/package-files/78/78122d482e7e8ed3b223d06a38004e4b0d6e7aa385edc283cd4011ff96748f2f/blob b/shared/package-files/78/78122d482e7e8ed3b223d06a38004e4b0d6e7aa385edc283cd4011ff96748f2f/blob new file mode 100644 index 0000000000000000000000000000000000000000..6e4986c639f0a12dec44a696df5992eddba148a0 --- /dev/null +++ b/shared/package-files/78/78122d482e7e8ed3b223d06a38004e4b0d6e7aa385edc283cd4011ff96748f2f/blob @@ -0,0 +1,254 @@ +"""Helper functions for graphics with Matplotlib""" +from statsmodels.compat.python import lrange + +import sys + +__all__ = ["create_mpl_ax", "create_mpl_fig"] + + +def _import_mpl(stacklevel=1): + """ + Import matplotlib.pyplot, raising a clear error if unavailable + + Parameters + ---------- + stacklevel : int, optional + How many frames up from this function to look when identifying the + caller to name in the error message. Follows the same convention as + ``stacklevel`` in ``warnings.warn``: the default, 1, names whichever + function directly calls ``_import_mpl``. Pass 2 (or higher) when + ``_import_mpl`` is itself called through one or more wrapper + functions, such as ``create_mpl_ax``, so that the error message + names the original, user-facing caller instead of the wrapper. + + Returns + ------- + module + The imported ``matplotlib.pyplot`` module. + + Notes + ----- + This function is not needed outside this utils module. + """ + # Identify the function/method that called _import_mpl (or, with + # stacklevel > 1, an earlier ancestor) so the error message below can + # name it, e.g. "statsmodels.graphics.gofplots.qqplot". + try: + frame = sys._getframe(stacklevel) + except ValueError: + # stacklevel reaches past the bottom of the stack; fall back to the + # immediate caller rather than raising here. + frame = sys._getframe(1) + module = frame.f_globals.get("__name__", "") + # co_qualname (Python >= 3.11) already includes the enclosing class, + # e.g. "ProbPlot.qqplot"; on 3.10 fall back to the bare function name, + # adding the class name when called as a bound or class method. + qualname = getattr(frame.f_code, "co_qualname", None) + if qualname is None: + qualname = frame.f_code.co_name + caller = frame.f_locals.get("self", frame.f_locals.get("cls")) + if caller is not None: + cls = caller if isinstance(caller, type) else type(caller) + qualname = f"{cls.__name__}.{qualname}" + fn = f"{module}.{qualname}" if module else qualname + + try: + import matplotlib.pyplot as plt + except ImportError as exc: + raise ImportError( + f"{fn} requires matplotlib but matplotlib is not installed." + ) from exc + + return plt + + +def create_mpl_ax(ax=None): + """ + Helper function for when a single plot axis is needed + + Parameters + ---------- + ax : AxesSubplot, optional + If given, this subplot is used to plot in instead of a new figure being + created. + + Returns + ------- + fig : Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + ax : AxesSubplot + The created axis if `ax` is None, otherwise the axis that was passed + in. + + Notes + ----- + This function imports `matplotlib.pyplot`, which should only be done to + create (a) figure(s) with ``plt.figure``. All other functionality exposed + by the pyplot module can and should be imported directly from its + Matplotlib module. + + See Also + -------- + create_mpl_fig + + Examples + -------- + A plotting function has a keyword ``ax=None``. Then calls: + + >>> from statsmodels.graphics import utils + >>> fig, ax = utils.create_mpl_ax(ax) + """ + if ax is None: + # stacklevel=2: name create_mpl_ax's own caller, not create_mpl_ax + plt = _import_mpl(stacklevel=2) + fig = plt.figure() + ax = fig.add_subplot(111) + else: + fig = ax.figure + + return fig, ax + + +def create_mpl_fig(fig=None, figsize=None): + """ + Helper function for when multiple plot axes are needed + + Those axes should be created in the functions they are used in, with + ``fig.add_subplot()``. + + Parameters + ---------- + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + figsize : tuple[float, float], optional + A ``(width, height)`` tuple in inches passed to ``plt.figure`` when + a new figure is created. Ignored if `fig` is given. + + Returns + ------- + Figure + If `fig` is None, the created figure. Otherwise the input `fig` is + returned. + + See Also + -------- + create_mpl_ax + """ + if fig is None: + # stacklevel=2: name create_mpl_fig's own caller, not create_mpl_fig + plt = _import_mpl(stacklevel=2) + fig = plt.figure(figsize=figsize) + + return fig + + +def maybe_name_or_idx(idx, model): + """ + Return the name(s) and integer location(s) of column(s) in a design matrix + + Parameters + ---------- + idx : int, str, list, tuple, or None + The column(s) to look up in `model`. If None, all columns of + ``model.exog`` are used. If an int, it is treated as an integer + location. If a str, it is treated as a column name. If a list or + tuple, each element is resolved recursively and the results are + collected into lists. + model : Model + A fitted or unfitted model instance exposing ``exog`` (the design + matrix) and ``exog_names`` (the corresponding column names). + + Returns + ------- + exog_name : str or list[str] + The name(s) of the column(s) corresponding to `idx`. + exog_idx : int or list[int] + The integer location(s) of the column(s) corresponding to `idx`. + """ + if idx is None: + idx = lrange(model.exog.shape[1]) + if isinstance(idx, int): + exog_name = model.exog_names[idx] + exog_idx = idx + # anticipate index as list and recurse + elif isinstance(idx, (tuple, list)): + exog_name = [] + exog_idx = [] + for item in idx: + exog_name_item, exog_idx_item = maybe_name_or_idx(item, model) + exog_name.append(exog_name_item) + exog_idx.append(exog_idx_item) + else: # assume we've got a string variable + exog_name = idx + exog_idx = model.exog_names.index(idx) + + return exog_name, exog_idx + + +def get_data_names(series_or_dataframe): + """ + Return the name(s) of a 1d array-like or pandas-like object + + Parameters + ---------- + series_or_dataframe : array_like, Series, or DataFrame + Input can be an array or pandas-like. Will handle 1d array-like but + not 2d. + + Returns + ------- + str or list[str] + A str for 1d data or a list of strings for 2d data. + """ + names = getattr(series_or_dataframe, "name", None) + if not names: + names = getattr(series_or_dataframe, "columns", None) + if not names: + shape = getattr(series_or_dataframe, "shape", [1]) + nvars = 1 if len(shape) == 1 else series_or_dataframe.shape[1] + names = ["X%d" for _ in range(nvars)] + if nvars == 1: + names = names[0] + else: + names = names.tolist() + return names + + +def annotate_axes(index, labels, points, offset_points, size, ax, **kwargs): + """ + Annotate Axes with labels, points, offset_points according to the given index + + Parameters + ---------- + index : array_like + Sequence of integer positions selecting which entries of `labels`, + `points`, and `offset_points` to annotate. + labels : array_like + Sequence of annotation text, one entry per position in `points`. + points : array_like + Sequence of ``(x, y)`` coordinates to annotate, one per entry in + `labels`. + offset_points : array_like + Sequence of ``(x, y)`` offsets, in points, used as `textcoords` for + each annotation. + size : float + Font size, in points, used for the annotation text. + ax : AxesSubplot + The axis to annotate. + **kwargs + Additional keyword arguments passed to ``ax.annotate``. + + Returns + ------- + AxesSubplot + The annotated axis, same object as `ax`. + """ + for i in index: + label = labels[i] + point = points[i] + offset = offset_points[i] + ax.annotate(label, point, xytext=offset, textcoords="offset points", + size=size, **kwargs) + return ax diff --git a/shared/package-files/78/7812eeab924a6809750d121753bfcae17041c9d93ff3b8f4916a36d23acbb048/blob b/shared/package-files/78/7812eeab924a6809750d121753bfcae17041c9d93ff3b8f4916a36d23acbb048/blob new file mode 100644 index 0000000000000000000000000000000000000000..b8704e1246a21152230f12e0192a3e72be22393b --- /dev/null +++ b/shared/package-files/78/7812eeab924a6809750d121753bfcae17041c9d93ff3b8f4916a36d23acbb048/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _cast_Double { + using schema = at::Tensor (const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cast_Double") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cast_Double(Tensor self, bool non_blocking=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, bool non_blocking); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/7813a510600a1427e316a569add6a58b73351bb97493f9316fb92ef8bcf66d4d/blob b/shared/package-files/78/7813a510600a1427e316a569add6a58b73351bb97493f9316fb92ef8bcf66d4d/blob new file mode 100644 index 0000000000000000000000000000000000000000..94a0f8f5cef626354f40901cbe06a84287291c1c --- /dev/null +++ b/shared/package-files/78/7813a510600a1427e316a569add6a58b73351bb97493f9316fb92ef8bcf66d4d/blob @@ -0,0 +1,67 @@ +import os +import platform +import sys +from importlib.metadata import PackageNotFoundError, version + + +def _get_sys_info(): + """ + Get useful system information. + + Returns + ------- + dict + Useful system information. + """ + return { + "python": sys.version.replace(os.linesep, " "), + "executable": sys.executable, + "machine": platform.platform(), + } + + +def _get_deps_info(): + """ + Get the versions of the dependencies. + + Returns + ------- + dict + Versions of the dependencies. + """ + deps = ["cobyqa", "numpy", "scipy", "setuptools", "pip"] + deps_info = {} + for module in deps: + try: + deps_info[module] = version(module) + except PackageNotFoundError: + deps_info[module] = None + return deps_info + + +def show_versions(): + """ + Display useful system and dependencies information. + + When reporting issues, please include this information. + """ + print("System settings") + print("---------------") + sys_info = _get_sys_info() + print( + "\n".join( + f"{k:>{max(map(len, sys_info.keys())) + 1}}: {v}" + for k, v in sys_info.items() + ) + ) + + print() + print("Python dependencies") + print("-------------------") + deps_info = _get_deps_info() + print( + "\n".join( + f"{k:>{max(map(len, deps_info.keys())) + 1}}: {v}" + for k, v in deps_info.items() + ) + ) diff --git a/shared/package-files/78/7813d4aecab6a4168944a790fc3a694f8ee1d7d377eb638791538d84ccaf9eba/blob b/shared/package-files/78/7813d4aecab6a4168944a790fc3a694f8ee1d7d377eb638791538d84ccaf9eba/blob new file mode 100644 index 0000000000000000000000000000000000000000..6e545363146e3432f29d1956839e674e1948c392 Binary files /dev/null and b/shared/package-files/78/7813d4aecab6a4168944a790fc3a694f8ee1d7d377eb638791538d84ccaf9eba/blob differ diff --git a/shared/package-files/78/7814d2156710a763354e0633af4d45f8a42b74224b1cfadc3cc1afb82b088f5b/blob b/shared/package-files/78/7814d2156710a763354e0633af4d45f8a42b74224b1cfadc3cc1afb82b088f5b/blob new file mode 100644 index 0000000000000000000000000000000000000000..7f70957007dad9cc589e6f589c48555fd90f527d --- /dev/null +++ b/shared/package-files/78/7814d2156710a763354e0633af4d45f8a42b74224b1cfadc3cc1afb82b088f5b/blob @@ -0,0 +1,144 @@ +""" +This file contains a minimal set of tests for compliance with the extension +array interface test suite, and should contain no other tests. +The test suite for the full functionality of the array is located in +`pandas/tests/arrays/`. + +The tests in this file are inherited from the BaseExtensionTests, and only +minimal tweaks should be applied to get the tests passing (by overwriting a +parent method). + +Additional tests should either be added to one of the BaseExtensionTests +classes (if they are relevant for the extension interface for all dtypes), or +be added to the array-specific tests in `pandas/tests/arrays/`. + +""" +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import DatetimeTZDtype + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import DatetimeArray +from pandas.tests.extension import base + + +@pytest.fixture(params=["US/Central"]) +def dtype(request): + return DatetimeTZDtype(unit="ns", tz=request.param) + + +@pytest.fixture +def data(dtype): + data = DatetimeArray._from_sequence( + pd.date_range("2000", periods=100, tz=dtype.tz), dtype=dtype + ) + return data + + +@pytest.fixture +def data_missing(dtype): + return DatetimeArray._from_sequence( + np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype + ) + + +@pytest.fixture +def data_for_sorting(dtype): + a = pd.Timestamp("2000-01-01") + b = pd.Timestamp("2000-01-02") + c = pd.Timestamp("2000-01-03") + return DatetimeArray._from_sequence( + np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype + ) + + +@pytest.fixture +def data_missing_for_sorting(dtype): + a = pd.Timestamp("2000-01-01") + b = pd.Timestamp("2000-01-02") + return DatetimeArray._from_sequence( + np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype + ) + + +@pytest.fixture +def data_for_grouping(dtype): + """ + Expected to be like [B, B, NA, NA, A, A, B, C] + + Where A < B < C and NA is missing + """ + a = pd.Timestamp("2000-01-01") + b = pd.Timestamp("2000-01-02") + c = pd.Timestamp("2000-01-03") + na = "NaT" + return DatetimeArray._from_sequence( + np.array([b, b, na, na, a, a, b, c], dtype="datetime64[ns]"), dtype=dtype + ) + + +@pytest.fixture +def na_cmp(): + def cmp(a, b): + return a is pd.NaT and a is b + + return cmp + + +# ---------------------------------------------------------------------------- +class TestDatetimeArray(base.ExtensionTests): + def _get_expected_exception(self, op_name, obj, other): + if op_name in ["__sub__", "__rsub__"]: + return None + return super()._get_expected_exception(op_name, obj, other) + + def _supports_accumulation(self, ser, op_name: str) -> bool: + return op_name in ["cummin", "cummax"] + + def _supports_reduction(self, obj, op_name: str) -> bool: + return op_name in ["min", "max", "median", "mean", "std", "any", "all"] + + @pytest.mark.parametrize("skipna", [True, False]) + def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna): + meth = all_boolean_reductions + msg = f"'{meth}' with datetime64 dtypes is deprecated and will raise in" + with tm.assert_produces_warning( + FutureWarning, match=msg, check_stacklevel=False + ): + super().test_reduce_series_boolean(data, all_boolean_reductions, skipna) + + def test_series_constructor(self, data): + # Series construction drops any .freq attr + data = data._with_freq(None) + super().test_series_constructor(data) + + @pytest.mark.parametrize("na_action", [None, "ignore"]) + def test_map(self, data, na_action): + result = data.map(lambda x: x, na_action=na_action) + tm.assert_extension_array_equal(result, data) + + def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool): + if op_name in ["median", "mean", "std"]: + alt = ser.astype("int64") + + res_op = getattr(ser, op_name) + exp_op = getattr(alt, op_name) + result = res_op(skipna=skipna) + expected = exp_op(skipna=skipna) + if op_name in ["mean", "median"]: + # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" + # has no attribute "tz" + tz = ser.dtype.tz # type: ignore[union-attr] + expected = pd.Timestamp(expected, tz=tz) + else: + expected = pd.Timedelta(expected) + tm.assert_almost_equal(result, expected) + + else: + return super().check_reduce(ser, op_name, skipna) + + +class Test2DCompat(base.NDArrayBacked2DTests): + pass diff --git a/shared/package-files/78/7815d7dd6af72c5c4c570ddc1c1a1b251d449f8add4d05dc81ff6a72efc5abff/blob b/shared/package-files/78/7815d7dd6af72c5c4c570ddc1c1a1b251d449f8add4d05dc81ff6a72efc5abff/blob new file mode 100644 index 0000000000000000000000000000000000000000..c5fd523381f36af2e156750085d0b98699ef0dfb Binary files /dev/null and b/shared/package-files/78/7815d7dd6af72c5c4c570ddc1c1a1b251d449f8add4d05dc81ff6a72efc5abff/blob differ diff --git a/shared/package-files/78/7817689d4e67f73b1b0bce80b1c1c22f117af17aa2aa1596c81255fbb60239d0/blob b/shared/package-files/78/7817689d4e67f73b1b0bce80b1c1c22f117af17aa2aa1596c81255fbb60239d0/blob new file mode 100644 index 0000000000000000000000000000000000000000..dd8c3eda9ed05b6844c90024631a1e90f755069e --- /dev/null +++ b/shared/package-files/78/7817689d4e67f73b1b0bce80b1c1c22f117af17aa2aa1596c81255fbb60239d0/blob @@ -0,0 +1,62 @@ +import numpy as np +import pytest + +import pandas as pd + + +@pytest.fixture +def data(): + """Fixture returning boolean array, with valid and missing values.""" + return pd.array( + [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False], + dtype="boolean", + ) + + +@pytest.mark.parametrize( + "values, exp_any, exp_all, exp_any_noskip, exp_all_noskip", + [ + ([True, pd.NA], True, True, True, pd.NA), + ([False, pd.NA], False, False, pd.NA, False), + ([pd.NA], False, True, pd.NA, pd.NA), + ([], False, True, False, True), + # GH-33253: all True / all False values buggy with skipna=False + ([True, True], True, True, True, True), + ([False, False], False, False, False, False), + ], +) +def test_any_all(values, exp_any, exp_all, exp_any_noskip, exp_all_noskip): + # the methods return numpy scalars + exp_any = pd.NA if exp_any is pd.NA else np.bool_(exp_any) + exp_all = pd.NA if exp_all is pd.NA else np.bool_(exp_all) + exp_any_noskip = pd.NA if exp_any_noskip is pd.NA else np.bool_(exp_any_noskip) + exp_all_noskip = pd.NA if exp_all_noskip is pd.NA else np.bool_(exp_all_noskip) + + for con in [pd.array, pd.Series]: + a = con(values, dtype="boolean") + assert a.any() is exp_any + assert a.all() is exp_all + assert a.any(skipna=False) is exp_any_noskip + assert a.all(skipna=False) is exp_all_noskip + + assert np.any(a.any()) is exp_any + assert np.all(a.all()) is exp_all + + +@pytest.mark.parametrize("dropna", [True, False]) +def test_reductions_return_types(dropna, data, all_numeric_reductions): + op = all_numeric_reductions + s = pd.Series(data) + if dropna: + s = s.dropna() + + if op in ("sum", "prod"): + assert isinstance(getattr(s, op)(), np.int_) + elif op == "count": + # Oddly on the 32 bit build (but not Windows), this is intc (!= intp) + assert isinstance(getattr(s, op)(), np.integer) + elif op in ("min", "max"): + assert isinstance(getattr(s, op)(), np.bool_) + else: + # "mean", "std", "var", "median", "kurt", "skew" + assert isinstance(getattr(s, op)(), np.float64) diff --git a/shared/package-files/78/781768a96ef55d307787f549cee9865cfc3f61e7cb435edc046cbc1f40260408/blob b/shared/package-files/78/781768a96ef55d307787f549cee9865cfc3f61e7cb435edc046cbc1f40260408/blob new file mode 100644 index 0000000000000000000000000000000000000000..0e27dc869e1d565a8de0db7277d9ccc6fc259bb4 --- /dev/null +++ b/shared/package-files/78/781768a96ef55d307787f549cee9865cfc3f61e7cb435edc046cbc1f40260408/blob @@ -0,0 +1,1330 @@ +""" +This file does three things: +- Contains the definition of SymNode +- Installs all the magic methods into SymBool, SymFloat, SymFloat at import time +- Does not depend on sympy at import time + +As this file is imported from within torch/__init__.py we do not want it to depend on SymPy +to avoid having to load SymPy at import time, as doing so is *very* slow. +""" + +import builtins +import itertools +import logging +import math +import operator +import sys +from functools import lru_cache, update_wrapper +from typing import Optional, Type, TYPE_CHECKING, Union + +import torch + +# NB: The sym_* functions are used via getattr() and must be imported here. +from torch import ( # noqa: F401 + sym_float, + sym_ite, + sym_max, + sym_min, + sym_not, + SymBool, + SymFloat, + SymInt, +) + +from torch.fx.experimental._sym_dispatch_mode import ( + handle_sym_dispatch, + sym_function_mode, +) + +if TYPE_CHECKING: + from torch.fx.experimental.symbolic_shapes import ShapeEnv + +log = logging.getLogger(__name__) +sym_node_log = torch._logging.getArtifactLogger(__name__, "sym_node") + + +__all__ = ["SymNode", "method_to_operator", "magic_methods"] + + +SymTypes = (SymInt, SymFloat, SymBool) + + +def _to_symtype(t): + if t is bool: + return SymBool + if t is int: + return SymInt + if t is float: + return SymFloat + return t + + +# TODO: An incomplete list +# 1. Set variables to be equal when we do equality +# 2. Specialize on 0/1 when we do subtraction +class SymNode: + """ + This is a type erased SymInt/SymFloat which we use to do actual operations. + End users don't touch this. Magic methods are NOT defined on this object. + """ + + def __init__( + self, + expr, + shape_env, + pytype, + hint: Optional[Union[int, float, bool]], + constant=None, + fx_node=None, + ): + self._expr = expr + self.shape_env = shape_env + self.pytype = pytype + # What's the difference between hint and constant? + # + # - A constant is known to be invariant across invocations of the model; + # it will always be this value. We only really know this when we + # encounter an honest-to-goodness literal (when wrapping it into + # a SymNode, we set constant.) Most of the time, constant is None + # + # - A hint is a *particular* value from the particular run we are + # tracing, but it may vary the next time around. It's useful to + # keep this around, as if we need a concrete value from a SymNode, + # we will return the hint and guard on the expression that produced + # it giving the same hint next time around. The hint is not + # guaranteed to be set either: if you have an unbacked SymNode, + # there won't be any hint; it was the result of some tensor-dependent + # computation, but we don't know what it actually is because we + # haven't actually run the tensor computation. + # + # If _hint is None, we will query maybe_evaluate_static(compute_hint=True) + # in hopes that we've learned enough about the unbacked symints to + # discharge the hint; otherwise, you're likely to just error out. + # + # (A previous version of this system had some optimizations to only + # recompute when it was possible we had learned enough about the + # unbacked symint that a hint was now possible, but as we added more + # potential refinements to unbacked symints this got harder to keep + # in sync, so we've deleted it for now.) + if hint is not None: + assert type(hint) is pytype or type(hint) is _to_symtype(pytype), ( + "Cannot create SymNode of type " + f"{pytype} with incompatible hint of type {type(hint)}" + ) + self._hint = hint + self.constant: Optional[Union[int, float, bool]] = constant + + # Record the FX node of the current node if we are doing translation + # validation. They will be used for building the input assertions for + # the translation validation problem. + self.fx_node = ( + fx_node if self.shape_env._translation_validation_enabled else None + ) + + def with_shape_env(self, shape_env: "ShapeEnv") -> "SymNode": + return SymNode( + self._expr, shape_env, self.pytype, self._hint, self.constant, self.fx_node + ) + + @property + def expr(self): + return self.shape_env.replace(self._expr) + + # Recompute the hint and see if we've got it now + # Precondition: self._hint is None + def _update_hint(self): + r = self.shape_env._maybe_evaluate_static(self.expr, compute_hint=True) + if r is not None: + self._hint = self.pytype(r) if not isinstance(r, SymTypes) else r + + @property + def hint(self): + if self._hint is None: + self._update_hint() + return self._hint + + def has_hint(self): + if self._hint is None: + self._update_hint() + return self._hint is not None + + def require_hint(self, fallback=None): + if self._hint is None: + self._update_hint() + if self._hint is None: + if fallback is not None: + return fallback + # NB: we expect this to raise + return self.shape_env.size_hint(self.expr) + return self._hint + + def maybe_as_int(self): + if self.expr.is_number: + return int(self.expr) + else: + return None + + def is_int(self): + return self.pytype is int + + def is_float(self): + return self.pytype is float + + def is_bool(self): + return self.pytype is bool + + def is_nested_int(self): + # Unbacked SymInts cannot be nested int today + return ( + self._hint is not None + and isinstance(self._hint, SymInt) + and self._hint.node.is_nested_int() + ) + + def wrap_int(self, num): + assert type(num) is int + import sympy + + return SymNode( + sympy.Integer(num), self.shape_env, int, num, constant=num, fx_node=num + ) + + def wrap_float(self, num): + assert type(num) is float + import sympy + + return SymNode( + sympy.Float(num), self.shape_env, float, num, constant=num, fx_node=num + ) + + def wrap_bool(self, num): + assert type(num) is bool + import sympy + + return SymNode( + sympy.true if num else sympy.false, + self.shape_env, + bool, + num, + constant=num, + fx_node=num, + ) + + def clone(self): + return self + + def str(self): + return f"{self.expr}" + + def __str__(self): + return self.str() + + def __repr__(self): + return self.str() + + # These methods call the metaprogrammed methods, they're hand written + # here so we get good stack traces + def abs(self) -> "SymNode": + return self._abs() # type: ignore[attr-defined] + + def pos(self) -> "SymNode": + return self._pos() # type: ignore[attr-defined] + + def round(self, ndigits=None) -> "SymNode": + return self._round(ndigits) # type: ignore[attr-defined] + + def add(self, other) -> "SymNode": + return self._add(other) # type: ignore[attr-defined] + + def sub(self, other) -> "SymNode": + return self._sub(other) # type: ignore[attr-defined] + + def mul(self, other) -> "SymNode": + return self._mul(other) # type: ignore[attr-defined] + + def mod(self, other) -> "SymNode": + return self._mod(other) # type: ignore[attr-defined] + + def pow(self, other) -> "SymNode": + return self._pow(other) # type: ignore[attr-defined] + + def and_(self, other) -> "SymNode": + return self._and_(other) # type: ignore[attr-defined] + + def or_(self, other) -> "SymNode": + return self._or_(other) # type: ignore[attr-defined] + + def truediv(self, other) -> "SymNode": + return self._truediv(other) # type: ignore[attr-defined] + + def floordiv(self, other) -> "SymNode": + return self._floordiv(other) # type: ignore[attr-defined] + + def lshift(self, other) -> "SymNode": + return self._lshift(other) # type: ignore[attr-defined] + + def rshift(self, other) -> "SymNode": + return self._rshift(other) # type: ignore[attr-defined] + + def sym_not(self) -> "SymNode": # noqa: F811 + return self._sym_not() # type: ignore[attr-defined] + + def eq(self, other) -> "SymNode": + return self._eq(other) # type: ignore[attr-defined] + + def ne(self, other) -> "SymNode": + return self._ne(other) # type: ignore[attr-defined] + + def gt(self, other) -> "SymNode": + return self._gt(other) # type: ignore[attr-defined] + + def lt(self, other) -> "SymNode": + return self._lt(other) # type: ignore[attr-defined] + + def le(self, other) -> "SymNode": + return self._le(other) # type: ignore[attr-defined] + + def ge(self, other) -> "SymNode": + return self._ge(other) # type: ignore[attr-defined] + + def floor(self) -> "SymNode": + return self._floor() # type: ignore[attr-defined] + + def is_integer(self) -> "SymNode": + return self._is_integer() # type: ignore[attr-defined] + + def sym_float(self) -> "SymNode": # noqa: F811 + return self._sym_float() # type: ignore[attr-defined] + + def sym_int(self) -> "SymNode": + return self._sym_int() # type: ignore[attr-defined] + + def ceil(self) -> "SymNode": + return self._ceil() # type: ignore[attr-defined] + + def neg(self) -> "SymNode": + return self._neg() # type: ignore[attr-defined] + + def sym_min(self, other) -> "SymNode": # noqa: F811 + return self._sym_min(other) # type: ignore[attr-defined] + + def sym_max(self, other) -> "SymNode": # noqa: F811 + return self._sym_max(other) # type: ignore[attr-defined] + + def sym_ite(self, then_val, else_val) -> "SymNode": + return self._sym_ite(then_val, else_val) # type: ignore[attr-defined] + + def is_contiguous(self, sizes, strides) -> "SymNode": + return self._is_contiguous(sizes, strides) # type: ignore[attr-defined] + + def is_channels_last_contiguous_2d(self, sizes, strides) -> "SymNode": + return self._is_channels_last_contiguous_2d(sizes, strides) # type: ignore[attr-defined] + + def is_channels_last_contiguous_3d(self, sizes, strides) -> "SymNode": + return self._is_channels_last_contiguous_3d(sizes, strides) # type: ignore[attr-defined] + + def is_channels_last_strides_2d(self, sizes, strides) -> "SymNode": + return self._is_channels_last_strides_2d(sizes, strides) # type: ignore[attr-defined] + + def is_channels_last_strides_3d(self, sizes, strides) -> "SymNode": + return self._is_channels_last_strides_3d(sizes, strides) # type: ignore[attr-defined] + + def is_non_overlapping_and_dense_indicator(self, sizes, strides) -> "SymNode": + return self._is_non_overlapping_and_dense_indicator(sizes, strides) # type: ignore[attr-defined] + + # Make C++ happy + def sym_or(self, other): + return self.or_(other) + + def sym_and(self, other): + return self.and_(other) + + def is_non_overlapping_and_dense(self, sizes, strides): + return self.is_non_overlapping_and_dense_indicator(sizes, strides).eq(to_node(self, 1)) # type: ignore[attr-defined] + + def int_(self): + return self.guard_int("", 0) # NB: uses Python backtrace + + # You can manually trigger a guard with this function + def guard_int(self, file, line): + # TODO: use the file/line for some useful diagnostic on why a + # guard occurred + r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node) + try: + return int(r) + except Exception: + log.warning("Failed to convert to int: %s", r) + raise + + def guard_float(self, file, line): + # TODO: use the file/line for some useful diagnostic on why a + # guard occurred + r = self.shape_env.evaluate_expr( + self.expr, self.hint, fx_node=self.fx_node, expect_rational=False + ) + try: + return float(r) + except Exception: + log.warning("Failed to convert to float: %s", r) + raise + + def guard_bool(self, file, line): + # TODO: use the file/line for some useful diagnostic on why a + # guard occurred + r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node) + try: + return bool(r) + except Exception: + log.warning("Failed to convert to bool: %s", r) + raise + + def expect_true(self, file, line): + from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + if self.has_hint() and not free_unbacked_symbols(self.expr): + # OK to generate guards + return self.guard_bool(file, line) + # Generate a deferred runtime assert (this might actually end up doing + # a regular guard if we can!) + # TODO: file/line here is very important, because the assert has been + # deferred so you can't backtrace easily + return self.shape_env.defer_runtime_assert( + self.expr, f"{file}:{line}", fx_node=self.fx_node + ) + + def expect_size(self, file, line): + from torch.fx.experimental.symbolic_shapes import _advise_is_size + + b = self.ge(self.wrap_int(0)) + # Generate a deferred runtime assert + r = b.expect_true(file, line) + # Refine compile time range, but only if it's unbacked. + # If you refine range for hinted variables, you can end up making + # improper deductions since compile time reasoning may be + # incompatible with runtime reasoning. + if r and not self.has_hint(): + _advise_is_size(SymInt(self)) + return r + + def guard_size_oblivious(self, file, line): + """ + Like guard_bool, but if we encounter unbacked symbols, if those symbols + are size-like, we will treat them as >= 2 for the purposes of the analysis. + + This CHANGES the runtime semantics, but all size-oblivious sites have been + audited to ensure that the runtime semantics don't change in a material way. + Acceptable runtime semantic changes are, e.g., squeeze() no longer dropping + an unbacked one size, or a tensor reporting as non-contiguous even if it's + contiguous if it would have been reported contiguous due to being empty. + """ + # TODO: use the file/line for some useful diagnostic on why a + # guard occurred + r = self.shape_env.evaluate_expr( + self.expr, self.hint, fx_node=self.fx_node, size_oblivious=True + ) + try: + return bool(r) + except Exception: + log.warning("Failed to convert to bool: %s", r) + raise + + def bool_(self): + return self.guard_bool("", 0) + + def is_symbolic(self): + return True + + def nested_int(self): + return None + + def is_constant(self): + return False + + +# TODO: this probably needs the sizes-strides eval functions +METHOD_TO_OPERATOR = { + "pos": operator.pos, + "abs": operator.abs, + "add": operator.add, + "and": operator.and_, + "ceil": math.ceil, + "eq": operator.eq, + "floor": math.floor, + "floordiv": operator.floordiv, + "ge": operator.ge, + "gt": operator.gt, + "is_integer": lambda x: x.is_integer(), + "le": operator.le, + "lshift": operator.lshift, + "lt": operator.lt, + "mod": operator.mod, + "mul": operator.mul, + "ne": operator.ne, + "neg": operator.neg, + "or": operator.or_, + "pow": operator.pow, + "round": builtins.round, + "rshift": operator.rshift, + "sub": operator.sub, + "sym_float": sym_float, + "sym_ite": sym_ite, + "sym_max": sym_max, + "sym_min": sym_min, + "sym_not": sym_not, + "truediv": operator.truediv, +} + +unary_magic_methods = { + "abs", + "sym_float", + "ceil", + "floor", + "neg", + "sym_not", + "pos", +} + + +# Adding math ops: sqrt, cos, sin, ... +def _get_sym_node_fn(name): + def fn(self): + return getattr(self, f"_sym_{name}")() + + return fn + + +math_op_names = ( + "sqrt", + "cos", + "cosh", + "sin", + "sinh", + "tan", + "tanh", + "asin", + "acos", + "atan", +) +for name in math_op_names: + sym_name = f"sym_{name}" + priv_sym_name = f"_{sym_name}" + setattr(SymNode, sym_name, _get_sym_node_fn(name)) + METHOD_TO_OPERATOR[sym_name] = getattr(torch, priv_sym_name) + unary_magic_methods.add(sym_name) + __all__.append(sym_name) + + +# Unary methods that are not magic methods +unary_nonmagic_methods = { + "is_integer", +} + +unary_methods = unary_magic_methods | unary_nonmagic_methods + +# Most methods are only registered on SymInt and SymFloat +# Some methods are only be registered on SymBool +only_bool_magic_methods = {"and", "or", "sym_not", "sym_ite"} +# Methods that implicitly convert SymBool into SymInt +bool_becomes_int_magic_methods = {"add", "sub", "mul"} +# Methods that are also on SymBool, in addition to on SymInt and SymFloat +also_bool_magic_methods = {"eq"} +bool_magic_methods = only_bool_magic_methods | also_bool_magic_methods + +# Methods that are only for float +only_float_magic_methods = {"is_integer"} + + +magic_methods_on_operator_with_trailing_underscore = {"and", "or"} + + +always_float_magic_methods = {"truediv", "sym_float", "pow"} + +for name in math_op_names: + sym_name = f"sym_{name}" + always_float_magic_methods.add(sym_name) + + +always_int_magic_methods = {"ceil", "floor"} +always_bool_magic_methods = { + "eq", + "ne", + "gt", + "lt", + "le", + "ge", + "and", + "or", + "sym_not", + "is_non_overlapping_and_dense", + "is_integer", +} + +# Methods that have a `__foo__` as well as `__rfoo__` + + +def _sympy_truediv(a, b): + from torch.utils._sympy.functions import TrueDiv + + return TrueDiv(a, b) + + +def _sympy_floordiv(a, b): + from torch.utils._sympy.functions import FloorDiv + + return FloorDiv(a, b) + + +def _sympy_mod(a, b): + from torch.utils._sympy.functions import Mod + + return Mod(a, b) + + +def _sympy_pow(a, b): + from torch.utils._sympy.functions import Pow + + return Pow(a, b) + + +def _sympy_and(a, b): + import sympy + + return sympy.And(a, b) + + +def _sympy_or(a, b): + import sympy + + return sympy.Or(a, b) + + +def _sympy_lshift(a, b): + from torch.utils._sympy.functions import LShift + + return LShift(a, b) + + +def _sympy_rshift(a, b): + from torch.utils._sympy.functions import RShift + + return RShift(a, b) + + +reflectable_magic_methods = { + "add": operator.add, + "sub": operator.sub, + "mul": operator.mul, + "mod": _sympy_mod, + "pow": _sympy_pow, + "and": _sympy_and, + "or": _sympy_or, + "truediv": _sympy_truediv, + "floordiv": _sympy_floordiv, + "lshift": _sympy_lshift, + "rshift": _sympy_rshift, +} + + +def _floor_ceil_helper(a, fn): + import sympy + + if isinstance(a, sympy.Mul): + aa = a.args + if len(aa) == 2 and isinstance(aa[0], sympy.Float) and aa[1].is_integer: + coef = sympy.Integer(aa[0]) + if aa[0] == coef: # structural equality test + return coef * aa[1] + if ( + isinstance(a, sympy.Float) + and a == sympy.Integer(a) + or isinstance(a, sympy.Integer) + ): + return sympy.Integer(a) + return fn(a) + + +def _sympy_floor(a): + import sympy + + return _floor_ceil_helper(a, sympy.floor) + + +def _sympy_ceil(a): + import sympy + + return _floor_ceil_helper(a, sympy.ceiling) + + +def _sympy_eq(a, b): + import sympy + + return sympy.Eq(a, b) + + +def _sympy_ne(a, b): + import sympy + + return sympy.Ne(a, b) + + +def _sympy_gt(a, b): + import sympy + + return sympy.Gt(a, b) + + +def _sympy_lt(a, b): + import sympy + + return sympy.Lt(a, b) + + +def _sympy_le(a, b): + import sympy + + return sympy.Le(a, b) + + +def _sympy_ge(a, b): + import sympy + + return sympy.Ge(a, b) + + +def _sympy_min(a, b): + import sympy + + return sympy.Min(a, b) + + +def _sympy_max(a, b): + import sympy + + return sympy.Max(a, b) + + +def _sympy_ite(a, t, f): + import sympy + + return sympy.Piecewise((t, a), (f, True)) + + +current_module = sys.modules[__name__] + + +def _get_sym_math_fn(name): + def fn(a): + import sympy + + return getattr(sympy, name)(a) + + return fn + + +for name in math_op_names: + priv_sympy_name = f"_sympy_{name}" + fn = _get_sym_math_fn(name) + fn.__qualname__ = fn.__name__ = priv_sympy_name + setattr(current_module, priv_sympy_name, fn) + +del fn, name, priv_sympy_name # type: ignore[possibly-undefined] + + +def _sympy_abs(a): + import sympy + + return sympy.Abs(a) + + +def _sympy_round(number, ndigits=None): + from torch.utils._sympy.functions import Round, RoundDecimal + + if ndigits is None: + return Round(number) + else: + return RoundDecimal(number, ndigits) + + +def _sympy_sym_float(a): + # Cannot use sympy.Float(a) here, coz it expects python literals + # Multiply by 1.0 to cast to float. This is needed when the input + # is a SymInt which has the assumption that it is integer and + # SymPy will otherwise assume that return value cannot be a float. + return a * 1.0 + + +def _sympy_is_integer(a): + import sympy + + return sympy.Eq(sympy.floor(a), a) + + +magic_methods = { + **reflectable_magic_methods, + "sym_not": operator.invert, + "pos": operator.pos, + "eq": _sympy_eq, + "ne": _sympy_ne, + "gt": _sympy_gt, + "lt": _sympy_lt, + "le": _sympy_le, + "ge": _sympy_ge, + "floor": _sympy_floor, + "sym_float": _sympy_sym_float, + "ceil": _sympy_ceil, + "neg": operator.neg, + "sym_min": _sympy_min, + "sym_max": _sympy_max, + "sym_ite": _sympy_ite, + "abs": _sympy_abs, + "round": _sympy_round, + "is_integer": _sympy_is_integer, +} + + +for name in math_op_names: + sym_name = f"sym_{name}" + magic_methods[sym_name] = getattr(current_module, f"_sympy_{name}") + +del name, sym_name, math_op_names, current_module # type: ignore[possibly-undefined] + + +def sympy_is_contiguous(sizes, strides): + dim = len(sizes) + return sympy_is_contiguous_generic(sizes, strides, list(range(dim - 1, -1, -1))) + + +def sympy_is_contiguous_generic(sizes, strides, dim_order): + import sympy + + dim = len(sizes) + + if len(dim_order) != dim: + return sympy.false + + is_contiguous = sympy.true + z = sympy.Integer(1) + # Contiguous if the strides make sense (or the dim is size 1) + for d in dim_order: + is_contiguous &= sympy.Eq(sizes[d], sympy.Integer(1)) | sympy.Eq(strides[d], z) + z *= sizes[d] + # OR if any size is zero + for d in range(dim): + is_contiguous |= sympy.Eq(sizes[d], sympy.Integer(0)) + return is_contiguous + + +# NB: There is a TODO in C++ to allow omitting the batch dim. If that +# happens you will need to refactor this + + +def sympy_is_channels_last_contiguous_2d(sizes, strides): + return sympy_is_contiguous_generic(sizes, strides, [1, 3, 2, 0]) + + +def sympy_is_channels_last_contiguous_3d(sizes, strides): + return sympy_is_contiguous_generic(sizes, strides, [1, 4, 3, 2, 0]) + + +def sympy_is_channels_last_strides_generic(sizes, strides, dim_order): + import sympy + + dim = len(sizes) + + if dim != len(dim_order): + return sympy.false + + m = sympy.Integer(0) + r = sympy.true + + # special case for trivial C dimension. default to NCHW + r &= sympy.Ne(strides[1], 0) + + for d in dim_order: + r &= sympy.Ne(sizes[d], 0) & (strides[d] >= m) + # Fallback to NCHW as default layout for ambiguous cases + # This is the flaw of implicit memory_format from strides. + # N111 tensor with identical strides for size 1 dimension; + # Two cases could lead us here: + # a. N111 contiguous Tensor ([N,1,1,1]@[1,1,1,1]) + # b. N11W contiguous Tensor sliced on the W-dimension. + # ([N,1,1,1]@[W,W,W,W]) + if d == 0: + r &= sympy.Ne(m, strides[1]) + # This is necessary to: + # 1. distinguish the memory_format of N1H1; + # [H, 1, 1, 1] channels_last stride + # [H, H, 1, 1] contiguous stride + # 2. permutation of 1C1W: + # [1, C, 1, H]@[HC, H, H, 1] transpose(1, 3) + # [1, H, 1, C]@[HC, 1, H, H] shouldn't be identified as + # channels_last + m = strides[d] * sympy.Max(sizes[d], 1) + + return r + + +def sympy_is_channels_last_strides_2d(sizes, strides): + return sympy_is_channels_last_strides_generic(sizes, strides, [1, 3, 2, 0]) + + +def sympy_is_channels_last_strides_3d(sizes, strides): + return sympy_is_channels_last_strides_generic(sizes, strides, [1, 4, 3, 2, 0]) + + +def _sympy_is_non_overlapping_and_dense_indicator(sizes, strides): + from torch.utils._sympy.functions import IsNonOverlappingAndDenseIndicator + + return IsNonOverlappingAndDenseIndicator(*sizes, *strides) + + +sizes_strides_methods = { + # TODO: These could also be done with indicators, maybe it is better + # for reasoning to do it that way + "is_contiguous": sympy_is_contiguous, + "is_channels_last_contiguous_2d": sympy_is_channels_last_contiguous_2d, + "is_channels_last_contiguous_3d": sympy_is_channels_last_contiguous_3d, + "is_channels_last_strides_2d": sympy_is_channels_last_strides_2d, + "is_channels_last_strides_3d": sympy_is_channels_last_strides_3d, + "is_non_overlapping_and_dense_indicator": _sympy_is_non_overlapping_and_dense_indicator, +} + +alternate_impl_if_hinted_methods = { + "sym_min": builtins.min, + "sym_max": builtins.max, +} + + +def to_node(self, num): + if isinstance(num, SymTypes): + return num.node + elif type(num) is bool: + return self.wrap_bool(num) + elif type(num) is int: + return self.wrap_int(num) + elif type(num) is float: + return self.wrap_float(num) + else: + # NotImplemented is important so that Python tries the + # other magic method + return NotImplemented + + +def wrap_node(x): + # TODO: let C++ also take advantage of this + if isinstance(x, SymNode) and x.constant is not None: + return x.constant + if x.is_int(): + return SymInt(x) + elif x.is_float(): + return SymFloat(x) + elif x.is_bool(): + return SymBool(x) + else: + raise AssertionError(f"unrecognized return type {x}") + + +def method_to_operator(method): + return METHOD_TO_OPERATOR[method] + + +def _make_node_magic(method, func): + func = lru_cache(256)(func) + + if method in magic_methods_on_operator_with_trailing_underscore: + method_attr = f"{method}_" + else: + method_attr = method + + def binary_magic_impl(self, other): + from torch.fx.experimental.symbolic_shapes import safe_expand + + op = method_to_operator(method) + + out_hint = None + if self.hint is not None and other.hint is not None: + out_hint = op(self.hint, other.hint) + + alternate_impl = alternate_impl_if_hinted_methods.get(method) + if alternate_impl and out_hint is not None: + return to_node(self, alternate_impl(wrap_node(self), wrap_node(other))) + + if sym_function_mode(): + return to_node( + self, handle_sym_dispatch(op, (wrap_node(self), wrap_node(other)), {}) + ) + assert isinstance(other, SymNode) + # TODO: consider constant prop here + try: + out = func(self.expr, other.expr) + except Exception: + log.warning("failed to eval %s(%s, %s)", method, self.expr, other.expr) + raise + out = safe_expand(out) + sym_node_log.debug("%s %s %s -> %s", func, self.expr, other.expr, out) + pytype: Type + # This is not strictly correct. In Python, a**b may return complex when + # a < 0 and b is a float: (-1)**2.1. Same for sympy.sqrt(-3.14). This + # returns a float while both arguments are ints: 2**(-1). Also, max and + # min do not type promote. To avoid having data-dependent control flow + # here, we just set the type to float if one of the args is a float. In + # case of a type mismatch, we assume that it will be detected during + # evaluation. + if method in always_float_magic_methods: + pytype = float + elif method in always_bool_magic_methods: + pytype = bool + elif self.pytype is float or other.pytype is float: + pytype = float + else: + pytype = self.pytype + + if ( + pytype is not None + and out_hint is not None + and not isinstance(out_hint, SymTypes) + ): + out_hint = pytype(out_hint) + + # Create a FX node that corresponds to the operation being applied to + # this node. + fx_node, _ = self.shape_env._create_fx_call_function( + op, (self.fx_node, other.fx_node) + ) + return SymNode(out, self.shape_env, pytype, out_hint, fx_node=fx_node) + + def unary_magic_impl(self): + from torch.fx.experimental.symbolic_shapes import safe_expand + + op = method_to_operator(method) + if sym_function_mode(): + return to_node(self, handle_sym_dispatch(op, (wrap_node(self),), {})) + # TODO: consider constant prop here + expr = self.expr + if method == "floor" or method == "ceiling": + expr = self.shape_env._simplify_floor_div(expr) + + try: + out = func(expr) + except Exception: + log.warning("failed to eval %s(%s)", method, expr) + raise + sym_node_log.debug("%s %s -> %s", func, expr, out) + out_hint = None + if self.hint is not None: + out_hint = op(self.hint) + out = safe_expand(out) + pytype: Type + if method in always_int_magic_methods: + pytype = int + elif method in always_bool_magic_methods: + pytype = bool + elif method in always_float_magic_methods: + pytype = float + else: + pytype = self.pytype + + fx_node, _ = self.shape_env._create_fx_call_function(op, (self.fx_node,)) + return SymNode(out, self.shape_env, pytype, out_hint, fx_node=fx_node) + + if method in unary_methods: + setattr(SymNode, f"_{method_attr}", unary_magic_impl) + elif method == "sym_ite": + + def sym_ite_impl(pred_node, then_node, else_node): + from torch.fx.experimental.symbolic_shapes import safe_expand + + out_hint = then_node.hint if pred_node.hint else else_node.hint + if sym_function_mode(): + return to_node( + pred_node, + handle_sym_dispatch( + sym_ite, + ( + wrap_node(pred_node), + wrap_node(then_node), + wrap_node(else_node), + ), + {}, + ), + ) + + try: + out = func(pred_node.expr, then_node.expr, else_node.expr) + except Exception: + log.warning( + "failed to eval %s(%s, %s, %s)", + method, + pred_node.expr, + then_node.expr, + else_node.expr, + ) + raise + + out = safe_expand(out) + fx_node, _ = pred_node.shape_env._create_fx_call_function( + sym_ite, (pred_node.fx_node, then_node.fx_node, else_node.fx_node) + ) + return SymNode( + out, pred_node.shape_env, then_node.pytype, out_hint, fx_node=fx_node + ) + + setattr(SymNode, f"_{method_attr}", sym_ite_impl) + elif method == "round": + + def round_impl(self, ndigits=None): + from torch.fx.experimental.symbolic_shapes import safe_expand + + op = builtins.round + if sym_function_mode(): + return to_node( + self, handle_sym_dispatch(op, (wrap_node(self), ndigits), {}) + ) + + expr = self.expr + try: + out = func(expr, ndigits) + except Exception: + log.warning("failed to eval %s(%s, ndigits=%s)", method, expr, ndigits) + raise + out = safe_expand(out) + + pytype = int if ndigits is None else self.pytype + + out_hint = None + if self.hint is not None: + out_hint = op(self.hint, ndigits) + + # Internally, None is used as sentinel to indicate that a something is not a node on an FX graph. At the + # same time, there is no way to wrap a plain None into an FX node. Thus, there is no way to pass None here + # without triggering some asserts that check whether we are mixing FX nodes with untracked arguments. The + # hack down below works, because all round function down the line all take ndigits=None as default in their + # signature. + # TODO: Remove the args construction below if a different sentinel is used by FX. + args = [self.fx_node] + if ndigits is not None: + args.append(ndigits) + fx_node, _ = self.shape_env._create_fx_call_function(op, tuple(args)) + return SymNode(out, self.shape_env, pytype, out_hint, fx_node=fx_node) + + setattr(SymNode, f"_{method_attr}", round_impl) + else: + setattr(SymNode, f"_{method_attr}", binary_magic_impl) + + +def _make_node_sizes_strides(method, func): + # NB: don't LRU cache, lots of arguments + + def sizes_strides_impl(self, sizes, strides): + op = getattr(sys.modules[__name__], method) + if sym_function_mode(): + return to_node( + self, + handle_sym_dispatch( + op, + ([wrap_node(s) for s in sizes], [wrap_node(s) for s in strides]), + {}, + ), + ) + size_exprs = [s.expr for s in sizes] + stride_exprs = [s.expr for s in strides] + try: + out = func(size_exprs, stride_exprs) + except Exception: + log.warning("failed to eval %s(%s, %s)", method, size_exprs, stride_exprs) + raise + # bool is never expandable + + size_hints = [] + out_hint = None + for s in sizes: + if s.hint is None: + break + size_hints.append(s.hint) + else: + stride_hints = [] + for s in strides: + if s.hint is None: + break + stride_hints.append(s.hint) + else: + out_hint = op(size_hints, stride_hints) + + # NB: This is the indicator function, not the actual bool! + pytype: Type + if method.endswith("_indicator"): + pytype = int + else: + pytype = bool + return SymNode(out, self.shape_env, pytype, out_hint) + + setattr(SymNode, f"_{method}", sizes_strides_impl) + + # TODO: This is technically hotpath, but in the ideal end state + # guards on this will resolve at a higher level so you never + # spend time in this code + def sizes_strides_user(sizes, strides): + import sympy + + from torch.fx.experimental.symbolic_shapes import ( + eval_is_non_overlapping_and_dense, + ) + + for a in itertools.chain(sizes, strides): + if isinstance(a, SymInt): + return wrap_node( + getattr(a.node, method)( + [to_node(a.node, b) for b in sizes], + [to_node(a.node, b) for b in strides], + ) + ) + if method == "is_non_overlapping_and_dense_indicator": + return eval_is_non_overlapping_and_dense(sizes, strides) + else: + # TODO: this is an awful implementation + return bool( + func( + [sympy.sympify(a) for a in sizes], + [sympy.sympify(a) for a in strides], + ) + ) + + # Skip for is_non_overlapping_and_dense_indicator + if not hasattr(sys.modules[__name__], method): + setattr(sys.modules[__name__], method, sizes_strides_user) + + +for method, func in magic_methods.items(): + _make_node_magic(method, func) + +for method, func in sizes_strides_methods.items(): + _make_node_sizes_strides(method, func) + + +def _make_user_magic(method, user_type): + # User magic takes care of wrapping the other operand into a node, + # so that our internal logic can assume everything is nodes + + if method in magic_methods_on_operator_with_trailing_underscore: + method_attr = f"sym_{method}" + else: + method_attr = method + + def get_constant(x: Union[SymInt, int, SymFloat, float, SymBool, bool]): + if isinstance(x, (int, float, bool)): + return x + if isinstance(x, SymBool): + return x.node.guard_bool("", 0) + raise AssertionError("expect to be called with constant SymBools") + + def is_constant(x): + if isinstance(x, (int, float, bool)): + return True + if isinstance(x, (SymInt, SymFloat, SymBool)): + return x.node.is_constant() + return False + + if method in bool_becomes_int_magic_methods: + + def promote(x): + """Implements True+True=2, which works in python but not sympy""" + if isinstance(x, SymBool): + return SymInt(x.node.wrap_int(int(x))) + return x + + else: + + def promote(x): + return x + + # Before and after performing the operation, check if any operands are constant. + # If so, extract out the constant values first. If `self` itself is a + # constant, then "redispatch" by calling back into the operator. Sometimes + # this means that operations involving SymBool return plain bools. + # Alternatively, we could also rewrap into constant Symbool (i.e. by + # implementing wrap_bool in ConstantSymNodeImpl), but we're not doing that + # today for no particular reason. + def unary_magic_impl(self): + self = promote(self) + if is_constant(self): + return (method_to_operator(method))(get_constant(self)) + return wrap_node(getattr(self.node, method_attr)()) + + def binary_magic_impl(self, other): + sym_node_log.debug("MAGIC %s %s %s", method, self, other) + self = promote(self) + other = promote(other) + if is_constant(self): + return (method_to_operator(method))(get_constant(self), other) + if is_constant(other): + other = get_constant(other) + other_node = to_node(self.node, other) + if other_node is NotImplemented: + return NotImplemented + ret = wrap_node(getattr(self.node, method_attr)(other_node)) + return get_constant(ret) if is_constant(ret) else ret + + def rbinary_magic_impl(self, other): + self = promote(self) + other = promote(other) + if is_constant(self): + return (method_to_operator(method))(get_constant(self), other) + if is_constant(other): + other = get_constant(other) + other_node = to_node(self.node, other) + if other_node is NotImplemented: + return NotImplemented + ret = wrap_node(getattr(other_node, method_attr)(self.node)) + return get_constant(ret) if is_constant(ret) else ret + + if method in unary_magic_methods: + setattr(user_type, f"__{method}__", unary_magic_impl) + elif method in unary_nonmagic_methods: + orig = getattr(user_type, method) + setattr(user_type, method, update_wrapper(unary_magic_impl, orig)) + elif method == "sym_ite": + + def sym_ite_magic_impl(pred, then_val, else_val): + pred_node = pred.node + then_node = to_node(pred_node, then_val) + else_node = to_node(pred_node, else_val) + if then_node is NotImplemented or else_node is NotImplemented: + return NotImplemented + assert ( + isinstance(then_node, SymNode) + and isinstance(else_node, SymNode) + and then_node.pytype == else_node.pytype + ) + ret = wrap_node(getattr(pred.node, method_attr)(then_node, else_node)) + return get_constant(ret) if ret.node.is_constant() else ret + + setattr(user_type, f"__{method}__", sym_ite_magic_impl) + elif method == "round": + + def round_magic_impl(self, ndigits=None): + if is_constant(self): + return builtins.round(get_constant(self), ndigits) + + return wrap_node(getattr(self.node, method)(ndigits)) + + setattr(user_type, f"__{method}__", round_magic_impl) + else: + setattr(user_type, f"__{method}__", binary_magic_impl) + if method in reflectable_magic_methods: + setattr(user_type, f"__r{method}__", rbinary_magic_impl) + + +for method, func in magic_methods.items(): # type: ignore[assignment] + if method in only_bool_magic_methods: + _make_user_magic(method, SymBool) + continue + if method in only_float_magic_methods: + _make_user_magic(method, SymFloat) + continue + if method in also_bool_magic_methods or method in bool_becomes_int_magic_methods: + _make_user_magic(method, SymBool) + _make_user_magic(method, SymInt) + _make_user_magic(method, SymFloat) + +del method +del func diff --git a/shared/package-files/78/78184ffaca0a3fcc327c35f2633e621ca3fdac870601700e8178f7d2f6a6ce16/blob b/shared/package-files/78/78184ffaca0a3fcc327c35f2633e621ca3fdac870601700e8178f7d2f6a6ce16/blob new file mode 100644 index 0000000000000000000000000000000000000000..5f652590f0a7a19628eb5e96e57f3a91f0a1d22c --- /dev/null +++ b/shared/package-files/78/78184ffaca0a3fcc327c35f2633e621ca3fdac870601700e8178f7d2f6a6ce16/blob @@ -0,0 +1,517 @@ +"""Reference Stata results for Cochrane-Orcutt regression tests.""" + +import numpy as np + +from statsmodels.tools.testing import ParamsTableTestBunch + +est = dict( + N=201, + df_m=2, + df_r=198, + F=221.0377347263228, + r2=.6906614775140222, + rmse=10.66735221013527, + mss=50304.8300537672, + rss=22530.89582866539, + r2_a=.6875368459737599, + ll=-759.5001027340874, + N_gaps=0, + tol=1.00000000000e-06, + max_ic=100, + ic=4, + dw=1.993977855026291, + dw_0=2.213805016982909, + rho=-.1080744185979703, + rank=3, + cmd="prais", + title="Prais-Winsten AR(1) regression", + cmdline="prais g_realinv g_realgdp L.realint, corc rhotype(tscorr)", + tranmeth="corc", + method="iterated", + depvar="g_realinv", + predict="prais_p", + rhotype="tscorr", + vce="ols", + properties="b V", +) + +params_table = np.array([ + 4.3704012379033, + .20815070994319, + 20.996331163589, + 2.939551581e-52, + 3.9599243998713, + 4.7808780759353, + 198, + 1.9720174778363, + 0, + -.5792713864578, + .26801792119756, + -2.1613158697355, + .03187117882819, + -1.1078074114328, + -.05073536148285, + 198, + 1.9720174778363, + 0, + -9.509886614971, + .99049648344574, + -9.6011311235432, + 3.656321106e-18, + -11.463162992061, + -7.5566102378806, + 198, + 1.9720174778363, + 0]).reshape(3, 9) + +params_table_colnames = "b se t pvalue ll ul df crit eform".split() + +params_table_rownames = "g_realgdp L.realint _cons".split() + +cov = np.array([ + .04609356125016, + -.00228616599156, + -.13992917065996, + -.00228616599156, + .08103590074551, + -.10312637237487, + -.13992917065996, + -.10312637237487, + 1.1416832888557]).reshape(3, 3) + +cov_colnames = "g_realgdp L.realint _cons".split() + +cov_rownames = "g_realgdp L.realint _cons".split() + +fittedvalues = np.array([ + 34.092961143383, + -12.024019193439, + -4.0322884907855, + 26.930266763436, + -18.388570551209, + -8.1324920108371, + -31.875322937642, + .21814034941388, + 21.286872048596, + 18.046781817358, + 24.839977757054, + 20.524927286892, + 9.4135589847345, + 5.0452309081846, + -5.6551802066401, + 11.985460837387, + 10.881000973745, + 22.932381778173, + 2.2243337561549, + 28.678018086877, + 8.4960232938048, + 12.595931232461, + -5.9735838194583, + 31.918171668207, + 12.51486507374, + 24.858076725235, + 30.404510147102, + 32.036251557873, + -3.4858432808681, + .47271857077911, + 4.4052813399748, + 3.2797897853075, + -10.188593201973, + 4.2830255779438, + 3.2910087767189, + 26.047109629787, + 18.955198396277, + 2.5715957164729, + -2.3281798982217, + 17.032381944743, + -4.0901785042795, + .91987313367478, + -18.683722252157, + -12.984352504073, + -6.6160771495293, + 4.5273942020195, + -28.749156193466, + 38.148138299645, + -.57670949517535, + 4.4996010868259, + -5.6725761358388, + 20.923003763987, + 31.094336738501, + 6.5964070665898, + 18.667129468109, + 34.425102067117, + 12.495888351027, + -20.391896794875, + 9.6404042884163, + -23.337183583421, + -3.2089713311258, + -25.745423471535, + -13.275374642526, + -29.102203184727, + 3.6718187868943, + 20.796143264795, + 13.375486730466, + 30.503754833333, + 1.9832701043709, + -.33573283324142, + 3.8454619057923, + 11.198841650909, + 27.300615912881, + 21.617271919636, + -10.213387774549, + -3.041115945304, + 58.662013692103, + 9.3875351174185, + 14.62429232726, + -7.0289661733807, + -6.3287417283568, + 5.3688078321969, + -3.9071766792954, + -2.3350903711443, + -45.218293861742, + -12.518622374718, + 22.354531985202, + 24.642689788549, + -26.596828143888, + 8.8860015710942, + -35.108835611339, + -42.53255546273, + -6.0981548538498, + -17.177799997821, + -11.40329039155, + 7.0180843697455, + 26.705585327159, + 21.928461900264, + 23.355257443029, + 21.894505946705, + 17.657379506229, + 3.4294676089343, + .97440677130275, + 3.509217298751, + 3.2828913970637, + 14.944972085155, + 1.2923006012963, + 6.0435554866624, + -8.8442213362579, + 5.4509233390479, + -2.6794059247137, + -.48161809935521, + 8.4201161664985, + 4.549532431433, + 18.996304264647, + -1.8170413137623, + 11.849281819014, + -1.7066851102854, + 12.218564198008, + 4.6715818362824, + 2.108627710813, + 2.1972303599907, + -8.5249858114578, + 8.0728543937531, + -4.5685185423019, + -11.135138151837, + -24.047910391406, + -19.615146607087, + -.44428684605231, + -3.4877810606396, + -3.9736701841582, + 9.0239662841874, + 8.5557600343168, + 8.2271736548708, + 9.0458357352972, + -6.3116081663522, + 1.5636968490473, + -.95723547143789, + 13.44821815082, + 6.7721586886424, + 13.649238514998, + 1.1579094135284, + 8.6396143031575, + -6.7325794361447, + -7.0767574403351, + 3.1400395218988, + .91586368309611, + 1.2368141501238, + 19.694940608963, + 4.0145204498294, + 8.3107956501685, + 2.7428657521209, + 13.988676494758, + 10.116898229369, + 2.524027931198, + 4.6794023157157, + 3.5155627033849, + 11.945878601415, + 18.880925278224, + 4.5865622289454, + 3.2393307465763, + 11.062953867859, + 20.793966231154, + -6.3076444941097, + 23.178864105791, + -8.9873099715132, + -1.107322743866, + -16.332040882272, + .42734142108626, + -15.050781890016, + -4.6612306163595, + 4.565652288529, + .80725599873503, + -.87706444767528, + -8.5407936802022, + -1.3521383036839, + 4.4765977604986, + 19.623863498831, + 7.1113956960438, + 3.9798487855641, + 3.6934842863203, + 4.6801104799091, + 6.7218162617593, + 7.7832579175778, + -1.2290990957424, + 3.0474310004174, + 2.7567736850761, + 11.188206993423, + -4.3306276498455, + -9.5365114805844, + -.53338170341178, + -5.206342794124, + 4.1154674910376, + 4.7884361973806, + -.64799653797949, + -10.743852791188, + -2.461403042047, + -17.431541988995, + -36.151189705211, + -43.711601400093, + -12.334881925913, + 4.3341943478598]) + +fittedvalues_colnames = "fittedvalues".split() + +fittedvalues_rownames = ["r"+str(n) for n in range(1, 203)] + +fittedvalues_se = np.array([ + 1.6473872957314, + 1.0113850707964, + .7652190209006, + 1.534040692487, + 1.2322657893516, + .91158310011358, + 1.8788908534927, + .69811681139453, + 1.1767226952576, + .98858641944986, + 1.2396486964702, + 1.0822616701665, + .7753481322096, + .76860948102754, + .82419167032501, + .82704859414698, + .82559058693092, + 1.1856589638289, + .75525402187835, + 1.3922568629515, + .91202394595876, + .88520111465725, + .83302439819375, + 1.5372725435314, + .89177714550085, + 1.2372408530959, + 1.5528101417195, + 1.5366212693726, + .89043286423929, + .75705684478985, + .73518329909511, + 1.0572392569996, + .93211401184553, + .75196863280241, + .69360947719119, + 1.3106012580927, + 1.0209999290642, + .81133440956099, + .75559203443239, + .94831739014224, + .93322729630976, + .69417535741881, + 1.2398628905688, + 1.0261547060202, + .86379439641561, + .75032871325094, + 1.6696098440084, + 1.8282957404356, + .70460484132802, + .79812152719782, + .8016314317639, + 1.0872600753814, + 1.4987341895633, + .70529145955969, + 1.0149968053074, + 1.6467690495895, + 1.4677194036031, + 1.3384921199391, + 1.7046600039586, + 1.8412203199988, + 1.4367363864341, + 1.8103264820977, + 2.1242535073081, + 2.1101077640804, + .745443770473, + 1.3651585515035, + .94103291060948, + 1.5981517654886, + .77654854940188, + .96643611834989, + .97013991129283, + .97997241479455, + 1.9501042753844, + 1.1758285978818, + .9603215961611, + .96398854110297, + 2.7840981863809, + 1.413576103565, + 1.2364541532613, + .85434724833597, + 1.3715636637071, + 1.6066244823944, + 1.0686828612843, + 1.3176342918943, + 2.5021204574497, + 1.1330278834213, + 1.1636905462155, + 1.3340487203567, + 1.8517041947194, + 1.1639745295786, + 2.304428659791, + 2.6786336953086, + 2.5354570978302, + 1.1805089049206, + 1.4742162139537, + 2.1143611509083, + 1.5986085606212, + 1.4576906503482, + 1.5624993432094, + 1.3158885079997, + 1.3538646144937, + 1.619414838601, + 1.5015020934095, + 1.3855500128549, + .86402762365746, + 1.2492579410465, + 1.0127848313981, + .7158840034754, + 2.6885176805365, + .83774886448436, + .81595294371756, + .70504062914926, + .73023061883128, + .69228489060199, + 1.0360869522995, + .75590017576772, + .80137295502042, + .73813943198212, + .87064014103306, + .93205385237951, + .73787688995958, + .90978243354856, + 1.2648707813937, + .72349602267222, + .93927915871284, + 1.0172563832871, + 1.6776109713009, + 1.3175046180712, + 1.1171209329088, + .78301185980687, + .78918856044216, + .74112029520399, + .74451851348435, + .76567972163601, + .87244845911018, + .90049784898067, + .76120214907789, + .71166085065751, + .90870901548966, + .70296598825213, + .84621726620383, + .69493630035748, + .75059818136305, + .87986442867509, + .86277076414594, + .87380573440987, + .80727321528666, + .70768449827207, + 1.040570485976, + .78088040381913, + .74507562843308, + .69792915007094, + 1.0988781063157, + 1.0027100639643, + .72261812289435, + .96179349200945, + 1.0868653716913, + .86400879397201, + 1.094197020208, + .74093235691985, + .67984744050458, + .8543509596351, + 1.0818096940792, + .84834713756928, + 1.1852779873098, + .89126223599075, + .87108400982232, + 1.1499249237911, + .75958251908371, + 1.1014705573844, + .80471862911078, + .68374044074715, + 1.1058743822208, + .78261190454279, + 1.1081858646506, + 1.1333032178191, + .79529240253276, + 1.0984357956297, + 1.0696598625923, + 1.1524457583105, + 1.0091448954756, + 1.2183914737714, + 1.1249902630054, + .78498039737187, + 1.04667102358, + .68135274836726, + 1.9934991355412, + .995276050357, + .77642057869112, + .92353879856007, + 1.5308870921603, + .78757917918954, + .73146117757714, + .70335029981046, + .73869949489316, + 1.6122142696964, + 1.023758116961, + 2.5353634753616, + 2.1057022389201, + 3.0080233992196, + 1.1648858140616, + 1.3964393384387]) + +fittedvalues_se_colnames = "fittedvalues_se".split() + +fittedvalues_se_rownames = ["r"+str(n) for n in range(1, 203)] + + +results = ParamsTableTestBunch( + params_table=params_table, + params_table_colnames=params_table_colnames, + params_table_rownames=params_table_rownames, + cov=cov, + cov_colnames=cov_colnames, + cov_rownames=cov_rownames, + fittedvalues=fittedvalues, + fittedvalues_colnames=fittedvalues_colnames, + fittedvalues_rownames=fittedvalues_rownames, + fittedvalues_se=fittedvalues_se, + fittedvalues_se_colnames=fittedvalues_se_colnames, + fittedvalues_se_rownames=fittedvalues_se_rownames, + **est +) diff --git a/shared/package-files/78/781ae5076fc4ff420878a1ab128e8b03b68691c3ada83ae6bf50b21c42182dae/blob b/shared/package-files/78/781ae5076fc4ff420878a1ab128e8b03b68691c3ada83ae6bf50b21c42182dae/blob new file mode 100644 index 0000000000000000000000000000000000000000..6cdb6e9660a1c62b9c19344055d9d96f93acee1a --- /dev/null +++ b/shared/package-files/78/781ae5076fc4ff420878a1ab128e8b03b68691c3ada83ae6bf50b21c42182dae/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/78/781ff82770fb17287532b6b9bb00739fb602415db5ef61c363c624350bd11d48/blob b/shared/package-files/78/781ff82770fb17287532b6b9bb00739fb602415db5ef61c363c624350bd11d48/blob new file mode 100644 index 0000000000000000000000000000000000000000..e226dac88b8824b68136b6e2efcba738e799c193 --- /dev/null +++ b/shared/package-files/78/781ff82770fb17287532b6b9bb00739fb602415db5ef61c363c624350bd11d48/blob @@ -0,0 +1,3926 @@ +""" test to_datetime """ + +import calendar +from collections import deque +from datetime import ( + date, + datetime, + timedelta, + timezone, +) +from decimal import Decimal +import locale + +from dateutil.parser import parse +from dateutil.tz.tz import tzoffset +import numpy as np +import pytest +import pytz + +from pandas._libs import tslib +from pandas._libs.tslibs import ( + iNaT, + parsing, +) +from pandas.compat import PY314 +from pandas.errors import ( + OutOfBoundsDatetime, + OutOfBoundsTimedelta, +) +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import is_datetime64_ns_dtype + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + NaT, + Series, + Timestamp, + date_range, + isna, + to_datetime, +) +import pandas._testing as tm +from pandas.core.arrays import DatetimeArray +from pandas.core.tools import datetimes as tools +from pandas.core.tools.datetimes import start_caching_at + +PARSING_ERR_MSG = ( + r"You might want to try:\n" + r" - passing `format` if your strings have a consistent format;\n" + r" - passing `format=\'ISO8601\'` if your strings are all ISO8601 " + r"but not necessarily in exactly the same format;\n" + r" - passing `format=\'mixed\'`, and the format will be inferred " + r"for each element individually. You might want to use `dayfirst` " + r"alongside this." +) + +if PY314: + NOT_99 = ", not 99" + DAY_IS_OUT_OF_RANGE = ( + r"day \d{1,2} must be in range 1\.\.\d{1,2} for month \d{1,2} in year \d{4}" + ", at position 0" + ) +else: + NOT_99 = "" + DAY_IS_OUT_OF_RANGE = "day is out of range for month, at position 0" + + +pytestmark = pytest.mark.filterwarnings( + "ignore:errors='ignore' is deprecated:FutureWarning" +) + + +@pytest.fixture(params=[True, False]) +def cache(request): + """ + cache keyword to pass to to_datetime. + """ + return request.param + + +class TestTimeConversionFormats: + @pytest.mark.parametrize("readonly", [True, False]) + def test_to_datetime_readonly(self, readonly): + # GH#34857 + arr = np.array([], dtype=object) + if readonly: + arr.setflags(write=False) + result = to_datetime(arr) + expected = to_datetime([]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "format, expected", + [ + [ + "%d/%m/%Y", + [Timestamp("20000101"), Timestamp("20000201"), Timestamp("20000301")], + ], + [ + "%m/%d/%Y", + [Timestamp("20000101"), Timestamp("20000102"), Timestamp("20000103")], + ], + ], + ) + def test_to_datetime_format(self, cache, index_or_series, format, expected): + values = index_or_series(["1/1/2000", "1/2/2000", "1/3/2000"]) + result = to_datetime(values, format=format, cache=cache) + expected = index_or_series(expected) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "arg, expected, format", + [ + ["1/1/2000", "20000101", "%d/%m/%Y"], + ["1/1/2000", "20000101", "%m/%d/%Y"], + ["1/2/2000", "20000201", "%d/%m/%Y"], + ["1/2/2000", "20000102", "%m/%d/%Y"], + ["1/3/2000", "20000301", "%d/%m/%Y"], + ["1/3/2000", "20000103", "%m/%d/%Y"], + ], + ) + def test_to_datetime_format_scalar(self, cache, arg, expected, format): + result = to_datetime(arg, format=format, cache=cache) + expected = Timestamp(expected) + assert result == expected + + def test_to_datetime_format_YYYYMMDD(self, cache): + ser = Series([19801222, 19801222] + [19810105] * 5) + expected = Series([Timestamp(x) for x in ser.apply(str)]) + + result = to_datetime(ser, format="%Y%m%d", cache=cache) + tm.assert_series_equal(result, expected) + + result = to_datetime(ser.apply(str), format="%Y%m%d", cache=cache) + tm.assert_series_equal(result, expected) + + def test_to_datetime_format_YYYYMMDD_with_nat(self, cache): + # Explicit cast to float to explicit cast when setting np.nan + ser = Series([19801222, 19801222] + [19810105] * 5, dtype="float") + # with NaT + expected = Series( + [Timestamp("19801222"), Timestamp("19801222")] + [Timestamp("19810105")] * 5 + ) + expected[2] = np.nan + ser[2] = np.nan + + result = to_datetime(ser, format="%Y%m%d", cache=cache) + tm.assert_series_equal(result, expected) + + # string with NaT + ser2 = ser.apply(str) + ser2[2] = "nat" + with pytest.raises( + ValueError, + match=( + 'unconverted data remains when parsing with format "%Y%m%d": ".0", ' + "at position 0" + ), + ): + # https://github.com/pandas-dev/pandas/issues/50051 + to_datetime(ser2, format="%Y%m%d", cache=cache) + + def test_to_datetime_format_YYYYMM_with_nat(self, cache): + # https://github.com/pandas-dev/pandas/issues/50237 + # Explicit cast to float to explicit cast when setting np.nan + ser = Series([198012, 198012] + [198101] * 5, dtype="float") + expected = Series( + [Timestamp("19801201"), Timestamp("19801201")] + [Timestamp("19810101")] * 5 + ) + expected[2] = np.nan + ser[2] = np.nan + result = to_datetime(ser, format="%Y%m", cache=cache) + tm.assert_series_equal(result, expected) + + def test_to_datetime_format_YYYYMMDD_ignore(self, cache): + # coercion + # GH 7930, GH 14487 + ser = Series([20121231, 20141231, 99991231]) + result = to_datetime(ser, format="%Y%m%d", errors="ignore", cache=cache) + expected = Series( + [20121231, 20141231, 99991231], + dtype=object, + ) + tm.assert_series_equal(result, expected) + + def test_to_datetime_format_YYYYMMDD_ignore_with_outofbounds(self, cache): + # https://github.com/pandas-dev/pandas/issues/26493 + result = to_datetime( + ["15010101", "20150101", np.nan], + format="%Y%m%d", + errors="ignore", + cache=cache, + ) + expected = Index(["15010101", "20150101", np.nan], dtype=object) + tm.assert_index_equal(result, expected) + + def test_to_datetime_format_YYYYMMDD_coercion(self, cache): + # coercion + # GH 7930 + ser = Series([20121231, 20141231, 99991231]) + result = to_datetime(ser, format="%Y%m%d", errors="coerce", cache=cache) + expected = Series(["20121231", "20141231", "NaT"], dtype="M8[ns]") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "input_s", + [ + # Null values with Strings + ["19801222", "20010112", None], + ["19801222", "20010112", np.nan], + ["19801222", "20010112", NaT], + ["19801222", "20010112", "NaT"], + # Null values with Integers + [19801222, 20010112, None], + [19801222, 20010112, np.nan], + [19801222, 20010112, NaT], + [19801222, 20010112, "NaT"], + ], + ) + def test_to_datetime_format_YYYYMMDD_with_none(self, input_s): + # GH 30011 + # format='%Y%m%d' + # with None + expected = Series([Timestamp("19801222"), Timestamp("20010112"), NaT]) + result = Series(to_datetime(input_s, format="%Y%m%d")) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "input_s, expected", + [ + # NaN before strings with invalid date values + [ + Series(["19801222", np.nan, "20010012", "10019999"]), + Series([Timestamp("19801222"), np.nan, np.nan, np.nan]), + ], + # NaN after strings with invalid date values + [ + Series(["19801222", "20010012", "10019999", np.nan]), + Series([Timestamp("19801222"), np.nan, np.nan, np.nan]), + ], + # NaN before integers with invalid date values + [ + Series([20190813, np.nan, 20010012, 20019999]), + Series([Timestamp("20190813"), np.nan, np.nan, np.nan]), + ], + # NaN after integers with invalid date values + [ + Series([20190813, 20010012, np.nan, 20019999]), + Series([Timestamp("20190813"), np.nan, np.nan, np.nan]), + ], + ], + ) + def test_to_datetime_format_YYYYMMDD_overflow(self, input_s, expected): + # GH 25512 + # format='%Y%m%d', errors='coerce' + result = to_datetime(input_s, format="%Y%m%d", errors="coerce") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "data, format, expected", + [ + ([pd.NA], "%Y%m%d%H%M%S", DatetimeIndex(["NaT"])), + ([pd.NA], None, DatetimeIndex(["NaT"])), + ( + [pd.NA, "20210202202020"], + "%Y%m%d%H%M%S", + DatetimeIndex(["NaT", "2021-02-02 20:20:20"]), + ), + (["201010", pd.NA], "%y%m%d", DatetimeIndex(["2020-10-10", "NaT"])), + (["201010", pd.NA], "%d%m%y", DatetimeIndex(["2010-10-20", "NaT"])), + ([None, np.nan, pd.NA], None, DatetimeIndex(["NaT", "NaT", "NaT"])), + ([None, np.nan, pd.NA], "%Y%m%d", DatetimeIndex(["NaT", "NaT", "NaT"])), + ], + ) + def test_to_datetime_with_NA(self, data, format, expected): + # GH#42957 + result = to_datetime(data, format=format) + tm.assert_index_equal(result, expected) + + def test_to_datetime_with_NA_with_warning(self): + # GH#42957 + result = to_datetime(["201010", pd.NA]) + expected = DatetimeIndex(["2010-10-20", "NaT"]) + tm.assert_index_equal(result, expected) + + def test_to_datetime_format_integer(self, cache): + # GH 10178 + ser = Series([2000, 2001, 2002]) + expected = Series([Timestamp(x) for x in ser.apply(str)]) + + result = to_datetime(ser, format="%Y", cache=cache) + tm.assert_series_equal(result, expected) + + ser = Series([200001, 200105, 200206]) + expected = Series([Timestamp(x[:4] + "-" + x[4:]) for x in ser.apply(str)]) + + result = to_datetime(ser, format="%Y%m", cache=cache) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "int_date, expected", + [ + # valid date, length == 8 + [20121030, datetime(2012, 10, 30)], + # short valid date, length == 6 + [199934, datetime(1999, 3, 4)], + # long integer date partially parsed to datetime(2012,1,1), length > 8 + [2012010101, 2012010101], + # invalid date partially parsed to datetime(2012,9,9), length == 8 + [20129930, 20129930], + # short integer date partially parsed to datetime(2012,9,9), length < 8 + [2012993, 2012993], + # short invalid date, length == 4 + [2121, 2121], + ], + ) + def test_int_to_datetime_format_YYYYMMDD_typeerror(self, int_date, expected): + # GH 26583 + result = to_datetime(int_date, format="%Y%m%d", errors="ignore") + assert result == expected + + def test_to_datetime_format_microsecond(self, cache): + month_abbr = calendar.month_abbr[4] + val = f"01-{month_abbr}-2011 00:00:01.978" + + format = "%d-%b-%Y %H:%M:%S.%f" + result = to_datetime(val, format=format, cache=cache) + exp = datetime.strptime(val, format) + assert result == exp + + @pytest.mark.parametrize( + "value, format, dt", + [ + ["01/10/2010 15:20", "%m/%d/%Y %H:%M", Timestamp("2010-01-10 15:20")], + ["01/10/2010 05:43", "%m/%d/%Y %I:%M", Timestamp("2010-01-10 05:43")], + [ + "01/10/2010 13:56:01", + "%m/%d/%Y %H:%M:%S", + Timestamp("2010-01-10 13:56:01"), + ], + # The 3 tests below are locale-dependent. + # They pass, except when the machine locale is zh_CN or it_IT . + pytest.param( + "01/10/2010 08:14 PM", + "%m/%d/%Y %I:%M %p", + Timestamp("2010-01-10 20:14"), + marks=pytest.mark.xfail( + locale.getlocale()[0] in ("zh_CN", "it_IT"), + reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", + strict=False, + ), + ), + pytest.param( + "01/10/2010 07:40 AM", + "%m/%d/%Y %I:%M %p", + Timestamp("2010-01-10 07:40"), + marks=pytest.mark.xfail( + locale.getlocale()[0] in ("zh_CN", "it_IT"), + reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", + strict=False, + ), + ), + pytest.param( + "01/10/2010 09:12:56 AM", + "%m/%d/%Y %I:%M:%S %p", + Timestamp("2010-01-10 09:12:56"), + marks=pytest.mark.xfail( + locale.getlocale()[0] in ("zh_CN", "it_IT"), + reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", + strict=False, + ), + ), + ], + ) + def test_to_datetime_format_time(self, cache, value, format, dt): + assert to_datetime(value, format=format, cache=cache) == dt + + @td.skip_if_not_us_locale + def test_to_datetime_with_non_exact(self, cache): + # GH 10834 + # 8904 + # exact kw + ser = Series( + ["19MAY11", "foobar19MAY11", "19MAY11:00:00:00", "19MAY11 00:00:00Z"] + ) + result = to_datetime(ser, format="%d%b%y", exact=False, cache=cache) + expected = to_datetime( + ser.str.extract(r"(\d+\w+\d+)", expand=False), format="%d%b%y", cache=cache + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "format, expected", + [ + ("%Y-%m-%d", Timestamp(2000, 1, 3)), + ("%Y-%d-%m", Timestamp(2000, 3, 1)), + ("%Y-%m-%d %H", Timestamp(2000, 1, 3, 12)), + ("%Y-%d-%m %H", Timestamp(2000, 3, 1, 12)), + ("%Y-%m-%d %H:%M", Timestamp(2000, 1, 3, 12, 34)), + ("%Y-%d-%m %H:%M", Timestamp(2000, 3, 1, 12, 34)), + ("%Y-%m-%d %H:%M:%S", Timestamp(2000, 1, 3, 12, 34, 56)), + ("%Y-%d-%m %H:%M:%S", Timestamp(2000, 3, 1, 12, 34, 56)), + ("%Y-%m-%d %H:%M:%S.%f", Timestamp(2000, 1, 3, 12, 34, 56, 123456)), + ("%Y-%d-%m %H:%M:%S.%f", Timestamp(2000, 3, 1, 12, 34, 56, 123456)), + ( + "%Y-%m-%d %H:%M:%S.%f%z", + Timestamp(2000, 1, 3, 12, 34, 56, 123456, tz="UTC+01:00"), + ), + ( + "%Y-%d-%m %H:%M:%S.%f%z", + Timestamp(2000, 3, 1, 12, 34, 56, 123456, tz="UTC+01:00"), + ), + ], + ) + def test_non_exact_doesnt_parse_whole_string(self, cache, format, expected): + # https://github.com/pandas-dev/pandas/issues/50412 + # the formats alternate between ISO8601 and non-ISO8601 to check both paths + result = to_datetime( + "2000-01-03 12:34:56.123456+01:00", format=format, exact=False + ) + assert result == expected + + @pytest.mark.parametrize( + "arg", + [ + "2012-01-01 09:00:00.000000001", + "2012-01-01 09:00:00.000001", + "2012-01-01 09:00:00.001", + "2012-01-01 09:00:00.001000", + "2012-01-01 09:00:00.001000000", + ], + ) + def test_parse_nanoseconds_with_formula(self, cache, arg): + # GH8989 + # truncating the nanoseconds when a format was provided + expected = to_datetime(arg, cache=cache) + result = to_datetime(arg, format="%Y-%m-%d %H:%M:%S.%f", cache=cache) + assert result == expected + + @pytest.mark.parametrize( + "value,fmt,expected", + [ + ["2009324", "%Y%W%w", Timestamp("2009-08-13")], + ["2013020", "%Y%U%w", Timestamp("2013-01-13")], + ], + ) + def test_to_datetime_format_weeks(self, value, fmt, expected, cache): + assert to_datetime(value, format=fmt, cache=cache) == expected + + @pytest.mark.parametrize( + "fmt,dates,expected_dates", + [ + [ + "%Y-%m-%d %H:%M:%S %Z", + ["2010-01-01 12:00:00 UTC"] * 2, + [Timestamp("2010-01-01 12:00:00", tz="UTC")] * 2, + ], + [ + "%Y-%m-%d %H:%M:%S%z", + ["2010-01-01 12:00:00+0100"] * 2, + [ + Timestamp( + "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=60)) + ) + ] + * 2, + ], + [ + "%Y-%m-%d %H:%M:%S %z", + ["2010-01-01 12:00:00 +0100"] * 2, + [ + Timestamp( + "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=60)) + ) + ] + * 2, + ], + [ + "%Y-%m-%d %H:%M:%S %z", + ["2010-01-01 12:00:00 Z", "2010-01-01 12:00:00 Z"], + [ + Timestamp( + "2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0) + ), # pytz coerces to UTC + Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0)), + ], + ], + ], + ) + def test_to_datetime_parse_tzname_or_tzoffset(self, fmt, dates, expected_dates): + # GH 13486 + result = to_datetime(dates, format=fmt) + expected = Index(expected_dates) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "fmt,dates,expected_dates", + [ + [ + "%Y-%m-%d %H:%M:%S %Z", + [ + "2010-01-01 12:00:00 UTC", + "2010-01-01 12:00:00 GMT", + "2010-01-01 12:00:00 US/Pacific", + ], + [ + Timestamp("2010-01-01 12:00:00", tz="UTC"), + Timestamp("2010-01-01 12:00:00", tz="GMT"), + Timestamp("2010-01-01 12:00:00", tz="US/Pacific"), + ], + ], + [ + "%Y-%m-%d %H:%M:%S %z", + ["2010-01-01 12:00:00 +0100", "2010-01-01 12:00:00 -0100"], + [ + Timestamp( + "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=60)) + ), + Timestamp( + "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=-60)) + ), + ], + ], + ], + ) + def test_to_datetime_parse_tzname_or_tzoffset_utc_false_deprecated( + self, fmt, dates, expected_dates + ): + # GH 13486, 50887 + msg = "parsing datetimes with mixed time zones will raise an error" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = to_datetime(dates, format=fmt) + expected = Index(expected_dates) + tm.assert_equal(result, expected) + + def test_to_datetime_parse_tzname_or_tzoffset_different_tz_to_utc(self): + # GH 32792 + dates = [ + "2010-01-01 12:00:00 +0100", + "2010-01-01 12:00:00 -0100", + "2010-01-01 12:00:00 +0300", + "2010-01-01 12:00:00 +0400", + ] + expected_dates = [ + "2010-01-01 11:00:00+00:00", + "2010-01-01 13:00:00+00:00", + "2010-01-01 09:00:00+00:00", + "2010-01-01 08:00:00+00:00", + ] + fmt = "%Y-%m-%d %H:%M:%S %z" + + result = to_datetime(dates, format=fmt, utc=True) + expected = DatetimeIndex(expected_dates) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "offset", ["+0", "-1foo", "UTCbar", ":10", "+01:000:01", ""] + ) + def test_to_datetime_parse_timezone_malformed(self, offset): + fmt = "%Y-%m-%d %H:%M:%S %z" + date = "2010-01-01 12:00:00 " + offset + + msg = "|".join( + [ + r'^time data ".*" doesn\'t match format ".*", at position 0. ' + f"{PARSING_ERR_MSG}$", + r'^unconverted data remains when parsing with format ".*": ".*", ' + f"at position 0. {PARSING_ERR_MSG}$", + ] + ) + with pytest.raises(ValueError, match=msg): + to_datetime([date], format=fmt) + + def test_to_datetime_parse_timezone_keeps_name(self): + # GH 21697 + fmt = "%Y-%m-%d %H:%M:%S %z" + arg = Index(["2010-01-01 12:00:00 Z"], name="foo") + result = to_datetime(arg, format=fmt) + expected = DatetimeIndex(["2010-01-01 12:00:00"], tz="UTC", name="foo") + tm.assert_index_equal(result, expected) + + +class TestToDatetime: + @pytest.mark.filterwarnings("ignore:Could not infer format") + def test_to_datetime_overflow(self): + # we should get an OutOfBoundsDatetime, NOT OverflowError + # TODO: Timestamp raises ValueError("could not convert string to Timestamp") + # can we make these more consistent? + arg = "08335394550" + msg = 'Parsing "08335394550" to datetime overflows, at position 0' + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(arg) + + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime([arg]) + + res = to_datetime(arg, errors="coerce") + assert res is NaT + res = to_datetime([arg], errors="coerce") + tm.assert_index_equal(res, Index([NaT])) + + res = to_datetime(arg, errors="ignore") + assert isinstance(res, str) and res == arg + res = to_datetime([arg], errors="ignore") + tm.assert_index_equal(res, Index([arg], dtype=object)) + + def test_to_datetime_mixed_datetime_and_string(self): + # GH#47018 adapted old doctest with new behavior + d1 = datetime(2020, 1, 1, 17, tzinfo=timezone(-timedelta(hours=1))) + d2 = datetime(2020, 1, 1, 18, tzinfo=timezone(-timedelta(hours=1))) + res = to_datetime(["2020-01-01 17:00 -0100", d2]) + expected = to_datetime([d1, d2]).tz_convert(timezone(timedelta(minutes=-60))) + tm.assert_index_equal(res, expected) + + def test_to_datetime_mixed_string_and_numeric(self): + # GH#55780 np.array(vals) would incorrectly cast the number to str + vals = ["2016-01-01", 0] + expected = DatetimeIndex([Timestamp(x) for x in vals]) + result = to_datetime(vals, format="mixed") + result2 = to_datetime(vals[::-1], format="mixed")[::-1] + result3 = DatetimeIndex(vals) + result4 = DatetimeIndex(vals[::-1])[::-1] + + tm.assert_index_equal(result, expected) + tm.assert_index_equal(result2, expected) + tm.assert_index_equal(result3, expected) + tm.assert_index_equal(result4, expected) + + @pytest.mark.parametrize( + "format", ["%Y-%m-%d", "%Y-%d-%m"], ids=["ISO8601", "non-ISO8601"] + ) + def test_to_datetime_mixed_date_and_string(self, format): + # https://github.com/pandas-dev/pandas/issues/50108 + d1 = date(2020, 1, 2) + res = to_datetime(["2020-01-01", d1], format=format) + expected = DatetimeIndex(["2020-01-01", "2020-01-02"], dtype="M8[ns]") + tm.assert_index_equal(res, expected) + + @pytest.mark.parametrize( + "fmt", + ["%Y-%d-%m %H:%M:%S%z", "%Y-%m-%d %H:%M:%S%z"], + ids=["non-ISO8601 format", "ISO8601 format"], + ) + @pytest.mark.parametrize( + "utc, args, expected", + [ + pytest.param( + True, + ["2000-01-01 01:00:00-08:00", "2000-01-01 02:00:00-08:00"], + DatetimeIndex( + ["2000-01-01 09:00:00+00:00", "2000-01-01 10:00:00+00:00"], + dtype="datetime64[ns, UTC]", + ), + id="all tz-aware, with utc", + ), + pytest.param( + False, + ["2000-01-01 01:00:00+00:00", "2000-01-01 02:00:00+00:00"], + DatetimeIndex( + ["2000-01-01 01:00:00+00:00", "2000-01-01 02:00:00+00:00"], + ), + id="all tz-aware, without utc", + ), + pytest.param( + True, + ["2000-01-01 01:00:00-08:00", "2000-01-01 02:00:00+00:00"], + DatetimeIndex( + ["2000-01-01 09:00:00+00:00", "2000-01-01 02:00:00+00:00"], + dtype="datetime64[ns, UTC]", + ), + id="all tz-aware, mixed offsets, with utc", + ), + pytest.param( + True, + ["2000-01-01 01:00:00", "2000-01-01 02:00:00+00:00"], + DatetimeIndex( + ["2000-01-01 01:00:00+00:00", "2000-01-01 02:00:00+00:00"], + dtype="datetime64[ns, UTC]", + ), + id="tz-aware string, naive pydatetime, with utc", + ), + ], + ) + @pytest.mark.parametrize( + "constructor", + [Timestamp, lambda x: Timestamp(x).to_pydatetime()], + ) + def test_to_datetime_mixed_datetime_and_string_with_format( + self, fmt, utc, args, expected, constructor + ): + # https://github.com/pandas-dev/pandas/issues/49298 + # https://github.com/pandas-dev/pandas/issues/50254 + # note: ISO8601 formats go down a fastpath, so we need to check both + # a ISO8601 format and a non-ISO8601 one + ts1 = constructor(args[0]) + ts2 = args[1] + result = to_datetime([ts1, ts2], format=fmt, utc=utc) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "fmt", + ["%Y-%d-%m %H:%M:%S%z", "%Y-%m-%d %H:%M:%S%z"], + ids=["non-ISO8601 format", "ISO8601 format"], + ) + @pytest.mark.parametrize( + "constructor", + [Timestamp, lambda x: Timestamp(x).to_pydatetime()], + ) + def test_to_datetime_mixed_datetime_and_string_with_format_mixed_offsets_utc_false( + self, fmt, constructor + ): + # https://github.com/pandas-dev/pandas/issues/49298 + # https://github.com/pandas-dev/pandas/issues/50254 + # note: ISO8601 formats go down a fastpath, so we need to check both + # a ISO8601 format and a non-ISO8601 one + args = ["2000-01-01 01:00:00", "2000-01-01 02:00:00+00:00"] + ts1 = constructor(args[0]) + ts2 = args[1] + msg = "parsing datetimes with mixed time zones will raise an error" + + expected = Index( + [ + Timestamp("2000-01-01 01:00:00"), + Timestamp("2000-01-01 02:00:00+0000", tz="UTC"), + ], + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = to_datetime([ts1, ts2], format=fmt, utc=False) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "fmt, expected", + [ + pytest.param( + "%Y-%m-%d %H:%M:%S%z", + Index( + [ + Timestamp("2000-01-01 09:00:00+0100", tz="UTC+01:00"), + Timestamp("2000-01-02 02:00:00+0200", tz="UTC+02:00"), + NaT, + ] + ), + id="ISO8601, non-UTC", + ), + pytest.param( + "%Y-%d-%m %H:%M:%S%z", + Index( + [ + Timestamp("2000-01-01 09:00:00+0100", tz="UTC+01:00"), + Timestamp("2000-02-01 02:00:00+0200", tz="UTC+02:00"), + NaT, + ] + ), + id="non-ISO8601, non-UTC", + ), + ], + ) + def test_to_datetime_mixed_offsets_with_none_tz(self, fmt, expected): + # https://github.com/pandas-dev/pandas/issues/50071 + msg = "parsing datetimes with mixed time zones will raise an error" + + with tm.assert_produces_warning(FutureWarning, match=msg): + result = to_datetime( + ["2000-01-01 09:00:00+01:00", "2000-01-02 02:00:00+02:00", None], + format=fmt, + utc=False, + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "fmt, expected", + [ + pytest.param( + "%Y-%m-%d %H:%M:%S%z", + DatetimeIndex( + ["2000-01-01 08:00:00+00:00", "2000-01-02 00:00:00+00:00", "NaT"], + dtype="datetime64[ns, UTC]", + ), + id="ISO8601, UTC", + ), + pytest.param( + "%Y-%d-%m %H:%M:%S%z", + DatetimeIndex( + ["2000-01-01 08:00:00+00:00", "2000-02-01 00:00:00+00:00", "NaT"], + dtype="datetime64[ns, UTC]", + ), + id="non-ISO8601, UTC", + ), + ], + ) + def test_to_datetime_mixed_offsets_with_none(self, fmt, expected): + # https://github.com/pandas-dev/pandas/issues/50071 + result = to_datetime( + ["2000-01-01 09:00:00+01:00", "2000-01-02 02:00:00+02:00", None], + format=fmt, + utc=True, + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "fmt", + ["%Y-%d-%m %H:%M:%S%z", "%Y-%m-%d %H:%M:%S%z"], + ids=["non-ISO8601 format", "ISO8601 format"], + ) + @pytest.mark.parametrize( + "args", + [ + pytest.param( + ["2000-01-01 01:00:00-08:00", "2000-01-01 02:00:00-07:00"], + id="all tz-aware, mixed timezones, without utc", + ), + ], + ) + @pytest.mark.parametrize( + "constructor", + [Timestamp, lambda x: Timestamp(x).to_pydatetime()], + ) + def test_to_datetime_mixed_datetime_and_string_with_format_raises( + self, fmt, args, constructor + ): + # https://github.com/pandas-dev/pandas/issues/49298 + # note: ISO8601 formats go down a fastpath, so we need to check both + # a ISO8601 format and a non-ISO8601 one + ts1 = constructor(args[0]) + ts2 = constructor(args[1]) + with pytest.raises( + ValueError, match="cannot be converted to datetime64 unless utc=True" + ): + to_datetime([ts1, ts2], format=fmt, utc=False) + + def test_to_datetime_np_str(self): + # GH#32264 + # GH#48969 + value = np.str_("2019-02-04 10:18:46.297000+0000") + + ser = Series([value]) + + exp = Timestamp("2019-02-04 10:18:46.297000", tz="UTC") + + assert to_datetime(value) == exp + assert to_datetime(ser.iloc[0]) == exp + + res = to_datetime([value]) + expected = Index([exp]) + tm.assert_index_equal(res, expected) + + res = to_datetime(ser) + expected = Series(expected) + tm.assert_series_equal(res, expected) + + @pytest.mark.parametrize( + "s, _format, dt", + [ + ["2015-1-1", "%G-%V-%u", datetime(2014, 12, 29, 0, 0)], + ["2015-1-4", "%G-%V-%u", datetime(2015, 1, 1, 0, 0)], + ["2015-1-7", "%G-%V-%u", datetime(2015, 1, 4, 0, 0)], + ], + ) + def test_to_datetime_iso_week_year_format(self, s, _format, dt): + # See GH#16607 + assert to_datetime(s, format=_format) == dt + + @pytest.mark.parametrize( + "msg, s, _format", + [ + [ + "ISO week directive '%V' is incompatible with the year directive " + "'%Y'. Use the ISO year '%G' instead.", + "1999 50", + "%Y %V", + ], + [ + "ISO year directive '%G' must be used with the ISO week directive " + "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 51", + "%G %V", + ], + [ + "ISO year directive '%G' must be used with the ISO week directive " + "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 Monday", + "%G %A", + ], + [ + "ISO year directive '%G' must be used with the ISO week directive " + "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 Mon", + "%G %a", + ], + [ + "ISO year directive '%G' must be used with the ISO week directive " + "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 6", + "%G %w", + ], + [ + "ISO year directive '%G' must be used with the ISO week directive " + "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 6", + "%G %u", + ], + [ + "ISO year directive '%G' must be used with the ISO week directive " + "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", + "2051", + "%G", + ], + [ + "Day of the year directive '%j' is not compatible with ISO year " + "directive '%G'. Use '%Y' instead.", + "1999 51 6 256", + "%G %V %u %j", + ], + [ + "ISO week directive '%V' is incompatible with the year directive " + "'%Y'. Use the ISO year '%G' instead.", + "1999 51 Sunday", + "%Y %V %A", + ], + [ + "ISO week directive '%V' is incompatible with the year directive " + "'%Y'. Use the ISO year '%G' instead.", + "1999 51 Sun", + "%Y %V %a", + ], + [ + "ISO week directive '%V' is incompatible with the year directive " + "'%Y'. Use the ISO year '%G' instead.", + "1999 51 1", + "%Y %V %w", + ], + [ + "ISO week directive '%V' is incompatible with the year directive " + "'%Y'. Use the ISO year '%G' instead.", + "1999 51 1", + "%Y %V %u", + ], + [ + "ISO week directive '%V' must be used with the ISO year directive " + "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", + "20", + "%V", + ], + [ + "ISO week directive '%V' must be used with the ISO year directive " + "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 51 Sunday", + "%V %A", + ], + [ + "ISO week directive '%V' must be used with the ISO year directive " + "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 51 Sun", + "%V %a", + ], + [ + "ISO week directive '%V' must be used with the ISO year directive " + "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 51 1", + "%V %w", + ], + [ + "ISO week directive '%V' must be used with the ISO year directive " + "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", + "1999 51 1", + "%V %u", + ], + [ + "Day of the year directive '%j' is not compatible with ISO year " + "directive '%G'. Use '%Y' instead.", + "1999 50", + "%G %j", + ], + [ + "ISO week directive '%V' must be used with the ISO year directive " + "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", + "20 Monday", + "%V %A", + ], + ], + ) + @pytest.mark.parametrize("errors", ["raise", "coerce", "ignore"]) + def test_error_iso_week_year(self, msg, s, _format, errors): + # See GH#16607, GH#50308 + # This test checks for errors thrown when giving the wrong format + # However, as discussed on PR#25541, overriding the locale + # causes a different error to be thrown due to the format being + # locale specific, but the test data is in english. + # Therefore, the tests only run when locale is not overwritten, + # as a sort of solution to this problem. + if locale.getlocale() != ("zh_CN", "UTF-8") and locale.getlocale() != ( + "it_IT", + "UTF-8", + ): + with pytest.raises(ValueError, match=msg): + to_datetime(s, format=_format, errors=errors) + + @pytest.mark.parametrize("tz", [None, "US/Central"]) + def test_to_datetime_dtarr(self, tz): + # DatetimeArray + dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz) + arr = dti._data + + result = to_datetime(arr) + assert result is arr + + # Doesn't work on Windows since tzpath not set correctly + @td.skip_if_windows + @pytest.mark.parametrize("arg_class", [Series, Index]) + @pytest.mark.parametrize("utc", [True, False]) + @pytest.mark.parametrize("tz", [None, "US/Central"]) + def test_to_datetime_arrow(self, tz, utc, arg_class): + pa = pytest.importorskip("pyarrow") + + dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz) + dti = arg_class(dti) + + dti_arrow = dti.astype(pd.ArrowDtype(pa.timestamp(unit="ns", tz=tz))) + + result = to_datetime(dti_arrow, utc=utc) + expected = to_datetime(dti, utc=utc).astype( + pd.ArrowDtype(pa.timestamp(unit="ns", tz=tz if not utc else "UTC")) + ) + if not utc and arg_class is not Series: + # Doesn't hold for utc=True, since that will astype + # to_datetime also returns a new object for series + assert result is dti_arrow + if arg_class is Series: + tm.assert_series_equal(result, expected) + else: + tm.assert_index_equal(result, expected) + + def test_to_datetime_pydatetime(self): + actual = to_datetime(datetime(2008, 1, 15)) + assert actual == datetime(2008, 1, 15) + + def test_to_datetime_YYYYMMDD(self): + actual = to_datetime("20080115") + assert actual == datetime(2008, 1, 15) + + def test_to_datetime_unparsable_ignore(self): + # unparsable + ser = "Month 1, 1999" + assert to_datetime(ser, errors="ignore") == ser + + @td.skip_if_windows # `tm.set_timezone` does not work in windows + def test_to_datetime_now(self): + # See GH#18666 + with tm.set_timezone("US/Eastern"): + # GH#18705 + now = Timestamp("now").as_unit("ns") + pdnow = to_datetime("now") + pdnow2 = to_datetime(["now"])[0] + + # These should all be equal with infinite perf; this gives + # a generous margin of 10 seconds + assert abs(pdnow._value - now._value) < 1e10 + assert abs(pdnow2._value - now._value) < 1e10 + + assert pdnow.tzinfo is None + assert pdnow2.tzinfo is None + + @td.skip_if_windows # `tm.set_timezone` does not work in windows + @pytest.mark.parametrize("tz", ["Pacific/Auckland", "US/Samoa"]) + def test_to_datetime_today(self, tz): + # See GH#18666 + # Test with one timezone far ahead of UTC and another far behind, so + # one of these will _almost_ always be in a different day from UTC. + # Unfortunately this test between 12 and 1 AM Samoa time + # this both of these timezones _and_ UTC will all be in the same day, + # so this test will not detect the regression introduced in #18666. + with tm.set_timezone(tz): + nptoday = np.datetime64("today").astype("datetime64[ns]").astype(np.int64) + pdtoday = to_datetime("today") + pdtoday2 = to_datetime(["today"])[0] + + tstoday = Timestamp("today").as_unit("ns") + tstoday2 = Timestamp.today().as_unit("ns") + + # These should all be equal with infinite perf; this gives + # a generous margin of 10 seconds + assert abs(pdtoday.normalize()._value - nptoday) < 1e10 + assert abs(pdtoday2.normalize()._value - nptoday) < 1e10 + assert abs(pdtoday._value - tstoday._value) < 1e10 + assert abs(pdtoday._value - tstoday2._value) < 1e10 + + assert pdtoday.tzinfo is None + assert pdtoday2.tzinfo is None + + @pytest.mark.parametrize("arg", ["now", "today"]) + def test_to_datetime_today_now_unicode_bytes(self, arg): + to_datetime([arg]) + + @pytest.mark.parametrize( + "format, expected_ds", + [ + ("%Y-%m-%d %H:%M:%S%z", "2020-01-03"), + ("%Y-%d-%m %H:%M:%S%z", "2020-03-01"), + (None, "2020-01-03"), + ], + ) + @pytest.mark.parametrize( + "string, attribute", + [ + ("now", "utcnow"), + ("today", "today"), + ], + ) + def test_to_datetime_now_with_format(self, format, expected_ds, string, attribute): + # https://github.com/pandas-dev/pandas/issues/50359 + result = to_datetime(["2020-01-03 00:00:00Z", string], format=format, utc=True) + expected = DatetimeIndex( + [expected_ds, getattr(Timestamp, attribute)()], dtype="datetime64[ns, UTC]" + ) + assert (expected - result).max().total_seconds() < 1 + + @pytest.mark.parametrize( + "dt", [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")] + ) + def test_to_datetime_dt64s(self, cache, dt): + assert to_datetime(dt, cache=cache) == Timestamp(dt) + + @pytest.mark.parametrize( + "arg, format", + [ + ("2001-01-01", "%Y-%m-%d"), + ("01-01-2001", "%d-%m-%Y"), + ], + ) + def test_to_datetime_dt64s_and_str(self, arg, format): + # https://github.com/pandas-dev/pandas/issues/50036 + result = to_datetime([arg, np.datetime64("2020-01-01")], format=format) + expected = DatetimeIndex(["2001-01-01", "2020-01-01"]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "dt", [np.datetime64("1000-01-01"), np.datetime64("5000-01-02")] + ) + @pytest.mark.parametrize("errors", ["raise", "ignore", "coerce"]) + def test_to_datetime_dt64s_out_of_ns_bounds(self, cache, dt, errors): + # GH#50369 We cast to the nearest supported reso, i.e. "s" + ts = to_datetime(dt, errors=errors, cache=cache) + assert isinstance(ts, Timestamp) + assert ts.unit == "s" + assert ts.asm8 == dt + + ts = Timestamp(dt) + assert ts.unit == "s" + assert ts.asm8 == dt + + @pytest.mark.skip_ubsan + def test_to_datetime_dt64d_out_of_bounds(self, cache): + dt64 = np.datetime64(np.iinfo(np.int64).max, "D") + + msg = "Out of bounds second timestamp: 25252734927768524-07-27" + with pytest.raises(OutOfBoundsDatetime, match=msg): + Timestamp(dt64) + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(dt64, errors="raise", cache=cache) + + assert to_datetime(dt64, errors="coerce", cache=cache) is NaT + + @pytest.mark.parametrize("unit", ["s", "D"]) + def test_to_datetime_array_of_dt64s(self, cache, unit): + # https://github.com/pandas-dev/pandas/issues/31491 + # Need at least 50 to ensure cache is used. + dts = [ + np.datetime64("2000-01-01", unit), + np.datetime64("2000-01-02", unit), + ] * 30 + # Assuming all datetimes are in bounds, to_datetime() returns + # an array that is equal to Timestamp() parsing + result = to_datetime(dts, cache=cache) + if cache: + # FIXME: behavior should not depend on cache + expected = DatetimeIndex([Timestamp(x).asm8 for x in dts], dtype="M8[s]") + else: + expected = DatetimeIndex([Timestamp(x).asm8 for x in dts], dtype="M8[ns]") + + tm.assert_index_equal(result, expected) + + # A list of datetimes where the last one is out of bounds + dts_with_oob = dts + [np.datetime64("9999-01-01")] + + # As of GH#51978 we do not raise in this case + to_datetime(dts_with_oob, errors="raise") + + result = to_datetime(dts_with_oob, errors="coerce", cache=cache) + if not cache: + # FIXME: shouldn't depend on cache! + expected = DatetimeIndex( + [Timestamp(dts_with_oob[0]).asm8, Timestamp(dts_with_oob[1]).asm8] * 30 + + [NaT], + ) + else: + expected = DatetimeIndex(np.array(dts_with_oob, dtype="M8[s]")) + tm.assert_index_equal(result, expected) + + # With errors='ignore', out of bounds datetime64s + # are converted to their .item(), which depending on the version of + # numpy is either a python datetime.datetime or datetime.date + result = to_datetime(dts_with_oob, errors="ignore", cache=cache) + if not cache: + # FIXME: shouldn't depend on cache! + expected = Index(dts_with_oob) + tm.assert_index_equal(result, expected) + + def test_out_of_bounds_errors_ignore(self): + # https://github.com/pandas-dev/pandas/issues/50587 + result = to_datetime(np.datetime64("9999-01-01"), errors="ignore") + expected = np.datetime64("9999-01-01") + assert result == expected + + def test_out_of_bounds_errors_ignore2(self): + # GH#12424 + msg = "errors='ignore' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = to_datetime(Series(["2362-01-01", np.nan]), errors="ignore") + exp = Series(["2362-01-01", np.nan]) + tm.assert_series_equal(res, exp) + + def test_to_datetime_tz(self, cache): + # xref 8260 + # uniform returns a DatetimeIndex + arr = [ + Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), + Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), + ] + result = to_datetime(arr, cache=cache) + expected = DatetimeIndex( + ["2013-01-01 13:00:00", "2013-01-02 14:00:00"], tz="US/Pacific" + ) + tm.assert_index_equal(result, expected) + + def test_to_datetime_tz_mixed(self, cache): + # mixed tzs will raise if errors='raise' + # https://github.com/pandas-dev/pandas/issues/50585 + arr = [ + Timestamp("2013-01-01 13:00:00", tz="US/Pacific"), + Timestamp("2013-01-02 14:00:00", tz="US/Eastern"), + ] + msg = ( + "Tz-aware datetime.datetime cannot be " + "converted to datetime64 unless utc=True" + ) + with pytest.raises(ValueError, match=msg): + to_datetime(arr, cache=cache) + + depr_msg = "errors='ignore' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = to_datetime(arr, cache=cache, errors="ignore") + expected = Index( + [ + Timestamp("2013-01-01 13:00:00-08:00"), + Timestamp("2013-01-02 14:00:00-05:00"), + ], + dtype="object", + ) + tm.assert_index_equal(result, expected) + result = to_datetime(arr, cache=cache, errors="coerce") + expected = DatetimeIndex( + ["2013-01-01 13:00:00-08:00", "NaT"], dtype="datetime64[ns, US/Pacific]" + ) + tm.assert_index_equal(result, expected) + + def test_to_datetime_different_offsets(self, cache): + # inspired by asv timeseries.ToDatetimeNONISO8601 benchmark + # see GH-26097 for more + ts_string_1 = "March 1, 2018 12:00:00+0400" + ts_string_2 = "March 1, 2018 12:00:00+0500" + arr = [ts_string_1] * 5 + [ts_string_2] * 5 + expected = Index([parse(x) for x in arr]) + msg = "parsing datetimes with mixed time zones will raise an error" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = to_datetime(arr, cache=cache) + tm.assert_index_equal(result, expected) + + def test_to_datetime_tz_pytz(self, cache): + # see gh-8260 + us_eastern = pytz.timezone("US/Eastern") + arr = np.array( + [ + us_eastern.localize( + datetime(year=2000, month=1, day=1, hour=3, minute=0) + ), + us_eastern.localize( + datetime(year=2000, month=6, day=1, hour=3, minute=0) + ), + ], + dtype=object, + ) + result = to_datetime(arr, utc=True, cache=cache) + expected = DatetimeIndex( + ["2000-01-01 08:00:00+00:00", "2000-06-01 07:00:00+00:00"], + dtype="datetime64[ns, UTC]", + freq=None, + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "init_constructor, end_constructor", + [ + (Index, DatetimeIndex), + (list, DatetimeIndex), + (np.array, DatetimeIndex), + (Series, Series), + ], + ) + def test_to_datetime_utc_true(self, cache, init_constructor, end_constructor): + # See gh-11934 & gh-6415 + data = ["20100102 121314", "20100102 121315"] + expected_data = [ + Timestamp("2010-01-02 12:13:14", tz="utc"), + Timestamp("2010-01-02 12:13:15", tz="utc"), + ] + + result = to_datetime( + init_constructor(data), format="%Y%m%d %H%M%S", utc=True, cache=cache + ) + expected = end_constructor(expected_data) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "scalar, expected", + [ + ["20100102 121314", Timestamp("2010-01-02 12:13:14", tz="utc")], + ["20100102 121315", Timestamp("2010-01-02 12:13:15", tz="utc")], + ], + ) + def test_to_datetime_utc_true_scalar(self, cache, scalar, expected): + # Test scalar case as well + result = to_datetime(scalar, format="%Y%m%d %H%M%S", utc=True, cache=cache) + assert result == expected + + def test_to_datetime_utc_true_with_series_single_value(self, cache): + # GH 15760 UTC=True with Series + ts = 1.5e18 + result = to_datetime(Series([ts]), utc=True, cache=cache) + expected = Series([Timestamp(ts, tz="utc")]) + tm.assert_series_equal(result, expected) + + def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): + ts = "2013-01-01 00:00:00-01:00" + expected_ts = "2013-01-01 01:00:00" + data = Series([ts] * 3) + result = to_datetime(data, utc=True, cache=cache) + expected = Series([Timestamp(expected_ts, tz="utc")] * 3) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "date, dtype", + [ + ("2013-01-01 01:00:00", "datetime64[ns]"), + ("2013-01-01 01:00:00", "datetime64[ns, UTC]"), + ], + ) + def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): + expected = Series( + [Timestamp("2013-01-01 01:00:00", tz="UTC")], dtype="M8[ns, UTC]" + ) + result = to_datetime(Series([date], dtype=dtype), utc=True, cache=cache) + tm.assert_series_equal(result, expected) + + def test_to_datetime_tz_psycopg2(self, request, cache): + # xref 8260 + psycopg2_tz = pytest.importorskip("psycopg2.tz") + + # misc cases + tz1 = psycopg2_tz.FixedOffsetTimezone(offset=-300, name=None) + tz2 = psycopg2_tz.FixedOffsetTimezone(offset=-240, name=None) + arr = np.array( + [ + datetime(2000, 1, 1, 3, 0, tzinfo=tz1), + datetime(2000, 6, 1, 3, 0, tzinfo=tz2), + ], + dtype=object, + ) + + result = to_datetime(arr, errors="coerce", utc=True, cache=cache) + expected = DatetimeIndex( + ["2000-01-01 08:00:00+00:00", "2000-06-01 07:00:00+00:00"], + dtype="datetime64[ns, UTC]", + freq=None, + ) + tm.assert_index_equal(result, expected) + + # dtype coercion + i = DatetimeIndex( + ["2000-01-01 08:00:00"], + tz=psycopg2_tz.FixedOffsetTimezone(offset=-300, name=None), + ) + assert is_datetime64_ns_dtype(i) + + # tz coercion + result = to_datetime(i, errors="coerce", cache=cache) + tm.assert_index_equal(result, i) + + result = to_datetime(i, errors="coerce", utc=True, cache=cache) + expected = DatetimeIndex(["2000-01-01 13:00:00"], dtype="datetime64[ns, UTC]") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("arg", [True, False]) + def test_datetime_bool(self, cache, arg): + # GH13176 + msg = r"dtype bool cannot be converted to datetime64\[ns\]" + with pytest.raises(TypeError, match=msg): + to_datetime(arg) + assert to_datetime(arg, errors="coerce", cache=cache) is NaT + assert to_datetime(arg, errors="ignore", cache=cache) is arg + + def test_datetime_bool_arrays_mixed(self, cache): + msg = f"{type(cache)} is not convertible to datetime" + with pytest.raises(TypeError, match=msg): + to_datetime([False, datetime.today()], cache=cache) + with pytest.raises( + ValueError, + match=( + r'^time data "True" doesn\'t match format "%Y%m%d", ' + f"at position 1. {PARSING_ERR_MSG}$" + ), + ): + to_datetime(["20130101", True], cache=cache) + tm.assert_index_equal( + to_datetime([0, False, NaT, 0.0], errors="coerce", cache=cache), + DatetimeIndex( + [to_datetime(0, cache=cache), NaT, NaT, to_datetime(0, cache=cache)] + ), + ) + + @pytest.mark.parametrize("arg", [bool, to_datetime]) + def test_datetime_invalid_datatype(self, arg): + # GH13176 + msg = "is not convertible to datetime" + with pytest.raises(TypeError, match=msg): + to_datetime(arg) + + @pytest.mark.parametrize("errors", ["coerce", "raise", "ignore"]) + def test_invalid_format_raises(self, errors): + # https://github.com/pandas-dev/pandas/issues/50255 + with pytest.raises( + ValueError, match="':' is a bad directive in format 'H%:M%:S%" + ): + to_datetime(["00:00:00"], format="H%:M%:S%", errors=errors) + + @pytest.mark.parametrize("value", ["a", "00:01:99"]) + @pytest.mark.parametrize("format", [None, "%H:%M:%S"]) + def test_datetime_invalid_scalar(self, value, format): + # GH24763 + res = to_datetime(value, errors="ignore", format=format) + assert res == value + + res = to_datetime(value, errors="coerce", format=format) + assert res is NaT + + msg = "|".join( + [ + r'^time data "a" doesn\'t match format "%H:%M:%S", at position 0. ' + f"{PARSING_ERR_MSG}$", + r'^Given date string "a" not likely a datetime, at position 0$', + r'^unconverted data remains when parsing with format "%H:%M:%S": "9", ' + f"at position 0. {PARSING_ERR_MSG}$", + rf"^second must be in 0..59{NOT_99}: 00:01:99, at position 0$", + ] + ) + with pytest.raises(ValueError, match=msg): + to_datetime(value, errors="raise", format=format) + + @pytest.mark.parametrize("value", ["3000/12/11 00:00:00"]) + @pytest.mark.parametrize("format", [None, "%H:%M:%S"]) + def test_datetime_outofbounds_scalar(self, value, format): + # GH24763 + res = to_datetime(value, errors="ignore", format=format) + assert res == value + + res = to_datetime(value, errors="coerce", format=format) + assert res is NaT + + if format is not None: + msg = r'^time data ".*" doesn\'t match format ".*", at position 0.' + with pytest.raises(ValueError, match=msg): + to_datetime(value, errors="raise", format=format) + else: + msg = "^Out of bounds .*, at position 0$" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(value, errors="raise", format=format) + + @pytest.mark.parametrize( + ("values"), [(["a"]), (["00:01:99"]), (["a", "b", "99:00:00"])] + ) + @pytest.mark.parametrize("format", [(None), ("%H:%M:%S")]) + def test_datetime_invalid_index(self, values, format): + # GH24763 + # Not great to have logic in tests, but this one's hard to + # parametrise over + if format is None and len(values) > 1: + warn = UserWarning + else: + warn = None + with tm.assert_produces_warning( + warn, match="Could not infer format", raise_on_extra_warnings=False + ): + res = to_datetime(values, errors="ignore", format=format) + tm.assert_index_equal( + res, Index(values, dtype="object" if format is None else "str") + ) + + with tm.assert_produces_warning( + warn, match="Could not infer format", raise_on_extra_warnings=False + ): + res = to_datetime(values, errors="coerce", format=format) + tm.assert_index_equal(res, DatetimeIndex([NaT] * len(values))) + + msg = "|".join( + [ + r'^Given date string "a" not likely a datetime, at position 0$', + r'^time data "a" doesn\'t match format "%H:%M:%S", at position 0. ' + f"{PARSING_ERR_MSG}$", + r'^unconverted data remains when parsing with format "%H:%M:%S": "9", ' + f"at position 0. {PARSING_ERR_MSG}$", + rf"^second must be in 0..59{NOT_99}: 00:01:99, at position 0$", + ] + ) + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning( + warn, match="Could not infer format", raise_on_extra_warnings=False + ): + to_datetime(values, errors="raise", format=format) + + @pytest.mark.parametrize("utc", [True, None]) + @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) + @pytest.mark.parametrize("constructor", [list, tuple, np.array, Index, deque]) + def test_to_datetime_cache(self, utc, format, constructor): + date = "20130101 00:00:00" + test_dates = [date] * 10**5 + data = constructor(test_dates) + + result = to_datetime(data, utc=utc, format=format, cache=True) + expected = to_datetime(data, utc=utc, format=format, cache=False) + + tm.assert_index_equal(result, expected) + + def test_to_datetime_from_deque(self): + # GH 29403 + result = to_datetime(deque([Timestamp("2010-06-02 09:30:00")] * 51)) + expected = to_datetime([Timestamp("2010-06-02 09:30:00")] * 51) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("utc", [True, None]) + @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) + def test_to_datetime_cache_series(self, utc, format): + date = "20130101 00:00:00" + test_dates = [date] * 10**5 + data = Series(test_dates) + result = to_datetime(data, utc=utc, format=format, cache=True) + expected = to_datetime(data, utc=utc, format=format, cache=False) + tm.assert_series_equal(result, expected) + + def test_to_datetime_cache_scalar(self): + date = "20130101 00:00:00" + result = to_datetime(date, cache=True) + expected = Timestamp("20130101 00:00:00") + assert result == expected + + @pytest.mark.parametrize( + "datetimelikes,expected_values", + ( + ( + (None, np.nan) + (NaT,) * start_caching_at, + (NaT,) * (start_caching_at + 2), + ), + ( + (None, Timestamp("2012-07-26")) + (NaT,) * start_caching_at, + (NaT, Timestamp("2012-07-26")) + (NaT,) * start_caching_at, + ), + ( + (None,) + + (NaT,) * start_caching_at + + ("2012 July 26", Timestamp("2012-07-26")), + (NaT,) * (start_caching_at + 1) + + (Timestamp("2012-07-26"), Timestamp("2012-07-26")), + ), + ), + ) + def test_convert_object_to_datetime_with_cache( + self, datetimelikes, expected_values + ): + # GH#39882 + ser = Series( + datetimelikes, + dtype="object", + ) + result_series = to_datetime(ser, errors="coerce") + expected_series = Series( + expected_values, + dtype="datetime64[ns]", + ) + tm.assert_series_equal(result_series, expected_series) + + @pytest.mark.parametrize("cache", [True, False]) + @pytest.mark.parametrize( + "input", + [ + Series([NaT] * 20 + [None] * 20, dtype="object"), + Series([NaT] * 60 + [None] * 60, dtype="object"), + Series([None] * 20), + Series([None] * 60), + Series([""] * 20), + Series([""] * 60), + Series([pd.NA] * 20), + Series([pd.NA] * 60), + Series([np.nan] * 20), + Series([np.nan] * 60), + ], + ) + def test_to_datetime_converts_null_like_to_nat(self, cache, input): + # GH35888 + expected = Series([NaT] * len(input), dtype="M8[ns]") + result = to_datetime(input, cache=cache) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "date, format", + [ + ("2017-20", "%Y-%W"), + ("20 Sunday", "%W %A"), + ("20 Sun", "%W %a"), + ("2017-21", "%Y-%U"), + ("20 Sunday", "%U %A"), + ("20 Sun", "%U %a"), + ], + ) + def test_week_without_day_and_calendar_year(self, date, format): + # GH16774 + + msg = "Cannot use '%W' or '%U' without day and year" + with pytest.raises(ValueError, match=msg): + to_datetime(date, format=format) + + def test_to_datetime_coerce(self): + # GH 26122 + ts_strings = [ + "March 1, 2018 12:00:00+0400", + "March 1, 2018 12:00:00+0500", + "20100240", + ] + msg = "parsing datetimes with mixed time zones will raise an error" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = to_datetime(ts_strings, errors="coerce") + expected = Index( + [ + datetime(2018, 3, 1, 12, 0, tzinfo=tzoffset(None, 14400)), + datetime(2018, 3, 1, 12, 0, tzinfo=tzoffset(None, 18000)), + NaT, + ] + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "string_arg, format", + [("March 1, 2018", "%B %d, %Y"), ("2018-03-01", "%Y-%m-%d")], + ) + @pytest.mark.parametrize( + "outofbounds", + [ + datetime(9999, 1, 1), + date(9999, 1, 1), + np.datetime64("9999-01-01"), + "January 1, 9999", + "9999-01-01", + ], + ) + def test_to_datetime_coerce_oob(self, string_arg, format, outofbounds): + # https://github.com/pandas-dev/pandas/issues/50255 + ts_strings = [string_arg, outofbounds] + result = to_datetime(ts_strings, errors="coerce", format=format) + expected = DatetimeIndex([datetime(2018, 3, 1), NaT]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "errors, expected", + [ + ("coerce", Index([NaT, NaT])), + ("ignore", Index(["200622-12-31", "111111-24-11"], dtype=object)), + ], + ) + def test_to_datetime_malformed_no_raise(self, errors, expected): + # GH 28299 + # GH 48633 + ts_strings = ["200622-12-31", "111111-24-11"] + with tm.assert_produces_warning( + UserWarning, match="Could not infer format", raise_on_extra_warnings=False + ): + result = to_datetime(ts_strings, errors=errors) + tm.assert_index_equal(result, expected) + + def test_to_datetime_malformed_raise(self): + # GH 48633 + ts_strings = ["200622-12-31", "111111-24-11"] + msg = ( + 'Parsed string "200622-12-31" gives an invalid tzoffset, which must ' + r"be between -timedelta\(hours=24\) and timedelta\(hours=24\), " + "at position 0" + ) + with pytest.raises( + ValueError, + match=msg, + ): + with tm.assert_produces_warning( + UserWarning, match="Could not infer format" + ): + to_datetime( + ts_strings, + errors="raise", + ) + + def test_iso_8601_strings_with_same_offset(self): + # GH 17697, 11736 + ts_str = "2015-11-18 15:30:00+05:30" + result = to_datetime(ts_str) + expected = Timestamp(ts_str) + assert result == expected + + expected = DatetimeIndex([Timestamp(ts_str)] * 2) + result = to_datetime([ts_str] * 2) + tm.assert_index_equal(result, expected) + + result = DatetimeIndex([ts_str] * 2) + tm.assert_index_equal(result, expected) + + def test_iso_8601_strings_with_different_offsets(self): + # GH 17697, 11736, 50887 + ts_strings = ["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30", NaT] + msg = "parsing datetimes with mixed time zones will raise an error" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = to_datetime(ts_strings) + expected = np.array( + [ + datetime(2015, 11, 18, 15, 30, tzinfo=tzoffset(None, 19800)), + datetime(2015, 11, 18, 16, 30, tzinfo=tzoffset(None, 23400)), + NaT, + ], + dtype=object, + ) + # GH 21864 + expected = Index(expected) + tm.assert_index_equal(result, expected) + + def test_iso_8601_strings_with_different_offsets_utc(self): + ts_strings = ["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30", NaT] + result = to_datetime(ts_strings, utc=True) + expected = DatetimeIndex( + [Timestamp(2015, 11, 18, 10), Timestamp(2015, 11, 18, 10), NaT], tz="UTC" + ) + tm.assert_index_equal(result, expected) + + def test_mixed_offsets_with_native_datetime_raises(self): + # GH 25978 + + vals = [ + "nan", + Timestamp("1990-01-01"), + "2015-03-14T16:15:14.123-08:00", + "2019-03-04T21:56:32.620-07:00", + None, + "today", + "now", + ] + ser = Series(vals) + assert all(ser[i] is vals[i] for i in range(len(vals))) # GH#40111 + + now = Timestamp("now") + today = Timestamp("today") + msg = "parsing datetimes with mixed time zones will raise an error" + with tm.assert_produces_warning(FutureWarning, match=msg): + mixed = to_datetime(ser) + expected = Series( + [ + "NaT", + Timestamp("1990-01-01"), + Timestamp("2015-03-14T16:15:14.123-08:00").to_pydatetime(), + Timestamp("2019-03-04T21:56:32.620-07:00").to_pydatetime(), + None, + ], + dtype=object, + ) + tm.assert_series_equal(mixed[:-2], expected) + # we'll check mixed[-1] and mixed[-2] match now and today to within + # call-timing tolerances + assert (now - mixed.iloc[-1]).total_seconds() <= 0.1 + assert (today - mixed.iloc[-2]).total_seconds() <= 0.1 + + with pytest.raises(ValueError, match="Tz-aware datetime.datetime"): + to_datetime(mixed) + + def test_non_iso_strings_with_tz_offset(self): + result = to_datetime(["March 1, 2018 12:00:00+0400"] * 2) + expected = DatetimeIndex( + [datetime(2018, 3, 1, 12, tzinfo=timezone(timedelta(minutes=240)))] * 2 + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "ts, expected", + [ + (Timestamp("2018-01-01"), Timestamp("2018-01-01", tz="UTC")), + ( + Timestamp("2018-01-01", tz="US/Pacific"), + Timestamp("2018-01-01 08:00", tz="UTC"), + ), + ], + ) + def test_timestamp_utc_true(self, ts, expected): + # GH 24415 + result = to_datetime(ts, utc=True) + assert result == expected + + @pytest.mark.parametrize("dt_str", ["00010101", "13000101", "30000101", "99990101"]) + def test_to_datetime_with_format_out_of_bounds(self, dt_str): + # GH 9107 + msg = "Out of bounds nanosecond timestamp" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(dt_str, format="%Y%m%d") + + def test_to_datetime_utc(self): + arr = np.array([parse("2012-06-13T01:39:00Z")], dtype=object) + + result = to_datetime(arr, utc=True) + assert result.tz is timezone.utc + + def test_to_datetime_fixed_offset(self): + from pandas.tests.indexes.datetimes.test_timezones import FixedOffset + + fixed_off = FixedOffset(-420, "-07:00") + + dates = [ + datetime(2000, 1, 1, tzinfo=fixed_off), + datetime(2000, 1, 2, tzinfo=fixed_off), + datetime(2000, 1, 3, tzinfo=fixed_off), + ] + result = to_datetime(dates) + assert result.tz == fixed_off + + @pytest.mark.parametrize( + "date", + [ + ["2020-10-26 00:00:00+06:00", "2020-10-26 00:00:00+01:00"], + ["2020-10-26 00:00:00+06:00", Timestamp("2018-01-01", tz="US/Pacific")], + [ + "2020-10-26 00:00:00+06:00", + datetime(2020, 1, 1, 18, tzinfo=pytz.timezone("Australia/Melbourne")), + ], + ], + ) + def test_to_datetime_mixed_offsets_with_utc_false_deprecated(self, date): + # GH 50887 + msg = "parsing datetimes with mixed time zones will raise an error" + with tm.assert_produces_warning(FutureWarning, match=msg): + to_datetime(date, utc=False) + + +class TestToDatetimeUnit: + @pytest.mark.parametrize("unit", ["Y", "M"]) + @pytest.mark.parametrize("item", [150, float(150)]) + def test_to_datetime_month_or_year_unit_int(self, cache, unit, item, request): + # GH#50870 Note we have separate tests that pd.Timestamp gets these right + ts = Timestamp(item, unit=unit) + expected = DatetimeIndex([ts], dtype="M8[ns]") + + result = to_datetime([item], unit=unit, cache=cache) + tm.assert_index_equal(result, expected) + + result = to_datetime(np.array([item], dtype=object), unit=unit, cache=cache) + tm.assert_index_equal(result, expected) + + result = to_datetime(np.array([item]), unit=unit, cache=cache) + tm.assert_index_equal(result, expected) + + # with a nan! + result = to_datetime(np.array([item, np.nan]), unit=unit, cache=cache) + assert result.isna()[1] + tm.assert_index_equal(result[:1], expected) + + @pytest.mark.parametrize("unit", ["Y", "M"]) + def test_to_datetime_month_or_year_unit_non_round_float(self, cache, unit): + # GH#50301 + # Match Timestamp behavior in disallowing non-round floats with + # Y or M unit + warn_msg = "strings will be parsed as datetime strings" + msg = f"Conversion of non-round float with unit={unit} is ambiguous" + with pytest.raises(ValueError, match=msg): + to_datetime([1.5], unit=unit, errors="raise") + with pytest.raises(ValueError, match=msg): + to_datetime(np.array([1.5]), unit=unit, errors="raise") + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + to_datetime(["1.5"], unit=unit, errors="raise") + + # with errors="ignore" we also end up raising within the Timestamp + # constructor; this may not be ideal + with pytest.raises(ValueError, match=msg): + to_datetime([1.5], unit=unit, errors="ignore") + + res = to_datetime([1.5], unit=unit, errors="coerce") + expected = Index([NaT], dtype="M8[ns]") + tm.assert_index_equal(res, expected) + + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + res = to_datetime(["1.5"], unit=unit, errors="coerce") + tm.assert_index_equal(res, expected) + + # round floats are OK + res = to_datetime([1.0], unit=unit) + expected = to_datetime([1], unit=unit) + tm.assert_index_equal(res, expected) + + def test_unit(self, cache): + # GH 11758 + # test proper behavior with errors + msg = "cannot specify both format and unit" + with pytest.raises(ValueError, match=msg): + to_datetime([1], unit="D", format="%Y%m%d", cache=cache) + + def test_unit_str(self, cache): + # GH 57051 + # Test that strs aren't dropping precision to 32-bit accidentally. + with tm.assert_produces_warning(FutureWarning): + res = to_datetime(["1704660000"], unit="s", origin="unix") + expected = to_datetime([1704660000], unit="s", origin="unix") + tm.assert_index_equal(res, expected) + + def test_unit_array_mixed_nans(self, cache): + values = [11111111111111111, 1, 1.0, iNaT, NaT, np.nan, "NaT", ""] + result = to_datetime(values, unit="D", errors="ignore", cache=cache) + expected = Index( + [ + 11111111111111111, + Timestamp("1970-01-02"), + Timestamp("1970-01-02"), + NaT, + NaT, + NaT, + NaT, + NaT, + ], + dtype=object, + ) + tm.assert_index_equal(result, expected) + + result = to_datetime(values, unit="D", errors="coerce", cache=cache) + expected = DatetimeIndex( + ["NaT", "1970-01-02", "1970-01-02", "NaT", "NaT", "NaT", "NaT", "NaT"], + dtype="M8[ns]", + ) + tm.assert_index_equal(result, expected) + + msg = "cannot convert input 11111111111111111 with the unit 'D'" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(values, unit="D", errors="raise", cache=cache) + + def test_unit_array_mixed_nans_large_int(self, cache): + values = [1420043460000000000000000, iNaT, NaT, np.nan, "NaT"] + + result = to_datetime(values, errors="ignore", unit="s", cache=cache) + expected = Index([1420043460000000000000000, NaT, NaT, NaT, NaT], dtype=object) + tm.assert_index_equal(result, expected) + + result = to_datetime(values, errors="coerce", unit="s", cache=cache) + expected = DatetimeIndex(["NaT", "NaT", "NaT", "NaT", "NaT"], dtype="M8[ns]") + tm.assert_index_equal(result, expected) + + msg = "cannot convert input 1420043460000000000000000 with the unit 's'" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(values, errors="raise", unit="s", cache=cache) + + def test_to_datetime_invalid_str_not_out_of_bounds_valuerror(self, cache): + # if we have a string, then we raise a ValueError + # and NOT an OutOfBoundsDatetime + msg = "non convertible value foo with the unit 's'" + with pytest.raises(ValueError, match=msg): + to_datetime("foo", errors="raise", unit="s", cache=cache) + + @pytest.mark.parametrize("error", ["raise", "coerce", "ignore"]) + def test_unit_consistency(self, cache, error): + # consistency of conversions + expected = Timestamp("1970-05-09 14:25:11") + result = to_datetime(11111111, unit="s", errors=error, cache=cache) + assert result == expected + assert isinstance(result, Timestamp) + + @pytest.mark.parametrize("errors", ["ignore", "raise", "coerce"]) + @pytest.mark.parametrize("dtype", ["float64", "int64"]) + def test_unit_with_numeric(self, cache, errors, dtype): + # GH 13180 + # coercions from floats/ints are ok + expected = DatetimeIndex( + ["2015-06-19 05:33:20", "2015-05-27 22:33:20"], dtype="M8[ns]" + ) + arr = np.array([1.434692e18, 1.432766e18]).astype(dtype) + result = to_datetime(arr, errors=errors, cache=cache) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "exp, arr, warning", + [ + [ + ["NaT", "2015-06-19 05:33:20", "2015-05-27 22:33:20"], + ["foo", 1.434692e18, 1.432766e18], + UserWarning, + ], + [ + ["2015-06-19 05:33:20", "2015-05-27 22:33:20", "NaT", "NaT"], + [1.434692e18, 1.432766e18, "foo", "NaT"], + None, + ], + ], + ) + def test_unit_with_numeric_coerce(self, cache, exp, arr, warning): + # but we want to make sure that we are coercing + # if we have ints/strings + expected = DatetimeIndex(exp, dtype="M8[ns]") + with tm.assert_produces_warning(warning, match="Could not infer format"): + result = to_datetime(arr, errors="coerce", cache=cache) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "arr", + [ + [Timestamp("20130101"), 1.434692e18, 1.432766e18], + [1.434692e18, 1.432766e18, Timestamp("20130101")], + ], + ) + def test_unit_mixed(self, cache, arr): + # GH#50453 pre-2.0 with mixed numeric/datetimes and errors="coerce" + # the numeric entries would be coerced to NaT, was never clear exactly + # why. + # mixed integers/datetimes + expected = Index([Timestamp(x) for x in arr], dtype="M8[ns]") + result = to_datetime(arr, errors="coerce", cache=cache) + tm.assert_index_equal(result, expected) + + # GH#49037 pre-2.0 this raised, but it always worked with Series, + # was never clear why it was disallowed + result = to_datetime(arr, errors="raise", cache=cache) + tm.assert_index_equal(result, expected) + + result = DatetimeIndex(arr) + tm.assert_index_equal(result, expected) + + def test_unit_rounding(self, cache): + # GH 14156 & GH 20445: argument will incur floating point errors + # but no premature rounding + value = 1434743731.8770001 + result = to_datetime(value, unit="s", cache=cache) + expected = Timestamp("2015-06-19 19:55:31.877000093") + assert result == expected + + alt = Timestamp(value, unit="s") + assert alt == result + + def test_unit_ignore_keeps_name(self, cache): + # GH 21697 + expected = Index([15e9] * 2, name="name") + result = to_datetime(expected, errors="ignore", unit="s", cache=cache) + tm.assert_index_equal(result, expected) + + def test_to_datetime_errors_ignore_utc_true(self): + # GH#23758 + result = to_datetime([1], unit="s", utc=True, errors="ignore") + expected = DatetimeIndex(["1970-01-01 00:00:01"], dtype="M8[ns, UTC]") + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("dtype", [int, float]) + def test_to_datetime_unit(self, dtype): + epoch = 1370745748 + ser = Series([epoch + t for t in range(20)]).astype(dtype) + result = to_datetime(ser, unit="s") + expected = Series( + [ + Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) + for t in range(20) + ], + dtype="M8[ns]", + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("null", [iNaT, np.nan]) + def test_to_datetime_unit_with_nulls(self, null): + epoch = 1370745748 + ser = Series([epoch + t for t in range(20)] + [null]) + result = to_datetime(ser, unit="s") + expected = Series( + [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + + [NaT], + dtype="M8[ns]", + ) + tm.assert_series_equal(result, expected) + + def test_to_datetime_unit_fractional_seconds(self): + # GH13834 + epoch = 1370745748 + ser = Series([epoch + t for t in np.arange(0, 2, 0.25)] + [iNaT]).astype(float) + result = to_datetime(ser, unit="s") + expected = Series( + [ + Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) + for t in np.arange(0, 2, 0.25) + ] + + [NaT], + dtype="M8[ns]", + ) + # GH20455 argument will incur floating point errors but no premature rounding + result = result.round("ms") + tm.assert_series_equal(result, expected) + + def test_to_datetime_unit_na_values(self): + result = to_datetime([1, 2, "NaT", NaT, np.nan], unit="D") + expected = DatetimeIndex( + [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 3, + dtype="M8[ns]", + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("bad_val", ["foo", 111111111]) + def test_to_datetime_unit_invalid(self, bad_val): + msg = f"{bad_val} with the unit 'D'" + with pytest.raises(ValueError, match=msg): + to_datetime([1, 2, bad_val], unit="D") + + @pytest.mark.parametrize("bad_val", ["foo", 111111111]) + def test_to_timestamp_unit_coerce(self, bad_val): + # coerce we can process + expected = DatetimeIndex( + [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 1, + dtype="M8[ns]", + ) + result = to_datetime([1, 2, bad_val], unit="D", errors="coerce") + tm.assert_index_equal(result, expected) + + def test_float_to_datetime_raise_near_bounds(self): + # GH50183 + msg = "cannot convert input with unit 'D'" + oneday_in_ns = 1e9 * 60 * 60 * 24 + tsmax_in_days = 2**63 / oneday_in_ns # 2**63 ns, in days + # just in bounds + should_succeed = Series( + [0, tsmax_in_days - 0.005, -tsmax_in_days + 0.005], dtype=float + ) + expected = (should_succeed * oneday_in_ns).astype(np.int64) + for error_mode in ["raise", "coerce", "ignore"]: + result1 = to_datetime(should_succeed, unit="D", errors=error_mode) + # Cast to `np.float64` so that `rtol` and inexact checking kick in + # (`check_exact` doesn't take place for integer dtypes) + tm.assert_almost_equal( + result1.astype(np.int64).astype(np.float64), + expected.astype(np.float64), + rtol=1e-10, + ) + # just out of bounds + should_fail1 = Series([0, tsmax_in_days + 0.005], dtype=float) + should_fail2 = Series([0, -tsmax_in_days - 0.005], dtype=float) + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(should_fail1, unit="D", errors="raise") + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(should_fail2, unit="D", errors="raise") + + +class TestToDatetimeDataFrame: + @pytest.fixture + def df(self): + return DataFrame( + { + "year": [2015, 2016], + "month": [2, 3], + "day": [4, 5], + "hour": [6, 7], + "minute": [58, 59], + "second": [10, 11], + "ms": [1, 1], + "us": [2, 2], + "ns": [3, 3], + } + ) + + def test_dataframe(self, df, cache): + result = to_datetime( + {"year": df["year"], "month": df["month"], "day": df["day"]}, cache=cache + ) + expected = Series( + [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:0:00")] + ) + tm.assert_series_equal(result, expected) + + # dict-like + result = to_datetime(df[["year", "month", "day"]].to_dict(), cache=cache) + tm.assert_series_equal(result, expected) + + def test_dataframe_dict_with_constructable(self, df, cache): + # dict but with constructable + df2 = df[["year", "month", "day"]].to_dict() + df2["month"] = 2 + result = to_datetime(df2, cache=cache) + expected2 = Series( + [Timestamp("20150204 00:00:00"), Timestamp("20160205 00:0:00")] + ) + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "unit", + [ + { + "year": "years", + "month": "months", + "day": "days", + "hour": "hours", + "minute": "minutes", + "second": "seconds", + }, + { + "year": "year", + "month": "month", + "day": "day", + "hour": "hour", + "minute": "minute", + "second": "second", + }, + ], + ) + def test_dataframe_field_aliases_column_subset(self, df, cache, unit): + # unit mappings + result = to_datetime(df[list(unit.keys())].rename(columns=unit), cache=cache) + expected = Series( + [Timestamp("20150204 06:58:10"), Timestamp("20160305 07:59:11")], + dtype="M8[ns]", + ) + tm.assert_series_equal(result, expected) + + def test_dataframe_field_aliases(self, df, cache): + d = { + "year": "year", + "month": "month", + "day": "day", + "hour": "hour", + "minute": "minute", + "second": "second", + "ms": "ms", + "us": "us", + "ns": "ns", + } + + result = to_datetime(df.rename(columns=d), cache=cache) + expected = Series( + [ + Timestamp("20150204 06:58:10.001002003"), + Timestamp("20160305 07:59:11.001002003"), + ] + ) + tm.assert_series_equal(result, expected) + + def test_dataframe_str_dtype(self, df, cache): + # coerce back to int + result = to_datetime(df.astype(str), cache=cache) + expected = Series( + [ + Timestamp("20150204 06:58:10.001002003"), + Timestamp("20160305 07:59:11.001002003"), + ] + ) + tm.assert_series_equal(result, expected) + + def test_dataframe_coerce(self, cache): + # passing coerce + df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) + + msg = ( + r'^cannot assemble the datetimes: time data ".+" doesn\'t ' + r'match format "%Y%m%d", at position 1\.' + ) + with pytest.raises(ValueError, match=msg): + to_datetime(df2, cache=cache) + + result = to_datetime(df2, errors="coerce", cache=cache) + expected = Series([Timestamp("20150204 00:00:00"), NaT]) + tm.assert_series_equal(result, expected) + + def test_dataframe_extra_keys_raisesm(self, df, cache): + # extra columns + msg = r"extra keys have been passed to the datetime assemblage: \[foo\]" + with pytest.raises(ValueError, match=msg): + df2 = df.copy() + df2["foo"] = 1 + to_datetime(df2, cache=cache) + + @pytest.mark.parametrize( + "cols", + [ + ["year"], + ["year", "month"], + ["year", "month", "second"], + ["month", "day"], + ["year", "day", "second"], + ], + ) + def test_dataframe_missing_keys_raises(self, df, cache, cols): + # not enough + msg = ( + r"to assemble mappings requires at least that \[year, month, " + r"day\] be specified: \[.+\] is missing" + ) + with pytest.raises(ValueError, match=msg): + to_datetime(df[cols], cache=cache) + + def test_dataframe_duplicate_columns_raises(self, cache): + # duplicates + msg = "cannot assemble with duplicate keys" + df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) + df2.columns = ["year", "year", "day"] + with pytest.raises(ValueError, match=msg): + to_datetime(df2, cache=cache) + + df2 = DataFrame( + {"year": [2015, 2016], "month": [2, 20], "day": [4, 5], "hour": [4, 5]} + ) + df2.columns = ["year", "month", "day", "day"] + with pytest.raises(ValueError, match=msg): + to_datetime(df2, cache=cache) + + def test_dataframe_int16(self, cache): + # GH#13451 + df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) + + # int16 + result = to_datetime(df.astype("int16"), cache=cache) + expected = Series( + [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:00:00")] + ) + tm.assert_series_equal(result, expected) + + def test_dataframe_mixed(self, cache): + # mixed dtypes + df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) + df["month"] = df["month"].astype("int8") + df["day"] = df["day"].astype("int8") + result = to_datetime(df, cache=cache) + expected = Series( + [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:00:00")] + ) + tm.assert_series_equal(result, expected) + + def test_dataframe_float(self, cache): + # float + df = DataFrame({"year": [2000, 2001], "month": [1.5, 1], "day": [1, 1]}) + msg = ( + r"^cannot assemble the datetimes: unconverted data remains when parsing " + r'with format ".*": "1", at position 0.' + ) + with pytest.raises(ValueError, match=msg): + to_datetime(df, cache=cache) + + def test_dataframe_utc_true(self): + # GH#23760 + df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) + result = to_datetime(df, utc=True) + expected = Series( + np.array(["2015-02-04", "2016-03-05"], dtype="datetime64[ns]") + ).dt.tz_localize("UTC") + tm.assert_series_equal(result, expected) + + +class TestToDatetimeMisc: + def test_to_datetime_barely_out_of_bounds(self): + # GH#19529 + # GH#19382 close enough to bounds that dropping nanos would result + # in an in-bounds datetime + arr = np.array(["2262-04-11 23:47:16.854775808"], dtype=object) + + msg = "^Out of bounds nanosecond timestamp: .*, at position 0" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime(arr) + + @pytest.mark.parametrize( + "arg, exp_str", + [ + ["2012-01-01 00:00:00", "2012-01-01 00:00:00"], + ["20121001", "2012-10-01"], # bad iso 8601 + ], + ) + def test_to_datetime_iso8601(self, cache, arg, exp_str): + result = to_datetime([arg], cache=cache) + exp = Timestamp(exp_str) + assert result[0] == exp + + @pytest.mark.parametrize( + "input, format", + [ + ("2012", "%Y-%m"), + ("2012-01", "%Y-%m-%d"), + ("2012-01-01", "%Y-%m-%d %H"), + ("2012-01-01 10", "%Y-%m-%d %H:%M"), + ("2012-01-01 10:00", "%Y-%m-%d %H:%M:%S"), + ("2012-01-01 10:00:00", "%Y-%m-%d %H:%M:%S.%f"), + ("2012-01-01 10:00:00.123", "%Y-%m-%d %H:%M:%S.%f%z"), + (0, "%Y-%m-%d"), + ], + ) + @pytest.mark.parametrize("exact", [True, False]) + def test_to_datetime_iso8601_fails(self, input, format, exact): + # https://github.com/pandas-dev/pandas/issues/12649 + # `format` is longer than the string, so this fails regardless of `exact` + with pytest.raises( + ValueError, + match=( + rf"time data \"{input}\" doesn't match format " + rf"\"{format}\", at position 0" + ), + ): + to_datetime(input, format=format, exact=exact) + + @pytest.mark.parametrize( + "input, format", + [ + ("2012-01-01", "%Y-%m"), + ("2012-01-01 10", "%Y-%m-%d"), + ("2012-01-01 10:00", "%Y-%m-%d %H"), + ("2012-01-01 10:00:00", "%Y-%m-%d %H:%M"), + (0, "%Y-%m-%d"), + ], + ) + def test_to_datetime_iso8601_exact_fails(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + # `format` is shorter than the date string, so only fails with `exact=True` + msg = "|".join( + [ + '^unconverted data remains when parsing with format ".*": ".*"' + f", at position 0. {PARSING_ERR_MSG}$", + f'^time data ".*" doesn\'t match format ".*", at position 0. ' + f"{PARSING_ERR_MSG}$", + ] + ) + with pytest.raises( + ValueError, + match=(msg), + ): + to_datetime(input, format=format) + + @pytest.mark.parametrize( + "input, format", + [ + ("2012-01-01", "%Y-%m"), + ("2012-01-01 00", "%Y-%m-%d"), + ("2012-01-01 00:00", "%Y-%m-%d %H"), + ("2012-01-01 00:00:00", "%Y-%m-%d %H:%M"), + ], + ) + def test_to_datetime_iso8601_non_exact(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + expected = Timestamp(2012, 1, 1) + result = to_datetime(input, format=format, exact=False) + assert result == expected + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-01", "%Y/%m"), + ("2020-01-01", "%Y/%m/%d"), + ("2020-01-01 00", "%Y/%m/%dT%H"), + ("2020-01-01T00", "%Y/%m/%d %H"), + ("2020-01-01 00:00", "%Y/%m/%dT%H:%M"), + ("2020-01-01T00:00", "%Y/%m/%d %H:%M"), + ("2020-01-01 00:00:00", "%Y/%m/%dT%H:%M:%S"), + ("2020-01-01T00:00:00", "%Y/%m/%d %H:%M:%S"), + ], + ) + def test_to_datetime_iso8601_separator(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + with pytest.raises( + ValueError, + match=( + rf"time data \"{input}\" doesn\'t match format " + rf"\"{format}\", at position 0" + ), + ): + to_datetime(input, format=format) + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-01", "%Y-%m"), + ("2020-01-01", "%Y-%m-%d"), + ("2020-01-01 00", "%Y-%m-%d %H"), + ("2020-01-01T00", "%Y-%m-%dT%H"), + ("2020-01-01 00:00", "%Y-%m-%d %H:%M"), + ("2020-01-01T00:00", "%Y-%m-%dT%H:%M"), + ("2020-01-01 00:00:00", "%Y-%m-%d %H:%M:%S"), + ("2020-01-01T00:00:00", "%Y-%m-%dT%H:%M:%S"), + ("2020-01-01T00:00:00.000", "%Y-%m-%dT%H:%M:%S.%f"), + ("2020-01-01T00:00:00.000000", "%Y-%m-%dT%H:%M:%S.%f"), + ("2020-01-01T00:00:00.000000000", "%Y-%m-%dT%H:%M:%S.%f"), + ], + ) + def test_to_datetime_iso8601_valid(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + expected = Timestamp(2020, 1, 1) + result = to_datetime(input, format=format) + assert result == expected + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-1", "%Y-%m"), + ("2020-1-1", "%Y-%m-%d"), + ("2020-1-1 0", "%Y-%m-%d %H"), + ("2020-1-1T0", "%Y-%m-%dT%H"), + ("2020-1-1 0:0", "%Y-%m-%d %H:%M"), + ("2020-1-1T0:0", "%Y-%m-%dT%H:%M"), + ("2020-1-1 0:0:0", "%Y-%m-%d %H:%M:%S"), + ("2020-1-1T0:0:0", "%Y-%m-%dT%H:%M:%S"), + ("2020-1-1T0:0:0.000", "%Y-%m-%dT%H:%M:%S.%f"), + ("2020-1-1T0:0:0.000000", "%Y-%m-%dT%H:%M:%S.%f"), + ("2020-1-1T0:0:0.000000000", "%Y-%m-%dT%H:%M:%S.%f"), + ], + ) + def test_to_datetime_iso8601_non_padded(self, input, format): + # https://github.com/pandas-dev/pandas/issues/21422 + expected = Timestamp(2020, 1, 1) + result = to_datetime(input, format=format) + assert result == expected + + @pytest.mark.parametrize( + "input, format", + [ + ("2020-01-01T00:00:00.000000000+00:00", "%Y-%m-%dT%H:%M:%S.%f%z"), + ("2020-01-01T00:00:00+00:00", "%Y-%m-%dT%H:%M:%S%z"), + ("2020-01-01T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z"), + ], + ) + def test_to_datetime_iso8601_with_timezone_valid(self, input, format): + # https://github.com/pandas-dev/pandas/issues/12649 + expected = Timestamp(2020, 1, 1, tzinfo=pytz.UTC) + result = to_datetime(input, format=format) + assert result == expected + + def test_to_datetime_default(self, cache): + rs = to_datetime("2001", cache=cache) + xp = datetime(2001, 1, 1) + assert rs == xp + + @pytest.mark.xfail(reason="fails to enforce dayfirst=True, which would raise") + def test_to_datetime_respects_dayfirst(self, cache): + # dayfirst is essentially broken + + # The msg here is not important since it isn't actually raised yet. + msg = "Invalid date specified" + with pytest.raises(ValueError, match=msg): + # if dayfirst is respected, then this would parse as month=13, which + # would raise + with tm.assert_produces_warning(UserWarning, match="Provide format"): + to_datetime("01-13-2012", dayfirst=True, cache=cache) + + def test_to_datetime_on_datetime64_series(self, cache): + # #2699 + ser = Series(date_range("1/1/2000", periods=10)) + + result = to_datetime(ser, cache=cache) + assert result[0] == ser[0] + + def test_to_datetime_with_space_in_series(self, cache): + # GH 6428 + ser = Series(["10/18/2006", "10/18/2008", " "]) + msg = ( + r'^time data " " doesn\'t match format "%m/%d/%Y", ' + rf"at position 2. {PARSING_ERR_MSG}$" + ) + with pytest.raises(ValueError, match=msg): + to_datetime(ser, errors="raise", cache=cache) + result_coerce = to_datetime(ser, errors="coerce", cache=cache) + expected_coerce = Series([datetime(2006, 10, 18), datetime(2008, 10, 18), NaT]) + tm.assert_series_equal(result_coerce, expected_coerce) + result_ignore = to_datetime(ser, errors="ignore", cache=cache) + tm.assert_series_equal(result_ignore, ser) + + @td.skip_if_not_us_locale + def test_to_datetime_with_apply(self, cache): + # this is only locale tested with US/None locales + # GH 5195 + # with a format and coerce a single item to_datetime fails + td = Series(["May 04", "Jun 02", "Dec 11"], index=[1, 2, 3]) + expected = to_datetime(td, format="%b %y", cache=cache) + result = td.apply(to_datetime, format="%b %y", cache=cache) + tm.assert_series_equal(result, expected) + + def test_to_datetime_timezone_name(self): + # https://github.com/pandas-dev/pandas/issues/49748 + result = to_datetime("2020-01-01 00:00:00UTC", format="%Y-%m-%d %H:%M:%S%Z") + expected = Timestamp(2020, 1, 1).tz_localize("UTC") + assert result == expected + + @td.skip_if_not_us_locale + @pytest.mark.parametrize("errors", ["raise", "coerce", "ignore"]) + def test_to_datetime_with_apply_with_empty_str(self, cache, errors): + # this is only locale tested with US/None locales + # GH 5195, GH50251 + # with a format and coerce a single item to_datetime fails + td = Series(["May 04", "Jun 02", ""], index=[1, 2, 3]) + expected = to_datetime(td, format="%b %y", errors=errors, cache=cache) + + result = td.apply( + lambda x: to_datetime(x, format="%b %y", errors="coerce", cache=cache) + ) + tm.assert_series_equal(result, expected) + + def test_to_datetime_empty_stt(self, cache): + # empty string + result = to_datetime("", cache=cache) + assert result is NaT + + def test_to_datetime_empty_str_list(self, cache): + result = to_datetime(["", ""], cache=cache) + assert isna(result).all() + + def test_to_datetime_zero(self, cache): + # ints + result = Timestamp(0) + expected = to_datetime(0, cache=cache) + assert result == expected + + def test_to_datetime_strings(self, cache): + # GH 3888 (strings) + expected = to_datetime(["2012"], cache=cache)[0] + result = to_datetime("2012", cache=cache) + assert result == expected + + def test_to_datetime_strings_variation(self, cache): + array = ["2012", "20120101", "20120101 12:01:01"] + expected = [to_datetime(dt_str, cache=cache) for dt_str in array] + result = [Timestamp(date_str) for date_str in array] + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize("result", [Timestamp("2012"), to_datetime("2012")]) + def test_to_datetime_strings_vs_constructor(self, result): + expected = Timestamp(2012, 1, 1) + assert result == expected + + def test_to_datetime_unprocessable_input(self, cache): + # GH 4928 + # GH 21864 + result = to_datetime([1, "1"], errors="ignore", cache=cache) + + expected = Index(np.array([1, "1"], dtype="O")) + tm.assert_equal(result, expected) + msg = '^Given date string "1" not likely a datetime, at position 1$' + with pytest.raises(ValueError, match=msg): + to_datetime([1, "1"], errors="raise", cache=cache) + + def test_to_datetime_unhashable_input(self, cache): + series = Series([["a"]] * 100) + result = to_datetime(series, errors="ignore", cache=cache) + tm.assert_series_equal(series, result) + + def test_to_datetime_other_datetime64_units(self): + # 5/25/2012 + scalar = np.int64(1337904000000000).view("M8[us]") + as_obj = scalar.astype("O") + + index = DatetimeIndex([scalar]) + assert index[0] == scalar.astype("O") + + value = Timestamp(scalar) + assert value == as_obj + + def test_to_datetime_list_of_integers(self): + rng = date_range("1/1/2000", periods=20) + rng = DatetimeIndex(rng.values) + + ints = list(rng.asi8) + + result = DatetimeIndex(ints) + + tm.assert_index_equal(rng, result) + + def test_to_datetime_overflow(self): + # gh-17637 + # we are overflowing Timedelta range here + msg = "Cannot cast 139999 days 00:00:00 to unit='ns' without overflow" + with pytest.raises(OutOfBoundsTimedelta, match=msg): + date_range(start="1/1/1700", freq="B", periods=100000) + + def test_string_invalid_operation(self, cache): + invalid = np.array(["87156549591102612381000001219H5"], dtype=object) + # GH #51084 + + with pytest.raises(ValueError, match="Unknown datetime string format"): + to_datetime(invalid, errors="raise", cache=cache) + + def test_string_na_nat_conversion(self, cache): + # GH #999, #858 + + strings = np.array(["1/1/2000", "1/2/2000", np.nan, "1/4/2000"], dtype=object) + + expected = np.empty(4, dtype="M8[ns]") + for i, val in enumerate(strings): + if isna(val): + expected[i] = iNaT + else: + expected[i] = parse(val) + + result = tslib.array_to_datetime(strings)[0] + tm.assert_almost_equal(result, expected) + + result2 = to_datetime(strings, cache=cache) + assert isinstance(result2, DatetimeIndex) + tm.assert_numpy_array_equal(result, result2.values) + + def test_string_na_nat_conversion_malformed(self, cache): + malformed = np.array(["1/100/2000", np.nan], dtype=object) + + # GH 10636, default is now 'raise' + msg = r"Unknown datetime string format" + with pytest.raises(ValueError, match=msg): + to_datetime(malformed, errors="raise", cache=cache) + + result = to_datetime(malformed, errors="ignore", cache=cache) + # GH 21864 + expected = Index(malformed, dtype=object) + tm.assert_index_equal(result, expected) + + with pytest.raises(ValueError, match=msg): + to_datetime(malformed, errors="raise", cache=cache) + + def test_string_na_nat_conversion_with_name(self, cache): + idx = ["a", "b", "c", "d", "e"] + series = Series( + ["1/1/2000", np.nan, "1/3/2000", np.nan, "1/5/2000"], index=idx, name="foo" + ) + dseries = Series( + [ + to_datetime("1/1/2000", cache=cache), + np.nan, + to_datetime("1/3/2000", cache=cache), + np.nan, + to_datetime("1/5/2000", cache=cache), + ], + index=idx, + name="foo", + ) + + result = to_datetime(series, cache=cache) + dresult = to_datetime(dseries, cache=cache) + + expected = Series(np.empty(5, dtype="M8[ns]"), index=idx) + for i in range(5): + x = series.iloc[i] + if isna(x): + expected.iloc[i] = NaT + else: + expected.iloc[i] = to_datetime(x, cache=cache) + + tm.assert_series_equal(result, expected, check_names=False) + assert result.name == "foo" + + tm.assert_series_equal(dresult, expected, check_names=False) + assert dresult.name == "foo" + + @pytest.mark.parametrize( + "unit", + ["h", "m", "s", "ms", "us", "ns"], + ) + def test_dti_constructor_numpy_timeunits(self, cache, unit): + # GH 9114 + dtype = np.dtype(f"M8[{unit}]") + base = to_datetime(["2000-01-01T00:00", "2000-01-02T00:00", "NaT"], cache=cache) + + values = base.values.astype(dtype) + + if unit in ["h", "m"]: + # we cast to closest supported unit + unit = "s" + exp_dtype = np.dtype(f"M8[{unit}]") + expected = DatetimeIndex(base.astype(exp_dtype)) + assert expected.dtype == exp_dtype + + tm.assert_index_equal(DatetimeIndex(values), expected) + tm.assert_index_equal(to_datetime(values, cache=cache), expected) + + def test_dayfirst(self, cache): + # GH 5917 + arr = ["10/02/2014", "11/02/2014", "12/02/2014"] + expected = DatetimeIndex( + [datetime(2014, 2, 10), datetime(2014, 2, 11), datetime(2014, 2, 12)] + ) + idx1 = DatetimeIndex(arr, dayfirst=True) + idx2 = DatetimeIndex(np.array(arr), dayfirst=True) + idx3 = to_datetime(arr, dayfirst=True, cache=cache) + idx4 = to_datetime(np.array(arr), dayfirst=True, cache=cache) + idx5 = DatetimeIndex(Index(arr), dayfirst=True) + idx6 = DatetimeIndex(Series(arr), dayfirst=True) + tm.assert_index_equal(expected, idx1) + tm.assert_index_equal(expected, idx2) + tm.assert_index_equal(expected, idx3) + tm.assert_index_equal(expected, idx4) + tm.assert_index_equal(expected, idx5) + tm.assert_index_equal(expected, idx6) + + def test_dayfirst_warnings_valid_input(self): + # GH 12585 + warning_msg = ( + "Parsing dates in .* format when dayfirst=.* was specified. " + "Pass `dayfirst=.*` or specify a format to silence this warning." + ) + + # CASE 1: valid input + arr = ["31/12/2014", "10/03/2011"] + expected = DatetimeIndex( + ["2014-12-31", "2011-03-10"], dtype="datetime64[ns]", freq=None + ) + + # A. dayfirst arg correct, no warning + res1 = to_datetime(arr, dayfirst=True) + tm.assert_index_equal(expected, res1) + + # B. dayfirst arg incorrect, warning + with tm.assert_produces_warning(UserWarning, match=warning_msg): + res2 = to_datetime(arr, dayfirst=False) + tm.assert_index_equal(expected, res2) + + def test_dayfirst_warnings_invalid_input(self): + # CASE 2: invalid input + # cannot consistently process with single format + # ValueError *always* raised + + # first in DD/MM/YYYY, second in MM/DD/YYYY + arr = ["31/12/2014", "03/30/2011"] + + with pytest.raises( + ValueError, + match=( + r'^time data "03/30/2011" doesn\'t match format ' + rf'"%d/%m/%Y", at position 1. {PARSING_ERR_MSG}$' + ), + ): + to_datetime(arr, dayfirst=True) + + @pytest.mark.parametrize("klass", [DatetimeIndex, DatetimeArray._from_sequence]) + def test_to_datetime_dta_tz(self, klass): + # GH#27733 + dti = date_range("2015-04-05", periods=3).rename("foo") + expected = dti.tz_localize("UTC") + + obj = klass(dti) + expected = klass(expected) + + result = to_datetime(obj, utc=True) + tm.assert_equal(result, expected) + + +class TestGuessDatetimeFormat: + @pytest.mark.parametrize( + "test_list", + [ + [ + "2011-12-30 00:00:00.000000", + "2011-12-30 00:00:00.000000", + "2011-12-30 00:00:00.000000", + ], + [np.nan, np.nan, "2011-12-30 00:00:00.000000"], + ["", "2011-12-30 00:00:00.000000"], + ["NaT", "2011-12-30 00:00:00.000000"], + ["2011-12-30 00:00:00.000000", "random_string"], + ["now", "2011-12-30 00:00:00.000000"], + ["today", "2011-12-30 00:00:00.000000"], + ], + ) + def test_guess_datetime_format_for_array(self, test_list): + expected_format = "%Y-%m-%d %H:%M:%S.%f" + test_array = np.array(test_list, dtype=object) + assert tools._guess_datetime_format_for_array(test_array) == expected_format + + @td.skip_if_not_us_locale + def test_guess_datetime_format_for_array_all_nans(self): + format_for_string_of_nans = tools._guess_datetime_format_for_array( + np.array([np.nan, np.nan, np.nan], dtype="O") + ) + assert format_for_string_of_nans is None + + +class TestToDatetimeInferFormat: + @pytest.mark.parametrize( + "test_format", ["%m-%d-%Y", "%m/%d/%Y %H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S.%f"] + ) + def test_to_datetime_infer_datetime_format_consistent_format( + self, cache, test_format + ): + ser = Series(date_range("20000101", periods=50, freq="h")) + + s_as_dt_strings = ser.apply(lambda x: x.strftime(test_format)) + + with_format = to_datetime(s_as_dt_strings, format=test_format, cache=cache) + without_format = to_datetime(s_as_dt_strings, cache=cache) + + # Whether the format is explicitly passed, or + # it is inferred, the results should all be the same + tm.assert_series_equal(with_format, without_format) + + def test_to_datetime_inconsistent_format(self, cache): + data = ["01/01/2011 00:00:00", "01-02-2011 00:00:00", "2011-01-03T00:00:00"] + ser = Series(np.array(data)) + msg = ( + r'^time data "01-02-2011 00:00:00" doesn\'t match format ' + rf'"%m/%d/%Y %H:%M:%S", at position 1. {PARSING_ERR_MSG}$' + ) + with pytest.raises(ValueError, match=msg): + to_datetime(ser, cache=cache) + + def test_to_datetime_consistent_format(self, cache): + data = ["Jan/01/2011", "Feb/01/2011", "Mar/01/2011"] + ser = Series(np.array(data)) + result = to_datetime(ser, cache=cache) + expected = Series( + ["2011-01-01", "2011-02-01", "2011-03-01"], dtype="datetime64[ns]" + ) + tm.assert_series_equal(result, expected) + + def test_to_datetime_series_with_nans(self, cache): + ser = Series( + np.array( + ["01/01/2011 00:00:00", np.nan, "01/03/2011 00:00:00", np.nan], + dtype=object, + ) + ) + result = to_datetime(ser, cache=cache) + expected = Series( + ["2011-01-01", NaT, "2011-01-03", NaT], dtype="datetime64[ns]" + ) + tm.assert_series_equal(result, expected) + + def test_to_datetime_series_start_with_nans(self, cache): + ser = Series( + np.array( + [ + np.nan, + np.nan, + "01/01/2011 00:00:00", + "01/02/2011 00:00:00", + "01/03/2011 00:00:00", + ], + dtype=object, + ) + ) + + result = to_datetime(ser, cache=cache) + expected = Series( + [NaT, NaT, "2011-01-01", "2011-01-02", "2011-01-03"], dtype="datetime64[ns]" + ) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "tz_name, offset", + [("UTC", 0), ("UTC-3", 180), ("UTC+3", -180)], + ) + def test_infer_datetime_format_tz_name(self, tz_name, offset): + # GH 33133 + ser = Series([f"2019-02-02 08:07:13 {tz_name}"]) + result = to_datetime(ser) + tz = timezone(timedelta(minutes=offset)) + expected = Series([Timestamp("2019-02-02 08:07:13").tz_localize(tz)]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "ts,zero_tz", + [ + ("2019-02-02 08:07:13", "Z"), + ("2019-02-02 08:07:13", ""), + ("2019-02-02 08:07:13.012345", "Z"), + ("2019-02-02 08:07:13.012345", ""), + ], + ) + def test_infer_datetime_format_zero_tz(self, ts, zero_tz): + # GH 41047 + ser = Series([ts + zero_tz]) + result = to_datetime(ser) + tz = pytz.utc if zero_tz == "Z" else None + expected = Series([Timestamp(ts, tz=tz)]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("format", [None, "%Y-%m-%d"]) + def test_to_datetime_iso8601_noleading_0s(self, cache, format): + # GH 11871 + ser = Series(["2014-1-1", "2014-2-2", "2015-3-3"]) + expected = Series( + [ + Timestamp("2014-01-01"), + Timestamp("2014-02-02"), + Timestamp("2015-03-03"), + ] + ) + result = to_datetime(ser, format=format, cache=cache) + tm.assert_series_equal(result, expected) + + def test_parse_dates_infer_datetime_format_warning(self): + # GH 49024 + with tm.assert_produces_warning( + UserWarning, + match="The argument 'infer_datetime_format' is deprecated", + ): + to_datetime(["10-10-2000"], infer_datetime_format=True) + + +class TestDaysInMonth: + # tests for issue #10154 + + @pytest.mark.parametrize( + "arg, format", + [ + ["2015-02-29", None], + ["2015-02-29", "%Y-%m-%d"], + ["2015-02-32", "%Y-%m-%d"], + ["2015-04-31", "%Y-%m-%d"], + ], + ) + def test_day_not_in_month_coerce(self, cache, arg, format): + assert isna(to_datetime(arg, errors="coerce", format=format, cache=cache)) + + def test_day_not_in_month_raise(self, cache): + if PY314: + msg = "day 29 must be in range 1..28 for month 2 in year 2015: 2015-02-29" + else: + msg = "day is out of range for month: 2015-02-29" + with pytest.raises(ValueError, match=msg): + to_datetime("2015-02-29", errors="raise", cache=cache) + + @pytest.mark.parametrize( + "arg, format, msg", + [ + ( + "2015-02-29", + "%Y-%m-%d", + f"^{DAY_IS_OUT_OF_RANGE}. {PARSING_ERR_MSG}$", + ), + ( + "2015-29-02", + "%Y-%d-%m", + f"^{DAY_IS_OUT_OF_RANGE}. {PARSING_ERR_MSG}$", + ), + ( + "2015-02-32", + "%Y-%m-%d", + '^unconverted data remains when parsing with format "%Y-%m-%d": "2", ' + f"at position 0. {PARSING_ERR_MSG}$", + ), + ( + "2015-32-02", + "%Y-%d-%m", + '^time data "2015-32-02" doesn\'t match format "%Y-%d-%m", ' + f"at position 0. {PARSING_ERR_MSG}$", + ), + ( + "2015-04-31", + "%Y-%m-%d", + f"^{DAY_IS_OUT_OF_RANGE}. {PARSING_ERR_MSG}$", + ), + ( + "2015-31-04", + "%Y-%d-%m", + f"^{DAY_IS_OUT_OF_RANGE}. {PARSING_ERR_MSG}$", + ), + ], + ) + def test_day_not_in_month_raise_value(self, cache, arg, format, msg): + # https://github.com/pandas-dev/pandas/issues/50462 + with pytest.raises(ValueError, match=msg): + to_datetime(arg, errors="raise", format=format, cache=cache) + + @pytest.mark.parametrize( + "expected, format", + [ + ["2015-02-29", None], + ["2015-02-29", "%Y-%m-%d"], + ["2015-02-29", "%Y-%m-%d"], + ["2015-04-31", "%Y-%m-%d"], + ], + ) + def test_day_not_in_month_ignore(self, cache, expected, format): + result = to_datetime(expected, errors="ignore", format=format, cache=cache) + assert result == expected + + +class TestDatetimeParsingWrappers: + @pytest.mark.parametrize( + "date_str, expected", + [ + ("2011-01-01", datetime(2011, 1, 1)), + ("2Q2005", datetime(2005, 4, 1)), + ("2Q05", datetime(2005, 4, 1)), + ("2005Q1", datetime(2005, 1, 1)), + ("05Q1", datetime(2005, 1, 1)), + ("2011Q3", datetime(2011, 7, 1)), + ("11Q3", datetime(2011, 7, 1)), + ("3Q2011", datetime(2011, 7, 1)), + ("3Q11", datetime(2011, 7, 1)), + # quarterly without space + ("2000Q4", datetime(2000, 10, 1)), + ("00Q4", datetime(2000, 10, 1)), + ("4Q2000", datetime(2000, 10, 1)), + ("4Q00", datetime(2000, 10, 1)), + ("2000q4", datetime(2000, 10, 1)), + ("2000-Q4", datetime(2000, 10, 1)), + ("00-Q4", datetime(2000, 10, 1)), + ("4Q-2000", datetime(2000, 10, 1)), + ("4Q-00", datetime(2000, 10, 1)), + ("00q4", datetime(2000, 10, 1)), + ("2005", datetime(2005, 1, 1)), + ("2005-11", datetime(2005, 11, 1)), + ("2005 11", datetime(2005, 11, 1)), + ("11-2005", datetime(2005, 11, 1)), + ("11 2005", datetime(2005, 11, 1)), + ("200511", datetime(2020, 5, 11)), + ("20051109", datetime(2005, 11, 9)), + ("20051109 10:15", datetime(2005, 11, 9, 10, 15)), + ("20051109 08H", datetime(2005, 11, 9, 8, 0)), + ("2005-11-09 10:15", datetime(2005, 11, 9, 10, 15)), + ("2005-11-09 08H", datetime(2005, 11, 9, 8, 0)), + ("2005/11/09 10:15", datetime(2005, 11, 9, 10, 15)), + ("2005/11/09 10:15:32", datetime(2005, 11, 9, 10, 15, 32)), + ("2005/11/09 10:15:32 AM", datetime(2005, 11, 9, 10, 15, 32)), + ("2005/11/09 10:15:32 PM", datetime(2005, 11, 9, 22, 15, 32)), + ("2005/11/09 08H", datetime(2005, 11, 9, 8, 0)), + ("Thu Sep 25 10:36:28 2003", datetime(2003, 9, 25, 10, 36, 28)), + ("Thu Sep 25 2003", datetime(2003, 9, 25)), + ("Sep 25 2003", datetime(2003, 9, 25)), + ("January 1 2014", datetime(2014, 1, 1)), + # GH#10537 + ("2014-06", datetime(2014, 6, 1)), + ("06-2014", datetime(2014, 6, 1)), + ("2014-6", datetime(2014, 6, 1)), + ("6-2014", datetime(2014, 6, 1)), + ("20010101 12", datetime(2001, 1, 1, 12)), + ("20010101 1234", datetime(2001, 1, 1, 12, 34)), + ("20010101 123456", datetime(2001, 1, 1, 12, 34, 56)), + ], + ) + def test_parsers(self, date_str, expected, cache): + # dateutil >= 2.5.0 defaults to yearfirst=True + # https://github.com/dateutil/dateutil/issues/217 + yearfirst = True + + result1, _ = parsing.parse_datetime_string_with_reso( + date_str, yearfirst=yearfirst + ) + result2 = to_datetime(date_str, yearfirst=yearfirst) + result3 = to_datetime([date_str], yearfirst=yearfirst) + # result5 is used below + result4 = to_datetime( + np.array([date_str], dtype=object), yearfirst=yearfirst, cache=cache + ) + result6 = DatetimeIndex([date_str], yearfirst=yearfirst) + # result7 is used below + result8 = DatetimeIndex(Index([date_str]), yearfirst=yearfirst) + result9 = DatetimeIndex(Series([date_str]), yearfirst=yearfirst) + + for res in [result1, result2]: + assert res == expected + for res in [result3, result4, result6, result8, result9]: + exp = DatetimeIndex([Timestamp(expected)]) + tm.assert_index_equal(res, exp) + + # these really need to have yearfirst, but we don't support + if not yearfirst: + result5 = Timestamp(date_str) + assert result5 == expected + result7 = date_range(date_str, freq="S", periods=1, yearfirst=yearfirst) + assert result7 == expected + + def test_na_values_with_cache( + self, cache, unique_nulls_fixture, unique_nulls_fixture2 + ): + # GH22305 + expected = Index([NaT, NaT], dtype="datetime64[ns]") + result = to_datetime([unique_nulls_fixture, unique_nulls_fixture2], cache=cache) + tm.assert_index_equal(result, expected) + + def test_parsers_nat(self): + # Test that each of several string-accepting methods return pd.NaT + result1, _ = parsing.parse_datetime_string_with_reso("NaT") + result2 = to_datetime("NaT") + result3 = Timestamp("NaT") + result4 = DatetimeIndex(["NaT"])[0] + assert result1 is NaT + assert result2 is NaT + assert result3 is NaT + assert result4 is NaT + + @pytest.mark.parametrize( + "date_str, dayfirst, yearfirst, expected", + [ + ("10-11-12", False, False, datetime(2012, 10, 11)), + ("10-11-12", True, False, datetime(2012, 11, 10)), + ("10-11-12", False, True, datetime(2010, 11, 12)), + ("10-11-12", True, True, datetime(2010, 12, 11)), + ("20/12/21", False, False, datetime(2021, 12, 20)), + ("20/12/21", True, False, datetime(2021, 12, 20)), + ("20/12/21", False, True, datetime(2020, 12, 21)), + ("20/12/21", True, True, datetime(2020, 12, 21)), + ], + ) + def test_parsers_dayfirst_yearfirst( + self, cache, date_str, dayfirst, yearfirst, expected + ): + # OK + # 2.5.1 10-11-12 [dayfirst=0, yearfirst=0] -> 2012-10-11 00:00:00 + # 2.5.2 10-11-12 [dayfirst=0, yearfirst=1] -> 2012-10-11 00:00:00 + # 2.5.3 10-11-12 [dayfirst=0, yearfirst=0] -> 2012-10-11 00:00:00 + + # OK + # 2.5.1 10-11-12 [dayfirst=0, yearfirst=1] -> 2010-11-12 00:00:00 + # 2.5.2 10-11-12 [dayfirst=0, yearfirst=1] -> 2010-11-12 00:00:00 + # 2.5.3 10-11-12 [dayfirst=0, yearfirst=1] -> 2010-11-12 00:00:00 + + # bug fix in 2.5.2 + # 2.5.1 10-11-12 [dayfirst=1, yearfirst=1] -> 2010-11-12 00:00:00 + # 2.5.2 10-11-12 [dayfirst=1, yearfirst=1] -> 2010-12-11 00:00:00 + # 2.5.3 10-11-12 [dayfirst=1, yearfirst=1] -> 2010-12-11 00:00:00 + + # OK + # 2.5.1 10-11-12 [dayfirst=1, yearfirst=0] -> 2012-11-10 00:00:00 + # 2.5.2 10-11-12 [dayfirst=1, yearfirst=0] -> 2012-11-10 00:00:00 + # 2.5.3 10-11-12 [dayfirst=1, yearfirst=0] -> 2012-11-10 00:00:00 + + # OK + # 2.5.1 20/12/21 [dayfirst=0, yearfirst=0] -> 2021-12-20 00:00:00 + # 2.5.2 20/12/21 [dayfirst=0, yearfirst=0] -> 2021-12-20 00:00:00 + # 2.5.3 20/12/21 [dayfirst=0, yearfirst=0] -> 2021-12-20 00:00:00 + + # OK + # 2.5.1 20/12/21 [dayfirst=0, yearfirst=1] -> 2020-12-21 00:00:00 + # 2.5.2 20/12/21 [dayfirst=0, yearfirst=1] -> 2020-12-21 00:00:00 + # 2.5.3 20/12/21 [dayfirst=0, yearfirst=1] -> 2020-12-21 00:00:00 + + # revert of bug in 2.5.2 + # 2.5.1 20/12/21 [dayfirst=1, yearfirst=1] -> 2020-12-21 00:00:00 + # 2.5.2 20/12/21 [dayfirst=1, yearfirst=1] -> month must be in 1..12 + # 2.5.3 20/12/21 [dayfirst=1, yearfirst=1] -> 2020-12-21 00:00:00 + + # OK + # 2.5.1 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00 + # 2.5.2 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00 + # 2.5.3 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00 + + # str : dayfirst, yearfirst, expected + + # compare with dateutil result + dateutil_result = parse(date_str, dayfirst=dayfirst, yearfirst=yearfirst) + assert dateutil_result == expected + + result1, _ = parsing.parse_datetime_string_with_reso( + date_str, dayfirst=dayfirst, yearfirst=yearfirst + ) + + # we don't support dayfirst/yearfirst here: + if not dayfirst and not yearfirst: + result2 = Timestamp(date_str) + assert result2 == expected + + result3 = to_datetime( + date_str, dayfirst=dayfirst, yearfirst=yearfirst, cache=cache + ) + + result4 = DatetimeIndex([date_str], dayfirst=dayfirst, yearfirst=yearfirst)[0] + + assert result1 == expected + assert result3 == expected + assert result4 == expected + + @pytest.mark.parametrize( + "date_str, exp_def", + [["10:15", datetime(1, 1, 1, 10, 15)], ["9:05", datetime(1, 1, 1, 9, 5)]], + ) + def test_parsers_timestring(self, date_str, exp_def): + # must be the same as dateutil result + exp_now = parse(date_str) + + result1, _ = parsing.parse_datetime_string_with_reso(date_str) + result2 = to_datetime(date_str) + result3 = to_datetime([date_str]) + result4 = Timestamp(date_str) + result5 = DatetimeIndex([date_str])[0] + # parse time string return time string based on default date + # others are not, and can't be changed because it is used in + # time series plot + assert result1 == exp_def + assert result2 == exp_now + assert result3 == exp_now + assert result4 == exp_now + assert result5 == exp_now + + @pytest.mark.parametrize( + "dt_string, tz, dt_string_repr", + [ + ( + "2013-01-01 05:45+0545", + timezone(timedelta(minutes=345)), + "Timestamp('2013-01-01 05:45:00+0545', tz='UTC+05:45')", + ), + ( + "2013-01-01 05:30+0530", + timezone(timedelta(minutes=330)), + "Timestamp('2013-01-01 05:30:00+0530', tz='UTC+05:30')", + ), + ], + ) + def test_parsers_timezone_minute_offsets_roundtrip( + self, cache, dt_string, tz, dt_string_repr + ): + # GH11708 + base = to_datetime("2013-01-01 00:00:00", cache=cache) + base = base.tz_localize("UTC").tz_convert(tz) + dt_time = to_datetime(dt_string, cache=cache) + assert base == dt_time + assert dt_string_repr == repr(dt_time) + + +@pytest.fixture(params=["D", "s", "ms", "us", "ns"]) +def units(request): + """Day and some time units. + + * D + * s + * ms + * us + * ns + """ + return request.param + + +@pytest.fixture +def epoch_1960(): + """Timestamp at 1960-01-01.""" + return Timestamp("1960-01-01") + + +@pytest.fixture +def units_from_epochs(): + return list(range(5)) + + +@pytest.fixture(params=["timestamp", "pydatetime", "datetime64", "str_1960"]) +def epochs(epoch_1960, request): + """Timestamp at 1960-01-01 in various forms. + + * Timestamp + * datetime.datetime + * numpy.datetime64 + * str + """ + assert request.param in {"timestamp", "pydatetime", "datetime64", "str_1960"} + if request.param == "timestamp": + return epoch_1960 + elif request.param == "pydatetime": + return epoch_1960.to_pydatetime() + elif request.param == "datetime64": + return epoch_1960.to_datetime64() + else: + return str(epoch_1960) + + +@pytest.fixture +def julian_dates(): + return date_range("2014-1-1", periods=10).to_julian_date().values + + +class TestOrigin: + def test_origin_and_unit(self): + # GH#42624 + ts = to_datetime(1, unit="s", origin=1) + expected = Timestamp("1970-01-01 00:00:02") + assert ts == expected + + ts = to_datetime(1, unit="s", origin=1_000_000_000) + expected = Timestamp("2001-09-09 01:46:41") + assert ts == expected + + def test_julian(self, julian_dates): + # gh-11276, gh-11745 + # for origin as julian + + result = Series(to_datetime(julian_dates, unit="D", origin="julian")) + expected = Series( + to_datetime(julian_dates - Timestamp(0).to_julian_date(), unit="D") + ) + tm.assert_series_equal(result, expected) + + def test_unix(self): + result = Series(to_datetime([0, 1, 2], unit="D", origin="unix")) + expected = Series( + [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")], + dtype="M8[ns]", + ) + tm.assert_series_equal(result, expected) + + def test_julian_round_trip(self): + result = to_datetime(2456658, origin="julian", unit="D") + assert result.to_julian_date() == 2456658 + + # out-of-bounds + msg = "1 is Out of Bounds for origin='julian'" + with pytest.raises(ValueError, match=msg): + to_datetime(1, origin="julian", unit="D") + + def test_invalid_unit(self, units, julian_dates): + # checking for invalid combination of origin='julian' and unit != D + if units != "D": + msg = "unit must be 'D' for origin='julian'" + with pytest.raises(ValueError, match=msg): + to_datetime(julian_dates, unit=units, origin="julian") + + @pytest.mark.parametrize("unit", ["ns", "D"]) + def test_invalid_origin(self, unit): + # need to have a numeric specified + msg = "it must be numeric with a unit specified" + with pytest.raises(ValueError, match=msg): + to_datetime("2005-01-01", origin="1960-01-01", unit=unit) + + @pytest.mark.parametrize( + "epochs", + [ + Timestamp(1960, 1, 1), + datetime(1960, 1, 1), + "1960-01-01", + np.datetime64("1960-01-01"), + ], + ) + def test_epoch(self, units, epochs): + epoch_1960 = Timestamp(1960, 1, 1) + units_from_epochs = np.arange(5, dtype=np.int64) + expected = Series( + [pd.Timedelta(x, unit=units) + epoch_1960 for x in units_from_epochs] + ) + + result = Series(to_datetime(units_from_epochs, unit=units, origin=epochs)) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "origin, exc", + [ + ("random_string", ValueError), + ("epoch", ValueError), + ("13-24-1990", ValueError), + (datetime(1, 1, 1), OutOfBoundsDatetime), + ], + ) + def test_invalid_origins(self, origin, exc, units, units_from_epochs): + msg = "|".join( + [ + f"origin {origin} is Out of Bounds", + f"origin {origin} cannot be converted to a Timestamp", + "Cannot cast .* to unit='ns' without overflow", + ] + ) + with pytest.raises(exc, match=msg): + to_datetime(units_from_epochs, unit=units, origin=origin) + + def test_invalid_origins_tzinfo(self): + # GH16842 + with pytest.raises(ValueError, match="must be tz-naive"): + to_datetime(1, unit="D", origin=datetime(2000, 1, 1, tzinfo=pytz.utc)) + + def test_incorrect_value_exception(self): + # GH47495 + msg = ( + "Unknown datetime string format, unable to parse: yesterday, at position 1" + ) + with pytest.raises(ValueError, match=msg): + to_datetime(["today", "yesterday"]) + + @pytest.mark.parametrize( + "format, warning", + [ + (None, UserWarning), + ("%Y-%m-%d %H:%M:%S", None), + ("%Y-%d-%m %H:%M:%S", None), + ], + ) + def test_to_datetime_out_of_bounds_with_format_arg(self, format, warning): + # see gh-23830 + msg = r"^Out of bounds nanosecond timestamp: 2417-10-10 00:00:00, at position 0" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime("2417-10-10 00:00:00", format=format) + + @pytest.mark.parametrize( + "arg, origin, expected_str", + [ + [200 * 365, "unix", "2169-11-13 00:00:00"], + [200 * 365, "1870-01-01", "2069-11-13 00:00:00"], + [300 * 365, "1870-01-01", "2169-10-20 00:00:00"], + ], + ) + def test_processing_order(self, arg, origin, expected_str): + # make sure we handle out-of-bounds *before* + # constructing the dates + + result = to_datetime(arg, unit="D", origin=origin) + expected = Timestamp(expected_str) + assert result == expected + + result = to_datetime(200 * 365, unit="D", origin="1870-01-01") + expected = Timestamp("2069-11-13 00:00:00") + assert result == expected + + result = to_datetime(300 * 365, unit="D", origin="1870-01-01") + expected = Timestamp("2169-10-20 00:00:00") + assert result == expected + + @pytest.mark.parametrize( + "offset,utc,exp", + [ + ["Z", True, "2019-01-01T00:00:00.000Z"], + ["Z", None, "2019-01-01T00:00:00.000Z"], + ["-01:00", True, "2019-01-01T01:00:00.000Z"], + ["-01:00", None, "2019-01-01T00:00:00.000-01:00"], + ], + ) + def test_arg_tz_ns_unit(self, offset, utc, exp): + # GH 25546 + arg = "2019-01-01T00:00:00.000" + offset + result = to_datetime([arg], unit="ns", utc=utc) + expected = to_datetime([exp]).as_unit("ns") + tm.assert_index_equal(result, expected) + + +class TestShouldCache: + @pytest.mark.parametrize( + "listlike,do_caching", + [ + ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], False), + ([1, 1, 1, 1, 4, 5, 6, 7, 8, 9], True), + ], + ) + def test_should_cache(self, listlike, do_caching): + assert ( + tools.should_cache(listlike, check_count=len(listlike), unique_share=0.7) + == do_caching + ) + + @pytest.mark.parametrize( + "unique_share,check_count, err_message", + [ + (0.5, 11, r"check_count must be in next bounds: \[0; len\(arg\)\]"), + (10, 2, r"unique_share must be in next bounds: \(0; 1\)"), + ], + ) + def test_should_cache_errors(self, unique_share, check_count, err_message): + arg = [5] * 10 + + with pytest.raises(AssertionError, match=err_message): + tools.should_cache(arg, unique_share, check_count) + + @pytest.mark.parametrize( + "listlike", + [ + (deque([Timestamp("2010-06-02 09:30:00")] * 51)), + ([Timestamp("2010-06-02 09:30:00")] * 51), + (tuple([Timestamp("2010-06-02 09:30:00")] * 51)), + ], + ) + def test_no_slicing_errors_in_should_cache(self, listlike): + # GH#29403 + assert tools.should_cache(listlike) is True + + +def test_nullable_integer_to_datetime(): + # Test for #30050 + ser = Series([1, 2, None, 2**61, None]) + ser = ser.astype("Int64") + ser_copy = ser.copy() + + res = to_datetime(ser, unit="ns") + + expected = Series( + [ + np.datetime64("1970-01-01 00:00:00.000000001"), + np.datetime64("1970-01-01 00:00:00.000000002"), + np.datetime64("NaT"), + np.datetime64("2043-01-25 23:56:49.213693952"), + np.datetime64("NaT"), + ] + ) + tm.assert_series_equal(res, expected) + # Check that ser isn't mutated + tm.assert_series_equal(ser, ser_copy) + + +@pytest.mark.parametrize("klass", [np.array, list]) +def test_na_to_datetime(nulls_fixture, klass): + if isinstance(nulls_fixture, Decimal): + with pytest.raises(TypeError, match="not convertible to datetime"): + to_datetime(klass([nulls_fixture])) + + else: + result = to_datetime(klass([nulls_fixture])) + + assert result[0] is NaT + + +@pytest.mark.parametrize("errors", ["raise", "coerce", "ignore"]) +@pytest.mark.parametrize( + "args, format", + [ + (["03/24/2016", "03/25/2016", ""], "%m/%d/%Y"), + (["2016-03-24", "2016-03-25", ""], "%Y-%m-%d"), + ], + ids=["non-ISO8601", "ISO8601"], +) +def test_empty_string_datetime(errors, args, format): + # GH13044, GH50251 + td = Series(args) + + # coerce empty string to pd.NaT + result = to_datetime(td, format=format, errors=errors) + expected = Series(["2016-03-24", "2016-03-25", NaT], dtype="datetime64[ns]") + tm.assert_series_equal(expected, result) + + +def test_empty_string_datetime_coerce__unit(): + # GH13044 + # coerce empty string to pd.NaT + result = to_datetime([1, ""], unit="s", errors="coerce") + expected = DatetimeIndex(["1970-01-01 00:00:01", "NaT"], dtype="datetime64[ns]") + tm.assert_index_equal(expected, result) + + # verify that no exception is raised even when errors='raise' is set + result = to_datetime([1, ""], unit="s", errors="raise") + tm.assert_index_equal(expected, result) + + +@pytest.mark.parametrize("cache", [True, False]) +def test_to_datetime_monotonic_increasing_index(cache): + # GH28238 + cstart = start_caching_at + times = date_range(Timestamp("1980"), periods=cstart, freq="YS") + times = times.to_frame(index=False, name="DT").sample(n=cstart, random_state=1) + times.index = times.index.to_series().astype(float) / 1000 + result = to_datetime(times.iloc[:, 0], cache=cache) + expected = times.iloc[:, 0] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "series_length", + [40, start_caching_at, (start_caching_at + 1), (start_caching_at + 5)], +) +def test_to_datetime_cache_coerce_50_lines_outofbounds(series_length): + # GH#45319 + ser = Series( + [datetime.fromisoformat("1446-04-12 00:00:00+00:00")] + + ([datetime.fromisoformat("1991-10-20 00:00:00+00:00")] * series_length), + dtype=object, + ) + result1 = to_datetime(ser, errors="coerce", utc=True) + + expected1 = Series( + [NaT] + ([Timestamp("1991-10-20 00:00:00+00:00")] * series_length) + ) + + tm.assert_series_equal(result1, expected1) + + result2 = to_datetime(ser, errors="ignore", utc=True) + + expected2 = Series( + [datetime.fromisoformat("1446-04-12 00:00:00+00:00")] + + ([datetime.fromisoformat("1991-10-20 00:00:00+00:00")] * series_length) + ) + + tm.assert_series_equal(result2, expected2) + + with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond timestamp"): + to_datetime(ser, errors="raise", utc=True) + + +def test_to_datetime_format_f_parse_nanos(): + # GH 48767 + timestamp = "15/02/2020 02:03:04.123456789" + timestamp_format = "%d/%m/%Y %H:%M:%S.%f" + result = to_datetime(timestamp, format=timestamp_format) + expected = Timestamp( + year=2020, + month=2, + day=15, + hour=2, + minute=3, + second=4, + microsecond=123456, + nanosecond=789, + ) + assert result == expected + + +def test_to_datetime_mixed_iso8601(): + # https://github.com/pandas-dev/pandas/issues/50411 + result = to_datetime(["2020-01-01", "2020-01-01 05:00:00"], format="ISO8601") + expected = DatetimeIndex(["2020-01-01 00:00:00", "2020-01-01 05:00:00"]) + tm.assert_index_equal(result, expected) + + +def test_to_datetime_mixed_other(): + # https://github.com/pandas-dev/pandas/issues/50411 + result = to_datetime(["01/11/2000", "12 January 2000"], format="mixed") + expected = DatetimeIndex(["2000-01-11", "2000-01-12"]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("exact", [True, False]) +@pytest.mark.parametrize("format", ["ISO8601", "mixed"]) +def test_to_datetime_mixed_or_iso_exact(exact, format): + msg = "Cannot use 'exact' when 'format' is 'mixed' or 'ISO8601'" + with pytest.raises(ValueError, match=msg): + to_datetime(["2020-01-01"], exact=exact, format=format) + + +def test_to_datetime_mixed_not_necessarily_iso8601_raise(): + # https://github.com/pandas-dev/pandas/issues/50411 + with pytest.raises( + ValueError, match="Time data 01-01-2000 is not ISO8601 format, at position 1" + ): + to_datetime(["2020-01-01", "01-01-2000"], format="ISO8601") + + +@pytest.mark.parametrize( + ("errors", "expected"), + [ + ("coerce", DatetimeIndex(["2020-01-01 00:00:00", NaT])), + ("ignore", Index(["2020-01-01", "01-01-2000"], dtype="str")), + ], +) +def test_to_datetime_mixed_not_necessarily_iso8601_coerce(errors, expected): + # https://github.com/pandas-dev/pandas/issues/50411 + result = to_datetime(["2020-01-01", "01-01-2000"], format="ISO8601", errors=errors) + tm.assert_index_equal(result, expected) + + +def test_ignoring_unknown_tz_deprecated(): + # GH#18702, GH#51476 + dtstr = "2014 Jan 9 05:15 FAKE" + msg = 'un-recognized timezone "FAKE". Dropping unrecognized timezones is deprecated' + with tm.assert_produces_warning(FutureWarning, match=msg): + res = Timestamp(dtstr) + assert res == Timestamp(dtstr[:-5]) + + with tm.assert_produces_warning(FutureWarning): + res = to_datetime(dtstr) + assert res == to_datetime(dtstr[:-5]) + with tm.assert_produces_warning(FutureWarning): + res = to_datetime([dtstr]) + tm.assert_index_equal(res, to_datetime([dtstr[:-5]])) + + +def test_from_numeric_arrow_dtype(any_numeric_ea_dtype): + # GH 52425 + pytest.importorskip("pyarrow") + ser = Series([1, 2], dtype=f"{any_numeric_ea_dtype.lower()}[pyarrow]") + result = to_datetime(ser) + expected = Series([1, 2], dtype="datetime64[ns]") + tm.assert_series_equal(result, expected) + + +def test_to_datetime_with_empty_str_utc_false_format_mixed(): + # GH 50887 + vals = ["2020-01-01 00:00+00:00", ""] + result = to_datetime(vals, format="mixed") + expected = Index([Timestamp("2020-01-01 00:00+00:00"), "NaT"], dtype="M8[ns, UTC]") + tm.assert_index_equal(result, expected) + + # Check that a couple of other similar paths work the same way + alt = to_datetime(vals) + tm.assert_index_equal(alt, expected) + alt2 = DatetimeIndex(vals) + tm.assert_index_equal(alt2, expected) + + +def test_to_datetime_with_empty_str_utc_false_offsets_and_format_mixed(): + # GH 50887 + msg = "parsing datetimes with mixed time zones will raise an error" + + with tm.assert_produces_warning(FutureWarning, match=msg): + to_datetime( + ["2020-01-01 00:00+00:00", "2020-01-01 00:00+02:00", ""], format="mixed" + ) + + +def test_to_datetime_mixed_tzs_mixed_types(): + # GH#55793, GH#55693 mismatched tzs but one is str and other is + # datetime object + ts = Timestamp("2016-01-02 03:04:05", tz="US/Pacific") + dtstr = "2023-10-30 15:06+01" + arr = [ts, dtstr] + + msg = ( + "Mixed timezones detected. pass utc=True in to_datetime or tz='UTC' " + "in DatetimeIndex to convert to a common timezone" + ) + with pytest.raises(ValueError, match=msg): + to_datetime(arr) + with pytest.raises(ValueError, match=msg): + to_datetime(arr, format="mixed") + with pytest.raises(ValueError, match=msg): + DatetimeIndex(arr) + + +def test_to_datetime_mixed_types_matching_tzs(): + # GH#55793 + dtstr = "2023-11-01 09:22:03-07:00" + ts = Timestamp(dtstr) + arr = [ts, dtstr] + res1 = to_datetime(arr) + res2 = to_datetime(arr[::-1])[::-1] + res3 = to_datetime(arr, format="mixed") + res4 = DatetimeIndex(arr) + + expected = DatetimeIndex([ts, ts]) + tm.assert_index_equal(res1, expected) + tm.assert_index_equal(res2, expected) + tm.assert_index_equal(res3, expected) + tm.assert_index_equal(res4, expected) + + +dtstr = "2020-01-01 00:00+00:00" +ts = Timestamp(dtstr) + + +@pytest.mark.filterwarnings("ignore:Could not infer format:UserWarning") +@pytest.mark.parametrize( + "aware_val", + [dtstr, Timestamp(dtstr)], + ids=lambda x: type(x).__name__, +) +@pytest.mark.parametrize( + "naive_val", + [dtstr[:-6], ts.tz_localize(None), ts.date(), ts.asm8, ts.value, float(ts.value)], + ids=lambda x: type(x).__name__, +) +@pytest.mark.parametrize("naive_first", [True, False]) +def test_to_datetime_mixed_awareness_mixed_types(aware_val, naive_val, naive_first): + # GH#55793, GH#55693 + # Empty string parses to NaT + vals = [aware_val, naive_val, ""] + + vec = vals + if naive_first: + # alas, the behavior is order-dependent, so we test both ways + vec = [naive_val, aware_val, ""] + + # both_strs-> paths that were previously already deprecated with warning + # issued in _array_to_datetime_object + both_strs = isinstance(aware_val, str) and isinstance(naive_val, str) + has_numeric = isinstance(naive_val, (int, float)) + + depr_msg = "In a future version of pandas, parsing datetimes with mixed time zones" + + first_non_null = next(x for x in vec if x != "") + # if first_non_null is a not a string, _guess_datetime_format_for_array + # doesn't guess a format so we don't go through array_strptime + if not isinstance(first_non_null, str): + # that case goes through array_strptime which has different behavior + msg = "Cannot mix tz-aware with tz-naive values" + if naive_first and isinstance(aware_val, Timestamp): + if isinstance(naive_val, Timestamp): + msg = "Tz-aware datetime.datetime cannot be converted to datetime64" + with pytest.raises(ValueError, match=msg): + to_datetime(vec) + else: + with pytest.raises(ValueError, match=msg): + to_datetime(vec) + + # No warning/error with utc=True + to_datetime(vec, utc=True) + + elif has_numeric and vec.index(aware_val) < vec.index(naive_val): + msg = "time data .* doesn't match format" + with pytest.raises(ValueError, match=msg): + to_datetime(vec) + with pytest.raises(ValueError, match=msg): + to_datetime(vec, utc=True) + + elif both_strs and vec.index(aware_val) < vec.index(naive_val): + msg = r"time data \"2020-01-01 00:00\" doesn't match format" + with pytest.raises(ValueError, match=msg): + to_datetime(vec) + with pytest.raises(ValueError, match=msg): + to_datetime(vec, utc=True) + + elif both_strs and vec.index(naive_val) < vec.index(aware_val): + msg = "unconverted data remains when parsing with format" + with pytest.raises(ValueError, match=msg): + to_datetime(vec) + with pytest.raises(ValueError, match=msg): + to_datetime(vec, utc=True) + + else: + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + to_datetime(vec) + + # No warning/error with utc=True + to_datetime(vec, utc=True) + + if both_strs: + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + to_datetime(vec, format="mixed") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + msg = "DatetimeIndex has mixed timezones" + with pytest.raises(TypeError, match=msg): + DatetimeIndex(vec) + else: + msg = "Cannot mix tz-aware with tz-naive values" + if naive_first and isinstance(aware_val, Timestamp): + if isinstance(naive_val, Timestamp): + msg = "Tz-aware datetime.datetime cannot be converted to datetime64" + with pytest.raises(ValueError, match=msg): + to_datetime(vec, format="mixed") + with pytest.raises(ValueError, match=msg): + DatetimeIndex(vec) + else: + with pytest.raises(ValueError, match=msg): + to_datetime(vec, format="mixed") + with pytest.raises(ValueError, match=msg): + DatetimeIndex(vec) diff --git a/shared/package-files/78/7822f7d149acbac0618efa880903664e86b56894cc2fc7d76afd4bd49e9bec55/blob b/shared/package-files/78/7822f7d149acbac0618efa880903664e86b56894cc2fc7d76afd4bd49e9bec55/blob new file mode 100644 index 0000000000000000000000000000000000000000..374c4fb50eaae54a9884015c124c245385e1761e --- /dev/null +++ b/shared/package-files/78/7822f7d149acbac0618efa880903664e86b56894cc2fc7d76afd4bd49e9bec55/blob @@ -0,0 +1,504 @@ +import itertools as it + +from sympy.core.expr import unchanged +from sympy.core.function import Function +from sympy.core.numbers import I, oo, Rational +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.external import import_module +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.integers import floor, ceiling +from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min, + Max, real_root, Rem) +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.functions.special.delta_functions import Heaviside + +from sympy.utilities.lambdify import lambdify +from sympy.testing.pytest import raises, skip, ignore_warnings + +def test_Min(): + from sympy.abc import x, y, z + n = Symbol('n', negative=True) + n_ = Symbol('n_', negative=True) + nn = Symbol('nn', nonnegative=True) + nn_ = Symbol('nn_', nonnegative=True) + p = Symbol('p', positive=True) + p_ = Symbol('p_', positive=True) + np = Symbol('np', nonpositive=True) + np_ = Symbol('np_', nonpositive=True) + r = Symbol('r', real=True) + + assert Min(5, 4) == 4 + assert Min(-oo, -oo) is -oo + assert Min(-oo, n) is -oo + assert Min(n, -oo) is -oo + assert Min(-oo, np) is -oo + assert Min(np, -oo) is -oo + assert Min(-oo, 0) is -oo + assert Min(0, -oo) is -oo + assert Min(-oo, nn) is -oo + assert Min(nn, -oo) is -oo + assert Min(-oo, p) is -oo + assert Min(p, -oo) is -oo + assert Min(-oo, oo) is -oo + assert Min(oo, -oo) is -oo + assert Min(n, n) == n + assert unchanged(Min, n, np) + assert Min(np, n) == Min(n, np) + assert Min(n, 0) == n + assert Min(0, n) == n + assert Min(n, nn) == n + assert Min(nn, n) == n + assert Min(n, p) == n + assert Min(p, n) == n + assert Min(n, oo) == n + assert Min(oo, n) == n + assert Min(np, np) == np + assert Min(np, 0) == np + assert Min(0, np) == np + assert Min(np, nn) == np + assert Min(nn, np) == np + assert Min(np, p) == np + assert Min(p, np) == np + assert Min(np, oo) == np + assert Min(oo, np) == np + assert Min(0, 0) == 0 + assert Min(0, nn) == 0 + assert Min(nn, 0) == 0 + assert Min(0, p) == 0 + assert Min(p, 0) == 0 + assert Min(0, oo) == 0 + assert Min(oo, 0) == 0 + assert Min(nn, nn) == nn + assert unchanged(Min, nn, p) + assert Min(p, nn) == Min(nn, p) + assert Min(nn, oo) == nn + assert Min(oo, nn) == nn + assert Min(p, p) == p + assert Min(p, oo) == p + assert Min(oo, p) == p + assert Min(oo, oo) is oo + + assert Min(n, n_).func is Min + assert Min(nn, nn_).func is Min + assert Min(np, np_).func is Min + assert Min(p, p_).func is Min + + # lists + assert Min() is S.Infinity + assert Min(x) == x + assert Min(x, y) == Min(y, x) + assert Min(x, y, z) == Min(z, y, x) + assert Min(x, Min(y, z)) == Min(z, y, x) + assert Min(x, Max(y, -oo)) == Min(x, y) + assert Min(p, oo, n, p, p, p_) == n + assert Min(p_, n_, p) == n_ + assert Min(n, oo, -7, p, p, 2) == Min(n, -7) + assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_) + assert Min(0, x, 1, y) == Min(0, x, y) + assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100) + assert unchanged(Min, sin(x), cos(x)) + assert Min(sin(x), cos(x)) == Min(cos(x), sin(x)) + assert Min(cos(x), sin(x)).subs(x, 1) == cos(1) + assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half) + raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I)) + raises(ValueError, lambda: Min(I)) + raises(ValueError, lambda: Min(I, x)) + raises(ValueError, lambda: Min(S.ComplexInfinity, x)) + + assert Min(1, x).diff(x) == Heaviside(1 - x) + assert Min(x, 1).diff(x) == Heaviside(1 - x) + assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \ + - 2*Heaviside(2*x + Min(0, -x) - 1) + + # issue 7619 + f = Function('f') + assert Min(1, 2*Min(f(1), 2)) # doesn't fail + + # issue 7233 + e = Min(0, x) + assert e.n().args == (0, x) + + # issue 8643 + m = Min(n, p_, n_, r) + assert m.is_positive is False + assert m.is_nonnegative is False + assert m.is_negative is True + + m = Min(p, p_) + assert m.is_positive is True + assert m.is_nonnegative is True + assert m.is_negative is False + + m = Min(p, nn_, p_) + assert m.is_positive is None + assert m.is_nonnegative is True + assert m.is_negative is False + + m = Min(nn, p, r) + assert m.is_positive is None + assert m.is_nonnegative is None + assert m.is_negative is None + + +def test_Max(): + from sympy.abc import x, y, z + n = Symbol('n', negative=True) + n_ = Symbol('n_', negative=True) + nn = Symbol('nn', nonnegative=True) + p = Symbol('p', positive=True) + p_ = Symbol('p_', positive=True) + r = Symbol('r', real=True) + + assert Max(5, 4) == 5 + + # lists + + assert Max() is S.NegativeInfinity + assert Max(x) == x + assert Max(x, y) == Max(y, x) + assert Max(x, y, z) == Max(z, y, x) + assert Max(x, Max(y, z)) == Max(z, y, x) + assert Max(x, Min(y, oo)) == Max(x, y) + assert Max(n, -oo, n_, p, 2) == Max(p, 2) + assert Max(n, -oo, n_, p) == p + assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p) + assert Max(0, x, 1, y) == Max(1, x, y) + assert Max(r, r + 1, r - 1) == 1 + r + assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000) + assert Max(cos(x), sin(x)) == Max(sin(x), cos(x)) + assert Max(cos(x), sin(x)).subs(x, 1) == sin(1) + assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half) + raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I)) + raises(ValueError, lambda: Max(I)) + raises(ValueError, lambda: Max(I, x)) + raises(ValueError, lambda: Max(S.ComplexInfinity, 1)) + assert Max(n, -oo, n_, p, 2) == Max(p, 2) + assert Max(n, -oo, n_, p, 1000) == Max(p, 1000) + + assert Max(1, x).diff(x) == Heaviside(x - 1) + assert Max(x, 1).diff(x) == Heaviside(x - 1) + assert Max(x**2, 1 + x, 1).diff(x) == \ + 2*x*Heaviside(x**2 - Max(1, x + 1)) \ + + Heaviside(x - Max(1, x**2) + 1) + + e = Max(0, x) + assert e.n().args == (0, x) + + # issue 8643 + m = Max(p, p_, n, r) + assert m.is_positive is True + assert m.is_nonnegative is True + assert m.is_negative is False + + m = Max(n, n_) + assert m.is_positive is False + assert m.is_nonnegative is False + assert m.is_negative is True + + m = Max(n, n_, r) + assert m.is_positive is None + assert m.is_nonnegative is None + assert m.is_negative is None + + m = Max(n, nn, r) + assert m.is_positive is None + assert m.is_nonnegative is True + assert m.is_negative is False + + +def test_minmax_assumptions(): + r = Symbol('r', real=True) + a = Symbol('a', real=True, algebraic=True) + t = Symbol('t', real=True, transcendental=True) + q = Symbol('q', rational=True) + p = Symbol('p', irrational=True) + n = Symbol('n', rational=True, integer=False) + i = Symbol('i', integer=True) + o = Symbol('o', odd=True) + e = Symbol('e', even=True) + k = Symbol('k', prime=True) + reals = [r, a, t, q, p, n, i, o, e, k] + + for ext in (Max, Min): + for x, y in it.product(reals, repeat=2): + + # Must be real + assert ext(x, y).is_real + + # Algebraic? + if x.is_algebraic and y.is_algebraic: + assert ext(x, y).is_algebraic + elif x.is_transcendental and y.is_transcendental: + assert ext(x, y).is_transcendental + else: + assert ext(x, y).is_algebraic is None + + # Rational? + if x.is_rational and y.is_rational: + assert ext(x, y).is_rational + elif x.is_irrational and y.is_irrational: + assert ext(x, y).is_irrational + else: + assert ext(x, y).is_rational is None + + # Integer? + if x.is_integer and y.is_integer: + assert ext(x, y).is_integer + elif x.is_noninteger and y.is_noninteger: + assert ext(x, y).is_noninteger + else: + assert ext(x, y).is_integer is None + + # Odd? + if x.is_odd and y.is_odd: + assert ext(x, y).is_odd + elif x.is_odd is False and y.is_odd is False: + assert ext(x, y).is_odd is False + else: + assert ext(x, y).is_odd is None + + # Even? + if x.is_even and y.is_even: + assert ext(x, y).is_even + elif x.is_even is False and y.is_even is False: + assert ext(x, y).is_even is False + else: + assert ext(x, y).is_even is None + + # Prime? + if x.is_prime and y.is_prime: + assert ext(x, y).is_prime + elif x.is_prime is False and y.is_prime is False: + assert ext(x, y).is_prime is False + else: + assert ext(x, y).is_prime is None + + +def test_issue_8413(): + x = Symbol('x', real=True) + # we can't evaluate in general because non-reals are not + # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError + assert Min(floor(x), x) == floor(x) + assert Min(ceiling(x), x) == x + assert Max(floor(x), x) == x + assert Max(ceiling(x), x) == ceiling(x) + + +def test_root(): + from sympy.abc import x + n = Symbol('n', integer=True) + k = Symbol('k', integer=True) + + assert root(2, 2) == sqrt(2) + assert root(2, 1) == 2 + assert root(2, 3) == 2**Rational(1, 3) + assert root(2, 3) == cbrt(2) + assert root(2, -5) == 2**Rational(4, 5)/2 + + assert root(-2, 1) == -2 + + assert root(-2, 2) == sqrt(2)*I + assert root(-2, 1) == -2 + + assert root(x, 2) == sqrt(x) + assert root(x, 1) == x + assert root(x, 3) == x**Rational(1, 3) + assert root(x, 3) == cbrt(x) + assert root(x, -5) == x**Rational(-1, 5) + + assert root(x, n) == x**(1/n) + assert root(x, -n) == x**(-1/n) + + assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n) + + +def test_real_root(): + assert real_root(-8, 3) == -2 + assert real_root(-16, 4) == root(-16, 4) + r = root(-7, 4) + assert real_root(r) == r + r1 = root(-1, 3) + r2 = r1**2 + r3 = root(-1, 4) + assert real_root(r1 + r2 + r3) == -1 + r2 + r3 + assert real_root(root(-2, 3)) == -root(2, 3) + assert real_root(-8., 3) == -2.0 + x = Symbol('x') + n = Symbol('n') + g = real_root(x, n) + assert g.subs({"x": -8, "n": 3}) == -2 + assert g.subs({"x": 8, "n": 3}) == 2 + # give principle root if there is no real root -- if this is not desired + # then maybe a Root class is needed to raise an error instead + assert g.subs({"x": I, "n": 3}) == cbrt(I) + assert g.subs({"x": -8, "n": 2}) == sqrt(-8) + assert g.subs({"x": I, "n": 2}) == sqrt(I) + + +def test_issue_11463(): + numpy = import_module('numpy') + if not numpy: + skip("numpy not installed.") + x = Symbol('x') + f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy') + # numpy.select evaluates all options before considering conditions, + # so it raises a warning about root of negative number which does + # not affect the outcome. This warning is suppressed here + with ignore_warnings(RuntimeWarning): + assert f(numpy.array(-1)) < -1 + + +def test_rewrite_MaxMin_as_Heaviside(): + from sympy.abc import x + assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x) + assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \ + 3*Heaviside(-x + 3) + assert Max(0, x+2, 2*x).rewrite(Heaviside) == \ + 2*x*Heaviside(2*x)*Heaviside(x - 2) + \ + (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2) + + assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x) + assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \ + 3*Heaviside(x - 3) + assert Min(x, -x, -2).rewrite(Heaviside) == \ + x*Heaviside(-2*x)*Heaviside(-x - 2) - \ + x*Heaviside(2*x)*Heaviside(x - 2) \ + - 2*Heaviside(-x + 2)*Heaviside(x + 2) + + +def test_rewrite_MaxMin_as_Piecewise(): + from sympy.core.symbol import symbols + from sympy.functions.elementary.piecewise import Piecewise + x, y, z, a, b = symbols('x y z a b', real=True) + vx, vy, va = symbols('vx vy va') + assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True)) + assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True)) + assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)), + (b, (b >= x) & (b >= y)), (x, x >= y), (y, True)) + assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True)) + assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True)) + assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)), + (b, (b <= x) & (b <= y)), (x, x <= y), (y, True)) + + # Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments + assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True)) + assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True)) + + +def test_issue_11099(): + from sympy.abc import x, y + # some fixed value tests + fixed_test_data = {x: -2, y: 3} + assert Min(x, y).evalf(subs=fixed_test_data) == \ + Min(x, y).subs(fixed_test_data).evalf() + assert Max(x, y).evalf(subs=fixed_test_data) == \ + Max(x, y).subs(fixed_test_data).evalf() + # randomly generate some test data + from sympy.core.random import randint + for i in range(20): + random_test_data = {x: randint(-100, 100), y: randint(-100, 100)} + assert Min(x, y).evalf(subs=random_test_data) == \ + Min(x, y).subs(random_test_data).evalf() + assert Max(x, y).evalf(subs=random_test_data) == \ + Max(x, y).subs(random_test_data).evalf() + + +def test_issue_12638(): + from sympy.abc import a, b, c + assert Min(a, b, c, Max(a, b)) == Min(a, b, c) + assert Min(a, b, Max(a, b, c)) == Min(a, b) + assert Min(a, b, Max(a, c)) == Min(a, b) + +def test_issue_21399(): + from sympy.abc import a, b, c + assert Max(Min(a, b), Min(a, b, c)) == Min(a, b) + + +def test_instantiation_evaluation(): + from sympy.abc import v, w, x, y, z + assert Min(1, Max(2, x)) == 1 + assert Max(3, Min(2, x)) == 3 + assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z)) + assert set(Min(Max(w, x), Max(y, z)).args) == { + Max(w, x), Max(y, z)} + assert Min(Max(x, y), Max(x, z), w) == Min( + w, Max(x, Min(y, z))) + A, B = Min, Max + for i in range(2): + assert A(x, B(x, y)) == x + assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z))) + A, B = B, A + assert Min(w, Max(x, y), Max(v, x, z)) == Min( + w, Max(x, Min(y, Max(v, z)))) + +def test_rewrite_as_Abs(): + from itertools import permutations + from sympy.functions.elementary.complexes import Abs + from sympy.abc import x, y, z, w + def test(e): + free = e.free_symbols + a = e.rewrite(Abs) + assert not a.has(Min, Max) + for i in permutations(range(len(free))): + reps = dict(zip(free, i)) + assert a.xreplace(reps) == e.xreplace(reps) + test(Min(x, y)) + test(Max(x, y)) + test(Min(x, y, z)) + test(Min(Max(w, x), Max(y, z))) + +def test_issue_14000(): + assert isinstance(sqrt(4, evaluate=False), Pow) == True + assert isinstance(cbrt(3.5, evaluate=False), Pow) == True + assert isinstance(root(16, 4, evaluate=False), Pow) == True + + assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False) + assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False) + assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False) + + assert root(16, 4, 2, evaluate=False).has(Pow) == True + assert real_root(-8, 3, evaluate=False).has(Pow) == True + +def test_issue_6899(): + from sympy.core.function import Lambda + x = Symbol('x') + eqn = Lambda(x, x) + assert eqn.func(*eqn.args) == eqn + +def test_Rem(): + from sympy.abc import x, y + assert Rem(5, 3) == 2 + assert Rem(-5, 3) == -2 + assert Rem(5, -3) == 2 + assert Rem(-5, -3) == -2 + assert Rem(x**3, y) == Rem(x**3, y) + assert Rem(Rem(-5, 3) + 3, 3) == 1 + + +def test_minmax_no_evaluate(): + from sympy import evaluate + p = Symbol('p', positive=True) + + assert Max(1, 3) == 3 + assert Max(1, 3).args == () + assert Max(0, p) == p + assert Max(0, p).args == () + assert Min(0, p) == 0 + assert Min(0, p).args == () + + assert Max(1, 3, evaluate=False) != 3 + assert Max(1, 3, evaluate=False).args == (1, 3) + assert Max(0, p, evaluate=False) != p + assert Max(0, p, evaluate=False).args == (0, p) + assert Min(0, p, evaluate=False) != 0 + assert Min(0, p, evaluate=False).args == (0, p) + + with evaluate(False): + assert Max(1, 3) != 3 + assert Max(1, 3).args == (1, 3) + assert Max(0, p) != p + assert Max(0, p).args == (0, p) + assert Min(0, p) != 0 + assert Min(0, p).args == (0, p) diff --git a/shared/package-files/78/78232f6b051ce6f559b04ae2ee2f1792a6e94e61c9c3c1233e2c4e2de0645f5f/blob b/shared/package-files/78/78232f6b051ce6f559b04ae2ee2f1792a6e94e61c9c3c1233e2c4e2de0645f5f/blob new file mode 100644 index 0000000000000000000000000000000000000000..aff9481390a752be6333a64f552a20e019b8174f --- /dev/null +++ b/shared/package-files/78/78232f6b051ce6f559b04ae2ee2f1792a6e94e61c9c3c1233e2c4e2de0645f5f/blob @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///tmp/build/80754af9/pexpect_1605563209008/work"} \ No newline at end of file diff --git a/shared/package-files/78/7824518ed8f5ef15fda47d0b4d70b75477e3afc75feceeca26165cc408cb57c9/blob b/shared/package-files/78/7824518ed8f5ef15fda47d0b4d70b75477e3afc75feceeca26165cc408cb57c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..f9c267587b444d5259814554fffd0f473188032e --- /dev/null +++ b/shared/package-files/78/7824518ed8f5ef15fda47d0b4d70b75477e3afc75feceeca26165cc408cb57c9/blob @@ -0,0 +1,23 @@ +*** Thu, 28 Jul 2016 16:41:32 *** +FORECASTING +Reference: Lütkepohl (1993), IMTSA, 2ed, ch. 5.2.6, ch. 10.5 +CI coverage: 0.95 +forecast horizon: 5 periods +using standard confidence intervals + + Dp +time forecast lower CI upper CI +/- +1999 Q1 -0.0175 -0.0293 -0.0058 0.0117 +1999 Q2 -0.0035 -0.0156 0.0086 0.0121 +1999 Q3 0.0010 -0.0115 0.0136 0.0125 +1999 Q4 0.0216 0.0090 0.0342 0.0126 +2000 Q1 -0.0176 -0.0342 -0.0010 0.0166 + + R +time forecast lower CI upper CI +/- +1999 Q1 0.0393 0.0292 0.0495 0.0102 +1999 Q2 0.0402 0.0248 0.0556 0.0154 +1999 Q3 0.0411 0.0220 0.0602 0.0191 +1999 Q4 0.0411 0.0181 0.0641 0.0230 +2000 Q1 0.0423 0.0159 0.0688 0.0264 + diff --git a/shared/package-files/78/7824a79d8e2c72d81ea95c03bfd3eb1fa8e9308e399c93e6033e2b7e36cfb1ff/blob b/shared/package-files/78/7824a79d8e2c72d81ea95c03bfd3eb1fa8e9308e399c93e6033e2b7e36cfb1ff/blob new file mode 100644 index 0000000000000000000000000000000000000000..3f5746a5b057e76b1bf7b33c2892de1640919519 --- /dev/null +++ b/shared/package-files/78/7824a79d8e2c72d81ea95c03bfd3eb1fa8e9308e399c93e6033e2b7e36cfb1ff/blob @@ -0,0 +1,34 @@ +import atexit + + +def _encode_string(s): + encoded = s.encode('utf-8') + return encoded + + +def _decode_string(b): + return b.decode('utf-8') + + +_encode_string.__doc__ = """Encode a string for use by LLVM.""" +_decode_string.__doc__ = """Decode a LLVM character (byte)string.""" + + +_shutting_down = [False] + + +def _at_shutdown(): + _shutting_down[0] = True + + +atexit.register(_at_shutdown) + + +def _is_shutting_down(_shutting_down=_shutting_down): + """ + Whether the interpreter is currently shutting down. + For use in finalizers, __del__ methods, and similar; it is advised + to early bind this function rather than look it up when calling it, + since at shutdown module globals may be cleared. + """ + return _shutting_down[0] diff --git a/shared/package-files/78/7824b3163e7fdaf47a9f9aaed6b1c4e3ac2f49519971d56acfce68bf8d19b07f/blob b/shared/package-files/78/7824b3163e7fdaf47a9f9aaed6b1c4e3ac2f49519971d56acfce68bf8d19b07f/blob new file mode 100644 index 0000000000000000000000000000000000000000..e13b7aade323933472751664088c68a682cecf6e --- /dev/null +++ b/shared/package-files/78/7824b3163e7fdaf47a9f9aaed6b1c4e3ac2f49519971d56acfce68bf8d19b07f/blob @@ -0,0 +1,3 @@ +# Seaborn colorblind palette +axes.prop_cycle: cycler('color', ['0072B2', '009E73', 'D55E00', 'CC79A7', 'F0E442', '56B4E9']) +patch.facecolor: 0072B2 diff --git a/shared/package-files/78/78251aeca890c7a16ef5a9fbcf42a753881b84287cd26e02da7a4bea60b353b9/blob b/shared/package-files/78/78251aeca890c7a16ef5a9fbcf42a753881b84287cd26e02da7a4bea60b353b9/blob new file mode 100644 index 0000000000000000000000000000000000000000..35ff5c8d16b86f2303115aaa39ba8fb81cbe0889 --- /dev/null +++ b/shared/package-files/78/78251aeca890c7a16ef5a9fbcf42a753881b84287cd26e02da7a4bea60b353b9/blob @@ -0,0 +1,372 @@ +""" +Results from Matlab and R +""" +import numpy as np + + +class DescStatRes: + """ + + The results were generated from Bruce Hansen's + MATLAb package: + + Bruce E. Hansen + Department of Economics + Social Science Building + University of Wisconsin + Madison, WI 53706-1393 + bhansen@ssc.wisc.edu + http://www.ssc.wisc.edu/~bhansen/ + + The R results are from Mai Zhou's emplik package + """ + + def __init__(self): + self.ci_mean = (13.556709, 14.559394) + self.test_mean_14 = (.080675, .776385) + self.test_mean_weights = np.array([[0.01969213], + [0.01911859], + [0.01973982], + [0.01982913], + [0.02004183], + [0.0195765], + [0.01970423], + [0.02015074], + [0.01898431], + [0.02067787], + [0.01878104], + [0.01920531], + [0.01981207], + [0.02031582], + [0.01857329], + [0.01907883], + [0.01943674], + [0.0210042], + [0.0197373], + [0.01997998], + [0.0199233], + [0.01986713], + [0.02017751], + [0.01962176], + [0.0214596], + [0.02118228], + [0.02013767], + [0.01918665], + [0.01908886], + [0.01943081], + [0.01916251], + [0.01868129], + [0.01918334], + [0.01969084], + [0.01984322], + [0.0198977], + [0.02098504], + [0.02132222], + [0.02100581], + [0.01970351], + [0.01942184], + [0.01979781], + [0.02114276], + [0.02096136], + [0.01999804], + [0.02044712], + [0.02174404], + [0.02189933], + [0.02077078], + [0.02082612]]).squeeze() + self.test_var_3 = (.199385, .655218) + self.ci_var = (2.290077, 4.423634) + self.test_var_weights = np.array([[0.020965], + [0.019686], + [0.021011], + [0.021073], + [0.021089], + [0.020813], + [0.020977], + [0.021028], + [0.019213], + [0.02017], + [0.018397], + [0.01996], + [0.021064], + [0.020854], + [0.017463], + [0.019552], + [0.020555], + [0.019283], + [0.021009], + [0.021103], + [0.021102], + [0.021089], + [0.021007], + [0.020879], + [0.017796], + [0.018726], + [0.021038], + [0.019903], + [0.019587], + [0.020543], + [0.019828], + [0.017959], + [0.019893], + [0.020963], + [0.02108], + [0.021098], + [0.01934], + [0.018264], + [0.019278], + [0.020977], + [0.020523], + [0.021055], + [0.018853], + [0.019411], + [0.0211], + [0.02065], + [0.016803], + [0.016259], + [0.019939], + [0.019793]]).squeeze() + self.mv_test_mean = (.7002663, .7045943) + self.mv_test_mean_wts = np.array([[0.01877015], + [0.01895746], + [0.01817092], + [0.01904308], + [0.01707106], + [0.01602806], + [0.0194296], + [0.01692204], + [0.01978322], + [0.01881313], + [0.02011785], + [0.0226274], + [0.01953733], + [0.01874346], + [0.01694224], + [0.01611816], + [0.02297437], + [0.01943187], + [0.01899873], + [0.02113375], + [0.02295293], + [0.02043509], + [0.02276583], + [0.02208274], + [0.02466621], + [0.02287983], + [0.0173136], + [0.01905693], + [0.01909335], + [0.01982534], + [0.01924093], + [0.0179352], + [0.01871907], + [0.01916633], + [0.02022359], + [0.02228696], + [0.02080555], + [0.01725214], + [0.02166185], + [0.01798537], + [0.02103582], + [0.02052757], + [0.03096074], + [0.01966538], + [0.02201629], + [0.02094854], + [0.02127771], + [0.01961964], + [0.02023756], + [0.01774807]]).squeeze() + self.test_skew = (2.498418, .113961) + self.test_skew_wts = np.array([[0.016698], + [0.01564], + [0.01701], + [0.017675], + [0.019673], + [0.016071], + [0.016774], + [0.020902], + [0.016397], + [0.027359], + [0.019136], + [0.015419], + [0.01754], + [0.022965], + [0.027203], + [0.015805], + [0.015565], + [0.028518], + [0.016992], + [0.019034], + [0.018489], + [0.01799], + [0.021222], + [0.016294], + [0.022725], + [0.027133], + [0.020748], + [0.015452], + [0.015759], + [0.01555], + [0.015506], + [0.021863], + [0.015459], + [0.01669], + [0.017789], + [0.018257], + [0.028578], + [0.025151], + [0.028512], + [0.01677], + [0.015529], + [0.01743], + [0.027563], + [0.028629], + [0.019216], + [0.024677], + [0.017376], + [0.014739], + [0.028112], + [0.02842]]).squeeze() + self.test_kurt_0 = (1.904269, .167601) + self.test_corr = (.012025, .912680,) + self.test_corr_weights = np.array([[0.020037], + [0.020108], + [0.020024], + [0.02001], + [0.019766], + [0.019971], + [0.020013], + [0.019663], + [0.019944], + [0.01982], + [0.01983], + [0.019436], + [0.020005], + [0.019897], + [0.020768], + [0.020468], + [0.019521], + [0.019891], + [0.020024], + [0.01997], + [0.019824], + [0.019976], + [0.019979], + [0.019753], + [0.020814], + [0.020474], + [0.019751], + [0.020085], + [0.020087], + [0.019977], + [0.020057], + [0.020435], + [0.020137], + [0.020025], + [0.019982], + [0.019866], + [0.020151], + [0.019046], + [0.020272], + [0.020034], + [0.019813], + [0.01996], + [0.020657], + [0.019947], + [0.019931], + [0.02008], + [0.02035], + [0.019823], + [0.02005], + [0.019497]]).squeeze() + self.test_joint_skew_kurt = (8.753952, .012563) + + +class RegressionResults: + """ + Results for EL Regression + """ + def __init__(self): + self.source = "Matlab" + self.test_beta0 = (1.758104, .184961, np.array([ + 0.04326392, 0.04736749, 0.03573865, 0.04770535, 0.04721684, + 0.04718301, 0.07088816, 0.05631242, 0.04865098, 0.06572099, + 0.04016013, 0.04438627, 0.04042288, 0.03938043, 0.04006474, + 0.04845233, 0.01991985, 0.03623254, 0.03617999, 0.05607242, + 0.0886806])) + + self.test_beta1 = (1.932529, .164482, np.array([ + 0.033328, 0.051412, 0.03395, 0.071695, 0.046433, 0.041303, + 0.033329, 0.036413, 0.03246, 0.037776, 0.043872, 0.037507, + 0.04762, 0.04881, 0.05874, 0.049553, 0.048898, 0.04512, + 0.041142, 0.048121, 0.11252])) + + self.test_beta2 = (.494593, .481866, np.array([ + 0.046287, 0.048632, 0.048772, 0.034769, 0.048416, 0.052447, + 0.053336, 0.050112, 0.056053, 0.049318, 0.053609, 0.055634, + 0.042188, 0.046519, 0.048415, 0.047897, 0.048673, 0.047695, + 0.047503, 0.047447, 0.026279])) + + self.test_beta3 = (3.537250, .060005, np.array([ + 0.036327, 0.070483, 0.048965, 0.087399, 0.041685, 0.036221, + 0.016752, 0.019585, 0.027467, 0.02957, 0.069204, 0.060167, + 0.060189, 0.030007, 0.067371, 0.046862, 0.069814, 0.053041, + 0.053362, 0.041585, 0.033943])) + + self.test_ci_beta0 = (-52.77128837058528, -24.11607348661947) + + self.test_ci_beta1 = (0.41969831751229664, 0.9857167306604057) + + self.test_ci_beta2 = (0.6012045929381431, 2.1847079367275692) + + self.test_ci_beta3 = (-0.3804313225443794, 0.006934528877337928) + + +class ANOVAResults: + """ + Results for ANOVA + """ + def __init__(self): + self.source = "Matlab" + self.compute_ANOVA = (.426163, .51387, np.array([9.582371]), np.array([ + 0.018494, 0.01943, 0.016624, 0.0172, 0.016985, 0.01922, + 0.016532, 0.015985, 0.016769, 0.017631, 0.017677, 0.017984, + 0.017049, 0.016721, 0.016382, 0.016566, 0.015642, 0.015894, + 0.016282, 0.015704, 0.016272, 0.015678, 0.015651, 0.015648, + 0.015618, 0.015726, 0.015981, 0.01635, 0.01586, 0.016443, + 0.016126, 0.01683, 0.01348, 0.017391, 0.011225, 0.017282, + 0.015568, 0.017543, 0.017009, 0.016325, 0.012841, 0.017648, + 0.01558, 0.015994, 0.017258, 0.017664, 0.017792, 0.017772, + 0.017527, 0.017797, 0.017856, 0.017849, 0.017749, 0.017827, + 0.017381, 0.017902, 0.016557, 0.015522, 0.017455, 0.017248])) + + +class AFTRes: + """ + Results for the AFT model from package emplik in R written by Mai Zhou + """ + def __init__(self): + self.test_params = np.array([3.77710799, -0.03281745]) + self.test_beta0 = (.132511, 0.7158323) + self.test_beta1 = (.297951, .5851693) + self.test_joint = (11.8068, 0.002730147) + + +class OriginResults: + """ + These results are from Bruce Hansen's Matlab package. + To replicate the results, the exogenous variables were scaled + down by 10**-2 and the results were then rescaled. + + These tests must also test likelihood functions because the + llr when conducting hypothesis tests is the MLE while + restricting the intercept to 0. Matlab's generic package always + uses the unrestricted MLE. + """ + def __init__(self): + self.test_params = np.array([0, .00351861]) + self.test_llf = -1719.793173 # llf when testing param = .0034 + self.test_llf_hat = -1717.95833 # llf when origin=0 + self.test_llf_hypoth = -2*(self.test_llf-self.test_llf_hat) + self.test_llf_conf = -1719.879077 # The likelihood func at conf_vals diff --git a/shared/package-files/78/78271e4f706c62fc006ec3c19822f20a5dfe36b33b79026de16139cd998ad8b9/blob b/shared/package-files/78/78271e4f706c62fc006ec3c19822f20a5dfe36b33b79026de16139cd998ad8b9/blob new file mode 100644 index 0000000000000000000000000000000000000000..461040d119312e63772566efb22e281c8309e304 --- /dev/null +++ b/shared/package-files/78/78271e4f706c62fc006ec3c19822f20a5dfe36b33b79026de16139cd998ad8b9/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor & exponential_(at::Tensor & self, double lambd=1, c10::optional generator=c10::nullopt); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/78/782b59fc8e5727623e594516b345284c5760021afd1cab1572614426c237e340/blob b/shared/package-files/78/782b59fc8e5727623e594516b345284c5760021afd1cab1572614426c237e340/blob new file mode 100644 index 0000000000000000000000000000000000000000..bf0a291c390078574c311bc6c7c82d5092d6dc7f --- /dev/null +++ b/shared/package-files/78/782b59fc8e5727623e594516b345284c5760021afd1cab1572614426c237e340/blob @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace c10 { +struct C10_API TempFile { + TempFile(std::string_view name, int fd = -1) noexcept : fd(fd), name(name) {} + TempFile(const TempFile&) = delete; + TempFile(TempFile&& other) noexcept + : fd(other.fd), name(std::move(other.name)) { + other.fd = -1; + } + + TempFile& operator=(const TempFile&) = delete; + TempFile& operator=(TempFile&& other) noexcept { + fd = other.fd; + name = std::move(other.name); + other.fd = -1; + return *this; + } +#if defined(_WIN32) + bool open(); +#endif + + ~TempFile(); + + int fd; + + std::string name; +}; + +struct C10_API TempDir { + TempDir() = delete; + explicit TempDir(std::string_view name) noexcept : name(name) {} + TempDir(const TempDir&) = delete; + TempDir(TempDir&& other) noexcept : name(std::move(other.name)) { + other.name.clear(); + } + + TempDir& operator=(const TempDir&) = delete; + TempDir& operator=(TempDir&& other) noexcept { + name = std::move(other.name); + return *this; + } + + ~TempDir(); + + std::string name; +}; + +/// Attempts to return a temporary file or returns `nullopt` if an error +/// occurred. +/// +/// The file returned follows the pattern +/// `/`, where `` is the value of +/// the `"TMPDIR"`, `"TMP"`, `"TEMP"` or +/// `"TEMPDIR"` environment variable if any is set, or otherwise `/tmp`; +/// `` is the value supplied to this function, and +/// `` is a random sequence of numbers. +/// On Windows, `name_prefix` is ignored and `tmpnam_s` is used, +/// and no temporary file is opened. +C10_API std::optional try_make_tempfile( + std::string_view name_prefix = "torch-file-"); + +/// Like `try_make_tempfile`, but throws an exception if a temporary file could +/// not be returned. +C10_API TempFile make_tempfile(std::string_view name_prefix = "torch-file-"); + +/// Attempts to return a temporary directory or returns `nullopt` if an error +/// occurred. +/// +/// The directory returned follows the pattern +/// `//`, where `` is the value +/// of the `"TMPDIR"`, `"TMP"`, `"TEMP"` or +/// `"TEMPDIR"` environment variable if any is set, or otherwise `/tmp`; +/// `` is the value supplied to this function, and +/// `` is a random sequence of numbers. +/// On Windows, `name_prefix` is ignored. +C10_API std::optional try_make_tempdir( + std::string_view name_prefix = "torch-dir-"); + +/// Like `try_make_tempdir`, but throws an exception if a temporary directory +/// could not be returned. +C10_API TempDir make_tempdir(std::string_view name_prefix = "torch-dir-"); +} // namespace c10 diff --git a/shared/package-files/78/782c3dbb5825eefcdff76b12c6a3bb5ab11cd2b8665415b9732754736aff7379/blob b/shared/package-files/78/782c3dbb5825eefcdff76b12c6a3bb5ab11cd2b8665415b9732754736aff7379/blob new file mode 100644 index 0000000000000000000000000000000000000000..502af374ff3d34218927b0d066b692d494a397d5 --- /dev/null +++ b/shared/package-files/78/782c3dbb5825eefcdff76b12c6a3bb5ab11cd2b8665415b9732754736aff7379/blob @@ -0,0 +1,12 @@ +#ifndef PROFILER_ITT_H +#define PROFILER_ITT_H +#include + +namespace torch::profiler { +TORCH_API bool itt_is_available(); +TORCH_API void itt_range_push(const char* msg); +TORCH_API void itt_range_pop(); +TORCH_API void itt_mark(const char* msg); +} // namespace torch::profiler + +#endif // PROFILER_ITT_H diff --git a/shared/package-files/78/782cbc9ad45c1f249989a58f576af6d432d9af39e3b51420823f32828426b36f/blob b/shared/package-files/78/782cbc9ad45c1f249989a58f576af6d432d9af39e3b51420823f32828426b36f/blob new file mode 100644 index 0000000000000000000000000000000000000000..649463383fdb62548b880d2d84624dd47ec938f0 --- /dev/null +++ b/shared/package-files/78/782cbc9ad45c1f249989a58f576af6d432d9af39e3b51420823f32828426b36f/blob @@ -0,0 +1,6 @@ +from __future__ import annotations + +from narwhals.testing.asserts.frame import assert_frame_equal +from narwhals.testing.asserts.series import assert_series_equal + +__all__ = ("assert_frame_equal", "assert_series_equal") diff --git a/shared/package-files/78/782d3eeddbd904249743018d3782f39d6cc90b6fd8d09026639d42557b3738ce/blob b/shared/package-files/78/782d3eeddbd904249743018d3782f39d6cc90b6fd8d09026639d42557b3738ce/blob new file mode 100644 index 0000000000000000000000000000000000000000..545f061d4993fded8e4b121ee2eea32160716861 Binary files /dev/null and b/shared/package-files/78/782d3eeddbd904249743018d3782f39d6cc90b6fd8d09026639d42557b3738ce/blob differ diff --git a/shared/package-files/78/7830d48bb67b1b7554f21ffaab867ade5ffb2f6ce073262e4c4df27fe192b7e2/blob b/shared/package-files/78/7830d48bb67b1b7554f21ffaab867ade5ffb2f6ce073262e4c4df27fe192b7e2/blob new file mode 100644 index 0000000000000000000000000000000000000000..2e46b9267f273b272d7b12f6754925adaa55385f --- /dev/null +++ b/shared/package-files/78/7830d48bb67b1b7554f21ffaab867ade5ffb2f6ce073262e4c4df27fe192b7e2/blob @@ -0,0 +1,8 @@ +from typing import Dict + +WEEKDAYS: Dict[int, str] +WEEKDAYS_ABBR: Dict[int, str] +MONTHS: Dict[int, str] +MONTHS_3: Dict[int, str] +MONTHS_AP: Dict[int, str] +MONTHS_ALT: Dict[int, str] diff --git a/shared/package-files/78/7831b013155cf59d5afb5cbf30c095f7a8c87246d9a919d12b50e1fb3753bd0e/blob b/shared/package-files/78/7831b013155cf59d5afb5cbf30c095f7a8c87246d9a919d12b50e1fb3753bd0e/blob new file mode 100644 index 0000000000000000000000000000000000000000..a64bc928cdfdcabd21608a46e32b2455ded975bf --- /dev/null +++ b/shared/package-files/78/7831b013155cf59d5afb5cbf30c095f7a8c87246d9a919d12b50e1fb3753bd0e/blob @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Useful utilities for working with the `mbox`_-formatted +mailboxes. Credit to Mark Williams for these. + +.. _mbox: https://en.wikipedia.org/wiki/Mbox +""" + +import mailbox +import tempfile + + +DEFAULT_MAXMEM = 4 * 1024 * 1024 # 4MB + + +class mbox_readonlydir(mailbox.mbox): + """A subclass of :class:`mailbox.mbox` suitable for use with mboxs + insides a read-only mail directory, e.g., ``/var/mail``. Otherwise + the API is exactly the same as the built-in mbox. + + Deletes messages via truncation, in the manner of `Heirloom mailx`_. + + Args: + path (str): Path to the mbox file. + factory (type): Message type (defaults to :class:`rfc822.Message`) + create (bool): Create mailbox if it does not exist. (defaults + to ``True``) + maxmem (int): Specifies, in bytes, the largest sized mailbox + to attempt to copy into memory. Larger mailboxes + will be copied incrementally which is more + hazardous. (defaults to 4MB) + + .. note:: + + Because this truncates and rewrites parts of the mbox file, + this class can corrupt your mailbox. Only use this if you know + the built-in :class:`mailbox.mbox` does not work for your use + case. + + .. _Heirloom mailx: http://heirloom.sourceforge.net/mailx.html + """ + def __init__(self, path, factory=None, create=True, maxmem=1024 * 1024): + mailbox.mbox.__init__(self, path, factory, create) + self.maxmem = maxmem + + def flush(self): + """Write any pending changes to disk. This is called on mailbox + close and is usually not called explicitly. + + .. note:: + + This deletes messages via truncation. Interruptions may + corrupt your mailbox. + """ + + # Appending and basic assertions are the same as in mailbox.mbox.flush. + if not self._pending: + if self._pending_sync: + # Messages have only been added, so syncing the file + # is enough. + mailbox._sync_flush(self._file) + self._pending_sync = False + return + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise mailbox.ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + + self._file.seek(0) + + # Truncation logic begins here. Mostly the same except we + # can use tempfile because we're not doing rename(2). + with tempfile.TemporaryFile() as new_file: + new_toc = {} + self._pre_mailbox_hook(new_file) + for key in sorted(self._toc.keys()): + start, stop = self._toc[key] + self._file.seek(start) + self._pre_message_hook(new_file) + new_start = new_file.tell() + while True: + buffer = self._file.read(min(4096, + stop - self._file.tell())) + if buffer == '': + break + new_file.write(buffer) + new_toc[key] = (new_start, new_file.tell()) + self._post_message_hook(new_file) + self._file_length = new_file.tell() + + self._file.seek(0) + new_file.seek(0) + + # Copy back our messages + if self._file_length <= self.maxmem: + self._file.write(new_file.read()) + else: + while True: + buffer = new_file.read(4096) + if not buffer: + break + self._file.write(buffer) + + # Delete the rest. + self._file.truncate() + + # Same wrap up. + self._toc = new_toc + self._pending = False + self._pending_sync = False + if self._locked: + mailbox._lock_file(self._file, dotlock=False) diff --git a/shared/package-files/78/7832a6c34f3d519d0cc5311b4d202d7766d6fd62247038138b0edefc2df8f781/blob b/shared/package-files/78/7832a6c34f3d519d0cc5311b4d202d7766d6fd62247038138b0edefc2df8f781/blob new file mode 100644 index 0000000000000000000000000000000000000000..df1996400a9b5ecf0c2362b894b6faacf0731423 --- /dev/null +++ b/shared/package-files/78/7832a6c34f3d519d0cc5311b4d202d7766d6fd62247038138b0edefc2df8f781/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _sparse_broadcast_to_copy_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size); +TORCH_API at::Tensor & _sparse_broadcast_to_copy_outf(const at::Tensor & self, at::IntArrayRef size, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/78/7832f16d7bbfe837f08f927516c391da41517f36403c16ce749dbc37de6cb8c6/blob b/shared/package-files/78/7832f16d7bbfe837f08f927516c391da41517f36403c16ce749dbc37de6cb8c6/blob new file mode 100644 index 0000000000000000000000000000000000000000..b71980858bfa1643e5b5919b9e26db8ec3c20b4c --- /dev/null +++ b/shared/package-files/78/7832f16d7bbfe837f08f927516c391da41517f36403c16ce749dbc37de6cb8c6/blob @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API quantile { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::optional, bool, c10::string_view); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantile") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation); +}; + +struct TORCH_API quantile_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::optional, bool, c10::string_view, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantile") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation, at::Tensor & out); +}; + +struct TORCH_API quantile_scalar { + using schema = at::Tensor (const at::Tensor &, double, c10::optional, bool, c10::string_view); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantile") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor") + static at::Tensor call(const at::Tensor & self, double q, c10::optional dim, bool keepdim, c10::string_view interpolation); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double q, c10::optional dim, bool keepdim, c10::string_view interpolation); +}; + +struct TORCH_API quantile_scalar_out { + using schema = at::Tensor & (const at::Tensor &, double, c10::optional, bool, c10::string_view, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::quantile") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "quantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, double q, c10::optional dim, bool keepdim, c10::string_view interpolation, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double q, c10::optional dim, bool keepdim, c10::string_view interpolation, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/783550b748d17fbe41c9090d7336aaef26d5bf98c8ccf3c8b1b0dc3fff164fd7/blob b/shared/package-files/78/783550b748d17fbe41c9090d7336aaef26d5bf98c8ccf3c8b1b0dc3fff164fd7/blob new file mode 100644 index 0000000000000000000000000000000000000000..2bbf43975eacc4453dc33ae561b1f5ff71bd36a1 --- /dev/null +++ b/shared/package-files/78/783550b748d17fbe41c9090d7336aaef26d5bf98c8ccf3c8b1b0dc3fff164fd7/blob @@ -0,0 +1,631 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +/* + * [Note: IListRef] + * Wrapper around different API containers (e.g. boxed and unboxed). + * + * What is it? + * =========== + * It is a tagged union of both boxed and unboxed API containers. + * Working implementations: + * + * - `IListRef` + * - `IListRef` + * + * Note that `IListRef` is a view type. Meaning that it won't own the + * tensors it holds. It's intended to be used only as argument parameters. + * Specifically, where these 2 worlds overlap. + * + * What is this for? + * ================= + * Historically, PyTorch has maintained 2 different APIs: the unboxed + * (called from C++ API and Python eager mode) and boxed APIs (called + * from the TorchScript JIT, mobile interpreter, and boxed fallbacks). + * + * Calling unboxed kernels from the boxed "world" and vice-versa may + * result in non-negligible overhead. Lists are one of those types: + * + * - Boxed world: `c10::List` + * - Unboxed world: `c10::ArrayRef` + * + * In this context, `c10::IListRef` solves this problem by wrapping those + * 2 container types, so that we don't need to convert from one to + * the other. + * + * (see https://github.com/pytorch/pytorch/issues/66328) + * + * What does it do? + * ================ + * This container wraps around the different tagged containers + * (currently, only boxed and unboxed), without incurring in extra + * overhead for converting from one to another. It does so while + * exposing usual container methods, which dispatch to corresponding + * implementations. + * + * While it works with different container types, it introduces + * overhead for repeatedly calling member functions (since those will + * get dispatched, again). Therefore, you should only use it to iterate + * through the list up to one time. If you need to do more complex things, + * call `materialize()` first. + * + * Adding support for a new Tag + * ============================ + * Suppose we want to add a new tag: `Chest`. Here are the steps + * we would have to go through: + * + * 1. Add a line for it in the macro `TORCH_ILISTREF_FORALL_TAGS`. + * + * #define TORCH_ILISTREF_FORALL_TAGS(_, ...) \ + * ... + * _(Chest, ##__VA_ARGS__) + * + * 2. Add type aliases, union members, and constructors. + * + * template + * class IListRef { + * ... + * using chest_type = + * typename detail::IListRefTagImpl::list_type; + * ... + * IListRef(...) : tag_(IListRefTag::Chest) { + * ... + * } + * ... + * union Payload { + * ... + * chest_type chest; + * ... + * }; + * ... + * }; + * + * 3. Add a default implementation for it (in 'IListRef_inl.h'). It's + * preferable to make the default implementation work for `T = Tensor` + * (both `Unboxed` and `Boxed` do it). + * + * template + * class IListRefTagImplBase { + * public: + * using elem_type = ListElemT; + * using list_type = ChestContainer; + * + * static const list_type& unwrap(const IListRef& ilist) { ... } + * + * static typename list_type::const_iterator& unwrap( + * IListRefIterator& it) { ... } + * + * static const typename list_type::const_iterator& unwrap( + * const IListRefIterator& it) { ... } + * + * static IListRefConstRef iterator_get( + * const typename list_type::const_iterator& it) { ... } + * } + * + * 4. Add an specialization for each of the already supported types. + * Finally, for consistency, add them to the tracking list. + * (see [Note: IListRefTagImpl Specializations]) + * + * template <> + * class IListRefTagImpl + * : public IListRefTagImplBase {}; + * + * Adding support for a new Type + * ============================= + * Suppose we want to add support for a new type: `Matrix`. + * Here are the steps we would have to go through: + * + * 1. Add an specialization for each of the existing tags. + * For consistency, add them to the tracking list. + * (see [Note: IListRefTagImpl Specializations]) + * + * template <> + * class IListRefTagImpl + * : public IListRefTagImplBase {}; + * + * template <> + * class IListRefTagImpl + * : public IListRefTagImplBase {}; + * + * Common Problems + * =============== + * 1. One of `IListRef(Iterator)` methods are failing to compile. + * + * That may be happening because the container type you added + * is not compatible with the code written for that method. If + * that's true, then you might have to transform that code into + * a static method call (see `List::operator[]` method). + * + * 2. Can't make `IListRefIterator::operator*` return a const-reference. + * + * First, keep in mind that we assume that boxed containers will + * have to deal with `IValue` (e.g. `c10::List`). In this context, + * what may be happening is that `IValue` doesn't store internally + * your type `T`. Instead, it constructs a type new `T` everytime + * you try to get `T` for it (see `IListRef`). + */ + +namespace c10 { +template +class IListRef; + +/* + * Applies arbitrary macros to each `IListRefTag`. + */ +#define TORCH_ILISTREF_FORALL_TAGS(_, ...) \ + _(Unboxed, ##__VA_ARGS__) \ + _(Boxed, ##__VA_ARGS__) \ + _(Materialized, ##__VA_ARGS__) + +/* + * Defines a "switch-case" for `TAG`. Inside, it executes `BODY`, + * while bringing to scope: + * + * - `ImplT`: the implementation class for `TAG` + * - `this_`: the result of unwrapping `this` + */ +#define TORCH_ILISTREF_UNWRAP_CASE(TAG, BODY) \ + case c10::IListRefTag::TAG: { \ + using ImplT = c10::detail::IListRefTagImpl; \ + auto& this_ = ImplT::unwrap(*this); \ + BODY \ + } break; + +/* + * Dispatches the unwrap call, depending on `TAG`, followed by + * the execution of `BODY`. It aborts if `TAG` is not a `IListRefTag`. + * + * This macro is useful because it allows us to handle different + * types (that correspond to different tags) to be implemented + * only once. We can do it even when the implementation of the + * different tags aren't syntatically the same, by dispatching + * it to a function (e.g. `ImplT::(this_)`). + */ +#define TORCH_ILISTREF_UNWRAP(TAG, BODY) \ + switch (TAG) { \ + TORCH_ILISTREF_FORALL_TAGS(TORCH_ILISTREF_UNWRAP_CASE, BODY) \ + break; \ + default: \ + TORCH_INTERNAL_ASSERT(false, "invalid IListRef tag."); \ + } + +enum class IListRefTag { +#define DEFINE_TAG(tag, ...) tag, + TORCH_ILISTREF_FORALL_TAGS(DEFINE_TAG) +#undef DEFINE_TAG + None +}; + +namespace detail { +/* + * Type alias that specifies whether we return a reference or a copy of `T`. + * + * What is this for? + * ================= + * Since values in the boxed world are represented by an `IValue`, we also + * depend on whether it can be converted to a const-reference (`Tensor`) or + * has to create a new copy of `T` (`OptionalTensorRef`). + */ +template +using IListRefConstRef = typename ivalue_to_const_ref_overload_return::type; + +/* + * Interface that implements key functions for each `IListRefTag` type. + * + * What is this for? + * ================= + * Given an `IListRef(Iterator)`, some methods have to be implemented + * differently for each `TAG`. Therefore, the methods inside this class + * are used as dispatch targets for the different `IListRefTag` values. + * + * You should create an specialization of this class for each possible + * combination of `IListRefTag` type (except `None`) and element types + * (e.g. `Tensor`). + * + * What does it do? + * ================ + * 1. defines static methods to be used as dispatch targets by both + * `IListRef` and `IListRefIterator` (see the implementation of + * `IListRefTagImplBase`). + * + * 2. defines the `elem_type` and `list_type` aliases that will be + * used in the definition of `IListRef`. In general, we should do + * so by inheriting from `IListRefTagImplBase`. + * + * [Note: IListRefTagImpl Specialization] + * ====================================== + * For `IListRef(Iterator)`: + * - + * - + * - + * + * For `IListRef(Iterator)`: + * - + * - + * - + */ +template +class IListRefTagImpl {}; + +/* + * Base implementation of `IListRefTagImpl` methods. + * + * What is this for? + * ================= + * This should make adding specializations for new types easier. For + * example, one should be able to add a new type just by making its + * `IListRefTagImpl` specialization inherit from `IListRefTagImplBase`. + * + * You should create a partial specialization for this class only if + * you introduce a new `IListRefTag`. The idea being that there is one + * default implementation for each possible value of `IListRefTag`. + * + * What does it do? + * ================ + * 1. defines `elem_type` as an alias to `ListElemT`. + * + * 1. defines `list_type` as an alias to the default container type + * that will hold a collection of `elem_type`. The idea being that + * all types tagged as `TAG` will have `list_type` as its container, + * with different `elem_type`. + * + * 3. defines the default implementation for each of the methods that + * are supposed to be defined on `IListRefTagImpl` specializations. + * + * 4. inheriting from `IListRefTagImplBase` also means + * that the payload of the type `IListRef` will be of type `list_type` + * when it is tagged as `TAG`. + */ +template +class IListRefTagImplBase {}; + +/* + * Materialized container for `IListRef`. + * + * What is this for? + * ================= + * Container that groups `T` references together. This exchanges the + * overhead of every method call from `IListRef` for a dynamic allocation. + * + * You should use this container instead of `IListRef` if: + * + * - You are going to iterate the list more than once + * - You need to repeatedly access arbitrary elements (using `operator[]`) + * What does it do? + + * ================ + * Removes the reference (&) from the type, and wraps it into a + * `std::reference_wrapper`. If `IListRefConstRef` is not a + * reference type, then it's left unchanged. + */ +template +using _MaterializedIListRefElem = typename std::conditional< + std::is_reference::value, + typename std::reference_wrapper::type>, + T>::type; + +template +using MaterializedIListRefElem = _MaterializedIListRefElem>; + +template +using MaterializedIListRef = std::vector>; + +} // namespace detail + +/* + * Iterator for `IListRef`. + * + * What is it? + * =========== + * Currently, a `std::bidirectional_iterator` that wraps the iterator + * types defined for each of the `IListRefTag`. + * + * One should be able to use it, as if it were the unwrapped + * iterators themselves. + + * What does it do? + * ================ + * Similarly to `IListRef`, this is a wrapper class. Specifically, it + * wraps each container's `const_iterator` type alias. So, for example, + * given that the container for `IListRefTag::Boxed` is `c10::List`, this + * iterator will wrap a `c10::List::const_iterator`. + * + * [Note: MSVC Iterator Debug] + * =========================== + * MSVC `vector::iterator` implementation (used in the boxed variant) + * makes it so this union's destructor, copy-constructor (assignment), and + * move-constructor (assignment) are implicitly deleted. + * + * Therefore, we need to explicitly define them as needed. Follows a list + * of places where these are needed and their reason: + * + * - `Payload` destructor: + * it is deleted only if the macro `_ITERATOR_DEBUG_LEVEL` is set to 2. + * + * - `IListRefIterator` destructor: + * same as above. However, we need to explicitly call the variant + * destructor explicitly. + * + * - `IListRefIterator` copy-constructor: + * it is deleted only if the macro `_ITERATOR_DEBUG_LEVEL` is different + * than 0. + */ +template +class IListRefIterator { + private: +#define DEFINE_FRIEND_CLASS(TAG, ...) \ + friend class detail::IListRefTagImpl; \ + friend class detail::IListRefTagImplBase< \ + IListRefTag::TAG, \ + T, \ + typename detail::IListRefTagImpl::elem_type>; + TORCH_ILISTREF_FORALL_TAGS(DEFINE_FRIEND_CLASS) +#undef DEFINE_FRIEND_CLASS + + public: + // C++17 friendly std::iterator implementation + using iterator_category = std::bidirectional_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T*; + using reference = T&; + + using unboxed_iterator_type = typename detail:: + IListRefTagImpl::list_type::const_iterator; + using boxed_iterator_type = typename detail:: + IListRefTagImpl::list_type::const_iterator; + using materialized_iterator_type = + typename detail::MaterializedIListRef::const_iterator; + + IListRefIterator() : tag_(IListRefTag::None) {} + +#if defined(_MSC_VER) && _ITERATOR_DEBUG_LEVEL != 0 + // See [Note: MSVC Iterator Debug] + IListRefIterator(const IListRefIterator& iterator) + : tag_(iterator.tag_) { + switch (tag_) { + case IListRefTag::Boxed: + payload_.boxed_iterator = iterator.payload_.boxed_iterator; + break; + case IListRefTag::Unboxed: + payload_.unboxed_iterator = iterator.payload_.unboxed_iterator; + break; + case IListRefTag::Materialized: + payload_.materialized_iterator = iterator.payload_.materialized_iterator; + break; + default: + TORCH_INTERNAL_ASSERT(false, "invalid IListRef tag."); + } + } +#endif + +#if defined(_MSC_VER) && _ITERATOR_DEBUG_LEVEL == 2 + // See [Note: MSVC Iterator Debug] + ~IListRefIterator() noexcept(false) { + switch (tag_) { + case IListRefTag::Boxed: + payload_.boxed_iterator.~boxed_iterator_type(); + break; + case IListRefTag::Unboxed: + payload_.unboxed_iterator.~unboxed_iterator_type(); + break; + case IListRefTag::Materialized: + payload_.materialized_iterator.~materialized_iterator_type(); + break; + default: + TORCH_INTERNAL_ASSERT(false, "invalid IListRef tag."); + } + } +#endif + + IListRefIterator(boxed_iterator_type boxed) : tag_(IListRefTag::Boxed) { + payload_.boxed_iterator = boxed; + } + + IListRefIterator(unboxed_iterator_type unboxed) : tag_(IListRefTag::Unboxed) { + payload_.unboxed_iterator = unboxed; + } + + IListRefIterator(materialized_iterator_type materialized) : tag_(IListRefTag::Materialized) { + payload_.materialized_iterator = materialized; + } + + detail::IListRefConstRef operator*() const { + TORCH_ILISTREF_UNWRAP(tag_, { return ImplT::iterator_get(this_); }); + } + + IListRefIterator& operator++() { + TORCH_ILISTREF_UNWRAP(tag_, { ++this_; }); + return *this; + } + + IListRefIterator operator++(int) { + auto old = *this; + TORCH_ILISTREF_UNWRAP(tag_, { ++this_; }); + return old; + } + + IListRefIterator& operator--() { + TORCH_ILISTREF_UNWRAP(tag_, { --this_; }); + return *this; + } + + IListRefIterator operator--(int) { + auto old = *this; + TORCH_ILISTREF_UNWRAP(tag_, { --this_; }); + return old; + } + + bool operator==(const IListRefIterator& rhs) const { + if (tag_ != rhs.tag_) { + return false; + } + TORCH_ILISTREF_UNWRAP(tag_, { + auto& rhs_it = ImplT::unwrap(rhs); + return this_ == rhs_it; + }); + } + + bool operator!=(const IListRefIterator& rhs) const { + return !(*this == rhs); + } + + private: + union Payload { + boxed_iterator_type boxed_iterator; + unboxed_iterator_type unboxed_iterator; + materialized_iterator_type materialized_iterator; + void* _init_ptr; + Payload() : _init_ptr(nullptr) {} +#if defined(_MSC_VER) + // See [Note: MSVC Iterator Debug] + ~Payload() {} +#endif + }; + + Payload payload_; + IListRefTag tag_; +}; + +/* + * See [Note: IListRef] + */ +template +class IListRef { + private: +#define DEFINE_FRIEND_CLASS(TAG, ...) \ + friend class detail::IListRefTagImpl; \ + friend class detail::IListRefTagImplBase< \ + IListRefTag::TAG, \ + T, \ + typename detail::IListRefTagImpl::elem_type>; + TORCH_ILISTREF_FORALL_TAGS(DEFINE_FRIEND_CLASS) +#undef DEFINE_FRIEND_CLASS + + public: + using unboxed_type = + typename detail::IListRefTagImpl::list_type; + using boxed_type = + typename detail::IListRefTagImpl::list_type; + using materialized_type = + typename detail::MaterializedIListRef; + + using iterator = IListRefIterator; + using const_iterator = IListRefIterator; + using reverse_iterator = std::reverse_iterator; + using value_type = typename iterator::value_type; + + IListRef() : tag_(IListRefTag::None) {} + + IListRef(const boxed_type& boxed) : tag_(IListRefTag::Boxed) { + payload_.boxed = &boxed; + } + + IListRef(const unboxed_type& unboxed) : tag_(IListRefTag::Unboxed) { + payload_.unboxed = unboxed; + } + + IListRef(const std::initializer_list& list) : tag_(IListRefTag::Unboxed) { + payload_.unboxed = at::ArrayRef(list); + } + + template < + typename... UnboxedConstructorArgs, + typename = std::enable_if_t< + std::is_constructible::value>> + IListRef(UnboxedConstructorArgs&&... args) : tag_(IListRefTag::Unboxed) { + payload_.unboxed = unboxed_type(std::forward(args)...); + } + + IListRef(const materialized_type& materialized) : tag_(IListRefTag::Materialized) { + payload_.materialized = &materialized; + } + + size_t size() const { + TORCH_ILISTREF_UNWRAP(tag_, { return this_.size(); }); + } + + bool empty() const { + return size() == 0; + } + + iterator begin() const { + TORCH_ILISTREF_UNWRAP(tag_, { return this_.begin(); }); + } + + iterator end() const { + TORCH_ILISTREF_UNWRAP(tag_, { return this_.end(); }); + } + + detail::IListRefConstRef front() const { + TORCH_ILISTREF_UNWRAP(tag_, { return ImplT::front(this_); }); + } + + /* + * Materializes the `IListRef` into a `std::vector`. + * + * This should be used when one wishes to either: + * + * - iterate over the list more than once: each `IListRefIterator` + * member function call has to go through a switch, introducing + * non-negligible overhead + * + * - randomly access an arbitrary element using `operator[]`: + * same reason as above + */ + detail::MaterializedIListRef materialize() const { + if (isMaterialized()) { + return toMaterialized(); + } + + detail::MaterializedIListRef materialized; + materialized.reserve(size()); + for (const auto& t : *this) { + materialized.emplace_back(t); + } + return materialized; + } + +#define DEFINE_CHECK(TAG, ...) \ + bool is##TAG() const { \ + return tag_ == IListRefTag::TAG; \ + } + TORCH_ILISTREF_FORALL_TAGS(DEFINE_CHECK); +#undef DEFINE_CHECK + + bool isNone() const { + return tag_ == IListRefTag::None; + } + +#define DEFINE_CASTING(TAG, ...) \ + const typename detail::IListRefTagImpl::list_type& \ + to##TAG() const { \ + TORCH_INTERNAL_ASSERT(is##TAG()); \ + return detail::IListRefTagImpl::unwrap(*this); \ + } + TORCH_ILISTREF_FORALL_TAGS(DEFINE_CASTING); +#undef DEFINE_CASTING + + private: + union Payload { + const boxed_type* boxed; + unboxed_type unboxed; + const materialized_type* materialized; + Payload() : boxed(nullptr) {} + }; + + Payload payload_; + IListRefTag tag_; +}; + +} // namespace c10 + +#include diff --git a/shared/package-files/78/783748f1198726cd0ca7a779ead35bf157ff076bfab4a8562a8c257ff1f3afec/blob b/shared/package-files/78/783748f1198726cd0ca7a779ead35bf157ff076bfab4a8562a8c257ff1f3afec/blob new file mode 100644 index 0000000000000000000000000000000000000000..f53bd58970e64dd742bed524d0ba37cafbe15a9c --- /dev/null +++ b/shared/package-files/78/783748f1198726cd0ca7a779ead35bf157ff076bfab4a8562a8c257ff1f3afec/blob @@ -0,0 +1,301 @@ +""" +A number of functions that enhance IDLE on macOS. +""" +from os.path import expanduser +import plistlib +from sys import platform # Used in _init_tk_type, changed by test. + +import tkinter + + +## Define functions that query the Mac graphics type. +## _tk_type and its initializer are private to this section. + +_tk_type = None + +def _init_tk_type(): + """ Initialize _tk_type for isXyzTk functions. + + This function is only called once, when _tk_type is still None. + """ + global _tk_type + if platform == 'darwin': + + # When running IDLE, GUI is present, test/* may not be. + # When running tests, test/* is present, GUI may not be. + # If not, guess most common. Does not matter for testing. + from idlelib.__init__ import testing + if testing: + from test.support import requires, ResourceDenied + try: + requires('gui') + except ResourceDenied: + _tk_type = "cocoa" + return + + root = tkinter.Tk() + ws = root.tk.call('tk', 'windowingsystem') + if 'x11' in ws: + _tk_type = "xquartz" + elif 'aqua' not in ws: + _tk_type = "other" + elif 'AppKit' in root.tk.call('winfo', 'server', '.'): + _tk_type = "cocoa" + else: + _tk_type = "carbon" + root.destroy() + else: + _tk_type = "other" + return + +def isAquaTk(): + """ + Returns True if IDLE is using a native OS X Tk (Cocoa or Carbon). + """ + if not _tk_type: + _init_tk_type() + return _tk_type == "cocoa" or _tk_type == "carbon" + +def isCarbonTk(): + """ + Returns True if IDLE is using a Carbon Aqua Tk (instead of the + newer Cocoa Aqua Tk). + """ + if not _tk_type: + _init_tk_type() + return _tk_type == "carbon" + +def isCocoaTk(): + """ + Returns True if IDLE is using a Cocoa Aqua Tk. + """ + if not _tk_type: + _init_tk_type() + return _tk_type == "cocoa" + +def isXQuartz(): + """ + Returns True if IDLE is using an OS X X11 Tk. + """ + if not _tk_type: + _init_tk_type() + return _tk_type == "xquartz" + + +def tkVersionWarning(root): + """ + Returns a string warning message if the Tk version in use appears to + be one known to cause problems with IDLE. + 1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable. + 2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but + can still crash unexpectedly. + """ + + if isCocoaTk(): + patchlevel = root.tk.call('info', 'patchlevel') + if patchlevel not in ('8.5.7', '8.5.9'): + return False + return ("WARNING: The version of Tcl/Tk ({0}) in use may" + " be unstable.\n" + "Visit https://www.python.org/download/mac/tcltk/" + " for current information.".format(patchlevel)) + else: + return False + + +def readSystemPreferences(): + """ + Fetch the macOS system preferences. + """ + if platform != 'darwin': + return None + + plist_path = expanduser('~/Library/Preferences/.GlobalPreferences.plist') + try: + with open(plist_path, 'rb') as plist_file: + return plistlib.load(plist_file) + except OSError: + return None + + +def preferTabsPreferenceWarning(): + """ + Warn if "Prefer tabs when opening documents" is set to "Always". + """ + if platform != 'darwin': + return None + + prefs = readSystemPreferences() + if prefs and prefs.get('AppleWindowTabbingMode') == 'always': + return ( + 'WARNING: The system preference "Prefer tabs when opening' + ' documents" is set to "Always". This will cause various problems' + ' with IDLE. For the best experience, change this setting when' + ' running IDLE (via System Preferences -> Dock).' + ) + return None + + +## Fix the menu and related functions. + +def addOpenEventSupport(root, flist): + """ + This ensures that the application will respond to open AppleEvents, which + makes is feasible to use IDLE as the default application for python files. + """ + def doOpenFile(*args): + for fn in args: + flist.open(fn) + + # The command below is a hook in aquatk that is called whenever the app + # receives a file open event. The callback can have multiple arguments, + # one for every file that should be opened. + root.createcommand("::tk::mac::OpenDocument", doOpenFile) + +def hideTkConsole(root): + try: + root.tk.call('console', 'hide') + except tkinter.TclError: + # Some versions of the Tk framework don't have a console object + pass + +def overrideRootMenu(root, flist): + """ + Replace the Tk root menu by something that is more appropriate for + IDLE with an Aqua Tk. + """ + # The menu that is attached to the Tk root (".") is also used by AquaTk for + # all windows that don't specify a menu of their own. The default menubar + # contains a number of menus, none of which are appropriate for IDLE. The + # Most annoying of those is an 'About Tck/Tk...' menu in the application + # menu. + # + # This function replaces the default menubar by a mostly empty one, it + # should only contain the correct application menu and the window menu. + # + # Due to a (mis-)feature of TkAqua the user will also see an empty Help + # menu. + from tkinter import Menu + from idlelib import mainmenu + from idlelib import window + + closeItem = mainmenu.menudefs[0][1][-2] + + # Remove the last 3 items of the file menu: a separator, close window and + # quit. Close window will be reinserted just above the save item, where + # it should be according to the HIG. Quit is in the application menu. + del mainmenu.menudefs[0][1][-3:] + mainmenu.menudefs[0][1].insert(6, closeItem) + + # Remove the 'About' entry from the help menu, it is in the application + # menu + del mainmenu.menudefs[-1][1][0:2] + # Remove the 'Configure Idle' entry from the options menu, it is in the + # application menu as 'Preferences' + del mainmenu.menudefs[-3][1][0:2] + menubar = Menu(root) + root.configure(menu=menubar) + menudict = {} + + menudict['window'] = menu = Menu(menubar, name='window', tearoff=0) + menubar.add_cascade(label='Window', menu=menu, underline=0) + + def postwindowsmenu(menu=menu): + end = menu.index('end') + if end is None: + end = -1 + + if end > 0: + menu.delete(0, end) + window.add_windows_to_menu(menu) + window.register_callback(postwindowsmenu) + + def about_dialog(event=None): + "Handle Help 'About IDLE' event." + # Synchronize with editor.EditorWindow.about_dialog. + from idlelib import help_about + help_about.AboutDialog(root) + + def config_dialog(event=None): + "Handle Options 'Configure IDLE' event." + # Synchronize with editor.EditorWindow.config_dialog. + from idlelib import configdialog + + # Ensure that the root object has an instance_dict attribute, + # mirrors code in EditorWindow (although that sets the attribute + # on an EditorWindow instance that is then passed as the first + # argument to ConfigDialog) + root.instance_dict = flist.inversedict + configdialog.ConfigDialog(root, 'Settings') + + def help_dialog(event=None): + "Handle Help 'IDLE Help' event." + # Synchronize with editor.EditorWindow.help_dialog. + from idlelib import help + help.show_idlehelp(root) + + root.bind('<>', about_dialog) + root.bind('<>', config_dialog) + root.createcommand('::tk::mac::ShowPreferences', config_dialog) + if flist: + root.bind('<>', flist.close_all_callback) + + # The binding above doesn't reliably work on all versions of Tk + # on macOS. Adding command definition below does seem to do the + # right thing for now. + root.createcommand('exit', flist.close_all_callback) + + if isCarbonTk(): + # for Carbon AquaTk, replace the default Tk apple menu + menudict['application'] = menu = Menu(menubar, name='apple', + tearoff=0) + menubar.add_cascade(label='IDLE', menu=menu) + mainmenu.menudefs.insert(0, + ('application', [ + ('About IDLE', '<>'), + None, + ])) + if isCocoaTk(): + # replace default About dialog with About IDLE one + root.createcommand('tkAboutDialog', about_dialog) + # replace default "Help" item in Help menu + root.createcommand('::tk::mac::ShowHelp', help_dialog) + # remove redundant "IDLE Help" from menu + del mainmenu.menudefs[-1][1][0] + +def fixb2context(root): + '''Removed bad AquaTk Button-2 (right) and Paste bindings. + + They prevent context menu access and seem to be gone in AquaTk8.6. + See issue #24801. + ''' + root.unbind_class('Text', '') + root.unbind_class('Text', '') + root.unbind_class('Text', '<>') + +def setupApp(root, flist): + """ + Perform initial OS X customizations if needed. + Called from pyshell.main() after initial calls to Tk() + + There are currently three major versions of Tk in use on OS X: + 1. Aqua Cocoa Tk (native default since OS X 10.6) + 2. Aqua Carbon Tk (original native, 32-bit only, deprecated) + 3. X11 (supported by some third-party distributors, deprecated) + There are various differences among the three that affect IDLE + behavior, primarily with menus, mouse key events, and accelerators. + Some one-time customizations are performed here. + Others are dynamically tested throughout idlelib by calls to the + isAquaTk(), isCarbonTk(), isCocoaTk(), isXQuartz() functions which + are initialized here as well. + """ + if isAquaTk(): + hideTkConsole(root) + overrideRootMenu(root, flist) + addOpenEventSupport(root, flist) + fixb2context(root) + + +if __name__ == '__main__': + from unittest import main + main('idlelib.idle_test.test_macosx', verbosity=2) diff --git a/shared/package-files/78/7838be92cfe995d93aa9b60c46c2d30c586709eefe7d1037838d4f2463e960d5/blob b/shared/package-files/78/7838be92cfe995d93aa9b60c46c2d30c586709eefe7d1037838d4f2463e960d5/blob new file mode 100644 index 0000000000000000000000000000000000000000..75ac00b6ffa199e236dfe09d8af2628da393e850 --- /dev/null +++ b/shared/package-files/78/7838be92cfe995d93aa9b60c46c2d30c586709eefe7d1037838d4f2463e960d5/blob @@ -0,0 +1,306 @@ +""" +Implementation of a minimal Pandas-like API. +""" + +import numpy as np + +from numba.core import types, cgutils +from numba.core.datamodel import models +from numba.core.extending import ( + typeof_impl, type_callable, register_model, + lower_builtin, box, unbox, NativeValue, + overload, overload_attribute, overload_method, make_attribute_wrapper) +from numba.core.imputils import impl_ret_borrowed + + +class Index(object): + """ + A minimal pandas.Index-like object. + """ + + def __init__(self, data): + assert isinstance(data, np.ndarray) + assert data.ndim == 1 + self._data = data + + def __iter__(self): + return iter(self._data) + + @property + def dtype(self): + return self._data.dtype + + @property + def flags(self): + return self._data.flags + + +class IndexType(types.Buffer): + """ + The type class for Index objects. + """ + array_priority = 1000 + + def __init__(self, dtype, layout, pyclass): + self.pyclass = pyclass + super(IndexType, self).__init__(dtype, 1, layout) + + @property + def key(self): + return self.pyclass, self.dtype, self.layout + + @property + def as_array(self): + return types.Array(self.dtype, 1, self.layout) + + def copy(self, dtype=None, ndim=1, layout=None): + assert ndim == 1 + if dtype is None: + dtype = self.dtype + layout = layout or self.layout + return type(self)(dtype, layout, self.pyclass) + + +class Series(object): + """ + A minimal pandas.Series-like object. + """ + + def __init__(self, data, index): + assert isinstance(data, np.ndarray) + assert isinstance(index, Index) + assert data.ndim == 1 + self._values = data + self._index = index + + def __iter__(self): + return iter(self._values) + + @property + def dtype(self): + return self._values.dtype + + @property + def flags(self): + return self._values.flags + + +class SeriesType(types.ArrayCompatible): + """ + The type class for Series objects. + """ + array_priority = 1000 + + def __init__(self, dtype, index): + assert isinstance(index, IndexType) + self.dtype = dtype + self.index = index + self.values = types.Array(self.dtype, 1, 'C') + name = "series(%s, %s)" % (dtype, index) + super(SeriesType, self).__init__(name) + + @property + def key(self): + return self.dtype, self.index + + @property + def as_array(self): + return self.values + + def copy(self, dtype=None, ndim=1, layout='C'): + assert ndim == 1 + assert layout == 'C' + if dtype is None: + dtype = self.dtype + return type(self)(dtype, self.index) + + +@typeof_impl.register(Index) +def typeof_index(val, c): + arrty = typeof_impl(val._data, c) + assert arrty.ndim == 1 + return IndexType(arrty.dtype, arrty.layout, type(val)) + +@typeof_impl.register(Series) +def typeof_series(val, c): + index = typeof_impl(val._index, c) + arrty = typeof_impl(val._values, c) + assert arrty.ndim == 1 + assert arrty.layout == 'C' + return SeriesType(arrty.dtype, index) + +@type_callable('__array_wrap__') +def type_array_wrap(context): + def typer(input_type, result): + if isinstance(input_type, (IndexType, SeriesType)): + return input_type.copy(dtype=result.dtype, + ndim=result.ndim, + layout=result.layout) + + return typer + +@type_callable(Series) +def type_series_constructor(context): + def typer(data, index): + if isinstance(index, IndexType) and isinstance(data, types.Array): + assert data.layout == 'C' + assert data.ndim == 1 + return SeriesType(data.dtype, index) + + return typer + + +# Backend extensions for Index and Series + +@register_model(IndexType) +class IndexModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [('data', fe_type.as_array)] + models.StructModel.__init__(self, dmm, fe_type, members) + +@register_model(SeriesType) +class SeriesModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('index', fe_type.index), + ('values', fe_type.as_array), + ] + models.StructModel.__init__(self, dmm, fe_type, members) + +make_attribute_wrapper(IndexType, 'data', '_data') +make_attribute_wrapper(SeriesType, 'index', '_index') +make_attribute_wrapper(SeriesType, 'values', '_values') + +def make_index(context, builder, typ, **kwargs): + return cgutils.create_struct_proxy(typ)(context, builder, **kwargs) + +def make_series(context, builder, typ, **kwargs): + return cgutils.create_struct_proxy(typ)(context, builder, **kwargs) + +@lower_builtin('__array__', IndexType) +def index_as_array(context, builder, sig, args): + val = make_index(context, builder, sig.args[0], ref=args[0]) + return val._get_ptr_by_name('data') + +@lower_builtin('__array__', SeriesType) +def series_as_array(context, builder, sig, args): + val = make_series(context, builder, sig.args[0], ref=args[0]) + return val._get_ptr_by_name('values') + +@lower_builtin('__array_wrap__', IndexType, types.Array) +def index_wrap_array(context, builder, sig, args): + dest = make_index(context, builder, sig.return_type) + dest.data = args[1] + return impl_ret_borrowed(context, builder, sig.return_type, dest._getvalue()) + +@lower_builtin('__array_wrap__', SeriesType, types.Array) +def series_wrap_array(context, builder, sig, args): + src = make_series(context, builder, sig.args[0], value=args[0]) + dest = make_series(context, builder, sig.return_type) + dest.values = args[1] + dest.index = src.index + return impl_ret_borrowed(context, builder, sig.return_type, dest._getvalue()) + +@lower_builtin(Series, types.Array, IndexType) +def pdseries_constructor(context, builder, sig, args): + data, index = args + series = make_series(context, builder, sig.return_type) + series.index = index + series.values = data + return impl_ret_borrowed(context, builder, sig.return_type, series._getvalue()) + + +@unbox(IndexType) +def unbox_index(typ, obj, c): + """ + Convert a Index object to a native structure. + """ + data = c.pyapi.object_getattr_string(obj, "_data") + index = make_index(c.context, c.builder, typ) + index.data = c.unbox(typ.as_array, data).value + + return NativeValue(index._getvalue()) + +@unbox(SeriesType) +def unbox_series(typ, obj, c): + """ + Convert a Series object to a native structure. + """ + index = c.pyapi.object_getattr_string(obj, "_index") + values = c.pyapi.object_getattr_string(obj, "_values") + series = make_series(c.context, c.builder, typ) + series.index = c.unbox(typ.index, index).value + series.values = c.unbox(typ.values, values).value + + return NativeValue(series._getvalue()) + + +@box(IndexType) +def box_index(typ, val, c): + """ + Convert a native index structure to a Index object. + """ + # First build a Numpy array object, then wrap it in a Index + index = make_index(c.context, c.builder, typ, value=val) + classobj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.pyclass)) + arrayobj = c.box(typ.as_array, index.data) + indexobj = c.pyapi.call_function_objargs(classobj, (arrayobj,)) + return indexobj + +@box(SeriesType) +def box_series(typ, val, c): + """ + Convert a native series structure to a Series object. + """ + series = make_series(c.context, c.builder, typ, value=val) + classobj = c.pyapi.unserialize(c.pyapi.serialize_object(Series)) + indexobj = c.box(typ.index, series.index) + arrayobj = c.box(typ.as_array, series.values) + seriesobj = c.pyapi.call_function_objargs(classobj, (arrayobj, indexobj)) + return seriesobj + + +@overload_attribute(IndexType, 'is_monotonic_increasing') +def index_is_monotonic_increasing(index): + """ + Index.is_monotonic_increasing + """ + def getter(index): + data = index._data + if len(data) == 0: + return True + u = data[0] + for v in data: + if v < u: + return False + v = u + return True + + return getter + +@overload(len) +def series_len(series): + """ + len(Series) + """ + if isinstance(series, SeriesType): + def len_impl(series): + return len(series._values) + return len_impl + +@overload_method(SeriesType, 'clip') +def series_clip(series, lower, upper): + """ + Series.clip(...) + """ + def clip_impl(series, lower, upper): + data = series._values.copy() + for i in range(len(data)): + v = data[i] + if v < lower: + data[i] = lower + elif v > upper: + data[i] = upper + return Series(data, series._index) + + return clip_impl diff --git a/shared/package-files/78/7839907b7872fb20599fac8677d80528660adeb8a317b5c5432fa8116b8b0a7b/blob b/shared/package-files/78/7839907b7872fb20599fac8677d80528660adeb8a317b5c5432fa8116b8b0a7b/blob new file mode 100644 index 0000000000000000000000000000000000000000..3817b537a2560f73e3f98a2033ee04ad2a3f76ed --- /dev/null +++ b/shared/package-files/78/7839907b7872fb20599fac8677d80528660adeb8a317b5c5432fa8116b8b0a7b/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor to_sparse_bsc(const at::Tensor & self, at::IntArrayRef blocksize, c10::optional dense_dim=c10::nullopt); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/78/783add667da806e1c5b58d5f1dc052246ab568433313e7987b77fcd247925d9e/blob b/shared/package-files/78/783add667da806e1c5b58d5f1dc052246ab568433313e7987b77fcd247925d9e/blob new file mode 100644 index 0000000000000000000000000000000000000000..a4dd3bfe5635f18a68b2a93117c1b0fb8fd2ad26 --- /dev/null +++ b/shared/package-files/78/783add667da806e1c5b58d5f1dc052246ab568433313e7987b77fcd247925d9e/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API adaptive_max_pool3d_out { + using schema = ::std::tuple (const at::Tensor &, at::IntArrayRef, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::adaptive_max_pool3d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "adaptive_max_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out, at::Tensor & indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out, at::Tensor & indices); +}; + +struct TORCH_API adaptive_max_pool3d { + using schema = ::std::tuple (const at::Tensor &, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::adaptive_max_pool3d") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & self, at::IntArrayRef output_size); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef output_size); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/783c5d074c72ce13ed1e8d6e99044989740513a4d9547308ee88202c16b64b10/blob b/shared/package-files/78/783c5d074c72ce13ed1e8d6e99044989740513a4d9547308ee88202c16b64b10/blob new file mode 100644 index 0000000000000000000000000000000000000000..bf7b6a464aa6c2e9842baa1d1e0459f7f73ee90b --- /dev/null +++ b/shared/package-files/78/783c5d074c72ce13ed1e8d6e99044989740513a4d9547308ee88202c16b64b10/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor vstack(at::TensorList tensors); +TORCH_API at::Tensor & vstack_out(at::TensorList tensors, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/78/783d1b66efc659fa02abefb05aa10a45ff85da1e40c284f23ba18c03dc093ebe/blob b/shared/package-files/78/783d1b66efc659fa02abefb05aa10a45ff85da1e40c284f23ba18c03dc093ebe/blob new file mode 100644 index 0000000000000000000000000000000000000000..f77ded2f31d4443c1bda42bb1c21f79fa100ce23 --- /dev/null +++ b/shared/package-files/78/783d1b66efc659fa02abefb05aa10a45ff85da1e40c284f23ba18c03dc093ebe/blob @@ -0,0 +1,44 @@ +# This test is ported from numpy.distutils +from numpy.f2py._src_pyf import process_str +from numpy.testing import assert_equal + + +pyf_src = """ +python module foo + <_rd=real,double precision> + interface + subroutine foosub(tol) + <_rd>, intent(in,out) :: tol + end subroutine foosub + end interface +end python module foo +""" + +expected_pyf = """ +python module foo + interface + subroutine sfoosub(tol) + real, intent(in,out) :: tol + end subroutine sfoosub + subroutine dfoosub(tol) + double precision, intent(in,out) :: tol + end subroutine dfoosub + end interface +end python module foo +""" + + +def normalize_whitespace(s): + """ + Remove leading and trailing whitespace, and convert internal + stretches of whitespace to a single space. + """ + return ' '.join(s.split()) + + +def test_from_template(): + """Regression test for gh-10712.""" + pyf = process_str(pyf_src) + normalized_pyf = normalize_whitespace(pyf) + normalized_expected_pyf = normalize_whitespace(expected_pyf) + assert_equal(normalized_pyf, normalized_expected_pyf) diff --git a/shared/package-files/78/78420007fd3b5fc10eec192b415cf6677ef89231cb2177bbe49167c768f4baab/blob b/shared/package-files/78/78420007fd3b5fc10eec192b415cf6677ef89231cb2177bbe49167c768f4baab/blob new file mode 100644 index 0000000000000000000000000000000000000000..36a44cebe74ba00ab82b88150c2cd11b5ae9a25e --- /dev/null +++ b/shared/package-files/78/78420007fd3b5fc10eec192b415cf6677ef89231cb2177bbe49167c768f4baab/blob @@ -0,0 +1,104 @@ +import numpy as np + +from numba.core.typing.typeof import typeof +from numba.core.typing.asnumbatype import as_numba_type + + +def pndindex(*args): + """ Provides an n-dimensional parallel iterator that generates index tuples + for each iteration point. Sequentially, pndindex is identical to np.ndindex. + """ + return np.ndindex(*args) + + +class prange(object): + """ Provides a 1D parallel iterator that generates a sequence of integers. + In non-parallel contexts, prange is identical to range. + """ + def __new__(cls, *args): + return range(*args) + + +def _gdb_python_call_gen(func_name, *args): + # generates a call to a function containing a compiled in gdb command, + # this is to make `numba.gdb*` work in the interpreter. + import numba + fn = getattr(numba, func_name) + argstr = ','.join(['"%s"' for _ in args]) % args + defn = """def _gdb_func_injection():\n\t%s(%s)\n + """ % (func_name, argstr) + l = {} + exec(defn, {func_name: fn}, l) + return numba.njit(l['_gdb_func_injection']) + + +def gdb(*args): + """ + Calling this function will invoke gdb and attach it to the current process + at the call site. Arguments are strings in the gdb command language syntax + which will be executed by gdb once initialisation has occurred. + """ + _gdb_python_call_gen('gdb', *args)() + + +def gdb_breakpoint(): + """ + Calling this function will inject a breakpoint at the call site that is + recognised by both `gdb` and `gdb_init`, this is to allow breaking at + multiple points. gdb will stop in the user defined code just after the frame + employed by the breakpoint returns. + """ + _gdb_python_call_gen('gdb_breakpoint')() + + +def gdb_init(*args): + """ + Calling this function will invoke gdb and attach it to the current process + at the call site, then continue executing the process under gdb's control. + Arguments are strings in the gdb command language syntax which will be + executed by gdb once initialisation has occurred. + """ + _gdb_python_call_gen('gdb_init', *args)() + + +def literally(obj): + """Forces Numba to interpret *obj* as an Literal value. + + *obj* must be either a literal or an argument of the caller function, where + the argument must be bound to a literal. The literal requirement + propagates up the call stack. + + This function is intercepted by the compiler to alter the compilation + behavior to wrap the corresponding function parameters as ``Literal``. + It has **no effect** outside of nopython-mode (interpreter, and objectmode). + + The current implementation detects literal arguments in two ways: + + 1. Scans for uses of ``literally`` via a compiler pass. + 2. ``literally`` is overloaded to raise ``numba.errors.ForceLiteralArg`` + to signal the dispatcher to treat the corresponding parameter + differently. This mode is to support indirect use (via a function call). + + The execution semantic of this function is equivalent to an identity + function. + + See :ghfile:`numba/tests/test_literal_dispatch.py` for examples. + """ + return obj + + +def literal_unroll(container): + return container + + +__all__ = [ + 'typeof', + 'as_numba_type', + 'prange', + 'pndindex', + 'gdb', + 'gdb_breakpoint', + 'gdb_init', + 'literally', + 'literal_unroll', +] diff --git a/shared/package-files/78/78435447883d2065eb6649cdb177be113eaa247899750facc4642fd7d9fd232c/blob b/shared/package-files/78/78435447883d2065eb6649cdb177be113eaa247899750facc4642fd7d9fd232c/blob new file mode 100644 index 0000000000000000000000000000000000000000..687d954554f7971f7e319c7840c9ea9ff1845db9 --- /dev/null +++ b/shared/package-files/78/78435447883d2065eb6649cdb177be113eaa247899750facc4642fd7d9fd232c/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API feature_dropout { + using schema = at::Tensor (const at::Tensor &, double, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::feature_dropout") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "feature_dropout(Tensor input, float p, bool train) -> Tensor") + static at::Tensor call(const at::Tensor & input, double p, bool train); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, double p, bool train); +}; + +struct TORCH_API feature_dropout_ { + using schema = at::Tensor & (at::Tensor &, double, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::feature_dropout_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "feature_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, double p, bool train); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, double p, bool train); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/7844a755343c2778812f6e1b58ab7b4e61f10b914988b64ca4a8f0d55dfbeaa6/blob b/shared/package-files/78/7844a755343c2778812f6e1b58ab7b4e61f10b914988b64ca4a8f0d55dfbeaa6/blob new file mode 100644 index 0000000000000000000000000000000000000000..5fbe60bb0c50f0b6ec36eb02b125e9e9bf0f81dd --- /dev/null +++ b/shared/package-files/78/7844a755343c2778812f6e1b58ab7b4e61f10b914988b64ca4a8f0d55dfbeaa6/blob @@ -0,0 +1,62 @@ +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestDatetimeIndexFillNA: + @pytest.mark.parametrize("tz", ["US/Eastern", "Asia/Tokyo"]) + def test_fillna_datetime64(self, tz): + # GH 11343 + idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"]) + + exp = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"] + ) + tm.assert_index_equal(idx.fillna(pd.Timestamp("2011-01-01 10:00")), exp) + + # tz mismatch + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 09:00"), + pd.Timestamp("2011-01-01 10:00", tz=tz), + pd.Timestamp("2011-01-01 11:00"), + ], + dtype=object, + ) + tm.assert_index_equal(idx.fillna(pd.Timestamp("2011-01-01 10:00", tz=tz)), exp) + + # object + exp = pd.Index( + [pd.Timestamp("2011-01-01 09:00"), "x", pd.Timestamp("2011-01-01 11:00")], + dtype=object, + ) + tm.assert_index_equal(idx.fillna("x"), exp) + + idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"], tz=tz) + + exp = pd.DatetimeIndex( + ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], tz=tz + ) + tm.assert_index_equal(idx.fillna(pd.Timestamp("2011-01-01 10:00", tz=tz)), exp) + + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 09:00", tz=tz), + pd.Timestamp("2011-01-01 10:00"), + pd.Timestamp("2011-01-01 11:00", tz=tz), + ], + dtype=object, + ) + tm.assert_index_equal(idx.fillna(pd.Timestamp("2011-01-01 10:00")), exp) + + # object + exp = pd.Index( + [ + pd.Timestamp("2011-01-01 09:00", tz=tz), + "x", + pd.Timestamp("2011-01-01 11:00", tz=tz), + ], + dtype=object, + ) + tm.assert_index_equal(idx.fillna("x"), exp) diff --git a/shared/package-files/78/7844a96fd3a687ab6871640decae78ef61b7bd9b32f72b5b5840e7a475a5041c/blob b/shared/package-files/78/7844a96fd3a687ab6871640decae78ef61b7bd9b32f72b5b5840e7a475a5041c/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b8b3afc2f1f5d95c8dc5e7814c1a8b5e50ac9f7 --- /dev/null +++ b/shared/package-files/78/7844a96fd3a687ab6871640decae78ef61b7bd9b32f72b5b5840e7a475a5041c/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_igamma : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Tensor & other); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/78/7844c5bdb3c7c0a7dda18c8e80d402c8aabf6659be9731f77f0c2950887eff85/blob b/shared/package-files/78/7844c5bdb3c7c0a7dda18c8e80d402c8aabf6659be9731f77f0c2950887eff85/blob new file mode 100644 index 0000000000000000000000000000000000000000..5afd99b420fbc480ed5eb743333a687110a90e49 --- /dev/null +++ b/shared/package-files/78/7844c5bdb3c7c0a7dda18c8e80d402c8aabf6659be9731f77f0c2950887eff85/blob @@ -0,0 +1,236 @@ +############################################################################### +# Queue and SimpleQueue implementation for loky +# +# authors: Thomas Moreau, Olivier Grisel +# +# based on multiprocessing/queues.py (16/02/2017) +# * Add some custom reducers for the Queues/SimpleQueue to tweak the +# pickling process. (overload Queue._feed/SimpleQueue.put) +# +import os +import sys +import errno +import weakref +import threading +from multiprocessing import util +from multiprocessing.queues import ( + Full, + Queue as mp_Queue, + SimpleQueue as mp_SimpleQueue, + _sentinel, +) +from multiprocessing.context import assert_spawning + +from .reduction import dumps + + +__all__ = ["Queue", "SimpleQueue", "Full"] + + +class Queue(mp_Queue): + def __init__(self, maxsize=0, reducers=None, ctx=None): + super().__init__(maxsize=maxsize, ctx=ctx) + self._reducers = reducers + + # Use custom queue set/get state to be able to reduce the custom reducers + def __getstate__(self): + assert_spawning(self) + return ( + self._ignore_epipe, + self._maxsize, + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + self._sem, + self._opid, + ) + + def __setstate__(self, state): + ( + self._ignore_epipe, + self._maxsize, + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + self._sem, + self._opid, + ) = state + if sys.version_info >= (3, 9): + self._reset() + else: + self._after_fork() + + # Overload _start_thread to correctly call our custom _feed + def _start_thread(self): + util.debug("Queue._start_thread()") + + # Start thread which transfers data from buffer to pipe + self._buffer.clear() + self._thread = threading.Thread( + target=Queue._feed, + args=( + self._buffer, + self._notempty, + self._send_bytes, + self._wlock, + self._writer.close, + self._reducers, + self._ignore_epipe, + self._on_queue_feeder_error, + self._sem, + ), + name="QueueFeederThread", + ) + self._thread.daemon = True + + util.debug("doing self._thread.start()") + self._thread.start() + util.debug("... done self._thread.start()") + + # On process exit we will wait for data to be flushed to pipe. + # + # However, if this process created the queue then all + # processes which use the queue will be descendants of this + # process. Therefore waiting for the queue to be flushed + # is pointless once all the child processes have been joined. + created_by_this_process = self._opid == os.getpid() + if not self._joincancelled and not created_by_this_process: + self._jointhread = util.Finalize( + self._thread, + Queue._finalize_join, + [weakref.ref(self._thread)], + exitpriority=-5, + ) + + # Send sentinel to the thread queue object when garbage collected + self._close = util.Finalize( + self, + Queue._finalize_close, + [self._buffer, self._notempty], + exitpriority=10, + ) + + # Overload the _feed methods to use our custom pickling strategy. + @staticmethod + def _feed( + buffer, + notempty, + send_bytes, + writelock, + close, + reducers, + ignore_epipe, + onerror, + queue_sem, + ): + util.debug("starting thread to feed data to pipe") + nacquire = notempty.acquire + nrelease = notempty.release + nwait = notempty.wait + bpopleft = buffer.popleft + sentinel = _sentinel + if sys.platform != "win32": + wacquire = writelock.acquire + wrelease = writelock.release + else: + wacquire = None + + while True: + try: + nacquire() + try: + if not buffer: + nwait() + finally: + nrelease() + try: + while True: + obj = bpopleft() + if obj is sentinel: + util.debug("feeder thread got sentinel -- exiting") + close() + return + + # serialize the data before acquiring the lock + obj_ = dumps(obj, reducers=reducers) + if wacquire is None: + send_bytes(obj_) + else: + wacquire() + try: + send_bytes(obj_) + finally: + wrelease() + # Remove references early to avoid leaking memory + del obj, obj_ + except IndexError: + pass + except BaseException as e: + if ignore_epipe and getattr(e, "errno", 0) == errno.EPIPE: + return + # Since this runs in a daemon thread the resources it uses + # may be become unusable while the process is cleaning up. + # We ignore errors which happen after the process has + # started to cleanup. + if util.is_exiting(): + util.info(f"error in queue thread: {e}") + return + else: + queue_sem.release() + onerror(e, obj) + + def _on_queue_feeder_error(self, e, obj): + """ + Private API hook called when feeding data in the background thread + raises an exception. For overriding by concurrent.futures. + """ + import traceback + + traceback.print_exc() + + +class SimpleQueue(mp_SimpleQueue): + def __init__(self, reducers=None, ctx=None): + super().__init__(ctx=ctx) + + # Add possiblity to use custom reducers + self._reducers = reducers + + def close(self): + self._reader.close() + self._writer.close() + + # Use custom queue set/get state to be able to reduce the custom reducers + def __getstate__(self): + assert_spawning(self) + return ( + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + ) + + def __setstate__(self, state): + ( + self._reader, + self._writer, + self._reducers, + self._rlock, + self._wlock, + ) = state + + # Overload put to use our customizable reducer + def put(self, obj): + # serialize the data before acquiring the lock + obj = dumps(obj, reducers=self._reducers) + if self._wlock is None: + # writes to a message oriented win32 pipe are atomic + self._writer.send_bytes(obj) + else: + with self._wlock: + self._writer.send_bytes(obj) diff --git a/shared/package-files/78/7847dfee4e6e1a025ae8b5bfe7d4503d86cf731653dc452804429c3b96c709eb/blob b/shared/package-files/78/7847dfee4e6e1a025ae8b5bfe7d4503d86cf731653dc452804429c3b96c709eb/blob new file mode 100644 index 0000000000000000000000000000000000000000..755fafb0ac64388632b472d18b4cd0175e7df615 --- /dev/null +++ b/shared/package-files/78/7847dfee4e6e1a025ae8b5bfe7d4503d86cf731653dc452804429c3b96c709eb/blob @@ -0,0 +1,50 @@ +from tkinter.ttk import Label, Frame + + +class MultiStatusBar(Frame): + + def __init__(self, master, **kw): + Frame.__init__(self, master, **kw) + self.labels = {} + + def set_label(self, name, text='', side='left', width=0): + if name not in self.labels: + label = Label(self, borderwidth=0, anchor='w') + label.pack(side=side, pady=0, padx=4) + self.labels[name] = label + else: + label = self.labels[name] + if width != 0: + label.config(width=width) + label.config(text=text) + + +def _multistatus_bar(parent): # htest # + from tkinter import Toplevel, Text + from tkinter.ttk import Frame, Button + top = Toplevel(parent) + x, y = map(int, parent.geometry().split('+')[1:]) + top.geometry("+%d+%d" %(x, y + 175)) + top.title("Test multistatus bar") + frame = Frame(top) + text = Text(frame, height=5, width=40) + text.pack() + msb = MultiStatusBar(frame) + msb.set_label("one", "hello") + msb.set_label("two", "world") + msb.pack(side='bottom', fill='x') + + def change(): + msb.set_label("one", "foo") + msb.set_label("two", "bar") + + button = Button(top, text="Update status", command=change) + button.pack(side='bottom') + frame.pack() + +if __name__ == '__main__': + from unittest import main + main('idlelib.idle_test.test_statusbar', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(_multistatus_bar) diff --git a/shared/package-files/78/7848b06290d03c2b5a6e5e7cc47258251a3b3bc361018eb4a9633a15176150f0/blob b/shared/package-files/78/7848b06290d03c2b5a6e5e7cc47258251a3b3bc361018eb4a9633a15176150f0/blob new file mode 100644 index 0000000000000000000000000000000000000000..27c122cb02eeb27326214bea32f540e13c667ef4 --- /dev/null +++ b/shared/package-files/78/7848b06290d03c2b5a6e5e7cc47258251a3b3bc361018eb4a9633a15176150f0/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor _upsample_bilinear2d_aa_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/78/784965b9a19f5fd63aae3136a143878d8ffce04d5b2815e08aca379dcd9f59c8/blob b/shared/package-files/78/784965b9a19f5fd63aae3136a143878d8ffce04d5b2815e08aca379dcd9f59c8/blob new file mode 100644 index 0000000000000000000000000000000000000000..e61f02a39f5ee2f8f5a42054442fdef5e9f466bc --- /dev/null +++ b/shared/package-files/78/784965b9a19f5fd63aae3136a143878d8ffce04d5b2815e08aca379dcd9f59c8/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:784965b9a19f5fd63aae3136a143878d8ffce04d5b2815e08aca379dcd9f59c8 +size 585312 diff --git a/shared/package-files/78/784aeb50b2b05f99a99bddbc595ee832d8d64477fa054797aff51ca454f05ff2/blob b/shared/package-files/78/784aeb50b2b05f99a99bddbc595ee832d8d64477fa054797aff51ca454f05ff2/blob new file mode 100644 index 0000000000000000000000000000000000000000..4f1cecf14636ded3661fe5c9b90066482868054e --- /dev/null +++ b/shared/package-files/78/784aeb50b2b05f99a99bddbc595ee832d8d64477fa054797aff51ca454f05ff2/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_special_chebyshev_polynomial_u_out : public at::meta::structured_special_chebyshev_polynomial_u { +void impl(const at::Tensor & x, const at::Tensor & n, const at::Tensor & out); +}; +TORCH_API at::Tensor special_chebyshev_polynomial_u(const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_u_out(const at::Scalar & x, const at::Tensor & n, at::Tensor & out); +TORCH_API at::Tensor special_chebyshev_polynomial_u(const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_u_out(const at::Tensor & x, const at::Scalar & n, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/78/784b0b3ffa3b3aa18616de4a8fdbe7a1bbc7c38b0d6951731c2b84e2b97211de/blob b/shared/package-files/78/784b0b3ffa3b3aa18616de4a8fdbe7a1bbc7c38b0d6951731c2b84e2b97211de/blob new file mode 100644 index 0000000000000000000000000000000000000000..0eb88e71771f896b84cfaea2a27657999ab167ea --- /dev/null +++ b/shared/package-files/78/784b0b3ffa3b3aa18616de4a8fdbe7a1bbc7c38b0d6951731c2b84e2b97211de/blob @@ -0,0 +1,19 @@ +import pytest + +from sklearn.utils._mask import safe_mask +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.validation import check_random_state + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_safe_mask(csr_container): + random_state = check_random_state(0) + X = random_state.rand(5, 4) + X_csr = csr_container(X) + mask = [False, False, True, True, True] + + mask = safe_mask(X, mask) + assert X[mask].shape[0] == 3 + + mask = safe_mask(X_csr, mask) + assert X_csr[mask].shape[0] == 3 diff --git a/shared/package-files/78/784c33dda4c226d4b91f5a443b3d320bd15f6e7192f88f4cd82dd4f10b2c0530/blob b/shared/package-files/78/784c33dda4c226d4b91f5a443b3d320bd15f6e7192f88f4cd82dd4f10b2c0530/blob new file mode 100644 index 0000000000000000000000000000000000000000..f9ef86adc92275842567a537343faa335a8eb59a --- /dev/null +++ b/shared/package-files/78/784c33dda4c226d4b91f5a443b3d320bd15f6e7192f88f4cd82dd4f10b2c0530/blob @@ -0,0 +1,1277 @@ +import builtins +import datetime as dt +from string import ascii_lowercase + +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT + +from pandas.core.dtypes.common import pandas_dtype +from pandas.core.dtypes.missing import na_value_for_dtype + +import pandas as pd +from pandas import ( + DataFrame, + MultiIndex, + Series, + Timestamp, + date_range, + isna, +) +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args +from pandas.util import _test_decorators as td + + +@pytest.mark.parametrize("agg_func", ["any", "all"]) +@pytest.mark.parametrize( + "vals", + [ + ["foo", "bar", "baz"], + ["foo", "", ""], + ["", "", ""], + [1, 2, 3], + [1, 0, 0], + [0, 0, 0], + [1.0, 2.0, 3.0], + [1.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [True, True, True], + [True, False, False], + [False, False, False], + [np.nan, np.nan, np.nan], + ], +) +def test_groupby_bool_aggs(skipna, agg_func, vals): + df = DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2}) + + # Figure out expectation using Python builtin + exp = getattr(builtins, agg_func)(vals) + + # edge case for missing data with skipna and 'any' + if skipna and all(isna(vals)) and agg_func == "any": + exp = False + + expected = DataFrame( + [exp] * 2, columns=["val"], index=pd.Index(["a", "b"], name="key") + ) + result = getattr(df.groupby("key"), agg_func)(skipna=skipna) + tm.assert_frame_equal(result, expected) + + +def test_any(): + df = DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], + columns=["A", "B", "C"], + ) + expected = DataFrame( + [[True, True], [False, True]], columns=["B", "C"], index=[1, 3] + ) + expected.index.name = "A" + result = df.groupby("A").any() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +def test_bool_aggs_dup_column_labels(bool_agg_func): + # GH#21668 + df = DataFrame([[True, True]], columns=["a", "a"]) + grp_by = df.groupby([0]) + result = getattr(grp_by, bool_agg_func)() + + expected = df.set_axis(np.array([0])) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +@pytest.mark.parametrize( + "data", + [ + [False, False, False], + [True, True, True], + [pd.NA, pd.NA, pd.NA], + [False, pd.NA, False], + [True, pd.NA, True], + [True, pd.NA, False], + ], +) +def test_masked_kleene_logic(bool_agg_func, skipna, data): + # GH#37506 + ser = Series(data, dtype="boolean") + + # The result should match aggregating on the whole series. Correctness + # there is verified in test_reductions.py::test_any_all_boolean_kleene_logic + expected_data = getattr(ser, bool_agg_func)(skipna=skipna) + expected = Series(expected_data, index=np.array([0]), dtype="boolean") + + result = ser.groupby([0, 0, 0]).agg(bool_agg_func, skipna=skipna) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype1,dtype2,exp_col1,exp_col2", + [ + ( + "float", + "Float64", + np.array([True], dtype=bool), + pd.array([pd.NA], dtype="boolean"), + ), + ( + "Int64", + "float", + pd.array([pd.NA], dtype="boolean"), + np.array([True], dtype=bool), + ), + ( + "Int64", + "Int64", + pd.array([pd.NA], dtype="boolean"), + pd.array([pd.NA], dtype="boolean"), + ), + ( + "Float64", + "boolean", + pd.array([pd.NA], dtype="boolean"), + pd.array([pd.NA], dtype="boolean"), + ), + ], +) +def test_masked_mixed_types(dtype1, dtype2, exp_col1, exp_col2): + # GH#37506 + data = [1.0, np.nan] + df = DataFrame( + {"col1": pd.array(data, dtype=dtype1), "col2": pd.array(data, dtype=dtype2)} + ) + result = df.groupby([1, 1]).agg("all", skipna=False) + + expected = DataFrame({"col1": exp_col1, "col2": exp_col2}, index=np.array([1])) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_masked_bool_aggs_skipna(bool_agg_func, dtype, skipna, frame_or_series): + # GH#40585 + obj = frame_or_series([pd.NA, 1], dtype=dtype) + expected_res = True + if not skipna and bool_agg_func == "all": + expected_res = pd.NA + expected = frame_or_series([expected_res], index=np.array([1]), dtype="boolean") + + result = obj.groupby([1, 1]).agg(bool_agg_func, skipna=skipna) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "bool_agg_func,data,expected_res", + [ + ("any", [pd.NA, np.nan], False), + ("any", [pd.NA, 1, np.nan], True), + ("all", [pd.NA, pd.NaT], True), + ("all", [pd.NA, False, pd.NaT], False), + ], +) +def test_object_type_missing_vals(bool_agg_func, data, expected_res, frame_or_series): + # GH#37501 + obj = frame_or_series(data, dtype=object) + result = obj.groupby([1] * len(data)).agg(bool_agg_func) + expected = frame_or_series([expected_res], index=np.array([1]), dtype="bool") + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +def test_object_NA_raises_with_skipna_false(bool_agg_func): + # GH#37501 + ser = Series([pd.NA], dtype=object) + with pytest.raises(TypeError, match="boolean value of NA is ambiguous"): + ser.groupby([1]).agg(bool_agg_func, skipna=False) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +def test_empty(frame_or_series, bool_agg_func): + # GH 45231 + kwargs = {"columns": ["a"]} if frame_or_series is DataFrame else {"name": "a"} + obj = frame_or_series(**kwargs, dtype=object) + result = getattr(obj.groupby(obj.index), bool_agg_func)() + expected = frame_or_series(**kwargs, dtype=bool) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +def test_idxmin_idxmax_extremes(how, any_real_numpy_dtype): + # GH#57040 + if any_real_numpy_dtype is int or any_real_numpy_dtype is float: + # No need to test + return + info = np.iinfo if "int" in any_real_numpy_dtype else np.finfo + min_value = info(any_real_numpy_dtype).min + max_value = info(any_real_numpy_dtype).max + df = DataFrame( + {"a": [2, 1, 1, 2], "b": [min_value, max_value, max_value, min_value]}, + dtype=any_real_numpy_dtype, + ) + gb = df.groupby("a") + result = getattr(gb, how)() + expected = DataFrame( + {"b": [1, 0]}, index=pd.Index([1, 2], name="a", dtype=any_real_numpy_dtype) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +def test_idxmin_idxmax_extremes_skipna(skipna, how, float_numpy_dtype): + # GH#57040 + min_value = np.finfo(float_numpy_dtype).min + max_value = np.finfo(float_numpy_dtype).max + df = DataFrame( + { + "a": Series(np.repeat(range(1, 6), repeats=2), dtype="intp"), + "b": Series( + [ + np.nan, + min_value, + np.nan, + max_value, + min_value, + np.nan, + max_value, + np.nan, + np.nan, + np.nan, + ], + dtype=float_numpy_dtype, + ), + }, + ) + gb = df.groupby("a") + + warn = None if skipna else FutureWarning + msg = f"The behavior of DataFrameGroupBy.{how} with all-NA values" + with tm.assert_produces_warning(warn, match=msg): + result = getattr(gb, how)(skipna=skipna) + if skipna: + values = [1, 3, 4, 6, np.nan] + else: + values = np.nan + expected = DataFrame( + {"b": values}, index=pd.Index(range(1, 6), name="a", dtype="intp") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "func, values", + [ + ("idxmin", {"c_int": [0, 2], "c_float": [1, 3], "c_date": [1, 2]}), + ("idxmax", {"c_int": [1, 3], "c_float": [0, 2], "c_date": [0, 3]}), + ], +) +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_idxmin_idxmax_returns_int_types(func, values, numeric_only): + # GH 25444 + df = DataFrame( + { + "name": ["A", "A", "B", "B"], + "c_int": [1, 2, 3, 4], + "c_float": [4.02, 3.03, 2.04, 1.05], + "c_date": ["2019", "2018", "2016", "2017"], + } + ) + df["c_date"] = pd.to_datetime(df["c_date"]) + df["c_date_tz"] = df["c_date"].dt.tz_localize("US/Pacific") + df["c_timedelta"] = df["c_date"] - df["c_date"].iloc[0] + df["c_period"] = df["c_date"].dt.to_period("W") + df["c_Integer"] = df["c_int"].astype("Int64") + df["c_Floating"] = df["c_float"].astype("Float64") + + result = getattr(df.groupby("name"), func)(numeric_only=numeric_only) + + expected = DataFrame(values, index=pd.Index(["A", "B"], name="name")) + if numeric_only: + expected = expected.drop(columns=["c_date"]) + else: + expected["c_date_tz"] = expected["c_date"] + expected["c_timedelta"] = expected["c_date"] + expected["c_period"] = expected["c_date"] + expected["c_Integer"] = expected["c_int"] + expected["c_Floating"] = expected["c_float"] + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data", + [ + ( + Timestamp("2011-01-15 12:50:28.502376"), + Timestamp("2011-01-20 12:50:28.593448"), + ), + (24650000000000001, 24650000000000002), + ], +) +@pytest.mark.parametrize("method", ["count", "min", "max", "first", "last"]) +def test_groupby_non_arithmetic_agg_int_like_precision(method, data): + # GH#6620, GH#9311 + df = DataFrame({"a": [1, 1], "b": data}) + + grouped = df.groupby("a") + result = getattr(grouped, method)() + if method == "count": + expected_value = 2 + elif method == "first": + expected_value = data[0] + elif method == "last": + expected_value = data[1] + else: + expected_value = getattr(df["b"], method)() + expected = DataFrame({"b": [expected_value]}, index=pd.Index([1], name="a")) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +def test_first_last_skipna(any_real_nullable_dtype, sort, skipna, how): + # GH#57019 + na_value = na_value_for_dtype(pandas_dtype(any_real_nullable_dtype)) + df = DataFrame( + { + "a": [2, 1, 1, 2, 3, 3], + "b": [na_value, 3.0, na_value, 4.0, np.nan, np.nan], + "c": [na_value, 3.0, na_value, 4.0, np.nan, np.nan], + }, + dtype=any_real_nullable_dtype, + ) + gb = df.groupby("a", sort=sort) + method = getattr(gb, how) + result = method(skipna=skipna) + + ilocs = { + ("first", True): [3, 1, 4], + ("first", False): [0, 1, 4], + ("last", True): [3, 1, 5], + ("last", False): [3, 2, 5], + }[how, skipna] + expected = df.iloc[ilocs].set_index("a") + if sort: + expected = expected.sort_index() + tm.assert_frame_equal(result, expected) + + +def test_idxmin_idxmax_axis1(): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), columns=["A", "B", "C", "D"] + ) + df["A"] = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4] + + gb = df.groupby("A") + + warn_msg = "DataFrameGroupBy.idxmax with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + res = gb.idxmax(axis=1) + + alt = df.iloc[:, 1:].idxmax(axis=1) + indexer = res.index.get_level_values(1) + + tm.assert_series_equal(alt[indexer], res.droplevel("A")) + + df["E"] = date_range("2016-01-01", periods=10) + gb2 = df.groupby("A") + + msg = "'>' not supported between instances of 'Timestamp' and 'float'" + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + gb2.idxmax(axis=1) + + +def test_groupby_mean_no_overflow(): + # Regression test for (#22487) + df = DataFrame( + { + "user": ["A", "A", "A", "A", "A"], + "connections": [4970, 4749, 4719, 4704, 18446744073699999744], + } + ) + assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840 + + +def test_mean_on_timedelta(): + # GH 17382 + df = DataFrame({"time": pd.to_timedelta(range(10)), "cat": ["A", "B"] * 5}) + result = df.groupby("cat")["time"].mean() + expected = Series( + pd.to_timedelta([4, 5]), name="time", index=pd.Index(["A", "B"], name="cat") + ) + tm.assert_series_equal(result, expected) + + +def test_cython_median(): + arr = np.random.default_rng(2).standard_normal(1000) + arr[::2] = np.nan + df = DataFrame(arr) + + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + labels[::17] = np.nan + + result = df.groupby(labels).median() + msg = "using DataFrameGroupBy.median" + with tm.assert_produces_warning(FutureWarning, match=msg): + exp = df.groupby(labels).agg(np.nanmedian) + tm.assert_frame_equal(result, exp) + + df = DataFrame(np.random.default_rng(2).standard_normal((1000, 5))) + msg = "using DataFrameGroupBy.median" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = df.groupby(labels).agg(np.median) + xp = df.groupby(labels).median() + tm.assert_frame_equal(rs, xp) + + +def test_median_empty_bins(observed): + df = DataFrame(np.random.default_rng(2).integers(0, 44, 500)) + + grps = range(0, 55, 5) + bins = pd.cut(df[0], grps) + + result = df.groupby(bins, observed=observed).median() + expected = df.groupby(bins, observed=observed).agg(lambda x: x.median()) + tm.assert_frame_equal(result, expected) + + +def test_max_min_non_numeric(): + # #2700 + aa = DataFrame({"nn": [11, 11, 22, 22], "ii": [1, 2, 3, 4], "ss": 4 * ["mama"]}) + + result = aa.groupby("nn").max() + assert "ss" in result + + result = aa.groupby("nn").max(numeric_only=False) + assert "ss" in result + + result = aa.groupby("nn").min() + assert "ss" in result + + result = aa.groupby("nn").min(numeric_only=False) + assert "ss" in result + + +def test_max_min_object_multiple_columns(using_array_manager, using_infer_string): + # GH#41111 case where the aggregation is valid for some columns but not + # others; we split object blocks column-wise, consistent with + # DataFrame._reduce + + df = DataFrame( + { + "A": [1, 1, 2, 2, 3], + "B": [1, "foo", 2, "bar", False], + "C": ["a", "b", "c", "d", "e"], + } + ) + df._consolidate_inplace() # should already be consolidate, but double-check + if not using_array_manager: + assert len(df._mgr.blocks) == 3 if using_infer_string else 2 + + gb = df.groupby("A") + + result = gb[["C"]].max() + # "max" is valid for column "C" but not for "B" + ei = pd.Index([1, 2, 3], name="A") + expected = DataFrame({"C": ["b", "d", "e"]}, index=ei) + tm.assert_frame_equal(result, expected) + + result = gb[["C"]].min() + # "min" is valid for column "C" but not for "B" + ei = pd.Index([1, 2, 3], name="A") + expected = DataFrame({"C": ["a", "c", "e"]}, index=ei) + tm.assert_frame_equal(result, expected) + + +def test_min_date_with_nans(): + # GH26321 + dates = pd.to_datetime( + Series(["2019-05-09", "2019-05-09", "2019-05-09"]), format="%Y-%m-%d" + ).dt.date + df = DataFrame({"a": [np.nan, "1", np.nan], "b": [0, 1, 1], "c": dates}) + + result = df.groupby("b", as_index=False)["c"].min()["c"] + expected = pd.to_datetime( + Series(["2019-05-09", "2019-05-09"], name="c"), format="%Y-%m-%d" + ).dt.date + tm.assert_series_equal(result, expected) + + result = df.groupby("b")["c"].min() + expected.index.name = "b" + tm.assert_series_equal(result, expected) + + +def test_max_inat(): + # GH#40767 dont interpret iNaT as NaN + ser = Series([1, iNaT]) + key = np.array([1, 1], dtype=np.int64) + gb = ser.groupby(key) + + result = gb.max(min_count=2) + expected = Series({1: 1}, dtype=np.int64) + tm.assert_series_equal(result, expected, check_exact=True) + + result = gb.min(min_count=2) + expected = Series({1: iNaT}, dtype=np.int64) + tm.assert_series_equal(result, expected, check_exact=True) + + # not enough entries -> gets masked to NaN + result = gb.min(min_count=3) + expected = Series({1: np.nan}) + tm.assert_series_equal(result, expected, check_exact=True) + + +def test_max_inat_not_all_na(): + # GH#40767 dont interpret iNaT as NaN + + # make sure we dont round iNaT+1 to iNaT + ser = Series([1, iNaT, 2, iNaT + 1]) + gb = ser.groupby([1, 2, 3, 3]) + result = gb.min(min_count=2) + + # Note: in converting to float64, the iNaT + 1 maps to iNaT, i.e. is lossy + expected = Series({1: np.nan, 2: np.nan, 3: iNaT + 1}) + expected.index = expected.index.astype(int) + tm.assert_series_equal(result, expected, check_exact=True) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_groupby_aggregate_period_column(func): + # GH 31471 + groups = [1, 2] + periods = pd.period_range("2020", periods=2, freq="Y") + df = DataFrame({"a": groups, "b": periods}) + + result = getattr(df.groupby("a")["b"], func)() + idx = pd.Index([1, 2], name="a") + expected = Series(periods, index=idx, name="b") + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_groupby_aggregate_period_frame(func): + # GH 31471 + groups = [1, 2] + periods = pd.period_range("2020", periods=2, freq="Y") + df = DataFrame({"a": groups, "b": periods}) + + result = getattr(df.groupby("a"), func)() + idx = pd.Index([1, 2], name="a") + expected = DataFrame({"b": periods}, index=idx) + + tm.assert_frame_equal(result, expected) + + +def test_aggregate_numeric_object_dtype(): + # https://github.com/pandas-dev/pandas/issues/39329 + # simplified case: multiple object columns where one is all-NaN + # -> gets split as the all-NaN is inferred as float + df = DataFrame( + {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": [np.nan] * 4}, + ).astype(object) + result = df.groupby("key").min() + expected = ( + DataFrame( + {"key": ["A", "B"], "col1": ["a", "c"], "col2": [np.nan, np.nan]}, + ) + .set_index("key") + .astype(object) + ) + tm.assert_frame_equal(result, expected) + + # same but with numbers + df = DataFrame( + {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": range(4)}, + ).astype(object) + result = df.groupby("key").min() + expected = ( + DataFrame({"key": ["A", "B"], "col1": ["a", "c"], "col2": [0, 2]}) + .set_index("key") + .astype(object) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_aggregate_categorical_lost_index(func: str): + # GH: 28641 groupby drops index, when grouping over categorical column with min/max + ds = Series(["b"], dtype="category").cat.as_ordered() + df = DataFrame({"A": [1997], "B": ds}) + result = df.groupby("A").agg({"B": func}) + expected = DataFrame({"B": ["b"]}, index=pd.Index([1997], name="A")) + + # ordered categorical dtype should be preserved + expected["B"] = expected["B"].astype(ds.dtype) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["Int64", "Int32", "Float64", "Float32", "boolean"]) +def test_groupby_min_max_nullable(dtype): + if dtype == "Int64": + # GH#41743 avoid precision loss + ts = 1618556707013635762 + elif dtype == "boolean": + ts = 0 + else: + ts = 4.0 + + df = DataFrame({"id": [2, 2], "ts": [ts, ts + 1]}) + df["ts"] = df["ts"].astype(dtype) + + gb = df.groupby("id") + + result = gb.min() + expected = df.iloc[:1].set_index("id") + tm.assert_frame_equal(result, expected) + + res_max = gb.max() + expected_max = df.iloc[1:].set_index("id") + tm.assert_frame_equal(res_max, expected_max) + + result2 = gb.min(min_count=3) + expected2 = DataFrame({"ts": [pd.NA]}, index=expected.index, dtype=dtype) + tm.assert_frame_equal(result2, expected2) + + res_max2 = gb.max(min_count=3) + tm.assert_frame_equal(res_max2, expected2) + + # Case with NA values + df2 = DataFrame({"id": [2, 2, 2], "ts": [ts, pd.NA, ts + 1]}) + df2["ts"] = df2["ts"].astype(dtype) + gb2 = df2.groupby("id") + + result3 = gb2.min() + tm.assert_frame_equal(result3, expected) + + res_max3 = gb2.max() + tm.assert_frame_equal(res_max3, expected_max) + + result4 = gb2.min(min_count=100) + tm.assert_frame_equal(result4, expected2) + + res_max4 = gb2.max(min_count=100) + tm.assert_frame_equal(res_max4, expected2) + + +def test_min_max_nullable_uint64_empty_group(): + # don't raise NotImplementedError from libgroupby + cat = pd.Categorical([0] * 10, categories=[0, 1]) + df = DataFrame({"A": cat, "B": pd.array(np.arange(10, dtype=np.uint64))}) + gb = df.groupby("A", observed=False) + + res = gb.min() + + idx = pd.CategoricalIndex([0, 1], dtype=cat.dtype, name="A") + expected = DataFrame({"B": pd.array([0, pd.NA], dtype="UInt64")}, index=idx) + tm.assert_frame_equal(res, expected) + + res = gb.max() + expected.iloc[0, 0] = 9 + tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize("func", ["first", "last", "min", "max"]) +def test_groupby_min_max_categorical(func): + # GH: 52151 + df = DataFrame( + { + "col1": pd.Categorical(["A"], categories=list("AB"), ordered=True), + "col2": pd.Categorical([1], categories=[1, 2], ordered=True), + "value": 0.1, + } + ) + result = getattr(df.groupby("col1", observed=False), func)() + + idx = pd.CategoricalIndex(data=["A", "B"], name="col1", ordered=True) + expected = DataFrame( + { + "col2": pd.Categorical([1, None], categories=[1, 2], ordered=True), + "value": [0.1, None], + }, + index=idx, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_min_empty_string_dtype(func, string_dtype_no_object): + # GH#55619 + dtype = string_dtype_no_object + df = DataFrame({"a": ["a"], "b": "a", "c": "a"}, dtype=dtype).iloc[:0] + result = getattr(df.groupby("a"), func)() + expected = DataFrame( + columns=["b", "c"], dtype=dtype, index=pd.Index([], dtype=dtype, name="a") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("min_count", [0, 1]) +@pytest.mark.parametrize("test_series", [True, False]) +def test_string_dtype_all_na( + string_dtype_no_object, reduction_func, min_count, test_series +): + # https://github.com/pandas-dev/pandas/issues/60985 + if reduction_func == "corrwith": + # corrwith is deprecated. + return + + dtype = string_dtype_no_object + + if reduction_func in [ + "any", + "all", + "idxmin", + "idxmax", + "mean", + "median", + "std", + "var", + ]: + kwargs = {} + elif reduction_func in ["kurt"]: + kwargs = {"min_count": min_count} + elif reduction_func in ["count", "nunique", "quantile", "sem", "size"]: + kwargs = {} + else: + kwargs = {"min_count": min_count} + + expected_dtype, expected_value = dtype, pd.NA + if reduction_func in ["all", "any"]: + expected_dtype = "bool" + # TODO: For skipna=False, bool(pd.NA) raises; should groupby? + expected_value = False if reduction_func == "any" else True + elif reduction_func in ["count", "nunique", "size"]: + # TODO: Should be more consistent - return Int64 when dtype.na_value is pd.NA? + if ( + test_series + and reduction_func == "size" + and dtype.storage == "pyarrow" + and dtype.na_value is pd.NA + ): + expected_dtype = "Int64" + else: + expected_dtype = "int64" + expected_value = 1 if reduction_func == "size" else 0 + elif reduction_func in ["idxmin", "idxmax"]: + expected_dtype, expected_value = "float64", np.nan + elif min_count > 0: + expected_value = pd.NA + elif reduction_func == "sum": + # https://github.com/pandas-dev/pandas/pull/60936 + expected_value = "" + + df = DataFrame({"a": ["x"], "b": [pd.NA]}, dtype=dtype) + obj = df["b"] if test_series else df + args = get_groupby_method_args(reduction_func, obj) + gb = obj.groupby(df["a"]) + method = getattr(gb, reduction_func) + + if reduction_func in [ + "mean", + "median", + "kurt", + "prod", + "quantile", + "sem", + "skew", + "std", + "var", + ]: + msg = f"dtype '{dtype}' does not support operation '{reduction_func}'" + with pytest.raises(TypeError, match=msg): + method(*args, **kwargs) + return + + result = method(*args, **kwargs) + index = pd.Index(["x"], name="a", dtype=dtype) + if test_series or reduction_func == "size": + name = None if not test_series and reduction_func == "size" else "b" + expected = Series(expected_value, index=index, dtype=expected_dtype, name=name) + else: + expected = DataFrame({"b": expected_value}, index=index, dtype=expected_dtype) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("min_count", [0, 1]) +def test_string_dtype_empty_sum(string_dtype_no_object, min_count): + # https://github.com/pandas-dev/pandas/issues/60229 + dtype = string_dtype_no_object + df = DataFrame({"a": ["x"], "b": [pd.NA]}, dtype=dtype) + gb = df.groupby("a") + result = gb.sum(min_count=min_count) + value = "" if min_count == 0 else pd.NA + expected = DataFrame( + {"b": value}, index=pd.Index(["x"], name="a", dtype=dtype), dtype=dtype + ) + tm.assert_frame_equal(result, expected) + + +def test_max_nan_bug(): + df = DataFrame( + { + "Unnamed: 0": ["-04-23", "-05-06", "-05-07"], + "Date": [ + "2013-04-23 00:00:00", + "2013-05-06 00:00:00", + "2013-05-07 00:00:00", + ], + "app": Series([np.nan, np.nan, "OE"]), + "File": ["log080001.log", "log.log", "xlsx"], + } + ) + gb = df.groupby("Date") + r = gb[["File"]].max() + e = gb["File"].max().to_frame() + tm.assert_frame_equal(r, e) + assert not r["File"].isna().any() + + +@pytest.mark.slow +@pytest.mark.parametrize("sort", [False, True]) +@pytest.mark.parametrize("dropna", [False, True]) +@pytest.mark.parametrize("as_index", [True, False]) +@pytest.mark.parametrize("with_nan", [True, False]) +@pytest.mark.parametrize("keys", [["joe"], ["joe", "jim"]]) +def test_series_groupby_nunique(sort, dropna, as_index, with_nan, keys): + n = 100 + m = 10 + days = date_range("2015-08-23", periods=10) + df = DataFrame( + { + "jim": np.random.default_rng(2).choice(list(ascii_lowercase), n), + "joe": np.random.default_rng(2).choice(days, n), + "julie": np.random.default_rng(2).integers(0, m, n), + } + ) + if with_nan: + df = df.astype({"julie": float}) # Explicit cast to avoid implicit cast below + df.loc[1::17, "jim"] = None + df.loc[3::37, "joe"] = None + df.loc[7::19, "julie"] = None + df.loc[8::19, "julie"] = None + df.loc[9::19, "julie"] = None + original_df = df.copy() + gr = df.groupby(keys, as_index=as_index, sort=sort) + left = gr["julie"].nunique(dropna=dropna) + + gr = df.groupby(keys, as_index=as_index, sort=sort) + right = gr["julie"].apply(Series.nunique, dropna=dropna) + if not as_index: + right = right.reset_index(drop=True) + + if as_index: + tm.assert_series_equal(left, right, check_names=False) + else: + tm.assert_frame_equal(left, right, check_names=False) + tm.assert_frame_equal(df, original_df) + + +def test_nunique(): + df = DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")}) + + expected = DataFrame({"A": list("abc"), "B": [1, 2, 1], "C": [1, 1, 2]}) + result = df.groupby("A", as_index=False).nunique() + tm.assert_frame_equal(result, expected) + + # as_index + expected.index = list("abc") + expected.index.name = "A" + expected = expected.drop(columns="A") + result = df.groupby("A").nunique() + tm.assert_frame_equal(result, expected) + + # with na + result = df.replace({"x": None}).groupby("A").nunique(dropna=False) + tm.assert_frame_equal(result, expected) + + # dropna + expected = DataFrame({"B": [1] * 3, "C": [1] * 3}, index=list("abc")) + expected.index.name = "A" + result = df.replace({"x": None}).groupby("A").nunique() + tm.assert_frame_equal(result, expected) + + +def test_nunique_with_object(): + # GH 11077 + data = DataFrame( + [ + [100, 1, "Alice"], + [200, 2, "Bob"], + [300, 3, "Charlie"], + [-400, 4, "Dan"], + [500, 5, "Edith"], + ], + columns=["amount", "id", "name"], + ) + + result = data.groupby(["id", "amount"])["name"].nunique() + index = MultiIndex.from_arrays([data.id, data.amount]) + expected = Series([1] * 5, name="name", index=index) + tm.assert_series_equal(result, expected) + + +def test_nunique_with_empty_series(): + # GH 12553 + data = Series(name="name", dtype=object) + result = data.groupby(level=0).nunique() + expected = Series(name="name", dtype="int64") + tm.assert_series_equal(result, expected) + + +def test_nunique_with_timegrouper(): + # GH 13453 + test = DataFrame( + { + "time": [ + Timestamp("2016-06-28 09:35:35"), + Timestamp("2016-06-28 16:09:30"), + Timestamp("2016-06-28 16:46:28"), + ], + "data": ["1", "2", "3"], + } + ).set_index("time") + result = test.groupby(pd.Grouper(freq="h"))["data"].nunique() + expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(Series.nunique) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "key, data, dropna, expected", + [ + ( + ["x", "x", "x"], + [Timestamp("2019-01-01"), pd.NaT, Timestamp("2019-01-01")], + True, + Series([1], index=pd.Index(["x"], name="key"), name="data"), + ), + ( + ["x", "x", "x"], + [dt.date(2019, 1, 1), pd.NaT, dt.date(2019, 1, 1)], + True, + Series([1], index=pd.Index(["x"], name="key"), name="data"), + ), + ( + ["x", "x", "x", "y", "y"], + [ + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + ], + False, + Series([2, 2], index=pd.Index(["x", "y"], name="key"), name="data"), + ), + ( + ["x", "x", "x", "x", "y"], + [ + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + ], + False, + Series([2, 1], index=pd.Index(["x", "y"], name="key"), name="data"), + ), + ], +) +def test_nunique_with_NaT(key, data, dropna, expected): + # GH 27951 + df = DataFrame({"key": key, "data": data}) + result = df.groupby(["key"])["data"].nunique(dropna=dropna) + tm.assert_series_equal(result, expected) + + +def test_nunique_preserves_column_level_names(): + # GH 23222 + test = DataFrame([1, 2, 2], columns=pd.Index(["A"], name="level_0")) + result = test.groupby([0, 0, 0]).nunique() + expected = DataFrame([2], index=np.array([0]), columns=test.columns) + tm.assert_frame_equal(result, expected) + + +def test_nunique_transform_with_datetime(): + # GH 35109 - transform with nunique on datetimes results in integers + df = DataFrame(date_range("2008-12-31", "2009-01-02"), columns=["date"]) + result = df.groupby([0, 0, 1])["date"].transform("nunique") + expected = Series([2, 2, 1], name="date") + tm.assert_series_equal(result, expected) + + +def test_empty_categorical(observed): + # GH#21334 + cat = Series([1]).astype("category") + ser = cat[:0] + gb = ser.groupby(ser, observed=observed) + result = gb.nunique() + if observed: + expected = Series([], index=cat[:0], dtype="int64") + else: + expected = Series([0], index=cat, dtype="int64") + tm.assert_series_equal(result, expected) + + +def test_intercept_builtin_sum(): + s = Series([1.0, 2.0, np.nan, 3.0]) + grouped = s.groupby([0, 1, 2, 2]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = grouped.agg(builtins.sum) + msg = "using np.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result2 = grouped.apply(builtins.sum) + expected = grouped.sum() + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) + + +@pytest.mark.parametrize("min_count", [0, 10]) +def test_groupby_sum_mincount_boolean(min_count): + b = True + a = False + na = np.nan + dfg = pd.array([b, b, na, na, a, a, b], dtype="boolean") + + df = DataFrame({"A": [1, 1, 2, 2, 3, 3, 1], "B": dfg}) + result = df.groupby("A").sum(min_count=min_count) + if min_count == 0: + expected = DataFrame( + {"B": pd.array([3, 0, 0], dtype="Int64")}, + index=pd.Index([1, 2, 3], name="A"), + ) + tm.assert_frame_equal(result, expected) + else: + expected = DataFrame( + {"B": pd.array([pd.NA] * 3, dtype="Int64")}, + index=pd.Index([1, 2, 3], name="A"), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_sum_below_mincount_nullable_integer(): + # https://github.com/pandas-dev/pandas/issues/32861 + df = DataFrame({"a": [0, 1, 2], "b": [0, 1, 2], "c": [0, 1, 2]}, dtype="Int64") + grouped = df.groupby("a") + idx = pd.Index([0, 1, 2], name="a", dtype="Int64") + + result = grouped["b"].sum(min_count=2) + expected = Series([pd.NA] * 3, dtype="Int64", index=idx, name="b") + tm.assert_series_equal(result, expected) + + result = grouped.sum(min_count=2) + expected = DataFrame({"b": [pd.NA] * 3, "c": [pd.NA] * 3}, dtype="Int64", index=idx) + tm.assert_frame_equal(result, expected) + + +def test_groupby_sum_timedelta_with_nat(): + # GH#42659 + df = DataFrame( + { + "a": [1, 1, 2, 2], + "b": [pd.Timedelta("1d"), pd.Timedelta("2d"), pd.Timedelta("3d"), pd.NaT], + } + ) + td3 = pd.Timedelta(days=3) + + gb = df.groupby("a") + + res = gb.sum() + expected = DataFrame({"b": [td3, td3]}, index=pd.Index([1, 2], name="a")) + tm.assert_frame_equal(res, expected) + + res = gb["b"].sum() + tm.assert_series_equal(res, expected["b"]) + + res = gb["b"].sum(min_count=2) + expected = Series([td3, pd.NaT], dtype="m8[ns]", name="b", index=expected.index) + tm.assert_series_equal(res, expected) + + +@pytest.mark.parametrize( + "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"] +) +@pytest.mark.parametrize( + "method,data", + [ + ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), + ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), + ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), + ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), + ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}), + ], +) +def test_groupby_non_arithmetic_agg_types(dtype, method, data): + # GH9311, GH6620 + df = DataFrame( + [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}] + ) + + df["b"] = df.b.astype(dtype) + + if "args" not in data: + data["args"] = [] + + if "out_type" in data: + out_type = data["out_type"] + else: + out_type = dtype + + exp = data["df"] + df_out = DataFrame(exp) + + df_out["b"] = df_out.b.astype(out_type) + df_out.set_index("a", inplace=True) + + grpd = df.groupby("a") + t = getattr(grpd, method)(*data["args"]) + tm.assert_frame_equal(t, df_out) + + +def scipy_sem(*args, **kwargs): + from scipy.stats import sem + + return sem(*args, ddof=1, **kwargs) + + +@pytest.mark.parametrize( + "op,targop", + [ + ("mean", np.mean), + ("median", np.median), + ("std", np.std), + ("var", np.var), + ("sum", np.sum), + ("prod", np.prod), + ("min", np.min), + ("max", np.max), + ("first", lambda x: x.iloc[0]), + ("last", lambda x: x.iloc[-1]), + ("count", np.size), + pytest.param("sem", scipy_sem, marks=td.skip_if_no("scipy")), + ], +) +def test_ops_general(op, targop): + df = DataFrame(np.random.default_rng(2).standard_normal(1000)) + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + + result = getattr(df.groupby(labels), op)() + warn = None if op in ("first", "last", "count", "sem") else FutureWarning + msg = f"using DataFrameGroupBy.{op}" + with tm.assert_produces_warning(warn, match=msg): + expected = df.groupby(labels).agg(targop) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "values", + [ + { + "a": [1, 1, 1, 2, 2, 2, 3, 3, 3], + "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2], + }, + {"a": [1, 1, 2, 2, 3, 3], "b": [1, 2, 1, 2, 1, 2]}, + ], +) +@pytest.mark.parametrize("function", ["mean", "median", "var"]) +def test_apply_to_nullable_integer_returns_float(values, function): + # https://github.com/pandas-dev/pandas/issues/32219 + output = 0.5 if function == "var" else 1.5 + arr = np.array([output] * 3, dtype=float) + idx = pd.Index([1, 2, 3], name="a", dtype="Int64") + expected = DataFrame({"b": arr}, index=idx).astype("Float64") + + groups = DataFrame(values, dtype="Int64").groupby("a") + + result = getattr(groups, function)() + tm.assert_frame_equal(result, expected) + + result = groups.agg(function) + tm.assert_frame_equal(result, expected) + + result = groups.agg([function]) + expected.columns = MultiIndex.from_tuples([("b", function)]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op", + [ + "sum", + "prod", + "min", + "max", + "median", + "mean", + "skew", + "std", + "var", + "sem", + ], +) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("skipna", [True, False]) +@pytest.mark.parametrize("sort", [True, False]) +def test_regression_allowlist_methods(op, axis, skipna, sort): + # GH6944 + # GH 17537 + # explicitly test the allowlist methods + raw_frame = DataFrame([0]) + if axis == 0: + frame = raw_frame + msg = "The 'axis' keyword in DataFrame.groupby is deprecated and will be" + else: + frame = raw_frame.T + msg = "DataFrame.groupby with axis=1 is deprecated" + + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = frame.groupby(level=0, axis=axis, sort=sort) + + if op == "skew": + # skew has skipna + result = getattr(grouped, op)(skipna=skipna) + expected = frame.groupby(level=0).apply( + lambda h: getattr(h, op)(axis=axis, skipna=skipna) + ) + if sort: + expected = expected.sort_index(axis=axis) + tm.assert_frame_equal(result, expected) + else: + result = getattr(grouped, op)() + expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(axis=axis)) + if sort: + expected = expected.sort_index(axis=axis) + tm.assert_frame_equal(result, expected) + + +def test_groupby_prod_with_int64_dtype(): + # GH#46573 + data = [ + [1, 11], + [1, 41], + [1, 17], + [1, 37], + [1, 7], + [1, 29], + [1, 31], + [1, 2], + [1, 3], + [1, 43], + [1, 5], + [1, 47], + [1, 19], + [1, 88], + ] + df = DataFrame(data, columns=["A", "B"], dtype="int64") + result = df.groupby(["A"]).prod().reset_index() + expected = DataFrame({"A": [1], "B": [180970905912331920]}, dtype="int64") + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/78/784d22f1ac51580d0653ade6b824084705f607215de26e785d55236d7425c079/blob b/shared/package-files/78/784d22f1ac51580d0653ade6b824084705f607215de26e785d55236d7425c079/blob new file mode 100644 index 0000000000000000000000000000000000000000..e0e1aa603be317bc5167b80d049e0eb54919f96c --- /dev/null +++ b/shared/package-files/78/784d22f1ac51580d0653ade6b824084705f607215de26e785d55236d7425c079/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_renorm : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/78/784fc1b2f8536c06af9364adf03e05edf0a4a5c94f09e5978243b71b9542b959/blob b/shared/package-files/78/784fc1b2f8536c06af9364adf03e05edf0a4a5c94f09e5978243b71b9542b959/blob new file mode 100644 index 0000000000000000000000000000000000000000..d4a0bf1ed572da393a18e1fbb96332c6586c5dcb Binary files /dev/null and b/shared/package-files/78/784fc1b2f8536c06af9364adf03e05edf0a4a5c94f09e5978243b71b9542b959/blob differ diff --git a/shared/package-files/78/785132032c12fa38abbb1103774d91b41828fdc5027e1fe4d42053476eb28199/blob b/shared/package-files/78/785132032c12fa38abbb1103774d91b41828fdc5027e1fe4d42053476eb28199/blob new file mode 100644 index 0000000000000000000000000000000000000000..0178270acb49d01effd9b4aca902fdbe4930218f Binary files /dev/null and b/shared/package-files/78/785132032c12fa38abbb1103774d91b41828fdc5027e1fe4d42053476eb28199/blob differ diff --git a/shared/package-files/78/785285de017a761db9d6fd603c578a79892cfd23c9b046bac4de4fb01589ee96/blob b/shared/package-files/78/785285de017a761db9d6fd603c578a79892cfd23c9b046bac4de4fb01589ee96/blob new file mode 100644 index 0000000000000000000000000000000000000000..05e8a7e8bc91981b5aba471b6203ad2b33b74697 Binary files /dev/null and b/shared/package-files/78/785285de017a761db9d6fd603c578a79892cfd23c9b046bac4de4fb01589ee96/blob differ diff --git a/shared/package-files/78/7853094a7cf576ad680222d11e89da93edb0b54cb4c08e84aaabdd90f5687c1c/blob b/shared/package-files/78/7853094a7cf576ad680222d11e89da93edb0b54cb4c08e84aaabdd90f5687c1c/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ff6b74ff5324aee3b16ba2f3c5704971b07be2a --- /dev/null +++ b/shared/package-files/78/7853094a7cf576ad680222d11e89da93edb0b54cb4c08e84aaabdd90f5687c1c/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor diagonal(const at::Tensor & self, at::Dimname outdim, at::Dimname dim1, at::Dimname dim2, int64_t offset=0); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/78/78533a0f60a22e0aec9b03792909bf918af321d1bb96615752e52236816b7a51/blob b/shared/package-files/78/78533a0f60a22e0aec9b03792909bf918af321d1bb96615752e52236816b7a51/blob new file mode 100644 index 0000000000000000000000000000000000000000..e38144f4c615b22c864a5b385e3b73fd74374f83 --- /dev/null +++ b/shared/package-files/78/78533a0f60a22e0aec9b03792909bf918af321d1bb96615752e52236816b7a51/blob @@ -0,0 +1,426 @@ +""" +This file contains a minimal set of tests for compliance with the extension +array interface test suite, and should contain no other tests. +The test suite for the full functionality of the array is located in +`pandas/tests/arrays/`. + +The tests in this file are inherited from the BaseExtensionTests, and only +minimal tweaks should be applied to get the tests passing (by overwriting a +parent method). + +Additional tests should either be added to one of the BaseExtensionTests +classes (if they are relevant for the extension interface for all dtypes), or +be added to the array-specific tests in `pandas/tests/arrays/`. + +Note: we do not bother with base.BaseIndexTests because NumpyExtensionArray +will never be held in an Index. +""" +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import NumpyEADtype + +import pandas as pd +import pandas._testing as tm +from pandas.api.types import is_object_dtype +from pandas.core.arrays.numpy_ import NumpyExtensionArray +from pandas.tests.extension import base + +orig_assert_attr_equal = tm.assert_attr_equal + + +def _assert_attr_equal(attr: str, left, right, obj: str = "Attributes"): + """ + patch tm.assert_attr_equal so NumpyEADtype("object") is closed enough to + np.dtype("object") + """ + if attr == "dtype": + lattr = getattr(left, "dtype", None) + rattr = getattr(right, "dtype", None) + if isinstance(lattr, NumpyEADtype) and not isinstance(rattr, NumpyEADtype): + left = left.astype(lattr.numpy_dtype) + elif isinstance(rattr, NumpyEADtype) and not isinstance(lattr, NumpyEADtype): + right = right.astype(rattr.numpy_dtype) + + orig_assert_attr_equal(attr, left, right, obj) + + +@pytest.fixture(params=["float", "object"]) +def dtype(request): + return NumpyEADtype(np.dtype(request.param)) + + +@pytest.fixture +def allow_in_pandas(monkeypatch): + """ + A monkeypatch to tells pandas to let us in. + + By default, passing a NumpyExtensionArray to an index / series / frame + constructor will unbox that NumpyExtensionArray to an ndarray, and treat + it as a non-EA column. We don't want people using EAs without + reason. + + The mechanism for this is a check against ABCNumpyExtensionArray + in each constructor. + + But, for testing, we need to allow them in pandas. So we patch + the _typ of NumpyExtensionArray, so that we evade the ABCNumpyExtensionArray + check. + """ + with monkeypatch.context() as m: + m.setattr(NumpyExtensionArray, "_typ", "extension") + m.setattr(tm.asserters, "assert_attr_equal", _assert_attr_equal) + yield + + +@pytest.fixture +def data(allow_in_pandas, dtype): + if dtype.numpy_dtype == "object": + return pd.Series([(i,) for i in range(100)]).array + return NumpyExtensionArray(np.arange(1, 101, dtype=dtype._dtype)) + + +@pytest.fixture +def data_missing(allow_in_pandas, dtype): + if dtype.numpy_dtype == "object": + return NumpyExtensionArray(np.array([np.nan, (1,)], dtype=object)) + return NumpyExtensionArray(np.array([np.nan, 1.0])) + + +@pytest.fixture +def na_cmp(): + def cmp(a, b): + return np.isnan(a) and np.isnan(b) + + return cmp + + +@pytest.fixture +def data_for_sorting(allow_in_pandas, dtype): + """Length-3 array with a known sort order. + + This should be three items [B, C, A] with + A < B < C + """ + if dtype.numpy_dtype == "object": + # Use an empty tuple for first element, then remove, + # to disable np.array's shape inference. + return NumpyExtensionArray(np.array([(), (2,), (3,), (1,)], dtype=object)[1:]) + return NumpyExtensionArray(np.array([1, 2, 0])) + + +@pytest.fixture +def data_missing_for_sorting(allow_in_pandas, dtype): + """Length-3 array with a known sort order. + + This should be three items [B, NA, A] with + A < B and NA missing. + """ + if dtype.numpy_dtype == "object": + return NumpyExtensionArray(np.array([(1,), np.nan, (0,)], dtype=object)) + return NumpyExtensionArray(np.array([1, np.nan, 0])) + + +@pytest.fixture +def data_for_grouping(allow_in_pandas, dtype): + """Data for factorization, grouping, and unique tests. + + Expected to be like [B, B, NA, NA, A, A, B, C] + + Where A < B < C and NA is missing + """ + if dtype.numpy_dtype == "object": + a, b, c = (1,), (2,), (3,) + else: + a, b, c = np.arange(3) + return NumpyExtensionArray( + np.array([b, b, np.nan, np.nan, a, a, b, c], dtype=dtype.numpy_dtype) + ) + + +@pytest.fixture +def data_for_twos(dtype): + if dtype.kind == "O": + pytest.skip(f"{dtype} is not a numeric dtype") + arr = np.ones(100) * 2 + return NumpyExtensionArray._from_sequence(arr, dtype=dtype) + + +@pytest.fixture +def skip_numpy_object(dtype, request): + """ + Tests for NumpyExtensionArray with nested data. Users typically won't create + these objects via `pd.array`, but they can show up through `.array` + on a Series with nested data. Many of the base tests fail, as they aren't + appropriate for nested data. + + This fixture allows these tests to be skipped when used as a usefixtures + marker to either an individual test or a test class. + """ + if dtype == "object": + mark = pytest.mark.xfail(reason="Fails for object dtype") + request.applymarker(mark) + + +skip_nested = pytest.mark.usefixtures("skip_numpy_object") + + +class TestNumpyExtensionArray(base.ExtensionTests): + @pytest.mark.skip(reason="We don't register our dtype") + # We don't want to register. This test should probably be split in two. + def test_from_dtype(self, data): + pass + + @skip_nested + def test_series_constructor_scalar_with_index(self, data, dtype): + # ValueError: Length of passed values is 1, index implies 3. + super().test_series_constructor_scalar_with_index(data, dtype) + + def test_check_dtype(self, data, request, using_infer_string): + if data.dtype.numpy_dtype == "object": + request.applymarker( + pytest.mark.xfail( + reason=f"NumpyExtensionArray expectedly clashes with a " + f"NumPy name: {data.dtype.numpy_dtype}" + ) + ) + super().test_check_dtype(data) + + def test_is_not_object_type(self, dtype, request): + if dtype.numpy_dtype == "object": + # Different from BaseDtypeTests.test_is_not_object_type + # because NumpyEADtype(object) is an object type + assert is_object_dtype(dtype) + else: + super().test_is_not_object_type(dtype) + + @skip_nested + def test_getitem_scalar(self, data): + # AssertionError + super().test_getitem_scalar(data) + + @skip_nested + def test_shift_fill_value(self, data): + # np.array shape inference. Shift implementation fails. + super().test_shift_fill_value(data) + + @skip_nested + def test_fillna_copy_frame(self, data_missing): + # The "scalar" for this array isn't a scalar. + super().test_fillna_copy_frame(data_missing) + + @skip_nested + def test_fillna_copy_series(self, data_missing): + # The "scalar" for this array isn't a scalar. + super().test_fillna_copy_series(data_missing) + + @skip_nested + def test_searchsorted(self, data_for_sorting, as_series): + # TODO: NumpyExtensionArray.searchsorted calls ndarray.searchsorted which + # isn't quite what we want in nested data cases. Instead we need to + # adapt something like libindex._bin_search. + super().test_searchsorted(data_for_sorting, as_series) + + @pytest.mark.xfail(reason="NumpyExtensionArray.diff may fail on dtype") + def test_diff(self, data, periods): + return super().test_diff(data, periods) + + def test_insert(self, data, request): + if data.dtype.numpy_dtype == object: + mark = pytest.mark.xfail(reason="Dimension mismatch in np.concatenate") + request.applymarker(mark) + + super().test_insert(data) + + @skip_nested + def test_insert_invalid(self, data, invalid_scalar): + # NumpyExtensionArray[object] can hold anything, so skip + super().test_insert_invalid(data, invalid_scalar) + + divmod_exc = None + series_scalar_exc = None + frame_scalar_exc = None + series_array_exc = None + + def test_divmod(self, data): + divmod_exc = None + if data.dtype.kind == "O": + divmod_exc = TypeError + self.divmod_exc = divmod_exc + super().test_divmod(data) + + def test_divmod_series_array(self, data): + ser = pd.Series(data) + exc = None + if data.dtype.kind == "O": + exc = TypeError + self.divmod_exc = exc + self._check_divmod_op(ser, divmod, data) + + def test_arith_series_with_scalar(self, data, all_arithmetic_operators, request): + opname = all_arithmetic_operators + series_scalar_exc = None + if data.dtype.numpy_dtype == object: + if opname in ["__mul__", "__rmul__"]: + mark = pytest.mark.xfail( + reason="the Series.combine step raises but not the Series method." + ) + request.node.add_marker(mark) + series_scalar_exc = TypeError + self.series_scalar_exc = series_scalar_exc + super().test_arith_series_with_scalar(data, all_arithmetic_operators) + + def test_arith_series_with_array(self, data, all_arithmetic_operators): + opname = all_arithmetic_operators + series_array_exc = None + if data.dtype.numpy_dtype == object and opname not in ["__add__", "__radd__"]: + series_array_exc = TypeError + self.series_array_exc = series_array_exc + super().test_arith_series_with_array(data, all_arithmetic_operators) + + def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request): + opname = all_arithmetic_operators + frame_scalar_exc = None + if data.dtype.numpy_dtype == object: + if opname in ["__mul__", "__rmul__"]: + mark = pytest.mark.xfail( + reason="the Series.combine step raises but not the Series method." + ) + request.node.add_marker(mark) + frame_scalar_exc = TypeError + self.frame_scalar_exc = frame_scalar_exc + super().test_arith_frame_with_scalar(data, all_arithmetic_operators) + + def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool: + if ser.dtype.kind == "O": + return op_name in ["sum", "min", "max", "any", "all"] + return True + + def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool): + res_op = getattr(ser, op_name) + # avoid coercing int -> float. Just cast to the actual numpy type. + # error: Item "ExtensionDtype" of "dtype[Any] | ExtensionDtype" has + # no attribute "numpy_dtype" + cmp_dtype = ser.dtype.numpy_dtype # type: ignore[union-attr] + alt = ser.astype(cmp_dtype) + exp_op = getattr(alt, op_name) + if op_name == "count": + result = res_op() + expected = exp_op() + else: + result = res_op(skipna=skipna) + expected = exp_op(skipna=skipna) + tm.assert_almost_equal(result, expected) + + @pytest.mark.skip("TODO: tests not written yet") + @pytest.mark.parametrize("skipna", [True, False]) + def test_reduce_frame(self, data, all_numeric_reductions, skipna): + pass + + @skip_nested + def test_fillna_series(self, data_missing): + # Non-scalar "scalar" values. + super().test_fillna_series(data_missing) + + @skip_nested + def test_fillna_frame(self, data_missing): + # Non-scalar "scalar" values. + super().test_fillna_frame(data_missing) + + @skip_nested + def test_setitem_invalid(self, data, invalid_scalar): + # object dtype can hold anything, so doesn't raise + super().test_setitem_invalid(data, invalid_scalar) + + @skip_nested + def test_setitem_sequence_broadcasts(self, data, box_in_series): + # ValueError: cannot set using a list-like indexer with a different + # length than the value + super().test_setitem_sequence_broadcasts(data, box_in_series) + + @skip_nested + @pytest.mark.parametrize("setter", ["loc", None]) + def test_setitem_mask_broadcast(self, data, setter): + # ValueError: cannot set using a list-like indexer with a different + # length than the value + super().test_setitem_mask_broadcast(data, setter) + + @skip_nested + def test_setitem_scalar_key_sequence_raise(self, data): + # Failed: DID NOT RAISE + super().test_setitem_scalar_key_sequence_raise(data) + + # TODO: there is some issue with NumpyExtensionArray, therefore, + # skip the setitem test for now, and fix it later (GH 31446) + + @skip_nested + @pytest.mark.parametrize( + "mask", + [ + np.array([True, True, True, False, False]), + pd.array([True, True, True, False, False], dtype="boolean"), + ], + ids=["numpy-array", "boolean-array"], + ) + def test_setitem_mask(self, data, mask, box_in_series): + super().test_setitem_mask(data, mask, box_in_series) + + @skip_nested + @pytest.mark.parametrize( + "idx", + [[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])], + ids=["list", "integer-array", "numpy-array"], + ) + def test_setitem_integer_array(self, data, idx, box_in_series): + super().test_setitem_integer_array(data, idx, box_in_series) + + @pytest.mark.parametrize( + "idx, box_in_series", + [ + ([0, 1, 2, pd.NA], False), + pytest.param([0, 1, 2, pd.NA], True, marks=pytest.mark.xfail), + (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False), + (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False), + ], + ids=["list-False", "list-True", "integer-array-False", "integer-array-True"], + ) + def test_setitem_integer_with_missing_raises(self, data, idx, box_in_series): + super().test_setitem_integer_with_missing_raises(data, idx, box_in_series) + + @skip_nested + def test_setitem_slice(self, data, box_in_series): + super().test_setitem_slice(data, box_in_series) + + @skip_nested + def test_setitem_loc_iloc_slice(self, data): + super().test_setitem_loc_iloc_slice(data) + + def test_setitem_with_expansion_dataframe_column(self, data, full_indexer): + # https://github.com/pandas-dev/pandas/issues/32395 + df = expected = pd.DataFrame({"data": pd.Series(data)}) + result = pd.DataFrame(index=df.index) + + # because result has object dtype, the attempt to do setting inplace + # is successful, and object dtype is retained + key = full_indexer(df) + result.loc[key, "data"] = df["data"] + + # base class method has expected = df; NumpyExtensionArray behaves oddly because + # we patch _typ for these tests. + if data.dtype.numpy_dtype != object: + if not isinstance(key, slice) or key != slice(None): + expected = pd.DataFrame({"data": data.to_numpy()}) + tm.assert_frame_equal(result, expected, check_column_type=False) + + @pytest.mark.xfail(reason="NumpyEADtype is unpacked") + def test_index_from_listlike_with_dtype(self, data): + super().test_index_from_listlike_with_dtype(data) + + @skip_nested + @pytest.mark.parametrize("engine", ["c", "python"]) + def test_EA_types(self, engine, data, request): + super().test_EA_types(engine, data, request) + + +class Test2DCompat(base.NDArrayBacked2DTests): + pass diff --git a/shared/package-files/78/7856697c69d4d284e6f35b69ab89e6e4ed55609733bd6c1391bc4a4bf97851bb/blob b/shared/package-files/78/7856697c69d4d284e6f35b69ab89e6e4ed55609733bd6c1391bc4a4bf97851bb/blob new file mode 100644 index 0000000000000000000000000000000000000000..c4b2211affb885ac1a91d01044ee274f8de4a3b0 --- /dev/null +++ b/shared/package-files/78/7856697c69d4d284e6f35b69ab89e6e4ed55609733bd6c1391bc4a4bf97851bb/blob @@ -0,0 +1,124 @@ +"r1","r2","r3","detN","m","detPmu","v","F","a1","a2","a3","detP","alphahat1","alphahat2","alphahat3","detV","muhat","detVmu","etahat","detVeta","epshat","Veps" +-0.298623564903529,0.0464543466183151,0.0155764625711166,0.0242491880845054,0,1.58276997,0.100000000000001,1.58276997,0.0785657999924686,0.100000000000001,0.0785658000574788,-1.98867004970709e-33,0.100000000000001,0.0431810197065789,0.0064820640700806,-1.03860333849967e-16,0.100000000000001,-3.68702782332918e-16,-0.158493232715932,0.0637243089732459,0,0 +0.0603655798179575,-0.14390542078167,0.0407038430096027,0.0276779497711476,0.0785657999924686,0.605791761367426,-0.17856579999247,0.605791761367426,-0.0343241666130994,-0.100000000000001,0.100000000000001,0,-0.100000000000001,0.100000000000001,0.0431810197065789,4.105768418189e-49,-0.100000000000001,-1.33992057656705e-16,0.0320387839895037,0.0353382930189409,0,0 +0.157745128130055,0.0135688392188804,-0.158932426756006,0.0296522664457274,-0.0343241666130994,0.568604935405402,0.0343241666130994,0.568604935405402,0.0162774200000002,0,-0.100000000000001,0,1.49096494423489e-19,-0.100000000000001,0.100000000000001,0,1.49096494423489e-19,-3.52730088834138e-52,0.0837225800000012,0,0,0 +-0.615932407579599,0.0766373147374974,0.0722433610770428,0.0296522664457274,0.0162774200000002,0.5307459,0.0837225800000012,0.5307459,0.0269036000000004,0.100000000000001,0,0,0.100000000000001,0,-0.100000000000001,0,0.100000000000001,0,-0.326903600000001,0,0,0 +0.279974503806813,0.0790743646629044,0.0499665795380055,0.0296522664457274,0.0269036000000004,0.5307459,-0.326903600000001,0.5307459,-0.14859532,-0.300000000000001,0.100000000000001,0,-0.300000000000001,0.100000000000001,0,0,-0.300000000000001,0,0.14859532,0,0,0 +0.19364226836232,-0.0564913040249382,0.0606277504437609,0.0296522664457274,-0.14859532,0.5307459,0.14859532,0.5307459,-0.00277483999999972,-2.77555756156289e-17,-0.300000000000001,0,-2.77555756156289e-17,-0.300000000000001,0.100000000000001,0,-2.77555756156289e-17,0,0.102774840000001,0,0,0 +0.234958951166645,-0.0148906939107358,-0.0788737991597094,0.000789565653211926,-0.00277483999999972,0.5307459,0.102774840000001,0.5307459,-0.0247034999999994,0.100000000000001,-2.77555756156289e-17,0,0.100000000000001,-2.77555756156289e-17,-0.300000000000001,0,0.100000000000001,0,0.124703499999997,0,0,0 +-0.30567034055279,0.020640367761019,0.0142278601017656,9.56087219148259e-10,-0.0247034999999994,0.5307459,0.124703499999997,0.5307459,0.062233279999999,0.0999999999999979,0.100000000000001,0,0.0999999999999979,0.100000000000001,-2.77555756156289e-17,0,0.0999999999999979,0,-0.162233279999997,0,0,0 +0.0551391576033748,0.022181819199585,0.0153877399268166,1.08228869221964e-15,0.062233279999999,0.5307459,-0.162233279999997,0.5307459,-0.0173774699999987,-0.0999999999999979,0.0999999999999979,0,-0.0999999999999979,0.0999999999999979,0.100000000000001,0,-0.0999999999999979,0,0.029264881827445,0.516613464828811,0,0 +0.0596341973364774,0.0237076717619417,0.0165009880368556,1.62548962585055e-14,-0.0173774699999987,0.5307459,NA,0.5307459,0.00711825082089532,-0.0173774699999987,-0.0999999999999979,0,0.0118874118274463,-0.0999999999999979,0.0999999999999979,0,0.0118874118274463,0.516613464828811,0.0316506057361263,0.51429641230965,0,0 +0.0639485188544041,0.0259287555811084,0.0176158527227966,2.44132322804034e-13,0.00711825082089532,0.678189428316176,NA,0.678189428316176,-0.0237071232453648,0.00711825082089532,-0.0173774699999987,0.149506454968222,0.0541935417191358,0.0118874118274463,-0.0999999999999979,0,0.0541935417191358,0.641741673395462,0.0339404141930477,0.511710193385462,0,0 +0.068269105308365,0.0279658191158661,0.0194253518595966,3.66662389529572e-12,-0.0237071232453648,0.752057576532677,NA,0.752057576532677,-0.0163012593428794,-0.0237071232453648,0.00711825082089532,0.202351215947534,0.0378331458215836,0.0541935417191358,0.0118874118274463,0.135529627304514,0.0378331458215836,0.689598709119198,0.036233547739083,0.508897528919332,0,0 +0.0752817029424115,0.0285902652159538,0.0207943862273582,5.50690323802289e-11,-0.0163012593428794,0.887345282058138,NA,0.887345282058138,-0.009013539183659,-0.0163012593428794,-0.0237071232453648,0.243291778123498,0.0644042421473539,0.0378331458215836,0.0541935417191358,0.175104401184564,0.0644042421473539,0.779504508898493,0.0399554551817028,0.504919212999066,0,0 +0.0805873076664188,0.0328064298097106,0.0209134135241508,8.27081918924803e-10,-0.009013539183659,0.989002252814016,NA,0.989002252814016,-0.0124209381746591,-0.009013539183659,-0.0163012593428794,0.290049531923305,0.0914889879849936,0.0644042421473539,0.0378331458215836,0.198694752747467,0.0914889879849936,0.823497135819756,0.0427713831359903,0.500635226716411,0,0 +0.0810485903069569,0.0378689056004456,0.0250856357339025,1.24219451667337e-08,-0.0124209381746591,1.06365089688705,NA,1.06365089688705,-0.0116116675805307,-0.0124209381746591,-0.009013539183659,0.32607397329287,0.10689014779784,0.0914889879849936,0.0644042421473539,0.220428782166723,0.10689014779784,0.829705186492621,0.0430162070061971,0.497911874524264,0,0 +0.0972177693918182,0.0298078747669572,0.0286078145050807,1.86565221889918e-07,-0.0116116675805307,1.13616695378602,NA,1.13616695378602,-0.00962922685693437,-0.0116116675805307,-0.0124209381746591,0.354910588525837,0.124688898296975,0.10689014779784,0.0914889879849936,0.227671907841632,0.124688898296975,0.823497135819756,0.051597932511853,0.489601091763771,0,0 +0.11086774689948,0.038782539731889,0.0192464690692418,2.80202347954704e-06,-0.00962922685693437,1.198783257886,NA,1.198783257886,-0.00938647658458114,-0.00962922685693437,-0.0116116675805307,0.381400966966074,0.151107798366203,0.124688898296975,0.10689014779784,0.220428782166723,0.151107798366203,0.779504508898493,0.0588426021091367,0.477040961387649,0,0 +0.074588454182629,0.0715542984707604,0.0316771466214613,4.2083596826881e-05,-0.00938647658458114,1.2507870324454,NA,1.2507870324454,-0.00886085941151256,-0.00938647658458114,-0.00962922685693437,0.404123464727995,0.177946695335136,0.151107798366203,0.124688898296975,0.198694752747468,0.177946695335136,0.689598709119198,0.0395875162447682,0.478095598311294,0,0 +0.122762746294449,0.0098837093490942,0.059859759667181,0.000632053633673964,-0.00886085941151256,1.2963771856,NA,1.2963771856,-0.00804915678982429,-0.00886085941151256,-0.00938647658458114,0.423347621758337,0.179947035404113,0.177946695335136,0.151107798366203,0.175104401184564,0.179947035404113,0.641741673395462,0.0651558242685191,0.460649757854981,0,0 +0.23198265225979,0.000491301793903431,-0.0122152596826213,0.00949281491988075,-0.00804915678982429,1.33591138779128,NA,1.33591138779128,-0.00750862230834648,-0.00804915678982429,-0.00886085941151256,0.440097195219267,0.215943387973169,0.179947035404113,0.177946695335136,0.135529627304514,0.215943387973169,0.516613464828812,0.123123841558009,0.28338271760758,0,0 +-0.0473394540000167,0.146786145155052,0.00500091972323522,0.024499267243187,-0.00750862230834648,1.36976078771892,0.307508622308347,1.36976078771892,0.227739694261289,0.300000000000001,0.219638056738543,0,0.300000000000001,0.215943387973169,0.179947035404113,-1.07148732853309e-17,0.300000000000001,-4.03634209227924e-17,-0.0251252211187475,0.0600535367423528,0,0 +0.0193807430498332,-0.0603510790594479,0.144939910377159,0.027730520886847,0.227739694261289,0.600746957836109,-0.0277396942612899,0.600746957836109,0.189000905378525,0.199999999999999,0.300000000000001,0,0.199999999999999,0.300000000000001,0.215943387973169,0,0.199999999999999,6.66963104563165e-17,0.0102862499126524,0.0343973226493759,0,0 +0.561705309452223,0.078563567092664,-0.113859857054769,0.0296522664457274,0.189000905378525,0.567526982489609,0.0109990946214783,0.567526982489609,0.201877210000002,0.200000000000003,0.199999999999999,0,0.200000000000003,0.199999999999999,0.300000000000001,0,0.200000000000003,0,0.298122789999998,0,0,0 +-0.44125655987168,-0.222568937914378,0.120598240619568,0.0296522664457274,0.201877210000002,0.5307459,0.298122789999998,0.5307459,0.33419511,0.5,0.200000000000003,0,0.5,0.200000000000003,0.199999999999999,0,0.5,0,-0.234195109999999,0,0,0 +0.46737073239755,-0.127042725752303,-0.267091281464521,0.0296522664457274,0.33419511,0.5307459,-0.234195109999999,0.5307459,0.151944900000001,0.100000000000001,0.5,0,0.100000000000001,0.5,0.200000000000003,0,0.100000000000001,0,0.248055099999997,0,0,0 +-1.03509509918023,-0.0257913344919775,-0.0284382209807651,0.0296522664457274,0.151944900000001,0.5307459,0.248055099999997,0.5307459,0.349372479999999,0.399999999999999,0.100000000000001,0,0.399999999999999,0.100000000000001,0.5,0,0.399999999999999,0,-0.549372480000002,0,0,0 +-0.110210498093344,0.0726932970806533,-0.015292539169958,0.0296522664457274,0.349372479999999,0.5307459,-0.549372480000002,0.5307459,-0.0415062300000012,-0.200000000000003,0.399999999999999,0,-0.200000000000003,0.399999999999999,0.100000000000001,0,-0.200000000000003,0,-0.0584937700000002,0,0,0 +-0.0592652529204627,0.0644587684713146,0.0783389821186854,0.0296522664457274,-0.0415062300000012,0.5307459,-0.0584937700000002,0.5307459,0.0314547899999986,-0.100000000000001,-0.200000000000003,0,-0.100000000000001,-0.200000000000003,0.399999999999999,0,-0.100000000000001,0,-0.0314547899999986,0,0,0 +0.303597691475341,0.177333565022131,0.0355376577043747,0.0296522664457274,0.0314547899999986,0.5307459,-0.0314547899999986,0.5307459,-0.0611332300000008,0,-0.100000000000001,0,0,-0.100000000000001,-0.200000000000003,0,0,0,0.161133230000002,0,0,0 +0.137723908936463,0.0381832850427984,0.164213806415762,0.0296522664457274,-0.0611332300000008,0.5307459,0.161133230000002,0.5307459,0.0269036000000004,0.100000000000001,0,0,0.100000000000001,0,-0.100000000000001,0,0.100000000000001,0,0.073096400000001,0,0,0 +0.636400055092272,0.00662995199265739,-0.0224410115253631,0.0296522664457274,0.0269036000000004,0.5307459,0.073096400000001,0.5307459,0.0622332800000009,0.100000000000001,0.100000000000001,0,0.100000000000001,0.100000000000001,0,0,0.100000000000001,0,0.337766719999998,0,0,0 +-0.0869686982037862,-0.056569024522395,0.0149147032428577,0.0296522664457274,0.0622332800000009,0.5307459,0.337766719999998,0.5307459,0.24615828,0.399999999999999,0.100000000000001,0,0.399999999999999,0.100000000000001,0.100000000000001,0,0.399999999999999,0,-0.0461582799999969,0,0,0 +0.057800974063095,0.160192995793857,-0.0620752204529117,0.0296522664457274,0.24615828,0.5307459,-0.0461582799999969,0.5307459,0.169322370000002,0.200000000000003,0.399999999999999,0,0.200000000000003,0.399999999999999,0.100000000000001,0,0.200000000000003,0,0.030677629999994,0,0,0 +-0.24056852817892,0.152841921703299,0.183109866527268,0.0296522664457274,0.169322370000002,0.5307459,0.030677629999994,0.5307459,0.227680759999998,0.199999999999996,0.200000000000003,0,0.199999999999996,0.200000000000003,0.399999999999999,0,0.199999999999996,0,-0.127680759999996,0,0,0 +0.709630521874967,0.0134955378125429,0.0852415956698116,0.0296522664457274,0.227680759999998,0.5307459,-0.127680759999996,0.5307459,0.123366510000001,0.100000000000001,0.199999999999996,0,0.100000000000001,0.199999999999996,0.200000000000003,0,0.100000000000001,0,0.376633489999999,0,0,0 +0.33034832676051,-0.0235398165630878,-0.0179738732474881,0.0296522664457274,0.123366510000001,0.5307459,0.376633489999999,0.5307459,0.324668979999999,0.5,0.100000000000001,0,0.5,0.100000000000001,0.199999999999996,0,0.5,0,0.175331020000001,0,0,0 +-0.0696565908469497,0.083352848686631,-0.0169042391654393,0.0296522664457274,0.324668979999999,0.5307459,0.175331020000001,0.5307459,0.33696995,0.5,0.5,0,0.5,0.5,0.100000000000001,0,0.5,0,-0.0369699499999961,0,0,0 +-0.0655112926920492,-0.0493426930030197,0.0895935395931561,0.0296522664457274,0.33696995,0.5307459,-0.0369699499999961,0.5307459,0.334769850000002,0.300000000000004,0.5,0,0.300000000000004,0.5,0.5,0,0.300000000000004,0,-0.0347698500000051,0,0,0 +0.347214005798257,-0.0452340335581077,-0.0824187505735691,0.0296522664457274,0.334769850000002,0.5307459,-0.0347698500000051,0.5307459,0.315717589999999,0.299999999999997,0.300000000000004,0,0.299999999999997,0.300000000000004,0.5,0,0.299999999999997,0,0.184282410000001,0,0,0 +-0.319408571973892,-0.128704132657991,-0.0148067577607313,0.0296522664457274,0.315717589999999,0.5307459,0.184282410000001,0.5307459,0.369524790000001,0.5,0.299999999999997,0,0.5,0.299999999999997,0.300000000000004,0,0.5,0,-0.169524789999998,0,0,0 +-0.0573826382832256,0.211855488309034,-0.123237787937701,0.0296522664457274,0.369524790000001,0.5307459,-0.169524789999998,0.5307459,0.230455600000001,0.200000000000003,0.5,0,0.200000000000003,0.5,0.299999999999997,0,0.200000000000003,0,-0.030455600000005,0,0,0 +-0.477600128423033,0.110639608962089,0.257352297422779,0.0296522664457274,0.230455600000001,0.5307459,-0.030455600000005,0.5307459,0.253484309999998,0.199999999999996,0.200000000000003,0,0.199999999999996,0.200000000000003,0.5,0,0.199999999999996,0,-0.253484309999998,0,0,0 +0.997352292311634,0.0213351799307562,0.0156305330385024,0.0296522664457274,0.253484309999998,0.5307459,-0.253484309999998,0.5307459,0.0706593600000003,0,0.199999999999996,0,0,0.199999999999996,0.200000000000003,0,0,0,0.529340640000001,0,0,0 +0.0605751264399761,-0.164924314098101,0.0155647146384197,0.0296522664457274,0.0706593600000003,0.5307459,0.529340640000001,0.5307459,0.36785,0.600000000000001,0,0,0.600000000000001,0,0.199999999999996,0,0.600000000000001,0,0.0321499999999989,0,0,0 +0.0603200514596625,0.213240392137561,-0.170670480616215,0.0296522664457274,0.36785,0.5307459,0.0321499999999989,0.5307459,0.267985379999999,0.399999999999999,0.600000000000001,0,0.399999999999999,0.600000000000001,0,0,0.399999999999999,0,0.0320146200000049,0,0,0 +-0.66142248107805,0.0794456822773055,0.276248357534281,0.0296522664457274,0.267985379999999,0.5307459,0.0320146200000049,0.5307459,0.351047270000002,0.300000000000004,0.399999999999999,0,0.300000000000004,0.399999999999999,0.600000000000001,0,0.300000000000004,0,-0.351047270000002,0,0,0 +1.07058275909432,0.0998473058585762,-0.0225394231116059,0.0296522664457274,0.351047270000002,0.5307459,-0.351047270000002,0.5307459,0.13179259,0,0.300000000000004,0,0,0.300000000000004,0.399999999999999,0,0,0,0.568207409999996,0,0,0 +-0.0873500859827654,-6.17594583794331e-05,0.108168388604406,0.0296522664457274,0.13179259,0.5307459,0.568207409999996,0.5307459,0.446360699999999,0.699999999999996,0,0,0.699999999999996,0,0.300000000000004,0,0.699999999999996,0,-0.0463607000000002,0,0,0 +0.419199639601552,0.733130822521038,-0.0399952620863547,0.0296522664457274,0.446360699999999,0.5307459,-0.0463607000000002,0.5307459,0.277511509999999,0.399999999999999,0.699999999999996,0,0.399999999999999,0.699999999999996,0,0,0.399999999999999,0,0.222488490000001,0,0,0 +-0.154999068292366,0.680334051010577,0.747896235265358,0.0296522664457274,0.277511509999999,0.5307459,0.222488490000001,0.5307459,0.482265119999999,0.5,0.399999999999999,0,0.5,0.399999999999999,0.699999999999996,0,0.5,0,-0.0822651199999931,0,0,0 +2.89842380317963,0.373672930771501,0.404226431568741,0.0296522664457274,0.482265119999999,0.5307459,-0.0822651199999931,0.5307459,0.361673450000003,0.400000000000006,0.5,0,0.400000000000006,0.5,0.399999999999999,0,0.400000000000006,0,1.53832655,0,0,0 +1.56655356169497,-0.514902622666697,0.224441001964808,0.0296522664457274,0.361673450000003,0.5307459,1.53832655,0.5307459,1.16855812,1.9,0.400000000000006,0,1.9,0.400000000000006,0.5,0,1.9,0,0.83144188,0,0,0 +0.869806681502383,0.801079403246931,-0.5977615378953,0.0296522664457274,1.16855812,0.5307459,0.83144188,0.5307459,1.33835367,2,1.9,0,2,1.9,0.400000000000006,0,2,0,0.461646329999996,0,0,0 +-2.31658643053107,0.190626802733698,1.02176043818168,0.0296522664457274,1.33835367,0.5307459,0.461646329999996,0.5307459,1.62951875,1.8,2,0,1.8,2,1.9,0,1.8,0,-1.22951875,0,0,0 +3.95976692424756,1.0566025139816,-0.186585742167126,0.0296522664457274,1.62951875,0.5307459,-1.22951875,0.5307459,0.898369939999999,0.399999999999999,1.8,0,0.399999999999999,1.8,2,0,0.399999999999999,0,2.10163006,0,0,0 +-0.723101054572435,-0.0869601523110229,1.12548606047155,0.0296522664457274,0.898369939999999,0.5307459,2.10163006,0.5307459,2.08378292,3,0.399999999999999,0,3,0.399999999999999,1.8,0,3,0,-0.383782919999996,0,0,0 +4.36174890847014,-1.02674334962278,-0.502466023605469,0.0296522664457274,2.08378292,0.5307459,-0.383782919999996,0.5307459,1.28501965,1.7,3,0,1.7,3,0.399999999999999,0,1.7,0,2.31498035,0,0,0 +-1.94727478818019,-0.553850616203382,-0.841243421843513,0.0296522664457274,1.28501965,0.5307459,2.31498035,0.5307459,2.83350811,3.6,1.7,0,3.6,1.7,3,0,3.6,0,-1.03350811,0,0,0 +-3.26018482667506,0.114035649026434,-0.243281171374041,0.0296522664457274,2.83350811,0.5307459,-1.03350811,0.5307459,1.73032973,1.8,3.6,0,1.8,3.6,1.7,0,1.8,0,-1.73032973,0,0,0 +-0.942820547459714,0.0316751337345581,0.203849960044158,0.0296522664457274,1.73032973,0.5307459,-1.73032973,0.5307459,1.10039814,0,1.8,0,0,1.8,3.6,0,0,0,-0.500398139999999,0,0,0 +0.790007421630582,-0.154833154050993,-0.0435820002596193,0.0296522664457274,1.10039814,0.5307459,-0.500398139999999,0.5307459,0.7807068,0.600000000000001,0,0,0.600000000000001,0,1.8,0,0.600000000000001,0,0.419293200000003,0,0,0 +-0.168899241614504,0.131132967323623,-0.138743592725781,0.0296522664457274,0.7807068,0.5307459,0.419293200000003,0.5307459,0.689642580000002,1.2,0.600000000000001,0,1.2,0.600000000000001,0,0,1.2,0,-0.0896425800000074,0,0,0 +-0.537691878542996,0.0878554245896234,0.18235419467307,0.0296522664457274,0.689642580000002,0.5307459,-0.0896425800000074,0.5307459,0.585377759999998,0.599999999999994,1.2,0,0.599999999999994,1.2,0.600000000000001,0,0.599999999999994,0,-0.285377759999993,0,0,0 +0.706701964160243,-0.00802346547950195,0.0205340767711652,0.0296522664457274,0.585377759999998,0.5307459,-0.285377759999993,0.5307459,0.524920830000002,0.300000000000004,0.599999999999994,0,0.300000000000004,0.599999999999994,1.2,0,0.300000000000004,0,0.375079169999996,0,0,0 +0.0795784950953076,0.401435001801264,-0.0156042163743246,0.0296522664457274,0.524920830000002,0.5307459,0.375079169999996,0.5307459,0.657764039999998,0.899999999999999,0.300000000000004,0,0.899999999999999,0.300000000000004,0.599999999999994,0,0.899999999999999,0,0.0422359600000046,0,0,0 +-0.0604731378989503,0.361252532298048,0.407195751532597,0.0296522664457274,0.657764039999998,0.5307459,0.0422359600000046,0.5307459,0.532095870000002,0.700000000000003,0.899999999999999,0,0.700000000000003,0.899999999999999,0.300000000000004,0,0.700000000000003,0,-0.0320958700000025,0,0,0 +1.57806097041918,-0.359826737029084,0.210924392776656,0.0296522664457274,0.532095870000002,0.5307459,-0.0320958700000025,0.5307459,0.56245061,0.5,0.700000000000003,0,0.5,0.700000000000003,0.899999999999999,0,0.5,0,0.837549389999999,0,0,0 +0.817423931112795,-0.0387425914882368,-0.437695603357999,0.0296522664457274,0.56245061,0.5307459,0.837549389999999,0.5307459,0.9661556,1.4,0.5,0,1.4,0.5,0.700000000000003,0,1.4,0,0.433844399999999,0,0,0 +-1.69626118637939,0.389353488785813,0.122845454265806,0.0296522664457274,0.9661556,0.5307459,0.433844399999999,0.5307459,1.00028367,1.4,1.4,0,1.4,1.4,0.5,0,1.4,0,-0.900283669999998,0,0,0 +0.476079664487275,0.665378936841417,0.344001521043191,0.0296522664457274,1.00028367,0.5307459,-0.900283669999998,0.5307459,0.54732267,0.100000000000001,1.4,0,0.100000000000001,1.4,1.4,0,0.100000000000001,0,0.252677329999997,0,0,0 +1.33315579074659,0.00260502509182386,0.538380783112369,0.0296522664457274,0.54732267,0.5307459,0.252677329999997,0.5307459,0.792433029999998,0.799999999999997,0.100000000000001,0,0.799999999999997,0.100000000000001,1.4,0,0.799999999999997,0,0.707566970000009,0,0,0 +2.0864601309214,0.16841227694028,-0.196153879377919,0.0296522664457274,0.792433029999998,0.5307459,0.707566970000009,0.5307459,0.892619840000004,1.50000000000001,0.799999999999997,0,1.50000000000001,0.799999999999997,0.100000000000001,0,1.50000000000001,0,1.10738016,0,0,0 +-0.760181755525573,0.597133579062212,0.240828179207928,0.0296522664457274,0.892619840000004,0.5307459,1.10738016,0.5307459,1.40346335,2,1.50000000000001,0,2,1.50000000000001,0.799999999999997,0,2,0,-0.40346335,0,0,0 +0.933314133938656,0.611506418569741,0.508224861354842,0.0296522664457274,1.40346335,0.5307459,-0.40346335,0.5307459,1.10464735,1,2,0,1,2,1.50000000000001,0,1,0,0.495352649999992,0,0,0 +1.96959279383977,0.291938162906109,0.423880448557933,0.0296522664457274,1.10464735,0.5307459,0.495352649999993,0.5307459,1.4546467,1.59999999999999,1,0,1.59999999999999,1,2,0,1.59999999999999,0,1.0453533,0,0,0 +1.64272144165409,0.387881375422164,0.135450382836267,0.0296522664457274,1.4546467,0.5307459,1.0453533,0.5307459,1.72813233,2.5,1.59999999999999,0,2.5,1.59999999999999,1,0,2.5,0,0.871867669999995,0,0,0 +0.524929255223669,0.773394846381199,0.337875932161525,0.0296522664457274,1.72813233,0.5307459,0.871867669999995,0.5307459,2.02139595,2.59999999999999,2.5,0,2.59999999999999,2.5,1.59999999999999,0,2.59999999999999,0,0.278604050000016,0,0,0 +1.30941646463965,-0.300367189877982,0.648658131718222,0.0296522664457274,2.02139595,0.5307459,0.278604050000016,0.5307459,2.10503258000001,2.30000000000001,2.59999999999999,0,2.30000000000001,2.59999999999999,2.5,0,2.30000000000001,0,0.694967419999991,0,0,0 +2.51383290949587,0.203748255662326,-0.539838180819341,0.0296522664457274,2.10503258000001,0.5307459,0.694967419999991,0.5307459,2.36579349,2.8,2.30000000000001,0,2.8,2.30000000000001,2.59999999999999,0,2.8,0,1.33420651,0,0,0 +-2.09210818208867,-0.139251184552095,0.403045200828729,0.0296522664457274,2.36579349,0.5307459,1.33420651,0.5307459,2.81037784,3.7,2.8,0,3.7,2.8,2.30000000000001,0,3.7,0,-1.11037784000002,0,0,0 +1.56197577786285,0.350889847612132,-0.288047027719821,0.0296522664457274,2.81037784,0.5307459,-1.11037784000002,0.5307459,1.97098775999999,1.69999999999999,3.7,0,1.69999999999999,3.7,2.8,0,1.69999999999999,0,0.829012240000018,0,0,0 +-1.11630774726664,0.0540067374478824,0.457230774816824,0.0296522664457274,1.97098775999999,0.5307459,0.829012240000018,0.5307459,2.59247576000001,2.80000000000001,1.69999999999999,0,2.80000000000001,1.69999999999999,3.7,0,2.80000000000001,0,-0.592475760000005,0,0,0 +1.77196848812208,-0.616127603414353,-0.114793284289661,0.0296522664457274,2.59247576000001,0.5307459,-0.592475760000005,0.5307459,1.75953499,2,2.80000000000001,0,2,2.80000000000001,1.69999999999999,0,2,0,0.94046500999999,0,0,0 +-0.44487399714249,-0.875782736137246,-0.573748328110363,0.0296522664457274,1.75953499,0.5307459,0.94046500999999,0.5307459,2.33611505,2.69999999999999,2,0,2.69999999999999,2,2.80000000000001,0,2.69999999999999,0,-0.236115049999988,0,0,0 +-2.223524778995,-0.126423131149624,-0.66396687510797,0.0296522664457274,2.33611505,0.5307459,-0.236115049999988,0.5307459,1.88012666,2.10000000000001,2.69999999999999,0,2.10000000000001,2.69999999999999,2,0,2.10000000000001,0,-1.18012666,0,0,0 +-2.57316096082892,-0.195744335153904,0.118699527088188,0.0296522664457274,1.88012666,0.5307459,-1.18012666,0.5307459,1.26569463,0.700000000000003,2.10000000000001,0,0.700000000000003,2.10000000000001,2.69999999999999,0,0.700000000000003,0,-1.36569463000001,0,0,0 +0.460012390109842,0.055896633133449,-0.239565713451875,0.0296522664457274,1.26569463,0.5307459,-1.36569463000001,0.5307459,0.555850309999998,-0.100000000000008,0.700000000000003,0,-0.100000000000008,0.700000000000003,2.10000000000001,0,-0.100000000000008,0,0.244149689999999,0,0,0 +-0.928421529021684,-0.105586821252778,0.144339274936042,0.0296522664457274,0.555850309999998,0.5307459,0.244149689999999,0.5307459,0.592755919999998,0.799999999999997,-0.100000000000008,0,0.799999999999997,-0.100000000000008,0.700000000000003,0,0.799999999999997,0,-0.49275591999999,0,0,0 +0.559377585394422,-0.0667308073075661,-0.158873857228311,0.0296522664457274,0.592755919999998,0.5307459,-0.49275591999999,0.5307459,0.103112640000002,0.100000000000009,0.799999999999997,0,0.100000000000009,0.799999999999997,-0.100000000000008,0,0.100000000000009,0,0.296887359999989,0,0,0 +-0.615705425138446,0.0624339054102411,-0.00807790809182508,0.0296522664457274,0.103112640000002,0.5307459,0.296887359999989,0.5307459,0.426783129999996,0.399999999999991,0.100000000000009,0,0.399999999999991,0.100000000000009,0.799999999999997,0,0.399999999999991,0,-0.326783129999987,0,0,0 +-0.0313054137582816,0.416274320571032,0.0654160998218929,0.0296522664457274,0.426783129999996,0.5307459,-0.326783129999987,0.5307459,0.116615220000006,0.100000000000009,0.399999999999991,0,0.100000000000009,0.399999999999991,0.100000000000009,0,0.100000000000009,0,-0.0166152200000116,0,0,0 +0.253515891502886,0.105163346061856,0.392124067175808,0.0296522664457274,0.116615220000006,0.5307459,-0.0166152200000116,0.5307459,0.165447479999996,0.0999999999999943,0.100000000000009,0,0.0999999999999943,0.100000000000009,0.399999999999991,0,0.0999999999999943,0,0.134552520000002,0,0,0 +1.51965162613597,0.308099633822476,-0.0396006433909703,0.0296522664457274,0.165447479999996,0.5307459,0.134552520000002,0.5307459,0.19345113,0.299999999999997,0.0999999999999943,0,0.299999999999997,0.0999999999999943,0.100000000000009,0,0.299999999999997,0,0.80654887,0,0,0 +-0.153469748894901,-0.0196349595209529,0.322719361612878,0.0296522664457274,0.19345113,0.5307459,0.80654887,0.5307459,0.581453439999998,1,0.299999999999997,0,1,0.299999999999997,0.0999999999999943,0,1,0,-0.0814534399999983,0,0,0 +1.25067814937432,-0.41588804373822,-0.138776185911945,0.0296522664457274,0.581453439999998,0.5307459,-0.0814534399999983,0.5307459,0.436207699999999,0.5,1,0,0.5,1,0.299999999999997,0,0.5,0,0.663792300000009,0,0,0 +-0.537818191341676,-0.395009368979804,-0.364654783667363,0.0296522664457274,0.436207699999999,0.5307459,0.663792300000009,0.5307459,0.885444800000004,1.10000000000001,0.5,0,1.10000000000001,0.5,1,0,1.10000000000001,0,-0.28544480000001,0,0,0 +-1.41319618295685,-0.182497081019815,-0.260386463436297,0.0296522664457274,0.885444800000004,0.5307459,-0.28544480000001,0.5307459,0.550048079999998,0.599999999999994,1.10000000000001,0,0.599999999999994,1.10000000000001,0.5,0,0.599999999999994,0,-0.750048080000001,0,0,0 +-1.00911100773458,0.106966335957151,-0.0863678545787083,0.0296522664457274,0.550048079999998,0.5307459,-0.750048080000001,0.5307459,0.23558153,-0.200000000000003,0.599999999999994,0,-0.200000000000003,0.599999999999994,1.10000000000001,0,-0.200000000000003,0,-0.535581529999997,0,0,0 +-0.334713070793392,-0.267788603388917,0.138851538207922,0.0296522664457274,0.23558153,0.5307459,-0.535581529999997,0.5307459,-0.0223524100000002,-0.299999999999997,-0.200000000000003,0,-0.299999999999997,-0.200000000000003,0.599999999999994,0,-0.299999999999997,0,-0.177647590000003,0,0,0 +0.538110214322919,0.373751762079172,-0.319049681948597,0.0296522664457274,-0.0223524100000002,0.5307459,-0.177647590000003,0.5307459,-0.185599790000002,-0.200000000000003,-0.299999999999997,0,-0.200000000000003,-0.299999999999997,-0.200000000000003,0,-0.200000000000003,0,0.28559979000001,0,0,0 +-1.23645654163321,-0.681672132408642,0.491538219628656,0.0296522664457274,-0.185599790000002,0.5307459,0.28559979000001,0.5307459,-0.043755759999995,0.100000000000009,-0.200000000000003,0,0.100000000000009,-0.200000000000003,-0.299999999999997,0,0.100000000000009,0,-0.656244240000008,0,0,0 +1.90492478604167,-0.749366988155991,-0.863137743929194,0.0296522664457274,-0.043755759999995,0.5307459,-0.656244240000008,0.5307459,-0.411031020000001,-0.700000000000003,0.100000000000009,0,-0.700000000000003,0.100000000000009,-0.200000000000003,0,-0.700000000000003,0,1.01103102,0,0,0 +-3.34503486508327,0.0533502038509226,-0.430714618362834,0.0296522664457274,-0.411031020000001,0.5307459,1.01103102,0.5307459,0.275363539999999,0.599999999999994,-0.700000000000003,0,0.599999999999994,-0.700000000000003,0.100000000000009,0,0.599999999999994,0,-1.77536354,0,0,0 +-1.66920682759866,0.672534195265053,0.212361016216847,0.0296522664457274,0.275363539999999,0.5307459,-1.77536354,0.5307459,-0.914075320000001,-1.5,0.599999999999994,0,-1.5,0.599999999999994,-0.700000000000003,0,-1.5,0,-0.885924679999996,0,0,0 +0.822991472944021,0.90060294662053,0.594134957663491,0.0296522664457274,-0.914075320000001,0.5307459,-0.885924679999996,0.5307459,-0.93679935,-1.8,-1.5,0,-1.8,-1.5,0.599999999999994,0,-1.8,0,0.43679935,0,0,0 +2.30253185187112,0.791713290597868,0.681260769119879,0.0296522664457274,-0.93679935,0.5307459,0.43679935,0.5307459,-0.82205934,-0.5,-1.8,0,-0.5,-1.8,-1.5,0,-0.5,0,1.22205934000001,0,0,0 +2.64018233584092,0.223101708570311,0.540206089048625,0.0296522664457274,-0.82205934,0.5307459,1.22205934000001,0.5307459,-0.301265949999996,0.400000000000006,-0.5,0,0.400000000000006,-0.5,-1.8,0,0.400000000000006,0,1.40126594999999,0,0,0 +2.09353398679106,-0.242145727812177,0.023668939394411,0.0296522664457274,-0.301265949999996,0.5307459,1.40126594999999,0.5307459,0.488865419999998,1.09999999999999,0.400000000000006,0,1.09999999999999,0.400000000000006,-0.5,0,1.09999999999999,0,1.11113458000001,0,0,0 +0.0917274537589246,-0.18070625883046,-0.250883804302942,0.0296522664457274,0.488865419999998,0.5307459,1.11113458000001,0.5307459,1.05131603000001,1.60000000000001,1.09999999999999,0,1.60000000000001,1.09999999999999,0.400000000000006,0,1.60000000000001,0,0.0486839699999888,0,0,0 +-0.97228406286322,0.430459312024697,-0.0880852150328281,0.0296522664457274,1.05131603000001,0.5307459,0.0486839699999888,0.5307459,1.01603578,1.09999999999999,1.60000000000001,0,1.09999999999999,1.60000000000001,1.09999999999999,0,1.09999999999999,0,-0.516035779999996,0,0,0 +-0.341368590883146,0.399672790502207,0.462978527771394,0.0296522664457274,1.01603578,0.5307459,-0.516035779999996,0.5307459,0.781179980000002,0.5,1.09999999999999,0,0.5,1.09999999999999,1.60000000000001,0,0.5,0,-0.181179980000007,0,0,0 +1.79424353537166,-0.206208202273017,0.228750818806107,0.0296522664457274,0.781179980000002,0.5307459,-0.181179980000007,0.5307459,0.647712599999996,0.599999999999994,0.5,0,0.599999999999994,0.5,1.09999999999999,0,0.599999999999994,0,0.952287400000013,0,0,0 +0.886509099740565,0.612582249294492,-0.290658211576132,0.0296522664457274,0.647712599999996,0.5307459,0.952287400000013,0.5307459,1.02948893,1.60000000000001,0.599999999999994,0,1.60000000000001,0.599999999999994,0.5,0,1.60000000000001,0,0.470511069999996,0,0,0 +-1.12642722251835,0.388794699108794,0.719887170866979,0.0296522664457274,1.02948893,0.5307459,0.470511069999996,0.5307459,1.09784663,1.5,1.60000000000001,0,1.5,1.60000000000001,0.599999999999994,0,1.5,0,-0.597846629999999,0,0,0 +2.78987647384557,-0.805170919383082,0.123027439370849,0.0296522664457274,1.09784663,0.5307459,-0.597846629999999,0.5307459,0.819284500000002,0.5,1.5,0,0.5,1.5,1.60000000000001,0,0.5,0,1.48071549999999,0,0,0 +0.47678493606829,-0.393582372246918,-0.850590072213365,0.0296522664457274,0.819284500000002,0.5307459,1.48071549999999,0.5307459,1.64694835,2.3,0.5,0,2.3,0.5,1.5,0,2.3,0,0.253051650000007,0,0,0 +-3.29640716960792,0.426177541910559,-0.0795623399407469,0.0296522664457274,1.64694835,0.5307459,0.253051650000007,0.5307459,1.34955459,1.90000000000001,2.3,0,1.90000000000001,2.3,0.5,0,1.90000000000001,0,-1.74955459000001,0,0,0 +-0.308338736107035,-0.307399264062802,0.455550290752472,0.0296522664457274,1.34955459,0.5307459,-1.74955459000001,0.5307459,0.563649519999997,-0.400000000000006,1.90000000000001,0,-0.400000000000006,1.90000000000001,2.3,0,-0.400000000000006,0,-0.163649519999991,0,0,0 +1.76545588011135,0.723744404108207,-0.475578886294854,0.0296522664457274,0.563649519999997,0.5307459,-0.163649519999991,0.5307459,0.662991530000004,0.400000000000006,-0.400000000000006,0,0.400000000000006,-0.400000000000006,1.90000000000001,0,0.400000000000006,0,0.93700846999999,0,0,0 +-1.84307541518455,1.28104893977355,0.899318164156728,0.0296522664457274,0.662991530000004,0.5307459,0.93700846999999,0.5307459,0.778204719999996,1.59999999999999,0.400000000000006,0,1.59999999999999,0.400000000000006,-0.400000000000006,0,1.59999999999999,0,-0.978204719999999,0,0,0 +3.48524975887708,0.350365504486796,0.949039516918231,0,0.778204719999996,0.5307459,-0.978204719999999,0.5307459,0.150217979999999,-0.200000000000003,1.59999999999999,0,-0.200000000000003,1.59999999999999,0.400000000000006,0,-0.200000000000003,0,1.84978202,0,0,0 +3.67794166662429,0,0,0,0.150217979999999,0.5307459,1.84978202,0.5307459,1.44794754,2,-0.200000000000003,0,2,-0.200000000000003,1.59999999999999,0,2,0,1.95205246000001,0,0,0 +0,0,0,0,1.44794754,0.5307459,1.95205246000001,0.5307459,1.9309586,3.40000000000001,2,0,3.40000000000001,2,-0.200000000000003,0,3.40000000000001,0,0,0.5307459,0,0 diff --git a/shared/package-files/78/7856a992635e725ecf1b6e8b84eb241f74c9205169fbb8a773ef8bc2eaa26ae4/blob b/shared/package-files/78/7856a992635e725ecf1b6e8b84eb241f74c9205169fbb8a773ef8bc2eaa26ae4/blob new file mode 100644 index 0000000000000000000000000000000000000000..e37e83e1d39e3aa5fbef9051e1beb52da773b2c3 --- /dev/null +++ b/shared/package-files/78/7856a992635e725ecf1b6e8b84eb241f74c9205169fbb8a773ef8bc2eaa26ae4/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & diagonal_copy_out(const at::Tensor & self, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out); +TORCH_API at::Tensor diagonal_copy(const at::Tensor & self, int64_t offset=0, int64_t dim1=0, int64_t dim2=1); +} // namespace native +} // namespace at diff --git a/shared/package-files/78/7856f5d28bf22e4dbe0b752cd30dd9f54a010c71494919434ed453b3028a13cf/blob b/shared/package-files/78/7856f5d28bf22e4dbe0b752cd30dd9f54a010c71494919434ed453b3028a13cf/blob new file mode 100644 index 0000000000000000000000000000000000000000..c207870a33b67c1201a90d0d983423cac748e755 --- /dev/null +++ b/shared/package-files/78/7856f5d28bf22e4dbe0b752cd30dd9f54a010c71494919434ed453b3028a13cf/blob @@ -0,0 +1,212 @@ +""" +Tests corresponding to sandbox.panel.correlation_structures +""" +import numpy as np +from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal +import pytest + +from statsmodels.sandbox.panel.correlation_structures import ( + ARCovariance, + corr2cov, + corr_ar, + corr_arma, + corr_equi, + whiten_ar, + yule_walker_acov, +) + + +def test_corr_equi(): + corr = corr_equi(3, 0.5) + expected = np.array([[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]) + assert_array_equal(corr, expected) + assert_array_equal(np.diag(corr), np.ones(3)) + + +def test_corr_ar_pads_short_ar(): + # ar shorter than k_vars is zero-padded before building the Toeplitz + # matrix, giving the documented (k_vars, k_vars) shape + corr = corr_ar(5, [1, 0.5]) + assert corr.shape == (5, 5) + expected = np.array( + [ + [1.0, 0.5, 0.0, 0.0, 0.0], + [0.5, 1.0, 0.5, 0.0, 0.0], + [0.0, 0.5, 1.0, 0.5, 0.0], + [0.0, 0.0, 0.5, 1.0, 0.5], + [0.0, 0.0, 0.0, 0.5, 1.0], + ] + ) + assert_array_almost_equal(corr, expected) + + +@pytest.mark.xfail( + reason=( + "BUG: corr_ar only pads `ar` up to k_vars when it is *shorter* " + "than k_vars; when `ar` is already >= k_vars long it is passed to " + "toeplitz() unmodified/untruncated, so the returned matrix has " + "shape (len(ar), len(ar)) instead of the documented (k_vars, " + "k_vars)." + ), + raises=AssertionError, + strict=True, +) +def test_corr_ar_truncates_long_ar(): + k_vars = 3 + corr = corr_ar(k_vars, [1, 0.5, 0.3, 0.1, 0.05]) + assert corr.shape == (k_vars, k_vars) + + +def test_corr_arma(): + corr = corr_arma(4, [1, 0.5], [1, 0.2]) + assert corr.shape == (4, 4) + assert_array_equal(np.diag(corr), np.ones(4)) + # symmetric, as any correlation matrix from a Toeplitz construction + assert_array_almost_equal(corr, corr.T) + + +def test_corr2cov_roundtrip_with_cov2corr(): + from statsmodels.stats.moment_helpers import cov2corr + + corr = corr_equi(3, 0.4) + std = np.array([1.0, 2.0, 3.0]) + cov = corr2cov(corr, std) + assert_array_almost_equal(np.diag(cov), std**2) + # corr2cov and cov2corr (the real, non-sandbox helper) are inverses + assert_array_almost_equal(cov2corr(cov), corr) + + +def test_corr2cov_scalar_std(): + corr = corr_equi(3, 0.4) + cov_scalar = corr2cov(corr, 2.0) + cov_array = corr2cov(corr, np.array([2.0, 2.0, 2.0])) + assert_array_almost_equal(cov_scalar, cov_array) + + +def test_whiten_ar_matches_manual_ar1_transform(): + x = np.arange(10.0) + rho = 0.5 + result = whiten_ar(x, np.array([rho]), order=1) + expected = x[1:] - rho * x[:-1] + assert_array_almost_equal(result, expected) + assert_array_equal(result.shape, (9,)) + + +def test_whiten_ar_order_zero_is_identity(): + x = np.arange(5.0) + result = whiten_ar(x, np.array([]), order=0) + assert_array_almost_equal(result, x) + + +def test_whiten_ar_2d(): + x = np.column_stack([np.arange(10.0), np.arange(10.0) * 2]) + rho = 0.5 + result = whiten_ar(x, np.array([rho]), order=1) + expected = x[1:] - rho * x[:-1] + assert_array_almost_equal(result, expected) + + +def test_yule_walker_acov_default_method_is_broken(): + # BUG: yule_walker_acov's default `method="unbiased"` is not a value + # accepted by the underlying statsmodels.regression.linear_model + # .yule_walker (which only accepts 'adjusted' or 'mle'), so calling + # yule_walker_acov with its own default arguments always raises. + acov = np.array([1.0, 0.5, 0.3]) + with pytest.raises(ValueError, match="method must be one of"): + yule_walker_acov(acov, order=1) + + +def test_yule_walker_acov_with_valid_method(): + acov = np.array([1.0, 0.5, 0.3]) + rho, sigma = yule_walker_acov(acov, order=1, method="adjusted") + assert_allclose(rho, [0.72761194], rtol=1e-6) + assert sigma > 0 + + +def test_arcovariance_corr_from_ar(): + cov = ARCovariance(ar=np.array([1, -0.5])) + result = cov.corr() + expected = np.array([[1.0, -0.5], [-0.5, 1.0]]) + assert_array_almost_equal(result, expected) + + +def test_arcovariance_corr_from_ar_coefs(): + cov = ARCovariance(ar_coefs=np.array([0.5])) + result = cov.corr() + expected = np.array([[1.0, -0.5], [-0.5, 1.0]]) + assert_array_almost_equal(result, expected) + + +def test_arcovariance_ar_and_ar_coefs_constructions_are_equivalent(): + # ar_coefs = -ar[1:], so these two constructions describe the same process + from_ar = ARCovariance(ar=np.array([1, -0.5])) + from_coefs = ARCovariance(ar_coefs=np.array([0.5])) + assert_array_almost_equal(from_ar.corr(), from_coefs.corr()) + + +@pytest.mark.xfail( + reason=( + "BUG: ARCovariance(ar_coefs=...) stores the coefficients as " + "self.arcoefs (no underscore), but .whiten() reads self.ar_coefs " + "(with underscore) -- a typo that means .whiten() always raises " + "AttributeError when the instance was built via the ar_coefs= " + "constructor path." + ), + raises=AttributeError, + strict=True, +) +def test_arcovariance_whiten_after_ar_coefs_construction(): + cov = ARCovariance(ar_coefs=np.array([0.5])) + cov.whiten(np.arange(10.0)) + + +@pytest.mark.xfail( + reason=( + "BUG: ARCovariance.whiten() reads self.order, but no constructor " + "path (ar= or ar_coefs=) ever sets self.order, so .whiten() always " + "raises AttributeError regardless of how the instance was built." + ), + raises=AttributeError, + strict=True, +) +def test_arcovariance_whiten_after_ar_construction(): + cov = ARCovariance(ar=np.array([1, -0.5])) + cov.whiten(np.arange(10.0)) + + +@pytest.mark.xfail( + reason=( + "BUG: ARCovariance.__init__ accepts a `sigma` parameter but never " + "stores it as self.sigma, so .cov() always raises AttributeError. " + "Separately, .cov() calls cov2corr(self.corr(...), self.sigma) -- " + "cov2corr converts covariance to correlation, the opposite of what " + "a method named .cov() should be doing; it likely meant to call " + "this module's own corr2cov(corr, std) instead." + ), + raises=AttributeError, + strict=True, +) +def test_arcovariance_cov(): + cov = ARCovariance(ar=np.array([1, -0.5]), sigma=2.0) + cov.cov() + + +@pytest.mark.xfail( + reason=( + "BUG: ARCovariance.fit() calls yule_walker_acov(cov, order=order, " + "**kwds) without a method= kwarg, hitting the same broken default " + "as test_yule_walker_acov_default_method_is_broken, so .fit() " + "always raises unless the caller passes method= explicitly." + ), + raises=ValueError, + strict=True, +) +def test_arcovariance_fit_default_method(): + acov = np.array([1.0, 0.5, 0.3]) + ARCovariance.fit(acov, order=1) + + +def test_arcovariance_fit_with_explicit_method(): + acov = np.array([1.0, 0.5, 0.3]) + fitted = ARCovariance.fit(acov, order=1, method="adjusted") + assert_allclose(fitted.arcoefs, [0.72761194], rtol=1e-6) diff --git a/shared/package-files/78/785c212f079c6f7bdff9b4ee1bda32c651da9e459bbf4de075a403f24191027a/blob b/shared/package-files/78/785c212f079c6f7bdff9b4ee1bda32c651da9e459bbf4de075a403f24191027a/blob new file mode 100644 index 0000000000000000000000000000000000000000..da4f5dc19d482d5d623b351049aa5acd93edb041 --- /dev/null +++ b/shared/package-files/78/785c212f079c6f7bdff9b4ee1bda32c651da9e459bbf4de075a403f24191027a/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:785c212f079c6f7bdff9b4ee1bda32c651da9e459bbf4de075a403f24191027a +size 415194 diff --git a/shared/package-files/78/785d5f469decadb59280d3c25cdbeabf85e3d05ecaaf95817f99eae4a6f004c8/blob b/shared/package-files/78/785d5f469decadb59280d3c25cdbeabf85e3d05ecaaf95817f99eae4a6f004c8/blob new file mode 100644 index 0000000000000000000000000000000000000000..dee69d9c408fe7c1ae2ac16fe5cd0788aaf1e108 --- /dev/null +++ b/shared/package-files/78/785d5f469decadb59280d3c25cdbeabf85e3d05ecaaf95817f99eae4a6f004c8/blob @@ -0,0 +1,14192 @@ +"""Adds docstrings to functions defined in the torch._C module.""" + +import re + +import torch._C +from torch._C import _add_docstr as add_docstr + + +def parse_kwargs(desc): + r"""Map a description of args to a dictionary of {argname: description}. + + Input: + (' weight (Tensor): a weight tensor\n' + + ' Some optional description') + Output: { + 'weight': \ + 'weight (Tensor): a weight tensor\n Some optional description' + } + """ + # Split on exactly 4 spaces after a newline + regx = re.compile(r"\n\s{4}(?!\s)") + kwargs = [section.strip() for section in regx.split(desc)] + kwargs = [section for section in kwargs if len(section) > 0] + return {desc.split(" ")[0]: desc for desc in kwargs} + + +def merge_dicts(*dicts): + """Merge dictionaries into a single dictionary.""" + return {x: d[x] for d in dicts for x in d} + + +common_args = parse_kwargs( + """ + input (Tensor): the input tensor. + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. +""" +) + +reduceops_common_args = merge_dicts( + common_args, + parse_kwargs( + """ + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + keepdim (bool): whether the output tensor has :attr:`dim` retained or not. +""" + ), +) + +multi_dim_common = merge_dicts( + reduceops_common_args, + parse_kwargs( + """ + dim (int or tuple of ints): the dimension or dimensions to reduce. +""" + ), + { + "keepdim_details": """ +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the +output tensor having 1 (or ``len(dim)``) fewer dimension(s). +""" + }, + { + "opt_dim": """ + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. +""" + }, +) + +single_dim_common = merge_dicts( + reduceops_common_args, + parse_kwargs( + """ + dim (int): the dimension to reduce. +""" + ), + { + "keepdim_details": """If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the output tensor having 1 fewer dimension than :attr:`input`.""" + }, +) + +factory_common_args = merge_dicts( + common_args, + parse_kwargs( + """ + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. +""" + ), + { + "sparse_factory_device_note": """\ +.. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor.""" + }, +) + +factory_like_common_args = parse_kwargs( + """ + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. +""" +) + +factory_data_common_args = parse_kwargs( + """ + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. +""" +) + +tf32_notes = { + "tf32_note": """This operator supports :ref:`TensorFloat32`.""" +} + +rocm_fp16_notes = { + "rocm_fp16_note": """On certain ROCm devices, when using float16 inputs this module will use \ +:ref:`different precision` for backward.""" +} + +reproducibility_notes = { + "forward_reproducibility_note": """This operation may behave nondeterministically when given tensors on \ +a CUDA device. See :doc:`/notes/randomness` for more information.""", + "backward_reproducibility_note": """This operation may produce nondeterministic gradients when given tensors on \ +a CUDA device. See :doc:`/notes/randomness` for more information.""", + "cudnn_reproducibility_note": """In some circumstances when given tensors on a CUDA device \ +and using CuDNN, this operator may select a nondeterministic algorithm to increase performance. If this is \ +undesirable, you can try to make the operation deterministic (potentially at \ +a performance cost) by setting ``torch.backends.cudnn.deterministic = True``. \ +See :doc:`/notes/randomness` for more information.""", +} + +sparse_support_notes = { + "sparse_beta_warning": """ +.. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request.""", +} + +add_docstr( + torch.abs, + r""" +abs(input, *, out=None) -> Tensor + +Computes the absolute value of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = |\text{input}_{i}| +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) +""".format( + **common_args + ), +) + +add_docstr( + torch.absolute, + r""" +absolute(input, *, out=None) -> Tensor + +Alias for :func:`torch.abs` +""", +) + +add_docstr( + torch.acos, + r""" +acos(input, *, out=None) -> Tensor + +Computes the inverse cosine of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arccos, + r""" +arccos(input, *, out=None) -> Tensor + +Alias for :func:`torch.acos`. +""", +) + +add_docstr( + torch.acosh, + r""" +acosh(input, *, out=None) -> Tensor + +Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + +Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arccosh, + r""" +arccosh(input, *, out=None) -> Tensor + +Alias for :func:`torch.acosh`. +""", +) + +add_docstr( + torch.index_add, + r""" +index_add(input, dim, index, source, *, alpha=1, out=None) -> Tensor + +See :meth:`~Tensor.index_add_` for function description. +""", +) + +add_docstr( + torch.index_copy, + r""" +index_copy(input, dim, index, source, *, out=None) -> Tensor + +See :meth:`~Tensor.index_add_` for function description. +""", +) + +add_docstr( + torch.index_reduce, + r""" +index_reduce(input, dim, index, source, reduce, *, include_self=True, out=None) -> Tensor + +See :meth:`~Tensor.index_reduce_` for function description. +""", +) + +add_docstr( + torch.add, + r""" +add(input, other, *, alpha=1, out=None) -> Tensor + +Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + +.. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to add to :attr:`input`. + +Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + {out} + +Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.addbmm, + r""" +addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices stored +in :attr:`batch1` and :attr:`batch2`, +with a reduced add step (all matrix multiplications get accumulated +along the first dimension). +:attr:`input` is added to the final result. + +:attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the +same number of matrices. + +If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a +:math:`(b \times m \times p)` tensor, :attr:`input` must be +:ref:`broadcastable ` with a :math:`(n \times p)` tensor +and :attr:`out` will be a :math:`(n \times p)` tensor. + +.. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + +If :attr:`beta` is 0, then :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` +must be real numbers, otherwise they should be integers. + +{tf32_note} + +{rocm_fp16_note} + +Args: + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + input (Tensor): matrix to be added + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) +""".format( + **common_args, **tf32_notes, **rocm_fp16_notes + ), +) + +add_docstr( + torch.addcdiv, + r""" +addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + +Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, +multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + +.. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + +.. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} +""" + + r""" + +The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be +:ref:`broadcastable `. + +For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be +a real number, otherwise an integer. + +Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + +Keyword args: + value (Number, optional): multiplier for :math:`\text{{tensor1}} / \text{{tensor2}}` + {out} + +Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.addcmul, + r""" +addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + +Performs the element-wise multiplication of :attr:`tensor1` +by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` +and adds it to :attr:`input`. + +.. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i +""" + + r""" +The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be +:ref:`broadcastable `. + +For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be +a real number, otherwise an integer. + +Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + +Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + {out} + +Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.addmm, + r""" +addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. +The matrix :attr:`input` is added to the final result. + +If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a +:math:`(m \times p)` tensor, then :attr:`input` must be +:ref:`broadcastable ` with a :math:`(n \times p)` tensor +and :attr:`out` will be a :math:`(n \times p)` tensor. + +:attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between +:attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + +If :attr:`beta` is 0, then :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +This operation has support for arguments with :ref:`sparse layouts`. If +:attr:`input` is sparse the result will have the same layout and if :attr:`out` +is provided it must have the same layout as :attr:`input`. + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) +""".format( + **common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes + ), +) + +add_docstr( + torch.adjoint, + r""" +adjoint(Tensor) -> Tensor +Returns a view of the tensor conjugated and with the last two dimensions transposed. + +``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and +to ``x.transpose(-2, -1)`` for real tensors. + +Example:: + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) +""", +) + +add_docstr( + torch.sspaddmm, + r""" +sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + +Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor +:attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + +Note: This function is equivalent to :func:`torch.addmm`, except +:attr:`input` and :attr:`mat1` are sparse. + +Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} +""".format( + **common_args + ), +) + +add_docstr( + torch.smm, + r""" +smm(input, mat) -> Tensor + +Performs a matrix multiplication of the sparse matrix :attr:`input` +with the dense matrix :attr:`mat`. + +Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied +""", +) + +add_docstr( + torch.addmv, + r""" +addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a matrix-vector product of the matrix :attr:`mat` and +the vector :attr:`vec`. +The vector :attr:`input` is added to the final result. + +If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of +size `m`, then :attr:`input` must be +:ref:`broadcastable ` with a 1-D tensor of size `n` and +:attr:`out` will be 1-D tensor of size `n`. + +:attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between +:attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + +If :attr:`beta` is 0, then :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) +""".format( + **common_args + ), +) + +add_docstr( + torch.addr, + r""" +addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` +and adds it to the matrix :attr:`input`. + +Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the +outer product between :attr:`vec1` and :attr:`vec2` and the added matrix +:attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + +If :attr:`beta` is 0, then :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector +of size `m`, then :attr:`input` must be +:ref:`broadcastable ` with a matrix of size +:math:`(n \times m)` and :attr:`out` will be a matrix of size +:math:`(n \times m)`. + +Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{vec1}} \otimes \text{{vec2}}` (:math:`\alpha`) + {out} + +Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.allclose, + r""" +allclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> bool + +This function checks if :attr:`input` and :attr:`other` satisfy the condition: + +.. math:: + \lvert \text{input} - \text{other} \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other} \rvert +""" + + r""" +elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to +`numpy.allclose `_ + +Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + +Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True +""", +) + +add_docstr( + torch.all, + r""" +all(input) -> Tensor + +Tests if all elements in :attr:`input` evaluate to `True`. + +.. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + +Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + +.. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + +For each row of :attr:`input` in the given dimension :attr:`dim`, +returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + +{keepdim_details} + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.any, + r""" +any(input) -> Tensor + +Tests if any element in :attr:`input` evaluates to `True`. + +.. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + +Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + +.. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + +For each row of :attr:`input` in the given dimension :attr:`dim`, +returns `True` if any element in the row evaluate to `True` and `False` otherwise. + +{keepdim_details} + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.angle, + r""" +angle(input, *, out=None) -> Tensor + +Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + +.. math:: + \text{out}_{i} = angle(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +.. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + +Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) +""".format( + **common_args + ), +) + +add_docstr( + torch.as_strided, + r""" +as_strided(input, size, stride, storage_offset=None) -> Tensor + +Create a view of an existing `torch.Tensor` :attr:`input` with specified +:attr:`size`, :attr:`stride` and :attr:`storage_offset`. + +.. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.expand`, + to setting a view's strides manually with `as_strided`, as this + function's behavior depends on the implementation of a tensor's storage. + The constructed view of the storage must only refer to elements within + the storage or a runtime error will be thrown, and if the view is + "overlapped" (with multiple indices referring to the same element in + memory) its behavior is undefined. + +Args: + {input} + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + +Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.as_tensor, + r""" +as_tensor(data, dtype=None, device=None) -> Tensor + +Converts :attr:`data` into a tensor, sharing data and preserving autograd +history if possible. + +If :attr:`data` is already a tensor with the requested dtype and device +then :attr:`data` itself is returned, but if :attr:`data` is a +tensor with a different dtype or device then it's copied as if using +`data.to(dtype=dtype, device=device)`. + +If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a +tensor is constructed using :func:`torch.from_numpy`. + +.. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + +Args: + {data} + {dtype} + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + +Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) +""".format( + **factory_data_common_args + ), +) + +add_docstr( + torch.asin, + r""" +asin(input, *, out=None) -> Tensor + +Returns a new tensor with the arcsine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arcsin, + r""" +arcsin(input, *, out=None) -> Tensor + +Alias for :func:`torch.asin`. +""", +) + +add_docstr( + torch.asinh, + r""" +asinh(input, *, out=None) -> Tensor + +Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arcsinh, + r""" +arcsinh(input, *, out=None) -> Tensor + +Alias for :func:`torch.asinh`. +""", +) + +add_docstr( + torch.atan, + r""" +atan(input, *, out=None) -> Tensor + +Returns a new tensor with the arctangent of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arctan, + r""" +arctan(input, *, out=None) -> Tensor + +Alias for :func:`torch.atan`. +""", +) + +add_docstr( + torch.atan2, + r""" +atan2(input, other, *, out=None) -> Tensor + +Element-wise arctangent of :math:`\text{{input}}_{{i}} / \text{{other}}_{{i}}` +with consideration of the quadrant. Returns a new tensor with the signed angles +in radians between vector :math:`(\text{{other}}_{{i}}, \text{{input}}_{{i}})` +and vector :math:`(1, 0)`. (Note that :math:`\text{{other}}_{{i}}`, the second +parameter, is the x-coordinate, while :math:`\text{{input}}_{{i}}`, the first +parameter, is the y-coordinate.) + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. + +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arctan2, + r""" +arctan2(input, other, *, out=None) -> Tensor +Alias for :func:`torch.atan2`. +""", +) + +add_docstr( + torch.atanh, + r""" +atanh(input, *, out=None) -> Tensor + +Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + +Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + +.. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) +""".format( + **common_args + ), +) + +add_docstr( + torch.arctanh, + r""" +arctanh(input, *, out=None) -> Tensor + +Alias for :func:`torch.atanh`. +""", +) + +add_docstr( + torch.asarray, + r""" +asarray(obj, *, dtype=None, device=None, copy=None, requires_grad=False) -> Tensor + +Converts :attr:`obj` to a tensor. + +:attr:`obj` can be one of: + +1. a tensor +2. a NumPy array or a NumPy scalar +3. a DLPack capsule +4. an object that implements Python's buffer protocol +5. a scalar +6. a sequence of scalars + +When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, +by default, not require a gradient, have the same datatype as :attr:`obj`, be on the +same device, and share memory with it. These properties can be controlled with the +:attr:`dtype`, :attr:`device`, :attr:`copy`, and :attr:`requires_grad` keyword arguments. +If the returned tensor is of a different datatype, on a different device, or a copy is +requested then it will not share its memory with :attr:`obj`. If :attr:`requires_grad` +is ``True`` then the returned tensor will require a gradient, and if :attr:`obj` is +also a tensor with an autograd history then the returned tensor will have the same history. + +When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's +buffer protocol then the buffer is interpreted as an array of bytes grouped according to +the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is +passed then the default floating point datatype is used, instead.) The returned tensor +will have the specified datatype (or default floating point datatype if none is specified) +and, by default, be on the CPU device and share memory with the buffer. + +When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on +the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will +be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + +When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the +returned tensor will, by default, infer its datatype from the scalar values, be on the +current default device, and not share its memory. + +.. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + +Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``False``, which causes the returned tensor not to require a gradient. + If ``True``, then the returned tensor will require a gradient, and if :attr:`obj` + is also a tensor with an autograd history then the returned tensor will have + the same history. + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) +""", +) + +add_docstr( + torch.baddbmm, + r""" +baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices in :attr:`batch1` +and :attr:`batch2`. +:attr:`input` is added to the final result. + +:attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same +number of matrices. + +If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a +:math:`(b \times m \times p)` tensor, then :attr:`input` must be +:ref:`broadcastable ` with a +:math:`(b \times n \times p)` tensor and :attr:`out` will be a +:math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the +same as the scaling factors used in :meth:`torch.addbmm`. + +.. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + +If :attr:`beta` is 0, then :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{batch1}} \mathbin{{@}} \text{{batch2}}` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) +""".format( + **common_args, **tf32_notes, **rocm_fp16_notes + ), +) + +add_docstr( + torch.bernoulli, + r""" +bernoulli(input, *, generator=None, out=None) -> Tensor + +Draws binary random numbers (0 or 1) from a Bernoulli distribution. + +The :attr:`input` tensor should be a tensor containing probabilities +to be used for drawing the binary random number. +Hence, all values in :attr:`input` have to be in the range: +:math:`0 \leq \text{input}_i \leq 1`. + +The :math:`\text{i}^{th}` element of the output tensor will draw a +value :math:`1` according to the :math:`\text{i}^{th}` probability value given +in :attr:`input`. + +.. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) +""" + + r""" +The returned :attr:`out` tensor only has values 0 or 1 and is of the same +shape as :attr:`input`. + +:attr:`out` can have integral ``dtype``, but :attr:`input` must have floating +point ``dtype``. + +Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + +Keyword args: + {generator} + {out} + +Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.bincount, + r""" +bincount(input, weights=None, minlength=0) -> Tensor + +Count the frequency of each value in an array of non-negative ints. + +The number of bins (size 1) is one larger than the largest value in +:attr:`input` unless :attr:`input` is empty, in which case the result is a +tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least +:attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size +:attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, +``out[n] += weights[i]`` if :attr:`weights` is specified else +``out[n] += 1``. + +Note: + {backward_reproducibility_note} + +Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + +Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + +Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) +""".format( + **reproducibility_notes + ), +) + +add_docstr( + torch.bitwise_not, + r""" +bitwise_not(input, *, out=None) -> Tensor + +Computes the bitwise NOT of the given input tensor. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical NOT. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) +""".format( + **common_args + ), +) + +add_docstr( + torch.bmm, + r""" +bmm(input, mat2, *, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices stored in :attr:`input` +and :attr:`mat2`. + +:attr:`input` and :attr:`mat2` must be 3-D tensors each containing +the same number of matrices. + +If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a +:math:`(b \times m \times p)` tensor, :attr:`out` will be a +:math:`(b \times n \times p)` tensor. + +.. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i +""" + + r""" +{tf32_note} + +{rocm_fp16_note} + +.. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + +Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + +Keyword Args: + {out} + +Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) +""".format( + **common_args, **tf32_notes, **rocm_fp16_notes + ), +) + +add_docstr( + torch.bitwise_and, + r""" +bitwise_and(input, other, *, out=None) -> Tensor + +Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical AND. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.bitwise_or, + r""" +bitwise_or(input, other, *, out=None) -> Tensor + +Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical OR. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.bitwise_xor, + r""" +bitwise_xor(input, other, *, out=None) -> Tensor + +Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical XOR. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.bitwise_left_shift, + r""" +bitwise_left_shift(input, other, *, out=None) -> Tensor + +Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. +The input tensor must be of integral type. This operator supports +:ref:`broadcasting to a common shape ` and +:ref:`type promotion `. + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{input}}_i << \text{{other}}_i + +Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) +""".format( + **common_args + ), +) + +add_docstr( + torch.bitwise_right_shift, + r""" +bitwise_right_shift(input, other, *, out=None) -> Tensor + +Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. +The input tensor must be of integral type. This operator supports +:ref:`broadcasting to a common shape ` and +:ref:`type promotion `. +In any case, if the value of the right operand is negative or is greater +or equal to the number of bits in the promoted left operand, the behavior is undefined. + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{input}}_i >> \text{{other}}_i + +Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) +""".format( + **common_args + ), +) + +add_docstr( + torch.broadcast_to, + r""" +broadcast_to(input, shape) -> Tensor + +Broadcasts :attr:`input` to the shape :attr:`\shape`. +Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + +Args: + {input} + shape (list, tuple, or :class:`torch.Size`): the new shape. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.stack, + r""" +stack(tensors, dim=0, *, out=None) -> Tensor + +Concatenates a sequence of tensors along a new dimension. + +All tensors need to be of the same size. + +.. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + +Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> x = torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + >>> x + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> x.size() + torch.Size([2, 2, 3]) + >>> x = torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> x = torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> x = torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.hstack, + r""" +hstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence horizontally (column wise). + +This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.vstack, + r""" +vstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence vertically (row wise). + +This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + + +""".format( + **common_args + ), +) + +add_docstr( + torch.dstack, + r""" +dstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence depthwise (along third axis). + +This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + + +""".format( + **common_args + ), +) + +add_docstr( + torch.tensor_split, + r""" +tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + +Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, +along dimension :attr:`dim` according to the indices or number of sections specified +by :attr:`indices_or_sections`. This function is based on NumPy's +:func:`numpy.array_split`. + +Args: + input (Tensor): the tensor to split + indices_or_sections (Tensor, int or list or tuple of ints): + If :attr:`indices_or_sections` is an integer ``n`` or a zero dimensional long tensor + with value ``n``, :attr:`input` is split into ``n`` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by ``n`` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / n`. If :attr:`input` + is not divisible by ``n``, the sizes of the first :code:`int(input.size(dim) % n)` + sections will have size :code:`int(input.size(dim) / n) + 1`, and the rest will + have size :code:`int(input.size(dim) / n)`. + + If :attr:`indices_or_sections` is a list or tuple of ints, or a one-dimensional long + tensor, then :attr:`input` is split along dimension :attr:`dim` at each of the indices + in the list, tuple or tensor. For instance, :code:`indices_or_sections=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and :code:`input[3:]`. + + If :attr:`indices_or_sections` is a tensor, it must be a zero-dimensional or one-dimensional + long tensor on the CPU. + + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + +Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) +""", +) + +add_docstr( + torch.chunk, + r""" +chunk(input, chunks, dim=0) -> List of Tensors + +Attempts to split a tensor into the specified number of chunks. Each chunk is a view of +the input tensor. + + +.. note:: + + This function may return fewer than the specified number of chunks! + +.. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + +If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, +all returned chunks will be the same size. +If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, +all returned chunks will be the same size, except the last one. +If such division is not possible, this function may return fewer +than the specified number of chunks. + +Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + +Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) +""", +) + +add_docstr( + torch.unsafe_chunk, + r""" +unsafe_chunk(input, chunks, dim=0) -> List of Tensors + +Works like :func:`torch.chunk` but without enforcing the autograd restrictions +on inplace modification of the outputs. + +.. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. +""", +) + +add_docstr( + torch.unsafe_split, + r""" +unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + +Works like :func:`torch.split` but without enforcing the autograd restrictions +on inplace modification of the outputs. + +.. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. +""", +) + +add_docstr( + torch.hsplit, + r""" +hsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors +horizontally according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +If :attr:`input` is one dimensional this is equivalent to calling +torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is +zero), and if :attr:`input` has two or more dimensions it's equivalent to calling +torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), +except that if :attr:`indices_or_sections` is an integer it must evenly divide +the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.hsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + +""", +) + +add_docstr( + torch.vsplit, + r""" +vsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors +vertically according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) +(the split dimension is 0), except that if :attr:`indices_or_sections` is an integer +it must evenly divide the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.vsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + +""", +) + +add_docstr( + torch.dsplit, + r""" +dsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors +depthwise according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) +(the split dimension is 2), except that if :attr:`indices_or_sections` is an integer +it must evenly divide the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.dsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + +""", +) + +add_docstr( + torch.can_cast, + r""" +can_cast(from, to) -> bool + +Determines if a type conversion is allowed under PyTorch casting rules +described in the type promotion :ref:`documentation `. + +Args: + from (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + +Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False +""", +) + +add_docstr( + torch.corrcoef, + r""" +corrcoef(input) -> Tensor + +Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, +where rows are the variables and columns are the observations. + +.. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + +.. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + +Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + +Returns: + (Tensor) The correlation coefficient matrix of the variables. + +.. seealso:: + + :func:`torch.cov` covariance matrix. + +Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) +""", +) + +add_docstr( + torch.cov, + r""" +cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + +Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are +the variables and columns are the observations. + +A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains +the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents +a single variable (Scalar or 1D) then its variance is returned. + +The sample covariance of the variables :math:`x` and :math:`y` is given by: + +.. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + +where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and +:math:`\delta N` is the :attr:`correction`. + +If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance +is calculated, which is given by: + +.. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + +where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is +provided, or :math:`w = f \times a` if both are provided, and +:math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not +provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + +Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + +Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered “important” and smaller for + observations considered less “important”. Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + +Returns: + (Tensor) The covariance matrix of the variables. + +.. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + +Example:: + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) +""", +) + +add_docstr( + torch.cat, + r""" +cat(tensors, dim=0, *, out=None) -> Tensor + +Concatenates the given sequence of :attr:`seq` tensors in the given dimension. +All tensors must either have the same shape (except in the concatenating +dimension) or be a 1-D empty tensor with size ``(0,)``. + +:func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` +and :func:`torch.chunk`. + +:func:`torch.cat` can be best understood via examples. + +.. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + +Args: + tensors (sequence of Tensors): any python sequence of tensors of the same type. + Non-empty tensors provided must have the same shape, except in the + cat dimension. + dim (int, optional): the dimension over which the tensors are concatenated + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.concat, + r""" +concat(tensors, dim=0, *, out=None) -> Tensor + +Alias of :func:`torch.cat`. +""", +) + +add_docstr( + torch.concatenate, + r""" +concatenate(tensors, axis=0, out=None) -> Tensor + +Alias of :func:`torch.cat`. +""", +) + +add_docstr( + torch.ceil, + r""" +ceil(input, *, out=None) -> Tensor + +Returns a new tensor with the ceil of the elements of :attr:`input`, +the smallest integer greater than or equal to each element. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +.. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.real, + r""" +real(input) -> Tensor + +Returns a new tensor containing real values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.imag, + r""" +imag(input) -> Tensor + +Returns a new tensor containing imaginary values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +.. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.view_as_real, + r""" +view_as_real(input) -> Tensor + +Returns a view of :attr:`input` as a real tensor. For an input complex tensor of +:attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new +real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 +represents the real and imaginary components of complex numbers. + +.. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.view_as_complex, + r""" +view_as_complex(input) -> Tensor + +Returns a view of :attr:`input` as a complex tensor. For an input complex +tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a +new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last +dimension of the input tensor is expected to represent the real and imaginary +components of complex numbers. + +.. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) +""".format( + **common_args + ), +) + +add_docstr( + torch.reciprocal, + r""" +reciprocal(input, *, out=None) -> Tensor + +Returns a new tensor with the reciprocal of the elements of :attr:`input` + +.. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + +.. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) +""".format( + **common_args + ), +) + +add_docstr( + torch.cholesky, + r""" +cholesky(input, upper=False, *, out=None) -> Tensor + +Computes the Cholesky decomposition of a symmetric positive-definite +matrix :math:`A` or for batches of symmetric positive-definite matrices. + +If :attr:`upper` is ``True``, the returned matrix ``U`` is upper-triangular, and +the decomposition has the form: + +.. math:: + + A = U^TU + +If :attr:`upper` is ``False``, the returned matrix ``L`` is lower-triangular, and +the decomposition has the form: + +.. math:: + + A = LL^T + +If :attr:`upper` is ``True``, and :math:`A` is a batch of symmetric positive-definite +matrices, then the returned tensor will be composed of upper-triangular Cholesky factors +of each of the individual matrices. Similarly, when :attr:`upper` is ``False``, the returned +tensor will be composed of lower-triangular Cholesky factors of each of the individual +matrices. + +.. warning:: + + :func:`torch.cholesky` is deprecated in favor of :func:`torch.linalg.cholesky` + and will be removed in a future PyTorch release. + + ``L = torch.cholesky(A)`` should be replaced with + + .. code:: python + + L = torch.linalg.cholesky(A) + + ``U = torch.cholesky(A, upper=True)`` should be replaced with + + .. code:: python + + U = torch.linalg.cholesky(A).mH + + This transform will produce equivalent results for all valid (symmetric positive definite) inputs. + +Args: + input (Tensor): the input tensor :math:`A` of size :math:`(*, n, n)` where `*` is zero or more + batch dimensions consisting of symmetric positive-definite matrices. + upper (bool, optional): flag that indicates whether to return a + upper or lower triangular matrix. Default: ``False`` + +Keyword args: + out (Tensor, optional): the output matrix + +Example:: + + >>> a = torch.randn(3, 3) + >>> a = a @ a.mT + 1e-3 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> a + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> l + tensor([[ 1.5528, 0.0000, 0.0000], + [-0.4821, 1.0592, 0.0000], + [ 0.9371, 0.5487, 0.7023]]) + >>> l @ l.mT + tensor([[ 2.4112, -0.7486, 1.4551], + [-0.7486, 1.3544, 0.1294], + [ 1.4551, 0.1294, 1.6724]]) + >>> a = torch.randn(3, 2, 2) # Example for batched input + >>> a = a @ a.mT + 1e-03 # make symmetric positive-definite + >>> l = torch.cholesky(a) + >>> z = l @ l.mT + >>> torch.dist(z, a) + tensor(2.3842e-07) +""", +) + +add_docstr( + torch.cholesky_solve, + r""" +cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + +Computes the solution of a system of linear equations with complex Hermitian +or real symmetric positive-definite lhs given its Cholesky decomposition. + +Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, +and :math:`L` its Cholesky decomposition such that: + +.. math:: + + A = LL^{\text{H}} + +where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, +and the transpose when :math:`L` is real-valued. + +Returns the solution :math:`X` of the following linear system: + +.. math:: + + AX = B + +Supports inputs of float, double, cfloat and cdouble dtypes. +Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices +then the output has the same batch dimensions. + +Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + +Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + +Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) +""", +) + +add_docstr( + torch.cholesky_inverse, + r""" +cholesky_inverse(L, upper=False, *, out=None) -> Tensor + +Computes the inverse of a complex Hermitian or real symmetric +positive-definite matrix given its Cholesky decomposition. + +Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, +and :math:`L` its Cholesky decomposition such that: + +.. math:: + + A = LL^{\text{H}} + +where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, +and the transpose when :math:`L` is real-valued. + +Computes the inverse matrix :math:`A^{-1}`. + +Supports input of float, double, cfloat and cdouble dtypes. +Also supports batches of matrices, and if :math:`A` is a batch of matrices +then the output has the same batch dimensions. + +Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + +Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + +Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) +""", +) + +add_docstr( + torch.clone, + r""" +clone(input, *, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of :attr:`input`. + +.. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + +Args: + {input} + +Keyword args: + {memory_format} +""".format( + **common_args + ), +) + +add_docstr( + torch.clamp, + r""" +clamp(input, min=None, max=None, *, out=None) -> Tensor + +Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. +Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + +.. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + +If :attr:`min` is ``None``, there is no lower bound. +Or, if :attr:`max` is ``None`` there is no upper bound. +""" + + r""" + +.. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + +Args: + {input} + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.clip, + r""" +clip(input, min=None, max=None, *, out=None) -> Tensor + +Alias for :func:`torch.clamp`. +""", +) + +add_docstr( + torch.column_stack, + r""" +column_stack(tensors, *, out=None) -> Tensor + +Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + +Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` +in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.complex, + r""" +complex(real, imag, *, out=None) -> Tensor + +Constructs a complex tensor with its real part equal to :attr:`real` and its +imaginary part equal to :attr:`imag`. + +Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + +Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + +Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + +""", +) + +add_docstr( + torch.polar, + r""" +polar(abs, angle, *, out=None) -> Tensor + +Constructs a complex tensor whose elements are Cartesian coordinates +corresponding to the polar coordinates with absolute value :attr:`abs` and angle +:attr:`angle`. + +.. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + +.. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + +""" + + r""" +Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + +Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + +Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) +""", +) + +add_docstr( + torch.conj_physical, + r""" +conj_physical(input, *, out=None) -> Tensor + +Computes the element-wise conjugate of the given :attr:`input` tensor. +If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + +.. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + +.. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + +.. math:: + \text{out}_{i} = conj(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) +""".format( + **common_args + ), +) + +add_docstr( + torch.conj, + r""" +conj(input) -> Tensor + +Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, +this function just returns :attr:`input`. + +.. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + +.. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True +""".format( + **common_args + ), +) + +add_docstr( + torch.resolve_conj, + r""" +resolve_conj(input) -> Tensor + +Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, +else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False +""".format( + **common_args + ), +) + +add_docstr( + torch.resolve_neg, + r""" +resolve_neg(input) -> Tensor + +Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, +else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False +""".format( + **common_args + ), +) + +add_docstr( + torch.copysign, + r""" +copysign(input, other, *, out=None) -> Tensor + +Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + +.. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +and integer and float inputs. + +Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + +.. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + +""".format( + **common_args + ), +) + +add_docstr( + torch.cos, + r""" +cos(input, *, out=None) -> Tensor + +Returns a new tensor with the cosine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \cos(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) +""".format( + **common_args + ), +) + +add_docstr( + torch.cosh, + r""" +cosh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic cosine of the elements of +:attr:`input`. + +.. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + +.. note:: + When :attr:`input` is on the CPU, the implementation of torch.cosh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. +""".format( + **common_args + ), +) + +add_docstr( + torch.cross, + r""" +cross(input, other, dim=None, *, out=None) -> Tensor + + +Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` +and :attr:`other`. + +Supports input of float, double, cfloat and cdouble dtypes. Also supports batches +of vectors, for which it computes the product along the dimension :attr:`dim`. +In this case, the output has the same batch dimensions as the inputs. + +.. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + +.. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + +Args: + {input} + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.logcumsumexp, + r""" +logcumsumexp(input, dim, *, out=None) -> Tensor +Returns the logarithm of the cumulative summation of the exponentiation of +elements of :attr:`input` in the dimension :attr:`dim`. + +For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{{logcumsumexp}}(x)_{{ij}} = \log \sum\limits_{{j=0}}^{{i}} \exp(x_{{ij}}) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) +""".format( + **reduceops_common_args + ), +) + +add_docstr( + torch.cummax, + r""" +cummax(input, dim, *, out=None) -> (Tensor, LongTensor) +Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of +elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index +location of each maximum value found in the dimension :attr:`dim`. + +.. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) +""".format( + **reduceops_common_args + ), +) + +add_docstr( + torch.cummin, + r""" +cummin(input, dim, *, out=None) -> (Tensor, LongTensor) +Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of +elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index +location of each maximum value found in the dimension :attr:`dim`. + +.. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) +""".format( + **reduceops_common_args + ), +) + +add_docstr( + torch.cumprod, + r""" +cumprod(input, dim, *, dtype=None, out=None) -> Tensor + +Returns the cumulative product of elements of :attr:`input` in the dimension +:attr:`dim`. + +For example, if :attr:`input` is a vector of size N, the result will also be +a vector of size N, with elements. + +.. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {dtype} + {out} + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) +""".format( + **reduceops_common_args + ), +) + +add_docstr( + torch.cumsum, + r""" +cumsum(input, dim, *, dtype=None, out=None) -> Tensor + +Returns the cumulative sum of elements of :attr:`input` in the dimension +:attr:`dim`. + +For example, if :attr:`input` is a vector of size N, the result will also be +a vector of size N, with elements. + +.. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {dtype} + {out} + +Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) +""".format( + **reduceops_common_args + ), +) + +add_docstr( + torch.count_nonzero, + r""" +count_nonzero(input, dim=None) -> Tensor + +Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. +If no dim is specified then all non-zeros in the tensor are counted. + +Args: + {input} + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + +Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) +""".format( + **reduceops_common_args + ), +) + +add_docstr( + torch.dequantize, + r""" +dequantize(tensor) -> Tensor + +Returns an fp32 Tensor by dequantizing a quantized Tensor + +Args: + tensor (Tensor): A quantized Tensor + +.. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + +Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + +Args: + tensors (sequence of Tensors): A list of quantized Tensors +""", +) + +add_docstr( + torch.diag, + r""" +diag(input, diagonal=0, *, out=None) -> Tensor + +- If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. +- If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + +The argument :attr:`diagonal` controls which diagonal to consider: + +- If :attr:`diagonal` = 0, it is the main diagonal. +- If :attr:`diagonal` > 0, it is above the main diagonal. +- If :attr:`diagonal` < 0, it is below the main diagonal. + +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +.. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + +Examples: + +Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + +Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) +""".format( + **common_args + ), +) + +add_docstr( + torch.diag_embed, + r""" +diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + +Creates a tensor whose diagonals of certain 2D planes (specified by +:attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. +To facilitate creating batched diagonal matrices, the 2D planes formed by +the last two dimensions of the returned tensor are chosen by default. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +The size of the new matrix will be calculated to make the specified diagonal +of the size of the last input dimension. +Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` +and :attr:`dim2` matters. Exchanging them is equivalent to changing the +sign of :attr:`offset`. + +Applying :meth:`torch.diagonal` to the output of this function with +the same arguments yields a matrix identical to input. However, +:meth:`torch.diagonal` has different default dimensions, so those +need to be explicitly specified. + +Args: + {input} Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + +Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) +""".format( + **common_args + ), +) + + +add_docstr( + torch.diagflat, + r""" +diagflat(input, offset=0) -> Tensor + +- If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. +- If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Args: + {input} + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + +Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.diagonal, + r""" +diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + +Returns a partial view of :attr:`input` with the its diagonal elements +with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension +at the end of the shape. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Applying :meth:`torch.diag_embed` to the output of this function with +the same arguments yields a diagonal matrix with the diagonal entries +of the input. However, :meth:`torch.diag_embed` has different default +dimensions, so those need to be explicitly specified. + +Args: + {input} Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + +.. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + +Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a, 0) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.diagonal_scatter, + r""" +diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` along +the diagonal elements of :attr:`input`, with respect to :attr:`dim1` +and :attr:`dim2`. + +This function returns a tensor with fresh storage; it does not +return a view. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Args: + {input} Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + +Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.as_strided_scatter, + r""" +as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` along +the elements corresponding to the result of calling +input.as_strided(size, stride, storage_offset). + +This function returns a tensor with fresh storage; it does not +return a view. + +Args: + {input} + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + +Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.diff, + r""" +diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + +Computes the n-th forward difference along the given dimension. + +The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order +differences are calculated by using :func:`torch.diff` recursively. + +Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.digamma, + r""" +digamma(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.digamma`. +""", +) + +add_docstr( + torch.dist, + r""" +dist(input, other, p=2) -> Tensor + +Returns the p-norm of (:attr:`input` - :attr:`other`) + +The shapes of :attr:`input` and :attr:`other` must be +:ref:`broadcastable `. + +Args: + {input} + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + +Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) +""".format( + **common_args + ), +) + +add_docstr( + torch.div, + r""" +div(input, other, *, rounding_mode=None, out=None) -> Tensor + +Divides each element of the input ``input`` by the corresponding element of +:attr:`other`. + +.. math:: + \text{{out}}_i = \frac{{\text{{input}}_i}}{{\text{{other}}_i}} + +.. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. +Always promotes integer types to the default scalar type. + +Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + +Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + {out} + +Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.divide, + r""" +divide(input, other, *, rounding_mode=None, out=None) -> Tensor + +Alias for :func:`torch.div`. +""", +) + +add_docstr( + torch.dot, + r""" +dot(input, other, *, out=None) -> Tensor + +Computes the dot product of two 1D tensors. + +.. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + +Args: + input (Tensor): first tensor in the dot product, must be 1D. + other (Tensor): second tensor in the dot product, must be 1D. + +Keyword args: + {out} + +Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) +""".format( + **common_args + ), +) + +add_docstr( + torch.vdot, + r""" +vdot(input, other, *, out=None) -> Tensor + +Computes the dot product of two 1D vectors along a dimension. + +In symbols, this function computes + +.. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + +where :math:`\overline{x_i}` denotes the conjugate for complex +vectors, and it is the identity for real vectors. + +.. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + +.. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + +Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + +Keyword args: +""" + + rf""" +.. note:: {common_args["out"]} +""" + + r""" + +Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) +""", +) + +add_docstr( + torch.eq, + r""" +eq(input, other, *, out=None) -> Tensor + +Computes element-wise equality + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.equal, + r""" +equal(input, other) -> bool + +``True`` if two tensors have the same size and elements, ``False`` otherwise. + +Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True +""", +) + +add_docstr( + torch.erf, + r""" +erf(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erf`. +""", +) + +add_docstr( + torch.erfc, + r""" +erfc(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erfc`. +""", +) + +add_docstr( + torch.erfinv, + r""" +erfinv(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erfinv`. +""", +) + +add_docstr( + torch.exp, + r""" +exp(input, *, out=None) -> Tensor + +Returns a new tensor with the exponential of the elements +of the input tensor :attr:`input`. + +.. math:: + y_{i} = e^{x_{i}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.exp2, + r""" +exp2(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.exp2`. +""", +) + +add_docstr( + torch.expm1, + r""" +expm1(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.expm1`. +""", +) + +add_docstr( + torch.eye, + r""" +eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + +Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + +Keyword arguments: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + +Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.floor, + r""" +floor(input, *, out=None) -> Tensor + +Returns a new tensor with the floor of the elements of :attr:`input`, +the largest integer less than or equal to each element. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +.. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.floor_divide, + r""" +floor_divide(input, other, *, out=None) -> Tensor + +.. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + +Computes :attr:`input` divided by :attr:`other`, elementwise, and floors +the result. + +.. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + +""" + + r""" + +Supports broadcasting to a common shape, type promotion, and integer and float inputs. + +Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) +""".format( + **common_args + ), +) + +add_docstr( + torch.fmod, + r""" +fmod(input, other, *, out=None) -> Tensor + +Applies C++'s `std::fmod `_ entrywise. +The result has the same sign as the dividend :attr:`input` and its absolute value +is less than that of :attr:`other`. + +This function may be defined in terms of :func:`torch.div` as + +.. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and float inputs. + +.. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + +.. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + +.. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + +Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + +Keyword args: + {out} + +Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.frac, + r""" +frac(input, *, out=None) -> Tensor + +Computes the fractional portion of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + +Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) +""", +) + +add_docstr( + torch.frexp, + r""" +frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + +Decomposes :attr:`input` into mantissa and exponent tensors +such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + +The range of mantissa is the open interval (-1, 1). + +Supports float inputs. + +Args: + input (Tensor): the input tensor + + +Keyword args: + out (tuple, optional): the output tensors + +Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) +""", +) + +add_docstr( + torch.from_numpy, + r""" +from_numpy(ndarray) -> Tensor + +Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + +The returned tensor and :attr:`ndarray` share the same memory. Modifications to +the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned +tensor is not resizable. + +It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, +``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, +``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, +and ``bool``. + +.. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + +Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) +""", +) + +add_docstr( + torch.frombuffer, + r""" +frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + +Creates a 1-dimensional :class:`Tensor` from an object that implements +the Python buffer protocol. + +Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of +the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` +elements. + +Note that either of the following must be true: + +1. :attr:`count` is a positive non-zero number, and the total number of bytes +in the buffer is more than :attr:`offset` plus :attr:`count` times the size +(in bytes) of :attr:`dtype`. + +2. :attr:`count` is negative, and the length (number of bytes) of the buffer +subtracted by the :attr:`offset` is a multiple of the size (in bytes) of +:attr:`dtype`. + +The returned tensor and buffer share the same memory. Modifications to +the tensor will be reflected in the buffer and vice versa. The returned +tensor is not resizable. + +.. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + +.. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + +.. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + +Args: + buffer (object): a Python object that exposes the buffer interface. + +Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + {requires_grad} + +Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.from_file, + r""" +from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + +Creates a CPU tensor with a storage backed by a memory-mapped file. + +If ``shared`` is True, then memory is shared between processes. All changes are written to the file. +If ``shared`` is False, then changes to the tensor do not affect the file. + +``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain +at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + +.. note:: + Only CPU tensors can be mapped to files. + +.. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + +Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + +Keyword args: + {dtype} + {layout} + {device} + {pin_memory} + +Example:: + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """.format( + **factory_common_args + ), +) + +add_docstr( + torch.flatten, + r""" +flatten(input, start_dim=0, end_dim=-1) -> Tensor + +Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` +are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. +The order of elements in :attr:`input` is unchanged. + +Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, +or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can +be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the +flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + +.. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + +Args: + {input} + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + +Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.unflatten, + r""" +unflatten(input, dim, sizes) -> Tensor + +Expands a dimension of the input tensor over multiple dimensions. + +.. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + +Args: + {input} + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + +Returns: + A View of input with the specified dimension unflattened. + +Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) +""".format( + **common_args + ), +) + +add_docstr( + torch.gather, + r""" +gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + +Gathers values along an axis specified by `dim`. + +For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + +:attr:`input` and :attr:`index` must have the same number of dimensions. +It is also required that ``index.size(d) <= input.size(d)`` for all +dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. +Note that ``input`` and ``index`` do not broadcast against each other. + +Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + +Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + +Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) +""", +) + + +add_docstr( + torch.gcd, + r""" +gcd(input, other, *, out=None) -> Tensor + +Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + +Both :attr:`input` and :attr:`other` must have integer types. + +.. note:: + This defines :math:`gcd(0, 0) = 0`. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) +""".format( + **common_args + ), +) + +add_docstr( + torch.ge, + r""" +ge(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \geq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.greater_equal, + r""" +greater_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.ge`. +""", +) + +add_docstr( + torch.gradient, + r""" +gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + +Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in +one or more dimensions using the `second-order accurate central differences method +`_ and +either first or second order estimates at the boundaries. + +The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not +specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates +to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional +:attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and +:math:`g(1, 2, 3)\ == input[1, 2, 3]`. + +When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. +This is detailed in the "Keyword Arguments" section below. + +The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is +accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be +improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative +is estimated using `Taylor’s theorem with remainder `_. +Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring +it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + +.. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + +Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + +.. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + +.. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + +The value of each partial derivative at the boundary points is computed differently. See edge_order below. + +Args: + input (``Tensor``): the tensor that represents the values of the function + +Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. + +Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + +""", +) + +add_docstr( + torch.geqrf, + r""" +geqrf(input, *, out=None) -> (Tensor, Tensor) + +This is a low-level function for calling LAPACK's geqrf directly. This function +returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + +Computes a QR decomposition of :attr:`input`. +Both `Q` and `R` matrices are stored in the same output tensor `a`. +The elements of `R` are stored on and above the diagonal. +Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` +are stored below the diagonal. +The results of this function can be used together with :func:`torch.linalg.householder_product` +to obtain the `Q` matrix or +with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, +for an efficient matrix-matrix multiplication. + +See `LAPACK documentation for geqrf`_ for further details. + +.. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + +Args: + input (Tensor): the input matrix + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + +.. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + +""", +) + +add_docstr( + torch.inner, + r""" +inner(input, other, *, out=None) -> Tensor + +Computes the dot product for 1D tensors. For higher dimensions, sums the product +of elements from :attr:`input` and :attr:`other` along their last dimension. + +.. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + +Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + +Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + +Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) +""", +) + +add_docstr( + torch.outer, + r""" +outer(input, vec2, *, out=None) -> Tensor + +Outer product of :attr:`input` and :attr:`vec2`. +If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of +size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + +.. note:: This function does not :ref:`broadcast `. + +Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + +Keyword args: + out (Tensor, optional): optional output matrix + +Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) +""", +) + +add_docstr( + torch.ger, + r""" +ger(input, vec2, *, out=None) -> Tensor + +Alias of :func:`torch.outer`. + +.. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. +""", +) + +add_docstr( + torch.get_default_dtype, + r""" +get_default_dtype() -> torch.dtype + +Get the current default floating point :class:`torch.dtype`. + +Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + +""", +) + +add_docstr( + torch.get_num_threads, + r""" +get_num_threads() -> int + +Returns the number of threads used for parallelizing CPU operations +""", +) + +add_docstr( + torch.get_num_interop_threads, + r""" +get_num_interop_threads() -> int + +Returns the number of threads used for inter-op parallelism on CPU +(e.g. in JIT interpreter) +""", +) + +add_docstr( + torch.gt, + r""" +gt(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} > \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + +Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.greater, + r""" +greater(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.gt`. +""", +) + +add_docstr( + torch.histc, + r""" +histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + +Computes the histogram of a tensor. + +The elements are sorted into equal width bins between :attr:`min` and +:attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and +maximum values of the data are used. + +Elements lower than min and higher than max and ``NaN`` elements are ignored. + +Args: + {input} + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + +Keyword args: + {out} + +Returns: + Tensor: Histogram represented as a tensor + +Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.histogram, + r""" +histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + +Computes a histogram of the values in a tensor. + +:attr:`bins` can be an integer or a 1D tensor. + +If :attr:`bins` is an int, it specifies the number of equal-width bins. +By default, the lower and upper range of the bins is determined by the +minimum and maximum elements of the input tensor. The :attr:`range` +argument can be provided to specify a range for the bins. + +If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges +including the rightmost edge. It should contain at least 2 elements +and its elements should be increasing. + +Args: + {input} + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + +Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + {out} (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + +Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + +Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) +""".format( + **common_args + ), +) + +add_docstr( + torch.histogramdd, + r""" +histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + +Computes a multi-dimensional histogram of the values in a tensor. + +Interprets the elements of an input tensor whose innermost dimension has size N +as a collection of N-dimensional points. Maps each of the points into a set of +N-dimensional bins and returns the number of points (or total weight) in each bin. + +:attr:`input` must be a tensor with at least 2 dimensions. +If input has shape (M, N), each of its M rows defines a point in N-dimensional space. +If input has three or more dimensions, all but the last dimension are flattened. + +Each dimension is independently associated with its own strictly increasing sequence +of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D +tensors. Alternatively, bin edges may be constructed automatically by passing a +sequence of integers specifying the number of equal-width bins in each dimension. + +For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + +:attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + +If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences +of bin edges. Each 1D tensor should contain a strictly increasing sequence with at +least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying +the left and right edges of all bins. Every bin is exclusive of its left edge. Only +the rightmost bin is inclusive of its right edge. + +If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins +in each dimension. By default, the leftmost and rightmost bin edges in each dimension +are determined by the minimum and maximum elements of the input tensor in the +corresponding dimension. The :attr:`range` argument can be provided to manually +specify the leftmost and rightmost bin edges in each dimension. + +If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + +.. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + +Args: + {input} + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. +Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. +Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + +Example:: + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + +""".format( + **common_args + ), +) +# TODO: Fix via https://github.com/pytorch/pytorch/issues/75798 +torch.histogramdd.__module__ = "torch" + +add_docstr( + torch.hypot, + r""" +hypot(input, other, *, out=None) -> Tensor + +Given the legs of a right triangle, return its hypotenuse. + +.. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. +""" + + r""" +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.i0, + r""" +i0(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.i0`. +""", +) + +add_docstr( + torch.igamma, + r""" +igamma(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.gammainc`. +""", +) + +add_docstr( + torch.igammac, + r""" +igammac(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.gammaincc`. +""", +) + +add_docstr( + torch.index_select, + r""" +index_select(input, dim, index, *, out=None) -> Tensor + +Returns a new tensor which indexes the :attr:`input` tensor along dimension +:attr:`dim` using the entries in :attr:`index` which is a `LongTensor`. + +The returned tensor has the same number of dimensions as the original tensor +(:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length +of :attr:`index`; other dimensions have the same size as in the original tensor. + +.. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + +Args: + {input} + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.inverse, + r""" +inverse(input, *, out=None) -> Tensor + +Alias for :func:`torch.linalg.inv` +""", +) + +add_docstr( + torch.isin, + r""" +isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + +Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns +a boolean tensor of the same shape as :attr:`elements` that is True for elements +in :attr:`test_elements` and False otherwise. + +.. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + +Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + +Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + +Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) +""", +) + +add_docstr( + torch.isinf, + r""" +isinf(input) -> Tensor + +Tests if each element of :attr:`input` is infinite +(positive or negative infinity) or not. + +.. note:: + Complex values are infinite when their real or imaginary part is + infinite. + +Args: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + +Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.isposinf, + r""" +isposinf(input, *, out=None) -> Tensor +Tests if each element of :attr:`input` is positive infinity or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.isneginf, + r""" +isneginf(input, *, out=None) -> Tensor +Tests if each element of :attr:`input` is negative infinity or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.isclose, + r""" +isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +Returns a new tensor with boolean elements representing if each element of +:attr:`input` is "close" to the corresponding element of :attr:`other`. +Closeness is defined as: + +.. math:: + \lvert \text{input} - \text{other} \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other} \rvert +""" + + r""" + +where :attr:`input` and :attr:`other` are finite. Where :attr:`input` +and/or :attr:`other` are nonfinite they are close if and only if +they are equal, with NaNs being considered equal to each other when +:attr:`equal_nan` is True. + +Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + +Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) +""", +) + +add_docstr( + torch.isfinite, + r""" +isfinite(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element is `finite` or not. + +Real values are finite when they are not NaN, negative infinity, or infinity. +Complex values are finite when both their real and imaginary parts are finite. + +Args: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + +Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.isnan, + r""" +isnan(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element of :attr:`input` +is NaN or not. Complex values are considered NaN when either their real +and/or imaginary part is NaN. + +Arguments: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + +Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.isreal, + r""" +isreal(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. +All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + +Arguments: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + +Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) +""".format( + **common_args + ), +) + +add_docstr( + torch.is_floating_point, + r""" +is_floating_point(input) -> (bool) + +Returns True if the data type of :attr:`input` is a floating point data type i.e., +one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + +Args: + {input} +""".format( + **common_args + ), +) + +add_docstr( + torch.is_complex, + r""" +is_complex(input) -> (bool) + +Returns True if the data type of :attr:`input` is a complex data type i.e., +one of ``torch.complex64``, and ``torch.complex128``. + +Args: + {input} +""".format( + **common_args + ), +) + +add_docstr( + torch.is_grad_enabled, + r""" +is_grad_enabled() -> (bool) + +Returns True if grad mode is currently enabled. +""".format( + **common_args + ), +) + +add_docstr( + torch.is_inference_mode_enabled, + r""" +is_inference_mode_enabled() -> (bool) + +Returns True if inference mode is currently enabled. +""".format( + **common_args + ), +) + +add_docstr( + torch.is_inference, + r""" +is_inference(input) -> (bool) + +Returns True if :attr:`input` is an inference tensor. + +A non-view tensor is an inference tensor if and only if it was +allocated during inference mode. A view tensor is an inference +tensor if and only if the tensor it is a view of is an inference tensor. + +For details on inference mode please see +`Inference Mode `_. + +Args: + {input} +""".format( + **common_args + ), +) + +add_docstr( + torch.is_conj, + r""" +is_conj(input) -> (bool) + +Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + +Args: + {input} +""".format( + **common_args + ), +) + +add_docstr( + torch.is_nonzero, + r""" +is_nonzero(input) -> (bool) + +Returns True if the :attr:`input` is a single element tensor which is not equal to zero +after type conversions. +i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or +``torch.tensor([False])``. +Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case +of sparse tensors). + +Args: + {input} + +Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: bool value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: bool value of Tensor with no values is ambiguous +""".format( + **common_args + ), +) + +add_docstr( + torch.kron, + r""" +kron(input, other, *, out=None) -> Tensor + +Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + +If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a +:math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a +:math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + +.. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + +where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. +If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + +Supports real-valued and complex-valued inputs. + +.. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + +Arguments: + input (Tensor) + other (Tensor) + +Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + +Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) +""", +) + +add_docstr( + torch.kthvalue, + r""" +kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + +Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th +smallest element of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each element found. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors +are the same size as :attr:`input`, except in the dimension :attr:`dim` where +they are of size 1. Otherwise, :attr:`dim` is squeezed +(see :func:`torch.squeeze`), resulting in both the :attr:`values` and +:attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + +.. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + +Args: + {input} + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + {keepdim} + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + +Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.lcm, + r""" +lcm(input, other, *, out=None) -> Tensor + +Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + +Both :attr:`input` and :attr:`other` must have integer types. + +.. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) +""".format( + **common_args + ), +) + +add_docstr( + torch.ldexp, + r""" +ldexp(input, other, *, out=None) -> Tensor + +Multiplies :attr:`input` by 2 ** :attr:`other`. + +.. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i +""" + + r""" + +Typically this function is used to construct floating point numbers by multiplying +mantissas in :attr:`input` with integral powers of two created from the exponents +in :attr:`other`. + +Args: + {input} + other (Tensor): a tensor of exponents, typically integers. + +Keyword args: + {out} + +Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + + +""".format( + **common_args + ), +) + +add_docstr( + torch.le, + r""" +le(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \leq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + +Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.less_equal, + r""" +less_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.le`. +""", +) + +add_docstr( + torch.lerp, + r""" +lerp(input, end, weight, *, out=None) + +Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based +on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + +.. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) +""" + + r""" +The shapes of :attr:`start` and :attr:`end` must be +:ref:`broadcastable `. If :attr:`weight` is a tensor, then +the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + +Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + +Keyword args: + {out} + +Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) +""".format( + **common_args + ), +) + +add_docstr( + torch.lgamma, + r""" +lgamma(input, *, out=None) -> Tensor + +Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + +.. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| +""" + + """ +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) +""".format( + **common_args + ), +) + +add_docstr( + torch.linspace, + r""" +linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly +spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + +.. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) +""" + + """ + +From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + +Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + +Keyword arguments: + {out} + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + {layout} + {device} + {requires_grad} + + +Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.log, + r""" +log(input, *, out=None) -> Tensor + +Returns a new tensor with the natural logarithm of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{e} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) +""".format( + **common_args + ), +) + +add_docstr( + torch.log10, + r""" +log10(input, *, out=None) -> Tensor + +Returns a new tensor with the logarithm to the base 10 of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{10} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.log1p, + r""" +log1p(input, *, out=None) -> Tensor + +Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + +.. math:: + y_i = \log_{e} (x_i + 1) +""" + + r""" +.. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) +""".format( + **common_args + ), +) + +add_docstr( + torch.log2, + r""" +log2(input, *, out=None) -> Tensor + +Returns a new tensor with the logarithm to the base 2 of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{2} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.logaddexp, + r""" +logaddexp(input, other, *, out=None) -> Tensor + +Logarithm of the sum of exponentiations of the inputs. + +Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful +in statistics where the calculated probabilities of events may be so small as to +exceed the range of normal floating point numbers. In such cases the logarithm +of the calculated probability is stored. This function allows adding +probabilities stored in such a fashion. + +This op should be disambiguated with :func:`torch.logsumexp` which performs a +reduction on a single tensor. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) +""".format( + **common_args + ), +) + +add_docstr( + torch.logaddexp2, + r""" +logaddexp2(input, other, *, out=None) -> Tensor + +Logarithm of the sum of exponentiations of the inputs in base-2. + +Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See +:func:`torch.logaddexp` for more details. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} +""".format( + **common_args + ), +) + +add_docstr( + torch.xlogy, + r""" +xlogy(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.xlogy`. +""", +) + +add_docstr( + torch.logical_and, + r""" +logical_and(input, other, *, out=None) -> Tensor + +Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute AND with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.logical_not, + r""" +logical_not(input, *, out=None) -> Tensor + +Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool +dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) +""".format( + **common_args + ), +) + +add_docstr( + torch.logical_or, + r""" +logical_or(input, other, *, out=None) -> Tensor + +Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute OR with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.logical_xor, + r""" +logical_xor(input, other, *, out=None) -> Tensor + +Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute XOR with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) +""".format( + **common_args + ), +) + +add_docstr( + torch.logspace, + """ +logspace(start, end, steps, base=10.0, *, \ + out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" + +Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly +spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to +:math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale +with base :attr:`base`. That is, the values are: + +.. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) +""" + + """ + + +From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + +Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + +Keyword arguments: + {out} + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.logsumexp, + r""" +logsumexp(input, dim, keepdim=False, *, out=None) + +Returns the log of summed exponentials of each row of the :attr:`input` +tensor in the given dimension :attr:`dim`. The computation is numerically +stabilized. + +For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{{logsumexp}}(x)_{{i}} = \log \sum_j \exp(x_{{ij}}) + +{keepdim_details} + +Args: + {input} + {opt_dim} + {keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.lt, + r""" +lt(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} < \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + +Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.lu_unpack, + r""" +lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + +Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + +.. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + +Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + +Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + +Returns: + A namedtuple ``(P, L, U)`` + +Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + +""".format( + **common_args + ), +) + +add_docstr( + torch.less, + r""" +less(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.lt`. +""", +) + +add_docstr( + torch.lu_solve, + r""" +lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + +Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted +LU factorization of A from :func:`~linalg.lu_factor`. + +This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + +.. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + +Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + +Keyword args: + {out} + +Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) +""".format( + **common_args + ), +) + +add_docstr( + torch.masked_select, + r""" +masked_select(input, mask, *, out=None) -> Tensor + +Returns a new 1-D tensor which indexes the :attr:`input` tensor according to +the boolean mask :attr:`mask` which is a `BoolTensor`. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need +to match, but they must be :ref:`broadcastable `. + +.. note:: The returned tensor does **not** use the same storage + as the original tensor + +Args: + {input} + mask (BoolTensor): the tensor containing the binary mask to index with + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) +""".format( + **common_args + ), +) + +add_docstr( + torch.matrix_power, + r""" +matrix_power(input, n, *, out=None) -> Tensor + +Alias for :func:`torch.linalg.matrix_power` +""", +) + +add_docstr( + torch.matrix_exp, + r""" +matrix_exp(A) -> Tensor + +Alias for :func:`torch.linalg.matrix_exp`. +""", +) + +add_docstr( + torch.max, + r""" +max(input) -> Tensor + +Returns the maximum value of all elements in the ``input`` tensor. + +.. warning:: + This function produces deterministic (sub)gradients unlike ``max(dim=0)`` + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + +.. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each maximum value found +(argmax). + +If ``keepdim`` is ``True``, the output tensors are of the same size +as ``input`` except in the dimension ``dim`` where they are of size 1. +Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting +in the output tensors having 1 fewer dimension than ``input``. + +.. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + +Args: + {input} + {dim} + {keepdim} Default: ``False``. + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + +.. function:: max(input, other, *, out=None) -> Tensor + :noindex: + +See :func:`torch.maximum`. + +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.maximum, + r""" +maximum(input, other, *, out=None) -> Tensor + +Computes the element-wise maximum of :attr:`input` and :attr:`other`. + +.. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) +""".format( + **common_args + ), +) + +add_docstr( + torch.fmax, + r""" +fmax(input, other, *, out=None) -> Tensor + +Computes the element-wise maximum of :attr:`input` and :attr:`other`. + +This is like :func:`torch.maximum` except it handles NaNs differently: +if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. +Only if both elements are NaN is NaN propagated. + +This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and floating-point inputs. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) +""".format( + **common_args + ), +) + +add_docstr( + torch.amax, + r""" +amax(input, dim, keepdim=False, *, out=None) -> Tensor + +Returns the maximum value of each slice of the :attr:`input` tensor in the given +dimension(s) :attr:`dim`. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices, + - ``amax``/``amin`` evenly distributes gradient between equal values, + while ``max(dim)``/``min(dim)`` propagates gradient only to a single + index in the source tensor. + +{keepdim_details} + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.argmax, + r""" +argmax(input) -> LongTensor + +Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + +This is the second value returned by :meth:`torch.max`. See its +documentation for the exact semantics of this method. + +.. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + +Args: + {input} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + +.. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + +Returns the indices of the maximum values of a tensor across a dimension. + +This is the second value returned by :meth:`torch.max`. See its +documentation for the exact semantics of this method. + +Args: + {input} + {dim} If ``None``, the argmax of the flattened input is returned. + {keepdim} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.argwhere, + r""" +argwhere(input) -> Tensor + +Returns a tensor containing the indices of all non-zero elements of +:attr:`input`. Each row in the result contains the indices of a non-zero +element in :attr:`input`. The result is sorted lexicographically, with +the last index changing the fastest (C-style). + +If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor +:attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +.. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + +Args: + {input} + +Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) +""", +) + +add_docstr( + torch.mean, + r""" +mean(input, *, dtype=None) -> Tensor + +Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + +Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + +.. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + +Returns the mean value of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + {dtype} + {out} + +.. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.nanmean, + r""" +nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + +Computes the mean of all `non-NaN` elements along the specified dimensions. + +This function is identical to :func:`torch.mean` when there are no `NaN` values +in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will +propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the +`NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + +{keepdim_details} + +Args: + {input} + {opt_dim} + {keepdim} + +Keyword args: + {dtype} + {out} + +.. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + +Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.median, + r""" +median(input) -> Tensor + +Returns the median of the values in :attr:`input`. + +.. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + +.. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + +.. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` +in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + +By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + +If :attr:`keepdim` is ``True``, the output tensors are of the same size +as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the outputs tensor having 1 fewer dimension than :attr:`input`. + +.. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + +.. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + +Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.nanmedian, + r""" +nanmedian(input) -> Tensor + +Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + +This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. +When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, +while this function will return the median of the non-``NaN`` elements in :attr:`input`. +If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + +Args: + {input} + +Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + +.. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` +in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values +found in the dimension :attr:`dim`. + +This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has +one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the +median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + +Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.quantile, + r""" +quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + +Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + +To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location +of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with +indices ``i`` and ``j`` in the sorted order, result is computed according to the given +:attr:`interpolation` method as follows: + +- ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. +- ``lower``: ``a``. +- ``higher``: ``b``. +- ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (rounding down for .5 fractions). +- ``midpoint``: ``(a + b) / 2``. + +If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size +equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + +.. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + +Args: + {input} + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + {dim} + {keepdim} + +Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + {out} + +Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.nanquantile, + r""" +nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + +This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, +computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did +not exist. If all values in a reduced row are ``NaN`` then the quantiles for +that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + +Args: + {input} + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + {dim} + {keepdim} + +Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + {out} + +Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.min, + r""" +min(input) -> Tensor + +Returns the minimum value of all elements in the :attr:`input` tensor. + +.. warning:: + This function produces deterministic (sub)gradients unlike ``min(dim=0)`` + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + +.. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each minimum value found +(argmin). + +If :attr:`keepdim` is ``True``, the output tensors are of the same size as +:attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the output tensors having 1 fewer dimension than :attr:`input`. + +.. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + +.. function:: min(input, other, *, out=None) -> Tensor + :noindex: + +See :func:`torch.minimum`. +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.minimum, + r""" +minimum(input, other, *, out=None) -> Tensor + +Computes the element-wise minimum of :attr:`input` and :attr:`other`. + +.. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) +""".format( + **common_args + ), +) + +add_docstr( + torch.fmin, + r""" +fmin(input, other, *, out=None) -> Tensor + +Computes the element-wise minimum of :attr:`input` and :attr:`other`. + +This is like :func:`torch.minimum` except it handles NaNs differently: +if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. +Only if both elements are NaN is NaN propagated. + +This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and floating-point inputs. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) +""".format( + **common_args + ), +) + +add_docstr( + torch.amin, + r""" +amin(input, dim, keepdim=False, *, out=None) -> Tensor + +Returns the minimum value of each slice of the :attr:`input` tensor in the given +dimension(s) :attr:`dim`. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices, + - ``amax``/``amin`` evenly distributes gradient between equal values, + while ``max(dim)``/``min(dim)`` propagates gradient only to a single + index in the source tensor. + +{keepdim_details} + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.aminmax, + r""" +aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + +Computes the minimum and maximum values of the :attr:`input` tensor. + +Args: + input (Tensor): + The input tensor + +Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + +Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + +Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + +.. note:: + NaN values are propagated to the output if at least one value is NaN. + +.. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + +Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) +""", +) + +add_docstr( + torch.argmin, + r""" +argmin(input, dim=None, keepdim=False) -> LongTensor + +Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + +This is the second value returned by :meth:`torch.min`. See its +documentation for the exact semantics of this method. + +.. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + +Args: + {input} + {dim} If ``None``, the argmin of the flattened input is returned. + {keepdim} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.mm, + r""" +mm(input, mat2, *, out=None) -> Tensor + +Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + +If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a +:math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + +.. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + +Supports strided and sparse 2-D tensors as inputs, autograd with +respect to strided inputs. + +This operation has support for arguments with :ref:`sparse layouts`. +If :attr:`out` is provided it's layout will be used. Otherwise, the result +layout will be deduced from that of :attr:`input`. + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + +Keyword args: + {out} + +Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) +""".format( + **common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes + ), +) + +add_docstr( + torch.hspmm, + r""" +hspmm(mat1, mat2, *, out=None) -> Tensor + +Performs a matrix multiplication of a :ref:`sparse COO matrix +` :attr:`mat1` and a strided matrix :attr:`mat2`. The +result is a (1 + 1)-dimensional :ref:`hybrid COO matrix +`. + +Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + +Keyword args: + {out} +""".format( + **common_args + ), +) + +add_docstr( + torch.matmul, + r""" +matmul(input, other, *, out=None) -> Tensor + +Matrix product of two tensors. + +The behavior depends on the dimensionality of the tensors as follows: + +- If both tensors are 1-dimensional, the dot product (scalar) is returned. +- If both arguments are 2-dimensional, the matrix-matrix product is returned. +- If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. +- If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. +- If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiple and removed after. + The non-matrix (i.e. batch) dimensions are :ref:`broadcasted ` (and thus + must be broadcastable). For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times n)` tensor and :attr:`other` is a :math:`(k \times n \times n)` + tensor, :attr:`out` will be a :math:`(j \times k \times n \times n)` tensor. + + Note that the broadcasting logic only looks at the batch dimensions when determining if the inputs + are broadcastable, and not the matrix dimensions. For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, these inputs are valid for broadcasting even though the final two dimensions (i.e. the + matrix dimensions) are different. :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + +This operation has support for arguments with :ref:`sparse layouts`. In particular the +matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions +as :func:`torch.mm` + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +.. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + +Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + +Keyword args: + {out} + +Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + +""".format( + **common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes + ), +) + +add_docstr( + torch.mode, + r""" +mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + +Returns a namedtuple ``(values, indices)`` where ``values`` is the mode +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`, i.e. a value which appears most often +in that row, and ``indices`` is the index location of each mode value found. + +By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + +If :attr:`keepdim` is ``True``, the output tensors are of the same size as +:attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting +in the output tensors having 1 fewer dimension than :attr:`input`. + +.. note:: This function is not defined for ``torch.cuda.Tensor`` yet. + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> b = torch.tensor( + [[0, 0, 0, 2, 0, 0, 2], + [0, 3, 0, 0, 2, 0, 1], + [2, 2, 2, 0, 0, 0, 3], + [2, 2, 3, 0, 1, 1, 0], + [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.mul, + r""" +mul(input, other, *, out=None) -> Tensor + +Multiplies :attr:`input` by :attr:`other`. + + +.. math:: + \text{out}_i = \text{input}_i \times \text{other}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number) - the tensor or number to multiply input by. + +Keyword args: + {out} + +Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.multiply, + r""" +multiply(input, other, *, out=None) + +Alias for :func:`torch.mul`. +""", +) + +add_docstr( + torch.multinomial, + r""" +multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + +Returns a tensor where each row contains :attr:`num_samples` indices sampled +from the multinomial (a stricter definition would be multivariate, +refer to torch.distributions.multinomial.Multinomial for more details) +probability distribution located in the corresponding row +of tensor :attr:`input`. + +.. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + +Indices are ordered from left to right according to when each was sampled +(first samples are placed in first column). + +If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + +If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape +:math:`(m \times \text{{num\_samples}})`. + +If replacement is ``True``, samples are drawn with replacement. + +If not, they are drawn without replacement, which means that when a +sample index is drawn for a row, it cannot be drawn again for that row. + +.. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + +Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + +Keyword args: + {generator} + {out} + +Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 4) # ERROR! + RuntimeError: invalid argument 2: invalid multinomial distribution (with replacement=False, + not enough non-negative category to sample) at ../aten/src/TH/generic/THTensorRandom.cpp:320 + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) +""".format( + **common_args + ), +) + +add_docstr( + torch.mv, + r""" +mv(input, vec, *, out=None) -> Tensor + +Performs a matrix-vector product of the matrix :attr:`input` and the vector +:attr:`vec`. + +If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of +size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + +.. note:: This function does not :ref:`broadcast `. + +Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + +Keyword args: + {out} + +Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) +""".format( + **common_args + ), +) + +add_docstr( + torch.mvlgamma, + r""" +mvlgamma(input, p, *, out=None) -> Tensor + +Alias for :func:`torch.special.multigammaln`. +""", +) + +add_docstr( + torch.movedim, + r""" +movedim(input, source, destination) -> Tensor + +Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` +to the position(s) in :attr:`destination`. + +Other dimensions of :attr:`input` that are not explicitly moved remain in +their original order and appear at the positions not specified in :attr:`destination`. + +Args: + {input} + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + +Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.moveaxis, + r""" +moveaxis(input, source, destination) -> Tensor + +Alias for :func:`torch.movedim`. + +This function is equivalent to NumPy's moveaxis function. + +Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.swapdims, + r""" +swapdims(input, dim0, dim1) -> Tensor + +Alias for :func:`torch.transpose`. + +This function is equivalent to NumPy's swapaxes function. + +Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.swapaxes, + r""" +swapaxes(input, axis0, axis1) -> Tensor + +Alias for :func:`torch.transpose`. + +This function is equivalent to NumPy's swapaxes function. + +Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.narrow, + r""" +narrow(input, dim, start, length) -> Tensor + +Returns a new tensor that is a narrowed version of :attr:`input` tensor. The +dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The +returned tensor and :attr:`input` tensor share the same underlying storage. + +Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) +""", +) + +add_docstr( + torch.narrow_copy, + r""" +narrow_copy(input, dim, start, length, *, out=None) -> Tensor + +Same as :meth:`Tensor.narrow` except this returns a copy rather +than shared storage. This is primarily for sparse tensors, which +do not have a shared-storage narrow method. + +Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + +Keyword args: + {out} + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + +.. seealso:: + + :func:`torch.narrow` for a non copy variant + +""".format( + **common_args + ), +) + +add_docstr( + torch.nan_to_num, + r""" +nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + +Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` +with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. +By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the +greatest finite value representable by :attr:`input`'s dtype, and negative infinity +is replaced with the least finite value representable by :attr:`input`'s dtype. + +Args: + {input} + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + +Keyword args: + {out} + +Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.ne, + r""" +ne(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \neq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.not_equal, + r""" +not_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.ne`. +""", +) + +add_docstr( + torch.neg, + r""" +neg(input, *, out=None) -> Tensor + +Returns a new tensor with the negative of the elements of :attr:`input`. + +.. math:: + \text{out} = -1 \times \text{input} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) +""".format( + **common_args + ), +) + +add_docstr( + torch.negative, + r""" +negative(input, *, out=None) -> Tensor + +Alias for :func:`torch.neg` +""", +) + +add_docstr( + torch.nextafter, + r""" +nextafter(input, other, *, out=None) -> Tensor + +Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. + +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.nonzero, + r""" +nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + +.. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + +**When** :attr:`as_tuple` **is** ``False`` **(default)**: + +Returns a tensor containing the indices of all non-zero elements of +:attr:`input`. Each row in the result contains the indices of a non-zero +element in :attr:`input`. The result is sorted lexicographically, with +the last index changing the fastest (C-style). + +If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor +:attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +**When** :attr:`as_tuple` **is** ``True``: + +Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, +each containing the indices (in that dimension) of all non-zero elements of +:attr:`input` . + +If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` +tensors of size :math:`z`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +As a special case, when :attr:`input` has zero dimensions and a nonzero scalar +value, it is treated as a one-dimensional tensor with one element. + +Args: + {input} + +Keyword args: + out (LongTensor, optional): the output tensor containing indices + +Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + +Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) +""".format( + **common_args + ), +) + +add_docstr( + torch.normal, + r""" +normal(mean, std, *, generator=None, out=None) -> Tensor + +Returns a tensor of random numbers drawn from separate normal distributions +whose mean and standard deviation are given. + +The :attr:`mean` is a tensor with the mean of +each output element's normal distribution + +The :attr:`std` is a tensor with the standard deviation of +each output element's normal distribution + +The shapes of :attr:`mean` and :attr:`std` don't need to match, but the +total number of elements in each tensor need to be the same. + +.. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + +.. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + +Args: + mean (Tensor): the tensor of per-element means + std (Tensor): the tensor of per-element standard deviations + +Keyword args: + {generator} + {out} + +Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + +.. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the means are shared among all drawn +elements. + +Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + +Keyword args: + {out} + +Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + +.. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the standard deviations are shared among +all drawn elements. + +Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + +Keyword args: + out (Tensor, optional): the output tensor + +Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + +.. function:: normal(mean, std, size, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the means and standard deviations are shared +among all drawn elements. The resulting tensor has size given by :attr:`size`. + +Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + +Keyword args: + {out} + +Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.numel, + r""" +numel(input) -> int + +Returns the total number of elements in the :attr:`input` tensor. + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + +""".format( + **common_args + ), +) + +add_docstr( + torch.ones, + r""" +ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with the scalar value `1`, with the shape defined +by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword arguments: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.ones_like, + r""" +ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor filled with the scalar value `1`, with the same size as +:attr:`input`. ``torch.ones_like(input)`` is equivalent to +``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + +Args: + {input} + +Keyword arguments: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.orgqr, + r""" +orgqr(input, tau) -> Tensor + +Alias for :func:`torch.linalg.householder_product`. +""", +) + +add_docstr( + torch.ormqr, + r""" +ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + +Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + +Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, +where `Q` is represented using Householder reflectors `(input, tau)`. +See `Representation of Orthogonal or Unitary Matrices`_ for further details. + +If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. +When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. +It has size :math:`n \times n` otherwise. +If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + +Supports inputs of float, double, cfloat and cdouble dtypes. +Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + +.. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + +.. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + +Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + +Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + +.. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html +""", +) + +add_docstr( + torch.permute, + r""" +permute(input, dims) -> Tensor + +Returns a view of the original tensor :attr:`input` with its dimensions permuted. + +Args: + {input} + dims (tuple of int): The desired ordering of dimensions + +Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) +""".format( + **common_args + ), +) + +add_docstr( + torch.poisson, + r""" +poisson(input, generator=None) -> Tensor + +Returns a tensor of the same size as :attr:`input` with each element +sampled from a Poisson distribution with rate parameter given by the corresponding +element in :attr:`input` i.e., + +.. math:: + \text{{out}}_i \sim \text{{Poisson}}(\text{{input}}_i) + +:attr:`input` must be non-negative. + +Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + +Keyword args: + {generator} + +Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.polygamma, + r""" +polygamma(n, input, *, out=None) -> Tensor + +Alias for :func:`torch.special.polygamma`. +""", +) + +add_docstr( + torch.positive, + r""" +positive(input) -> Tensor + +Returns :attr:`input`. +Throws a runtime error if :attr:`input` is a bool tensor. +""" + + r""" +Args: + {input} + +Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) +""".format( + **common_args + ), +) + +add_docstr( + torch.pow, + r""" +pow(input, exponent, *, out=None) -> Tensor + +Takes the power of each element in :attr:`input` with :attr:`exponent` and +returns a tensor with the result. + +:attr:`exponent` can be either a single ``float`` number or a `Tensor` +with the same number of elements as :attr:`input`. + +When :attr:`exponent` is a scalar value, the operation applied is: + +.. math:: + \text{out}_i = x_i ^ \text{exponent} + +When :attr:`exponent` is a tensor, the operation applied is: + +.. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} +""" + + r""" +When :attr:`exponent` is a tensor, the shapes of :attr:`input` +and :attr:`exponent` must be :ref:`broadcastable `. + +Args: + {input} + exponent (float or tensor): the exponent value + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + +.. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + +:attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. +The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{self}} ^ {{\text{{exponent}}_i}} + +Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + +Keyword args: + {out} + +Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.float_power, + r""" +float_power(input, exponent, *, out=None) -> Tensor + +Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. +If neither input is complex returns a ``torch.float64`` tensor, +and if one or more inputs is complex returns a ``torch.complex128`` tensor. + +.. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + +Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + +Keyword args: + {out} + +Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) +""".format( + **common_args + ), +) + +add_docstr( + torch.prod, + r""" +prod(input, *, dtype=None) -> Tensor + +Returns the product of all elements in the :attr:`input` tensor. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + +.. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the product of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. + +{keepdim_details} + +Args: + {input} + {dim} + {keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) +""".format( + **single_dim_common + ), +) + +add_docstr( + torch.promote_types, + r""" +promote_types(type1, type2) -> dtype + +Returns the :class:`torch.dtype` with the smallest size and scalar kind that is +not smaller nor of lower kind than either `type1` or `type2`. See type promotion +:ref:`documentation ` for more information on the type +promotion logic. + +Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + +Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long +""", +) + +add_docstr( + torch.qr, + r""" +qr(input, some=True, *, out=None) -> (Tensor, Tensor) + +Computes the QR decomposition of a matrix or a batch of matrices :attr:`input`, +and returns a namedtuple (Q, R) of tensors such that :math:`\text{input} = Q R` +with :math:`Q` being an orthogonal matrix or batch of orthogonal matrices and +:math:`R` being an upper triangular matrix or batch of upper triangular matrices. + +If :attr:`some` is ``True``, then this function returns the thin (reduced) QR factorization. +Otherwise, if :attr:`some` is ``False``, this function returns the complete QR factorization. + +.. warning:: + + :func:`torch.qr` is deprecated in favor of :func:`torch.linalg.qr` + and will be removed in a future PyTorch release. The boolean parameter :attr:`some` has been + replaced with a string parameter :attr:`mode`. + + ``Q, R = torch.qr(A)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A) + + ``Q, R = torch.qr(A, some=False)`` should be replaced with + + .. code:: python + + Q, R = torch.linalg.qr(A, mode="complete") + +.. warning:: + If you plan to backpropagate through QR, note that the current backward implementation + is only well-defined when the first :math:`\min(input.size(-1), input.size(-2))` + columns of :attr:`input` are linearly independent. + This behavior will probably change once QR supports pivoting. + +.. note:: This function uses LAPACK for CPU inputs and MAGMA for CUDA inputs, + and may produce different (valid) decompositions on different device types + or different platforms. + +Args: + input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more + batch dimensions consisting of matrices of dimension :math:`m \times n`. + some (bool, optional): Set to ``True`` for reduced QR decomposition and ``False`` for + complete QR decomposition. If `k = min(m, n)` then: + + * ``some=True`` : returns `(Q, R)` with dimensions (m, k), (k, n) (default) + + * ``'some=False'``: returns `(Q, R)` with dimensions (m, m), (m, n) + +Keyword args: + out (tuple, optional): tuple of `Q` and `R` tensors. + The dimensions of `Q` and `R` are detailed in the description of :attr:`some` above. + +Example:: + + >>> a = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]]) + >>> q, r = torch.qr(a) + >>> q + tensor([[-0.8571, 0.3943, 0.3314], + [-0.4286, -0.9029, -0.0343], + [ 0.2857, -0.1714, 0.9429]]) + >>> r + tensor([[ -14.0000, -21.0000, 14.0000], + [ 0.0000, -175.0000, 70.0000], + [ 0.0000, 0.0000, -35.0000]]) + >>> torch.mm(q, r).round() + tensor([[ 12., -51., 4.], + [ 6., 167., -68.], + [ -4., 24., -41.]]) + >>> torch.mm(q.t(), q).round() + tensor([[ 1., 0., 0.], + [ 0., 1., -0.], + [ 0., -0., 1.]]) + >>> a = torch.randn(3, 4, 5) + >>> q, r = torch.qr(a, some=False) + >>> torch.allclose(torch.matmul(q, r), a) + True + >>> torch.allclose(torch.matmul(q.mT, q), torch.eye(5)) + True +""", +) + +add_docstr( + torch.rad2deg, + r""" +rad2deg(input, *, out=None) -> Tensor + +Returns a new tensor with each of the elements of :attr:`input` +converted from angles in radians to degrees. + +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.deg2rad, + r""" +deg2rad(input, *, out=None) -> Tensor + +Returns a new tensor with each of the elements of :attr:`input` +converted from angles in degrees to radians. + +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.heaviside, + r""" +heaviside(input, values, *, out=None) -> Tensor + +Computes the Heaviside step function for each element in :attr:`input`. +The Heaviside step function is defined as: + +.. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} +""" + + r""" + +Args: + {input} + values (Tensor): The values to use where :attr:`input` is zero. + +Keyword arguments: + {out} + +Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.rand, + """ +rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, \ +requires_grad=False, pin_memory=False) -> Tensor +""" + + r""" +Returns a tensor filled with random numbers from a uniform distribution +on the interval :math:`[0, 1)` + +The shape of the tensor is defined by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.rand_like, + r""" +rand_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor with the same size as :attr:`input` that is filled with +random numbers from a uniform distribution on the interval :math:`[0, 1)`. +``torch.rand_like(input)`` is equivalent to +``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.randint, + """ +randint(low=0, high, size, \\*, generator=None, out=None, \ +dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with random integers generated uniformly +between :attr:`low` (inclusive) and :attr:`high` (exclusive). + +The shape of the tensor is defined by the variable argument :attr:`size`. + +.. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + +Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + +Keyword args: + {generator} + {out} + dtype (`torch.dtype`, optional) - the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + + +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.randint_like, + """ +randint_like(input, low=0, high, \\*, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +memory_format=torch.preserve_format) -> Tensor + +Returns a tensor with the same shape as Tensor :attr:`input` filled with +random integers generated uniformly between :attr:`low` (inclusive) and +:attr:`high` (exclusive). + +.. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + +Args: + {input} + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.randn, + """ +randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a tensor filled with random numbers from a normal distribution +with mean `0` and variance `1` (also called the standard normal +distribution). + +.. math:: + \text{{out}}_{{i}} \sim \mathcal{{N}}(0, 1) + +For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and +unit variance as + +.. math:: + \text{{out}}_{{i}} \sim \mathcal{{CN}}(0, 1) + +This is equivalent to separately sampling the real :math:`(\operatorname{{Re}})` and imaginary +:math:`(\operatorname{{Im}})` part of :math:`\text{{out}}_i` as + +.. math:: + \operatorname{{Re}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}),\quad + \operatorname{{Im}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}) + +The shape of the tensor is defined by the variable argument :attr:`size`. + + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + +.. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.randn_like, + r""" +randn_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor with the same size as :attr:`input` that is filled with +random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the +sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to +``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.randperm, + """ +randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, \ +device=None, requires_grad=False, pin_memory=False) -> Tensor +""" + + r""" +Returns a random permutation of integers from ``0`` to ``n - 1``. + +Args: + n (int): the upper bound (exclusive) + +Keyword args: + {generator} + {out} + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.tensor, + r""" +tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + +.. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.clone().detach()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.clone().detach().requires_grad_(True)``. + +.. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + +Args: + {data} + +Keyword args: + {dtype} + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + {requires_grad} + {pin_memory} + + +Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) +""".format( + **factory_data_common_args + ), +) + +add_docstr( + torch.range, + r""" +range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` +with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is +the gap between two values in the tensor. + +.. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. +""" + + r""" +.. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + +Args: + start (float): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float): the gap between each pair of adjacent points. Default: ``1``. + +Keyword args: + {out} + {dtype} If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.arange, + r""" +arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` +with values from the interval ``[start, end)`` taken with common difference +:attr:`step` beginning from `start`. + +Note that non-integer :attr:`step` is subject to floating point rounding errors when +comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` +in such cases. + +.. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} +""" + + r""" +Args: + start (Number): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number): the gap between each pair of adjacent points. Default: ``1``. + +Keyword args: + {out} + {dtype} If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `stop` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.ravel, + r""" +ravel(input) -> Tensor + +Return a contiguous flattened tensor. A copy is made only if needed. + +Args: + {input} + +Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) +""".format( + **common_args + ), +) + +add_docstr( + torch.remainder, + r""" +remainder(input, other, *, out=None) -> Tensor + +Computes +`Python's modulus operation `_ +entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value +is less than that of :attr:`other`. + +It may also be defined in terms of :func:`torch.div` as + +.. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and float inputs. + +.. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + +.. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + +Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + +Keyword args: + {out} + +Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) +""".format( + **common_args + ), +) + +add_docstr( + torch.renorm, + r""" +renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + +Returns a tensor where each sub-tensor of :attr:`input` along dimension +:attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower +than the value :attr:`maxnorm` + +.. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + +Args: + {input} + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + +Keyword args: + {out} + +Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.reshape, + r""" +reshape(input, shape) -> Tensor + +Returns a tensor with the same data and number of elements as :attr:`input`, +but with the specified shape. When possible, the returned tensor will be a view +of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs +with compatible strides can be reshaped without copying, but you should not +depend on the copying vs. viewing behavior. + +See :meth:`torch.Tensor.view` on when it is possible to return a view. + +A single dimension may be -1, in which case it's inferred from the remaining +dimensions and the number of elements in :attr:`input`. + +Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + +Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) +""", +) + + +add_docstr( + torch.result_type, + r""" +result_type(tensor1, tensor2) -> dtype + +Returns the :class:`torch.dtype` that would result from performing an arithmetic +operation on the provided input tensors. See type promotion :ref:`documentation ` +for more information on the type promotion logic. + +Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + +Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 +""", +) + +add_docstr( + torch.row_stack, + r""" +row_stack(tensors, *, out=None) -> Tensor + +Alias of :func:`torch.vstack`. +""", +) + +add_docstr( + torch.round, + r""" +round(input, *, decimals=0, out=None) -> Tensor + +Rounds elements of :attr:`input` to the nearest integer. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. +The return type of output is same as that of input's dtype. + +.. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + +.. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + +Args: + {input} + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + +Keyword args: + {out} + +Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # the nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to the to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.rsqrt, + r""" +rsqrt(input, *, out=None) -> Tensor + +Returns a new tensor with the reciprocal of the square-root of each of +the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) +""".format( + **common_args + ), +) + +add_docstr( + torch.scatter, + r""" +scatter(input, dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_` +""", +) + +add_docstr( + torch.scatter_add, + r""" +scatter_add(input, dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_add_` +""", +) + +add_docstr( + torch.scatter_reduce, + r""" +scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` +""", +) + +add_docstr( + torch.select, + r""" +select(input, dim, index) -> Tensor + +Slices the :attr:`input` tensor along the selected dimension at the given index. +This function returns a view of the original tensor with the given dimension removed. + +.. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + +Args: + {input} + dim (int): the dimension to slice + index (int): the index to select with + +.. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. +""".format( + **common_args + ), +) + +add_docstr( + torch.select_scatter, + r""" +select_scatter(input, src, dim, index) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. +This function returns a tensor with fresh storage; it does not create a view. + + +Args: + {input} + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + +Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.slice_scatter, + r""" +slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` at the given +dimension. +This function returns a tensor with fresh storage; it does not create a view. + + +Args: + {input} + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + +Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.set_flush_denormal, + r""" +set_flush_denormal(mode) -> bool + +Disables denormal floating numbers on CPU. + +Returns ``True`` if your system supports flushing denormal numbers and it +successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` +is supported on x86 architectures supporting SSE3 and AArch64 architecture. + +Args: + mode (bool): Controls whether to enable flush denormal mode or not + +Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) +""", +) + +add_docstr( + torch.set_num_threads, + r""" +set_num_threads(int) + +Sets the number of threads used for intraop parallelism on CPU. + +.. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. +""", +) + +add_docstr( + torch.set_num_interop_threads, + r""" +set_num_interop_threads(int) + +Sets the number of threads used for interop parallelism +(e.g. in JIT interpreter) on CPU. + +.. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). +""", +) + +add_docstr( + torch.sigmoid, + r""" +sigmoid(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.expit`. +""", +) + +add_docstr( + torch.logit, + r""" +logit(input, eps=None, *, out=None) -> Tensor + +Alias for :func:`torch.special.logit`. +""", +) + +add_docstr( + torch.sign, + r""" +sign(input, *, out=None) -> Tensor + +Returns a new tensor with the signs of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.signbit, + r""" +signbit(input, *, out=None) -> Tensor + +Tests if each element of :attr:`input` has its sign bit set or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + +.. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + +""".format( + **common_args + ), +) + +add_docstr( + torch.sgn, + r""" +sgn(input, *, out=None) -> Tensor + +This function is an extension of torch.sign() to complex tensors. +It computes a new tensor whose elements have +the same angles as the corresponding elements of :attr:`input` and +absolute values (i.e. magnitudes) of one for complex tensors and +is equivalent to torch.sign() for non-complex tensors. + +.. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) +""".format( + **common_args + ), +) + +add_docstr( + torch.sin, + r""" +sin(input, *, out=None) -> Tensor + +Returns a new tensor with the sine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sin(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) +""".format( + **common_args + ), +) + +add_docstr( + torch.sinc, + r""" +sinc(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.sinc`. +""", +) + +add_docstr( + torch.sinh, + r""" +sinh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic sine of the elements of +:attr:`input`. + +.. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + +.. note:: + When :attr:`input` is on the CPU, the implementation of torch.sinh may use + the Sleef library, which rounds very large results to infinity or negative + infinity. See `here `_ for details. +""".format( + **common_args + ), +) + +add_docstr( + torch.sort, + r""" +sort(input, dim=-1, descending=False, stable=False, *, out=None) -> (Tensor, LongTensor) + +Sorts the elements of the :attr:`input` tensor along a given dimension +in ascending order by value. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`descending` is ``True`` then the elements are sorted in descending +order by value. + +If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving +the order of equivalent elements. + +A namedtuple of (values, indices) is returned, where the `values` are the +sorted values and `indices` are the indices of the elements in the original +`input` tensor. + +Args: + {input} + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + +Keyword args: + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + +Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) +""".format( + **common_args + ), +) + +add_docstr( + torch.argsort, + r""" +argsort(input, dim=-1, descending=False, stable=False) -> Tensor + +Returns the indices that sort a tensor along a given dimension in ascending +order by value. + +This is the second value returned by :meth:`torch.sort`. See its documentation +for the exact semantics of this method. + +If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving +the order of equivalent elements. If ``False``, the relative order of values +which compare equal is not guaranteed. ``True`` is slower. + +Args: + {input} + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + stable (bool, optional): controls the relative order of equivalent elements + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.msort, + r""" +msort(input, *, out=None) -> Tensor + +Sorts the elements of the :attr:`input` tensor along its first dimension +in ascending order by value. + +.. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.sparse_compressed_tensor, + r"""sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, """ + r"""*, dtype=None, layout=None, device=None, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, +CSC, BSR, or BSC - ` with specified values at +the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse +matrix multiplication operations in Compressed Sparse format are +typically faster than that for sparse tensors in COO format. Make you +have a look at :ref:`the note on the data type of the indices +`. + +{sparse_factory_device_note} + +Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + co-ordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {requires_grad} + {check_invariants} + +Example:: + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.sparse_csr_tensor, + r"""sparse_csr_tensor(crow_indices, col_indices, values, size=None, """ + r"""*, dtype=None, device=None, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified +values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations +in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look +at :ref:`the note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column co-ordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {requires_grad} + {check_invariants} + +Example:: + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.sparse_csc_tensor, + r"""sparse_csc_tensor(ccol_indices, row_indices, values, size=None, """ + r"""*, dtype=None, device=None, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) +` with specified values at the given +:attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix +multiplication operations in CSC format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row co-ordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {requires_grad} + {check_invariants} + +Example:: + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.sparse_bsr_tensor, + r"""sparse_bsr_tensor(crow_indices, col_indices, values, size=None, """ + r"""*, dtype=None, device=None, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) +` with specified 2-dimensional blocks at the given +:attr:`crow_indices` and :attr:`col_indices`. Sparse matrix +multiplication operations in BSR format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block co-ordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {requires_grad} + {check_invariants} + +Example:: + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.sparse_bsc_tensor, + r"""sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, """ + r"""*, dtype=None, device=None, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse +Column)) ` with specified 2-dimensional blocks at the +given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix +multiplication operations in BSC format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block co-ordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {requires_grad} + {check_invariants} + +Example:: + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.sparse_coo_tensor, + r"""sparse_coo_tensor(indices, values, size=None, """ + r"""*, dtype=None, device=None, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + +Constructs a :ref:`sparse tensor in COO(rdinate) format +` with specified values at the given +:attr:`indices`. + +.. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + +{sparse_factory_device_note} + +Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + {requires_grad} + {check_invariants} + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescion please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + +Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + +.. _torch.sparse: https://pytorch.org/docs/stable/sparse.html +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.sqrt, + r""" +sqrt(input, *, out=None) -> Tensor + +Returns a new tensor with the square-root of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) +""".format( + **common_args + ), +) + +add_docstr( + torch.square, + r""" +square(input, *, out=None) -> Tensor + +Returns a new tensor with the square of the elements of :attr:`input`. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) +""".format( + **common_args + ), +) + +add_docstr( + torch.squeeze, + r""" +squeeze(input, dim=None) -> Tensor + +Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + +For example, if `input` is of shape: +:math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` +will be of shape: :math:`(A \times B \times C \times D)`. + +When :attr:`dim` is given, a squeeze operation is done only in the given +dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, +``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` +will squeeze the tensor to the shape :math:`(A \times B)`. + +.. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + +.. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + +Args: + {input} + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + +Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) +""".format( + **common_args + ), +) + +add_docstr( + torch.std, + r""" +std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + +Calculates the standard deviation over the dimensions specified by :attr:`dim`. +:attr:`dim` can be a single dimension, list of dimensions, or ``None`` to +reduce over all dimensions. + +The standard deviation (:math:`\sigma`) is calculated as + +.. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {dim} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {keepdim} + {out} + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]]) + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.std_mean, + r""" +std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + +Calculates the standard deviation and mean over the dimensions specified by +:attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or +``None`` to reduce over all dimensions. + +The standard deviation (:math:`\sigma`) is calculated as + +.. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. + +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {keepdim} + {out} + +Returns: + A tuple (std, mean) containing the standard deviation and mean. + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]]) + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.sub, + r""" +sub(input, other, *, alpha=1, out=None) -> Tensor + +Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + +.. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + +Keyword args: + alpha (Number): the multiplier for :attr:`other`. + {out} + +Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) +""".format( + **common_args + ), +) + +add_docstr( + torch.subtract, + r""" +subtract(input, other, *, alpha=1, out=None) -> Tensor + +Alias for :func:`torch.sub`. +""", +) + +add_docstr( + torch.sum, + r""" +sum(input, *, dtype=None) -> Tensor + +Returns the sum of all elements in the :attr:`input` tensor. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + +.. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the sum of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim} + {keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.nansum, + r""" +nansum(input, *, dtype=None) -> Tensor + +Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + +.. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the sum of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. +If :attr:`dim` is a list of dimensions, reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim} + {keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + 1.0 + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.svd, + r""" +svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + +Computes the singular value decomposition of either a matrix or batch of +matrices :attr:`input`. The singular value decomposition is represented as a +namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. +where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, +and the conjugate transpose of `V` for complex inputs. +If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also +batched with the same batch dimensions as :attr:`input`. + +If :attr:`some` is `True` (default), the method returns the reduced singular +value decomposition. In this case, if the last two dimensions of :attr:`input` are +`m` and `n`, then the returned `U` and `V` matrices will contain only +`min(n, m)` orthonormal columns. + +If :attr:`compute_uv` is `False`, the returned `U` and `V` will be +zero-filled matrices of shape `(m, m)` and `(n, n)` +respectively, and the same device as :attr:`input`. The argument :attr:`some` +has no effect when :attr:`compute_uv` is `False`. + +Supports :attr:`input` of float, double, cfloat and cdouble data types. +The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will +always be real-valued, even if :attr:`input` is complex. + +.. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + +.. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + +.. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + +.. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + +.. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + +.. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched` on CUDA 10.1.243 + and later, and MAGMA's routine `gesdd` on earlier versions of CUDA. + +.. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + +.. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + +.. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + +.. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + +Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + +Keyword args: + out (tuple, optional): the output tuple of tensors + +Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + +.. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) +""", +) + + +add_docstr( + torch.t, + r""" +t(input) -> Tensor + +Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 +and 1. + +0-D and 1-D tensors are returned as is. When input is a 2-D tensor this +is equivalent to ``transpose(input, 0, 1)``. + +Args: + {input} + +Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + +See also :func:`torch.transpose`. +""".format( + **common_args + ), +) + +add_docstr( + torch.flip, + r""" +flip(input, dims) -> Tensor + +Reverse the order of an n-D tensor along given axis in dims. + +.. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + +Args: + {input} + dims (a list or tuple): axis to flip on + +Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.fliplr, + r""" +fliplr(input) -> Tensor + +Flip tensor in the left/right direction, returning a new tensor. + +Flip the entries in each row in the left/right direction. +Columns are preserved, but appear in a different order than before. + +Note: + Requires the tensor to be at least 2-D. + +.. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + +Args: + input (Tensor): Must be at least 2-dimensional. + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.flipud, + r""" +flipud(input) -> Tensor + +Flip tensor in the up/down direction, returning a new tensor. + +Flip the entries in each column in the up/down direction. +Rows are preserved, but appear in a different order than before. + +Note: + Requires the tensor to be at least 1-D. + +.. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + +Args: + input (Tensor): Must be at least 1-dimensional. + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.roll, + r""" +roll(input, shifts, dims=None) -> Tensor + +Roll the tensor :attr:`input` along the given dimension(s). Elements that are +shifted beyond the last position are re-introduced at the first position. If +:attr:`dims` is `None`, the tensor will be flattened before rolling and then +restored to the original shape. + +Args: + {input} + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.rot90, + r""" +rot90(input, k=1, dims=[0,1]) -> Tensor + +Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. +Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + +Args: + {input} + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.take, + r""" +take(input, index) -> Tensor + +Returns a new tensor with the elements of :attr:`input` at the given indices. +The input tensor is treated as if it were viewed as a 1-D tensor. The result +takes the same shape as the indices. + +Args: + {input} + index (LongTensor): the indices into tensor + +Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) +""".format( + **common_args + ), +) + +add_docstr( + torch.take_along_dim, + r""" +take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + +Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + +If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + +Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, +are designed to work with this function. See the examples below. + +.. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + +Args: + {input} + indices (tensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. + +Keyword args: + {out} + +Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.tan, + r""" +tan(input, *, out=None) -> Tensor + +Returns a new tensor with the tangent of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \tan(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) +""".format( + **common_args + ), +) + +add_docstr( + torch.tanh, + r""" +tanh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic tangent of the elements +of :attr:`input`. + +.. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) +""".format( + **common_args + ), +) + +add_docstr( + # torch.softmax doc str. Point this to torch.nn.functional.softmax + torch.softmax, + r""" +softmax(input, dim, *, dtype=None) -> Tensor + +Alias for :func:`torch.nn.functional.softmax`. +""", +) + +add_docstr( + torch.topk, + r""" +topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + +Returns the :attr:`k` largest elements of the given :attr:`input` tensor along +a given dimension. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + +A namedtuple of `(values, indices)` is returned with the `values` and +`indices` of the largest `k` elements of each row of the `input` tensor in the +given dimension `dim`. + +The boolean option :attr:`sorted` if ``True``, will make sure that the returned +`k` elements are themselves sorted + +Args: + {input} + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + +Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) +""".format( + **common_args + ), +) + +add_docstr( + torch.trace, + r""" +trace(input) -> Tensor + +Returns the sum of the elements of the diagonal of the input 2-D matrix. + +Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) +""", +) + +add_docstr( + torch.transpose, + r""" +transpose(input, dim0, dim1) -> Tensor + +Returns a tensor that is a transposed version of :attr:`input`. +The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + +If :attr:`input` is a strided tensor then the resulting :attr:`out` +tensor shares its underlying storage with the :attr:`input` tensor, so +changing the content of one would change the content of the other. + +If :attr:`input` is a :ref:`sparse tensor ` then the +resulting :attr:`out` tensor *does not* share the underlying storage +with the :attr:`input` tensor. + +If :attr:`input` is a :ref:`sparse tensor ` with compressed +layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments +:attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must +both be sparse dimensions. The batch dimensions of a sparse tensor are the +dimensions preceding the sparse dimensions. + +.. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + +Args: + {input} + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + +See also :func:`torch.t`. +""".format( + **common_args + ), +) + +add_docstr( + torch.triangular_solve, + r""" +triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + +Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` +and multiple right-hand sides :math:`b`. + +In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular +(or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + +`torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are +batches of 2D matrices. If the inputs are batches, then returns +batched outputs `X` + +If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and +:attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, +the result may contain `NaN` s. + +Supports input of float, double, cfloat and cdouble data types. + +.. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + +Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + +Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + +Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + +Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) +""", +) + +add_docstr( + torch.tril, + r""" +tril(input, diagonal=0, *, out=None) -> Tensor + +Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices +:attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + +The lower triangular part of the matrix is defined as the elements on and +below the diagonal. + +The argument :attr:`diagonal` controls which diagonal to consider. If +:attr:`diagonal` = 0, all elements on and below the main diagonal are +retained. A positive value includes just as many diagonals above the main +diagonal, and similarly a negative value excludes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where +:math:`d_{1}, d_{2}` are the dimensions of the matrix. +""" + + r""" +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) +""".format( + **common_args + ), +) + +# docstr is split in two parts to avoid format mis-captureing :math: braces '{}' +# as common args. +add_docstr( + torch.tril_indices, + r""" +tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + +Returns the indices of the lower triangular part of a :attr:`row`-by- +:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row +coordinates of all indices and the second row contains column coordinates. +Indices are ordered based on rows and then columns. + +The lower triangular part of the matrix is defined as the elements on and +below the diagonal. + +The argument :attr:`offset` controls which diagonal to consider. If +:attr:`offset` = 0, all elements on and below the main diagonal are +retained. A positive value includes just as many diagonals above the main +diagonal, and similarly a negative value excludes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` +where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + +.. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. +""" + + r""" +Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, ``torch.long``. + {device} + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + +Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.triu, + r""" +triu(input, diagonal=0, *, out=None) -> Tensor + +Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices +:attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + +The upper triangular part of the matrix is defined as the elements on and +above the diagonal. + +The argument :attr:`diagonal` controls which diagonal to consider. If +:attr:`diagonal` = 0, all elements on and above the main diagonal are +retained. A positive value excludes just as many diagonals above the main +diagonal, and similarly a negative value includes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where +:math:`d_{1}, d_{2}` are the dimensions of the matrix. +""" + + r""" +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) +""".format( + **common_args + ), +) + +# docstr is split in two parts to avoid format mis-capturing :math: braces '{}' +# as common args. +add_docstr( + torch.triu_indices, + r""" +triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + +Returns the indices of the upper triangular part of a :attr:`row` by +:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row +coordinates of all indices and the second row contains column coordinates. +Indices are ordered based on rows and then columns. + +The upper triangular part of the matrix is defined as the elements on and +above the diagonal. + +The argument :attr:`offset` controls which diagonal to consider. If +:attr:`offset` = 0, all elements on and above the main diagonal are +retained. A positive value excludes just as many diagonals above the main +diagonal, and similarly a negative value includes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` +where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + +.. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. +""" + + r""" +Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, ``torch.long``. + {device} + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + +Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.true_divide, + r""" +true_divide(dividend, divisor, *, out) -> Tensor + +Alias for :func:`torch.div` with ``rounding_mode=None``. +""", +) + +add_docstr( + torch.trunc, + r""" +trunc(input, *, out=None) -> Tensor + +Returns a new tensor with the truncated integer values of +the elements of :attr:`input`. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) +""".format( + **common_args + ), +) + +add_docstr( + torch.fake_quantize_per_tensor_affine, + r""" +fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + +Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, +:attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + +.. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + +Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + +Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + +Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) +""", +) + +add_docstr( + torch.fake_quantize_per_channel_affine, + r""" +fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + +Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, +:attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + +.. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + +Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + +Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + +Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) +""", +) + +add_docstr( + torch.fix, + r""" +fix(input, *, out=None) -> Tensor + +Alias for :func:`torch.trunc` +""", +) + +add_docstr( + torch.unsqueeze, + r""" +unsqueeze(input, dim) -> Tensor + +Returns a new tensor with a dimension of size one inserted at the +specified position. + +The returned tensor shares the same underlying data with this tensor. + +A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` +can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` +applied at :attr:`dim` = ``dim + input.dim() + 1``. + +Args: + {input} + dim (int): the index at which to insert the singleton dimension + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) +""".format( + **common_args + ), +) + +add_docstr( + torch.var, + r""" +var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + +Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` +can be a single dimension, list of dimensions, or ``None`` to reduce over all +dimensions. + +The variance (:math:`\sigma^2`) is calculated as + +.. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {keepdim} + {out} + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]]) + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.var_mean, + r""" +var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + +Calculates the variance and mean over the dimensions specified by :attr:`dim`. +:attr:`dim` can be a single dimension, list of dimensions, or ``None`` to +reduce over all dimensions. + +The variance (:math:`\sigma^2`) is calculated as + +.. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {keepdim} + {out} + +Returns: + A tuple (var, mean) containing the variance and mean. + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]]) + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format( + **multi_dim_common + ), +) + +add_docstr( + torch.zeros, + r""" +zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with the scalar value `0`, with the shape defined +by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.zeros_like, + r""" +zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor filled with the scalar value `0`, with the same size as +:attr:`input`. ``torch.zeros_like(input)`` is equivalent to +``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.empty, + """ +empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, \ +memory_format=torch.contiguous_format) -> Tensor + +Returns a tensor filled with uninitialized data. The shape of the tensor is +defined by the variable argument :attr:`size`. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + {memory_format} + +Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.empty_like, + r""" +empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns an uninitialized tensor with the same size as :attr:`input`. +``torch.empty_like(input)`` is equivalent to +``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.empty_strided, + r""" +empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + +.. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.empty_permuted, + r""" +empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Creates an uninitialized, non-overlapping and dense tensor with the +specified :attr:`size`, with :attr:`physical_layout` specifying how the +dimensions are physically laid out in memory (each logical dimension is listed +from outermost to innermost). :attr:`physical_layout` is a generalization +of NCHW/NHWC notation: if each dimension is assigned a number according to +what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` +while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output +tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` +(notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + +Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense +tensor with no overlaps. If possible, prefer using this function over +:func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.full, + r""" +full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The +tensor's dtype is inferred from :attr:`fill_value`. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) +""".format( + **factory_common_args + ), +) + +add_docstr( + torch.full_like, + """ +full_like(input, fill_value, \\*, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +memory_format=torch.preserve_format) -> Tensor + +Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. +``torch.full_like(input, fill_value)`` is equivalent to +``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + fill_value: the number to fill the output tensor with. + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} +""".format( + **factory_like_common_args + ), +) + +add_docstr( + torch.det, + r""" +det(input) -> Tensor + +Alias for :func:`torch.linalg.det` +""", +) + +add_docstr( + torch.where, + r""" +where(condition, input, other, *, out=None) -> Tensor + +Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + +The operation is defined as: + +.. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} +""" + + r""" +.. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + +Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + +Keyword args: + {out} + +Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + +Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + +.. function:: where(condition) -> tuple of LongTensor + :noindex: + +``torch.where(condition)`` is identical to +``torch.nonzero(condition, as_tuple=True)``. + +.. note:: + See also :func:`torch.nonzero`. +""".format( + **common_args + ), +) + +add_docstr( + torch.logdet, + r""" +logdet(input) -> Tensor + +Calculates log determinant of a square matrix or batches of square matrices. + +It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has +a negative determinant. + +.. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + +.. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + +Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + +Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) +""", +) + +add_docstr( + torch.slogdet, + r""" +slogdet(input) -> (Tensor, Tensor) + +Alias for :func:`torch.linalg.slogdet` +""", +) + +add_docstr( + torch.pinverse, + r""" +pinverse(input, rcond=1e-15) -> Tensor + +Alias for :func:`torch.linalg.pinv` +""", +) + +add_docstr( + torch.hann_window, + """ +hann_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Hann window function. + +.. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.hann_window(L, periodic=True)`` equal to +``torch.hann_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format( + **factory_common_args + ), +) + + +add_docstr( + torch.hamming_window, + """ +hamming_window(window_length, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Hamming window function. + +.. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.hamming_window(L, periodic=True)`` equal to +``torch.hamming_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + +.. note:: + This is a generalized version of :meth:`torch.hann_window`. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float, optional): The coefficient :math:`\alpha` in the equation above + beta (float, optional): The coefficient :math:`\beta` in the equation above + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +""".format( + **factory_common_args + ), +) + + +add_docstr( + torch.bartlett_window, + """ +bartlett_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Bartlett window function. + +.. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.bartlett_window(L, periodic=True)`` equal to +``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format( + **factory_common_args + ), +) + + +add_docstr( + torch.blackman_window, + """ +blackman_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Blackman window function. + +.. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.blackman_window(L, periodic=True)`` equal to +``torch.blackman_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format( + **factory_common_args + ), +) + + +add_docstr( + torch.kaiser_window, + """ +kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + +Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and +``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, +where ``L`` is the :attr:`window_length`. This function computes: + +.. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + +Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling +``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. +The :attr:`periodic` argument is intended as a helpful shorthand +to produce a periodic window as input to functions like :func:`torch.stft`. + +.. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + +""" + + r""" +Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + +Keyword args: + {dtype} + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +""".format( + **factory_common_args + ), +) + + +add_docstr( + torch.vander, + """ +vander(x, N=None, increasing=False) -> Tensor +""" + + r""" +Generates a Vandermonde matrix. + +The columns of the output matrix are elementwise powers of the input vector :math:`x^{{(N-1)}}, x^{{(N-2)}}, ..., x^0`. +If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{{(N-1)}}`. Such a +matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + +Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + +Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{{(N-1)}}`, + the second :math:`x^{{(N-2)}}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{{(N-1)}}`. + +Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + +""".format( + **factory_common_args + ), +) + + +add_docstr( + torch.unbind, + r""" +unbind(input, dim=0) -> seq + +Removes a tensor dimension. + +Returns a tuple of all slices along a given dimension, already without it. + +Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + +Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) +""", +) + + +add_docstr( + torch.combinations, + r""" +combinations(input, r=2, with_replacement=False) -> seq + +Compute combinations of length :math:`r` of the given tensor. The behavior is similar to +python's `itertools.combinations` when `with_replacement` is set to `False`, and +`itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + +Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + +Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + +Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + +""", +) + +add_docstr( + torch.trapezoid, + r""" +trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + +Computes the `trapezoidal rule `_ along +:attr:`dim`. By default the spacing between elements is assumed to be 1, but +:attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be +used to specify arbitrary spacing along :attr:`dim`. + + +Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, +the default computation is + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n-1} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + +When :attr:`dx` is specified the computation becomes + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n-1} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + +effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, +assuming :attr:`x` is also a one-dimensional tensor with +elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n-1} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + +When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. +The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` +and :attr:`y`, the function computes the difference between consecutive elements along +dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have +the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. +After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. +See the examples below for details. + +.. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + +Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + +Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + +Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) +""", +) + +add_docstr( + torch.trapz, + r""" +trapz(y, x, *, dim=-1) -> Tensor + +Alias for :func:`torch.trapezoid`. +""", +) + +add_docstr( + torch.cumulative_trapezoid, + r""" +cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + +Cumulatively computes the `trapezoidal rule `_ +along :attr:`dim`. By default the spacing between elements is assumed to be 1, but +:attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be +used to specify arbitrary spacing along :attr:`dim`. + +For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` +and this function is that, :func:`torch.trapezoid` returns a value for each integration, +where as this function returns a cumulative value for every spacing within the integration. This +is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + +Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + +Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + +Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) +""", +) + +add_docstr( + torch.repeat_interleave, + r""" +repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + +Repeat elements of a tensor. + +.. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + +Args: + {input} + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + +Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + +Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + +If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be +`tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, +`1` appears `n2` times, `2` appears `n3` times, etc. + +.. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + +Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + +Args: + repeats (Tensor): The number of repetitions for each element. + +Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + +Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + +""".format( + **common_args + ), +) + +add_docstr( + torch.tile, + r""" +tile(input, dims) -> Tensor + +Constructs a tensor by repeating the elements of :attr:`input`. +The :attr:`dims` argument specifies the number of repetitions +in each dimension. + +If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then +ones are prepended to :attr:`dims` until all dimensions are specified. +For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` +is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + +Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` +specifies, then :attr:`input` is treated as if it were unsqueezed at +dimension zero until it has as many dimensions as :attr:`dims` specifies. +For example, if :attr:`input` has shape (4, 2) and :attr:`dims` +is (3, 3, 2, 2), then :attr:`input` is treated as if it had the +shape (1, 1, 4, 2). + +.. note:: + + This function is similar to NumPy's tile function. + +Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) +""", +) + +add_docstr( + torch.quantize_per_tensor, + r""" +quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + +Converts a float tensor to a quantized tensor with given scale and zero point. + +Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + +Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + +Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) +""", +) + +add_docstr( + torch.quantize_per_tensor_dynamic, + r""" +quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + +Converts a float tensor to a quantized tensor with scale and zero_point calculated +dynamically based on the input. + +Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + +Returns: + Tensor: A newly (dynamically) quantized tensor + +Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) +""", +) + +add_docstr( + torch.quantize_per_channel, + r""" +quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + +Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + +Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + +Returns: + Tensor: A newly quantized tensor + +Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) +""", +) + + +add_docstr( + torch.quantized_batch_norm, + r""" +quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + +Applies batch normalization on a 4D (NCHW) quantized tensor. + +.. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + +Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + +Returns: + Tensor: A quantized tensor with batch normalization applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) +""", +) + + +add_docstr( + torch.quantized_max_pool1d, + r""" +quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + +Applies a 1D max pooling over an input quantized tensor composed of several input planes. + +Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + +Returns: + Tensor: A quantized tensor with max_pool1d applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) +""", +) + + +add_docstr( + torch.quantized_max_pool2d, + r""" +quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + +Applies a 2D max pooling over an input quantized tensor composed of several input planes. + +Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + +Returns: + Tensor: A quantized tensor with max_pool2d applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) +""", +) + + +add_docstr( + torch.Generator, + r""" +Generator(device='cpu') -> Generator + +Creates and returns a generator object that manages the state of the algorithm which +produces pseudo random numbers. Used as a keyword argument in many :ref:`inplace-random-sampling` +functions. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the generator. + +Returns: + Generator: An torch.Generator object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> g_cpu = torch.Generator() + >>> g_cuda = torch.Generator(device='cuda') +""", +) + + +add_docstr( + torch.Generator.set_state, + r""" +Generator.set_state(new_state) -> void + +Sets the Generator state. + +Arguments: + new_state (torch.ByteTensor): The desired state. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu_other = torch.Generator() + >>> g_cpu.set_state(g_cpu_other.get_state()) +""", +) + + +add_docstr( + torch.Generator.get_state, + r""" +Generator.get_state() -> Tensor + +Returns the Generator state as a ``torch.ByteTensor``. + +Returns: + Tensor: A ``torch.ByteTensor`` which contains all the necessary bits + to restore a Generator to a specific point in time. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.get_state() +""", +) + + +add_docstr( + torch.Generator.manual_seed, + r""" +Generator.manual_seed(seed) -> Generator + +Sets the seed for generating random numbers. Returns a `torch.Generator` object. Any 32-bit integer is a valid seed. + +Arguments: + seed (int): The desired seed. Value must be within the inclusive range + `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError + is raised. Negative inputs are remapped to positive values with the formula + `0xffff_ffff_ffff_ffff + seed`. + +Returns: + Generator: An torch.Generator object. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.manual_seed(2147483647) +""", +) + + +add_docstr( + torch.Generator.initial_seed, + r""" +Generator.initial_seed() -> int + +Returns the initial seed for generating random numbers. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.initial_seed() + 2147483647 +""", +) + + +add_docstr( + torch.Generator.seed, + r""" +Generator.seed() -> int + +Gets a non-deterministic random number from std::random_device or the current +time and uses it to seed a Generator. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.seed() + 1516516984916 +""", +) + + +add_docstr( + torch.Generator.device, + r""" +Generator.device -> device + +Gets the current device of the generator. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.device + device(type='cpu') +""", +) + +add_docstr( + torch._assert_async, + r""" +_assert_async(tensor) -> void + +Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, +this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for +CUDA tensors, we DO NOT synchronize and you may only find out the assertion +failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for +testing invariants in CUDA tensors without giving up performance. This function +is NOT intended to be used for regular error checking, as it will trash your CUDA +context if the assert fails (forcing you to restart your PyTorch process.) + +Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. +""", +) + +add_docstr( + torch.searchsorted, + r""" +searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + +Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the +corresponding values in :attr:`values` were inserted before the indices, when sorted, the order +of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. +Return a new tensor with the same size as :attr:`values`. More formally, +the returned index satisfies the following rules: + +.. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + +Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + +Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + +Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) +""", +) + +add_docstr( + torch.bucketize, + r""" +bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + +Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the +boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size +as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that +this behavior is opposite the behavior of +`numpy.digitize `_. +More formally, the returned index satisfies the following rules: + +.. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + +Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + +Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of :attr:`boundaries` (one pass the last index). + In other words, if False, gets the lower bound index for each value in :attr:`input` + from :attr:`boundaries`. If True, gets the upper bound index instead. + Default value is False. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + +Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) +""", +) + +add_docstr( + torch.view_as_real_copy, + r""" +Performs the same operation as :func:`torch.view_as_real`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.view_as_complex_copy, + r""" +Performs the same operation as :func:`torch.view_as_complex`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.as_strided_copy, + r""" +Performs the same operation as :func:`torch.as_strided`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.diagonal_copy, + r""" +Performs the same operation as :func:`torch.diagonal`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.expand_copy, + r""" +Performs the same operation as :func:`torch.expand`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.permute_copy, + r""" +Performs the same operation as :func:`torch.permute`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.select_copy, + r""" +Performs the same operation as :func:`torch.select`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.detach_copy, + r""" +Performs the same operation as :func:`torch.detach`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.slice_copy, + r""" +Performs the same operation as :func:`torch.slice`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.split_copy, + r""" +Performs the same operation as :func:`torch.split`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.split_with_sizes_copy, + r""" +Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.squeeze_copy, + r""" +Performs the same operation as :func:`torch.squeeze`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.t_copy, + r""" +Performs the same operation as :func:`torch.t`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.transpose_copy, + r""" +Performs the same operation as :func:`torch.transpose`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unsqueeze_copy, + r""" +Performs the same operation as :func:`torch.unsqueeze`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.indices_copy, + r""" +Performs the same operation as :func:`torch.indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.values_copy, + r""" +Performs the same operation as :func:`torch.values`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.crow_indices_copy, + r""" +Performs the same operation as :func:`torch.crow_indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.col_indices_copy, + r""" +Performs the same operation as :func:`torch.col_indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unbind_copy, + r""" +Performs the same operation as :func:`torch.unbind`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.view_copy, + r""" +Performs the same operation as :func:`torch.view`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unfold_copy, + r""" +Performs the same operation as :func:`torch.unfold`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.alias_copy, + r""" +Performs the same operation as :func:`torch.alias`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +for unary_base_func_name in ( + "exp", + "sqrt", + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "cosh", + "erf", + "erfc", + "expm1", + "floor", + "log", + "log10", + "log1p", + "log2", + "neg", + "tan", + "tanh", + "sin", + "sinh", + "round", + "lgamma", + "frac", + "reciprocal", + "sigmoid", + "trunc", + "zero", +): + unary_foreach_func_name = f"_foreach_{unary_base_func_name}" + if hasattr(torch, unary_foreach_func_name): + add_docstr( + getattr(torch, unary_foreach_func_name), + rf""" +{unary_foreach_func_name}(self: List[Tensor]) -> List[Tensor] + +Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list. + """, + ) + unary_inplace_foreach_func_name = f"{unary_foreach_func_name}_" + if hasattr(torch, unary_inplace_foreach_func_name): + add_docstr( + getattr(torch, unary_inplace_foreach_func_name), + rf""" +{unary_inplace_foreach_func_name}(self: List[Tensor]) -> None + +Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list. + """, + ) diff --git a/shared/package-files/78/785daf3b82e9386a0fbc828a91b3df9f2badf214f852279b64fa5bf8160641d2/blob b/shared/package-files/78/785daf3b82e9386a0fbc828a91b3df9f2badf214f852279b64fa5bf8160641d2/blob new file mode 100644 index 0000000000000000000000000000000000000000..7b6f6a324bad46c7d78fe6ab4ad9630ba674f0a6 --- /dev/null +++ b/shared/package-files/78/785daf3b82e9386a0fbc828a91b3df9f2badf214f852279b64fa5bf8160641d2/blob @@ -0,0 +1,43 @@ +""" + pygments.modeline + ~~~~~~~~~~~~~~~~~ + + A simple modeline parser (based on pymodeline). + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +__all__ = ['get_filetype_from_buffer'] + + +modeline_re = re.compile(r''' + (?: vi | vim | ex ) (?: [<=>]? \d* )? : + .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ ) +''', re.VERBOSE) + + +def get_filetype_from_line(l): + m = modeline_re.search(l) + if m: + return m.group(1) + + +def get_filetype_from_buffer(buf, max_lines=5): + """ + Scan the buffer for modelines and return filetype if one is found. + """ + lines = buf.splitlines() + for l in lines[-1:-max_lines-1:-1]: + ret = get_filetype_from_line(l) + if ret: + return ret + for i in range(max_lines, -1, -1): + if i < len(lines): + ret = get_filetype_from_line(lines[i]) + if ret: + return ret + + return None diff --git a/shared/package-files/78/7861ba2c19d57005e5b4bde56832c9b8c9d0377e207c8fc66c6cda45788f15b7/blob b/shared/package-files/78/7861ba2c19d57005e5b4bde56832c9b8c9d0377e207c8fc66c6cda45788f15b7/blob new file mode 100644 index 0000000000000000000000000000000000000000..2737b88e31856d3a88b7a31b2aa585fe52acb683 --- /dev/null +++ b/shared/package-files/78/7861ba2c19d57005e5b4bde56832c9b8c9d0377e207c8fc66c6cda45788f15b7/blob @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +from numba import int32, int64, uint32, uint64, float32, float64 +from numba.core.types import range_iter32_type +from numba.core import itanium_mangler +import unittest + + +class TestItaniumManager(unittest.TestCase): + def test_ident(self): + got = itanium_mangler.mangle_identifier("apple") + expect = "5apple" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_identifier("ap_ple") + expect = "6ap_ple" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_identifier("apple213") + expect = "8apple213" + self.assertEqual(expect, got) + + def test_types(self): + got = itanium_mangler.mangle_type(int32) + expect = "i" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_type(int64) + expect = "x" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_type(uint32) + expect = "j" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_type(uint64) + expect = "y" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_type(float32) + expect = "f" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle_type(float64) + expect = "d" + self.assertEqual(expect, got) + + def test_function(self): + got = itanium_mangler.mangle("what", [int32, float32]) + expect = "_Z4whatif" + self.assertEqual(expect, got) + + got = itanium_mangler.mangle("a_little_brown_fox", [uint64, + uint32, + float64]) + expect = "_Z18a_little_brown_foxyjd" + self.assertEqual(expect, got) + + def test_custom_type(self): + got = itanium_mangler.mangle_type(range_iter32_type) + name = str(range_iter32_type) + expect = "{n}{name}".format(n=len(name), name=name) + self.assertEqual(expect, got) + + def test_mangle_literal(self): + # check int + got = itanium_mangler.mangle_value(123) + expect = "Li123E" + self.assertEqual(expect, got) + # check float (not handled using standard) + got = itanium_mangler.mangle_value(12.3) + self.assertRegex(got, r'^\d+_12_[0-9a-z][0-9a-z]3$') + + def test_mangle_unicode(self): + name = u'f∂ƒ©z' + got = itanium_mangler.mangle_identifier(name) + self.assertRegex(got, r'^\d+f(_[a-z0-9][a-z0-9])+z$') + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/78/7862b15049922f1a4d1a88fd60f4030d7ebc1744a4556866d244d4b9e0aaf6d2/blob b/shared/package-files/78/7862b15049922f1a4d1a88fd60f4030d7ebc1744a4556866d244d4b9e0aaf6d2/blob new file mode 100644 index 0000000000000000000000000000000000000000..56c610162ebea055077206070277df4cf3776d14 Binary files /dev/null and b/shared/package-files/78/7862b15049922f1a4d1a88fd60f4030d7ebc1744a4556866d244d4b9e0aaf6d2/blob differ diff --git a/shared/package-files/78/78650bbd1c31e179a3be10e0e0d6fe910d655a9fccefbad9a6668e06d4081038/blob b/shared/package-files/78/78650bbd1c31e179a3be10e0e0d6fe910d655a9fccefbad9a6668e06d4081038/blob new file mode 100644 index 0000000000000000000000000000000000000000..676350260552923493d08640f16d5d5559784eb1 --- /dev/null +++ b/shared/package-files/78/78650bbd1c31e179a3be10e0e0d6fe910d655a9fccefbad9a6668e06d4081038/blob @@ -0,0 +1,40 @@ +import operator +import sys +PY3 = sys.version_info[0] > 2 +PY33 = sys.version_info[0] == 3 and sys.version_info[1] == 3 +PY34 = sys.version_info[0] == 3 and sys.version_info[1] == 4 +PYPY = hasattr(sys, 'pypy_version_info') + +__all__ = ('map', 'filter', 'range', 'zip', 'reduce', 'zip_longest', + 'iteritems', 'iterkeys', 'itervalues', 'filterfalse', + 'PY3', 'PY34', 'PYPY', 'import_module') + +if PY3: + map = map + filter = filter + range = range + zip = zip + from functools import reduce + from itertools import zip_longest + from itertools import filterfalse + iteritems = operator.methodcaller('items') + iterkeys = operator.methodcaller('keys') + itervalues = operator.methodcaller('values') +else: + range = xrange + reduce = reduce + from itertools import imap as map + from itertools import ifilter as filter + from itertools import ifilterfalse as filterfalse + from itertools import izip as zip + from itertools import izip_longest as zip_longest + iteritems = operator.methodcaller('iteritems') + iterkeys = operator.methodcaller('iterkeys') + itervalues = operator.methodcaller('itervalues') + +try: + from importlib import import_module +except ImportError: + def import_module(name): + __import__(name) + return sys.modules[name] diff --git a/shared/package-files/78/786724a988d97f9e1b0b800ed426a26d9e57d116cf75c80458a14fd0db2360b7/_massformer_graph_featurizer.py b/shared/package-files/78/786724a988d97f9e1b0b800ed426a26d9e57d116cf75c80458a14fd0db2360b7/_massformer_graph_featurizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eff8a11e06778be1d75979c9686530de8c830eee --- /dev/null +++ b/shared/package-files/78/786724a988d97f9e1b0b800ed426a26d9e57d116cf75c80458a14fd0db2360b7/_massformer_graph_featurizer.py @@ -0,0 +1,25 @@ +from rdkit import Chem + +from .massformer_code import gf_data_utils + + +class MassformerGraphFeaturizer: + """ + Thin wrapper over Massformer code to match the API we were using for graph featurizer. + Note that Massformer makes use of Pytorch Geometric Graph datastructures. + """ + + def __call__(self, input_molecule: Chem.Mol): + out = gf_data_utils.gf_preprocess(input_molecule, 0, "algos2") + # ^ we'll just set everything as index 0 for now. we can give it consecutive indices in the collate + # although not sure how improtant this is anyhow. + return out + + @classmethod + def collate_func(cls, list_of_items): + # we'll give each graph consecutive indices. In the original Massformer code they used the spctra + # ID given that we don't have that I'll just use consecutive indices. + for i, el in enumerate(list_of_items): + el.idx = i + out = gf_data_utils.collator(list_of_items) + return out diff --git a/shared/package-files/78/7868c6961eace03b9b85fae4f8aa7ddf562047c2b268735cc5b4d6d6baada9b2/blob b/shared/package-files/78/7868c6961eace03b9b85fae4f8aa7ddf562047c2b268735cc5b4d6d6baada9b2/blob new file mode 100644 index 0000000000000000000000000000000000000000..141d558c3a8cfa85bde0d353e3b63e92a830a6c9 --- /dev/null +++ b/shared/package-files/78/7868c6961eace03b9b85fae4f8aa7ddf562047c2b268735cc5b4d6d6baada9b2/blob @@ -0,0 +1,466 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/bitmap_ops.h" +#include "arrow/util/bitmap_reader.h" +#include "arrow/util/bitmap_writer.h" +#include "arrow/util/compare.h" +#include "arrow/util/endian.h" +#include "arrow/util/functional.h" +#include "arrow/util/span.h" +#include "arrow/util/string_util.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class BooleanArray; + +namespace internal { + +class ARROW_EXPORT Bitmap : public util::ToStringOstreamable, + public util::EqualityComparable { + public: + Bitmap() = default; + + Bitmap(const std::shared_ptr& buffer, int64_t offset, int64_t length) + : data_(buffer->data()), offset_(offset), length_(length) { + if (buffer->is_mutable()) { + mutable_data_ = buffer->mutable_data(); + } + } + + Bitmap(const void* data, int64_t offset, int64_t length) + : data_(reinterpret_cast(data)), offset_(offset), length_(length) {} + + Bitmap(void* data, int64_t offset, int64_t length) + : data_(reinterpret_cast(data)), + mutable_data_(reinterpret_cast(data)), + offset_(offset), + length_(length) {} + + Bitmap Slice(int64_t offset) const { + if (mutable_data_ != NULLPTR) { + return {mutable_data_, offset_ + offset, length_ - offset}; + } else { + return {data_, offset_ + offset, length_ - offset}; + } + } + + Bitmap Slice(int64_t offset, int64_t length) const { + if (mutable_data_ != NULLPTR) { + return {mutable_data_, offset_ + offset, length}; + } else { + return {data_, offset_ + offset, length}; + } + } + + std::string ToString() const; + + bool Equals(const Bitmap& other) const; + + std::string Diff(const Bitmap& other) const; + + bool GetBit(int64_t i) const { return bit_util::GetBit(data_, i + offset_); } + + bool operator[](int64_t i) const { return GetBit(i); } + + void SetBitTo(int64_t i, bool v) const { + bit_util::SetBitTo(mutable_data_, i + offset_, v); + } + + void SetBitsTo(bool v) { bit_util::SetBitsTo(mutable_data_, offset_, length_, v); } + + void CopyFrom(const Bitmap& other); + void CopyFromInverted(const Bitmap& other); + + /// \brief Visit bits from each bitmap as bitset + /// + /// All bitmaps must have identical length. + template + static void VisitBits(const Bitmap (&bitmaps)[N], Visitor&& visitor) { + int64_t bit_length = BitLength(bitmaps, N); + std::bitset bits; + for (int64_t bit_i = 0; bit_i < bit_length; ++bit_i) { + for (size_t i = 0; i < N; ++i) { + bits[i] = bitmaps[i].GetBit(bit_i); + } + visitor(bits); + } + } + + /// \brief Visit bits from each bitmap as bitset + /// + /// All bitmaps must have identical length. + template + static void VisitBits(const std::array& bitmaps, Visitor&& visitor) { + int64_t bit_length = BitLength(bitmaps); + std::bitset bits; + for (int64_t bit_i = 0; bit_i < bit_length; ++bit_i) { + for (size_t i = 0; i < N; ++i) { + bits[i] = bitmaps[i].GetBit(bit_i); + } + visitor(bits); + } + } + + /// \brief Visit words of bits from each bitmap as array + /// + /// All bitmaps must have identical length. The first bit in a visited bitmap + /// may be offset within the first visited word, but words will otherwise contain + /// densely packed bits loaded from the bitmap. That offset within the first word is + /// returned. + /// + /// TODO(bkietz) allow for early termination + // NOTE: this function is efficient on 3+ sufficiently large bitmaps. + // It also has a large prolog / epilog overhead and should be used + // carefully in other cases. + // For 2 bitmaps or less, and/or smaller bitmaps, see also VisitTwoBitBlocksVoid + // and BitmapUInt64Reader. + template >::type::value_type> + static int64_t VisitWords(const Bitmap (&bitmaps_arg)[N], Visitor&& visitor) { + constexpr int64_t kBitWidth = sizeof(Word) * 8; + + // local, mutable variables which will be sliced/decremented to represent consumption: + Bitmap bitmaps[N]; + int64_t offsets[N]; + int64_t bit_length = BitLength(bitmaps_arg, N); + util::span words[N]; + for (size_t i = 0; i < N; ++i) { + bitmaps[i] = bitmaps_arg[i]; + offsets[i] = bitmaps[i].template word_offset(); + assert(offsets[i] >= 0 && offsets[i] < kBitWidth); + words[i] = bitmaps[i].template words(); + } + + auto consume = [&](int64_t consumed_bits) { + for (size_t i = 0; i < N; ++i) { + bitmaps[i] = bitmaps[i].Slice(consumed_bits, bit_length - consumed_bits); + offsets[i] = bitmaps[i].template word_offset(); + assert(offsets[i] >= 0 && offsets[i] < kBitWidth); + words[i] = bitmaps[i].template words(); + } + bit_length -= consumed_bits; + }; + + std::array visited_words; + visited_words.fill(0); + + if (bit_length <= kBitWidth * 2) { + // bitmaps fit into one or two words so don't bother with optimization + while (bit_length > 0) { + auto leading_bits = std::min(bit_length, kBitWidth); + SafeLoadWords(bitmaps, 0, leading_bits, false, &visited_words); + visitor(visited_words); + consume(leading_bits); + } + return 0; + } + + int64_t max_offset = *std::max_element(offsets, offsets + N); + int64_t min_offset = *std::min_element(offsets, offsets + N); + if (max_offset > 0) { + // consume leading bits + auto leading_bits = kBitWidth - min_offset; + SafeLoadWords(bitmaps, 0, leading_bits, true, &visited_words); + visitor(visited_words); + consume(leading_bits); + } + assert(*std::min_element(offsets, offsets + N) == 0); + + int64_t whole_word_count = bit_length / kBitWidth; + assert(whole_word_count >= 1); + + if (min_offset == max_offset) { + // all offsets were identical, all leading bits have been consumed + assert( + std::all_of(offsets, offsets + N, [](int64_t offset) { return offset == 0; })); + + for (int64_t word_i = 0; word_i < whole_word_count; ++word_i) { + for (size_t i = 0; i < N; ++i) { + visited_words[i] = words[i][word_i]; + } + visitor(visited_words); + } + consume(whole_word_count * kBitWidth); + } else { + // leading bits from potentially incomplete words have been consumed + + // word_i such that words[i][word_i] and words[i][word_i + 1] are lie entirely + // within the bitmap for all i + for (int64_t word_i = 0; word_i < whole_word_count - 1; ++word_i) { + for (size_t i = 0; i < N; ++i) { + if (offsets[i] == 0) { + visited_words[i] = words[i][word_i]; + } else { + auto words0 = bit_util::ToLittleEndian(words[i][word_i]); + auto words1 = bit_util::ToLittleEndian(words[i][word_i + 1]); + visited_words[i] = bit_util::FromLittleEndian( + (words0 >> offsets[i]) | (words1 << (kBitWidth - offsets[i]))); + } + } + visitor(visited_words); + } + consume((whole_word_count - 1) * kBitWidth); + + SafeLoadWords(bitmaps, 0, kBitWidth, false, &visited_words); + + visitor(visited_words); + consume(kBitWidth); + } + + // load remaining bits + if (bit_length > 0) { + SafeLoadWords(bitmaps, 0, bit_length, false, &visited_words); + visitor(visited_words); + } + + return min_offset; + } + + template >::type::value_type> + static void RunVisitWordsAndWriteLoop(int64_t bit_length, + std::array& readers, + std::array& writers, + Visitor&& visitor) { + constexpr int64_t kBitWidth = sizeof(Word) * 8; + + std::array visited_words; + std::array output_words; + + // every reader will have same number of words, since they are same length'ed + // TODO($JIRA) this will be inefficient in some cases. When there are offsets beyond + // Word boundary, every Word would have to be created from 2 adjoining Words + auto n_words = readers[0].words(); + bit_length -= n_words * kBitWidth; + while (n_words--) { + // first collect all words to visited_words array + for (size_t i = 0; i < N; i++) { + visited_words[i] = readers[i].NextWord(); + } + visitor(visited_words, &output_words); + for (size_t i = 0; i < M; i++) { + writers[i].PutNextWord(output_words[i]); + } + } + + // every reader will have same number of trailing bytes, because of the above reason + // tailing portion could be more than one word! (ref: BitmapWordReader constructor) + // remaining full/ partial words to write + + if (bit_length) { + // convert the word visitor lambda to a byte_visitor + auto byte_visitor = [&](const std::array& in, + std::array* out) { + std::array in_words; + std::array out_words; + std::copy(in.begin(), in.end(), in_words.begin()); + visitor(in_words, &out_words); + for (size_t i = 0; i < M; i++) { + out->at(i) = static_cast(out_words[i]); + } + }; + + std::array visited_bytes; + std::array output_bytes; + int n_bytes = readers[0].trailing_bytes(); + while (n_bytes--) { + visited_bytes.fill(0); + output_bytes.fill(0); + int valid_bits; + for (size_t i = 0; i < N; i++) { + visited_bytes[i] = readers[i].NextTrailingByte(valid_bits); + } + byte_visitor(visited_bytes, &output_bytes); + for (size_t i = 0; i < M; i++) { + writers[i].PutNextTrailingByte(output_bytes[i], valid_bits); + } + } + } + } + + /// \brief Visit words of bits from each input bitmap as array and collects + /// outputs to an array, to be written into the output bitmaps accordingly. + /// + /// All bitmaps must have identical length. The first bit in a visited bitmap + /// may be offset within the first visited word, but words will otherwise contain + /// densely packed bits loaded from the bitmap. That offset within the first word is + /// returned. + /// Visitor is expected to have the following signature + /// [](const std::array& in_words, std::array* out_words){...} + /// + // NOTE: this function is efficient on 3+ sufficiently large bitmaps. + // It also has a large prolog / epilog overhead and should be used + // carefully in other cases. + // For 2 bitmaps or less, and/or smaller bitmaps, see also VisitTwoBitBlocksVoid + // and BitmapUInt64Reader. + template >::type::value_type> + static void VisitWordsAndWrite(const std::array& bitmaps_arg, + std::array* out_bitmaps_arg, + Visitor&& visitor) { + int64_t bit_length = BitLength(bitmaps_arg); + assert(bit_length == BitLength(*out_bitmaps_arg)); + + // if both input and output bitmaps have no byte offset, then use special template + if (std::all_of(bitmaps_arg.begin(), bitmaps_arg.end(), + [](const Bitmap& b) { return b.offset_ % 8 == 0; }) && + std::all_of(out_bitmaps_arg->begin(), out_bitmaps_arg->end(), + [](const Bitmap& b) { return b.offset_ % 8 == 0; })) { + std::array, N> readers; + for (size_t i = 0; i < N; ++i) { + const Bitmap& in_bitmap = bitmaps_arg[i]; + readers[i] = BitmapWordReader( + in_bitmap.data_, in_bitmap.offset_, in_bitmap.length_); + } + + std::array, M> writers; + for (size_t i = 0; i < M; ++i) { + const Bitmap& out_bitmap = out_bitmaps_arg->at(i); + writers[i] = BitmapWordWriter( + out_bitmap.mutable_data_, out_bitmap.offset_, out_bitmap.length_); + } + + RunVisitWordsAndWriteLoop(bit_length, readers, writers, visitor); + } else { + std::array, N> readers; + for (size_t i = 0; i < N; ++i) { + const Bitmap& in_bitmap = bitmaps_arg[i]; + readers[i] = + BitmapWordReader(in_bitmap.data_, in_bitmap.offset_, in_bitmap.length_); + } + + std::array, M> writers; + for (size_t i = 0; i < M; ++i) { + const Bitmap& out_bitmap = out_bitmaps_arg->at(i); + writers[i] = BitmapWordWriter(out_bitmap.mutable_data_, out_bitmap.offset_, + out_bitmap.length_); + } + + RunVisitWordsAndWriteLoop(bit_length, readers, writers, visitor); + } + } + + const uint8_t* data() const { return data_; } + uint8_t* mutable_data() { return mutable_data_; } + + /// offset of first bit relative to buffer().data() + int64_t offset() const { return offset_; } + + /// number of bits in this Bitmap + int64_t length() const { return length_; } + + /// span of all bytes which contain any bit in this Bitmap + util::span bytes() const { + auto byte_offset = offset_ / 8; + auto byte_count = bit_util::CeilDiv(offset_ + length_, 8) - byte_offset; + return {data_ + byte_offset, static_cast(byte_count)}; + } + + private: + /// span of all Words which contain any bit in this Bitmap + /// + /// For example, given Word=uint16_t and a bitmap spanning bits [20, 36) + /// words() would span bits [16, 48). + /// + /// 0 16 32 48 64 + /// |-------|-------|------|------| (buffer) + /// [ ] (bitmap) + /// |-------|------| (returned words) + /// + /// \warning The words may contain bytes which lie outside the buffer or are + /// uninitialized. + template + util::span words() const { + auto bytes_addr = reinterpret_cast(bytes().data()); + auto words_addr = bytes_addr - bytes_addr % sizeof(Word); + auto word_byte_count = + bit_util::RoundUpToPowerOf2(static_cast(bytes_addr + bytes().size()), + static_cast(sizeof(Word))) - + words_addr; + return {reinterpret_cast(words_addr), + static_cast(word_byte_count / sizeof(Word))}; + } + + /// offset of first bit relative to words().data() + template + int64_t word_offset() const { + return offset_ + 8 * (reinterpret_cast(data_) - + reinterpret_cast(words().data())); + } + + /// load words from bitmaps bitwise + template + static void SafeLoadWords(const Bitmap (&bitmaps)[N], int64_t offset, + int64_t out_length, bool set_trailing_bits, + std::array* out) { + out->fill(0); + + int64_t out_offset = set_trailing_bits ? sizeof(Word) * 8 - out_length : 0; + + Bitmap slices[N], out_bitmaps[N]; + for (size_t i = 0; i < N; ++i) { + slices[i] = bitmaps[i].Slice(offset, out_length); + out_bitmaps[i] = Bitmap(&out->at(i), out_offset, out_length); + } + + int64_t bit_i = 0; + Bitmap::VisitBits(slices, [&](std::bitset bits) { + for (size_t i = 0; i < N; ++i) { + out_bitmaps[i].SetBitTo(bit_i, bits[i]); + } + ++bit_i; + }); + } + + /// assert bitmaps have identical length and return that length + static int64_t BitLength(const Bitmap* bitmaps, size_t N); + + template + static int64_t BitLength(const std::array& bitmaps) { + for (size_t i = 1; i < N; ++i) { + assert(bitmaps[i].length() == bitmaps[0].length()); + } + return bitmaps[0].length(); + } + + const uint8_t* data_ = NULLPTR; + uint8_t* mutable_data_ = NULLPTR; + int64_t offset_ = 0, length_ = 0; +}; + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/78/7868f0b3f21270719534601ee94de4d20efb67f97627e2c8c1233ef4265e5227/blob b/shared/package-files/78/7868f0b3f21270719534601ee94de4d20efb67f97627e2c8c1233ef4265e5227/blob new file mode 100644 index 0000000000000000000000000000000000000000..756f1bc38c97fdb5d0d1124512960d9d0e38198a --- /dev/null +++ b/shared/package-files/78/7868f0b3f21270719534601ee94de4d20efb67f97627e2c8c1233ef4265e5227/blob @@ -0,0 +1,2287 @@ +# Copyright 2007 Google Inc. +# Licensed to PSF under a Contributor Agreement. + +"""A fast, lightweight IPv4/IPv6 manipulation library in Python. + +This library is used to create/poke/manipulate IPv4 and IPv6 addresses +and networks. + +""" + +__version__ = '1.0' + + +import functools + +IPV4LENGTH = 32 +IPV6LENGTH = 128 + + +class AddressValueError(ValueError): + """A Value Error related to the address.""" + + +class NetmaskValueError(ValueError): + """A Value Error related to the netmask.""" + + +def ip_address(address): + """Take an IP string/int and return an object of the correct type. + + Args: + address: A string or integer, the IP address. Either IPv4 or + IPv6 addresses may be supplied; integers less than 2**32 will + be considered to be IPv4 by default. + + Returns: + An IPv4Address or IPv6Address object. + + Raises: + ValueError: if the *address* passed isn't either a v4 or a v6 + address + + """ + try: + return IPv4Address(address) + except (AddressValueError, NetmaskValueError): + pass + + try: + return IPv6Address(address) + except (AddressValueError, NetmaskValueError): + pass + + raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 address') + + +def ip_network(address, strict=True): + """Take an IP string/int and return an object of the correct type. + + Args: + address: A string or integer, the IP network. Either IPv4 or + IPv6 networks may be supplied; integers less than 2**32 will + be considered to be IPv4 by default. + + Returns: + An IPv4Network or IPv6Network object. + + Raises: + ValueError: if the string passed isn't either a v4 or a v6 + address. Or if the network has host bits set. + + """ + try: + return IPv4Network(address, strict) + except (AddressValueError, NetmaskValueError): + pass + + try: + return IPv6Network(address, strict) + except (AddressValueError, NetmaskValueError): + pass + + raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 network') + + +def ip_interface(address): + """Take an IP string/int and return an object of the correct type. + + Args: + address: A string or integer, the IP address. Either IPv4 or + IPv6 addresses may be supplied; integers less than 2**32 will + be considered to be IPv4 by default. + + Returns: + An IPv4Interface or IPv6Interface object. + + Raises: + ValueError: if the string passed isn't either a v4 or a v6 + address. + + Notes: + The IPv?Interface classes describe an Address on a particular + Network, so they're basically a combination of both the Address + and Network classes. + + """ + try: + return IPv4Interface(address) + except (AddressValueError, NetmaskValueError): + pass + + try: + return IPv6Interface(address) + except (AddressValueError, NetmaskValueError): + pass + + raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 interface') + + +def v4_int_to_packed(address): + """Represent an address as 4 packed bytes in network (big-endian) order. + + Args: + address: An integer representation of an IPv4 IP address. + + Returns: + The integer address packed as 4 bytes in network (big-endian) order. + + Raises: + ValueError: If the integer is negative or too large to be an + IPv4 IP address. + + """ + try: + return address.to_bytes(4, 'big') + except OverflowError: + raise ValueError("Address negative or too large for IPv4") + + +def v6_int_to_packed(address): + """Represent an address as 16 packed bytes in network (big-endian) order. + + Args: + address: An integer representation of an IPv6 IP address. + + Returns: + The integer address packed as 16 bytes in network (big-endian) order. + + """ + try: + return address.to_bytes(16, 'big') + except OverflowError: + raise ValueError("Address negative or too large for IPv6") + + +def _split_optional_netmask(address): + """Helper to split the netmask and raise AddressValueError if needed""" + addr = str(address).split('/') + if len(addr) > 2: + raise AddressValueError(f"Only one '/' permitted in {address!r}") + return addr + + +def _find_address_range(addresses): + """Find a sequence of sorted deduplicated IPv#Address. + + Args: + addresses: a list of IPv#Address objects. + + Yields: + A tuple containing the first and last IP addresses in the sequence. + + """ + it = iter(addresses) + first = last = next(it) + for ip in it: + if ip._ip != last._ip + 1: + yield first, last + first = ip + last = ip + yield first, last + + +def _count_righthand_zero_bits(number, bits): + """Count the number of zero bits on the right hand side. + + Args: + number: an integer. + bits: maximum number of bits to count. + + Returns: + The number of zero bits on the right hand side of the number. + + """ + if number == 0: + return bits + return min(bits, (~number & (number-1)).bit_length()) + + +def summarize_address_range(first, last): + """Summarize a network range given the first and last IP addresses. + + Example: + >>> list(summarize_address_range(IPv4Address('192.0.2.0'), + ... IPv4Address('192.0.2.130'))) + ... #doctest: +NORMALIZE_WHITESPACE + [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), + IPv4Network('192.0.2.130/32')] + + Args: + first: the first IPv4Address or IPv6Address in the range. + last: the last IPv4Address or IPv6Address in the range. + + Returns: + An iterator of the summarized IPv(4|6) network objects. + + Raise: + TypeError: + If the first and last objects are not IP addresses. + If the first and last objects are not the same version. + ValueError: + If the last object is not greater than the first. + If the version of the first address is not 4 or 6. + + """ + if (not (isinstance(first, _BaseAddress) and + isinstance(last, _BaseAddress))): + raise TypeError('first and last must be IP addresses, not networks') + if first.version != last.version: + raise TypeError("%s and %s are not of the same version" % ( + first, last)) + if first > last: + raise ValueError('last IP address must be greater than first') + + if first.version == 4: + ip = IPv4Network + elif first.version == 6: + ip = IPv6Network + else: + raise ValueError('unknown IP version') + + ip_bits = first._max_prefixlen + first_int = first._ip + last_int = last._ip + while first_int <= last_int: + nbits = min(_count_righthand_zero_bits(first_int, ip_bits), + (last_int - first_int + 1).bit_length() - 1) + net = ip((first_int, ip_bits - nbits)) + yield net + first_int += 1 << nbits + if first_int - 1 == ip._ALL_ONES: + break + + +def _collapse_addresses_internal(addresses): + """Loops through the addresses, collapsing concurrent netblocks. + + Example: + + ip1 = IPv4Network('192.0.2.0/26') + ip2 = IPv4Network('192.0.2.64/26') + ip3 = IPv4Network('192.0.2.128/26') + ip4 = IPv4Network('192.0.2.192/26') + + _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> + [IPv4Network('192.0.2.0/24')] + + This shouldn't be called directly; it is called via + collapse_addresses([]). + + Args: + addresses: A list of IPv4Network's or IPv6Network's + + Returns: + A list of IPv4Network's or IPv6Network's depending on what we were + passed. + + """ + # First merge + to_merge = list(addresses) + subnets = {} + while to_merge: + net = to_merge.pop() + supernet = net.supernet() + existing = subnets.get(supernet) + if existing is None: + subnets[supernet] = net + elif existing != net: + # Merge consecutive subnets + del subnets[supernet] + to_merge.append(supernet) + # Then iterate over resulting networks, skipping subsumed subnets + last = None + for net in sorted(subnets.values()): + if last is not None: + # Since they are sorted, last.network_address <= net.network_address + # is a given. + if last.broadcast_address >= net.broadcast_address: + continue + yield net + last = net + + +def collapse_addresses(addresses): + """Collapse a list of IP objects. + + Example: + collapse_addresses([IPv4Network('192.0.2.0/25'), + IPv4Network('192.0.2.128/25')]) -> + [IPv4Network('192.0.2.0/24')] + + Args: + addresses: An iterator of IPv4Network or IPv6Network objects. + + Returns: + An iterator of the collapsed IPv(4|6)Network objects. + + Raises: + TypeError: If passed a list of mixed version objects. + + """ + addrs = [] + ips = [] + nets = [] + + # split IP addresses and networks + for ip in addresses: + if isinstance(ip, _BaseAddress): + if ips and ips[-1]._version != ip._version: + raise TypeError("%s and %s are not of the same version" % ( + ip, ips[-1])) + ips.append(ip) + elif ip._prefixlen == ip._max_prefixlen: + if ips and ips[-1]._version != ip._version: + raise TypeError("%s and %s are not of the same version" % ( + ip, ips[-1])) + try: + ips.append(ip.ip) + except AttributeError: + ips.append(ip.network_address) + else: + if nets and nets[-1]._version != ip._version: + raise TypeError("%s and %s are not of the same version" % ( + ip, nets[-1])) + nets.append(ip) + + # sort and dedup + ips = sorted(set(ips)) + + # find consecutive address ranges in the sorted sequence and summarize them + if ips: + for first, last in _find_address_range(ips): + addrs.extend(summarize_address_range(first, last)) + + return _collapse_addresses_internal(addrs + nets) + + +def get_mixed_type_key(obj): + """Return a key suitable for sorting between networks and addresses. + + Address and Network objects are not sortable by default; they're + fundamentally different so the expression + + IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') + + doesn't make any sense. There are some times however, where you may wish + to have ipaddress sort these for you anyway. If you need to do this, you + can use this function as the key= argument to sorted(). + + Args: + obj: either a Network or Address object. + Returns: + appropriate key. + + """ + if isinstance(obj, _BaseNetwork): + return obj._get_networks_key() + elif isinstance(obj, _BaseAddress): + return obj._get_address_key() + return NotImplemented + + +class _IPAddressBase: + + """The mother class.""" + + __slots__ = () + + @property + def exploded(self): + """Return the longhand version of the IP address as a string.""" + return self._explode_shorthand_ip_string() + + @property + def compressed(self): + """Return the shorthand version of the IP address as a string.""" + return str(self) + + @property + def reverse_pointer(self): + """The name of the reverse DNS pointer for the IP address, e.g.: + >>> ipaddress.ip_address("127.0.0.1").reverse_pointer + '1.0.0.127.in-addr.arpa' + >>> ipaddress.ip_address("2001:db8::1").reverse_pointer + '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' + + """ + return self._reverse_pointer() + + @property + def version(self): + msg = '%200s has no version specified' % (type(self),) + raise NotImplementedError(msg) + + def _check_int_address(self, address): + if address < 0: + msg = "%d (< 0) is not permitted as an IPv%d address" + raise AddressValueError(msg % (address, self._version)) + if address > self._ALL_ONES: + msg = "%d (>= 2**%d) is not permitted as an IPv%d address" + raise AddressValueError(msg % (address, self._max_prefixlen, + self._version)) + + def _check_packed_address(self, address, expected_len): + address_len = len(address) + if address_len != expected_len: + msg = "%r (len %d != %d) is not permitted as an IPv%d address" + raise AddressValueError(msg % (address, address_len, + expected_len, self._version)) + + @classmethod + def _ip_int_from_prefix(cls, prefixlen): + """Turn the prefix length into a bitwise netmask + + Args: + prefixlen: An integer, the prefix length. + + Returns: + An integer. + + """ + return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen) + + @classmethod + def _prefix_from_ip_int(cls, ip_int): + """Return prefix length from the bitwise netmask. + + Args: + ip_int: An integer, the netmask in expanded bitwise format + + Returns: + An integer, the prefix length. + + Raises: + ValueError: If the input intermingles zeroes & ones + """ + trailing_zeroes = _count_righthand_zero_bits(ip_int, + cls._max_prefixlen) + prefixlen = cls._max_prefixlen - trailing_zeroes + leading_ones = ip_int >> trailing_zeroes + all_ones = (1 << prefixlen) - 1 + if leading_ones != all_ones: + byteslen = cls._max_prefixlen // 8 + details = ip_int.to_bytes(byteslen, 'big') + msg = 'Netmask pattern %r mixes zeroes & ones' + raise ValueError(msg % details) + return prefixlen + + @classmethod + def _report_invalid_netmask(cls, netmask_str): + msg = '%r is not a valid netmask' % netmask_str + raise NetmaskValueError(msg) from None + + @classmethod + def _prefix_from_prefix_string(cls, prefixlen_str): + """Return prefix length from a numeric string + + Args: + prefixlen_str: The string to be converted + + Returns: + An integer, the prefix length. + + Raises: + NetmaskValueError: If the input is not a valid netmask + """ + # int allows a leading +/- as well as surrounding whitespace, + # so we ensure that isn't the case + if not (prefixlen_str.isascii() and prefixlen_str.isdigit()): + cls._report_invalid_netmask(prefixlen_str) + try: + prefixlen = int(prefixlen_str) + except ValueError: + cls._report_invalid_netmask(prefixlen_str) + if not (0 <= prefixlen <= cls._max_prefixlen): + cls._report_invalid_netmask(prefixlen_str) + return prefixlen + + @classmethod + def _prefix_from_ip_string(cls, ip_str): + """Turn a netmask/hostmask string into a prefix length + + Args: + ip_str: The netmask/hostmask to be converted + + Returns: + An integer, the prefix length. + + Raises: + NetmaskValueError: If the input is not a valid netmask/hostmask + """ + # Parse the netmask/hostmask like an IP address. + try: + ip_int = cls._ip_int_from_string(ip_str) + except AddressValueError: + cls._report_invalid_netmask(ip_str) + + # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). + # Note that the two ambiguous cases (all-ones and all-zeroes) are + # treated as netmasks. + try: + return cls._prefix_from_ip_int(ip_int) + except ValueError: + pass + + # Invert the bits, and try matching a /0+1+/ hostmask instead. + ip_int ^= cls._ALL_ONES + try: + return cls._prefix_from_ip_int(ip_int) + except ValueError: + cls._report_invalid_netmask(ip_str) + + @classmethod + def _split_addr_prefix(cls, address): + """Helper function to parse address of Network/Interface. + + Arg: + address: Argument of Network/Interface. + + Returns: + (addr, prefix) tuple. + """ + # a packed address or integer + if isinstance(address, (bytes, int)): + return address, cls._max_prefixlen + + if not isinstance(address, tuple): + # Assume input argument to be string or any object representation + # which converts into a formatted IP prefix string. + address = _split_optional_netmask(address) + + # Constructing from a tuple (addr, [mask]) + if len(address) > 1: + return address + return address[0], cls._max_prefixlen + + def __reduce__(self): + return self.__class__, (str(self),) + + +_address_fmt_re = None + +@functools.total_ordering +class _BaseAddress(_IPAddressBase): + + """A generic IP object. + + This IP class contains the version independent methods which are + used by single IP addresses. + """ + + __slots__ = () + + def __int__(self): + return self._ip + + def __eq__(self, other): + try: + return (self._ip == other._ip + and self._version == other._version) + except AttributeError: + return NotImplemented + + def __lt__(self, other): + if not isinstance(other, _BaseAddress): + return NotImplemented + if self._version != other._version: + raise TypeError('%s and %s are not of the same version' % ( + self, other)) + if self._ip != other._ip: + return self._ip < other._ip + return False + + # Shorthand for Integer addition and subtraction. This is not + # meant to ever support addition/subtraction of addresses. + def __add__(self, other): + if not isinstance(other, int): + return NotImplemented + return self.__class__(int(self) + other) + + def __sub__(self, other): + if not isinstance(other, int): + return NotImplemented + return self.__class__(int(self) - other) + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, str(self)) + + def __str__(self): + return str(self._string_from_ip_int(self._ip)) + + def __hash__(self): + return hash(hex(int(self._ip))) + + def _get_address_key(self): + return (self._version, self) + + def __reduce__(self): + return self.__class__, (self._ip,) + + def __format__(self, fmt): + """Returns an IP address as a formatted string. + + Supported presentation types are: + 's': returns the IP address as a string (default) + 'b': converts to binary and returns a zero-padded string + 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string + 'n': the same as 'b' for IPv4 and 'x' for IPv6 + + For binary and hex presentation types, the alternate form specifier + '#' and the grouping option '_' are supported. + """ + + # Support string formatting + if not fmt or fmt[-1] == 's': + return format(str(self), fmt) + + # From here on down, support for 'bnXx' + global _address_fmt_re + if _address_fmt_re is None: + import re + _address_fmt_re = re.compile('(#?)(_?)([xbnX])') + + m = _address_fmt_re.fullmatch(fmt) + if not m: + return super().__format__(fmt) + + alternate, grouping, fmt_base = m.groups() + + # Set some defaults + if fmt_base == 'n': + if self._version == 4: + fmt_base = 'b' # Binary is default for ipv4 + else: + fmt_base = 'x' # Hex is default for ipv6 + + if fmt_base == 'b': + padlen = self._max_prefixlen + else: + padlen = self._max_prefixlen // 4 + + if grouping: + padlen += padlen // 4 - 1 + + if alternate: + padlen += 2 # 0b or 0x + + return format(int(self), f'{alternate}0{padlen}{grouping}{fmt_base}') + + +@functools.total_ordering +class _BaseNetwork(_IPAddressBase): + """A generic IP network object. + + This IP class contains the version independent methods which are + used by networks. + """ + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, str(self)) + + def __str__(self): + return '%s/%d' % (self.network_address, self.prefixlen) + + def hosts(self): + """Generate Iterator over usable hosts in a network. + + This is like __iter__ except it doesn't return the network + or broadcast addresses. + + """ + network = int(self.network_address) + broadcast = int(self.broadcast_address) + for x in range(network + 1, broadcast): + yield self._address_class(x) + + def __iter__(self): + network = int(self.network_address) + broadcast = int(self.broadcast_address) + for x in range(network, broadcast + 1): + yield self._address_class(x) + + def __getitem__(self, n): + network = int(self.network_address) + broadcast = int(self.broadcast_address) + if n >= 0: + if network + n > broadcast: + raise IndexError('address out of range') + return self._address_class(network + n) + else: + n += 1 + if broadcast + n < network: + raise IndexError('address out of range') + return self._address_class(broadcast + n) + + def __lt__(self, other): + if not isinstance(other, _BaseNetwork): + return NotImplemented + if self._version != other._version: + raise TypeError('%s and %s are not of the same version' % ( + self, other)) + if self.network_address != other.network_address: + return self.network_address < other.network_address + if self.netmask != other.netmask: + return self.netmask < other.netmask + return False + + def __eq__(self, other): + try: + return (self._version == other._version and + self.network_address == other.network_address and + int(self.netmask) == int(other.netmask)) + except AttributeError: + return NotImplemented + + def __hash__(self): + return hash(int(self.network_address) ^ int(self.netmask)) + + def __contains__(self, other): + # always false if one is v4 and the other is v6. + if self._version != other._version: + return False + # dealing with another network. + if isinstance(other, _BaseNetwork): + return False + # dealing with another address + else: + # address + return other._ip & self.netmask._ip == self.network_address._ip + + def overlaps(self, other): + """Tell if self is partly contained in other.""" + return self.network_address in other or ( + self.broadcast_address in other or ( + other.network_address in self or ( + other.broadcast_address in self))) + + @functools.cached_property + def broadcast_address(self): + return self._address_class(int(self.network_address) | + int(self.hostmask)) + + @functools.cached_property + def hostmask(self): + return self._address_class(int(self.netmask) ^ self._ALL_ONES) + + @property + def with_prefixlen(self): + return '%s/%d' % (self.network_address, self._prefixlen) + + @property + def with_netmask(self): + return '%s/%s' % (self.network_address, self.netmask) + + @property + def with_hostmask(self): + return '%s/%s' % (self.network_address, self.hostmask) + + @property + def num_addresses(self): + """Number of hosts in the current subnet.""" + return int(self.broadcast_address) - int(self.network_address) + 1 + + @property + def _address_class(self): + # Returning bare address objects (rather than interfaces) allows for + # more consistent behaviour across the network address, broadcast + # address and individual host addresses. + msg = '%200s has no associated address class' % (type(self),) + raise NotImplementedError(msg) + + @property + def prefixlen(self): + return self._prefixlen + + def address_exclude(self, other): + """Remove an address from a larger block. + + For example: + + addr1 = ip_network('192.0.2.0/28') + addr2 = ip_network('192.0.2.1/32') + list(addr1.address_exclude(addr2)) = + [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), + IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] + + or IPv6: + + addr1 = ip_network('2001:db8::1/32') + addr2 = ip_network('2001:db8::1/128') + list(addr1.address_exclude(addr2)) = + [ip_network('2001:db8::1/128'), + ip_network('2001:db8::2/127'), + ip_network('2001:db8::4/126'), + ip_network('2001:db8::8/125'), + ... + ip_network('2001:db8:8000::/33')] + + Args: + other: An IPv4Network or IPv6Network object of the same type. + + Returns: + An iterator of the IPv(4|6)Network objects which is self + minus other. + + Raises: + TypeError: If self and other are of differing address + versions, or if other is not a network object. + ValueError: If other is not completely contained by self. + + """ + if not self._version == other._version: + raise TypeError("%s and %s are not of the same version" % ( + self, other)) + + if not isinstance(other, _BaseNetwork): + raise TypeError("%s is not a network object" % other) + + if not other.subnet_of(self): + raise ValueError('%s not contained in %s' % (other, self)) + if other == self: + return + + # Make sure we're comparing the network of other. + other = other.__class__('%s/%s' % (other.network_address, + other.prefixlen)) + + s1, s2 = self.subnets() + while s1 != other and s2 != other: + if other.subnet_of(s1): + yield s2 + s1, s2 = s1.subnets() + elif other.subnet_of(s2): + yield s1 + s1, s2 = s2.subnets() + else: + # If we got here, there's a bug somewhere. + raise AssertionError('Error performing exclusion: ' + 's1: %s s2: %s other: %s' % + (s1, s2, other)) + if s1 == other: + yield s2 + elif s2 == other: + yield s1 + else: + # If we got here, there's a bug somewhere. + raise AssertionError('Error performing exclusion: ' + 's1: %s s2: %s other: %s' % + (s1, s2, other)) + + def compare_networks(self, other): + """Compare two IP objects. + + This is only concerned about the comparison of the integer + representation of the network addresses. This means that the + host bits aren't considered at all in this method. If you want + to compare host bits, you can easily enough do a + 'HostA._ip < HostB._ip' + + Args: + other: An IP object. + + Returns: + If the IP versions of self and other are the same, returns: + + -1 if self < other: + eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') + IPv6Network('2001:db8::1000/124') < + IPv6Network('2001:db8::2000/124') + 0 if self == other + eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') + IPv6Network('2001:db8::1000/124') == + IPv6Network('2001:db8::1000/124') + 1 if self > other + eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') + IPv6Network('2001:db8::2000/124') > + IPv6Network('2001:db8::1000/124') + + Raises: + TypeError if the IP versions are different. + + """ + # does this need to raise a ValueError? + if self._version != other._version: + raise TypeError('%s and %s are not of the same type' % ( + self, other)) + # self._version == other._version below here: + if self.network_address < other.network_address: + return -1 + if self.network_address > other.network_address: + return 1 + # self.network_address == other.network_address below here: + if self.netmask < other.netmask: + return -1 + if self.netmask > other.netmask: + return 1 + return 0 + + def _get_networks_key(self): + """Network-only key function. + + Returns an object that identifies this address' network and + netmask. This function is a suitable "key" argument for sorted() + and list.sort(). + + """ + return (self._version, self.network_address, self.netmask) + + def subnets(self, prefixlen_diff=1, new_prefix=None): + """The subnets which join to make the current subnet. + + In the case that self contains only one IP + (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 + for IPv6), yield an iterator with just ourself. + + Args: + prefixlen_diff: An integer, the amount the prefix length + should be increased by. This should not be set if + new_prefix is also set. + new_prefix: The desired new prefix length. This must be a + larger number (smaller prefix) than the existing prefix. + This should not be set if prefixlen_diff is also set. + + Returns: + An iterator of IPv(4|6) objects. + + Raises: + ValueError: The prefixlen_diff is too small or too large. + OR + prefixlen_diff and new_prefix are both set or new_prefix + is a smaller number than the current prefix (smaller + number means a larger network) + + """ + if self._prefixlen == self._max_prefixlen: + yield self + return + + if new_prefix is not None: + if new_prefix < self._prefixlen: + raise ValueError('new prefix must be longer') + if prefixlen_diff != 1: + raise ValueError('cannot set prefixlen_diff and new_prefix') + prefixlen_diff = new_prefix - self._prefixlen + + if prefixlen_diff < 0: + raise ValueError('prefix length diff must be > 0') + new_prefixlen = self._prefixlen + prefixlen_diff + + if new_prefixlen > self._max_prefixlen: + raise ValueError( + 'prefix length diff %d is invalid for netblock %s' % ( + new_prefixlen, self)) + + start = int(self.network_address) + end = int(self.broadcast_address) + 1 + step = (int(self.hostmask) + 1) >> prefixlen_diff + for new_addr in range(start, end, step): + current = self.__class__((new_addr, new_prefixlen)) + yield current + + def supernet(self, prefixlen_diff=1, new_prefix=None): + """The supernet containing the current network. + + Args: + prefixlen_diff: An integer, the amount the prefix length of + the network should be decreased by. For example, given a + /24 network and a prefixlen_diff of 3, a supernet with a + /21 netmask is returned. + + Returns: + An IPv4 network object. + + Raises: + ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have + a negative prefix length. + OR + If prefixlen_diff and new_prefix are both set or new_prefix is a + larger number than the current prefix (larger number means a + smaller network) + + """ + if self._prefixlen == 0: + return self + + if new_prefix is not None: + if new_prefix > self._prefixlen: + raise ValueError('new prefix must be shorter') + if prefixlen_diff != 1: + raise ValueError('cannot set prefixlen_diff and new_prefix') + prefixlen_diff = self._prefixlen - new_prefix + + new_prefixlen = self.prefixlen - prefixlen_diff + if new_prefixlen < 0: + raise ValueError( + 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % + (self.prefixlen, prefixlen_diff)) + return self.__class__(( + int(self.network_address) & (int(self.netmask) << prefixlen_diff), + new_prefixlen + )) + + @property + def is_multicast(self): + """Test if the address is reserved for multicast use. + + Returns: + A boolean, True if the address is a multicast address. + See RFC 2373 2.7 for details. + + """ + return (self.network_address.is_multicast and + self.broadcast_address.is_multicast) + + @staticmethod + def _is_subnet_of(a, b): + try: + # Always false if one is v4 and the other is v6. + if a._version != b._version: + raise TypeError(f"{a} and {b} are not of the same version") + return (b.network_address <= a.network_address and + b.broadcast_address >= a.broadcast_address) + except AttributeError: + raise TypeError(f"Unable to test subnet containment " + f"between {a} and {b}") + + def subnet_of(self, other): + """Return True if this network is a subnet of other.""" + return self._is_subnet_of(self, other) + + def supernet_of(self, other): + """Return True if this network is a supernet of other.""" + return self._is_subnet_of(other, self) + + @property + def is_reserved(self): + """Test if the address is otherwise IETF reserved. + + Returns: + A boolean, True if the address is within one of the + reserved IPv6 Network ranges. + + """ + return (self.network_address.is_reserved and + self.broadcast_address.is_reserved) + + @property + def is_link_local(self): + """Test if the address is reserved for link-local. + + Returns: + A boolean, True if the address is reserved per RFC 4291. + + """ + return (self.network_address.is_link_local and + self.broadcast_address.is_link_local) + + @property + def is_private(self): + """Test if this address is allocated for private networks. + + Returns: + A boolean, True if the address is reserved per + iana-ipv4-special-registry or iana-ipv6-special-registry. + + """ + return (self.network_address.is_private and + self.broadcast_address.is_private) + + @property + def is_global(self): + """Test if this address is allocated for public networks. + + Returns: + A boolean, True if the address is not reserved per + iana-ipv4-special-registry or iana-ipv6-special-registry. + + """ + return not self.is_private + + @property + def is_unspecified(self): + """Test if the address is unspecified. + + Returns: + A boolean, True if this is the unspecified address as defined in + RFC 2373 2.5.2. + + """ + return (self.network_address.is_unspecified and + self.broadcast_address.is_unspecified) + + @property + def is_loopback(self): + """Test if the address is a loopback address. + + Returns: + A boolean, True if the address is a loopback address as defined in + RFC 2373 2.5.3. + + """ + return (self.network_address.is_loopback and + self.broadcast_address.is_loopback) + +class _BaseV4: + + """Base IPv4 object. + + The following methods are used by IPv4 objects in both single IP + addresses and networks. + + """ + + __slots__ = () + _version = 4 + # Equivalent to 255.255.255.255 or 32 bits of 1's. + _ALL_ONES = (2**IPV4LENGTH) - 1 + + _max_prefixlen = IPV4LENGTH + # There are only a handful of valid v4 netmasks, so we cache them all + # when constructed (see _make_netmask()). + _netmask_cache = {} + + def _explode_shorthand_ip_string(self): + return str(self) + + @classmethod + def _make_netmask(cls, arg): + """Make a (netmask, prefix_len) tuple from the given argument. + + Argument can be: + - an integer (the prefix length) + - a string representing the prefix length (e.g. "24") + - a string representing the prefix netmask (e.g. "255.255.255.0") + """ + if arg not in cls._netmask_cache: + if isinstance(arg, int): + prefixlen = arg + if not (0 <= prefixlen <= cls._max_prefixlen): + cls._report_invalid_netmask(prefixlen) + else: + try: + # Check for a netmask in prefix length form + prefixlen = cls._prefix_from_prefix_string(arg) + except NetmaskValueError: + # Check for a netmask or hostmask in dotted-quad form. + # This may raise NetmaskValueError. + prefixlen = cls._prefix_from_ip_string(arg) + netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen)) + cls._netmask_cache[arg] = netmask, prefixlen + return cls._netmask_cache[arg] + + @classmethod + def _ip_int_from_string(cls, ip_str): + """Turn the given IP string into an integer for comparison. + + Args: + ip_str: A string, the IP ip_str. + + Returns: + The IP ip_str as an integer. + + Raises: + AddressValueError: if ip_str isn't a valid IPv4 Address. + + """ + if not ip_str: + raise AddressValueError('Address cannot be empty') + + octets = ip_str.split('.') + if len(octets) != 4: + raise AddressValueError("Expected 4 octets in %r" % ip_str) + + try: + return int.from_bytes(map(cls._parse_octet, octets), 'big') + except ValueError as exc: + raise AddressValueError("%s in %r" % (exc, ip_str)) from None + + @classmethod + def _parse_octet(cls, octet_str): + """Convert a decimal octet into an integer. + + Args: + octet_str: A string, the number to parse. + + Returns: + The octet as an integer. + + Raises: + ValueError: if the octet isn't strictly a decimal from [0..255]. + + """ + if not octet_str: + raise ValueError("Empty octet not permitted") + # Reject non-ASCII digits. + if not (octet_str.isascii() and octet_str.isdigit()): + msg = "Only decimal digits permitted in %r" + raise ValueError(msg % octet_str) + # We do the length check second, since the invalid character error + # is likely to be more informative for the user + if len(octet_str) > 3: + msg = "At most 3 characters permitted in %r" + raise ValueError(msg % octet_str) + # Handle leading zeros as strict as glibc's inet_pton() + # See security bug bpo-36384 + if octet_str != '0' and octet_str[0] == '0': + msg = "Leading zeros are not permitted in %r" + raise ValueError(msg % octet_str) + # Convert to integer (we know digits are legal) + octet_int = int(octet_str, 10) + if octet_int > 255: + raise ValueError("Octet %d (> 255) not permitted" % octet_int) + return octet_int + + @classmethod + def _string_from_ip_int(cls, ip_int): + """Turns a 32-bit integer into dotted decimal notation. + + Args: + ip_int: An integer, the IP address. + + Returns: + The IP address as a string in dotted decimal notation. + + """ + return '.'.join(map(str, ip_int.to_bytes(4, 'big'))) + + def _reverse_pointer(self): + """Return the reverse DNS pointer name for the IPv4 address. + + This implements the method described in RFC1035 3.5. + + """ + reverse_octets = str(self).split('.')[::-1] + return '.'.join(reverse_octets) + '.in-addr.arpa' + + @property + def max_prefixlen(self): + return self._max_prefixlen + + @property + def version(self): + return self._version + + +class IPv4Address(_BaseV4, _BaseAddress): + + """Represent and manipulate single IPv4 Addresses.""" + + __slots__ = ('_ip', '__weakref__') + + def __init__(self, address): + + """ + Args: + address: A string or integer representing the IP + + Additionally, an integer can be passed, so + IPv4Address('192.0.2.1') == IPv4Address(3221225985). + or, more generally + IPv4Address(int(IPv4Address('192.0.2.1'))) == + IPv4Address('192.0.2.1') + + Raises: + AddressValueError: If ipaddress isn't a valid IPv4 address. + + """ + # Efficient constructor from integer. + if isinstance(address, int): + self._check_int_address(address) + self._ip = address + return + + # Constructing from a packed address + if isinstance(address, bytes): + self._check_packed_address(address, 4) + self._ip = int.from_bytes(address, 'big') + return + + # Assume input argument to be string or any object representation + # which converts into a formatted IP string. + addr_str = str(address) + if '/' in addr_str: + raise AddressValueError(f"Unexpected '/' in {address!r}") + self._ip = self._ip_int_from_string(addr_str) + + @property + def packed(self): + """The binary representation of this address.""" + return v4_int_to_packed(self._ip) + + @property + def is_reserved(self): + """Test if the address is otherwise IETF reserved. + + Returns: + A boolean, True if the address is within the + reserved IPv4 Network range. + + """ + return self in self._constants._reserved_network + + @property + @functools.lru_cache() + def is_private(self): + """Test if this address is allocated for private networks. + + Returns: + A boolean, True if the address is reserved per + iana-ipv4-special-registry. + + """ + return any(self in net for net in self._constants._private_networks) + + @property + @functools.lru_cache() + def is_global(self): + return self not in self._constants._public_network and not self.is_private + + @property + def is_multicast(self): + """Test if the address is reserved for multicast use. + + Returns: + A boolean, True if the address is multicast. + See RFC 3171 for details. + + """ + return self in self._constants._multicast_network + + @property + def is_unspecified(self): + """Test if the address is unspecified. + + Returns: + A boolean, True if this is the unspecified address as defined in + RFC 5735 3. + + """ + return self == self._constants._unspecified_address + + @property + def is_loopback(self): + """Test if the address is a loopback address. + + Returns: + A boolean, True if the address is a loopback per RFC 3330. + + """ + return self in self._constants._loopback_network + + @property + def is_link_local(self): + """Test if the address is reserved for link-local. + + Returns: + A boolean, True if the address is link-local per RFC 3927. + + """ + return self in self._constants._linklocal_network + + +class IPv4Interface(IPv4Address): + + def __init__(self, address): + addr, mask = self._split_addr_prefix(address) + + IPv4Address.__init__(self, addr) + self.network = IPv4Network((addr, mask), strict=False) + self.netmask = self.network.netmask + self._prefixlen = self.network._prefixlen + + @functools.cached_property + def hostmask(self): + return self.network.hostmask + + def __str__(self): + return '%s/%d' % (self._string_from_ip_int(self._ip), + self._prefixlen) + + def __eq__(self, other): + address_equal = IPv4Address.__eq__(self, other) + if address_equal is NotImplemented or not address_equal: + return address_equal + try: + return self.network == other.network + except AttributeError: + # An interface with an associated network is NOT the + # same as an unassociated address. That's why the hash + # takes the extra info into account. + return False + + def __lt__(self, other): + address_less = IPv4Address.__lt__(self, other) + if address_less is NotImplemented: + return NotImplemented + try: + return (self.network < other.network or + self.network == other.network and address_less) + except AttributeError: + # We *do* allow addresses and interfaces to be sorted. The + # unassociated address is considered less than all interfaces. + return False + + def __hash__(self): + return hash((self._ip, self._prefixlen, int(self.network.network_address))) + + __reduce__ = _IPAddressBase.__reduce__ + + @property + def ip(self): + return IPv4Address(self._ip) + + @property + def with_prefixlen(self): + return '%s/%s' % (self._string_from_ip_int(self._ip), + self._prefixlen) + + @property + def with_netmask(self): + return '%s/%s' % (self._string_from_ip_int(self._ip), + self.netmask) + + @property + def with_hostmask(self): + return '%s/%s' % (self._string_from_ip_int(self._ip), + self.hostmask) + + +class IPv4Network(_BaseV4, _BaseNetwork): + + """This class represents and manipulates 32-bit IPv4 network + addresses.. + + Attributes: [examples for IPv4Network('192.0.2.0/27')] + .network_address: IPv4Address('192.0.2.0') + .hostmask: IPv4Address('0.0.0.31') + .broadcast_address: IPv4Address('192.0.2.32') + .netmask: IPv4Address('255.255.255.224') + .prefixlen: 27 + + """ + # Class to use when creating address objects + _address_class = IPv4Address + + def __init__(self, address, strict=True): + """Instantiate a new IPv4 network object. + + Args: + address: A string or integer representing the IP [& network]. + '192.0.2.0/24' + '192.0.2.0/255.255.255.0' + '192.0.2.0/0.0.0.255' + are all functionally the same in IPv4. Similarly, + '192.0.2.1' + '192.0.2.1/255.255.255.255' + '192.0.2.1/32' + are also functionally equivalent. That is to say, failing to + provide a subnetmask will create an object with a mask of /32. + + If the mask (portion after the / in the argument) is given in + dotted quad form, it is treated as a netmask if it starts with a + non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it + starts with a zero field (e.g. 0.255.255.255 == /8), with the + single exception of an all-zero mask which is treated as a + netmask == /0. If no mask is given, a default of /32 is used. + + Additionally, an integer can be passed, so + IPv4Network('192.0.2.1') == IPv4Network(3221225985) + or, more generally + IPv4Interface(int(IPv4Interface('192.0.2.1'))) == + IPv4Interface('192.0.2.1') + + Raises: + AddressValueError: If ipaddress isn't a valid IPv4 address. + NetmaskValueError: If the netmask isn't valid for + an IPv4 address. + ValueError: If strict is True and a network address is not + supplied. + """ + addr, mask = self._split_addr_prefix(address) + + self.network_address = IPv4Address(addr) + self.netmask, self._prefixlen = self._make_netmask(mask) + packed = int(self.network_address) + if packed & int(self.netmask) != packed: + if strict: + raise ValueError('%s has host bits set' % self) + else: + self.network_address = IPv4Address(packed & + int(self.netmask)) + + if self._prefixlen == (self._max_prefixlen - 1): + self.hosts = self.__iter__ + elif self._prefixlen == (self._max_prefixlen): + self.hosts = lambda: [IPv4Address(addr)] + + @property + @functools.lru_cache() + def is_global(self): + """Test if this address is allocated for public networks. + + Returns: + A boolean, True if the address is not reserved per + iana-ipv4-special-registry. + + """ + return (not (self.network_address in IPv4Network('100.64.0.0/10') and + self.broadcast_address in IPv4Network('100.64.0.0/10')) and + not self.is_private) + + +class _IPv4Constants: + _linklocal_network = IPv4Network('169.254.0.0/16') + + _loopback_network = IPv4Network('127.0.0.0/8') + + _multicast_network = IPv4Network('224.0.0.0/4') + + _public_network = IPv4Network('100.64.0.0/10') + + _private_networks = [ + IPv4Network('0.0.0.0/8'), + IPv4Network('10.0.0.0/8'), + IPv4Network('127.0.0.0/8'), + IPv4Network('169.254.0.0/16'), + IPv4Network('172.16.0.0/12'), + IPv4Network('192.0.0.0/29'), + IPv4Network('192.0.0.170/31'), + IPv4Network('192.0.2.0/24'), + IPv4Network('192.168.0.0/16'), + IPv4Network('198.18.0.0/15'), + IPv4Network('198.51.100.0/24'), + IPv4Network('203.0.113.0/24'), + IPv4Network('240.0.0.0/4'), + IPv4Network('255.255.255.255/32'), + ] + + _reserved_network = IPv4Network('240.0.0.0/4') + + _unspecified_address = IPv4Address('0.0.0.0') + + +IPv4Address._constants = _IPv4Constants + + +class _BaseV6: + + """Base IPv6 object. + + The following methods are used by IPv6 objects in both single IP + addresses and networks. + + """ + + __slots__ = () + _version = 6 + _ALL_ONES = (2**IPV6LENGTH) - 1 + _HEXTET_COUNT = 8 + _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') + _max_prefixlen = IPV6LENGTH + + # There are only a bunch of valid v6 netmasks, so we cache them all + # when constructed (see _make_netmask()). + _netmask_cache = {} + + @classmethod + def _make_netmask(cls, arg): + """Make a (netmask, prefix_len) tuple from the given argument. + + Argument can be: + - an integer (the prefix length) + - a string representing the prefix length (e.g. "24") + - a string representing the prefix netmask (e.g. "255.255.255.0") + """ + if arg not in cls._netmask_cache: + if isinstance(arg, int): + prefixlen = arg + if not (0 <= prefixlen <= cls._max_prefixlen): + cls._report_invalid_netmask(prefixlen) + else: + prefixlen = cls._prefix_from_prefix_string(arg) + netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen)) + cls._netmask_cache[arg] = netmask, prefixlen + return cls._netmask_cache[arg] + + @classmethod + def _ip_int_from_string(cls, ip_str): + """Turn an IPv6 ip_str into an integer. + + Args: + ip_str: A string, the IPv6 ip_str. + + Returns: + An int, the IPv6 address + + Raises: + AddressValueError: if ip_str isn't a valid IPv6 Address. + + """ + if not ip_str: + raise AddressValueError('Address cannot be empty') + + parts = ip_str.split(':') + + # An IPv6 address needs at least 2 colons (3 parts). + _min_parts = 3 + if len(parts) < _min_parts: + msg = "At least %d parts expected in %r" % (_min_parts, ip_str) + raise AddressValueError(msg) + + # If the address has an IPv4-style suffix, convert it to hexadecimal. + if '.' in parts[-1]: + try: + ipv4_int = IPv4Address(parts.pop())._ip + except AddressValueError as exc: + raise AddressValueError("%s in %r" % (exc, ip_str)) from None + parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) + parts.append('%x' % (ipv4_int & 0xFFFF)) + + # An IPv6 address can't have more than 8 colons (9 parts). + # The extra colon comes from using the "::" notation for a single + # leading or trailing zero part. + _max_parts = cls._HEXTET_COUNT + 1 + if len(parts) > _max_parts: + msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) + raise AddressValueError(msg) + + # Disregarding the endpoints, find '::' with nothing in between. + # This indicates that a run of zeroes has been skipped. + skip_index = None + for i in range(1, len(parts) - 1): + if not parts[i]: + if skip_index is not None: + # Can't have more than one '::' + msg = "At most one '::' permitted in %r" % ip_str + raise AddressValueError(msg) + skip_index = i + + # parts_hi is the number of parts to copy from above/before the '::' + # parts_lo is the number of parts to copy from below/after the '::' + if skip_index is not None: + # If we found a '::', then check if it also covers the endpoints. + parts_hi = skip_index + parts_lo = len(parts) - skip_index - 1 + if not parts[0]: + parts_hi -= 1 + if parts_hi: + msg = "Leading ':' only permitted as part of '::' in %r" + raise AddressValueError(msg % ip_str) # ^: requires ^:: + if not parts[-1]: + parts_lo -= 1 + if parts_lo: + msg = "Trailing ':' only permitted as part of '::' in %r" + raise AddressValueError(msg % ip_str) # :$ requires ::$ + parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo) + if parts_skipped < 1: + msg = "Expected at most %d other parts with '::' in %r" + raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str)) + else: + # Otherwise, allocate the entire address to parts_hi. The + # endpoints could still be empty, but _parse_hextet() will check + # for that. + if len(parts) != cls._HEXTET_COUNT: + msg = "Exactly %d parts expected without '::' in %r" + raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str)) + if not parts[0]: + msg = "Leading ':' only permitted as part of '::' in %r" + raise AddressValueError(msg % ip_str) # ^: requires ^:: + if not parts[-1]: + msg = "Trailing ':' only permitted as part of '::' in %r" + raise AddressValueError(msg % ip_str) # :$ requires ::$ + parts_hi = len(parts) + parts_lo = 0 + parts_skipped = 0 + + try: + # Now, parse the hextets into a 128-bit integer. + ip_int = 0 + for i in range(parts_hi): + ip_int <<= 16 + ip_int |= cls._parse_hextet(parts[i]) + ip_int <<= 16 * parts_skipped + for i in range(-parts_lo, 0): + ip_int <<= 16 + ip_int |= cls._parse_hextet(parts[i]) + return ip_int + except ValueError as exc: + raise AddressValueError("%s in %r" % (exc, ip_str)) from None + + @classmethod + def _parse_hextet(cls, hextet_str): + """Convert an IPv6 hextet string into an integer. + + Args: + hextet_str: A string, the number to parse. + + Returns: + The hextet as an integer. + + Raises: + ValueError: if the input isn't strictly a hex number from + [0..FFFF]. + + """ + # Reject non-ASCII digits. + if not cls._HEX_DIGITS.issuperset(hextet_str): + raise ValueError("Only hex digits permitted in %r" % hextet_str) + # We do the length check second, since the invalid character error + # is likely to be more informative for the user + if len(hextet_str) > 4: + msg = "At most 4 characters permitted in %r" + raise ValueError(msg % hextet_str) + # Length check means we can skip checking the integer value + return int(hextet_str, 16) + + @classmethod + def _compress_hextets(cls, hextets): + """Compresses a list of hextets. + + Compresses a list of strings, replacing the longest continuous + sequence of "0" in the list with "" and adding empty strings at + the beginning or at the end of the string such that subsequently + calling ":".join(hextets) will produce the compressed version of + the IPv6 address. + + Args: + hextets: A list of strings, the hextets to compress. + + Returns: + A list of strings. + + """ + best_doublecolon_start = -1 + best_doublecolon_len = 0 + doublecolon_start = -1 + doublecolon_len = 0 + for index, hextet in enumerate(hextets): + if hextet == '0': + doublecolon_len += 1 + if doublecolon_start == -1: + # Start of a sequence of zeros. + doublecolon_start = index + if doublecolon_len > best_doublecolon_len: + # This is the longest sequence of zeros so far. + best_doublecolon_len = doublecolon_len + best_doublecolon_start = doublecolon_start + else: + doublecolon_len = 0 + doublecolon_start = -1 + + if best_doublecolon_len > 1: + best_doublecolon_end = (best_doublecolon_start + + best_doublecolon_len) + # For zeros at the end of the address. + if best_doublecolon_end == len(hextets): + hextets += [''] + hextets[best_doublecolon_start:best_doublecolon_end] = [''] + # For zeros at the beginning of the address. + if best_doublecolon_start == 0: + hextets = [''] + hextets + + return hextets + + @classmethod + def _string_from_ip_int(cls, ip_int=None): + """Turns a 128-bit integer into hexadecimal notation. + + Args: + ip_int: An integer, the IP address. + + Returns: + A string, the hexadecimal representation of the address. + + Raises: + ValueError: The address is bigger than 128 bits of all ones. + + """ + if ip_int is None: + ip_int = int(cls._ip) + + if ip_int > cls._ALL_ONES: + raise ValueError('IPv6 address is too large') + + hex_str = '%032x' % ip_int + hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] + + hextets = cls._compress_hextets(hextets) + return ':'.join(hextets) + + def _explode_shorthand_ip_string(self): + """Expand a shortened IPv6 address. + + Args: + ip_str: A string, the IPv6 address. + + Returns: + A string, the expanded IPv6 address. + + """ + if isinstance(self, IPv6Network): + ip_str = str(self.network_address) + elif isinstance(self, IPv6Interface): + ip_str = str(self.ip) + else: + ip_str = str(self) + + ip_int = self._ip_int_from_string(ip_str) + hex_str = '%032x' % ip_int + parts = [hex_str[x:x+4] for x in range(0, 32, 4)] + if isinstance(self, (_BaseNetwork, IPv6Interface)): + return '%s/%d' % (':'.join(parts), self._prefixlen) + return ':'.join(parts) + + def _reverse_pointer(self): + """Return the reverse DNS pointer name for the IPv6 address. + + This implements the method described in RFC3596 2.5. + + """ + reverse_chars = self.exploded[::-1].replace(':', '') + return '.'.join(reverse_chars) + '.ip6.arpa' + + @staticmethod + def _split_scope_id(ip_str): + """Helper function to parse IPv6 string address with scope id. + + See RFC 4007 for details. + + Args: + ip_str: A string, the IPv6 address. + + Returns: + (addr, scope_id) tuple. + + """ + addr, sep, scope_id = ip_str.partition('%') + if not sep: + scope_id = None + elif not scope_id or '%' in scope_id: + raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str) + return addr, scope_id + + @property + def max_prefixlen(self): + return self._max_prefixlen + + @property + def version(self): + return self._version + + +class IPv6Address(_BaseV6, _BaseAddress): + + """Represent and manipulate single IPv6 Addresses.""" + + __slots__ = ('_ip', '_scope_id', '__weakref__') + + def __init__(self, address): + """Instantiate a new IPv6 address object. + + Args: + address: A string or integer representing the IP + + Additionally, an integer can be passed, so + IPv6Address('2001:db8::') == + IPv6Address(42540766411282592856903984951653826560) + or, more generally + IPv6Address(int(IPv6Address('2001:db8::'))) == + IPv6Address('2001:db8::') + + Raises: + AddressValueError: If address isn't a valid IPv6 address. + + """ + # Efficient constructor from integer. + if isinstance(address, int): + self._check_int_address(address) + self._ip = address + self._scope_id = None + return + + # Constructing from a packed address + if isinstance(address, bytes): + self._check_packed_address(address, 16) + self._ip = int.from_bytes(address, 'big') + self._scope_id = None + return + + # Assume input argument to be string or any object representation + # which converts into a formatted IP string. + addr_str = str(address) + if '/' in addr_str: + raise AddressValueError(f"Unexpected '/' in {address!r}") + addr_str, self._scope_id = self._split_scope_id(addr_str) + + self._ip = self._ip_int_from_string(addr_str) + + def __str__(self): + ip_str = super().__str__() + return ip_str + '%' + self._scope_id if self._scope_id else ip_str + + def __hash__(self): + return hash((self._ip, self._scope_id)) + + def __eq__(self, other): + address_equal = super().__eq__(other) + if address_equal is NotImplemented: + return NotImplemented + if not address_equal: + return False + return self._scope_id == getattr(other, '_scope_id', None) + + @property + def scope_id(self): + """Identifier of a particular zone of the address's scope. + + See RFC 4007 for details. + + Returns: + A string identifying the zone of the address if specified, else None. + + """ + return self._scope_id + + @property + def packed(self): + """The binary representation of this address.""" + return v6_int_to_packed(self._ip) + + @property + def is_multicast(self): + """Test if the address is reserved for multicast use. + + Returns: + A boolean, True if the address is a multicast address. + See RFC 2373 2.7 for details. + + """ + return self in self._constants._multicast_network + + @property + def is_reserved(self): + """Test if the address is otherwise IETF reserved. + + Returns: + A boolean, True if the address is within one of the + reserved IPv6 Network ranges. + + """ + return any(self in x for x in self._constants._reserved_networks) + + @property + def is_link_local(self): + """Test if the address is reserved for link-local. + + Returns: + A boolean, True if the address is reserved per RFC 4291. + + """ + return self in self._constants._linklocal_network + + @property + def is_site_local(self): + """Test if the address is reserved for site-local. + + Note that the site-local address space has been deprecated by RFC 3879. + Use is_private to test if this address is in the space of unique local + addresses as defined by RFC 4193. + + Returns: + A boolean, True if the address is reserved per RFC 3513 2.5.6. + + """ + return self in self._constants._sitelocal_network + + @property + @functools.lru_cache() + def is_private(self): + """Test if this address is allocated for private networks. + + Returns: + A boolean, True if the address is reserved per + iana-ipv6-special-registry, or is ipv4_mapped and is + reserved in the iana-ipv4-special-registry. + + """ + ipv4_mapped = self.ipv4_mapped + if ipv4_mapped is not None: + return ipv4_mapped.is_private + return any(self in net for net in self._constants._private_networks) + + @property + def is_global(self): + """Test if this address is allocated for public networks. + + Returns: + A boolean, true if the address is not reserved per + iana-ipv6-special-registry. + + """ + return not self.is_private + + @property + def is_unspecified(self): + """Test if the address is unspecified. + + Returns: + A boolean, True if this is the unspecified address as defined in + RFC 2373 2.5.2. + + """ + return self._ip == 0 + + @property + def is_loopback(self): + """Test if the address is a loopback address. + + Returns: + A boolean, True if the address is a loopback address as defined in + RFC 2373 2.5.3. + + """ + return self._ip == 1 + + @property + def ipv4_mapped(self): + """Return the IPv4 mapped address. + + Returns: + If the IPv6 address is a v4 mapped address, return the + IPv4 mapped address. Return None otherwise. + + """ + if (self._ip >> 32) != 0xFFFF: + return None + return IPv4Address(self._ip & 0xFFFFFFFF) + + @property + def teredo(self): + """Tuple of embedded teredo IPs. + + Returns: + Tuple of the (server, client) IPs or None if the address + doesn't appear to be a teredo address (doesn't start with + 2001::/32) + + """ + if (self._ip >> 96) != 0x20010000: + return None + return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), + IPv4Address(~self._ip & 0xFFFFFFFF)) + + @property + def sixtofour(self): + """Return the IPv4 6to4 embedded address. + + Returns: + The IPv4 6to4-embedded address if present or None if the + address doesn't appear to contain a 6to4 embedded address. + + """ + if (self._ip >> 112) != 0x2002: + return None + return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) + + +class IPv6Interface(IPv6Address): + + def __init__(self, address): + addr, mask = self._split_addr_prefix(address) + + IPv6Address.__init__(self, addr) + self.network = IPv6Network((addr, mask), strict=False) + self.netmask = self.network.netmask + self._prefixlen = self.network._prefixlen + + @functools.cached_property + def hostmask(self): + return self.network.hostmask + + def __str__(self): + return '%s/%d' % (super().__str__(), + self._prefixlen) + + def __eq__(self, other): + address_equal = IPv6Address.__eq__(self, other) + if address_equal is NotImplemented or not address_equal: + return address_equal + try: + return self.network == other.network + except AttributeError: + # An interface with an associated network is NOT the + # same as an unassociated address. That's why the hash + # takes the extra info into account. + return False + + def __lt__(self, other): + address_less = IPv6Address.__lt__(self, other) + if address_less is NotImplemented: + return address_less + try: + return (self.network < other.network or + self.network == other.network and address_less) + except AttributeError: + # We *do* allow addresses and interfaces to be sorted. The + # unassociated address is considered less than all interfaces. + return False + + def __hash__(self): + return hash((self._ip, self._prefixlen, int(self.network.network_address))) + + __reduce__ = _IPAddressBase.__reduce__ + + @property + def ip(self): + return IPv6Address(self._ip) + + @property + def with_prefixlen(self): + return '%s/%s' % (self._string_from_ip_int(self._ip), + self._prefixlen) + + @property + def with_netmask(self): + return '%s/%s' % (self._string_from_ip_int(self._ip), + self.netmask) + + @property + def with_hostmask(self): + return '%s/%s' % (self._string_from_ip_int(self._ip), + self.hostmask) + + @property + def is_unspecified(self): + return self._ip == 0 and self.network.is_unspecified + + @property + def is_loopback(self): + return self._ip == 1 and self.network.is_loopback + + +class IPv6Network(_BaseV6, _BaseNetwork): + + """This class represents and manipulates 128-bit IPv6 networks. + + Attributes: [examples for IPv6('2001:db8::1000/124')] + .network_address: IPv6Address('2001:db8::1000') + .hostmask: IPv6Address('::f') + .broadcast_address: IPv6Address('2001:db8::100f') + .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') + .prefixlen: 124 + + """ + + # Class to use when creating address objects + _address_class = IPv6Address + + def __init__(self, address, strict=True): + """Instantiate a new IPv6 Network object. + + Args: + address: A string or integer representing the IPv6 network or the + IP and prefix/netmask. + '2001:db8::/128' + '2001:db8:0000:0000:0000:0000:0000:0000/128' + '2001:db8::' + are all functionally the same in IPv6. That is to say, + failing to provide a subnetmask will create an object with + a mask of /128. + + Additionally, an integer can be passed, so + IPv6Network('2001:db8::') == + IPv6Network(42540766411282592856903984951653826560) + or, more generally + IPv6Network(int(IPv6Network('2001:db8::'))) == + IPv6Network('2001:db8::') + + strict: A boolean. If true, ensure that we have been passed + A true network address, eg, 2001:db8::1000/124 and not an + IP address on a network, eg, 2001:db8::1/124. + + Raises: + AddressValueError: If address isn't a valid IPv6 address. + NetmaskValueError: If the netmask isn't valid for + an IPv6 address. + ValueError: If strict was True and a network address was not + supplied. + """ + addr, mask = self._split_addr_prefix(address) + + self.network_address = IPv6Address(addr) + self.netmask, self._prefixlen = self._make_netmask(mask) + packed = int(self.network_address) + if packed & int(self.netmask) != packed: + if strict: + raise ValueError('%s has host bits set' % self) + else: + self.network_address = IPv6Address(packed & + int(self.netmask)) + + if self._prefixlen == (self._max_prefixlen - 1): + self.hosts = self.__iter__ + elif self._prefixlen == self._max_prefixlen: + self.hosts = lambda: [IPv6Address(addr)] + + def hosts(self): + """Generate Iterator over usable hosts in a network. + + This is like __iter__ except it doesn't return the + Subnet-Router anycast address. + + """ + network = int(self.network_address) + broadcast = int(self.broadcast_address) + for x in range(network + 1, broadcast + 1): + yield self._address_class(x) + + @property + def is_site_local(self): + """Test if the address is reserved for site-local. + + Note that the site-local address space has been deprecated by RFC 3879. + Use is_private to test if this address is in the space of unique local + addresses as defined by RFC 4193. + + Returns: + A boolean, True if the address is reserved per RFC 3513 2.5.6. + + """ + return (self.network_address.is_site_local and + self.broadcast_address.is_site_local) + + +class _IPv6Constants: + + _linklocal_network = IPv6Network('fe80::/10') + + _multicast_network = IPv6Network('ff00::/8') + + _private_networks = [ + IPv6Network('::1/128'), + IPv6Network('::/128'), + IPv6Network('::ffff:0:0/96'), + IPv6Network('100::/64'), + IPv6Network('2001::/23'), + IPv6Network('2001:2::/48'), + IPv6Network('2001:db8::/32'), + IPv6Network('2001:10::/28'), + IPv6Network('fc00::/7'), + IPv6Network('fe80::/10'), + ] + + _reserved_networks = [ + IPv6Network('::/8'), IPv6Network('100::/8'), + IPv6Network('200::/7'), IPv6Network('400::/6'), + IPv6Network('800::/5'), IPv6Network('1000::/4'), + IPv6Network('4000::/3'), IPv6Network('6000::/3'), + IPv6Network('8000::/3'), IPv6Network('A000::/3'), + IPv6Network('C000::/3'), IPv6Network('E000::/4'), + IPv6Network('F000::/5'), IPv6Network('F800::/6'), + IPv6Network('FE00::/9'), + ] + + _sitelocal_network = IPv6Network('fec0::/10') + + +IPv6Address._constants = _IPv6Constants diff --git a/shared/package-files/78/786c7a6001b01c09448d9151233395393b86b642379b18d1a8c40a5513ab7d13/blob b/shared/package-files/78/786c7a6001b01c09448d9151233395393b86b642379b18d1a8c40a5513ab7d13/blob new file mode 100644 index 0000000000000000000000000000000000000000..8f84c90f467598bb4a2162d8d0bfcb40d5450c49 --- /dev/null +++ b/shared/package-files/78/786c7a6001b01c09448d9151233395393b86b642379b18d1a8c40a5513ab7d13/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API max_pool2d_with_indices_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::max_pool2d_with_indices_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "max_pool2d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & indices, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & indices, at::Tensor & grad_input); +}; + +struct TORCH_API max_pool2d_with_indices_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::max_pool2d_with_indices_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & indices); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & indices); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/786ec958264edd6e4569cf8ebd7fe9014a767377feff7ac11e0c4eb5b5c86c64/blob b/shared/package-files/78/786ec958264edd6e4569cf8ebd7fe9014a767377feff7ac11e0c4eb5b5c86c64/blob new file mode 100644 index 0000000000000000000000000000000000000000..e13d2953e6611d495c4b03a25eb730b1fc4e5afb --- /dev/null +++ b/shared/package-files/78/786ec958264edd6e4569cf8ebd7fe9014a767377feff7ac11e0c4eb5b5c86c64/blob @@ -0,0 +1,1003 @@ +from __future__ import annotations + +from statsmodels.compat.python import lrange + +from typing import TYPE_CHECKING, Literal, NamedTuple +import warnings + +import numpy as np +import pandas as pd +from pandas import DataFrame +from pandas.tseries import offsets +from pandas.tseries.frequencies import to_offset + +from statsmodels.tools.data import _is_recarray, _is_using_pandas +from statsmodels.tools.sm_exceptions import ValueWarning +from statsmodels.tools.validation import ( + array_like, + bool_like, + int_like, + string_like, +) + +if TYPE_CHECKING: + from statsmodels.tools.typing import NDArray + +__all__ = [ + "LagmatResult", + "add_trend", + "commutation_matrix", + "duplication_matrix", + "elimination_matrix", + "freq_to_period", + "lagmat", + "lagmat2ds", + "unvec", + "unvech", + "vec", + "vech", +] + + +def add_trend(x, trend="c", prepend=False, has_constant="skip"): + """ + Add a trend and/or constant to an array + + Parameters + ---------- + x : array_like + Original array of data. + trend : {'n', 'c', 't', 'ct', 'ctt'}, optional + The trend to add. + + * 'n' add no trend. + * 'c' add constant only. + * 't' add trend only. + * 'ct' add constant and linear trend. + * 'ctt' add constant and linear and quadratic trend. + prepend : bool, optional + If True, prepends the new data to the columns of X. + has_constant : {'raise', 'add', 'skip'}, optional + Controls what happens when trend is 'c' and a constant column already + exists in x. 'raise' will raise an error. 'add' will add a column of + 1s. 'skip' will return the data without change. 'skip' is the default. + + Returns + ------- + ndarray, Series, or DataFrame + The original data with the additional trend columns. If x is a + pandas Series or DataFrame, then the trend column names are 'const', + 'trend' and 'trend_squared'. A Series is only returned when + ``trend='n'`` and x is a Series, since no columns are added. + + See Also + -------- + statsmodels.tools.tools.add_constant + Add a constant column to an array. + + Notes + ----- + Returns columns as ['ctt','ct','c'] whenever applicable. There is currently + no checking for an existing trend. + """ + prepend = bool_like(prepend, "prepend") + trend = string_like(trend, "trend", options=("n", "c", "t", "ct", "ctt")) + has_constant = string_like( + has_constant, "has_constant", options=("raise", "add", "skip") + ) + + # TODO: could be generalized for trend of aribitrary order + columns = ["const", "trend", "trend_squared"] + if trend == "n": + return x.copy() + elif trend == "c": # handles structured arrays + columns = columns[:1] + trendorder = 0 + elif trend == "ct" or trend == "t": + columns = columns[:2] + if trend == "t": + columns = columns[1:2] + trendorder = 1 + elif trend == "ctt": + trendorder = 2 + + if _is_recarray(x): + from statsmodels.tools.sm_exceptions import recarray_exception + + raise NotImplementedError(recarray_exception) + + is_pandas = _is_using_pandas(x, None) + if is_pandas: + if isinstance(x, pd.Series): + x = pd.DataFrame(x) + else: + x = x.copy() + else: + x = np.asanyarray(x) + + nobs = len(x) + trendarr = np.vander(np.arange(1, nobs + 1, dtype=np.float64), trendorder + 1) + # put in order ctt + trendarr = np.fliplr(trendarr) + if trend == "t": + trendarr = trendarr[:, 1] + + if "c" in trend: + if is_pandas: + # Mixed type protection + def safe_is_const(s): + try: + return np.ptp(s) == 0.0 and np.any(s != 0.0) + except Exception: + return False + + col_const = x.apply(safe_is_const, 0) + else: + ptp0 = np.ptp(np.asanyarray(x), axis=0) + col_is_const = ptp0 == 0 + nz_const = col_is_const & (x[0] != 0) + col_const = nz_const + + if np.any(col_const): + if has_constant == "raise": + if x.ndim == 1: + base_err = "x is constant." + else: + columns = np.arange(x.shape[1])[col_const] + if isinstance(x, pd.DataFrame): + columns = x.columns[col_const] + const_cols = ", ".join([str(c) for c in columns]) + base_err = ( + "x contains one or more constant columns. Column(s) " + f"{const_cols} are constant." + ) + raise ValueError( + f"{base_err} Adding a constant with trend='{trend}' is " + "not allowed." + ) + elif has_constant == "skip": + columns = columns[1:] + trendarr = trendarr[:, 1:] + + order = 1 if prepend else -1 + if is_pandas: + trendarr = pd.DataFrame(trendarr, index=x.index, columns=columns) + x = [trendarr, x] + x = pd.concat(x[::order], axis=1) + else: + x = [trendarr, x] + x = np.column_stack(x[::order]) + + return x + + +def add_lag(x, col=None, lags=1, drop=False, insert=True): + """ + Returns an array with lags included given an array + + Parameters + ---------- + x : array_like + An array or NumPy ndarray subclass. Can be either a 1d or 2d array with + observations in columns. + col : int, optional + `col` can be an int of the zero-based column index. If it's a + 1d array `col` can be None. + lags : int, optional + The number of lags desired. + drop : bool, optional + Whether to keep the contemporaneous variable for the data. + insert : bool or int, optional + If True, inserts the lagged values after `col`. If False, appends + the data. If int inserts the lags at int. + + Returns + ------- + array : ndarray + Array with lags + + Notes + ----- + Trims the array both forward and backward, so that the length of the + returned array is len(`X`) - lags. The lags are returned in increasing + order, i.e., t-1,t-2,...,t-lags + + Examples + -------- + >>> import statsmodels.api as sm + >>> data = sm.datasets.macrodata.load() + >>> data = data.data[['year','quarter','realgdp','cpi']] + >>> data = sm.tsa.add_lag(data, 'realgdp', lags=2) + """ + lags = int_like(lags, "lags") + drop = bool_like(drop, "drop") + x = array_like(x, "x", ndim=2) + if col is None: + col = 0 + + # handle negative index + if col < 0: + col = x.shape[1] + col + if x.ndim == 1: + x = x[:, None] + contemp = x[:, col] + + if insert is True: + ins_idx = col + 1 + elif insert is False: + ins_idx = x.shape[1] + else: + if insert < 0: # handle negative index + insert = x.shape[1] + insert + 1 + if insert > x.shape[1]: + insert = x.shape[1] + + warnings.warn( + "insert > number of variables, inserting at the last position", + ValueWarning, + stacklevel=2, + ) + ins_idx = insert + + ndlags = lagmat(contemp, lags, trim="Both") + first_cols = lrange(ins_idx) + last_cols = lrange(ins_idx, x.shape[1]) + if drop: + if col in first_cols: + first_cols.pop(first_cols.index(col)) + else: + last_cols.pop(last_cols.index(col)) + return np.column_stack((x[lags:, first_cols], ndlags, x[lags:, last_cols])) + + +def detrend(x, order=1, axis=0): + """ + Detrend an array with a trend of given order along axis 0 or 1 + + Parameters + ---------- + x : ndarray + Data, 1d or 2d. If 2d, then each row or column is independently + detrended with the same trendorder, but independent trend estimates. + order : int, optional + The polynomial order of the trend, zero is constant, one is + linear trend, two is quadratic trend. + axis : int, optional + Axis can be either 0, observations by rows, or 1, observations by + columns. + + Returns + ------- + ndarray + The detrended series is the residual of the linear regression of the + data on the trend of given order. + """ + order = int_like(order, "order") + axis = int_like(axis, "axis") + + if x.ndim == 2 and int(axis) == 1: + x = x.T + elif x.ndim > 2: + raise NotImplementedError("x.ndim > 2 is not implemented until it is needed") + + nobs = x.shape[0] + if order == 0: + # Special case demean + resid = x - x.mean(axis=0) + else: + trends = np.vander(np.arange(float(nobs)), N=order + 1) + beta = np.linalg.pinv(trends).dot(x) + resid = x - np.dot(trends, beta) + + if x.ndim == 2 and int(axis) == 1: + resid = resid.T + + return resid + + +class LagmatResult(NamedTuple): + """ + Result of :func:`lagmat`. + + Parameters + ---------- + lags : ndarray or DataFrame + The array with lagged observations. + leads : ndarray, DataFrame, or None + The original (unlagged) array, truncated to have the same number + of rows as ``lags``. + """ + + lags: NDArray | DataFrame + leads: NDArray | DataFrame | None + + +def lagmat( + x, + maxlag: int | list[int] | NDArray, + trim: Literal["forward", "backward", "both", "none"] = "forward", + original: Literal["ex", "sep", "in"] = "ex", + use_pandas: bool = False, + *, + result_object: bool | None = None, +) -> NDArray | DataFrame | LagmatResult: + """ + Create 2d array of lags + + Parameters + ---------- + x : array_like + Data; if 2d, observation in rows and variables in columns. + maxlag : int or array_like of int + The lags to be applied. + + * int : All lags from zero to maxlag are included. + * array_like : All lags associated to the values in the array. + Must contain non-negative integers. + trim : {'forward', 'backward', 'both', 'none', None}, optional + The trimming method to use. + + * 'forward' : trim invalid observations in front. + * 'backward' : trim invalid initial observations. + * 'both' : trim invalid observations on both sides. + * 'none', None : no trimming of observations. + original : {'ex','sep','in'}, optional + How the original is treated. + + * 'ex' : drops the original array returning only the lagged values. + * 'in' : returns the original array and the lagged values as a single + array. + * 'sep' : returns a tuple (original array, lagged values). The original + array is truncated to have the same number of rows as + the returned lagmat. + use_pandas : bool, optional + If true, returns a DataFrame when the input is a pandas + Series or DataFrame. If false, return numpy ndarrays. + result_object : bool, optional + Flag controlling whether a :class:`LagmatResult` is returned. When + ``original="sep"`` a :class:`LagmatResult` is always returned. For + other values of ``original`` a bare array is returned unless + ``result_object=True``, which additionally yields a + :class:`LagmatResult` with ``leads`` set to ``None``. + + Returns + ------- + LagmatResult, ndarray, or DataFrame + When ``original="sep"`` (or ``result_object=True``), a + :class:`LagmatResult` with fields: + + lags : ndarray or DataFrame + The array with lagged observations. + leads : ndarray, DataFrame, or None + The original (unlagged) array, truncated to have the same + number of rows as ``lags``. ``None`` for other values of + ``original``, where the original series was either excluded + ("ex") or folded into ``lags`` ("in"). + + For other values of ``original`` a bare array (or, when + ``use_pandas=True`` and `x` is a pandas object, a DataFrame) of + lagged observations is returned instead. + + Notes + ----- + When using a pandas DataFrame or Series with use_pandas=True, trim can only + be 'forward' or 'both' since it is not possible to consistently extend + index values. + + Examples + -------- + >>> from statsmodels.tsa.tsatools import lagmat + >>> import numpy as np + >>> X = np.arange(1,7).reshape(-1,2) + >>> lagmat(X, maxlag=2, trim="forward", original='in') + array([[ 1., 2., 0., 0., 0., 0.], + [ 3., 4., 1., 2., 0., 0.], + [ 5., 6., 3., 4., 1., 2.]]) + + >>> lagmat(X, maxlag=2, trim="backward", original='in') + array([[ 5., 6., 3., 4., 1., 2.], + [ 0., 0., 5., 6., 3., 4.], + [ 0., 0., 0., 0., 5., 6.]]) + + >>> lagmat(X, maxlag=2, trim="both", original='in') + array([[ 5., 6., 3., 4., 1., 2.]]) + + >>> lagmat(X, maxlag=2, trim="none", original='in') + array([[ 1., 2., 0., 0., 0., 0.], + [ 3., 4., 1., 2., 0., 0.], + [ 5., 6., 3., 4., 1., 2.], + [ 0., 0., 5., 6., 3., 4.], + [ 0., 0., 0., 0., 5., 6.]]) + + >>> lagmat(X, maxlag=[1, 3], trim="forward", original='ex') + array([[ 1., 2., 0., 0., 0., 0.], + [ 3., 4., 1., 2., 0., 0.], + [ 5., 6., 3., 4., 1., 2.]]) + + """ + if np.isscalar(maxlag): + maxlag = int_like(maxlag, "maxlag") + if maxlag < 0: + raise ValueError(f"`maxlag` must be greater than 0. Got {maxlag}.") + # Convert to array to simplify and use only array path + lag_indices = np.arange(1, maxlag + 1, dtype=int) + else: + lag_indices = array_like(maxlag, "maxlag", dtype=int, ndim=1, maxdim=1) + if not np.all(lag_indices >= 0): + raise ValueError( + f"All values in `maxlag` must be >= 0. Found {lag_indices[lag_indices < 0]}." + ) + if len(np.unique(lag_indices)) != len(lag_indices): + from collections import Counter + + bad_lags = [ + int(key) for key, val in Counter(lag_indices).items() if val > 1 + ] + raise ValueError( + f"`maxlag` must contain unique values. maxlag contains the following " + f"duplicate values: {bad_lags}." + ) + # Special case for lag_indices = [0] to empty to match above + lag_indices = lag_indices[lag_indices > 0] + use_pandas = bool_like(use_pandas, "use_pandas") + result_object = bool_like(result_object, "result_object", optional=True) + trim = string_like( + trim, + "trim", + optional=True, + options=("forward", "backward", "both", "none"), + ) + original = string_like(original, "original", options=("ex", "sep", "in")) + + orig = x + x = array_like(x, "x", ndim=2, dtype=None) + is_pandas = _is_using_pandas(orig, None) and use_pandas + trim = "none" if trim is None else trim + trim = trim.lower() + if is_pandas and trim in ("none", "backward"): + raise ValueError( + "trim cannot be 'none' or 'backward' when used on Series or DataFrames" + ) + + dropidx = 0 + nobs, nvar = x.shape + if original in ["ex", "sep"]: + dropidx = nvar + + nlags = lag_indices.shape[0] + max_lag_value = lag_indices.max() if nlags else 0 + if max_lag_value >= nobs: + raise ValueError("maximum of maxlag should be < nobs") + lm = np.zeros((nobs + max_lag_value, nvar * (nlags + 1))) + for i, k in enumerate([0] + lag_indices.tolist()): + lm[k : nobs + k, nvar * (i) : nvar * (i + 1)] = x + + if trim in ("none", "forward"): + startobs = 0 + else: # trim in ("backward", "both") + startobs = max_lag_value + + if trim in ("none", "backward"): + stopobs = len(lm) + else: + stopobs = nobs + + if is_pandas: + x = orig + if isinstance(x, DataFrame): + x_columns = [str(c) for c in x.columns] + if len(set(x_columns)) != x.shape[1]: + raise ValueError( + "Columns names must be distinct after conversion to string " + "(if not already strings)." + ) + else: + x_columns = [str(x.name)] + columns = [str(col) for col in x_columns] + for lag in lag_indices: + lag_str = str(lag) + columns.extend([str(col) + ".L." + lag_str for col in x_columns]) + lm = DataFrame(lm[:stopobs], index=x.index, columns=columns) + lags = lm.iloc[startobs:] + if original in ("sep", "ex"): + leads = lags[x_columns] + lags = lags.drop(x_columns, axis=1) + else: + lags = lm[startobs:stopobs, dropidx:] + if original == "sep": + leads = lm[startobs:stopobs, :dropidx] + + # LagmatResult is always used when original="sep". For other values of + # `original` a bare array is returned, as before; pass + # result_object=True to always get a LagmatResult. `leads` is only + # meaningful for "sep" -- for "ex" the caller asked for it to be + # excluded and for "in" it is part of `lags`. + if result_object or original == "sep": + return LagmatResult(lags, leads if original == "sep" else None) + return lags + + +def lagmat2ds(x, maxlag0, maxlagex=None, dropex=0, trim="forward", use_pandas=False): + """ + Generate lagmatrix for 2d array, columns arranged by variables + + Parameters + ---------- + x : ndarray, Series, or DataFrame + Data, 1d or 2d. Observations in rows and variables in columns. + maxlag0 : int + The first variable all lags from zero to maxlag are included. + maxlagex : int, optional + The max lag for all other variables all lags from zero to maxlag are + included. If None, defaults to maxlag0. + dropex : int, optional + Exclude first dropex lags from other variables. For all variables, + except the first, lags from dropex to maxlagex are included. + trim : {'forward', 'backward', 'both', 'none'}, optional + The trimming method to use. + + * 'forward' : trim invalid observations in front. + * 'backward' : trim invalid initial observations. + * 'both' : trim invalid observations on both sides. + * 'none' : no trimming of observations. + use_pandas : bool, optional + If true, returns a DataFrame when the input is a pandas + Series or DataFrame. If false, return numpy ndarrays. + + Returns + ------- + ndarray or DataFrame + The array with lagged observations, columns ordered by variable. A + DataFrame is returned if `x` is a pandas Series or DataFrame and + `use_pandas` is True. + + Notes + ----- + Inefficient implementation for unequal lags, implemented for convenience. + """ + maxlag0 = int_like(maxlag0, "maxlag0") + maxlagex = int_like(maxlagex, "maxlagex", optional=True) + trim = string_like( + trim, + "trim", + optional=True, + options=("forward", "backward", "both", "none"), + ) + if maxlagex is None: + maxlagex = maxlag0 + maxlag = max(maxlag0, maxlagex) + is_pandas = _is_using_pandas(x, None) + + if x.ndim == 1: + if is_pandas: + x = pd.DataFrame(x) + else: + x = x[:, None] + elif x.ndim == 0 or x.ndim > 2: + raise ValueError("Only supports 1 and 2-dimensional data.") + + nobs, nvar = x.shape + + if is_pandas and use_pandas: + lags = lagmat(x.iloc[:, 0], maxlag, trim=trim, original="in", use_pandas=True) + lagsli = [lags.iloc[:, : maxlag0 + 1]] + for k in range(1, nvar): + lags = lagmat( + x.iloc[:, k], maxlag, trim=trim, original="in", use_pandas=True + ) + lagsli.append(lags.iloc[:, dropex : maxlagex + 1]) + return pd.concat(lagsli, axis=1) + elif is_pandas: + x = np.asanyarray(x) + + lagsli = [lagmat(x[:, 0], maxlag, trim=trim, original="in")[:, : maxlag0 + 1]] + for k in range(1, nvar): + lagsli.append( + lagmat(x[:, k], maxlag, trim=trim, original="in")[:, dropex : maxlagex + 1] + ) + return np.column_stack(lagsli) + + +def vec(mat): + """ + Vectorize a matrix by stacking its columns + + Parameters + ---------- + mat : ndarray + A 2d array. + + Returns + ------- + ndarray + A 1d array containing the columns of `mat` stacked on top of + one another (Fortran, i.e. column-major, order). + + See Also + -------- + unvec + Inverse operation. + vech + Half-vectorization operator for symmetric matrices. + """ + return mat.ravel("F") + + +def vech(mat): + """ + Half-vectorize a symmetric matrix by stacking its lower triangle + + Parameters + ---------- + mat : ndarray + A symmetric 2d array. + + Returns + ------- + ndarray + A 1d array containing the lower-triangular elements of `mat`, + stacked column by column (Fortran, i.e. column-major, order). + + See Also + -------- + unvech + Inverse operation. + vec + Full vectorization operator. + """ + # Gets Fortran-order + return mat.T.take(_triu_indices(len(mat))) + + +# tril/triu/diag, suitable for ndarray.take + + +def _tril_indices(n): + rows, cols = np.tril_indices(n) + return rows * n + cols + + +def _triu_indices(n): + rows, cols = np.triu_indices(n) + return rows * n + cols + + +def _diag_indices(n): + rows, cols = np.diag_indices(n) + return rows * n + cols + + +def unvec(v): + """ + Reconstruct a square matrix from its vectorized (stacked-column) form + + Parameters + ---------- + v : ndarray + A 1d array whose length is a perfect square. + + Returns + ------- + ndarray + The square matrix whose columns, stacked on top of one another, + equal `v`. + + See Also + -------- + vec + Inverse operation. + """ + k = int(np.sqrt(len(v))) + assert k * k == len(v) + return v.reshape((k, k), order="F") + + +def unvech(v): + """ + Reconstruct a symmetric matrix from its half-vectorized form + + Parameters + ---------- + v : ndarray + A 1d array containing the stacked lower-triangular elements of a + symmetric matrix, as produced by :func:`vech`. + + Returns + ------- + ndarray + The symmetric matrix whose lower-triangular elements, stacked + column by column, equal `v`. + + See Also + -------- + vech + Inverse operation. + """ + # quadratic formula, correct fp error + rows = 0.5 * (-1 + np.sqrt(1 + 8 * len(v))) + rows = int(np.round(rows)) + + result = np.zeros((rows, rows)) + result[np.triu_indices(rows)] = v + result = result + result.T + + # divide diagonal elements by 2 + result[np.diag_indices(rows)] /= 2 + + return result + + +def duplication_matrix(n): + """ + Create duplication matrix D_n which satisfies vec(S) = D_n vech(S) for + symmetric matrix S + + Parameters + ---------- + n : int + The number of rows/columns of the symmetric matrix S. + + Returns + ------- + D_n : ndarray + The duplication matrix. + """ + n = int_like(n, "n") + tmp = np.eye(n * (n + 1) // 2) + return np.array([unvech(x).ravel() for x in tmp]).T + + +def elimination_matrix(n): + """ + Create the elimination matrix L_n which satisfies vech(M) = L_n vec(M) for + any matrix M + + Parameters + ---------- + n : int + The number of rows/columns of the matrix M. + + Returns + ------- + L_n : ndarray + The elimination matrix. + """ + n = int_like(n, "n") + vech_indices = vec(np.tril(np.ones((n, n)))) + return np.eye(n * n)[vech_indices != 0] + + +def commutation_matrix(p, q): + """ + Create the commutation matrix K_{p,q} satisfying vec(A') = K_{p,q} vec(A) + + Parameters + ---------- + p : int + Number of rows of A. + q : int + Number of columns of A. + + Returns + ------- + K : ndarray + The commutation matrix, of shape `(pq, pq)`. + """ + p = int_like(p, "p") + q = int_like(q, "q") + + K = np.eye(p * q) + indices = np.arange(p * q).reshape((p, q), order="F") + return K.take(indices.ravel(), axis=0) + + +def _ar_transparams(params): + """ + Transforms params to induce stationarity/invertibility + + Parameters + ---------- + params : ndarray + The AR coefficients + + Returns + ------- + ndarray + The transformed AR coefficients. + + References + ---------- + Jones(1980) + """ + newparams = np.tanh(params / 2) + tmp = np.tanh(params / 2) + for j in range(1, len(params)): + a = newparams[j] + for kiter in range(j): + tmp[kiter] -= a * newparams[j - kiter - 1] + newparams[:j] = tmp[:j] + return newparams + + +def _ar_invtransparams(params): + """ + Inverse of the Jones reparameterization + + Parameters + ---------- + params : ndarray + The transformed AR coefficients + + Returns + ------- + ndarray + The untransformed AR coefficients. + """ + params = params.copy() + tmp = params.copy() + for j in range(len(params) - 1, 0, -1): + a = params[j] + for kiter in range(j): + tmp[kiter] = (params[kiter] + a * params[j - kiter - 1]) / (1 - a**2) + params[:j] = tmp[:j] + invarcoefs = 2 * np.arctanh(params) + return invarcoefs + + +def _ma_transparams(params): + """ + Transforms params to induce stationarity/invertibility + + Parameters + ---------- + params : ndarray + The ma coefficients of an (AR)MA model. + + Returns + ------- + ndarray + The transformed MA coefficients. + + References + ---------- + Jones(1980) + """ + newparams = ((1 - np.exp(-params)) / (1 + np.exp(-params))).copy() + tmp = ((1 - np.exp(-params)) / (1 + np.exp(-params))).copy() + + # levinson-durbin to get macf + for j in range(1, len(params)): + b = newparams[j] + for kiter in range(j): + tmp[kiter] += b * newparams[j - kiter - 1] + newparams[:j] = tmp[:j] + return newparams + + +def _ma_invtransparams(macoefs): + """ + Inverse of the Jones reparameterization + + Parameters + ---------- + macoefs : ndarray + The transformed MA coefficients + + Returns + ------- + ndarray + The untransformed MA coefficients. + """ + tmp = macoefs.copy() + for j in range(len(macoefs) - 1, 0, -1): + b = macoefs[j] + for kiter in range(j): + tmp[kiter] = (macoefs[kiter] - b * macoefs[j - kiter - 1]) / (1 - b**2) + macoefs[:j] = tmp[:j] + invmacoefs = -np.log((1 - macoefs) / (1 + macoefs)) + return invmacoefs + + +def unintegrate_levels(x, d): + """ + Returns the successive differences needed to unintegrate the series + + Parameters + ---------- + x : array_like + The original series + d : int + The number of differences of the differenced series. + + Returns + ------- + y : ndarray + The increasing differences from 0 to d-1 of the first d elements + of x. + + See Also + -------- + unintegrate + """ + d = int_like(d, "d") + x = x[:d] + return np.asarray([np.diff(x, d - i)[0] for i in range(d, 0, -1)]) + + +def unintegrate(x, levels): + """ + After taking n-differences of a series, return the original series + + Parameters + ---------- + x : array_like + The n-th differenced series + levels : sequence of float + The first-value in each differenced series, for + [first-difference, second-difference, ..., n-th difference] + + Returns + ------- + y : ndarray + The original series de-differenced + + Examples + -------- + >>> x = np.array([1, 3, 9., 19, 8.]) + >>> levels = unintegrate_levels(x, 2) + >>> levels + array([ 1., 2.]) + >>> unintegrate(np.diff(x, 2), levels) + array([ 1., 3., 9., 19., 8.]) + """ + levels = list(levels)[:] # copy + if len(levels) > 1: + x0 = levels.pop(-1) + return unintegrate(np.cumsum(np.r_[x0, x]), levels) + x0 = levels[0] + return np.cumsum(np.r_[x0, x]) + + +def freq_to_period(freq: str | offsets.DateOffset) -> int: + """ + Convert a pandas frequency to a periodicity + + Parameters + ---------- + freq : str or offset + Frequency to convert + + Returns + ------- + int + Periodicity of freq + + Notes + ----- + Annual maps to 1, quarterly maps to 4, monthly to 12, weekly to 52. + """ + if not isinstance(freq, offsets.BaseOffset): + freq = to_offset(freq) # go ahead and standardize + assert isinstance(freq, offsets.BaseOffset) + freq = freq.rule_code.upper() + + yearly_freqs = ("A-", "AS-", "Y-", "YS-", "YE-") + if freq in ("A", "Y") or freq.startswith(yearly_freqs): + return 1 + elif freq == "Q" or freq.startswith(("Q-", "QS", "QE")): + return 4 + elif freq == "M" or freq.startswith(("M-", "MS", "ME")): + return 12 + elif freq == "W" or freq.startswith("W-"): + return 52 + elif freq == "D": + return 7 + elif freq == "B": + return 5 + elif freq == "H": + return 24 + else: # pragma : no cover + raise ValueError( + f"freq {freq} not understood. Please report if you " + "think this is in error." + ) diff --git a/shared/package-files/78/786f29b88771e439187dd2e86ad4d255dd185e0c1ea3f8c37d21770fd1df253a/blob b/shared/package-files/78/786f29b88771e439187dd2e86ad4d255dd185e0c1ea3f8c37d21770fd1df253a/blob new file mode 100644 index 0000000000000000000000000000000000000000..59307eb96ee451f7682034add2d2737673ef04c2 --- /dev/null +++ b/shared/package-files/78/786f29b88771e439187dd2e86ad4d255dd185e0c1ea3f8c37d21770fd1df253a/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:786f29b88771e439187dd2e86ad4d255dd185e0c1ea3f8c37d21770fd1df253a +size 196623 diff --git a/shared/package-files/78/7872c76dcfd4a243b57bf63d257e5407c41d6c3bb1219c17a85145d133b9ad34/blob b/shared/package-files/78/7872c76dcfd4a243b57bf63d257e5407c41d6c3bb1219c17a85145d133b9ad34/blob new file mode 100644 index 0000000000000000000000000000000000000000..284d752387378d3957b9f02f851d1be49534ab98 --- /dev/null +++ b/shared/package-files/78/7872c76dcfd4a243b57bf63d257e5407c41d6c3bb1219c17a85145d133b9ad34/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautogradnestedtensor { + +TORCH_API at::Tensor randn_like(const at::Tensor & self, at::TensorOptions options={}, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor randn_like(const at::Tensor & self, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, c10::optional memory_format); + +} // namespace compositeimplicitautogradnestedtensor +} // namespace at diff --git a/shared/package-files/78/7878021c29bb5c7a721c2da66167341da9f3c7ed6af081120d32ecdb86f6cf12/blob b/shared/package-files/78/7878021c29bb5c7a721c2da66167341da9f3c7ed6af081120d32ecdb86f6cf12/blob new file mode 100644 index 0000000000000000000000000000000000000000..41c9feb5234debbe688dd6fd72dcc8752f8ba28f --- /dev/null +++ b/shared/package-files/78/7878021c29bb5c7a721c2da66167341da9f3c7ed6af081120d32ecdb86f6cf12/blob @@ -0,0 +1,443 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +import inspect +import math +from random import Random +from typing import Any, Dict + +import attr + +from hypothesis.control import should_note +from hypothesis.internal.reflection import define_function_signature +from hypothesis.reporting import report +from hypothesis.strategies._internal.core import ( + binary, + lists, + permutations, + sampled_from, +) +from hypothesis.strategies._internal.numbers import floats, integers +from hypothesis.strategies._internal.strategies import SearchStrategy + + +class HypothesisRandom(Random): + """A subclass of Random designed to expose the seed it was initially + provided with.""" + + def __init__(self, note_method_calls): + self.__note_method_calls = note_method_calls + + def __deepcopy__(self, table): + return self.__copy__() + + def __repr__(self): + raise NotImplementedError + + def seed(self, seed): + raise NotImplementedError + + def getstate(self): + raise NotImplementedError + + def setstate(self, state): + raise NotImplementedError + + def _hypothesis_log_random(self, method, kwargs, result): + if not (self.__note_method_calls and should_note()): + return + + args, kwargs = convert_kwargs(method, kwargs) + argstr = ", ".join( + list(map(repr, args)) + [f"{k}={v!r}" for k, v in kwargs.items()] + ) + report(f"{self!r}.{method}({argstr}) -> {result!r}") + + def _hypothesis_do_random(self, method, kwargs): + raise NotImplementedError + + +RANDOM_METHODS = [ + name + for name in [ + "_randbelow", + "betavariate", + "binomialvariate", + "choice", + "choices", + "expovariate", + "gammavariate", + "gauss", + "getrandbits", + "lognormvariate", + "normalvariate", + "paretovariate", + "randint", + "random", + "randrange", + "sample", + "shuffle", + "triangular", + "uniform", + "vonmisesvariate", + "weibullvariate", + "randbytes", + ] + if hasattr(Random, name) +] + + +# Fake shims to get a good signature +def getrandbits(self, n: int) -> int: # type: ignore + raise NotImplementedError + + +def random(self) -> float: # type: ignore + raise NotImplementedError + + +def _randbelow(self, n: int) -> int: # type: ignore + raise NotImplementedError + + +STUBS = {f.__name__: f for f in [getrandbits, random, _randbelow]} + + +SIGNATURES: Dict[str, inspect.Signature] = {} + + +def sig_of(name): + try: + return SIGNATURES[name] + except KeyError: + pass + + target = getattr(Random, name) + result = inspect.signature(STUBS.get(name, target)) + SIGNATURES[name] = result + return result + + +def define_copy_method(name): + target = getattr(Random, name) + + def implementation(self, **kwargs): + result = self._hypothesis_do_random(name, kwargs) + self._hypothesis_log_random(name, kwargs, result) + return result + + sig = inspect.signature(STUBS.get(name, target)) + + result = define_function_signature(target.__name__, target.__doc__, sig)( + implementation + ) + + result.__module__ = __name__ + result.__qualname__ = "HypothesisRandom." + result.__name__ + + setattr(HypothesisRandom, name, result) + + +for r in RANDOM_METHODS: + define_copy_method(r) + + +@attr.s(slots=True) +class RandomState: + next_states: dict = attr.ib(factory=dict) + state_id: Any = attr.ib(default=None) + + +def state_for_seed(data, seed): + try: + seeds_to_states = data.seeds_to_states + except AttributeError: + seeds_to_states = {} + data.seeds_to_states = seeds_to_states + + try: + state = seeds_to_states[seed] + except KeyError: + state = RandomState() + seeds_to_states[seed] = state + + return state + + +UNIFORM = floats(0, 1) + + +def normalize_zero(f: float) -> float: + if f == 0.0: + return 0.0 + else: + return f + + +class ArtificialRandom(HypothesisRandom): + VERSION = 10**6 + + def __init__(self, note_method_calls, data): + super().__init__(note_method_calls=note_method_calls) + self.__data = data + self.__state = RandomState() + + def __repr__(self): + return "HypothesisRandom(generated data)" + + def __copy__(self): + result = ArtificialRandom( + note_method_calls=self._HypothesisRandom__note_method_calls, + data=self.__data, + ) + result.setstate(self.getstate()) + return result + + def __convert_result(self, method, kwargs, result): + if method == "choice": + return kwargs.get("seq")[result] + if method in ("choices", "sample"): + seq = kwargs["population"] + return [seq[i] for i in result] + if method == "shuffle": + seq = kwargs["x"] + original = list(seq) + for i, i2 in enumerate(result): + seq[i] = original[i2] + return None + return result + + def _hypothesis_do_random(self, method, kwargs): + if method == "choices": + key = (method, len(kwargs["population"]), kwargs.get("k")) + elif method == "choice": + key = (method, len(kwargs["seq"])) + elif method == "shuffle": + key = (method, len(kwargs["x"])) + else: + key = (method, *sorted(kwargs)) + + try: + result, self.__state = self.__state.next_states[key] + except KeyError: + pass + else: + return self.__convert_result(method, kwargs, result) + + if method == "_randbelow": + result = self.__data.draw_integer(0, kwargs["n"] - 1) + elif method in ("betavariate", "random"): + result = self.__data.draw(UNIFORM) + elif method == "uniform": + a = normalize_zero(kwargs["a"]) + b = normalize_zero(kwargs["b"]) + result = self.__data.draw(floats(a, b)) + elif method in ("weibullvariate", "gammavariate"): + result = self.__data.draw(floats(min_value=0.0, allow_infinity=False)) + elif method in ("gauss", "normalvariate"): + mu = kwargs["mu"] + result = mu + self.__data.draw( + floats(allow_nan=False, allow_infinity=False) + ) + elif method == "vonmisesvariate": + result = self.__data.draw(floats(0, 2 * math.pi)) + elif method == "randrange": + if kwargs["stop"] is None: + stop = kwargs["start"] + start = 0 + else: + start = kwargs["start"] + stop = kwargs["stop"] + + step = kwargs["step"] + if start == stop: + raise ValueError(f"empty range for randrange({start}, {stop}, {step})") + + if step != 1: + endpoint = (stop - start) // step + if (start - stop) % step == 0: + endpoint -= 1 + + i = self.__data.draw_integer(0, endpoint) + result = start + i * step + else: + result = self.__data.draw_integer(start, stop - 1) + elif method == "randint": + result = self.__data.draw_integer(kwargs["a"], kwargs["b"]) + # New in Python 3.12, so not taken by our coverage job + elif method == "binomialvariate": # pragma: no cover + result = self.__data.draw_integer(0, kwargs["n"]) + elif method == "choice": + seq = kwargs["seq"] + result = self.__data.draw_integer(0, len(seq) - 1) + elif method == "choices": + k = kwargs["k"] + result = self.__data.draw( + lists( + integers(0, len(kwargs["population"]) - 1), + min_size=k, + max_size=k, + ) + ) + elif method == "sample": + k = kwargs["k"] + seq = kwargs["population"] + + if k > len(seq) or k < 0: + raise ValueError( + f"Sample size {k} not in expected range 0 <= k <= {len(seq)}" + ) + + if k == 0: + result = [] + else: + result = self.__data.draw( + lists( + sampled_from(range(len(seq))), + min_size=k, + max_size=k, + unique=True, + ) + ) + + elif method == "getrandbits": + result = self.__data.draw_integer(0, 2 ** kwargs["n"] - 1) + elif method == "triangular": + low = normalize_zero(kwargs["low"]) + high = normalize_zero(kwargs["high"]) + mode = normalize_zero(kwargs["mode"]) + if mode is None: + result = self.__data.draw(floats(low, high)) + elif self.__data.draw_boolean(0.5): + result = self.__data.draw(floats(mode, high)) + else: + result = self.__data.draw(floats(low, mode)) + elif method in ("paretovariate", "expovariate", "lognormvariate"): + result = self.__data.draw(floats(min_value=0.0)) + elif method == "shuffle": + result = self.__data.draw(permutations(range(len(kwargs["x"])))) + elif method == "randbytes": + n = kwargs["n"] + result = self.__data.draw(binary(min_size=n, max_size=n)) + else: + raise NotImplementedError(method) + + new_state = RandomState() + self.__state.next_states[key] = (result, new_state) + self.__state = new_state + + return self.__convert_result(method, kwargs, result) + + def seed(self, seed): + self.__state = state_for_seed(self.__data, seed) + + def getstate(self): + if self.__state.state_id is not None: + return self.__state.state_id + + try: + states_for_ids = self.__data.states_for_ids + except AttributeError: + states_for_ids = {} + self.__data.states_for_ids = states_for_ids + + self.__state.state_id = len(states_for_ids) + states_for_ids[self.__state.state_id] = self.__state + + return self.__state.state_id + + def setstate(self, state): + self.__state = self.__data.states_for_ids[state] + + +DUMMY_RANDOM = Random(0) + + +def convert_kwargs(name, kwargs): + kwargs = dict(kwargs) + + signature = sig_of(name) + + bound = signature.bind(DUMMY_RANDOM, **kwargs) + bound.apply_defaults() + + for k in list(kwargs): + if ( + kwargs[k] is signature.parameters[k].default + or signature.parameters[k].kind != inspect.Parameter.KEYWORD_ONLY + ): + kwargs.pop(k) + + arg_names = list(signature.parameters)[1:] + + args = [] + + for a in arg_names: + if signature.parameters[a].kind == inspect.Parameter.KEYWORD_ONLY: + break + args.append(bound.arguments[a]) + kwargs.pop(a, None) + + while args: + name = arg_names[len(args) - 1] + if args[-1] is signature.parameters[name].default: + args.pop() + else: + break + + return (args, kwargs) + + +class TrueRandom(HypothesisRandom): + def __init__(self, seed, note_method_calls): + super().__init__(note_method_calls) + self.__seed = seed + self.__random = Random(seed) + + def _hypothesis_do_random(self, method, kwargs): + args, kwargs = convert_kwargs(method, kwargs) + + return getattr(self.__random, method)(*args, **kwargs) + + def __copy__(self): + result = TrueRandom( + seed=self.__seed, + note_method_calls=self._HypothesisRandom__note_method_calls, + ) + result.setstate(self.getstate()) + return result + + def __repr__(self): + return f"Random({self.__seed!r})" + + def seed(self, seed): + self.__random.seed(seed) + self.__seed = seed + + def getstate(self): + return self.__random.getstate() + + def setstate(self, state): + self.__random.setstate(state) + + +class RandomStrategy(SearchStrategy): + def __init__(self, note_method_calls, use_true_random): + self.__note_method_calls = note_method_calls + self.__use_true_random = use_true_random + + def do_draw(self, data): + if self.__use_true_random: + seed = data.draw_integer(0, 2**64 - 1) + return TrueRandom(seed=seed, note_method_calls=self.__note_method_calls) + else: + return ArtificialRandom( + note_method_calls=self.__note_method_calls, data=data + ) diff --git a/shared/package-files/78/7878255a4b78b7d091c4ec17a9db2870c3daf0ca491531e7d658417f91007cc5/blob b/shared/package-files/78/7878255a4b78b7d091c4ec17a9db2870c3daf0ca491531e7d658417f91007cc5/blob new file mode 100644 index 0000000000000000000000000000000000000000..5168feeddd59a01c25846cbf21e38c3a15442b7d --- /dev/null +++ b/shared/package-files/78/7878255a4b78b7d091c4ec17a9db2870c3daf0ca491531e7d658417f91007cc5/blob @@ -0,0 +1,106 @@ +from typing import Dict, Optional + +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from cryptography.x509 import ObjectIdentifier + +class ExtensionOID: + SUBJECT_DIRECTORY_ATTRIBUTES: ObjectIdentifier = ... + SUBJECT_KEY_IDENTIFIER: ObjectIdentifier = ... + KEY_USAGE: ObjectIdentifier = ... + SUBJECT_ALTERNATIVE_NAME: ObjectIdentifier = ... + ISSUER_ALTERNATIVE_NAME: ObjectIdentifier = ... + BASIC_CONSTRAINTS: ObjectIdentifier = ... + NAME_CONSTRAINTS: ObjectIdentifier = ... + CRL_DISTRIBUTION_POINTS: ObjectIdentifier = ... + CERTIFICATE_POLICIES: ObjectIdentifier = ... + POLICY_MAPPINGS: ObjectIdentifier = ... + AUTHORITY_KEY_IDENTIFIER: ObjectIdentifier = ... + POLICY_CONSTRAINTS: ObjectIdentifier = ... + EXTENDED_KEY_USAGE: ObjectIdentifier = ... + FRESHEST_CRL: ObjectIdentifier = ... + INHIBIT_ANY_POLICY: ObjectIdentifier = ... + ISSUING_DISTRIBUTION_POINT: ObjectIdentifier = ... + AUTHORITY_INFORMATION_ACCESS: ObjectIdentifier = ... + SUBJECT_INFORMATION_ACCESS: ObjectIdentifier = ... + OCSP_NO_CHECK: ObjectIdentifier = ... + TLS_FEATURE: ObjectIdentifier = ... + CRL_NUMBER: ObjectIdentifier = ... + DELTA_CRL_INDICATOR: ObjectIdentifier = ... + PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ObjectIdentifier = ... + PRECERT_POISON: ObjectIdentifier = ... + +class OCSPExtensionOID: + NONCE: ObjectIdentifier = ... + +class CRLEntryExtensionOID: + CERTIFICATE_ISSUER: ObjectIdentifier = ... + CRL_REASON: ObjectIdentifier = ... + INVALIDITY_DATE: ObjectIdentifier = ... + +class NameOID: + COMMON_NAME: ObjectIdentifier = ... + COUNTRY_NAME: ObjectIdentifier = ... + LOCALITY_NAME: ObjectIdentifier = ... + STATE_OR_PROVINCE_NAME: ObjectIdentifier = ... + STREET_ADDRESS: ObjectIdentifier = ... + ORGANIZATION_NAME: ObjectIdentifier = ... + ORGANIZATIONAL_UNIT_NAME: ObjectIdentifier = ... + SERIAL_NUMBER: ObjectIdentifier = ... + SURNAME: ObjectIdentifier = ... + GIVEN_NAME: ObjectIdentifier = ... + TITLE: ObjectIdentifier = ... + GENERATION_QUALIFIER: ObjectIdentifier = ... + X500_UNIQUE_IDENTIFIER: ObjectIdentifier = ... + DN_QUALIFIER: ObjectIdentifier = ... + PSEUDONYM: ObjectIdentifier = ... + USER_ID: ObjectIdentifier = ... + DOMAIN_COMPONENT: ObjectIdentifier = ... + EMAIL_ADDRESS: ObjectIdentifier = ... + JURISDICTION_COUNTRY_NAME: ObjectIdentifier = ... + JURISDICTION_LOCALITY_NAME: ObjectIdentifier = ... + JURISDICTION_STATE_OR_PROVINCE_NAME: ObjectIdentifier = ... + BUSINESS_CATEGORY: ObjectIdentifier = ... + POSTAL_ADDRESS: ObjectIdentifier = ... + POSTAL_CODE: ObjectIdentifier = ... + +class SignatureAlgorithmOID: + RSA_WITH_MD5: ObjectIdentifier = ... + RSA_WITH_SHA1: ObjectIdentifier = ... + _RSA_WITH_SHA1: ObjectIdentifier = ... + RSA_WITH_SHA224: ObjectIdentifier = ... + RSA_WITH_SHA256: ObjectIdentifier = ... + RSA_WITH_SHA384: ObjectIdentifier = ... + RSA_WITH_SHA512: ObjectIdentifier = ... + RSASSA_PSS: ObjectIdentifier = ... + ECDSA_WITH_SHA1: ObjectIdentifier = ... + ECDSA_WITH_SHA224: ObjectIdentifier = ... + ECDSA_WITH_SHA256: ObjectIdentifier = ... + ECDSA_WITH_SHA384: ObjectIdentifier = ... + ECDSA_WITH_SHA512: ObjectIdentifier = ... + DSA_WITH_SHA1: ObjectIdentifier = ... + DSA_WITH_SHA224: ObjectIdentifier = ... + DSA_WITH_SHA256: ObjectIdentifier = ... + ED25519: ObjectIdentifier = ... + ED448: ObjectIdentifier = ... + +class ExtendedKeyUsageOID: + SERVER_AUTH: ObjectIdentifier = ... + CLIENT_AUTH: ObjectIdentifier = ... + CODE_SIGNING: ObjectIdentifier = ... + EMAIL_PROTECTION: ObjectIdentifier = ... + TIME_STAMPING: ObjectIdentifier = ... + OCSP_SIGNING: ObjectIdentifier = ... + ANY_EXTENDED_KEY_USAGE: ObjectIdentifier = ... + +class AuthorityInformationAccessOID: + CA_ISSUERS: ObjectIdentifier = ... + OCSP: ObjectIdentifier = ... + +class CertificatePoliciesOID: + CPS_QUALIFIER: ObjectIdentifier = ... + CPS_USER_NOTICE: ObjectIdentifier = ... + ANY_POLICY: ObjectIdentifier = ... + +_OID_NAMES: Dict[ObjectIdentifier, str] = ... + +_SIG_OIDS_TO_HASH: Dict[ObjectIdentifier, Optional[HashAlgorithm]] = ... diff --git a/shared/package-files/78/787ab9c57bc0344b72d73ddd9d7c7317a150819a32df698971ce578a95ec8ee4/blob b/shared/package-files/78/787ab9c57bc0344b72d73ddd9d7c7317a150819a32df698971ce578a95ec8ee4/blob new file mode 100644 index 0000000000000000000000000000000000000000..64e0f46663c8b3b95fb919c395c9f1a1496bf5e4 --- /dev/null +++ b/shared/package-files/78/787ab9c57bc0344b72d73ddd9d7c7317a150819a32df698971ce578a95ec8ee4/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _version { + using schema = int64_t (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_version") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_version(Tensor self) -> int") + static int64_t call(const at::Tensor & self); + static int64_t redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/787fadc52db3ab51dd3694ddf4b71951c548c1ec0088d53482b9aae708ca9ce9/blob b/shared/package-files/78/787fadc52db3ab51dd3694ddf4b71951c548c1ec0088d53482b9aae708ca9ce9/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b98fca7233be6dd9324cd2b6d71b6a8ac91a6cb --- /dev/null +++ b/shared/package-files/78/787fadc52db3ab51dd3694ddf4b71951c548c1ec0088d53482b9aae708ca9ce9/blob @@ -0,0 +1,252 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import operator +import os +import platform +import sys +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +from ._parser import ( + MarkerAtom, + MarkerList, + Op, + Value, + Variable, + parse_marker as _parse_marker, +) +from ._tokenizer import ParserSyntaxError +from .specifiers import InvalidSpecifier, Specifier +from .utils import canonicalize_name + +__all__ = [ + "InvalidMarker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "Marker", + "default_environment", +] + +Operator = Callable[[str, str], bool] + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +def _normalize_extra_values(results: Any) -> Any: + """ + Normalize extra values. + """ + if isinstance(results[0], tuple): + lhs, op, rhs = results[0] + if isinstance(lhs, Variable) and lhs.value == "extra": + normalized_extra = canonicalize_name(rhs.value) + rhs = Value(normalized_extra) + elif isinstance(rhs, Variable) and rhs.value == "extra": + normalized_extra = canonicalize_name(lhs.value) + lhs = Value(normalized_extra) + results[0] = lhs, op, rhs + return results + + +def _format_marker( + marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True +) -> str: + + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: Dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _eval_op(lhs: str, op: Op, rhs: str) -> bool: + try: + spec = Specifier("".join([op.serialize(), rhs])) + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Optional[Operator] = _operators.get(op.serialize()) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize(*values: str, key: str) -> Tuple[str, ...]: + # PEP 685 – Comparison of extra names for optional distribution dependencies + # https://peps.python.org/pep-0685/ + # > When comparing extra names, tools MUST normalize the names being + # > compared using the semantics outlined in PEP 503 for names + if key == "extra": + return tuple(canonicalize_name(v) for v in values) + + # other environment markers don't have such standards + return values + + +def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool: + groups: List[List[bool]] = [[]] + + for marker in markers: + assert isinstance(marker, (list, tuple, str)) + + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + environment_key = lhs.value + lhs_value = environment[environment_key] + rhs_value = rhs.value + else: + lhs_value = lhs.value + environment_key = rhs.value + rhs_value = environment[environment_key] + + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value)) + else: + assert marker in ["and", "or"] + if marker == "or": + groups.append([]) + + return any(all(item) for item in groups) + + +def format_full_version(info: "sys._version_info") -> str: + version = "{0.major}.{0.minor}.{0.micro}".format(info) + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Dict[str, str]: + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + def __init__(self, marker: str) -> None: + # Note: We create a Marker object without calling this constructor in + # packaging.requirements.Requirement. If any additional logic is + # added here, make sure to mirror/adapt Requirement. + try: + self._markers = _normalize_extra_values(_parse_marker(marker)) + # The attribute `_markers` can be described in terms of a recursive type: + # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] + # + # For example, the following expression: + # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") + # + # is parsed into: + # [ + # (, ')>, ), + # 'and', + # [ + # (, , ), + # 'or', + # (, , ) + # ] + # ] + except ParserSyntaxError as e: + raise InvalidMarker(str(e)) from e + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash((self.__class__.__name__, str(self))) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. + + The environment is determined from the current Python process. + """ + current_environment = default_environment() + current_environment["extra"] = "" + if environment is not None: + current_environment.update(environment) + # The API used to allow setting extra to None. We need to handle this + # case for backwards compatibility. + if current_environment["extra"] is None: + current_environment["extra"] = "" + + return _evaluate_markers(self._markers, current_environment) diff --git a/shared/package-files/78/7880365af0ae58a5d50491067d6a09ae7e967d4b215ff357b6daeb7f22db3672/blob b/shared/package-files/78/7880365af0ae58a5d50491067d6a09ae7e967d4b215ff357b6daeb7f22db3672/blob new file mode 100644 index 0000000000000000000000000000000000000000..bc95004ef5ba4421927289a049a9197d208c30d0 --- /dev/null +++ b/shared/package-files/78/7880365af0ae58a5d50491067d6a09ae7e967d4b215ff357b6daeb7f22db3672/blob @@ -0,0 +1,155 @@ +from sympy.concrete.summations import Sum +from sympy.core.basic import Basic +from sympy.core.function import (Derivative, Function, count_ops) +from sympy.core.numbers import (I, Rational, pi) +from sympy.core.relational import (Eq, Rel) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.integrals.integrals import Integral +from sympy.logic.boolalg import (And, Equivalent, ITE, Implies, Nand, + Nor, Not, Or, Xor) +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.core.containers import Tuple + +x, y, z = symbols('x,y,z') +a, b, c = symbols('a,b,c') + +def test_count_ops_non_visual(): + def count(val): + return count_ops(val, visual=False) + assert count(x) == 0 + assert count(x) is not S.Zero + assert count(x + y) == 1 + assert count(x + y) is not S.One + assert count(x + y*x + 2*y) == 4 + assert count({x + y: x}) == 1 + assert count({x + y: S(2) + x}) is not S.One + assert count(x < y) == 1 + assert count(Or(x,y)) == 1 + assert count(And(x,y)) == 1 + assert count(Not(x)) == 1 + assert count(Nor(x,y)) == 2 + assert count(Nand(x,y)) == 2 + assert count(Xor(x,y)) == 1 + assert count(Implies(x,y)) == 1 + assert count(Equivalent(x,y)) == 1 + assert count(ITE(x,y,z)) == 1 + assert count(ITE(True,x,y)) == 0 + + +def test_count_ops_visual(): + ADD, MUL, POW, SIN, COS, EXP, AND, D, G, M = symbols( + 'Add Mul Pow sin cos exp And Derivative Integral Sum'.upper()) + DIV, SUB, NEG = symbols('DIV SUB NEG') + LT, LE, GT, GE, EQ, NE = symbols('LT LE GT GE EQ NE') + NOT, OR, AND, XOR, IMPLIES, EQUIVALENT, _ITE, BASIC, TUPLE = symbols( + 'Not Or And Xor Implies Equivalent ITE Basic Tuple'.upper()) + + def count(val): + return count_ops(val, visual=True) + + assert count(7) is S.Zero + assert count(S(7)) is S.Zero + assert count(-1) == NEG + assert count(-2) == NEG + assert count(S(2)/3) == DIV + assert count(Rational(2, 3)) == DIV + assert count(pi/3) == DIV + assert count(-pi/3) == DIV + NEG + assert count(I - 1) == SUB + assert count(1 - I) == SUB + assert count(1 - 2*I) == SUB + MUL + + assert count(x) is S.Zero + assert count(-x) == NEG + assert count(-2*x/3) == NEG + DIV + MUL + assert count(Rational(-2, 3)*x) == NEG + DIV + MUL + assert count(1/x) == DIV + assert count(1/(x*y)) == DIV + MUL + assert count(-1/x) == NEG + DIV + assert count(-2/x) == NEG + DIV + assert count(x/y) == DIV + assert count(-x/y) == NEG + DIV + + assert count(x**2) == POW + assert count(-x**2) == POW + NEG + assert count(-2*x**2) == POW + MUL + NEG + + assert count(x + pi/3) == ADD + DIV + assert count(x + S.One/3) == ADD + DIV + assert count(x + Rational(1, 3)) == ADD + DIV + assert count(x + y) == ADD + assert count(x - y) == SUB + assert count(y - x) == SUB + assert count(-1/(x - y)) == DIV + NEG + SUB + assert count(-1/(y - x)) == DIV + NEG + SUB + assert count(1 + x**y) == ADD + POW + assert count(1 + x + y) == 2*ADD + assert count(1 + x + y + z) == 3*ADD + assert count(1 + x**y + 2*x*y + y**2) == 3*ADD + 2*POW + 2*MUL + assert count(2*z + y + x + 1) == 3*ADD + MUL + assert count(2*z + y**17 + x + 1) == 3*ADD + MUL + POW + assert count(2*z + y**17 + x + sin(x)) == 3*ADD + POW + MUL + SIN + assert count(2*z + y**17 + x + sin(x**2)) == 3*ADD + MUL + 2*POW + SIN + assert count(2*z + y**17 + x + sin( + x**2) + exp(cos(x))) == 4*ADD + MUL + 2*POW + EXP + COS + SIN + + assert count(Derivative(x, x)) == D + assert count(Integral(x, x) + 2*x/(1 + x)) == G + DIV + MUL + 2*ADD + assert count(Sum(x, (x, 1, x + 1)) + 2*x/(1 + x)) == M + DIV + MUL + 3*ADD + assert count(Basic()) is S.Zero + + assert count({x + 1: sin(x)}) == ADD + SIN + assert count([x + 1, sin(x) + y, None]) == ADD + SIN + ADD + assert count({x + 1: sin(x), y: cos(x) + 1}) == SIN + COS + 2*ADD + assert count({}) is S.Zero + assert count([x + 1, sin(x)*y, None]) == SIN + ADD + MUL + assert count([]) is S.Zero + + assert count(Basic()) == 0 + assert count(Basic(Basic(),Basic(x,x+y))) == ADD + 2*BASIC + assert count(Basic(x, x + y)) == ADD + BASIC + assert [count(Rel(x, y, op)) for op in '< <= > >= == <> !='.split() + ] == [LT, LE, GT, GE, EQ, NE, NE] + assert count(Or(x, y)) == OR + assert count(And(x, y)) == AND + assert count(Or(x, Or(y, And(z, a)))) == AND + OR + assert count(Nor(x, y)) == NOT + OR + assert count(Nand(x, y)) == NOT + AND + assert count(Xor(x, y)) == XOR + assert count(Implies(x, y)) == IMPLIES + assert count(Equivalent(x, y)) == EQUIVALENT + assert count(ITE(x, y, z)) == _ITE + assert count([Or(x, y), And(x, y), Basic(x + y)] + ) == ADD + AND + BASIC + OR + + assert count(Basic(Tuple(x))) == BASIC + TUPLE + #It checks that TUPLE is counted as an operation. + + assert count(Eq(x + y, S(2))) == ADD + EQ + + +def test_issue_9324(): + def count(val): + return count_ops(val, visual=False) + + M = MatrixSymbol('M', 10, 10) + assert count(M[0, 0]) == 0 + assert count(2 * M[0, 0] + M[5, 7]) == 2 + P = MatrixSymbol('P', 3, 3) + Q = MatrixSymbol('Q', 3, 3) + assert count(P + Q) == 1 + m = Symbol('m', integer=True) + n = Symbol('n', integer=True) + M = MatrixSymbol('M', m + n, m * m) + assert count(M[0, 1]) == 2 + + +def test_issue_21532(): + f = Function('f') + g = Function('g') + FUNC_F, FUNC_G = symbols('FUNC_F, FUNC_G') + assert f(x).count_ops(visual=True) == FUNC_F + assert g(x).count_ops(visual=True) == FUNC_G diff --git a/shared/package-files/78/7880835e6e22052550ad65e6540b065b452a32634c059e2b3260fe294cf2c31a/blob b/shared/package-files/78/7880835e6e22052550ad65e6540b065b452a32634c059e2b3260fe294cf2c31a/blob new file mode 100644 index 0000000000000000000000000000000000000000..2a923a8fa6098844b8b9604e50689b49230deb22 --- /dev/null +++ b/shared/package-files/78/7880835e6e22052550ad65e6540b065b452a32634c059e2b3260fe294cf2c31a/blob @@ -0,0 +1,14 @@ +executing-0.8.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +executing-0.8.3.dist-info/LICENSE.txt,sha256=pHaiyw70xBRQNApXeii5GsTH9mkTay7hSAR_q9X8QYE,1066 +executing-0.8.3.dist-info/METADATA,sha256=9cDby4bm9FfHuYdf1fznJVKAgF3RAENFgLr7-RnqhtM,8597 +executing-0.8.3.dist-info/RECORD,, +executing-0.8.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +executing-0.8.3.dist-info/WHEEL,sha256=z9j0xAa_JmUKMpmz72K0ZGALSM_n-wQVmGbleXx2VHg,110 +executing-0.8.3.dist-info/direct_url.json,sha256=vthDmeIxwJPmoEAjGNAePBfQObXvYFJ6k8-W0iQZd4s,83 +executing-0.8.3.dist-info/top_level.txt,sha256=b9Rtf3NtSqc0_Kak6L_lvnbdKPA0GUim2p-XcFQsf5g,10 +executing/__init__.py,sha256=Pg1QmduUZW5T4YTSYyTLYIwID1JlYT_0OvJyFFAeQxU,734 +executing/__pycache__/__init__.cpython-310.pyc,, +executing/__pycache__/executing.cpython-310.pyc,, +executing/__pycache__/version.cpython-310.pyc,, +executing/executing.py,sha256=VP1imbHdCpANyzJ1_IhSmGOsn8BqA6ZCDdY-ncY69hg,38172 +executing/version.py,sha256=iYWnlaVVD03FdK4GtciVxyyZbZmAwXDhMxbBYbc8RjU,21 diff --git a/shared/package-files/78/7881e1803d48a9d5d4d5f11326d20f815167318082cc5cc3261eec175698d835/blob b/shared/package-files/78/7881e1803d48a9d5d4d5f11326d20f815167318082cc5cc3261eec175698d835/blob new file mode 100644 index 0000000000000000000000000000000000000000..e74fe9958df09309c40d6c7e8a9d33c3efb3acee --- /dev/null +++ b/shared/package-files/78/7881e1803d48a9d5d4d5f11326d20f815167318082cc5cc3261eec175698d835/blob @@ -0,0 +1,13 @@ +*** Sat, 3 Sep 2016 22:34:58 *** +TEST FOR GRANGER-CAUSALITY: +H0: "realcons, realgdp" do not Granger-cause "realinv" + +Test statistic l = 15.6399 +pval-F( l; 8, 546) = 0.0000 + +TEST FOR INSTANTANEOUS CAUSALITY: +H0: No instantaneous causality between "realcons, realgdp" and "realinv" + +Test statistic: c = 79.9025 +pval-Chi( c; 2) = 0.0000 + diff --git a/shared/package-files/78/7882841731309021613c5d064e67fa48bbb15d3dfce06a9d0899e188bd94d014/blob b/shared/package-files/78/7882841731309021613c5d064e67fa48bbb15d3dfce06a9d0899e188bd94d014/blob new file mode 100644 index 0000000000000000000000000000000000000000..8466392ac930f13f2419c9c04eef9dcc2884e9bd --- /dev/null +++ b/shared/package-files/78/7882841731309021613c5d064e67fa48bbb15d3dfce06a9d0899e188bd94d014/blob @@ -0,0 +1,15 @@ +import sympy.physics.mechanics as _me +import sympy as _sm +import math as m +import numpy as _np + +f = _sm.S(3) +g = _sm.S(9.81) +a, b = _sm.symbols('a b', real=True) +s, s1 = _sm.symbols('s s1', real=True) +s2, s3 = _sm.symbols('s2 s3', real=True, nonnegative=True) +s4 = _sm.symbols('s4', real=True, nonpositive=True) +k1, k2, k3, k4, l1, l2, l3, p11, p12, p13, p21, p22, p23 = _sm.symbols('k1 k2 k3 k4 l1 l2 l3 p11 p12 p13 p21 p22 p23', real=True) +c11, c12, c13, c21, c22, c23 = _sm.symbols('c11 c12 c13 c21 c22 c23', real=True) +e1 = a*f+s2-g +e2 = f**2+k3*k2*g diff --git a/shared/package-files/78/7882f9a6ba9691c81204c1b1364e37029cb133cf6eec46067d3e0b98e8de0d30/blob b/shared/package-files/78/7882f9a6ba9691c81204c1b1364e37029cb133cf6eec46067d3e0b98e8de0d30/blob new file mode 100644 index 0000000000000000000000000000000000000000..3ea527481ca98f5ac8c812df152b809c30eff10a --- /dev/null +++ b/shared/package-files/78/7882f9a6ba9691c81204c1b1364e37029cb133cf6eec46067d3e0b98e8de0d30/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API linalg_svdvals { + using schema = at::Tensor (const at::Tensor &, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_svdvals") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_svdvals(Tensor A, *, str? driver=None) -> Tensor") + static at::Tensor call(const at::Tensor & A, c10::optional driver); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, c10::optional driver); +}; + +struct TORCH_API linalg_svdvals_out { + using schema = at::Tensor & (const at::Tensor &, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_svdvals") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_svdvals.out(Tensor A, *, str? driver=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & A, c10::optional driver, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, c10::optional driver, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/78843ab5ac5ce8411fed406634a684a2cd4064e8049ce6934d6b63b57e547c71/blob b/shared/package-files/78/78843ab5ac5ce8411fed406634a684a2cd4064e8049ce6934d6b63b57e547c71/blob new file mode 100644 index 0000000000000000000000000000000000000000..0d2111f05cc7d9be58387888e513426bd1ebc76d Binary files /dev/null and b/shared/package-files/78/78843ab5ac5ce8411fed406634a684a2cd4064e8049ce6934d6b63b57e547c71/blob differ diff --git a/shared/package-files/78/78884fae900185e433db5584f38e542e579393cddee04b499c44b88c02d6ea63/blob b/shared/package-files/78/78884fae900185e433db5584f38e542e579393cddee04b499c44b88c02d6ea63/blob new file mode 100644 index 0000000000000000000000000000000000000000..d72e8f7d74d51659b67355c2bdf6b7a107102b75 --- /dev/null +++ b/shared/package-files/78/78884fae900185e433db5584f38e542e579393cddee04b499c44b88c02d6ea63/blob @@ -0,0 +1,132 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/filesystem/filesystem.h" + +namespace arrow { +namespace internal { + +class Uri; + +} + +namespace fs { + +/// Options for the LocalFileSystem implementation. +struct ARROW_EXPORT LocalFileSystemOptions { + static constexpr int32_t kDefaultDirectoryReadahead = 16; + static constexpr int32_t kDefaultFileInfoBatchSize = 1000; + + /// Whether OpenInputStream and OpenInputFile return a mmap'ed file, + /// or a regular one. + bool use_mmap = false; + + /// Options related to `GetFileInfoGenerator` interface. + + /// EXPERIMENTAL: The maximum number of directories processed in parallel + /// by `GetFileInfoGenerator`. + int32_t directory_readahead = kDefaultDirectoryReadahead; + + /// EXPERIMENTAL: The maximum number of entries aggregated into each + /// FileInfoVector chunk by `GetFileInfoGenerator`. + /// + /// Since each FileInfo entry needs a separate `stat` system call, a + /// directory with a very large number of files may take a lot of time to + /// process entirely. By generating a FileInfoVector after this chunk + /// size is reached, we ensure FileInfo entries can start being consumed + /// from the FileInfoGenerator with less initial latency. + int32_t file_info_batch_size = kDefaultFileInfoBatchSize; + + /// \brief Initialize with defaults + static LocalFileSystemOptions Defaults(); + + bool Equals(const LocalFileSystemOptions& other) const; + + static Result FromUri(const ::arrow::util::Uri& uri, + std::string* out_path); +}; + +/// \brief A FileSystem implementation accessing files on the local machine. +/// +/// This class handles only `/`-separated paths. If desired, conversion +/// from Windows backslash-separated paths should be done by the caller. +/// Details such as symlinks are abstracted away (symlinks are always +/// followed, except when deleting an entry). +class ARROW_EXPORT LocalFileSystem : public FileSystem { + public: + explicit LocalFileSystem(const io::IOContext& = io::default_io_context()); + explicit LocalFileSystem(const LocalFileSystemOptions&, + const io::IOContext& = io::default_io_context()); + ~LocalFileSystem() override; + + std::string type_name() const override { return "local"; } + + Result NormalizePath(std::string path) override; + Result PathFromUri(const std::string& uri_string) const override; + Result MakeUri(std::string path) const override; + + bool Equals(const FileSystem& other) const override; + + LocalFileSystemOptions options() const { return options_; } + + /// \cond FALSE + using FileSystem::CreateDir; + using FileSystem::DeleteDirContents; + using FileSystem::GetFileInfo; + using FileSystem::OpenAppendStream; + using FileSystem::OpenOutputStream; + /// \endcond + + Result GetFileInfo(const std::string& path) override; + Result> GetFileInfo(const FileSelector& select) override; + FileInfoGenerator GetFileInfoGenerator(const FileSelector& select) override; + + Status CreateDir(const std::string& path, bool recursive) override; + + Status DeleteDir(const std::string& path) override; + Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override; + Status DeleteRootDirContents() override; + + Status DeleteFile(const std::string& path) override; + + Status Move(const std::string& src, const std::string& dest) override; + + Status CopyFile(const std::string& src, const std::string& dest) override; + + Result> OpenInputStream( + const std::string& path) override; + Result> OpenInputFile( + const std::string& path) override; + Result> OpenOutputStream( + const std::string& path, + const std::shared_ptr& metadata) override; + Result> OpenAppendStream( + const std::string& path, + const std::shared_ptr& metadata) override; + + protected: + LocalFileSystemOptions options_; +}; + +} // namespace fs +} // namespace arrow diff --git a/shared/package-files/78/78892dfdf7bc753f6d0715c552a7f90449ba1d98916d92abc57ead71b5d7a328/blob b/shared/package-files/78/78892dfdf7bc753f6d0715c552a7f90449ba1d98916d92abc57ead71b5d7a328/blob new file mode 100644 index 0000000000000000000000000000000000000000..deb235f3906890896614a5b4d77caa0275c85f21 --- /dev/null +++ b/shared/package-files/78/78892dfdf7bc753f6d0715c552a7f90449ba1d98916d92abc57ead71b5d7a328/blob @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_clamp_max_out : public at::meta::structured_clamp_max { +void impl(const at::Tensor & self, const at::Scalar & max, const at::Tensor & out); +}; +struct TORCH_API structured_clamp_max_Tensor_out : public at::meta::structured_clamp_max_Tensor { +void impl(const at::Tensor & self, const at::Tensor & max, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/78/788dc44c9cc20a15ed4af8b7c70d0657daa71611ec1b3ed57378dde07c3bd1ba/blob b/shared/package-files/78/788dc44c9cc20a15ed4af8b7c70d0657daa71611ec1b3ed57378dde07c3bd1ba/blob new file mode 100644 index 0000000000000000000000000000000000000000..a4dc3a16860b88db41f96097d51e24eec9a0e2dd Binary files /dev/null and b/shared/package-files/78/788dc44c9cc20a15ed4af8b7c70d0657daa71611ec1b3ed57378dde07c3bd1ba/blob differ diff --git a/shared/package-files/78/788e5af2e920edbcc93754796d971a467d916218fb240d0acfe07cde805f1137/blob b/shared/package-files/78/788e5af2e920edbcc93754796d971a467d916218fb240d0acfe07cde805f1137/blob new file mode 100644 index 0000000000000000000000000000000000000000..7f1ed3db998c1a7ca5b31ae5423832fcf154e761 --- /dev/null +++ b/shared/package-files/78/788e5af2e920edbcc93754796d971a467d916218fb240d0acfe07cde805f1137/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple batch_norm_backward_reduce_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const c10::optional & weight, bool input_g, bool weight_g, bool bias_g); +TORCH_API ::std::tuple batch_norm_backward_reduce_outf(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const c10::optional & weight, bool input_g, bool weight_g, bool bias_g, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/78/788eb5d677d7c194866c373f293bfea0af3012c816316403a4fee5c8f168cc7e/blob b/shared/package-files/78/788eb5d677d7c194866c373f293bfea0af3012c816316403a4fee5c8f168cc7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..2611b0d81e9b300259303bb5b6c20c50e88243c1 --- /dev/null +++ b/shared/package-files/78/788eb5d677d7c194866c373f293bfea0af3012c816316403a4fee5c8f168cc7e/blob @@ -0,0 +1,97 @@ +import inspect +from typing import Dict, List, Union + +from torch import _C +from torch.onnx import _constants +from torch.onnx._internal import registration + + +class _TorchSchema: + def __init__(self, schema: Union[_C.FunctionSchema, str]) -> None: + if isinstance(schema, _C.FunctionSchema): + self.name: str = schema.name + self.overload_name: str = schema.overload_name + self.arguments: List[str] = [arg.name for arg in schema.arguments] + self.optional_arguments: List[str] = [] + self.returns: List[str] = [ret.name for ret in schema.returns] + self.opsets: List[int] = [] + else: + self.name = schema + self.overload_name = "" + self.arguments = [] + self.optional_arguments = [] + self.returns = [] + self.opsets = [] + + def __str__(self) -> str: + s = ( + f"{self.name}.{self.overload_name}(" + + ", ".join(self.arguments) + + ") -> (" + + ", ".join(self.returns) + + ")" + + " in opsets " + + ", ".join(str(opset) for opset in self.opsets) + ) + return s + + def __hash__(self): + # TODO(thiagocrepaldi): handle overload_name? + return hash(self.name) + + def __eq__(self, other) -> bool: + if not isinstance(other, _TorchSchema): + return False + # TODO(thiagocrepaldi): handle overload_name? + return self.name == other.name + + def is_aten(self) -> bool: + return self.name.startswith("aten::") + + def is_backward(self) -> bool: + return "backward" in self.name + + +def _symbolic_argument_count(func): + params = [] + signature = inspect.signature(func) + optional_params = [] + for name, parameter in signature.parameters.items(): + if name in {"_outputs", "g"}: + continue + if parameter.default is parameter.empty: + optional_params.append(parameter) + else: + params.append(str(parameter)) + return params + + +def all_forward_schemas() -> Dict[str, _TorchSchema]: + """Returns schemas for all TorchScript forward ops.""" + torch_schemas = [_TorchSchema(s) for s in _C._jit_get_all_schemas()] + return {schema.name: schema for schema in torch_schemas if not schema.is_backward()} + + +def all_symbolics_schemas() -> Dict[str, _TorchSchema]: + """Returns schemas for all onnx supported ops.""" + symbolics_schemas = {} + + for name in registration.registry.all_functions(): + func_group = registration.registry.get_function_group(name) + assert func_group is not None + symbolics_schema = _TorchSchema(name) + func = func_group.get(_constants.ONNX_MAX_OPSET) + if func is not None: + symbolics_schema.arguments = _symbolic_argument_count(func) + symbolics_schema.opsets = list( + range(func_group.get_min_supported(), _constants.ONNX_MAX_OPSET + 1) + ) + else: + # Only support opset < 9 + func = func_group.get(7) + symbolics_schema.arguments = _symbolic_argument_count(func) + symbolics_schema.opsets = list(range(7, _constants.ONNX_BASE_OPSET)) + + symbolics_schemas[name] = symbolics_schema + + return symbolics_schemas diff --git a/shared/package-files/78/788fe85e53724a40b299051c4abc9cf74d42b27e7968325b80891c25f79adb4b/blob b/shared/package-files/78/788fe85e53724a40b299051c4abc9cf74d42b27e7968325b80891c25f79adb4b/blob new file mode 100644 index 0000000000000000000000000000000000000000..dcec4760996be2143d28a12718adc8f9e050bf29 --- /dev/null +++ b/shared/package-files/78/788fe85e53724a40b299051c4abc9cf74d42b27e7968325b80891c25f79adb4b/blob @@ -0,0 +1,27 @@ +Copyright (c) 2016, Gregory Szorc +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/shared/package-files/78/7891a0f502a12ce53a953714c1b15c8b4f54ed1f26daed6b2218dfff0942f5f9/blob b/shared/package-files/78/7891a0f502a12ce53a953714c1b15c8b4f54ed1f26daed6b2218dfff0942f5f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..ce50d61345e05742017d1a337c68bf56dcaffd22 --- /dev/null +++ b/shared/package-files/78/7891a0f502a12ce53a953714c1b15c8b4f54ed1f26daed6b2218dfff0942f5f9/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::vector _foreach_log1p(at::TensorList self); +TORCH_API void _foreach_log1p_(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/78/7892be1960f628c3dfb7def0b4099c8686068efb591a3ac4b2e5a0dcadc61069/blob b/shared/package-files/78/7892be1960f628c3dfb7def0b4099c8686068efb591a3ac4b2e5a0dcadc61069/blob new file mode 100644 index 0000000000000000000000000000000000000000..ac7215b46c1483f171584b48691d6794434e3e3f --- /dev/null +++ b/shared/package-files/78/7892be1960f628c3dfb7def0b4099c8686068efb591a3ac4b2e5a0dcadc61069/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API int64_t _cufft_get_plan_cache_size(at::DeviceIndex device_index); +} // namespace native +} // namespace at diff --git a/shared/package-files/78/7893434e53ffa81cf1b0ff916fa42e3336892bdc3af465bd2561ac04a247d684/blob b/shared/package-files/78/7893434e53ffa81cf1b0ff916fa42e3336892bdc3af465bd2561ac04a247d684/blob new file mode 100644 index 0000000000000000000000000000000000000000..158498ff957cbd42c55901ca6a02a4a087c50d12 --- /dev/null +++ b/shared/package-files/78/7893434e53ffa81cf1b0ff916fa42e3336892bdc3af465bd2561ac04a247d684/blob @@ -0,0 +1,45 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::squeeze(Tensor(a) self) -> Tensor(a) +inline at::Tensor squeeze(const at::Tensor & self) { + return at::_ops::squeeze::call(self); +} + +// aten::squeeze.dim(Tensor(a) self, int dim) -> Tensor(a) +inline at::Tensor squeeze(const at::Tensor & self, int64_t dim) { + return at::_ops::squeeze_dim::call(self, dim); +} + +// aten::squeeze.dimname(Tensor(a) self, Dimname dim) -> Tensor(a) +inline at::Tensor squeeze(const at::Tensor & self, at::Dimname dim) { + return at::_ops::squeeze_dimname::call(self, dim); +} + +// aten::squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a) +inline at::Tensor squeeze(const at::Tensor & self, at::IntArrayRef dim) { + return at::_ops::squeeze_dims::call(self, dim); +} + +} diff --git a/shared/package-files/78/78936e57f0866e3f80c2a8eb1aeae97c8e988a790bb0c7cc72e41da464317627/blob b/shared/package-files/78/78936e57f0866e3f80c2a8eb1aeae97c8e988a790bb0c7cc72e41da464317627/blob new file mode 100644 index 0000000000000000000000000000000000000000..7add774680483876342f5803f760aa1c9851c794 --- /dev/null +++ b/shared/package-files/78/78936e57f0866e3f80c2a8eb1aeae97c8e988a790bb0c7cc72e41da464317627/blob @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API index_select_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_select") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_select.out(Tensor self, int dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, int64_t dim, const at::Tensor & index, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, at::Tensor & out); +}; + +struct TORCH_API index_select { + using schema = at::Tensor (const at::Tensor &, int64_t, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_select") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_select(Tensor self, int dim, Tensor index) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t dim, const at::Tensor & index); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index); +}; + +struct TORCH_API index_select_dimname_out { + using schema = at::Tensor & (const at::Tensor &, at::Dimname, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_select") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dimname_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_select.dimname_out(Tensor self, Dimname dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, const at::Tensor & index, at::Tensor & out); +}; + +struct TORCH_API index_select_dimname { + using schema = at::Tensor (const at::Tensor &, at::Dimname, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_select") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dimname") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_select.dimname(Tensor self, Dimname dim, Tensor index) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::Dimname dim, const at::Tensor & index); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, const at::Tensor & index); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/789536c6198ff7c96cf5204616ba4a540b4287101c3c791d17cd8604d531bdac/blob b/shared/package-files/78/789536c6198ff7c96cf5204616ba4a540b4287101c3c791d17cd8604d531bdac/blob new file mode 100644 index 0000000000000000000000000000000000000000..258e54266477c6b3cab695cb4214f7c71f5315d5 --- /dev/null +++ b/shared/package-files/78/789536c6198ff7c96cf5204616ba4a540b4287101c3c791d17cd8604d531bdac/blob @@ -0,0 +1,242 @@ +import functools +import itertools +import logging +from typing import List, Optional +from unittest.mock import patch + +import sympy + +import torch +from ...autotune_process import CUDABenchmarkRequest, TensorMeta +from ...ir import Buffer, CUDATemplateBuffer, IRNode, Layout + +from ...utils import IndentedBuffer, unique +from ...virtualized import V +from ..common import KernelTemplate +from .cuda_kernel import CUDATemplateCaller, CUDATemplateKernel + +log = logging.getLogger(__name__) + + +class CUDATemplate(KernelTemplate): + index_counter = itertools.count() + + def __init__( + self, + name: str, + input_nodes: List[Buffer], + layout: Layout, + input_reorder: Optional[List[int]] = None, + ): + """ + + Baseclass for CUDA C++ Templates, derived from KernelTemplate. Not to be instantiated directly. + + Args: + name (str): The name of the CUDATemplate object. + input_nodes (List[IRNode]): A list of input IRNodes. + layout (Layout): The layout of the output buffer / tensor. + input_reorder (Optional[List[int]]): An optional list that specifies the order of the input nodes. + + """ + super().__init__(name) + self.input_nodes = input_nodes + self.output_node: Buffer = Buffer("buf_out", layout) + self.input_reorder = input_reorder + self.layout = layout + + def generate( # type: ignore[override] + self, + **kwargs, + ) -> CUDATemplateCaller: + """ + Generates the CUDA template caller object for the given GEMM template and operation. This CUDATemplateCaller + may be used to call and benchmark the generated CUDA kernel in a standalone manner to enable Autotuning. + + Args: + kwargs: Additional keyword arguments. + + Returns: + A CUDATemplateCaller object representing the generated CUDA template caller. + """ + kernel_name = f"cuda_{self.name}" + with patch.object( + V.graph, "get_dtype", self._fake_get_dtype(self.output_node) + ), CUDATemplateKernel( + kernel_name=kernel_name, + ) as kernel: + code = self.render(kernel=kernel, **kwargs) + _, call_args, _ = kernel.args.python_argdefs() + log.debug("Generated Code:\n%s", code) + log.debug( + "Args: cpp_argdefs: %s, python_argdefs: %s", + kernel.args.cpp_argdefs(), + kernel.args.python_argdefs(), + ) + + input_reorder = ( + self.input_reorder + if self.input_reorder is not None + else list(range(len(self.input_nodes))) + ) + expected_args = list( + unique(self.input_nodes[idx].get_name() for idx in input_reorder) + ) + expected_args.extend([self.output_node.get_name()]) + assert list(call_args)[: len(expected_args)] == expected_args, ( + call_args, + expected_args, + ) + extra_args = V.graph.sizevars.size_hints( + map(sympy.expand, call_args[len(expected_args) :]) + ) + + kernel_hash_name = f"cuda_{self.name}_{next(self.index_counter)}" + + # create the BenchmarkRequest + bmreq = CUDABenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(self.output_node), + extra_args=extra_args, + source_code=code, + ) + + def make_kernel_render( + template_node: CUDATemplateBuffer, + epilogue_nodes: Optional[List[IRNode]] = None, + ): + kernel = CUDATemplateKernel( + kernel_name="KERNEL_NAME", + ) + render = functools.partial( + self.render, + kernel=kernel, + template_buffer_node=template_node, + epilogue_nodes=epilogue_nodes, + **kwargs, # includes "op" argument in case of CUTLASSGemmTemplate + ) + return kernel, render + + return CUDATemplateCaller( + kernel_hash_name, + self.name, + self.input_nodes, + self.output_node.get_layout(), + make_kernel_render, + bmreq, + self, + kwargs, + ) + + def header(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + #include + #include + #include + #include + #include + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + // We compile all models with -fvisibility=hidden. Any symbols that need to be + // exposed in the final shared library must be declared with PT_EXPORT to make + // them visible. + #ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++) + #define PT_EXPORT __attribute__((__visibility__("default"))) + #else + #ifdef _WIN32 + #define PT_EXPORT __declspec(dllexport) + #else + #define PT_EXPORT + #endif + #endif + using bfloat16 = nv_bfloat16; + """ + ) + return res + + def render(self, **kwargs) -> str: + raise NotImplementedError + + +class CUTLASSTemplate(CUDATemplate): + """ + CUTLASSTemplate is a class that provides a template for generating CUTLASS Templates. Used as a baseclass for the + CUTLASSGemmTemplate, providing functionality that might also be relevant for non-GEMM CUTLASS Kernels. + """ + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + #include "cute/tensor.hpp" + #include "cutlass/cutlass.h" + #include "cutlass/numeric_types.h" + #include "cutlass/tensor_ref.h" + #include "cutlass/util/host_tensor.h" + #include "cutlass/util/reference/host/tensor_fill.h" + #include "cutlass/util/reference/device/tensor_fill.h" + #include "cutlass/util/device_memory.h" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + using namespace cute; + #define CUTLASS_CHECK(status) \\ + { \\ + cutlass::Status error = status; \\ + if (error != cutlass::Status::kSuccess) { \\ + auto msg = std::string("[") + __FILE__ + "] Got cutlass error: " + \\ + cutlassGetStatusString(error) + " at: " + std::to_string(__LINE__); \\ + throw std::runtime_error(msg); \\ + } \\ + } + + // Used as pass-through functor in EVT just for type casting / rounding + template + struct identity_op { + CUTLASS_HOST_DEVICE + T operator()(T val) const { return val; } + }; + + """ + ) + return res + + def cute_int(self, int_str: str, var_name: str) -> str: + res = "" + if int_str in {"1", "1L"}: + res = "cute::Int<1>{}" + else: + res = int_str + + return f"{res} /* {var_name} */" + + _DTYPE_TO_CUTLASS = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "cutlass::half_t", + torch.int32: "int", + torch.int8: "int8_t", + torch.uint8: "uint8_t", + torch.bool: "bool", + torch.bfloat16: "cutlass::bfloat16_t", + } + + def cutlass_type_cast(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._DTYPE_TO_CUTLASS.get(node.get_dtype())}*)({ptr})" diff --git a/shared/package-files/78/7897353636d44e061b8553be0af75f61544a0fb8e1786c0f40aba2826fdb15f3/blob b/shared/package-files/78/7897353636d44e061b8553be0af75f61544a0fb8e1786c0f40aba2826fdb15f3/blob new file mode 100644 index 0000000000000000000000000000000000000000..1a776892b7bb754e16aaa34e6dbe281b354ee751 --- /dev/null +++ b/shared/package-files/78/7897353636d44e061b8553be0af75f61544a0fb8e1786c0f40aba2826fdb15f3/blob @@ -0,0 +1,1739 @@ +from datetime import datetime +import warnings + +import numpy as np +import pytest + +from pandas.compat import is_platform_arm + +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas as pd +from pandas import ( + DataFrame, + MultiIndex, + Series, + Timestamp, + date_range, +) +import pandas._testing as tm +from pandas.tests.frame.common import zip_frames +from pandas.util.version import Version + + +@pytest.fixture +def int_frame_const_col(): + """ + Fixture for DataFrame of ints which are constant per column + + Columns are ['A', 'B', 'C'], with values (per column): [1, 2, 3] + """ + df = DataFrame( + np.tile(np.arange(3, dtype="int64"), 6).reshape(6, -1) + 1, + columns=["A", "B", "C"], + ) + return df + + +@pytest.fixture(params=["python", pytest.param("numba", marks=pytest.mark.single_cpu)]) +def engine(request): + if request.param == "numba": + pytest.importorskip("numba") + return request.param + + +def test_apply(float_frame, engine, request): + if engine == "numba": + mark = pytest.mark.xfail(reason="numba engine not supporting numpy ufunc yet") + request.node.add_marker(mark) + with np.errstate(all="ignore"): + # ufunc + result = np.sqrt(float_frame["A"]) + expected = float_frame.apply(np.sqrt, engine=engine)["A"] + tm.assert_series_equal(result, expected) + + # aggregator + result = float_frame.apply(np.mean, engine=engine)["A"] + expected = np.mean(float_frame["A"]) + assert result == expected + + d = float_frame.index[0] + result = float_frame.apply(np.mean, axis=1, engine=engine) + expected = np.mean(float_frame.xs(d)) + assert result[d] == expected + assert result.index is float_frame.index + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("raw", [True, False]) +def test_apply_args(float_frame, axis, raw, engine, request): + if engine == "numba": + numba = pytest.importorskip("numba") + if Version(numba.__version__) == Version("0.61") and is_platform_arm(): + pytest.skip(f"Segfaults on ARM platforms with numba {numba.__version__}") + mark = pytest.mark.xfail(reason="numba engine doesn't support args") + request.node.add_marker(mark) + result = float_frame.apply( + lambda x, y: x + y, axis, args=(1,), raw=raw, engine=engine + ) + expected = float_frame + 1 + tm.assert_frame_equal(result, expected) + + +def test_apply_categorical_func(): + # GH 9573 + df = DataFrame({"c0": ["A", "A", "B", "B"], "c1": ["C", "C", "D", "D"]}) + result = df.apply(lambda ts: ts.astype("category")) + + assert result.shape == (4, 2) + assert isinstance(result["c0"].dtype, CategoricalDtype) + assert isinstance(result["c1"].dtype, CategoricalDtype) + + +def test_apply_axis1_with_ea(): + # GH#36785 + expected = DataFrame({"A": [Timestamp("2013-01-01", tz="UTC")]}) + result = expected.apply(lambda x: x, axis=1) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data, dtype", + [(1, None), (1, CategoricalDtype([1])), (Timestamp("2013-01-01", tz="UTC"), None)], +) +def test_agg_axis1_duplicate_index(data, dtype): + # GH 42380 + expected = DataFrame([[data], [data]], index=["a", "a"], dtype=dtype) + result = expected.agg(lambda x: x, axis=1) + tm.assert_frame_equal(result, expected) + + +def test_apply_mixed_datetimelike(): + # mixed datetimelike + # GH 7778 + expected = DataFrame( + { + "A": date_range("20130101", periods=3), + "B": pd.to_timedelta(np.arange(3), unit="s"), + } + ) + result = expected.apply(lambda x: x, axis=1) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", [np.sqrt, np.mean]) +def test_apply_empty(func, engine): + # empty + empty_frame = DataFrame() + + result = empty_frame.apply(func, engine=engine) + assert result.empty + + +def test_apply_float_frame(float_frame, engine): + no_rows = float_frame[:0] + result = no_rows.apply(lambda x: x.mean(), engine=engine) + expected = Series(np.nan, index=float_frame.columns) + tm.assert_series_equal(result, expected) + + no_cols = float_frame.loc[:, []] + result = no_cols.apply(lambda x: x.mean(), axis=1, engine=engine) + expected = Series(np.nan, index=float_frame.index) + tm.assert_series_equal(result, expected) + + +def test_apply_empty_except_index(engine): + # GH 2476 + expected = DataFrame(index=["a"]) + result = expected.apply(lambda x: x["a"], axis=1, engine=engine) + tm.assert_frame_equal(result, expected) + + +def test_apply_with_reduce_empty(): + # reduce with an empty DataFrame + empty_frame = DataFrame() + + x = [] + result = empty_frame.apply(x.append, axis=1, result_type="expand") + tm.assert_frame_equal(result, empty_frame) + result = empty_frame.apply(x.append, axis=1, result_type="reduce") + expected = Series([], dtype=np.float64) + tm.assert_series_equal(result, expected) + + empty_with_cols = DataFrame(columns=["a", "b", "c"]) + result = empty_with_cols.apply(x.append, axis=1, result_type="expand") + tm.assert_frame_equal(result, empty_with_cols) + result = empty_with_cols.apply(x.append, axis=1, result_type="reduce") + expected = Series([], dtype=np.float64) + tm.assert_series_equal(result, expected) + + # Ensure that x.append hasn't been called + assert x == [] + + +@pytest.mark.parametrize("func", ["sum", "prod", "any", "all"]) +def test_apply_funcs_over_empty(func): + # GH 28213 + df = DataFrame(columns=["a", "b", "c"]) + + result = df.apply(getattr(np, func)) + expected = getattr(df, func)() + if func in ("sum", "prod"): + expected = expected.astype(float) + tm.assert_series_equal(result, expected) + + +def test_nunique_empty(): + # GH 28213 + df = DataFrame(columns=["a", "b", "c"]) + + result = df.nunique() + expected = Series(0, index=df.columns) + tm.assert_series_equal(result, expected) + + result = df.T.nunique() + expected = Series([], dtype=np.float64) + tm.assert_series_equal(result, expected) + + +def test_apply_standard_nonunique(): + df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"]) + + result = df.apply(lambda s: s[0], axis=1) + expected = Series([1, 4, 7], ["a", "a", "c"]) + tm.assert_series_equal(result, expected) + + result = df.T.apply(lambda s: s[0], axis=0) + tm.assert_series_equal(result, expected) + + +def test_apply_broadcast_scalars(float_frame): + # scalars + result = float_frame.apply(np.mean, result_type="broadcast") + expected = DataFrame([float_frame.mean()], index=float_frame.index) + tm.assert_frame_equal(result, expected) + + +def test_apply_broadcast_scalars_axis1(float_frame): + result = float_frame.apply(np.mean, axis=1, result_type="broadcast") + m = float_frame.mean(axis=1) + expected = DataFrame({c: m for c in float_frame.columns}) + tm.assert_frame_equal(result, expected) + + +def test_apply_broadcast_lists_columns(float_frame): + # lists + result = float_frame.apply( + lambda x: list(range(len(float_frame.columns))), + axis=1, + result_type="broadcast", + ) + m = list(range(len(float_frame.columns))) + expected = DataFrame( + [m] * len(float_frame.index), + dtype="float64", + index=float_frame.index, + columns=float_frame.columns, + ) + tm.assert_frame_equal(result, expected) + + +def test_apply_broadcast_lists_index(float_frame): + result = float_frame.apply( + lambda x: list(range(len(float_frame.index))), result_type="broadcast" + ) + m = list(range(len(float_frame.index))) + expected = DataFrame( + {c: m for c in float_frame.columns}, + dtype="float64", + index=float_frame.index, + ) + tm.assert_frame_equal(result, expected) + + +def test_apply_broadcast_list_lambda_func(int_frame_const_col): + # preserve columns + df = int_frame_const_col + result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="broadcast") + tm.assert_frame_equal(result, df) + + +def test_apply_broadcast_series_lambda_func(int_frame_const_col): + df = int_frame_const_col + result = df.apply( + lambda x: Series([1, 2, 3], index=list("abc")), + axis=1, + result_type="broadcast", + ) + expected = df.copy() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_apply_raw_float_frame(float_frame, axis, engine): + if engine == "numba": + pytest.skip("numba can't handle when UDF returns None.") + + def _assert_raw(x): + assert isinstance(x, np.ndarray) + assert x.ndim == 1 + + float_frame.apply(_assert_raw, axis=axis, engine=engine, raw=True) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_apply_raw_float_frame_lambda(float_frame, axis, engine): + result = float_frame.apply(np.mean, axis=axis, engine=engine, raw=True) + expected = float_frame.apply(lambda x: x.values.mean(), axis=axis) + tm.assert_series_equal(result, expected) + + +def test_apply_raw_float_frame_no_reduction(float_frame, engine): + # no reduction + result = float_frame.apply(lambda x: x * 2, engine=engine, raw=True) + expected = float_frame * 2 + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +def test_apply_raw_mixed_type_frame(axis, engine): + if engine == "numba": + pytest.skip("isinstance check doesn't work with numba") + + def _assert_raw(x): + assert isinstance(x, np.ndarray) + assert x.ndim == 1 + + # Mixed dtype (GH-32423) + df = DataFrame( + { + "a": 1.0, + "b": 2, + "c": "foo", + "float32": np.array([1.0] * 10, dtype="float32"), + "int32": np.array([1] * 10, dtype="int32"), + }, + index=np.arange(10), + ) + df.apply(_assert_raw, axis=axis, engine=engine, raw=True) + + +def test_apply_axis1(float_frame): + d = float_frame.index[0] + result = float_frame.apply(np.mean, axis=1)[d] + expected = np.mean(float_frame.xs(d)) + assert result == expected + + +def test_apply_mixed_dtype_corner(): + df = DataFrame({"A": ["foo"], "B": [1.0]}) + result = df[:0].apply(np.mean, axis=1) + # the result here is actually kind of ambiguous, should it be a Series + # or a DataFrame? + expected = Series(np.nan, index=pd.Index([], dtype="int64")) + tm.assert_series_equal(result, expected) + + +def test_apply_mixed_dtype_corner_indexing(): + df = DataFrame({"A": ["foo"], "B": [1.0]}) + result = df.apply(lambda x: x["A"], axis=1) + expected = Series(["foo"], index=[0]) + tm.assert_series_equal(result, expected) + + result = df.apply(lambda x: x["B"], axis=1) + expected = Series([1.0], index=[0]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +@pytest.mark.parametrize("ax", ["index", "columns"]) +@pytest.mark.parametrize( + "func", [lambda x: x, lambda x: x.mean()], ids=["identity", "mean"] +) +@pytest.mark.parametrize("raw", [True, False]) +@pytest.mark.parametrize("axis", [0, 1]) +def test_apply_empty_infer_type(ax, func, raw, axis, engine, request): + df = DataFrame(**{ax: ["a", "b", "c"]}) + + with np.errstate(all="ignore"): + test_res = func(np.array([], dtype="f8")) + is_reduction = not isinstance(test_res, np.ndarray) + + result = df.apply(func, axis=axis, engine=engine, raw=raw) + if is_reduction: + agg_axis = df._get_agg_axis(axis) + assert isinstance(result, Series) + assert result.index is agg_axis + else: + assert isinstance(result, DataFrame) + + +def test_apply_empty_infer_type_broadcast(): + no_cols = DataFrame(index=["a", "b", "c"]) + result = no_cols.apply(lambda x: x.mean(), result_type="broadcast") + assert isinstance(result, DataFrame) + + +def test_apply_with_args_kwds_add_some(float_frame): + def add_some(x, howmuch=0): + return x + howmuch + + result = float_frame.apply(add_some, howmuch=2) + expected = float_frame.apply(lambda x: x + 2) + tm.assert_frame_equal(result, expected) + + +def test_apply_with_args_kwds_agg_and_add(float_frame): + def agg_and_add(x, howmuch=0): + return x.mean() + howmuch + + result = float_frame.apply(agg_and_add, howmuch=2) + expected = float_frame.apply(lambda x: x.mean() + 2) + tm.assert_series_equal(result, expected) + + +def test_apply_with_args_kwds_subtract_and_divide(float_frame): + def subtract_and_divide(x, sub, divide=1): + return (x - sub) / divide + + result = float_frame.apply(subtract_and_divide, args=(2,), divide=2) + expected = float_frame.apply(lambda x: (x - 2.0) / 2.0) + tm.assert_frame_equal(result, expected) + + +def test_apply_yield_list(float_frame): + result = float_frame.apply(list) + tm.assert_frame_equal(result, float_frame) + + +def test_apply_reduce_Series(float_frame): + float_frame.iloc[::2, float_frame.columns.get_loc("A")] = np.nan + expected = float_frame.mean(1) + result = float_frame.apply(np.mean, axis=1) + tm.assert_series_equal(result, expected) + + +def test_apply_reduce_to_dict(): + # GH 25196 37544 + data = DataFrame([[1, 2], [3, 4]], columns=["c0", "c1"], index=["i0", "i1"]) + + result = data.apply(dict, axis=0) + expected = Series([{"i0": 1, "i1": 3}, {"i0": 2, "i1": 4}], index=data.columns) + tm.assert_series_equal(result, expected) + + result = data.apply(dict, axis=1) + expected = Series([{"c0": 1, "c1": 2}, {"c0": 3, "c1": 4}], index=data.index) + tm.assert_series_equal(result, expected) + + +def test_apply_differently_indexed(): + df = DataFrame(np.random.default_rng(2).standard_normal((20, 10))) + + result = df.apply(Series.describe, axis=0) + expected = DataFrame({i: v.describe() for i, v in df.items()}, columns=df.columns) + tm.assert_frame_equal(result, expected) + + result = df.apply(Series.describe, axis=1) + expected = DataFrame({i: v.describe() for i, v in df.T.items()}, columns=df.index).T + tm.assert_frame_equal(result, expected) + + +def test_apply_bug(): + # GH 6125 + positions = DataFrame( + [ + [1, "ABC0", 50], + [1, "YUM0", 20], + [1, "DEF0", 20], + [2, "ABC1", 50], + [2, "YUM1", 20], + [2, "DEF1", 20], + ], + columns=["a", "market", "position"], + ) + + def f(r): + return r["market"] + + expected = positions.apply(f, axis=1) + + positions = DataFrame( + [ + [datetime(2013, 1, 1), "ABC0", 50], + [datetime(2013, 1, 2), "YUM0", 20], + [datetime(2013, 1, 3), "DEF0", 20], + [datetime(2013, 1, 4), "ABC1", 50], + [datetime(2013, 1, 5), "YUM1", 20], + [datetime(2013, 1, 6), "DEF1", 20], + ], + columns=["a", "market", "position"], + ) + result = positions.apply(f, axis=1) + tm.assert_series_equal(result, expected) + + +def test_apply_convert_objects(): + expected = DataFrame( + { + "A": [ + "foo", + "foo", + "foo", + "foo", + "bar", + "bar", + "bar", + "bar", + "foo", + "foo", + "foo", + ], + "B": [ + "one", + "one", + "one", + "two", + "one", + "one", + "one", + "two", + "two", + "two", + "one", + ], + "C": [ + "dull", + "dull", + "shiny", + "dull", + "dull", + "shiny", + "shiny", + "dull", + "shiny", + "shiny", + "shiny", + ], + "D": np.random.default_rng(2).standard_normal(11), + "E": np.random.default_rng(2).standard_normal(11), + "F": np.random.default_rng(2).standard_normal(11), + } + ) + + result = expected.apply(lambda x: x, axis=1) + tm.assert_frame_equal(result, expected) + + +def test_apply_attach_name(float_frame): + result = float_frame.apply(lambda x: x.name) + expected = Series(float_frame.columns, index=float_frame.columns) + tm.assert_series_equal(result, expected) + + +def test_apply_attach_name_axis1(float_frame): + result = float_frame.apply(lambda x: x.name, axis=1) + expected = Series(float_frame.index, index=float_frame.index) + tm.assert_series_equal(result, expected) + + +def test_apply_attach_name_non_reduction(float_frame): + # non-reductions + result = float_frame.apply(lambda x: np.repeat(x.name, len(x))) + expected = DataFrame( + np.tile(float_frame.columns, (len(float_frame.index), 1)), + index=float_frame.index, + columns=float_frame.columns, + ) + tm.assert_frame_equal(result, expected) + + +def test_apply_attach_name_non_reduction_axis1(float_frame): + result = float_frame.apply(lambda x: np.repeat(x.name, len(x)), axis=1) + expected = Series( + np.repeat(t[0], len(float_frame.columns)) for t in float_frame.itertuples() + ) + expected.index = float_frame.index + tm.assert_series_equal(result, expected) + + +def test_apply_multi_index(): + index = MultiIndex.from_arrays([["a", "a", "b"], ["c", "d", "d"]]) + s = DataFrame([[1, 2], [3, 4], [5, 6]], index=index, columns=["col1", "col2"]) + result = s.apply(lambda x: Series({"min": min(x), "max": max(x)}), 1) + expected = DataFrame([[1, 2], [3, 4], [5, 6]], index=index, columns=["min", "max"]) + tm.assert_frame_equal(result, expected, check_like=True) + + +@pytest.mark.parametrize( + "df, dicts", + [ + [ + DataFrame([["foo", "bar"], ["spam", "eggs"]]), + Series([{0: "foo", 1: "spam"}, {0: "bar", 1: "eggs"}]), + ], + [DataFrame([[0, 1], [2, 3]]), Series([{0: 0, 1: 2}, {0: 1, 1: 3}])], + ], +) +def test_apply_dict(df, dicts): + # GH 8735 + fn = lambda x: x.to_dict() + reduce_true = df.apply(fn, result_type="reduce") + reduce_false = df.apply(fn, result_type="expand") + reduce_none = df.apply(fn) + + tm.assert_series_equal(reduce_true, dicts) + tm.assert_frame_equal(reduce_false, df) + tm.assert_series_equal(reduce_none, dicts) + + +def test_apply_non_numpy_dtype(): + # GH 12244 + df = DataFrame({"dt": date_range("2015-01-01", periods=3, tz="Europe/Brussels")}) + result = df.apply(lambda x: x) + tm.assert_frame_equal(result, df) + + result = df.apply(lambda x: x + pd.Timedelta("1day")) + expected = DataFrame( + {"dt": date_range("2015-01-02", periods=3, tz="Europe/Brussels")} + ) + tm.assert_frame_equal(result, expected) + + +def test_apply_non_numpy_dtype_category(): + df = DataFrame({"dt": ["a", "b", "c", "a"]}, dtype="category") + result = df.apply(lambda x: x) + tm.assert_frame_equal(result, df) + + +def test_apply_dup_names_multi_agg(): + # GH 21063 + df = DataFrame([[0, 1], [2, 3]], columns=["a", "a"]) + expected = DataFrame([[0, 1]], columns=["a", "a"], index=["min"]) + result = df.agg(["min"]) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("op", ["apply", "agg"]) +def test_apply_nested_result_axis_1(op): + # GH 13820 + def apply_list(row): + return [2 * row["A"], 2 * row["C"], 2 * row["B"]] + + df = DataFrame(np.zeros((4, 4)), columns=list("ABCD")) + result = getattr(df, op)(apply_list, axis=1) + expected = Series( + [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] + ) + tm.assert_series_equal(result, expected) + + +def test_apply_noreduction_tzaware_object(): + # https://github.com/pandas-dev/pandas/issues/31505 + expected = DataFrame( + {"foo": [Timestamp("2020", tz="UTC")]}, dtype="datetime64[ns, UTC]" + ) + result = expected.apply(lambda x: x) + tm.assert_frame_equal(result, expected) + result = expected.apply(lambda x: x.copy()) + tm.assert_frame_equal(result, expected) + + +def test_apply_function_runs_once(): + # https://github.com/pandas-dev/pandas/issues/30815 + + df = DataFrame({"a": [1, 2, 3]}) + names = [] # Save row names function is applied to + + def reducing_function(row): + names.append(row.name) + + def non_reducing_function(row): + names.append(row.name) + return row + + for func in [reducing_function, non_reducing_function]: + del names[:] + + df.apply(func, axis=1) + assert names == list(df.index) + + +def test_apply_raw_function_runs_once(engine): + # https://github.com/pandas-dev/pandas/issues/34506 + if engine == "numba": + pytest.skip("appending to list outside of numba func is not supported") + + df = DataFrame({"a": [1, 2, 3]}) + values = [] # Save row values function is applied to + + def reducing_function(row): + values.extend(row) + + def non_reducing_function(row): + values.extend(row) + return row + + for func in [reducing_function, non_reducing_function]: + del values[:] + + df.apply(func, engine=engine, raw=True, axis=1) + assert values == list(df.a.to_list()) + + +def test_apply_with_byte_string(): + # GH 34529 + df = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"]) + expected = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"], dtype=object) + # After we make the apply we expect a dataframe just + # like the original but with the object datatype + result = df.apply(lambda x: x.astype("object")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("val", ["asd", 12, None, np.nan]) +def test_apply_category_equalness(val): + # Check if categorical comparisons on apply, GH 21239 + df_values = ["asd", None, 12, "asd", "cde", np.nan] + df = DataFrame({"a": df_values}, dtype="category") + + result = df.a.apply(lambda x: x == val) + expected = Series( + [np.nan if pd.isnull(x) else x == val for x in df_values], name="a" + ) + tm.assert_series_equal(result, expected) + + +# the user has supplied an opaque UDF where +# they are transforming the input that requires +# us to infer the output + + +def test_infer_row_shape(): + # GH 17437 + # if row shape is changing, infer it + df = DataFrame(np.random.default_rng(2).random((10, 2))) + result = df.apply(np.fft.fft, axis=0).shape + assert result == (10, 2) + + result = df.apply(np.fft.rfft, axis=0).shape + assert result == (6, 2) + + +@pytest.mark.parametrize( + "ops, by_row, expected", + [ + ({"a": lambda x: x + 1}, "compat", DataFrame({"a": [2, 3]})), + ({"a": lambda x: x + 1}, False, DataFrame({"a": [2, 3]})), + ({"a": lambda x: x.sum()}, "compat", Series({"a": 3})), + ({"a": lambda x: x.sum()}, False, Series({"a": 3})), + ( + {"a": ["sum", np.sum, lambda x: x.sum()]}, + "compat", + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]), + ), + ( + {"a": ["sum", np.sum, lambda x: x.sum()]}, + False, + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]), + ), + ({"a": lambda x: 1}, "compat", DataFrame({"a": [1, 1]})), + ({"a": lambda x: 1}, False, Series({"a": 1})), + ], +) +def test_dictlike_lambda(ops, by_row, expected): + # GH53601 + df = DataFrame({"a": [1, 2]}) + result = df.apply(ops, by_row=by_row) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "ops", + [ + {"a": lambda x: x + 1}, + {"a": lambda x: x.sum()}, + {"a": ["sum", np.sum, lambda x: x.sum()]}, + {"a": lambda x: 1}, + ], +) +def test_dictlike_lambda_raises(ops): + # GH53601 + df = DataFrame({"a": [1, 2]}) + with pytest.raises(ValueError, match="by_row=True not allowed"): + df.apply(ops, by_row=True) + + +def test_with_dictlike_columns(): + # GH 17602 + df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1) + expected = Series([{"s": 3} for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + df["tm"] = [ + Timestamp("2017-05-01 00:00:00"), + Timestamp("2017-05-02 00:00:00"), + ] + result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1) + tm.assert_series_equal(result, expected) + + # compose a series + result = (df["a"] + df["b"]).apply(lambda x: {"s": x}) + expected = Series([{"s": 3}, {"s": 3}]) + tm.assert_series_equal(result, expected) + + +def test_with_dictlike_columns_with_datetime(): + # GH 18775 + df = DataFrame() + df["author"] = ["X", "Y", "Z"] + df["publisher"] = ["BBC", "NBC", "N24"] + df["date"] = pd.to_datetime( + ["17-10-2010 07:15:30", "13-05-2011 08:20:35", "15-01-2013 09:09:09"], + dayfirst=True, + ) + result = df.apply(lambda x: {}, axis=1) + expected = Series([{}, {}, {}]) + tm.assert_series_equal(result, expected) + + +def test_with_dictlike_columns_with_infer(): + # GH 17602 + df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) + result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand") + expected = DataFrame({"s": [3, 3]}) + tm.assert_frame_equal(result, expected) + + df["tm"] = [ + Timestamp("2017-05-01 00:00:00"), + Timestamp("2017-05-02 00:00:00"), + ] + result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "ops, by_row, expected", + [ + ([lambda x: x + 1], "compat", DataFrame({("a", ""): [2, 3]})), + ([lambda x: x + 1], False, DataFrame({("a", ""): [2, 3]})), + ([lambda x: x.sum()], "compat", DataFrame({"a": [3]}, index=[""])), + ([lambda x: x.sum()], False, DataFrame({"a": [3]}, index=[""])), + ( + ["sum", np.sum, lambda x: x.sum()], + "compat", + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]), + ), + ( + ["sum", np.sum, lambda x: x.sum()], + False, + DataFrame({"a": [3, 3, 3]}, index=["sum", "sum", ""]), + ), + ( + [lambda x: x + 1, lambda x: 3], + "compat", + DataFrame([[2, 3], [3, 3]], columns=[["a", "a"], ["", ""]]), + ), + ( + [lambda x: 2, lambda x: 3], + False, + DataFrame({"a": [2, 3]}, ["", ""]), + ), + ], +) +def test_listlike_lambda(ops, by_row, expected): + # GH53601 + df = DataFrame({"a": [1, 2]}) + result = df.apply(ops, by_row=by_row) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "ops", + [ + [lambda x: x + 1], + [lambda x: x.sum()], + ["sum", np.sum, lambda x: x.sum()], + [lambda x: x + 1, lambda x: 3], + ], +) +def test_listlike_lambda_raises(ops): + # GH53601 + df = DataFrame({"a": [1, 2]}) + with pytest.raises(ValueError, match="by_row=True not allowed"): + df.apply(ops, by_row=True) + + +def test_with_listlike_columns(): + # GH 17348 + df = DataFrame( + { + "a": Series(np.random.default_rng(2).standard_normal(4)), + "b": ["a", "list", "of", "words"], + "ts": date_range("2016-10-01", periods=4, freq="h"), + } + ) + + result = df[["a", "b"]].apply(tuple, axis=1) + expected = Series([t[1:] for t in df[["a", "b"]].itertuples()]) + tm.assert_series_equal(result, expected) + + result = df[["a", "ts"]].apply(tuple, axis=1) + expected = Series([t[1:] for t in df[["a", "ts"]].itertuples()]) + tm.assert_series_equal(result, expected) + + +def test_with_listlike_columns_returning_list(): + # GH 18919 + df = DataFrame({"x": Series([["a", "b"], ["q"]]), "y": Series([["z"], ["q", "t"]])}) + df.index = MultiIndex.from_tuples([("i0", "j0"), ("i1", "j1")]) + + result = df.apply(lambda row: [el for el in row["x"] if el in row["y"]], axis=1) + expected = Series([[], ["q"]], index=df.index) + tm.assert_series_equal(result, expected) + + +def test_infer_output_shape_columns(): + # GH 18573 + + df = DataFrame( + { + "number": [1.0, 2.0], + "string": ["foo", "bar"], + "datetime": [ + Timestamp("2017-11-29 03:30:00"), + Timestamp("2017-11-29 03:45:00"), + ], + } + ) + result = df.apply(lambda row: (row.number, row.string), axis=1) + expected = Series([(t.number, t.string) for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + +def test_infer_output_shape_listlike_columns(): + # GH 16353 + + df = DataFrame( + np.random.default_rng(2).standard_normal((6, 3)), columns=["A", "B", "C"] + ) + + result = df.apply(lambda x: [1, 2, 3], axis=1) + expected = Series([[1, 2, 3] for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + result = df.apply(lambda x: [1, 2], axis=1) + expected = Series([[1, 2] for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("val", [1, 2]) +def test_infer_output_shape_listlike_columns_np_func(val): + # GH 17970 + df = DataFrame({"a": [1, 2, 3]}, index=list("abc")) + + result = df.apply(lambda row: np.ones(val), axis=1) + expected = Series([np.ones(val) for t in df.itertuples()], index=df.index) + tm.assert_series_equal(result, expected) + + +def test_infer_output_shape_listlike_columns_with_timestamp(): + # GH 17892 + df = DataFrame( + { + "a": [ + Timestamp("2010-02-01"), + Timestamp("2010-02-04"), + Timestamp("2010-02-05"), + Timestamp("2010-02-06"), + ], + "b": [9, 5, 4, 3], + "c": [5, 3, 4, 2], + "d": [1, 2, 3, 4], + } + ) + + def fun(x): + return (1, 2) + + result = df.apply(fun, axis=1) + expected = Series([(1, 2) for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("lst", [[1, 2, 3], [1, 2]]) +def test_consistent_coerce_for_shapes(lst): + # we want column names to NOT be propagated + # just because the shape matches the input shape + df = DataFrame( + np.random.default_rng(2).standard_normal((4, 3)), columns=["A", "B", "C"] + ) + + result = df.apply(lambda x: lst, axis=1) + expected = Series([lst for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + +def test_consistent_names(int_frame_const_col): + # if a Series is returned, we should use the resulting index names + df = int_frame_const_col + + result = df.apply( + lambda x: Series([1, 2, 3], index=["test", "other", "cols"]), axis=1 + ) + expected = int_frame_const_col.rename( + columns={"A": "test", "B": "other", "C": "cols"} + ) + tm.assert_frame_equal(result, expected) + + result = df.apply(lambda x: Series([1, 2], index=["test", "other"]), axis=1) + expected = expected[["test", "other"]] + tm.assert_frame_equal(result, expected) + + +def test_result_type(int_frame_const_col): + # result_type should be consistent no matter which + # path we take in the code + df = int_frame_const_col + + result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="expand") + expected = df.copy() + expected.columns = [0, 1, 2] + tm.assert_frame_equal(result, expected) + + +def test_result_type_shorter_list(int_frame_const_col): + # result_type should be consistent no matter which + # path we take in the code + df = int_frame_const_col + result = df.apply(lambda x: [1, 2], axis=1, result_type="expand") + expected = df[["A", "B"]].copy() + expected.columns = [0, 1] + tm.assert_frame_equal(result, expected) + + +def test_result_type_broadcast(int_frame_const_col, request, engine): + # result_type should be consistent no matter which + # path we take in the code + if engine == "numba": + mark = pytest.mark.xfail(reason="numba engine doesn't support list return") + request.node.add_marker(mark) + df = int_frame_const_col + # broadcast result + result = df.apply( + lambda x: [1, 2, 3], axis=1, result_type="broadcast", engine=engine + ) + expected = df.copy() + tm.assert_frame_equal(result, expected) + + +def test_result_type_broadcast_series_func(int_frame_const_col, engine, request): + # result_type should be consistent no matter which + # path we take in the code + if engine == "numba": + mark = pytest.mark.xfail( + reason="numba Series constructor only support ndarrays not list data" + ) + request.node.add_marker(mark) + df = int_frame_const_col + columns = ["other", "col", "names"] + result = df.apply( + lambda x: Series([1, 2, 3], index=columns), + axis=1, + result_type="broadcast", + engine=engine, + ) + expected = df.copy() + tm.assert_frame_equal(result, expected) + + +def test_result_type_series_result(int_frame_const_col, engine, request): + # result_type should be consistent no matter which + # path we take in the code + if engine == "numba": + mark = pytest.mark.xfail( + reason="numba Series constructor only support ndarrays not list data" + ) + request.node.add_marker(mark) + df = int_frame_const_col + # series result + result = df.apply(lambda x: Series([1, 2, 3], index=x.index), axis=1, engine=engine) + expected = df.copy() + tm.assert_frame_equal(result, expected) + + +def test_result_type_series_result_other_index(int_frame_const_col, engine, request): + # result_type should be consistent no matter which + # path we take in the code + + if engine == "numba": + mark = pytest.mark.xfail( + reason="no support in numba Series constructor for list of columns" + ) + request.node.add_marker(mark) + df = int_frame_const_col + # series result with other index + columns = ["other", "col", "names"] + result = df.apply(lambda x: Series([1, 2, 3], index=columns), axis=1, engine=engine) + expected = df.copy() + expected.columns = columns + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "box", + [lambda x: list(x), lambda x: tuple(x), lambda x: np.array(x, dtype="int64")], + ids=["list", "tuple", "array"], +) +def test_consistency_for_boxed(box, int_frame_const_col): + # passing an array or list should not affect the output shape + df = int_frame_const_col + + result = df.apply(lambda x: box([1, 2]), axis=1) + expected = Series([box([1, 2]) for t in df.itertuples()]) + tm.assert_series_equal(result, expected) + + result = df.apply(lambda x: box([1, 2]), axis=1, result_type="expand") + expected = int_frame_const_col[["A", "B"]].rename(columns={"A": 0, "B": 1}) + tm.assert_frame_equal(result, expected) + + +def test_agg_transform(axis, float_frame): + other_axis = 1 if axis in {0, "index"} else 0 + + with np.errstate(all="ignore"): + f_abs = np.abs(float_frame) + f_sqrt = np.sqrt(float_frame) + + # ufunc + expected = f_sqrt.copy() + result = float_frame.apply(np.sqrt, axis=axis) + tm.assert_frame_equal(result, expected) + + # list-like + result = float_frame.apply([np.sqrt], axis=axis) + expected = f_sqrt.copy() + if axis in {0, "index"}: + expected.columns = MultiIndex.from_product([float_frame.columns, ["sqrt"]]) + else: + expected.index = MultiIndex.from_product([float_frame.index, ["sqrt"]]) + tm.assert_frame_equal(result, expected) + + # multiple items in list + # these are in the order as if we are applying both + # functions per series and then concatting + result = float_frame.apply([np.abs, np.sqrt], axis=axis) + expected = zip_frames([f_abs, f_sqrt], axis=other_axis) + if axis in {0, "index"}: + expected.columns = MultiIndex.from_product( + [float_frame.columns, ["absolute", "sqrt"]] + ) + else: + expected.index = MultiIndex.from_product( + [float_frame.index, ["absolute", "sqrt"]] + ) + tm.assert_frame_equal(result, expected) + + +def test_demo(): + # demonstration tests + df = DataFrame({"A": range(5), "B": 5}) + + result = df.agg(["min", "max"]) + expected = DataFrame( + {"A": [0, 4], "B": [5, 5]}, columns=["A", "B"], index=["min", "max"] + ) + tm.assert_frame_equal(result, expected) + + +def test_demo_dict_agg(): + # demonstration tests + df = DataFrame({"A": range(5), "B": 5}) + result = df.agg({"A": ["min", "max"], "B": ["sum", "max"]}) + expected = DataFrame( + {"A": [4.0, 0.0, np.nan], "B": [5.0, np.nan, 25.0]}, + columns=["A", "B"], + index=["max", "min", "sum"], + ) + tm.assert_frame_equal(result.reindex_like(expected), expected) + + +def test_agg_with_name_as_column_name(): + # GH 36212 - Column name is "name" + data = {"name": ["foo", "bar"]} + df = DataFrame(data) + + # result's name should be None + result = df.agg({"name": "count"}) + expected = Series({"name": 2}) + tm.assert_series_equal(result, expected) + + # Check if name is still preserved when aggregating series instead + result = df["name"].agg({"name": "count"}) + expected = Series({"name": 2}, name="name") + tm.assert_series_equal(result, expected) + + +def test_agg_multiple_mixed(): + # GH 20909 + mdf = DataFrame( + { + "A": [1, 2, 3], + "B": [1.0, 2.0, 3.0], + "C": ["foo", "bar", "baz"], + } + ) + expected = DataFrame( + { + "A": [1, 6], + "B": [1.0, 6.0], + "C": ["bar", "foobarbaz"], + }, + index=["min", "sum"], + ) + # sorted index + result = mdf.agg(["min", "sum"]) + tm.assert_frame_equal(result, expected) + + result = mdf[["C", "B", "A"]].agg(["sum", "min"]) + # GH40420: the result of .agg should have an index that is sorted + # according to the arguments provided to agg. + expected = expected[["C", "B", "A"]].reindex(["sum", "min"]) + tm.assert_frame_equal(result, expected) + + +def test_agg_multiple_mixed_raises(): + # GH 20909 + mdf = DataFrame( + { + "A": [1, 2, 3], + "B": [1.0, 2.0, 3.0], + "C": ["foo", "bar", "baz"], + "D": date_range("20130101", periods=3), + } + ) + + # sorted index + msg = "does not support reduction" + with pytest.raises(TypeError, match=msg): + mdf.agg(["min", "sum"]) + + with pytest.raises(TypeError, match=msg): + mdf[["D", "C", "B", "A"]].agg(["sum", "min"]) + + +def test_agg_reduce(axis, float_frame): + other_axis = 1 if axis in {0, "index"} else 0 + name1, name2 = float_frame.axes[other_axis].unique()[:2].sort_values() + + # all reducers + expected = pd.concat( + [ + float_frame.mean(axis=axis), + float_frame.max(axis=axis), + float_frame.sum(axis=axis), + ], + axis=1, + ) + expected.columns = ["mean", "max", "sum"] + expected = expected.T if axis in {0, "index"} else expected + + result = float_frame.agg(["mean", "max", "sum"], axis=axis) + tm.assert_frame_equal(result, expected) + + # dict input with scalars + func = {name1: "mean", name2: "sum"} + result = float_frame.agg(func, axis=axis) + expected = Series( + [ + float_frame.loc(other_axis)[name1].mean(), + float_frame.loc(other_axis)[name2].sum(), + ], + index=[name1, name2], + ) + tm.assert_series_equal(result, expected) + + # dict input with lists + func = {name1: ["mean"], name2: ["sum"]} + result = float_frame.agg(func, axis=axis) + expected = DataFrame( + { + name1: Series([float_frame.loc(other_axis)[name1].mean()], index=["mean"]), + name2: Series([float_frame.loc(other_axis)[name2].sum()], index=["sum"]), + } + ) + expected = expected.T if axis in {1, "columns"} else expected + tm.assert_frame_equal(result, expected) + + # dict input with lists with multiple + func = {name1: ["mean", "sum"], name2: ["sum", "max"]} + result = float_frame.agg(func, axis=axis) + expected = pd.concat( + { + name1: Series( + [ + float_frame.loc(other_axis)[name1].mean(), + float_frame.loc(other_axis)[name1].sum(), + ], + index=["mean", "sum"], + ), + name2: Series( + [ + float_frame.loc(other_axis)[name2].sum(), + float_frame.loc(other_axis)[name2].max(), + ], + index=["sum", "max"], + ), + }, + axis=1, + ) + expected = expected.T if axis in {1, "columns"} else expected + tm.assert_frame_equal(result, expected) + + +def test_nuiscance_columns(): + # GH 15015 + df = DataFrame( + { + "A": [1, 2, 3], + "B": [1.0, 2.0, 3.0], + "C": ["foo", "bar", "baz"], + "D": date_range("20130101", periods=3), + } + ) + + result = df.agg("min") + expected = Series([1, 1.0, "bar", Timestamp("20130101")], index=df.columns) + tm.assert_series_equal(result, expected) + + result = df.agg(["min"]) + expected = DataFrame( + [[1, 1.0, "bar", Timestamp("20130101").as_unit("ns")]], + index=["min"], + columns=df.columns, + ) + tm.assert_frame_equal(result, expected) + + msg = "does not support reduction" + with pytest.raises(TypeError, match=msg): + df.agg("sum") + + result = df[["A", "B", "C"]].agg("sum") + expected = Series([6, 6.0, "foobarbaz"], index=["A", "B", "C"]) + tm.assert_series_equal(result, expected) + + msg = "does not support reduction" + with pytest.raises(TypeError, match=msg): + df.agg(["sum"]) + + +@pytest.mark.parametrize("how", ["agg", "apply"]) +def test_non_callable_aggregates(how): + # GH 16405 + # 'size' is a property of frame/series + # validate that this is working + # GH 39116 - expand to apply + df = DataFrame( + {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]} + ) + + # Function aggregate + result = getattr(df, how)({"A": "count"}) + expected = Series({"A": 2}) + + tm.assert_series_equal(result, expected) + + # Non-function aggregate + result = getattr(df, how)({"A": "size"}) + expected = Series({"A": 3}) + + tm.assert_series_equal(result, expected) + + # Mix function and non-function aggs + result1 = getattr(df, how)(["count", "size"]) + result2 = getattr(df, how)( + {"A": ["count", "size"], "B": ["count", "size"], "C": ["count", "size"]} + ) + expected = DataFrame( + { + "A": {"count": 2, "size": 3}, + "B": {"count": 2, "size": 3}, + "C": {"count": 2, "size": 3}, + } + ) + + tm.assert_frame_equal(result1, result2, check_like=True) + tm.assert_frame_equal(result2, expected, check_like=True) + + # Just functional string arg is same as calling df.arg() + result = getattr(df, how)("count") + expected = df.count() + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("how", ["agg", "apply"]) +def test_size_as_str(how, axis): + # GH 39934 + df = DataFrame( + {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]} + ) + # Just a string attribute arg same as calling df.arg + # on the columns + result = getattr(df, how)("size", axis=axis) + if axis in (0, "index"): + expected = Series(df.shape[0], index=df.columns) + else: + expected = Series(df.shape[1], index=df.index) + tm.assert_series_equal(result, expected) + + +def test_agg_listlike_result(): + # GH-29587 user defined function returning list-likes + df = DataFrame({"A": [2, 2, 3], "B": [1.5, np.nan, 1.5], "C": ["foo", None, "bar"]}) + + def func(group_col): + return list(group_col.dropna().unique()) + + result = df.agg(func) + expected = Series([[2, 3], [1.5], ["foo", "bar"]], index=["A", "B", "C"]) + tm.assert_series_equal(result, expected) + + result = df.agg([func]) + expected = expected.to_frame("func").T + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize( + "args, kwargs", + [ + ((1, 2, 3), {}), + ((8, 7, 15), {}), + ((1, 2), {}), + ((1,), {"b": 2}), + ((), {"a": 1, "b": 2}), + ((), {"a": 2, "b": 1}), + ((), {"a": 1, "b": 2, "c": 3}), + ], +) +def test_agg_args_kwargs(axis, args, kwargs): + def f(x, a, b, c=3): + return x.sum() + (a + b) / c + + df = DataFrame([[1, 2], [3, 4]]) + + if axis == 0: + expected = Series([5.0, 7.0]) + else: + expected = Series([4.0, 8.0]) + + result = df.agg(f, axis, *args, **kwargs) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("num_cols", [2, 3, 5]) +def test_frequency_is_original(num_cols, engine, request): + # GH 22150 + if engine == "numba": + mark = pytest.mark.xfail(reason="numba engine only supports numeric indices") + request.node.add_marker(mark) + index = pd.DatetimeIndex(["1950-06-30", "1952-10-24", "1953-05-29"]) + original = index.copy() + df = DataFrame(1, index=index, columns=range(num_cols)) + df.apply(lambda x: x, engine=engine) + assert index.freq == original.freq + + +def test_apply_datetime_tz_issue(engine, request): + # GH 29052 + + if engine == "numba": + mark = pytest.mark.xfail( + reason="numba engine doesn't support non-numeric indexes" + ) + request.node.add_marker(mark) + + timestamps = [ + Timestamp("2019-03-15 12:34:31.909000+0000", tz="UTC"), + Timestamp("2019-03-15 12:34:34.359000+0000", tz="UTC"), + Timestamp("2019-03-15 12:34:34.660000+0000", tz="UTC"), + ] + df = DataFrame(data=[0, 1, 2], index=timestamps) + result = df.apply(lambda x: x.name, axis=1, engine=engine) + expected = Series(index=timestamps, data=timestamps) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("df", [DataFrame({"A": ["a", None], "B": ["c", "d"]})]) +@pytest.mark.parametrize("method", ["min", "max", "sum"]) +def test_mixed_column_raises(df, method, using_infer_string): + # GH 16832 + if method == "sum": + msg = r'can only concatenate str \(not "int"\) to str|does not support' + else: + msg = "not supported between instances of 'str' and 'float'" + if not using_infer_string: + with pytest.raises(TypeError, match=msg): + getattr(df, method)() + else: + getattr(df, method)() + + +@pytest.mark.parametrize("col", [1, 1.0, True, "a", np.nan]) +def test_apply_dtype(col): + # GH 31466 + df = DataFrame([[1.0, col]], columns=["a", "b"]) + result = df.apply(lambda x: x.dtype) + expected = df.dtypes + + tm.assert_series_equal(result, expected) + + +def test_apply_mutating(using_array_manager, using_copy_on_write, warn_copy_on_write): + # GH#35462 case where applied func pins a new BlockManager to a row + df = DataFrame({"a": range(100), "b": range(100, 200)}) + df_orig = df.copy() + + def func(row): + mgr = row._mgr + row.loc["a"] += 1 + assert row._mgr is not mgr + return row + + expected = df.copy() + expected["a"] += 1 + + with tm.assert_cow_warning(warn_copy_on_write): + result = df.apply(func, axis=1) + + tm.assert_frame_equal(result, expected) + if using_copy_on_write or using_array_manager: + # INFO(CoW) With copy on write, mutating a viewing row doesn't mutate the parent + # INFO(ArrayManager) With BlockManager, the row is a view and mutated in place, + # with ArrayManager the row is not a view, and thus not mutated in place + tm.assert_frame_equal(df, df_orig) + else: + tm.assert_frame_equal(df, result) + + +def test_apply_empty_list_reduce(): + # GH#35683 get columns correct + df = DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=["a", "b"]) + + result = df.apply(lambda x: [], result_type="reduce") + expected = Series({"a": [], "b": []}, dtype=object) + tm.assert_series_equal(result, expected) + + +def test_apply_no_suffix_index(engine, request): + # GH36189 + if engine == "numba": + mark = pytest.mark.xfail( + reason="numba engine doesn't support list-likes/dict-like callables" + ) + request.node.add_marker(mark) + pdf = DataFrame([[4, 9]] * 3, columns=["A", "B"]) + result = pdf.apply(["sum", lambda x: x.sum(), lambda x: x.sum()], engine=engine) + expected = DataFrame( + {"A": [12, 12, 12], "B": [27, 27, 27]}, index=["sum", "", ""] + ) + + tm.assert_frame_equal(result, expected) + + +def test_apply_raw_returns_string(engine): + # https://github.com/pandas-dev/pandas/issues/35940 + if engine == "numba": + pytest.skip("No object dtype support in numba") + df = DataFrame({"A": ["aa", "bbb"]}) + result = df.apply(lambda x: x[0], engine=engine, axis=1, raw=True) + expected = Series(["aa", "bbb"]) + tm.assert_series_equal(result, expected) + + +def test_aggregation_func_column_order(): + # GH40420: the result of .agg should have an index that is sorted + # according to the arguments provided to agg. + df = DataFrame( + [ + (1, 0, 0), + (2, 0, 0), + (3, 0, 0), + (4, 5, 4), + (5, 6, 6), + (6, 7, 7), + ], + columns=("att1", "att2", "att3"), + ) + + def sum_div2(s): + return s.sum() / 2 + + aggs = ["sum", sum_div2, "count", "min"] + result = df.agg(aggs) + expected = DataFrame( + { + "att1": [21.0, 10.5, 6.0, 1.0], + "att2": [18.0, 9.0, 6.0, 0.0], + "att3": [17.0, 8.5, 6.0, 0.0], + }, + index=["sum", "sum_div2", "count", "min"], + ) + tm.assert_frame_equal(result, expected) + + +def test_apply_getitem_axis_1(engine, request): + # GH 13427 + if engine == "numba": + mark = pytest.mark.xfail( + reason="numba engine not supporting duplicate index values" + ) + request.node.add_marker(mark) + df = DataFrame({"a": [0, 1, 2], "b": [1, 2, 3]}) + result = df[["a", "a"]].apply( + lambda x: x.iloc[0] + x.iloc[1], axis=1, engine=engine + ) + expected = Series([0, 2, 4]) + tm.assert_series_equal(result, expected) + + +def test_nuisance_depr_passes_through_warnings(): + # GH 43740 + # DataFrame.agg with list-likes may emit warnings for both individual + # args and for entire columns, but we only want to emit once. We + # catch and suppress the warnings for individual args, but need to make + # sure if some other warnings were raised, they get passed through to + # the user. + + def expected_warning(x): + warnings.warn("Hello, World!") + return x.sum() + + df = DataFrame({"a": [1, 2, 3]}) + with tm.assert_produces_warning(UserWarning, match="Hello, World!"): + df.agg([expected_warning]) + + +def test_apply_type(): + # GH 46719 + df = DataFrame( + {"col1": [3, "string", float], "col2": [0.25, datetime(2020, 1, 1), np.nan]}, + index=["a", "b", "c"], + ) + + # axis=0 + result = df.apply(type, axis=0) + expected = Series({"col1": Series, "col2": Series}) + tm.assert_series_equal(result, expected) + + # axis=1 + result = df.apply(type, axis=1) + expected = Series({"a": Series, "b": Series, "c": Series}) + tm.assert_series_equal(result, expected) + + +def test_apply_on_empty_dataframe(engine): + # GH 39111 + df = DataFrame({"a": [1, 2], "b": [3, 0]}) + result = df.head(0).apply(lambda x: max(x["a"], x["b"]), axis=1, engine=engine) + expected = Series([], dtype=np.float64) + tm.assert_series_equal(result, expected) + + +def test_apply_return_list(): + df = DataFrame({"a": [1, 2], "b": [2, 3]}) + result = df.apply(lambda x: [x.values]) + expected = DataFrame({"a": [[1, 2]], "b": [[2, 3]]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "test, constant", + [ + ({"a": [1, 2, 3], "b": [1, 1, 1]}, {"a": [1, 2, 3], "b": [1]}), + ({"a": [2, 2, 2], "b": [1, 1, 1]}, {"a": [2], "b": [1]}), + ], +) +def test_unique_agg_type_is_series(test, constant): + # GH#22558 + df1 = DataFrame(test) + expected = Series(data=constant, index=["a", "b"], dtype="object") + aggregation = {"a": "unique", "b": "unique"} + + result = df1.agg(aggregation) + + tm.assert_series_equal(result, expected) + + +def test_any_apply_keyword_non_zero_axis_regression(): + # https://github.com/pandas-dev/pandas/issues/48656 + df = DataFrame({"A": [1, 2, 0], "B": [0, 2, 0], "C": [0, 0, 0]}) + expected = Series([True, True, False]) + tm.assert_series_equal(df.any(axis=1), expected) + + result = df.apply("any", axis=1) + tm.assert_series_equal(result, expected) + + result = df.apply("any", 1) + tm.assert_series_equal(result, expected) + + +def test_agg_mapping_func_deprecated(): + # GH 53325 + df = DataFrame({"x": [1, 2, 3]}) + + def foo1(x, a=1, c=0): + return x + a + c + + def foo2(x, b=2, c=0): + return x + b + c + + # single func already takes the vectorized path + result = df.agg(foo1, 0, 3, c=4) + expected = df + 7 + tm.assert_frame_equal(result, expected) + + msg = "using .+ in Series.agg cannot aggregate and" + + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.agg([foo1, foo2], 0, 3, c=4) + expected = DataFrame( + [[8, 8], [9, 9], [10, 10]], columns=[["x", "x"], ["foo1", "foo2"]] + ) + tm.assert_frame_equal(result, expected) + + # TODO: the result below is wrong, should be fixed (GH53325) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.agg({"x": foo1}, 0, 3, c=4) + expected = DataFrame([2, 3, 4], columns=["x"]) + tm.assert_frame_equal(result, expected) + + +def test_agg_std(): + df = DataFrame(np.arange(6).reshape(3, 2), columns=["A", "B"]) + + with tm.assert_produces_warning(FutureWarning, match="using DataFrame.std"): + result = df.agg(np.std) + expected = Series({"A": 2.0, "B": 2.0}, dtype=float) + tm.assert_series_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match="using Series.std"): + result = df.agg([np.std]) + expected = DataFrame({"A": 2.0, "B": 2.0}, index=["std"]) + tm.assert_frame_equal(result, expected) + + +def test_agg_dist_like_and_nonunique_columns(): + # GH#51099 + df = DataFrame( + {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]} + ) + df.columns = ["A", "A", "C"] + + result = df.agg({"A": "count"}) + expected = df["A"].count() + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/78/789735636e568522c2e8e18d252170d2e03473a2d25207d34339b25ec5ea5688/blob b/shared/package-files/78/789735636e568522c2e8e18d252170d2e03473a2d25207d34339b25ec5ea5688/blob new file mode 100644 index 0000000000000000000000000000000000000000..88a9f8deb1abfaa82533eeb6308bbfbd5516ed4d --- /dev/null +++ b/shared/package-files/78/789735636e568522c2e8e18d252170d2e03473a2d25207d34339b25ec5ea5688/blob @@ -0,0 +1,231 @@ +"""Byrd-Omojokun Trust-Region SQP method.""" + +from scipy.sparse import eye as speye +from .projections import projections +from .qp_subproblem import modified_dogleg, projected_cg, box_intersections +import numpy as np +from numpy.linalg import norm + +__all__ = ['equality_constrained_sqp'] + + +def default_scaling(x): + n, = np.shape(x) + return speye(n) + + +def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess, + x0, fun0, grad0, constr0, + jac0, stop_criteria, + state, + initial_penalty, + initial_trust_radius, + factorization_method, + trust_lb=None, + trust_ub=None, + scaling=default_scaling): + """Solve nonlinear equality-constrained problem using trust-region SQP. + + Solve optimization problem: + + minimize fun(x) + subject to: constr(x) = 0 + + using Byrd-Omojokun Trust-Region SQP method described in [1]_. Several + implementation details are based on [2]_ and [3]_, p. 549. + + References + ---------- + .. [1] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. "On the + implementation of an algorithm for large-scale equality + constrained optimization." SIAM Journal on + Optimization 8.3 (1998): 682-706. + .. [2] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. + "An interior point algorithm for large-scale nonlinear + programming." SIAM Journal on Optimization 9.4 (1999): 877-900. + .. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization" + Second Edition (2006). + """ + PENALTY_FACTOR = 0.3 # Rho from formula (3.51), reference [2]_, p.891. + LARGE_REDUCTION_RATIO = 0.9 + INTERMEDIARY_REDUCTION_RATIO = 0.3 + SUFFICIENT_REDUCTION_RATIO = 1e-8 # Eta from reference [2]_, p.892. + TRUST_ENLARGEMENT_FACTOR_L = 7.0 + TRUST_ENLARGEMENT_FACTOR_S = 2.0 + MAX_TRUST_REDUCTION = 0.5 + MIN_TRUST_REDUCTION = 0.1 + SOC_THRESHOLD = 0.1 + TR_FACTOR = 0.8 # Zeta from formula (3.21), reference [2]_, p.885. + BOX_FACTOR = 0.5 + + n, = np.shape(x0) # Number of parameters + + # Set default lower and upper bounds. + if trust_lb is None: + trust_lb = np.full(n, -np.inf) + if trust_ub is None: + trust_ub = np.full(n, np.inf) + + # Initial values + x = np.copy(x0) + trust_radius = initial_trust_radius + penalty = initial_penalty + # Compute Values + f = fun0 + c = grad0 + b = constr0 + A = jac0 + S = scaling(x) + # Get projections + try: + Z, LS, Y = projections(A, factorization_method) + except ValueError as e: + if str(e) == "expected square matrix": + # can be the case if there are more equality + # constraints than independent variables + raise ValueError( + "The 'expected square matrix' error can occur if there are" + " more equality constraints than independent variables." + " Consider how your constraints are set up, or use" + " factorization_method='SVDFactorization'." + ) from e + else: + raise e + + # Compute least-square lagrange multipliers + v = -LS.dot(c) + # Compute Hessian + H = lagr_hess(x, v) + + # Update state parameters + optimality = norm(c + A.T.dot(v), np.inf) + constr_violation = norm(b, np.inf) if len(b) > 0 else 0 + cg_info = {'niter': 0, 'stop_cond': 0, + 'hits_boundary': False} + + last_iteration_failed = False + while not stop_criteria(state, x, last_iteration_failed, + optimality, constr_violation, + trust_radius, penalty, cg_info): + # Normal Step - `dn` + # minimize 1/2*||A dn + b||^2 + # subject to: + # ||dn|| <= TR_FACTOR * trust_radius + # BOX_FACTOR * lb <= dn <= BOX_FACTOR * ub. + dn = modified_dogleg(A, Y, b, + TR_FACTOR*trust_radius, + BOX_FACTOR*trust_lb, + BOX_FACTOR*trust_ub) + + # Tangential Step - `dt` + # Solve the QP problem: + # minimize 1/2 dt.T H dt + dt.T (H dn + c) + # subject to: + # A dt = 0 + # ||dt|| <= sqrt(trust_radius**2 - ||dn||**2) + # lb - dn <= dt <= ub - dn + c_t = H.dot(dn) + c + b_t = np.zeros_like(b) + trust_radius_t = np.sqrt(trust_radius**2 - np.linalg.norm(dn)**2) + lb_t = trust_lb - dn + ub_t = trust_ub - dn + dt, cg_info = projected_cg(H, c_t, Z, Y, b_t, + trust_radius_t, + lb_t, ub_t) + + # Compute update (normal + tangential steps). + d = dn + dt + + # Compute second order model: 1/2 d H d + c.T d + f. + quadratic_model = 1/2*(H.dot(d)).dot(d) + c.T.dot(d) + # Compute linearized constraint: l = A d + b. + linearized_constr = A.dot(d)+b + # Compute new penalty parameter according to formula (3.52), + # reference [2]_, p.891. + vpred = norm(b) - norm(linearized_constr) + # Guarantee `vpred` always positive, + # regardless of roundoff errors. + vpred = max(1e-16, vpred) + previous_penalty = penalty + if quadratic_model > 0: + new_penalty = quadratic_model / ((1-PENALTY_FACTOR)*vpred) + penalty = max(penalty, new_penalty) + # Compute predicted reduction according to formula (3.52), + # reference [2]_, p.891. + predicted_reduction = -quadratic_model + penalty*vpred + + # Compute merit function at current point + merit_function = f + penalty*norm(b) + # Evaluate function and constraints at trial point + x_next = x + S.dot(d) + f_next, b_next = fun_and_constr(x_next) + # Compute merit function at trial point + merit_function_next = f_next + penalty*norm(b_next) + # Compute actual reduction according to formula (3.54), + # reference [2]_, p.892. + actual_reduction = merit_function - merit_function_next + # Compute reduction ratio + reduction_ratio = actual_reduction / predicted_reduction + + # Second order correction (SOC), reference [2]_, p.892. + if reduction_ratio < SUFFICIENT_REDUCTION_RATIO and \ + norm(dn) <= SOC_THRESHOLD * norm(dt): + # Compute second order correction + y = -Y.dot(b_next) + # Make sure increment is inside box constraints + _, t, intersect = box_intersections(d, y, trust_lb, trust_ub) + # Compute tentative point + x_soc = x + S.dot(d + t*y) + f_soc, b_soc = fun_and_constr(x_soc) + # Recompute actual reduction + merit_function_soc = f_soc + penalty*norm(b_soc) + actual_reduction_soc = merit_function - merit_function_soc + # Recompute reduction ratio + reduction_ratio_soc = actual_reduction_soc / predicted_reduction + if intersect and reduction_ratio_soc >= SUFFICIENT_REDUCTION_RATIO: + x_next = x_soc + f_next = f_soc + b_next = b_soc + reduction_ratio = reduction_ratio_soc + + # Readjust trust region step, formula (3.55), reference [2]_, p.892. + if reduction_ratio >= LARGE_REDUCTION_RATIO: + trust_radius = max(TRUST_ENLARGEMENT_FACTOR_L * norm(d), + trust_radius) + elif reduction_ratio >= INTERMEDIARY_REDUCTION_RATIO: + trust_radius = max(TRUST_ENLARGEMENT_FACTOR_S * norm(d), + trust_radius) + # Reduce trust region step, according to reference [3]_, p.696. + elif reduction_ratio < SUFFICIENT_REDUCTION_RATIO: + trust_reduction = ((1-SUFFICIENT_REDUCTION_RATIO) / + (1-reduction_ratio)) + new_trust_radius = trust_reduction * norm(d) + if new_trust_radius >= MAX_TRUST_REDUCTION * trust_radius: + trust_radius *= MAX_TRUST_REDUCTION + elif new_trust_radius >= MIN_TRUST_REDUCTION * trust_radius: + trust_radius = new_trust_radius + else: + trust_radius *= MIN_TRUST_REDUCTION + + # Update iteration + if reduction_ratio >= SUFFICIENT_REDUCTION_RATIO: + x = x_next + f, b = f_next, b_next + c, A = grad_and_jac(x) + S = scaling(x) + # Get projections + Z, LS, Y = projections(A, factorization_method) + # Compute least-square lagrange multipliers + v = -LS.dot(c) + # Compute Hessian + H = lagr_hess(x, v) + # Set Flag + last_iteration_failed = False + # Optimality values + optimality = norm(c + A.T.dot(v), np.inf) + constr_violation = norm(b, np.inf) if len(b) > 0 else 0 + else: + penalty = previous_penalty + last_iteration_failed = True + + return x, state diff --git a/shared/package-files/78/78990279508f07bd780e2b2b47543520d214a88057f6fd6b17694db416a69536/blob b/shared/package-files/78/78990279508f07bd780e2b2b47543520d214a88057f6fd6b17694db416a69536/blob new file mode 100644 index 0000000000000000000000000000000000000000..3c31650ddf94af6830a92844faee1004e4b14e76 --- /dev/null +++ b/shared/package-files/78/78990279508f07bd780e2b2b47543520d214a88057f6fd6b17694db416a69536/blob @@ -0,0 +1,507 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import datetime +import sys + +import pytest +import hypothesis as h +import hypothesis.strategies as st +try: + import hypothesis.extra.numpy as npst +except ImportError: + npst = None +try: + import hypothesis.extra.pytz as tzst +except ImportError: + tzst = None +try: + import zoneinfo +except ImportError: + zoneinfo = None +if sys.platform == 'win32': + try: + import tzdata # noqa:F401 + except ImportError: + zoneinfo = None +try: + import numpy as np +except ImportError: + np = None + +import pyarrow as pa + + +# Text generation strategies for various character sets +custom_text = st.text( + alphabet=st.characters( + min_codepoint=0x41, + max_codepoint=0x7E + ) +) + +# alphanum_text: Only alphanumeric characters (a-z, A-Z, 0-9) +alphanum_text = st.text( + alphabet=st.characters( + whitelist_categories=('Ll', 'Lu', 'Nd'), # Lowercase, Uppercase, Decimal Number + min_codepoint=0x30, # Start from '0' (U+0030) + max_codepoint=0x7A # End at 'z' (U+007A) + ) +) + +# surrogate_text: Unicode supplementary planes (U+10000 to U+10FFFF) +surrogate_text = st.text( + alphabet=st.characters( + min_codepoint=0x10000, # Start of Plane 1 (Supplementary Multilingual Plane) + max_codepoint=0x10FFFF # End of valid Unicode range (last code point) + ) +) + +null_type = st.just(pa.null()) +bool_type = st.just(pa.bool_()) + +binary_type = st.just(pa.binary()) +string_type = st.just(pa.string()) +large_binary_type = st.just(pa.large_binary()) +large_string_type = st.just(pa.large_string()) +fixed_size_binary_type = st.builds( + pa.binary, + st.integers(min_value=0, max_value=16) +) +binary_like_types = st.one_of( + binary_type, + string_type, + large_binary_type, + large_string_type, + fixed_size_binary_type +) + +signed_integer_types = st.sampled_from([ + pa.int8(), + pa.int16(), + pa.int32(), + pa.int64() +]) +unsigned_integer_types = st.sampled_from([ + pa.uint8(), + pa.uint16(), + pa.uint32(), + pa.uint64() +]) +integer_types = st.one_of(signed_integer_types, unsigned_integer_types) + +floating_types = st.sampled_from([ + pa.float16(), + pa.float32(), + pa.float64() +]) +decimal32_type = st.builds( + pa.decimal32, + precision=st.integers(min_value=1, max_value=9), + scale=st.integers(min_value=1, max_value=9) +) +decimal64_type = st.builds( + pa.decimal64, + precision=st.integers(min_value=1, max_value=18), + scale=st.integers(min_value=1, max_value=18) +) +decimal128_type = st.builds( + pa.decimal128, + precision=st.integers(min_value=1, max_value=38), + scale=st.integers(min_value=1, max_value=38) +) +decimal256_type = st.builds( + pa.decimal256, + precision=st.integers(min_value=1, max_value=76), + scale=st.integers(min_value=1, max_value=76) +) +numeric_types = st.one_of(integer_types, floating_types, + decimal128_type, decimal256_type) + +date_types = st.sampled_from([ + pa.date32(), + pa.date64() +]) +time_types = st.sampled_from([ + pa.time32('s'), + pa.time32('ms'), + pa.time64('us'), + pa.time64('ns') +]) + +if tzst and zoneinfo: + timezones = st.one_of(st.none(), tzst.timezones(), st.timezones()) +elif tzst: + timezones = st.one_of(st.none(), tzst.timezones()) +elif zoneinfo: + timezones = st.one_of(st.none(), st.timezones()) +else: + timezones = st.none() +timestamp_types = st.builds( + pa.timestamp, + unit=st.sampled_from(['s', 'ms', 'us', 'ns']), + tz=timezones +) +duration_types = st.builds( + pa.duration, + st.sampled_from(['s', 'ms', 'us', 'ns']) +) +interval_types = st.just(pa.month_day_nano_interval()) +temporal_types = st.one_of( + date_types, + time_types, + timestamp_types, + duration_types, + interval_types +) + +primitive_types = st.one_of( + null_type, + bool_type, + numeric_types, + temporal_types, + binary_like_types +) + +metadata = st.dictionaries(st.text(), st.text()) + + +@st.composite +def fields(draw, type_strategy=primitive_types, name_strategy=None): + if name_strategy is None: + name_strategy = custom_text + name = draw(name_strategy) + typ = draw(type_strategy) + if pa.types.is_null(typ): + nullable = True + else: + nullable = draw(st.booleans()) + meta = draw(metadata) + return pa.field(name, type=typ, nullable=nullable, metadata=meta) + + +def list_types(item_strategy=primitive_types): + return ( + st.builds(pa.list_, item_strategy) | + st.builds(pa.large_list, item_strategy) | + st.builds( + pa.list_, + item_strategy, + st.integers(min_value=0, max_value=16) + ) | + st.builds(pa.list_view, item_strategy) | + st.builds(pa.large_list_view, item_strategy) + ) + + +@st.composite +def struct_types(draw, item_strategy=primitive_types): + fields_strategy = st.lists(fields(item_strategy)) + fields_rendered = draw(fields_strategy) + field_names = [field.name for field in fields_rendered] + # check that field names are unique, see ARROW-9997 + h.assume(len(set(field_names)) == len(field_names)) + return pa.struct(fields_rendered) + + +def dictionary_types(key_strategy=None, value_strategy=None): + if key_strategy is None: + key_strategy = signed_integer_types + if value_strategy is None: + value_strategy = st.one_of( + bool_type, + integer_types, + st.sampled_from([pa.float32(), pa.float64()]), + binary_type, + string_type, + fixed_size_binary_type, + ) + return st.builds(pa.dictionary, key_strategy, value_strategy) + + +@st.composite +def map_types(draw, key_strategy=primitive_types, + item_strategy=primitive_types): + key_type = draw(key_strategy) + h.assume(not pa.types.is_null(key_type)) + value_type = draw(item_strategy) + return pa.map_(key_type, value_type) + + +# union type +# extension type + + +def schemas(type_strategy=primitive_types, max_fields=None): + children = st.lists(fields(type_strategy), max_size=max_fields) + return st.builds(pa.schema, children) + + +all_types = st.deferred( + lambda: ( + primitive_types | + list_types() | + struct_types() | + dictionary_types() | + map_types() | + list_types(all_types) | + struct_types(all_types) + ) +) +all_fields = st.one_of( + fields(all_types), # custom_text + fields(all_types, name_strategy=alphanum_text), + fields(all_types, name_strategy=surrogate_text) +) +all_schemas = schemas(all_types) + + +_default_array_sizes = st.integers(min_value=0, max_value=20) + + +@st.composite +def _pylist(draw, value_type, size, nullable=True): + arr = draw(arrays(value_type, size=size, nullable=False)) + return arr.to_pylist() + + +@st.composite +def _pymap(draw, key_type, value_type, size, nullable=True): + length = draw(size) + keys = draw(_pylist(key_type, size=length, nullable=False)) + values = draw(_pylist(value_type, size=length, nullable=nullable)) + return list(zip(keys, values)) + + +@st.composite +def arrays(draw, type, size=None, nullable=True): + if isinstance(type, st.SearchStrategy): + ty = draw(type) + elif isinstance(type, pa.DataType): + ty = type + else: + raise TypeError('Type must be a pyarrow DataType') + + if isinstance(size, st.SearchStrategy): + size = draw(size) + elif size is None: + size = draw(_default_array_sizes) + elif not isinstance(size, int): + raise TypeError('Size must be an integer') + + if pa.types.is_null(ty): + h.assume(nullable) + value = st.none() + elif pa.types.is_boolean(ty): + value = st.booleans() + elif pa.types.is_integer(ty): + values = draw(npst.arrays(ty.to_pandas_dtype(), shape=(size,))) + return pa.array(values, type=ty) + elif pa.types.is_floating(ty): + values = draw(npst.arrays(ty.to_pandas_dtype(), shape=(size,))) + # Workaround ARROW-4952: no easy way to assert array equality + # in a NaN-tolerant way. + values[np.isnan(values)] = -42.0 + return pa.array(values, type=ty) + elif pa.types.is_decimal(ty): + # TODO(kszucs): properly limit the precision + # value = st.decimals(places=type.scale, allow_infinity=False) + h.reject() + elif pa.types.is_time(ty): + value = st.times() + elif pa.types.is_date(ty): + value = st.dates() + elif pa.types.is_timestamp(ty): + if zoneinfo is None: + pytest.skip('no module named zoneinfo (or tzdata on Windows)') + if ty.tz is None: + pytest.skip('requires timezone not None') + min_int64 = -(2**63) + max_int64 = 2**63 - 1 + min_datetime = datetime.datetime.fromtimestamp( + min_int64 // 10**9) + datetime.timedelta(hours=12) + max_datetime = datetime.datetime.fromtimestamp( + max_int64 // 10**9) - datetime.timedelta(hours=12) + try: + offset = ty.tz.split(":") + offset_hours = int(offset[0]) + offset_min = int(offset[1]) + tz = datetime.timedelta(hours=offset_hours, minutes=offset_min) + except ValueError: + tz = zoneinfo.ZoneInfo(ty.tz) + value = st.datetimes(timezones=st.just(tz), min_value=min_datetime, + max_value=max_datetime) + elif pa.types.is_duration(ty): + if ty.unit in ('s', 'ms'): + min_value = datetime.timedelta.min + max_value = datetime.timedelta.max + elif ty.unit == 'us': + max_int64 = 2**63 - 1 + max_days = max_int64 // (86400 * 10**6) + min_value = datetime.timedelta(days=-max_days) + max_value = datetime.timedelta(days=max_days) + else: # 'ns' + # Empirically tested value + min_value = datetime.timedelta(days=-96_075) + max_value = datetime.timedelta(days=96_075) + value = st.timedeltas(min_value=min_value, max_value=max_value) + elif pa.types.is_interval(ty): + # Empirically tested value + value = st.timedeltas( + min_value=datetime.timedelta(days=-96_075), + max_value=datetime.timedelta(days=96_075) + ) + elif pa.types.is_binary(ty) or pa.types.is_large_binary(ty): + value = st.binary() + elif pa.types.is_string(ty) or pa.types.is_large_string(ty): + value = st.text() + elif pa.types.is_fixed_size_binary(ty): + value = st.binary(min_size=ty.byte_width, max_size=ty.byte_width) + elif pa.types.is_list(ty): + value = _pylist(ty.value_type, size=size, nullable=nullable) + elif pa.types.is_large_list(ty): + value = _pylist(ty.value_type, size=size, nullable=nullable) + elif pa.types.is_fixed_size_list(ty): + value = _pylist(ty.value_type, size=ty.list_size, nullable=nullable) + elif pa.types.is_list_view(ty): + value = _pylist(ty.value_type, size=size, nullable=nullable) + elif pa.types.is_large_list_view(ty): + value = _pylist(ty.value_type, size=size, nullable=nullable) + elif pa.types.is_dictionary(ty): + values = _pylist(ty.value_type, size=size, nullable=nullable) + return pa.array(draw(values), type=ty) + elif pa.types.is_map(ty): + value = _pymap(ty.key_type, ty.item_type, size=_default_array_sizes, + nullable=nullable) + elif pa.types.is_struct(ty): + h.assume(len(ty) > 0) + fields, child_arrays = [], [] + for field in ty: + fields.append(field) + child_arrays.append(draw(arrays(field.type, size=size))) + return pa.StructArray.from_arrays(child_arrays, fields=fields) + else: + raise NotImplementedError(ty) + + if nullable: + value = st.one_of(st.none(), value) + values = st.lists(value, min_size=size, max_size=size) + + return pa.array(draw(values), type=ty) + + +@st.composite +def chunked_arrays(draw, type, min_chunks=0, max_chunks=None, chunk_size=None): + if isinstance(type, st.SearchStrategy): + type = draw(type) + + chunk = arrays(type, size=chunk_size) + chunks = st.lists(chunk, min_size=min_chunks, max_size=max_chunks) + + return pa.chunked_array(draw(chunks), type=type) + + +@st.composite +def record_batches(draw, type, rows=None, max_fields=None): + if isinstance(rows, st.SearchStrategy): + rows = draw(rows) + elif rows is None: + rows = draw(_default_array_sizes) + elif not isinstance(rows, int): + raise TypeError('Rows must be an integer') + + schema = draw(schemas(type, max_fields=max_fields)) + children = [draw(arrays(field.type, size=rows)) for field in schema] + return pa.RecordBatch.from_arrays(children, schema=schema) + + +@st.composite +def tables(draw, type, rows=None, max_fields=None): + if isinstance(rows, st.SearchStrategy): + rows = draw(rows) + elif rows is None: + rows = draw(_default_array_sizes) + elif not isinstance(rows, int): + raise TypeError('Rows must be an integer') + + schema = draw(schemas(type, max_fields=max_fields)) + children = [draw(arrays(field.type, size=rows)) for field in schema] + return pa.Table.from_arrays(children, schema=schema) + + +all_arrays = arrays(all_types) +all_chunked_arrays = chunked_arrays(all_types) +all_record_batches = record_batches(all_types) +all_tables = tables(all_types) + + +# Define the same rules as above for pandas tests by excluding certain types +# from the generation because of known issues. + +pandas_compatible_primitive_types = st.one_of( + null_type, + bool_type, + integer_types, + st.sampled_from([pa.float32(), pa.float64()]), + decimal128_type, + date_types, + time_types, + # Need to exclude timestamp and duration types otherwise hypothesis + # discovers ARROW-10210 + # timestamp_types, + # duration_types + interval_types, + binary_type, + string_type, + large_binary_type, + large_string_type, +) + +# Need to exclude floating point types otherwise hypothesis discovers +# ARROW-10211 +pandas_compatible_dictionary_value_types = st.one_of( + bool_type, + integer_types, + binary_type, + string_type, + fixed_size_binary_type, +) + + +def pandas_compatible_list_types( + item_strategy=pandas_compatible_primitive_types +): + # Need to exclude fixed size list type otherwise hypothesis discovers + # ARROW-10194 + return ( + st.builds(pa.list_, item_strategy) | + st.builds(pa.large_list, item_strategy) + ) + + +pandas_compatible_types = st.deferred( + lambda: st.one_of( + pandas_compatible_primitive_types, + pandas_compatible_list_types(pandas_compatible_primitive_types), + struct_types(pandas_compatible_primitive_types), + dictionary_types( + value_strategy=pandas_compatible_dictionary_value_types + ), + pandas_compatible_list_types(pandas_compatible_types), + struct_types(pandas_compatible_types) + ) +) diff --git a/shared/package-files/78/78994687678604bbf899eed2cc804e557001da6d643ca2e303e7d340593336a7/model_manifest.json b/shared/package-files/78/78994687678604bbf899eed2cc804e557001da6d643ca2e303e7d340593336a7/model_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ac9814c77d4b4f7616c316b7489ac7938e2efad9 --- /dev/null +++ b/shared/package-files/78/78994687678604bbf899eed2cc804e557001da6d643ca2e303e7d340593336a7/model_manifest.json @@ -0,0 +1 @@ +{"checkpoint":{"format":"pytorch","path":"model.pt","sha256":"e1a27fbe5db99c9868650e830c65dc53ce420a4ab1362d7a166d833e5ae0c8f4"},"model_config":"model_config.json","schema":"massspecgym-retrieval-model/v1","training_provenance":{"data":"MassSpecGym v1.5 train fold","pretrained_assets":[]}} diff --git a/shared/package-files/78/7899dc834a7cdf39b51533ef33d6ae353ea86af22f5da89b9911437f5aa6c246/blob b/shared/package-files/78/7899dc834a7cdf39b51533ef33d6ae353ea86af22f5da89b9911437f5aa6c246/blob new file mode 100644 index 0000000000000000000000000000000000000000..6a254c1c5e2584dae80f58d38e9a48aae7ec1237 --- /dev/null +++ b/shared/package-files/78/7899dc834a7cdf39b51533ef33d6ae353ea86af22f5da89b9911437f5aa6c246/blob @@ -0,0 +1,331 @@ +# testing.py + +from contextlib import contextmanager +import typing + +from .core import ( + ParserElement, + ParseException, + Keyword, + __diag__, + __compat__, +) + + +class pyparsing_test: + """ + namespace class for classes useful in writing unit tests + """ + + class reset_pyparsing_context: + """ + Context manager to be used when writing unit tests that modify pyparsing config values: + - packrat parsing + - bounded recursion parsing + - default whitespace characters. + - default keyword characters + - literal string auto-conversion class + - __diag__ settings + + Example:: + + with reset_pyparsing_context(): + # test that literals used to construct a grammar are automatically suppressed + ParserElement.inlineLiteralsUsing(Suppress) + + term = Word(alphas) | Word(nums) + group = Group('(' + term[...] + ')') + + # assert that the '()' characters are not included in the parsed tokens + self.assertParseAndCheckList(group, "(abc 123 def)", ['abc', '123', 'def']) + + # after exiting context manager, literals are converted to Literal expressions again + """ + + def __init__(self): + self._save_context = {} + + def save(self): + self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS + self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS + + self._save_context[ + "literal_string_class" + ] = ParserElement._literalStringClass + + self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace + + self._save_context["packrat_enabled"] = ParserElement._packratEnabled + if ParserElement._packratEnabled: + self._save_context[ + "packrat_cache_size" + ] = ParserElement.packrat_cache.size + else: + self._save_context["packrat_cache_size"] = None + self._save_context["packrat_parse"] = ParserElement._parse + self._save_context[ + "recursion_enabled" + ] = ParserElement._left_recursion_enabled + + self._save_context["__diag__"] = { + name: getattr(__diag__, name) for name in __diag__._all_names + } + + self._save_context["__compat__"] = { + "collect_all_And_tokens": __compat__.collect_all_And_tokens + } + + return self + + def restore(self): + # reset pyparsing global state + if ( + ParserElement.DEFAULT_WHITE_CHARS + != self._save_context["default_whitespace"] + ): + ParserElement.set_default_whitespace_chars( + self._save_context["default_whitespace"] + ) + + ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"] + + Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"] + ParserElement.inlineLiteralsUsing( + self._save_context["literal_string_class"] + ) + + for name, value in self._save_context["__diag__"].items(): + (__diag__.enable if value else __diag__.disable)(name) + + ParserElement._packratEnabled = False + if self._save_context["packrat_enabled"]: + ParserElement.enable_packrat(self._save_context["packrat_cache_size"]) + else: + ParserElement._parse = self._save_context["packrat_parse"] + ParserElement._left_recursion_enabled = self._save_context[ + "recursion_enabled" + ] + + __compat__.collect_all_And_tokens = self._save_context["__compat__"] + + return self + + def copy(self): + ret = type(self)() + ret._save_context.update(self._save_context) + return ret + + def __enter__(self): + return self.save() + + def __exit__(self, *args): + self.restore() + + class TestParseResultsAsserts: + """ + A mixin class to add parse results assertion methods to normal unittest.TestCase classes. + """ + + def assertParseResultsEquals( + self, result, expected_list=None, expected_dict=None, msg=None + ): + """ + Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``, + and compare any defined results names with an optional ``expected_dict``. + """ + if expected_list is not None: + self.assertEqual(expected_list, result.as_list(), msg=msg) + if expected_dict is not None: + self.assertEqual(expected_dict, result.as_dict(), msg=msg) + + def assertParseAndCheckList( + self, expr, test_string, expected_list, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting ``ParseResults.asList()`` is equal to the ``expected_list``. + """ + result = expr.parse_string(test_string, parse_all=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg) + + def assertParseAndCheckDict( + self, expr, test_string, expected_dict, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``. + """ + result = expr.parse_string(test_string, parseAll=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg) + + def assertRunTestResults( + self, run_tests_report, expected_parse_results=None, msg=None + ): + """ + Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of + list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped + with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``. + Finally, asserts that the overall ``runTests()`` success value is ``True``. + + :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests + :param expected_parse_results (optional): [tuple(str, list, dict, Exception)] + """ + run_test_success, run_test_results = run_tests_report + + if expected_parse_results is not None: + merged = [ + (*rpt, expected) + for rpt, expected in zip(run_test_results, expected_parse_results) + ] + for test_string, result, expected in merged: + # expected should be a tuple containing a list and/or a dict or an exception, + # and optional failure message string + # an empty tuple will skip any result validation + fail_msg = next( + (exp for exp in expected if isinstance(exp, str)), None + ) + expected_exception = next( + ( + exp + for exp in expected + if isinstance(exp, type) and issubclass(exp, Exception) + ), + None, + ) + if expected_exception is not None: + with self.assertRaises( + expected_exception=expected_exception, msg=fail_msg or msg + ): + if isinstance(result, Exception): + raise result + else: + expected_list = next( + (exp for exp in expected if isinstance(exp, list)), None + ) + expected_dict = next( + (exp for exp in expected if isinstance(exp, dict)), None + ) + if (expected_list, expected_dict) != (None, None): + self.assertParseResultsEquals( + result, + expected_list=expected_list, + expected_dict=expected_dict, + msg=fail_msg or msg, + ) + else: + # warning here maybe? + print(f"no validation for {test_string!r}") + + # do this last, in case some specific test results can be reported instead + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + + @contextmanager + def assertRaisesParseException(self, exc_type=ParseException, msg=None): + with self.assertRaises(exc_type, msg=msg): + yield + + @staticmethod + def with_line_numbers( + s: str, + start_line: typing.Optional[int] = None, + end_line: typing.Optional[int] = None, + expand_tabs: bool = True, + eol_mark: str = "|", + mark_spaces: typing.Optional[str] = None, + mark_control: typing.Optional[str] = None, + ) -> str: + """ + Helpful method for debugging a parser - prints a string with line and column numbers. + (Line and column numbers are 1-based.) + + :param s: tuple(bool, str - string to be printed with line and column numbers + :param start_line: int - (optional) starting line number in s to print (default=1) + :param end_line: int - (optional) ending line number in s to print (default=len(s)) + :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default + :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default="|") + :param mark_spaces: str - (optional) special character to display in place of spaces + :param mark_control: str - (optional) convert non-printing control characters to a placeholding + character; valid values: + - "unicode" - replaces control chars with Unicode symbols, such as "␍" and "␊" + - any single character string - replace control characters with given string + - None (default) - string is displayed as-is + + :return: str - input string with leading line numbers and column number headers + """ + if expand_tabs: + s = s.expandtabs() + if mark_control is not None: + mark_control = typing.cast(str, mark_control) + if mark_control == "unicode": + transtable_map = { + c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433)) + } + transtable_map[127] = 0x2421 + tbl = str.maketrans(transtable_map) + eol_mark = "" + else: + ord_mark_control = ord(mark_control) + tbl = str.maketrans( + {c: ord_mark_control for c in list(range(0, 32)) + [127]} + ) + s = s.translate(tbl) + if mark_spaces is not None and mark_spaces != " ": + if mark_spaces == "unicode": + tbl = str.maketrans({9: 0x2409, 32: 0x2423}) + s = s.translate(tbl) + else: + s = s.replace(" ", mark_spaces) + if start_line is None: + start_line = 1 + if end_line is None: + end_line = len(s) + end_line = min(end_line, len(s)) + start_line = min(max(1, start_line), end_line) + + if mark_control != "unicode": + s_lines = s.splitlines()[start_line - 1 : end_line] + else: + s_lines = [line + "␊" for line in s.split("␊")[start_line - 1 : end_line]] + if not s_lines: + return "" + + lineno_width = len(str(end_line)) + max_line_len = max(len(line) for line in s_lines) + lead = " " * (lineno_width + 1) + if max_line_len >= 99: + header0 = ( + lead + + "".join( + f"{' ' * 99}{(i + 1) % 100}" + for i in range(max(max_line_len // 100, 1)) + ) + + "\n" + ) + else: + header0 = "" + header1 = ( + header0 + + lead + + "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10))) + + "\n" + ) + header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n" + return ( + header1 + + header2 + + "\n".join( + f"{i:{lineno_width}d}:{line}{eol_mark}" + for i, line in enumerate(s_lines, start=start_line) + ) + + "\n" + ) diff --git a/shared/package-files/78/789a5eff653f2792f2f64865ff7dc0bc5f0469769e0bfc6f19c70b99de1379cd/blob b/shared/package-files/78/789a5eff653f2792f2f64865ff7dc0bc5f0469769e0bfc6f19c70b99de1379cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..bb1061e8dce7a217c1c705ce3ea262becdba5a5c --- /dev/null +++ b/shared/package-files/78/789a5eff653f2792f2f64865ff7dc0bc5f0469769e0bfc6f19c70b99de1379cd/blob @@ -0,0 +1,544 @@ +"""DEPRECATED: Input transformer classes to support IPython special syntax. + +This module was deprecated in IPython 7.0, in favour of inputtransformer2. + +This includes the machinery to recognise and transform ``%magic`` commands, +``!system`` commands, ``help?`` querying, prompt stripping, and so forth. +""" +import abc +import functools +import re +import tokenize +from tokenize import untokenize, TokenError +from io import StringIO + +from IPython.core.splitinput import LineInfo +from IPython.utils import tokenutil + +#----------------------------------------------------------------------------- +# Globals +#----------------------------------------------------------------------------- + +# The escape sequences that define the syntax transformations IPython will +# apply to user input. These can NOT be just changed here: many regular +# expressions and other parts of the code may use their hardcoded values, and +# for all intents and purposes they constitute the 'IPython syntax', so they +# should be considered fixed. + +ESC_SHELL = '!' # Send line to underlying system shell +ESC_SH_CAP = '!!' # Send line to system shell and capture output +ESC_HELP = '?' # Find information about object +ESC_HELP2 = '??' # Find extra-detailed information about object +ESC_MAGIC = '%' # Call magic function +ESC_MAGIC2 = '%%' # Call cell-magic function +ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call +ESC_QUOTE2 = ';' # Quote all args as a single string, call +ESC_PAREN = '/' # Call first argument with rest of line as arguments + +ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\ + ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\ + ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ] + + +class InputTransformer(metaclass=abc.ABCMeta): + """Abstract base class for line-based input transformers.""" + + @abc.abstractmethod + def push(self, line): + """Send a line of input to the transformer, returning the transformed + input or None if the transformer is waiting for more input. + + Must be overridden by subclasses. + + Implementations may raise ``SyntaxError`` if the input is invalid. No + other exceptions may be raised. + """ + pass + + @abc.abstractmethod + def reset(self): + """Return, transformed any lines that the transformer has accumulated, + and reset its internal state. + + Must be overridden by subclasses. + """ + pass + + @classmethod + def wrap(cls, func): + """Can be used by subclasses as a decorator, to return a factory that + will allow instantiation with the decorated object. + """ + @functools.wraps(func) + def transformer_factory(**kwargs): + return cls(func, **kwargs) # type: ignore [call-arg] + + return transformer_factory + +class StatelessInputTransformer(InputTransformer): + """Wrapper for a stateless input transformer implemented as a function.""" + def __init__(self, func): + self.func = func + + def __repr__(self): + return "StatelessInputTransformer(func={0!r})".format(self.func) + + def push(self, line): + """Send a line of input to the transformer, returning the + transformed input.""" + return self.func(line) + + def reset(self): + """No-op - exists for compatibility.""" + pass + +class CoroutineInputTransformer(InputTransformer): + """Wrapper for an input transformer implemented as a coroutine.""" + def __init__(self, coro, **kwargs): + # Prime it + self.coro = coro(**kwargs) + next(self.coro) + + def __repr__(self): + return "CoroutineInputTransformer(coro={0!r})".format(self.coro) + + def push(self, line): + """Send a line of input to the transformer, returning the + transformed input or None if the transformer is waiting for more + input. + """ + return self.coro.send(line) + + def reset(self): + """Return, transformed any lines that the transformer has + accumulated, and reset its internal state. + """ + return self.coro.send(None) + +class TokenInputTransformer(InputTransformer): + """Wrapper for a token-based input transformer. + + func should accept a list of tokens (5-tuples, see tokenize docs), and + return an iterable which can be passed to tokenize.untokenize(). + """ + def __init__(self, func): + self.func = func + self.buf = [] + self.reset_tokenizer() + + def reset_tokenizer(self): + it = iter(self.buf) + self.tokenizer = tokenutil.generate_tokens_catch_errors(it.__next__) + + def push(self, line): + self.buf.append(line + '\n') + if all(l.isspace() for l in self.buf): + return self.reset() + + tokens = [] + stop_at_NL = False + try: + for intok in self.tokenizer: + tokens.append(intok) + t = intok[0] + if t == tokenize.NEWLINE or (stop_at_NL and t == tokenize.NL): + # Stop before we try to pull a line we don't have yet + break + elif t == tokenize.ERRORTOKEN: + stop_at_NL = True + except TokenError: + # Multi-line statement - stop and try again with the next line + self.reset_tokenizer() + return None + + return self.output(tokens) + + def output(self, tokens): + self.buf.clear() + self.reset_tokenizer() + return untokenize(self.func(tokens)).rstrip('\n') + + def reset(self): + l = ''.join(self.buf) + self.buf.clear() + self.reset_tokenizer() + if l: + return l.rstrip('\n') + +class assemble_python_lines(TokenInputTransformer): + def __init__(self): + super(assemble_python_lines, self).__init__(None) + + def output(self, tokens): + return self.reset() + +@CoroutineInputTransformer.wrap +def assemble_logical_lines(): + r"""Join lines following explicit line continuations (\)""" + line = '' + while True: + line = (yield line) + if not line or line.isspace(): + continue + + parts = [] + while line is not None: + if line.endswith('\\') and (not has_comment(line)): + parts.append(line[:-1]) + line = (yield None) # Get another line + else: + parts.append(line) + break + + # Output + line = ''.join(parts) + +# Utilities +def _make_help_call(target: str, esc: str, lspace: str) -> str: + """Prepares a pinfo(2)/psearch call from a target name and the escape + (i.e. ? or ??)""" + method = 'pinfo2' if esc == '??' \ + else 'psearch' if '*' in target \ + else 'pinfo' + arg = " ".join([method, target]) + #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) + t_magic_name, _, t_magic_arg_s = arg.partition(' ') + t_magic_name = t_magic_name.lstrip(ESC_MAGIC) + return "%sget_ipython().run_line_magic(%r, %r)" % ( + lspace, + t_magic_name, + t_magic_arg_s, + ) + + +# These define the transformations for the different escape characters. +def _tr_system(line_info: LineInfo): + "Translate lines escaped with: !" + cmd = line_info.line.lstrip().lstrip(ESC_SHELL) + return '%sget_ipython().system(%r)' % (line_info.pre, cmd) + + +def _tr_system2(line_info: LineInfo): + "Translate lines escaped with: !!" + cmd = line_info.line.lstrip()[2:] + return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd) + + +def _tr_help(line_info: LineInfo): + "Translate lines escaped with: ?/??" + # A naked help line should just fire the intro help screen + if not line_info.line[1:]: + return 'get_ipython().show_usage()' + + return _make_help_call(line_info.ifun, line_info.esc, line_info.pre) + + +def _tr_magic(line_info: LineInfo): + "Translate lines escaped with: %" + tpl = '%sget_ipython().run_line_magic(%r, %r)' + if line_info.line.startswith(ESC_MAGIC2): + return line_info.line + cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip() + #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) + t_magic_name, _, t_magic_arg_s = cmd.partition(' ') + t_magic_name = t_magic_name.lstrip(ESC_MAGIC) + return tpl % (line_info.pre, t_magic_name, t_magic_arg_s) + + +def _tr_quote(line_info: LineInfo): + "Translate lines escaped with: ," + return '%s%s("%s")' % (line_info.pre, line_info.ifun, + '", "'.join(line_info.the_rest.split()) ) + + +def _tr_quote2(line_info: LineInfo): + "Translate lines escaped with: ;" + return '%s%s("%s")' % (line_info.pre, line_info.ifun, + line_info.the_rest) + + +def _tr_paren(line_info: LineInfo): + "Translate lines escaped with: /" + return '%s%s(%s)' % (line_info.pre, line_info.ifun, + ", ".join(line_info.the_rest.split())) + +tr = { ESC_SHELL : _tr_system, + ESC_SH_CAP : _tr_system2, + ESC_HELP : _tr_help, + ESC_HELP2 : _tr_help, + ESC_MAGIC : _tr_magic, + ESC_QUOTE : _tr_quote, + ESC_QUOTE2 : _tr_quote2, + ESC_PAREN : _tr_paren } + +@StatelessInputTransformer.wrap +def escaped_commands(line: str): + """Transform escaped commands - %magic, !system, ?help + various autocalls.""" + if not line or line.isspace(): + return line + lineinf = LineInfo(line) + if lineinf.esc not in tr: + return line + + return tr[lineinf.esc](lineinf) + +_initial_space_re = re.compile(r'\s*') + +_help_end_re = re.compile(r"""(%{0,2} + (?!\d)[\w*]+ # Variable name + (\.(?!\d)[\w*]+)* # .etc.etc + ) + (\?\??)$ # ? or ?? + """, + re.VERBOSE) + +# Extra pseudotokens for multiline strings and data structures +_MULTILINE_STRING = object() +_MULTILINE_STRUCTURE = object() + +def _line_tokens(line): + """Helper for has_comment and ends_in_comment_or_string.""" + readline = StringIO(line).readline + toktypes = set() + try: + for t in tokenutil.generate_tokens_catch_errors(readline): + toktypes.add(t[0]) + except TokenError as e: + # There are only two cases where a TokenError is raised. + if 'multi-line string' in e.args[0]: + toktypes.add(_MULTILINE_STRING) + else: + toktypes.add(_MULTILINE_STRUCTURE) + return toktypes + +def has_comment(src): + """Indicate whether an input line has (i.e. ends in, or is) a comment. + + This uses tokenize, so it can distinguish comments from # inside strings. + + Parameters + ---------- + src : string + A single line input string. + + Returns + ------- + comment : bool + True if source has a comment. + """ + return (tokenize.COMMENT in _line_tokens(src)) + +def ends_in_comment_or_string(src): + """Indicates whether or not an input line ends in a comment or within + a multiline string. + + Parameters + ---------- + src : string + A single line input string. + + Returns + ------- + comment : bool + True if source ends in a comment or multiline string. + """ + toktypes = _line_tokens(src) + return (tokenize.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes) + + +@StatelessInputTransformer.wrap +def help_end(line: str): + """Translate lines with ?/?? at the end""" + m = _help_end_re.search(line) + if m is None or ends_in_comment_or_string(line): + return line + target = m.group(1) + esc = m.group(3) + match = _initial_space_re.match(line) + assert match is not None + lspace = match.group(0) + + return _make_help_call(target, esc, lspace) + + +@CoroutineInputTransformer.wrap +def cellmagic(end_on_blank_line: bool = False): + """Captures & transforms cell magics. + + After a cell magic is started, this stores up any lines it gets until it is + reset (sent None). + """ + tpl = 'get_ipython().run_cell_magic(%r, %r, %r)' + cellmagic_help_re = re.compile(r'%%\w+\?') + line = '' + while True: + line = (yield line) + # consume leading empty lines + while not line: + line = (yield line) + + if not line.startswith(ESC_MAGIC2): + # This isn't a cell magic, idle waiting for reset then start over + while line is not None: + line = (yield line) + continue + + if cellmagic_help_re.match(line): + # This case will be handled by help_end + continue + + first = line + body = [] + line = (yield None) + while (line is not None) and \ + ((line.strip() != '') or not end_on_blank_line): + body.append(line) + line = (yield None) + + # Output + magic_name, _, first = first.partition(' ') + magic_name = magic_name.lstrip(ESC_MAGIC2) + line = tpl % (magic_name, first, u'\n'.join(body)) + + +def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None): + """Remove matching input prompts from a block of input. + + Parameters + ---------- + prompt_re : regular expression + A regular expression matching any input prompt (including continuation) + initial_re : regular expression, optional + A regular expression matching only the initial prompt, but not continuation. + If no initial expression is given, prompt_re will be used everywhere. + Used mainly for plain Python prompts, where the continuation prompt + ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. + + Notes + ----- + If `initial_re` and `prompt_re differ`, + only `initial_re` will be tested against the first line. + If any prompt is found on the first two lines, + prompts will be stripped from the rest of the block. + """ + if initial_re is None: + initial_re = prompt_re + line = '' + while True: + line = (yield line) + + # First line of cell + if line is None: + continue + out, n1 = initial_re.subn('', line, count=1) + if turnoff_re and not n1: + if turnoff_re.match(line): + # We're in e.g. a cell magic; disable this transformer for + # the rest of the cell. + while line is not None: + line = (yield line) + continue + + line = (yield out) + + if line is None: + continue + # check for any prompt on the second line of the cell, + # because people often copy from just after the first prompt, + # so we might not see it in the first line. + out, n2 = prompt_re.subn('', line, count=1) + line = (yield out) + + if n1 or n2: + # Found a prompt in the first two lines - check for it in + # the rest of the cell as well. + while line is not None: + line = (yield prompt_re.sub('', line, count=1)) + + else: + # Prompts not in input - wait for reset + while line is not None: + line = (yield line) + +@CoroutineInputTransformer.wrap +def classic_prompt(): + """Strip the >>>/... prompts of the Python interactive shell.""" + # FIXME: non-capturing version (?:...) usable? + prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)') + initial_re = re.compile(r'^>>>( |$)') + # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts + turnoff_re = re.compile(r'^[%!]') + return _strip_prompts(prompt_re, initial_re, turnoff_re) + +@CoroutineInputTransformer.wrap +def ipy_prompt(): + """Strip IPython's In [1]:/...: prompts.""" + # FIXME: non-capturing version (?:...) usable? + prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)') + # Disable prompt stripping inside cell magics + turnoff_re = re.compile(r'^%%') + return _strip_prompts(prompt_re, turnoff_re=turnoff_re) + + +@CoroutineInputTransformer.wrap +def leading_indent(): + """Remove leading indentation. + + If the first line starts with a spaces or tabs, the same whitespace will be + removed from each following line until it is reset. + """ + space_re = re.compile(r'^[ \t]+') + line = '' + while True: + line = (yield line) + + if line is None: + continue + + m = space_re.match(line) + if m: + space = m.group(0) + while line is not None: + if line.startswith(space): + line = line[len(space):] + line = (yield line) + else: + # No leading spaces - wait for reset + while line is not None: + line = (yield line) + + +_assign_pat = \ +r'''(?P(\s*) + ([\w\.]+) # Initial identifier + (\s*,\s* + \*?[\w\.]+)* # Further identifiers for unpacking + \s*?,? # Trailing comma + ) + \s*=\s* +''' + +assign_system_re = re.compile(r'{}!\s*(?P.*)'.format(_assign_pat), re.VERBOSE) +assign_system_template = '%s = get_ipython().getoutput(%r)' +@StatelessInputTransformer.wrap +def assign_from_system(line): + """Transform assignment from system commands (e.g. files = !ls)""" + m = assign_system_re.match(line) + if m is None: + return line + + return assign_system_template % m.group('lhs', 'cmd') + +assign_magic_re = re.compile(r'{}%\s*(?P.*)'.format(_assign_pat), re.VERBOSE) +assign_magic_template = '%s = get_ipython().run_line_magic(%r, %r)' +@StatelessInputTransformer.wrap +def assign_from_magic(line): + """Transform assignment from magic commands (e.g. a = %who_ls)""" + m = assign_magic_re.match(line) + if m is None: + return line + #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) + m_lhs, m_cmd = m.group('lhs', 'cmd') + t_magic_name, _, t_magic_arg_s = m_cmd.partition(' ') + t_magic_name = t_magic_name.lstrip(ESC_MAGIC) + return assign_magic_template % (m_lhs, t_magic_name, t_magic_arg_s) diff --git a/shared/package-files/78/78a03d0eb5fdebe6e9a1645d78d9ef0bbdda25f3ed0a707bf1698c3c25d0f6b7/blob b/shared/package-files/78/78a03d0eb5fdebe6e9a1645d78d9ef0bbdda25f3ed0a707bf1698c3c25d0f6b7/blob new file mode 100644 index 0000000000000000000000000000000000000000..637cfc849f9dc8ef3916883d5870bcbdde67e632 --- /dev/null +++ b/shared/package-files/78/78a03d0eb5fdebe6e9a1645d78d9ef0bbdda25f3ed0a707bf1698c3c25d0f6b7/blob @@ -0,0 +1,814 @@ +""" +Module for creating Sankey diagrams using Matplotlib. +""" + +import logging +from types import SimpleNamespace + +import numpy as np + +import matplotlib as mpl +from matplotlib.path import Path +from matplotlib.patches import PathPatch +from matplotlib.transforms import Affine2D +from matplotlib import _docstring + +_log = logging.getLogger(__name__) + +__author__ = "Kevin L. Davies" +__credits__ = ["Yannick Copin"] +__license__ = "BSD" +__version__ = "2011/09/16" + +# Angles [deg/90] +RIGHT = 0 +UP = 1 +# LEFT = 2 +DOWN = 3 + + +class Sankey: + """ + Sankey diagram. + + Sankey diagrams are a specific type of flow diagram, in which + the width of the arrows is shown proportionally to the flow + quantity. They are typically used to visualize energy or + material or cost transfers between processes. + `Wikipedia (6/1/2011) `_ + + """ + + def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25, + radius=0.1, shoulder=0.03, offset=0.15, head_angle=100, + margin=0.4, tolerance=1e-6, **kwargs): + """ + Create a new Sankey instance. + + The optional arguments listed below are applied to all subdiagrams so + that there is consistent alignment and formatting. + + In order to draw a complex Sankey diagram, create an instance of + `Sankey` by calling it without any kwargs:: + + sankey = Sankey() + + Then add simple Sankey sub-diagrams:: + + sankey.add() # 1 + sankey.add() # 2 + #... + sankey.add() # n + + Finally, create the full diagram:: + + sankey.finish() + + Or, instead, simply daisy-chain those calls:: + + Sankey().add().add... .add().finish() + + Other Parameters + ---------------- + ax : `~matplotlib.axes.Axes` + Axes onto which the data should be plotted. If *ax* isn't + provided, new Axes will be created. + scale : float + Scaling factor for the flows. *scale* sizes the width of the paths + in order to maintain proper layout. The same scale is applied to + all subdiagrams. The value should be chosen such that the product + of the scale and the sum of the inputs is approximately 1.0 (and + the product of the scale and the sum of the outputs is + approximately -1.0). + unit : str + The physical unit associated with the flow quantities. If *unit* + is None, then none of the quantities are labeled. + format : str or callable + A Python number formatting string or callable used to label the + flows with their quantities (i.e., a number times a unit, where the + unit is given). If a format string is given, the label will be + ``format % quantity``. If a callable is given, it will be called + with ``quantity`` as an argument. + gap : float + Space between paths that break in/break away to/from the top or + bottom. + radius : float + Inner radius of the vertical paths. + shoulder : float + Size of the shoulders of output arrows. + offset : float + Text offset (from the dip or tip of the arrow). + head_angle : float + Angle, in degrees, of the arrow heads (and negative of the angle of + the tails). + margin : float + Minimum space between Sankey outlines and the edge of the plot + area. + tolerance : float + Acceptable maximum of the magnitude of the sum of flows. The + magnitude of the sum of connected flows cannot be greater than + *tolerance*. + **kwargs + Any additional keyword arguments will be passed to `add`, which + will create the first subdiagram. + + See Also + -------- + Sankey.add + Sankey.finish + + Examples + -------- + .. plot:: gallery/specialty_plots/sankey_basics.py + """ + # Check the arguments. + if gap < 0: + raise ValueError( + "'gap' is negative, which is not allowed because it would " + "cause the paths to overlap") + if radius > gap: + raise ValueError( + "'radius' is greater than 'gap', which is not allowed because " + "it would cause the paths to overlap") + if head_angle < 0: + raise ValueError( + "'head_angle' is negative, which is not allowed because it " + "would cause inputs to look like outputs and vice versa") + if tolerance < 0: + raise ValueError( + "'tolerance' is negative, but it must be a magnitude") + + # Create Axes if necessary. + if ax is None: + import matplotlib.pyplot as plt + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[]) + + self.diagrams = [] + + # Store the inputs. + self.ax = ax + self.unit = unit + self.format = format + self.scale = scale + self.gap = gap + self.radius = radius + self.shoulder = shoulder + self.offset = offset + self.margin = margin + self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0) + self.tolerance = tolerance + + # Initialize the vertices of tight box around the diagram(s). + self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf)) + + # If there are any kwargs, create the first subdiagram. + if len(kwargs): + self.add(**kwargs) + + def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)): + """ + Return the codes and vertices for a rotated, scaled, and translated + 90 degree arc. + + Other Parameters + ---------------- + quadrant : {0, 1, 2, 3}, default: 0 + Uses 0-based indexing (0, 1, 2, or 3). + cw : bool, default: True + If True, the arc vertices are produced clockwise; counter-clockwise + otherwise. + radius : float, default: 1 + The radius of the arc. + center : (float, float), default: (0, 0) + (x, y) tuple of the arc's center. + """ + # Note: It would be possible to use matplotlib's transforms to rotate, + # scale, and translate the arc, but since the angles are discrete, + # it's just as easy and maybe more efficient to do it here. + ARC_CODES = [Path.LINETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4] + # Vertices of a cubic Bezier curve approximating a 90 deg arc + # These can be determined by Path.arc(0, 90). + ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00], + [1.00000000e+00, 2.65114773e-01], + [8.94571235e-01, 5.19642327e-01], + [7.07106781e-01, 7.07106781e-01], + [5.19642327e-01, 8.94571235e-01], + [2.65114773e-01, 1.00000000e+00], + # Insignificant + # [6.12303177e-17, 1.00000000e+00]]) + [0.00000000e+00, 1.00000000e+00]]) + if quadrant in (0, 2): + if cw: + vertices = ARC_VERTICES + else: + vertices = ARC_VERTICES[:, ::-1] # Swap x and y. + else: # 1, 3 + # Negate x. + if cw: + # Swap x and y. + vertices = np.column_stack((-ARC_VERTICES[:, 1], + ARC_VERTICES[:, 0])) + else: + vertices = np.column_stack((-ARC_VERTICES[:, 0], + ARC_VERTICES[:, 1])) + if quadrant > 1: + radius = -radius # Rotate 180 deg. + return list(zip(ARC_CODES, radius * vertices + + np.tile(center, (ARC_VERTICES.shape[0], 1)))) + + def _add_input(self, path, angle, flow, length): + """ + Add an input to a path and return its tip and label locations. + """ + if angle is None: + return [0, 0], [0, 0] + else: + x, y = path[-1][1] # Use the last point as a reference. + dipdepth = (flow / 2) * self.pitch + if angle == RIGHT: + x -= length + dip = [x + dipdepth, y + flow / 2.0] + path.extend([(Path.LINETO, [x, y]), + (Path.LINETO, dip), + (Path.LINETO, [x, y + flow]), + (Path.LINETO, [x + self.gap, y + flow])]) + label_location = [dip[0] - self.offset, dip[1]] + else: # Vertical + x -= self.gap + if angle == UP: + sign = 1 + else: + sign = -1 + + dip = [x - flow / 2, y - sign * (length - dipdepth)] + if angle == DOWN: + quadrant = 2 + else: + quadrant = 1 + + # Inner arc isn't needed if inner radius is zero + if self.radius: + path.extend(self._arc(quadrant=quadrant, + cw=angle == UP, + radius=self.radius, + center=(x + self.radius, + y - sign * self.radius))) + else: + path.append((Path.LINETO, [x, y])) + path.extend([(Path.LINETO, [x, y - sign * length]), + (Path.LINETO, dip), + (Path.LINETO, [x - flow, y - sign * length])]) + path.extend(self._arc(quadrant=quadrant, + cw=angle == DOWN, + radius=flow + self.radius, + center=(x + self.radius, + y - sign * self.radius))) + path.append((Path.LINETO, [x - flow, y + sign * flow])) + label_location = [dip[0], dip[1] - sign * self.offset] + + return dip, label_location + + def _add_output(self, path, angle, flow, length): + """ + Append an output to a path and return its tip and label locations. + + .. note:: *flow* is negative for an output. + """ + if angle is None: + return [0, 0], [0, 0] + else: + x, y = path[-1][1] # Use the last point as a reference. + tipheight = (self.shoulder - flow / 2) * self.pitch + if angle == RIGHT: + x += length + tip = [x + tipheight, y + flow / 2.0] + path.extend([(Path.LINETO, [x, y]), + (Path.LINETO, [x, y + self.shoulder]), + (Path.LINETO, tip), + (Path.LINETO, [x, y - self.shoulder + flow]), + (Path.LINETO, [x, y + flow]), + (Path.LINETO, [x - self.gap, y + flow])]) + label_location = [tip[0] + self.offset, tip[1]] + else: # Vertical + x += self.gap + if angle == UP: + sign, quadrant = 1, 3 + else: + sign, quadrant = -1, 0 + + tip = [x - flow / 2.0, y + sign * (length + tipheight)] + # Inner arc isn't needed if inner radius is zero + if self.radius: + path.extend(self._arc(quadrant=quadrant, + cw=angle == UP, + radius=self.radius, + center=(x - self.radius, + y + sign * self.radius))) + else: + path.append((Path.LINETO, [x, y])) + path.extend([(Path.LINETO, [x, y + sign * length]), + (Path.LINETO, [x - self.shoulder, + y + sign * length]), + (Path.LINETO, tip), + (Path.LINETO, [x + self.shoulder - flow, + y + sign * length]), + (Path.LINETO, [x - flow, y + sign * length])]) + path.extend(self._arc(quadrant=quadrant, + cw=angle == DOWN, + radius=self.radius - flow, + center=(x - self.radius, + y + sign * self.radius))) + path.append((Path.LINETO, [x - flow, y + sign * flow])) + label_location = [tip[0], tip[1] + sign * self.offset] + return tip, label_location + + def _revert(self, path, first_action=Path.LINETO): + """ + A path is not simply reversible by path[::-1] since the code + specifies an action to take from the **previous** point. + """ + reverse_path = [] + next_code = first_action + for code, position in path[::-1]: + reverse_path.append((next_code, position)) + next_code = code + return reverse_path + # This might be more efficient, but it fails because 'tuple' object + # doesn't support item assignment: + # path[1] = path[1][-1:0:-1] + # path[1][0] = first_action + # path[2] = path[2][::-1] + # return path + + @_docstring.interpd + def add(self, patchlabel='', flows=None, orientations=None, labels='', + trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0), + rotation=0, **kwargs): + """ + Add a simple Sankey diagram with flows at the same hierarchical level. + + Parameters + ---------- + patchlabel : str + Label to be placed at the center of the diagram. + Note that *label* (not *patchlabel*) can be passed as keyword + argument to create an entry in the legend. + + flows : list of float + Array of flow values. By convention, inputs are positive and + outputs are negative. + + Flows are placed along the top of the diagram from the inside out + in order of their index within *flows*. They are placed along the + sides of the diagram from the top down and along the bottom from + the outside in. + + If the sum of the inputs and outputs is + nonzero, the discrepancy will appear as a cubic Bézier curve along + the top and bottom edges of the trunk. + + orientations : list of {-1, 0, 1} + List of orientations of the flows (or a single orientation to be + used for all flows). Valid values are 0 (inputs from + the left, outputs to the right), 1 (from and to the top) or -1 + (from and to the bottom). + + labels : list of (str or None) + List of labels for the flows (or a single label to be used for all + flows). Each label may be *None* (no label), or a labeling string. + If an entry is a (possibly empty) string, then the quantity for the + corresponding flow will be shown below the string. However, if + the *unit* of the main diagram is None, then quantities are never + shown, regardless of the value of this argument. + + trunklength : float + Length between the bases of the input and output groups (in + data-space units). + + pathlengths : list of float + List of lengths of the vertical arrows before break-in or after + break-away. If a single value is given, then it will be applied to + the first (inside) paths on the top and bottom, and the length of + all other arrows will be justified accordingly. The *pathlengths* + are not applied to the horizontal inputs and outputs. + + prior : int + Index of the prior diagram to which this diagram should be + connected. + + connect : (int, int) + A (prior, this) tuple indexing the flow of the prior diagram and + the flow of this diagram which should be connected. If this is the + first diagram or *prior* is *None*, *connect* will be ignored. + + rotation : float + Angle of rotation of the diagram in degrees. The interpretation of + the *orientations* argument will be rotated accordingly (e.g., if + *rotation* == 90, an *orientations* entry of 1 means to/from the + left). *rotation* is ignored if this diagram is connected to an + existing one (using *prior* and *connect*). + + Returns + ------- + Sankey + The current `.Sankey` instance. + + Other Parameters + ---------------- + **kwargs + Additional keyword arguments set `matplotlib.patches.PathPatch` + properties, listed below. For example, one may want to use + ``fill=False`` or ``label="A legend entry"``. + + %(Patch:kwdoc)s + + See Also + -------- + Sankey.finish + """ + # Check and preprocess the arguments. + flows = np.array([1.0, -1.0]) if flows is None else np.array(flows) + n = flows.shape[0] # Number of flows + if rotation is None: + rotation = 0 + else: + # In the code below, angles are expressed in deg/90. + rotation /= 90.0 + if orientations is None: + orientations = 0 + try: + orientations = np.broadcast_to(orientations, n) + except ValueError: + raise ValueError( + f"The shapes of 'flows' {np.shape(flows)} and 'orientations' " + f"{np.shape(orientations)} are incompatible" + ) from None + try: + labels = np.broadcast_to(labels, n) + except ValueError: + raise ValueError( + f"The shapes of 'flows' {np.shape(flows)} and 'labels' " + f"{np.shape(labels)} are incompatible" + ) from None + if trunklength < 0: + raise ValueError( + "'trunklength' is negative, which is not allowed because it " + "would cause poor layout") + if abs(np.sum(flows)) > self.tolerance: + _log.info("The sum of the flows is nonzero (%f; patchlabel=%r); " + "is the system not at steady state?", + np.sum(flows), patchlabel) + scaled_flows = self.scale * flows + gain = sum(max(flow, 0) for flow in scaled_flows) + loss = sum(min(flow, 0) for flow in scaled_flows) + if prior is not None: + if prior < 0: + raise ValueError("The index of the prior diagram is negative") + if min(connect) < 0: + raise ValueError( + "At least one of the connection indices is negative") + if prior >= len(self.diagrams): + raise ValueError( + f"The index of the prior diagram is {prior}, but there " + f"are only {len(self.diagrams)} other diagrams") + if connect[0] >= len(self.diagrams[prior].flows): + raise ValueError( + "The connection index to the source diagram is {}, but " + "that diagram has only {} flows".format( + connect[0], len(self.diagrams[prior].flows))) + if connect[1] >= n: + raise ValueError( + f"The connection index to this diagram is {connect[1]}, " + f"but this diagram has only {n} flows") + if self.diagrams[prior].angles[connect[0]] is None: + raise ValueError( + f"The connection cannot be made, which may occur if the " + f"magnitude of flow {connect[0]} of diagram {prior} is " + f"less than the specified tolerance") + flow_error = (self.diagrams[prior].flows[connect[0]] + + flows[connect[1]]) + if abs(flow_error) >= self.tolerance: + raise ValueError( + f"The scaled sum of the connected flows is {flow_error}, " + f"which is not within the tolerance ({self.tolerance})") + + # Determine if the flows are inputs. + are_inputs = [None] * n + for i, flow in enumerate(flows): + if flow >= self.tolerance: + are_inputs[i] = True + elif flow <= -self.tolerance: + are_inputs[i] = False + else: + _log.info( + "The magnitude of flow %d (%f) is below the tolerance " + "(%f).\nIt will not be shown, and it cannot be used in a " + "connection.", i, flow, self.tolerance) + + # Determine the angles of the arrows (before rotation). + angles = [None] * n + for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)): + if orient == 1: + if is_input: + angles[i] = DOWN + elif is_input is False: + # Be specific since is_input can be None. + angles[i] = UP + elif orient == 0: + if is_input is not None: + angles[i] = RIGHT + else: + if orient != -1: + raise ValueError( + f"The value of orientations[{i}] is {orient}, " + f"but it must be -1, 0, or 1") + if is_input: + angles[i] = UP + elif is_input is False: + angles[i] = DOWN + + # Justify the lengths of the paths. + if np.iterable(pathlengths): + if len(pathlengths) != n: + raise ValueError( + f"The lengths of 'flows' ({n}) and 'pathlengths' " + f"({len(pathlengths)}) are incompatible") + else: # Make pathlengths into a list. + urlength = pathlengths + ullength = pathlengths + lrlength = pathlengths + lllength = pathlengths + d = dict(RIGHT=pathlengths) + pathlengths = [d.get(angle, 0) for angle in angles] + # Determine the lengths of the top-side arrows + # from the middle outwards. + for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs, + scaled_flows)): + if angle == DOWN and is_input: + pathlengths[i] = ullength + ullength += flow + elif angle == UP and is_input is False: + pathlengths[i] = urlength + urlength -= flow # Flow is negative for outputs. + # Determine the lengths of the bottom-side arrows + # from the middle outwards. + for i, (angle, is_input, flow) in enumerate(reversed(list(zip( + angles, are_inputs, scaled_flows)))): + if angle == UP and is_input: + pathlengths[n - i - 1] = lllength + lllength += flow + elif angle == DOWN and is_input is False: + pathlengths[n - i - 1] = lrlength + lrlength -= flow + # Determine the lengths of the left-side arrows + # from the bottom upwards. + has_left_input = False + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, zip(scaled_flows, pathlengths))))): + if angle == RIGHT: + if is_input: + if has_left_input: + pathlengths[n - i - 1] = 0 + else: + has_left_input = True + # Determine the lengths of the right-side arrows + # from the top downwards. + has_right_output = False + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == RIGHT: + if is_input is False: + if has_right_output: + pathlengths[i] = 0 + else: + has_right_output = True + + # Begin the subpaths, and smooth the transition if the sum of the flows + # is nonzero. + urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right + gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, + gain / 2.0]), + (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, + gain / 2.0]), + (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, + -loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, + -loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap), + -loss / 2.0])] + llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left + loss / 2.0]), + (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, + loss / 2.0]), + (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, + loss / 2.0]), + (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, + -gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, + -gain / 2.0]), + (Path.LINETO, [(self.gap - trunklength / 2.0), + -gain / 2.0])] + lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right + loss / 2.0])] + ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left + gain / 2.0])] + + # Add the subpaths and assign the locations of the tips and labels. + tips = np.zeros((n, 2)) + label_locations = np.zeros((n, 2)) + # Add the top-side inputs and outputs from the middle outwards. + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == DOWN and is_input: + tips[i, :], label_locations[i, :] = self._add_input( + ulpath, angle, *spec) + elif angle == UP and is_input is False: + tips[i, :], label_locations[i, :] = self._add_output( + urpath, angle, *spec) + # Add the bottom-side inputs and outputs from the middle outwards. + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + if angle == UP and is_input: + tip, label_location = self._add_input(llpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + elif angle == DOWN and is_input is False: + tip, label_location = self._add_output(lrpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + # Add the left-side inputs from the bottom upwards. + has_left_input = False + for i, (angle, is_input, spec) in enumerate(reversed(list(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + if angle == RIGHT and is_input: + if not has_left_input: + # Make sure the lower path extends + # at least as far as the upper one. + if llpath[-1][1][0] > ulpath[-1][1][0]: + llpath.append((Path.LINETO, [ulpath[-1][1][0], + llpath[-1][1][1]])) + has_left_input = True + tip, label_location = self._add_input(llpath, angle, *spec) + tips[n - i - 1, :] = tip + label_locations[n - i - 1, :] = label_location + # Add the right-side outputs from the top downwards. + has_right_output = False + for i, (angle, is_input, spec) in enumerate(zip( + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + if angle == RIGHT and is_input is False: + if not has_right_output: + # Make sure the upper path extends + # at least as far as the lower one. + if urpath[-1][1][0] < lrpath[-1][1][0]: + urpath.append((Path.LINETO, [lrpath[-1][1][0], + urpath[-1][1][1]])) + has_right_output = True + tips[i, :], label_locations[i, :] = self._add_output( + urpath, angle, *spec) + # Trim any hanging vertices. + if not has_left_input: + ulpath.pop() + llpath.pop() + if not has_right_output: + lrpath.pop() + urpath.pop() + + # Concatenate the subpaths in the correct order (clockwise from top). + path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) + + [(Path.CLOSEPOLY, urpath[0][1])]) + + # Create a patch with the Sankey outline. + codes, vertices = zip(*path) + vertices = np.array(vertices) + + def _get_angle(a, r): + if a is None: + return None + else: + return a + r + + if prior is None: + if rotation != 0: # By default, none of this is needed. + angles = [_get_angle(angle, rotation) for angle in angles] + rotate = Affine2D().rotate_deg(rotation * 90).transform_affine + tips = rotate(tips) + label_locations = rotate(label_locations) + vertices = rotate(vertices) + text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center') + else: + rotation = (self.diagrams[prior].angles[connect[0]] - + angles[connect[1]]) + angles = [_get_angle(angle, rotation) for angle in angles] + rotate = Affine2D().rotate_deg(rotation * 90).transform_affine + tips = rotate(tips) + offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]] + translate = Affine2D().translate(*offset).transform_affine + tips = translate(tips) + label_locations = translate(rotate(label_locations)) + vertices = translate(rotate(vertices)) + kwds = dict(s=patchlabel, ha='center', va='center') + text = self.ax.text(*offset, **kwds) + if mpl.rcParams['_internal.classic_mode']: + fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4')) + lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5)) + else: + fc = kwargs.pop('fc', kwargs.pop('facecolor', None)) + lw = kwargs.pop('lw', kwargs.pop('linewidth', None)) + if fc is None: + fc = self.ax._get_patches_for_fill.get_next_color() + patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs) + self.ax.add_patch(patch) + + # Add the path labels. + texts = [] + for number, angle, label, location in zip(flows, angles, labels, + label_locations): + if label is None or angle is None: + label = '' + elif self.unit is not None: + if isinstance(self.format, str): + quantity = self.format % abs(number) + self.unit + elif callable(self.format): + quantity = self.format(number) + else: + raise TypeError( + 'format must be callable or a format string') + if label != '': + label += "\n" + label += quantity + texts.append(self.ax.text(x=location[0], y=location[1], + s=label, + ha='center', va='center')) + # Text objects are placed even they are empty (as long as the magnitude + # of the corresponding flow is larger than the tolerance) in case the + # user wants to provide labels later. + + # Expand the size of the diagram if necessary. + self.extent = (min(np.min(vertices[:, 0]), + np.min(label_locations[:, 0]), + self.extent[0]), + max(np.max(vertices[:, 0]), + np.max(label_locations[:, 0]), + self.extent[1]), + min(np.min(vertices[:, 1]), + np.min(label_locations[:, 1]), + self.extent[2]), + max(np.max(vertices[:, 1]), + np.max(label_locations[:, 1]), + self.extent[3])) + # Include both vertices _and_ label locations in the extents; there are + # where either could determine the margins (e.g., arrow shoulders). + + # Add this diagram as a subdiagram. + self.diagrams.append( + SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips, + text=text, texts=texts)) + + # Allow a daisy-chained call structure (see docstring for the class). + return self + + def finish(self): + """ + Adjust the Axes and return a list of information about the Sankey + subdiagram(s). + + Returns a list of subdiagrams with the following fields: + + ======== ============================================================= + Field Description + ======== ============================================================= + *patch* Sankey outline (a `~matplotlib.patches.PathPatch`). + *flows* Flow values (positive for input, negative for output). + *angles* List of angles of the arrows [deg/90]. + For example, if the diagram has not been rotated, + an input to the top side has an angle of 3 (DOWN), + and an output from the top side has an angle of 1 (UP). + If a flow has been skipped (because its magnitude is less + than *tolerance*), then its angle will be *None*. + *tips* (N, 2)-array of the (x, y) positions of the tips (or "dips") + of the flow paths. + If the magnitude of a flow is less the *tolerance* of this + `Sankey` instance, the flow is skipped and its tip will be at + the center of the diagram. + *text* `.Text` instance for the diagram label. + *texts* List of `.Text` instances for the flow labels. + ======== ============================================================= + + See Also + -------- + Sankey.add + """ + self.ax.axis([self.extent[0] - self.margin, + self.extent[1] + self.margin, + self.extent[2] - self.margin, + self.extent[3] + self.margin]) + self.ax.set_aspect('equal', adjustable='datalim') + return self.diagrams diff --git a/shared/package-files/78/78a1068deb262fd4746d8413940dc3cabc36a0cf008b77ed34e86e563929cbd9/blob b/shared/package-files/78/78a1068deb262fd4746d8413940dc3cabc36a0cf008b77ed34e86e563929cbd9/blob new file mode 100644 index 0000000000000000000000000000000000000000..b47cdacfc5bd918cd5ea9ddaac7298963b15786e --- /dev/null +++ b/shared/package-files/78/78a1068deb262fd4746d8413940dc3cabc36a0cf008b77ed34e86e563929cbd9/blob @@ -0,0 +1,228 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, ClassVar, cast + +import pyarrow as pa +import pyarrow.compute as pc + +from narwhals._arrow.utils import UNITS_DICT, ArrowSeriesNamespace, floordiv_compat, lit +from narwhals._compliant.any_namespace import DateTimeNamespace +from narwhals._constants import ( + MS_PER_MINUTE, + MS_PER_SECOND, + NS_PER_MICROSECOND, + NS_PER_MILLISECOND, + NS_PER_MINUTE, + NS_PER_SECOND, + SECONDS_PER_DAY, + SECONDS_PER_MINUTE, + US_PER_MINUTE, + US_PER_SECOND, +) +from narwhals._duration import Interval + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from typing import TypeAlias + + from narwhals._arrow.series import ArrowSeries + from narwhals._arrow.typing import ChunkedArrayAny, ScalarAny + from narwhals.dtypes import Datetime + from narwhals.typing import TimeUnit + + UnitCurrent: TypeAlias = TimeUnit + UnitTarget: TypeAlias = TimeUnit + BinOpBroadcast: TypeAlias = Callable[[ChunkedArrayAny, ScalarAny], ChunkedArrayAny] + IntoRhs: TypeAlias = int + + +class ArrowSeriesDateTimeNamespace( + ArrowSeriesNamespace, DateTimeNamespace["ArrowSeries"] +): + _TIMESTAMP_DATE_FACTOR: ClassVar[Mapping[TimeUnit, int]] = { + "ns": NS_PER_SECOND, + "us": US_PER_SECOND, + "ms": MS_PER_SECOND, + "s": 1, + } + _TIMESTAMP_DATETIME_OP_FACTOR: ClassVar[ + Mapping[tuple[UnitCurrent, UnitTarget], tuple[BinOpBroadcast, IntoRhs]] + ] = { + ("ns", "us"): (floordiv_compat, 1_000), + ("ns", "ms"): (floordiv_compat, 1_000_000), + ("us", "ns"): (pc.multiply, NS_PER_MICROSECOND), + ("us", "ms"): (floordiv_compat, 1_000), + ("ms", "ns"): (pc.multiply, NS_PER_MILLISECOND), + ("ms", "us"): (pc.multiply, 1_000), + ("s", "ns"): (pc.multiply, NS_PER_SECOND), + ("s", "us"): (pc.multiply, US_PER_SECOND), + ("s", "ms"): (pc.multiply, MS_PER_SECOND), + } + + @property + def unit(self) -> TimeUnit: # NOTE: Unsafe (native). + return cast("pa.TimestampType[TimeUnit, Any]", self.native.type).unit + + @property + def time_zone(self) -> str | None: # NOTE: Unsafe (narwhals). + return cast("Datetime", self.compliant.dtype).time_zone + + def to_string(self, format: str) -> ArrowSeries: + # PyArrow differs from other libraries in that %S also prints out + # the fractional part of the second...:'( + # https://arrow.apache.org/docs/python/generated/pyarrow.compute.strftime.html + format = format.replace("%S.%f", "%S").replace("%S%.f", "%S") + return self.with_native(pc.strftime(self.native, format)) + + def replace_time_zone(self, time_zone: str | None) -> ArrowSeries: + if time_zone is not None: + result = pc.assume_timezone(pc.local_timestamp(self.native), time_zone) + else: + result = pc.local_timestamp(self.native) + return self.with_native(result) + + def convert_time_zone(self, time_zone: str) -> ArrowSeries: + ser = self.replace_time_zone("UTC") if self.time_zone is None else self.compliant + return self.with_native(ser.native.cast(pa.timestamp(self.unit, time_zone))) + + def timestamp(self, time_unit: TimeUnit) -> ArrowSeries: + ser = self.compliant + dtypes = ser._version.dtypes + if isinstance(ser.dtype, dtypes.Datetime): + current = ser.dtype.time_unit + s_cast = self.native.cast(pa.int64()) + if current == time_unit: + result = s_cast + elif item := self._TIMESTAMP_DATETIME_OP_FACTOR.get((current, time_unit)): + fn, factor = item + result = fn(s_cast, lit(factor)) + else: # pragma: no cover + msg = f"unexpected time unit {current}, please report an issue at https://github.com/narwhals-dev/narwhals" + raise AssertionError(msg) + return self.with_native(result) + if isinstance(ser.dtype, dtypes.Date): + time_s = pc.multiply(self.native.cast(pa.int32()), lit(SECONDS_PER_DAY)) + factor = self._TIMESTAMP_DATE_FACTOR[time_unit] + return self.with_native(pc.multiply(time_s, lit(factor))) + msg = "Input should be either of Date or Datetime type" + raise TypeError(msg) + + def date(self) -> ArrowSeries: + return self.with_native(self.native.cast(pa.date32())) + + def year(self) -> ArrowSeries: + return self.with_native(pc.year(self.native)) + + def month(self) -> ArrowSeries: + return self.with_native(pc.month(self.native)) + + def day(self) -> ArrowSeries: + return self.with_native(pc.day(self.native)) + + def hour(self) -> ArrowSeries: + return self.with_native(pc.hour(self.native)) + + def minute(self) -> ArrowSeries: + return self.with_native(pc.minute(self.native)) + + def second(self) -> ArrowSeries: + return self.with_native(pc.second(self.native)) + + def millisecond(self) -> ArrowSeries: + return self.with_native(pc.millisecond(self.native)) + + def microsecond(self) -> ArrowSeries: + arr = self.native + result = pc.add(pc.multiply(pc.millisecond(arr), lit(1000)), pc.microsecond(arr)) + return self.with_native(result) + + def nanosecond(self) -> ArrowSeries: + result = pc.add( + pc.multiply(self.microsecond().native, lit(1000)), pc.nanosecond(self.native) + ) + return self.with_native(result) + + def ordinal_day(self) -> ArrowSeries: + return self.with_native(pc.day_of_year(self.native)) + + def weekday(self) -> ArrowSeries: + return self.with_native(pc.day_of_week(self.native, count_from_zero=False)) + + def total_minutes(self) -> ArrowSeries: + unit_to_minutes_factor = { + "s": SECONDS_PER_MINUTE, + "ms": MS_PER_MINUTE, + "us": US_PER_MINUTE, + "ns": NS_PER_MINUTE, + } + factor = lit(unit_to_minutes_factor[self.unit], type=pa.int64()) + return self.with_native(pc.divide(self.native, factor).cast(pa.int64())) + + def total_seconds(self) -> ArrowSeries: + unit_to_seconds_factor = { + "s": 1, + "ms": MS_PER_SECOND, + "us": US_PER_SECOND, + "ns": NS_PER_SECOND, + } + factor = lit(unit_to_seconds_factor[self.unit], type=pa.int64()) + return self.with_native(pc.divide(self.native, factor).cast(pa.int64())) + + def total_milliseconds(self) -> ArrowSeries: + unit_to_milli_factor = { + "s": 1e3, # seconds + "ms": 1, # milli + "us": 1e3, # micro + "ns": 1e6, # nano + } + factor = lit(unit_to_milli_factor[self.unit], type=pa.int64()) + if self.unit == "s": + return self.with_native(pc.multiply(self.native, factor).cast(pa.int64())) + return self.with_native(pc.divide(self.native, factor).cast(pa.int64())) + + def total_microseconds(self) -> ArrowSeries: + unit_to_micro_factor = { + "s": 1e6, # seconds + "ms": 1e3, # milli + "us": 1, # micro + "ns": 1e3, # nano + } + factor = lit(unit_to_micro_factor[self.unit], type=pa.int64()) + if self.unit in {"s", "ms"}: + return self.with_native(pc.multiply(self.native, factor).cast(pa.int64())) + return self.with_native(pc.divide(self.native, factor).cast(pa.int64())) + + def total_nanoseconds(self) -> ArrowSeries: + unit_to_nano_factor = { + "s": NS_PER_SECOND, + "ms": NS_PER_MILLISECOND, + "us": NS_PER_MICROSECOND, + "ns": 1, + } + factor = lit(unit_to_nano_factor[self.unit], type=pa.int64()) + return self.with_native(pc.multiply(self.native, factor).cast(pa.int64())) + + def truncate(self, every: str) -> ArrowSeries: + interval = Interval.parse(every) + return self.with_native( + pc.floor_temporal(self.native, interval.multiple, UNITS_DICT[interval.unit]) + ) + + def offset_by(self, by: str) -> ArrowSeries: + interval = Interval.parse_no_constraints(by) + native = self.native + if interval.unit in {"y", "q", "mo"}: + msg = f"Offsetting by {interval.unit} is not yet supported for pyarrow." + raise NotImplementedError(msg) + dtype = self.compliant.dtype + datetime_dtype = self.version.dtypes.Datetime + if interval.unit == "d" and isinstance(dtype, datetime_dtype) and dtype.time_zone: + offset: pa.DurationScalar[Any] = lit(interval.to_timedelta()) + native_naive = pc.local_timestamp(native) + result = pc.assume_timezone(pc.add(native_naive, offset), dtype.time_zone) + return self.with_native(result) + if interval.unit == "ns": # pragma: no cover + offset = lit(interval.multiple, pa.duration("ns")) + else: + offset = lit(interval.to_timedelta()) + return self.with_native(pc.add(native, offset)) diff --git a/shared/package-files/78/78a3a01d9585d7f4d45599776bc5b7529a037f737bdc3d3b354e48c35aa26861/blob b/shared/package-files/78/78a3a01d9585d7f4d45599776bc5b7529a037f737bdc3d3b354e48c35aa26861/blob new file mode 100644 index 0000000000000000000000000000000000000000..cb33b493f02923be4c32488c1f67dbb62ec57ff0 --- /dev/null +++ b/shared/package-files/78/78a3a01d9585d7f4d45599776bc5b7529a037f737bdc3d3b354e48c35aa26861/blob @@ -0,0 +1,34 @@ +from typing import Any, List, Optional, Sequence, Tuple, Type + +from django.db.backends.base.schema import BaseDatabaseSchemaEditor +from django.db.backends.ddl_references import Statement +from django.db.models.base import Model +from django.db.models.query_utils import Q + +class Index: + model: Type[Model] + suffix: str = ... + max_name_length: int = ... + fields: Sequence[str] = ... + fields_orders: Sequence[Tuple[str, str]] = ... + name: str = ... + db_tablespace: Optional[str] = ... + opclasses: Sequence[str] = ... + condition: Optional[Q] = ... + def __init__( + self, + *, + fields: Sequence[str] = ..., + name: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + opclasses: Sequence[str] = ..., + condition: Optional[Q] = ... + ) -> None: ... + def check_name(self) -> List[str]: ... + def create_sql( + self, model: Type[Model], schema_editor: BaseDatabaseSchemaEditor, using: str = ... + ) -> Statement: ... + def remove_sql(self, model: Type[Model], schema_editor: BaseDatabaseSchemaEditor) -> str: ... + def deconstruct(self) -> Any: ... + def clone(self) -> Index: ... + def set_name_with_model(self, model: Type[Model]) -> None: ... diff --git a/shared/package-files/78/78a4381a5566e3fea2d9b6a1ed3f79aad25d5d62c9276f32af2dbb6a31867c8a/blob b/shared/package-files/78/78a4381a5566e3fea2d9b6a1ed3f79aad25d5d62c9276f32af2dbb6a31867c8a/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d8ebd7265141eb638d92ff243a8e194ff95663d --- /dev/null +++ b/shared/package-files/78/78a4381a5566e3fea2d9b6a1ed3f79aad25d5d62c9276f32af2dbb6a31867c8a/blob @@ -0,0 +1,979 @@ +from sympy.assumptions.ask import (Q, ask) +from sympy.core import Basic, Add, Mul, S +from sympy.core.sympify import _sympify +from sympy.functions import adjoint +from sympy.functions.elementary.complexes import re, im +from sympy.strategies import typed, exhaust, condition, do_one, unpack +from sympy.strategies.traverse import bottom_up +from sympy.utilities.iterables import is_sequence, sift +from sympy.utilities.misc import filldedent + +from sympy.matrices import Matrix, ShapeError +from sympy.matrices.common import NonInvertibleMatrixError +from sympy.matrices.expressions.determinant import det, Determinant +from sympy.matrices.expressions.inverse import Inverse +from sympy.matrices.expressions.matadd import MatAdd +from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement +from sympy.matrices.expressions.matmul import MatMul +from sympy.matrices.expressions.matpow import MatPow +from sympy.matrices.expressions.slice import MatrixSlice +from sympy.matrices.expressions.special import ZeroMatrix, Identity +from sympy.matrices.expressions.trace import trace +from sympy.matrices.expressions.transpose import Transpose, transpose + + +class BlockMatrix(MatrixExpr): + """A BlockMatrix is a Matrix comprised of other matrices. + + The submatrices are stored in a SymPy Matrix object but accessed as part of + a Matrix Expression + + >>> from sympy import (MatrixSymbol, BlockMatrix, symbols, + ... Identity, ZeroMatrix, block_collapse) + >>> n,m,l = symbols('n m l') + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> Z = MatrixSymbol('Z', n, m) + >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) + >>> print(B) + Matrix([ + [X, Z], + [0, Y]]) + + >>> C = BlockMatrix([[Identity(n), Z]]) + >>> print(C) + Matrix([[I, Z]]) + + >>> print(block_collapse(C*B)) + Matrix([[X, Z + Z*Y]]) + + Some matrices might be comprised of rows of blocks with + the matrices in each row having the same height and the + rows all having the same total number of columns but + not having the same number of columns for each matrix + in each row. In this case, the matrix is not a block + matrix and should be instantiated by Matrix. + + >>> from sympy import ones, Matrix + >>> dat = [ + ... [ones(3,2), ones(3,3)*2], + ... [ones(2,3)*3, ones(2,2)*4]] + ... + >>> BlockMatrix(dat) + Traceback (most recent call last): + ... + ValueError: + Although this matrix is comprised of blocks, the blocks do not fill + the matrix in a size-symmetric fashion. To create a full matrix from + these arguments, pass them directly to Matrix. + >>> Matrix(dat) + Matrix([ + [1, 1, 2, 2, 2], + [1, 1, 2, 2, 2], + [1, 1, 2, 2, 2], + [3, 3, 3, 4, 4], + [3, 3, 3, 4, 4]]) + + See Also + ======== + sympy.matrices.matrices.MatrixBase.irregular + """ + def __new__(cls, *args, **kwargs): + from sympy.matrices.immutable import ImmutableDenseMatrix + isMat = lambda i: getattr(i, 'is_Matrix', False) + if len(args) != 1 or \ + not is_sequence(args[0]) or \ + len({isMat(r) for r in args[0]}) != 1: + raise ValueError(filldedent(''' + expecting a sequence of 1 or more rows + containing Matrices.''')) + rows = args[0] if args else [] + if not isMat(rows): + if rows and isMat(rows[0]): + rows = [rows] # rows is not list of lists or [] + # regularity check + # same number of matrices in each row + blocky = ok = len({len(r) for r in rows}) == 1 + if ok: + # same number of rows for each matrix in a row + for r in rows: + ok = len({i.rows for i in r}) == 1 + if not ok: + break + blocky = ok + if ok: + # same number of cols for each matrix in each col + for c in range(len(rows[0])): + ok = len({rows[i][c].cols + for i in range(len(rows))}) == 1 + if not ok: + break + if not ok: + # same total cols in each row + ok = len({ + sum([i.cols for i in r]) for r in rows}) == 1 + if blocky and ok: + raise ValueError(filldedent(''' + Although this matrix is comprised of blocks, + the blocks do not fill the matrix in a + size-symmetric fashion. To create a full matrix + from these arguments, pass them directly to + Matrix.''')) + raise ValueError(filldedent(''' + When there are not the same number of rows in each + row's matrices or there are not the same number of + total columns in each row, the matrix is not a + block matrix. If this matrix is known to consist of + blocks fully filling a 2-D space then see + Matrix.irregular.''')) + mat = ImmutableDenseMatrix(rows, evaluate=False) + obj = Basic.__new__(cls, mat) + return obj + + @property + def shape(self): + numrows = numcols = 0 + M = self.blocks + for i in range(M.shape[0]): + numrows += M[i, 0].shape[0] + for i in range(M.shape[1]): + numcols += M[0, i].shape[1] + return (numrows, numcols) + + @property + def blockshape(self): + return self.blocks.shape + + @property + def blocks(self): + return self.args[0] + + @property + def rowblocksizes(self): + return [self.blocks[i, 0].rows for i in range(self.blockshape[0])] + + @property + def colblocksizes(self): + return [self.blocks[0, i].cols for i in range(self.blockshape[1])] + + def structurally_equal(self, other): + return (isinstance(other, BlockMatrix) + and self.shape == other.shape + and self.blockshape == other.blockshape + and self.rowblocksizes == other.rowblocksizes + and self.colblocksizes == other.colblocksizes) + + def _blockmul(self, other): + if (isinstance(other, BlockMatrix) and + self.colblocksizes == other.rowblocksizes): + return BlockMatrix(self.blocks*other.blocks) + + return self * other + + def _blockadd(self, other): + if (isinstance(other, BlockMatrix) + and self.structurally_equal(other)): + return BlockMatrix(self.blocks + other.blocks) + + return self + other + + def _eval_transpose(self): + # Flip all the individual matrices + matrices = [transpose(matrix) for matrix in self.blocks] + # Make a copy + M = Matrix(self.blockshape[0], self.blockshape[1], matrices) + # Transpose the block structure + M = M.transpose() + return BlockMatrix(M) + + def _eval_adjoint(self): + # Adjoint all the individual matrices + matrices = [adjoint(matrix) for matrix in self.blocks] + # Make a copy + M = Matrix(self.blockshape[0], self.blockshape[1], matrices) + # Transpose the block structure + M = M.transpose() + return BlockMatrix(M) + + def _eval_trace(self): + if self.rowblocksizes == self.colblocksizes: + return Add(*[trace(self.blocks[i, i]) + for i in range(self.blockshape[0])]) + raise NotImplementedError( + "Can't perform trace of irregular blockshape") + + def _eval_determinant(self): + if self.blockshape == (1, 1): + return det(self.blocks[0, 0]) + if self.blockshape == (2, 2): + [[A, B], + [C, D]] = self.blocks.tolist() + if ask(Q.invertible(A)): + return det(A)*det(D - C*A.I*B) + elif ask(Q.invertible(D)): + return det(D)*det(A - B*D.I*C) + return Determinant(self) + + def _eval_as_real_imag(self): + real_matrices = [re(matrix) for matrix in self.blocks] + real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices) + + im_matrices = [im(matrix) for matrix in self.blocks] + im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices) + + return (BlockMatrix(real_matrices), BlockMatrix(im_matrices)) + + def transpose(self): + """Return transpose of matrix. + + Examples + ======== + + >>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix + >>> from sympy.abc import m, n + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> Z = MatrixSymbol('Z', n, m) + >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) + >>> B.transpose() + Matrix([ + [X.T, 0], + [Z.T, Y.T]]) + >>> _.transpose() + Matrix([ + [X, Z], + [0, Y]]) + """ + return self._eval_transpose() + + def schur(self, mat = 'A', generalized = False): + """Return the Schur Complement of the 2x2 BlockMatrix + + Parameters + ========== + + mat : String, optional + The matrix with respect to which the + Schur Complement is calculated. 'A' is + used by default + + generalized : bool, optional + If True, returns the generalized Schur + Component which uses Moore-Penrose Inverse + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + + The default Schur Complement is evaluated with "A" + + >>> X.schur() + -C*A**(-1)*B + D + >>> X.schur('D') + A - B*D**(-1)*C + + Schur complement with non-invertible matrices is not + defined. Instead, the generalized Schur complement can + be calculated which uses the Moore-Penrose Inverse. To + achieve this, `generalized` must be set to `True` + + >>> X.schur('B', generalized=True) + C - D*(B.T*B)**(-1)*B.T*A + >>> X.schur('C', generalized=True) + -A*(C.T*C)**(-1)*C.T*D + B + + Returns + ======= + + M : Matrix + The Schur Complement Matrix + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If given matrix is non-invertible + + References + ========== + + .. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement + + See Also + ======== + + sympy.matrices.matrices.MatrixBase.pinv + """ + + if self.blockshape == (2, 2): + [[A, B], + [C, D]] = self.blocks.tolist() + d={'A' : A, 'B' : B, 'C' : C, 'D' : D} + try: + inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv() + if mat == 'A': + return D - C * inv * B + elif mat == 'B': + return C - D * inv * A + elif mat == 'C': + return B - A * inv * D + elif mat == 'D': + return A - B * inv * C + #For matrices where no sub-matrix is square + return self + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \ + to compute the generalized Schur Complement which uses Moore-Penrose Inverse') + else: + raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices') + + def LDUdecomposition(self): + """Returns the Block LDU decomposition of + a 2x2 Block Matrix + + Returns + ======= + + (L, D, U) : Matrices + L : Lower Diagonal Matrix + D : Diagonal Matrix + U : Upper Diagonal Matrix + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + >>> L, D, U = X.LDUdecomposition() + >>> block_collapse(L*D*U) + Matrix([ + [A, B], + [C, D]]) + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If the matrix "A" is non-invertible + + See Also + ======== + sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition + sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition + """ + if self.blockshape == (2,2): + [[A, B], + [C, D]] = self.blocks.tolist() + try: + AI = A.I + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\ + "A" is singular') + Ip = Identity(B.shape[0]) + Iq = Identity(B.shape[1]) + Z = ZeroMatrix(*B.shape) + L = BlockMatrix([[Ip, Z], [C*AI, Iq]]) + D = BlockDiagMatrix(A, self.schur()) + U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]]) + return L, D, U + else: + raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices") + + def UDLdecomposition(self): + """Returns the Block UDL decomposition of + a 2x2 Block Matrix + + Returns + ======= + + (U, D, L) : Matrices + U : Upper Diagonal Matrix + D : Diagonal Matrix + L : Lower Diagonal Matrix + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + >>> U, D, L = X.UDLdecomposition() + >>> block_collapse(U*D*L) + Matrix([ + [A, B], + [C, D]]) + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If the matrix "D" is non-invertible + + See Also + ======== + sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition + sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition + """ + if self.blockshape == (2,2): + [[A, B], + [C, D]] = self.blocks.tolist() + try: + DI = D.I + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\ + "D" is singular') + Ip = Identity(A.shape[0]) + Iq = Identity(B.shape[1]) + Z = ZeroMatrix(*B.shape) + U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]]) + D = BlockDiagMatrix(self.schur('D'), D) + L = BlockMatrix([[Ip, Z],[DI*C, Iq]]) + return U, D, L + else: + raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices") + + def LUdecomposition(self): + """Returns the Block LU decomposition of + a 2x2 Block Matrix + + Returns + ======= + + (L, U) : Matrices + L : Lower Diagonal Matrix + U : Upper Diagonal Matrix + + Examples + ======== + + >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse + >>> m, n = symbols('m n') + >>> A = MatrixSymbol('A', n, n) + >>> B = MatrixSymbol('B', n, m) + >>> C = MatrixSymbol('C', m, n) + >>> D = MatrixSymbol('D', m, m) + >>> X = BlockMatrix([[A, B], [C, D]]) + >>> L, U = X.LUdecomposition() + >>> block_collapse(L*U) + Matrix([ + [A, B], + [C, D]]) + + Raises + ====== + + ShapeError + If the block matrix is not a 2x2 matrix + + NonInvertibleMatrixError + If the matrix "A" is non-invertible + + See Also + ======== + sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition + sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition + """ + if self.blockshape == (2,2): + [[A, B], + [C, D]] = self.blocks.tolist() + try: + A = A**0.5 + AI = A.I + except NonInvertibleMatrixError: + raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\ + "A" is singular') + Z = ZeroMatrix(*B.shape) + Q = self.schur()**0.5 + L = BlockMatrix([[A, Z], [C*AI, Q]]) + U = BlockMatrix([[A, AI*B],[Z.T, Q]]) + return L, U + else: + raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices") + + def _entry(self, i, j, **kwargs): + # Find row entry + orig_i, orig_j = i, j + for row_block, numrows in enumerate(self.rowblocksizes): + cmp = i < numrows + if cmp == True: + break + elif cmp == False: + i -= numrows + elif row_block < self.blockshape[0] - 1: + # Can't tell which block and it's not the last one, return unevaluated + return MatrixElement(self, orig_i, orig_j) + for col_block, numcols in enumerate(self.colblocksizes): + cmp = j < numcols + if cmp == True: + break + elif cmp == False: + j -= numcols + elif col_block < self.blockshape[1] - 1: + return MatrixElement(self, orig_i, orig_j) + return self.blocks[row_block, col_block][i, j] + + @property + def is_Identity(self): + if self.blockshape[0] != self.blockshape[1]: + return False + for i in range(self.blockshape[0]): + for j in range(self.blockshape[1]): + if i==j and not self.blocks[i, j].is_Identity: + return False + if i!=j and not self.blocks[i, j].is_ZeroMatrix: + return False + return True + + @property + def is_structurally_symmetric(self): + return self.rowblocksizes == self.colblocksizes + + def equals(self, other): + if self == other: + return True + if (isinstance(other, BlockMatrix) and self.blocks == other.blocks): + return True + return super().equals(other) + + +class BlockDiagMatrix(BlockMatrix): + """A sparse matrix with block matrices along its diagonals + + Examples + ======== + + >>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols + >>> n, m, l = symbols('n m l') + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> BlockDiagMatrix(X, Y) + Matrix([ + [X, 0], + [0, Y]]) + + Notes + ===== + + If you want to get the individual diagonal blocks, use + :meth:`get_diag_blocks`. + + See Also + ======== + + sympy.matrices.dense.diag + """ + def __new__(cls, *mats): + return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats]) + + @property + def diag(self): + return self.args + + @property + def blocks(self): + from sympy.matrices.immutable import ImmutableDenseMatrix + mats = self.args + data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols) + for j in range(len(mats))] + for i in range(len(mats))] + return ImmutableDenseMatrix(data, evaluate=False) + + @property + def shape(self): + return (sum(block.rows for block in self.args), + sum(block.cols for block in self.args)) + + @property + def blockshape(self): + n = len(self.args) + return (n, n) + + @property + def rowblocksizes(self): + return [block.rows for block in self.args] + + @property + def colblocksizes(self): + return [block.cols for block in self.args] + + def _all_square_blocks(self): + """Returns true if all blocks are square""" + return all(mat.is_square for mat in self.args) + + def _eval_determinant(self): + if self._all_square_blocks(): + return Mul(*[det(mat) for mat in self.args]) + # At least one block is non-square. Since the entire matrix must be square we know there must + # be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient + return S.Zero + + def _eval_inverse(self, expand='ignored'): + if self._all_square_blocks(): + return BlockDiagMatrix(*[mat.inverse() for mat in self.args]) + # See comment in _eval_determinant() + raise NonInvertibleMatrixError('Matrix det == 0; not invertible.') + + def _eval_transpose(self): + return BlockDiagMatrix(*[mat.transpose() for mat in self.args]) + + def _blockmul(self, other): + if (isinstance(other, BlockDiagMatrix) and + self.colblocksizes == other.rowblocksizes): + return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)]) + else: + return BlockMatrix._blockmul(self, other) + + def _blockadd(self, other): + if (isinstance(other, BlockDiagMatrix) and + self.blockshape == other.blockshape and + self.rowblocksizes == other.rowblocksizes and + self.colblocksizes == other.colblocksizes): + return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)]) + else: + return BlockMatrix._blockadd(self, other) + + def get_diag_blocks(self): + """Return the list of diagonal blocks of the matrix. + + Examples + ======== + + >>> from sympy import BlockDiagMatrix, Matrix + + >>> A = Matrix([[1, 2], [3, 4]]) + >>> B = Matrix([[5, 6], [7, 8]]) + >>> M = BlockDiagMatrix(A, B) + + How to get diagonal blocks from the block diagonal matrix: + + >>> diag_blocks = M.get_diag_blocks() + >>> diag_blocks[0] + Matrix([ + [1, 2], + [3, 4]]) + >>> diag_blocks[1] + Matrix([ + [5, 6], + [7, 8]]) + """ + return self.args + + +def block_collapse(expr): + """Evaluates a block matrix expression + + >>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse + >>> n,m,l = symbols('n m l') + >>> X = MatrixSymbol('X', n, n) + >>> Y = MatrixSymbol('Y', m, m) + >>> Z = MatrixSymbol('Z', n, m) + >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]]) + >>> print(B) + Matrix([ + [X, Z], + [0, Y]]) + + >>> C = BlockMatrix([[Identity(n), Z]]) + >>> print(C) + Matrix([[I, Z]]) + + >>> print(block_collapse(C*B)) + Matrix([[X, Z + Z*Y]]) + """ + from sympy.strategies.util import expr_fns + + hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) + + conditioned_rl = condition( + hasbm, + typed( + {MatAdd: do_one(bc_matadd, bc_block_plus_ident), + MatMul: do_one(bc_matmul, bc_dist), + MatPow: bc_matmul, + Transpose: bc_transpose, + Inverse: bc_inverse, + BlockMatrix: do_one(bc_unpack, deblock)} + ) + ) + + rule = exhaust( + bottom_up( + exhaust(conditioned_rl), + fns=expr_fns + ) + ) + + result = rule(expr) + doit = getattr(result, 'doit', None) + if doit is not None: + return doit() + else: + return result + +def bc_unpack(expr): + if expr.blockshape == (1, 1): + return expr.blocks[0, 0] + return expr + +def bc_matadd(expr): + args = sift(expr.args, lambda M: isinstance(M, BlockMatrix)) + blocks = args[True] + if not blocks: + return expr + + nonblocks = args[False] + block = blocks[0] + for b in blocks[1:]: + block = block._blockadd(b) + if nonblocks: + return MatAdd(*nonblocks) + block + else: + return block + +def bc_block_plus_ident(expr): + idents = [arg for arg in expr.args if arg.is_Identity] + if not idents: + return expr + + blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)] + if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks) + and blocks[0].is_structurally_symmetric): + block_id = BlockDiagMatrix(*[Identity(k) + for k in blocks[0].rowblocksizes]) + rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)] + return MatAdd(block_id * len(idents), *blocks, *rest).doit() + + return expr + +def bc_dist(expr): + """ Turn a*[X, Y] into [a*X, a*Y] """ + factor, mat = expr.as_coeff_mmul() + if factor == 1: + return expr + + unpacked = unpack(mat) + + if isinstance(unpacked, BlockDiagMatrix): + B = unpacked.diag + new_B = [factor * mat for mat in B] + return BlockDiagMatrix(*new_B) + elif isinstance(unpacked, BlockMatrix): + B = unpacked.blocks + new_B = [ + [factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)] + return BlockMatrix(new_B) + return expr + + +def bc_matmul(expr): + if isinstance(expr, MatPow): + if expr.args[1].is_Integer: + factor, matrices = (1, [expr.args[0]]*expr.args[1]) + else: + return expr + else: + factor, matrices = expr.as_coeff_matrices() + + i = 0 + while (i+1 < len(matrices)): + A, B = matrices[i:i+2] + if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix): + matrices[i] = A._blockmul(B) + matrices.pop(i+1) + elif isinstance(A, BlockMatrix): + matrices[i] = A._blockmul(BlockMatrix([[B]])) + matrices.pop(i+1) + elif isinstance(B, BlockMatrix): + matrices[i] = BlockMatrix([[A]])._blockmul(B) + matrices.pop(i+1) + else: + i+=1 + return MatMul(factor, *matrices).doit() + +def bc_transpose(expr): + collapse = block_collapse(expr.arg) + return collapse._eval_transpose() + + +def bc_inverse(expr): + if isinstance(expr.arg, BlockDiagMatrix): + return expr.inverse() + + expr2 = blockinverse_1x1(expr) + if expr != expr2: + return expr2 + return blockinverse_2x2(Inverse(reblock_2x2(expr.arg))) + +def blockinverse_1x1(expr): + if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1): + mat = Matrix([[expr.arg.blocks[0].inverse()]]) + return BlockMatrix(mat) + return expr + + +def blockinverse_2x2(expr): + if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2): + # See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou + [[A, B], + [C, D]] = expr.arg.blocks.tolist() + + formula = _choose_2x2_inversion_formula(A, B, C, D) + if formula != None: + MI = expr.arg.schur(formula).I + if formula == 'A': + AI = A.I + return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]]) + if formula == 'B': + BI = B.I + return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]]) + if formula == 'C': + CI = C.I + return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]]) + if formula == 'D': + DI = D.I + return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]]) + + return expr + + +def _choose_2x2_inversion_formula(A, B, C, D): + """ + Assuming [[A, B], [C, D]] would form a valid square block matrix, find + which of the classical 2x2 block matrix inversion formulas would be + best suited. + + Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion + of the given argument or None if the matrix cannot be inverted using + any of those formulas. + """ + # Try to find a known invertible matrix. Note that the Schur complement + # is currently not being considered for this + A_inv = ask(Q.invertible(A)) + if A_inv == True: + return 'A' + B_inv = ask(Q.invertible(B)) + if B_inv == True: + return 'B' + C_inv = ask(Q.invertible(C)) + if C_inv == True: + return 'C' + D_inv = ask(Q.invertible(D)) + if D_inv == True: + return 'D' + # Otherwise try to find a matrix that isn't known to be non-invertible + if A_inv != False: + return 'A' + if B_inv != False: + return 'B' + if C_inv != False: + return 'C' + if D_inv != False: + return 'D' + return None + + +def deblock(B): + """ Flatten a BlockMatrix of BlockMatrices """ + if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix): + return B + wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]]) + bb = B.blocks.applyfunc(wrap) # everything is a block + + try: + MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), []) + for row in range(0, bb.shape[0]): + M = Matrix(bb[row, 0].blocks) + for col in range(1, bb.shape[1]): + M = M.row_join(bb[row, col].blocks) + MM = MM.col_join(M) + + return BlockMatrix(MM) + except ShapeError: + return B + + +def reblock_2x2(expr): + """ + Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If + possible in such a way that the matrix continues to be invertible using the + classical 2x2 block inversion formulas. + """ + if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape): + return expr + + BM = BlockMatrix # for brevity's sake + rowblocks, colblocks = expr.blockshape + blocks = expr.blocks + for i in range(1, rowblocks): + for j in range(1, colblocks): + # try to split rows at i and cols at j + A = bc_unpack(BM(blocks[:i, :j])) + B = bc_unpack(BM(blocks[:i, j:])) + C = bc_unpack(BM(blocks[i:, :j])) + D = bc_unpack(BM(blocks[i:, j:])) + + formula = _choose_2x2_inversion_formula(A, B, C, D) + if formula is not None: + return BlockMatrix([[A, B], [C, D]]) + + # else: nothing worked, just split upper left corner + return BM([[blocks[0, 0], BM(blocks[0, 1:])], + [BM(blocks[1:, 0]), BM(blocks[1:, 1:])]]) + + +def bounds(sizes): + """ Convert sequence of numbers into pairs of low-high pairs + + >>> from sympy.matrices.expressions.blockmatrix import bounds + >>> bounds((1, 10, 50)) + [(0, 1), (1, 11), (11, 61)] + """ + low = 0 + rv = [] + for size in sizes: + rv.append((low, low + size)) + low += size + return rv + +def blockcut(expr, rowsizes, colsizes): + """ Cut a matrix expression into Blocks + + >>> from sympy import ImmutableMatrix, blockcut + >>> M = ImmutableMatrix(4, 4, range(16)) + >>> B = blockcut(M, (1, 3), (1, 3)) + >>> type(B).__name__ + 'BlockMatrix' + >>> ImmutableMatrix(B.blocks[0, 1]) + Matrix([[1, 2, 3]]) + """ + + rowbounds = bounds(rowsizes) + colbounds = bounds(colsizes) + return BlockMatrix([[MatrixSlice(expr, rowbound, colbound) + for colbound in colbounds] + for rowbound in rowbounds]) diff --git a/shared/package-files/78/78a55ead1d0ba03f42b8d969c2805c9fb048763dfef31e7a54d83ef909fb1e07/blob b/shared/package-files/78/78a55ead1d0ba03f42b8d969c2805c9fb048763dfef31e7a54d83ef909fb1e07/blob new file mode 100644 index 0000000000000000000000000000000000000000..38b812261125e6aabef8618955b234f6c7b04955 Binary files /dev/null and b/shared/package-files/78/78a55ead1d0ba03f42b8d969c2805c9fb048763dfef31e7a54d83ef909fb1e07/blob differ diff --git a/shared/package-files/78/78af03db6282166b17c93a12b401bd757513127c195fe5800e72ab6fb9059c75/blob b/shared/package-files/78/78af03db6282166b17c93a12b401bd757513127c195fe5800e72ab6fb9059c75/blob new file mode 100644 index 0000000000000000000000000000000000000000..79d85a63ac4db2f559640044f09b2f95ff3b8c75 --- /dev/null +++ b/shared/package-files/78/78af03db6282166b17c93a12b401bd757513127c195fe5800e72ab6fb9059c75/blob @@ -0,0 +1,39 @@ +import sys +from subprocess import PIPE, Popen + + +def get_output_error_code(cmd): + """Get stdout, stderr, and exit code from running a command""" + p = Popen(cmd, stdout=PIPE, stderr=PIPE) + out, err = p.communicate() + out = out.decode("utf8", "replace") # type:ignore + err = err.decode("utf8", "replace") # type:ignore + return out, err, p.returncode + + +def check_help_output(pkg, subcommand=None): + """test that `python -m PKG [subcommand] -h` works""" + cmd = [sys.executable, "-m", pkg] + if subcommand: + cmd.extend(subcommand) + cmd.append("-h") + out, err, rc = get_output_error_code(cmd) + assert rc == 0, err + assert "Traceback" not in err + assert "Options" in out + assert "--help-all" in out + return out, err + + +def check_help_all_output(pkg, subcommand=None): + """test that `python -m PKG --help-all` works""" + cmd = [sys.executable, "-m", pkg] + if subcommand: + cmd.extend(subcommand) + cmd.append("--help-all") + out, err, rc = get_output_error_code(cmd) + assert rc == 0, err + assert "Traceback" not in err + assert "Options" in out + assert "Class options" in out + return out, err diff --git a/shared/package-files/78/78b11837dc5568c36e03a1095589b8962ec774e1f10aa9952af9cea89a7216dd/blob b/shared/package-files/78/78b11837dc5568c36e03a1095589b8962ec774e1f10aa9952af9cea89a7216dd/blob new file mode 100644 index 0000000000000000000000000000000000000000..2bd9eb0073d3e0a6c56311b42097ff322f75dcdd --- /dev/null +++ b/shared/package-files/78/78b11837dc5568c36e03a1095589b8962ec774e1f10aa9952af9cea89a7216dd/blob @@ -0,0 +1,994 @@ +import builtins +import collections +import dataclasses +import inspect +import os +import sys +from array import array +from collections import Counter, UserDict, UserList, defaultdict, deque +from dataclasses import dataclass, fields, is_dataclass +from inspect import isclass +from itertools import islice +from types import MappingProxyType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + DefaultDict, + Dict, + Iterable, + List, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +from pip._vendor.rich.repr import RichReprResult + +try: + import attr as _attr_module + + _has_attrs = hasattr(_attr_module, "ib") +except ImportError: # pragma: no cover + _has_attrs = False + +from . import get_console +from ._loop import loop_last +from ._pick import pick_bool +from .abc import RichRenderable +from .cells import cell_len +from .highlighter import ReprHighlighter +from .jupyter import JupyterMixin, JupyterRenderable +from .measure import Measurement +from .text import Text + +if TYPE_CHECKING: + from .console import ( + Console, + ConsoleOptions, + HighlighterType, + JustifyMethod, + OverflowMethod, + RenderResult, + ) + + +def _is_attr_object(obj: Any) -> bool: + """Check if an object was created with attrs module.""" + return _has_attrs and _attr_module.has(type(obj)) + + +def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]: + """Get fields for an attrs object.""" + return _attr_module.fields(type(obj)) if _has_attrs else [] + + +def _is_dataclass_repr(obj: object) -> bool: + """Check if an instance of a dataclass contains the default repr. + + Args: + obj (object): A dataclass instance. + + Returns: + bool: True if the default repr is used, False if there is a custom repr. + """ + # Digging in to a lot of internals here + # Catching all exceptions in case something is missing on a non CPython implementation + try: + return obj.__repr__.__code__.co_filename == dataclasses.__file__ + except Exception: # pragma: no coverage + return False + + +_dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", []) + + +def _has_default_namedtuple_repr(obj: object) -> bool: + """Check if an instance of namedtuple contains the default repr + + Args: + obj (object): A namedtuple + + Returns: + bool: True if the default repr is used, False if there's a custom repr. + """ + obj_file = None + try: + obj_file = inspect.getfile(obj.__repr__) + except (OSError, TypeError): + # OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available. + # TypeError trapped defensively, in case of object without filename slips through. + pass + default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__) + return obj_file == default_repr_file + + +def _ipy_display_hook( + value: Any, + console: Optional["Console"] = None, + overflow: "OverflowMethod" = "ignore", + crop: bool = False, + indent_guides: bool = False, + max_length: Optional[int] = None, + max_string: Optional[int] = None, + max_depth: Optional[int] = None, + expand_all: bool = False, +) -> Union[str, None]: + # needed here to prevent circular import: + from .console import ConsoleRenderable + + # always skip rich generated jupyter renderables or None values + if _safe_isinstance(value, JupyterRenderable) or value is None: + return None + + console = console or get_console() + + with console.capture() as capture: + # certain renderables should start on a new line + if _safe_isinstance(value, ConsoleRenderable): + console.line() + console.print( + value + if _safe_isinstance(value, RichRenderable) + else Pretty( + value, + overflow=overflow, + indent_guides=indent_guides, + max_length=max_length, + max_string=max_string, + max_depth=max_depth, + expand_all=expand_all, + margin=12, + ), + crop=crop, + new_line_start=True, + end="", + ) + # strip trailing newline, not usually part of a text repr + # I'm not sure if this should be prevented at a lower level + return capture.get().rstrip("\n") + + +def _safe_isinstance( + obj: object, class_or_tuple: Union[type, Tuple[type, ...]] +) -> bool: + """isinstance can fail in rare cases, for example types with no __class__""" + try: + return isinstance(obj, class_or_tuple) + except Exception: + return False + + +def install( + console: Optional["Console"] = None, + overflow: "OverflowMethod" = "ignore", + crop: bool = False, + indent_guides: bool = False, + max_length: Optional[int] = None, + max_string: Optional[int] = None, + max_depth: Optional[int] = None, + expand_all: bool = False, +) -> None: + """Install automatic pretty printing in the Python REPL. + + Args: + console (Console, optional): Console instance or ``None`` to use global console. Defaults to None. + overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore". + crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False. + indent_guides (bool, optional): Enable indentation guides. Defaults to False. + max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. + Defaults to None. + max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None. + max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None. + expand_all (bool, optional): Expand all containers. Defaults to False. + max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. + """ + from pip._vendor.rich import get_console + + console = console or get_console() + assert console is not None + + def display_hook(value: Any) -> None: + """Replacement sys.displayhook which prettifies objects with Rich.""" + if value is not None: + assert console is not None + builtins._ = None # type: ignore[attr-defined] + console.print( + value + if _safe_isinstance(value, RichRenderable) + else Pretty( + value, + overflow=overflow, + indent_guides=indent_guides, + max_length=max_length, + max_string=max_string, + max_depth=max_depth, + expand_all=expand_all, + ), + crop=crop, + ) + builtins._ = value # type: ignore[attr-defined] + + if "get_ipython" in globals(): + ip = get_ipython() # type: ignore[name-defined] + from IPython.core.formatters import BaseFormatter + + class RichFormatter(BaseFormatter): # type: ignore[misc] + pprint: bool = True + + def __call__(self, value: Any) -> Any: + if self.pprint: + return _ipy_display_hook( + value, + console=get_console(), + overflow=overflow, + indent_guides=indent_guides, + max_length=max_length, + max_string=max_string, + max_depth=max_depth, + expand_all=expand_all, + ) + else: + return repr(value) + + # replace plain text formatter with rich formatter + rich_formatter = RichFormatter() + ip.display_formatter.formatters["text/plain"] = rich_formatter + else: + sys.displayhook = display_hook + + +class Pretty(JupyterMixin): + """A rich renderable that pretty prints an object. + + Args: + _object (Any): An object to pretty print. + highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None. + indent_size (int, optional): Number of spaces in indent. Defaults to 4. + justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None. + overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None. + no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False. + indent_guides (bool, optional): Enable indentation guides. Defaults to False. + max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. + Defaults to None. + max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None. + max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None. + expand_all (bool, optional): Expand all containers. Defaults to False. + margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0. + insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False. + """ + + def __init__( + self, + _object: Any, + highlighter: Optional["HighlighterType"] = None, + *, + indent_size: int = 4, + justify: Optional["JustifyMethod"] = None, + overflow: Optional["OverflowMethod"] = None, + no_wrap: Optional[bool] = False, + indent_guides: bool = False, + max_length: Optional[int] = None, + max_string: Optional[int] = None, + max_depth: Optional[int] = None, + expand_all: bool = False, + margin: int = 0, + insert_line: bool = False, + ) -> None: + self._object = _object + self.highlighter = highlighter or ReprHighlighter() + self.indent_size = indent_size + self.justify: Optional["JustifyMethod"] = justify + self.overflow: Optional["OverflowMethod"] = overflow + self.no_wrap = no_wrap + self.indent_guides = indent_guides + self.max_length = max_length + self.max_string = max_string + self.max_depth = max_depth + self.expand_all = expand_all + self.margin = margin + self.insert_line = insert_line + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + pretty_str = pretty_repr( + self._object, + max_width=options.max_width - self.margin, + indent_size=self.indent_size, + max_length=self.max_length, + max_string=self.max_string, + max_depth=self.max_depth, + expand_all=self.expand_all, + ) + pretty_text = Text.from_ansi( + pretty_str, + justify=self.justify or options.justify, + overflow=self.overflow or options.overflow, + no_wrap=pick_bool(self.no_wrap, options.no_wrap), + style="pretty", + ) + pretty_text = ( + self.highlighter(pretty_text) + if pretty_text + else Text( + f"{type(self._object)}.__repr__ returned empty string", + style="dim italic", + ) + ) + if self.indent_guides and not options.ascii_only: + pretty_text = pretty_text.with_indent_guides( + self.indent_size, style="repr.indent" + ) + if self.insert_line and "\n" in pretty_text: + yield "" + yield pretty_text + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + pretty_str = pretty_repr( + self._object, + max_width=options.max_width, + indent_size=self.indent_size, + max_length=self.max_length, + max_string=self.max_string, + max_depth=self.max_depth, + expand_all=self.expand_all, + ) + text_width = ( + max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0 + ) + return Measurement(text_width, text_width) + + +def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]: + return ( + f"defaultdict({_object.default_factory!r}, {{", + "})", + f"defaultdict({_object.default_factory!r}, {{}})", + ) + + +def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]: + return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})") + + +_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = { + os._Environ: lambda _object: ("environ({", "})", "environ({})"), + array: _get_braces_for_array, + defaultdict: _get_braces_for_defaultdict, + Counter: lambda _object: ("Counter({", "})", "Counter()"), + deque: lambda _object: ("deque([", "])", "deque()"), + dict: lambda _object: ("{", "}", "{}"), + UserDict: lambda _object: ("{", "}", "{}"), + frozenset: lambda _object: ("frozenset({", "})", "frozenset()"), + list: lambda _object: ("[", "]", "[]"), + UserList: lambda _object: ("[", "]", "[]"), + set: lambda _object: ("{", "}", "set()"), + tuple: lambda _object: ("(", ")", "()"), + MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"), +} +_CONTAINERS = tuple(_BRACES.keys()) +_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict) + + +def is_expandable(obj: Any) -> bool: + """Check if an object may be expanded by pretty print.""" + return ( + _safe_isinstance(obj, _CONTAINERS) + or (is_dataclass(obj)) + or (hasattr(obj, "__rich_repr__")) + or _is_attr_object(obj) + ) and not isclass(obj) + + +@dataclass +class Node: + """A node in a repr tree. May be atomic or a container.""" + + key_repr: str = "" + value_repr: str = "" + open_brace: str = "" + close_brace: str = "" + empty: str = "" + last: bool = False + is_tuple: bool = False + is_namedtuple: bool = False + children: Optional[List["Node"]] = None + key_separator: str = ": " + separator: str = ", " + + def iter_tokens(self) -> Iterable[str]: + """Generate tokens for this node.""" + if self.key_repr: + yield self.key_repr + yield self.key_separator + if self.value_repr: + yield self.value_repr + elif self.children is not None: + if self.children: + yield self.open_brace + if self.is_tuple and not self.is_namedtuple and len(self.children) == 1: + yield from self.children[0].iter_tokens() + yield "," + else: + for child in self.children: + yield from child.iter_tokens() + if not child.last: + yield self.separator + yield self.close_brace + else: + yield self.empty + + def check_length(self, start_length: int, max_length: int) -> bool: + """Check the length fits within a limit. + + Args: + start_length (int): Starting length of the line (indent, prefix, suffix). + max_length (int): Maximum length. + + Returns: + bool: True if the node can be rendered within max length, otherwise False. + """ + total_length = start_length + for token in self.iter_tokens(): + total_length += cell_len(token) + if total_length > max_length: + return False + return True + + def __str__(self) -> str: + repr_text = "".join(self.iter_tokens()) + return repr_text + + def render( + self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False + ) -> str: + """Render the node to a pretty repr. + + Args: + max_width (int, optional): Maximum width of the repr. Defaults to 80. + indent_size (int, optional): Size of indents. Defaults to 4. + expand_all (bool, optional): Expand all levels. Defaults to False. + + Returns: + str: A repr string of the original object. + """ + lines = [_Line(node=self, is_root=True)] + line_no = 0 + while line_no < len(lines): + line = lines[line_no] + if line.expandable and not line.expanded: + if expand_all or not line.check_length(max_width): + lines[line_no : line_no + 1] = line.expand(indent_size) + line_no += 1 + + repr_str = "\n".join(str(line) for line in lines) + return repr_str + + +@dataclass +class _Line: + """A line in repr output.""" + + parent: Optional["_Line"] = None + is_root: bool = False + node: Optional[Node] = None + text: str = "" + suffix: str = "" + whitespace: str = "" + expanded: bool = False + last: bool = False + + @property + def expandable(self) -> bool: + """Check if the line may be expanded.""" + return bool(self.node is not None and self.node.children) + + def check_length(self, max_length: int) -> bool: + """Check this line fits within a given number of cells.""" + start_length = ( + len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix) + ) + assert self.node is not None + return self.node.check_length(start_length, max_length) + + def expand(self, indent_size: int) -> Iterable["_Line"]: + """Expand this line by adding children on their own line.""" + node = self.node + assert node is not None + whitespace = self.whitespace + assert node.children + if node.key_repr: + new_line = yield _Line( + text=f"{node.key_repr}{node.key_separator}{node.open_brace}", + whitespace=whitespace, + ) + else: + new_line = yield _Line(text=node.open_brace, whitespace=whitespace) + child_whitespace = self.whitespace + " " * indent_size + tuple_of_one = node.is_tuple and len(node.children) == 1 + for last, child in loop_last(node.children): + separator = "," if tuple_of_one else node.separator + line = _Line( + parent=new_line, + node=child, + whitespace=child_whitespace, + suffix=separator, + last=last and not tuple_of_one, + ) + yield line + + yield _Line( + text=node.close_brace, + whitespace=whitespace, + suffix=self.suffix, + last=self.last, + ) + + def __str__(self) -> str: + if self.last: + return f"{self.whitespace}{self.text}{self.node or ''}" + else: + return ( + f"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}" + ) + + +def _is_namedtuple(obj: Any) -> bool: + """Checks if an object is most likely a namedtuple. It is possible + to craft an object that passes this check and isn't a namedtuple, but + there is only a minuscule chance of this happening unintentionally. + + Args: + obj (Any): The object to test + + Returns: + bool: True if the object is a namedtuple. False otherwise. + """ + try: + fields = getattr(obj, "_fields", None) + except Exception: + # Being very defensive - if we cannot get the attr then its not a namedtuple + return False + return isinstance(obj, tuple) and isinstance(fields, tuple) + + +def traverse( + _object: Any, + max_length: Optional[int] = None, + max_string: Optional[int] = None, + max_depth: Optional[int] = None, +) -> Node: + """Traverse object and generate a tree. + + Args: + _object (Any): Object to be traversed. + max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. + Defaults to None. + max_string (int, optional): Maximum length of string before truncating, or None to disable truncating. + Defaults to None. + max_depth (int, optional): Maximum depth of data structures, or None for no maximum. + Defaults to None. + + Returns: + Node: The root of a tree structure which can be used to render a pretty repr. + """ + + def to_repr(obj: Any) -> str: + """Get repr string for an object, but catch errors.""" + if ( + max_string is not None + and _safe_isinstance(obj, (bytes, str)) + and len(obj) > max_string + ): + truncated = len(obj) - max_string + obj_repr = f"{obj[:max_string]!r}+{truncated}" + else: + try: + obj_repr = repr(obj) + except Exception as error: + obj_repr = f"" + return obj_repr + + visited_ids: Set[int] = set() + push_visited = visited_ids.add + pop_visited = visited_ids.remove + + def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node: + """Walk the object depth first.""" + + obj_id = id(obj) + if obj_id in visited_ids: + # Recursion detected + return Node(value_repr="...") + + obj_type = type(obj) + children: List[Node] + reached_max_depth = max_depth is not None and depth >= max_depth + + def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]: + for arg in rich_args: + if _safe_isinstance(arg, tuple): + if len(arg) == 3: + key, child, default = arg + if default == child: + continue + yield key, child + elif len(arg) == 2: + key, child = arg + yield key, child + elif len(arg) == 1: + yield arg[0] + else: + yield arg + + try: + fake_attributes = hasattr( + obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492" + ) + except Exception: + fake_attributes = False + + rich_repr_result: Optional[RichReprResult] = None + if not fake_attributes: + try: + if hasattr(obj, "__rich_repr__") and not isclass(obj): + rich_repr_result = obj.__rich_repr__() + except Exception: + pass + + if rich_repr_result is not None: + push_visited(obj_id) + angular = getattr(obj.__rich_repr__, "angular", False) + args = list(iter_rich_args(rich_repr_result)) + class_name = obj.__class__.__name__ + + if args: + children = [] + append = children.append + + if reached_max_depth: + if angular: + node = Node(value_repr=f"<{class_name}...>") + else: + node = Node(value_repr=f"{class_name}(...)") + else: + if angular: + node = Node( + open_brace=f"<{class_name} ", + close_brace=">", + children=children, + last=root, + separator=" ", + ) + else: + node = Node( + open_brace=f"{class_name}(", + close_brace=")", + children=children, + last=root, + ) + for last, arg in loop_last(args): + if _safe_isinstance(arg, tuple): + key, child = arg + child_node = _traverse(child, depth=depth + 1) + child_node.last = last + child_node.key_repr = key + child_node.key_separator = "=" + append(child_node) + else: + child_node = _traverse(arg, depth=depth + 1) + child_node.last = last + append(child_node) + else: + node = Node( + value_repr=f"<{class_name}>" if angular else f"{class_name}()", + children=[], + last=root, + ) + pop_visited(obj_id) + elif _is_attr_object(obj) and not fake_attributes: + push_visited(obj_id) + children = [] + append = children.append + + attr_fields = _get_attr_fields(obj) + if attr_fields: + if reached_max_depth: + node = Node(value_repr=f"{obj.__class__.__name__}(...)") + else: + node = Node( + open_brace=f"{obj.__class__.__name__}(", + close_brace=")", + children=children, + last=root, + ) + + def iter_attrs() -> Iterable[ + Tuple[str, Any, Optional[Callable[[Any], str]]] + ]: + """Iterate over attr fields and values.""" + for attr in attr_fields: + if attr.repr: + try: + value = getattr(obj, attr.name) + except Exception as error: + # Can happen, albeit rarely + yield (attr.name, error, None) + else: + yield ( + attr.name, + value, + attr.repr if callable(attr.repr) else None, + ) + + for last, (name, value, repr_callable) in loop_last(iter_attrs()): + if repr_callable: + child_node = Node(value_repr=str(repr_callable(value))) + else: + child_node = _traverse(value, depth=depth + 1) + child_node.last = last + child_node.key_repr = name + child_node.key_separator = "=" + append(child_node) + else: + node = Node( + value_repr=f"{obj.__class__.__name__}()", children=[], last=root + ) + pop_visited(obj_id) + elif ( + is_dataclass(obj) + and not _safe_isinstance(obj, type) + and not fake_attributes + and _is_dataclass_repr(obj) + ): + push_visited(obj_id) + children = [] + append = children.append + if reached_max_depth: + node = Node(value_repr=f"{obj.__class__.__name__}(...)") + else: + node = Node( + open_brace=f"{obj.__class__.__name__}(", + close_brace=")", + children=children, + last=root, + empty=f"{obj.__class__.__name__}()", + ) + + for last, field in loop_last( + field for field in fields(obj) if field.repr + ): + child_node = _traverse(getattr(obj, field.name), depth=depth + 1) + child_node.key_repr = field.name + child_node.last = last + child_node.key_separator = "=" + append(child_node) + + pop_visited(obj_id) + elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj): + push_visited(obj_id) + class_name = obj.__class__.__name__ + if reached_max_depth: + # If we've reached the max depth, we still show the class name, but not its contents + node = Node( + value_repr=f"{class_name}(...)", + ) + else: + children = [] + append = children.append + node = Node( + open_brace=f"{class_name}(", + close_brace=")", + children=children, + empty=f"{class_name}()", + ) + for last, (key, value) in loop_last(obj._asdict().items()): + child_node = _traverse(value, depth=depth + 1) + child_node.key_repr = key + child_node.last = last + child_node.key_separator = "=" + append(child_node) + pop_visited(obj_id) + elif _safe_isinstance(obj, _CONTAINERS): + for container_type in _CONTAINERS: + if _safe_isinstance(obj, container_type): + obj_type = container_type + break + + push_visited(obj_id) + + open_brace, close_brace, empty = _BRACES[obj_type](obj) + + if reached_max_depth: + node = Node(value_repr=f"{open_brace}...{close_brace}") + elif obj_type.__repr__ != type(obj).__repr__: + node = Node(value_repr=to_repr(obj), last=root) + elif obj: + children = [] + node = Node( + open_brace=open_brace, + close_brace=close_brace, + children=children, + last=root, + ) + append = children.append + num_items = len(obj) + last_item_index = num_items - 1 + + if _safe_isinstance(obj, _MAPPING_CONTAINERS): + iter_items = iter(obj.items()) + if max_length is not None: + iter_items = islice(iter_items, max_length) + for index, (key, child) in enumerate(iter_items): + child_node = _traverse(child, depth=depth + 1) + child_node.key_repr = to_repr(key) + child_node.last = index == last_item_index + append(child_node) + else: + iter_values = iter(obj) + if max_length is not None: + iter_values = islice(iter_values, max_length) + for index, child in enumerate(iter_values): + child_node = _traverse(child, depth=depth + 1) + child_node.last = index == last_item_index + append(child_node) + if max_length is not None and num_items > max_length: + append(Node(value_repr=f"... +{num_items - max_length}", last=True)) + else: + node = Node(empty=empty, children=[], last=root) + + pop_visited(obj_id) + else: + node = Node(value_repr=to_repr(obj), last=root) + node.is_tuple = _safe_isinstance(obj, tuple) + node.is_namedtuple = _is_namedtuple(obj) + return node + + node = _traverse(_object, root=True) + return node + + +def pretty_repr( + _object: Any, + *, + max_width: int = 80, + indent_size: int = 4, + max_length: Optional[int] = None, + max_string: Optional[int] = None, + max_depth: Optional[int] = None, + expand_all: bool = False, +) -> str: + """Prettify repr string by expanding on to new lines to fit within a given width. + + Args: + _object (Any): Object to repr. + max_width (int, optional): Desired maximum width of repr string. Defaults to 80. + indent_size (int, optional): Number of spaces to indent. Defaults to 4. + max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. + Defaults to None. + max_string (int, optional): Maximum length of string before truncating, or None to disable truncating. + Defaults to None. + max_depth (int, optional): Maximum depth of nested data structure, or None for no depth. + Defaults to None. + expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False. + + Returns: + str: A possibly multi-line representation of the object. + """ + + if _safe_isinstance(_object, Node): + node = _object + else: + node = traverse( + _object, max_length=max_length, max_string=max_string, max_depth=max_depth + ) + repr_str: str = node.render( + max_width=max_width, indent_size=indent_size, expand_all=expand_all + ) + return repr_str + + +def pprint( + _object: Any, + *, + console: Optional["Console"] = None, + indent_guides: bool = True, + max_length: Optional[int] = None, + max_string: Optional[int] = None, + max_depth: Optional[int] = None, + expand_all: bool = False, +) -> None: + """A convenience function for pretty printing. + + Args: + _object (Any): Object to pretty print. + console (Console, optional): Console instance, or None to use default. Defaults to None. + max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. + Defaults to None. + max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None. + max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None. + indent_guides (bool, optional): Enable indentation guides. Defaults to True. + expand_all (bool, optional): Expand all containers. Defaults to False. + """ + _console = get_console() if console is None else console + _console.print( + Pretty( + _object, + max_length=max_length, + max_string=max_string, + max_depth=max_depth, + indent_guides=indent_guides, + expand_all=expand_all, + overflow="ignore", + ), + soft_wrap=True, + ) + + +if __name__ == "__main__": # pragma: no cover + + class BrokenRepr: + def __repr__(self) -> str: + 1 / 0 + return "this will fail" + + from typing import NamedTuple + + class StockKeepingUnit(NamedTuple): + name: str + description: str + price: float + category: str + reviews: List[str] + + d = defaultdict(int) + d["foo"] = 5 + data = { + "foo": [ + 1, + "Hello World!", + 100.123, + 323.232, + 432324.0, + {5, 6, 7, (1, 2, 3, 4), 8}, + ], + "bar": frozenset({1, 2, 3}), + "defaultdict": defaultdict( + list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]} + ), + "counter": Counter( + [ + "apple", + "orange", + "pear", + "kumquat", + "kumquat", + "durian" * 100, + ] + ), + "atomic": (False, True, None), + "namedtuple": StockKeepingUnit( + "Sparkling British Spring Water", + "Carbonated spring water", + 0.9, + "water", + ["its amazing!", "its terrible!"], + ), + "Broken": BrokenRepr(), + } + data["foo"].append(data) # type: ignore[attr-defined] + + from pip._vendor.rich import print + + # print(Pretty(data, indent_guides=True, max_string=20)) + + class Thing: + def __repr__(self) -> str: + return "Hello\x1b[38;5;239m World!" + + print(Pretty(Thing())) diff --git a/shared/package-files/78/78b1af6aaa7175aa13d428134edce7f7f3e5089edf2cc999fefa9c0ec4de048d/blob b/shared/package-files/78/78b1af6aaa7175aa13d428134edce7f7f3e5089edf2cc999fefa9c0ec4de048d/blob new file mode 100644 index 0000000000000000000000000000000000000000..f3a9ce96e64c00f2818b43d147baaa363d6895ee --- /dev/null +++ b/shared/package-files/78/78b1af6aaa7175aa13d428134edce7f7f3e5089edf2cc999fefa9c0ec4de048d/blob @@ -0,0 +1,31 @@ +from ...utils._typedefs cimport intp_t, float64_t + +{{for name_suffix in ['64', '32']}} + +from ._base cimport BaseDistancesReduction{{name_suffix}} +from ._middle_term_computer cimport MiddleTermComputer{{name_suffix}} + +cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): + """float{{name_suffix}} implementation of the ArgKmin.""" + + cdef: + intp_t k + + intp_t[:, ::1] argkmin_indices + float64_t[:, ::1] argkmin_distances + + # Used as array of pointers to private datastructures used in threads. + float64_t ** heaps_r_distances_chunks + intp_t ** heaps_indices_chunks + + +cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): + """EuclideanDistance-specialisation of ArgKmin{{name_suffix}}.""" + cdef: + MiddleTermComputer{{name_suffix}} middle_term_computer + const float64_t[::1] X_norm_squared + const float64_t[::1] Y_norm_squared + + bint use_squared_distances + +{{endfor}} diff --git a/shared/package-files/78/78b220ec6aa34a346a52d9ebe5952f0a0e436b041ec07e64b3d369a0c7cedd04/blob b/shared/package-files/78/78b220ec6aa34a346a52d9ebe5952f0a0e436b041ec07e64b3d369a0c7cedd04/blob new file mode 100644 index 0000000000000000000000000000000000000000..dd642ba838afb7562737c79535262514429a2185 --- /dev/null +++ b/shared/package-files/78/78b220ec6aa34a346a52d9ebe5952f0a0e436b041ec07e64b3d369a0c7cedd04/blob @@ -0,0 +1,1089 @@ +import functools +import os +import sys +import traceback + +import matplotlib as mpl +from matplotlib import _api, backend_tools, cbook +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import ( + _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, + TimerBase, cursors, ToolContainerBase, MouseButton, + CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent, + _allow_interrupt) +import matplotlib.backends.qt_editor.figureoptions as figureoptions +from . import qt_compat +from .qt_compat import ( + QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted) + + +# SPECIAL_KEYS are Qt::Key that do *not* return their Unicode name +# instead they have manually specified names. +SPECIAL_KEYS = { + _to_int(getattr(QtCore.Qt.Key, k)): v for k, v in [ + ("Key_Escape", "escape"), + ("Key_Tab", "tab"), + ("Key_Backspace", "backspace"), + ("Key_Return", "enter"), + ("Key_Enter", "enter"), + ("Key_Insert", "insert"), + ("Key_Delete", "delete"), + ("Key_Pause", "pause"), + ("Key_SysReq", "sysreq"), + ("Key_Clear", "clear"), + ("Key_Home", "home"), + ("Key_End", "end"), + ("Key_Left", "left"), + ("Key_Up", "up"), + ("Key_Right", "right"), + ("Key_Down", "down"), + ("Key_PageUp", "pageup"), + ("Key_PageDown", "pagedown"), + ("Key_Shift", "shift"), + # In macOS, the control and super (aka cmd/apple) keys are switched. + ("Key_Control", "control" if sys.platform != "darwin" else "cmd"), + ("Key_Meta", "meta" if sys.platform != "darwin" else "control"), + ("Key_Alt", "alt"), + ("Key_CapsLock", "caps_lock"), + ("Key_F1", "f1"), + ("Key_F2", "f2"), + ("Key_F3", "f3"), + ("Key_F4", "f4"), + ("Key_F5", "f5"), + ("Key_F6", "f6"), + ("Key_F7", "f7"), + ("Key_F8", "f8"), + ("Key_F9", "f9"), + ("Key_F10", "f10"), + ("Key_F11", "f11"), + ("Key_F12", "f12"), + ("Key_Super_L", "super"), + ("Key_Super_R", "super"), + ] +} +# Define which modifier keys are collected on keyboard events. +# Elements are (Qt::KeyboardModifiers, Qt::Key) tuples. +# Order determines the modifier order (ctrl+alt+...) reported by Matplotlib. +_MODIFIER_KEYS = [ + (_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)), + _to_int(getattr(QtCore.Qt.Key, key))) + for mod, key in [ + ("ControlModifier", "Key_Control"), + ("AltModifier", "Key_Alt"), + ("ShiftModifier", "Key_Shift"), + ("MetaModifier", "Key_Meta"), + ] +] +cursord = { + k: getattr(QtCore.Qt.CursorShape, v) for k, v in [ + (cursors.MOVE, "SizeAllCursor"), + (cursors.HAND, "PointingHandCursor"), + (cursors.POINTER, "ArrowCursor"), + (cursors.SELECT_REGION, "CrossCursor"), + (cursors.WAIT, "WaitCursor"), + (cursors.RESIZE_HORIZONTAL, "SizeHorCursor"), + (cursors.RESIZE_VERTICAL, "SizeVerCursor"), + ] +} + + +# lru_cache keeps a reference to the QApplication instance, keeping it from +# being GC'd. +@functools.lru_cache(1) +def _create_qApp(): + app = QtWidgets.QApplication.instance() + + # Create a new QApplication and configure it if none exists yet, as only + # one QApplication can exist at a time. + if app is None: + # display_is_valid returns False only if on Linux and neither X11 + # nor Wayland display can be opened. + if not mpl._c_internal_utils.display_is_valid(): + raise RuntimeError('Invalid DISPLAY variable') + + # Check to make sure a QApplication from a different major version + # of Qt is not instantiated in the process + if QT_API in {'PyQt6', 'PySide6'}: + other_bindings = ('PyQt5', 'PySide2') + qt_version = 6 + elif QT_API in {'PyQt5', 'PySide2'}: + other_bindings = ('PyQt6', 'PySide6') + qt_version = 5 + else: + raise RuntimeError("Should never be here") + + for binding in other_bindings: + mod = sys.modules.get(f'{binding}.QtWidgets') + if mod is not None and mod.QApplication.instance() is not None: + other_core = sys.modules.get(f'{binding}.QtCore') + _api.warn_external( + f'Matplotlib is using {QT_API} which wraps ' + f'{QtCore.qVersion()} however an instantiated ' + f'QApplication from {binding} which wraps ' + f'{other_core.qVersion()} exists. Mixing Qt major ' + 'versions may not work as expected.' + ) + break + if qt_version == 5: + try: + QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) + except AttributeError: # Only for Qt>=5.6, <6. + pass + try: + QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy( + QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) + except AttributeError: # Only for Qt>=5.14. + pass + app = QtWidgets.QApplication(["matplotlib"]) + if sys.platform == "darwin": + image = str(cbook._get_data_path('images/matplotlib.svg')) + icon = QtGui.QIcon(image) + app.setWindowIcon(icon) + app.setQuitOnLastWindowClosed(True) + cbook._setup_new_guiapp() + if qt_version == 5: + app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) + + return app + + +def _allow_interrupt_qt(qapp_or_eventloop): + """A context manager that allows terminating a plot by sending a SIGINT.""" + + # Use QSocketNotifier to read the socketpair while the Qt event loop runs. + + def prepare_notifier(rsock): + sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read) + + @sn.activated.connect + def _may_clear_sock(): + # Running a Python function on socket activation gives the interpreter a + # chance to handle the signal in Python land. We also need to drain the + # socket with recv() to re-arm it, because it will be written to as part of + # the wakeup. (We need this in case set_wakeup_fd catches a signal other + # than SIGINT and we shall continue waiting.) + try: + rsock.recv(1) + except BlockingIOError: + # This may occasionally fire too soon or more than once on Windows, so + # be forgiving about reading an empty socket. + pass + + # We return the QSocketNotifier so that the caller holds a reference, and we + # also explicitly clean it up in handle_sigint(). Without doing both, deletion + # of the socket notifier can happen prematurely or not at all. + return sn + + def handle_sigint(sn): + sn.deleteLater() + QtCore.QCoreApplication.sendPostedEvents(sn, QtCore.QEvent.Type.DeferredDelete) + if hasattr(qapp_or_eventloop, 'closeAllWindows'): + qapp_or_eventloop.closeAllWindows() + qapp_or_eventloop.quit() + + return _allow_interrupt(prepare_notifier, handle_sigint) + + +class TimerQT(TimerBase): + """Subclass of `.TimerBase` using QTimer events.""" + + def __init__(self, *args, **kwargs): + # Create a new timer and connect the timeout() signal to the + # _on_timer method. + self._timer = QtCore.QTimer() + self._timer.timeout.connect(self._on_timer) + super().__init__(*args, **kwargs) + + def __del__(self): + # The check for deletedness is needed to avoid an error at animation + # shutdown with PySide2. + if not _isdeleted(self._timer): + self._timer_stop() + + def _timer_set_single_shot(self): + self._timer.setSingleShot(self._single) + + def _timer_set_interval(self): + self._timer.setInterval(self._interval) + + def _timer_start(self): + self._timer.start() + + def _timer_stop(self): + self._timer.stop() + + +class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget): + required_interactive_framework = "qt" + _timer_cls = TimerQT + manager_class = _api.classproperty(lambda cls: FigureManagerQT) + + buttond = { + getattr(QtCore.Qt.MouseButton, k): v for k, v in [ + ("LeftButton", MouseButton.LEFT), + ("RightButton", MouseButton.RIGHT), + ("MiddleButton", MouseButton.MIDDLE), + ("XButton1", MouseButton.BACK), + ("XButton2", MouseButton.FORWARD), + ] + } + + def __init__(self, figure=None): + _create_qApp() + super().__init__(figure=figure) + + self._draw_pending = False + self._is_drawing = False + self._draw_rect_callback = lambda painter: None + self._in_resize_event = False + + self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent) + self.setMouseTracking(True) + self.resize(*self.get_width_height()) + + palette = QtGui.QPalette(QtGui.QColor("white")) + self.setPalette(palette) + + @QtCore.Slot() + def _update_pixel_ratio(self): + if self._set_device_pixel_ratio( + self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0 + # The easiest way to resize the canvas is to emit a resizeEvent + # since we implement all the logic for resizing the canvas for + # that event. + event = QtGui.QResizeEvent(self.size(), self.size()) + self.resizeEvent(event) + + @QtCore.Slot(QtGui.QScreen) + def _update_screen(self, screen): + # Handler for changes to a window's attached screen. + self._update_pixel_ratio() + if screen is not None: + screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio) + screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio) + + def eventFilter(self, source, event): + if event.type() == QtCore.QEvent.Type.DevicePixelRatioChange: + self._update_pixel_ratio() + return super().eventFilter(source, event) + + def showEvent(self, event): + # Set up correct pixel ratio, and connect to any signal changes for it, + # once the window is shown (and thus has these attributes). + window = self.window().windowHandle() + current_version = tuple(int(x) for x in QtCore.qVersion().split('.', 2)[:2]) + if current_version >= (6, 6): + self._update_pixel_ratio() + window.installEventFilter(self) + else: + window.screenChanged.connect(self._update_screen) + self._update_screen(window.screen()) + + def set_cursor(self, cursor): + # docstring inherited + self.setCursor(_api.check_getitem(cursord, cursor=cursor)) + + def mouseEventCoords(self, pos=None): + """ + Calculate mouse coordinates in physical pixels. + + Qt uses logical pixels, but the figure is scaled to physical + pixels for rendering. Transform to physical pixels so that + all of the down-stream transforms work as expected. + + Also, the origin is different and needs to be corrected. + """ + if pos is None: + pos = self.mapFromGlobal(QtGui.QCursor.pos()) + elif hasattr(pos, "position"): # qt6 QtGui.QEvent + pos = pos.position() + elif hasattr(pos, "pos"): # qt5 QtCore.QEvent + pos = pos.pos() + # (otherwise, it's already a QPoint) + x = pos.x() + # flip y so y=0 is bottom of canvas + y = self.figure.bbox.height / self.device_pixel_ratio - pos.y() + return x * self.device_pixel_ratio, y * self.device_pixel_ratio + + def enterEvent(self, event): + # Force querying of the modifiers, as the cached modifier state can + # have been invalidated while the window was out of focus. + mods = QtWidgets.QApplication.instance().queryKeyboardModifiers() + if self.figure is None: + return + LocationEvent("figure_enter_event", self, + *self.mouseEventCoords(event), + modifiers=self._mpl_modifiers(mods), + guiEvent=event)._process() + + def leaveEvent(self, event): + QtWidgets.QApplication.restoreOverrideCursor() + if self.figure is None: + return + LocationEvent("figure_leave_event", self, + *self.mouseEventCoords(), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mousePressEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_press_event", self, + *self.mouseEventCoords(event), button, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseDoubleClickEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_press_event", self, + *self.mouseEventCoords(event), button, dblclick=True, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseMoveEvent(self, event): + if self.figure is None: + return + MouseEvent("motion_notify_event", self, + *self.mouseEventCoords(event), + buttons=self._mpl_buttons(event.buttons()), + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def mouseReleaseEvent(self, event): + button = self.buttond.get(event.button()) + if button is not None and self.figure is not None: + MouseEvent("button_release_event", self, + *self.mouseEventCoords(event), button, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def wheelEvent(self, event): + # from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not + # provided (`isNull()`) and is unreliable on X11 ("xcb"). + if (event.pixelDelta().isNull() + or QtWidgets.QApplication.instance().platformName() == "xcb"): + steps = event.angleDelta().y() / 120 + else: + steps = event.pixelDelta().y() + if steps and self.figure is not None: + MouseEvent("scroll_event", self, + *self.mouseEventCoords(event), step=steps, + modifiers=self._mpl_modifiers(), + guiEvent=event)._process() + + def keyPressEvent(self, event): + key = self._get_key(event) + if key is not None and self.figure is not None: + KeyEvent("key_press_event", self, + key, *self.mouseEventCoords(), + guiEvent=event)._process() + + def keyReleaseEvent(self, event): + key = self._get_key(event) + if key is not None and self.figure is not None: + KeyEvent("key_release_event", self, + key, *self.mouseEventCoords(), + guiEvent=event)._process() + + def resizeEvent(self, event): + if self._in_resize_event: # Prevent PyQt6 recursion + return + if self.figure is None: + return + self._in_resize_event = True + try: + w = event.size().width() * self.device_pixel_ratio + h = event.size().height() * self.device_pixel_ratio + dpival = self.figure.dpi + winch = w / dpival + hinch = h / dpival + self.figure.set_size_inches(winch, hinch, forward=False) + # pass back into Qt to let it finish + QtWidgets.QWidget.resizeEvent(self, event) + # emit our resize events + ResizeEvent("resize_event", self)._process() + self.draw_idle() + finally: + self._in_resize_event = False + + def sizeHint(self): + w, h = self.get_width_height() + return QtCore.QSize(w, h) + + def minimumSizeHint(self): + return QtCore.QSize(10, 10) + + @staticmethod + def _mpl_buttons(buttons): + buttons = _to_int(buttons) + # State *after* press/release. + return {button for mask, button in FigureCanvasQT.buttond.items() + if _to_int(mask) & buttons} + + @staticmethod + def _mpl_modifiers(modifiers=None, *, exclude=None): + if modifiers is None: + modifiers = QtWidgets.QApplication.instance().keyboardModifiers() + modifiers = _to_int(modifiers) + # get names of the pressed modifier keys + # 'control' is named 'control' when a standalone key, but 'ctrl' when a + # modifier + # bit twiddling to pick out modifier keys from modifiers bitmask, + # if exclude is a MODIFIER, it should not be duplicated in mods + return [SPECIAL_KEYS[key].replace('control', 'ctrl') + for mask, key in _MODIFIER_KEYS + if exclude != key and modifiers & mask] + + def _get_key(self, event): + event_key = event.key() + mods = self._mpl_modifiers(exclude=event_key) + try: + # for certain keys (enter, left, backspace, etc) use a word for the + # key, rather than Unicode + key = SPECIAL_KEYS[event_key] + except KeyError: + # Unicode defines code points up to 0x10ffff (sys.maxunicode) + # QT will use Key_Codes larger than that for keyboard keys that are + # not Unicode characters (like multimedia keys) + # skip these + # if you really want them, you should add them to SPECIAL_KEYS + if event_key > sys.maxunicode: + return None + + key = chr(event_key) + # qt delivers capitalized letters. fix capitalization + # note that capslock is ignored + if 'shift' in mods: + mods.remove('shift') + else: + key = key.lower() + + return '+'.join(mods + [key]) + + def flush_events(self): + # docstring inherited + QtWidgets.QApplication.instance().processEvents() + + def start_event_loop(self, timeout=0): + # docstring inherited + if hasattr(self, "_event_loop") and self._event_loop.isRunning(): + raise RuntimeError("Event loop already running") + self._event_loop = event_loop = QtCore.QEventLoop() + if timeout > 0: + _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit) + + with _allow_interrupt_qt(event_loop): + qt_compat._exec(event_loop) + + def stop_event_loop(self, event=None): + # docstring inherited + if hasattr(self, "_event_loop"): + self._event_loop.quit() + + def draw(self): + """Render the figure, and queue a request for a Qt draw.""" + # The renderer draw is done here; delaying causes problems with code + # that uses the result of the draw() to update plot elements. + if self._is_drawing: + return + with cbook._setattr_cm(self, _is_drawing=True): + super().draw() + self.update() + + def draw_idle(self): + """Queue redraw of the Agg buffer and request Qt paintEvent.""" + # The Agg draw needs to be handled by the same thread Matplotlib + # modifies the scene graph from. Post Agg draw request to the + # current event loop in order to ensure thread affinity and to + # accumulate multiple draw requests from event handling. + # TODO: queued signal connection might be safer than singleShot + if not (getattr(self, '_draw_pending', False) or + getattr(self, '_is_drawing', False)): + self._draw_pending = True + QtCore.QTimer.singleShot(0, self._draw_idle) + + def blit(self, bbox=None): + # docstring inherited + if bbox is None and self.figure: + bbox = self.figure.bbox # Blit the entire canvas if bbox is None. + # repaint uses logical pixels, not physical pixels like the renderer. + l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds) + t = b + h + self.repaint(l, self.rect().height() - t, w, h) + + def _draw_idle(self): + with self._idle_draw_cntx(): + if not self._draw_pending: + return + self._draw_pending = False + if _isdeleted(self) or self.height() <= 0 or self.width() <= 0: + return + try: + self.draw() + except Exception: + # Uncaught exceptions are fatal for PyQt5, so catch them. + traceback.print_exc() + + def drawRectangle(self, rect): + # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs + # to be called at the end of paintEvent. + if rect is not None: + x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect) + x1 = x0 + w + y1 = y0 + h + def _draw_rect_callback(painter): + pen = QtGui.QPen( + QtGui.QColor("black"), + 1 / self.device_pixel_ratio + ) + + pen.setDashPattern([3, 3]) + for color, offset in [ + (QtGui.QColor("black"), 0), + (QtGui.QColor("white"), 3), + ]: + pen.setDashOffset(offset) + pen.setColor(color) + painter.setPen(pen) + # Draw the lines from x0, y0 towards x1, y1 so that the + # dashes don't "jump" when moving the zoom box. + painter.drawLine(x0, y0, x0, y1) + painter.drawLine(x0, y0, x1, y0) + painter.drawLine(x0, y1, x1, y1) + painter.drawLine(x1, y0, x1, y1) + else: + def _draw_rect_callback(painter): + return + self._draw_rect_callback = _draw_rect_callback + self.update() + + +class MainWindow(QtWidgets.QMainWindow): + closing = QtCore.Signal() + + def closeEvent(self, event): + self.closing.emit() + super().closeEvent(event) + + +class FigureManagerQT(FigureManagerBase): + """ + Attributes + ---------- + canvas : `FigureCanvas` + The FigureCanvas instance + num : int or str + The Figure number + toolbar : qt.QToolBar + The qt.QToolBar + window : qt.QMainWindow + The qt.QMainWindow + """ + + def __init__(self, canvas, num): + self.window = MainWindow() + super().__init__(canvas, num) + self.window.closing.connect(self._widgetclosed) + + if sys.platform != "darwin": + image = str(cbook._get_data_path('images/matplotlib.svg')) + icon = QtGui.QIcon(image) + self.window.setWindowIcon(icon) + + self.window._destroying = False + + if self.toolbar: + self.window.addToolBar(self.toolbar) + tbs_height = self.toolbar.sizeHint().height() + else: + tbs_height = 0 + + # resize the main window so it will display the canvas with the + # requested size: + cs = canvas.sizeHint() + cs_height = cs.height() + height = cs_height + tbs_height + self.window.resize(cs.width(), height) + + self.window.setCentralWidget(self.canvas) + + if mpl.is_interactive(): + self.window.show() + self.canvas.draw_idle() + + # Give the keyboard focus to the figure instead of the manager: + # StrongFocus accepts both tab and click to focus and will enable the + # canvas to process event without clicking. + # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum + self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) + self.canvas.setFocus() + + self.window.raise_() + + def full_screen_toggle(self): + if self.window.isFullScreen(): + self.window.showNormal() + else: + self.window.showFullScreen() + + def _widgetclosed(self): + CloseEvent("close_event", self.canvas)._process() + if self.window._destroying: + return + self.window._destroying = True + try: + Gcf.destroy(self) + except AttributeError: + pass + # It seems that when the python session is killed, + # Gcf can get destroyed before the Gcf.destroy + # line is run, leading to a useless AttributeError. + + def resize(self, width, height): + # The Qt methods return sizes in 'virtual' pixels so we do need to + # rescale from physical to logical pixels. + width = int(width / self.canvas.device_pixel_ratio) + height = int(height / self.canvas.device_pixel_ratio) + extra_width = self.window.width() - self.canvas.width() + extra_height = self.window.height() - self.canvas.height() + self.canvas.resize(width, height) + self.window.resize(width + extra_width, height + extra_height) + + @classmethod + def start_main_loop(cls): + qapp = QtWidgets.QApplication.instance() + if qapp: + with _allow_interrupt_qt(qapp): + qt_compat._exec(qapp) + + def show(self): + self.window._destroying = False + self.window.show() + if mpl.rcParams['figure.raise_window']: + self.window.activateWindow() + self.window.raise_() + + def destroy(self, *args): + # check for qApp first, as PySide deletes it in its atexit handler + if QtWidgets.QApplication.instance() is None: + return + if self.window._destroying: + return + self.window._destroying = True + if self.toolbar: + self.toolbar.destroy() + self.window.close() + + def get_window_title(self): + return self.window.windowTitle() + + def set_window_title(self, title): + self.window.setWindowTitle(title) + + +class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): + toolitems = [*NavigationToolbar2.toolitems] + toolitems.insert( + # Add 'customize' action after 'subplots' + [name for name, *_ in toolitems].index("Subplots") + 1, + ("Customize", "Edit axis, curve and image parameters", + "qt4_editor_options", "edit_parameters")) + + def __init__(self, canvas, parent=None, coordinates=True): + """coordinates: should we show the coordinates on the right?""" + QtWidgets.QToolBar.__init__(self, parent) + self.setAllowedAreas(QtCore.Qt.ToolBarArea( + _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | + _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) + self.coordinates = coordinates + self._actions = {} # mapping of toolitem method names to QActions. + self._subplot_dialog = None + + for text, tooltip_text, image_file, callback in self.toolitems: + if text is None: + self.addSeparator() + else: + slot = getattr(self, callback) + # https://bugreports.qt.io/browse/PYSIDE-2512 + slot = functools.wraps(slot)(functools.partial(slot)) + slot = QtCore.Slot()(slot) + + a = self.addAction(self._icon(image_file + '.png'), + text, slot) + self._actions[callback] = a + if callback in ['zoom', 'pan']: + a.setCheckable(True) + if tooltip_text is not None: + a.setToolTip(tooltip_text) + + # Add the (x, y) location widget at the right side of the toolbar + # The stretch factor is 1 which means any resizing of the toolbar + # will resize this label instead of the buttons. + if self.coordinates: + self.locLabel = QtWidgets.QLabel("", self) + self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag( + _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | + _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) + + self.locLabel.setSizePolicy(QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Policy.Expanding, + QtWidgets.QSizePolicy.Policy.Ignored, + )) + labelAction = self.addWidget(self.locLabel) + labelAction.setVisible(True) + + NavigationToolbar2.__init__(self, canvas) + + def _icon(self, name): + """ + Construct a `.QIcon` from an image file *name*, including the extension + and relative to Matplotlib's "images" data directory. + """ + # use a high-resolution icon with suffix '_large' if available + # note: user-provided icons may not have '_large' versions + path_regular = cbook._get_data_path('images', name) + path_large = path_regular.with_name( + path_regular.name.replace('.png', '_large.png')) + filename = str(path_large if path_large.exists() else path_regular) + + pm = QtGui.QPixmap(filename) + pm.setDevicePixelRatio( + self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0 + if self.palette().color(self.backgroundRole()).value() < 128: + icon_color = self.palette().color(self.foregroundRole()) + mask = pm.createMaskFromColor( + QtGui.QColor('black'), + QtCore.Qt.MaskMode.MaskOutColor) + pm.fill(icon_color) + pm.setMask(mask) + return QtGui.QIcon(pm) + + def edit_parameters(self): + axes = self.canvas.figure.get_axes() + if not axes: + QtWidgets.QMessageBox.warning( + self.canvas.parent(), "Error", "There are no Axes to edit.") + return + elif len(axes) == 1: + ax, = axes + else: + titles = [ + ax.get_label() or + ax.get_title() or + ax.get_title("left") or + ax.get_title("right") or + " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or + f"" + for ax in axes] + duplicate_titles = [ + title for title in titles if titles.count(title) > 1] + for i, ax in enumerate(axes): + if titles[i] in duplicate_titles: + titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles. + item, ok = QtWidgets.QInputDialog.getItem( + self.canvas.parent(), + 'Customize', 'Select Axes:', titles, 0, False) + if not ok: + return + ax = axes[titles.index(item)] + figureoptions.figure_edit(ax, self) + + def _update_buttons_checked(self): + # sync button checkstates to match active mode + if 'pan' in self._actions: + self._actions['pan'].setChecked(self.mode.name == 'PAN') + if 'zoom' in self._actions: + self._actions['zoom'].setChecked(self.mode.name == 'ZOOM') + + def pan(self, *args): + super().pan(*args) + self._update_buttons_checked() + + def zoom(self, *args): + super().zoom(*args) + self._update_buttons_checked() + + def set_message(self, s): + if self.coordinates: + self.locLabel.setText(s) + + def draw_rubberband(self, event, x0, y0, x1, y1): + height = self.canvas.figure.bbox.height + y1 = height - y1 + y0 = height - y0 + rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] + self.canvas.drawRectangle(rect) + + def remove_rubberband(self): + self.canvas.drawRectangle(None) + + def configure_subplots(self): + if self._subplot_dialog is None: + self._subplot_dialog = SubplotToolQt( + self.canvas.figure, self.canvas.parent()) + self.canvas.mpl_connect( + "close_event", lambda e: self._subplot_dialog.reject()) + self._subplot_dialog.update_from_current_subplotpars() + self._subplot_dialog.setModal(True) + self._subplot_dialog.show() + return self._subplot_dialog + + def save_figure(self, *args): + filetypes = self.canvas.get_supported_filetypes_grouped() + sorted_filetypes = sorted(filetypes.items()) + default_filetype = self.canvas.get_default_filetype() + + startpath = os.path.expanduser(mpl.rcParams['savefig.directory']) + start = os.path.join(startpath, self.canvas.get_default_filename()) + filters = [] + selectedFilter = None + for name, exts in sorted_filetypes: + exts_list = " ".join(['*.%s' % ext for ext in exts]) + filter = f'{name} ({exts_list})' + if default_filetype in exts: + selectedFilter = filter + filters.append(filter) + filters = ';;'.join(filters) + + fname, filter = QtWidgets.QFileDialog.getSaveFileName( + self.canvas.parent(), "Choose a filename to save to", start, + filters, selectedFilter) + if fname: + # Save dir for next time, unless empty str (i.e., use cwd). + if startpath != "": + mpl.rcParams['savefig.directory'] = os.path.dirname(fname) + try: + self.canvas.figure.savefig(fname) + except Exception as e: + QtWidgets.QMessageBox.critical( + self, "Error saving file", str(e), + QtWidgets.QMessageBox.StandardButton.Ok, + QtWidgets.QMessageBox.StandardButton.NoButton) + return fname + + def set_history_buttons(self): + can_backward = self._nav_stack._pos > 0 + can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 + if 'back' in self._actions: + self._actions['back'].setEnabled(can_backward) + if 'forward' in self._actions: + self._actions['forward'].setEnabled(can_forward) + + +class SubplotToolQt(QtWidgets.QDialog): + def __init__(self, targetfig, parent): + super().__init__(parent) + self.setWindowIcon(QtGui.QIcon( + str(cbook._get_data_path("images/matplotlib.png")))) + self.setObjectName("SubplotTool") + self._spinboxes = {} + main_layout = QtWidgets.QHBoxLayout() + self.setLayout(main_layout) + for group, spinboxes, buttons in [ + ("Borders", + ["top", "bottom", "left", "right"], + [("Export values", self._export_values)]), + ("Spacings", + ["hspace", "wspace"], + [("Tight layout", self._tight_layout), + ("Reset", self._reset), + ("Close", self.close)])]: + layout = QtWidgets.QVBoxLayout() + main_layout.addLayout(layout) + box = QtWidgets.QGroupBox(group) + layout.addWidget(box) + inner = QtWidgets.QFormLayout(box) + for name in spinboxes: + self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox() + spinbox.setRange(0, 1) + spinbox.setDecimals(3) + spinbox.setSingleStep(0.005) + spinbox.setKeyboardTracking(False) + spinbox.valueChanged.connect(self._on_value_changed) + inner.addRow(name, spinbox) + layout.addStretch(1) + for name, method in buttons: + button = QtWidgets.QPushButton(name) + # Don't trigger on , which is used to input values. + button.setAutoDefault(False) + button.clicked.connect(method) + layout.addWidget(button) + if name == "Close": + button.setFocus() + self._figure = targetfig + self._defaults = {} + self._export_values_dialog = None + self.update_from_current_subplotpars() + + def update_from_current_subplotpars(self): + self._defaults = {spinbox: getattr(self._figure.subplotpars, name) + for name, spinbox in self._spinboxes.items()} + self._reset() # Set spinbox current values without triggering signals. + + def _export_values(self): + # Explicitly round to 3 decimals (which is also the spinbox precision) + # to avoid numbers of the form 0.100...001. + self._export_values_dialog = QtWidgets.QDialog() + layout = QtWidgets.QVBoxLayout() + self._export_values_dialog.setLayout(layout) + text = QtWidgets.QPlainTextEdit() + text.setReadOnly(True) + layout.addWidget(text) + text.setPlainText( + ",\n".join(f"{attr}={spinbox.value():.3}" + for attr, spinbox in self._spinboxes.items())) + # Adjust the height of the text widget to fit the whole text, plus + # some padding. + size = text.maximumSize() + size.setHeight( + QtGui.QFontMetrics(text.document().defaultFont()) + .size(0, text.toPlainText()).height() + 20) + text.setMaximumSize(size) + self._export_values_dialog.show() + + def _on_value_changed(self): + spinboxes = self._spinboxes + # Set all mins and maxes, so that this can also be used in _reset(). + for lower, higher in [("bottom", "top"), ("left", "right")]: + spinboxes[higher].setMinimum(spinboxes[lower].value() + .001) + spinboxes[lower].setMaximum(spinboxes[higher].value() - .001) + self._figure.subplots_adjust( + **{attr: spinbox.value() for attr, spinbox in spinboxes.items()}) + self._figure.canvas.draw_idle() + + def _tight_layout(self): + self._figure.tight_layout() + for attr, spinbox in self._spinboxes.items(): + spinbox.blockSignals(True) + spinbox.setValue(getattr(self._figure.subplotpars, attr)) + spinbox.blockSignals(False) + self._figure.canvas.draw_idle() + + def _reset(self): + for spinbox, value in self._defaults.items(): + spinbox.setRange(0, 1) + spinbox.blockSignals(True) + spinbox.setValue(value) + spinbox.blockSignals(False) + self._on_value_changed() + + +class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): + def __init__(self, toolmanager, parent=None): + ToolContainerBase.__init__(self, toolmanager) + QtWidgets.QToolBar.__init__(self, parent) + self.setAllowedAreas(QtCore.Qt.ToolBarArea( + _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | + _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) + message_label = QtWidgets.QLabel("") + message_label.setAlignment(QtCore.Qt.AlignmentFlag( + _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | + _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) + message_label.setSizePolicy(QtWidgets.QSizePolicy( + QtWidgets.QSizePolicy.Policy.Expanding, + QtWidgets.QSizePolicy.Policy.Ignored, + )) + self._message_action = self.addWidget(message_label) + self._toolitems = {} + self._groups = {} + + def add_toolitem( + self, name, group, position, image_file, description, toggle): + + button = QtWidgets.QToolButton(self) + if image_file: + button.setIcon(NavigationToolbar2QT._icon(self, image_file)) + button.setText(name) + if description: + button.setToolTip(description) + + def handler(): + self.trigger_tool(name) + if toggle: + button.setCheckable(True) + button.toggled.connect(handler) + else: + button.clicked.connect(handler) + + self._toolitems.setdefault(name, []) + self._add_to_group(group, name, button, position) + self._toolitems[name].append((button, handler)) + + def _add_to_group(self, group, name, button, position): + gr = self._groups.get(group, []) + if not gr: + sep = self.insertSeparator(self._message_action) + gr.append(sep) + before = gr[position] + widget = self.insertWidget(before, button) + gr.insert(position, widget) + self._groups[group] = gr + + def toggle_toolitem(self, name, toggled): + if name not in self._toolitems: + return + for button, handler in self._toolitems[name]: + button.toggled.disconnect(handler) + button.setChecked(toggled) + button.toggled.connect(handler) + + def remove_toolitem(self, name): + for button, handler in self._toolitems.pop(name, []): + button.setParent(None) + + def set_message(self, s): + self.widgetForAction(self._message_action).setText(s) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._subplot_dialog = None + + def trigger(self, *args): + NavigationToolbar2QT.configure_subplots(self) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class SaveFigureQt(backend_tools.SaveFigureBase): + def trigger(self, *args): + NavigationToolbar2QT.save_figure( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class RubberbandQt(backend_tools.RubberbandBase): + def draw_rubberband(self, x0, y0, x1, y1): + NavigationToolbar2QT.draw_rubberband( + self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) + + def remove_rubberband(self): + NavigationToolbar2QT.remove_rubberband( + self._make_classic_style_pseudo_toolbar()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class HelpQt(backend_tools.ToolHelpBase): + def trigger(self, *args): + QtWidgets.QMessageBox.information(None, "Help", self._get_help_html()) + + +@backend_tools._register_tool_class(FigureCanvasQT) +class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase): + def trigger(self, *args, **kwargs): + pixmap = self.canvas.grab() + QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap) + + +FigureManagerQT._toolbar2_class = NavigationToolbar2QT +FigureManagerQT._toolmanager_toolbar_class = ToolbarQt + + +@_Backend.export +class _BackendQT(_Backend): + backend_version = __version__ + FigureCanvas = FigureCanvasQT + FigureManager = FigureManagerQT + mainloop = FigureManagerQT.start_main_loop diff --git a/shared/package-files/78/78b6a171ca7a69f9bf9d12ed6fdceec4acca47f5cfa54105768db8ae36b9a2ab/blob b/shared/package-files/78/78b6a171ca7a69f9bf9d12ed6fdceec4acca47f5cfa54105768db8ae36b9a2ab/blob new file mode 100644 index 0000000000000000000000000000000000000000..87e1e44fbe1aac89176e2fbce6982a19f8fe2ddb --- /dev/null +++ b/shared/package-files/78/78b6a171ca7a69f9bf9d12ed6fdceec4acca47f5cfa54105768db8ae36b9a2ab/blob @@ -0,0 +1,103 @@ +# This module contains functions that *will be allowed* by dynamo + +import functools + +import torch +import torch.utils._pytree as pytree + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + + +def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + + If need to check specifically that TorchDynamo is used, then use + torch.compiler.is_dynamo_compiling(). + + TODO(khabinov): we should deprecate this function and use one of these two: + * torch.compiler.is_compiling(), + * torch.compiler.is_dynamo_compiling(). + It will depend on the context where to use what. + """ + return torch.compiler.is_compiling() + + +def wrap_inline(fn): + """ + Create an extra frame around fn that is not in skipfiles + """ + + @functools.wraps(fn) + def inner(*args, **kwargs): + return fn(*args, **kwargs) + + return inner + + +def call_hook(hook, *args): + """ + Used by compiled autograd to handle hook returning None + """ + result = hook(*args) + if result is None: + return args[0] + return result + + +def wrap_numpy(f): + r"""Decorator that turns a function from ``np.ndarray``s to ``np.ndarray``s into a function + from ``torch.Tensor``s to ``torch.Tensor``s. + """ + if not np: + return f + + @functools.wraps(f) + def wrap(*args, **kwargs): + args, kwargs = pytree.tree_map_only( + torch.Tensor, lambda x: x.numpy(), (args, kwargs) + ) + out = f(*args, **kwargs) + return pytree.tree_map_only(np.ndarray, lambda x: torch.as_tensor(x), out) + + return wrap + + +class FakeContext: + def __init__(self, saved_tensors): + # this will cache the results of saved_tensors + # and will no longer call into c++ binding + self.saved_tensors = saved_tensors + + +def call_backward(backward_fn, saved_tensors, *args): + grads = backward_fn(FakeContext(saved_tensors), *args) + + # in eager, we wrap in a tuple when there's only one grad output + if type(grads) is not tuple: + grads = (grads,) + + return grads + + +def untyped_storage_size(x: torch.Tensor): + return x.untyped_storage().size() + + +def call_hook_from_backward_state(*args, bw_state, hook_name: str, **kwargs): + return getattr(bw_state, hook_name)(*args, **kwargs) + + +def call_module_hooks_from_backward_state( + _, result, *args, bw_state, hooks_name: str, module_name: str +): + module = getattr(bw_state, module_name) + hooks = getattr(bw_state, hooks_name) + for hook in hooks: + new_result = hook(module, result, *args) + if new_result is not None: + result = new_result + return result diff --git a/shared/package-files/78/78b85ced43fdb6d3490db4de0ddb1ffa284c14e464b2687b03449c03984b44e2/blob b/shared/package-files/78/78b85ced43fdb6d3490db4de0ddb1ffa284c14e464b2687b03449c03984b44e2/blob new file mode 100644 index 0000000000000000000000000000000000000000..b471e9621cd4b125fd44e8f2f4239c7f720ac95d --- /dev/null +++ b/shared/package-files/78/78b85ced43fdb6d3490db4de0ddb1ffa284c14e464b2687b03449c03984b44e2/blob @@ -0,0 +1,64 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Contains declarations of time related Arrow builder types. + +#pragma once + +#include + +#include "arrow/array/builder_base.h" +#include "arrow/array/builder_primitive.h" + +namespace arrow { + +/// \addtogroup temporal-builders +/// +/// @{ + +class ARROW_EXPORT DayTimeIntervalBuilder : public NumericBuilder { + public: + using DayMilliseconds = DayTimeIntervalType::DayMilliseconds; + + explicit DayTimeIntervalBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : DayTimeIntervalBuilder(day_time_interval(), pool, alignment) {} + + explicit DayTimeIntervalBuilder(std::shared_ptr type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : NumericBuilder(type, pool, alignment) {} +}; + +class ARROW_EXPORT MonthDayNanoIntervalBuilder + : public NumericBuilder { + public: + using MonthDayNanos = MonthDayNanoIntervalType::MonthDayNanos; + + explicit MonthDayNanoIntervalBuilder(MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : MonthDayNanoIntervalBuilder(month_day_nano_interval(), pool, alignment) {} + + explicit MonthDayNanoIntervalBuilder(std::shared_ptr type, + MemoryPool* pool = default_memory_pool(), + int64_t alignment = kDefaultBufferAlignment) + : NumericBuilder(type, pool, alignment) {} +}; + +/// @} + +} // namespace arrow diff --git a/shared/package-files/78/78b9aa5c87ce9326c7ad134a4c6b647a7f750376fdead07005281af99bb39a78/graff_ms_data.py b/shared/package-files/78/78b9aa5c87ce9326c7ad134a4c6b647a7f750376fdead07005281af99bb39a78/graff_ms_data.py new file mode 100644 index 0000000000000000000000000000000000000000..443c6a2e5594684aa8b83728a721a967dea5b189 --- /dev/null +++ b/shared/package-files/78/78b9aa5c87ce9326c7ad134a4c6b647a7f750376fdead07005281af99bb39a78/graff_ms_data.py @@ -0,0 +1,378 @@ +from collections import defaultdict +import logging +import json +import numpy as np +from tqdm import tqdm + +import torch +from rdkit import Chem +from torch.utils.data.dataset import Dataset +import dgl +import ast +import copy + +import ms_pred.common as common + + +def array_to_string(array): + """ + Converts a 1D NumPy array into a string. + + Args: + array: 1D NumPy array + + Returns: + str_array: String representation of the array + """ + str_array = np.array2string(array, separator=",") + return str_array + + +def string_to_array(str_array): + """ + Converts a string representation of a 1D NumPy array back into the array. + + Args: + str_array: String representation of the array + + Returns: + array: 1D NumPy array + """ + array = np.fromstring(str_array[1:-1], sep=",") + return array + + +def extract_single_dict(entry): + root = entry["root_form"] + intens, new_forms = entry["intens"], entry["formulae"] + freqs = defaultdict(lambda: 0) + dense_forms = np.vstack([common.formula_to_dense(i) for i in new_forms]) + base_form = common.formula_to_dense(root) + diffs = -(base_form[None, :] - dense_forms) + + for i, inten in zip(diffs, intens): + freqs[array_to_string(i)] += inten + + for i, inten in zip(dense_forms, intens): + freqs[array_to_string(i)] += inten + + return freqs + + +def merge_diffs(diff_list): + """merge_diffs. + + Args: + diff_list: + """ + + freq_diffs = defaultdict(lambda: 0) + for freq_diff in tqdm(diff_list): + for k, v in freq_diff.items(): + freq_diffs[k] += v + return freq_diffs + + +def process_form_file(form_dict_file, upper_limit, num_bins): + """process_form_file.""" + if form_dict_file is None or not form_dict_file.exists(): + return None + with open(form_dict_file, "r") as fp: + return process_form_str(fp.read(), upper_limit, num_bins) + + +def process_form_str(form_dict_str, upper_limit, num_bins): + form_dict = json.loads(form_dict_str) + root_form = form_dict["cand_form"] + out_tbl = form_dict["output_tbl"] + + if out_tbl is None: + return None + + intens = out_tbl.get("ms2_inten", []) + formulae = out_tbl.get("formula", []) + + # Get raw spec + raw_spec = np.array(out_tbl.get("raw_spec")) + + bins = np.linspace(0, upper_limit, num_bins) + bin_posts = np.clip(np.digitize(raw_spec[:, 0], bins), 0, num_bins-1) + new_out = np.zeros_like(bins) + for bin_post, inten in zip(bin_posts, raw_spec[:, 1]): + new_out[bin_post] = max(new_out[bin_post], inten) + out_inten = new_out + + out_dict = dict( + root_form=root_form, + intens=intens, + formulae=formulae, + raw_spec=raw_spec, + raw_binned=out_inten, + ) + return out_dict + + +class BinnedDataset(Dataset): + """BinnedDataset.""" + + def __init__( + self, + df, + form_map, + form_h5, + num_bins, + graph_featurizer, + num_workers=0, + upper_limit=1500, + **kwargs, + ): + self.df = df + self.num_bins = num_bins + self.file_map = form_map + self.form_h5 = form_h5 + self.num_workers = num_workers + self.upper_limit = upper_limit + self.bins = np.linspace(0, self.upper_limit, self.num_bins) + self.name_to_adduct = dict(self.df[["spec", "ionization"]].values) + + valid_spec_ids = set([common.rm_collision_str(i) for i in self.file_map]) + valid_specs = [i in valid_spec_ids for i in self.df["spec"].values] + self.df_sub = self.df[valid_specs] + + if len(self.df_sub) == 0: + self.spec_names = [] + self.smiles = [] + self.name_to_dict = {} + else: + ori_label_map = self.df_sub.set_index("spec").drop("collision_energies", axis=1).to_dict(orient="index") # labels without collision energy + self.spec_names = [] + self.smiles = [] + self.name_to_dict = {} + for i in self.file_map: + ori_id = common.rm_collision_str(i) + if ori_id in ori_label_map: + label_dict = ori_label_map[ori_id] + self.spec_names.append(i) + self.smiles.append(label_dict["smiles"]) + self.name_to_dict[i] = copy.deepcopy(label_dict) + + for i in self.name_to_dict: + self.name_to_dict[i]["formula_file"] = self.file_map[i] + + logging.info(f"{len(self.df_sub)} of {len(self.df)} spec have {len(self.spec_names)} form dicts.") + self.form_files = [ + self.name_to_dict[i]["formula_file"] for i in self.spec_names + ] + + # Read in all molecules + self.graph_featurizer = graph_featurizer + + self.mols = [Chem.MolFromSmiles(i) for i in self.smiles] + self.weights = [common.ExactMolWt(i) for i in self.mols] + self.weights = np.array(self.weights) + + # Read in all specs + spec_files = self.form_files + def read_spec(name): + if not name.endswith('.json'): + name += '.json' + h5_obj = common.HDF5Dataset(self.form_h5) + spec_form_obj = process_form_str(h5_obj.read_str(name), self.upper_limit, self.num_bins) + return spec_form_obj + + spec_outputs = [read_spec(i) for i in tqdm(spec_files, desc='reading spec')] + + self.name_to_forms = dict(zip(self.spec_names, spec_outputs)) + self.name_to_smiles = dict(zip(self.spec_names, self.smiles)) + self.name_to_mols = dict(zip(self.spec_names, self.mols)) + + len_spec_names = len(self.spec_names) + self.spec_names = [ + i + for i in self.spec_names + if self.name_to_forms.get(i) is not None + and len(self.name_to_forms.get(i)["formulae"]) > 0 + ] + post_len_spec_names = len(self.spec_names) + logging.info(f"{post_len_spec_names} of {len_spec_names} have nonzero intens.") + self.spec_names = np.array(self.spec_names) + self.name_to_root_form = { + i: self.name_to_forms[i]["root_form"] for i in self.spec_names + } + + self.bins = np.linspace(0, 1500, 15000) + self.adducts = [ + self.name_to_adduct[common.rm_collision_str(i)] for i in self.spec_names + ] + + def get_top_forms(self): + all_freqs = [] + for i in self.spec_names: + entry = self.name_to_forms[i] + extracted = extract_single_dict(entry) + all_freqs.append(extracted) + freq_diff = merge_diffs(all_freqs) + forms, cts = zip(*list(freq_diff.items())) + cts = np.array(cts) + forms = np.array([string_to_array(i) for i in forms]) + new_order = np.argsort(cts)[::-1] + cts = cts[new_order] + forms = forms[new_order] + return {"forms": forms, "cts": cts} + + def __len__(self): + return len(self.spec_names) + + def __getitem__(self, idx: int): + name = self.spec_names[idx] + + smiles = self.name_to_smiles[name] + mol = self.name_to_mols[name] + graph = self.graph_featurizer.get_dgl_graph(mol) + spec_form_obj = self.name_to_forms[name] + collision_energy = common.get_collision_energy(name) + + ar = spec_form_obj["raw_binned"] + adduct = self.adducts[idx] + precursor = common.mass_from_smi(smiles) + common.ion2mass[adduct] + nce = int(common.ev_to_nce(int(collision_energy), precursor)) + + outdict = { + "name": name, + "root_form": common.formula_to_dense(spec_form_obj["root_form"]), + "binned": ar, + "adduct": common.ion2onehot_pos[adduct], + "graph": graph, + "smiles": smiles, + "nce": nce, + "collision_energy": collision_energy, + } + return outdict + + @classmethod + def get_collate_fn(cls): + return BinnedDataset.collate_fn + + @staticmethod + def collate_fn(input_list): + """collate_fn""" + names = [j["name"] for j in input_list] + spec_ars = [j["binned"] for j in input_list] + graphs = [j["graph"] for j in input_list] + full_forms = [j["root_form"] for j in input_list] + adducts = [j["adduct"] for j in input_list] + nces = [j["nce"] for j in input_list] + collision_energies = [j["collision_energy"] for j in input_list] + + # Now pad everything else to the max channel dim + spectra_tensors = torch.stack([torch.tensor(spectra) for spectra in spec_ars]) + + batched_graph = dgl.batch(graphs) + # frag_batch.set_n_initializer(dgl.init.zero_initializer) + # frag_batch.set_e_initializer(dgl.init.zero_initializer) + + adducts = torch.FloatTensor(adducts) + full_forms = torch.FloatTensor(full_forms) + nces = torch.FloatTensor(nces) + + return_dict = { + "spectra": spectra_tensors, + "graphs": batched_graph, + "full_forms": full_forms, + "names": names, + "adducts": adducts, + "nces": nces, + "collision_energies": collision_energies, + } + return return_dict + + +class MolDataset(Dataset): + """MolDataset.""" + + def __init__(self, df, graph_featurizer, num_workers: int = 0, **kwargs): + + self.df = df + self.graph_featurizer = graph_featurizer + self.name_to_adduct = dict(self.df[["spec", "ionization"]].values) + + # Read in all molecules + self.spec_names = [] + self.smiles = [] + self.collision_energies = [] + self.mols = [] + self.weights = [] + self.mol_graphs = [] + for i, row in tqdm(self.df.iterrows(), total=self.df.shape[0], desc='preprocess data'): + smi = row["smiles"] + mol = Chem.MolFromSmiles(smi) + weight = common.ExactMolWt(mol) + mol_graph = self.graph_featurizer.get_dgl_graph(mol) + for colli_eng in ast.literal_eval(row["collision_energies"]): + self.smiles.append(smi) + self.mols.append(mol) + self.weights.append(weight) + self.mol_graphs.append(mol_graph) + self.spec_names.append( + row["spec"] if "spec" in list(row.keys()) else "" + ) + self.collision_energies.append(int(colli_eng)) + + # Extract + self.weights = np.array(self.weights) + self.adducts = [ + self.name_to_adduct[i] for i in self.spec_names + ] + + def __len__(self): + return len(self.spec_names) + + def __getitem__(self, idx: int): + smi = self.smiles[idx] + root_form = common.formula_to_dense(common.form_from_smi(smi)) + graph = self.mol_graphs[idx] + spec_name = self.spec_names[idx] + adduct = self.adducts[idx] + collision_energy = self.collision_energies[idx] + precursor = common.mass_from_smi(smi) + common.ion2mass[adduct] + nce = int(common.ev_to_nce(int(collision_energy), precursor)) + outdict = { + "smi": smi, + "graph": graph, + "root_form": root_form, + "adduct": common.ion2onehot_pos[adduct], + "spec_name": spec_name, + "nce": nce, + "collision_energy": collision_energy, + } + return outdict + + @classmethod + def get_collate_fn(cls): + return MolDataset.collate_fn + + @staticmethod + def collate_fn(input_list): + """collate_fn""" + names = [j["smi"] for j in input_list] + spec_names = [j["spec_name"] for j in input_list] + graphs = [j["graph"] for j in input_list] + adducts = [j["adduct"] for j in input_list] + nces = [j["nce"] for j in input_list] + collision_energies = [j["collision_energy"] for j in input_list] + + adducts = torch.FloatTensor(adducts) + nces = torch.FloatTensor(nces) + + full_forms = torch.FloatTensor([j["root_form"] for j in input_list]) + batched_graph = dgl.batch(graphs) + return_dict = { + "graphs": batched_graph, + "spec_names": spec_names, + "names": names, + "full_forms": full_forms, + "adducts": adducts, + "nces": nces, + "collision_energies": collision_energies, + } + return return_dict diff --git a/shared/package-files/78/78bbcf5742cc809e942cdff0b50cae1bb48a68d2313676d223edba56551d7504/blob b/shared/package-files/78/78bbcf5742cc809e942cdff0b50cae1bb48a68d2313676d223edba56551d7504/blob new file mode 100644 index 0000000000000000000000000000000000000000..80ad107b794f034ecea5b1def84abe30133e169f --- /dev/null +++ b/shared/package-files/78/78bbcf5742cc809e942cdff0b50cae1bb48a68d2313676d223edba56551d7504/blob @@ -0,0 +1,824 @@ +import operator +from contextlib import contextmanager +from enum import Enum + +from typing import Any, cast, Dict, List, Optional, Tuple + +import torch + +import torch.distributed.distributed_c10d as c10d +import torch.fx as fx +import torch.library +import torch.nn as nn + +import torch.utils._pytree as pytree + +from torch.distributed._spmd.batch_dim_utils import BatchDimAnalyzer +from torch.distributed._tensor import DeviceMesh, distribute_tensor, Replicate, Shard + +from torch.distributed._tensor._utils import compute_local_shape +from torch.distributed._tensor.op_schema import ( + OpStrategy, + PlacementStrategy, + StrategyType, + TupleStrategy, +) +from torch.distributed._tensor.placement_types import _Partial, DTensorSpec, Placement +from torch.distributed._tensor.redistribute import redistribute_local_tensor +from torch.fx import GraphModule +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.passes.shape_prop import _extract_tensor_metadata +from torch.nn.utils._named_member_accessor import NamedMemberAccessor + +aten = torch.ops.aten + +# Dummy op used by data parallel to tag gradients. +_spmd_lib_def = torch.library.Library("_spmd", "DEF") +_spmd_lib_def.define("tag_grad(Tensor self) -> Tensor") + +_spmd_lib_impl = torch.library.Library("_spmd", "IMPL") +_spmd_lib_impl.impl("tag_grad", lambda x: x, "CompositeExplicitAutograd") + + +class DataParallelStyle(Enum): + """This enum represents the style of the data-parallel operation. + + We have three types of Data Parallel style: + 1. DEFAULT: the default data parallel style, which is to represent a mixed + replicate and fully shard behavior. For each parameter that is able + to be sharded evenly, we shard it, otherwise we would replicate the + parameter. This style avoids potential padding if the parameters + cannot be sharded evenly, but it would generate a mixed of all_reduce + and reduce_scatter. + 2. REPLICATE: the data parallel style that replicates all model parameters. + This is similar to the behavior of DistributedDataParallel. + 3. FULLY_SHARD: the data parallel style that shards all model parameters. This + is similar to the behavior of FullyShardedDataParallel, the + difference is that FullyShardedDataParallel (ZERO-3), which + shards the model using FlatParameter based sharding, + while this style shards each parameter into DTensor. + """ + + DEFAULT = 0 + REPLICATE = 1 + FULLY_SHARD = 2 + + +class NodeType(Enum): + """NodeType is an enum that records the type of the tensors in the graph. + + This is used to determine the data parallel strategy. + """ + + PARAM = 0 + ACT = 1 + GRAD = 2 + STATE = 3 + NON_TENSOR = 4 # NON_TENSOR is to tag non tensor node (i.e. graph output) + + +class DataParallelStrategy(OpStrategy): + """DataParallelStrategy is a special case of OpStrategy that only records the "data parallel style" placement + strategy for each fx Node. + + It takes a list of PlacementStrategy, where each PlacementStrategy describes + one way to distribute the tensor and computation. In the DataParallel case, + there're two possible ways to distribute the parameters: + 1. replicate the parameter over a set of devices (DDP like behavior) + 2. shard the parameter on its tensor dimension 0 over a set of devices + (FSDP like behavior). + + In addition to the strategy list, we also need to: + 1. `node_type`: record the type of each node in the graph, so that we can + determine how to propagate in a data parallel fashion. + 2. `reduce_over_batch` is specifically tied to data parallel as the loss + calculation usually results in scalar tensor where it comes from a + reduction over the batch dimension. We need to know this information + so that we could keep the output as sharded. + """ + + def __init__( + self, + node_type: NodeType, + strategy_list: List[PlacementStrategy], + reduction_over_batch: bool = False, + ): + super().__init__(strategy_list) + self.node_type = node_type + self.reduction_over_batch = reduction_over_batch + + def __str__(self) -> str: + return f"type: {self.node_type}, {super().__str__()}" + + +@contextmanager +def gradients_tagging(params: Dict[str, torch.Tensor]): + """Tag the gradient of the parameters with a special tag, so that we can identify them during SPMD expansion. + + It's safe to trace those hooks and we would remove those nodes later. + """ + tagging_hooks = [] + try: + for p in params.values(): + h = p.register_hook(torch.ops._spmd.tag_grad) + tagging_hooks.append(h) + yield + finally: + # remove those hooks after tracing + for h in tagging_hooks: + h.remove() + + +def _gen_shard_strategy( + mesh: DeviceMesh, shard_dim: int, input_specs: Optional[List[DTensorSpec]] = None +) -> PlacementStrategy: + """Util function to generate a shard strategy on shard_dim.""" + return PlacementStrategy( + output_specs=DTensorSpec(mesh=mesh, placements=(Shard(shard_dim),)), + input_specs=input_specs, + ) + + +def _gen_replicate_strategy( + mesh: DeviceMesh, input_specs: Optional[List[DTensorSpec]] = None +) -> PlacementStrategy: + """Util function to generate a replicate strategy.""" + return PlacementStrategy( + output_specs=DTensorSpec(mesh=mesh, placements=(Replicate(),)), + input_specs=input_specs, + ) + + +def _gen_partial_strategy(mesh: DeviceMesh) -> PlacementStrategy: + """Util function to generate a partial strategy.""" + # NOTE: we use AVG by default, avg reduction is needed depending on + # the loss function, for most loss function it should do + # gradient averaging. There might be certain cases it should + # not do gradient averaging (i.e. sum) but it's pretty rare. + # TODO: Only NCCL supports AVG so using backend like Gloo would + # crash, we should figure out a way to support avg reduction + # for non-NCCL backend + reduce_op = c10d.ReduceOp.AVG # type: ignore[attr-defined] + return PlacementStrategy( + output_specs=DTensorSpec(mesh=mesh, placements=(_Partial(reduce_op),)), + ) + + +def build_data_parallel_strategies( + train_step_graph: GraphModule, + num_params: int, + num_states: int, + mesh: DeviceMesh, + batch_dim: int = 0, +) -> Dict[fx.Node, StrategyType]: + """Loop through the train step graph and build the data parallel strategy for each fx Node.""" + activation_idx = num_params + num_states + non_compute_ops = [ + aten.clone.default, + aten.detach.default, + aten.ones_like.default, + aten.reshape.default, + aten.t.default, + aten.view.default, + torch.ops._spmd.tag_grad.default, + operator.getitem, + ] + + tuple_strategy_ops = [aten._fused_adam.default] + + dp_strategy_map: Dict[fx.Node, StrategyType] = {} + batch_dim_analyzer = BatchDimAnalyzer(batch_dim) + placeholder_idx = 0 + num_param_grad = 0 + + # first we backward propagate to mark the param gradients sharding + # with tag_grad node helps and then delete the tag_grad nodes + for node in reversed(list(train_step_graph.graph.nodes)): + # find a param_grad node via the tagging + if node.target == torch.ops._spmd.tag_grad.default: + cur_node = node + while cur_node.target in non_compute_ops: + cur_node = cur_node.args[0] + partial_strategy = _gen_partial_strategy(mesh) + dp_strategy_map[cur_node] = DataParallelStrategy( + NodeType.GRAD, [partial_strategy] + ) + num_param_grad += 1 + # remove the tag_grad node from graph + node.replace_all_uses_with(node.args[0]) + train_step_graph.graph.erase_node(node) + + if num_param_grad == num_params: + # early break if we have already processed all param_grads + break + + # next we forward propagate to mark all the sharding + for node in train_step_graph.graph.nodes: + if node.op == "placeholder": + if "val" not in node.meta: + # NOTE: There're certain cases where the placeholder nodes do + # not have real tensor values: + # 1. optimizer states can be None sometimes, i.e. SGD with + # no momentum, optimizer states populate `momentum` state + # as None, the full graph we get from `compile` would have + # None as the placeholder value + # 2. function args might not only contain params or activations, + # but also contain other non-tensor inputs, i.e. the model + # and optimizer instances baked in as a placeholder, there might + # also be some scalar argument which is not a tensor + # + # For the above cases, we create a NON_TENSOR stratgy so that we + # know it's not a tensor and we don't need to shard it + dp_strategy_map[node] = DataParallelStrategy(NodeType.NON_TENSOR, []) + + elif placeholder_idx < num_params: + # during compilation there's an assumption that the first num_params + # placeholders should be parameters + shard_strategy = _gen_shard_strategy(mesh, 0) + replica_strategy = _gen_replicate_strategy(mesh) + dp_strategy_map[node] = DataParallelStrategy( + NodeType.PARAM, [replica_strategy, shard_strategy] + ) + + elif placeholder_idx < activation_idx: + # optimizer states follow the same strategy as + # the corresponding parameters + replica_strategy = _gen_replicate_strategy(mesh) + shard_strategy = _gen_shard_strategy(mesh, 0) + + dp_strategy_map[node] = DataParallelStrategy( + NodeType.STATE, [replica_strategy, shard_strategy] + ) + else: + activation_batch_dim_size = node.meta["val"].shape[batch_dim] + # find the first activation node and use its batch dim size + if batch_dim_analyzer.batch_dim_size == -1: + batch_dim_analyzer.init_batch_dim_size(activation_batch_dim_size) + + batch_dim_analyzer.set_batch_dim(node, batch_dim) + shard_strategy = _gen_shard_strategy(mesh, batch_dim) + dp_strategy_map[node] = DataParallelStrategy( + NodeType.ACT, [shard_strategy] + ) + placeholder_idx += 1 + elif node.op == "call_function": + # Annotate node types for the computation graph + # Data Parallel node propagation logic: + # param (non-compute) -> out: param + # grad (non-compute before/after) -> out: grad + # state -> output: state + # + # param + activation (param must be replicate, act be sharded) -> out: activation + # param/state + grad (param/state/grad be the same spec) -> out: param/state + # param + state -> out: param + + if node.target in non_compute_ops: + # At this point, we should have removed all the `tag_grad` nodes in the graph + assert node.target != torch.ops._spmd.tag_grad.default + + input_nodes = node.all_input_nodes + assert ( + len(input_nodes) == 1 + ), f"non-compute op only support one input now, found node: {node} with length of inputs: {len(node.args)}" + arg_strategy = dp_strategy_map[input_nodes[0]] + + if node.target == operator.getitem: + # for getitem call, just forward the strategy from the input + getitem_idx = node.args[1] + if isinstance(arg_strategy, TupleStrategy): + # for tuple strategy, we need to get the child strategy from the tuple + dp_strategy_map[node] = arg_strategy.childs[getitem_idx] + else: + # if it's not a tuple strategy, we just forward the arg strategy + dp_strategy_map[node] = arg_strategy + else: + assert isinstance(arg_strategy, DataParallelStrategy) + arg_node_type = arg_strategy.node_type + if arg_node_type == NodeType.PARAM: + replica_strategy = _gen_replicate_strategy(mesh) + dp_strategy_map[node] = DataParallelStrategy( + NodeType.PARAM, [replica_strategy] + ) + elif arg_node_type == NodeType.GRAD: + partial_sig = _gen_partial_strategy(mesh) + dp_strategy_map[node] = DataParallelStrategy( + NodeType.GRAD, [partial_sig] + ) + elif arg_node_type == NodeType.ACT: + arg_node_spec = batch_dim_analyzer.compute_act_spec( + input_nodes[0], mesh + ) + + output_spec = batch_dim_analyzer.compute_act_spec(node, mesh) + + shard_strategy = PlacementStrategy( + output_specs=output_spec, input_specs=[arg_node_spec] + ) + dp_strategy_map[node] = DataParallelStrategy( + NodeType.ACT, [shard_strategy] + ) + else: + raise RuntimeError( + f"non compute op not supporting {arg_node_type}! " + ) + + # finished processing this non-compute node + continue + + # for computatation nodes, we need to check all the inputs + input_args = node.all_input_nodes + input_specs = [] + if node in dp_strategy_map: + # found a param_grad node that already have output pre-filled spec + # fill in the expected input specs for the pre-filled strategy + node_strategy = dp_strategy_map[node] + assert isinstance(node_strategy, DataParallelStrategy) + node_type = node_strategy.node_type + assert node_type == NodeType.GRAD + produce_param_grad_strat = node_strategy.strategies + has_activation = False + for arg in input_args: + arg_strategy = dp_strategy_map[arg] + assert isinstance(arg_strategy, DataParallelStrategy) + arg_node_type = arg_strategy.node_type + if arg_node_type == NodeType.ACT: + # activation sharded + has_activation = True + act_spec = batch_dim_analyzer.compute_act_spec(arg, mesh) + + input_specs.append(act_spec) + + if has_activation: + assert len(produce_param_grad_strat) == 1 + produce_param_grad_strat[0].input_specs = input_specs + elif node.target in tuple_strategy_ops: + # ops that need to build tuple strategy instead of normal strategy + # This should happen rarely and only needed when we need to generate + # different node strategy for multiple outputs (i.e. fused_adam op) + # TODO: Currently this specializes to fused optimizer ops, but we need + # to see how to generalize this strategy building logic + output_strategy_len = len(node.args) - 1 + tuple_strategies = [] + for i in range(output_strategy_len): + if not isinstance(node.args[i], list): + raise RuntimeError( + f"Expecting list as arg to build Tuple Strategy, but found type {type(node.args[i])}!" + ) + # for list/tuple arg, use the first one to find out the node type + if len(node.args[i]) > 0: + arg_strategy = dp_strategy_map[node.args[i][0]] + assert isinstance(arg_strategy, DataParallelStrategy) + assert arg_strategy.node_type in [ + NodeType.PARAM, + NodeType.GRAD, + NodeType.STATE, + ], "Expecting param/grad/state as arg to build Tuple Strategy!" + replica_strategy = _gen_replicate_strategy(mesh) + shard_strategy = _gen_shard_strategy(mesh, shard_dim=0) + out_node_strategy: StrategyType = DataParallelStrategy( + arg_strategy.node_type, [replica_strategy, shard_strategy] + ) + + tuple_strategies.append(out_node_strategy) + + output_tuple_strategy = TupleStrategy(tuple(tuple_strategies)) + dp_strategy_map[node] = output_tuple_strategy + else: + # NOTE: This is the common region for all regular computation ops + + input_node_types = [ + cast(DataParallelStrategy, dp_strategy_map[arg]).node_type + for arg in input_args + if isinstance(dp_strategy_map[arg], DataParallelStrategy) + ] + if NodeType.GRAD in input_node_types: + # param/state + grad, build up acceptable strategy + # the strategy should be the same for all the inputs/outputs + # TODO: optimizer parts should follow the dtensor prop logic + # to support more general cases that allows optimizer states + # to have different shardings compare to the params + replica_strategy = _gen_replicate_strategy(mesh) + shard_strategy = _gen_shard_strategy(mesh, shard_dim=0) + output_node_type = NodeType.PARAM + + non_grad_types = [t for t in input_node_types if t != NodeType.GRAD] + + output_node_type = non_grad_types[0] + for non_grad_type in non_grad_types: + assert ( + non_grad_type == output_node_type + ), f"Found more than one non grad types! Expect {output_node_type} but found {non_grad_type}!" + assert output_node_type in [ + NodeType.PARAM, + NodeType.STATE, + ], f"Expecting output node type to be either state or param, but found {output_node_type}!" + + dp_strategy_map[node] = DataParallelStrategy( + output_node_type, [replica_strategy, shard_strategy] + ) + elif NodeType.STATE in input_node_types: + # either param + state or state + state + replica_strategy = _gen_replicate_strategy(mesh) + shard_strategy = _gen_shard_strategy(mesh, shard_dim=0) + output_node_type = ( + NodeType.PARAM + if NodeType.PARAM in input_node_types + else NodeType.STATE + ) + + dp_strategy_map[node] = DataParallelStrategy( + output_node_type, [replica_strategy, shard_strategy] + ) + elif NodeType.PARAM in input_node_types: + if NodeType.ACT in input_node_types: + # param + activation, build up acceptable strategy + # param must be replicated, activation must be sharded + for arg in input_args: + arg_strategy = dp_strategy_map[arg] + assert isinstance(arg_strategy, DataParallelStrategy) + node_type = arg_strategy.node_type + if node_type == NodeType.ACT: + # compute activation spec + act_spec = batch_dim_analyzer.compute_act_spec( + arg, mesh + ) + + input_specs.append(act_spec) + elif node_type == NodeType.PARAM: + # param must be replicated + input_specs.append( + DTensorSpec(mesh=mesh, placements=(Replicate(),)) + ) + else: + raise RuntimeError( + f"Expecting node with parameter and activation, but found {input_node_types}! " + ) + # produce activation type sharding for output + output_spec = batch_dim_analyzer.compute_act_spec(node, mesh) + + act_strategy = PlacementStrategy( + output_specs=output_spec, input_specs=input_specs + ) + + dp_strategy_map[node] = DataParallelStrategy( + NodeType.ACT, [act_strategy] + ) + else: + # If inputs only have parameters, the + # strategy of this node should follow input + dp_strategy_map[node] = dp_strategy_map[input_args[0]] + else: + # If input nodes does not have PARAM/GRAD/STATE, then + # it should be a pure activation computation, it should + # produce activation output. + # Activations are usually sharded unless model creates + # new tensors during computation, which depend on whether + # the new tensor associate with a batch dim or not, it could + # be shard/replicate/partial, batch dim analyzer should tell + # us the correct sharding. + for arg in input_args: + arg_strategy = dp_strategy_map[arg] + assert isinstance(arg_strategy, DataParallelStrategy) + input_spec = batch_dim_analyzer.compute_act_spec(arg, mesh) + + input_specs.append(input_spec) + + act_spec = batch_dim_analyzer.compute_act_spec(node, mesh) + op_strategy = PlacementStrategy( + output_specs=act_spec, input_specs=input_specs + ) + dp_strategy_map[node] = DataParallelStrategy( + NodeType.ACT, [op_strategy] + ) + + elif node.op == "output": + dp_strategy_map[node] = DataParallelStrategy(NodeType.NON_TENSOR, []) + else: + raise RuntimeError(f"op code {node.op} not supported") + + return dp_strategy_map # type: ignore[return-value] + + +def mark_data_parallel_shardings( + train_step_graph: GraphModule, + num_parameters: int, + num_states: int, + dp_strategy_map: Dict[fx.Node, StrategyType], + parallel_mode: DataParallelStyle = DataParallelStyle.FULLY_SHARD, +) -> None: + """Mark the sharding for the nodes in the train_step_graph.""" + activation_idx = num_parameters + num_states + placeholder_idx = 0 + for node in train_step_graph.graph.nodes: + node_strategy = dp_strategy_map[node] + if node.op == "placeholder": + assert isinstance(node_strategy, DataParallelStrategy) + node_type = node_strategy.node_type + node_strategies = node_strategy.strategies + if node_type == NodeType.NON_TENSOR: + # set node sharding to None + node_sharding = None + elif placeholder_idx < activation_idx: + assert len(node_strategies) > 0, "node_strategies should not be empty" + if parallel_mode == DataParallelStyle.REPLICATE: + # set to replicate for replicate style + node_sharding = node_strategies[0] + elif parallel_mode == DataParallelStyle.FULLY_SHARD: + # set to shard for fully shard style + if len(node_strategies) == 1: + # only one strategy, use that instead + # i.e. optimizer state steps can only be replicate + node_sharding = node_strategies[0] + else: + # use the full sharding strategy + node_sharding = node_strategies[1] + elif parallel_mode == DataParallelStyle.DEFAULT: + # TODO: add support for default mode + # default mode would generate either replicate or shard + raise NotImplementedError("default mode not implemented") + else: + assert len(node_strategies) > 0, "node_strategies should not be empty" + # mark activation as sharded on batch dim + node_sharding = node_strategies[0] + + node.meta["sharding"] = node_sharding # type: ignore[possibly-undefined] + + placeholder_idx += 1 + elif node.op == "call_function": + if isinstance(node_strategy, TupleStrategy): + # For tuple strategy in the data parallel mode, it should have the same strategy + # for all tuple elements, assert that then use the first element's strategy as sharding + first_strategy = cast(DataParallelStrategy, node_strategy.childs[0]) + for child_strategy in node_strategy.childs: + assert isinstance(child_strategy, DataParallelStrategy) + assert child_strategy.strategies == first_strategy.strategies + + node_strategies = first_strategy.strategies + else: + assert isinstance(node_strategy, DataParallelStrategy) + node_strategies = node_strategy.strategies + + assert ( + len(node_strategies) <= 2 + ), "data parallel should have at most 2 strategies" + if len(node_strategies) == 1: + node.meta["sharding"] = node_strategies[0] + elif len(node_strategies) == 2: + if parallel_mode == DataParallelStyle.REPLICATE: + # set to replicate for replicate style + node.meta["sharding"] = node_strategies[0] + elif parallel_mode == DataParallelStyle.FULLY_SHARD: + # set to shard for fully shard style + node.meta["sharding"] = node_strategies[1] + else: + raise RuntimeError("default mode not supported yet!") + else: + raise RuntimeError( + f"node {node} strategy length {len(node_strategies)} is not expected!" + ) + elif node.op == "output": + assert ( + isinstance(node_strategy, DataParallelStrategy) + and node_strategy.node_type == NodeType.NON_TENSOR + ), "output node should not be tensor" + node.meta["sharding"] = None + else: + raise RuntimeError(f"op code {node.op} not supported") + + +def _partition_val(val: Any, spec: DTensorSpec) -> Any: + """Util function to convert a full tensor val to its local component.""" + if isinstance(val, torch.Tensor): + local_shard = val + if val.ndim == 0: + # If it's already a scalar tensor, it is already local, we don't + # need to do anything + return local_shard + + for idx, placement in enumerate(spec.placements): + if placement.is_shard(): + placement = cast(Shard, placement) + num_chunks = spec.mesh.size(mesh_dim=idx) + my_coord = spec.mesh.get_coordinate() + assert my_coord is not None, "current rank not in mesh!" + my_coord_on_mesh_dim = my_coord[idx] + local_shard = placement._split_tensor( + local_shard, num_chunks, with_padding=False, contiguous=False + )[0][my_coord_on_mesh_dim] + return local_shard + elif isinstance(val, (tuple, list)): + return val.__class__(_partition_val(v, spec) for v in val) + else: + raise RuntimeError(f"val type {type(val)} not supported") + + +def partitioner(graph: GraphModule) -> GraphModule: + """Graph partitioner that partitions the single device graph to distributed graph.""" + shape_adjustment_ops = { + aten._unsafe_view.default: 1, + aten.expand.default: 1, + aten.new_zeros.default: 1, + aten.ones.default: 0, + aten.reshape.default: 1, + aten.view.default: 1, + aten.zeros.default: 0, + } + # partition the graph to distributed + for node in graph.graph.nodes: + node_sharding = node.meta["sharding"] + # None sharding means this node don't need sharding + if node_sharding is None: + continue + + if node.op == "placeholder": + out_spec = node_sharding.output_spec + if not hasattr(out_spec, "from_local"): + local_val = _partition_val(node.meta["val"], out_spec) + # update node value + node.meta["val"] = local_val + elif node.op == "call_function": + out_spec = node_sharding.output_spec + + # check if there's misaligned sharding, insert reshard if there is + expected_input_specs = node_sharding.input_specs + for idx, input_arg in enumerate(node.all_input_nodes): + input_arg_sharding = input_arg.meta["sharding"] + + input_arg_spec = input_arg_sharding.output_spec + desired_spec = ( + out_spec + if expected_input_specs is None + else expected_input_specs[idx] + ) + if input_arg_spec != desired_spec: + input_arg_spec.tensor_meta = input_arg.meta["tensor_meta"] + desired_spec.tensor_meta = input_arg.meta["tensor_meta"] + input_arg_tensor = input_arg.meta["val"] + + # insert reshard operation + def reshard_fn(local_tensor: torch.Tensor) -> torch.Tensor: + return redistribute_local_tensor( + local_tensor, + input_arg_spec, + desired_spec, + ) + + reshard_gm = make_fx(reshard_fn)(input_arg_tensor) + reshard_gm_nodes = list(reshard_gm.graph.nodes) + input_node = reshard_gm_nodes[0] + with graph.graph.inserting_before(node): + output_node = graph.graph.graph_copy( + reshard_gm.graph, + val_map={ + input_node: input_arg, + }, + ) + node.replace_input_with(input_arg, output_node) + + output_val = node.meta["val"] + + if node.target == torch.ops.aten.repeat.default: + # for repeat op, we need to infer the repeat sizes + assert isinstance(output_val, torch.Tensor) + local_shape = compute_local_shape( + output_val.shape, out_spec.mesh, out_spec.placements + ) + input_shape = node.args[0].meta["val"].shape + + def infer_repeat_sizes(repeated_shape, input_shape): + repeated_size = [1] * len(repeated_shape) + padded_length = len(repeated_shape) - len(input_shape) + for i in range(len(repeated_shape)): + if i < padded_length: + repeated_size[i] = repeated_shape[i] + else: + repeated_size[i] = ( + repeated_shape[i] // input_shape[i - padded_length] + ) + + return repeated_size + + node.update_arg(1, infer_repeat_sizes(local_shape, input_shape)) + + elif node.target in shape_adjustment_ops: + # for view related op that needs shape, adjust shape to local shape if needed + assert isinstance(output_val, torch.Tensor) + local_shape = compute_local_shape( + output_val.shape, out_spec.mesh, out_spec.placements + ) + shape_arg_num = shape_adjustment_ops[node.target] + node.update_arg(shape_arg_num, local_shape) + + # convert output val to its local component + node.meta["val"] = _partition_val(output_val, out_spec) + + elif node.op == "output": + break + else: + raise RuntimeError(f"op code {node} not supported") + + # clean up the graph by removing sharding and partitioning related metadata + for node in graph.graph.nodes: + if "sharding" in node.meta: + del node.meta["sharding"] + if "val" in node.meta and isinstance(node.meta["val"], torch.Tensor): + local_tensor_meta = _extract_tensor_metadata(node.meta["val"]) + node.meta["tensor_meta"] = local_tensor_meta + + graph.graph.lint() + graph.recompile() + return graph + + +def partition_data_parallel( + graph: GraphModule, + model: nn.Module, + optimizer: Optional[torch.optim.Optimizer], + params_buffers: Dict[str, torch.Tensor], + named_states: Dict[str, Any], + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + mesh: DeviceMesh, + parallel_style: DataParallelStyle, + input_batch_dim: int, +) -> GraphModule: + """Partition the graph to into a data parallel graph. + + This function also shards/replicates the model parameters and optimizer states to DTensors. + """ + num_params_buffers = len(params_buffers) + flattened_states = pytree.tree_leaves(named_states) + num_states = len(flattened_states) + + changed = graph.graph.eliminate_dead_code() + if changed: + graph.recompile() + + # 1. First build up data parallel strategies for the whole graph + strategy_map = build_data_parallel_strategies( + graph, num_params_buffers, num_states, mesh=mesh, batch_dim=input_batch_dim + ) + + # 2. Next we mark the data parallel strategy for each node base on + # the parallel_style + mark_data_parallel_shardings( + graph, + num_parameters=num_params_buffers, + num_states=num_states, + dp_strategy_map=strategy_map, + parallel_mode=parallel_style, + ) + + # 3. Partition the single machine graph to the distribute graph + partitioned_graph = partitioner(graph) + + # preserve node types for the expanded graph + for node in partitioned_graph.graph.nodes: + if node in strategy_map: + node_strategy = strategy_map[node] + if isinstance(node_strategy, DataParallelStrategy): + node.meta["node_type"] = node_strategy.node_type + elif isinstance(node_strategy, TupleStrategy): + node.meta["node_type"] = NodeType.NON_TENSOR + else: + raise RuntimeError(f"Unknown node strategy {node_strategy}") + else: + # if the nodes are expanded nodes (collectives), we mark them + # the same type as the input node. + input_node = node.all_input_nodes[0] + node.meta["node_type"] = input_node.meta["node_type"] + + # 4. Last, inplace partition the weights and optim states to + # DTensors base on the parallel style + accessor = NamedMemberAccessor(model) + for param_key, param in params_buffers.items(): + placement: Placement = Replicate() + if parallel_style == DataParallelStyle.FULLY_SHARD: + placement = Shard(0) + elif parallel_style != DataParallelStyle.REPLICATE: + raise RuntimeError(f"parallel style {parallel_style} not supported yet") + + dtensor_param = distribute_tensor(param, mesh, [placement]) + # update re-parameterized module param dict and optim states dict to DTensor + params_buffers[param_key] = dtensor_param.to_local() + # update module parameters to DTensor + accessor.set_tensor(param_key, dtensor_param) + + # update the optimizer state key and values to DTensor + if optimizer is not None and param in optimizer.state: + param_states = named_states[param_key] + param_dtensor_states = {} + for state_key, state_val in param_states.items(): + if isinstance(state_val, torch.Tensor) and state_val.ndim > 0: + # shard/replicate non-scalar tensors, for scalar tensor, we + # don't do anything + dtensor_state = distribute_tensor(state_val, mesh, [placement]) + param_dtensor_states[state_key] = dtensor_state + param_states[state_key] = dtensor_state.to_local() + else: + param_dtensor_states[state_key] = state_val + + optimizer.state.pop(param) # type: ignore[call-overload] + optimizer.state[dtensor_param] = param_dtensor_states # type: ignore[index] + + return partitioned_graph diff --git a/shared/package-files/78/78bbd355b21879dd7ea9387c01d58f67deb0199466fac5b2df399cfc1441c747/blob b/shared/package-files/78/78bbd355b21879dd7ea9387c01d58f67deb0199466fac5b2df399cfc1441c747/blob new file mode 100644 index 0000000000000000000000000000000000000000..35310f85da65d35a053dfadd33d57d87ac8d5696 --- /dev/null +++ b/shared/package-files/78/78bbd355b21879dd7ea9387c01d58f67deb0199466fac5b2df399cfc1441c747/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor gelu(const at::Tensor & self, c10::string_view approximate="none"); +TORCH_API at::Tensor & gelu_(at::Tensor & self, c10::string_view approximate="none"); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/78/78bc119ff31c17e70b0e30ad833bdde84dd35a1ec5c29a772ee852d59ae610a3/blob b/shared/package-files/78/78bc119ff31c17e70b0e30ad833bdde84dd35a1ec5c29a772ee852d59ae610a3/blob new file mode 100644 index 0000000000000000000000000000000000000000..6b704fa8094e8b367e9eba47102863ba845415b9 --- /dev/null +++ b/shared/package-files/78/78bc119ff31c17e70b0e30ad833bdde84dd35a1ec5c29a772ee852d59ae610a3/blob @@ -0,0 +1,22 @@ +# flake8: noqa: F401 +r""" +This file is in the process of migration to `torch/ao/quantization`, and +is kept here for compatibility while the migration process is ongoing. +If you are adding a new entry/functionality, please, add it to the +`torch/ao/quantization/fuse_modules.py`, while adding an import statement +here. +""" + +# TODO: These functions are not used outside the `fuse_modules.py` +# Keeping here for now, need to remove them later. +from torch.ao.quantization.fuse_modules import ( + _fuse_modules, + _get_module, + _set_module, + fuse_known_modules, + fuse_modules, + get_fuser_method, +) + +# for backward compatiblity +from torch.ao.quantization.fuser_method_mappings import fuse_conv_bn, fuse_conv_bn_relu diff --git a/shared/package-files/78/78bc43d0a1d95570f93eec3b55f0ccbd86c069786266b53f87570b59ff12064b/blob b/shared/package-files/78/78bc43d0a1d95570f93eec3b55f0ccbd86c069786266b53f87570b59ff12064b/blob new file mode 100644 index 0000000000000000000000000000000000000000..77fb36997507483f20fc89154f2b90532abbcc94 --- /dev/null +++ b/shared/package-files/78/78bc43d0a1d95570f93eec3b55f0ccbd86c069786266b53f87570b59ff12064b/blob @@ -0,0 +1,117 @@ +# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29, +# with extension for dataclasses and type annotation. + +from __future__ import annotations + +import dataclasses +from typing import Any, List, Optional + +from torch.onnx._internal.diagnostics.infra.sarif import ( + _artifact_location, + _configuration_override, + _notification, + _property_bag, +) + + +@dataclasses.dataclass +class Invocation(object): + """The runtime environment of the analysis tool run.""" + + execution_successful: bool = dataclasses.field( + metadata={"schema_property_name": "executionSuccessful"} + ) + account: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "account"} + ) + arguments: Optional[List[str]] = dataclasses.field( + default=None, metadata={"schema_property_name": "arguments"} + ) + command_line: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "commandLine"} + ) + end_time_utc: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "endTimeUtc"} + ) + environment_variables: Any = dataclasses.field( + default=None, metadata={"schema_property_name": "environmentVariables"} + ) + executable_location: Optional[ + _artifact_location.ArtifactLocation + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "executableLocation"} + ) + exit_code: Optional[int] = dataclasses.field( + default=None, metadata={"schema_property_name": "exitCode"} + ) + exit_code_description: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "exitCodeDescription"} + ) + exit_signal_name: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "exitSignalName"} + ) + exit_signal_number: Optional[int] = dataclasses.field( + default=None, metadata={"schema_property_name": "exitSignalNumber"} + ) + machine: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "machine"} + ) + notification_configuration_overrides: Optional[ + List[_configuration_override.ConfigurationOverride] + ] = dataclasses.field( + default=None, + metadata={"schema_property_name": "notificationConfigurationOverrides"}, + ) + process_id: Optional[int] = dataclasses.field( + default=None, metadata={"schema_property_name": "processId"} + ) + process_start_failure_message: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "processStartFailureMessage"} + ) + properties: Optional[_property_bag.PropertyBag] = dataclasses.field( + default=None, metadata={"schema_property_name": "properties"} + ) + response_files: Optional[ + List[_artifact_location.ArtifactLocation] + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "responseFiles"} + ) + rule_configuration_overrides: Optional[ + List[_configuration_override.ConfigurationOverride] + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "ruleConfigurationOverrides"} + ) + start_time_utc: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "startTimeUtc"} + ) + stderr: Optional[_artifact_location.ArtifactLocation] = dataclasses.field( + default=None, metadata={"schema_property_name": "stderr"} + ) + stdin: Optional[_artifact_location.ArtifactLocation] = dataclasses.field( + default=None, metadata={"schema_property_name": "stdin"} + ) + stdout: Optional[_artifact_location.ArtifactLocation] = dataclasses.field( + default=None, metadata={"schema_property_name": "stdout"} + ) + stdout_stderr: Optional[_artifact_location.ArtifactLocation] = dataclasses.field( + default=None, metadata={"schema_property_name": "stdoutStderr"} + ) + tool_configuration_notifications: Optional[ + List[_notification.Notification] + ] = dataclasses.field( + default=None, + metadata={"schema_property_name": "toolConfigurationNotifications"}, + ) + tool_execution_notifications: Optional[ + List[_notification.Notification] + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "toolExecutionNotifications"} + ) + working_directory: Optional[ + _artifact_location.ArtifactLocation + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "workingDirectory"} + ) + + +# flake8: noqa diff --git a/shared/package-files/78/78bd636c12c4a4262504ec9d6dee739b0dde1008d8f6f017a9ed2bb68bc0ee90/blob b/shared/package-files/78/78bd636c12c4a4262504ec9d6dee739b0dde1008d8f6f017a9ed2bb68bc0ee90/blob new file mode 100644 index 0000000000000000000000000000000000000000..76f5559be1a9e026d3e554e0c6dd347bf820780f --- /dev/null +++ b/shared/package-files/78/78bd636c12c4a4262504ec9d6dee739b0dde1008d8f6f017a9ed2bb68bc0ee90/blob @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::index_copy.out(Tensor self, int dim, Tensor index, Tensor source, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & index_copy_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source) { + return at::_ops::index_copy_out::call(self, dim, index, source, out); +} +// aten::index_copy.out(Tensor self, int dim, Tensor index, Tensor source, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & index_copy_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, at::Tensor & out) { + return at::_ops::index_copy_out::call(self, dim, index, source, out); +} + +// aten::index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor +inline at::Tensor index_copy(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source) { + return at::_ops::index_copy::call(self, dim, index, source); +} + +// aten::index_copy.dimname(Tensor self, Dimname dim, Tensor index, Tensor source) -> Tensor +inline at::Tensor index_copy(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, const at::Tensor & source) { + return at::_ops::index_copy_dimname::call(self, dim, index, source); +} + +} diff --git a/shared/package-files/78/78bec78cab122c0b29768f01b30ad8003b36c1dd94fbd6049229d20f92558e8c/blob b/shared/package-files/78/78bec78cab122c0b29768f01b30ad8003b36c1dd94fbd6049229d20f92558e8c/blob new file mode 100644 index 0000000000000000000000000000000000000000..8f95b848bb3332fe0dcbdf9e5b46dc18d6554408 --- /dev/null +++ b/shared/package-files/78/78bec78cab122c0b29768f01b30ad8003b36c1dd94fbd6049229d20f92558e8c/blob @@ -0,0 +1,1761 @@ +"""Laplace Transforms""" +from sympy.core import S, pi, I +from sympy.core.add import Add +from sympy.core.cache import cacheit +from sympy.core.function import ( + AppliedUndef, Derivative, expand, expand_complex, expand_mul, expand_trig, + Lambda, WildFunction, diff) +from sympy.core.mul import Mul, prod +from sympy.core.relational import _canonical, Ge, Gt, Lt, Unequality, Eq +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, symbols, Wild +from sympy.functions.elementary.complexes import ( + re, im, arg, Abs, polar_lift, periodic_argument) +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, asinh +from sympy.functions.elementary.miscellaneous import Max, Min, sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import cos, sin, atan +from sympy.functions.special.bessel import besseli, besselj, besselk, bessely +from sympy.functions.special.delta_functions import DiracDelta, Heaviside +from sympy.functions.special.error_functions import erf, erfc, Ei +from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma +from sympy.integrals import integrate, Integral +from sympy.integrals.transforms import ( + _simplify, IntegralTransform, IntegralTransformError) +from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And +from sympy.matrices.matrices import MatrixBase +from sympy.polys.matrices.linsolve import _lin_eq2dict +from sympy.polys.polyerrors import PolynomialError +from sympy.polys.polyroots import roots +from sympy.polys.polytools import Poly +from sympy.polys.rationaltools import together +from sympy.polys.rootoftools import RootSum +from sympy.utilities.exceptions import ( + sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) +from sympy.utilities.misc import debug, debugf + + +def _simplifyconds(expr, s, a): + r""" + Naively simplify some conditions occurring in ``expr``, + given that `\operatorname{Re}(s) > a`. + + Examples + ======== + + >>> from sympy.integrals.laplace import _simplifyconds + >>> from sympy.abc import x + >>> from sympy import sympify as S + >>> _simplifyconds(abs(x**2) < 1, x, 1) + False + >>> _simplifyconds(abs(x**2) < 1, x, 2) + False + >>> _simplifyconds(abs(x**2) < 1, x, 0) + Abs(x**2) < 1 + >>> _simplifyconds(abs(1/x**2) < 1, x, 1) + True + >>> _simplifyconds(S(1) < abs(x), x, 1) + True + >>> _simplifyconds(S(1) < abs(1/x), x, 1) + False + + >>> from sympy import Ne + >>> _simplifyconds(Ne(1, x**3), x, 1) + True + >>> _simplifyconds(Ne(1, x**3), x, 2) + True + >>> _simplifyconds(Ne(1, x**3), x, 0) + Ne(1, x**3) + """ + + def power(ex): + if ex == s: + return 1 + if ex.is_Pow and ex.base == s: + return ex.exp + return None + + def bigger(ex1, ex2): + """ Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|. + Else return None. """ + if ex1.has(s) and ex2.has(s): + return None + if isinstance(ex1, Abs): + ex1 = ex1.args[0] + if isinstance(ex2, Abs): + ex2 = ex2.args[0] + if ex1.has(s): + return bigger(1/ex2, 1/ex1) + n = power(ex2) + if n is None: + return None + try: + if n > 0 and (Abs(ex1) <= Abs(a)**n) == S.true: + return False + if n < 0 and (Abs(ex1) >= Abs(a)**n) == S.true: + return True + except TypeError: + pass + + def replie(x, y): + """ simplify x < y """ + if (not (x.is_positive or isinstance(x, Abs)) + or not (y.is_positive or isinstance(y, Abs))): + return (x < y) + r = bigger(x, y) + if r is not None: + return not r + return (x < y) + + def replue(x, y): + b = bigger(x, y) + if b in (True, False): + return True + return Unequality(x, y) + + def repl(ex, *args): + if ex in (True, False): + return bool(ex) + return ex.replace(*args) + from sympy.simplify.radsimp import collect_abs + expr = collect_abs(expr) + expr = repl(expr, Lt, replie) + expr = repl(expr, Gt, lambda x, y: replie(y, x)) + expr = repl(expr, Unequality, replue) + return S(expr) + + +def expand_dirac_delta(expr): + """ + Expand an expression involving DiractDelta to get it as a linear + combination of DiracDelta functions. + """ + return _lin_eq2dict(expr, expr.atoms(DiracDelta)) + + +def _laplace_transform_integration(f, t, s_, simplify=True): + """ The backend function for doing Laplace transforms by integration. + + This backend assumes that the frontend has already split sums + such that `f` is to an addition anymore. + """ + s = Dummy('s') + debugf('[LT _l_t_i ] started with (%s, %s, %s)', (f, t, s)) + debugf('[LT _l_t_i ] and simplify=%s', (simplify, )) + + if f.has(DiracDelta): + return None + + F = integrate(f*exp(-s*t), (t, S.Zero, S.Infinity)) + debugf('[LT _l_t_i ] integrated: %s', (F, )) + + if not F.has(Integral): + return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true + + if not F.is_Piecewise: + debug('[LT _l_t_i ] not piecewise.') + return None + + F, cond = F.args[0] + if F.has(Integral): + debug('[LT _l_t_i ] integral in unexpected form.') + return None + + def process_conds(conds): + """ Turn ``conds`` into a strip and auxiliary conditions. """ + from sympy.solvers.inequalities import _solve_inequality + a = S.NegativeInfinity + aux = S.true + conds = conjuncts(to_cnf(conds)) + p, q, w1, w2, w3, w4, w5 = symbols( + 'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s]) + patterns = ( + p*Abs(arg((s + w3)*q)) < w2, + p*Abs(arg((s + w3)*q)) <= w2, + Abs(periodic_argument((s + w3)**p*q, w1)) < w2, + Abs(periodic_argument((s + w3)**p*q, w1)) <= w2, + Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2, + Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2) + for c in conds: + a_ = S.Infinity + aux_ = [] + for d in disjuncts(c): + if d.is_Relational and s in d.rhs.free_symbols: + d = d.reversed + if d.is_Relational and isinstance(d, (Ge, Gt)): + d = d.reversedsign + for pat in patterns: + m = d.match(pat) + if m: + break + if m and m[q].is_positive and m[w2]/m[p] == pi/2: + d = -re(s + m[w3]) < 0 + m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0) + if not m: + m = d.match( + cos(p - Abs(periodic_argument(s**w1*w5, q))*w2) * + Abs(s**w3)**w4 < 0) + if not m: + m = d.match( + p - cos( + Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2 + )*Abs(s**w3)**w4 < 0) + if m and all(m[wild].is_positive for wild in [ + w1, w2, w3, w4, w5]): + d = re(s) > m[p] + d_ = d.replace( + re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t) + if ( + not d.is_Relational or d.rel_op in ('==', '!=') + or d_.has(s) or not d_.has(t)): + aux_ += [d] + continue + soln = _solve_inequality(d_, t) + if not soln.is_Relational or soln.rel_op in ('==', '!='): + aux_ += [d] + continue + if soln.lts == t: + debug('[LT _l_t_i ] convergence not in half-plane.') + return None + else: + a_ = Min(soln.lts, a_) + if a_ is not S.Infinity: + a = Max(a_, a) + else: + aux = And(aux, Or(*aux_)) + return a, aux.canonical if aux.is_Relational else aux + + conds = [process_conds(c) for c in disjuncts(cond)] + conds2 = [x for x in conds if x[1] != + S.false and x[0] is not S.NegativeInfinity] + if not conds2: + conds2 = [x for x in conds if x[1] != S.false] + conds = list(ordered(conds2)) + + def cnt(expr): + if expr in (True, False): + return 0 + return expr.count_ops() + conds.sort(key=lambda x: (-x[0], cnt(x[1]))) + + if not conds: + debug('[LT _l_t_i ] no convergence found.') + return None + a, aux = conds[0] # XXX is [0] always the right one? + + def sbs(expr): + return expr.subs(s, s_) + if simplify: + F = _simplifyconds(F, s, a) + aux = _simplifyconds(aux, s, a) + return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux)) + + +def _laplace_deep_collect(f, t): + """ + This is an internal helper function that traverses through the epression + tree of `f(t)` and collects arguments. The purpose of it is that + anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that + it can match `f(a*t+b)`. + """ + func = f.func + args = list(f.args) + if len(f.args) == 0: + return f + else: + args = [_laplace_deep_collect(arg, t) for arg in args] + if func.is_Add: + return func(*args).collect(t) + else: + return func(*args) + + +@cacheit +def _laplace_build_rules(): + """ + This is an internal helper function that returns the table of Laplace + transform rules in terms of the time variable `t` and the frequency + variable `s`. It is used by ``_laplace_apply_rules``. Each entry is a + tuple containing: + + (time domain pattern, + frequency-domain replacement, + condition for the rule to be applied, + convergence plane, + preparation function) + + The preparation function is a function with one argument that is applied + to the expression before matching. For most rules it should be + ``_laplace_deep_collect``. + """ + t = Dummy('t') + s = Dummy('s') + a = Wild('a', exclude=[t]) + b = Wild('b', exclude=[t]) + n = Wild('n', exclude=[t]) + tau = Wild('tau', exclude=[t]) + omega = Wild('omega', exclude=[t]) + def dco(f): return _laplace_deep_collect(f, t) + debug('_laplace_build_rules is building rules') + + laplace_transform_rules = [ + (a, a/s, + S.true, S.Zero, dco), # 4.2.1 + (DiracDelta(a*t-b), exp(-s*b/a)/Abs(a), + Or(And(a > 0, b >= 0), And(a < 0, b <= 0)), + S.NegativeInfinity, dco), # Not in Bateman54 + (DiracDelta(a*t-b), S(0), + Or(And(a < 0, b >= 0), And(a > 0, b <= 0)), + S.NegativeInfinity, dco), # Not in Bateman54 + (Heaviside(a*t-b), exp(-s*b/a)/s, + And(a > 0, b > 0), S.Zero, dco), # 4.4.1 + (Heaviside(a*t-b), (1-exp(-s*b/a))/s, + And(a < 0, b < 0), S.Zero, dco), # 4.4.1 + (Heaviside(a*t-b), 1/s, + And(a > 0, b <= 0), S.Zero, dco), # 4.4.1 + (Heaviside(a*t-b), 0, + And(a < 0, b > 0), S.Zero, dco), # 4.4.1 + (t, 1/s**2, + S.true, S.Zero, dco), # 4.2.3 + (1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a, + Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.6 + (1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a, + Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.18 + ((a*t+b)**(-S(3)/2), + 2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s) * erfc(sqrt(b/a*s))/a, + Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.20 + (sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)), + Abs(arg(b)) < pi, S.Zero, dco), # 4.2.22 + (1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)), + S.true, S.Zero, dco), # Not in Bateman54 + (t**n, gamma(n+1)/s**(n+1), + n > -1, S.Zero, dco), # 4.3.1 + ((a*t+b)**n, lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a, + And(n > -1, Abs(arg(b/a)) < pi), S.Zero, dco), # 4.3.4 + (t**n/(t+a), a**n*gamma(n+1)*lowergamma(-n, a*s), + And(n > -1, Abs(arg(a)) < pi), S.Zero, dco), # 4.3.7 + (exp(a*t-tau), exp(-tau)/(s-a), + S.true, re(a), dco), # 4.5.1 + (t*exp(a*t-tau), exp(-tau)/(s-a)**2, + S.true, re(a), dco), # 4.5.2 + (t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1), + re(n) > -1, re(a), dco), # 4.5.3 + (exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)), + re(a) > 0, S.Zero, dco), # 4.5.21 + (t*exp(-a*t**2), + 1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)), + re(a) > 0, S.Zero, dco), # 4.5.22 + (exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)), + re(a) >= 0, S.Zero, dco), # 4.5.25 + (sqrt(t)*exp(-a/t), + S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)), + re(a) >= 0, S.Zero, dco), # 4.5.26 + (exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)), + re(a) >= 0, S.Zero, dco), # 4.5.27 + (exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)), + re(a) > 0, S.Zero, dco), # 4.5.28 + (t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)), + re(a) > 0, S.Zero, dco), # 4.5.29 + (exp(-2*sqrt(a*t)), + s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s) * erfc(sqrt(a/s)), + Abs(arg(a)) < pi, S.Zero, dco), # 4.5.31 + (exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)), + Abs(arg(a)) < pi, S.Zero, dco), # 4.5.33 + (log(a*t), -log(exp(S.EulerGamma)*s/a)/s, + a > 0, S.Zero, dco), # 4.6.1 + (log(1+a*t), -exp(s/a)/s*Ei(-s/a), + Abs(arg(a)) < pi, S.Zero, dco), # 4.6.4 + (log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a, + And(a > 0, Abs(arg(b)) < pi), S.Zero, dco), # 4.6.5 + (log(t)/sqrt(t), -sqrt(pi/s)*log(4*s*exp(S.EulerGamma)), + S.true, S.Zero, dco), # 4.6.9 + (t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)), + re(n) > -1, S.Zero, dco), # 4.6.11 + (log(a*t)**2, (log(exp(S.EulerGamma)*s/a)**2+pi**2/6)/s, + a > 0, S.Zero, dco), # 4.6.13 + (sin(omega*t), omega/(s**2+omega**2), + S.true, Abs(im(omega)), dco), # 4,7,1 + (Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega), + omega > 0, S.Zero, dco), # 4.7.2 + (sin(omega*t)/t, atan(omega/s), + S.true, Abs(im(omega)), dco), # 4.7.16 + (sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4, + S.true, 2*Abs(im(omega)), dco), # 4.7.17 + (sin(omega*t)**2/t**2, + omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4, + S.true, 2*Abs(im(omega)), dco), # 4.7.20 + (sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s), + S.true, S.Zero, dco), # 4.7.32 + (sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)), + S.true, S.Zero, dco), # 4.7.34 + (cos(omega*t), s/(s**2+omega**2), + S.true, Abs(im(omega)), dco), # 4.7.43 + (cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s, + S.true, 2*Abs(im(omega)), dco), # 4.7.45 + (sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s), + S.true, S.Zero, dco), # 4.7.66 + (cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s), + S.true, S.Zero, dco), # 4.7.67 + (sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2), + S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.78 + (cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), + S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.79 + (cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), + S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.80 + (sinh(a*t), a/(s**2-a**2), + S.true, Abs(re(a)), dco), # 4.9.1 + (cosh(a*t), s/(s**2-a**2), + S.true, Abs(re(a)), dco), # 4.9.2 + (sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s), + S.true, 2*Abs(re(a)), dco), # 4.9.3 + (cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s), + S.true, 2*Abs(re(a)), dco), # 4.9.4 + (sinh(a*t)/t, log((s+a)/(s-a))/2, + S.true, Abs(re(a)), dco), # 4.9.12 + (t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)), + n > -2, Abs(a), dco), # 4.9.18 + (t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)), + n > -1, Abs(a), dco), # 4.9.19 + (sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s), + S.true, S.Zero, dco), # 4.9.34 + (cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)), + S.true, S.Zero, dco), # 4.9.35 + ( + sqrt(t)*sinh(2*sqrt(a*t)), + pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a) * + exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2), + S.true, S.Zero, dco), # 4.9.36 + (sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s), + S.true, S.Zero, dco), # 4.9.37 + (sinh(2*sqrt(a*t))/sqrt(t), + pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s) * erf(sqrt(a/s)), + S.true, S.Zero, dco), # 4.9.38 + (cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s), + S.true, S.Zero, dco), # 4.9.39 + (sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1), + S.true, S.Zero, dco), # 4.9.40 + (cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1), + S.true, S.Zero, dco), # 4.9.41 + (erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s, + 4*Abs(arg(a)) < pi, S.Zero, dco), # 4.12.2 + (erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s, + S.true, Max(S.Zero, -re(a)), dco), # 4.12.4 + (exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a), + S.true, Max(S.Zero, re(a)), dco), # 4.12.5 + (erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s, + re(a) > 0, S.Zero, dco), # 4.12.6 + (erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s, + S.true, -re(a), dco), # 4.12.9 + (exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)), + S.true, S.Zero, dco), # 4.12.10 + (erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s, + re(a) > 0, S.Zero, dco), # 4.2.11 + (besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n), + re(n) > -1, Abs(im(a)), dco), # 4.14.1 + (t**b*besselj(n, a*t), + 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half), + And(re(n) > -S.Half, Eq(b, n)), Abs(im(a)), dco), # 4.14.7 + (t**b*besselj(n, a*t), + 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2), + And(re(n) > -1, Eq(b, n+1)), Abs(im(a)), dco), # 4.14.8 + (besselj(0, 2*sqrt(a*t)), exp(-a/s)/s, + S.true, S.Zero, dco), # 4.14.25 + (t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s), + And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.14.30 + (besselj(0, a*sqrt(t**2+b*t)), + exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2), + Abs(arg(b)) < pi, Abs(im(a)), dco), # 4.15.19 + (besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n), + re(n) > -1, Abs(re(a)), dco), # 4.16.1 + (t**b*besseli(n, a*t), + 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half), + And(re(n) > -S.Half, Eq(b, n)), Abs(re(a)), dco), # 4.16.6 + (t**b*besseli(n, a*t), + 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2), + And(re(n) > -1, Eq(b, n+1)), Abs(re(a)), dco), # 4.16.7 + (t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s), + And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.16.18 + (bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2), + S.true, Abs(im(a)), dco), # 4.15.44 + (besselk(0, a*t), log((s + sqrt(s**2-a**2))/a)/(sqrt(s**2-a**2)), + S.true, -re(a), dco) # 4.16.23 + ] + return laplace_transform_rules, t, s + + +def _laplace_rule_timescale(f, t, s): + """ + This function applies the time-scaling rule of the Laplace transform in + a straight-forward way. For example, if it gets ``(f(a*t), t, s)``, it will + compute ``LaplaceTransform(f(t)/a, t, s/a)`` if ``a>0``. + """ + + a = Wild('a', exclude=[t]) + g = WildFunction('g', nargs=1) + ma1 = f.match(g) + if ma1: + arg = ma1[g].args[0].collect(t) + ma2 = arg.match(a*t) + if ma2 and ma2[a].is_positive and ma2[a] != 1: + debug('_laplace_apply_prog rules match:') + debugf(' f: %s _ %s, %s )', (f, ma1, ma2)) + debug(' rule: time scaling (4.1.4)') + r, pr, cr = _laplace_transform(1/ma2[a]*ma1[g].func(t), + t, s/ma2[a], simplify=False) + return (r, pr, cr) + return None + + +def _laplace_rule_heaviside(f, t, s): + """ + This function deals with time-shifted Heaviside step functions. If the time + shift is positive, it applies the time-shift rule of the Laplace transform. + For example, if it gets ``(Heaviside(t-a)*f(t), t, s)``, it will compute + ``exp(-a*s)*LaplaceTransform(f(t+a), t, s)``. + + If the time shift is negative, the Heaviside function is simply removed + as it means nothing to the Laplace transform. + + The function does not remove a factor ``Heaviside(t)``; this is done by + the simple rules. + """ + + a = Wild('a', exclude=[t]) + y = Wild('y') + g = Wild('g') + ma1 = f.match(Heaviside(y)*g) + if ma1: + ma2 = ma1[y].match(t-a) + if ma2 and ma2[a].is_positive: + debug('_laplace_apply_prog_rules match:') + debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) + debug(' rule: time shift (4.1.4)') + r, pr, cr = _laplace_transform(ma1[g].subs(t, t+ma2[a]), t, s, + simplify=False) + return (exp(-ma2[a]*s)*r, pr, cr) + if ma2 and ma2[a].is_negative: + debug('_laplace_apply_prog_rules match:') + debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) + debug(' rule: Heaviside factor, negative time shift (4.1.4)') + r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) + return (r, pr, cr) + return None + + +def _laplace_rule_exp(f, t, s): + """ + If this function finds a factor ``exp(a*t)``, it applies the + frequency-shift rule of the Laplace transform and adjusts the convergence + plane accordingly. For example, if it gets ``(exp(-a*t)*f(t), t, s)``, it + will compute ``LaplaceTransform(f(t), t, s+a)``. + """ + + a = Wild('a', exclude=[t]) + y = Wild('y') + z = Wild('z') + ma1 = f.match(exp(y)*z) + if ma1: + ma2 = ma1[y].collect(t).match(a*t) + if ma2: + debug('_laplace_apply_prog_rules match:') + debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) + debug(' rule: multiply with exp (4.1.5)') + r, pr, cr = _laplace_transform(ma1[z], t, s-ma2[a], + simplify=False) + return (r, pr+re(ma2[a]), cr) + return None + + +def _laplace_rule_delta(f, t, s): + """ + If this function finds a factor ``DiracDelta(b*t-a)``, it applies the + masking property of the delta distribution. For example, if it gets + ``(DiracDelta(t-a)*f(t), t, s)``, it will return + ``(f(a)*exp(-a*s), -a, True)``. + """ + # This rule is not in Bateman54 + + a = Wild('a', exclude=[t]) + b = Wild('b', exclude=[t]) + + y = Wild('y') + z = Wild('z') + ma1 = f.match(DiracDelta(y)*z) + if ma1 and not ma1[z].has(DiracDelta): + ma2 = ma1[y].collect(t).match(b*t-a) + if ma2: + debug('_laplace_apply_prog_rules match:') + debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) + debug(' rule: multiply with DiracDelta') + loc = ma2[a]/ma2[b] + if re(loc) >= 0 and im(loc) == 0: + r = exp(-ma2[a]/ma2[b]*s)*ma1[z].subs(t, ma2[a]/ma2[b])/ma2[b] + return (r, S.NegativeInfinity, S.true) + else: + return (0, S.NegativeInfinity, S.true) + if ma1[y].is_polynomial(t): + ro = roots(ma1[y], t) + if roots is not {} and set(ro.values()) == {1}: + slope = diff(ma1[y], t) + r = Add( + *[exp(-x*s)*ma1[z].subs(t, s)/slope.subs(t, x) + for x in list(ro.keys()) if im(x) == 0 and re(x) >= 0]) + return (r, S.NegativeInfinity, S.true) + return None + + +def _laplace_trig_split(fn): + """ + Helper function for `_laplace_rule_trig`. This function returns two terms + `f` and `g`. `f` contains all product terms with sin, cos, sinh, cosh in + them; `g` contains everything else. + """ + trigs = [S.One] + other = [S.One] + for term in Mul.make_args(fn): + if term.has(sin, cos, sinh, cosh, exp): + trigs.append(term) + else: + other.append(term) + f = Mul(*trigs) + g = Mul(*other) + return f, g + + +def _laplace_trig_expsum(f, t): + """ + Helper function for `_laplace_rule_trig`. This function expects the `f` + from `_laplace_trig_split`. It returns two lists `xm` and `xn`. `xm` is + a list of dictionaries with keys `k` and `a` representing a function + `k*exp(a*t)`. `xn` is a list of all terms that cannot be brought into + that form, which may happen, e.g., when a trigonometric function has + another function in its argument. + """ + m = Wild('m') + p = Wild('p', exclude=[t]) + xm = [] + xn = [] + + x1 = f.rewrite(exp).expand() + + for term in Add.make_args(x1): + if not term.has(t): + xm.append({'k': term, 'a': 0, re: 0, im: 0}) + continue + term = term.powsimp(combine='exp') + if (r := term.match(p*exp(m))) is not None: + if (mp := r[m].as_poly(t)) is not None: + mc = mp.all_coeffs() + if len(mc) == 2: + xm.append({ + 'k': r[p]*exp(mc[1]), 'a': mc[0], + re: re(mc[0]), im: im(mc[0])}) + else: + xn.append(term) + else: + xn.append(term) + else: + xn.append(term) + return xm, xn + + +def _laplace_trig_ltex(xm, t, s): + """ + Helper function for `_laplace_rule_trig`. This function takes the list of + exponentials `xm` from `_laplace_trig_expsum` and simplifies complex + conjugate and real symmetric poles. It returns the result as a sum and + the convergence plane. + """ + results = [] + planes = [] + + def _simpc(coeffs): + nc = coeffs.copy() + for k in range(len(nc)): + ri = nc[k].as_real_imag() + if ri[0].has(im): + nc[k] = nc[k].rewrite(cos) + else: + nc[k] = (ri[0] + I*ri[1]).rewrite(cos) + return nc + + def _quadpole(t1, k1, k2, k3, s): + a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im] + nc = [ + k0 + k1 + k2 + k3, + a*(k0 + k1 - k2 - k3) - 2*I*a_i*k1 + 2*I*a_i*k2, + ( + a**2*(-k0 - k1 - k2 - k3) + + a*(4*I*a_i*k0 + 4*I*a_i*k3) + + 4*a_i**2*k0 + 4*a_i**2*k3), + ( + a**3*(-k0 - k1 + k2 + k3) + + a**2*(4*I*a_i*k0 + 2*I*a_i*k1 - 2*I*a_i*k2 - 4*I*a_i*k3) + + a*(4*a_i**2*k0 - 4*a_i**2*k3)) + ] + dc = [ + S.One, S.Zero, 2*a_i**2 - 2*a_r**2, + S.Zero, a_i**4 + 2*a_i**2*a_r**2 + a_r**4] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + debugf(' quadpole: (%s) / (%s)', (n, d)) + return n/d + + def _ccpole(t1, k1, s): + a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im] + nc = [k0 + k1, -a*k0 - a*k1 + 2*I*a_i*k0] + dc = [S.One, -2*a_r, a_i**2 + a_r**2] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + debugf(' ccpole: (%s) / (%s)', (n, d)) + return n/d + + def _rspole(t1, k2, s): + a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im] + nc = [k0 + k2, a*k0 - a*k2 - 2*I*a_i*k0] + dc = [S.One, -2*I*a_i, -a_i**2 - a_r**2] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + debugf(' rspole: (%s) / (%s)', (n, d)) + return n/d + + def _sypole(t1, k3, s): + a, k0 = t1['a'], t1['k'] + nc = [k0 + k3, a*(k0 - k3)] + dc = [S.One, S.Zero, -a**2] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + debugf(' sypole: (%s) / (%s)', (n, d)) + return n/d + + def _simplepole(t1, s): + a, k0 = t1['a'], t1['k'] + n = k0 + d = s - a + debugf(' simplepole: (%s) / (%s)', (n, d)) + return n/d + + while len(xm) > 0: + t1 = xm.pop() + i_imagsym = None + i_realsym = None + i_pointsym = None + # The following code checks all remaining poles. If t1 is a pole at + # a+b*I, then we check for a-b*I, -a+b*I, and -a-b*I, and + # assign the respective indices to i_imagsym, i_realsym, i_pointsym. + # -a-b*I / i_pointsym only applies if both a and b are != 0. + for i in range(len(xm)): + real_eq = t1[re] == xm[i][re] + realsym = t1[re] == -xm[i][re] + imag_eq = t1[im] == xm[i][im] + imagsym = t1[im] == -xm[i][im] + if realsym and imagsym and t1[re] != 0 and t1[im] != 0: + i_pointsym = i + elif realsym and imag_eq and t1[re] != 0: + i_realsym = i + elif real_eq and imagsym and t1[im] != 0: + i_imagsym = i + + # The next part looks for four possible pole constellations: + # quad: a+b*I, a-b*I, -a+b*I, -a-b*I + # cc: a+b*I, a-b*I (a may be zero) + # quad: a+b*I, -a+b*I (b may be zero) + # point: a+b*I, -a-b*I (a!=0 and b!=0 is needed, but that has been + # asserted when finding i_pointsym above.) + # If none apply, then t1 is a simple pole. + if ( + i_imagsym is not None and i_realsym is not None + and i_pointsym is not None): + results.append( + _quadpole(t1, + xm[i_imagsym]['k'], xm[i_realsym]['k'], + xm[i_pointsym]['k'], s)) + planes.append(Abs(re(t1['a']))) + # The three additional poles have now been used; to pop them + # easily we have to do it from the back. + indices_to_pop = [i_imagsym, i_realsym, i_pointsym] + indices_to_pop.sort(reverse=True) + for i in indices_to_pop: + xm.pop(i) + elif i_imagsym is not None: + results.append(_ccpole(t1, xm[i_imagsym]['k'], s)) + planes.append(t1[re]) + xm.pop(i_imagsym) + elif i_realsym is not None: + results.append(_rspole(t1, xm[i_realsym]['k'], s)) + planes.append(Abs(t1[re])) + xm.pop(i_realsym) + elif i_pointsym is not None: + results.append(_sypole(t1, xm[i_pointsym]['k'], s)) + planes.append(Abs(t1[re])) + xm.pop(i_pointsym) + else: + results.append(_simplepole(t1, s)) + planes.append(t1[re]) + + return Add(*results), Max(*planes) + + +def _laplace_rule_trig(fn, t_, s, doit=True, **hints): + """ + This rule covers trigonometric factors by splitting everything into a + sum of exponential functions and collecting complex conjugate poles and + real symmetric poles. + """ + t = Dummy('t', real=True) + + if not fn.has(sin, cos, sinh, cosh): + return None + + debugf('_laplace_rule_trig: (%s, %s, %s)', (fn, t_, s)) + + f, g = _laplace_trig_split(fn.subs(t_, t)) + debugf(' f = %s\n g = %s', (f, g)) + + xm, xn = _laplace_trig_expsum(f, t) + debugf(' xm = %s\n xn = %s', (xm, xn)) + + if len(xn) > 0: + # not implemented yet + debug(' --> xn is not empty; giving up.') + return None + + if not g.has(t): + r, p = _laplace_trig_ltex(xm, t, s) + return g*r, p, S.true + else: + # Just transform `g` and make frequency-shifted copies + planes = [] + results = [] + G, G_plane, G_cond = _laplace_transform(g, t, s) + for x1 in xm: + results.append(x1['k']*G.subs(s, s-x1['a'])) + planes.append(G_plane+re(x1['a'])) + return Add(*results).subs(t, t_), Max(*planes), G_cond + + +def _laplace_rule_diff(f, t, s, doit=True, **hints): + """ + This function looks for derivatives in the time domain and replaces it + by factors of `s` and initial conditions in the frequency domain. For + example, if it gets ``(diff(f(t), t), t, s)``, it will compute + ``s*LaplaceTransform(f(t), t, s) - f(0)``. + """ + + a = Wild('a', exclude=[t]) + n = Wild('n', exclude=[t]) + g = WildFunction('g') + ma1 = f.match(a*Derivative(g, (t, n))) + if ma1 and ma1[n].is_integer: + m = [z.has(t) for z in ma1[g].args] + if sum(m) == 1: + debug('_laplace_apply_rules match:') + debugf(' f, n: %s, %s', (f, ma1[n])) + debug(' rule: time derivative (4.1.8)') + d = [] + for k in range(ma1[n]): + if k == 0: + y = ma1[g].subs(t, 0) + else: + y = Derivative(ma1[g], (t, k)).subs(t, 0) + d.append(s**(ma1[n]-k-1)*y) + r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) + return (ma1[a]*(s**ma1[n]*r - Add(*d)), pr, cr) + return None + + +def _laplace_rule_sdiff(f, t, s, doit=True, **hints): + """ + This function looks for multiplications with polynoimials in `t` as they + correspond to differentiation in the frequency domain. For example, if it + gets ``(t*f(t), t, s)``, it will compute + ``-Derivative(LaplaceTransform(f(t), t, s), s)``. + """ + + if f.is_Mul: + pfac = [1] + ofac = [1] + for fac in Mul.make_args(f): + if fac.is_polynomial(t): + pfac.append(fac) + else: + ofac.append(fac) + if len(pfac) > 1: + pex = prod(pfac) + pc = Poly(pex, t).all_coeffs() + N = len(pc) + if N > 1: + debug('_laplace_apply_rules match:') + debugf(' f, n: %s, %s', (f, pfac)) + debug(' rule: frequency derivative (4.1.6)') + oex = prod(ofac) + r_, p_, c_ = _laplace_transform(oex, t, s, simplify=False) + deri = [r_] + d1 = False + try: + d1 = -diff(deri[-1], s) + except ValueError: + d1 = False + if r_.has(LaplaceTransform): + for k in range(N-1): + deri.append((-1)**(k+1)*Derivative(r_, s, k+1)) + else: + if d1: + deri.append(d1) + for k in range(N-2): + deri.append(-diff(deri[-1], s)) + if d1: + r = Add(*[pc[N-n-1]*deri[n] for n in range(N)]) + return (r, p_, c_) + return None + + +def _laplace_expand(f, t, s, doit=True, **hints): + """ + This function tries to expand its argument with successively stronger + methods: first it will expand on the top level, then it will expand any + multiplications in depth, then it will try all avilable expansion methods, + and finally it will try to expand trigonometric functions. + + If it can expand, it will then compute the Laplace transform of the + expanded term. + """ + + if f.is_Add: + return None + r = expand(f, deep=False) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + r = expand_mul(f) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + r = expand(f) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + if r != f: + return _laplace_transform(r, t, s, simplify=False) + r = expand(expand_trig(f)) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + return None + + +def _laplace_apply_prog_rules(f, t, s): + """ + This function applies all program rules and returns the result if one + of them gives a result. + """ + + prog_rules = [_laplace_rule_heaviside, _laplace_rule_delta, + _laplace_rule_timescale, _laplace_rule_exp, + _laplace_rule_trig, + _laplace_rule_diff, _laplace_rule_sdiff] + + for p_rule in prog_rules: + if (L := p_rule(f, t, s)) is not None: + return L + return None + + +def _laplace_apply_simple_rules(f, t, s): + """ + This function applies all simple rules and returns the result if one + of them gives a result. + """ + simple_rules, t_, s_ = _laplace_build_rules() + prep_old = '' + prep_f = '' + for t_dom, s_dom, check, plane, prep in simple_rules: + if prep_old != prep: + prep_f = prep(f.subs({t: t_})) + prep_old = prep + ma = prep_f.match(t_dom) + if ma: + try: + c = check.xreplace(ma) + except TypeError: + # This may happen if the time function has imaginary + # numbers in it. Then we give up. + continue + if c == S.true: + debug('_laplace_apply_simple_rules match:') + debugf(' f: %s', (f,)) + debugf(' rule: %s o---o %s', (t_dom, s_dom)) + debugf(' match: %s', (ma, )) + return (s_dom.xreplace(ma).subs({s_: s}), + plane.xreplace(ma), S.true) + return None + + +def _laplace_transform(fn, t_, s_, simplify=True): + """ + Front-end function of the Laplace transform. It tries to apply all known + rules recursively, and if everything else fails, it tries to integrate. + """ + debugf('[LT _l_t] (%s, %s, %s)', (fn, t_, s_)) + + terms = Add.make_args(fn) + terms_s = [] + planes = [] + conditions = [] + for ff in terms: + k, ft = ff.as_independent(t_, as_Add=False) + if (r := _laplace_apply_simple_rules(ft, t_, s_)) is not None: + pass + elif (r := _laplace_apply_prog_rules(ft, t_, s_)) is not None: + pass + elif (r := _laplace_expand(ft, t_, s_)) is not None: + pass + elif any(undef.has(t_) for undef in ft.atoms(AppliedUndef)): + # If there are undefined functions f(t) then integration is + # unlikely to do anything useful so we skip it and given an + # unevaluated LaplaceTransform. + r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) + elif (r := _laplace_transform_integration( + ft, t_, s_, simplify=simplify)) is not None: + pass + else: + r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) + (ri_, pi_, ci_) = r + terms_s.append(k*ri_) + planes.append(pi_) + conditions.append(ci_) + + result = Add(*terms_s) + if simplify: + result = result.simplify(doit=False) + plane = Max(*planes) + condition = And(*conditions) + + return result, plane, condition + + +class LaplaceTransform(IntegralTransform): + """ + Class representing unevaluated Laplace transforms. + + For usage of this class, see the :class:`IntegralTransform` docstring. + + For how to compute Laplace transforms, see the :func:`laplace_transform` + docstring. + + If this is called with ``.doit()``, it returns the Laplace transform as an + expression. If it is called with ``.doit(noconds=False)``, it returns a + tuple containing the same expression, a convergence plane, and conditions. + """ + + _name = 'Laplace' + + def _compute_transform(self, f, t, s, **hints): + _simplify = hints.get('simplify', False) + LT = _laplace_transform_integration(f, t, s, simplify=_simplify) + return LT + + def _as_integral(self, f, t, s): + return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity)) + + def _collapse_extra(self, extra): + conds = [] + planes = [] + for plane, cond in extra: + conds.append(cond) + planes.append(plane) + cond = And(*conds) + plane = Max(*planes) + if cond == S.false: + raise IntegralTransformError( + 'Laplace', None, 'No combined convergence.') + return plane, cond + + def doit(self, **hints): + """ + Try to evaluate the transform in closed form. + + Explanation + =========== + + Standard hints are the following: + - ``noconds``: if True, do not return convergence conditions. The + default setting is `True`. + - ``simplify``: if True, it simplifies the final result. The + default setting is `False`. + """ + _noconds = hints.get('noconds', True) + _simplify = hints.get('simplify', False) + + debugf('[LT doit] (%s, %s, %s)', (self.function, + self.function_variable, + self.transform_variable)) + + t_ = self.function_variable + s_ = self.transform_variable + fn = self.function + + r = _laplace_transform(fn, t_, s_, simplify=_simplify) + + if _noconds: + return r[0] + else: + return r + + +def laplace_transform(f, t, s, legacy_matrix=True, **hints): + r""" + Compute the Laplace Transform `F(s)` of `f(t)`, + + .. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t. + + Explanation + =========== + + For all sensible functions, this converges absolutely in a + half-plane + + .. math :: a < \operatorname{Re}(s) + + This function returns ``(F, a, cond)`` where ``F`` is the Laplace + transform of ``f``, `a` is the half-plane of convergence, and `cond` are + auxiliary convergence conditions. + + The implementation is rule-based, and if you are interested in which + rules are applied, and whether integration is attempted, you can switch + debug information on by setting ``sympy.SYMPY_DEBUG=True``. The numbers + of the rules in the debug information (and the code) refer to Bateman's + Tables of Integral Transforms [1]. + + The lower bound is `0-`, meaning that this bound should be approached + from the lower side. This is only necessary if distributions are involved. + At present, it is only done if `f(t)` contains ``DiracDelta``, in which + case the Laplace transform is computed implicitly as + + .. math :: + F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} + f(t) \mathrm{d}t + + by applying rules. + + If the Laplace transform cannot be fully computed in closed form, this + function returns expressions containing unevaluated + :class:`LaplaceTransform` objects. + + For a description of possible hints, refer to the docstring of + :func:`sympy.integrals.transforms.IntegralTransform.doit`. If + ``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also + not the plane ``a``). + + .. deprecated:: 1.9 + Legacy behavior for matrices where ``laplace_transform`` with + ``noconds=False`` (the default) returns a Matrix whose elements are + tuples. The behavior of ``laplace_transform`` for matrices will change + in a future release of SymPy to return a tuple of the transformed + Matrix and the convergence conditions for the matrix as a whole. Use + ``legacy_matrix=False`` to enable the new behavior. + + Examples + ======== + + >>> from sympy import DiracDelta, exp, laplace_transform + >>> from sympy.abc import t, s, a + >>> laplace_transform(t**4, t, s) + (24/s**5, 0, True) + >>> laplace_transform(t**a, t, s) + (gamma(a + 1)/(s*s**a), 0, re(a) > -1) + >>> laplace_transform(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) + (s/(a + s), -re(a), True) + + References + ========== + + .. [1] Erdelyi, A. (ed.), Tables of Integral Transforms, Volume 1, + Bateman Manuscript Prooject, McGraw-Hill (1954), available: + https://resolver.caltech.edu/CaltechAUTHORS:20140123-101456353 + + See Also + ======== + + inverse_laplace_transform, mellin_transform, fourier_transform + hankel_transform, inverse_hankel_transform + + """ + + _noconds = hints.get('noconds', False) + _simplify = hints.get('simplify', False) + + if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'): + + conds = not hints.get('noconds', False) + + if conds and legacy_matrix: + adt = 'deprecated-laplace-transform-matrix' + sympy_deprecation_warning( + """ +Calling laplace_transform() on a Matrix with noconds=False (the default) is +deprecated. Either noconds=True or use legacy_matrix=False to get the new +behavior. + """, + deprecated_since_version='1.9', + active_deprecations_target=adt, + ) + # Temporarily disable the deprecation warning for non-Expr objects + # in Matrix + with ignore_warnings(SymPyDeprecationWarning): + return f.applyfunc( + lambda fij: laplace_transform(fij, t, s, **hints)) + else: + elements_trans = [laplace_transform( + fij, t, s, **hints) for fij in f] + if conds: + elements, avals, conditions = zip(*elements_trans) + f_laplace = type(f)(*f.shape, elements) + return f_laplace, Max(*avals), And(*conditions) + else: + return type(f)(*f.shape, elements_trans) + + LT = LaplaceTransform(f, t, s).doit(noconds=False, simplify=_simplify) + + if not _noconds: + return LT + else: + return LT[0] + + +def _inverse_laplace_transform_integration(F, s, t_, plane, simplify=True): + """ The backend function for inverse Laplace transforms. """ + from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp + from sympy.integrals.transforms import inverse_mellin_transform + + # There are two strategies we can try: + # 1) Use inverse mellin transform, related by a simple change of variables. + # 2) Use the inversion integral. + + t = Dummy('t', real=True) + + def pw_simp(*args): + """ Simplify a piecewise expression from hyperexpand. """ + # XXX we break modularity here! + if len(args) != 3: + return Piecewise(*args) + arg = args[2].args[0].argument + coeff, exponent = _get_coeff_exp(arg, t) + e1 = args[0].args[0] + e2 = args[1].args[0] + return ( + Heaviside(1/Abs(coeff) - t**exponent)*e1 + + Heaviside(t**exponent - 1/Abs(coeff))*e2) + + if F.is_rational_function(s): + F = F.apart(s) + + if F.is_Add: + f = Add( + *[_inverse_laplace_transform_integration(X, s, t, plane, simplify) + for X in F.args]) + return _simplify(f.subs(t, t_), simplify), True + + try: + f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity), + needeval=True, noconds=False) + except IntegralTransformError: + f = None + if f is None: + f = meijerint_inversion(F, s, t) + if f is None: + return None + if f.is_Piecewise: + f, cond = f.args[0] + if f.has(Integral): + return None + else: + cond = S.true + f = f.replace(Piecewise, pw_simp) + + if f.is_Piecewise: + # many of the functions called below can't work with piecewise + # (b/c it has a bool in args) + return f.subs(t, t_), cond + + u = Dummy('u') + + def simp_heaviside(arg, H0=S.Half): + a = arg.subs(exp(-t), u) + if a.has(t): + return Heaviside(arg, H0) + from sympy.solvers.inequalities import _solve_inequality + rel = _solve_inequality(a > 0, u) + if rel.lts == u: + k = log(rel.gts) + return Heaviside(t + k, H0) + else: + k = log(rel.lts) + return Heaviside(-(t + k), H0) + + f = f.replace(Heaviside, simp_heaviside) + + def simp_exp(arg): + return expand_complex(exp(arg)) + + f = f.replace(exp, simp_exp) + + # TODO it would be nice to fix cosh and sinh ... simplify messes these + # exponentials up + + return _simplify(f.subs(t, t_), simplify), cond + + +def _complete_the_square_in_denom(f, s): + from sympy.simplify.radsimp import fraction + [n, d] = fraction(f) + if d.is_polynomial(s): + cf = d.as_poly(s).all_coeffs() + if len(cf) == 3: + a, b, c = cf + d = a*((s+b/(2*a))**2+c/a-(b/(2*a))**2) + return n/d + + +@cacheit +def _inverse_laplace_build_rules(): + """ + This is an internal helper function that returns the table of inverse + Laplace transform rules in terms of the time variable `t` and the + frequency variable `s`. It is used by `_inverse_laplace_apply_rules`. + """ + s = Dummy('s') + t = Dummy('t') + a = Wild('a', exclude=[s]) + b = Wild('b', exclude=[s]) + c = Wild('c', exclude=[s]) + + debug('_inverse_laplace_build_rules is building rules') + + def _frac(f, s): + try: + return f.factor(s) + except PolynomialError: + return f + + def same(f): return f + # This list is sorted according to the prep function needed. + _ILT_rules = [ + (a/s, a, S.true, same, 1), + (b*(s+a)**(-c), t**(c-1)*exp(-a*t)/gamma(c), c > 0, same, 1), + (1/(s**2+a**2)**2, (sin(a*t) - a*t*cos(a*t))/(2*a**3), + S.true, same, 1), + # The next two rules must be there in that order. For the second + # one, the condition would be a != 0 or, respectively, to take the + # limit a -> 0 after the transform if a == 0. It is much simpler if + # the case a == 0 has its own rule. + (1/(s**b), t**(b - 1)/gamma(b), S.true, same, 1), + (1/(s*(s+a)**b), lowergamma(b, a*t)/(a**b*gamma(b)), + S.true, same, 1) + ] + return _ILT_rules, s, t + + +def _inverse_laplace_apply_simple_rules(f, s, t): + """ + Helper function for the class InverseLaplaceTransform. + """ + if f == 1: + debug('_inverse_laplace_apply_simple_rules match:') + debugf(' f: %s', (1,)) + debugf(' rule: 1 o---o DiracDelta(%s)', (t,)) + return DiracDelta(t), S.true + + _ILT_rules, s_, t_ = _inverse_laplace_build_rules() + _prep = '' + fsubs = f.subs({s: s_}) + + for s_dom, t_dom, check, prep, fac in _ILT_rules: + if _prep != (prep, fac): + _F = prep(fsubs*fac) + _prep = (prep, fac) + ma = _F.match(s_dom) + if ma: + try: + c = check.xreplace(ma) + except TypeError: + continue + if c == S.true: + debug('_inverse_laplace_apply_simple_rules match:') + debugf(' f: %s', (f,)) + debugf(' rule: %s o---o %s', (s_dom, t_dom)) + debugf(' ma: %s', (ma,)) + return Heaviside(t)*t_dom.xreplace(ma).subs({t_: t}), S.true + + return None + + +def _inverse_laplace_time_shift(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + a = Wild('a', exclude=[s]) + g = Wild('g') + + if not F.has(s): + return F*DiracDelta(t), S.true + ma1 = F.match(exp(a*s)) + if ma1: + if ma1[a].is_negative: + debug('_inverse_laplace_time_shift match:') + debugf(' f: %s', (F,)) + debug(' rule: exp(-a*s) o---o DiracDelta(t-a)') + debugf(' ma: %s', (ma1,)) + return DiracDelta(t+ma1[a]), S.true + else: + debug('_inverse_laplace_time_shift match: negative time shift') + return InverseLaplaceTransform(F, s, t, plane), S.true + + ma1 = F.match(exp(a*s)*g) + if ma1: + if ma1[a].is_negative: + debug('_inverse_laplace_time_shift match:') + debugf(' f: %s', (F,)) + debug(' rule: exp(-a*s)*F(s) o---o Heaviside(t-a)*f(t-a)') + debugf(' ma: %s', (ma1,)) + return _inverse_laplace_transform(ma1[g], s, t+ma1[a], plane) + else: + debug('_inverse_laplace_time_shift match: negative time shift') + return InverseLaplaceTransform(F, s, t, plane), S.true + return None + + +def _inverse_laplace_time_diff(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + n = Wild('n', exclude=[s]) + g = Wild('g') + + ma1 = F.match(s**n*g) + if ma1 and ma1[n].is_integer and ma1[n].is_positive: + debug('_inverse_laplace_time_diff match:') + debugf(' f: %s', (F,)) + debug(' rule: s**n*F(s) o---o diff(f(t), t, n)') + debugf(' ma: %s', (ma1,)) + r, c = _inverse_laplace_transform(ma1[g], s, t, plane) + r = r.replace(Heaviside(t), 1) + if r.has(InverseLaplaceTransform): + return diff(r, t, ma1[n]), c + else: + return Heaviside(t)*diff(r, t, ma1[n]), c + return None + + +def _inverse_laplace_apply_prog_rules(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + prog_rules = [_inverse_laplace_time_shift, + _inverse_laplace_time_diff] + + for p_rule in prog_rules: + if (r := p_rule(F, s, t, plane)) is not None: + return r + return None + + +def _inverse_laplace_expand(fn, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + if fn.is_Add: + return None + r = expand(fn, deep=False) + if r.is_Add: + return _inverse_laplace_transform(r, s, t, plane) + r = expand_mul(fn) + if r.is_Add: + return _inverse_laplace_transform(r, s, t, plane) + r = expand(fn) + if r.is_Add: + return _inverse_laplace_transform(r, s, t, plane) + if fn.is_rational_function(s): + r = fn.apart(s).doit() + if r.is_Add: + return _inverse_laplace_transform(r, s, t, plane) + return None + + +def _inverse_laplace_rational(fn, s, t, plane, simplify): + """ + Helper function for the class InverseLaplaceTransform. + """ + debugf('[ILT _i_l_r] (%s, %s, %s)', (fn, s, t)) + x_ = symbols('x_') + f = fn.apart(s) + terms = Add.make_args(f) + terms_t = [] + conditions = [S.true] + for term in terms: + [n, d] = term.as_numer_denom() + dc = d.as_poly(s).all_coeffs() + dc_lead = dc[0] + dc = [x/dc_lead for x in dc] + nc = [x/dc_lead for x in n.as_poly(s).all_coeffs()] + if len(dc) == 1: + r = nc[0]*DiracDelta(t) + terms_t.append(r) + elif len(dc) == 2: + r = nc[0]*exp(-dc[1]*t) + terms_t.append(Heaviside(t)*r) + elif len(dc) == 3: + a = dc[1]/2 + b = (dc[2]-a**2).factor() + if len(nc) == 1: + nc = [S.Zero] + nc + l, m = tuple(nc) + if b == 0: + r = (m*t+l*(1-a*t))*exp(-a*t) + else: + hyp = False + if b.is_negative: + b = -b + hyp = True + b2 = list(roots(x_**2-b, x_).keys())[0] + bs = sqrt(b).simplify() + if hyp: + r = ( + l*exp(-a*t)*cosh(b2*t) + (m-a*l) / + bs*exp(-a*t)*sinh(bs*t)) + else: + r = l*exp(-a*t)*cos(b2*t) + (m-a*l)/bs*exp(-a*t)*sin(bs*t) + terms_t.append(Heaviside(t)*r) + else: + ft, cond = _inverse_laplace_transform( + fn, s, t, plane, simplify=True, dorational=False) + terms_t.append(ft) + conditions.append(cond) + + result = Add(*terms_t) + if simplify: + result = result.simplify(doit=False) + debugf('[ILT _i_l_r] returns %s', (result,)) + return result, And(*conditions) + + +def _inverse_laplace_transform( + fn, s_, t_, plane, simplify=True, dorational=True): + """ + Front-end function of the inverse Laplace transform. It tries to apply all + known rules recursively. If everything else fails, it tries to integrate. + """ + terms = Add.make_args(fn) + terms_t = [] + conditions = [] + + debugf('[ILT _i_l_t] (%s, %s, %s)', (fn, s_, t_)) + + for term in terms: + k, f = term.as_independent(s_, as_Add=False) + if ( + dorational and term.is_rational_function(s_) and + ( + r := _inverse_laplace_rational( + f, s_, t_, plane, simplify)) is not None): + pass + elif (r := _inverse_laplace_apply_simple_rules(f, s_, t_)) is not None: + pass + elif (r := _inverse_laplace_expand(f, s_, t_, plane)) is not None: + pass + elif ( + (r := _inverse_laplace_apply_prog_rules(f, s_, t_, plane)) + is not None): + pass + elif any(undef.has(s_) for undef in f.atoms(AppliedUndef)): + # If there are undefined functions f(t) then integration is + # unlikely to do anything useful so we skip it and given an + # unevaluated LaplaceTransform. + r = (InverseLaplaceTransform(f, s_, t_, plane), S.true) + elif ( + r := _inverse_laplace_transform_integration( + f, s_, t_, plane, simplify=simplify)) is not None: + pass + else: + r = (InverseLaplaceTransform(f, s_, t_, plane), S.true) + (ri_, ci_) = r + terms_t.append(k*ri_) + conditions.append(ci_) + + result = Add(*terms_t) + if simplify: + result = result.simplify(doit=False) + condition = And(*conditions) + + return result, condition + + +class InverseLaplaceTransform(IntegralTransform): + """ + Class representing unevaluated inverse Laplace transforms. + + For usage of this class, see the :class:`IntegralTransform` docstring. + + For how to compute inverse Laplace transforms, see the + :func:`inverse_laplace_transform` docstring. + """ + + _name = 'Inverse Laplace' + _none_sentinel = Dummy('None') + _c = Dummy('c') + + def __new__(cls, F, s, x, plane, **opts): + if plane is None: + plane = InverseLaplaceTransform._none_sentinel + return IntegralTransform.__new__(cls, F, s, x, plane, **opts) + + @property + def fundamental_plane(self): + plane = self.args[3] + if plane is InverseLaplaceTransform._none_sentinel: + plane = None + return plane + + def _compute_transform(self, F, s, t, **hints): + return _inverse_laplace_transform_integration( + F, s, t, self.fundamental_plane, **hints) + + def _as_integral(self, F, s, t): + c = self.__class__._c + return ( + Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity, + c + S.ImaginaryUnit*S.Infinity)) / + (2*S.Pi*S.ImaginaryUnit)) + + def doit(self, **hints): + """ + Try to evaluate the transform in closed form. + + Explanation + =========== + + Standard hints are the following: + - ``noconds``: if True, do not return convergence conditions. The + default setting is `True`. + - ``simplify``: if True, it simplifies the final result. The + default setting is `False`. + """ + _noconds = hints.get('noconds', True) + _simplify = hints.get('simplify', False) + + debugf('[ILT doit] (%s, %s, %s)', (self.function, + self.function_variable, + self.transform_variable)) + + s_ = self.function_variable + t_ = self.transform_variable + fn = self.function + plane = self.fundamental_plane + + r = _inverse_laplace_transform(fn, s_, t_, plane, simplify=_simplify) + + if _noconds: + return r[0] + else: + return r + + +def inverse_laplace_transform(F, s, t, plane=None, **hints): + r""" + Compute the inverse Laplace transform of `F(s)`, defined as + + .. math :: + f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} + F(s) \mathrm{d}s, + + for `c` so large that `F(s)` has no singularites in the + half-plane `\operatorname{Re}(s) > c-\epsilon`. + + Explanation + =========== + + The plane can be specified by + argument ``plane``, but will be inferred if passed as None. + + Under certain regularity conditions, this recovers `f(t)` from its + Laplace Transform `F(s)`, for non-negative `t`, and vice + versa. + + If the integral cannot be computed in closed form, this function returns + an unevaluated :class:`InverseLaplaceTransform` object. + + Note that this function will always assume `t` to be real, + regardless of the SymPy assumption on `t`. + + For a description of possible hints, refer to the docstring of + :func:`sympy.integrals.transforms.IntegralTransform.doit`. + + Examples + ======== + + >>> from sympy import inverse_laplace_transform, exp, Symbol + >>> from sympy.abc import s, t + >>> a = Symbol('a', positive=True) + >>> inverse_laplace_transform(exp(-a*s)/s, s, t) + Heaviside(-a + t) + + See Also + ======== + + laplace_transform + hankel_transform, inverse_hankel_transform + """ + if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'): + return F.applyfunc( + lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints)) + return InverseLaplaceTransform(F, s, t, plane).doit(**hints) + + +def _fast_inverse_laplace(e, s, t): + """Fast inverse Laplace transform of rational function including RootSum""" + a, b, n = symbols('a, b, n', cls=Wild, exclude=[s]) + + def _ilt(e): + if not e.has(s): + return e + elif e.is_Add: + return _ilt_add(e) + elif e.is_Mul: + return _ilt_mul(e) + elif e.is_Pow: + return _ilt_pow(e) + elif isinstance(e, RootSum): + return _ilt_rootsum(e) + else: + raise NotImplementedError + + def _ilt_add(e): + return e.func(*map(_ilt, e.args)) + + def _ilt_mul(e): + coeff, expr = e.as_independent(s) + if expr.is_Mul: + raise NotImplementedError + return coeff * _ilt(expr) + + def _ilt_pow(e): + match = e.match((a*s + b)**n) + if match is not None: + nm, am, bm = match[n], match[a], match[b] + if nm.is_Integer and nm < 0: + return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm)) + if nm == 1: + return exp(-(bm/am)*t) / am + raise NotImplementedError + + def _ilt_rootsum(e): + expr = e.fun.expr + [variable] = e.fun.variables + return RootSum(e.poly, Lambda(variable, together(_ilt(expr)))) + + return _ilt(e) diff --git a/shared/package-files/78/78c0a919bbfb93590efa8d0bc5f59b3e2bd5396f39b31ce18fcd26efd290aa56/blob b/shared/package-files/78/78c0a919bbfb93590efa8d0bc5f59b3e2bd5396f39b31ce18fcd26efd290aa56/blob new file mode 100644 index 0000000000000000000000000000000000000000..6722fa2b144ae19faa1c7b3ee1438134e603348a --- /dev/null +++ b/shared/package-files/78/78c0a919bbfb93590efa8d0bc5f59b3e2bd5396f39b31ce18fcd26efd290aa56/blob @@ -0,0 +1,103 @@ +# +# The Python Imaging Library +# +# load a GIMP brush file +# +# History: +# 96-03-14 fl Created +# 16-01-08 es Version 2 +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# Copyright (c) Eric Soroos 2016. +# +# See the README file for information on usage and redistribution. +# +# +# See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for +# format documentation. +# +# This code Interprets version 1 and 2 .gbr files. +# Version 1 files are obsolete, and should not be used for new +# brushes. +# Version 2 files are saved by GIMP v2.8 (at least) +# Version 3 files have a format specifier of 18 for 16bit floats in +# the color depth field. This is currently unsupported by Pillow. +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i32be as i32 + + +def _accept(prefix): + return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2) + + +## +# Image plugin for the GIMP brush format. + + +class GbrImageFile(ImageFile.ImageFile): + format = "GBR" + format_description = "GIMP brush file" + + def _open(self): + header_size = i32(self.fp.read(4)) + if header_size < 20: + msg = "not a GIMP brush" + raise SyntaxError(msg) + version = i32(self.fp.read(4)) + if version not in (1, 2): + msg = f"Unsupported GIMP brush version: {version}" + raise SyntaxError(msg) + + width = i32(self.fp.read(4)) + height = i32(self.fp.read(4)) + color_depth = i32(self.fp.read(4)) + if width <= 0 or height <= 0: + msg = "not a GIMP brush" + raise SyntaxError(msg) + if color_depth not in (1, 4): + msg = f"Unsupported GIMP brush color depth: {color_depth}" + raise SyntaxError(msg) + + if version == 1: + comment_length = header_size - 20 + else: + comment_length = header_size - 28 + magic_number = self.fp.read(4) + if magic_number != b"GIMP": + msg = "not a GIMP brush, bad magic number" + raise SyntaxError(msg) + self.info["spacing"] = i32(self.fp.read(4)) + + comment = self.fp.read(comment_length)[:-1] + + if color_depth == 1: + self._mode = "L" + else: + self._mode = "RGBA" + + self._size = width, height + + self.info["comment"] = comment + + # Image might not be small + Image._decompression_bomb_check(self.size) + + # Data is an uncompressed block of w * h * bytes/pixel + self._data_size = width * height * color_depth + + def load(self): + if not self.im: + self.im = Image.core.new(self.mode, self.size) + self.frombytes(self.fp.read(self._data_size)) + return Image.Image.load(self) + + +# +# registry + + +Image.register_open(GbrImageFile.format, GbrImageFile, _accept) +Image.register_extension(GbrImageFile.format, ".gbr") diff --git a/shared/package-files/78/78c2261a57d84503397aca058561cec031982b746e5ddacdbd2b544707050e57/blob b/shared/package-files/78/78c2261a57d84503397aca058561cec031982b746e5ddacdbd2b544707050e57/blob new file mode 100644 index 0000000000000000000000000000000000000000..40a6fa599e2bc7f7813a9d2c3f2ce6d89397bb39 --- /dev/null +++ b/shared/package-files/78/78c2261a57d84503397aca058561cec031982b746e5ddacdbd2b544707050e57/blob @@ -0,0 +1,37 @@ +from llvmlite import ir + +from numba.cuda.cudadrv import nvvm +from numba.cuda.testing import unittest, ContextResettingTestCase +from numba.cuda.testing import skip_on_cudasim + + +@skip_on_cudasim('Inline PTX cannot be used in the simulator') +class TestCudaInlineAsm(ContextResettingTestCase): + def test_inline_rsqrt(self): + mod = ir.Module(__name__) + mod.triple = 'nvptx64-nvidia-cuda' + nvvm.add_ir_version(mod) + fnty = ir.FunctionType(ir.VoidType(), [ir.PointerType(ir.FloatType())]) + fn = ir.Function(mod, fnty, 'cu_rsqrt') + bldr = ir.IRBuilder(fn.append_basic_block('entry')) + + rsqrt_approx_fnty = ir.FunctionType(ir.FloatType(), [ir.FloatType()]) + inlineasm = ir.InlineAsm(rsqrt_approx_fnty, + 'rsqrt.approx.f32 $0, $1;', + '=f,f', side_effect=True) + val = bldr.load(fn.args[0]) + res = bldr.call(inlineasm, [val]) + + bldr.store(res, fn.args[0]) + bldr.ret_void() + + # generate ptx + mod.data_layout = nvvm.NVVM().data_layout + nvvm.set_cuda_kernel(fn) + nvvmir = str(mod) + ptx = nvvm.compile_ir(nvvmir) + self.assertTrue('rsqrt.approx.f32' in str(ptx)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/78/78c28bf1d64aae07a47f9558546475e1a9f6f4918422746d50ef2e8bd001cb08/blob b/shared/package-files/78/78c28bf1d64aae07a47f9558546475e1a9f6f4918422746d50ef2e8bd001cb08/blob new file mode 100644 index 0000000000000000000000000000000000000000..8db55dcbaa3e7bab091781b17ce22fde1fc239f2 --- /dev/null +++ b/shared/package-files/78/78c28bf1d64aae07a47f9558546475e1a9f6f4918422746d50ef2e8bd001cb08/blob @@ -0,0 +1,65 @@ +from __future__ import annotations + +import os +import sys +from contextlib import suppress +from errno import EACCES +from pathlib import Path +from typing import cast + +from ._api import BaseFileLock +from ._util import ensure_directory_exists, raise_on_not_writable_file + +if sys.platform == "win32": # pragma: win32 cover + import msvcrt + + class WindowsFileLock(BaseFileLock): + """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems.""" + + def _acquire(self) -> None: + raise_on_not_writable_file(self.lock_file) + ensure_directory_exists(self.lock_file) + flags = ( + os.O_RDWR # open for read and write + | os.O_CREAT # create file if not exists + | os.O_TRUNC # truncate file if not empty + ) + try: + fd = os.open(self.lock_file, flags, self._context.mode) + except OSError as exception: + if exception.errno != EACCES: # has no access to this lock + raise + else: + try: + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + except OSError as exception: + os.close(fd) # close file first + if exception.errno != EACCES: # file is already locked + raise + else: + self._context.lock_file_fd = fd + + def _release(self) -> None: + fd = cast(int, self._context.lock_file_fd) + self._context.lock_file_fd = None + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + os.close(fd) + + with suppress(OSError): # Probably another instance of the application hat acquired the file lock. + Path(self.lock_file).unlink() + +else: # pragma: win32 no cover + + class WindowsFileLock(BaseFileLock): + """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems.""" + + def _acquire(self) -> None: + raise NotImplementedError + + def _release(self) -> None: + raise NotImplementedError + + +__all__ = [ + "WindowsFileLock", +] diff --git a/shared/package-files/78/78c9747bc2db92f47ee2775ee64ba4cd7c8d6875c04132782201f543c355ad90/blob b/shared/package-files/78/78c9747bc2db92f47ee2775ee64ba4cd7c8d6875c04132782201f543c355ad90/blob new file mode 100644 index 0000000000000000000000000000000000000000..862d2c3542649fac26bf449ff81714584a3c404b --- /dev/null +++ b/shared/package-files/78/78c9747bc2db92f47ee2775ee64ba4cd7c8d6875c04132782201f543c355ad90/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78c9747bc2db92f47ee2775ee64ba4cd7c8d6875c04132782201f543c355ad90 +size 208346 diff --git a/shared/package-files/78/78cce4f3057535eeba51cfb543a88add149d42729036c36fd07e04065aeac9c6/blob b/shared/package-files/78/78cce4f3057535eeba51cfb543a88add149d42729036c36fd07e04065aeac9c6/blob new file mode 100644 index 0000000000000000000000000000000000000000..3aa6204c4de7da9179bd703d3c81b9fecfbae600 --- /dev/null +++ b/shared/package-files/78/78cce4f3057535eeba51cfb543a88add149d42729036c36fd07e04065aeac9c6/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78cce4f3057535eeba51cfb543a88add149d42729036c36fd07e04065aeac9c6 +size 2071644 diff --git a/shared/package-files/78/78cceb9b368cb3a4ceec948c49f4a891f0155bf75a326b3eed77a5e57caa2997/blob b/shared/package-files/78/78cceb9b368cb3a4ceec948c49f4a891f0155bf75a326b3eed77a5e57caa2997/blob new file mode 100644 index 0000000000000000000000000000000000000000..aade231e46f560cb3b42d1616fe208d8996b1ab3 --- /dev/null +++ b/shared/package-files/78/78cceb9b368cb3a4ceec948c49f4a891f0155bf75a326b3eed77a5e57caa2997/blob @@ -0,0 +1,40 @@ +from threadpoolctl import threadpool_info + +from sklearn.utils._show_versions import _get_deps_info, _get_sys_info, show_versions +from sklearn.utils._testing import ignore_warnings + + +def test_get_sys_info(): + sys_info = _get_sys_info() + + assert "python" in sys_info + assert "executable" in sys_info + assert "machine" in sys_info + + +def test_get_deps_info(): + with ignore_warnings(): + deps_info = _get_deps_info() + + assert "pip" in deps_info + assert "setuptools" in deps_info + assert "sklearn" in deps_info + assert "numpy" in deps_info + assert "scipy" in deps_info + assert "Cython" in deps_info + assert "pandas" in deps_info + assert "matplotlib" in deps_info + assert "joblib" in deps_info + + +def test_show_versions(capsys): + with ignore_warnings(): + show_versions() + out, err = capsys.readouterr() + + assert "python" in out + assert "numpy" in out + + info = threadpool_info() + if info: + assert "threadpoolctl info:" in out diff --git a/shared/package-files/78/78d53fd68f218f501661f2885081431584b067bb2feb35e05539d4b0076331b6/blob b/shared/package-files/78/78d53fd68f218f501661f2885081431584b067bb2feb35e05539d4b0076331b6/blob new file mode 100644 index 0000000000000000000000000000000000000000..dbfdd08cbe32b7d2a5b0325b31558abdf5928bc2 --- /dev/null +++ b/shared/package-files/78/78d53fd68f218f501661f2885081431584b067bb2feb35e05539d4b0076331b6/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor adaptive_max_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/shared/package-files/78/78dd3a400d494bac2302deff019cd6df1a33b4733f86869d945525fe1c2c1221/blob b/shared/package-files/78/78dd3a400d494bac2302deff019cd6df1a33b4733f86869d945525fe1c2c1221/blob new file mode 100644 index 0000000000000000000000000000000000000000..ac91d399d9b6b0ade65a3efed6b096650ddd6eb7 --- /dev/null +++ b/shared/package-files/78/78dd3a400d494bac2302deff019cd6df1a33b4733f86869d945525fe1c2c1221/blob @@ -0,0 +1,19 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from narwhals._compliant import LazyExprNamespace +from narwhals._compliant.any_namespace import StructNamespace +from narwhals._duckdb.utils import F, lit + +if TYPE_CHECKING: + from narwhals._duckdb.expr import DuckDBExpr + + +class DuckDBExprStructNamespace( + LazyExprNamespace["DuckDBExpr"], StructNamespace["DuckDBExpr"] +): + def field(self, name: str) -> DuckDBExpr: + return self.compliant._with_elementwise( + lambda expr: F("struct_extract", expr, lit(name)) + ).alias(name) diff --git a/shared/package-files/78/78de22efbb8155374f4d2233ba30c17cda1e861f362bc703235e717a185f45bc/blob b/shared/package-files/78/78de22efbb8155374f4d2233ba30c17cda1e861f362bc703235e717a185f45bc/blob new file mode 100644 index 0000000000000000000000000000000000000000..6b820bd02882e37c97e7b0802cac2f1235899514 --- /dev/null +++ b/shared/package-files/78/78de22efbb8155374f4d2233ba30c17cda1e861f362bc703235e717a185f45bc/blob @@ -0,0 +1,12 @@ +#pragma once + +#include +#include +#include + +namespace torch::utils { + +void initializeMemoryFormats(); +TORCH_PYTHON_API PyObject* getTHPMemoryFormat(c10::MemoryFormat); + +} // namespace torch::utils diff --git a/shared/package-files/78/78e0f83db78dcf4ea14887e915a408af08d9d9a351f2542f29a5d222b9284efe/blob b/shared/package-files/78/78e0f83db78dcf4ea14887e915a408af08d9d9a351f2542f29a5d222b9284efe/blob new file mode 100644 index 0000000000000000000000000000000000000000..bd4623c617183a54143759a596a66a5f73cbcb6c --- /dev/null +++ b/shared/package-files/78/78e0f83db78dcf4ea14887e915a408af08d9d9a351f2542f29a5d222b9284efe/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78e0f83db78dcf4ea14887e915a408af08d9d9a351f2542f29a5d222b9284efe +size 1472368 diff --git a/shared/package-files/78/78e1080695172da1f922439c6b92a8dc741d5067c3203143c2696ccfb4411890/blob b/shared/package-files/78/78e1080695172da1f922439c6b92a8dc741d5067c3203143c2696ccfb4411890/blob new file mode 100644 index 0000000000000000000000000000000000000000..08f4c746735f8574dfe05735dac487861d2105c9 --- /dev/null +++ b/shared/package-files/78/78e1080695172da1f922439c6b92a8dc741d5067c3203143c2696ccfb4411890/blob @@ -0,0 +1,44 @@ +from abc import ABCMeta, abstractmethod +from typing import Optional + +from cryptography.hazmat.backends.interfaces import CipherBackend +from cryptography.hazmat.primitives.ciphers.modes import Mode + +class AEADCipherContext(metaclass=ABCMeta): + @abstractmethod + def authenticate_additional_data(self, data: bytes) -> None: ... + +class AEADDecryptionContext(metaclass=ABCMeta): + @abstractmethod + def finalize_with_tag(self, tag: bytes) -> bytes: ... + +class AEADEncryptionContext(metaclass=ABCMeta): + @property + @abstractmethod + def tag(self) -> bytes: ... + +class BlockCipherAlgorithm(metaclass=ABCMeta): + @property + @abstractmethod + def block_size(self) -> int: ... + +class Cipher(object): + def __init__(self, algorithm: CipherAlgorithm, mode: Optional[Mode], backend: Optional[CipherBackend] = ...) -> None: ... + def decryptor(self) -> CipherContext: ... + def encryptor(self) -> CipherContext: ... + +class CipherAlgorithm(metaclass=ABCMeta): + @property + @abstractmethod + def key_size(self) -> int: ... + @property + @abstractmethod + def name(self) -> str: ... + +class CipherContext(metaclass=ABCMeta): + @abstractmethod + def finalize(self) -> bytes: ... + @abstractmethod + def update(self, data: bytes) -> bytes: ... + @abstractmethod + def update_into(self, data: bytes, buf: bytearray) -> int: ... diff --git a/shared/package-files/78/78e2d9bcf32b3ba2cc5d4b489f6ddee43680a780bb8f8eea23cd96271b26a003/blob b/shared/package-files/78/78e2d9bcf32b3ba2cc5d4b489f6ddee43680a780bb8f8eea23cd96271b26a003/blob new file mode 100644 index 0000000000000000000000000000000000000000..16a5b8377df319a25a29307b8d878b97dd1aa1af --- /dev/null +++ b/shared/package-files/78/78e2d9bcf32b3ba2cc5d4b489f6ddee43680a780bb8f8eea23cd96271b26a003/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API reflection_pad2d_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::reflection_pad2d_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "reflection_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input); +}; + +struct TORCH_API reflection_pad2d_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::reflection_pad2d_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "reflection_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/78/78e34ba4756971b90ac747dcb96ec96f3837fdcad5efda30a7eefdc3a5bd65be/blob b/shared/package-files/78/78e34ba4756971b90ac747dcb96ec96f3837fdcad5efda30a7eefdc3a5bd65be/blob new file mode 100644 index 0000000000000000000000000000000000000000..4a86de324a43a322e1149d879d41e222959f9a50 Binary files /dev/null and b/shared/package-files/78/78e34ba4756971b90ac747dcb96ec96f3837fdcad5efda30a7eefdc3a5bd65be/blob differ diff --git a/shared/package-files/78/78e374e148884cf6475a49ed4626190c1a6c26fae743cf2783aa7180c72c5e90/blob b/shared/package-files/78/78e374e148884cf6475a49ed4626190c1a6c26fae743cf2783aa7180c72c5e90/blob new file mode 100644 index 0000000000000000000000000000000000000000..158d125b743c6ff90e4cfe42ed925176e3df1dc2 --- /dev/null +++ b/shared/package-files/78/78e374e148884cf6475a49ed4626190c1a6c26fae743cf2783aa7180c72c5e90/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor +inline at::Tensor clone(const at::Tensor & self, c10::optional memory_format=c10::nullopt) { + return at::_ops::clone::call(self, memory_format); +} + +// aten::clone.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clone_out(at::Tensor & out, const at::Tensor & self, c10::optional memory_format=c10::nullopt) { + return at::_ops::clone_out::call(self, memory_format, out); +} +// aten::clone.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & clone_outf(const at::Tensor & self, c10::optional memory_format, at::Tensor & out) { + return at::_ops::clone_out::call(self, memory_format, out); +} + +} diff --git a/shared/package-files/78/78e4282500468c0a8572cc1d3418a91e818c18180b8b02c5348cd3b99e574a42/blob b/shared/package-files/78/78e4282500468c0a8572cc1d3418a91e818c18180b8b02c5348cd3b99e574a42/blob new file mode 100644 index 0000000000000000000000000000000000000000..3c6517a872b76df61cfd2e1d11e5164b809f3e90 --- /dev/null +++ b/shared/package-files/78/78e4282500468c0a8572cc1d3418a91e818c18180b8b02c5348cd3b99e574a42/blob @@ -0,0 +1,907 @@ +import json + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + Series, + json_normalize, +) +import pandas._testing as tm + +from pandas.io.json._normalize import nested_to_record + + +@pytest.fixture +def deep_nested(): + # deeply nested data + return [ + { + "country": "USA", + "states": [ + { + "name": "California", + "cities": [ + {"name": "San Francisco", "pop": 12345}, + {"name": "Los Angeles", "pop": 12346}, + ], + }, + { + "name": "Ohio", + "cities": [ + {"name": "Columbus", "pop": 1234}, + {"name": "Cleveland", "pop": 1236}, + ], + }, + ], + }, + { + "country": "Germany", + "states": [ + {"name": "Bayern", "cities": [{"name": "Munich", "pop": 12347}]}, + { + "name": "Nordrhein-Westfalen", + "cities": [ + {"name": "Duesseldorf", "pop": 1238}, + {"name": "Koeln", "pop": 1239}, + ], + }, + ], + }, + ] + + +@pytest.fixture +def state_data(): + return [ + { + "counties": [ + {"name": "Dade", "population": 12345}, + {"name": "Broward", "population": 40000}, + {"name": "Palm Beach", "population": 60000}, + ], + "info": {"governor": "Rick Scott"}, + "shortname": "FL", + "state": "Florida", + }, + { + "counties": [ + {"name": "Summit", "population": 1234}, + {"name": "Cuyahoga", "population": 1337}, + ], + "info": {"governor": "John Kasich"}, + "shortname": "OH", + "state": "Ohio", + }, + ] + + +@pytest.fixture +def author_missing_data(): + return [ + {"info": None}, + { + "info": {"created_at": "11/08/1993", "last_updated": "26/05/2012"}, + "author_name": {"first": "Jane", "last_name": "Doe"}, + }, + ] + + +@pytest.fixture +def missing_metadata(): + return [ + { + "name": "Alice", + "addresses": [ + { + "number": 9562, + "street": "Morris St.", + "city": "Massillon", + "state": "OH", + "zip": 44646, + } + ], + "previous_residences": {"cities": [{"city_name": "Foo York City"}]}, + }, + { + "addresses": [ + { + "number": 8449, + "street": "Spring St.", + "city": "Elizabethton", + "state": "TN", + "zip": 37643, + } + ], + "previous_residences": {"cities": [{"city_name": "Barmingham"}]}, + }, + ] + + +@pytest.fixture +def max_level_test_input_data(): + """ + input data to test json_normalize with max_level param + """ + return [ + { + "CreatedBy": {"Name": "User001"}, + "Lookup": { + "TextField": "Some text", + "UserField": {"Id": "ID001", "Name": "Name001"}, + }, + "Image": {"a": "b"}, + } + ] + + +class TestJSONNormalize: + def test_simple_records(self): + recs = [ + {"a": 1, "b": 2, "c": 3}, + {"a": 4, "b": 5, "c": 6}, + {"a": 7, "b": 8, "c": 9}, + {"a": 10, "b": 11, "c": 12}, + ] + + result = json_normalize(recs) + expected = DataFrame(recs) + + tm.assert_frame_equal(result, expected) + + def test_simple_normalize(self, state_data): + result = json_normalize(state_data[0], "counties") + expected = DataFrame(state_data[0]["counties"]) + tm.assert_frame_equal(result, expected) + + result = json_normalize(state_data, "counties") + + expected = [] + for rec in state_data: + expected.extend(rec["counties"]) + expected = DataFrame(expected) + + tm.assert_frame_equal(result, expected) + + result = json_normalize(state_data, "counties", meta="state") + expected["state"] = np.array(["Florida", "Ohio"]).repeat([3, 2]) + + tm.assert_frame_equal(result, expected) + + def test_fields_list_type_normalize(self): + parse_metadata_fields_list_type = [ + {"values": [1, 2, 3], "metadata": {"listdata": [1, 2]}} + ] + result = json_normalize( + parse_metadata_fields_list_type, + record_path=["values"], + meta=[["metadata", "listdata"]], + ) + expected = DataFrame( + {0: [1, 2, 3], "metadata.listdata": [[1, 2], [1, 2], [1, 2]]} + ) + tm.assert_frame_equal(result, expected) + + def test_empty_array(self): + result = json_normalize([]) + expected = DataFrame() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "data, record_path, exception_type", + [ + ([{"a": 0}, {"a": 1}], None, None), + ({"a": [{"a": 0}, {"a": 1}]}, "a", None), + ('{"a": [{"a": 0}, {"a": 1}]}', None, NotImplementedError), + (None, None, NotImplementedError), + ], + ) + def test_accepted_input(self, data, record_path, exception_type): + if exception_type is not None: + with pytest.raises(exception_type, match=""): + json_normalize(data, record_path=record_path) + else: + result = json_normalize(data, record_path=record_path) + expected = DataFrame([0, 1], columns=["a"]) + tm.assert_frame_equal(result, expected) + + def test_simple_normalize_with_separator(self, deep_nested): + # GH 14883 + result = json_normalize({"A": {"A": 1, "B": 2}}) + expected = DataFrame([[1, 2]], columns=["A.A", "A.B"]) + tm.assert_frame_equal(result.reindex_like(expected), expected) + + result = json_normalize({"A": {"A": 1, "B": 2}}, sep="_") + expected = DataFrame([[1, 2]], columns=["A_A", "A_B"]) + tm.assert_frame_equal(result.reindex_like(expected), expected) + + result = json_normalize({"A": {"A": 1, "B": 2}}, sep="\u03c3") + expected = DataFrame([[1, 2]], columns=["A\u03c3A", "A\u03c3B"]) + tm.assert_frame_equal(result.reindex_like(expected), expected) + + result = json_normalize( + deep_nested, + ["states", "cities"], + meta=["country", ["states", "name"]], + sep="_", + ) + expected = Index(["name", "pop", "country", "states_name"]).sort_values() + assert result.columns.sort_values().equals(expected) + + def test_normalize_with_multichar_separator(self): + # GH #43831 + data = {"a": [1, 2], "b": {"b_1": 2, "b_2": (3, 4)}} + result = json_normalize(data, sep="__") + expected = DataFrame([[[1, 2], 2, (3, 4)]], columns=["a", "b__b_1", "b__b_2"]) + tm.assert_frame_equal(result, expected) + + def test_value_array_record_prefix(self): + # GH 21536 + result = json_normalize({"A": [1, 2]}, "A", record_prefix="Prefix.") + expected = DataFrame([[1], [2]], columns=["Prefix.0"]) + tm.assert_frame_equal(result, expected) + + def test_nested_object_record_path(self): + # GH 22706 + data = { + "state": "Florida", + "info": { + "governor": "Rick Scott", + "counties": [ + {"name": "Dade", "population": 12345}, + {"name": "Broward", "population": 40000}, + {"name": "Palm Beach", "population": 60000}, + ], + }, + } + result = json_normalize(data, record_path=["info", "counties"]) + expected = DataFrame( + [["Dade", 12345], ["Broward", 40000], ["Palm Beach", 60000]], + columns=["name", "population"], + ) + tm.assert_frame_equal(result, expected) + + def test_more_deeply_nested(self, deep_nested): + result = json_normalize( + deep_nested, ["states", "cities"], meta=["country", ["states", "name"]] + ) + ex_data = { + "country": ["USA"] * 4 + ["Germany"] * 3, + "states.name": [ + "California", + "California", + "Ohio", + "Ohio", + "Bayern", + "Nordrhein-Westfalen", + "Nordrhein-Westfalen", + ], + "name": [ + "San Francisco", + "Los Angeles", + "Columbus", + "Cleveland", + "Munich", + "Duesseldorf", + "Koeln", + ], + "pop": [12345, 12346, 1234, 1236, 12347, 1238, 1239], + } + + expected = DataFrame(ex_data, columns=result.columns) + tm.assert_frame_equal(result, expected) + + def test_shallow_nested(self): + data = [ + { + "state": "Florida", + "shortname": "FL", + "info": {"governor": "Rick Scott"}, + "counties": [ + {"name": "Dade", "population": 12345}, + {"name": "Broward", "population": 40000}, + {"name": "Palm Beach", "population": 60000}, + ], + }, + { + "state": "Ohio", + "shortname": "OH", + "info": {"governor": "John Kasich"}, + "counties": [ + {"name": "Summit", "population": 1234}, + {"name": "Cuyahoga", "population": 1337}, + ], + }, + ] + + result = json_normalize( + data, "counties", ["state", "shortname", ["info", "governor"]] + ) + ex_data = { + "name": ["Dade", "Broward", "Palm Beach", "Summit", "Cuyahoga"], + "state": ["Florida"] * 3 + ["Ohio"] * 2, + "shortname": ["FL", "FL", "FL", "OH", "OH"], + "info.governor": ["Rick Scott"] * 3 + ["John Kasich"] * 2, + "population": [12345, 40000, 60000, 1234, 1337], + } + expected = DataFrame(ex_data, columns=result.columns) + tm.assert_frame_equal(result, expected) + + def test_nested_meta_path_with_nested_record_path(self, state_data): + # GH 27220 + result = json_normalize( + data=state_data, + record_path=["counties"], + meta=["state", "shortname", ["info", "governor"]], + errors="ignore", + ) + + ex_data = { + "name": ["Dade", "Broward", "Palm Beach", "Summit", "Cuyahoga"], + "population": [12345, 40000, 60000, 1234, 1337], + "state": ["Florida"] * 3 + ["Ohio"] * 2, + "shortname": ["FL"] * 3 + ["OH"] * 2, + "info.governor": ["Rick Scott"] * 3 + ["John Kasich"] * 2, + } + + expected = DataFrame(ex_data) + tm.assert_frame_equal(result, expected) + + def test_meta_name_conflict(self): + data = [ + { + "foo": "hello", + "bar": "there", + "data": [ + {"foo": "something", "bar": "else"}, + {"foo": "something2", "bar": "else2"}, + ], + } + ] + + msg = r"Conflicting metadata name (foo|bar), need distinguishing prefix" + with pytest.raises(ValueError, match=msg): + json_normalize(data, "data", meta=["foo", "bar"]) + + result = json_normalize(data, "data", meta=["foo", "bar"], meta_prefix="meta") + + for val in ["metafoo", "metabar", "foo", "bar"]: + assert val in result + + def test_meta_parameter_not_modified(self): + # GH 18610 + data = [ + { + "foo": "hello", + "bar": "there", + "data": [ + {"foo": "something", "bar": "else"}, + {"foo": "something2", "bar": "else2"}, + ], + } + ] + + COLUMNS = ["foo", "bar"] + result = json_normalize(data, "data", meta=COLUMNS, meta_prefix="meta") + + assert COLUMNS == ["foo", "bar"] + for val in ["metafoo", "metabar", "foo", "bar"]: + assert val in result + + def test_record_prefix(self, state_data): + result = json_normalize(state_data[0], "counties") + expected = DataFrame(state_data[0]["counties"]) + tm.assert_frame_equal(result, expected) + + result = json_normalize( + state_data, "counties", meta="state", record_prefix="county_" + ) + + expected = [] + for rec in state_data: + expected.extend(rec["counties"]) + expected = DataFrame(expected) + expected = expected.rename(columns=lambda x: "county_" + x) + expected["state"] = np.array(["Florida", "Ohio"]).repeat([3, 2]) + + tm.assert_frame_equal(result, expected) + + def test_non_ascii_key(self): + testjson = ( + b'[{"\xc3\x9cnic\xc3\xb8de":0,"sub":{"A":1, "B":2}},' + b'{"\xc3\x9cnic\xc3\xb8de":1,"sub":{"A":3, "B":4}}]' + ).decode("utf8") + + testdata = { + b"\xc3\x9cnic\xc3\xb8de".decode("utf8"): [0, 1], + "sub.A": [1, 3], + "sub.B": [2, 4], + } + expected = DataFrame(testdata) + + result = json_normalize(json.loads(testjson)) + tm.assert_frame_equal(result, expected) + + def test_missing_field(self, author_missing_data): + # GH20030: + result = json_normalize(author_missing_data) + ex_data = [ + { + "info": np.nan, + "info.created_at": np.nan, + "info.last_updated": np.nan, + "author_name.first": np.nan, + "author_name.last_name": np.nan, + }, + { + "info": None, + "info.created_at": "11/08/1993", + "info.last_updated": "26/05/2012", + "author_name.first": "Jane", + "author_name.last_name": "Doe", + }, + ] + expected = DataFrame(ex_data) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "max_level,expected", + [ + ( + 0, + [ + { + "TextField": "Some text", + "UserField": {"Id": "ID001", "Name": "Name001"}, + "CreatedBy": {"Name": "User001"}, + "Image": {"a": "b"}, + }, + { + "TextField": "Some text", + "UserField": {"Id": "ID001", "Name": "Name001"}, + "CreatedBy": {"Name": "User001"}, + "Image": {"a": "b"}, + }, + ], + ), + ( + 1, + [ + { + "TextField": "Some text", + "UserField.Id": "ID001", + "UserField.Name": "Name001", + "CreatedBy": {"Name": "User001"}, + "Image": {"a": "b"}, + }, + { + "TextField": "Some text", + "UserField.Id": "ID001", + "UserField.Name": "Name001", + "CreatedBy": {"Name": "User001"}, + "Image": {"a": "b"}, + }, + ], + ), + ], + ) + def test_max_level_with_records_path(self, max_level, expected): + # GH23843: Enhanced JSON normalize + test_input = [ + { + "CreatedBy": {"Name": "User001"}, + "Lookup": [ + { + "TextField": "Some text", + "UserField": {"Id": "ID001", "Name": "Name001"}, + }, + { + "TextField": "Some text", + "UserField": {"Id": "ID001", "Name": "Name001"}, + }, + ], + "Image": {"a": "b"}, + "tags": [ + {"foo": "something", "bar": "else"}, + {"foo": "something2", "bar": "else2"}, + ], + } + ] + + result = json_normalize( + test_input, + record_path=["Lookup"], + meta=[["CreatedBy"], ["Image"]], + max_level=max_level, + ) + expected_df = DataFrame(data=expected, columns=result.columns.values) + tm.assert_equal(expected_df, result) + + def test_nested_flattening_consistent(self): + # see gh-21537 + df1 = json_normalize([{"A": {"B": 1}}]) + df2 = json_normalize({"dummy": [{"A": {"B": 1}}]}, "dummy") + + # They should be the same. + tm.assert_frame_equal(df1, df2) + + def test_nonetype_record_path(self, nulls_fixture): + # see gh-30148 + # should not raise TypeError + result = json_normalize( + [ + {"state": "Texas", "info": nulls_fixture}, + {"state": "Florida", "info": [{"i": 2}]}, + ], + record_path=["info"], + ) + expected = DataFrame({"i": 2}, index=[0]) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("value", ["false", "true", "{}", "1", '"text"']) + def test_non_list_record_path_errors(self, value): + # see gh-30148, GH 26284 + parsed_value = json.loads(value) + test_input = {"state": "Texas", "info": parsed_value} + test_path = "info" + msg = ( + f"{test_input} has non list value {parsed_value} for path {test_path}. " + "Must be list or null." + ) + with pytest.raises(TypeError, match=msg): + json_normalize([test_input], record_path=[test_path]) + + def test_meta_non_iterable(self): + # GH 31507 + data = """[{"id": 99, "data": [{"one": 1, "two": 2}]}]""" + + result = json_normalize(json.loads(data), record_path=["data"], meta=["id"]) + expected = DataFrame( + {"one": [1], "two": [2], "id": np.array([99], dtype=object)} + ) + tm.assert_frame_equal(result, expected) + + def test_generator(self, state_data): + # GH35923 Fix pd.json_normalize to not skip the first element of a + # generator input + def generator_data(): + yield from state_data[0]["counties"] + + result = json_normalize(generator_data()) + expected = DataFrame(state_data[0]["counties"]) + + tm.assert_frame_equal(result, expected) + + def test_top_column_with_leading_underscore(self): + # 49861 + data = {"_id": {"a1": 10, "l2": {"l3": 0}}, "gg": 4} + result = json_normalize(data, sep="_") + expected = DataFrame([[4, 10, 0]], columns=["gg", "_id_a1", "_id_l2_l3"]) + + tm.assert_frame_equal(result, expected) + + +class TestNestedToRecord: + def test_flat_stays_flat(self): + recs = [{"flat1": 1, "flat2": 2}, {"flat3": 3, "flat2": 4}] + result = nested_to_record(recs) + expected = recs + assert result == expected + + def test_one_level_deep_flattens(self): + data = {"flat1": 1, "dict1": {"c": 1, "d": 2}} + + result = nested_to_record(data) + expected = {"dict1.c": 1, "dict1.d": 2, "flat1": 1} + + assert result == expected + + def test_nested_flattens(self): + data = { + "flat1": 1, + "dict1": {"c": 1, "d": 2}, + "nested": {"e": {"c": 1, "d": 2}, "d": 2}, + } + + result = nested_to_record(data) + expected = { + "dict1.c": 1, + "dict1.d": 2, + "flat1": 1, + "nested.d": 2, + "nested.e.c": 1, + "nested.e.d": 2, + } + + assert result == expected + + def test_json_normalize_errors(self, missing_metadata): + # GH14583: + # If meta keys are not always present a new option to set + # errors='ignore' has been implemented + + msg = ( + "Key 'name' not found. To replace missing values of " + "'name' with np.nan, pass in errors='ignore'" + ) + with pytest.raises(KeyError, match=msg): + json_normalize( + data=missing_metadata, + record_path="addresses", + meta="name", + errors="raise", + ) + + def test_missing_meta(self, missing_metadata): + # GH25468 + # If metadata is nullable with errors set to ignore, the null values + # should be numpy.nan values + result = json_normalize( + data=missing_metadata, record_path="addresses", meta="name", errors="ignore" + ) + ex_data = [ + [9562, "Morris St.", "Massillon", "OH", 44646, "Alice"], + [8449, "Spring St.", "Elizabethton", "TN", 37643, np.nan], + ] + columns = ["number", "street", "city", "state", "zip", "name"] + expected = DataFrame(ex_data, columns=columns) + tm.assert_frame_equal(result, expected) + + def test_missing_nested_meta(self): + # GH44312 + # If errors="ignore" and nested metadata is null, we should return nan + data = {"meta": "foo", "nested_meta": None, "value": [{"rec": 1}, {"rec": 2}]} + result = json_normalize( + data, + record_path="value", + meta=["meta", ["nested_meta", "leaf"]], + errors="ignore", + ) + ex_data = [[1, "foo", np.nan], [2, "foo", np.nan]] + columns = ["rec", "meta", "nested_meta.leaf"] + expected = DataFrame(ex_data, columns=columns).astype( + {"nested_meta.leaf": object} + ) + tm.assert_frame_equal(result, expected) + + # If errors="raise" and nested metadata is null, we should raise with the + # key of the first missing level + with pytest.raises(KeyError, match="'leaf' not found"): + json_normalize( + data, + record_path="value", + meta=["meta", ["nested_meta", "leaf"]], + errors="raise", + ) + + def test_missing_meta_multilevel_record_path_errors_raise(self, missing_metadata): + # GH41876 + # Ensure errors='raise' works as intended even when a record_path of length + # greater than one is passed in + msg = ( + "Key 'name' not found. To replace missing values of " + "'name' with np.nan, pass in errors='ignore'" + ) + with pytest.raises(KeyError, match=msg): + json_normalize( + data=missing_metadata, + record_path=["previous_residences", "cities"], + meta="name", + errors="raise", + ) + + def test_missing_meta_multilevel_record_path_errors_ignore(self, missing_metadata): + # GH41876 + # Ensure errors='ignore' works as intended even when a record_path of length + # greater than one is passed in + result = json_normalize( + data=missing_metadata, + record_path=["previous_residences", "cities"], + meta="name", + errors="ignore", + ) + ex_data = [ + ["Foo York City", "Alice"], + ["Barmingham", np.nan], + ] + columns = ["city_name", "name"] + expected = DataFrame(ex_data, columns=columns) + tm.assert_frame_equal(result, expected) + + def test_donot_drop_nonevalues(self): + # GH21356 + data = [ + {"info": None, "author_name": {"first": "Smith", "last_name": "Appleseed"}}, + { + "info": {"created_at": "11/08/1993", "last_updated": "26/05/2012"}, + "author_name": {"first": "Jane", "last_name": "Doe"}, + }, + ] + result = nested_to_record(data) + expected = [ + { + "info": None, + "author_name.first": "Smith", + "author_name.last_name": "Appleseed", + }, + { + "author_name.first": "Jane", + "author_name.last_name": "Doe", + "info.created_at": "11/08/1993", + "info.last_updated": "26/05/2012", + }, + ] + + assert result == expected + + def test_nonetype_top_level_bottom_level(self): + # GH21158: If inner level json has a key with a null value + # make sure it does not do a new_d.pop twice and except + data = { + "id": None, + "location": { + "country": { + "state": { + "id": None, + "town.info": { + "id": None, + "region": None, + "x": 49.151580810546875, + "y": -33.148521423339844, + "z": 27.572303771972656, + }, + } + } + }, + } + result = nested_to_record(data) + expected = { + "id": None, + "location.country.state.id": None, + "location.country.state.town.info.id": None, + "location.country.state.town.info.region": None, + "location.country.state.town.info.x": 49.151580810546875, + "location.country.state.town.info.y": -33.148521423339844, + "location.country.state.town.info.z": 27.572303771972656, + } + assert result == expected + + def test_nonetype_multiple_levels(self): + # GH21158: If inner level json has a key with a null value + # make sure it does not do a new_d.pop twice and except + data = { + "id": None, + "location": { + "id": None, + "country": { + "id": None, + "state": { + "id": None, + "town.info": { + "region": None, + "x": 49.151580810546875, + "y": -33.148521423339844, + "z": 27.572303771972656, + }, + }, + }, + }, + } + result = nested_to_record(data) + expected = { + "id": None, + "location.id": None, + "location.country.id": None, + "location.country.state.id": None, + "location.country.state.town.info.region": None, + "location.country.state.town.info.x": 49.151580810546875, + "location.country.state.town.info.y": -33.148521423339844, + "location.country.state.town.info.z": 27.572303771972656, + } + assert result == expected + + @pytest.mark.parametrize( + "max_level, expected", + [ + ( + None, + [ + { + "CreatedBy.Name": "User001", + "Lookup.TextField": "Some text", + "Lookup.UserField.Id": "ID001", + "Lookup.UserField.Name": "Name001", + "Image.a": "b", + } + ], + ), + ( + 0, + [ + { + "CreatedBy": {"Name": "User001"}, + "Lookup": { + "TextField": "Some text", + "UserField": {"Id": "ID001", "Name": "Name001"}, + }, + "Image": {"a": "b"}, + } + ], + ), + ( + 1, + [ + { + "CreatedBy.Name": "User001", + "Lookup.TextField": "Some text", + "Lookup.UserField": {"Id": "ID001", "Name": "Name001"}, + "Image.a": "b", + } + ], + ), + ], + ) + def test_with_max_level(self, max_level, expected, max_level_test_input_data): + # GH23843: Enhanced JSON normalize + output = nested_to_record(max_level_test_input_data, max_level=max_level) + assert output == expected + + def test_with_large_max_level(self): + # GH23843: Enhanced JSON normalize + max_level = 100 + input_data = [ + { + "CreatedBy": { + "user": { + "name": {"firstname": "Leo", "LastName": "Thomson"}, + "family_tree": { + "father": { + "name": "Father001", + "father": { + "Name": "Father002", + "father": { + "name": "Father003", + "father": {"Name": "Father004"}, + }, + }, + } + }, + } + } + } + ] + expected = [ + { + "CreatedBy.user.name.firstname": "Leo", + "CreatedBy.user.name.LastName": "Thomson", + "CreatedBy.user.family_tree.father.name": "Father001", + "CreatedBy.user.family_tree.father.father.Name": "Father002", + "CreatedBy.user.family_tree.father.father.father.name": "Father003", + "CreatedBy.user.family_tree.father.father.father.father.Name": "Father004", # noqa: E501 + } + ] + output = nested_to_record(input_data, max_level=max_level) + assert output == expected + + def test_series_non_zero_index(self): + # GH 19020 + data = { + 0: {"id": 1, "name": "Foo", "elements": {"a": 1}}, + 1: {"id": 2, "name": "Bar", "elements": {"b": 2}}, + 2: {"id": 3, "name": "Baz", "elements": {"c": 3}}, + } + s = Series(data) + s.index = [1, 2, 3] + result = json_normalize(s) + expected = DataFrame( + { + "id": [1, 2, 3], + "name": ["Foo", "Bar", "Baz"], + "elements.a": [1.0, np.nan, np.nan], + "elements.b": [np.nan, 2.0, np.nan], + "elements.c": [np.nan, np.nan, 3.0], + } + ) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/78/78e5ed1d6326ee900335da9e69c4b67a95bae558613170f3f36fe71cbe036553/blob b/shared/package-files/78/78e5ed1d6326ee900335da9e69c4b67a95bae558613170f3f36fe71cbe036553/blob new file mode 100644 index 0000000000000000000000000000000000000000..a9b14bc9a5c965f866641eee21e719374da270b3 --- /dev/null +++ b/shared/package-files/78/78e5ed1d6326ee900335da9e69c4b67a95bae558613170f3f36fe71cbe036553/blob @@ -0,0 +1,203 @@ +"","dfb.1_","dfb.ggdp","dfb.lint","dffit","cov.r","cook.d","hat" +"1",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"2",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"3",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"4",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"5",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE +"6",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"7",FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,FALSE +"8",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"9",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"10",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"11",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"12",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"13",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"14",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"15",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"16",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"17",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"18",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"19",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"20",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"21",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"22",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"23",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"24",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"25",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"26",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"27",FALSE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE +"28",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"29",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"30",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"31",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"32",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"33",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"34",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"35",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"36",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"37",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"38",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"39",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"40",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"41",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"42",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"43",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"44",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"45",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"46",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"47",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"48",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"49",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"50",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"51",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"52",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"53",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"54",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"55",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"56",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"57",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"58",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"59",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"60",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE +"61",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"62",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE +"63",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,TRUE +"64",FALSE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE +"65",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"66",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"67",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"68",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"69",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"70",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"71",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"72",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"73",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE +"74",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"75",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"76",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"77",FALSE,FALSE,FALSE,TRUE,TRUE,FALSE,TRUE +"78",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"79",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"80",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"81",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"82",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"83",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"84",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"85",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE +"86",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"87",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"88",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"89",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"90",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"91",FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,TRUE +"92",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE +"93",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE +"94",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"95",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE +"96",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE +"97",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"98",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"99",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"100",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"101",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"102",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"103",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"104",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"105",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"106",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"107",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"108",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"109",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE +"110",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"111",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"112",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"113",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"114",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"115",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"116",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"117",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"118",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"119",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"120",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"121",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"122",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"123",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"124",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"125",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"126",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"127",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"128",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"129",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"130",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"131",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"132",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"133",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"134",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"135",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"136",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"137",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"138",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"139",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"140",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"141",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"142",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"143",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"144",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"145",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"146",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"147",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"148",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"149",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"150",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"151",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"152",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"153",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"154",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"155",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"156",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"157",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"158",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"159",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"160",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"161",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"162",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"163",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"164",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"165",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"166",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"167",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"168",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"169",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"170",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"171",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"172",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"173",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"174",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"175",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"176",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"177",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"178",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"179",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"180",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"181",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"182",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"183",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"184",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"185",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"186",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"187",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"188",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"189",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"190",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"191",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"192",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"193",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"194",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"195",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"196",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"197",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"198",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE +"199",FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE +"200",FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,TRUE +"201",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE +"202",FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE diff --git a/shared/package-files/78/78e60cd0b8f28694f30195482c33d76908d846b0d15278deb7332aa22ba8e412/blob b/shared/package-files/78/78e60cd0b8f28694f30195482c33d76908d846b0d15278deb7332aa22ba8e412/blob new file mode 100644 index 0000000000000000000000000000000000000000..94f954567b1c4a33c601b6bf3688ec08b695cbc0 --- /dev/null +++ b/shared/package-files/78/78e60cd0b8f28694f30195482c33d76908d846b0d15278deb7332aa22ba8e412/blob @@ -0,0 +1,24 @@ +All contributions towards Jedi are MIT licensed. + +------------------------------------------------------------------------------- +The MIT License (MIT) + +Copyright (c) <2013> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/shared/package-files/78/78e994bb8ab48a11936d8a4295ea029d8b6fc21d530421194108cb78969430d0/blob b/shared/package-files/78/78e994bb8ab48a11936d8a4295ea029d8b6fc21d530421194108cb78969430d0/blob new file mode 100644 index 0000000000000000000000000000000000000000..cb44f91f34dec80c090d3ce3fc9a2dbd4578bb57 --- /dev/null +++ b/shared/package-files/78/78e994bb8ab48a11936d8a4295ea029d8b6fc21d530421194108cb78969430d0/blob @@ -0,0 +1,20 @@ +import pytest + +from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike + + +@pytest.mark.parametrize("datum1", [1, 2.0, "3", (4, 5), [6, 7], None]) +@pytest.mark.parametrize("datum2", [8, 9.0, "10", (11, 12), [13, 14], None]) +def test_cast_1d_array(datum1, datum2): + data = [datum1, datum2] + result = construct_1d_object_array_from_listlike(data) + + # Direct comparison fails: https://github.com/numpy/numpy/issues/10218 + assert result.dtype == "object" + assert list(result) == data + + +@pytest.mark.parametrize("val", [1, 2.0, None]) +def test_cast_1d_array_invalid_scalar(val): + with pytest.raises(TypeError, match="has no len()"): + construct_1d_object_array_from_listlike(val) diff --git a/shared/package-files/78/78ea0e147eeb70fcca5dde2bc493e4465e8b2fbb4cce9bee323424d5a7cd1e1f/blob b/shared/package-files/78/78ea0e147eeb70fcca5dde2bc493e4465e8b2fbb4cce9bee323424d5a7cd1e1f/blob new file mode 100644 index 0000000000000000000000000000000000000000..27a25ad5a4c48ea81bd514ccc8556b13cba8329a --- /dev/null +++ b/shared/package-files/78/78ea0e147eeb70fcca5dde2bc493e4465e8b2fbb4cce9bee323424d5a7cd1e1f/blob @@ -0,0 +1,38 @@ +from .exceptions import ( + GrammarError, + LarkError, + LexError, + ParseError, + UnexpectedCharacters, + UnexpectedEOF, + UnexpectedInput, + UnexpectedToken, +) +from .lark import Lark +from .lexer import Token +from .tree import ParseTree, Tree +from .utils import logger +from .visitors import Discard, Transformer, Transformer_NonRecursive, Visitor, v_args + +__version__: str = "1.1.9" + +__all__ = ( + "GrammarError", + "LarkError", + "LexError", + "ParseError", + "UnexpectedCharacters", + "UnexpectedEOF", + "UnexpectedInput", + "UnexpectedToken", + "Lark", + "Token", + "ParseTree", + "Tree", + "logger", + "Discard", + "Transformer", + "Transformer_NonRecursive", + "Visitor", + "v_args", +) diff --git a/shared/package-files/78/78eea04a7cf86787b8612187b4b17d96d27ab0ba91d08c17a96274ec7a5fc37e/blob b/shared/package-files/78/78eea04a7cf86787b8612187b4b17d96d27ab0ba91d08c17a96274ec7a5fc37e/blob new file mode 100644 index 0000000000000000000000000000000000000000..dfbb349007a231025ec493921d65c52589221553 --- /dev/null +++ b/shared/package-files/78/78eea04a7cf86787b8612187b4b17d96d27ab0ba91d08c17a96274ec7a5fc37e/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78eea04a7cf86787b8612187b4b17d96d27ab0ba91d08c17a96274ec7a5fc37e +size 343968 diff --git a/shared/package-files/78/78efab6b47bcbd3dbb33f8a42fe4b5f64aa529193da80c51ba1295842e604c07/blob b/shared/package-files/78/78efab6b47bcbd3dbb33f8a42fe4b5f64aa529193da80c51ba1295842e604c07/blob new file mode 100644 index 0000000000000000000000000000000000000000..0441115d0719dd7c5b5b0262d95330a5ae76b534 --- /dev/null +++ b/shared/package-files/78/78efab6b47bcbd3dbb33f8a42fe4b5f64aa529193da80c51ba1295842e604c07/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor & geometric_(at::Tensor & self, double p, c10::optional generator=c10::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/78/78f240316b9cb511ef2a1748164653f4200611d1c1671c7e06fecf5116bc341e/blob b/shared/package-files/78/78f240316b9cb511ef2a1748164653f4200611d1c1671c7e06fecf5116bc341e/blob new file mode 100644 index 0000000000000000000000000000000000000000..07e8f951ef20fcdee8850b5bb47f3468e9a0b2e2 --- /dev/null +++ b/shared/package-files/78/78f240316b9cb511ef2a1748164653f4200611d1c1671c7e06fecf5116bc341e/blob @@ -0,0 +1,197 @@ +""" + pygments.style + ~~~~~~~~~~~~~~ + + Basic style object. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.token import Token, STANDARD_TYPES + +# Default mapping of ansixxx to RGB colors. +_ansimap = { + # dark + 'ansiblack': '000000', + 'ansired': '7f0000', + 'ansigreen': '007f00', + 'ansiyellow': '7f7fe0', + 'ansiblue': '00007f', + 'ansimagenta': '7f007f', + 'ansicyan': '007f7f', + 'ansigray': 'e5e5e5', + # normal + 'ansibrightblack': '555555', + 'ansibrightred': 'ff0000', + 'ansibrightgreen': '00ff00', + 'ansibrightyellow': 'ffff00', + 'ansibrightblue': '0000ff', + 'ansibrightmagenta': 'ff00ff', + 'ansibrightcyan': '00ffff', + 'ansiwhite': 'ffffff', +} +# mapping of deprecated #ansixxx colors to new color names +_deprecated_ansicolors = { + # dark + '#ansiblack': 'ansiblack', + '#ansidarkred': 'ansired', + '#ansidarkgreen': 'ansigreen', + '#ansibrown': 'ansiyellow', + '#ansidarkblue': 'ansiblue', + '#ansipurple': 'ansimagenta', + '#ansiteal': 'ansicyan', + '#ansilightgray': 'ansigray', + # normal + '#ansidarkgray': 'ansibrightblack', + '#ansired': 'ansibrightred', + '#ansigreen': 'ansibrightgreen', + '#ansiyellow': 'ansibrightyellow', + '#ansiblue': 'ansibrightblue', + '#ansifuchsia': 'ansibrightmagenta', + '#ansiturquoise': 'ansibrightcyan', + '#ansiwhite': 'ansiwhite', +} +ansicolors = set(_ansimap) + + +class StyleMeta(type): + + def __new__(mcs, name, bases, dct): + obj = type.__new__(mcs, name, bases, dct) + for token in STANDARD_TYPES: + if token not in obj.styles: + obj.styles[token] = '' + + def colorformat(text): + if text in ansicolors: + return text + if text[0:1] == '#': + col = text[1:] + if len(col) == 6: + return col + elif len(col) == 3: + return col[0] * 2 + col[1] * 2 + col[2] * 2 + elif text == '': + return '' + elif text.startswith('var') or text.startswith('calc'): + return text + assert False, "wrong color format %r" % text + + _styles = obj._styles = {} + + for ttype in obj.styles: + for token in ttype.split(): + if token in _styles: + continue + ndef = _styles.get(token.parent, None) + styledefs = obj.styles.get(token, '').split() + if not ndef or token is None: + ndef = ['', 0, 0, 0, '', '', 0, 0, 0] + elif 'noinherit' in styledefs and token is not Token: + ndef = _styles[Token][:] + else: + ndef = ndef[:] + _styles[token] = ndef + for styledef in obj.styles.get(token, '').split(): + if styledef == 'noinherit': + pass + elif styledef == 'bold': + ndef[1] = 1 + elif styledef == 'nobold': + ndef[1] = 0 + elif styledef == 'italic': + ndef[2] = 1 + elif styledef == 'noitalic': + ndef[2] = 0 + elif styledef == 'underline': + ndef[3] = 1 + elif styledef == 'nounderline': + ndef[3] = 0 + elif styledef[:3] == 'bg:': + ndef[4] = colorformat(styledef[3:]) + elif styledef[:7] == 'border:': + ndef[5] = colorformat(styledef[7:]) + elif styledef == 'roman': + ndef[6] = 1 + elif styledef == 'sans': + ndef[7] = 1 + elif styledef == 'mono': + ndef[8] = 1 + else: + ndef[0] = colorformat(styledef) + + return obj + + def style_for_token(cls, token): + t = cls._styles[token] + ansicolor = bgansicolor = None + color = t[0] + if color in _deprecated_ansicolors: + color = _deprecated_ansicolors[color] + if color in ansicolors: + ansicolor = color + color = _ansimap[color] + bgcolor = t[4] + if bgcolor in _deprecated_ansicolors: + bgcolor = _deprecated_ansicolors[bgcolor] + if bgcolor in ansicolors: + bgansicolor = bgcolor + bgcolor = _ansimap[bgcolor] + + return { + 'color': color or None, + 'bold': bool(t[1]), + 'italic': bool(t[2]), + 'underline': bool(t[3]), + 'bgcolor': bgcolor or None, + 'border': t[5] or None, + 'roman': bool(t[6]) or None, + 'sans': bool(t[7]) or None, + 'mono': bool(t[8]) or None, + 'ansicolor': ansicolor, + 'bgansicolor': bgansicolor, + } + + def list_styles(cls): + return list(cls) + + def styles_token(cls, ttype): + return ttype in cls._styles + + def __iter__(cls): + for token in cls._styles: + yield token, cls.style_for_token(token) + + def __len__(cls): + return len(cls._styles) + + +class Style(metaclass=StyleMeta): + + #: overall background color (``None`` means transparent) + background_color = '#ffffff' + + #: highlight background color + highlight_color = '#ffffcc' + + #: line number font color + line_number_color = 'inherit' + + #: line number background color + line_number_background_color = 'transparent' + + #: special line number font color + line_number_special_color = '#000000' + + #: special line number background color + line_number_special_background_color = '#ffffc0' + + #: Style definitions for individual token types. + styles = {} + + # Attribute for lexers defined within Pygments. If set + # to True, the style is not shown in the style gallery + # on the website. This is intended for language-specific + # styles. + web_style_gallery_exclude = False diff --git a/shared/package-files/78/78f66dca6d993df874125770a738059f6dc3a21a0758cf58c784395099145277/blob b/shared/package-files/78/78f66dca6d993df874125770a738059f6dc3a21a0758cf58c784395099145277/blob new file mode 100644 index 0000000000000000000000000000000000000000..cf621f34cc63735d7f7557f48146bb76467b8afc --- /dev/null +++ b/shared/package-files/78/78f66dca6d993df874125770a738059f6dc3a21a0758cf58c784395099145277/blob @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +// This file creates a fake allocator that just throws exceptions if +// it is actually used. + +// state passed to the allocator is the std::function called +// when the blob is release by ATen + +namespace at { + +static cpu_fixed_malloc(void*, ptrdiff_t) { + AT_ERROR("attempting to resize a tensor view of an external blob"); +} + +static cpu_fixed_realloc(void*, void*, ptrdiff_t) { + AT_ERROR("attempting to resize a tensor view of an external blob"); +} + +static cpu_fixed_free(void* state, void* allocation) { + auto on_release = static_cast*>(state); + (*on_release)(allocation); + delete on_release; +} + +static Allocator CPU_fixed_allocator = { + cpu_fixed_malloc, + cpu_fixed_realloc, + cpu_fixed_free}; + +} // namespace at diff --git a/shared/package-files/78/78f778a09c2d08e83b7b986379173345181ac475126acc659913cd1ccb4a4e81/blob b/shared/package-files/78/78f778a09c2d08e83b7b986379173345181ac475126acc659913cd1ccb4a4e81/blob new file mode 100644 index 0000000000000000000000000000000000000000..f631c19e4580ffe56abdc622554d1fc293bd8778 --- /dev/null +++ b/shared/package-files/78/78f778a09c2d08e83b7b986379173345181ac475126acc659913cd1ccb4a4e81/blob @@ -0,0 +1,88 @@ +Metadata-Version: 2.1 +Name: pip +Version: 23.3.1 +Summary: The PyPA recommended tool for installing Python packages. +Home-page: https://pip.pypa.io/ +Author: The pip developers +Author-email: distutils-sig@python.org +License: MIT +Project-URL: Documentation, https://pip.pypa.io +Project-URL: Source, https://github.com/pypa/pip +Project-URL: Changelog, https://pip.pypa.io/en/stable/news/ +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Topic :: Software Development :: Build Tools +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.7 +License-File: LICENSE.txt +License-File: AUTHORS.txt + +pip - The Python Package Installer +================================== + +.. image:: https://img.shields.io/pypi/v/pip.svg + :target: https://pypi.org/project/pip/ + :alt: PyPI + +.. image:: https://img.shields.io/pypi/pyversions/pip + :target: https://pypi.org/project/pip + :alt: PyPI - Python Version + +.. image:: https://readthedocs.org/projects/pip/badge/?version=latest + :target: https://pip.pypa.io/en/latest + :alt: Documentation + +pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes. + +Please take a look at our documentation for how to install and use pip: + +* `Installation`_ +* `Usage`_ + +We release updates regularly, with a new version every 3 months. Find more details in our documentation: + +* `Release notes`_ +* `Release process`_ + +If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms: + +* `Issue tracking`_ +* `Discourse channel`_ +* `User IRC`_ + +If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms: + +* `GitHub page`_ +* `Development documentation`_ +* `Development IRC`_ + +Code of Conduct +--------------- + +Everyone interacting in the pip project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _package installer: https://packaging.python.org/guides/tool-recommendations/ +.. _Python Package Index: https://pypi.org +.. _Installation: https://pip.pypa.io/en/stable/installation/ +.. _Usage: https://pip.pypa.io/en/stable/ +.. _Release notes: https://pip.pypa.io/en/stable/news.html +.. _Release process: https://pip.pypa.io/en/latest/development/release-process/ +.. _GitHub page: https://github.com/pypa/pip +.. _Development documentation: https://pip.pypa.io/en/latest/development +.. _Issue tracking: https://github.com/pypa/pip/issues +.. _Discourse channel: https://discuss.python.org/c/packaging +.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa +.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md diff --git a/shared/package-files/78/78f7b1a3f2f99201b524b592436bf42093ccff65d35c55dcb983854a40c74847/blob b/shared/package-files/78/78f7b1a3f2f99201b524b592436bf42093ccff65d35c55dcb983854a40c74847/blob new file mode 100644 index 0000000000000000000000000000000000000000..39e9a6fbc3f340798ec45473ef2cb981cabf45ae Binary files /dev/null and b/shared/package-files/78/78f7b1a3f2f99201b524b592436bf42093ccff65d35c55dcb983854a40c74847/blob differ diff --git a/shared/package-files/78/78faae0a7e29d0c692458850ef3681b76bc9a2bbc444d0376769421c1bf0722a/EXPERIMENTS.md b/shared/package-files/78/78faae0a7e29d0c692458850ef3681b76bc9a2bbc444d0376769421c1bf0722a/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..714db9af444a3319b79a520be92711c6db351f87 --- /dev/null +++ b/shared/package-files/78/78faae0a7e29d0c692458850ef3681b76bc9a2bbc444d0376769421c1bf0722a/EXPERIMENTS.md @@ -0,0 +1,2023 @@ +# Experiments + +All models initialize from random weights. Train labels are used for fitting; validation labels only for selection and error analysis. No test data or pretrained assets are available. Hardware: one H100 80 GB, 22 CPU allocation. Primary reported metrics are validation retrieval rates, not estimates of the external reference's test improvement. + +## E000 — starter plumbing smoke +- Hypothesis: the supplied train/publish/relocate/replay path works. +- Seed 0; one epoch; deterministic 4,096 train / 512 validation-loss rows. +- Retrieval: deterministic 128-spectrum sample, seed 0; query JSONL SHA256 `9fe86c73720456e94f6e454516b3f1768e289413f89b185df2dff3fa8f23f75a`. +- Checkpoint SHA256 `e1a27fbe5db99c9868650e830c65dc53ce420a4ab1362d7a166d833e5ae0c8f4`. +- Compute: training 10.358 s (one H100 allocated), relocated inference 18.373 s; no scientific benchmark claim from this subset. +- Metrics: `{"hit_rate_at_1": 0.0, "hit_rate_at_20": 0.0546875, "hit_rate_at_5": 0.015625, "mces_at_1": 30.61328125}`. All 128 rankings valid. +- Deliberately truncated ranking correctly invalidated with `ranking is not an exact candidate permutation`. +- Initial timing invocation failed because /usr/bin/time is unavailable; replaced with Python monotonic timing. Initial MCES invocation failed in GLACIER Python; evaluation uses the supplied system Python with myopic_mces. Neither failure changed fitting or inference. +- Selection: validation cosine loss for commissioning only. + +## E001 — all-condition inverse spectrum encoder +- Hypothesis: explicit fragment and neutral-loss bins retain more discriminating spectrum information than DeepSets mean pooling and provide a useful all-condition fallback. +- Changed factor: residual binned-spectrum architecture; 0.1 Da bins through 1500 Da, up to 128 peaks; Morgan4096 radius 2; cosine plus weighted BCE loss. Metadata uses precursor, adduct, instrument and observed/missing energy, never true formula. +- Seed 1; complete 194,119 training spectra; 50 epochs scheduled; one H100; AdamW, batch 512, width 1024, three residual blocks. +- Selection: full 19,429-query validation retrieval Hit@1 each epoch. Query JSONL SHA256 `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. +- No validation parameters fitted; candidate fingerprints are derived only from supplied structures. +- Completed 50 epochs in 160.517 s on one H100; max allocated GPU memory 5.631 GB. Selected epoch 2; Hit@1 0.09511555, Hit@5 0.21622317, Hit@20 0.39348397. Independent full replay: Hit@1 0.09393175, Hit@5 0.21606876, Hit@20 0.39389572; 19,429 complete rankings in 49.663 s. MCES running. +- Checkpoint SHA256 `bce84afa449b4952efaddd558af4c5439e8170976cbe56143a57abf98540f608`. Negative result: continued fitting overfit; final epoch Hit@1 0.08749807. Keep epoch 2. The initially logged retrieval used input-order tie resolution; replay uses candidate-ID ties. All 23 top-one discrepancies were identical-fingerprint ties. Validation cache now uses candidate-ID ties too; repeated evaluation exactly matches replay. No fitting or checkpoint change. Replay 95% molecule bootstrap interval: [0.08021314, 0.10881266], 3,185 molecule groups, 2,000 resamples. Paired smoke subset gain versus E000: +0.0703125; same 117 molecule groups. +- Packaging adapter initially imported the starter predict module because of sys.path precedence; fixed before any live publication. A premature replay invocation failed while the candidate package was not yet built; the complete replay subsequently passed. + + + +## E002 — clean synthetic augmentation +- Hypothesis: 435,076 synthetic molecular structures increase chemical coverage and reduce the severe train/validation generalization gap in E001. +- Changed factor: add only the supplied 2,333,485 sanitized ICEBERG simulations. Same formula-free input features; synthetic precursor masses derived from train-only simulation formula metadata. No simulated validation structures or pretrained assets. +- Seed 1; same architecture/loss as E001, random initialization; 40 epochs × 1,200 steps, batch 512, 25% experimental train / 75% clean synthetic sampling. Eight null/empty simulation spectra are excluded from fitting, leaving 2,333,477 usable rows. Initial preparation stopped on an empty payload; resumed from 1,283,584 complete rows, finished remaining rows in 44.062 s. Failed log and prior source retained. Full-validation selection uses fixed candidate-ID ties. Completed 40 epochs in 292.360 s on the one H100; max allocated CUDA memory 12.316 GB. Selected epoch 40, checkpoint SHA256 `bc0f0251108bb6c602c0ea44de892719c6b0d29c69ef26854911726c57c0faf2`. Independent replay: all 19,429 rankings valid in 86.279 s; Hit@1 0.2329507437, Hit@5 0.3749034948, Hit@20 0.5380101910. Replay exactly matches selection. Same full-validation query hash as E001. Paired molecule-bootstrap improvement over E001 +0.13901899 (95% CI [0.12379366,0.15556200], 3,185 molecule groups, 2,000 resamples). MCES running. +- Error analysis: H+ Hit@1 0.2745712 versus Na+ 0.1038632; missing energy 0.1650095; released GLACIER conditions 0.3017259 versus remaining conditions 0.1638989. Missing-condition and sodium transfer remain weak. + + +## E003 — GLACIER all-condition training (preparing) +- Hypothesis: the native forward model can learn spectra outside the published condition domain using explicit missing-energy and unknown-instrument embeddings already present in native code. +- Changed factor: broaden fragment-supervised fitting to all conditions. Preserve existing prepared targets, derive additional MAGMa targets only from corresponding training/validation structures and spectra. Engine reuse per SMILES reduces preparation time without using information across folds. Native architecture kept intact. +- The first 100-molecule/209-spectrum preparation smoke revealed missing sibling fragments when compared against native preparation. Invalidated those 209 derived rows, added native sibling expansion, and verified all 10 selected cases exactly (root canonical SMILES, raw target spectrum, fragment-mask set). Full preparation now running on 17,050 additional molecular groups / 104,473 spectra, retaining supplied targets unchanged. + +## E004 — fine-mass peak transformer +- Hypothesis: shared peak attention and fine mass-defect features reduce the information loss of 0.1 Da bins and improve unseen-structure retrieval. +- Changed factor: spectrum architecture/representation; same seed 1, same train+clean-synthetic mixture and loss as E002. Four transformer layers, width 384, 64 strongest peaks, 0.1 Da learned embeddings plus exact-mass sine/cosine features, precursor/condition token. 12,836,736 parameters. +- Full train fold, 40 epochs × 1,200 steps, batch 512; 25% experimental/75% synthetic. Exact original source/config/logs in E004. Retrieval uses the same full validation query set and candidate-ID ties. Completed in 1120.843 s on the sole H100, maximum allocated CUDA memory10.957 GB. Selected epoch37, checkpoint SHA256 `1d1d4418b4e305306996953e54426a15cd35f0b767c989840c91ec0880818193`; ordinary-cosine validation Hit@1 .30207421895, Hit@5 .47269545525, Hit@20 .63482423182. Final epoch40 was lower (.29996397138), so retained epoch37. Independent replay will use the stronger E008 ranking of these same trained weights. + +## Evaluation engineering notes +- E001 full MCES initially spent 671.031 s in a serial-result pool and was restarted to add an exact identical-graph shortcut and a persistent completed-pair cache. Official MCES threshold=15, stronger bound and CBC solver options are unchanged. The zero shortcut only recognizes the same atom/bond graph (stereochemistry is ignored by the supplied MCES graph definition). +- Cached MCES jobs were restarted once more after changing SQLite transactions to commit each completed pair, avoiding write locks across long solves. Diagnostic compute is CPU-only; full secondary metrics remain pending until every pair completes. + +## E005 — sodium mass-coordinate normalization (prepared) +- Hypothesis: shifting Na+ fragment and precursor masses by -21.981944235 Da to proton-equivalent coordinates shares fragmentation features with the much larger H+ training population. Neutral losses and the observed adduct indicator remain unchanged. +- Changed factor: mass-coordinate preprocessing only, compared with E002. Planned same random seed 1, MLP architecture, training mixture, loss, epochs and steps. All training structures remain in the train/clean-synthetic folds. Preparation took 14.136 s; corrected synthetic fractional-precursor feature to preserve original H+ rows exactly. No synthetic positive peak falls below the normalization shift. Candidate IDs never affect the learned score. +- Completed40 epochs in 306.592s; maxCUDA12.316GB. Selected epoch31 SHA256 `cfa96e4e60bee9ab19dc8acae446f08c7d5ddbd114ba999ad1eb58bcb3c2cca7`; Hit@1 0.230068454, Hit@5 0.368727160, Hit@20 0.527407484. Negative result versus E002: overall delta-.00288229 (95% molecule-CI[-.01317966,.00657117]); sodium delta-.01393287 (CI[-.03895166,.01135473]); proton delta+.00068064 (CI[-.00860138,.00998709]). Did not publish. Separately checked40train+40validation records: normalized preprocessing exactly matches runtime features. + +Further engineering: E002 passed new-input contract probes including arbitrary IDs, unseen structures, singleton pools, out-of-window peaks, missing/novel instrument labels, and candidate-order invariance. E003 preparation resumed with ten CPU workers after 787.907 s; committed targets retained. Batch-32/accumulation-1 native training will scale MAGMa schedule intervals from 2500 to625 microbatches to preserve the original schedule per observed spectrum; optimizer warmup remains2000 steps. + +## E006 — fixed fingerprint score comparison +- Hypothesis: common Morgan bits dominate ordinary cosine; weighting by their training-fold information content improves discrimination without retraining the spectrum encoder. +- Changed factor: fixed ranking function only, using the completed E002 checkpoint. Compared eight prespecified rules: cosine, soft Tanimoto, BCE likelihood, size-normalized BCE, cosine with sqrt-IDF, cosine with IDF, square-root-size-normalized dot, and mean dot. No validation fitting; IDF uses only 25,046 experimental train SMILES fingerprints. +- Selected IDF-weighted cosine: Hit@1 0.2459725153, Hit@5 0.3981162180, Hit@20 0.5622008338 on the same full validation query hash. Paired molecule-bootstrap gain over E002 +0.01302177 (95% CI [0.00855167,0.01742674], 3,185 groups). Eight-rule comparison took 8.841 s on the sole H100, overlapping E004 training briefly. +- Negative comparisons: BCE Hit@1 0.20433373; normalized BCE 0.22358330; mean dot 0.20505430. Tanimoto 0.23310515; sqrt-IDF cosine 0.24226671; dot/sqrt(size) equals cosine ranking 0.23295074. All results/source retained. Derived checkpoint SHA256 `c20a89ff4ee9c6ec69b593b48971e15a233c8f0382ad5d828700568b550583c7`; full independent replay passed all 19,429 queries in 115.219 s and exactly matched all three hit rates. MCES pending. + +## E007 — training-only hard-negative contrastive fine-tuning (prepared) +- Hypothesis: fingerprint regression ignores which similar-mass candidates must be separated; listwise training against training-only molecular negatives improves retrieval. +- Changed factor: add multi-positive near-mass InfoNCE to the fingerprint loss, initialized from the task-trained E004 checkpoint after its run completes. No external initialization assets. +- Negative pools derive solely from 25,046 experimental train and 435,076 sanitized synthetic molecular structures. Neutral masses use their training formula metadata. A ±0.01 Da neighborhood is widened to at least 32 molecules; identical fingerprint negatives are treated as positives to avoid contradictory supervision. Pool preparation 14.511 s. +- Planned fixed settings: 32 negatives, temperature 0.05, contrastive loss weight0.2, learning rate1e-4,20epochs×1200steps; same experimental/synthetic mixture. Validation only selects checkpoints; no validation candidate is used as a training negative. Training pending. + +## E008 — transformer with training-IDF fingerprint ranking +- Hypothesis/change: apply the fixed training-IDF weighting from E006 to E004 outputs. Network parameters are unchanged; weights derive only from train fingerprints. Same eight predefined fixed rules evaluated in4.108 s; full comparison retained. +- Selected weighted-cosine validation Hit@1 .31988264965, Hit@5 .49997426527, Hit@20 .67131607391. Source checkpoint E004 epoch37; derived checkpoint SHA256 `c611ede98e88041dafc82cfb71182dcb34f4ac4d93e91603557d0438e859036d`. Full replay passed all19,429 queries in98.440s and exactly matched all hit rates. Paired gain over E006 +.07391013,95% molecule-CI[.05529783,.09264636]. Proton Hit@1 .3674789, sodium .1722609; released GLACIER domain .4087734, remaining conditions .2306343. MCES pending. Exact selected fitting source, configuration, metrics and logs are copied into E008/research lineage; no external pretrained assets. + +## E009 — ten-peak transformer (planned from training-source analysis) +- Hypothesis: retaining many diffuse simulated peaks creates a source mismatch and distracts the encoder; limit both experimental and simulated inputs to the ten strongest peaks. +- Training-only analysis: deterministic seed1 samples of100,000 spectra per source show top10 retains89.963% of experimental raw intensity versus40.715% of synthetic intensity; mean retained peak counts33.50 versus58.35 (cap128). The ten-peak setting also matches the supplied MIST reproduction recipe. +- Changed factor versus E004: maximum peak tokens64→10, with the same width384/depth4, seed1, loss, mixture, steps, epochs and cosine checkpoint selection. Check fixed IDF ranking afterward using the already established scoring family. Training pending native smoke and single-GPU availability. + +## E010 — precursor mass likelihood (training-only calibration, prepared) +- Hypothesis: accurate observed precursor mass separates different formulae within mass-based candidate pools, complementing learned fingerprints. No true query formula is used. +- Fit only experimental-train residuals between observed precursor and RDKit exact target mass plus the public adduct. Robust Cauchy offsets/scales are median/MAD per adduct/instrument, scale floor0.1ppm; unknown instruments fall back to adduct-specific training calibration. Train audit8.290s: median absolute error0.229ppm overall, proton0.153ppm, sodium2.896ppm. +- Predefined score family: E008 IDF cosine plus mass log-likelihood with coefficient in [0,.005,.01,.02,.05]. Validation selects one fixed rule; no query fitting. Candidate mass caching uses only candidate SMILES and is a development convenience; runtime computes these from supplied structures. Results pending. + +E003 pipeline smoke completed: native full-size architecture trained128 optimizer steps, seed1, provided original training supervision, batch32/accumulation1. Wall114.478s, peakCUDA5.589GB; steady steps25–125 took26.477s. This is only a pipeline/timing probe, not baseline confirmation or scientific model selection. Ten deterministic validation strata queries replayed successfully in76.540s from /tmp; every supported candidate had a prediction, including sodium and missing CE/instrument. Hit@1=.3 on this tiny nonrepresentative probe, not a full-validation result. Full all-condition preparation remains running. For the next throughput probe, enable TF32 high matmul precision and examine larger batches before committing the full run. + +E009 training started from scratch with40epochs×1200steps, batch512, seed1, max10peaks; all other E004 settings retained. + +E010 internal full-validation result: coefficient.05 selected Hit@1 .373256472284, Hit@5 .558855319368, Hit@20 .722167893355. Coefficient.02 yields .368881568789/.563899325750/.731020639251; primary Hit@1 governs selection. Paired gain over E008 +.05337382,95% molecule-CI[.04342458,.06387135]. Proton Hit@1 .43615573 (gain+.06867683); sodium .17817184 (gain+.00591091, CI includeszero). Five-rule evaluation10.078s on soleH100, briefly overlapping E009. Candidate mass preparation84.728s on2CPUs, uses only candidate SMILES. Derived checkpoint SHA256 `72e3da9cc1bb57846e15932f057cf43d63fc1f3b9ea40c74bf69a9c70d9cba13`; validation query hash `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. Relocated independent replay started; not yet published. + +E003 throughput preparation: added an explicit training matmul-precision setting (high enables TF32), configurable native learning-rate decay interval, and a bounded per-worker graph-feature cache. The cache holds only deterministic molecular graph features with one-hot edge tensors packed as uint8; targets remain spectrum-specific. Exact collated tensor comparison passed64 deterministic seed1 training examples, testing misses and repeated hits, in3.390s. Batch128 schedule preserves sample counts with LRwarmup500/decay1250 and MAGMa156/156 (rounded from156.25); peak LR unchanged. Larger-batch probe pending GPU availability. + +## E011 — equal-weight peak-encoder ensemble (planned) +- Hypothesis: ten-peak and64-peak encoders make complementary errors; a fixed equal-weight ensemble improves retrieval. +- After E009 completes, compare two predefined rules using E004 and E009: arithmetic mean of fingerprint probabilities, or arithmetic mean of training-IDF cosine scores. Both use E010's already-selected train-calibrated mass score with coefficient.05. No parameter fitting or labels at inference; select on full validation Hit@1, report molecule-bootstrap uncertainty. + +E010 independent relocated full replay PASSED:19,429/19,429 valid rankings, no global error,113.689s (overlapped E009 training and CPU research jobs). All three hit rates exactly match internal evaluation. New-input probes passed in11.634s: arbitrary IDs/new structures, singleton pools, missing/novel instruments, out-of-range peaks, candidate-order invariance, no package mutation. Published as the new selected package after these checks; MCES remains pending. + +## E013 — condition-aware precursor calibration (prepared) +- E010 validation error analysis: released-domain Hit@1 rose to.53133, but remaining conditions fell to.21454 fromE008's.23063; proton/missing-CE Hit@1 is.24929. Hypothesis: metadata completeness marks different precursor-error distributions, and pooled calibration overtrusts missing-CE precursor masses. +- Changed factor: fit train-only median/MAD calibration separately by adduct, instrument, and whether collision energy is present. Groups smaller than64 train rows fall back to adduct/CE, then adduct. Retain E010 coefficient.05, E004 network and training-IDF weights. No validation fitting. Calibration/evaluation pending. + +E009 COMPLETE:574.627s on oneH100 (brief scoring/replay overlaps logged), peakCUDA9.256GB. Epoch37 selected by raw cosine retrieval; Hit@1 .333676463019, Hit@5 .501878635030, Hit@20 .661639816769. Raw checkpoint SHA256 `6960d7591a47579956d77ae2fed7257680d8fd6b0602bcda03865abdce412c0e`. Paired raw-score gain vs64peak E004 0.03160224406814555,95% molecule-CI[0.018987894860506185,0.04320836517468455]. Final weighted/mass and ensemble evaluation pending. + +E013 full-validation internal result .382520973802/.575531422101/.736167584539 (Hit@1/5/20), versus E010 .37325647/.55885532/.72216789. Paired Hit@1 gain+.00926450,95% molecule-CI[.00652667,.01220483]. Train audit confirms proton precursor MAD.0401ppm with knownCE versus1.2050ppm with missingCE; calibration remains train-only. Evaluation12.819s, briefly overlapping E009. Derived checkpoint SHA256 `9c3570d912486378c6e4fea28f967da1c49b9369b1dd52e364801e9a07218dac`; same full validation query hash. Independent replay pending. + +E011 COMPLETE internal evaluation: ten-peak IDF-only .35374955; ten-peak plus fixed E010mass .39744712/.57079623/.73277060. Equal-probability ensemble .424725925163/.596788306140/.750939317515; equal-cosine ensemble .42060837/.59287663/.74754233. Select equal probabilities by Hit@1. Evaluation36.783s; a redundant NPZ-index read inside the mass loop was fixed afterward without changing scores. Source before/after preserved. E012 names the ten-peak+mass ablation. + +## E014 — combine selected equal-probability ensemble and condition-aware mass calibration +- Combine independently promising E011 encoder ensemble with E013 train-calibrated precursor likelihood. Same coefficient.05 and equal encoder weights; no new fitted parameter or validation weight search. Compare both prior ensemble rules and single-encoder controls for a complete ablation. Independent replay will target the strongest full-validation candidate. + +E014 internal full-validation result: equal-probability ensemble .432446343095/.611971794740/.765299294868; equal-cosine .42971846/.61053065/.76313758. Single ten-peak conditioned control .40537341/.58721499/.74630707;64-peak exactly reproduces E013 .38252097. Evaluation5.231s after caching the NPZ indices, during native probe startup. Paired gain vs publishedE010+.05918987,95% molecule-CI[.05121523,.06739473]; vs E011+.00772042,CI[.00518289,.01035210]; vs single ten-peak conditioned+.02707293,CI[.01861828,.03595447]. Checkpoint SHA256 `33f307d4f57bc0df4b2e5a3080cd5efa60e7c5e3e28648eda492a2f4b7a0709c`. E013/E012 are retained ablations; strongest E014 proceeds to independent replay. + +E003 larger-batch probe INTERRUPTED for diagnosis after248.421s: CSV stopped after step30; parent CPU remained active while GPU was idle for over two minutes. Peak observed GPU reserved memory28.45GB, no OOM reported. This is a failed throughput probe, not a scored scientific model. Exact source/config/logs retained in smoke-b128; a seed1 batch128 reproduction with periodic Python stack dumps and checkpoints every16steps is running. No affected model was published. + +E014 independent relocated replay PASSED:19,429/19,429 valid rankings, exact agreement with all internal hit rates,118.138s, peak summed process RSS9,148,887,040bytes. Unseen-input/candidate-order/package-mutation probes passed13.545s. Published as selected package. MCES pending; validation is not directly comparable to the external test score. + +E003 full fragment preparation COMPLETE:189,031/194,119 train spectra and18,170/19,429 validation spectra annotated;6,347 total no-fragment exclusions affect only fitting/loss validation, never retrieval denominator. Resumed phase2414.156s plus recorded prior787.907s=3202.062s, excluding earlier invalidated smoke. Manifest and source digests preserved. Batch128 debug repetition completed40steps in134.157s, peakCUDA25.757GB; prior stall did not reproduce. Stack dumps identify substantial worker-startup/loading time but do not establish the original stall cause. Added compact worker metadata and retained periodic checkpoints. +Native source audit found a separate signed-bit bug: packed boundary atom63 was erased by a >0 test on signed int64. Changed to !=0; direct tests at32,64,65,100atoms now recover every expected boundary. This changes training fragment supervision for large molecules and is recorded as an additional E003 factor. No previous inverse/ensemble model is affected. +Full native training will start from random seed1 with all189,031 training spectra, batch128,6loader workers, TF32 high precision, sample-scaled LR/MAGMa schedules; first stage4000optimizersteps, retain milestones every2000. A fixed hash-selected4096 validation spectra monitors loss; checkpoint/model publication to root requires validation retrieval metrics. Current root remains independently verified E014 during native fitting. + +## E015 — native forward reranking of ensemble shortlists (implementation/pipeline phase) +- Hypothesis: the native simulator can resolve ambiguous top candidates while E014 limits candidate-simulation cost. Use the top20 ensemble candidates per query; union candidates sharing the same public pool/condition to reuse simulations. Rank only each query's own shortlist, then append its remaining ensemble order. +- Compare fixed reciprocal-rank fusion with native weights[0,.25,.5,.75,1] and offset10; no query-specific fit. Unsupported candidates retain their ensemble rank as neutral native evidence; unsupported observations keep the ensemble ranking. Shortlist unit checks pass complete permutations, union deduplication, order invariance, exact zero-weight identity, and own-shortlist-only reranking. A pipeline smoke uses the prior40-step native probe; scientific evaluation awaits native training milestones. + +## E016 — training-only mixture model for precursor errors (fitting) +- Hypothesis: precursor errors combine very precise and noisy sources within each metadata group, which one Cauchy scale cannot capture. +- Replace E014's single Cauchy density with a mixture of fixed Cauchy scales[.003,.01,.03,.1,.3,1,3,10,30,100,1000]ppm. Fit only mixture weights by100 deterministic EM iterations on experimental-train residuals, with one pseudo-observation/component; offsets are training medians. Keep E014 encoder ensemble, equal member weights, coefficient.05 and metadata grouping unchanged. No validation coefficient search. Results pending. + +E015 pipeline replay PASSED after relocation:10/10 complete valid rankings acrossadduct/energy/instrumentstrata,62.081s. Native smoke weights only, so tiny Hit@1 .4/Hit@5 .7/Hit@20 .9 is not scientific selection. Full-validation top20 staging needs217,475 candidate-condition simulations for19,429queries,about91.7% fewer than256candidates across10,192conditions; stage51.069s. A fixed1024query uniform sample(seed0,query hash`84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e`) has17,656 simulations; stage8.146s. This sample is for checkpoint screening, with full validation required before root publication. +E016 fitting16.348s CPU, evaluation11.969s on soleH100 overlapping native training. Fixed mean-probability ensemble Hit@1 .433475732153,Hit@5 .612074733646,Hit@20 .765299294868. Gain over E014+.00102939,95% molecule-CI[-.00031004,.00243175]:54 queries gained,34lost; the small gain is statistically uncertain. Derived checkpointSHA256 `51461bd376a5e4faeef4b57286af5a7d8739b36dbf9115f1d1ca36adcb3eb719`. Independent relocated replay returned successfully in101.208s,peak summed RSS9,139,843,072bytes; score/probe checks pending. + +E016 final independent checks PASSED: 19,429/19,429 valid rankings, all hit rates exactly reproduced; unseen-query and candidate-order probes passed in14.670s with package unchanged. Exact paired MCES@1 delta versus E014 is−.01636729 (lower is better),95% molecule-CI[−.09724679,.07164605]; unchanged predictions cancel,450changed queries,90new molecular pairs,20.982s/2CPU workers. Both Hit@1 and MCES changes are statistically uncertain. Select E016 by its higher primary validation point estimate; E014 remains the fixed E015 checkpoint-screening control. Full absolute MCES remains pending. Root publication includes the selected fitting source, all encoder lineage/config/logs and these checks. + +## E017 — synthetic collision-energy masking (prepared) +- Training-only source audit: experimental spectra have47.656% missing energy; clean simulations have none. With25% real/75% synthetic sampling, only11.914% of training inputs have missing energy. Validation error analysis shows this remains a weak condition. +- Hypothesis: masking energy on50% of sampled synthetic spectra teaches the same encoder to handle unknown collision energy across more molecules. Keep the spectrum, target, adduct and instrument unchanged. This probability is a fixed rounded training-source rate, not fitted on validation. +- Planned changed factor versus E009: synthetic energy metadata masking only; random seed1, max10peaks,40epochs×1200steps,batch512,width384/depth4,same objective/optimizer/mixture. An independent seed17001 augmentation RNG preserves the main data/dropout RNG stream and is checkpointed for resumption. Training not yet started. CPU source audit.252s; source prepared inpeak-condition-drop. + +E015 first scientific checkpoint screen COMPLETE (E003 step1477, exported checkpointSHA256`79b83bea7d6039994d3d4dfda38fafbb656afa4ff490abdf3a82a7391b2fa759`). Fixed1024query set as above; native replay199.876s,peak summedRSS12,260,560,896bytes,full screening203.264s,oneH100 overlapping native training. All1024 rankings valid. Hit@1 forweights[0,.25,.5,.75,1]=[.41894531,.44628906,.45996094,.44042969,.42675781]. Select.5 on this screen:Hit@5 .64453125,Hit@20 .7578125;pairedHit@1gain+.041015625,95%molecule-CI[.01421717,.06907370] overE014on668groups. Known-domain Hit@1 .692164 vsbaseline.604478;remainingconditions .204918 vs.215164, so the early benefit is concentrated inknown-energyproton spectra. This is a subset screen, not a full-validation or test result. Next comparestep2000beforefullvalidation. + +E017 starting on the same soleH100 alongside E003. E009 measured peak allocated9.256GB and current E003 GPU reservation55.1GB leave capacity; cap E017 allocator at16% of totalGPU memory (~12.8GiB), retaining headroom. The cap changes resource allocation, not training math. All wall times will explicitly record overlap; no secondGPU is used. + +E017 preregistered post-training retrieval comparisons: apply frozen E016 training-IDF/mass-mixture score to the selected E017 encoder alone; replace E009 in the E004+E009 equal-probability ensemble withE017; and use an equal three-member E004+E009+E017 ensemble. Include E016 unchanged as an exact control. No learned ensemble weights or new mass coefficient; select by full-validation Hit@1 with molecule-group uncertainty. + +E001 full absolute MCES@1 COMPLETE:19.734700705132 on19,429queries. Exact official settings,8,663unique molecular pairs; current resumed phase computed8,363new pairs in4249.433s with4CPU workers, with earlier cache-preparation/interrupted logs retained separately. This updates only the secondary metric for the early MLP control; model selection is unchanged. + +E015 step2000 scientific screen COMPLETE: checkpointSHA256`e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369`,same1024queryhash/seed. Native replay251.147s,peak summedRSS12,563,185,664bytes,total254.038s; overlaps E003/E017training onsoleH100. Forweights[0,.25,.5,.75,1],Hit@1=[.41894531,.4375,.46484375,.435546875,.416015625]. Selectweight.5:Hit@5 .63671875,Hit@20 .7578125;gainvsE014+.04589844,95%molecule-CI[.01937100,.07447167]. The primary point estimate improves overstep1477by.0048828125, whileHit@5 decreases; full validation is next. Exactnative-alone shortlistreranking isweakerthanE014 atthischeckpoint, so the gain depends onthehybrid. + +Full absolute MCES is now complete for E014 andE016:10.276828452314 and10.260461166298 respectively. E014 used6,339unique pairs,2,375new pairs,1820.068s with4CPU workers. E016 used6,315pairs,allcached,5.363s with2workers. The difference exactly reproduces the independently calculated pairedMCES delta. Selection remainsE016 whileE015 fullvalidation runs. + +E015 step2000 fixed hybrid relocated-package unseen-input probes PASSED in114.968s: newstructures/arbitraryqueryIDs,completecandidatepermutations,singletonpool,missing/novelinstrument,out-of-windowpeaks,candidate-orderinvariance,andpackageimmutability. Full19,429queryreplay isrunning. Nativecheckpoint remainsfixed atstep2000 despite continued E003training. + +E017 training COMPLETE:676.215s onsoleH100 overlappingE003training/E015retrieval;peakallocated9,255,555,584bytes. Epoch28 selectedrawHit@1 .339801327912,Hit@5 .507540274847,Hit@20 .658963405219;checkpointSHA256`15d84dfaaacf65ad9224f15f513f2689afffe4eecbff1b35ce8bc55cd1539248`. RawgainoverE009+.00612486,95%molecule-CI[−.00430701,.01656211],statisticallyuncertain. Fixedcalibrated postscore8.922s:single .41000566/.59977353/.75253487;replacementE004+E017 .43553451/.61933193/.76998302;threeE004+E009+E017 .44289464/.62710381/.77904164. ControlE016 exactlyreproduced. Three-member gainvsE016+.00941891,95%molecule-CI[.00365417,.01517550]. + +## E018 — selected three-member inverse ensemble +- Select the preregistered equal E004/E009/E017 probability ensemble from E017 postscore. Same train-IDF and frozen train-only E016 precursor-mixture likelihood, coefficient.05; no fitted ensemble weight. Fullvalidation queryhash`7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. Independentreplaypending; preserveallthree traininglineages. + +E007 contrastive training STARTING: originally preregistered E004epoch37 initialization,20epochs×1200steps,batch512,seed1,lr1e-4,25%real/75%clean synthetic,32near-mass negatives,temp.05,lossweight.2. Negativesfromtrain/cleansynthetic structuresonly. Allocate atmost20%of soleGPU memory; overlapsE003/E015, nosecondGPU. CurrentE003reservation42.8GB leaves headroom for~14GB estimated contrastive peak. + +E017 condition diagnosis supports the masking hypothesis: rawsingle-encoder Hit@1 onmissing-energy spectra rises .22033002→.24328327,delta+.02295325,95%molecule-CI[.00815355,.03826665];sodium .17394976→.19886004,delta+.02491028,CI[.00146445,.04560380]. Known-energy rawperformance decreases .44110276→.43127820 (CIincludeszero). In E018three-memberensemble,missing-energy Hit@1 improves .25142797→.26591919 andsodium .19674900→.21173739; bothpairedCIspositive. Additional post-hoc attribution control: duplicate E009 in an equal E004/E009/E009 ensemble to distinguish added encoder diversity from merely increasing ten-peak weight. This control does not fit any parameter. + +E007 attempt 1 FAILED before a completed epoch or selected checkpoint. Observed log lifetime58.718s (filesystem creation to last error write; cleanup excluded). Float32 negative sampling added the large pool offset before flooring, occasionally rounding to the exclusive upper bound. Reproduction on the real highest-mass pool produced index460122 for an array of length460122. Fixed by flooring the random offset before integer addition and enforcing the upper bound. Check:29,447,808draws over all460,122pools had3,999old out-of-pool samples andzero fixed failures; CUDAedgecase fixed460122→460121,1.094s. Failedsource/recipe/log retained in E007/failed-attempt-1. Restart from the same original E004 checkpoint,seed1; no validation update was selected from the failed run. + +E018 independent relocated full replay PASSED:19,429/19,429 valid rankings and exact agreement with internal Hit@1 .442894642030,Hit@5 .627103813886,Hit@20 .779041638787. Wall103.294s,peak summedRSS9,598,693,376bytes; oneH100 overlapping E003/E007training,E015replay andCPU MCES. Unseen/order/package-immutability probes passed15.337s. CheckpointSHA256`b2cf7e886b8f81bb0d14953d4bdb5027760cf027bf9b11936f042518ef52975c`. Select and publish by the improved full-validation primary metric; pairedMCES is running and will be added when complete. +Attribution control15.589s: repeating E009 as a third member yieldsHit@1 .43100520,Hit@5 .61197179,Hit@20 .76246847,below E016. The selected distinct E017 member reproduces .44289464/.62710381/.77904164. Thus simply increasing the original ten-peak encoder weight does not explain E018's gain. +E015 step1477 sample pairedMCES complete:delta−.55224609,95%molecule-CI[−1.23643969,.16746359],439changed queries,195newpairs,761.893s/2workers. This remains a1024-query screening result; no full-hybrid score is claimed. + +## E019 — combine the improved inverse ensemble with later forward checkpoints +- Hypothesis: E018's stronger missing-energy retrieval and higher top-20 recall complement continued E003 forward training. Replace the E014 shortlist source with the fixed, verified E018 ensemble; retain top 20, the same fixed RRF family [0, .25, .5, .75, 1], and offset 10. No additional fitting or new scoring coefficient. +- Stage the same fixed 1,024-query screen and the complete validation fold using public inputs and E018 predictions only. Test the next retained native milestone when available; compare against E018 on exactly the same queries, then require full replay before root publication. This is a combined-model experiment, so its gain will not be attributed solely to either component. No E019 retrieval result yet. + +## E020 — coarse extension of the global precursor-score coefficient +- Hypothesis: E010 selected the largest coefficient in its original fixed grid, so E018 may benefit from a stronger precursor likelihood. Compare exactly [.05, .1, .2], using .05 as the verified control. +- Changed factor: one fixed global scoring constant. Keep all E018 encoders, equal weights, training-IDF weights and train-fitted mass-error distributions fixed. No query-specific coefficient or calibration fitting. Select the fixed ranking rule on full-validation retrieval and report paired molecule-group uncertainty. + +E018 MCES COMPLETE:9.988136291111 versus E01610.260461166298. Exact paired delta−.272324875187,95%molecule-CI[−.43056669,−.12622224];3,317changed predictions,617new pairs,353.519s with4CPU workers. Full absolute score then used6,173cached pairs in5.261s. All four validation metrics improve. +E020 first scoring attempt was interrupted after168.637s (175.30CPU seconds), without metrics, because it was unexpectedly slow; originalsource/log/record retained in slow-attempt-1. Instrumented restart identifies time spent loading the large candidate NPZ via NumPy read_array, not in ranking or model fitting. Letting the read finish; no cause beyond the observed location is established. This changes no scientific scoring rule. + +E020 COMPLETE, negative result. Coefficient .05 exactly reproduces E018. Coefficient .1 lowers Hit@1 to .43450512 (paired delta −.00838952, 95% molecule-CI [−.01146519, −.00538412]); .2 lowers it to .40830717 (delta −.03458747, CI [−.04214415, −.02730915]). Hit@5/20 also decrease for both. Retain .05. Instrumented scoring took 51.390 s, including about 45.2 s loading the candidate cache, plus the separately recorded 168.637 s interrupted attempt. No model parameter or package change was selected. +E007 preregistered post-training rules: with fixed E018 IDF/mass calibration, compare the selected contrastive encoder alone, replace E004 with E007 in the three-member ensemble, and use an equal four-member E004/E007/E009/E017 ensemble. Include E018 unchanged as control. Keep global mass coefficient .05 after the negative E020 result; compare paired outcomes against E018. + +## E021 — independent masked-energy encoder for ensemble diversity (prepared) +- Hypothesis: an independently initialized masked-energy encoder makes complementary errors and improves the fixed ensemble. This run is for a new ensemble member, not to confirm a baseline score. +- Changed factor versus E017: seed 1 → 2, including the independent augmentation generator seed 17001 → 17002. Keep architecture, 10 peaks, 50% synthetic energy masking, data mixture, objective, 40 × 1200 steps, batch 512 and learning-rate schedule identical. Start from random initialization. +- After fitting, compare E021 alone with the frozen calibration, replacing E017 in E018, and an equal E004/E009/E017/E021 ensemble; include E018 unchanged. No fitted ensemble weights or new mass coefficient. Begin after E007 finishes so the single GPU remains within the established memory allocation. + + +E007 contrastive restart COMPLETE:880.379s on the sole H100 overlapping native training and hybrid replay; peak allocated13,295,123,968bytes. Select epoch4 by full-validation raw retrieval:Hit@1 .310000514695,Hit@5 .483143754182,Hit@20 .643882855525,checkpointSHA256 `0440569a4a87aadf5571781bf60078b22bc11459abf153a2039ed229056087f2`. Later training loss decreases without retrieval improvement. Add the failed first-attempt observed58.718s separately; no failed weights selected. Frozen calibrated score-family evaluation10.864s: single .38658706/.57887694/.73560142; replacement E007/E009/E017 .44279170/.62978023/.77847547; four E004/E007/E009/E017 .44418138/.62545679/.77698286; E018 control exactly reproduced. Four-member Hit@1 gain+.00128674,95% molecule-CI[−.00327597,.00582098] is small and uncertain, with lower Hit@5/20. Same full validation query hash `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. + +## E021 — independent seed for masked synthetic encoder (training) +- Hypothesis: a second independently trained masked ten-peak encoder contributes complementary errors. This tests ensemble diversity, not reproduction of a supplied baseline. +- Change E017 random seed1 to2 (separate augmentation RNG17002); otherwise retain40×1200steps,batch512,50% synthetic energy masking,25% experimental sampling,lr.0003,top10peaks and from-scratch initialization. Sole H100 allocator cap16%; overlap E003 native training/E015 replay. Preserve frozen-training and copied fit source. +- Predefined fixed postscore comparisons: E021 alone, replace E017 in E004/E009/E017 by E021, equal four-member E004/E009/E017/E021, with exact E018 control. Frozen train-IDF/mass mixture and coefficient.05; full-validation retrieval selection and molecule uncertainty. Compute/checkpoint/result pending. + +## E022 — four-member inverse ensemble including contrastive encoder +- Select the preregistered E007 four-member score family by primary validation point estimate. Same E018 calibration, coefficient.05 and equal probabilities; no additional fitting. Full independent relocation/replay, input probes and paired MCES pending before publication. + + +## E023 — increase experimental fraction (prepared) +- Hypothesis: increasing experimental sampling reduces the simulated-to-experimental spectral gap that remains strongest for missing energy and sodium. Change only E017 real_fraction from.25 to.50; random seed1,40×1200steps,batch512,max10peaks,synthetic energy masking.5 and all other training settings unchanged. Train from scratch after E021 finishes. +- Predefined fixed comparisons: calibrated E023 alone, replace E017 in E018, or add E023 as a fourth equal-probability member; E018 unchanged control. Retain frozen training-IDF/mass-mixture and coefficient.05. Full validation selection with molecule-group uncertainty; result/compute/checkpoint pending. + + +## E024 — expand native shortlist to64 (prepared) +- Hypothesis: the current top20 shortlist excludes about22% of full-validation correct candidates under E018, limiting recovery. Compare top64 with top20 on the same fixed1024query screen, same E018 baseline, same upcoming native step4000 weights and fixed RRF family[0,.25,.5,.75,1],offset10. No labels or query fitting used to form shortlists. Measure simulation work and replay resources; full validation required before publishing. Compute/checkpoint/results pending. + + +## E025 — conservative native fusion outside known-energy proton spectra (planned) +- Early E015 screens show gains concentrated in proton spectra with known collision energy. Test three fixed public-condition rules on the upcoming E019 step4000/top20 screen: known-energy proton native RRF weight.5, with all other conditions receiving.5(control),.25,or0. Rank offset10 and E018 baseline unchanged. This is global rule selection, not fitted/query-specific parameters. Full validation required before publication. Reuse fixed native outputs; no extra model fitting or label-derived shortlists. + + +E003 native first stage COMPLETE at4000optimizersteps:3839.656s cumulative wall time on the sole H100 with inverse fitting/scoring/native replay overlaps; peak allocated42,274,433,024bytes. Random seed1/all189,031 annotated train spectra; latest loss validation at2954 gives.60216558 versus.62852305 at1477. Loss-selected checkpoint remains2954; immutable step4000 milestone will be evaluated on retrieval separately. Resume exactly preserved optimizer/sampler/RNG/MAGMa state to8000steps under cumulative24000s budget, keeping identical frozen recipe/source. Stage4000 result/log/checksum preserved. + + +E022 independently relocated full replay PASSED in114.330s,peak summed RSS9,884,073,984bytes,19,429/19,429 complete valid rankings and all three hit rates exactly reproduced. Unseen-structure/arbitrary-ID/singleton/missing-or-novel-instrument/candidate-order/package-immutability probes passed18.359s. Derived checkpointSHA256 `bdb075fec1a50bd0ca3f8a8e3ee939f977407cb1808605e69c1a34238b00ba30`. Paired MCES is computing165new molecular pairs for2,320changed top predictions; retain E018 until this comparison and current hybrid full retrieval are available. +E007 raw contrastive gain over E004 is+.00792630,95%molecule-CI[.00241820,.01342294];known-energy gain+.01463659,CI[.00727480,.02181830],missing-energy and sodium intervals includezero. The small four-member ensemble gain is uncertain in every major adduct/energy stratum. +E024 top64 subset preparation completed26.228s,55,556candidate-condition simulations versus17,666for top20. Query hash unchanged. The forthcoming subset replay will measure the roughly3.14×simulation-work tradeoff. + + +E022 MCES COMPLETE:9.921174532915 versus E0189.988136291111;delta−.0669617582,95%molecule-CI[−.169066412,.028457375],also uncertain. Paired computation165newpairs/2workers/199.675s; absolute6208cachedpairs4.913s. Select E022 by primary full-validation Hit@1 point estimate after exact relocated replay and unseen-input checks; Hit@5/20 decline slightly. This is a small, uncertain improvement and no evidence of surpassing the test reference. Publish the fixed four-member package atomically while native hybrid evaluation continues. + + +## E026 — align contrastive training with training-IDF retrieval (prepared) +- Hypothesis: E007 ordinary-cosine contrastive training differs from the selected IDF-weighted retrieval metric. Change only the contrastive cosine to multiply predicted/candidate fingerprint features by square-root training-IDF, computed from unique experimental training structures. No validation statistics. Keep E007 initializationE004,seed1,20×1200steps,batch512,lr1e-4,32near-mass negatives,temp.05,lossweight.2 and raw retrieval checkpoint selection. +- After E023, compare calibrated E026/E007 single encoders, replacement of E007 in E022, and a five-member equal-probability ensemble. Frozen E018 mass coefficient.05,full-validation Hit@1 selection and molecule uncertainty. Result/compute/checkpoint pending. + + +E021 independent-seed masked encoder COMPLETE:692.382153s on sole H100 with native fitting/replay overlap,peak allocated9,255,555,584bytes. Selectedepoch35 rawHit@1 .339286633383,Hit@5 .510525503114,Hit@20 .660456019353,checkpointSHA256 `6033332c96b67d6b8384da54ec79d8c8a220dcb9998ffa6c3079944b5e3487c0`. Calibrated fixed score-family9.557344s:single .41067476/.59797210/.75752741;replacement E004/E009/E021 .45076947/.63230223/.77806372;four E004/E009/E017/E021 .45272531/.63724330/.78249009. E018 and current E022 controls reproduced exactly. Four-member gainovercurrentE022+.00854393,95%molecule-CI[.00333186,.01361497]. Same fullqueryhash `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`. Fixed calibration/IDF/mass coefficient.05 unchanged. Post-hoc attribution control will duplicate E017 at the same four-member weight to distinguish new-seed diversity from increasing masked-model weight; no fitting. + +## E027 — ensemble with both masked-encoder seeds +- Select preregistered E021 four-member rule E004/E009/E017/E021 by full-validation Hit@1. Preserve all fit lineages. Relocated independent replay, unseen-input/order checks and MCES comparison pending before root publication. + +E023 started after E021 scoring on the same GPU, maintaining native training and retrieval overlap. Exact prepared seed1 recipe with experimental fraction.50; training results pending. + + +## E028 — fingerprint similarity family for stronger ensemble (prepared) +- Hypothesis: with the stronger E027 ensemble, Tanimoto/Jaccard may better reflect candidate fingerprint cardinality, while fixed binarization may suppress diffuse weak bits. Evaluate training-IDF cosine(control), squared-norm Tanimoto, soft Jaccard, and binary IDF-Tanimoto at fixed thresholds[.1,.2,.3,.5]. Retain the same E004/E009/E017/E021 probabilities and frozen training-only precursor likelihood,coefficient.05. No additional fitting. Select by full-validation Hit@1 with molecule-group uncertainty; independent replay needed for a changed runtime rule. Run after E027 replay frees GPU resources. + + +E015 step2000/E014-top20/uniformRRF.5 FULL REPLAY COMPLETE:2676.615274s,peak summed RSS18,870,747,136bytes,sampledCPU6087.96s,19,429/19,429 valid complete rankings. Hit@1 .457409027742,Hit@5 .658345771784,Hit@20 .765299294868. Against current E022,Hit@1 gain+.01322765,95%molecule-CI[−.00057051,.02772758];against E027+.00468372,CI[−.01008924,.02005136]. Point estimates improve primary Hit@1 but differences are uncertain; Hit@20 decreases. Known-energy proton Hit@1 .68091227,other conditions .23300670; sodium .17880515,showing the remaining condition imbalance. Prior relocated unseen/order/immutability probes passed114.968s. MCES is computing1814new pairs with2workers. Primary retrieval governs selection; select and atomically publish this verified fixed package while the secondary metric continues, explicitly pending. Native checkpointSHAe79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369; full queryhash unchanged. + +E019 step4000 with E018 top20 subset screen COMPLETE:237.849315s native replay,RSS12,401,762,304bytes,total241.105239s;native exportedSHA8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527. Same1024queryhash84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e. RRFweights[0,.25,.5,.75,1] Hit@1=[.4296875,.45800781,.46191406,.45507813,.43652344]. Weight.5 selected:Hit@5 .67089844,Hit@20 .77441406,gainvsE018+.03222656,CI[.00755183,.05981277]. The baseline and native checkpoint both changed from E015; this does not establish a checkpoint-only improvement. +E025 conditional-rule screen5.547154s:uniform.5/.5 gives.46191406;known-energy-proton.5/other.25 gives.47070313/.66210938/.77441406;known-proton.5/other0 gives.47167969/.65136719/.77441406. Selectother0 byprimarypointestimate;gainvsE018+.04199219,95%molecule-CI[.02293099,.06274910]. Full validation and packaged conditional routing remain pending. +E021 attribution control:duplicating masked seed1 in E004/E009/E017/E017 yields.44274023/.62736116/.77806372,versus distinctseed2 four.45272531/.63724330/.78249009. Additional seed contributes beyond merely increasing masked-model weight. +E027 relocated full replay PASSED104.278846s,RSS9,978,441,728bytes,19,429valid andexacthitmetrics;new-input/order/immutableprobes16.183228s. CheckpointSHAa836e8e99ce5676c5116c9f62234d8d74e75ab860af43dc7b4cc73c8edce054d. PairedMCES vsE022 is computing349newpairs. E027 is currently the strongest inverse-only model; E015 has higher full-validation primary point estimate. +E028 initial scorer failed before results because stable argsort requires keyword dim. First process duration was not captured;117s is only a conservative log-birth-to-error-archival upper bound (1sresolution,includesidleafterexit). Timing-record helper failures and missing /usr/bin/time are preserved; a repeated failed scorer is timed8.667140s. Corrected keyword argument and added a Python timing wrapper that records failed executions. No fitted parameter/checkpoint/model selection changed in these failures; corrected evaluation running. +Development-only attempt to preserve completed E015 forward predictions found the temporary directory already cleaned; no assets copied or results changed. Empty-cache status records this. No submission depends on a development cache. + + +## E029 — fixed native/inverse composition by public conditions +- Full-validation error analysis shows E015 strong on known-energy proton spectra but weaker on sodium/missing-energy spectra. E025 independently tested this public-condition rule on the fixed subset with step4000/E018. Now combine fixed E015 for known-energy proton inputs with verified E027 inverse ensemble for all other inputs. This changes both the inverse component and routing relative to E015, so it is a combined-model experiment. No labels/IDs/formulae are used to route inference. +- Construct full validation ranks from independently replayed components, measure all retrieval metrics/uncertainty, then package and independently relocate/replay the full composition if better. No parameter fitting. + + +E027 MCES COMPLETE:9.681429821401;pairedgainversusE022−.239744711514,95%molecule-CI[−.38422582,−.10200790],349newpairs/2workers/313.500823s,3547changedtop predictions. All full-replay/probe checks passed. Retain as strongest inverse component even though E015 has higher overall primary point estimate. +E028 COMPLETE NEGATIVE:cosine control exactly reproduces all E027 ranks. Hit@1 for squared Tanimoto .42904936,softJaccard .42791703,binarythresholds[.1,.2,.3,.5]=[.43146842,.40676309,.38319008,.33491173];everyvariant reduces all three hit rates. Retain cosine. Corrected scoring computation12.522339s,external timed process16.253912s includingimports; failed attempts/timing-helper issues separately preserved. Same E027checkpoint/queryhash; no package change. +E029 fixed-condition composed full-validation result .479643831386/.666426475887/.780637191827 (Hit@1/5/20). GainoverE015+.022234803644,95%molecule-CI[.010433974590,.033726201927]. Derived solely from independently replayed component ranks using public adduct/energy presence; no fitting. Full end-to-end relocated replay and unseen/order checks are next, before publication. +E026 now starts the prepared train-IDF contrastive objective from E004,seed1,20×1200steps,all other E007 settings fixed. SoleGPU/22CPUshared allocation; result pending. +E015 selected-final generation was promoted atomically with publish_directory after exact runtime/config/native+baseline checkpoint equality to the verified relocated package. Initial premature snapshot calls were rejected before changing the current manifest; snapshot CLI requires a new directory and is not the promotion API. The current selected generation is generation-1x4e_dwk; public model remains fully valid throughout. MCES still computing. + + +## E030 — add stronger inverse ranking evidence within the native branch +- Hypothesis: E027 may correct residual errors in E015's known-energy proton ranking beyond the older E014 inverse component. For known-energy proton spectra only, compare fixed RRF of full E015 and E027 rankings with inverse weights[0,.25,.5],offset10; all other inputs retain E027. Weight0 must exactly reproduce E029. No training or query-specific fit. Select full-validation Hit@1 with molecule-group uncertainty; any selected runtime change requires independent replay. + + +E023 real-fraction.50 training COMPLETE:683.151044s,peakallocated9,255,555,584bytes,seed1,epoch37 rawselected.296515518040/.463997117711/.632199289722,checkpointSHA256 `025eb1297877bb16d496c49f58952dc22fde58e505cd41423ac28667b4bc87cb`. This is below E017 raw.33980133. Calibrated score-family9.881355s:single.37248443/.57048742/.73122652,replacement.44263729/.62545679/.77147563,four.44654897/.62993463/.77708580. Four improves olderE022 by.00236759 withCI[−.00293817,.00741728],but is below the strongerE027.45272531; no promotion. Full queryhash unchanged. +E024 top64 step4000 screen COMPLETE663.863061s total. Weights[0,.25,.5,.75,1] Hit@1=[.4296875,.46972656,.47167969,.45605469,.42480469]. Select.5:Hit@5.67871094,Hit@20.796875;comparedtop20sameweights.46191406/.67089844/.77441406,all three improve. Full validation remains pending. Extend the already-fixed E025 conditional-weight comparisons to these top64 outputs as an additional screen; no fitting. An explicit development-only snapshot of forward predictions was successfully captured after the writer completed:294,341,508bytes HDF5,copy.568256s. It is not a package asset or inference dependency; condition mapping and deterministic reuse still require verification. +E030 fixed full-rank fusion COMPLETE35.390457s:inverseweights[0,.25,.5] giveHit@1[.47964383,.47815122,.47068815]. Higher inverse weight raisesHit@20slightly but lowers primaryHit@1; retainweight0,exactlyE029. No runtimechange. +E029 relocated unseen/order/immutability probes PASSED135.549754s;full end-to-end replay now running. +E026 first attempt FAILED before a completed epoch/selectedcheckpoint,14.518228s measured in exceptionhandler. Native fitting process grew to67GiBGPU memory,leavinginsufficientspaceforE026's12.15GiB; no failed weights selected. Preserve source/recipe/log/failure record. Restart the exact original E026recipe after rescheduling native fitting. +E003 deliberately stopped for resource scheduling after preservingstep5250checkpointSHA256`03a048abe4844d84cd8b8ebc6e19458dc99cb2f56504d9d2d1ac18b2f44f99bb`;checkpointelapsed5208.127598s. Lastmetrics5350elapsed5271.257472s;post-checkpointstepswillbereplayed. Conservative cumulativebudgetledger5294.819912s chargesallworkincludingloststeps/import/shutdown. No model/source/recipe change. Resume fromthisspecificsnapshot to8000after large GPU replay and contrastive work finish; rootlast.ckpt maystillbeolder and mustnotbeused. Whole research remains active. New scheduling separates the large nativefit from contrastive/inference GPU workloads. + + +## E031 — add objective/source diversity to the best inverse ensemble (prepared) +- After E026, compare E027control; addE007; addE026; addE023; addE026+E023; addallthree. Each uses equal mean probabilities and frozen training-IDF/mass coefficient.05; no learned weights. These fixed sets test whether contrastive objectives or real-data sampling complement the two masked seeds. Full validation/molecule uncertainty, then replay for any improved candidate. E026's originally planned single/replacement/E022-plus comparisons will also be retained. + +## E032 — additional experimental peaks with synthetic truncation retained (prepared) +- Hypothesis: more real fragment evidence can help while synthetic diffuse peaks remain suppressed. Change only effective experimental peak cap from10to32 relative to E017; set modelmax_peaks32 and synthetic_peaks10,so synthetic input remains its top10. Randomseed1,40×1200steps,batch512,real_fraction.25,syntheticCEmasking.5,lr.0003,other architecture/objective unchanged. +- After E026 and its scoring, train this small encoder alongside native inference, keeping the large E003fit rescheduled. Compare calibratedsingle,replaceE004inE027,andaddasfifthmember. Full validation selection and molecule uncertainty; no new fitted calibration. + + +## E033 — reduce experimental oversampling (prepared, later scheduling window) +- E023 real_fraction.50 doubled experimental exposure fromabout32to63passes and reduced simulated coverage,hurting standalone retrieval. Hypothesis: real_fraction.10 improves held-out-structure generalization through greater simulated chemical diversity while synthetic energy masking preserves realistic missingness. Change only fraction.25→.10 versusE017;seed1,40×1200steps,batch512,max10,syntheticCEmasking.5,lr.0003,fromscratch. +- Compare calibratedsingle,replaceE017inE027,andaddfifthmember,with frozen training calibration. Run only after large E003fit reaches8000or during a safe inference window,not concurrently with the large fit. Compute/results pending. + + +E025 top64 conditional screen COMPLETE:uniform.5/.5 gives.47167969/.67871094/.796875;known-proton.5/other.25 gives.48632813/.67285156/.80078125;known-proton.5/other0 gives.48242188/.66210938/.796875. Select other.25 by subsetHit@1; this remains a subset result using E018 and native4000,not a full-validation or test result. The best top20/top64 conditional choices differ,so comparisons between their selected rules combine shortlist and rule changes. A full native4000/top64 conditional replay is a later GPU scheduling candidate. + + +E008 full MCES COMPLETE13.366333830871 on19,429queries;7,826unique pairs,5,454newpairs,5679.476428s with2CPUworkers,officialexactsettings. This updates the secondary metric of the earlier64peak+IDF model; selection remains the later nativehybrid. +E029 branch diagnosis versusE027:known-energy-proton Hit@1.68091227vs.62718307,gain+.05372920,95%molecule-CI[.03845800,.06950437] on9,734queries/2,334groups;other9,695queries remainexactlyE027 at.27756576. This confirms the composed rule's intended behavior; full-runtime replay still pending. + + +## E034 — calibrated precursor evidence within native ranking +- Hypothesis: native entropy ranks lose useful precursor-error confidence; a small training-only mass likelihood term before rank fusion may reduce incompatible-formula competitors. On the exact E024top64/step4000fixedsubset,compare native score−entropy+lambda×frozenE018precursorloglikelihood forlambda[0,.005,.01,.05],then nativeRRFweight[.5,1],offset10. BaselineE018shortlist/remainingorder unchanged; unsupportedcandidates retainneutralbaselinerank. +- Reuse the exact cached E024generatedspectra for identical staged queries/candidates/conditions,no remapping. Lambda0 must reproduce E024rankings exactly. No parameters fitted; no truequeryformula used. Fullvalidation and independentpackagereplay required beforepublication. + + +E026 corrected-schedule run COMPLETE690.948666s,peakallocated13,440,710,656bytes;failedfirstattempt14.518228s separatelycharged. Epoch4 selectedraw.305419733388/.478408564517/.639147665860,checkpointSHAce0f03cfdc7b2600376e9c7d676aa4f3529c2f7dac2cacd49a23d77a14dc38c7. Originalcalibratedfamily9.324957s:single.38643265vsE007.38658706,replacementE022.44366668vs.44418138,addingbothfine-tunedencoders.43949766. No standalone objective-alignment benefit established. +E031 diversityfamily9.337930s:controlE027.45272531;addE007.45380617;addE026.45370323;addE023.45540172;addE026+E023.45627670/.63976530/.78182099;addallthree.45457821. Select the six-member E004/E009/E017/E021/E023/E026 point estimate for furthercomponentverification. Fixed-condition composed evaluation2.009142s gives.48283494/.66833085/.77868135,deltaoverE029+.00319111,95%molecule-CI[.00033945,.00627948]. Thiscombinationgain does not establish an IDFcontrastive-training benefit. An additional attributioncontrol compares oldE007+E023 againstE026+E023 under the same six-member structure. +E032 experimental32/synthetic10 training hasstarted automatically aftertheseE026/E031scores. E003largefit remains rescheduled until smallfitting/scoring and E029nativeGPU inference finish. + + +E034 COMPLETE:exactzero-mass controls reproduce all E024rankings. Native-only addition of mass raisesHit@1.42480469→.4453125 atlambda.01,but hybridRRF.5 remains strongest atlambda0:.47167969/.67871094/.796875. Positive lambdas[.005,.01,.05] givehybridHit@1[.46972656,.46484375,.44921875];retainunchangednativeentropy. Cached-scoreevaluation140.510738s,CPU-only,identicalquery/candidate/condition predictions. The inverse ranking already includes precursor evidence; this result doesnot establish that adding it twice helps. No runtime/modelchange. +Resource diagnosis clarification:the OOM log measures67GiB totalmemoryuse bynativeprocess; the exact split between active batch tensors and reserved allocator memory wasnot separatelycaptured. Scheduling uses the observed footprint,without claiming an unmeasured allocator cause. + + +E031 additional attribution comparison COMPLETE8.965414s:oldE007+E023six-memberensemble.457254619383/.640074116012/.781872458696 beats E026+E023six.45627670/.63976530/.78182099 bypointestimate. Under unchangedE029publicconditioncomposition,oldCF+real yields.483092284729/.668433784549/.778784291523,deltaoverE029+.00344845,95%molecule-CI[.00054013,.00665180];IDF-CF+real yields.48283494. The IDFcontrastivechange isnotselected; retain its negative results. + +## E035 — six-member inverse component +- Select additional E031attribution rule E004/E007/E009/E017/E021/E023 usingequalmeanprobabilities and frozen E018calibration. This is an additional comparison following the initial family,explicitly recorded; no fitted weights. Preserveallselectedtraininglineages. Independentreplay/probes/MCES pending. Candidate for improving the inverse branch of E029; current published package remains E015 until stronger verified composition is ready. + + +## E036 — continuous score fusion on the fixed top64 screen +- Hypothesis: calibrated inverse cosine/mass scores and native entropy similarities retain confidence margins that rank fusion discards. Compare fixed native coefficients[0,.1,.25,.5,1,2],sameE018inverse,step4000native,top64candidateinputs,and1024queryhash84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e. Unsupportednativecandidatesreceivezeroextracontribution; inversetailunchanged. No fitting. Zero uses exact baseline; independently checkCPUinverse-scoreordering against packagedbaseline and preserveanyroundingdifferences. Save model-derived rawscores for identical-input research only,neverpackageassets. Fullvalidation/replay required beforepublication. + +E035 full relocated replay COMPLETE114.295734s,RSS10,649,985,024bytes;all19,429valid and exactscreenhitmetrics .457254619383/.640074116012/.781872458696. Unseen/order/packageimmutabilityprobes19.024052s passed. MCES9.556333316177;pairedvsE027−.125096505224,95%molecule-CI[−.214510594149,−.034071065873],148newpairs113.541414s2workers. Candidate improves E027inverse,while standaloneprimaryremains slightlybelowE015; use as potentialcondition-hybridcomponent. +E029 composed MCES COMPLETE9.038216068763,6,178pairs/96new798.181942s2workers. End-to-end replay remains authoritative and isstillpending. + + +## E037 — native spectral metric/intensity comparison +- Hypothesis:cosine-trainednativeintensities mayrank better withcosineororiginal-intensityscoring. ExactE024step4000/top64/1024inputcache; compareentropyandcosine withsqrt-intensity orrestoredoriginalintensities. EachusesfixeduniformRRF.5andpreviousE025publiccondition.5/.25;noadditionalweightsearch/fitting. Entropysqrtcontrols mustexactlyreproduceE024andE025. Preserverawdistancesforidentical-inputresearch. Fullvalidation/replay required beforepublication. + + +## E038 — replace/add the wider-peak encoder in E035 +- Fixed equal ensembles: controlE035;replaceE004byE032;addE032. PlannedafterobservingrawE032improvement,beforeviewingthisensemblecomparison. No fitting. Native-resume driver waited11.740853s for scoring,withongoingCPUreplay; resumedautomatically. + +## E039 — full-validation transfer of continuous fusion +- Transfer E036selectednativecoefficient1 toexistingE029known-energy-protonbranch,keepingE003step2000/E014top20inputs/otherE027branchfixed. ReuseexactE029forwardpredictions,notrekeyed; reconstructRRFcontrolandrequireallranksexact againstfullE029replay. No fitting/additionalcoefficientsearch. Full19,429validationselection andmoleculegroupuncertainty; runtimeverificationrequiredbeforepublication. + + +E032 completed: 804.328503 seconds, peak CUDA allocation 9,653,676,032 bytes, seed 1, selected epoch 38. Raw Hit@1/5/20 = .352823099490/.521591435483/.674764527254; SHA256 7ffcaea9641c049f2f710030e9fd0f931054a553cb3220054be8fc5cd7f8b8ca. Calibrated single = .41875547; replacement in E027 = .45735756; adding a fifth member = .46214422/.64285347/.78547532. Five-member gain versus E027 .00941891, molecule CI [.00617547,.01270078]. Scoring took 7.890546 seconds. + +E038 completed: replacing E004 in E035 with E032 gives .464151526069/.644088733337/.783519481188; gain .006896906686, molecule CI [.002935439462,.010690458586]. Adding E032 gives .462298625766/.644603427866/.784394461887. Select replacement by primary Hit@1. Scoring took 7.679218 seconds; both E032/E038 scoring jobs preceded large native training, despite the generic scorer’s stale overlap description. Model weights and calibration were fixed. + +E036 completed: fixed native coefficients [0,.1,.25,.5,1,2] gave screen Hit@1 [.4296875,.46582031,.49609375,.52148438,.54394531,.54296875]. Select coefficient 1: Hit@5 .693359375, Hit@20 .806640625. CPU scoring took 188.743023 seconds, external process 191.010128 seconds. CPU inverse recomputation differed in three lower-order rankings from the GPU replay, with no top-1 differences and one top64 ordering difference; recorded explicitly. Zero control uses the exact baseline. This is a 1024-query screen, not full validation or test evidence. Fixed-coefficient transfer to E029 is E039. + +E037 completed negative: entropy on square-root intensities remains best. Uniform/public-condition Hit@1: entropy sqrt .47167969/.48632813; entropy original .44628906/.45703125; cosine sqrt .44726563/.46386719; cosine original .4140625/.43457031. Both entropy-sqrt controls exactly reproduce E024/E025. CPU scoring 144.562353 seconds. No runtime metric change selected. + +E039 first attempt failed after 48.925095 seconds in development mass calculation on invalid candidate SMILES. Source/log/timing preserved; corrected to NaN mass and neutral likelihood, matching the existing packaged inverse. No fitted weights changed. Corrected full-analysis run started. + +## E040 — wider-peak replacement inverse package +Select E038 replacement E032/E007/E009/E017/E021/E023, equal probabilities and frozen training-only IDF/mass calibration. Derived checkpoint SHA256 95a9f513278f9b854ceb5f516486a33237b98a1763f71bc764b124a383eae1b1. Preserve E004 training lineage as E007 task-trained initialization even though it is no longer a direct voting member. Independent relocated replay, arbitrary-query/order probes, and MCES follow. + +E029 full relocated replay PASSED: 1833.537362 seconds, peak summed RSS16,749,576,192 bytes, all19,429valid. Authoritative Hit@1/5/20 = .479695300839/.666272067528/.780637191827; gain over publishedE015 .022286273097,95%moleculeCI[.010538643735,.033746547174]. Actual runtime differs from separately composed ranks on2598complete permutations and44top predictions; branch attribution is recorded. The actual replay, not the composed approximation, determines selection. Unseen/order/immutability probes already passed135.549754s. Refreshing MCES for changed actual predictions. Atomically promote after runtime-asset equality to the independently replayed generation. + +E029 atomically published with all209runtime assets byte-identical to the replayed generation; primary checkpoint remains e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369 and inverse a836e8e99ce5676c5116c9f62234d8d74e75ab860af43dc7b4cc73c8edce054d. Actual replay MCES9.039863091255 (14newpairs/14.098211seconds). The44top changes versus component composition all arise in the known-proton branch; the inverse branch has only2lower-order differences and no top-1 changes. Current selection uses actual replay metrics. + + +## E041 — portable continuous-score conditional hybrid +Prepare a fixed package using E039 native2000/E014top20 continuous similarity coefficient1 for known-energy protons, and verified E040 inverse weights otherwise. This combines two independently evaluated changes; E039 isolates fusion. Internal score sidecars are computed only from current inputs inside an owned temporary directory and removed at completion. No external cache or query fitting. Publish only after full selection and package replay. + + +## E042 — second seed of the wider-peak encoder +Repeat E032 with seed2 only; all other architecture, training mixture,40×1200steps and masking settings unchanged. Evaluate single, replace E032 in E040, and add as a seventh equal member, using frozen training-only calibration. Run after E033 and while large native fitting is checkpointed. E033 lower-experimental-fraction training has started. Native6000 preserved with SHA2564d0fb6ac154f03690d87467c703d05e87c0df17aa907e8a4859477271b5ee372; checkpointelapsed5930.422737s and conservative cumulative ledger5950.910453s. Validation5908loss.584782302380. + + +E039 corrected full analysis completed: RRF control exactly reproduces every E029 ranking. Fixed continuous coefficient1 gives Hit@1/5/20 .510834319831/.667455864944/.780637191827, gain .031139018992, molecule CI [.025991188375,.036648383902]. CPU analysis305.747798s, external309.808768s; failed48.925095s separately preserved. Recomputed inverse scores have31 lower-order differences and zero top1 changes relative to packaged GPU baseline; actual package replay will be authoritative. + +E040 fully verified: relocated replay108.260723s, RSS10,661,572,608bytes, unseen/order/immutability probes18.539235s; exact Hit@1/5/20 .464151526069/.644088733337/.783519481188. MCES9.385042976993, paired versusE035−.171290339184, molecule CI[−.268217831794,−.073235187374],196newpairs237.988240s2workers. + +E041 composed selection gives .516393020742/.671367543363/.779968088939; Hit1 gain overE029 .036697719903, molecule CI[.030773143460,.042972008107]. Component-based development selection pending independent package replay. First runtime probe failed because baseline launcher dropped optional internal score arguments; corrected launcher forwards all arguments. The premature probe before build completion is separately recorded. No weights changed or failed model promoted. Failed runtime native simulation1.867344s; full failed wall time was not directly captured,296.968868s is a conservative log-birth-to-archival upper bound including idle diagnosis and slow archive copy. Subsequent probes use the external timing wrapper. + +E002 MCES completed:16.865947809975,9461pairs/9405new,9503.114812s2workers. Earlier primary metrics unchanged. + + +## E043 — larger molecular neighborhoods in the inverse target +Change only Morgan fingerprint radius2 to3,keeping4096bits and E032 experimental32/synthetic10 model/recipe,seed1. Prepare deterministic candidate/train/synthetic fingerprints without changing spectral inputs or label indices. New IDF uses unique experimental training structures only; precursor calibration stays frozen. No averaging across incompatible fingerprint coordinate systems. CPU preparation starts now; fitting is scheduled for a later safe GPU window after native8000 or explicit rescheduling. +E041 corrected relocated probes passed140.282452s (external140.318174s); full replay started after native6000 checkpoint and shutdown. + + +## E044 — stronger inverse scores with fixed native coverage +Compare E036 exact continuous1 control with E040 inverse scores,holding E018top64 shortlist/tail,native4000 predictions and coefficient1 fixed. This isolates scoring under the same simulator coverage; it does not test a new E040 shortlist. No fitting; fixed1024subset then fullverification if useful. + +E043 fingerprint preparation complete68.289470s (external69.003930s),10CPUworkers. Train25,046,validation3,386,candidate828,117,clean-synthetic435,076molecules; all spectral inputs and row/label indices retained unchanged. Fingerprint file hashes and source manifests are recorded. No fitting yet. + +E033 lower-real-fraction training completed558.500856s,peakCUDA9,255,556,096bytes,seed1; selected epoch31 rawHit1 .343404189613,checkpointSHA5f7ceeb8c23c2b06a730741f1da0698092f5a734230a8067251da5355f5899d2. Calibrated replacement inE027 .458026661177/.642750527562/.787894384683; adding fifth .459879561480/.643625508261/.790210510062. Five gain overE027+.007154253950,CI[.004037911401,.010516443428],scoring7.657642s. Below E040 primary,so no standalonepromotion. E042 seed2 wider-peak training has started. +E044 fixed-coverage stronger-inverse comparison completed8.488117sCPU: E018control EXACT .5439453125/.693359375/.806640625; E040scores .5546875/.7041015625/.8115234375. Hit1 gain .0107421875,moleculeCI[−.001957187692,.023414808008] crosseszero. SameE018top64simulatorcoverage/native4000; no claim that new E040shortlisting is tested. Promising for later full candidate,not published. + + +## E045 — all-condition top64 continuous-fusion candidate (preparation) +Stage fixed E040top64 candidates for every usable public condition, with no labels, to measure simulation load. This candidate family combines wider coverage, stronger inverse scores and native evidence outside the known-energy-proton branch. Native4000 has supporting subset results; later6000/8000 checkpoints require their own retrieval screen before full-replay selection. No model is published from this preparation alone. + +E041 composed MCES completed8.382701116887,5774pairs/339new,779.870035s2workers. Fullruntime replay remains pending. +E043 validation representation diagnosis: exact fingerprint-and-exact-mass competitors affect272queries with radius2 versus92withradius3; tie set shrinks on205queries and never grows. Counts only diagnose representation limits and do not predict trained retrieval gains. Exact-mass analysis3.706628s; earlier near-mass tolerance analysis retained separately (6.021980s external) and superseded for strict tie claims. No fitting or runtime answers were encoded. + + +## E046 — combine source-fraction and seed diversity +Fixed equal ensembles: E040control;addE033 lower-real-fraction member;addE042 second wider-peak seed;addboth;replace E023real.5 with E033real.1 while adding E042. Compare all full-validation metrics and molecule-group uncertainty. Defined before inspecting E042 ensemble results; generation timestamps are recorded separately in plan.json. No fitting. The pending native-resume shell is temporarily held until this short family completes, with automatic resume in a finally block. + +E042 seed2 wider-peak fit completed797.048802s,peak9,653,676,032bytes,selectedepoch40raw .356580369551/.529105975603/.684234906583,SHA4448ab7a55cb304071a442b7ddd970851c211b975a2adefd3fe2d92b53619807. Calibrated single .42488033;replace E032 inE040 .46389418;addseed .467805857224/.649801842606/.789078182099,delta+.003654331154CI[.000616724186,.006837367729]. Scoring8.541588680818677s. +E046 family completed8.314853356219828s: control.46415153;addlower-real.46713675;addsecondseed.46780586;addboth .470173452056/.653147357044/.793453085594;replaceE023withE033andaddseed .46991610/.65325030/.79515158. Select both by primary. GainvsE040+.006021925987CI[.002341792691,.009720839474]. Training/calibration fixed; plan records generation/inspection timing. Large native-resume shell was automatically released after scoring. +E045 exact public top64 staging requires674,875candidate simulations across19,429queries,125.420322s preparation. Linear scaling from E029 predicts5931.925GPU seconds; this is planning only and does not establish full runtime. +E015 MCES completed9.644037263884;pairedvsE022−.277137269031,CI[−.663706006646,.110747722877],1814newpairs4078.282604s2workers. This fills the historical secondary metric; current root remains stronger E029. + +## E047 — eight-member inverse component +Select E046both: E032/E007/E009/E017/E021/E023/E042/E033, fixed equal probabilities and unchanged training-only IDF/precursor mixture. Independent relocated full replay, contract probes and MCES follow. Preserve E004 as E007 task-training initialization lineage. + +E041 actual full relocated replay completed: {"composition_check": {"complete_ranking_differences": 2, "note": "actual end-to-end replay is authoritative; cached CPU inverse and batch-dependent native predictions can have numerical differences", "queries": 19429, "top_one_differences": 0}, "metrics": {"hit_rate_at_1": 0.5163930207421895, "hit_rate_at_20": 0.7799680889392145, "hit_rate_at_5": 0.6713675433630141, "mces_at_1": 8.382701116887127}, "paired_delta_vs_E029": {"confidence": 0.95, "estimate": 0.036697719903237426, "grouping": "supplied target_inchikey connectivity block", "lower": 0.03077314346017011, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.04297200810663419}, "peak_rss_bytes": 16826572800, "replay_seconds": 1539.617059001699}. Select actual replay and atomically promote only after runtime-asset equality to the verified generation. + + +## E048 — replace the inverse branch with E047 +Keep E041continuous native branch and public routing unchanged; substitute E047eight-member inverse for other conditions. Independently replay the new inverse on its exact public partition. Reuse the already verified native branch only after exact input-hash equality, all native runtime-asset equality and parent-code equality; configuration may differ only in the inverse checkpoint hash. Officially score the complete composed rankings and run relocated end-to-end arbitrary-input/order/immutability probes. This is component-based full-validation verification, not a repeated full native GPU replay; report the distinction and a conservative measured component runtime sum. No fitting. + +E041 atomically published after full replay and all210runtime assets verified byte-identical to the tested generation. Actual metrics .516393020742/.671367543363/.779968088939,MCES8.382701116887;1539.617059s,peakRSS16,826,572,800bytes. Only2lower-order ranking differences versus component analysis,zero top1 differences. Publication-record.json identifies the selected immutable generation. Research continues. + +E047 complete relocated validation: {"checkpoint_sha256": "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "delta_vs_E040": {"confidence": 0.95, "estimate": 0.006021925986926759, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0023417926905038608, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.00972083947417943}, "metrics": {"hit_rate_at_1": 0.47017345205620464, "hit_rate_at_20": 0.7934530855937001, "hit_rate_at_5": 0.6531473570435946, "mces_at_1": 9.201219826033249}, "probe_seconds": 17.909732793923467, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "replay_seconds": 97.21025992929935, "rss_bytes": 11440472064}. All probes passed. Best inverse component; primary remains E041 pending E048 branch-combination validation. Source/configuration/logs archived in research/E047-completed and lineage preserved in component package. + +E048 component-based full validation completed: {"checkpoint_sha256": "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "conservative_component_wall_sum": 1584.7063106442802, "metrics": {"hit_rate_at_1": 0.5181429821400999, "hit_rate_at_20": 0.7882546708528488, "hit_rate_at_5": 0.676823305368264, "mces_at_1": 8.276776982860673}, "paired_delta_vs_E041": {"confidence": 0.95, "estimate": 0.0017499613979103403, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0011288682151963936, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.004648510340562341}, "probe_wall_seconds": 136.13644129224122, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": {"configuration_changes": {"inverse_checkpoint_sha256": ["95a9f513278f9b854ceb5f516486a33237b98a1763f71bc764b124a383eae1b1", "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec"]}, "native_asset_files": 190, "native_input_hashes_equal": true, "parent_inference_source_equal": true, "unchanged_native_runtime_assets": true, "verification_kind": "changed inverse branch replay plus unchanged native branch reuse from E041fullreplay and end-to-end arbitrary-input probes"}}. Selection uses validation Hit@1; uncertainty includes zero. No new full native GPU replay: identical native component and exact public partition reuse the E041 actual replay; changed inverse branch is independently replayed and complete combined rankings officially scored. Atomic publication follows byte-equality to the probed package. + +E049 prepared fixed checkpoint screen: {"baseline_control": "Reconstruct E044new_E040 complete rankings exactly before later checkpoints.", "candidate_tsv_sha256": "0c5b6aea5fa736d8f1b17e9970818216cf44c1fd0bd65566ff657168250bcc6f", "changed_factor": "native optimizer step4000 versus6000 versus8000, seed1 and frozen training recipe unchanged", "created_utc": "2026-10-21T07:49:37.938115+00:00", "full_training_source_sha256": "df6c44d0ca2561aa246e3855f75caf3a52d13d2fb38e42cf503ba8c76b23f0a3", "hypothesis": "More train-only native optimization improves retrieval under fixed inverse scores and candidate coverage.", "molecule_groups": 668, "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "schedule": "Wait native8000 training and process exit; sequential native batch32 simulations may share soleH100 with E043smallfit using .16memorycap; no overlap with large native fitting.", "selection": "maximum Hit@1 over fixed three-checkpoint family; secondary hitrates and molecule-group uncertainty reported", "selection_queries": 1024, "unchanged": "E040 six-member inverse scores, E018top64 shortlist/tail, continuous native coefficient1, entropy-sqrt, batch32 prediction and exact candidate TSV"}. No scores yet for6000/8000; unchanged4000 exact-control first. + +E048 atomic promotion completed: selected rootgeneration-tcu6j6n5, runtime210assets byteequal to probed generation-kgboan_i after audit refresh. Publication-record.json records component-based validation and full metrics. E049 exact4000 control reconstructed all E044rankings; scores .5546875/.7041015625/.8115234375. Preparation9.6267905s/external12.9636108s; control14.0838185s/external15.9799265s. E049 checkpoint6000/8000screen queued after native8000training exit; no latercheckpointretrievalresults yet. + +E050 prepared fixed mixed-radius candidate-score family before radius3fitresults: {"changed_factor": "E047radius2 score mixed with E043radius3 score; no incompatible fingerprint coordinates are averaged", "controls": "zero exactly reproduces E047savedranks; one exactly reproduces E043idf_mass ranks; each source TF32setting matched explicitly", "created_utc": "2026-10-21T07:53:15.499032+00:00", "fixed_family_radius3_weights": [0, 0.125, 0.25, 0.5, 1], "hypothesis": "Larger Morgan neighborhoods may complement local radius2 predictions when fused as candidate scores.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "schedule": "wait E043fit and score complete; may overlap E049nativebatch32 onsoleH100; scoringGPUcap0.20", "seed": "member training seeds preserved; molecule bootstrapseed0", "selection": "validationHit@1, secondary hits and molecule-group confidence interval; no fittedensembleweights", "unchanged": "Both IDF calibrations use experimental training molecules only; mass calibration E016mixture and coefficient0.05 once; all network weights frozen"}. No fitting or query-specific parameters. + +E048 validation-only failure diagnosis completed: sparse <=5positivepeaks/missingCE Hit1.17922171 versus >32peaks/missingCE .44595300. KnownH .74316828, missingH .34368697, knownNa .23236515, missingNa .23865658. E048vsE041147corrected/113regressed. MoleculeunweightedHit1 .67741256; largest10groups1581queries/1280misses account13.6723%ofallmisses. Diagnosis3.634328588s internal/external5.074839310s. No query-specific inference rules. Motivates syntheticpeakcountaugmentation and broader nativecoverage. + +E051 prepared synthetic peak-count augmentation: {"baseline": "E03232experimental/10synthetic,seed1,real_fraction0.25,CEdrop0.5,40epochs*1200steps*512,lr0.0003", "calibration": "unchanged train-only E016IDF/mass coefficient0.05", "changed_factor": "On50percent of synthetic training examples retain a uniformly drawn1..10 strongest peaks; remaining synthetic examples retain10; experimental spectra unchanged", "created_utc": "2026-10-21T07:54:25.235731+00:00", "fixed_postscore_family": ["E047control", "singleE051", "replaceE032byE051inE047", "addE051toE047"], "hypothesis": "Sparse missing-energy spectra are weak; randomly reducing synthetic peak counts may improve robustness to incomplete experimental fragmentation.", "labels": "experimentaltrain and held-out-clean supplied synthetic only; validationretrieval checkpointselection", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "rng": "separate seed+27000generator; CEaugmentation stream and model/batch RNG remain unchanged", "scheduling": "afterE043andE050 complete; may shareGPU withE049batch32nativeinference, neverlargeE003fit", "synthetic_order_check": {"descending_intensity": true, "sampled_valid_rows": 4102, "strongest_positive": true}}. Training is queued behind earlier scientific comparisons. + +E052 prepared fixed native inference-throughput comparison: {"changed_factor": "native inference batch32 versus128; batch64 only if128 fails capacity", "checkpoint_selection": "E049fixed family selected by validationHit1, then frozen for all batchsizes", "created_utc": "2026-10-21T07:56:57.389835+00:00", "hypothesis": "Larger native inference batches can reduce full top64simulation cost within oneH100 limits.", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "schedule": "waitE049complete; no large native fitting; may share soleH100withE051smalltraining; processallocatorcap0.65,smallfitcap0.16", "selection": "among successful batches without lower Hit1 than freshbatch32, choose lower measured prediction walltime; independent full package replay remains required", "unchanged": "E049exact1024queries,candidates.tsv,E040inverse,E018top64coverage,coefficient1,allweightsandnativecode", "verification": "both batches produce fullscreen rankings; report numericalchanges and molecule-group uncertainty"}. All failed executions retained; no training changes. + +E003native8000stage completed: {"continuation": "same frozen source and resumed optimizer/sampler/RNG from explicitstep6000 snapshot; no validation fitting", "publication": "only native work-package auto-exported; root model unchanged pending retrieval", "result": {"data_manifest_sha256": "ca938de9bab1e4208ce258419556b9f173d234267e020118969636f52ca444de", "elapsed_seconds": 7328.420031986665, "global_step": 8000, "hardware": "NVIDIA H100 80GB HBM3", "last_validation_loss": 0.5811559557914734, "peak_cuda_allocated_bytes": 42273342976, "selected_checkpoint": "/run-state/workspace/research/E003/full-b128/checkpoints/best.ckpt", "selected_on": "validation spectrum loss; retrieval must be measured separately", "source_sha256": "df6c44d0ca2561aa246e3855f75caf3a52d13d2fb38e42cf503ba8c76b23f0a3", "validation_loss": 0.5811559557914734}, "source_checkpoint_path": "/workspace/research/E003/full-b128/milestones/step-8000.ckpt", "source_checkpoint_sha256": "63af6576ca7ed0010f8394de3cf9adb3302f46d1f0b4c526c94c367a520d65f3", "training_seed": 1}. Cumulativechargedtime7328.420032s including finalization; peakallocated42,273,342,976bytes. E043radius3fit and E049fixedcheckpoint retrievalscreen nowstarted; no furtherlargefit until current smallfit/inferencequeue completes. + +E049 secondaryMCES queue added before6000/8000retrievalresults: exact officialsubset MCES for4000/6000/8000,2CPUworkers,sharedexactpaircache. Primaryselectionunchanged; results recorded separately inE049/mces-results.json. + +E053 prepared future all-conditiontop64continuous-fusion package with fixedE047inverse: {"comparison": "publishedE048 on all19429validationqueries with molecule-group uncertainty; full relocated package replay and MCES required before promotion", "condition_coverage": "all public adduct/energy/instrument conditions with structural/peak support; unsupported cases retain inverse fallback", "created_utc": "2026-10-21T08:01:17.937923+00:00", "current_action": "public-input staging and simulation-count planning only; no native inference until selections complete", "fixed_inverse": "E047eight-member,checkpoint4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "hypothesis": "The stronger inverse shortlist and later task-trained native simulator can improve every public condition through continuous-score reranking at top64.", "inference_batch": "pending fixedE052throughput/accuracy check", "native_checkpoint": "pending fixedE0494000/6000/8000 screen selection", "native_coefficient": 1, "replaces_staging_experiment": "E045 usedE040baseline; retained separately as a count-only planning experiment", "top_k": 64}. Nativeweight/batch choices pending existing fixed screens; only public-input staging starts now. E045E040stage remains separate, not silently reused for a different baseline. + +E051 pretrainingpostscore extension: {"created_utc": "2026-10-21T08:02:47.425276+00:00", "reason": "sparse missingCE failure analysis and syntheticaugmentationmax10 motivate one fixed global public condition rule", "rule": "E047+E051equalprobabilityensemble only for missingCE and<=10positiveintensities; E047otherwise", "status": "defined before E051training or retrieval results"}. Singlemodel sparse/remaining strata compareE032 to isolate augmentation; fixedconditionalmodel is an additional validation selection option. + +E053 full-verification driver prepared and queued: waitsE052checkpoint/batchselection andE051postscore/trainerexit, then fixed nativeexport+E047top64continuous1 package, relocation, end-to-endprobes, independent fullreplay, officialHit1/5/20+groupCI, MCES. Fullreplay measuresCPU RSS/time and ownedTMPDIR/output storage; checks18000s/64GiB/50GiB. No automatic rootpromotion before finalscientificselection/audit. + +E053 public staging completed122.595560s/external123.341180s:674264candidate-condition simulations acrossall19429queries usingE047. Count-based extrapolation5926.55GPUseconds is planning only, not actualruntime. +E052 allocator wrapper corrected before execution to apply the cap only when the native model moves toCUDA, after CPUDataLoaderworkers fork; this preserves the pinned native loader ordering. No weights, math, data or measuredresultchanged. + +E052 pre-execution resource schedule update: {"change": "GPU predictions remain sequential; evaluate completedbatch onCPU while nextbatch predicts, then join evaluations before selection", "completed_experiment_work_before_change": false, "original_driver": "run-initial-sequential.py", "previous_driver_had_no_children": true, "previous_waiting_driver_pid": 30079, "reason": "avoid GPU idle interval during independent CPU entropy evaluation", "unchanged": "models,data,checkpointfamily,batchfamily,metrics,rankingmath,selectionrule", "utc": "2026-10-21T08:08:50.889839+00:00"}. No scientificrunfailed or measuredresultdiscarded. +E049 public candidatekeyaudit10.587334s/external11.076522s,4CPUworkers:25duplicate native InChiKeygroups contain51candidate rows with distinct canonicalSMILES, across23conditions in55556inputrows. No labelsread or inferencemutation. This identifies a possible candidate-key collision issue for a later isolated experiment; currentfixedreplaysunchanged. + +E0496000 fixedscreen NEGATIVE: {"factor": "native checkpoint only; inverse E040, shortlist/tail E018top64, native coefficient1 fixed", "fitting": "none in evaluation; native trained on training fold only", "inverse_score_sha256": "08d3c51f26b8552fce82158c021d01dccdc801c72a9d4da08ca5913022d1de05", "metrics": {"hit_rate_at_1": 0.5361328125, "hit_rate_at_20": 0.810546875, "hit_rate_at_5": 0.6943359375}, "native_checkpoint_sha256": "7f6c3108fee735d862962a66e1357760442f29f014d5324bc7af15f1abca8b02", "paired_delta_vs_step4000": {"confidence": 0.95, "estimate": -0.0185546875, "grouping": "supplied target_inchikey connectivity block", "lower": -0.034318919262088965, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0020366080807536677}, "prediction_sha256": "bfa9520cfd14630be11f20e04aa65b34ed96579d90ac6e5ae4d0293dcde8938d", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "wall_seconds": 109.85500700725242}. Prediction510.218836s, CPUevaluation109.855007s/external111.456391s; nativeexport7f6c3108fee735d862962a66e1357760442f29f014d5324bc7af15f1abca8b02. Hit1falls1.85547pointswithmoleculeCIbelowzero despite lower spectrumloss. Step8000screen continues; no furthernativefitting currentlyqueued. Control4000MCES7.2451171875,86newpairs352.406969s2workers. + +E043 radius3 trainingcompleted768.037447s, peakCUDA9,653,676,032bytes, seed1,epoch37 selected. RawHit1/5/20 .360337639611/.528642750528/.682587884091; checkpoint0e826bbf817eae6d5fa8211a9602b4ac5b75b4da4d9bcc5b03646f521d7d2194. Fixedcalibratedscore{"calibration": "radius3 IDF from unique experimental training molecules; unchanged E016 precursor mixture and fixed coefficient0.05", "checkpoint_sha256": "0e826bbf817eae6d5fa8211a9602b4ac5b75b4da4d9bcc5b03646f521d7d2194", "fitting": "no validation fitting", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"idf_mass": {"hit_rate_at_1": 0.4279170312419579, "hit_rate_at_20": 0.7540789541407175, "hit_rate_at_5": 0.6104277111534304, "paired_delta_vs_E032_matching_rule": {"confidence": 0.95, "estimate": 0.009161562612589429, "grouping": "supplied target_inchikey connectivity block", "lower": -5.6164317218957414e-05, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.018707676076592506}}, "raw": {"hit_rate_at_1": 0.36033763961089094, "hit_rate_at_20": 0.6825878840907921, "hit_rate_at_5": 0.5286427505275619, "paired_delta_vs_E032_matching_rule": {"confidence": 0.95, "estimate": 0.0075145401204385195, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0022048491350484833, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.017696264546879295}}}, "wall_seconds": 6.816029710229486}. +E050 fixed mixed-radiusfamilycompleted: {"fitting": "none; fixed candidate-score weights, validation model selection only", "formula": "(1-alpha)*E047radius2_IDFcosine + alpha*E043radius3_IDFcosine + fixed0.05train_mass_likelihood", "max_cuda_allocated": 8533967360, "overlap": "oneH100 may share E049batch32native simulation; waits E043fit and single-modelscore to finish", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "radius2_checkpoint_sha256": "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "radius3_checkpoint_sha256": "0e826bbf817eae6d5fa8211a9602b4ac5b75b4da4d9bcc5b03646f521d7d2194", "results": {"0.0": {"hit_rate_at_1": 0.47017345205620464, "hit_rate_at_20": 0.7934530855937001, "hit_rate_at_5": 0.6531473570435946, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "0.125": {"hit_rate_at_1": 0.47506305007977767, "hit_rate_at_20": 0.793298677235061, "hit_rate_at_5": 0.6542282155540686, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.004889598023573009, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0016016934946936467, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.008956275820112488}}, "0.25": {"hit_rate_at_1": 0.4761953780431314, "hit_rate_at_20": 0.792578104894745, "hit_rate_at_5": 0.6539193988367904, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.006021925986926759, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0014786732353629624, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.010820159038317375}}, "0.5": {"hit_rate_at_1": 0.47007051315044523, "hit_rate_at_20": 0.7897987544392403, "hit_rate_at_5": 0.6494930258891348, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": -0.00010293890575943178, "grouping": "supplied target_inchikey connectivity block", "lower": -0.00626833797046343, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.005968667558201503}}, "1.0": {"hit_rate_at_1": 0.4279170312419579, "hit_rate_at_20": 0.7540789541407175, "hit_rate_at_5": 0.6104277111534304, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": -0.04225642081424674, "grouping": "supplied target_inchikey connectivity block", "lower": -0.052750819481318746, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.032182327117425774}}}, "selected": "0.25", "wall_seconds": 13.929276458919048}. Selectalpha.25 for packaging/independentreplay; endpointcontrols exact. This is inversecomponent selection, not an improvement claim for publishedhybrid/test. +E049 discriminationdiagnostic6000vs4000 (conditional936supportedtruth-in-top64queries): native-onlyHit1 .47329vs.46474,uncertaingainCI[-.01522,.03229]; averagecorrectsimilarity+.007583 butstrongestfalse+.009168. This differs fromnegativehybridresult and suggestscheckingfusioncalibration before attributing all decline to simulatorquality. No scorecoefficientschanged or selected bydiagnosis. + +E054 portable mixed-radius package prepared: {"changed_factor": "E047radius2score coefficient0.75 plusE043radius3score coefficient0.25; frozenmasslikelihood coefficient0.05 once", "component_checkpoint_sha256": ["4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "0e826bbf817eae6d5fa8211a9602b4ac5b75b4da4d9bcc5b03646f521d7d2194"], "created_utc": "2026-10-21T08:16:55.447240+00:00", "fitting": "none; all networkweights and bothIDFs fitted on authorized trainingdata; mixture selected on validation", "hypothesis": "The selected mixed-radius candidate score combines complementary structural neighborhoods and should reproduce E050alpha0.25 in a portable package.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "seeds": "E047member seeds preserved; radius3seed1; bootstrap0", "verification": "new-input/candidate-order/immutablepackage/internal-score probes, fullindependentrelocatedreplay, comparisonwithinternalranks, Hit1/5/20 andMCES"}. Independent verification starts; root remains E048. E053all-conditioncandidate retains its predefinedE047baseline for an isolated comparison. + +E055 new fixed fusion-calibration diagnosis after E0496000result: {"changed_factor": "fixednativecoefficients0.5,1,2 acrossalready-screened4000/6000/8000 checkpoints", "controls": "coefficient1 for eachcheckpoint must reconstructeveryE049ranking exactly", "created_utc": "2026-10-21T08:18:29.673196+00:00", "fitting": "none; fixed globalhyperparameter modelselection onvalidation", "hypothesis": "The negative6000hybrid result with uncertainly improved native-only discrimination and slightly lowerMCES may reflect changed fusion calibration.", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "seeds": "native1; bootstrap0", "timing": "defined after6000negative and its discriminationanalysis, before8000screenresults; newhypothesis, not an originally preregistered E049family", "unchanged": "E040inverse scores,E018top64shortlist/tail,nativeentropy scoring,identicalpublicinput/nativepredictions"}. E053 currentlykeeps its frozenplannedcoefficient1; later changes require explicitrecordedselection. + +E053 development-only capture scheduled after native writer completion: preserve exact fullreplay HDF5,publicinput/candidates,routing,baseline andinverse scores outside package for later fixed-input score experiments. Verify source unchanged and bytehashes. Capture may add read-only disk contention to measuredreplay; no inference code reads thiscache. Any later reuse requires exactactualrankingcontrols. + +E049 complete fixedcheckpointfamily selected4000: {"metrics": {"4000": {"hit_rate_at_1": 0.5546875, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.7041015625}, "6000": {"hit_rate_at_1": 0.5361328125, "hit_rate_at_20": 0.810546875, "hit_rate_at_5": 0.6943359375}, "8000": {"hit_rate_at_1": 0.546875, "hit_rate_at_20": 0.810546875, "hit_rate_at_5": 0.7041015625}}, "native8000_delta": {"confidence": 0.95, "estimate": -0.0078125, "grouping": "supplied target_inchikey connectivity block", "lower": -0.026714881637805023, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.011290090291045565}, "native8000_sha256": "5564b9bf26f95cb93d465595b0b5d9bbb96e48ff280946fa541579c18556aced", "prediction_seconds": {"6000": 510.218835872598, "8000": 452.6207456449047}}. No latercheckpointpromoted. MCES4000=7.2451171875,6000=7.2041015625;8000pending. +E055 completeNEGATIVE: fixed0.5/1/2fusionfamily across4000/6000/8000 selectsunchanged4000coefficient1;4.0948226sCPU. Allcoefficient1 controls exactlymatchE049complete rankings. Fullresultsandfailuresinresearch/E055-completed; no modelchange. +E054 mixed-radiuspackage built checkpointc4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf; derivation1.986076s,publication14.071134s. Contract/arbitraryinputs/candidateordering/immutability/score-rankingconsistency probes PASS18.937366s. Independentfullreplaypending; root remainsE048. + +E056 conditionalmixed-radiusbranch candidateprepared: {"changed_factor": "E047inverse toE054inverse only; public routing and nativebranch remainfixed", "component_checkpoint_sha256": {"inverse": "c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf", "native": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "created_utc": "2026-10-21T08:22:44.680582+00:00", "disclosure": "component-based complete validation; no new fullunchangednativeGPUreplay", "fitting": "none", "hypothesis": "Use the independently replayed E054mixed-radius model for E048otherconditions while preserving its native continuous branch.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": "changed9695queryinversepartition replay; exactunchangednative190assets/publicinputhashes; fullcombinedofficialvalidation; end-to-endnovel/order/immutabilityprobes; MCES"}. Independentchangedbranch replay and probes start; MCESwaits E054completion to avoid duplicatepairwork. E054actualfullreplay145.326314s,RSS16,878,260,224bytes;actualHit1 .476246847496 (oneadditionalhit versusinternal),Hit5/20unchanged. Actualreplayauthoritative. +E053 re-export identitycheckpassed: exactcheckpointSHA andallweights of step4000 match previouslyscreened8600c828...; no latercheckpointsubstitution. + +E054 independentreplay COMPLETE: {"checkpoint_sha256": "c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf", "metrics": {"hit_rate_at_1": 0.4762468474960111, "hit_rate_at_20": 0.792578104894745, "hit_rate_at_5": 0.6539193988367904, "mces_at_1": 9.118688558340624}, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.006073395439806475, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0015251815353057234, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0109741257230538}, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6"}. Replay145.326314sRSS16.878260GB; probes18.937366s;MCES177newpairs265.942959s2workers. Actualvsinternal5truerankdifferences,1Hit1difference; actualmetricsauthoritative. E056conditionedbranchverificationactive. +E049allsecondaryMCEScomplete:4000 7.2451171875,6000 7.2041015625,8000 7.2265625. Latercheckpoints slightlyreducegraphdistance but primaryHit1selects4000;800044newpairs239.394873s2workers. + +E051 peakcountaugmentation complete: {"postscore": {"checkpoint_sha256": "bd4ec15e48284eede754638ef95d994346ac28be7f30e3f47af7a3cf67a61757", "diagnostics": {"add_sparse_rule_vs_E047": {"hit_rate_at_1": 0.4697102269802872, "hit_rate_at_20": 0.7942251273868959, "hit_rate_at_5": 0.6536105821195121, "paired_hit1_delta": {"confidence": 0.95, "estimate": -0.000463225075917443, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0013475330731427505, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0004978964415034779}, "queries": 19429}, "fitting": "none; predefined global public condition rule", "inference_fields": ["collision_energy presence", "positive intensity count"], "single_change_vs_E032": {"all": {"hit_rate_at_1": 0.4260126614854084, "hit_rate_at_20": 0.754902465386793, "hit_rate_at_5": 0.6085233413968809, "paired_hit1_delta": {"confidence": 0.95, "estimate": 0.00725719285603994, "grouping": "supplied target_inchikey connectivity block", "lower": -0.006104469797610913, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.02086029442158673}, "queries": 19429}, "missingCE_atmost10positivepeaks": {"hit_rate_at_1": 0.1671034065712558, "hit_rate_at_20": 0.49989921386817177, "hit_rate_at_5": 0.30901028018544646, "paired_hit1_delta": {"confidence": 0.95, "estimate": 0.011892763555734731, "grouping": "supplied target_inchikey connectivity block", "lower": -0.011059920755047166, "molecule_groups": 337, "queries": 4961, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.03851518347564658}, "queries": 4961}, "remaining": {"hit_rate_at_1": 0.5147912634780205, "hit_rate_at_20": 0.8423417196571744, "hit_rate_at_5": 0.711224771910423, "paired_hit1_delta": {"confidence": 0.95, "estimate": 0.005667680398119989, "grouping": "supplied target_inchikey connectivity block", "lower": -0.00793136951364365, "molecule_groups": 3107, "queries": 14468, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0193061740579803}, "queries": 14468}}, "sparse_rule": "use E047+E051equalprobabilityensemble only when CE is missing and input has atmost10positiveintensities; otherwiseE047"}, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"add": {"hit_rate_at_1": 0.4716145967368367, "hit_rate_at_20": 0.796747130578002, "hit_rate_at_5": 0.6538679293839107, "members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033", "E051"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.001441144680632045, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0008734175478559077, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003841286013943265}}, "add_sparse": {"hit_rate_at_1": 0.4697102269802872, "hit_rate_at_20": 0.7942251273868959, "hit_rate_at_5": 0.6536105821195121, "paired_delta_vs_E047": {"confidence": 0.95, "estimate": -0.000463225075917443, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0013475330731427505, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0004978964415034779}}, "control": {"hit_rate_at_1": 0.47017345205620464, "hit_rate_at_20": 0.7934530855937001, "hit_rate_at_5": 0.6531473570435946, "members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "replace": {"hit_rate_at_1": 0.47053373822636263, "hit_rate_at_20": 0.7959236193319265, "hit_rate_at_5": 0.654537032271347, "members": ["E051", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.00036028617015801124, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0028821556411361845, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003540440553781928}}, "single": {"hit_rate_at_1": 0.4260126614854084, "hit_rate_at_20": 0.754902465386793, "hit_rate_at_5": 0.6085233413968809, "members": ["E051"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": -0.044160790570796235, "grouping": "supplied target_inchikey connectivity block", "lower": -0.055352664577666, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.03152496590114371}}}, "selected": "add", "wall_seconds": 1.21684436686337}, "selection": {"checkpoint_sha256": "bd4ec15e48284eede754638ef95d994346ac28be7f30e3f47af7a3cf67a61757", "cosine_loss": 0.45647483706701325, "elapsed_seconds": 779.1373475990258, "epoch": 40, "epoch_seconds": 20.02748972317204, "hit_rate_at_1": 0.3606979257810489, "hit_rate_at_20": 0.6833599258839879, "hit_rate_at_5": 0.528797158886201, "selected_on": "full validation retrieval Hit@1", "train_loss": 0.3032201219598452}, "training": {"best_hit_at_1": 0.3606979257810489, "max_cuda_allocated": 9653728768, "wall_seconds": 779.7276322040707}}. Sparsepublicrule isnegative; globaladd pointestimate improves modestly withCIcrossingzero. No standalonepublication; next isolate whether this member complements selectedmixedradiusE054. + +E057 fixed mixed-radiusaugmentation-memberfamily prepared: {"changed_factor": "radius2group: E047control, replaceE032byE051, addE051; radius3E043coefficient.25 fixed", "created_utc": "2026-10-21T08:27:43.765066+00:00", "fitting": "none", "hypothesis": "E051augmentation may complement the selected mixed-radius model despite its sparse-onlyrule failure.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "seeds": "source memberseeds preserved;bootstrap0", "selection": "fixedthree-model family byvalidationHit1, exact E050alpha.25 control; E054actualreportedseparately becausebatcharithmeticchangedonehit", "unchanged": "alltrainedweights,training-only IDFs,massmixturecoefficient.05 andfeaturecaches"}. GPUscorecap0.22 onsoleH100; no newfitting. + +E058 secondradius3seed prepared: {"calibration": "same train-only radius3IDF and frozenE016mass score.05", "changed_factor": "E043radius3 trainingseed1to2 only; architecture,data,32experimental/10synthetic,real.25,CEdrop.5,40x1200x512,lr.0003unchanged", "created_utc": "2026-10-21T08:29:14.014413+00:00", "hypothesis": "A second independently initialized radius3 model may reduce ensemble variance and complement the selected mixed-radius score.", "initialization": "randomseed2; no pretrainedweights or firstseed initialization", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "schedule": "wait E053fullinference replay success and nativepredict process exit; may overlap CPU MCES, no largeGPUinference/fitting", "selection": "fullvalidationrawcheckpoint selection; fixedcalibratedsingle comparisonvsE043; any mixed ensemble evaluated subsequently with fixedglobalchoices"}. QueueafterE053fullmodelinference, preserving oneH100allocation. + +E056 component-based full validation completed: {"checkpoint_sha256": "c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf", "conservative_component_wall_sum": 1635.8140419833362, "metrics": {"hit_rate_at_1": 0.5205105769725668, "hit_rate_at_20": 0.7864532400020587, "hit_rate_at_5": 0.67574244685779, "mces_at_1": 8.248340110144628}, "paired_delta_vs_E048": {"confidence": 0.95, "estimate": 0.0023675948324669307, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0012326110892261404, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.006510171372252855}, "probe_wall_seconds": 142.86385368509218, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": {"configuration_changes": {"inverse_checkpoint_sha256": ["4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf"]}, "native_asset_files": 190, "native_input_hashes_equal": true, "parent_inference_source_equal": true, "unchanged_native_runtime_assets": true, "verification_kind": "changed inverse branch replay plus unchanged native branch reuse from E041fullreplay (also E048native branch) and end-to-end arbitrary-input probes"}}. Selection uses validation Hit@1; paired molecule-group interval is reported without a test claim. No new full native GPU replay: identical native component and exact public partition reuse the E041 actual replay; changed inverse branch is independently replayed and complete combined rankings officially scored. Atomic publication follows byte-equality to the probed package. + +E052 completed: {"checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", "native_step": 4000, "results": {"128": {"prediction_time": {"candidate_tsv_sha256": "0c5b6aea5fa736d8f1b17e9970818216cf44c1fd0bd65566ff657168250bcc6f", "checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", "command": ["/opt/glacier/bin/python", "/workspace/research/E052/capped_predict.py", "/workspace/research/E019/checkpoint-4000/native-package/.versions/generation-bei1t5a4/vendor/ms_pred/glacier/predict_smis_joint.py", "--dataset-labels", "/workspace/research/cache/native-predictions-step4000-top64-screen/candidates.tsv", "--checkpoint", "/workspace/research/E019/checkpoint-4000/native-package/.versions/generation-bei1t5a4/glacier.ckpt", "--save-dir", "/workspace/research/E052/batch-128/predictions", "--out-name", "preds.hdf5", "--sparse-out", "--sparse-k", "100", "--batch-size", "128", "--num-cpu-workers", "6", "--feat-cache-size", "64", "--prefetch-factor", "1", "--gpu"], "native_step": 4000, "overlap": "may overlap E051smallfit onsoleH100; alljobs common22CPUaffinity; processCUDAallocatorfraction0.65", "peak_sampled_gpu_MiB": 48302, "peak_summed_process_rss_bytes": 16905064448, "returncode": 0, "started_utc": "2026-10-21T08:27:12.217899+00:00", "wall_seconds": 268.98798583401367}, "retrieval": {"complete_ranking_differences": 643, "factor": "inference batch size only; frozen native checkpoint, E040scores, E018top64shortlist/tail and coefficient1", "fitting": "none in evaluation; native trained on training fold only", "inverse_score_sha256": "08d3c51f26b8552fce82158c021d01dccdc801c72a9d4da08ca5913022d1de05", "metrics": {"hit_rate_at_1": 0.5537109375, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.7041015625}, "native_checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", "paired_delta_vs_source_batch32": {"confidence": 0.95, "estimate": -0.0009765625, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0046918791837491005, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.002040868441349982}, "prediction_sha256": "487afaee8dfa79a1cac0b79b626b729b21f284283508928736b63dc9b95090a2", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "top_one_differences": 55, "wall_seconds": 114.40363743202761}}, "32": {"prediction_time": {"candidate_tsv_sha256": "0c5b6aea5fa736d8f1b17e9970818216cf44c1fd0bd65566ff657168250bcc6f", "checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", "command": ["/opt/glacier/bin/python", "/workspace/research/E052/capped_predict.py", "/workspace/research/E019/checkpoint-4000/native-package/.versions/generation-bei1t5a4/vendor/ms_pred/glacier/predict_smis_joint.py", "--dataset-labels", "/workspace/research/cache/native-predictions-step4000-top64-screen/candidates.tsv", "--checkpoint", "/workspace/research/E019/checkpoint-4000/native-package/.versions/generation-bei1t5a4/glacier.ckpt", "--save-dir", "/workspace/research/E052/batch-32/predictions", "--out-name", "preds.hdf5", "--sparse-out", "--sparse-k", "100", "--batch-size", "32", "--num-cpu-workers", "6", "--feat-cache-size", "64", "--prefetch-factor", "1", "--gpu"], "native_step": 4000, "overlap": "may overlap E051smallfit onsoleH100; alljobs common22CPUaffinity; processCUDAallocatorfraction0.65", "peak_sampled_gpu_MiB": 14128, "peak_summed_process_rss_bytes": 12850970624, "returncode": 0, "started_utc": "2026-10-21T08:19:06.573134+00:00", "wall_seconds": 485.5882496996783}, "retrieval": {"complete_ranking_differences": 0, "factor": "inference batch size only; frozen native checkpoint, E040scores, E018top64shortlist/tail and coefficient1", "fitting": "none in evaluation; native trained on training fold only", "inverse_score_sha256": "08d3c51f26b8552fce82158c021d01dccdc801c72a9d4da08ca5913022d1de05", "metrics": {"hit_rate_at_1": 0.5546875, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.7041015625}, "native_checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", "paired_delta_vs_source_batch32": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "prediction_sha256": "c295d810bcbe0ddd009b708139becf81b08e03745b5399f86814bb09564074c0", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "top_one_differences": 0, "wall_seconds": 121.29663681611419}}}, "selected_batch_size": 32, "selection": "lowest measured prediction walltime among batches with no lower validationHit1 than fresh32; no fullreplay claim"}. All selection uses validation; negative variants retained. + +E057 completed: {"fitting": "none; fixedthree-member-set family, validation selection only", "formula": "fixed.75radius2_IDFcos +.25E043radius3_IDFcos +fixed.05mass", "max_cuda_allocated": 9171059200, "new_member_checkpoint_sha256": "bd4ec15e48284eede754638ef95d994346ac28be7f30e3f47af7a3cf67a61757", "overlap": "soleH100 may share E052native batch evaluation or E056smallprobes; no largefitting", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"add": {"hit_rate_at_1": 0.47753358381800404, "hit_rate_at_20": 0.7951001080858511, "hit_rate_at_5": 0.6539708682896701, "paired_delta_vs_E050matched_control": {"confidence": 0.95, "estimate": 0.0013382057748726132, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0009360032847808436, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0035614221730077738}, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": 0.0012867363219928973, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0009914237514003599, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003511595297096432}, "radius2_members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033", "E051"]}, "control": {"hit_rate_at_1": 0.4761953780431314, "hit_rate_at_20": 0.792578104894745, "hit_rate_at_5": 0.6539193988367904, "paired_delta_vs_E050matched_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": -5.146945287971589e-05, "grouping": "supplied target_inchikey connectivity block", "lower": -0.00017473599707279371, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "radius2_members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"]}, "replace": {"hit_rate_at_1": 0.47634978640177056, "hit_rate_at_20": 0.795460394256009, "hit_rate_at_5": 0.6561840547634978, "paired_delta_vs_E050matched_control": {"confidence": 0.95, "estimate": 0.00015440835863914768, "grouping": "supplied target_inchikey connectivity block", "lower": -0.002447019320672342, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003021043331341349}, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": 0.00010293890575943178, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0025111344252334643, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.002937379950892772}, "radius2_members": ["E051", "E007", "E009", "E017", "E021", "E023", "E042", "E033"]}}, "selected": "add", "wall_seconds": 11.95528426207602}. All selection uses validation; negative variants retained. + +E059 prepared: {"changed_factor": "Fixed native entropy-score averages: step4000 control, mean4000_6000, mean4000_8000, mean4000_6000_8000.", "compute": "CPU cached-score experiment; if selected a new package must predict every member at inference and pass replay limits", "created_utc": "2026-10-21T08:35:50.802693+00:00", "fitting": "none; arithmetic mean selected globally using validation retrieval", "hypothesis": "Later native checkpoints may complement step4000 despite worse individual fused retrieval.", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "seed": "source training1; bootstrap0", "unchanged": "E049 exact predictions, query subset, candidate coverage, E040 inverse score, native coefficient1, tail and support mask."} + +E056 atomic promotion completed: {"configuration": {"inverse_checkpoint_sha256": "c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf", "method": "fixed-public-condition-native-inverse-composition", "native_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "rule": "native hybrid for [M+H]+ and non-null collision energy; inverse ensemble otherwise", "runtime": "/opt/glacier/bin/python"}, "manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-7p4_gv4j/native/.versions/generation-z3iv_pqm/native/.versions/generation-5y79tkae/glacier.ckpt", "sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "model_config": ".versions/generation-7p4_gv4j/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 experimental train and supplied held-out-clean ICEBERG simulations; validation only for selection", "pretrained_assets": []}}, "promoted_utc": "2026-10-21T08:37:28.404121+00:00", "runtime_equality": {"excluded": "research records, EXPERIMENTS, top-level README, bytecode caches", "files": 208, "new_generation": "/workspace/research/E056/selected-final/.versions/generation-pnfizgi9", "primary_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "reference_generation": "/workspace/research/E056/relocated-package/.versions/generation-n9bs1vq4", "runtime_asset_equality": true}, "validation": {"hit_rate_at_1": 0.5205105769725668, "hit_rate_at_20": 0.7864532400020587, "hit_rate_at_5": 0.67574244685779, "mces_at_1": 8.248340110144628}, "verification": "component-based E041 unchanged native runtime and public input hashes, changed inverse branch replay, whole-package contract probes and complete metrics"} +E059 completed: { + "results": { + "control4000": { + "native_steps": [ + 4000 + ], + "native_coefficient": 1.0, + "hit_rate_at_1": 0.5546875, + "hit_rate_at_5": 0.7041015625, + "hit_rate_at_20": 0.8115234375, + "paired_delta_vs_step4000_coefficient1": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 668, + "queries": 1024, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "mean4000_6000": { + "native_steps": [ + 4000, + 6000 + ], + "native_coefficient": 1.0, + "hit_rate_at_1": 0.55859375, + "hit_rate_at_5": 0.705078125, + "hit_rate_at_20": 0.814453125, + "paired_delta_vs_step4000_coefficient1": { + "estimate": 0.00390625, + "lower": -0.007273772204806686, + "upper": 0.01704076895770186, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 668, + "queries": 1024, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "mean4000_8000": { + "native_steps": [ + 4000, + 8000 + ], + "native_coefficient": 1.0, + "hit_rate_at_1": 0.5546875, + "hit_rate_at_5": 0.7099609375, + "hit_rate_at_20": 0.80859375, + "paired_delta_vs_step4000_coefficient1": { + "estimate": 0.0, + "lower": -0.015399793413334669, + "upper": 0.01614571547972153, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 668, + "queries": 1024, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "mean4000_6000_8000": { + "native_steps": [ + 4000, + 6000, + 8000 + ], + "native_coefficient": 1.0, + "hit_rate_at_1": 0.560546875, + "hit_rate_at_5": 0.7109375, + "hit_rate_at_20": 0.8115234375, + "paired_delta_vs_step4000_coefficient1": { + "estimate": 0.005859375, + "lower": -0.007577568225273767, + "upper": 0.020662890685550644, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 668, + "queries": 1024, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + } + }, + "selected": "mean4000_6000_8000", + "wall_seconds": 2.4445132296532393, + "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", + "checkpoint_sha256": { + "4000": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", + "6000": "7f6c3108fee735d862962a66e1357760442f29f014d5324bc7af15f1abca8b02", + "8000": "5564b9bf26f95cb93d465595b0b5d9bbb96e48ff280946fa541579c18556aced" + }, + "scope": "fixed native-checkpoint averaging after individually negative later checkpoints; exact1024subset, no newtraining, no full/test claim", + "fitting": "none; fixed checkpoint averages selected by validationretrieval" +}. Initial control assertion caught an indentation error (1.071553 seconds failed CPU run), archived and corrected before any selection. Three-checkpoint mean gains6/1024 top1 hits; CI includeszero; not published because inference cost/replay not yet established. + +E060 prepared and queued: {"changed_factor": "Add E007 multi-positive near-mass contrastive loss to E032, with a fresh fine-tuning optimizer.", "created_utc": "2026-10-21T08:39:11.388336+00:00", "hypothesis": "Near-mass contrastive fine-tuning may improve the stronger E032 encoder; E007 used an older 64-peak initializer without synthetic energy dropout.", "initial_checkpoint": "E032/best.pt", "initial_checkpoint_sha256": "7ffcaea9641c049f2f710030e9fd0f931054a553cb3220054be8fc5cd7f8b8ca", "negative_source": "existing E007 pools: experimental train plus sanitized synthetic structures only; same-fingerprint examples are positives; no validation candidate used for fitting", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "schedule": "after E058 completes; E053 full inference must have succeeded first; may share with later native32 screens on soleH100", "selection": "unchanged initializer and all epochs eligible by full validation raw retrieval; fixed post-family E047 control, single, replaceE032, addninth; molecule-group uncertainty", "settings": {"batch_size": 512, "contrastive_weight": 0.2, "cuda_memory_fraction": 0.2, "epochs": 20, "experimental_max_peaks": 32, "learning_rate": 0.0001, "negatives": 32, "real_fraction": 0.25, "seed": 1, "steps_per_epoch": 1200, "synthetic_energy_dropout": 0.5, "synthetic_max_peaks": 10, "temperature": 0.05}} + +E061 prepared: { + "hypothesis": "Averaging native weights along one training trajectory may recover checkpoint-ensemble benefits at single-model runtime.", + "changed_factor": "Equal arithmetic mean of floating state tensors from native steps4000,6000,8000; identical tensors copied exactly; nonfloating tensors must agree.", + "source": "E003 task-trained random-initialized checkpoints; no external weights", + "unchanged": "native architecture, batch32, E049 exact candidate input/coverage, E040 inverse, coefficient1 and tail", + "selection": "fixed1024query screen against exact E049step4000; full replay required before publishing", + "seed": 1, + "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", + "schedule": "CPU derivation/publication now; GPU screen after successful E053fullreplay, may overlap E058smallfitting under .65/.16 allocator caps", + "created_utc": "2026-10-21T08:39:56.522763+00:00" +} + +E062 precision audit prepared: { + "hypothesis": "Public peak mass precision may explain part of the weak missing-energy performance and native exact-bin mismatch.", + "work": "Training/validation descriptive audit only: minimum decimal precision covering95percent of positive peaks; summarize public-condition strata and E056validation retrieval.", + "fitting": "none; no model or inference change in this audit", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "created_utc": "2026-10-21T08:41:16.715701+00:00" +} + +E063 fixed bin-width family prepared: { + "hypothesis": "A coarser fixed entropy bin can tolerate fragment-mass error, especially for spectra with missing collision energy.", + "changed_factor": "Bin counts150000(control),75000,30000,15000 over0..1500Da; compare each globally and each coarse count only for missingCE while knownCE stays150000.", + "unchanged": "E049native4000 predictions, E040 inverse scores, E018top64 coverage and tail, coefficient1, sqrtintensities, observed50peaks", + "controls": "Every control ranking must equal E049step4000 exactly; no native simulation rerun", + "fitting": "none; fixed seven-rule validation selection, no query-fitted parameters or true formula", + "seed": "source1,bootstrap0", + "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", + "created_utc": "2026-10-21T08:43:08.395172+00:00" +} + +E058/E053 resource scheduling update before E058 fitting: {"old_children_wait_only": true, "old_waiting_driver_pid": 32929, "reason": "E053 graph preparation left the soleH100 idle at repeated samples, with GPU memory4MiB and utilization0%. Use queued small training concurrently to use the allocation; keep native GPU predictions sequential.", "schedule": "E058startsnow with0.16GPUcap; E060afterE058 with0.20cap; E053nativebatch32simulations may overlap; E061nativeaveragedscreenstillwaits E053fullreplaysuccess", "scientific_run_cancelled": false, "training_started_before_change": false, "unchanged": "E058 training source, data, seed2, optimization, validation selection; E060 next small fit likewise retains settings", "utc": "2026-10-21T08:46:23.246717+00:00"} + +E059 secondary metric and E062 precision audit completed: {"E059": {"hit_rate_at_1": 0.560546875, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.7109375, "mces_at_1": 7.14453125}, "E059_mces_compute": {"new_pairs": 7, "options": "threshold=15, always_stronger_bound=True, PULP_CBC_CMD; exactly identical graphs return zero", "pairs": 857, "wall_seconds": 61.916666933801025, "workers": 2}, "E062_finding": "7220missingCEvalidation spectra at approximately3decimal precision cover270moleculegroups and have E056Hit1.242105; 1762missingCEfive-decimal spectra have.488082. These are correlated observational strata, not causal evidence.", "E062_initial_strict_definition_seconds": 20.670733804814517, "E062_precision_counts": {"train": {"0": 1, "1": 15, "2": 162, "3": 40597, "4": 69973, "5": 62126, "6": 21245}, "validation": {"1": 4, "2": 36, "3": 7225, "4": 3269, "5": 6017, "6": 2878}}, "E062_wall_seconds": 18.671739993151277} + +E065 prepared: {"changed_factor": "radius3group E043control, E058replacement, equal-probability meanE043/E058", "controls": "exact E050alpha.25 ranks; independently replayed E054context separately", "created_utc": "2026-10-21T08:47:48.224750+00:00", "fitting": "none; frozen trained checkpoints, validation selection only", "hypothesis": "A second radius3 training seed can complement E043, holding radius2 and mixture weights fixed.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "schedule": "waitE060score-familyresults anddriverexit; then evaluate before E064 fitting", "unchanged": "E047radius2eightmembers, weights.75/.25, trainIDFs and frozen precursor term.05"} + +E064 prepared: {"calibration_sha256": "1a068f220fb36b65429e28ca7cb2f79b7cda01fa88a7cee4516333184cd7ad27", "changed_factor": "E032 recipe plus synthetic peak-mass Cauchy-mixture noise for missing-energy rows; distribution copied from training-only E016precursor residual calibration, +/-20ppm clip.", "created_utc": "2026-10-21T08:49:07.456651+00:00", "data": "Experimental TRAIN and supplied sanitized synthetic only; no validation fitting.", "hypothesis": "Training exact-mass synthetic spectra may make fine mass-defect features brittle to observed experimental mass errors.", "negative_controls": "E047 unchanged, new singleencoder, replaceE032, addninth under fixedIDF/mass calibration.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "rng": "Separate CUDA mass_noise_rng seed37001, resumed from saved state; existing CE/model RNG streams unchanged.", "schedule": "AfterE060finetune andE065scorefamily, soleH100cap.16; may overlap E053nativebatch32 prediction.", "scientific_limit": "Precursor error is a proxy for fragment error; this transfer is a hypothesis to validate, not an established error model.", "unchanged": "Random seed1,32experimental/10synthetic peaks, realfraction.25, CE dropout.5,40x1200steps512,lr.0003, sameBCE/cosine loss and validation selection. Experimental observations and precursor metadata unchanged."}. Initial setup heredoc syntax failure happened before files or scientific work; corrected with distinct delimiters and archived. + +E067 prepared: { + "hypothesis": "The E063 fixed missing-energy 0.05Da rule transfers to the actual full E053candidate.", + "changed_factor": "Known energy remains150000bins; missing energy uses30000bins. Fixed coefficient1 and all E053native weights/inverse scores/shortlists remain unchanged.", + "verification": "Use development capture of E053closed HDF writer; byte hashes match capturedmanifest; fine-bin control must reproduce every actualE053ranking before scoring experimental results.", + "fitting": "none; no query-fitted parameters. Validation labels used only by officialscore/MCES after exactcontrol.", + "scope": "component rescoring of identical actual simulation inputs, not a new fullGPUreplay; no publication by this driver", + "schedule": "after E053developmentcapture; CPU scoring may overlap actualE053CPUscoring, recorded as resource overlap", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "created_utc": "2026-10-21T08:50:06.488911+00:00" +} + +E063 completed: {"fitting": "none; fixed bin-count family selected with validation, same native simulations and candidate coverage", "mces_compute": {"new_pairs": 30, "options": "threshold=15, always_stronger_bound=True, PULP_CBC_CMD; exactly identical graphs return zero", "pairs": 849, "wall_seconds": 111.25214744266123, "workers": 2}, "native_checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", "prediction_sha256": "c295d810bcbe0ddd009b708139becf81b08e03745b5399f86814bb09564074c0", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "results": {"global-15000": {"hit_rate_at_1": 0.546875, "hit_rate_at_20": 0.8046875, "hit_rate_at_5": 0.7119140625, "missing_only": false, "num_bins": 15000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": -0.0078125, "grouping": "supplied target_inchikey connectivity block", "lower": -0.022657778853540325, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.007851026951574311}}, "global-150000": {"hit_rate_at_1": 0.5546875, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.7041015625, "missing_only": false, "num_bins": 150000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "global-30000": {"hit_rate_at_1": 0.55859375, "hit_rate_at_20": 0.8134765625, "hit_rate_at_5": 0.71484375, "missing_only": false, "num_bins": 30000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": 0.00390625, "grouping": "supplied target_inchikey connectivity block", "lower": -0.009991263756323995, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.019001429287863584}}, "global-75000": {"hit_rate_at_1": 0.55859375, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.712890625, "missing_only": false, "num_bins": 75000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": 0.00390625, "grouping": "supplied target_inchikey connectivity block", "lower": -0.007472486624981741, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.015448265396995974}}, "missing-15000": {"hit_rate_at_1": 0.5576171875, "hit_rate_at_20": 0.8056640625, "hit_rate_at_5": 0.7099609375, "missing_only": true, "num_bins": 15000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": 0.0029296875, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0068580619672700795, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.01280851394920224}}, "missing-30000": {"hit_rate_at_1": 0.560546875, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.712890625, "missing_only": true, "num_bins": 30000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": 0.005859375, "grouping": "supplied target_inchikey connectivity block", "lower": -0.002131426846100733, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.014986329460013664}}, "missing-75000": {"hit_rate_at_1": 0.5595703125, "hit_rate_at_20": 0.8095703125, "hit_rate_at_5": 0.708984375, "missing_only": true, "num_bins": 75000, "paired_delta_vs_fine_control": {"confidence": 0.95, "estimate": 0.0048828125, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0021912670852479114, "molecule_groups": 668, "queries": 1024, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.012784227761089001}}}, "selected": "missing-30000", "selected_secondary": {"hit_rate_at_1": 0.560546875, "hit_rate_at_20": 0.8115234375, "hit_rate_at_5": 0.712890625, "mces_at_1": 6.9873046875}, "wall_seconds": 138.81338015338406}. Fixedmissing-energy30000bins selected; all control rankings exact. FullE067transfer queued, no publication or test claim. + +E066 prepared: { + "hypothesis": "Independent query scoring can use four CPU workers to reduce native entropy-scoring runtime without changing any model output.", + "changed_factor": "One serial scorer versus four subprocesses partitioned by query-ID hash; exactly same code, input, predictions and scoring.", + "verification": "Every native ranking and internal candidate distance must be equal; own-shortlist distances checked against E049step4000.", + "data": "Fixed E024 public input and identical native4000 HDF only; no labels read by scorers or verification.", + "scope": "Engineering throughput experiment, no model selection or new scientific metric claim. Future full-package integration must be independently checked.", + "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", + "native_checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", + "schedule": "CPU only, may overlap E053nativebatch32 and E058smalltraining; score processes OMP1/OPENBLAS1", + "created_utc": "2026-10-21T08:54:30.118590+00:00" +} + +E056 MCES paired molecule uncertainty: { + "direction": "negative means lower MCES and better", + "metric": "candidate MCES@1 minus baseline MCES@1", + "exact_full_denominator_delta": -0.02843687271604303, + "molecule_bootstrap": { + "estimate": -0.02843687271604303, + "lower": -0.11256785070258118, + "upper": 0.05521263012837026, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "changed_queries": 1463, + "queries": 19429, + "compute": { + "new_pairs": 0, + "workers": 2, + "wall_seconds": 6.924475445877761, + "options": "same official MCES settings as score_mces.py; unchanged predictions cancel exactly" + } +} + +E063 MCES paired molecule uncertainty: { + "direction": "negative means lower MCES and better", + "metric": "candidate MCES@1 minus baseline MCES@1", + "exact_full_denominator_delta": -0.2578125, + "molecule_bootstrap": { + "estimate": -0.2578125, + "lower": -0.5514605209605209, + "upper": 9.587727708480758e-05, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 668, + "queries": 1024, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "changed_queries": 114, + "queries": 1024, + "compute": { + "new_pairs": 0, + "workers": 2, + "wall_seconds": 1.3823851132765412, + "options": "same official MCES settings as score_mces.py; unchanged predictions cancel exactly" + } +} + +E068 jointmetric prepared and queued: { + "hypothesis": "A learned shared nonlinear projection of predicted and candidate fingerprints can improve discrimination beyond fixed IDF cosine, while fingerprint regression anchors generalization.", + "initialization": "E032task-trained peakencoder; newprojection from randomseed47001. No externalpretraining.", + "initial_checkpoint_sha256": "7ffcaea9641c049f2f710030e9fd0f931054a553cb3220054be8fc5cd7f8b8ca", + "changed_factor": "E060near-mass InfoNCE uses learnedshared4096->512->256projection on train-IDF-normalized fingerprints; bothcandidate andquery projections receivegradients. Inference ranks learnedcosine plus samefrozenprecursor term.", + "training": "E032fp cosine+0.25BCE(posweight5) plus0.2multi-positiveInfoNCE/temp.05,32train-onlynear-mass negatives; seed1,20x1200x512,lr.0001,real.25,32experimental/10synthetic,CEdrop.5; no validation fitting", + "controls": "Initial backbone raw fingerprint rankings must matchE032exactly; epoch0eligible. Projection initialization preservesparentCPU/CUDA RNG states.", + "selection": "Fullvalidation learnedembedding+fixedtrainmasscoefficient.05 Hit1; also report embedding-only andfprawmetrics. Posttraining comparecalibratedsingle againstE032 and fixed scoremixeswithE054; anymixture selection declared before evaluation.", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "schedule": "afterE064fullfit/scoring, soleH100cap.22, may share E053nativebatch32prediction; no simultaneouslargeGPUbatch128", + "created_utc": "2026-10-21T08:57:06.443061+00:00" +}. Runtime,publisher,relocation,arbitrary-input/internal-scoreprobes andfullreplay pipeline included. No rootpromotion by driver. Postmixed-scorefamily still to implement, fixedalpha[0,.125,.25,.5,1] withE054 andonefrozenmass term. + +E058 complete: {"resource_schedule": {"old_children_wait_only": true, "old_waiting_driver_pid": 32929, "reason": "E053 graph preparation left the soleH100 idle at repeated samples, with GPU memory4MiB and utilization0%. Use queued small training concurrently to use the allocation; keep native GPU predictions sequential.", "schedule": "E058startsnow with0.16GPUcap; E060afterE058 with0.20cap; E053nativebatch32simulations may overlap; E061nativeaveragedscreenstillwaits E053fullreplaysuccess", "scientific_run_cancelled": false, "training_started_before_change": false, "unchanged": "E058 training source, data, seed2, optimization, validation selection; E060 next small fit likewise retains settings", "utc": "2026-10-21T08:46:23.246717+00:00"}, "scoring": {"calibration": "radius3 IDF from unique experimental training molecules; unchanged E016 precursor mixture and fixed coefficient0.05", "checkpoint_sha256": "cc9b112973b647fce0754538b1f53690cdb401bd7b4855886f89fb0d93a9b5dd", "fitting": "no validation fitting", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"idf_mass": {"hit_rate_at_1": 0.43918884142261566, "hit_rate_at_20": 0.7621081887899531, "hit_rate_at_5": 0.6159864120644397, "paired_delta_vs_E043_matching_rule": {"confidence": 0.95, "estimate": 0.011271810180657779, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0003184868479653106, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.022722213644966065}}, "raw": {"hit_rate_at_1": 0.3692933244119615, "hit_rate_at_20": 0.6855731123578156, "hit_rate_at_5": 0.5324514900406608, "paired_delta_vs_E043_matching_rule": {"confidence": 0.95, "estimate": 0.008955684801070564, "grouping": "supplied target_inchikey connectivity block", "lower": -0.004033593605352493, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.022584797440555245}}}, "wall_seconds": 5.95180322509259}, "selection": {"checkpoint_sha256": "cc9b112973b647fce0754538b1f53690cdb401bd7b4855886f89fb0d93a9b5dd", "cosine_loss": 0.5178008566698379, "elapsed_seconds": 759.7533755027689, "epoch": 38, "epoch_seconds": 18.639423670247197, "hit_rate_at_1": 0.3692933244119615, "hit_rate_at_20": 0.6855731123578156, "hit_rate_at_5": 0.5324514900406608, "selected_on": "full validation retrieval Hit@1", "train_loss": 0.36277062659462295}, "source_sha256": "58b0e5abcaebf307702160fa820d58adbaec2d19075fa887ce06de3acf420769", "training": {"best_hit_at_1": 0.3692933244119615, "max_cuda_allocated": 9653676032, "wall_seconds": 798.3012866266072}}. Seed2calibratedsinglegainvsE043.01127181 CIincludeszero. FixedmixedradiusE065comparison queued. +E066 CPUthroughput complete: { + "measurements": { + "1": { + "workers": 1, + "wall_seconds": 111.57881874218583, + "peak_summed_rss_bytes": 949276672, + "returncodes": [ + 0 + ], + "queries_per_worker": [ + 1024 + ], + "overlap": "CPU scorers share22CPU allocation with E053nativebatch32 and E058smalltraining" + }, + "4": { + "workers": 4, + "wall_seconds": 47.371187875047326, + "peak_summed_rss_bytes": 3737100288, + "returncodes": [ + 0, + 0, + 0, + 0 + ], + "queries_per_worker": [ + 265, + 267, + 237, + 255 + ], + "overlap": "CPU scorers share22CPU allocation with E053nativebatch32 and E058smalltraining" + } + }, + "all_rankings_equal": true, + "all_candidate_distances_equal": true, + "E049_own_shortlist_distance_control_exact": true, + "queries": 1024, + "speedup": 2.355415258669495, + "scorer_sha256": "6510aeb8ae8ae385e3058f4089e0def58055bb36d4c772c36aba7ae10a66685d", + "checkpoint_sha256": "8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527", + "prediction_sha256": "c295d810bcbe0ddd009b708139becf81b08e03745b5399f86814bb09564074c0", + "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", + "fitting": "none; no validation labels read by this experiment" +}. No modelmathchange; allnativecandidate distances andrankings exact, includingE049cachedcontrol. Futurepackageintegration remains pending. + +E070 verification prepared: { + "hypothesis": "Publish and independently verify the E065selected radius3 seed ensemble while holding E047radius2 and.75/.25 scoreweights fixed.", + "trigger": "Only if E065selects a non-control member set; otherwise record no-improvement without publishing identical weights.", + "verification": "Portablepackage, relocation, novel/order/immutability/internalscore probes, full19,429queryreplay, official retrieval vsE054 andMCES.", + "fitting": "none; all learned components train-only. Validation selects fixed member set.", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "schedule": "AfterE065; may overlap E053nativebatch32 and E064smalltraining ononeH100. Noautomatic rootpromotion.", + "created_utc": "2026-10-21T09:04:18.745786+00:00" +} + +E068 newarchitecture pipeline smoke: {"created_utc": "2026-10-21T09:05:20.324773+00:00", "epochs": 1, "initialization": "E032own task-trained checkpoint plus randommetric47001", "schedule": "may share soleH100 with E053native32 and E060smallfit; allocatorfraction.22", "scope": "Two-optimizer-step end-to-end smoke for a new learned-metric architecture; not a baseline retraining or model candidate.", "seed": 1, "steps": 2, "verification": "initialbackbone exact raw validationcontrol, two train-only gradientsteps, publish, relocate, arbitraryinput/order/immutability/internal-scoreprobes"} + +E069 fixedjoint-metric scorefamily prepared: { + "hypothesis": "The learned joint metric may complement the fixed E054mixed-radius score even if its single-model accuracy is lower.", + "changed_factor": "Fixedalpha[0,.125,.25,.5,1] blending E054fingerprint similarity and E068learned similarity; frozen training precursor likelihood.05 addedonce.", + "controls": "alpha0 exactE050matchedmixed-radius ranks; alpha1 exactE068selected-training calibrated ranks. E054actual context separately.", + "fitting": "none; all checkpoints frozen after train-only fitting, validation chooses globalalpha.", + "schedule": "AfterE068trainingresult andtrainerexit; may overlap E068packageverification and E053nativebatch32 on soleH100, cap.22", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "created_utc": "2026-10-21T09:06:56.861238+00:00" +} + +E068two-step pipeline smoke PASSED: {"checkpoint_sha256": "5f37444ee43f8cc9ca98639de0a8e06e982b88513e4476989f4be1444e7a737b", "pipeline": {"command": ["sh", "/workspace/research/E068/smoke/run.sh"], "cpu_system_seconds": 9.230524, "cpu_user_seconds": 29.095582, "max_child_rss_kib": 3842424, "returncode": 0, "start_unix_time": 1792573520.4124994, "wall_seconds": 58.316512077115476}, "probes": {"candidate_order_invariant": true, "complete_permutations": true, "internal_score_ranking_consistency": true, "missing_and_novel_instrument": true, "new_structures_and_arbitrary_query_ids": true, "out_of_window_peaks": true, "package_unchanged": true, "singleton_pool": true, "wall_seconds": 15.209323348943144}, "purpose": "newarchitecturetwo-step pipeline smoke; not scientific model selection", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "training": {"best_hit_at_1": 0.3374852025322971, "max_cuda_allocated": 12609729536, "wall_seconds": 18.090526144951582}}. Initial rawfingerprint endpoint exactlyE032. Newmetricfulltraining remainsqueued; no rootpromotion fromsmoke. + +E072 prepared: {"changed_factor": "E047radius2group control versus replacingE032withE060, only. SelectedE065radius3group fixed.", "controls": "exact selectedE065rankings; E054actual provided only as older context, not currentmatchedbaseline", "created_utc": "2026-10-21T09:10:46.468795+00:00", "fitting": "none; fixedtwo-rule validation comparison", "hypothesis": "E060contrastive replacement may retain its E047gain with the selected E065radius3 seed ensemble.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "unchanged": ".75/.25cross-radius scoreweights, trainingIDFs andsinglefrozenprecursor term.05"} + +E073 independent inverse verification prepared: {"changed_factor": "E070radius2 firstmemberE032 replacedbyE060; E043/E058radius3mean andallscoreweights unchanged.", "created_utc": "2026-10-21T09:13:23.976180+00:00", "fitting": "none; componenttrainedonly ontrain/cleansynthetic, validationselection", "hypothesis": "The positive E072contrastive replacement survives independent portable inference and improves the selected mixed-radius inverse.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": "Publish, relocate, allcontractprobes, fullvalidationreplay vsE070, exactmetriccomparisons andMCES; no automatic rootpromotion."} + +E071conditionalverification prepared: {"changed_factor": "E054inverse toE073inverse only; public routing and native2000/E014top20continuous1 branch remainfixed.", "created_utc": "2026-10-21T09:14:32.743936+00:00", "disclosure": "component-based fullvalidation; no new unchanged nativeGPUreplay. Provisionalcomposition52.375315% isnot authoritative beforechangedbranchreplay.", "fitting": "none; validationmodelselection only", "hypothesis": "Use E073independentlyverified contrastive/two-seed mixed-radius inverse for E056otherconditions, preserving known-energy proton nativebranch.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": "WaitE073packageprobes; replaychanged9695inversequeries; exactunchangednative190runtimeassets,parentcodeandE041publicpartitionhashes; completecomposedofficialscorevsE056; wholepackagenovel/order/immutabilityprobes;MCES afterE073MCES."} + +E060 completed: {"actual_overlap": "E053nativeinference andbriefE068smoke; genericfamilytoolsoverlapstringislegacy", "family": {"add": {"hit_rate_at_1": 0.4719748829069947, "hit_rate_at_20": 0.7934530855937001, "hit_rate_at_5": 0.6533017654022337, "members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033", "E060"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.0018014308507900562, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0007792574305858817, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.004239791053461497}}, "compute": {"calibration_checkpoint_sha256": "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "formula": "equal mean of sigmoid probabilities; frozen training-IDF and Cauchy-mixture likelihood; fixed coefficient0.05", "hardware": "NVIDIA H100 80GB HBM3", "members_sha256": {"E007": "0440569a4a87aadf5571781bf60078b22bc11459abf153a2039ed229056087f2", "E009": "6960d7591a47579956d77ae2fed7257680d8fd6b0602bcda03865abdce412c0e", "E017": "15d84dfaaacf65ad9224f15f513f2689afffe4eecbff1b35ce8bc55cd1539248", "E021": "6033332c96b67d6b8384da54ec79d8c8a220dcb9998ffa6c3079944b5e3487c0", "E023": "025eb1297877bb16d496c49f58952dc22fde58e505cd41423ac28667b4bc87cb", "E032": "7ffcaea9641c049f2f710030e9fd0f931054a553cb3220054be8fc5cd7f8b8ca", "E033": "5f7ceeb8c23c2b06a730741f1da0698092f5a734230a8067251da5355f5899d2", "E042": "4448ab7a55cb304071a442b7ddd970851c211b975a2adefd3fe2d92b53619807", "E060": "38acc015ffa8f19f89853a4a660e07556ddbc2f45b7b07fde0276fab6cab72be"}, "overlap": "native fitting and CPU MCES research jobs", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "wall_seconds": 8.148907470982522}, "control": {"hit_rate_at_1": 0.47017345205620464, "hit_rate_at_20": 0.7934530855937001, "hit_rate_at_5": 0.6531473570435946, "members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "replace": {"hit_rate_at_1": 0.47223223017139326, "hit_rate_at_20": 0.7948942302743321, "hit_rate_at_5": 0.6550517268001441, "members": ["E060", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.0020587781151886354, "grouping": "supplied target_inchikey connectivity block", "lower": 0.00040597913066141284, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003750283552804278}}, "single": {"hit_rate_at_1": 0.42215245251942973, "hit_rate_at_20": 0.7603067579391631, "hit_rate_at_5": 0.6067733799989706, "members": ["E060"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": -0.048020999536774925, "grouping": "supplied target_inchikey connectivity block", "lower": -0.05865476005562629, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.037428445469446056}}}, "selection": {"checkpoint_sha256": "38acc015ffa8f19f89853a4a660e07556ddbc2f45b7b07fde0276fab6cab72be", "cosine_loss": 0.4754054692752498, "elapsed_seconds": 132.31846722774208, "epoch": 6, "epoch_seconds": 20.247638512868434, "hit_rate_at_1": 0.3576612280611457, "hit_rate_at_20": 0.6861392763394926, "hit_rate_at_5": 0.5281795254516445, "selected_on": "full validation retrieval Hit@1", "train_loss": 0.34899532246092957}, "training": {"best_hit_at_1": 0.3576612280611457, "max_cuda_allocated": 12122535424, "wall_seconds": 424.5449762758799}} + +E065 completed: {"fitting": "none; fixedthree-member-set family, validation selection only", "formula": "fixed.75E047radius2_IDFcos +.25radius3group_IDFcos +fixed.05mass", "max_cuda_allocated": 9171501568, "new_member_checkpoint_sha256": "cc9b112973b647fce0754538b1f53690cdb401bd7b4855886f89fb0d93a9b5dd", "overlap": "soleH100 may share E053native batch32 inference; waitsE060smallfitting andscorecomplete", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"add": {"hit_rate_at_1": 0.4787688506871172, "hit_rate_at_20": 0.797467702918318, "hit_rate_at_5": 0.6574193216326111, "paired_delta_vs_E050matched_control": {"confidence": 0.95, "estimate": 0.0025734726439857946, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0006922343678920401, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.006175986174151276}, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": 0.0025220031911060785, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0007453626226133949, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0061174332681894405}, "radius2_members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"]}, "control": {"hit_rate_at_1": 0.4761953780431314, "hit_rate_at_20": 0.792578104894745, "hit_rate_at_5": 0.6539193988367904, "paired_delta_vs_E050matched_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": -5.146945287971589e-05, "grouping": "supplied target_inchikey connectivity block", "lower": -0.00017473599707279371, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "radius2_members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043"]}, "replace": {"hit_rate_at_1": 0.47871738123423746, "hit_rate_at_20": 0.7969530083895208, "hit_rate_at_5": 0.6552576046116629, "paired_delta_vs_E050matched_control": {"confidence": 0.95, "estimate": 0.0025220031911060785, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0031137993439212955, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.008516704995480254}, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": 0.002470533738226363, "grouping": "supplied target_inchikey connectivity block", "lower": -0.003116740367226354, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.00841776863773291}, "radius2_members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E058"]}}, "selected": "add", "wall_seconds": 11.296526493970305} + +E072 completed: {"fitting": "none; fixedtwo-member-set family, validation selection only", "formula": "fixed.75radius2_IDFcos +.25selectedE065radius3_IDFcos +fixed.05mass", "max_cuda_allocated": 8852734464, "new_member_checkpoint_sha256": "38acc015ffa8f19f89853a4a660e07556ddbc2f45b7b07fde0276fab6cab72be", "overlap": "soleH100 shared with E053nativebatch32,E064smallfit andE070verification; allocatorcap.22", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"control": {"hit_rate_at_1": 0.4787688506871172, "hit_rate_at_20": 0.797467702918318, "hit_rate_at_5": 0.6574193216326111, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": 0.0025220031911060785, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0007453626226133949, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0061174332681894405}, "paired_delta_vs_E065matched_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "radius2_members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"]}, "replace": {"hit_rate_at_1": 0.4810849760667044, "hit_rate_at_20": 0.7986515003345515, "hit_rate_at_5": 0.6577281383498893, "paired_delta_vs_E054actual_context": {"confidence": 0.95, "estimate": 0.0048381285706932935, "grouping": "supplied target_inchikey connectivity block", "lower": 0.00139776333498659, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.008702414018014902}, "paired_delta_vs_E065matched_control": {"confidence": 0.95, "estimate": 0.002316125379587215, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0008694541252302261, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003901080336192233}, "radius2_members": ["E060", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"]}}, "selected": "replace", "wall_seconds": 12.830672090407461} + +E074 sodiumexpert prepared: { + "hypothesis": "A sodium-specific inverse encoder may reduce the weakest adduct errors. Sodium is14.2%of experimental training and8.1%of valid synthetic spectra, versus24.4%of validationqueries.", + "changed_factor": "Fine-tune E032only on [M+Na]+ training spectra, keeping real/syntheticfraction.25; no change to fingerprints, peakfeatures or inferencearchitecture.", + "initial_checkpoint_sha256": "7ffcaea9641c049f2f710030e9fd0f931054a553cb3220054be8fc5cd7f8b8ca", + "training_counts": { + "experimental_sodium_spectra": 27640, + "experimental_sodium_unique_smiles": 5522, + "synthetic_sodium_valid_spectra": 189115 + }, + "settings": { + "seed": 1, + "epochs": 20, + "steps_per_epoch": 1200, + "batch": 512, + "lr": 0.0001, + "experimental_peaks": 32, + "synthetic_peaks": 10, + "CE_dropout": 0.5, + "cuda_fraction": 0.16 + }, + "selection": "checkpoint by validationNa rawHit1, initializereligible/exactcontrol; deploy only through onefixed public-adduct rule with Hbaselineunchanged.", + "postfamily": "Fixed beta[0,.25,.5,1] probability interpolation between E072radius2mean and newNaencoder forNaqueries only; E043/E058radius3mean and.75/.25scores plus.05mass fixed. beta0exactE072control. Fullvalidationprimary and moleculegroupuncertainty.", + "fitting": "traininglabels only; validation selection, no testaccess or queryfittedparameters", + "schedule": "After E068training andE069scorefamily, soleH100cap.16; may share E053nativebatch32.", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "created_utc": "2026-10-21T09:16:28.580109+00:00" +} + +E070 completed: {"actual_overlap": "E053 native inference and E064 small fitting; E073 additionally overlapped E071 changed-inverse replay. All one H100 and 22 CPU affinity.", "internal_replay_comparison": {"authority": "actual independently relocated package replay", "hit1_outcome_differences": 0, "queries": 19429, "true_rank_differences": 6}, "metrics": {"hit_rate_at_1": 0.4787688506871172, "hit_rate_at_20": 0.797467702918318, "hit_rate_at_5": 0.6574193216326111, "mces_at_1": 9.076200524988419}, "paired_baseline_delta": {"confidence": 0.95, "estimate": 0.0025220031911060785, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0007453626226133949, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0061174332681894405}, "replay": {"elapsed_seconds": 158.33725856384262, "finished_utc": "2026-10-21T09:11:06.166080+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 shared with E053nativebatch32 and possibly E064smallfitting; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-dyo_11tv/model.pt", "sha256": "d410f3d6368cb22e296846bbb4c4447967473ccea8ebc79ed5521a660dc859bd"}, "model_config": ".versions/generation-dyo_11tv/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 16953397248, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "returncode": 0, "sampled_total_cpu_seconds": 545.4100000000001, "started_utc": "2026-10-21T09:08:27.828812+00:00"}, "selection": "add", "status": "verified inverse component; current conditional root requires separate changed-branch evaluation before promotion"}. Full actual replay is authoritative when present. All validation confidence intervals resample molecule groups. Training-only data used for fitting; no test inference or claim. + +E073 completed: {"actual_overlap": "E053 native inference and E064 small fitting; E073 additionally overlapped E071 changed-inverse replay. All one H100 and 22 CPU affinity.", "internal_replay_comparison": {"authority": "actual independently relocated package replay", "hit1_outcome_differences": 0, "queries": 19429, "true_rank_differences": 10}, "metrics": {"hit_rate_at_1": 0.4810849760667044, "hit_rate_at_20": 0.7986515003345515, "hit_rate_at_5": 0.6577281383498893, "mces_at_1": 9.051984147408513}, "paired_baseline_delta": {"confidence": 0.95, "estimate": 0.002316125379587215, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0008694541252302261, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003901080336192233}, "replay": {"elapsed_seconds": 156.32978663174435, "finished_utc": "2026-10-21T09:16:51.257223+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 shared with E053nativebatch32 and possibly E064smallfitting; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-v_w2c2eo/model.pt", "sha256": "e900ae617e43ed90b9b3e7b8992c0aecbdb3636d3edc88a3ed5cbadef56dbf33"}, "model_config": ".versions/generation-v_w2c2eo/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 16956178432, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "returncode": 0, "sampled_total_cpu_seconds": 544.37, "started_utc": "2026-10-21T09:14:14.927427+00:00"}, "selection": "replace", "status": "verified inverse component; current conditional root requires separate changed-branch evaluation before promotion"}. Full actual replay is authoritative when present. All validation confidence intervals resample molecule groups. Training-only data used for fitting; no test inference or claim. + +E064 completed: {"actual_overlap": "E053 native inference throughout; brief E070/E073 inverse verification and E071 changed-branch verification. Generic evaluator overlap string is stale; no native fitting ran.", "checkpoint_sha256": "dc030008171bb90240d31b0a42be73656bf212391e692230b229151b15ff3647", "family": {"add": {"hit_rate_at_1": 0.4741880693808225, "hit_rate_at_20": 0.7968500694837614, "hit_rate_at_5": 0.6555149518760616, "members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033", "E064"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.004014617324617839, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0014669869367454381, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.006538069531996206}}, "compute": {"calibration_checkpoint_sha256": "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "formula": "equal mean of sigmoid probabilities; frozen training-IDF and Cauchy-mixture likelihood; fixed coefficient0.05", "hardware": "NVIDIA H100 80GB HBM3", "members_sha256": {"E007": "0440569a4a87aadf5571781bf60078b22bc11459abf153a2039ed229056087f2", "E009": "6960d7591a47579956d77ae2fed7257680d8fd6b0602bcda03865abdce412c0e", "E017": "15d84dfaaacf65ad9224f15f513f2689afffe4eecbff1b35ce8bc55cd1539248", "E021": "6033332c96b67d6b8384da54ec79d8c8a220dcb9998ffa6c3079944b5e3487c0", "E023": "025eb1297877bb16d496c49f58952dc22fde58e505cd41423ac28667b4bc87cb", "E032": "7ffcaea9641c049f2f710030e9fd0f931054a553cb3220054be8fc5cd7f8b8ca", "E033": "5f7ceeb8c23c2b06a730741f1da0698092f5a734230a8067251da5355f5899d2", "E042": "4448ab7a55cb304071a442b7ddd970851c211b975a2adefd3fe2d92b53619807", "E064": "dc030008171bb90240d31b0a42be73656bf212391e692230b229151b15ff3647"}, "overlap": "native fitting and CPU MCES research jobs", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "wall_seconds": 8.208706670906395}, "control": {"hit_rate_at_1": 0.47017345205620464, "hit_rate_at_20": 0.7934530855937001, "hit_rate_at_5": 0.6531473570435946, "members": ["E032", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "replace": {"hit_rate_at_1": 0.47305574141746876, "hit_rate_at_20": 0.7968500694837614, "hit_rate_at_5": 0.6560296464048587, "members": ["E064", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": 0.00288228936126409, "grouping": "supplied target_inchikey connectivity block", "lower": -0.00028411327656455246, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0060369274832180984}}, "single": {"hit_rate_at_1": 0.4320345874723352, "hit_rate_at_20": 0.7710638735910237, "hit_rate_at_5": 0.6169643316691543, "members": ["E064"], "paired_delta_vs_E047": {"confidence": 0.95, "estimate": -0.038138864583869475, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0528181303601715, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.020267478098852452}}}, "selection": "Addition improves E047-only family; transfer to selected E073 mixed-radius model remains to be evaluated.", "training": {"best_hit_at_1": 0.3648669514643059, "max_cuda_allocated": 9654274048, "wall_seconds": 807.3804952139035}}. Full actual replay is authoritative when present. All validation confidence intervals resample molecule groups. Training-only data used for fitting; no test inference or claim. + +E071 component-based full validation completed: {"checkpoint_sha256": "e900ae617e43ed90b9b3e7b8992c0aecbdb3636d3edc88a3ed5cbadef56dbf33", "conservative_component_wall_sum": 1605.7666614456102, "metrics": {"hit_rate_at_1": 0.5237531525039889, "hit_rate_at_20": 0.7917031241957898, "hit_rate_at_5": 0.6787791445776932, "mces_at_1": 8.185264295640538}, "paired_delta_vs_E056": {"confidence": 0.95, "estimate": 0.003242575531422101, "grouping": "supplied target_inchikey connectivity block", "lower": 0.00026888583300629904, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.006789091861587859}, "probe_wall_seconds": 137.47057001199573, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": {"configuration_changes": {"inverse_checkpoint_sha256": ["c4ae35dddd874668c4cf08ce5b24ba9919c75ce14d9991428c91d59d6c2ee7bf", "e900ae617e43ed90b9b3e7b8992c0aecbdb3636d3edc88a3ed5cbadef56dbf33"]}, "native_asset_files": 190, "native_input_hashes_equal": true, "parent_inference_source_equal": true, "unchanged_native_runtime_assets": true, "verification_kind": "changed inverse branch replay plus unchanged native branch reuse from E041fullreplay (also E056native branch) and end-to-end arbitrary-input probes"}}. Selection uses validation Hit@1; paired molecule-group interval is reported without a test claim. No new full native GPU replay: identical native component and exact public partition reuse the E041 actual replay; changed inverse branch is independently replayed and complete combined rankings officially scored. Atomic publication follows byte-equality to the probed package. + +E075 prepared: {"changed_factor": "radius2 probabilities only: fixed E073 control, replace E060 with E064, or add E064 as ninth equal-probability member; radius3 E043/E058 and score weights unchanged", "checkpoint_sha256": "dc030008171bb90240d31b0a42be73656bf212391e692230b229151b15ff3647", "control": "every true rank must match E072 selected internal control; E073 actual results separately reported", "fitting": "none; finite global validation selection", "hypothesis": "Synthetic missing-CE peak mass noise improves complementary structure evidence and transfers into the selected E073 ensemble.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100; 22 CPU affinity, allocator .22; brief scoring overlaps native E053 and E068 fitting", "seed": "inherited E064 seed1; interval seed0"} + +E075 completed: { + "results": { + "control": { + "radius2_members": [ + "E060", + "E007", + "E009", + "E017", + "E021", + "E023", + "E042", + "E033" + ], + "radius3_members": [ + "E043", + "E058" + ], + "hit_rate_at_1": 0.4810849760667044, + "hit_rate_at_5": 0.6577281383498893, + "hit_rate_at_20": 0.7986515003345515, + "paired_delta_vs_E072matched_control": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E073actual_context": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "replace": { + "radius2_members": [ + "E064", + "E007", + "E009", + "E017", + "E021", + "E023", + "E042", + "E033" + ], + "radius3_members": [ + "E043", + "E058" + ], + "hit_rate_at_1": 0.48185701785990015, + "hit_rate_at_5": 0.6593751608420403, + "hit_rate_at_20": 0.7996808893921458, + "paired_delta_vs_E072matched_control": { + "estimate": 0.0007720417931957384, + "lower": -0.0023704265597022933, + "upper": 0.004166966524282662, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E073actual_context": { + "estimate": 0.0007720417931957384, + "lower": -0.0023704265597022933, + "upper": 0.004166966524282662, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "add": { + "radius2_members": [ + "E060", + "E007", + "E009", + "E017", + "E021", + "E023", + "E042", + "E033", + "E064" + ], + "radius3_members": [ + "E043", + "E058" + ], + "hit_rate_at_1": 0.48479077667404397, + "hit_rate_at_5": 0.6615368778629883, + "hit_rate_at_20": 0.8013793813371763, + "paired_delta_vs_E072matched_control": { + "estimate": 0.003705800607339544, + "lower": 0.0009700527854722082, + "upper": 0.006785245745677638, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E073actual_context": { + "estimate": 0.003705800607339544, + "lower": 0.0009700527854722082, + "upper": 0.006785245745677638, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + } + }, + "selected": "add", + "wall_seconds": 13.693178507033736, + "max_cuda_allocated": 9171059200, + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "new_member_checkpoint_sha256": "dc030008171bb90240d31b0a42be73656bf212391e692230b229151b15ff3647", + "formula": "fixed.75radius2_IDFcos +.25selectedE065radius3_IDFcos +fixed.05mass", + "fitting": "none; fixedthree-member-set family, validation selection only", + "overlap": "soleH100 shared with E053nativebatch32 andE068jointembeddingfit; allocatorcap.22" +}; conditional diagnosis: { + "control": { + "metrics": { + "1": 0.5237531525039889, + "5": 0.6787791445776932, + "20": 0.7917031241957898 + }, + "paired_delta_vs_E071": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "authority": "internal composition screening only; actual changed-branch replay required" + }, + "replace": { + "metrics": { + "1": 0.526275155695095, + "5": 0.6810952699572803, + "20": 0.7927839827062638 + }, + "paired_delta_vs_E071": { + "estimate": 0.0025220031911060785, + "lower": 0.00010501630786695057, + "upper": 0.005271459219483671, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "authority": "internal composition screening only; actual changed-branch replay required" + }, + "add": { + "metrics": { + "1": 0.5272016058469299, + "5": 0.68114673941016, + "20": 0.7939163106696175 + }, + "paired_delta_vs_E071": { + "estimate": 0.0034484533429409645, + "lower": 0.0011865251681286702, + "upper": 0.006322209463130338, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "authority": "internal composition screening only; actual changed-branch replay required" + } +} +E076 prepared: {"changed_factor": "one ninth radius2 member; all previous eight radius2 and two radius3 members, score weights and mass term fixed", "checkpoint_parent_sha256": "dc030008171bb90240d31b0a42be73656bf212391e692230b229151b15ff3647", "hypothesis": "Adding E064 mass-noise encoder to E073 improves inverse ranking and conditional fallback generalization.", "promotion": "no automatic root promotion; conditional branch independently checked afterward", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100; may overlap E053native and small E068/E074 fitting; exact measurements recorded", "selection": "preselected E075 add; full independent relocation/replay required", "source_seeds": "E064 seed1, inherited all earlier members", "training": "none in publication; E064 fitted only training and clean synthetic; validation selection only"} + +E071 atomically published: {"inverse_checkpoint_sha256": "e900ae617e43ed90b9b3e7b8992c0aecbdb3636d3edc88a3ed5cbadef56dbf33", "manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-f1zjs26j/native/.versions/generation-z3iv_pqm/native/.versions/generation-5y79tkae/glacier.ckpt", "sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "model_config": ".versions/generation-f1zjs26j/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 experimental train and supplied held-out-clean ICEBERG simulations; validation only for selection", "pretrained_assets": []}}, "metrics": {"hit_rate_at_1": 0.5237531525039889, "hit_rate_at_20": 0.7917031241957898, "hit_rate_at_5": 0.6787791445776932, "mces_at_1": 8.185264295640538}, "published_utc": "2026-10-21T09:24:19.874539+00:00", "runtime_equality": {"excluded": "research records, EXPERIMENTS, top-level README, bytecode caches", "files": 208, "new_generation": "/workspace/research/E071/selected-final/.versions/generation-ie8fu2xe", "primary_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "reference_generation": "/workspace/research/E071/relocated-package/.versions/generation-zqwlpuws", "runtime_asset_equality": true}, "verification": "component-based exact unchanged-native runtime and input proof, changed inverse independent replay and end-to-end probes; no new full native GPU replay"} +E071 MCES paired delta versus E056: { + "direction": "negative means lower MCES and better", + "metric": "candidate MCES@1 minus baseline MCES@1", + "exact_full_denominator_delta": -0.06307581450409182, + "molecule_bootstrap": { + "estimate": -0.06307581450409182, + "lower": -0.13004077337203476, + "upper": 0.0036336677078487338, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "changed_queries": 1059, + "queries": 19429, + "compute": { + "new_pairs": 0, + "workers": 2, + "wall_seconds": 6.155496932100505, + "options": "same official MCES settings as score_mces.py; unchanged predictions cancel exactly" + } +} +E071 condition and molecule-group error analysis: { + "strata": { + "adduct_energy:[M+H]+/known": { + "queries": 9734, + "hit_rate_at_1": 0.7431682761454695, + "hit_rate_at_5": 0.8750770495171564, + "hit_rate_at_20": 0.9161701253338812, + "corrected": 0, + "regressed": 0, + "misses": 2500 + }, + "adduct_energy:[M+H]+/missing": { + "queries": 4958, + "hit_rate_at_1": 0.34772085518354173, + "hit_rate_at_5": 0.527027027027027, + "hit_rate_at_20": 0.6924162968939088, + "corrected": 78, + "regressed": 65, + "misses": 3234 + }, + "adduct_energy:[M+Na]+/known": { + "queries": 241, + "hit_rate_at_1": 0.24481327800829875, + "hit_rate_at_5": 0.4605809128630705, + "hit_rate_at_20": 0.7261410788381742, + "corrected": 5, + "regressed": 2, + "misses": 182 + }, + "adduct_energy:[M+Na]+/missing": { + "queries": 4496, + "hit_rate_at_1": 0.2577846975088968, + "hit_rate_at_5": 0.43282918149466193, + "hit_rate_at_20": 0.6352313167259787, + "corrected": 89, + "regressed": 42, + "misses": 3337 + }, + "instrument_energy:/missing": { + "queries": 486, + "hit_rate_at_1": 0.43415637860082307, + "hit_rate_at_5": 0.7098765432098766, + "hit_rate_at_20": 0.8539094650205762, + "corrected": 7, + "regressed": 12, + "misses": 275 + }, + "instrument_energy:Orbitrap/known": { + "queries": 8370, + "hit_rate_at_1": 0.7835125448028674, + "hit_rate_at_5": 0.8958183990442055, + "hit_rate_at_20": 0.9273596176821983, + "corrected": 1, + "regressed": 2, + "misses": 1812 + }, + "instrument_energy:Orbitrap/missing": { + "queries": 8069, + "hit_rate_at_1": 0.28281075721898624, + "hit_rate_at_5": 0.4487544925021688, + "hit_rate_at_20": 0.6383690667988599, + "corrected": 140, + "regressed": 77, + "misses": 5787 + }, + "instrument_energy:QTOF/known": { + "queries": 1605, + "hit_rate_at_1": 0.45794392523364486, + "hit_rate_at_5": 0.7046728971962617, + "hit_rate_at_20": 0.8292834890965732, + "corrected": 4, + "regressed": 0, + "misses": 870 + }, + "instrument_energy:QTOF/missing": { + "queries": 899, + "hit_rate_at_1": 0.43381535038932145, + "hit_rate_at_5": 0.6596218020022246, + "hit_rate_at_20": 0.8042269187986651, + "corrected": 20, + "regressed": 18, + "misses": 509 + }, + "peak_count_energy:1-5/known": { + "queries": 1209, + "hit_rate_at_1": 0.6013234077750207, + "hit_rate_at_5": 0.7857733664185277, + "hit_rate_at_20": 0.8610421836228288, + "corrected": 2, + "regressed": 0, + "misses": 482 + }, + "peak_count_energy:1-5/missing": { + "queries": 2801, + "hit_rate_at_1": 0.18779007497322384, + "hit_rate_at_5": 0.3423777222420564, + "hit_rate_at_20": 0.5694394858978936, + "corrected": 39, + "regressed": 17, + "misses": 2275 + }, + "peak_count_energy:11-32/known": { + "queries": 4365, + "hit_rate_at_1": 0.7665521191294388, + "hit_rate_at_5": 0.8849942726231386, + "hit_rate_at_20": 0.922794959908362, + "corrected": 1, + "regressed": 0, + "misses": 1019 + }, + "peak_count_energy:11-32/missing": { + "queries": 2578, + "hit_rate_at_1": 0.36578743211792086, + "hit_rate_at_5": 0.5492629945694336, + "hit_rate_at_20": 0.7071373157486424, + "corrected": 53, + "regressed": 40, + "misses": 1635 + }, + "peak_count_energy:33+/known": { + "queries": 2906, + "hit_rate_at_1": 0.7470750172057812, + "hit_rate_at_5": 0.8812801101169994, + "hit_rate_at_20": 0.9222298692360633, + "corrected": 0, + "regressed": 2, + "misses": 735 + }, + "peak_count_energy:33+/missing": { + "queries": 1915, + "hit_rate_at_1": 0.4621409921671018, + "hit_rate_at_5": 0.6793733681462141, + "hit_rate_at_20": 0.8073107049608355, + "corrected": 34, + "regressed": 35, + "misses": 1030 + }, + "peak_count_energy:6-10/known": { + "queries": 1495, + "hit_rate_at_1": 0.7016722408026755, + "hit_rate_at_5": 0.8394648829431438, + "hit_rate_at_20": 0.8989966555183947, + "corrected": 2, + "regressed": 0, + "misses": 446 + }, + "peak_count_energy:6-10/missing": { + "queries": 2160, + "hit_rate_at_1": 0.2449074074074074, + "hit_rate_at_5": 0.40879629629629627, + "hit_rate_at_20": 0.6134259259259259, + "corrected": 41, + "regressed": 15, + "misses": 1631 + } + }, + "molecule_groups": { + "count": 3185, + "unweighted_mean_hit1": 0.6792884908539226, + "zero_hit_groups": 648, + "all_hit_groups": 1732, + "largest10_groups_queries": 1581, + "largest10_groups_misses": 1239, + "total_misses": 9253, + "largest10_groups_misses_fraction": 0.1339025181022371 + }, + "overall_changes": { + "queries": 19429, + "hit_rate_at_1": 0.5237531525039889, + "hit_rate_at_5": 0.6787791445776932, + "hit_rate_at_20": 0.7917031241957898, + "corrected": 172, + "regressed": 109, + "misses": 9253 + }, + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "wall_seconds": 2.8904027258977294, + "purpose": "validation diagnostics only; no inference answers or query-specific rules" +} + +E077 prepared: {"changed_factor": "E071 inverse component E073 replaced with independently replayed E076; public routing, native weights and scores fixed", "compute": "measured conservative component sum, explicitly not a new full native GPU replay", "fitting": "none; validation selection only", "hypothesis": "E075 mass-noise encoder addition improves the weak inverse branch without changing known-energy proton native ranking.", "publication": "manual after driver exit0, all metrics and final runtime byte equality; no automatic promotion", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "seed": "inherited task-trained components; molecule-bootstrap seed0", "validation": "exact unchanged native assets/parent source/public input identity; changed9695-query branch replay, full combined official metrics, end-to-end unseen/order/immutability probes, MCES"} + +E078 prepared: {"calibration_sha256": "1a068f220fb36b65429e28ca7cb2f79b7cda01fa88a7cee4516333184cd7ad27", "changed_factor": "E043 seed1 recipe plus identical E064 synthetic missing-energy peak m/z noise; no other training or inference factor changed", "hypothesis": "Mass-noise augmentation that improved radius2 fallback will improve or complement radius3 structural fingerprints.", "noise": "training-only E016 precursor residual mixture used as a fragment-error proxy; independent peak residuals, per-row mixture scale, clamp +/-20ppm; only synthetic missing-CE rows; separate resumed noise RNG37001", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100; waits E074training/scoring completion; cap.16; may overlap E053native inference", "seed": 1, "selection": "fullvalidation raw radius3 Hit1, then fixed calibrated scoring vs matched E043 and finite E079 ensemble family", "training": "random initialization; training labels and held-out-clean supplied simulations only; 40x1200x512 updates; real.25; max32real/10synth peaks; lr.0003; CE dropout.5"} + +E079 prepared: {"changed_factor": "only radius3 probability ensemble: E043/E058 control, replace E043 with E078, or add E078; E075 selected nine radius2 members and .75/.25/mass.05 fixed", "control": "every true rank must exactly equal E075 add; E076 actual package separately reported", "fitting": "none; finite global validation selection", "hypothesis": "E078 synthetic mass noise improves or complements radius3 component after radius2 noise addition.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100; cap.22; waits E078 training/scoring and E076 actualverification", "seed": "E078seed1 and inherited components, bootstrapseed0"} + +E080 capacity experiment prepared: {"changed_factor": "E064 mass-noise recipe capacity from width384/depth4 to width512/depth6; other learning/data/augmentation factors fixed", "hypothesis": "A larger peak transformer can model structural ambiguity beyond the current 384-wide four-layer encoder and complement its mass-noise representation.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100, cap.25; two-step capacity/memory smoke first, full fit waits E079; no baseline retraining", "seed": 1, "smoke": "two optimizer steps + full validation forward solely a pipeline/resource check; not scientific model selection, full run starts from random seed1", "training": "random initialization, 40x1200x512, lr.0003, train/clean synthetic real.25, max32/10peaks, CE dropout.5, fixed training-derived mass noise", "validation": "select raw Hit1 checkpoint; fixed E076 nine-member radius2 control vs E064 replacement vs tenth-member addition; fixed radius3 and score weights"} + +E080 capacity smoke passed: {"optimizer_steps": 2, "overlap": "E053native, E068jointmetric fitting, E076/E077inverse verification all singleH100", "parameters": 26186880, "passed": true, "purpose": "capacity/memory check only, random full run starts independently", "source_byte_identity": true, "training_smoke": {"best_hit_at_1": 0.0030366977199032374, "max_cuda_allocated": 11054650880, "wall_seconds": 15.474893126171082}}; full random-initialized capacity experiment queued after E079. No scientific smoke model selection. + +E076 verified actual inverse replay: {"actual_overlap": "E053native, E068joint fitting, E077changed-inverse replay, brief E080capacitysmoke; E069/E074 had not started during main E076replay.", "internal_replay_comparison": {"authority": "actual independently relocated package replay", "hit1_outcome_differences": 1, "queries": 19429, "true_rank_differences": 7}, "metrics": {"hit_rate_at_1": 0.48484224612692367, "hit_rate_at_20": 0.8013793813371763, "hit_rate_at_5": 0.6615368778629883, "mces_at_1": 8.948015852591487}, "paired_baseline_delta": {"confidence": 0.95, "estimate": 0.0037572700602192598, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0009988080504842612, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.006832425750589165}, "replay": {"elapsed_seconds": 165.38881245302036, "finished_utc": "2026-10-21T09:27:51.135409+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 shared with E053nativebatch32 and E068joint-metric fitting, E069scorefamily or E074sodiumfitting; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-xngvzlsv/model.pt", "sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052"}, "model_config": ".versions/generation-xngvzlsv/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 16934567936, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "returncode": 0, "sampled_total_cpu_seconds": 566.1, "started_utc": "2026-10-21T09:25:05.746588+00:00"}, "selection": "add", "status": "verified inverse component; current conditional root requires separate changed-branch evaluation before promotion"} + +E069 completed: { + "results": { + "0.0": { + "hit_rate_at_1": 0.4761953780431314, + "hit_rate_at_5": 0.6539193988367904, + "hit_rate_at_20": 0.792578104894745, + "paired_delta_vs_matched_E050_control": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E054actual_context": { + "estimate": -5.146945287971589e-05, + "lower": -0.00017473599707279371, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "0.125": { + "hit_rate_at_1": 0.48149673168974216, + "hit_rate_at_5": 0.6623089196561841, + "hit_rate_at_20": 0.7988573781460703, + "paired_delta_vs_matched_E050_control": { + "estimate": 0.005301353646610736, + "lower": 4.994365331421187e-05, + "upper": 0.010110043950559464, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E054actual_context": { + "estimate": 0.005249884193731021, + "lower": 4.871006010391107e-05, + "upper": 0.010034263872515638, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "0.25": { + "hit_rate_at_1": 0.47892325904575633, + "hit_rate_at_5": 0.6624633280148232, + "hit_rate_at_20": 0.7965412527664831, + "paired_delta_vs_matched_E050_control": { + "estimate": 0.002727881002624942, + "lower": -0.005347955696606573, + "upper": 0.010645500685060552, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E054actual_context": { + "estimate": 0.0026764115497452264, + "lower": -0.00547411904666626, + "upper": 0.010596571071520648, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "0.5": { + "hit_rate_at_1": 0.45437233002213184, + "hit_rate_at_5": 0.6491327397189768, + "hit_rate_at_20": 0.7870194039837356, + "paired_delta_vs_matched_E050_control": { + "estimate": -0.021823048020999537, + "lower": -0.03357713685245854, + "upper": -0.010619329880173847, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E054actual_context": { + "estimate": -0.02187451747387925, + "lower": -0.0336319186491221, + "upper": -0.010671394736882493, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "1.0": { + "hit_rate_at_1": 0.38499150754027484, + "hit_rate_at_5": 0.5865458850172423, + "hit_rate_at_20": 0.7365793401616141, + "paired_delta_vs_matched_E050_control": { + "estimate": -0.09120387050285655, + "lower": -0.10764168375745757, + "upper": -0.0747090156080425, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E054actual_context": { + "estimate": -0.09125533995573627, + "lower": -0.10774245658308147, + "upper": -0.07478963862136262, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + } + }, + "selected": "0.125", + "wall_seconds": 12.783728239126503, + "max_cuda_allocated": 9462268928, + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "joint_checkpoint_sha256": "5325e9c083efc5f49b25e05ca06a75d419a2306fec72dcc6ef02089183c15c59", + "fitting": "none; fixed five-rule score mixture, validation selection only; independent package replay required" +} +E081 prepared: {"changed_factor": "fixed alpha.125 joint score vs alpha0; M2 E075 selected nine members, M3 E043/E058, .75/.25 and mass term unchanged", "control": "every true rank must equal E075add; actual E076 separate context", "fitting": "none; no new weight search; validation transfer check", "hypothesis": "The small learned-metric score contribution selected in E069 transfers to the stronger E076 fingerprint ensemble.", "joint_checkpoint_sha256": "5325e9c083efc5f49b25e05ca06a75d419a2306fec72dcc6ef02089183c15c59", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100,cap.22; overlaps E053native,E074sodiumfit,E068verification andE077wholepackageprobes", "seed": "inherited E068seed1 and trained ensemble seeds; bootstrap0"} + +E068 training completed: {"selection": {"checkpoint_sha256": "5325e9c083efc5f49b25e05ca06a75d419a2306fec72dcc6ef02089183c15c59", "cosine_loss": 0.4662385120143475, "elapsed_seconds": 222.0871567139402, "embedding_hit_rate_at_1": 0.33661022183334194, "embedding_hit_rate_at_20": 0.6808379226928818, "embedding_hit_rate_at_5": 0.5254001749961398, "epoch": 9, "epoch_seconds": 23.21006054012105, "fingerprint_hit_rate_at_1": 0.3523084049616553, "fingerprint_hit_rate_at_20": 0.6784188584075351, "fingerprint_hit_rate_at_5": 0.5209223325956045, "hit_rate_at_1": 0.38499150754027484, "hit_rate_at_20": 0.7365793401616141, "hit_rate_at_5": 0.5865458850172423, "selected_on": "full validation learned-metric+fixedmass Hit@1", "train_loss": 0.3035000361253818}, "status": "fitting complete; independent package replay and MCES ongoing; E069selectedsmallscoreweight must transfer and replay before publication", "training": {"best_hit_at_1": 0.38499150754027484, "max_cuda_allocated": 12611336704, "wall_seconds": 485.5093306619674}} + +E077 component-based full validation completed: {"checkpoint_sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052", "conservative_component_wall_sum": 1614.8027452598326, "metrics": {"hit_rate_at_1": 0.5272530752998096, "hit_rate_at_20": 0.7939163106696175, "hit_rate_at_5": 0.68114673941016, "mces_at_1": 8.104405785166504}, "paired_delta_vs_E071": {"confidence": 0.95, "estimate": 0.0034999227958206806, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0012307313793415602, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.006381059181719397}, "probe_wall_seconds": 143.91855189297348, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "verification": {"configuration_changes": {"inverse_checkpoint_sha256": ["e900ae617e43ed90b9b3e7b8992c0aecbdb3636d3edc88a3ed5cbadef56dbf33", "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052"]}, "native_asset_files": 190, "native_input_hashes_equal": true, "parent_inference_source_equal": true, "unchanged_native_runtime_assets": true, "verification_kind": "changed inverse branch replay plus unchanged native branch reuse from E041fullreplay (also E071native branch) and end-to-end arbitrary-input probes"}}. Selection uses validation Hit@1; paired molecule-group interval is reported without a test claim. No new full native GPU replay: identical native component and exact public partition reuse the E041 actual replay; changed inverse branch is independently replayed and complete combined rankings officially scored. Atomic publication follows byte-equality to the probed package. + +E081 completed and rejected for conditional publication: {"conditional": {"authority": "internal composition only; changedbranchreplay required", "metrics": {"1": 0.5255031139018992, "20": 0.78985022389212, "5": 0.680426167069844}, "paired_delta_vs_E077": {"confidence": 0.95, "estimate": -0.0017499613979103403, "grouping": "supplied target_inchikey connectivity block", "lower": -0.005270275782435761, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0016878599609486018}}, "future": "may be considered only in a separately evaluated native score fusion; no published change", "global": {"fitting": "none; fixed E069 selected alpha0.125 versus zero transferred to E076, validation selection only; independent package replay required", "joint_checkpoint_sha256": "5325e9c083efc5f49b25e05ca06a75d419a2306fec72dcc6ef02089183c15c59", "max_cuda_allocated": 9462268928, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"0.0": {"hit_rate_at_1": 0.48479077667404397, "hit_rate_at_20": 0.8013793813371763, "hit_rate_at_5": 0.6615368778629883, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -5.146945287971589e-05, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0001602466273080509, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "0.125": {"hit_rate_at_1": 0.48901127181018067, "hit_rate_at_20": 0.802357300941891, "hit_rate_at_5": 0.6675073343970354, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": 0.004169025683256987, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0008724306664859341, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.009102203667280416}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": 0.004220495136136703, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0008026351320140169, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.00911671530375389}}}, "selected": "0.125", "wall_seconds": 12.625122794881463}, "selection": "do not replace E077 inverse branch; internal mixed model improves aggregate inverse Hit1 but regresses conditional package fallback"} + +E077 atomically published: {"inverse_checkpoint_sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052", "manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-v8hmsjfo/native/.versions/generation-z3iv_pqm/native/.versions/generation-5y79tkae/glacier.ckpt", "sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "model_config": ".versions/generation-v8hmsjfo/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 experimental train and supplied held-out-clean ICEBERG simulations; validation only for selection", "pretrained_assets": []}}, "metrics": {"hit_rate_at_1": 0.5272530752998096, "hit_rate_at_20": 0.7939163106696175, "hit_rate_at_5": 0.68114673941016, "mces_at_1": 8.104405785166504}, "published_utc": "2026-10-21T09:33:07.645105+00:00", "runtime_equality": {"excluded": "research records, EXPERIMENTS, top-level README, bytecode caches", "files": 208, "new_generation": "/workspace/research/E077/selected-final/.versions/generation-ggl4qs_4", "primary_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "reference_generation": "/workspace/research/E077/relocated-package/.versions/generation-_z133gis", "runtime_asset_equality": true}, "verification": "component-based exact unchanged-native runtime and input proof, changed inverse independent replay and end-to-end probes; no new full native GPU replay"} +E077 MCES paired delta versus E071: { + "direction": "negative means lower MCES and better", + "metric": "candidate MCES@1 minus baseline MCES@1", + "exact_full_denominator_delta": -0.08085851047403365, + "molecule_bootstrap": { + "estimate": -0.08085851047403365, + "lower": -0.15841841074643648, + "upper": -0.017407455068814106, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "changed_queries": 600, + "queries": 19429, + "compute": { + "new_pairs": 0, + "workers": 2, + "wall_seconds": 5.968013674020767, + "options": "same official MCES settings as score_mces.py; unchanged predictions cancel exactly" + } +} +E077 condition/molecule-group error analysis: { + "strata": { + "adduct_energy:[M+H]+/known": { + "queries": 9734, + "hit_rate_at_1": 0.7431682761454695, + "hit_rate_at_5": 0.8750770495171564, + "hit_rate_at_20": 0.9161701253338812, + "corrected": 0, + "regressed": 0, + "misses": 2500 + }, + "adduct_energy:[M+H]+/missing": { + "queries": 4958, + "hit_rate_at_1": 0.35175473981444133, + "hit_rate_at_5": 0.5286405808793868, + "hit_rate_at_20": 0.6942315449778136, + "corrected": 46, + "regressed": 26, + "misses": 3214 + }, + "adduct_energy:[M+Na]+/known": { + "queries": 241, + "hit_rate_at_1": 0.23651452282157676, + "hit_rate_at_5": 0.46473029045643155, + "hit_rate_at_20": 0.7427385892116183, + "corrected": 1, + "regressed": 3, + "misses": 184 + }, + "adduct_energy:[M+Na]+/missing": { + "queries": 4496, + "hit_rate_at_1": 0.26890569395017794, + "hit_rate_at_5": 0.44105871886120995, + "hit_rate_at_20": 0.6419039145907474, + "corrected": 73, + "regressed": 23, + "misses": 3287 + }, + "instrument_energy:/missing": { + "queries": 486, + "hit_rate_at_1": 0.4506172839506173, + "hit_rate_at_5": 0.7057613168724279, + "hit_rate_at_20": 0.8600823045267489, + "corrected": 10, + "regressed": 2, + "misses": 267 + }, + "instrument_energy:Orbitrap/known": { + "queries": 8370, + "hit_rate_at_1": 0.7836320191158901, + "hit_rate_at_5": 0.8959378733572282, + "hit_rate_at_20": 0.9278375149342891, + "corrected": 1, + "regressed": 0, + "misses": 1811 + }, + "instrument_energy:Orbitrap/missing": { + "queries": 8069, + "hit_rate_at_1": 0.28937910521749904, + "hit_rate_at_5": 0.4537117362746313, + "hit_rate_at_20": 0.6428305861940761, + "corrected": 92, + "regressed": 39, + "misses": 5734 + }, + "instrument_energy:QTOF/known": { + "queries": 1605, + "hit_rate_at_1": 0.45607476635514016, + "hit_rate_at_5": 0.7046728971962617, + "hit_rate_at_20": 0.8292834890965732, + "corrected": 0, + "regressed": 3, + "misses": 873 + }, + "instrument_energy:QTOF/missing": { + "queries": 899, + "hit_rate_at_1": 0.44382647385984425, + "hit_rate_at_5": 0.6674082313681868, + "hit_rate_at_20": 0.8042269187986651, + "corrected": 17, + "regressed": 8, + "misses": 500 + }, + "peak_count_energy:1-5/known": { + "queries": 1209, + "hit_rate_at_1": 0.6004962779156328, + "hit_rate_at_5": 0.7866004962779156, + "hit_rate_at_20": 0.8610421836228288, + "corrected": 0, + "regressed": 1, + "misses": 483 + }, + "peak_count_energy:1-5/missing": { + "queries": 2801, + "hit_rate_at_1": 0.18921813637986434, + "hit_rate_at_5": 0.3405926454837558, + "hit_rate_at_20": 0.5655123170296322, + "corrected": 16, + "regressed": 12, + "misses": 2271 + }, + "peak_count_energy:11-32/known": { + "queries": 4365, + "hit_rate_at_1": 0.7665521191294388, + "hit_rate_at_5": 0.8849942726231386, + "hit_rate_at_20": 0.9232531500572738, + "corrected": 0, + "regressed": 0, + "misses": 1019 + }, + "peak_count_energy:11-32/missing": { + "queries": 2578, + "hit_rate_at_1": 0.373933281613654, + "hit_rate_at_5": 0.5546935608999224, + "hit_rate_at_20": 0.7137315748642359, + "corrected": 35, + "regressed": 14, + "misses": 1614 + }, + "peak_count_energy:33+/known": { + "queries": 2906, + "hit_rate_at_1": 0.7474191328286304, + "hit_rate_at_5": 0.8812801101169994, + "hit_rate_at_20": 0.9222298692360633, + "corrected": 1, + "regressed": 0, + "misses": 734 + }, + "peak_count_energy:33+/missing": { + "queries": 1915, + "hit_rate_at_1": 0.4715404699738903, + "hit_rate_at_5": 0.6825065274151436, + "hit_rate_at_20": 0.808355091383812, + "corrected": 33, + "regressed": 15, + "misses": 1012 + }, + "peak_count_energy:6-10/known": { + "queries": 1495, + "hit_rate_at_1": 0.7003344481605351, + "hit_rate_at_5": 0.8394648829431438, + "hit_rate_at_20": 0.9003344481605351, + "corrected": 0, + "regressed": 2, + "misses": 448 + }, + "peak_count_energy:6-10/missing": { + "queries": 2160, + "hit_rate_at_1": 0.2574074074074074, + "hit_rate_at_5": 0.42268518518518516, + "hit_rate_at_20": 0.6277777777777778, + "corrected": 35, + "regressed": 8, + "misses": 1604 + } + }, + "molecule_groups": { + "count": 3185, + "unweighted_mean_hit1": 0.6814866115781745, + "zero_hit_groups": 639, + "all_hit_groups": 1738, + "largest10_groups_queries": 1581, + "largest10_groups_misses": 1206, + "total_misses": 9185, + "largest10_groups_misses_fraction": 0.13130103429504628 + }, + "overall_changes": { + "queries": 19429, + "hit_rate_at_1": 0.5272530752998096, + "hit_rate_at_5": 0.68114673941016, + "hit_rate_at_20": 0.7939163106696175, + "corrected": 120, + "regressed": 52, + "misses": 9185 + }, + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "wall_seconds": 2.850625252816826, + "purpose": "validation diagnostics only; no inference answers or query-specific rules" +} + +E067 CPU parallelization verified and queued: {"change": "CPU scheduling only; no scientific rule/input/weights changes", "helper_sha256": "ca98113b2ac11bc525d605c30860a128ff02a878846b29fcaec3bc4080320496", "measured": {"comparison": "all internal distances equal E063 serial calculation; only CPU scheduling changes", "fine_distances_exact": true, "labels_read": false, "missing_energy_coarse_distances_exact": true, "prediction_sha256": "c295d810bcbe0ddd009b708139becf81b08e03745b5399f86814bb09564074c0", "queries": 1024, "query_input_sha256": "daf27ef35debf6caba29c07f3d6293547a95f0b5817dbb1860b8924aaf2f9ad3", "shared_state": "none; independent read-only HDF5 handles", "source_sha256": "ca98113b2ac11bc525d605c30860a128ff02a878846b29fcaec3bc4080320496", "wall_seconds": 30.47427133237943, "workers": 4}, "old_waiting_driver_stopped_before_scoring": true, "source_sha256": "adb422cd3a880433cf1ec459d4099bbebd30c58c42a0baaf70675aea0870f0b5", "status": "Four-worker implementation selected after exact serial-distance comparison on all1024screen queries, fine and missing-energy coarse bins. Full E053actual ranking control remains mandatory."} + +E082 prepared: {"changed_factor": "E064 recipe real-row sampling only: weights1/count(training targetSMILES), synthetic rows unchanged; preserve parent defaultRNG consumption using separate generator57001", "hypothesis": "Uniform experimental molecule sampling improves unseen-structure generalization by reducing repeated-spectrum dominance.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100; queue after E080; cap.16", "runtime": "same generic encoder, no query-fitted parameters or stored label lookup", "seed": 1, "training": "random width384depth4; same E064 40x1200x512/real.25/CEdrop.5/mass-noise recipe; only experimental training SMILES counts set sampling weights", "validation": "raw checkpoint selection; fixed E076 inverse control vs replace E064 or add E082; molecule-group intervals; no fitted validation weights"} + +E074 completed negative sodium specialist experiment: {"decision": "control selected; all Na expert mixture weights regress Hit1/5/20. Reject specialist publication; no transfer or runtime change needed.", "family": {"fitting": "none; fixedfour-weight sodiumspecialist family, validation selection only", "formula": "Na-onlyfixedprobabilitymixture inradius2, fixed.75/.25cross-radius and.05mass", "max_cuda_allocated": 9490288128, "new_member_checkpoint_sha256": "1c422d8f3e2cdbbe7b6db1b2bb2d2dd980fe8b70854782ff4055795d004030f4", "overlap": "soleH100 may share E053nativebatch32; followsE074fitting; allocatorcap.22", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"beta0.25": {"hit_rate_at_1": 0.4802099953677492, "hit_rate_at_20": 0.7971588862010397, "hit_rate_at_5": 0.6552576046116629, "paired_delta_vs_E072matched_control": {"confidence": 0.95, "estimate": -0.0008749806989551701, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0035937146042862174, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0013702331937595683}, "paired_delta_vs_E073actual_context": {"confidence": 0.95, "estimate": -0.0008749806989551701, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0035937146042862174, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0013702331937595683}, "radius2_members": ["E060", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"], "sodium_probability_weight": 0.25}, "beta0.5": {"hit_rate_at_1": 0.4797467702918318, "hit_rate_at_20": 0.7941221884811365, "hit_rate_at_5": 0.6536105821195121, "paired_delta_vs_E072matched_control": {"confidence": 0.95, "estimate": -0.0013382057748726132, "grouping": "supplied target_inchikey connectivity block", "lower": -0.004579423127097465, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0014744888570953534}, "paired_delta_vs_E073actual_context": {"confidence": 0.95, "estimate": -0.0013382057748726132, "grouping": "supplied target_inchikey connectivity block", "lower": -0.004579423127097465, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0014744888570953534}, "radius2_members": ["E060", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"], "sodium_probability_weight": 0.5}, "beta1.0": {"hit_rate_at_1": 0.47542333624993566, "hit_rate_at_20": 0.7877399763240517, "hit_rate_at_5": 0.647640125585465, "paired_delta_vs_E072matched_control": {"confidence": 0.95, "estimate": -0.005661639816768748, "grouping": "supplied target_inchikey connectivity block", "lower": -0.010349330270905193, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0013925321496790545}, "paired_delta_vs_E073actual_context": {"confidence": 0.95, "estimate": -0.005661639816768748, "grouping": "supplied target_inchikey connectivity block", "lower": -0.010349330270905193, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0013925321496790545}, "radius2_members": ["E060", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"], "sodium_probability_weight": 1.0}, "control": {"hit_rate_at_1": 0.4810849760667044, "hit_rate_at_20": 0.7986515003345515, "hit_rate_at_5": 0.6577281383498893, "paired_delta_vs_E072matched_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "paired_delta_vs_E073actual_context": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "radius2_members": ["E060", "E007", "E009", "E017", "E021", "E023", "E042", "E033"], "radius3_members": ["E043", "E058"], "sodium_probability_weight": 0.0}}, "selected": "control", "wall_seconds": 125.74052161583677}, "selection": {"checkpoint_sha256": "1c422d8f3e2cdbbe7b6db1b2bb2d2dd980fe8b70854782ff4055795d004030f4", "cosine_loss": 0.4892837789080896, "elapsed_seconds": 88.45978281181306, "epoch": 4, "epoch_seconds": 19.212505663279444, "hit_rate_at_1": 0.29167738946934996, "hit_rate_at_20": 0.6220083380513665, "hit_rate_at_5": 0.46178393123681094, "selected_on": "validation sodium raw retrieval Hit@1; globalmetrics reported separately", "sodium_hit_rate_at_1": 0.1923158116951657, "sodium_hit_rate_at_20": 0.5144606290901415, "sodium_hit_rate_at_5": 0.3411441840827528, "train_loss": 0.27593306042253973}, "training": {"best_sodium_hit_at_1": 0.1923158116951657, "max_cuda_allocated": 9631823360, "wall_seconds": 406.9103051861748}} + +E083 setup-only syntax failure and correction: { + "error": "SyntaxError in generated unlaunched driver: conditional expression had else6 without space. AST validation failed before run.py was written. Subsequent shell launch reported missingrun.py.", + "scientific_work_started": false, + "weights_or_inputs_changed": false, + "fix": "Regenerate from verified E052 driver and AST-check before launch", + "utc": "2026-10-21T09:40:56.827666+00:00" +} +E083 native loading optimization prepared: {"changed_factor": "num-cpu-workers6->12 only; native4000batch32, prefetch1, cache64 and allotherflags unchanged", "fitting": "none; no baseline retraining", "hypothesis": "More CPU graph-loading workers reduce native inference stalls while preserving batch32 numerical behavior.", "prediction_control_sha256": "c295d810bcbe0ddd009b708139becf81b08e03745b5399f86814bb09564074c0", "query_set_sha256": "84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e", "resource": "one H100; waitsE053 andE061; CPUworkers12,mainTorch4; RSS measured against64GiBreplaylimit", "seed": "none; frozen checkpoint and inference inputs", "selection": "exactlyunchangedcomplete rankings, within64GiB andobservedfaster; old6worker timings carryoverlapcaveat"} + +E084 native confidence substitution prepared: {"changed_factor": "only within-shortlist inverse confidence: E014control vs E076 vs E081 fixed.125joint; E014top20candidatecoverage/tail, native2000entropycoef1, and E077otherbranch fixed", "control": "every cached-score reconstructed native ranking must exactly equal actual E041/E077 ranking, all9734knownH; allotherqueries unchanged", "fitting": "none; finite three-rule validation selection", "hypothesis": "Stronger inverse confidence improves the native known-energy proton reranker; learned joint metric may complement native evidence despite failing the fallback branch.", "inverse_checkpoint_sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052", "joint_checkpoint_sha256": "5325e9c083efc5f49b25e05ca06a75d419a2306fec72dcc6ef02089183c15c59", "native_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "publication": "screening only; actual reranker and wholepackage verification required if better; cache never packaged", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "one H100 cap.22; brief scorer overlaps E053/E078, no native resimulation"} + +E084 complete cached-score study: { + "results": { + "control": { + "hit_rate_at_1": 0.5272530752998096, + "hit_rate_at_5": 0.68114673941016, + "hit_rate_at_20": 0.7939163106696175, + "paired_delta_vs_E077": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "inverse_E076": { + "hit_rate_at_1": 0.5326573678521798, + "hit_rate_at_5": 0.6835658036955067, + "hit_rate_at_20": 0.7939163106696175, + "paired_delta_vs_E077": { + "estimate": 0.0054042925523701685, + "lower": 0.0028906205030719864, + "upper": 0.008196112339539693, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "inverse_E081": { + "hit_rate_at_1": 0.5323485511349014, + "hit_rate_at_5": 0.6842863760358228, + "hit_rate_at_20": 0.7939163106696175, + "paired_delta_vs_E077": { + "estimate": 0.005095475835091873, + "lower": 0.0022705611196342027, + "upper": 0.007994608950895732, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + } + }, + "selected": "inverse_E076", + "wall_seconds": 29.05202161381021, + "max_cuda_allocated": 9457426944, + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "raw_native_score_sha256": "fadb530e82b920eeecdbbee85da2075dccbf3646fa1a1b4d0e9daa9fa4cc90b5", + "cache_manifest": { + "native_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", + "source": "completed E029 known-energy proton native simulation and exact public-input baseline/routing", + "labels_copied": false, + "purpose": "explicit development-only forward score studies; not a package asset or inference dependency", + "reuse_status": "only identical query/candidate/condition rescoring permitted before additional determinism checks", + "wait_seconds": 711.2867428287864, + "copy_seconds": 2.111660035327077, + "files": { + "preds.hdf5": { + "sha256": "48be68620f4e7c07b08e0348224f6ceb7eeca8af3c4474d4abc1208642c9eb42", + "bytes": 829607488 + }, + "candidates.tsv": { + "sha256": "7886b51a7fb4f029734d96e9d47f5697186335915176587391857f77072d6b10", + "bytes": 37749015 + }, + "queries.jsonl": { + "sha256": "460c6751dc3723ac8e38871a2694b378f93e54126a1dc6c912d4126e20a63ead", + "bytes": 8955287 + }, + "candidate_pools.jsonl": { + "sha256": "5a3151b857e10f371f329ad3fd5412a46d1890963b45983dfbe1511ef91892d6", + "bytes": 25642933 + }, + "routing.json": { + "sha256": "ed7bf5620019d42212b0360a8f9f3c7ff329bd05ef0c58a25a4170b87af09b8b", + "bytes": 18083542 + }, + "baseline-rankings.jsonl": { + "sha256": "eb127cefad5304dd39237fb10920cc36d115bc6985581d0bf28b4ad8c7342d5d", + "bytes": 167245106 + } + } + }, + "exact_all_published_control_rankings": true, + "rule": "Same E014 top20 coverage/tail and native2000 coefficient1; only inverse confidence within that shortlist changes; other conditions exactly E077.", + "fitting": "none; fixed three-rule validation comparison; actual reranker output and package verification required before publication", + "overlap": "one H100 shared with E053native inference and E078radius3 fitting; CPU MCES also active" +} +E085 independent confidence-reranker verification prepared: {"changed_factor": "within-knownHshortlist inverse score source E014->E076 only; selectorcoverage/tail, nativepredictor/checkpoint/coeff1, outerrouting/otherbranch fixed", "fitting": "none; E084preselectedrule; actual independent wholepackage fullreplay beforepromotion", "hypothesis": "E084 selected E076confidence improves fixed native2000/E014top20 proton retrieval and preserves E077otherbranch.", "native_checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "publication": "noautomaticrootpromotion; allactualmetrics/probesandfinalaudit required", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "reranker_checkpoint_sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052", "resource": "one H100; E053native andsmallfit mayoverlap, allcommon22CPUaffinity; fullreplaytime/RSS/ownedtempstorage measured", "seed": "inheritedtrainedseeds; moleculebootstrap0"} + +E061 queued resource scheduling update before any GPU work: {"gpu_work_started": false, "new_overlap": "may overlap E053CPUscore,E067parallelCPUrescore,E085nativeverification andsmallinversefitting onthe sameH100/common22CPUaffinity", "old_waiting_pid": 33897, "reason": "E061 depends on native prediction GPU availability, not E053 CPU scoring or labels. Start after E053 closedprediction capture AND predictorprocess exit, while serial CPU scoring continues. Avoid leaving single GPU idle.", "scientific_change": false, "utc": "2026-10-21T09:50:09.280560+00:00"} + +E083 queued scheduling clarification: {"old_waiting_pid": 37516, "reason": "Follow E061 resource reschedule and wait for E067 CPU rescoring before 12-worker loading benchmark; E053 serial CPU scoring may still continue.", "scientific_factors_changed": false, "scientific_work_started": false, "utc": "2026-10-21T09:51:11.103370+00:00"} + +E086 prepared training-IDF objective: { + "hypothesis": "Training the fingerprint predictor under the deployed training-IDF geometry improves candidate discrimination beyond post-hoc weighting alone.", + "changed_factor": "E064 training cosine term multiplied bysqrt(training-IDF) on both predicted and target fingerprints; BCE, data sampling, mass noise, modelsize, seed, schedule and rawcheckpoint-selection criterion unchanged", + "seed": 1, + "training": "randomwidth384depth4;40x1200x512lr.0003,real.25,32/10peaks,CEdrop.5,syntheticmissingCE massnoise; training-IDF vector independently checked against experimental training uniqueSMILES counts", + "validation": "same rawHit1 checkpointselection asE064; fixed E076ensemble control vsreplaceE064 vsaddE086; no fittedvalidationparameters", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "resource": "one H100 cap.16, queuedafterE082; actualtimes/overlaprecorded", + "runtime": "unchangedencoder; onlytrainingobjective differs" +}; calibration: {"independent_training_count_verification": true, "max_absolute_difference": 0.0, "source_checkpoint_sha256": "4b9bdcb42ff4dfc05f28b6fd1417f27c95892be2f29c8c403b6ccf9e7fc9f3ec", "training_smiles": 25046, "validation_used": false, "weights_sha256": "ba048079f070d8c5f3aab9c44ff64c4dbb83047e7d435bf8de0ce34f0322cded"} + +E078 training completed: { + "wall_seconds": 806.8537559020333, + "max_cuda_allocated": 9654274048, + "best_hit_at_1": 0.37269030830202277 +}; rawselection { + "checkpoint_sha256": "43b881ba34f9151af9bf810209d2247f1f0e0378e206ce5352b9a39c94149acd", + "selected_on": "full validation retrieval Hit@1", + "epoch": 38, + "train_loss": 0.36984320846696694, + "elapsed_seconds": 766.7747875610366, + "epoch_seconds": 19.4760820181109, + "hit_rate_at_1": 0.37269030830202277, + "hit_rate_at_5": 0.5357970044778424, + "hit_rate_at_20": 0.6933449997426527, + "cosine_loss": 0.5153030276918222 +}; calibrated { + "results": { + "raw": { + "hit_rate_at_1": 0.37269030830202277, + "hit_rate_at_5": 0.5357970044778424, + "hit_rate_at_20": 0.6933449997426527, + "paired_delta_vs_E043_matching_rule": { + "estimate": 0.012352668691131814, + "lower": 0.002791480029376408, + "upper": 0.02132912613269585, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "idf_mass": { + "hit_rate_at_1": 0.4392403108754954, + "hit_rate_at_5": 0.6171187400277935, + "hit_rate_at_20": 0.7684904009470379, + "paired_delta_vs_E043_matching_rule": { + "estimate": 0.011323279633537495, + "lower": 0.0033464912734910567, + "upper": 0.019865253843103142, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + } + }, + "wall_seconds": 6.413792695384473, + "checkpoint_sha256": "43b881ba34f9151af9bf810209d2247f1f0e0378e206ce5352b9a39c94149acd", + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "calibration": "radius3 IDF from unique experimental training molecules; unchanged E016 precursor mixture and fixed coefficient0.05", + "fitting": "no validation fitting" +} +E079 fixed-radius3 family completed: { + "results": { + "control": { + "radius3_members": [ + "E043", + "E058" + ], + "radius2_members": [ + "E060", + "E007", + "E009", + "E017", + "E021", + "E023", + "E042", + "E033", + "E064" + ], + "hit_rate_at_1": 0.48479077667404397, + "hit_rate_at_5": 0.6615368778629883, + "hit_rate_at_20": 0.8013793813371763, + "paired_delta_vs_E075matched_control": { + "estimate": 0.0, + "lower": 0.0, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E076actual_context": { + "estimate": -5.146945287971589e-05, + "lower": -0.0001602466273080509, + "upper": 0.0, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "replace": { + "radius3_members": [ + "E078", + "E058" + ], + "radius2_members": [ + "E060", + "E007", + "E009", + "E017", + "E021", + "E023", + "E042", + "E033", + "E064" + ], + "hit_rate_at_1": 0.48520253229708166, + "hit_rate_at_5": 0.6628236141849813, + "hit_rate_at_20": 0.802717587112049, + "paired_delta_vs_E075matched_control": { + "estimate": 0.0004117556230377271, + "lower": -0.002492382030532633, + "upper": 0.0033628016567529228, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E076actual_context": { + "estimate": 0.00036028617015801124, + "lower": -0.0025433451421542144, + "upper": 0.003308547527732643, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + }, + "add": { + "radius3_members": [ + "E043", + "E058", + "E078" + ], + "radius2_members": [ + "E060", + "E007", + "E009", + "E017", + "E021", + "E023", + "E042", + "E033", + "E064" + ], + "hit_rate_at_1": 0.4852540017499614, + "hit_rate_at_5": 0.6635956559781769, + "hit_rate_at_20": 0.8015852591486953, + "paired_delta_vs_E075matched_control": { + "estimate": 0.000463225075917443, + "lower": -0.0016413589666941402, + "upper": 0.0025999957134619253, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + }, + "paired_delta_vs_E076actual_context": { + "estimate": 0.0004117556230377271, + "lower": -0.0016581270663068312, + "upper": 0.0025398999676740715, + "confidence": 0.95, + "resamples": 2000, + "seed": 0, + "molecule_groups": 3185, + "queries": 19429, + "grouping": "supplied target_inchikey connectivity block", + "statistic": "spectrum-weighted mean; molecules sampled with replacement" + } + } + }, + "selected": "add", + "wall_seconds": 11.837327958084643, + "max_cuda_allocated": 9171501568, + "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", + "new_member_checkpoint_sha256": "43b881ba34f9151af9bf810209d2247f1f0e0378e206ce5352b9a39c94149acd", + "formula": "fixed.75E075selectedradius2_IDFcos +.25radius3group_IDFcos +fixed.05mass", + "fitting": "none; fixedthree-member-set family, validation selection only", + "overlap": "soleH100 may share E053native batch32 inference; waitsE078smallfitting andscorecomplete" +}; conditionalbranch {"control": {"metrics": {"1": 0.5272016058469299, "5": 0.68114673941016, "20": 0.7939163106696175}, "paired_delta_vs_E077": {"estimate": -5.146945287971589e-05, "lower": -0.0001602466273080509, "upper": 0.0, "confidence": 0.95, "resamples": 2000, "seed": 0, "molecule_groups": 3185, "queries": 19429, "grouping": "supplied target_inchikey connectivity block", "statistic": "spectrum-weighted mean; molecules sampled with replacement"}, "authority": "internal screening only; actual inverse replay beforepublication"}, "replace": {"metrics": {"1": 0.5272016058469299, "5": 0.6834628647897473, "20": 0.7953574553502496}, "paired_delta_vs_E077": {"estimate": -5.146945287971589e-05, "lower": -0.002722340735793718, "upper": 0.0024162619343378266, "confidence": 0.95, "resamples": 2000, "seed": 0, "molecule_groups": 3185, "queries": 19429, "grouping": "supplied target_inchikey connectivity block", "statistic": "spectrum-weighted mean; molecules sampled with replacement"}, "authority": "internal screening only; actual inverse replay beforepublication"}, "add": {"metrics": {"1": 0.5268413196767718, "5": 0.6831025786195892, "20": 0.7941736579340162}, "paired_delta_vs_E077": {"estimate": -0.0004117556230377271, "lower": -0.0021963032116808527, "upper": 0.0012183659996154903, "confidence": 0.95, "resamples": 2000, "seed": 0, "molecule_groups": 3185, "queries": 19429, "grouping": "supplied target_inchikey connectivity block", "statistic": "spectrum-weighted mean; molecules sampled with replacement"}, "authority": "internal screening only; actual inverse replay beforepublication"}} + +E087 cross-radius weight family prepared: {"changed_factor": "globalradius3 weight [0,.125,.25,.5,.75,1] only; currentE076 nineM2/twoM3members and mass.05fixed", "control": "alpha.25 everytrue rank matchesE075add; actualE076 differences separatelyreported", "fitting": "none; predefined finite globalmodelselection, no validationgradientfit", "hypothesis": "The relative value of radius2 andradius3 scores may change after the E060/E064 upgrades and secondradius3seed; a fixedcoarse weightfamily may improve the deployed mix.", "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "resource": "oneH100 cap.22;briefscore overlapsE053,E080andE085verification", "seed": "inheritedcomponents; bootstrap0", "selection": "reportinverse andcurrentE077conditional Hit1 withmoleculegroups; anycandidate also needsnativeconfidence reranker transfer andindependent packageverification"} + +E087 negative weightsearch completed: {"decision": "retain currentradius3 weight.25, selectedbybothinverseandconditionalHit1", "results": {"fitting": "none; fixed six-rule radius3 score weight family; same frozen groups and mass coefficient, validation selection only; independent package replay required", "max_cuda_allocated": 8533967360, "member_checkpoint_sha256": {"E007": "0440569a4a87aadf5571781bf60078b22bc11459abf153a2039ed229056087f2", "E009": "6960d7591a47579956d77ae2fed7257680d8fd6b0602bcda03865abdce412c0e", "E017": "15d84dfaaacf65ad9224f15f513f2689afffe4eecbff1b35ce8bc55cd1539248", "E021": "6033332c96b67d6b8384da54ec79d8c8a220dcb9998ffa6c3079944b5e3487c0", "E023": "025eb1297877bb16d496c49f58952dc22fde58e505cd41423ac28667b4bc87cb", "E033": "5f7ceeb8c23c2b06a730741f1da0698092f5a734230a8067251da5355f5899d2", "E042": "4448ab7a55cb304071a442b7ddd970851c211b975a2adefd3fe2d92b53619807", "E043": "0e826bbf817eae6d5fa8211a9602b4ac5b75b4da4d9bcc5b03646f521d7d2194", "E058": "cc9b112973b647fce0754538b1f53690cdb401bd7b4855886f89fb0d93a9b5dd", "E060": "38acc015ffa8f19f89853a4a660e07556ddbc2f45b7b07fde0276fab6cab72be", "E064": "dc030008171bb90240d31b0a42be73656bf212391e692230b229151b15ff3647"}, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "results": {"0.0": {"conditional_metrics": {"hit_rate_at_1": 0.5209223325956045, "hit_rate_at_20": 0.7926295743476247, "hit_rate_at_5": 0.6792423696536106, "paired_delta_vs_E077actual": {"confidence": 0.95, "estimate": -0.006330742704205054, "grouping": "supplied target_inchikey connectivity block", "lower": -0.010195855345325041, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0028219772188741786}, "paired_delta_vs_matched_control": {"confidence": 0.95, "estimate": -0.006279273251325338, "grouping": "supplied target_inchikey connectivity block", "lower": -0.010077289770838294, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0028072334528282334}}, "hit_rate_at_1": 0.4760409696844923, "hit_rate_at_20": 0.7983941530701528, "hit_rate_at_5": 0.6582428328786865, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -0.008801276442431416, "grouping": "supplied target_inchikey connectivity block", "lower": -0.013422192740052123, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.004217322439962465}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": -0.008749806989551702, "grouping": "supplied target_inchikey connectivity block", "lower": -0.01329080262221279, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.004204848374100111}}, "0.125": {"conditional_metrics": {"hit_rate_at_1": 0.5260178084306963, "hit_rate_at_20": 0.7927839827062638, "hit_rate_at_5": 0.6805291059756035, "paired_delta_vs_E077actual": {"confidence": 0.95, "estimate": -0.0012352668691131814, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0027903885358177096, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.00025967424015424414}, "paired_delta_vs_matched_control": {"confidence": 0.95, "estimate": -0.0011837974162334653, "grouping": "supplied target_inchikey connectivity block", "lower": -0.002740676416447556, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0003168994429258049}}, "hit_rate_at_1": 0.48304081527613363, "hit_rate_at_20": 0.7996808893921458, "hit_rate_at_5": 0.6599927942765969, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -0.0018014308507900562, "grouping": "supplied target_inchikey connectivity block", "lower": -0.004132318912973382, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0004284776490604485}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": -0.0017499613979103403, "grouping": "supplied target_inchikey connectivity block", "lower": -0.004097657240945164, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0004947788843059905}}, "0.25": {"conditional_metrics": {"hit_rate_at_1": 0.5272016058469299, "hit_rate_at_20": 0.7939163106696175, "hit_rate_at_5": 0.68114673941016, "paired_delta_vs_E077actual": {"confidence": 0.95, "estimate": -5.146945287971589e-05, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0001602466273080509, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "paired_delta_vs_matched_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "hit_rate_at_1": 0.48479077667404397, "hit_rate_at_20": 0.8013793813371763, "hit_rate_at_5": 0.6615368778629883, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -5.146945287971589e-05, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0001602466273080509, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": 0.0, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0}}, "0.5": {"conditional_metrics": {"hit_rate_at_1": 0.5257604611662978, "hit_rate_at_20": 0.7915487158371507, "hit_rate_at_5": 0.6792938391064903, "paired_delta_vs_E077actual": {"confidence": 0.95, "estimate": -0.0014926141335117609, "grouping": "supplied target_inchikey connectivity block", "lower": -0.0042258111712296, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0012266803518144597}, "paired_delta_vs_matched_control": {"confidence": 0.95, "estimate": -0.001441144680632045, "grouping": "supplied target_inchikey connectivity block", "lower": -0.004122777465943586, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.001260079676600035}}, "hit_rate_at_1": 0.48309228472901333, "hit_rate_at_20": 0.79890884759895, "hit_rate_at_5": 0.6587575274074836, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -0.0017499613979103403, "grouping": "supplied target_inchikey connectivity block", "lower": -0.005163471187635555, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0017932116133052033}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": -0.0016984919450306244, "grouping": "supplied target_inchikey connectivity block", "lower": -0.00503385316908625, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.001805782386505908}}, "0.75": {"conditional_metrics": {"hit_rate_at_1": 0.5227237634463946, "hit_rate_at_20": 0.7848062175099079, "hit_rate_at_5": 0.6737866076483607, "paired_delta_vs_E077actual": {"confidence": 0.95, "estimate": -0.004529311853414998, "grouping": "supplied target_inchikey connectivity block", "lower": -0.009047397096124782, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.00020250753699083485}, "paired_delta_vs_matched_control": {"confidence": 0.95, "estimate": -0.004477842400535282, "grouping": "supplied target_inchikey connectivity block", "lower": -0.008912313646159195, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.00019981412069475428}}, "hit_rate_at_1": 0.47547480570281536, "hit_rate_at_20": 0.7919090020073086, "hit_rate_at_5": 0.6493900869833754, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -0.009367440424108291, "grouping": "supplied target_inchikey connectivity block", "lower": -0.01522583926968767, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0038277231521889527}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": -0.009315970971228577, "grouping": "supplied target_inchikey connectivity block", "lower": -0.01518817224638592, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.0037731326248518654}}, "1.0": {"conditional_metrics": {"hit_rate_at_1": 0.5180915126872201, "hit_rate_at_20": 0.7744093880282052, "hit_rate_at_5": 0.664676514488651, "paired_delta_vs_E077actual": {"confidence": 0.95, "estimate": -0.009161562612589429, "grouping": "supplied target_inchikey connectivity block", "lower": -0.015137837478454296, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.003492400189772623}, "paired_delta_vs_matched_control": {"confidence": 0.95, "estimate": -0.009110093159709712, "grouping": "supplied target_inchikey connectivity block", "lower": -0.014981340217343377, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.003463835944737461}}, "hit_rate_at_1": 0.46080601163209634, "hit_rate_at_20": 0.7799166194863348, "hit_rate_at_5": 0.6348242318184157, "paired_delta_vs_E076actual_context": {"confidence": 0.95, "estimate": -0.02403623449482732, "grouping": "supplied target_inchikey connectivity block", "lower": -0.031787574189841517, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.016335673947666836}, "paired_delta_vs_matched_E075_control": {"confidence": 0.95, "estimate": -0.023984765041947603, "grouping": "supplied target_inchikey connectivity block", "lower": -0.03173189656064937, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": -0.016324358010999834}}}, "selected_by_conditional": "0.25", "selected_by_inverse": "0.25", "wall_seconds": 21.587388852145523}} + +E085 development-only closed-writer capture scheduled: exact HDF,candidate/publicnativeinputs,E014selector/routing,E076reranker scores/ranks, bytehash/sourceimmutability checked. Neverpackagecache oruseatinference. Readcopy mayadddiskcontention to measuredreplay. {"domain": "known-energy [M+H]+ publiccondition; E014 selector, E076 confidence", "native_batch_size": 32, "native_coefficient": 1.0, "native_export_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "reranker_checkpoint_sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052", "selector_checkpoint_sha256": "33f307d4f57bc0df4b2e5a3080cd5efa60e7c5e3e28648eda492a2f4b7a0709c", "top_k": 20} + +E084 selected cached-score output official metrics: {"hit_rate_at_1": 0.5326573678521798, "hit_rate_at_20": 0.7939163106696175, "hit_rate_at_5": 0.6835658036955067, "mces_at_1": 7.986772350609913}; MCEScompute {"pairs": 5627, "new_pairs": 83, "wall_seconds": 336.212524170056, "workers": 2, "options": "threshold=15, always_stronger_bound=True, PULP_CBC_CMD; exactly identical graphs return zero"}; pairedMCES {"direction": "negative means lower MCES and better", "metric": "candidate MCES@1 minus baseline MCES@1", "exact_full_denominator_delta": -0.11763343455659066, "molecule_bootstrap": {"estimate": -0.11763343455659066, "lower": -0.1645420823970152, "upper": -0.07437789082987745, "confidence": 0.95, "resamples": 2000, "seed": 0, "molecule_groups": 3185, "queries": 19429, "grouping": "supplied target_inchikey connectivity block", "statistic": "spectrum-weighted mean; molecules sampled with replacement"}, "changed_queries": 896, "queries": 19429, "compute": {"new_pairs": 0, "workers": 2, "wall_seconds": 6.5059804469347, "options": "same official MCES settings as score_mces.py; unchanged predictions cancel exactly"}}; independent package E085 replay remains ongoing, not yet published. + +E088/E089 prepared: paired own-native4000 fine-tunes with fresh AdamW1e-4,warmup50,seed1,B128,1000steps,retained500/1000,1024forward-loss validation. E088cosine control; E089onlychange existingentropy intensityloss. InitialfullcheckpointSHA83b28050fe3eee2226d9864d6704260ff93a12906249e6a75151e571b18a877a; strict parameter equality and MAGMa4000 restored, unchanged native source. TRAIN-only labels; no external initialization. Targets already sqrt normalized; max-training/sum-prediction pooling caveat explicitlyrecorded. Fixed1024retrievalscreenhash84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e, E040confidence/E018top64/nativecoef1/batch32. Wait earlier native screens/replay beforefullfit; noautomaticpromotion. E089 two-step isolated pipeline smoke starts first, no scientificselection. + +E089 first two-step smoke failed before fit at strict data-manifest identity assertion; inherited default selected operator GLACIERsubset, while own E003 used preparedall-conditionTRAINcache. 0steps,14.811808654s. Corrected explicit/default path to /cache/glacier-all, preservingassertions andunchangedscientificdataset. Failurelogs/source archived. E088/E089 drivers correctedbeforelaunch. + +E089 corrected entropy smoke passed: strictinitialparameter equality/MAGMa4000 preserved; 2steps B8, external 42.65545530570671s, training24.050506971s,peakCUDA1169820160bytes, finitevalentropy.766142785549; exporter succeeded. E088/E089 train source byteidentical. Fulltrials usefresh E003step4000 initialization, notsmoke. + +E090 prepared/queued after E080complete: larger-encoder transfer to nativeconfidence andfallback. Prespecified7rules: unchangedE084, E080replaceE064/add appliedtofallback/confidence/both. E014top20/native2000coef1/2M3weightsallfixed. ExactE084knownHfullorders andE080fullinversecontrols required. Fullvalqueryhash7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6; no fitting; selectedofficialHit1/5/20, moleculeCI andMCES. Noautomaticpublication; actualpackage needed if better. + +E091 launched CPU-only fixedmass-tolerant entropy study: samecachednative4000/E040confidence/E018top64/coef1; tolerance max20ppm,.002Da nearestobservedpeak, many-to-onepredictionintensitysum, unmatchedpredictionprobabilityretained. Threefixedrules finecontrol/missingCEonly/all. Requiremathematical endpoints/intensityconservation andeverycomplete1024 E049controlorder exact. Queryhash84cb02ac31cd0711f2fae667ec8c529f6bced72c00ee13b98565616cdb25035e. FourCPUworkers, overlapsE053/E085 native+E080fit; no labels used bymetric, noautomaticpromotion. Selectedmetrics/CI/MCESrecordedaftercompute. + +E092 fulltransfer queued forfixedE091 all-condition20ppm/.002Da entropy. E0911024screen Hit1 .5546875 ->.5693359375, delta.0146484375 molecule95CI[.003846061479,.026523035596]; Hit5.71875,Hit20.810546875. MCESstillpending whenqueued. E092waitsE091complete/E053actualcapture/E083exit; checksumallcapturefiles, recomputeexactfullE053controlbeforeofficialmetrics, 4CPUworkers. No additionalfit/rulechanges andnoautomaticrootpromotion. + +E091 COMPLETE: all-condition tolerant matching selected,Hit1.5693359375/Hit5.71875/Hit20.810546875/MCES6.73974609375 vsfinecontrol.5546875/.7041015625/.8115234375/MCES7.2451171875; +15/1024Hit1,molecule95CI[.003846061479,.026523035596]. Missingonly .5654296875/.7158203125/.80859375. ExactALLfinecontrolorderspassed; sanity/intensityconservationpassed. Compute48.347006392s total (parallel31.852982728s), MCES9newpairs35.945451006s. NativeSHA8600c82817533b0d8bca768c14bfdb17cca4b75f3ce1e773615ff9ada4f62527; cachedpredictionSHAc295d810bcbe0ddd009b708139becf81b08e03745b5399f86814bb09564074c0; fulltransferE092queued, no runtimepromotion. + +E080 capacity experiment COMPLETE: train1420.647370882s,peakCUDA11057796608bytes,best rawHit1.389417880488; SHA19e31bb7a53664867bc2c264a8df2391e33e3484943a17e3b1dab6b939730390. SameE064recipe only512wide6layerscapacity. FixedE076inverse control.484790776674,replace.485974574090,addSELECTED.487518657677/.662257450203/.801791136960. Addgain53/19429=.002727881003, molecule95CI[.000645167169,.004769278366]; actualE076contextgain52. Compute12.839403372s. Fullsource/config/logs/checkpointselectionarchived; E090conditionaltransfer pending, no runtimepromotionyet. +E091 MCESdelta confirmed-.50537109375 versusfine, molecule95CI[-.812457728697,-.246086584447],129changedqueries,1.175900589s no newpairs. FullvalidationtransferE092queued. + +E093 queued secondfixedE091transfer ontoactualE085native2000/E014top20/E076confidence, metriconly, othersE085exact. WaitE085actualcapture/E067rescoreexit; 2CPUworkers; strictfullactualcontrolranking equality beforemetrics; fullqueryhash7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6. No fit/newGPUreplay/automaticpublication. E091 fullallcondition4k transfer remainsE092, independent. + +E094 actualinversepackage verification launched for E090selectedadd_both. E090cachedfull .534304390344/.685264295641/.794688352463, MCES7.956302434505; gain32/19429vsE084=.001647022492 moleculeCI[.000158600185,.003248704792]. E094 appendsE080toE076M2 group (10M2+2M3), identicalruntimecode/calibration/scoreweights; independentlypublishrelocateprobe/fullinverseGPUreplay/officialmetrics/MCES beforeconditionalcomposition. Noautomaticrootpromotion. + +E090 COMPLETE fullcached7rulefamily: add_bothSELECTED .534304390344/.685264295641/.794688352463, MCES7.956302434505; vsE084delta32/19429=.001647022492, molecule95CI[.000158600185,.003248704792]. ExactallE084nativecontrols andE080inversecontrols passed. Compute35.858946479s;MCES24newpairs58.471304568s. Replacefallbacknegative. NewE080checkpointSHA19e31bb7a53664867bc2c264a8df2391e33e3484943a17e3b1dab6b939730390;queryhash7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6. Officialmetrics andallnegativefamily/source archived. E094actualinverseverificationactive; no rootpromotion. +E053/E085 actualnative-score capture watchers startedread-only: hold scorefileinode throughtemporarycleanup, waitwriterexitbeforecopy,checkcompletequeryset andstablefinalsize, recordactualscoreSHA. This supports exactscore reuse/proofs aftersuccessfulfullreplay only. Neverpackage developmentscorefiles. CapturecopyI/O canoverlap measuredreplay. + +E095 conditionalupgrade verification queued afterE094actualinverse replay: sameE085native2000/E014top20/source/outerroute; replacebothconfidenceandfallback withE094. Independentlymeasure exactknownHscores andotherpartitionranks, wholepackagenovel/order/immutabilityprobes, usecapturedACTUAL E085native-scorefile withhashcheck, reconstructevery19429E085controlorderexact, compareallruntimeassets/configdiffs, thenofficialmetrics/MCES/internalnumericaldiffs. Conservativeoldfull+newtwo-branch wall/RSS/storagebounds, explicitlyNOT newfullnativeGPUreplay. WaitE085andE094verificationcomplete. Noautoatomicpromotion; finalauditandlatestrootscoreselectionstillrequired. + +E094 COMPLETE actualrelocated12encoderinverse replay: .487518657677/.662257450203/.801791136960,MCES8.890447269546. SHAe7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b, gen8cx8qeyy. Actual218.594410464s,peakRSS16962195456bytes,probes26.378356605sexternalpassed. MCES16newpairs36.731942814s/37.292345534external. OfficialprimarymatchesinternalE080add exactly; exactrankdiffsrecorded. Allsource/derivation/logs/selection/metrics archived. E095conditionalverificationactive, no rootpromotion. + +E085 actual full verification completed: {"checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "metrics": {"hit_rate_at_1": 0.5326573678521798, "hit_rate_at_20": 0.7939163106696175, "hit_rate_at_5": 0.6835658036955067, "mces_at_1": 7.986772350609913}, "paired_delta_vs_E077": {"confidence": 0.95, "estimate": 0.0054042925523701685, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0028906205030719864, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.008196112339539693}, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "reranker_checkpoint_sha256": "83044ab4662986488a21c7c5acc3de3d1127256345cb4cc45d6440c7737ae052", "rule": "Known-energy proton: E014 top20 selector and tail, native2000 entropy plus E076 calibrated confidence with coefficient1. Other public conditions: E076.", "selection": "validation Hit@1; compare to latest published model before atomic promotion; no test claim", "storage": {"package_logical_bytes": 1442291200, "peak_scratch_and_output_bytes": 1643477263, "sample_seconds": 5, "samples": 442}, "timing": {"elapsed_seconds": 2219.1339097637683, "finished_utc": "2026-10-21T10:31:04.840020+00:00", "hardware": "one H100; no additional GPU", "overlap": "one H100; E053 native inference and E078/E080 or later small fitting may overlap; common22CPU affinity; CPU MCES also active; actual timestamps authoritative", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-topf9n1z/native/.versions/generation-gqu12r2w/native/.versions/generation-5y79tkae/glacier.ckpt", "sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "model_config": ".versions/generation-topf9n1z/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 experimental train and supplied held-out-clean ICEBERG simulations; validation only for selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 16794832896, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "returncode": 0, "sampled_total_cpu_seconds": 4444.840000000001, "started_utc": "2026-10-21T09:54:05.706101+00:00"}, "verification": "actual full 19429-query GPU replay, official metrics, MCES, novel-input/order/immutability probes"}; replay comparison: {"authority": "actual independently relocated full package replay", "complete_ranking_differences": 25, "queries": 19429, "top1_differences": 0} + +E085 ATOMICALLY PUBLISHED 2026-10-21T10:35:05.541702+00:00 generation generation-751puae6: actualfullHit1.532657367852/Hit5.683565803696/Hit20.793916310670/MCES7.986772350610. Actualfull2219.133909764s,peakRSS16794832896bytes,peakownedScratchAndOutput1643477263bytes, package1442291200bytes; novel/order/immutabilityprobespassed. Final219runtimeassets byteequal. Internal25completerankdifferences0top1diff; actualauthority. PriorE077 .527253075300; allmodelselectionvalidationonly. Fullsource/config/logs/auditretained. Researchcontinues E095/E093andotherqueuedexperiments. + +E068 finalMCES COMPLETE:11.759277368882,3096newpairs3469.938941623s. ActualfullHit1.384991507540/Hit5.586545885017/Hit20.736579340162,105.243284466s. Standaloneverified, conditionalE081mix rejected; finalalllogs/proofs/MCESarchived. Internalactualcomparison {"true_rank_differences": 0, "hit1_outcome_differences": 0, "authority": "actualfullrelocatedpackage replay"}. +E082 uniformTRAINmolecule sampler COMPLETE:829.861193307s,peakCUDA9655251456,selectedepoch40raw.361212620310/.536260229554/.687837768285,SHA c1ddde305d727d572747676e2a15324f8e60ef5ecdd06e4aba2ab84292d4f598. FixedE076control.484790776674,replace.485562818467,add.486798085336/.662617736373/.803541098358. Adddelta39/19429=.002007308662,moleculeCI[-.000502355488,.004448273032],12.827443240sevaluation. CurrentE094ensembletransfer notyettested; no runtimepromotion. E086nextIDFtrainingactive. + +E096 fixedcombination launched: verifiedE095larger-encoderconfidence/fallback +E093mass-tolerantnative metric, coefficient1 andE014top20/native2000weightsunchanged. CheckEVERYactualnativefine distance194680 andeveryE095fullcontrolorder beforeofficialHit1/5/20/groupCI/MCES. Nofit orautomaticpublication. Bothparentspositive separately; complementarity notassumed. + +E093 fullknownHmass-tolerance transfer COMPLETE: .534922023779/.684595192753/.793916310670/MCES7.931828709661 vsactualE085.532657367852/7.986772350610; +44/19429=.002264655927, molecule95CI[.000915942744,.003812071085]. Exactallactual19429controlorders andall194680fineentropyvalues. CPU2score140.196914618s,total156.464248629 beforewaiting;external327.086075940includeswaitE085fullreplay. MCES34newpairs226.793182420s. Allsource/cachehashproofs/results/compute archived; runtimeimplementationstillpending. +E061 equalnative4000/6000/8000SWA screen COMPLETE: .5625/.712890625/.814453125,MCES7.1279296875 vsnative4000.5546875/7.2451171875; +8/1024CI[-.008791887866,.024262243861]. Pred562.140129805sreported,CPUeval120.253617727s,MCES18newpairs176.195965265s. SWA SHA1d3c7b134f9a7879a0b5433e12aa875eab8cb1d76d9a5b9321d21c214e5b4eb2. Needsfulltransfer ifpursued; no runtimepromotion. E083workerthroughputstudy nowfollows. + +E095 conditional component verification completed: {"checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "inverse_and_reranker_checkpoint_sha256": "e7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b", "metrics": {"hit_rate_at_1": 0.5343043903443306, "hit_rate_at_20": 0.7946883524628133, "hit_rate_at_5": 0.6852642956405374, "mces_at_1": 7.956302434505122}, "paired_delta_vs_E085": {"confidence": 0.95, "estimate": 0.0016470224921509085, "grouping": "supplied target_inchikey connectivity block", "lower": 0.00015860018521226323, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.003248704792248741}, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "rule": "Known-energy proton: unchanged E014top20 andtail, native2000entropy plusE094confidence. OthersE094. Coef1. E09410M2+2M3, IDFcos .75/.25, mass.05once.", "runtime_bound": {"actual_fullreference": {"elapsed_seconds": 2219.1339097637683, "finished_utc": "2026-10-21T10:31:04.840020+00:00", "hardware": "one H100; no additional GPU", "overlap": "one H100; E053 native inference and E078/E080 or later small fitting may overlap; common22CPU affinity; CPU MCES also active; actual timestamps authoritative", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-topf9n1z/native/.versions/generation-gqu12r2w/native/.versions/generation-5y79tkae/glacier.ckpt", "sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "model_config": ".versions/generation-topf9n1z/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 experimental train and supplied held-out-clean ICEBERG simulations; validation only for selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 16794832896, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "returncode": 0, "sampled_total_cpu_seconds": 4444.840000000001, "started_utc": "2026-10-21T09:54:05.706101+00:00"}, "changed_inversebranch": {"elapsed_seconds": 68.17253970820457, "finished_utc": "2026-10-21T10:30:47.076044+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 with E061/E083native screening,E082orE086smallfit; E053/E085CPUscore/E067parallelscore/MCES may overlap; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-8cx8qeyy/model.pt", "sha256": "e7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b"}, "model_config": ".versions/generation-8cx8qeyy/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 7394902016, "query_set_sha256": "3f2e5f420b68ac8db30fb4b6d901924c690872852fdfe0b36a2f27332db23818", "returncode": 0, "sampled_total_cpu_seconds": 222.29000000000002, "started_utc": "2026-10-21T10:29:38.903497+00:00"}, "changed_knownbranch": {"elapsed_seconds": 112.28447951097041, "finished_utc": "2026-10-21T10:29:38.768429+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 with E061/E083native screening,E082orE086smallfit; E053/E085CPUscore/E067parallelscore/MCES may overlap; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-8cx8qeyy/model.pt", "sha256": "e7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b"}, "model_config": ".versions/generation-8cx8qeyy/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 12459704320, "query_set_sha256": "e58b4089ab00cc452d6d81989fab23d717a035582d707888e21dfd2edc3c09ee", "returncode": 0, "sampled_total_cpu_seconds": 387.78000000000003, "started_utc": "2026-10-21T10:27:46.483943+00:00"}, "kind": "conservative sum of old actual fullreplay plus both changedbranch measurements and composition; not actual newfullreplay", "new_package_logical_bytes": 1669290745, "rss_bytes_upper_sum": 36649439232, "wall_seconds_upper_sum": 2418.665438164957, "writable_bytes_upper_sum": 3531014465}, "selection": "validationHit1; compare latestroot before manualatomicpromotion; no test performanceclaim", "verification": "actual changedknownconfidence andotherfallback branch replays, exactactualE085native-score reuse and allcontrolreconstruction, unchangednative/selector/source proofs, end-to-endnovel/order/immutabilityprobes; NOT newfullnativeGPUreplay"} + +E096 combinedfixedchange COMPLETE: .536569046271/.686190745792/.794688352463,MCES7.906943229193. LargerE095inverseplusE093massmetric complement; everyactualcontrolnativevalue194680 andeveryE095fullorder exact. Allsources/officialmetrics/compute archived. +E097 portablemetricverification launched: unchangedownnative2000/E014top20/E094confidence+fallback; nativeadapter distanceoption mass_tolerant_entropy, purefunctions ASTidenticalE091, helperSHA7e10d00fe5ddc9eb41670f423122e8a2a0ae658dbb8958d0fb720481d1d2a9ab, scorerSHAbd5ce7ea562ad476bf8e44c34412a42a6e7f996289503f31f81e1a3afbde0ad9. Publish/relocate, actualpackagedCPUscorer onhashedactualE085HDF/nativepublicinputs, every194680distance mustequalE093 andevery19429composedrankingE096; fullnovel/order/immutabilityprobes; officialmetrics/MCES; conservativecomponentbounds. NoactualnewGPUfullreplay/noautomaticpromotion. No runtimecache orlabels. + +E095 ATOMICALLY PUBLISHED 2026-10-21T10:42:55.792622+00:00 generation generation-f1t1z43e: validation .534304390344/.685264295641/.794688352463,MCES7.956302434505. Final219runtimeassets byteequal. Actualknownpartition andotherpartitionreplays plusEXACTactualE085native-scores; notnewfullnativeGPU. Conservative2418.665438165s/RSS36649439232bytes/storage3531014465bytes; wholepackageprobespassed. E085nowprevious. E097portablemassmetric combinationverificationactive; no testclaim. + +E098 all-conditionconfidence/metric study launched: actualE094fullvalidation replaywithscores (everyorder mustequalpriorE094actual), then unchangedE053native4000/E047top64/coef1. FixedoldE047vsnewE094confidence x fine150k/missing30k/all20ppm-.002Da; allthreeoldconfidencecontrols mustexactlyreconstructE053/E067/E092 fullorders. WaitE092controlproof; officialselectedHit1/5/20,groupCI,MCES. No newfit/nativeGPU simulation orautomaticpromotion. CurrentE053fullHit1.567193370734,coarsemissingE067.571722682588; secondaryMCESpending. + +E083 completed: 12workers482.302833486s versus6workers485.588249700s, byte-identical HDF and complete1024 rankings, Hit1.5546875; peakRSS23,958,183,936 versus12,850,970,624. Different overlap prevents isolated throughput inference. Scriptselected12; deployment retains6 given tiny timing gain and largerRAM. All source/measurements archived. +E086 completed: TRAIN-IDFweighted cosine only, seed1,769.504493199s fit,peak9,653,465,088; selectedepoch34rawHit1.362653764990/Hit5.527716300376/Hit20.682999639714,checkpoint44b491001919e38727d28fc9285a0c4d98dc9c903fd50adfa2485c7b09bdad26. OLD E076ensemble fixedreplace regressed.483195223635; add.486849554789/.662772144732/.802923464924 versusmatched.484790776674, moleculeCI[.000054590262,.004018486829]. Eval12.639319368s. Fullvalidationqueryhash7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6; notyettransferredtolatestpackage. Fullsource/recipe/trainlogs archived. + +E099 prepared portable all-condition E098selectedrule verification. Native4000/E047top64 coverage unchanged, optional actualE094confidence, fixed selected fine or mass-tolerant metric. Actual runtimeCPUscorer will be checked against all selected cached distances, every19429order againstE098, strict unchangedmodel/prediction/selector/route bytes; wholepackageprobes and conservative actualcomponent replay bound. No newfit and no automaticpromotion. WaitE098selection and E097runtimeproof. + +E102 fixed SWA-plus-massmetric screen launched. Same1024/668moleculegroups, E040confidence/E018top64. ExactSWAfinecontrol mustmatchE061; compareselected20ppm/.002Dametric toSWAfine andnative4000-tolerantE091. TwoCPUworkers, no newGPU simulation orfit; selectedMCESwithscreenquery-input required. Hypothesiscomplementary checkpointaveragingandphysicallymotivatedmatching. + +E101 queued fixed4inverse-diversity transfer afterE098actualfull scores: E094control/addE082uniformmolecule/addE086TRAIN-IDFloss/addboth. All-condition native4000/E047top64/coef1/E098selectedmetric frozen. Compare matchedcachedcontrol andactualselectedE098, report numericalcontexts. Validationglobalrule selection only; actualselectedportable replayneeded. + +E097 mass-tolerant runtime component verification completed: {"checkpoint_sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369", "inverse_and_reranker_checkpoint_sha256": "e7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b", "metrics": {"hit_rate_at_1": 0.5365690462710382, "hit_rate_at_20": 0.7946883524628133, "hit_rate_at_5": 0.6861907457923723, "mces_at_1": 7.906943229193474}, "paired_delta_vs_E095": {"confidence": 0.95, "estimate": 0.002264655926707499, "grouping": "supplied target_inchikey connectivity block", "lower": 0.0008059699867403904, "molecule_groups": 3185, "queries": 19429, "resamples": 2000, "seed": 0, "statistic": "spectrum-weighted mean; molecules sampled with replacement", "upper": 0.0038470347634726957}, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "rule": "Known-energy proton: unchanged E014top20 andtail, native2000 mass-tolerant entropy plusE094confidence. OthersE094. Coef1. E09410M2+2M3, IDFcos .75/.25, mass.05once.", "runtime_bound": {"actual_CPU_measurement": {"command": ["/opt/glacier/bin/python", "/workspace/research/E097/relocated-package/.versions/generation-aro1_jwx/native/.versions/generation-au8gj_b_/native/.versions/generation-jsmj74vb/score_glacier_predictions.py", "--input-root", "/workspace/research/E097/native-input", "--pred-file", "/workspace/research/cache/native-predictions-E085-known-top20/preds.hdf5", "--output-root", "/workspace/research/E097/native-check/output", "--distance", "mass_tolerant_entropy", "--scores-output", "/workspace/research/E097/native-check/native-scores.jsonl"], "elapsed_seconds": 268.5783350048587, "finished_utc": "2026-10-21T10:48:43.601801+00:00", "peak_summed_process_rss_bytes": 1003819008, "resource": "CPU scorer only, on common22CPUaffinity; other native/smalltraining/CPUstudies may overlap", "returncode": 0, "sampled_total_cpu_seconds": 262.77, "started_utc": "2026-10-21T10:44:15.023463+00:00"}, "kind": "conservative prior componentbound plus actual changedCPUscorer; NOT a new fullnativeGPUreplay", "package_logical_bytes": 1655277530, "prior_bound": {"actual_fullreference": {"elapsed_seconds": 2219.1339097637683, "finished_utc": "2026-10-21T10:31:04.840020+00:00", "hardware": "one H100; no additional GPU", "overlap": "one H100; E053 native inference and E078/E080 or later small fitting may overlap; common22CPU affinity; CPU MCES also active; actual timestamps authoritative", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-topf9n1z/native/.versions/generation-gqu12r2w/native/.versions/generation-5y79tkae/glacier.ckpt", "sha256": "e79b4150ce92647fe99446477caf1f6c3819d343ea3867db8af1e2e7ad0ed369"}, "model_config": ".versions/generation-topf9n1z/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 experimental train and supplied held-out-clean ICEBERG simulations; validation only for selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 16794832896, "query_set_sha256": "7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6", "returncode": 0, "sampled_total_cpu_seconds": 4444.840000000001, "started_utc": "2026-10-21T09:54:05.706101+00:00"}, "changed_inversebranch": {"elapsed_seconds": 68.17253970820457, "finished_utc": "2026-10-21T10:30:47.076044+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 with E061/E083native screening,E082orE086smallfit; E053/E085CPUscore/E067parallelscore/MCES may overlap; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-8cx8qeyy/model.pt", "sha256": "e7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b"}, "model_config": ".versions/generation-8cx8qeyy/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 7394902016, "query_set_sha256": "3f2e5f420b68ac8db30fb4b6d901924c690872852fdfe0b36a2f27332db23818", "returncode": 0, "sampled_total_cpu_seconds": 222.29000000000002, "started_utc": "2026-10-21T10:29:38.903497+00:00"}, "changed_knownbranch": {"elapsed_seconds": 112.28447951097041, "finished_utc": "2026-10-21T10:29:38.768429+00:00", "hardware": "one H100; no additional GPU", "overlap": "oneH100 with E061/E083native screening,E082orE086smallfit; E053/E085CPUscore/E067parallelscore/MCES may overlap; common22CPUaffinity", "package_manifest": {"checkpoint": {"format": "pytorch", "path": ".versions/generation-8cx8qeyy/model.pt", "sha256": "e7a187fe0175f81c107a2a4e1de70d84eb9b977267c42dc7b7fd8e1c0a5fe59b"}, "model_config": ".versions/generation-8cx8qeyy/model_config.json", "schema": "massspecgym-retrieval-model/v1", "training_provenance": {"data": "MassSpecGym v1.5 train and supplied held-out-clean ICEBERG simulations; validation only for model selection", "pretrained_assets": []}}, "peak_summed_process_rss_bytes": 12459704320, "query_set_sha256": "e58b4089ab00cc452d6d81989fab23d717a035582d707888e21dfd2edc3c09ee", "returncode": 0, "sampled_total_cpu_seconds": 387.78000000000003, "started_utc": "2026-10-21T10:27:46.483943+00:00"}, "kind": "conservative sum of old actual fullreplay plus both changedbranch measurements and composition; not actual newfullreplay", "new_package_logical_bytes": 1669290745, "rss_bytes_upper_sum": 36649439232, "wall_seconds_upper_sum": 2418.665438164957, "writable_bytes_upper_sum": 3531014465}, "rss_bytes_upper_sum": 37653258240, "wall_seconds_upper_sum": 2711.683406477794, "writable_bytes_upper_sum": 5204064368}, "selection": "validationHit1; compare latestroot before manualatomicpromotion; no test performanceclaim", "verification": "actual portable changedCPUscorer on hashed actual E085 predictions; every194680distance equalsE093 and every19429ranking equalsE096; unchangedmodel/prediction/selector/inverse/routing proofs, end-to-endnovel/order/immutabilityprobes; NOT newfullnativeGPUreplay"} diff --git a/shared/package-files/78/78fb3fb0ec11f61bc6cf0947f3c3923aa18e1c6513684058ed0fa01ac858143e/blob b/shared/package-files/78/78fb3fb0ec11f61bc6cf0947f3c3923aa18e1c6513684058ed0fa01ac858143e/blob new file mode 100644 index 0000000000000000000000000000000000000000..77d8f711804f954d15520c8f9e40720fd6fb5e64 Binary files /dev/null and b/shared/package-files/78/78fb3fb0ec11f61bc6cf0947f3c3923aa18e1c6513684058ed0fa01ac858143e/blob differ diff --git a/shared/package-files/78/78fb4dce12225480f3e5040ff2fd93f29ea0a968b5687dcd82c4dc690c4833ca/blob b/shared/package-files/78/78fb4dce12225480f3e5040ff2fd93f29ea0a968b5687dcd82c4dc690c4833ca/blob new file mode 100644 index 0000000000000000000000000000000000000000..5e5d87f946355b3771bee469d769bf480a0b9936 --- /dev/null +++ b/shared/package-files/78/78fb4dce12225480f3e5040ff2fd93f29ea0a968b5687dcd82c4dc690c4833ca/blob @@ -0,0 +1,197 @@ +#pragma once +#include +#include +#include +#include +#include + +#include + +namespace torch { +namespace jit { +namespace mobile { +using Stack = std::vector; + +// A CompilationUnit object is the one that gets executed by the lite +// interpreter. +// +// A CompilationUnit object contains a list of Method Objects. These are methods +// that appear in the original PyTorch Model. These method correspond to Python +// member functions of the Model class. +// +// Methods in turn contain a Function, and a back-pointer to the Module that +// owns this Method instance. +// +// A Function contains a Code Object (code_) which is defined in interpreter.h +// +// A Code object contains the following: +// +// std::vector instructions_; +// std::vector op_names_; +// std::vector> operators_; +// std::vector constants_; +// std::vector types_; +// size_t register_size_; // Aggregated output size. +// +class CompilationUnit { + public: + void register_function(std::unique_ptr fn); + std::vector>& methods() { + return methods_; + } + const std::vector>& methods() const { + return methods_; + } + Function* find_function(const c10::QualifiedName& qn); + const Function* find_function(const c10::QualifiedName& qn) const; + + void unsafeRemoveFunction(const int64_t index) { + methods_.erase(methods_.begin() + index); + } + + private: + std::vector> methods_; +}; + +// A Torch Mobile Module is a representation of the model (trained in case +// of inference). A Mobile Module contains +// +// 1. data (object_) +// 2. metadata (optional) about the model (metadata_ from the metadata.pkl +// file added after training) +// 3. Compilation Unit (cu_) +// +class TORCH_API Module { + public: + Module( + c10::intrusive_ptr object, + std::shared_ptr cu) + : object_(std::move(object)), cu_(std::move(cu)) {} + Module() = default; + Method get_method(const std::string& method_name) const; + template + c10::IValue run_method(const std::string& method_name, Types&&... args) { + return get_method(method_name)({IValue(std::forward(args))...}); + } + c10::IValue forward(std::vector inputs) { + return get_method("forward")(std::move(inputs)); + } + c10::optional find_method(const std::string& basename) const; + + const std::string name() const { + return object_->name(); + } + const std::vector& slots() const { + return object_->slots(); + } + const c10::intrusive_ptr _ivalue() const { + return object_; + } + const std::vector parameters() const; + const std::map named_parameters() const; + std::string get_forward_method_debug_info(int64_t debug_handle) const; + std::string getModuleHierarchy(const int64_t debug_handle) const; + std::string getCallStack(const int64_t debug_handle) const; + /// Enables "training" mode. + void train(bool on = true); + /// Calls train(false) to enable "eval" mode. + void eval() { + train(/*on=*/false); + } + /// True if the module is in training mode. + bool is_training() const; + const std::unordered_map getMetadata() const { + return metadata_; + } + void setMetadata( + const std::unordered_map& metadata) { + metadata_ = metadata; + } + const std::vector get_methods() const; + + c10::IValue attr(const std::string& name, c10::IValue or_else) const { + if (auto r = object_->type()->findAttributeSlot(name)) { + return object_->getSlot(*r); + } + if (auto r = object_->type()->findConstantSlot(name)) { + return object_->type()->getConstant(*r); + } + return or_else; + } + + void setDebugTable(MobileDebugTable&& debug_table) { + debug_table_ = std::move(debug_table); + } + const MobileDebugTable& getDebugTable() const { + return debug_table_; + } + + void setHasDebugHandles(bool has_debug_handles) { + has_debug_handles_ = has_debug_handles; + } + + bool hasDebugHandles() const { + return has_debug_handles_; + } + + const CompilationUnit& compilation_unit() const { + return *cu_.get(); + } + + void set_delete_memory(std::shared_ptr delete_mem) { + mem_to_delete_ = std::move(delete_mem); + } + + void set_min_operator_version(int64_t version) { + min_operator_version_ = version; + } + + int64_t min_operator_version() const { + return min_operator_version_; + } + + void set_bytecode_version(int64_t version) { + bytecode_version_ = version; + } + + int64_t bytecode_version() const { + return bytecode_version_; + } + + private: + friend class quantization::PTQQuanizationHelper; + + bool compareMethodSchemas( + const std::string& name_1, + const std::string& name_2); + + void unsafeRemoveMethod(const std::string& basename); + + void unsafeCopyMethod( + const std::string& new_method_name, + const Function& to_be_copied); + + c10::intrusive_ptr object_; + std::unordered_map metadata_; + std::shared_ptr cu_; + MobileDebugTable debug_table_; + bool has_debug_handles_ = false; + int64_t min_operator_version_ = 4; + int64_t bytecode_version_ = 4; + + // Extra handle for the module to delete when itself is deleted + std::shared_ptr mem_to_delete_; +}; + +struct TORCH_API ModuleInfo { + uint64_t bytecode_version; + uint64_t operator_version; + std::unordered_map opname_to_num_args; + std::unordered_set function_names; + std::unordered_set type_names; +}; +TORCH_API ModuleInfo get_module_info(const mobile::Module& module); + +} // namespace mobile +} // namespace jit +} // namespace torch diff --git a/shared/package-files/78/78fc7ea64bd13bfb0372b1e6edb84c35c6f07dc455dd4e929484d715b708b99f/blob b/shared/package-files/78/78fc7ea64bd13bfb0372b1e6edb84c35c6f07dc455dd4e929484d715b708b99f/blob new file mode 100644 index 0000000000000000000000000000000000000000..78552ef7ae23f14df1f66bd6670f74bc7a6f6ee6 Binary files /dev/null and b/shared/package-files/78/78fc7ea64bd13bfb0372b1e6edb84c35c6f07dc455dd4e929484d715b708b99f/blob differ diff --git a/shared/package-files/78/78ff44e51c26bd36cbddb29fb17d0e081e72e5bec9129f162a508bbd10ccb567/blob b/shared/package-files/78/78ff44e51c26bd36cbddb29fb17d0e081e72e5bec9129f162a508bbd10ccb567/blob new file mode 100644 index 0000000000000000000000000000000000000000..7cc0f58ad766b4ff5321a64c6e1b7105a3d80d1d --- /dev/null +++ b/shared/package-files/78/78ff44e51c26bd36cbddb29fb17d0e081e72e5bec9129f162a508bbd10ccb567/blob @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & copy_out(const at::Tensor & self, const at::Tensor & src, bool non_blocking, at::Tensor & out); +TORCH_API at::Tensor & copy_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false); +TORCH_API at::Tensor & copy_nested_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false); +TORCH_API at::Tensor & copy_sparse_wrapper_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false); +TORCH_API at::Tensor & copy_sparse_compressed_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false); +TORCH_API at::Tensor & copy_mkldnn_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false); +TORCH_API at::Tensor copy(const at::Tensor & self, const at::Tensor & src, bool non_blocking=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/79/7903c2ea80bd412cc0d6701c38f645063a2f77a502cb7b1c5d9ee9d6ef38e4df/blob b/shared/package-files/79/7903c2ea80bd412cc0d6701c38f645063a2f77a502cb7b1c5d9ee9d6ef38e4df/blob new file mode 100644 index 0000000000000000000000000000000000000000..c13eb7adde8747317f71b0586c35bceec287d0de --- /dev/null +++ b/shared/package-files/79/7903c2ea80bd412cc0d6701c38f645063a2f77a502cb7b1c5d9ee9d6ef38e4df/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7903c2ea80bd412cc0d6701c38f645063a2f77a502cb7b1c5d9ee9d6ef38e4df +size 208346 diff --git a/shared/package-files/79/7903d6a364ca6d1b0f63c254b7976b8c16f245d54a060793d841781c6839d685/blob b/shared/package-files/79/7903d6a364ca6d1b0f63c254b7976b8c16f245d54a060793d841781c6839d685/blob new file mode 100644 index 0000000000000000000000000000000000000000..4da5031b990ca742eb0d303003af5c6a821c4db9 --- /dev/null +++ b/shared/package-files/79/7903d6a364ca6d1b0f63c254b7976b8c16f245d54a060793d841781c6839d685/blob @@ -0,0 +1,750 @@ +# axis3d.py, original mplot3d version by John Porter +# Created: 23 Sep 2005 +# Parts rewritten by Reinier Heeres + +import inspect + +import numpy as np + +import matplotlib as mpl +from matplotlib import ( + _api, artist, lines as mlines, axis as maxis, patches as mpatches, + transforms as mtransforms, colors as mcolors) +from . import art3d, proj3d + + +def _move_from_center(coord, centers, deltas, axmask=(True, True, True)): + """ + For each coordinate where *axmask* is True, move *coord* away from + *centers* by *deltas*. + """ + coord = np.asarray(coord) + return coord + axmask * np.copysign(1, coord - centers) * deltas + + +def _tick_update_position(tick, tickxs, tickys, labelpos): + """Update tick line and label position and style.""" + + tick.label1.set_position(labelpos) + tick.label2.set_position(labelpos) + tick.tick1line.set_visible(True) + tick.tick2line.set_visible(False) + tick.tick1line.set_linestyle('-') + tick.tick1line.set_marker('') + tick.tick1line.set_data(tickxs, tickys) + tick.gridline.set_data([0], [0]) + + +class Axis(maxis.XAxis): + """An Axis class for the 3D plots.""" + # These points from the unit cube make up the x, y and z-planes + _PLANES = ( + (0, 3, 7, 4), (1, 2, 6, 5), # yz planes + (0, 1, 5, 4), (3, 2, 6, 7), # xz planes + (0, 1, 2, 3), (4, 5, 6, 7), # xy planes + ) + + # Some properties for the axes + _AXINFO = { + 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2)}, + 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2)}, + 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1)}, + } + + def _old_init(self, adir, v_intervalx, d_intervalx, axes, *args, + rotate_label=None, **kwargs): + return locals() + + def _new_init(self, axes, *, rotate_label=None, **kwargs): + return locals() + + def __init__(self, *args, **kwargs): + params = _api.select_matching_signature( + [self._old_init, self._new_init], *args, **kwargs) + if "adir" in params: + _api.warn_deprecated( + "3.6", message=f"The signature of 3D Axis constructors has " + f"changed in %(since)s; the new signature is " + f"{inspect.signature(type(self).__init__)}", pending=True) + if params["adir"] != self.axis_name: + raise ValueError(f"Cannot instantiate {type(self).__name__} " + f"with adir={params['adir']!r}") + axes = params["axes"] + rotate_label = params["rotate_label"] + args = params.get("args", ()) + kwargs = params["kwargs"] + + name = self.axis_name + + self._label_position = 'default' + self._tick_position = 'default' + + # This is a temporary member variable. + # Do not depend on this existing in future releases! + self._axinfo = self._AXINFO[name].copy() + # Common parts + self._axinfo.update({ + 'label': {'va': 'center', 'ha': 'center', + 'rotation_mode': 'anchor'}, + 'color': mpl.rcParams[f'axes3d.{name}axis.panecolor'], + 'tick': { + 'inward_factor': 0.2, + 'outward_factor': 0.1, + }, + }) + + if mpl.rcParams['_internal.classic_mode']: + self._axinfo.update({ + 'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)}, + 'grid': { + 'color': (0.9, 0.9, 0.9, 1), + 'linewidth': 1.0, + 'linestyle': '-', + }, + }) + self._axinfo['tick'].update({ + 'linewidth': { + True: mpl.rcParams['lines.linewidth'], # major + False: mpl.rcParams['lines.linewidth'], # minor + } + }) + else: + self._axinfo.update({ + 'axisline': { + 'linewidth': mpl.rcParams['axes.linewidth'], + 'color': mpl.rcParams['axes.edgecolor'], + }, + 'grid': { + 'color': mpl.rcParams['grid.color'], + 'linewidth': mpl.rcParams['grid.linewidth'], + 'linestyle': mpl.rcParams['grid.linestyle'], + }, + }) + self._axinfo['tick'].update({ + 'linewidth': { + True: ( # major + mpl.rcParams['xtick.major.width'] if name in 'xz' + else mpl.rcParams['ytick.major.width']), + False: ( # minor + mpl.rcParams['xtick.minor.width'] if name in 'xz' + else mpl.rcParams['ytick.minor.width']), + } + }) + + super().__init__(axes, *args, **kwargs) + + # data and viewing intervals for this direction + if "d_intervalx" in params: + self.set_data_interval(*params["d_intervalx"]) + if "v_intervalx" in params: + self.set_view_interval(*params["v_intervalx"]) + self.set_rotate_label(rotate_label) + self._init3d() # Inline after init3d deprecation elapses. + + __init__.__signature__ = inspect.signature(_new_init) + adir = _api.deprecated("3.6", pending=True)( + property(lambda self: self.axis_name)) + + def _init3d(self): + self.line = mlines.Line2D( + xdata=(0, 0), ydata=(0, 0), + linewidth=self._axinfo['axisline']['linewidth'], + color=self._axinfo['axisline']['color'], + antialiased=True) + + # Store dummy data in Polygon object + self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False) + self.set_pane_color(self._axinfo['color']) + + self.axes._set_artist_props(self.line) + self.axes._set_artist_props(self.pane) + self.gridlines = art3d.Line3DCollection([]) + self.axes._set_artist_props(self.gridlines) + self.axes._set_artist_props(self.label) + self.axes._set_artist_props(self.offsetText) + # Need to be able to place the label at the correct location + self.label._transform = self.axes.transData + self.offsetText._transform = self.axes.transData + + @_api.deprecated("3.6", pending=True) + def init3d(self): # After deprecation elapses, inline _init3d to __init__. + self._init3d() + + def get_major_ticks(self, numticks=None): + ticks = super().get_major_ticks(numticks) + for t in ticks: + for obj in [ + t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]: + obj.set_transform(self.axes.transData) + return ticks + + def get_minor_ticks(self, numticks=None): + ticks = super().get_minor_ticks(numticks) + for t in ticks: + for obj in [ + t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]: + obj.set_transform(self.axes.transData) + return ticks + + def set_ticks_position(self, position): + """ + Set the ticks position. + + Parameters + ---------- + position : {'lower', 'upper', 'both', 'default', 'none'} + The position of the bolded axis lines, ticks, and tick labels. + """ + _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'], + position=position) + self._tick_position = position + + def get_ticks_position(self): + """ + Get the ticks position. + + Returns + ------- + str : {'lower', 'upper', 'both', 'default', 'none'} + The position of the bolded axis lines, ticks, and tick labels. + """ + return self._tick_position + + def set_label_position(self, position): + """ + Set the label position. + + Parameters + ---------- + position : {'lower', 'upper', 'both', 'default', 'none'} + The position of the axis label. + """ + _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'], + position=position) + self._label_position = position + + def get_label_position(self): + """ + Get the label position. + + Returns + ------- + str : {'lower', 'upper', 'both', 'default', 'none'} + The position of the axis label. + """ + return self._label_position + + def set_pane_color(self, color, alpha=None): + """ + Set pane color. + + Parameters + ---------- + color : :mpltype:`color` + Color for axis pane. + alpha : float, optional + Alpha value for axis pane. If None, base it on *color*. + """ + color = mcolors.to_rgba(color, alpha) + self._axinfo['color'] = color + self.pane.set_edgecolor(color) + self.pane.set_facecolor(color) + self.pane.set_alpha(color[-1]) + self.stale = True + + def set_rotate_label(self, val): + """ + Whether to rotate the axis label: True, False or None. + If set to None the label will be rotated if longer than 4 chars. + """ + self._rotate_label = val + self.stale = True + + def get_rotate_label(self, text): + if self._rotate_label is not None: + return self._rotate_label + else: + return len(text) > 4 + + def _get_coord_info(self): + mins, maxs = np.array([ + self.axes.get_xbound(), + self.axes.get_ybound(), + self.axes.get_zbound(), + ]).T + + # Project the bounds along the current position of the cube: + bounds = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2] + bounds_proj = self.axes._transformed_cube(bounds) + + # Determine which one of the parallel planes are higher up: + means_z0 = np.zeros(3) + means_z1 = np.zeros(3) + for i in range(3): + means_z0[i] = np.mean(bounds_proj[self._PLANES[2 * i], 2]) + means_z1[i] = np.mean(bounds_proj[self._PLANES[2 * i + 1], 2]) + highs = means_z0 < means_z1 + + # Special handling for edge-on views + equals = np.abs(means_z0 - means_z1) <= np.finfo(float).eps + if np.sum(equals) == 2: + vertical = np.where(~equals)[0][0] + if vertical == 2: # looking at XY plane + highs = np.array([True, True, highs[2]]) + elif vertical == 1: # looking at XZ plane + highs = np.array([True, highs[1], False]) + elif vertical == 0: # looking at YZ plane + highs = np.array([highs[0], False, False]) + + return mins, maxs, bounds_proj, highs + + def _calc_centers_deltas(self, maxs, mins): + centers = 0.5 * (maxs + mins) + # In mpl3.8, the scale factor was 1/12. mpl3.9 changes this to + # 1/12 * 24/25 = 0.08 to compensate for the change in automargin + # behavior and keep appearance the same. The 24/25 factor is from the + # 1/48 padding added to each side of the axis in mpl3.8. + scale = 0.08 + deltas = (maxs - mins) * scale + return centers, deltas + + def _get_axis_line_edge_points(self, minmax, maxmin, position=None): + """Get the edge points for the black bolded axis line.""" + # When changing vertical axis some of the axes has to be + # moved to the other plane so it looks the same as if the z-axis + # was the vertical axis. + mb = [minmax, maxmin] # line from origin to nearest corner to camera + mb_rev = mb[::-1] + mm = [[mb, mb_rev, mb_rev], [mb_rev, mb_rev, mb], [mb, mb, mb]] + mm = mm[self.axes._vertical_axis][self._axinfo["i"]] + + juggled = self._axinfo["juggled"] + edge_point_0 = mm[0].copy() # origin point + + if ((position == 'lower' and mm[1][juggled[-1]] < mm[0][juggled[-1]]) or + (position == 'upper' and mm[1][juggled[-1]] > mm[0][juggled[-1]])): + edge_point_0[juggled[-1]] = mm[1][juggled[-1]] + else: + edge_point_0[juggled[0]] = mm[1][juggled[0]] + + edge_point_1 = edge_point_0.copy() + edge_point_1[juggled[1]] = mm[1][juggled[1]] + + return edge_point_0, edge_point_1 + + def _get_all_axis_line_edge_points(self, minmax, maxmin, axis_position=None): + # Determine edge points for the axis lines + edgep1s = [] + edgep2s = [] + position = [] + if axis_position in (None, 'default'): + edgep1, edgep2 = self._get_axis_line_edge_points(minmax, maxmin) + edgep1s = [edgep1] + edgep2s = [edgep2] + position = ['default'] + else: + edgep1_l, edgep2_l = self._get_axis_line_edge_points(minmax, maxmin, + position='lower') + edgep1_u, edgep2_u = self._get_axis_line_edge_points(minmax, maxmin, + position='upper') + if axis_position in ('lower', 'both'): + edgep1s.append(edgep1_l) + edgep2s.append(edgep2_l) + position.append('lower') + if axis_position in ('upper', 'both'): + edgep1s.append(edgep1_u) + edgep2s.append(edgep2_u) + position.append('upper') + return edgep1s, edgep2s, position + + def _get_tickdir(self, position): + """ + Get the direction of the tick. + + Parameters + ---------- + position : str, optional : {'upper', 'lower', 'default'} + The position of the axis. + + Returns + ------- + tickdir : int + Index which indicates which coordinate the tick line will + align with. + """ + _api.check_in_list(('upper', 'lower', 'default'), position=position) + + # TODO: Move somewhere else where it's triggered less: + tickdirs_base = [v["tickdir"] for v in self._AXINFO.values()] # default + elev_mod = np.mod(self.axes.elev + 180, 360) - 180 + azim_mod = np.mod(self.axes.azim, 360) + if position == 'upper': + if elev_mod >= 0: + tickdirs_base = [2, 2, 0] + else: + tickdirs_base = [1, 0, 0] + if 0 <= azim_mod < 180: + tickdirs_base[2] = 1 + elif position == 'lower': + if elev_mod >= 0: + tickdirs_base = [1, 0, 1] + else: + tickdirs_base = [2, 2, 1] + if 0 <= azim_mod < 180: + tickdirs_base[2] = 0 + info_i = [v["i"] for v in self._AXINFO.values()] + + i = self._axinfo["i"] + vert_ax = self.axes._vertical_axis + j = vert_ax - 2 + # default: tickdir = [[1, 2, 1], [2, 2, 0], [1, 0, 0]][vert_ax][i] + tickdir = np.roll(info_i, -j)[np.roll(tickdirs_base, j)][i] + return tickdir + + def active_pane(self): + mins, maxs, tc, highs = self._get_coord_info() + info = self._axinfo + index = info['i'] + if not highs[index]: + loc = mins[index] + plane = self._PLANES[2 * index] + else: + loc = maxs[index] + plane = self._PLANES[2 * index + 1] + xys = np.array([tc[p] for p in plane]) + return xys, loc + + def draw_pane(self, renderer): + """ + Draw pane. + + Parameters + ---------- + renderer : `~matplotlib.backend_bases.RendererBase` subclass + """ + renderer.open_group('pane3d', gid=self.get_gid()) + xys, loc = self.active_pane() + self.pane.xy = xys[:, :2] + self.pane.draw(renderer) + renderer.close_group('pane3d') + + def _axmask(self): + axmask = [True, True, True] + axmask[self._axinfo["i"]] = False + return axmask + + def _draw_ticks(self, renderer, edgep1, centers, deltas, highs, + deltas_per_point, pos): + ticks = self._update_ticks() + info = self._axinfo + index = info["i"] + juggled = info["juggled"] + + mins, maxs, tc, highs = self._get_coord_info() + centers, deltas = self._calc_centers_deltas(maxs, mins) + + # Draw ticks: + tickdir = self._get_tickdir(pos) + tickdelta = deltas[tickdir] if highs[tickdir] else -deltas[tickdir] + + tick_info = info['tick'] + tick_out = tick_info['outward_factor'] * tickdelta + tick_in = tick_info['inward_factor'] * tickdelta + tick_lw = tick_info['linewidth'] + edgep1_tickdir = edgep1[tickdir] + out_tickdir = edgep1_tickdir + tick_out + in_tickdir = edgep1_tickdir - tick_in + + default_label_offset = 8. # A rough estimate + points = deltas_per_point * deltas + for tick in ticks: + # Get tick line positions + pos = edgep1.copy() + pos[index] = tick.get_loc() + pos[tickdir] = out_tickdir + x1, y1, z1 = proj3d.proj_transform(*pos, self.axes.M) + pos[tickdir] = in_tickdir + x2, y2, z2 = proj3d.proj_transform(*pos, self.axes.M) + + # Get position of label + labeldeltas = (tick.get_pad() + default_label_offset) * points + + pos[tickdir] = edgep1_tickdir + pos = _move_from_center(pos, centers, labeldeltas, self._axmask()) + lx, ly, lz = proj3d.proj_transform(*pos, self.axes.M) + + _tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly)) + tick.tick1line.set_linewidth(tick_lw[tick._major]) + tick.draw(renderer) + + def _draw_offset_text(self, renderer, edgep1, edgep2, labeldeltas, centers, + highs, pep, dx, dy): + # Get general axis information: + info = self._axinfo + index = info["i"] + juggled = info["juggled"] + tickdir = info["tickdir"] + + # Which of the two edge points do we want to + # use for locating the offset text? + if juggled[2] == 2: + outeredgep = edgep1 + outerindex = 0 + else: + outeredgep = edgep2 + outerindex = 1 + + pos = _move_from_center(outeredgep, centers, labeldeltas, + self._axmask()) + olx, oly, olz = proj3d.proj_transform(*pos, self.axes.M) + self.offsetText.set_text(self.major.formatter.get_offset()) + self.offsetText.set_position((olx, oly)) + angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx))) + self.offsetText.set_rotation(angle) + # Must set rotation mode to "anchor" so that + # the alignment point is used as the "fulcrum" for rotation. + self.offsetText.set_rotation_mode('anchor') + + # ---------------------------------------------------------------------- + # Note: the following statement for determining the proper alignment of + # the offset text. This was determined entirely by trial-and-error + # and should not be in any way considered as "the way". There are + # still some edge cases where alignment is not quite right, but this + # seems to be more of a geometry issue (in other words, I might be + # using the wrong reference points). + # + # (TT, FF, TF, FT) are the shorthand for the tuple of + # (centpt[tickdir] <= pep[tickdir, outerindex], + # centpt[index] <= pep[index, outerindex]) + # + # Three-letters (e.g., TFT, FTT) are short-hand for the array of bools + # from the variable 'highs'. + # --------------------------------------------------------------------- + centpt = proj3d.proj_transform(*centers, self.axes.M) + if centpt[tickdir] > pep[tickdir, outerindex]: + # if FT and if highs has an even number of Trues + if (centpt[index] <= pep[index, outerindex] + and np.count_nonzero(highs) % 2 == 0): + # Usually, this means align right, except for the FTT case, + # in which offset for axis 1 and 2 are aligned left. + if highs.tolist() == [False, True, True] and index in (1, 2): + align = 'left' + else: + align = 'right' + else: + # The FF case + align = 'left' + else: + # if TF and if highs has an even number of Trues + if (centpt[index] > pep[index, outerindex] + and np.count_nonzero(highs) % 2 == 0): + # Usually mean align left, except if it is axis 2 + align = 'right' if index == 2 else 'left' + else: + # The TT case + align = 'right' + + self.offsetText.set_va('center') + self.offsetText.set_ha(align) + self.offsetText.draw(renderer) + + def _draw_labels(self, renderer, edgep1, edgep2, labeldeltas, centers, dx, dy): + label = self._axinfo["label"] + + # Draw labels + lxyz = 0.5 * (edgep1 + edgep2) + lxyz = _move_from_center(lxyz, centers, labeldeltas, self._axmask()) + tlx, tly, tlz = proj3d.proj_transform(*lxyz, self.axes.M) + self.label.set_position((tlx, tly)) + if self.get_rotate_label(self.label.get_text()): + angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx))) + self.label.set_rotation(angle) + self.label.set_va(label['va']) + self.label.set_ha(label['ha']) + self.label.set_rotation_mode(label['rotation_mode']) + self.label.draw(renderer) + + @artist.allow_rasterization + def draw(self, renderer): + self.label._transform = self.axes.transData + self.offsetText._transform = self.axes.transData + renderer.open_group("axis3d", gid=self.get_gid()) + + # Get general axis information: + mins, maxs, tc, highs = self._get_coord_info() + centers, deltas = self._calc_centers_deltas(maxs, mins) + + # Calculate offset distances + # A rough estimate; points are ambiguous since 3D plots rotate + reltoinches = self.get_figure(root=False).dpi_scale_trans.inverted() + ax_inches = reltoinches.transform(self.axes.bbox.size) + ax_points_estimate = sum(72. * ax_inches) + deltas_per_point = 48 / ax_points_estimate + default_offset = 21. + labeldeltas = (self.labelpad + default_offset) * deltas_per_point * deltas + + # Determine edge points for the axis lines + minmax = np.where(highs, maxs, mins) # "origin" point + maxmin = np.where(~highs, maxs, mins) # "opposite" corner near camera + + for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points( + minmax, maxmin, self._tick_position)): + # Project the edge points along the current position + pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M) + pep = np.asarray(pep) + + # The transAxes transform is used because the Text object + # rotates the text relative to the display coordinate system. + # Therefore, if we want the labels to remain parallel to the + # axis regardless of the aspect ratio, we need to convert the + # edge points of the plane to display coordinates and calculate + # an angle from that. + # TODO: Maybe Text objects should handle this themselves? + dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) - + self.axes.transAxes.transform([pep[0:2, 0]]))[0] + + # Draw the lines + self.line.set_data(pep[0], pep[1]) + self.line.draw(renderer) + + # Draw ticks + self._draw_ticks(renderer, edgep1, centers, deltas, highs, + deltas_per_point, pos) + + # Draw Offset text + self._draw_offset_text(renderer, edgep1, edgep2, labeldeltas, + centers, highs, pep, dx, dy) + + for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points( + minmax, maxmin, self._label_position)): + # See comments above + pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M) + pep = np.asarray(pep) + dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) - + self.axes.transAxes.transform([pep[0:2, 0]]))[0] + + # Draw labels + self._draw_labels(renderer, edgep1, edgep2, labeldeltas, centers, dx, dy) + + renderer.close_group('axis3d') + self.stale = False + + @artist.allow_rasterization + def draw_grid(self, renderer): + if not self.axes._draw_grid: + return + + renderer.open_group("grid3d", gid=self.get_gid()) + + ticks = self._update_ticks() + if len(ticks): + # Get general axis information: + info = self._axinfo + index = info["i"] + + mins, maxs, tc, highs = self._get_coord_info() + + minmax = np.where(highs, maxs, mins) + maxmin = np.where(~highs, maxs, mins) + + # Grid points where the planes meet + xyz0 = np.tile(minmax, (len(ticks), 1)) + xyz0[:, index] = [tick.get_loc() for tick in ticks] + + # Grid lines go from the end of one plane through the plane + # intersection (at xyz0) to the end of the other plane. The first + # point (0) differs along dimension index-2 and the last (2) along + # dimension index-1. + lines = np.stack([xyz0, xyz0, xyz0], axis=1) + lines[:, 0, index - 2] = maxmin[index - 2] + lines[:, 2, index - 1] = maxmin[index - 1] + self.gridlines.set_segments(lines) + gridinfo = info['grid'] + self.gridlines.set_color(gridinfo['color']) + self.gridlines.set_linewidth(gridinfo['linewidth']) + self.gridlines.set_linestyle(gridinfo['linestyle']) + self.gridlines.do_3d_projection() + self.gridlines.draw(renderer) + + renderer.close_group('grid3d') + + # TODO: Get this to work (more) properly when mplot3d supports the + # transforms framework. + def get_tightbbox(self, renderer=None, *, for_layout_only=False): + # docstring inherited + if not self.get_visible(): + return + # We have to directly access the internal data structures + # (and hope they are up to date) because at draw time we + # shift the ticks and their labels around in (x, y) space + # based on the projection, the current view port, and their + # position in 3D space. If we extend the transforms framework + # into 3D we would not need to do this different book keeping + # than we do in the normal axis + major_locs = self.get_majorticklocs() + minor_locs = self.get_minorticklocs() + + ticks = [*self.get_minor_ticks(len(minor_locs)), + *self.get_major_ticks(len(major_locs))] + view_low, view_high = self.get_view_interval() + if view_low > view_high: + view_low, view_high = view_high, view_low + interval_t = self.get_transform().transform([view_low, view_high]) + + ticks_to_draw = [] + for tick in ticks: + try: + loc_t = self.get_transform().transform(tick.get_loc()) + except AssertionError: + # Transform.transform doesn't allow masked values but + # some scales might make them, so we need this try/except. + pass + else: + if mtransforms._interval_contains_close(interval_t, loc_t): + ticks_to_draw.append(tick) + + ticks = ticks_to_draw + + bb_1, bb_2 = self._get_ticklabel_bboxes(ticks, renderer) + other = [] + + if self.line.get_visible(): + other.append(self.line.get_window_extent(renderer)) + if (self.label.get_visible() and not for_layout_only and + self.label.get_text()): + other.append(self.label.get_window_extent(renderer)) + + return mtransforms.Bbox.union([*bb_1, *bb_2, *other]) + + d_interval = _api.deprecated( + "3.6", alternative="get_data_interval", pending=True)( + property(lambda self: self.get_data_interval(), + lambda self, minmax: self.set_data_interval(*minmax))) + v_interval = _api.deprecated( + "3.6", alternative="get_view_interval", pending=True)( + property(lambda self: self.get_view_interval(), + lambda self, minmax: self.set_view_interval(*minmax))) + + +class XAxis(Axis): + axis_name = "x" + get_view_interval, set_view_interval = maxis._make_getset_interval( + "view", "xy_viewLim", "intervalx") + get_data_interval, set_data_interval = maxis._make_getset_interval( + "data", "xy_dataLim", "intervalx") + + +class YAxis(Axis): + axis_name = "y" + get_view_interval, set_view_interval = maxis._make_getset_interval( + "view", "xy_viewLim", "intervaly") + get_data_interval, set_data_interval = maxis._make_getset_interval( + "data", "xy_dataLim", "intervaly") + + +class ZAxis(Axis): + axis_name = "z" + get_view_interval, set_view_interval = maxis._make_getset_interval( + "view", "zz_viewLim", "intervalx") + get_data_interval, set_data_interval = maxis._make_getset_interval( + "data", "zz_dataLim", "intervalx") diff --git a/shared/package-files/79/7907962c7ca29b1484b8d564812cf9c6fbc7c0051b1b69c2e3fdf1941520c281/blob b/shared/package-files/79/7907962c7ca29b1484b8d564812cf9c6fbc7c0051b1b69c2e3fdf1941520c281/blob new file mode 100644 index 0000000000000000000000000000000000000000..b53e0976e58364f7af217b4ea0ff026e59fe6e5b --- /dev/null +++ b/shared/package-files/79/7907962c7ca29b1484b8d564812cf9c6fbc7c0051b1b69c2e3fdf1941520c281/blob @@ -0,0 +1,244 @@ +"""Tests for dimension reduction regression models.""" + +import warnings + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pandas as pd +import pytest + +from statsmodels.regression.dimred import CORE, PHD, SAVE, SlicedInverseReg +from statsmodels.tools.numdiff import approx_fprime + + +def test_poisson(): + + rs = np.random.RandomState(43242) + + # Generate a non-orthogonal design matrix + xmat = rs.normal(size=(500, 5)) + xmat[:, 1] = 0.5 * xmat[:, 0] + np.sqrt(1 - 0.5**2) * xmat[:, 1] + xmat[:, 3] = 0.5 * xmat[:, 2] + np.sqrt(1 - 0.5**2) * xmat[:, 3] + + b = np.r_[0, 1, -1, 0, 0.5] + lpr = np.dot(xmat, b) + ev = np.exp(lpr) + y = rs.poisson(ev) + + for method in range(6): + + if method == 0: + model = SlicedInverseReg(y, xmat) + rslt = model.fit() + elif method == 1: + model = SAVE(y, xmat) + rslt = model.fit(slice_n=100) + elif method == 2: + model = SAVE(y, xmat, bc=True) + rslt = model.fit(slice_n=100) + elif method == 3: + df = pd.DataFrame( + { + "y": y, + "x0": xmat[:, 0], + "x1": xmat[:, 1], + "x2": xmat[:, 2], + "x3": xmat[:, 3], + "x4": xmat[:, 4], + } + ) + model = SlicedInverseReg.from_formula( + "y ~ 0 + x0 + x1 + x2 + x3 + x4", data=df + ) + rslt = model.fit() + elif method == 4: + model = PHD(y, xmat) + rslt = model.fit() + elif method == 5: + model = PHD(y, xmat) + rslt = model.fit(resid=True) + + # Check for concentration in one direction (this is + # a single index model) + assert_equal(np.abs(rslt.eigs[0] / rslt.eigs[1]) > 5, True) + + # Check that the estimated direction aligns with the true + # direction + params = np.asarray(rslt.params) + q = np.dot(params[:, 0], b) + q /= np.sqrt(np.sum(params[:, 0] ** 2)) + q /= np.sqrt(np.sum(b**2)) + assert_equal(np.abs(q) > 0.95, True) + + +def test_sir_regularized_numdiff(): + # Use numeric gradients to check the analytic gradient + # for the regularized SIRobjective function. + + rs = np.random.RandomState(93482) + + n = 1000 + p = 10 + xmat = rs.normal(size=(n, p)) + y1 = np.dot(xmat, np.linspace(-1, 1, p)) + y2 = xmat.sum(1) + y = y2 / (1 + y1**2) + rs.normal(size=n) + model = SlicedInverseReg(y, xmat) + _ = model.fit() + + # Second difference penalty matrix. + fmat = np.zeros((p - 2, p)) + for i in range(p - 2): + fmat[i, i : i + 3] = [1, -2, 1] + + with pytest.warns(UserWarning, match="SIR.fit_regularized did not"): + model.fit_regularized(2, 3 * fmat) + + # Compare the gradients to the numerical derivatives + for _ in range(5): + pa = rs.normal(size=(p, 2)) + pa, _, _ = np.linalg.svd(pa, 0) + gn = approx_fprime(pa.ravel(), model._regularized_objective, 1e-7) + gr = model._regularized_grad(pa.ravel()) + assert_allclose(gn, gr, atol=1e-5, rtol=1e-4) + + +def test_sir_regularized_1d(): + # Compare regularized SIR to traditional SIR, in a setting where the + # regularization is compatible with the true parameters (i.e., there + # is no regularization bias). + + rs = np.random.RandomState(93482) + + n = 1000 + p = 10 + xmat = rs.normal(size=(n, p)) + y = np.dot(xmat[:, 0:4], np.r_[1, 1, -1, -1]) + rs.normal(size=n) + model = SlicedInverseReg(y, xmat) + rslt = model.fit() + + # The penalty drives p[0] ~ p[1] and p[2] ~ p[3]] + fmat = np.zeros((2, p)) + fmat[0, 0:2] = [1, -1] + fmat[1, 2:4] = [1, -1] + + rslt2 = model.fit_regularized(1, 3 * fmat) + + pa0 = np.zeros(p) + pa0[0:4] = [1, 1, -1, -1] + pa1 = rslt.params[:, 0] + pa2 = rslt2.params[:, 0:2] + + # Compare two 1d subspaces + def sim(x, y): + x = x / np.sqrt(np.sum(x * x)) + y = y / np.sqrt(np.sum(y * y)) + return 1 - np.abs(np.dot(x, y)) + + # Regularized SIRshould be closer to the truth than traditional SIR + assert_equal(sim(pa0, pa1) > sim(pa0, pa2), True) + + # Regularized SIR should be close to the truth + assert_equal(sim(pa0, pa2) < 1e-3, True) + + # Regularized SIR should have a smaller penalty value than traditional SIR + assert_equal(np.sum(np.dot(fmat, pa1) ** 2) > np.sum(np.dot(fmat, pa2) ** 2), True) + + +def test_sir_regularized_2d(): + # Compare regularized SIR to traditional SIR when there is no penalty. + # The two procedures should agree exactly. + + rs = np.random.RandomState(93482) + + n = 1000 + p = 10 + xmat = rs.normal(size=(n, p)) + y1 = np.dot(xmat[:, 0:4], np.r_[1, 1, -1, -1]) + y2 = np.dot(xmat[:, 4:8], np.r_[1, 1, -1, -1]) + y = y1 + np.arctan(y2) + rs.normal(size=n) + model = SlicedInverseReg(y, xmat) + rslt1 = model.fit() + + fmat = np.zeros((1, p)) + + for d in 1, 2, 3, 4: + if d < 3: + rslt2 = model.fit_regularized(d, fmat) + else: + with pytest.warns(UserWarning, match="SIR.fit_regularized did"): + rslt2 = model.fit_regularized(d, fmat) + pa1 = rslt1.params[:, 0:d] + pa1, _, _ = np.linalg.svd(pa1, 0) + pa2 = rslt2.params + _, s, _ = np.linalg.svd(np.dot(pa1.T, pa2)) + assert_allclose(np.sum(s), d, atol=1e-1, rtol=1e-1) + + +def test_covreduce(): + + rs = np.random.RandomState(34324) + + p = 4 + endog = [] + exog = [] + for k in range(3): + c = np.eye(p) + x = rs.normal(size=(2, 2)) + # The differences between the covariance matrices + # are all in the first 2 rows/columns. + c[0:2, 0:2] = np.dot(x.T, x) + + cr = np.linalg.cholesky(c) + m = 1000 * k + 50 * k + x = rs.normal(size=(m, p)) + x = np.dot(x, cr.T) + exog.append(x) + endog.append(k * np.ones(m)) + + endog = np.concatenate(endog) + exog = np.concatenate(exog, axis=0) + + for dim in 1, 2, 3: + + cr = CORE(endog, exog, dim) + + pt = rs.normal(size=(p, dim)) + pt, _, _ = np.linalg.svd(pt, 0) + gn = approx_fprime(pt.ravel(), cr.loglike, 1e-7) + g = cr.score(pt.ravel()) + + assert_allclose(g, gn, 1e-5, 1e-5) + + rslt = cr.fit() + proj = rslt.params + assert_equal(proj.shape[0], p) + assert_equal(proj.shape[1], dim) + assert_allclose(np.dot(proj.T, proj), np.eye(dim), 1e-8, 1e-8) + + if dim == 2: + # Here we know the approximate truth + projt = np.zeros((p, 2)) + projt[0:2, 0:2] = np.eye(2) + assert_allclose(np.trace(np.dot(proj.T, projt)), 2, rtol=1e-3, atol=1e-3) + + +def test_sir_regularized_slice_n(): + # GH: fit_regularized re-read slice_n from kwargs.get("slice_n", 20), + # but slice_n is a named parameter so it never ends up in kwargs -- an + # explicitly passed slice_n was silently discarded and 20 always used. + rs = np.random.RandomState(93482) + n = 300 + p = 5 + xmat = rs.normal(size=(n, p)) + y = xmat.sum(1) + rs.normal(size=n) + model = SlicedInverseReg(y, xmat) + fmat = np.eye(p) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + model.fit_regularized(1, fmat, slice_n=30, maxiter=1) + + # n_slice is the *count* of slices, i.e., nobs // slice_n + assert model.n_slice == n // 30 + assert len(model._slice_props) == n // 30 diff --git a/shared/package-files/79/790810399d7dff9bdb483870a99c4929ae861cbaa99607f98696e4527d9f6bd9/blob b/shared/package-files/79/790810399d7dff9bdb483870a99c4929ae861cbaa99607f98696e4527d9f6bd9/blob new file mode 100644 index 0000000000000000000000000000000000000000..64b485b5b26b3301ad5eb4f7d1dc7c4a63809ea8 --- /dev/null +++ b/shared/package-files/79/790810399d7dff9bdb483870a99c4929ae861cbaa99607f98696e4527d9f6bd9/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor fake_quantize_per_tensor_affine_cachemask_backward(const at::Tensor & grad, const at::Tensor & mask); +} // namespace native +} // namespace at diff --git a/shared/package-files/79/79086db3efd9e4f592ec1a707c2dfe7b76141019b6a47b3171463bf3539541f8/blob b/shared/package-files/79/79086db3efd9e4f592ec1a707c2dfe7b76141019b6a47b3171463bf3539541f8/blob new file mode 100644 index 0000000000000000000000000000000000000000..7504c984794e8d1b10d6b7d25d34817ecbb74127 --- /dev/null +++ b/shared/package-files/79/79086db3efd9e4f592ec1a707c2dfe7b76141019b6a47b3171463bf3539541f8/blob @@ -0,0 +1,252 @@ +from datetime import ( + datetime, + timezone, +) + +import numpy as np +import pytest + +from pandas.errors import InvalidIndexError + +from pandas import ( + CategoricalDtype, + CategoricalIndex, + DataFrame, + DatetimeIndex, + MultiIndex, + Series, + Timestamp, +) +import pandas._testing as tm + + +def test_at_timezone(): + # https://github.com/pandas-dev/pandas/issues/33544 + result = DataFrame({"foo": [datetime(2000, 1, 1)]}) + with tm.assert_produces_warning(FutureWarning, match="incompatible dtype"): + result.at[0, "foo"] = datetime(2000, 1, 2, tzinfo=timezone.utc) + expected = DataFrame( + {"foo": [datetime(2000, 1, 2, tzinfo=timezone.utc)]}, dtype=object + ) + tm.assert_frame_equal(result, expected) + + +def test_selection_methods_of_assigned_col(): + # GH 29282 + df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) + df2 = DataFrame(data={"c": [7, 8, 9]}, index=[2, 1, 0]) + df["c"] = df2["c"] + df.at[1, "c"] = 11 + result = df + expected = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [9, 11, 7]}) + tm.assert_frame_equal(result, expected) + result = df.at[1, "c"] + assert result == 11 + + result = df["c"] + expected = Series([9, 11, 7], name="c") + tm.assert_series_equal(result, expected) + + result = df[["c"]] + expected = DataFrame({"c": [9, 11, 7]}) + tm.assert_frame_equal(result, expected) + + +class TestAtSetItem: + def test_at_setitem_item_cache_cleared(self): + # GH#22372 Note the multi-step construction is necessary to trigger + # the original bug. pandas/issues/22372#issuecomment-413345309 + df = DataFrame(index=[0]) + df["x"] = 1 + df["cost"] = 2 + + # accessing df["cost"] adds "cost" to the _item_cache + df["cost"] + + # This loc[[0]] lookup used to call _consolidate_inplace at the + # BlockManager level, which failed to clear the _item_cache + df.loc[[0]] + + df.at[0, "x"] = 4 + df.at[0, "cost"] = 789 + + expected = DataFrame({"x": [4], "cost": 789}, index=[0]) + tm.assert_frame_equal(df, expected) + + # And in particular, check that the _item_cache has updated correctly. + tm.assert_series_equal(df["cost"], expected["cost"]) + + def test_at_setitem_mixed_index_assignment(self): + # GH#19860 + ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) + ser.at["a"] = 11 + assert ser.iat[0] == 11 + ser.at[1] = 22 + assert ser.iat[3] == 22 + + def test_at_setitem_categorical_missing(self): + df = DataFrame( + index=range(3), columns=range(3), dtype=CategoricalDtype(["foo", "bar"]) + ) + df.at[1, 1] = "foo" + + expected = DataFrame( + [ + [np.nan, np.nan, np.nan], + [np.nan, "foo", np.nan], + [np.nan, np.nan, np.nan], + ], + dtype=CategoricalDtype(["foo", "bar"]), + ) + + tm.assert_frame_equal(df, expected) + + def test_at_setitem_multiindex(self): + df = DataFrame( + np.zeros((3, 2), dtype="int64"), + columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]), + ) + df.at[0, "a"] = 10 + expected = DataFrame( + [[10, 10], [0, 0], [0, 0]], + columns=MultiIndex.from_tuples([("a", 0), ("a", 1)]), + ) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("row", (Timestamp("2019-01-01"), "2019-01-01")) + def test_at_datetime_index(self, row): + # Set float64 dtype to avoid upcast when setting .5 + df = DataFrame( + data=[[1] * 2], index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]) + ).astype({0: "float64"}) + expected = DataFrame( + data=[[0.5, 1], [1.0, 1]], + index=DatetimeIndex(data=["2019-01-01", "2019-01-02"]), + ) + + df.at[row, 0] = 0.5 + tm.assert_frame_equal(df, expected) + + +class TestAtSetItemWithExpansion: + def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture): + # GH#25506 + ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture) + result = Series(ts) + result.at[1] = ts + expected = Series([ts, ts]) + tm.assert_series_equal(result, expected) + + +class TestAtWithDuplicates: + def test_at_with_duplicate_axes_requires_scalar_lookup(self): + # GH#33041 check that falling back to loc doesn't allow non-scalar + # args to slip in + + arr = np.random.default_rng(2).standard_normal(6).reshape(3, 2) + df = DataFrame(arr, columns=["A", "A"]) + + msg = "Invalid call for scalar access" + with pytest.raises(ValueError, match=msg): + df.at[[1, 2]] + with pytest.raises(ValueError, match=msg): + df.at[1, ["A"]] + with pytest.raises(ValueError, match=msg): + df.at[:, "A"] + + with pytest.raises(ValueError, match=msg): + df.at[[1, 2]] = 1 + with pytest.raises(ValueError, match=msg): + df.at[1, ["A"]] = 1 + with pytest.raises(ValueError, match=msg): + df.at[:, "A"] = 1 + + +class TestAtErrors: + # TODO: De-duplicate/parametrize + # test_at_series_raises_key_error2, test_at_frame_raises_key_error2 + + def test_at_series_raises_key_error(self, indexer_al): + # GH#31724 .at should match .loc + + ser = Series([1, 2, 3], index=[3, 2, 1]) + result = indexer_al(ser)[1] + assert result == 3 + + with pytest.raises(KeyError, match="a"): + indexer_al(ser)["a"] + + def test_at_frame_raises_key_error(self, indexer_al): + # GH#31724 .at should match .loc + + df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1]) + + result = indexer_al(df)[1, 0] + assert result == 3 + + with pytest.raises(KeyError, match="a"): + indexer_al(df)["a", 0] + + with pytest.raises(KeyError, match="a"): + indexer_al(df)[1, "a"] + + def test_at_series_raises_key_error2(self, indexer_al): + # at should not fallback + # GH#7814 + # GH#31724 .at should match .loc + ser = Series([1, 2, 3], index=list("abc")) + result = indexer_al(ser)["a"] + assert result == 1 + + with pytest.raises(KeyError, match="^0$"): + indexer_al(ser)[0] + + def test_at_frame_raises_key_error2(self, indexer_al): + # GH#31724 .at should match .loc + df = DataFrame({"A": [1, 2, 3]}, index=list("abc")) + result = indexer_al(df)["a", "A"] + assert result == 1 + + with pytest.raises(KeyError, match="^0$"): + indexer_al(df)["a", 0] + + def test_at_frame_multiple_columns(self): + # GH#48296 - at shouldn't modify multiple columns + df = DataFrame({"a": [1, 2], "b": [3, 4]}) + new_row = [6, 7] + with pytest.raises( + InvalidIndexError, + match=f"You can only assign a scalar value not a \\{type(new_row)}", + ): + df.at[5] = new_row + + def test_at_getitem_mixed_index_no_fallback(self): + # GH#19860 + ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) + with pytest.raises(KeyError, match="^0$"): + ser.at[0] + with pytest.raises(KeyError, match="^4$"): + ser.at[4] + + def test_at_categorical_integers(self): + # CategoricalIndex with integer categories that don't happen to match + # the Categorical's codes + ci = CategoricalIndex([3, 4]) + + arr = np.arange(4).reshape(2, 2) + frame = DataFrame(arr, index=ci) + + for df in [frame, frame.T]: + for key in [0, 1]: + with pytest.raises(KeyError, match=str(key)): + df.at[key, key] + + def test_at_applied_for_rows(self): + # GH#48729 .at should raise InvalidIndexError when assigning rows + df = DataFrame(index=["a"], columns=["col1", "col2"]) + new_row = [123, 15] + with pytest.raises( + InvalidIndexError, + match=f"You can only assign a scalar value not a \\{type(new_row)}", + ): + df.at["a"] = new_row diff --git a/shared/package-files/79/7909ffce946e7c3b88869f369ed937d8b553aa024dda492fc7f6c077ea1e0ea2/blob b/shared/package-files/79/7909ffce946e7c3b88869f369ed937d8b553aa024dda492fc7f6c077ea1e0ea2/blob new file mode 100644 index 0000000000000000000000000000000000000000..3fd7132fde3b7e8c5ab8a6c484c2096a87ef7f5b --- /dev/null +++ b/shared/package-files/79/7909ffce946e7c3b88869f369ed937d8b553aa024dda492fc7f6c077ea1e0ea2/blob @@ -0,0 +1,1159 @@ +#!/usr/bin/env python3 +""" The Python Hipify script. +## +# Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. +# 2017-2018 Advanced Micro Devices, Inc. and +# Facebook Inc. All rights reserved. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +""" +import argparse +import fnmatch +import re +import shutil +import sys +import os + +from . import constants +from .cuda_to_hip_mappings import CUDA_TO_HIP_MAPPINGS +from .cuda_to_hip_mappings import MATH_TRANSPILATIONS + +from typing import Dict, List, Iterator, Optional +from collections.abc import Mapping, Iterable +from enum import Enum + +class CurrentState(Enum): + INITIALIZED = 1 + DONE = 2 + +class HipifyResult: + def __init__(self, current_state, hipified_path): + self.current_state = current_state + self.hipified_path = hipified_path + self.status = "" + + def __str__(self): + return ("HipifyResult:: current_state: {}, hipified_path : {}, status: {}".format(self.current_state, + self.hipified_path, self.status)) + +HipifyFinalResult = Dict[str, HipifyResult] +HIPIFY_C_BREADCRUMB = "// !!! This is a file automatically generated by hipify!!!\n" +HIPIFY_FINAL_RESULT: HipifyFinalResult = {} + +# Hardcode the PyTorch template map +"""This dictionary provides the mapping from PyTorch kernel template types +to their actual types.""" +PYTORCH_TEMPLATE_MAP = {"Dtype": "scalar_t", "T": "scalar_t"} + +__all__ = ['InputError', 'openf', 'bcolors', 'GeneratedFileCleaner', 'match_extensions', 'matched_files_iter', + 'preprocess_file_and_save_result', 'compute_stats', 'add_dim3', 'processKernelLaunches', 'find_closure_group', + 'find_bracket_group', 'find_parentheses_group', 'replace_math_functions', 'hip_header_magic', 'replace_extern_shared', + 'get_hip_file_path', 'is_out_of_place', 'is_pytorch_file', 'is_cusparse_file', 'is_special_file', 'is_caffe2_gpu_file', + 'is_caffe2_gpu_file', 'Trie', 'preprocessor', 'file_specific_replacement', 'file_add_header', + 'fix_static_global_kernels', 'extract_arguments', 'str2bool', 'CurrentState', 'HipifyResult', 'hipify'] + + +class InputError(Exception): + # Exception raised for errors in the input. + + def __init__(self, message): + super().__init__(message) + self.message = message + + def __str__(self): + return f"Input error: {self.message}" + + +def openf(filename, mode): + return open(filename, mode, errors='ignore') + + +# Color coding for printing +class bcolors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + + +# To the programmer, the output of hipify most likely are intermediates. +# This class allows users of hipify to ask for a cleanup by running the +# hipify and compilation in a with instantiating this context manager class +# with keep_intermediates=False. +# The main usecase is the cpp_extensions, specifically the load method. +# It is a good idea to keep intermediates (in case of errors or to +# not recompile unchanged files), but in cases where you don't want to +# keep them (e.g. in the CI), this can be used to remove files. +class GeneratedFileCleaner: + """Context Manager to clean up generated files""" + def __init__(self, keep_intermediates=False): + self.keep_intermediates = keep_intermediates + self.files_to_clean = set() + self.dirs_to_clean = [] + + def __enter__(self): + return self + + def open(self, fn, *args, **kwargs): + if not os.path.exists(fn): + self.files_to_clean.add(os.path.abspath(fn)) + return open(fn, *args, **kwargs) + + def makedirs(self, dn, exist_ok=False): + parent, n = os.path.split(dn) + if not n: + parent, n = os.path.split(parent) + if parent and n and not os.path.exists(parent): + self.makedirs(parent, exist_ok=True) + if not os.path.isdir(dn) or not exist_ok: + os.mkdir(dn) + self.dirs_to_clean.append(os.path.abspath(dn)) + + def __exit__(self, type, value, traceback): + if not self.keep_intermediates: + for f in self.files_to_clean: + os.unlink(f) + for d in self.dirs_to_clean[::-1]: + os.rmdir(d) + + +def match_extensions(filename: str, extensions: Iterable) -> bool: + """Helper method to see if filename ends with certain extension""" + return any(filename.endswith(e) for e in extensions) + + +def _fnmatch(filepath, patterns): + return any(fnmatch.fnmatch(filepath, pattern) for pattern in patterns) + + +def matched_files_iter( + root_path: str, + includes: Iterable = (), + ignores: Iterable = (), + extensions: Iterable = (), + out_of_place_only: bool = False, + is_pytorch_extension: bool = False) -> Iterator[str]: + + exact_matches = set(includes) + + # This is a very rough heuristic; really, we want to avoid scanning + # any file which is not checked into source control, but this script + # needs to work even if you're in a Git or Hg checkout, so easier to + # just block the biggest time sinks that won't matter in the + # end. + for (abs_dirpath, dirs, filenames) in os.walk(root_path, topdown=True): + rel_dirpath = os.path.relpath(abs_dirpath, root_path) + if rel_dirpath == '.': + # Blah blah blah O(n) blah blah + if ".git" in dirs: + dirs.remove(".git") + if "build" in dirs: + dirs.remove("build") + if "third_party" in dirs: + dirs.remove("third_party") + dirs.append("third_party/nvfuser") + for filename in filenames: + filepath = os.path.join(abs_dirpath, filename) + rel_filepath = os.path.join(rel_dirpath, filename) + # We respect extensions, UNLESS you wrote the entire + # filename verbatim, in which case we always accept it + if ( + _fnmatch(filepath, includes) + and (not _fnmatch(filepath, ignores)) + and (match_extensions(filepath, extensions) or filepath in exact_matches) + ): + if not is_pytorch_extension: # for pytorch extensions, consider all files + if not is_pytorch_file(rel_filepath) and not is_caffe2_gpu_file(rel_filepath): + continue + if out_of_place_only and not is_out_of_place(rel_filepath): + continue + yield filepath + + +def preprocess_file_and_save_result( + output_directory: str, + filepath: str, + all_files: Iterable, + header_include_dirs: Iterable, + stats: Dict[str, List], + hip_clang_launch: bool, + is_pytorch_extension: bool, + clean_ctx: GeneratedFileCleaner, + show_progress: bool) -> None: + fin_path = os.path.abspath(os.path.join(output_directory, filepath)) + hipify_result = HipifyResult(current_state=CurrentState.INITIALIZED, hipified_path=fin_path) + HIPIFY_FINAL_RESULT[fin_path] = hipify_result + result = preprocessor(output_directory, filepath, all_files, header_include_dirs, stats, + hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress) + + # Show what happened + if show_progress and "ignored" not in result.status: + print( + fin_path, "->", + result.hipified_path, result.status, flush=True) + + HIPIFY_FINAL_RESULT[fin_path] = result + + +def compute_stats(stats): + unsupported_calls = {cuda_call for (cuda_call, _filepath) in stats["unsupported_calls"]} + + # Print the number of unsupported calls + print(f"Total number of unsupported CUDA function calls: {len(unsupported_calls):d}") + + # Print the list of unsupported calls + print(", ".join(unsupported_calls)) + + # Print the number of kernel launches + print(f"\nTotal number of replaced kernel launches: {len(stats['kernel_launches']):d}") + + +def add_dim3(kernel_string, cuda_kernel): + '''adds dim3() to the second and third arguments in the kernel launch''' + count = 0 + closure = 0 + kernel_string = kernel_string.replace("<<<", "").replace(">>>", "") + arg_locs: List[Dict[str, int]] = [{} for _ in range(2)] + arg_locs[count]['start'] = 0 + for ind, c in enumerate(kernel_string): + if count > 1: + break + if c == "(": + closure += 1 + elif c == ")": + closure -= 1 + if (c == "," or ind == len(kernel_string) - 1) and closure == 0: + arg_locs[count]['end'] = ind + (c != ",") + count += 1 + if count < 2: + arg_locs[count]['start'] = ind + 1 + + first_arg_raw = kernel_string[arg_locs[0]['start']:arg_locs[0]['end'] + 1] + second_arg_raw = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']] + + first_arg_clean = kernel_string[arg_locs[0]['start']:arg_locs[0]['end']].replace("\n", "").strip(" ") + second_arg_clean = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']].replace("\n", "").strip(" ") + + first_arg_dim3 = f"dim3({first_arg_clean})" + second_arg_dim3 = f"dim3({second_arg_clean})" + + first_arg_raw_dim3 = first_arg_raw.replace(first_arg_clean, first_arg_dim3) + second_arg_raw_dim3 = second_arg_raw.replace(second_arg_clean, second_arg_dim3) + cuda_kernel = cuda_kernel.replace(first_arg_raw + second_arg_raw, first_arg_raw_dim3 + second_arg_raw_dim3) + return cuda_kernel + + +RE_KERNEL_LAUNCH = re.compile(r'([ ]+)(detail?)::[ ]+\\\n[ ]+') + + +def processKernelLaunches(string, stats): + """ Replace the CUDA style Kernel launches with the HIP style kernel launches.""" + # Concat the namespace with the kernel names. (Find cleaner way of doing this later). + string = RE_KERNEL_LAUNCH.sub(lambda inp: f"{inp.group(1)}{inp.group(2)}::", string) + + def grab_method_and_template(in_kernel): + # The positions for relevant kernel components. + pos = { + "kernel_launch": {"start": in_kernel["start"], "end": in_kernel["end"]}, + "kernel_name": {"start": -1, "end": -1}, + "template": {"start": -1, "end": -1} + } + + # Count for balancing template + count = {"<>": 0} + + # Status for whether we are parsing a certain item. + START = 0 + AT_TEMPLATE = 1 + AFTER_TEMPLATE = 2 + AT_KERNEL_NAME = 3 + + status = START + + # Parse the string character by character + for i in range(pos["kernel_launch"]["start"] - 1, -1, -1): + char = string[i] + + # Handle Templating Arguments + if status in (START, AT_TEMPLATE): + if char == ">": + if status == START: + status = AT_TEMPLATE + pos["template"]["end"] = i + count["<>"] += 1 + + if char == "<": + count["<>"] -= 1 + if count["<>"] == 0 and (status == AT_TEMPLATE): + pos["template"]["start"] = i + status = AFTER_TEMPLATE + + # Handle Kernel Name + if status != AT_TEMPLATE: + if string[i].isalnum() or string[i] in {'(', ')', '_', ':', '#'}: + if status != AT_KERNEL_NAME: + status = AT_KERNEL_NAME + pos["kernel_name"]["end"] = i + + # Case: Kernel name starts the string. + if i == 0: + pos["kernel_name"]["start"] = 0 + + # Finished + return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])] + + else: + # Potential ending point if we're already traversing a kernel's name. + if status == AT_KERNEL_NAME: + pos["kernel_name"]["start"] = i + + # Finished + return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])] + + def find_kernel_bounds(string): + """Finds the starting and ending points for all kernel launches in the string.""" + kernel_end = 0 + kernel_positions = [] + + # Continue until we cannot find any more kernels anymore. + while string.find("<<<", kernel_end) != -1: + # Get kernel starting position (starting from the previous ending point) + kernel_start = string.find("<<<", kernel_end) + + # Get kernel ending position (adjust end point past the >>>) + kernel_end = string.find(">>>", kernel_start) + 3 + if kernel_end <= 0: + raise InputError("no kernel end found") + + # Add to list of traversed kernels + kernel_positions.append({"start": kernel_start, "end": kernel_end, + "group": string[kernel_start: kernel_end]}) + + return kernel_positions + + # Replace comments and string literals from the code so that find_kernel_bounds does not + # wrongly capture kernels in comments and string literals. + # This function replaces them with "x" to keep positions. + def mask_comments(string): + in_comment = '' + prev_c = '' + new_string = '' + for c in string: + if in_comment == '': + # Outside comments + if c == '/' and prev_c == '/': + in_comment = '//' + elif c == '*' and prev_c == '/': + in_comment = '/*' + elif c == '"' and prev_c != '\\' and prev_c != "'": + in_comment = '"' + elif in_comment == '//': + # In // xxx + if c == '\r' or c == '\n': + in_comment = '' + elif in_comment == '/*': + # In /* xxx */ + if c == '/' and prev_c == '*': + in_comment = '' + elif in_comment == '"': + # In "" + if c == '"' and prev_c != '\\': + in_comment = '' + prev_c = c + if in_comment == '': + new_string += c + else: + new_string += 'x' + return new_string + + # Grab positional ranges of all kernel launches + get_kernel_positions = list(find_kernel_bounds(mask_comments(string))) + output_string = string + + # Replace each CUDA kernel with a HIP kernel. + for kernel in get_kernel_positions: + # Get kernel components + params = grab_method_and_template(kernel) + + # Find parenthesis after kernel launch + parenthesis = string.find("(", kernel["end"]) + + # Extract cuda kernel + cuda_kernel = string[params[0]["start"]:parenthesis + 1] + kernel_string = string[kernel['start']:kernel['end']] + end_param_index = 0 if params[1]['end'] == -1 else 1 + kernel_name_with_template = string[params[0]['start']:params[end_param_index]['end'] + 1] + cuda_kernel_dim3 = add_dim3(kernel_string, cuda_kernel) + # Keep number of kernel launch params consistent (grid dims, group dims, stream, dynamic shared size) + num_klp = len(extract_arguments(0, kernel["group"].replace("<<<", "(").replace(">>>", ")"))) + + hip_kernel = "hipLaunchKernelGGL(" + cuda_kernel_dim3[0:-1].replace( + ">>>", ", 0" * (4 - num_klp) + ">>>").replace("<<<", ", ").replace( + ">>>", ", ").replace(kernel_name_with_template, "(" + kernel_name_with_template + ")") + + # Replace cuda kernel with hip kernel + output_string = output_string.replace(cuda_kernel, hip_kernel) + + # Update the statistics + stats["kernel_launches"].append(hip_kernel) + + return output_string + + +def find_closure_group(input_string, start, group): + """Generalization for finding a balancing closure group + + if group = ["(", ")"], then finds the first balanced parentheses. + if group = ["{", "}"], then finds the first balanced bracket. + + Given an input string, a starting position in the input string, and the group type, + find_closure_group returns the positions of group[0] and group[1] as a tuple. + + Example: + >>> find_closure_group("(hi)", 0, ["(", ")"]) + (0, 3) + """ + + inside_parenthesis = False + parens = 0 + pos = start + p_start, p_end = -1, -1 + + while pos < len(input_string): + if input_string[pos] == group[0]: + if inside_parenthesis is False: + inside_parenthesis = True + parens = 1 + p_start = pos + else: + parens += 1 + elif input_string[pos] == group[1] and inside_parenthesis: + parens -= 1 + + if parens == 0: + p_end = pos + return p_start, p_end + + pos += 1 + return None, None + + +def find_bracket_group(input_string, start): + """Finds the first balanced parantheses.""" + return find_closure_group(input_string, start, group=["{", "}"]) + + +def find_parentheses_group(input_string, start): + """Finds the first balanced bracket.""" + return find_closure_group(input_string, start, group=["(", ")"]) + + +RE_ASSERT = re.compile(r"\bassert[ ]*\(") + + +def replace_math_functions(input_string): + """FIXME: Temporarily replace std:: invocations of math functions + with non-std:: versions to prevent linker errors NOTE: This + can lead to correctness issues when running tests, since the + correct version of the math function (exp/expf) might not get + called. Plan is to remove this function once HIP supports + std:: math function calls inside device code + + """ + output_string = input_string + for func in MATH_TRANSPILATIONS: + output_string = output_string.replace(fr'{func}(', f'{MATH_TRANSPILATIONS[func]}(') + + return output_string + + +RE_SYNCTHREADS = re.compile(r":?:?\b(__syncthreads)\b(\w*\()") + + +def hip_header_magic(input_string): + """If the file makes kernel builtin calls and does not include the cuda_runtime.h header, + then automatically add an #include to match the "magic" includes provided by NVCC. + TODO: + Update logic to ignore cases where the cuda_runtime.h is included by another file. + """ + + # Copy the input. + output_string = input_string + + # Check if one of the following headers is already included. + headers = ["hip/hip_runtime.h", "hip/hip_runtime_api.h"] + if any(re.search(fr'#include ("{ext}"|<{ext}>)', output_string) for ext in headers): + return output_string + + # Rough logic to detect if we're inside device code + hasDeviceLogic: int + hasDeviceLogic = "hipLaunchKernelGGL" in output_string + hasDeviceLogic += "__global__" in output_string + hasDeviceLogic += "__shared__" in output_string + hasDeviceLogic += RE_SYNCTHREADS.search(output_string) is not None + + # If device logic found, provide the necessary header. + if hasDeviceLogic: + output_string = '#include "hip/hip_runtime.h"\n' + input_string + + return output_string + + +RE_EXTERN_SHARED = re.compile(r"extern\s+([\w\(\)]+)?\s*__shared__\s+([\w:<>\s]+)\s+(\w+)\s*\[\s*\]\s*;") + + +def replace_extern_shared(input_string): + """Match extern __shared__ type foo[]; syntax and use HIP_DYNAMIC_SHARED() MACRO instead. + https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md#__shared__ + Example: + "extern __shared__ char smemChar[];" => "HIP_DYNAMIC_SHARED( char, smemChar)" + "extern __shared__ unsigned char smem[];" => "HIP_DYNAMIC_SHARED( unsigned char, my_smem)" + """ + output_string = input_string + output_string = RE_EXTERN_SHARED.sub( + lambda inp: f"HIP_DYNAMIC_SHARED({inp.group(1) or ''} {inp.group(2)}, {inp.group(3)})", output_string) + + return output_string + + +def get_hip_file_path(rel_filepath, is_pytorch_extension=False): + """ + Returns the new name of the hipified file + """ + # At the moment, some PyTorch source files are HIPified in place. The predicate + # is_out_of_place tells us if this is the case or not. + assert not os.path.isabs(rel_filepath) + if not is_pytorch_extension and not is_out_of_place(rel_filepath): + return rel_filepath + + dirpath, filename = os.path.split(rel_filepath) + root, ext = os.path.splitext(filename) + + # Here's the plan: + # + # In general, we need to disambiguate the HIPified filename so that + # it gets a different name from the original filename, so + # that we don't overwrite the original file + # + # There's a lot of different naming conventions across PyTorch + # and Caffe2, but the general recipe is to convert occurrences + # of cuda/gpu to hip, and add hip if there are no occurrences + # of cuda/gpu anywhere. + # + # Concretely, we do the following: + # + # - If there is a directory component named "cuda", replace + # it with "hip", AND + # + # - If the file name contains "CUDA", replace it with "HIP", AND + # + # - ALWAYS replace '.cu' with '.hip', because those files + # contain CUDA kernels that needs to be hipified and processed with + # hip compiler + # + # - If we are not hipifying a PyTorch extension, and the parent + # directory name did not change as a result of the above + # transformations, insert "hip" in the file path + # as the direct parent folder of the file + # + # - If we are hipifying a PyTorch extension, and the parent directory + # name as well as the filename (incl. extension) did not change as + # a result of the above transformations, insert "_hip" in the filename + # + # This isn't set in stone; we might adjust this to support other + # naming conventions. + + if ext == '.cu': + ext = '.hip' + + orig_filename = filename + orig_dirpath = dirpath + + dirpath = dirpath.replace('cuda', 'hip') + dirpath = dirpath.replace('CUDA', 'HIP') + dirpath = dirpath.replace('THC', 'THH') + + root = root.replace('cuda', 'hip') + root = root.replace('CUDA', 'HIP') + # Special case to handle caffe2/core/THCCachingAllocator + if dirpath != "caffe2/core": + root = root.replace('THC', 'THH') + + if not is_pytorch_extension and dirpath == orig_dirpath: + dirpath = os.path.join(dirpath, 'hip') + + if is_pytorch_extension and dirpath == orig_dirpath and (root + ext) == orig_filename: + root = root + "_hip" + + return os.path.join(dirpath, root + ext) + + +def is_out_of_place(rel_filepath): + assert not os.path.isabs(rel_filepath) + if rel_filepath.startswith("torch/"): + return False + if rel_filepath.startswith("third_party/nvfuser/"): + return False + if rel_filepath.startswith("tools/autograd/templates/"): + return False + return True + + +# Keep this synchronized with includes/ignores in build_amd.py +def is_pytorch_file(rel_filepath): + assert not os.path.isabs(rel_filepath) + if rel_filepath.startswith("aten/"): + if rel_filepath.startswith("aten/src/ATen/core/"): + return False + return True + if rel_filepath.startswith("torch/"): + return True + if rel_filepath.startswith("third_party/nvfuser/"): + return True + if rel_filepath.startswith("tools/autograd/templates/"): + return True + return False + + +def is_cusparse_file(rel_filepath): + if is_pytorch_file(rel_filepath): + return "sparse" in rel_filepath.lower() + return False + + +def is_special_file(rel_filepath): + if is_pytorch_file(rel_filepath): + if "sparse" in rel_filepath.lower(): + return True + elif "linalg" in rel_filepath.lower(): + if "batchlinearalgebralibblas" in rel_filepath.lower(): + return False # don't use "special" mappings for this specific linalg cublas file + return True + return False + +def is_caffe2_gpu_file(rel_filepath): + assert not os.path.isabs(rel_filepath) + if rel_filepath.startswith("c10/cuda"): + return True + filename = os.path.basename(rel_filepath) + _, ext = os.path.splitext(filename) + return ('gpu' in filename or ext in ['.cu', '.cuh']) and ('cudnn' not in filename) + +class TrieNode: + """A Trie node whose children are represented as a directory of char: TrieNode. + A special char '' represents end of word + """ + + def __init__(self): + self.children = {} + +class Trie: + """Creates a Trie out of a list of words. The trie can be exported to a Regex pattern. + The corresponding Regex should match much faster than a simple Regex union.""" + + def __init__(self): + """Initialize the trie with an empty root node.""" + self.root = TrieNode() + + def add(self, word): + """Add a word to the Trie. """ + node = self.root + + for char in word: + node.children.setdefault(char, TrieNode()) + node = node.children[char] + node.children[''] = True # Mark the end of the word + + def dump(self): + """Return the root node of Trie. """ + return self.root + + def quote(self, char): + """ Escape a char for regex. """ + return re.escape(char) + + def search(self, word): + """Search whether word is present in the Trie. + Returns True if yes, else return False""" + node = self.root + for char in word: + if char in node.children: + node = node.children[char] + else: + return False + + # make sure to check the end-of-word marker present + return '' in node.children + + def _pattern(self, root): + """Convert a Trie into a regular expression pattern""" + node = root + + if "" in node.children and len(node.children.keys()) == 1: + return None + + alt = [] # store alternative patterns + cc = [] # store char to char classes + q = 0 # for node representing the end of word + for char in sorted(node.children.keys()): + if isinstance(node.children[char], TrieNode): + try: + recurse = self._pattern(node.children[char]) + alt.append(self.quote(char) + recurse) + except Exception: + cc.append(self.quote(char)) + else: + q = 1 + cconly = not len(alt) > 0 + + if len(cc) > 0: + if len(cc) == 1: + alt.append(cc[0]) + else: + alt.append('[' + ''.join(cc) + ']') + + if len(alt) == 1: + result = alt[0] + else: + result = "(?:" + "|".join(alt) + ")" + + if q: + if cconly: + result += "?" + else: + result = f"(?:{result})?" + return result + + def pattern(self): + """Export the Trie to a regex pattern.""" + return self._pattern(self.root) + + def export_to_regex(self): + """Export the Trie to a regex pattern.""" + return self._pattern(self.root) + +CAFFE2_TRIE = Trie() +CAFFE2_MAP = {} +PYTORCH_TRIE = Trie() +PYTORCH_MAP: Dict[str, object] = {} + +# In PyTorch, we map cuBLAS->rocBLAS and cuSPARSE->hipSPARSE. Note the prefix, roc versus hip. +# The 'hip' APIs offer a more direct CUDA-friendly mapping, but calling rocBLAS directly has better performance. +# Unfortunately, the roc* types and hip* types differ, i.e., rocblas_float_complex versus hipComplex. +# In the case of SPARSE, we must use the hip types for complex instead of the roc types, +# but the pytorch mappings assume roc. Therefore, we create a new SPARSE mapping that has a higher priority. +# Its mappings will trigger first, and only when a miss occurs will the lower-priority pytorch mapping take place. +# When a file contains "sparse" in the filename, a mapping marked with API_SPARSE is preferred over other choices. +# Similarly, "linalg" files require rocBLAS -> hipSOLVER so they also need special handling. +PYTORCH_SPECIAL_MAP = {} + +for mapping in CUDA_TO_HIP_MAPPINGS: + assert isinstance(mapping, Mapping) + for src, value in mapping.items(): + dst = value[0] + meta_data = value[1:] + if constants.API_CAFFE2 not in meta_data: + PYTORCH_TRIE.add(src) + # if src is already in PYTORCH_MAP and dst belongs to API_SPECIAL + # do not overwrite PYTORCH_MAP, store dst separately + if constants.API_SPECIAL in meta_data and PYTORCH_MAP.get(src, ""): + PYTORCH_SPECIAL_MAP[src] = dst + else: + PYTORCH_MAP[src] = dst + if constants.API_PYTORCH not in meta_data and constants.API_SPECIAL not in meta_data: + CAFFE2_TRIE.add(src) + CAFFE2_MAP[src] = dst +RE_CAFFE2_PREPROCESSOR = re.compile(CAFFE2_TRIE.export_to_regex()) +RE_PYTORCH_PREPROCESSOR = re.compile(fr'(?<=\W)({PYTORCH_TRIE.export_to_regex()})(?=\W)') + +RE_QUOTE_HEADER = re.compile(r'#include "([^"]+)"') +RE_ANGLE_HEADER = re.compile(r'#include <([^>]+)>') +RE_THC_GENERIC_FILE = re.compile(r'#define THC_GENERIC_FILE "([^"]+)"') +RE_CU_SUFFIX = re.compile(r'\.cu\b') # be careful not to pick up .cuh + +""" +Returns a HipifyResult object with the following details: + "hipified_path" : absolute path of hipified source file + "status" : "ok" if hipified file was written out + "skipped" if an identical hipified file already existed or hipified file couldn't be written out + "ignored" if the source file was a hipified file itself or not meant to be hipified + "current_state" : CurrentState.INITIALIZED if source file is first ready to be hipified + CurrentState.DONE if source file is done with hipification process +""" + + +def preprocessor( + output_directory: str, + filepath: str, + all_files: Iterable, + header_include_dirs: Iterable, + stats: Dict[str, List], + hip_clang_launch: bool, + is_pytorch_extension: bool, + clean_ctx: GeneratedFileCleaner, + show_progress: bool) -> HipifyResult: + """ Executes the CUDA -> HIP conversion on the specified file. """ + fin_path = os.path.abspath(os.path.join(output_directory, filepath)) + hipify_result = HIPIFY_FINAL_RESULT[fin_path] + if filepath not in all_files: + hipify_result.hipified_path = None + hipify_result.status = "[ignored, not to be hipified]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + + rel_filepath = os.path.relpath(filepath, output_directory) + + with open(fin_path, encoding='utf-8') as fin: + if fin.readline() == HIPIFY_C_BREADCRUMB: + hipify_result.hipified_path = None + hipify_result.status = "[ignored, input is hipified output]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + fin.seek(0) + output_source = fin.read() + + orig_output_source = output_source + + # get_hip_file_path needs a relative path to work correctly + fout_path = os.path.abspath(os.path.join(output_directory, get_hip_file_path(rel_filepath, is_pytorch_extension))) + if not os.path.exists(os.path.dirname(fout_path)): + clean_ctx.makedirs(os.path.dirname(fout_path)) + + # unsupported_calls statistics reporting is broken atm + def pt_repl(m): + return PYTORCH_MAP[m.group(0)] + + def pt_special_repl(m): + # checks SPECIAL map first, and if a miss occurs, falls back to pytorch mappings + return PYTORCH_SPECIAL_MAP.get(m.group(0), pt_repl(m)) + + + if is_pytorch_extension: + output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source) + else: + if is_special_file(rel_filepath): + output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_special_repl, output_source) + elif is_pytorch_file(rel_filepath): + output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source) + else: + def c2_repl(m): + return CAFFE2_MAP[m.group(0)] + output_source = RE_CAFFE2_PREPROCESSOR.sub(c2_repl, output_source) + + # Header rewrites + def mk_repl(templ, include_current_dir=True): + def repl(m): + f = m.group(1) + dirpath, filename = os.path.split(f) + if ( + f.startswith(("ATen/cuda", + "ATen/native/cuda", + "ATen/native/nested/cuda", + "ATen/native/quantized/cuda", + "ATen/native/sparse/cuda", + "ATen/native/transformers/cuda", + "THC/")) or + (f.startswith("THC") and not f.startswith("THCP")) + ): + return templ.format(get_hip_file_path(m.group(1), is_pytorch_extension)) + # if filename is one of the files being hipified for this extension + if (is_pytorch_extension and any(s.endswith(filename) for s in all_files)): + header_dir = None + header_filepath = None + # If include_current_dir True, look first in same dir as the including source file + if include_current_dir: + header_dir_to_check = os.path.dirname(fin_path) + header_path_to_check = os.path.abspath(os.path.join(header_dir_to_check, f)) + if os.path.exists(header_path_to_check): + header_dir = header_dir_to_check + header_filepath = header_path_to_check + # If not found, look in include dirs one by one and first match wins + if header_filepath is None: + for header_include_dir in header_include_dirs: + header_dir_to_check = os.path.join(output_directory, header_include_dir) + header_path_to_check = os.path.abspath(os.path.join(header_dir_to_check, f)) + if os.path.exists(header_path_to_check): + header_dir = header_dir_to_check + header_filepath = header_path_to_check + # If header file not found, keep as is + if header_filepath is None: + return m.group(0) + # Hipify header file first if needed + if header_filepath not in HIPIFY_FINAL_RESULT: + preprocess_file_and_save_result(output_directory, + header_filepath, + all_files, header_include_dirs, stats, hip_clang_launch, + is_pytorch_extension, clean_ctx, show_progress) + elif header_filepath in HIPIFY_FINAL_RESULT: + header_result = HIPIFY_FINAL_RESULT[header_filepath] + if header_result.current_state == CurrentState.INITIALIZED: + # get_hip_file_path needs a relative path to work correctly + header_rel_path = os.path.relpath(header_filepath, output_directory) + header_fout_path = os.path.abspath(os.path.join(output_directory, + get_hip_file_path(header_rel_path, is_pytorch_extension))) + header_result.hipified_path = header_fout_path + HIPIFY_FINAL_RESULT[header_filepath] = header_result + return templ.format(os.path.relpath(header_fout_path if header_fout_path is not None + else header_filepath, header_dir)) + hipified_header_filepath = HIPIFY_FINAL_RESULT[header_filepath].hipified_path + return templ.format(os.path.relpath(hipified_header_filepath if hipified_header_filepath is not None + else header_filepath, header_dir)) + + return m.group(0) + return repl + output_source = RE_QUOTE_HEADER.sub(mk_repl('#include "{0}"', True), output_source) + output_source = RE_ANGLE_HEADER.sub(mk_repl('#include <{0}>', False), output_source) + output_source = RE_THC_GENERIC_FILE.sub(mk_repl('#define THC_GENERIC_FILE "{0}"'), output_source) + + # CMakeLists.txt rewrites + if filepath.endswith('CMakeLists.txt'): + output_source = output_source.replace('CUDA', 'HIP') + output_source = output_source.replace('THC', 'THH') + output_source = RE_CU_SUFFIX.sub('.hip', output_source) + + # Perform Kernel Launch Replacements + if not hip_clang_launch: + output_source = processKernelLaunches(output_source, stats) + + # Replace std:: with non-std:: versions + if (filepath.endswith((".cu", ".cuh"))) and "PowKernel" not in filepath: + output_source = replace_math_functions(output_source) + + # Include header if device code is contained. + output_source = hip_header_magic(output_source) + + # Replace the extern __shared__ + # NOTE: No longer needed after transition from hcc to hipclang. + # output_source = replace_extern_shared(output_source) + + # Don't write out identical hipified files for extensions if dirpath has not changed + if ( + is_pytorch_extension + and orig_output_source == output_source + and os.path.dirname(fin_path) == os.path.dirname(fout_path) + ): + hipify_result.hipified_path = fin_path + hipify_result.status = "[skipped, no changes]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + + # Add hipify breadcrumb for C-style files to avoid re-hipification + if fin_path != fout_path and match_extensions(fin_path, (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".hpp")): + output_source = HIPIFY_C_BREADCRUMB + output_source + + do_write = True + if os.path.exists(fout_path): + with open(fout_path, encoding='utf-8') as fout_old: + do_write = fout_old.read() != output_source + if do_write: + try: + with clean_ctx.open(fout_path, 'w', encoding='utf-8') as fout: + fout.write(output_source) + hipify_result.hipified_path = fout_path + hipify_result.status = "[ok]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + except PermissionError as e: + print(f"{bcolors.WARNING}Failed to save {fout_path} with \"{e.strerror}\", leaving {fin_path} unchanged.{bcolors.ENDC}", + file=sys.stderr) + hipify_result.hipified_path = fin_path + hipify_result.status = "[skipped, no permissions]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + else: + hipify_result.hipified_path = fout_path + hipify_result.status = "[skipped, already hipified]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + +def file_specific_replacement(filepath, search_string, replace_string, strict=False): + with openf(filepath, "r+") as f: + contents = f.read() + if strict: + contents = re.sub(fr'\b({re.escape(search_string)})\b', lambda x: replace_string, contents) + else: + contents = contents.replace(search_string, replace_string) + f.seek(0) + f.write(contents) + f.truncate() + + +def file_add_header(filepath, header): + with openf(filepath, "r+") as f: + contents = f.read() + if header[0] != "<" and header[-1] != ">": + header = f'"{header}"' + contents = (f'#include {header} \n') + contents + f.seek(0) + f.write(contents) + f.truncate() + + +def fix_static_global_kernels(in_txt): + """Static global kernels in HIP results in a compilation error.""" + in_txt = in_txt.replace(" __global__ static", "__global__") + return in_txt + + +RE_INCLUDE = re.compile(r"#include .*\n") + + +def extract_arguments(start, string): + """ Return the list of arguments in the upcoming function parameter closure. + Example: + string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' + arguments (output): + '[{'start': 1, 'end': 7}, + {'start': 8, 'end': 16}, + {'start': 17, 'end': 19}, + {'start': 20, 'end': 53}]' + """ + + arguments = [] + closures = { + "<": 0, + "(": 0 + } + current_position = start + argument_start_pos = current_position + 1 + + # Search for final parenthesis + while current_position < len(string): + if string[current_position] == "(": + closures["("] += 1 + elif string[current_position] == ")": + closures["("] -= 1 + elif string[current_position] == "<": + closures["<"] += 1 + elif string[current_position] == ">" and string[current_position - 1] != "-" and closures["<"] > 0: + closures["<"] -= 1 + + # Finished all arguments + if closures["("] == 0 and closures["<"] == 0: + # Add final argument + arguments.append({"start": argument_start_pos, "end": current_position}) + break + + # Finished current argument + if closures["("] == 1 and closures["<"] == 0 and string[current_position] == ",": + arguments.append({"start": argument_start_pos, "end": current_position}) + argument_start_pos = current_position + 1 + + current_position += 1 + + return arguments + + +def str2bool(v): + """ArgumentParser doesn't support type=bool. Thus, this helper method will convert + from possible string types to True / False.""" + if v.lower() in ('yes', 'true', 't', 'y', '1'): + return True + elif v.lower() in ('no', 'false', 'f', 'n', '0'): + return False + else: + raise argparse.ArgumentTypeError('Boolean value expected.') + + +def hipify( + project_directory: str, + show_detailed: bool = False, + extensions: Iterable = (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".in", ".hpp"), + header_extensions: Iterable = (".cuh", ".h", ".hpp"), + output_directory: str = "", + header_include_dirs: Iterable = (), + includes: Iterable = ('*',), + extra_files: Iterable = (), + out_of_place_only: bool = False, + ignores: Iterable = (), + show_progress: bool = True, + hip_clang_launch: bool = False, + is_pytorch_extension: bool = False, + hipify_extra_files_only: bool = False, + clean_ctx: Optional[GeneratedFileCleaner] = None +) -> HipifyFinalResult: + if project_directory == "": + project_directory = os.getcwd() + + # Verify the project directory exists. + if not os.path.exists(project_directory): + print("The project folder specified does not exist.") + sys.exit(1) + + # If no output directory, provide a default one. + if not output_directory: + project_directory.rstrip("/") + output_directory = project_directory + "_amd" + + if project_directory != output_directory: + includes = [include.replace(project_directory, output_directory) for include in includes] + ignores = [ignore.replace(project_directory, output_directory) for ignore in ignores] + + # Copy from project directory to output directory if not done already. + if not os.path.exists(output_directory): + shutil.copytree(project_directory, output_directory) + + all_files = list(matched_files_iter(output_directory, includes=includes, + ignores=ignores, extensions=extensions, + out_of_place_only=out_of_place_only, + is_pytorch_extension=is_pytorch_extension)) + all_files_set = set(all_files) + for f in extra_files: + if not os.path.isabs(f): + f = os.path.join(output_directory, f) + if f not in all_files_set: + all_files.append(f) + + # List all files in header_include_paths to ensure they are hipified + from pathlib import Path + for header_include_dir in header_include_dirs: + if os.path.isabs(header_include_dir): + header_include_dir_path = Path(header_include_dir) + else: + header_include_dir_path = Path(os.path.join(output_directory, header_include_dir)) + for path in header_include_dir_path.rglob('*'): + if ( + path.is_file() + and _fnmatch(str(path), includes) + and (not _fnmatch(str(path), ignores)) + and match_extensions(path.name, header_extensions) + ): + all_files.append(str(path)) + + if clean_ctx is None: + clean_ctx = GeneratedFileCleaner(keep_intermediates=True) + + # Preprocessing statistics. + stats: Dict[str, List] = {"unsupported_calls": [], "kernel_launches": []} + + for filepath in (all_files if not hipify_extra_files_only else extra_files): + preprocess_file_and_save_result(output_directory, filepath, all_files, header_include_dirs, + stats, hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress) + + print(bcolors.OKGREEN + "Successfully preprocessed all matching files." + bcolors.ENDC, file=sys.stderr) + + # Show detailed summary + if show_detailed: + compute_stats(stats) + + return HIPIFY_FINAL_RESULT diff --git a/shared/package-files/79/790b0b2a8c83c8664d3de71bc42d47473748c16fc3044a74c7faf7803eb6d29c/blob b/shared/package-files/79/790b0b2a8c83c8664d3de71bc42d47473748c16fc3044a74c7faf7803eb6d29c/blob new file mode 100644 index 0000000000000000000000000000000000000000..ad35bec70f668f1df9808d1aebec2b1405424bc1 --- /dev/null +++ b/shared/package-files/79/790b0b2a8c83c8664d3de71bc42d47473748c16fc3044a74c7faf7803eb6d29c/blob @@ -0,0 +1,83 @@ +""" +Tests that apply to all groupby operation methods. + +The only tests that should appear here are those that use the `groupby_func` fixture. +Even if it does use that fixture, prefer a more specific test file if it available +such as: + + - test_categorical + - test_groupby_dropna + - test_groupby_subclass + - test_raises +""" + +import pytest + +import pandas as pd +from pandas import DataFrame +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +def test_multiindex_group_all_columns_when_empty(groupby_func): + # GH 32464 + df = DataFrame({"a": [], "b": [], "c": []}).set_index(["a", "b", "c"]) + gb = df.groupby(["a", "b", "c"], group_keys=False) + method = getattr(gb, groupby_func) + args = get_groupby_method_args(groupby_func, df) + + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = method(*args).index + expected = df.index + tm.assert_index_equal(result, expected) + + +def test_duplicate_columns(request, groupby_func, as_index): + # GH#50806 + if groupby_func == "corrwith": + msg = "GH#50845 - corrwith fails when there are duplicate columns" + request.applymarker(pytest.mark.xfail(reason=msg)) + df = DataFrame([[1, 3, 6], [1, 4, 7], [2, 5, 8]], columns=list("abb")) + args = get_groupby_method_args(groupby_func, df) + gb = df.groupby("a", as_index=as_index) + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = getattr(gb, groupby_func)(*args) + + expected_df = df.set_axis(["a", "b", "c"], axis=1) + expected_args = get_groupby_method_args(groupby_func, expected_df) + expected_gb = expected_df.groupby("a", as_index=as_index) + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + expected = getattr(expected_gb, groupby_func)(*expected_args) + if groupby_func not in ("size", "ngroup", "cumcount"): + expected = expected.rename(columns={"c": "b"}) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "idx", + [ + pd.Index(["a", "a"], name="foo"), + pd.MultiIndex.from_tuples((("a", "a"), ("a", "a")), names=["foo", "bar"]), + ], +) +def test_dup_labels_output_shape(groupby_func, idx): + if groupby_func in {"size", "ngroup", "cumcount"}: + pytest.skip(f"Not applicable for {groupby_func}") + + df = DataFrame([[1, 1]], columns=idx) + grp_by = df.groupby([0]) + + args = get_groupby_method_args(groupby_func, df) + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = getattr(grp_by, groupby_func)(*args) + + assert result.shape == (1, 2) + tm.assert_index_equal(result.columns, idx) diff --git a/shared/package-files/79/790c255c2b8d41daf46223eed00674b72738080e7e8003eed24cbf767f894306/blob b/shared/package-files/79/790c255c2b8d41daf46223eed00674b72738080e7e8003eed24cbf767f894306/blob new file mode 100644 index 0000000000000000000000000000000000000000..f97c87a249b37504191e3a455da751a7ba37859a Binary files /dev/null and b/shared/package-files/79/790c255c2b8d41daf46223eed00674b72738080e7e8003eed24cbf767f894306/blob differ diff --git a/shared/package-files/79/790c43699c54f398f1c3d35776bcfe7cd4e69c479ed1732959520610359c77d7/blob b/shared/package-files/79/790c43699c54f398f1c3d35776bcfe7cd4e69c479ed1732959520610359c77d7/blob new file mode 100644 index 0000000000000000000000000000000000000000..3fb290c812f8de293c9731ecd6bc83ee88fd2239 --- /dev/null +++ b/shared/package-files/79/790c43699c54f398f1c3d35776bcfe7cd4e69c479ed1732959520610359c77d7/blob @@ -0,0 +1,45 @@ +import numpy as np +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.ticker as ticker + +__all__ = ["palplot", "dogplot"] + + +def palplot(pal, size=1): + """Plot the values in a color palette as a horizontal array. + + Parameters + ---------- + pal : sequence of matplotlib colors + colors, i.e. as returned by seaborn.color_palette() + size : + scaling factor for size of plot + + """ + n = len(pal) + _, ax = plt.subplots(1, 1, figsize=(n * size, size)) + ax.imshow(np.arange(n).reshape(1, n), + cmap=mpl.colors.ListedColormap(list(pal)), + interpolation="nearest", aspect="auto") + ax.set_xticks(np.arange(n) - .5) + ax.set_yticks([-.5, .5]) + # Ensure nice border between colors + ax.set_xticklabels(["" for _ in range(n)]) + # The proper way to set no ticks + ax.yaxis.set_major_locator(ticker.NullLocator()) + + +def dogplot(*_, **__): + """Who's a good boy?""" + from urllib.request import urlopen + from io import BytesIO + + url = "https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png" + pic = np.random.randint(2, 7) + data = BytesIO(urlopen(url.format(pic)).read()) + img = plt.imread(data) + f, ax = plt.subplots(figsize=(5, 5), dpi=100) + f.subplots_adjust(0, 0, 1, 1) + ax.imshow(img) + ax.set_axis_off() diff --git a/shared/package-files/79/790f1a0d8183420287354837a32ab598af6c78df09b484b8fee0c7649e3cc903/blob b/shared/package-files/79/790f1a0d8183420287354837a32ab598af6c78df09b484b8fee0c7649e3cc903/blob new file mode 100644 index 0000000000000000000000000000000000000000..8d2ba45ad3cc0526d00975413494997a0d2c846d --- /dev/null +++ b/shared/package-files/79/790f1a0d8183420287354837a32ab598af6c78df09b484b8fee0c7649e3cc903/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & adaptive_max_pool2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices) { + return at::_ops::adaptive_max_pool2d_backward_grad_input::call(grad_output, self, indices, grad_input); +} +// aten::adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & adaptive_max_pool2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, at::Tensor & grad_input) { + return at::_ops::adaptive_max_pool2d_backward_grad_input::call(grad_output, self, indices, grad_input); +} + +// aten::adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor +inline at::Tensor adaptive_max_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices) { + return at::_ops::adaptive_max_pool2d_backward::call(grad_output, self, indices); +} + +} diff --git a/shared/package-files/79/7911f351921afaec51c79b7247dc821960a8620058cc0cec3a16499b7ba43a88/blob b/shared/package-files/79/7911f351921afaec51c79b7247dc821960a8620058cc0cec3a16499b7ba43a88/blob new file mode 100644 index 0000000000000000000000000000000000000000..1b4c16b474327c2712d99881a282a553bdf60155 --- /dev/null +++ b/shared/package-files/79/7911f351921afaec51c79b7247dc821960a8620058cc0cec3a16499b7ba43a88/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API huber_loss_backward_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, double, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::huber_loss_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "huber_loss_backward.out(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta, *, Tensor(a!) grad_input) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double delta, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double delta, at::Tensor & grad_input); +}; + +struct TORCH_API huber_loss_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::huber_loss_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double delta); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double delta); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/79/7917256306b904a42d46fbd0cca76c94626e557aa0641dd5f7300203754f3966/blob b/shared/package-files/79/7917256306b904a42d46fbd0cca76c94626e557aa0641dd5f7300203754f3966/blob new file mode 100644 index 0000000000000000000000000000000000000000..cd9e2784c94a6ccfb097a3be2910a0a0f3bdbaae --- /dev/null +++ b/shared/package-files/79/7917256306b904a42d46fbd0cca76c94626e557aa0641dd5f7300203754f3966/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API int64_t sparse_dim(const at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/79/791dfbec0f25f3603d9f2cea55db0ac24ad63aaec341523f08f9766604be251d/blob b/shared/package-files/79/791dfbec0f25f3603d9f2cea55db0ac24ad63aaec341523f08f9766604be251d/blob new file mode 100644 index 0000000000000000000000000000000000000000..a9a66a3dbb9d1dfbe8b8a7b926d70bee0a645258 --- /dev/null +++ b/shared/package-files/79/791dfbec0f25f3603d9f2cea55db0ac24ad63aaec341523f08f9766604be251d/blob @@ -0,0 +1,47 @@ +#include +#include + +namespace at { +namespace native { + +inline void check_pixel_shuffle_shapes(const Tensor& self, int64_t upscale_factor) { + TORCH_CHECK(self.dim() >= 3, + "pixel_shuffle expects input to have at least 3 dimensions, but got input with ", + self.dim(), " dimension(s)"); + TORCH_CHECK(upscale_factor > 0, + "pixel_shuffle expects a positive upscale_factor, but got ", + upscale_factor); + int64_t c = self.size(-3); + int64_t upscale_factor_squared = upscale_factor * upscale_factor; + TORCH_CHECK(c % upscale_factor_squared == 0, + "pixel_shuffle expects its input's 'channel' dimension to be divisible by the square of " + "upscale_factor, but input.size(-3)=", c, " is not divisible by ", upscale_factor_squared); +} + +inline void check_pixel_unshuffle_shapes(const Tensor& self, int64_t downscale_factor) { + TORCH_CHECK( + self.dim() >= 3, + "pixel_unshuffle expects input to have at least 3 dimensions, but got input with ", + self.dim(), + " dimension(s)"); + TORCH_CHECK( + downscale_factor > 0, + "pixel_unshuffle expects a positive downscale_factor, but got ", + downscale_factor); + int64_t h = self.size(-2); + int64_t w = self.size(-1); + TORCH_CHECK( + h % downscale_factor == 0, + "pixel_unshuffle expects height to be divisible by downscale_factor, but input.size(-2)=", + h, + " is not divisible by ", + downscale_factor); + TORCH_CHECK( + w % downscale_factor == 0, + "pixel_unshuffle expects width to be divisible by downscale_factor, but input.size(-1)=", + w, + " is not divisible by ", + downscale_factor); +} + +}} // namespace at::native diff --git a/shared/package-files/79/791e7dd0aec1099b6c69bf92b6b770f23bb42ee7edf98c4597b8267bf83da6da/blob b/shared/package-files/79/791e7dd0aec1099b6c69bf92b6b770f23bb42ee7edf98c4597b8267bf83da6da/blob new file mode 100644 index 0000000000000000000000000000000000000000..a6015e4e90ece7ffe9f570af554b692659bcb99d --- /dev/null +++ b/shared/package-files/79/791e7dd0aec1099b6c69bf92b6b770f23bb42ee7edf98c4597b8267bf83da6da/blob @@ -0,0 +1,174 @@ +from enum import Enum +from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union + +from django.http.request import HttpRequest +from django.template.context import Context as Context +from django.template.engine import Engine +from django.template.library import Library +from django.template.loaders.base import Loader +from django.utils.safestring import SafeText + +FILTER_SEPARATOR: str +FILTER_ARGUMENT_SEPARATOR: str +VARIABLE_ATTRIBUTE_SEPARATOR: str +BLOCK_TAG_START: str +BLOCK_TAG_END: str +VARIABLE_TAG_START: str +VARIABLE_TAG_END: str +COMMENT_TAG_START: str +COMMENT_TAG_END: str +TRANSLATOR_COMMENT_MARK: str +SINGLE_BRACE_START: str +SINGLE_BRACE_END: str +UNKNOWN_SOURCE: str +tag_re: Any +logger: Any + +class TokenType(Enum): + TEXT: int = ... + VAR: int = ... + BLOCK: int = ... + COMMENT: int = ... + +class VariableDoesNotExist(Exception): + msg: str = ... + params: Tuple[Union[Dict[str, str], str]] = ... + def __init__(self, msg: str, params: Tuple[Union[Dict[str, str], str]] = ...) -> None: ... + +class Origin: + name: str = ... + template_name: Optional[Union[bytes, str]] = ... + loader: Optional[Loader] = ... + def __init__( + self, name: str, template_name: Optional[Union[bytes, str]] = ..., loader: Optional[Loader] = ... + ) -> None: ... + @property + def loader_name(self) -> Optional[str]: ... + +class Template: + name: Optional[str] = ... + origin: Origin = ... + engine: Engine = ... + source: str = ... + nodelist: NodeList = ... + def __init__( + self, + template_string: Union[Template, str], + origin: Optional[Origin] = ..., + name: Optional[str] = ..., + engine: Optional[Engine] = ..., + ) -> None: ... + def __iter__(self) -> None: ... + def render( + self, context: Optional[Union[Context, Dict[str, Any]]] = ..., request: Optional[HttpRequest] = ... + ) -> Any: ... + def compile_nodelist(self) -> NodeList: ... + def get_exception_info(self, exception: Exception, token: Token) -> Dict[str, Any]: ... + +def linebreak_iter(template_source: str) -> Iterator[int]: ... + +class Token: + contents: str + token_type: TokenType + lineno: Optional[int] = ... + position: Optional[Tuple[int, int]] = ... + def __init__( + self, + token_type: TokenType, + contents: str, + position: Optional[Tuple[int, int]] = ..., + lineno: Optional[int] = ..., + ) -> None: ... + def split_contents(self) -> List[str]: ... + +class Lexer: + template_string: str = ... + verbatim: Union[bool, str] = ... + def __init__(self, template_string: str) -> None: ... + def tokenize(self) -> List[Token]: ... + def create_token( + self, token_string: str, position: Optional[Tuple[int, int]], lineno: int, in_tag: bool + ) -> Token: ... + +class DebugLexer(Lexer): + template_string: str + verbatim: Union[bool, str] + def tokenize(self) -> List[Token]: ... + +class Parser: + tokens: Union[List[Token], str] = ... + tags: Dict[str, Callable] = ... + filters: Dict[str, Callable] = ... + command_stack: List[Tuple[str, Token]] = ... + libraries: Dict[str, Library] = ... + origin: Optional[Origin] = ... + def __init__( + self, + tokens: Union[List[Token], str], + libraries: Optional[Dict[str, Library]] = ..., + builtins: Optional[List[Library]] = ..., + origin: Optional[Origin] = ..., + ) -> None: ... + def parse(self, parse_until: Optional[Tuple[str]] = ...) -> NodeList: ... + def skip_past(self, endtag: str) -> None: ... + def extend_nodelist(self, nodelist: NodeList, node: Node, token: Token) -> None: ... + def error(self, token: Token, e: Union[Exception, str]) -> Exception: ... + def invalid_block_tag(self, token: Token, command: str, parse_until: Union[List[Any], Tuple[str]] = ...) -> Any: ... + def unclosed_block_tag(self, parse_until: Tuple[str]) -> Any: ... + def next_token(self) -> Token: ... + def prepend_token(self, token: Token) -> None: ... + def delete_first_token(self) -> None: ... + def add_library(self, lib: Library) -> None: ... + def compile_filter(self, token: str) -> FilterExpression: ... + def find_filter(self, filter_name: str) -> Callable: ... + +constant_string: Any +filter_raw_string: Any +filter_re: Any + +class FilterExpression: + token: str = ... + filters: List[Any] = ... + var: Any = ... + def __init__(self, token: str, parser: Parser) -> None: ... + def resolve(self, context: Mapping[str, Any], ignore_failures: bool = ...) -> Any: ... + @staticmethod + def args_check(name: str, func: Callable, provided: List[Tuple[bool, Any]]) -> bool: ... + +class Variable: + var: Union[Dict[Any, Any], str] = ... + literal: Optional[Union[SafeText, float]] = ... + lookups: Optional[Tuple[str]] = ... + translate: bool = ... + message_context: Optional[str] = ... + def __init__(self, var: Union[Dict[Any, Any], str]) -> None: ... + def resolve(self, context: Union[Mapping[str, Mapping[str, Any]], Context, int, str]) -> Any: ... + +class Node: + must_be_first: bool = ... + child_nodelists: Any = ... + origin: Origin + token: Token = ... + def render(self, context: Context) -> str: ... + def render_annotated(self, context: Context) -> Union[int, str]: ... + def __iter__(self) -> None: ... + def get_nodes_by_type(self, nodetype: Type[Node]) -> List[Node]: ... + +class NodeList(List[Node]): + contains_nontext: bool = ... + def render(self, context: Context) -> SafeText: ... + def get_nodes_by_type(self, nodetype: Type[Node]) -> List[Node]: ... + +class TextNode(Node): + s: str = ... + def __init__(self, s: str) -> None: ... + +def render_value_in_context(value: Any, context: Context) -> str: ... + +class VariableNode(Node): + filter_expression: FilterExpression = ... + def __init__(self, filter_expression: FilterExpression) -> None: ... + +kwarg_re: Any + +def token_kwargs(bits: Sequence[str], parser: Parser, support_legacy: bool = ...) -> Dict[str, FilterExpression]: ... diff --git a/shared/package-files/79/791fb27f249f78f25cf8e24707819889bf8348c519deab01eddac6188bad36a6/blob b/shared/package-files/79/791fb27f249f78f25cf8e24707819889bf8348c519deab01eddac6188bad36a6/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b779d9f5e44978a7ada730278daf23f03a0a917 --- /dev/null +++ b/shared/package-files/79/791fb27f249f78f25cf8e24707819889bf8348c519deab01eddac6188bad36a6/blob @@ -0,0 +1,289 @@ +""" +Assesment of Generalized Estimating Equations using simulation. + +This script checks ordinal and nominal models for multinomial data. + +See the generated file "gee_categorical_simulation_check.txt" for +results. +""" +from statsmodels.compat.python import lrange + +from pathlib import Path + +import numpy as np +from scipy import stats + +from statsmodels.genmod.cov_struct import GlobalOddsRatio +from statsmodels.genmod.families import Binomial +from statsmodels.genmod.generalized_estimating_equations import ( + GEE, + Multinomial, + gee_ordinal_starting_values, + gee_setup_nominal, + gee_setup_ordinal, +) + +from .gee_gaussian_simulation_check import GEE_simulator + + +class ordinal_simulator(GEE_simulator): + + # The thresholds where the latent continuous process is cut to + # obtain the categorical values. + thresholds = None + + def true_params(self): + return np.concatenate((self.thresholds, self.params)) + + def starting_values(self, nconstraints): + beta = gee_ordinal_starting_values(self.endog, + len(self.params)) + if nconstraints > 0: + m = self.exog_ex.shape[1] - nconstraints + beta = beta[0:m] + + return beta + + def print_dparams(self, dparams_est): + OUT.write(f"Odds ratio estimate: {dparams_est[0]:8.4f}\n") + OUT.write(f"Odds ratio truth: {self.dparams[0]:8.4f}\n") + OUT.write("\n") + + def simulate(self): + + endog, exog, group, time = [], [], [], [] + + for i in range(self.ngroups): + + gsize = np.random.randint(self.group_size_range[0], + self.group_size_range[1]) + + group.append([i,] * gsize) + + time1 = np.random.normal(size=(gsize, 2)) + time.append(time1) + + exog1 = np.random.normal(size=(gsize, len(self.params))) + exog.append(exog1) + + lp = np.dot(exog1, self.params) + + z = np.random.uniform(size=gsize) + z = np.log(z / (1 - z)) + lp + endog1 = np.array([np.sum(x > self.thresholds) for x in z]) + endog.append(endog1) + + self.exog = np.concatenate(exog, axis=0) + self.endog = np.concatenate(endog) + self.time = np.concatenate(time, axis=0) + self.group = np.concatenate(group) + self.offset = np.zeros(len(self.endog), dtype=np.float64) + + +class nominal_simulator(GEE_simulator): + + def starting_values(self, nconstraints): + return None + + def true_params(self): + return np.concatenate(self.params[:-1]) + + def print_dparams(self, dparams_est): + OUT.write(f"Odds ratio estimate: {dparams_est[0]:8.4f}\n") + OUT.write(f"Odds ratio truth: {self.dparams[0]:8.4f}\n") + OUT.write("\n") + + def simulate(self): + + endog, exog, group, time = [], [], [], [] + + for i in range(self.ngroups): + + gsize = np.random.randint(self.group_size_range[0], + self.group_size_range[1]) + + group.append([i,] * gsize) + + time1 = np.random.normal(size=(gsize, 2)) + time.append(time1) + + exog1 = np.random.normal(size=(gsize, len(self.params[0]))) + exog.append(exog1) + + # Probabilities for each outcome + prob = [np.exp(np.dot(exog1, p)) for p in self.params] + prob = np.vstack(prob).T + prob /= prob.sum(1)[:, None] + + m = len(self.params) + endog1 = [] + for k in range(gsize): + pdist = stats.rv_discrete(values=(lrange(m), + prob[k, :])) + endog1.append(pdist.rvs()) + + endog.append(np.asarray(endog1)) + + self.exog = np.concatenate(exog, axis=0) + self.endog = np.concatenate(endog).astype(np.int32) + self.time = np.concatenate(time, axis=0) + self.group = np.concatenate(group) + self.offset = np.zeros(len(self.endog), dtype=np.float64) + + +def gendat_ordinal(): + + os = ordinal_simulator() + os.params = np.r_[0., 1] + os.ngroups = 200 + os.thresholds = [1, 0, -1] + os.dparams = [1.,] + os.simulate() + + data = np.concatenate((os.endog[:, None], os.exog, + os.group[:, None]), axis=1) + + os.endog_ex, os.exog_ex, os.intercepts, os.nthresh = \ + gee_setup_ordinal(data, 0) + + os.group_ex = os.exog_ex[:, -1] + os.exog_ex = os.exog_ex[:, 0:-1] + + os.exog_ex = np.concatenate((os.intercepts, os.exog_ex), + axis=1) + + va = GlobalOddsRatio(4, "ordinal") + + lhs = np.array([[0., 0., 0, 1., 0.], [0., 0, 0, 0, 1]]) + rhs = np.r_[0., 1] + + return os, va, Binomial(), (lhs, rhs) + + +def gendat_nominal(): + + ns = nominal_simulator() + + # The last component of params must be identically zero + ns.params = [np.r_[0., 1], np.r_[-1., 0], np.r_[0., 0]] + ns.ngroups = 200 + ns.dparams = [1., ] + ns.simulate() + + data = np.concatenate((ns.endog[:, None], ns.exog, + ns.group[:, None]), axis=1) + + ns.endog_ex, ns.exog_ex, ns.exog_ne, ns.nlevel = \ + gee_setup_nominal(data, 0, [3,]) + + ns.group_ex = ns.exog_ne[:, 0] + + va = GlobalOddsRatio(3, "nominal") + + lhs = np.array([[0., 1., 1, 0],]) + rhs = np.r_[0.,] + + return ns, va, Multinomial(3), (lhs, rhs) + + +if __name__ == "__main__": + + nrep = 100 + + OUT = Path("gee_categorical_simulation_check.txt").open("w", encoding="utf-8") + + np.set_printoptions(formatter={"all": lambda x: f"{x:8.3f}"}, + suppress=True) + + # Loop over data generating models + gendats = [gendat_nominal, gendat_ordinal] + + for jg, gendat in enumerate(gendats): + + dparams = [] + params = [] + std_errors = [] + pvalues = [] + + for _ in range(nrep): + + da, va, mt, constraint = gendat() + + beta = da.starting_values(0) + + md = GEE(da.endog_ex, da.exog_ex, da.group_ex, None, + mt, va) + mdf = md.fit(start_params=beta) + + if mdf is None: + continue + + scale_inv = 1 / md.estimate_scale() + + dparams.append(np.r_[va.dparams, scale_inv]) + + params.append(np.asarray(mdf.params)) + std_errors.append(np.asarray(mdf.standard_errors)) + + da, va, mt, constraint = gendat() + + beta = da.starting_values(constraint[0].shape[0]) + + md = GEE(da.endog_ex, da.exog_ex, da.group_ex, None, + mt, va, constraint=constraint) + mdf = md.fit(start_params=beta) + + if mdf is None: + continue + + score = md.score_test_results + pvalues.append(score["p-value"]) + + dparams_mean = np.array(sum(dparams) / len(dparams)) + + OUT.write("{} data.\n".format(("Nominal", "Ordinal")[jg])) + OUT.write(f"{len(pvalues):d} runs converged successfully.\n") + + OUT.write("Checking dependence parameters:\n") + da.print_dparams(dparams_mean) + + params = np.array(params) + eparams = params.mean(0) + sdparams = params.std(0) + std_errors = np.array(std_errors) + std_errors = std_errors.mean(0) + true_params = da.true_params() + + OUT.write("Checking parameter values:\n") + OUT.write("Observed: ") + OUT.write(np.array_str(eparams) + "\n") + OUT.write("Expected: ") + OUT.write(np.array_str(true_params) + "\n") + OUT.write("Absolute difference: ") + OUT.write(np.array_str(eparams - true_params) + "\n") + OUT.write("Relative difference: ") + OUT.write(np.array_str((eparams - true_params) / true_params) + + "\n") + OUT.write("\n") + + OUT.write("Checking standard errors:\n") + OUT.write("Observed: ") + OUT.write(np.array_str(sdparams) + "\n") + OUT.write("Expected: ") + OUT.write(np.array_str(std_errors) + "\n") + OUT.write("Absolute difference: ") + OUT.write(np.array_str(sdparams - std_errors) + "\n") + OUT.write("Relative difference: ") + OUT.write(np.array_str((sdparams - std_errors) / std_errors) + + "\n") + OUT.write("\n") + + OUT.write("Checking constrained estimation:\n") + OUT.write("Observed Expected\n") + + pvalues.sort() + OUT.writelines(f"{pvalues[int(q*len(pvalues))]:10.3f} {q:10.3f}\n" for q in np.arange(0.1, 0.91, 0.1)) + + OUT.write("=" * 80 + "\n\n") + + OUT.close() diff --git a/shared/package-files/79/79223e955c81cd85b50f6bd140faef8573e1429440ae1bff1a8071d4021f5877/blob b/shared/package-files/79/79223e955c81cd85b50f6bd140faef8573e1429440ae1bff1a8071d4021f5877/blob new file mode 100644 index 0000000000000000000000000000000000000000..a8a37302daa000d736ef9d935813892a725cbede --- /dev/null +++ b/shared/package-files/79/79223e955c81cd85b50f6bd140faef8573e1429440ae1bff1a8071d4021f5877/blob @@ -0,0 +1,201 @@ +from collections import OrderedDict, deque +from datetime import date, time, datetime +from decimal import Decimal +from fractions import Fraction +import ast +import enum +import typing + + +class CannotEval(Exception): + def __repr__(self): + return self.__class__.__name__ + + __str__ = __repr__ + + +def is_any(x, *args): + return any( + x is arg + for arg in args + ) + + +def of_type(x, *types): + if is_any(type(x), *types): + return x + else: + raise CannotEval + + +def of_standard_types(x, *, check_dict_values: bool, deep: bool): + if is_standard_types(x, check_dict_values=check_dict_values, deep=deep): + return x + else: + raise CannotEval + + +def is_standard_types(x, *, check_dict_values: bool, deep: bool): + try: + return _is_standard_types_deep(x, check_dict_values, deep)[0] + except RecursionError: + return False + + +def _is_standard_types_deep(x, check_dict_values: bool, deep: bool): + typ = type(x) + if is_any( + typ, + str, + int, + bool, + float, + bytes, + complex, + date, + time, + datetime, + Fraction, + Decimal, + type(None), + object, + ): + return True, 0 + + if is_any(typ, tuple, frozenset, list, set, dict, OrderedDict, deque, slice): + if typ in [slice]: + length = 0 + else: + length = len(x) + assert isinstance(deep, bool) + if not deep: + return True, length + + if check_dict_values and typ in (dict, OrderedDict): + items = (v for pair in x.items() for v in pair) + elif typ is slice: + items = [x.start, x.stop, x.step] + else: + items = x + for item in items: + if length > 100000: + return False, length + is_standard, item_length = _is_standard_types_deep( + item, check_dict_values, deep + ) + if not is_standard: + return False, length + length += item_length + return True, length + + return False, 0 + + +class _E(enum.Enum): + pass + + +class _C: + def foo(self): pass # pragma: nocover + + def bar(self): pass # pragma: nocover + + @classmethod + def cm(cls): pass # pragma: nocover + + @staticmethod + def sm(): pass # pragma: nocover + + +safe_name_samples = { + "len": len, + "append": list.append, + "__add__": list.__add__, + "insert": [].insert, + "__mul__": [].__mul__, + "fromkeys": dict.__dict__['fromkeys'], + "is_any": is_any, + "__repr__": CannotEval.__repr__, + "foo": _C().foo, + "bar": _C.bar, + "cm": _C.cm, + "sm": _C.sm, + "ast": ast, + "CannotEval": CannotEval, + "_E": _E, +} + +typing_annotation_samples = { + name: getattr(typing, name) + for name in "List Dict Tuple Set Callable Mapping".split() +} + +safe_name_types = tuple({ + type(f) + for f in safe_name_samples.values() +}) + + +typing_annotation_types = tuple({ + type(f) + for f in typing_annotation_samples.values() +}) + + +def eq_checking_types(a, b): + return type(a) is type(b) and a == b + + +def ast_name(node): + if isinstance(node, ast.Name): + return node.id + elif isinstance(node, ast.Attribute): + return node.attr + else: + return None + + +def safe_name(value): + typ = type(value) + if is_any(typ, *safe_name_types): + return value.__name__ + elif value is typing.Optional: + return "Optional" + elif value is typing.Union: + return "Union" + elif is_any(typ, *typing_annotation_types): + return getattr(value, "__name__", None) or getattr(value, "_name", None) + else: + return None + + +def has_ast_name(value, node): + value_name = safe_name(value) + if type(value_name) is not str: + return False + return eq_checking_types(ast_name(node), value_name) + + +def copy_ast_without_context(x): + if isinstance(x, ast.AST): + kwargs = { + field: copy_ast_without_context(getattr(x, field)) + for field in x._fields + if field != 'ctx' + if hasattr(x, field) + } + return type(x)(**kwargs) + elif isinstance(x, list): + return list(map(copy_ast_without_context, x)) + else: + return x + + +def ensure_dict(x): + """ + Handles invalid non-dict inputs + """ + try: + return dict(x) + except Exception: + return {} diff --git a/shared/package-files/79/7923cdce02f46d719df43663dcf5f5bf21e28ac5397c950ec7dc4e357881b33f/blob b/shared/package-files/79/7923cdce02f46d719df43663dcf5f5bf21e28ac5397c950ec7dc4e357881b33f/blob new file mode 100644 index 0000000000000000000000000000000000000000..97dc90c6e4644a71cd19683e31c8624ea3184824 --- /dev/null +++ b/shared/package-files/79/7923cdce02f46d719df43663dcf5f5bf21e28ac5397c950ec7dc4e357881b33f/blob @@ -0,0 +1,147 @@ +"""Record of phased-in incompatible language changes. + +Each line is of the form: + + FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," + CompilerFlag ")" + +where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples +of the same form as sys.version_info: + + (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int + PY_MINOR_VERSION, # the 1; an int + PY_MICRO_VERSION, # the 0; an int + PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string + PY_RELEASE_SERIAL # the 3; an int + ) + +OptionalRelease records the first release in which + + from __future__ import FeatureName + +was accepted. + +In the case of MandatoryReleases that have not yet occurred, +MandatoryRelease predicts the release in which the feature will become part +of the language. + +Else MandatoryRelease records when the feature became part of the language; +in releases at or after that, modules no longer need + + from __future__ import FeatureName + +to use the feature in question, but may continue to use such imports. + +MandatoryRelease may also be None, meaning that a planned feature got +dropped. + +Instances of class _Feature have two corresponding methods, +.getOptionalRelease() and .getMandatoryRelease(). + +CompilerFlag is the (bitfield) flag that should be passed in the fourth +argument to the builtin function compile() to enable the feature in +dynamically compiled code. This flag is stored in the .compiler_flag +attribute on _Future instances. These values must match the appropriate +#defines of CO_xxx flags in Include/cpython/compile.h. + +No feature line is ever to be deleted from this file. +""" + +all_feature_names = [ + "nested_scopes", + "generators", + "division", + "absolute_import", + "with_statement", + "print_function", + "unicode_literals", + "barry_as_FLUFL", + "generator_stop", + "annotations", +] + +__all__ = ["all_feature_names"] + all_feature_names + +# The CO_xxx symbols are defined here under the same names defined in +# code.h and used by compile.h, so that an editor search will find them here. +# However, they're not exported in __all__, because they don't really belong to +# this module. +CO_NESTED = 0x0010 # nested_scopes +CO_GENERATOR_ALLOWED = 0 # generators (obsolete, was 0x1000) +CO_FUTURE_DIVISION = 0x20000 # division +CO_FUTURE_ABSOLUTE_IMPORT = 0x40000 # perform absolute imports by default +CO_FUTURE_WITH_STATEMENT = 0x80000 # with statement +CO_FUTURE_PRINT_FUNCTION = 0x100000 # print function +CO_FUTURE_UNICODE_LITERALS = 0x200000 # unicode string literals +CO_FUTURE_BARRY_AS_BDFL = 0x400000 +CO_FUTURE_GENERATOR_STOP = 0x800000 # StopIteration becomes RuntimeError in generators +CO_FUTURE_ANNOTATIONS = 0x1000000 # annotations become strings at runtime + + +class _Feature: + + def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): + self.optional = optionalRelease + self.mandatory = mandatoryRelease + self.compiler_flag = compiler_flag + + def getOptionalRelease(self): + """Return first release in which this feature was recognized. + + This is a 5-tuple, of the same form as sys.version_info. + """ + return self.optional + + def getMandatoryRelease(self): + """Return release in which this feature will become mandatory. + + This is a 5-tuple, of the same form as sys.version_info, or, if + the feature was dropped, is None. + """ + return self.mandatory + + def __repr__(self): + return "_Feature" + repr((self.optional, + self.mandatory, + self.compiler_flag)) + + +nested_scopes = _Feature((2, 1, 0, "beta", 1), + (2, 2, 0, "alpha", 0), + CO_NESTED) + +generators = _Feature((2, 2, 0, "alpha", 1), + (2, 3, 0, "final", 0), + CO_GENERATOR_ALLOWED) + +division = _Feature((2, 2, 0, "alpha", 2), + (3, 0, 0, "alpha", 0), + CO_FUTURE_DIVISION) + +absolute_import = _Feature((2, 5, 0, "alpha", 1), + (3, 0, 0, "alpha", 0), + CO_FUTURE_ABSOLUTE_IMPORT) + +with_statement = _Feature((2, 5, 0, "alpha", 1), + (2, 6, 0, "alpha", 0), + CO_FUTURE_WITH_STATEMENT) + +print_function = _Feature((2, 6, 0, "alpha", 2), + (3, 0, 0, "alpha", 0), + CO_FUTURE_PRINT_FUNCTION) + +unicode_literals = _Feature((2, 6, 0, "alpha", 2), + (3, 0, 0, "alpha", 0), + CO_FUTURE_UNICODE_LITERALS) + +barry_as_FLUFL = _Feature((3, 1, 0, "alpha", 2), + (4, 0, 0, "alpha", 0), + CO_FUTURE_BARRY_AS_BDFL) + +generator_stop = _Feature((3, 5, 0, "beta", 1), + (3, 7, 0, "alpha", 0), + CO_FUTURE_GENERATOR_STOP) + +annotations = _Feature((3, 7, 0, "beta", 1), + (3, 11, 0, "alpha", 0), + CO_FUTURE_ANNOTATIONS) diff --git a/shared/package-files/79/7928926549663d7a953ca92733b19c12fefa043823d08251bb71577195e99aa7/blob b/shared/package-files/79/7928926549663d7a953ca92733b19c12fefa043823d08251bb71577195e99aa7/blob new file mode 100644 index 0000000000000000000000000000000000000000..0420511a7d722374fa5f3043c3557c0bb2bb3b09 --- /dev/null +++ b/shared/package-files/79/7928926549663d7a953ca92733b19c12fefa043823d08251bb71577195e99aa7/blob @@ -0,0 +1,185 @@ +import sys +from typing import Any +from collections.abc import Callable + +import numpy as np +import numpy.typing as npt + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +vectorized_func: np.vectorize + +f8: np.float64 +AR_LIKE_f8: list[float] + +AR_i8: npt.NDArray[np.int64] +AR_f8: npt.NDArray[np.float64] +AR_c16: npt.NDArray[np.complex128] +AR_m: npt.NDArray[np.timedelta64] +AR_M: npt.NDArray[np.datetime64] +AR_O: npt.NDArray[np.object_] +AR_b: npt.NDArray[np.bool_] +AR_U: npt.NDArray[np.str_] +CHAR_AR_U: np.chararray[Any, np.dtype[np.str_]] + +def func(*args: Any, **kwargs: Any) -> Any: ... + +assert_type(vectorized_func.pyfunc, Callable[..., Any]) +assert_type(vectorized_func.cache, bool) +assert_type(vectorized_func.signature, None | str) +assert_type(vectorized_func.otypes, None | str) +assert_type(vectorized_func.excluded, set[int | str]) +assert_type(vectorized_func.__doc__, None | str) +assert_type(vectorized_func([1]), Any) +assert_type(np.vectorize(int), np.vectorize) +assert_type( + np.vectorize(int, otypes="i", doc="doc", excluded=(), cache=True, signature=None), + np.vectorize, +) + +assert_type(np.add_newdoc("__main__", "blabla", doc="test doc"), None) +assert_type(np.add_newdoc("__main__", "blabla", doc=("meth", "test doc")), None) +assert_type(np.add_newdoc("__main__", "blabla", doc=[("meth", "test doc")]), None) + +assert_type(np.rot90(AR_f8, k=2), npt.NDArray[np.float64]) +assert_type(np.rot90(AR_LIKE_f8, axes=(0, 1)), npt.NDArray[Any]) + +assert_type(np.flip(f8), np.float64) +assert_type(np.flip(1.0), Any) +assert_type(np.flip(AR_f8, axis=(0, 1)), npt.NDArray[np.float64]) +assert_type(np.flip(AR_LIKE_f8, axis=0), npt.NDArray[Any]) + +assert_type(np.iterable(1), bool) +assert_type(np.iterable([1]), bool) + +assert_type(np.average(AR_f8), np.floating[Any]) +assert_type(np.average(AR_f8, weights=AR_c16), np.complexfloating[Any, Any]) +assert_type(np.average(AR_O), Any) +assert_type(np.average(AR_f8, returned=True), tuple[np.floating[Any], np.floating[Any]]) +assert_type(np.average(AR_f8, weights=AR_c16, returned=True), tuple[np.complexfloating[Any, Any], np.complexfloating[Any, Any]]) +assert_type(np.average(AR_O, returned=True), tuple[Any, Any]) +assert_type(np.average(AR_f8, axis=0), Any) +assert_type(np.average(AR_f8, axis=0, returned=True), tuple[Any, Any]) + +assert_type(np.asarray_chkfinite(AR_f8), npt.NDArray[np.float64]) +assert_type(np.asarray_chkfinite(AR_LIKE_f8), npt.NDArray[Any]) +assert_type(np.asarray_chkfinite(AR_f8, dtype=np.float64), npt.NDArray[np.float64]) +assert_type(np.asarray_chkfinite(AR_f8, dtype=float), npt.NDArray[Any]) + +assert_type(np.piecewise(AR_f8, AR_b, [func]), npt.NDArray[np.float64]) +assert_type(np.piecewise(AR_LIKE_f8, AR_b, [func]), npt.NDArray[Any]) + +assert_type(np.select([AR_f8], [AR_f8]), npt.NDArray[Any]) + +assert_type(np.copy(AR_LIKE_f8), npt.NDArray[Any]) +assert_type(np.copy(AR_U), npt.NDArray[np.str_]) +assert_type(np.copy(CHAR_AR_U), np.ndarray[Any, Any]) +assert_type(np.copy(CHAR_AR_U, "K", subok=True), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.copy(CHAR_AR_U, subok=True), np.chararray[Any, np.dtype[np.str_]]) + +assert_type(np.gradient(AR_f8, axis=None), Any) +assert_type(np.gradient(AR_LIKE_f8, edge_order=2), Any) + +assert_type(np.diff("bob", n=0), str) +assert_type(np.diff(AR_f8, axis=0), npt.NDArray[Any]) +assert_type(np.diff(AR_LIKE_f8, prepend=1.5), npt.NDArray[Any]) + +assert_type(np.angle(f8), np.floating[Any]) +assert_type(np.angle(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.angle(AR_c16, deg=True), npt.NDArray[np.floating[Any]]) +assert_type(np.angle(AR_O), npt.NDArray[np.object_]) + +assert_type(np.unwrap(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.unwrap(AR_O), npt.NDArray[np.object_]) + +assert_type(np.sort_complex(AR_f8), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.trim_zeros(AR_f8), npt.NDArray[np.float64]) +assert_type(np.trim_zeros(AR_LIKE_f8), list[float]) + +assert_type(np.extract(AR_i8, AR_f8), npt.NDArray[np.float64]) +assert_type(np.extract(AR_i8, AR_LIKE_f8), npt.NDArray[Any]) + +assert_type(np.place(AR_f8, mask=AR_i8, vals=5.0), None) + +assert_type(np.disp(1, linefeed=True), None) +with open("test", "w") as f: + assert_type(np.disp("message", device=f), None) + +assert_type(np.cov(AR_f8, bias=True), npt.NDArray[np.floating[Any]]) +assert_type(np.cov(AR_f8, AR_c16, ddof=1), npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(np.cov(AR_f8, aweights=AR_f8, dtype=np.float32), npt.NDArray[np.float32]) +assert_type(np.cov(AR_f8, fweights=AR_f8, dtype=float), npt.NDArray[Any]) + +assert_type(np.corrcoef(AR_f8, rowvar=True), npt.NDArray[np.floating[Any]]) +assert_type(np.corrcoef(AR_f8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(np.corrcoef(AR_f8, dtype=np.float32), npt.NDArray[np.float32]) +assert_type(np.corrcoef(AR_f8, dtype=float), npt.NDArray[Any]) + +assert_type(np.blackman(5), npt.NDArray[np.floating[Any]]) +assert_type(np.bartlett(6), npt.NDArray[np.floating[Any]]) +assert_type(np.hanning(4.5), npt.NDArray[np.floating[Any]]) +assert_type(np.hamming(0), npt.NDArray[np.floating[Any]]) +assert_type(np.i0(AR_i8), npt.NDArray[np.floating[Any]]) +assert_type(np.kaiser(4, 5.9), npt.NDArray[np.floating[Any]]) + +assert_type(np.sinc(1.0), np.floating[Any]) +assert_type(np.sinc(1j), np.complexfloating[Any, Any]) +assert_type(np.sinc(AR_f8), npt.NDArray[np.floating[Any]]) +assert_type(np.sinc(AR_c16), npt.NDArray[np.complexfloating[Any, Any]]) + +assert_type(np.median(AR_f8, keepdims=False), np.floating[Any]) +assert_type(np.median(AR_c16, overwrite_input=True), np.complexfloating[Any, Any]) +assert_type(np.median(AR_m), np.timedelta64) +assert_type(np.median(AR_O), Any) +assert_type(np.median(AR_f8, keepdims=True), Any) +assert_type(np.median(AR_c16, axis=0), Any) +assert_type(np.median(AR_LIKE_f8, out=AR_c16), npt.NDArray[np.complex128]) + +assert_type(np.add_newdoc_ufunc(np.add, "docstring"), None) + +assert_type(np.percentile(AR_f8, 50), np.floating[Any]) +assert_type(np.percentile(AR_c16, 50), np.complexfloating[Any, Any]) +assert_type(np.percentile(AR_m, 50), np.timedelta64) +assert_type(np.percentile(AR_M, 50, overwrite_input=True), np.datetime64) +assert_type(np.percentile(AR_O, 50), Any) +assert_type(np.percentile(AR_f8, [50]), npt.NDArray[np.floating[Any]]) +assert_type(np.percentile(AR_c16, [50]), npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(np.percentile(AR_m, [50]), npt.NDArray[np.timedelta64]) +assert_type(np.percentile(AR_M, [50], method="nearest"), npt.NDArray[np.datetime64]) +assert_type(np.percentile(AR_O, [50]), npt.NDArray[np.object_]) +assert_type(np.percentile(AR_f8, [50], keepdims=True), Any) +assert_type(np.percentile(AR_f8, [50], axis=[1]), Any) +assert_type(np.percentile(AR_f8, [50], out=AR_c16), npt.NDArray[np.complex128]) + +assert_type(np.quantile(AR_f8, 0.5), np.floating[Any]) +assert_type(np.quantile(AR_c16, 0.5), np.complexfloating[Any, Any]) +assert_type(np.quantile(AR_m, 0.5), np.timedelta64) +assert_type(np.quantile(AR_M, 0.5, overwrite_input=True), np.datetime64) +assert_type(np.quantile(AR_O, 0.5), Any) +assert_type(np.quantile(AR_f8, [0.5]), npt.NDArray[np.floating[Any]]) +assert_type(np.quantile(AR_c16, [0.5]), npt.NDArray[np.complexfloating[Any, Any]]) +assert_type(np.quantile(AR_m, [0.5]), npt.NDArray[np.timedelta64]) +assert_type(np.quantile(AR_M, [0.5], method="nearest"), npt.NDArray[np.datetime64]) +assert_type(np.quantile(AR_O, [0.5]), npt.NDArray[np.object_]) +assert_type(np.quantile(AR_f8, [0.5], keepdims=True), Any) +assert_type(np.quantile(AR_f8, [0.5], axis=[1]), Any) +assert_type(np.quantile(AR_f8, [0.5], out=AR_c16), npt.NDArray[np.complex128]) + +assert_type(np.meshgrid(AR_f8, AR_i8, copy=False), list[npt.NDArray[Any]]) +assert_type(np.meshgrid(AR_f8, AR_i8, AR_c16, indexing="ij"), list[npt.NDArray[Any]]) + +assert_type(np.delete(AR_f8, np.s_[:5]), npt.NDArray[np.float64]) +assert_type(np.delete(AR_LIKE_f8, [0, 4, 9], axis=0), npt.NDArray[Any]) + +assert_type(np.insert(AR_f8, np.s_[:5], 5), npt.NDArray[np.float64]) +assert_type(np.insert(AR_LIKE_f8, [0, 4, 9], [0.5, 9.2, 7], axis=0), npt.NDArray[Any]) + +assert_type(np.append(AR_f8, 5), npt.NDArray[Any]) +assert_type(np.append(AR_LIKE_f8, 1j, axis=0), npt.NDArray[Any]) + +assert_type(np.digitize(4.5, [1]), np.intp) +assert_type(np.digitize(AR_f8, [1, 2, 3]), npt.NDArray[np.intp]) diff --git a/shared/package-files/79/7929ac8bcb9093a308e7dd4982d4aed9e948bac6f4f1b992652d21f60c5befa2/blob b/shared/package-files/79/7929ac8bcb9093a308e7dd4982d4aed9e948bac6f4f1b992652d21f60c5befa2/blob new file mode 100644 index 0000000000000000000000000000000000000000..7aef2477d1331bcefc7e5dfdacd415b27ffcd3c8 --- /dev/null +++ b/shared/package-files/79/7929ac8bcb9093a308e7dd4982d4aed9e948bac6f4f1b992652d21f60c5befa2/blob @@ -0,0 +1,421 @@ +import itertools + +import pytest + +import networkx as nx +from networkx.algorithms import flow +from networkx.algorithms.connectivity import ( + local_edge_connectivity, + local_node_connectivity, +) + +flow_funcs = [ + flow.boykov_kolmogorov, + flow.dinitz, + flow.edmonds_karp, + flow.preflow_push, + flow.shortest_augmenting_path, +] + + +# helper functions for tests + + +def _generate_no_biconnected(max_attempts=50): + attempts = 0 + while True: + G = nx.fast_gnp_random_graph(100, 0.0575, seed=42) + if nx.is_connected(G) and not nx.is_biconnected(G): + attempts = 0 + yield G + else: + if attempts >= max_attempts: + msg = f"Tried {max_attempts} times: no suitable Graph." + raise Exception(msg) + else: + attempts += 1 + + +def test_average_connectivity(): + # figure 1 from: + # Beineke, L., O. Oellermann, and R. Pippert (2002). The average + # connectivity of a graph. Discrete mathematics 252(1-3), 31-45 + # http://www.sciencedirect.com/science/article/pii/S0012365X01001807 + G1 = nx.path_graph(3) + G1.add_edges_from([(1, 3), (1, 4)]) + G2 = nx.path_graph(3) + G2.add_edges_from([(1, 3), (1, 4), (0, 3), (0, 4), (3, 4)]) + G3 = nx.Graph() + for flow_func in flow_funcs: + kwargs = {"flow_func": flow_func} + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert nx.average_node_connectivity(G1, **kwargs) == 1, errmsg + assert nx.average_node_connectivity(G2, **kwargs) == 2.2, errmsg + assert nx.average_node_connectivity(G3, **kwargs) == 0, errmsg + + +def test_average_connectivity_directed(): + G = nx.DiGraph([(1, 3), (1, 4), (1, 5)]) + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert nx.average_node_connectivity(G) == 0.25, errmsg + + +def test_articulation_points(): + Ggen = _generate_no_biconnected() + for flow_func in flow_funcs: + for i in range(3): + G = next(Ggen) + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert nx.node_connectivity(G, flow_func=flow_func) == 1, errmsg + + +def test_brandes_erlebach(): + # Figure 1 chapter 7: Connectivity + # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf + G = nx.Graph() + G.add_edges_from( + [ + (1, 2), + (1, 3), + (1, 4), + (1, 5), + (2, 3), + (2, 6), + (3, 4), + (3, 6), + (4, 6), + (4, 7), + (5, 7), + (6, 8), + (6, 9), + (7, 8), + (7, 10), + (8, 11), + (9, 10), + (9, 11), + (10, 11), + ] + ) + for flow_func in flow_funcs: + kwargs = {"flow_func": flow_func} + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 3 == local_edge_connectivity(G, 1, 11, **kwargs), errmsg + assert 3 == nx.edge_connectivity(G, 1, 11, **kwargs), errmsg + assert 2 == local_node_connectivity(G, 1, 11, **kwargs), errmsg + assert 2 == nx.node_connectivity(G, 1, 11, **kwargs), errmsg + assert 2 == nx.edge_connectivity(G, **kwargs), errmsg + assert 2 == nx.node_connectivity(G, **kwargs), errmsg + if flow_func is flow.preflow_push: + assert 3 == nx.edge_connectivity(G, 1, 11, cutoff=2, **kwargs), errmsg + else: + assert 2 == nx.edge_connectivity(G, 1, 11, cutoff=2, **kwargs), errmsg + + +def test_white_harary_1(): + # Figure 1b white and harary (2001) + # https://doi.org/10.1111/0081-1750.00098 + # A graph with high adhesion (edge connectivity) and low cohesion + # (vertex connectivity) + G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) + G.remove_node(7) + for i in range(4, 7): + G.add_edge(0, i) + G = nx.disjoint_union(G, nx.complete_graph(4)) + G.remove_node(G.order() - 1) + for i in range(7, 10): + G.add_edge(0, i) + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 1 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 3 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_white_harary_2(): + # Figure 8 white and harary (2001) + # https://doi.org/10.1111/0081-1750.00098 + G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) + G.add_edge(0, 4) + # kappa <= lambda <= delta + assert 3 == min(nx.core_number(G).values()) + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 1 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 1 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_complete_graphs(): + for n in range(5, 20, 5): + for flow_func in flow_funcs: + G = nx.complete_graph(n) + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert n - 1 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert n - 1 == nx.node_connectivity( + G.to_directed(), flow_func=flow_func + ), errmsg + assert n - 1 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + assert n - 1 == nx.edge_connectivity( + G.to_directed(), flow_func=flow_func + ), errmsg + + +def test_empty_graphs(): + for k in range(5, 25, 5): + G = nx.empty_graph(k) + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 0 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 0 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_petersen(): + G = nx.petersen_graph() + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 3 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 3 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_tutte(): + G = nx.tutte_graph() + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 3 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 3 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_dodecahedral(): + G = nx.dodecahedral_graph() + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 3 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 3 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_octahedral(): + G = nx.octahedral_graph() + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 4 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 4 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_icosahedral(): + G = nx.icosahedral_graph() + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 5 == nx.node_connectivity(G, flow_func=flow_func), errmsg + assert 5 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + + +def test_missing_source(): + G = nx.path_graph(4) + for flow_func in flow_funcs: + pytest.raises( + nx.NetworkXError, nx.node_connectivity, G, 10, 1, flow_func=flow_func + ) + + +def test_missing_target(): + G = nx.path_graph(4) + for flow_func in flow_funcs: + pytest.raises( + nx.NetworkXError, nx.node_connectivity, G, 1, 10, flow_func=flow_func + ) + + +def test_edge_missing_source(): + G = nx.path_graph(4) + for flow_func in flow_funcs: + pytest.raises( + nx.NetworkXError, nx.edge_connectivity, G, 10, 1, flow_func=flow_func + ) + + +def test_edge_missing_target(): + G = nx.path_graph(4) + for flow_func in flow_funcs: + pytest.raises( + nx.NetworkXError, nx.edge_connectivity, G, 1, 10, flow_func=flow_func + ) + + +def test_not_weakly_connected(): + G = nx.DiGraph() + nx.add_path(G, [1, 2, 3]) + nx.add_path(G, [4, 5]) + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert nx.node_connectivity(G) == 0, errmsg + assert nx.edge_connectivity(G) == 0, errmsg + + +def test_not_connected(): + G = nx.Graph() + nx.add_path(G, [1, 2, 3]) + nx.add_path(G, [4, 5]) + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert nx.node_connectivity(G) == 0, errmsg + assert nx.edge_connectivity(G) == 0, errmsg + + +def test_directed_edge_connectivity(): + G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction + D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges + for flow_func in flow_funcs: + errmsg = f"Assertion failed in function: {flow_func.__name__}" + assert 1 == nx.edge_connectivity(G, flow_func=flow_func), errmsg + assert 1 == local_edge_connectivity(G, 1, 4, flow_func=flow_func), errmsg + assert 1 == nx.edge_connectivity(G, 1, 4, flow_func=flow_func), errmsg + assert 2 == nx.edge_connectivity(D, flow_func=flow_func), errmsg + assert 2 == local_edge_connectivity(D, 1, 4, flow_func=flow_func), errmsg + assert 2 == nx.edge_connectivity(D, 1, 4, flow_func=flow_func), errmsg + + +def test_cutoff(): + G = nx.complete_graph(5) + for local_func in [local_edge_connectivity, local_node_connectivity]: + for flow_func in flow_funcs: + if flow_func is flow.preflow_push: + # cutoff is not supported by preflow_push + continue + for cutoff in [3, 2, 1]: + result = local_func(G, 0, 4, flow_func=flow_func, cutoff=cutoff) + assert cutoff == result, f"cutoff error in {flow_func.__name__}" + + +def test_invalid_auxiliary(): + G = nx.complete_graph(5) + pytest.raises(nx.NetworkXError, local_node_connectivity, G, 0, 3, auxiliary=G) + + +def test_interface_only_source(): + G = nx.complete_graph(5) + for interface_func in [nx.node_connectivity, nx.edge_connectivity]: + pytest.raises(nx.NetworkXError, interface_func, G, s=0) + + +def test_interface_only_target(): + G = nx.complete_graph(5) + for interface_func in [nx.node_connectivity, nx.edge_connectivity]: + pytest.raises(nx.NetworkXError, interface_func, G, t=3) + + +def test_edge_connectivity_flow_vs_stoer_wagner(): + graph_funcs = [nx.icosahedral_graph, nx.octahedral_graph, nx.dodecahedral_graph] + for graph_func in graph_funcs: + G = graph_func() + assert nx.stoer_wagner(G)[0] == nx.edge_connectivity(G) + + +class TestAllPairsNodeConnectivity: + @classmethod + def setup_class(cls): + cls.path = nx.path_graph(7) + cls.directed_path = nx.path_graph(7, create_using=nx.DiGraph()) + cls.cycle = nx.cycle_graph(7) + cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) + cls.gnp = nx.gnp_random_graph(30, 0.1, seed=42) + cls.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True, seed=42) + cls.K20 = nx.complete_graph(20) + cls.K10 = nx.complete_graph(10) + cls.K5 = nx.complete_graph(5) + cls.G_list = [ + cls.path, + cls.directed_path, + cls.cycle, + cls.directed_cycle, + cls.gnp, + cls.directed_gnp, + cls.K10, + cls.K5, + cls.K20, + ] + + def test_cycles(self): + K_undir = nx.all_pairs_node_connectivity(self.cycle) + for source in K_undir: + for target, k in K_undir[source].items(): + assert k == 2 + K_dir = nx.all_pairs_node_connectivity(self.directed_cycle) + for source in K_dir: + for target, k in K_dir[source].items(): + assert k == 1 + + def test_complete(self): + for G in [self.K10, self.K5, self.K20]: + K = nx.all_pairs_node_connectivity(G) + for source in K: + for target, k in K[source].items(): + assert k == len(G) - 1 + + def test_paths(self): + K_undir = nx.all_pairs_node_connectivity(self.path) + for source in K_undir: + for target, k in K_undir[source].items(): + assert k == 1 + K_dir = nx.all_pairs_node_connectivity(self.directed_path) + for source in K_dir: + for target, k in K_dir[source].items(): + if source < target: + assert k == 1 + else: + assert k == 0 + + def test_all_pairs_connectivity_nbunch(self): + G = nx.complete_graph(5) + nbunch = [0, 2, 3] + C = nx.all_pairs_node_connectivity(G, nbunch=nbunch) + assert len(C) == len(nbunch) + + def test_all_pairs_connectivity_icosahedral(self): + G = nx.icosahedral_graph() + C = nx.all_pairs_node_connectivity(G) + assert all(5 == C[u][v] for u, v in itertools.combinations(G, 2)) + + def test_all_pairs_connectivity(self): + G = nx.Graph() + nodes = [0, 1, 2, 3] + nx.add_path(G, nodes) + A = {n: {} for n in G} + for u, v in itertools.combinations(nodes, 2): + A[u][v] = A[v][u] = nx.node_connectivity(G, u, v) + C = nx.all_pairs_node_connectivity(G) + assert sorted((k, sorted(v)) for k, v in A.items()) == sorted( + (k, sorted(v)) for k, v in C.items() + ) + + def test_all_pairs_connectivity_directed(self): + G = nx.DiGraph() + nodes = [0, 1, 2, 3] + nx.add_path(G, nodes) + A = {n: {} for n in G} + for u, v in itertools.permutations(nodes, 2): + A[u][v] = nx.node_connectivity(G, u, v) + C = nx.all_pairs_node_connectivity(G) + assert sorted((k, sorted(v)) for k, v in A.items()) == sorted( + (k, sorted(v)) for k, v in C.items() + ) + + def test_all_pairs_connectivity_nbunch_combinations(self): + G = nx.complete_graph(5) + nbunch = [0, 2, 3] + A = {n: {} for n in nbunch} + for u, v in itertools.combinations(nbunch, 2): + A[u][v] = A[v][u] = nx.node_connectivity(G, u, v) + C = nx.all_pairs_node_connectivity(G, nbunch=nbunch) + assert sorted((k, sorted(v)) for k, v in A.items()) == sorted( + (k, sorted(v)) for k, v in C.items() + ) + + def test_all_pairs_connectivity_nbunch_iter(self): + G = nx.complete_graph(5) + nbunch = [0, 2, 3] + A = {n: {} for n in nbunch} + for u, v in itertools.combinations(nbunch, 2): + A[u][v] = A[v][u] = nx.node_connectivity(G, u, v) + C = nx.all_pairs_node_connectivity(G, nbunch=iter(nbunch)) + assert sorted((k, sorted(v)) for k, v in A.items()) == sorted( + (k, sorted(v)) for k, v in C.items() + ) diff --git a/shared/package-files/79/792a8948fd5d79a77bad54d65b92f4a8bbfa2d54211ecb93a8884066f56427e8/blob b/shared/package-files/79/792a8948fd5d79a77bad54d65b92f4a8bbfa2d54211ecb93a8884066f56427e8/blob new file mode 100644 index 0000000000000000000000000000000000000000..0127ba71fc4bc4c6d019fca645ae95e1b6bcbec5 --- /dev/null +++ b/shared/package-files/79/792a8948fd5d79a77bad54d65b92f4a8bbfa2d54211ecb93a8884066f56427e8/blob @@ -0,0 +1,100 @@ +"""Tests for distutils.command.config.""" +import unittest +import os +import sys +import sysconfig +from test.support import run_unittest, missing_compiler_executable + +from distutils.command.config import dump_file, config +from distutils.tests import support +from distutils import log + +class ConfigTestCase(support.LoggingSilencer, + support.TempdirManager, + unittest.TestCase): + + def _info(self, msg, *args): + for line in msg.splitlines(): + self._logs.append(line) + + def setUp(self): + super(ConfigTestCase, self).setUp() + self._logs = [] + self.old_log = log.info + log.info = self._info + self.old_config_vars = dict(sysconfig._CONFIG_VARS) + + def tearDown(self): + log.info = self.old_log + sysconfig._CONFIG_VARS.clear() + sysconfig._CONFIG_VARS.update(self.old_config_vars) + super(ConfigTestCase, self).tearDown() + + def test_dump_file(self): + this_file = os.path.splitext(__file__)[0] + '.py' + f = open(this_file) + try: + numlines = len(f.readlines()) + finally: + f.close() + + dump_file(this_file, 'I am the header') + self.assertEqual(len(self._logs), numlines+1) + + @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") + def test_search_cpp(self): + cmd = missing_compiler_executable(['preprocessor']) + if cmd is not None: + self.skipTest('The %r command is not found' % cmd) + pkg_dir, dist = self.create_dist() + cmd = config(dist) + cmd._check_compiler() + compiler = cmd.compiler + if sys.platform[:3] == "aix" and "xlc" in compiler.preprocessor[0].lower(): + self.skipTest('xlc: The -E option overrides the -P, -o, and -qsyntaxonly options') + + # simple pattern searches + match = cmd.search_cpp(pattern='xxx', body='/* xxx */') + self.assertEqual(match, 0) + + match = cmd.search_cpp(pattern='_configtest', body='/* xxx */') + self.assertEqual(match, 1) + + def test_finalize_options(self): + # finalize_options does a bit of transformation + # on options + pkg_dir, dist = self.create_dist() + cmd = config(dist) + cmd.include_dirs = 'one%stwo' % os.pathsep + cmd.libraries = 'one' + cmd.library_dirs = 'three%sfour' % os.pathsep + cmd.ensure_finalized() + + self.assertEqual(cmd.include_dirs, ['one', 'two']) + self.assertEqual(cmd.libraries, ['one']) + self.assertEqual(cmd.library_dirs, ['three', 'four']) + + def test_clean(self): + # _clean removes files + tmp_dir = self.mkdtemp() + f1 = os.path.join(tmp_dir, 'one') + f2 = os.path.join(tmp_dir, 'two') + + self.write_file(f1, 'xxx') + self.write_file(f2, 'xxx') + + for f in (f1, f2): + self.assertTrue(os.path.exists(f)) + + pkg_dir, dist = self.create_dist() + cmd = config(dist) + cmd._clean(f1, f2) + + for f in (f1, f2): + self.assertFalse(os.path.exists(f)) + +def test_suite(): + return unittest.makeSuite(ConfigTestCase) + +if __name__ == "__main__": + run_unittest(test_suite()) diff --git a/shared/package-files/79/792db2df86531b4ddd34982d549daa497416676d8f1c858161e0bc71bbc8d722/blob b/shared/package-files/79/792db2df86531b4ddd34982d549daa497416676d8f1c858161e0bc71bbc8d722/blob new file mode 100644 index 0000000000000000000000000000000000000000..3e1b01356a74b8e4f16d66811060be698cfed199 --- /dev/null +++ b/shared/package-files/79/792db2df86531b4ddd34982d549daa497416676d8f1c858161e0bc71bbc8d722/blob @@ -0,0 +1,427 @@ +from functools import partial +from typing import Any, List, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torchvision.models import shufflenetv2 + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..shufflenetv2 import ( + ShuffleNet_V2_X0_5_Weights, + ShuffleNet_V2_X1_0_Weights, + ShuffleNet_V2_X1_5_Weights, + ShuffleNet_V2_X2_0_Weights, +) +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableShuffleNetV2", + "ShuffleNet_V2_X0_5_QuantizedWeights", + "ShuffleNet_V2_X1_0_QuantizedWeights", + "ShuffleNet_V2_X1_5_QuantizedWeights", + "ShuffleNet_V2_X2_0_QuantizedWeights", + "shufflenet_v2_x0_5", + "shufflenet_v2_x1_0", + "shufflenet_v2_x1_5", + "shufflenet_v2_x2_0", +] + + +class QuantizableInvertedResidual(shufflenetv2.InvertedResidual): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.cat = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.stride == 1: + x1, x2 = x.chunk(2, dim=1) + out = self.cat.cat([x1, self.branch2(x2)], dim=1) + else: + out = self.cat.cat([self.branch1(x), self.branch2(x)], dim=1) + + out = shufflenetv2.channel_shuffle(out, 2) + + return out + + +class QuantizableShuffleNetV2(shufflenetv2.ShuffleNetV2): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, inverted_residual=QuantizableInvertedResidual, **kwargs) # type: ignore[misc] + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in shufflenetv2 model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. + + .. note:: + Note that this operation does not change numerics + and the model after modification is in floating point + """ + for name, m in self._modules.items(): + if name in ["conv1", "conv5"] and m is not None: + _fuse_modules(m, [["0", "1", "2"]], is_qat, inplace=True) + for m in self.modules(): + if type(m) is QuantizableInvertedResidual: + if len(m.branch1._modules.items()) > 0: + _fuse_modules(m.branch1, [["0", "1"], ["2", "3", "4"]], is_qat, inplace=True) + _fuse_modules( + m.branch2, + [["0", "1", "2"], ["3", "4"], ["5", "6", "7"]], + is_qat, + inplace=True, + ) + + +def _shufflenetv2( + stages_repeats: List[int], + stages_out_channels: List[int], + *, + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableShuffleNetV2(stages_repeats, stages_out_channels, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, +} + + +class ShuffleNet_V2_X0_5_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x0.5_fbgemm-00845098.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 1366792, + "unquantized": ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 57.972, + "acc@5": 79.780, + } + }, + "_ops": 0.04, + "_file_size": 1.501, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X1_0_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-1e62bb32.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2278604, + "unquantized": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 68.360, + "acc@5": 87.582, + } + }, + "_ops": 0.145, + "_file_size": 2.334, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X1_5_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_5_fbgemm-d7401f05.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 3503624, + "unquantized": ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.052, + "acc@5": 90.700, + } + }, + "_ops": 0.296, + "_file_size": 3.672, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X2_0_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x2_0_fbgemm-5cac526c.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 7393996, + "unquantized": ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.354, + "acc@5": 92.488, + } + }, + "_ops": 0.583, + "_file_size": 7.467, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_shufflenet_v2_x0_5") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1, + ) +) +def shufflenet_v2_x0_5( + *, + weights: Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights, ShuffleNet_V2_X0_5_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 0.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X0_5_QuantizedWeights if quantize else ShuffleNet_V2_X0_5_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 48, 96, 192, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x1_0") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1, + ) +) +def shufflenet_v2_x1_0( + *, + weights: Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights, ShuffleNet_V2_X1_0_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 1.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X1_0_QuantizedWeights if quantize else ShuffleNet_V2_X1_0_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 116, 232, 464, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x1_5") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ShuffleNet_V2_X1_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1, + ) +) +def shufflenet_v2_x1_5( + *, + weights: Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights, ShuffleNet_V2_X1_5_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 1.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X1_5_QuantizedWeights if quantize else ShuffleNet_V2_X1_5_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 176, 352, 704, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x2_0") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ShuffleNet_V2_X2_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1, + ) +) +def shufflenet_v2_x2_0( + *, + weights: Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights, ShuffleNet_V2_X2_0_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 2.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X2_0_QuantizedWeights if quantize else ShuffleNet_V2_X2_0_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 244, 488, 976, 2048], weights=weights, progress=progress, quantize=quantize, **kwargs + ) diff --git a/shared/package-files/79/792ed3f25486f3ae268df944dba84311b8f6a30696a34a3ad36f069bd83898a5/blob b/shared/package-files/79/792ed3f25486f3ae268df944dba84311b8f6a30696a34a3ad36f069bd83898a5/blob new file mode 100644 index 0000000000000000000000000000000000000000..9cfb430245257391718d6ec22bfa858655d965fd --- /dev/null +++ b/shared/package-files/79/792ed3f25486f3ae268df944dba84311b8f6a30696a34a3ad36f069bd83898a5/blob @@ -0,0 +1,421 @@ + +import hashlib +import torch +import torch.fx +from typing import Any, Dict, Optional, TYPE_CHECKING +from torch.fx.node import _get_qualified_name, _format_arg +from torch.fx.graph import _parse_stack_trace +from torch.fx.passes.shape_prop import TensorMetadata +from torch.fx._compatibility import compatibility +from itertools import chain + +__all__ = ['FxGraphDrawer'] +try: + import pydot + HAS_PYDOT = True +except ImportError: + HAS_PYDOT = False + +_COLOR_MAP = { + "placeholder": '"AliceBlue"', + "call_module": "LemonChiffon1", + "get_param": "Yellow2", + "get_attr": "LightGrey", + "output": "PowderBlue", +} + +_HASH_COLOR_MAP = [ + "CadetBlue1", + "Coral", + "DarkOliveGreen1", + "DarkSeaGreen1", + "GhostWhite", + "Khaki1", + "LavenderBlush1", + "LightSkyBlue", + "MistyRose1", + "MistyRose2", + "PaleTurquoise2", + "PeachPuff1", + "Salmon", + "Thistle1", + "Thistle3", + "Wheat1", +] + +_WEIGHT_TEMPLATE = { + "fillcolor": "Salmon", + "style": '"filled,rounded"', + "fontcolor": "#000000", +} + +if HAS_PYDOT: + @compatibility(is_backward_compatible=False) + class FxGraphDrawer: + """ + Visualize a torch.fx.Graph with graphviz + Basic usage: + g = FxGraphDrawer(symbolic_traced, "resnet18") + g.get_dot_graph().write_svg("a.svg") + """ + + def __init__( + self, + graph_module: torch.fx.GraphModule, + name: str, + ignore_getattr: bool = False, + ignore_parameters_and_buffers: bool = False, + skip_node_names_in_args: bool = True, + parse_stack_trace: bool = False, + dot_graph_shape: Optional[str] = None, + ): + self._name = name + self.dot_graph_shape = ( + dot_graph_shape if dot_graph_shape is not None else "record" + ) + _WEIGHT_TEMPLATE["shape"] = self.dot_graph_shape + + self._dot_graphs = { + name: self._to_dot( + graph_module, name, ignore_getattr, ignore_parameters_and_buffers, skip_node_names_in_args, parse_stack_trace + ) + } + + for node in graph_module.graph.nodes: + if node.op != "call_module": + continue + + leaf_node = self._get_leaf_node(graph_module, node) + + if not isinstance(leaf_node, torch.fx.GraphModule): + continue + + + self._dot_graphs[f"{name}_{node.target}"] = self._to_dot( + leaf_node, + f"{name}_{node.target}", + ignore_getattr, + ignore_parameters_and_buffers, + skip_node_names_in_args, + parse_stack_trace, + ) + + def get_dot_graph(self, submod_name=None) -> pydot.Dot: + """ + Visualize a torch.fx.Graph with graphviz + Example: + >>> # xdoctest: +REQUIRES(module:pydot) + >>> # define module + >>> class MyModule(torch.nn.Module): + >>> def __init__(self): + >>> super().__init__() + >>> self.linear = torch.nn.Linear(4, 5) + >>> def forward(self, x): + >>> return self.linear(x).clamp(min=0.0, max=1.0) + >>> module = MyModule() + >>> # trace the module + >>> symbolic_traced = torch.fx.symbolic_trace(module) + >>> # setup output file + >>> import ubelt as ub + >>> dpath = ub.Path.appdir('torch/tests/FxGraphDrawer').ensuredir() + >>> fpath = dpath / 'linear.svg' + >>> # draw the graph + >>> g = FxGraphDrawer(symbolic_traced, "linear") + >>> g.get_dot_graph().write_svg(fpath) + """ + if submod_name is None: + return self.get_main_dot_graph() + else: + return self.get_submod_dot_graph(submod_name) + + def get_main_dot_graph(self) -> pydot.Dot: + return self._dot_graphs[self._name] + + def get_submod_dot_graph(self, submod_name) -> pydot.Dot: + return self._dot_graphs[f"{self._name}_{submod_name}"] + + def get_all_dot_graphs(self) -> Dict[str, pydot.Dot]: + return self._dot_graphs + + def _get_node_style(self, node: torch.fx.Node) -> Dict[str, str]: + + template = { + "shape": self.dot_graph_shape, + "fillcolor": "#CAFFE3", + "style": '"filled,rounded"', + "fontcolor": "#000000", + } + if node.op in _COLOR_MAP: + template["fillcolor"] = _COLOR_MAP[node.op] + else: + # Use a random color for each node; based on its name so it's stable. + target_name = node._pretty_print_target(node.target) + target_hash = int(hashlib.md5(target_name.encode()).hexdigest()[:8], 16) + template["fillcolor"] = _HASH_COLOR_MAP[target_hash % len(_HASH_COLOR_MAP)] + return template + + def _get_leaf_node( + self, module: torch.nn.Module, node: torch.fx.Node + ) -> torch.nn.Module: + py_obj = module + assert isinstance(node.target, str) + atoms = node.target.split(".") + for atom in atoms: + if not hasattr(py_obj, atom): + raise RuntimeError( + str(py_obj) + " does not have attribute " + atom + "!" + ) + py_obj = getattr(py_obj, atom) + return py_obj + + def _typename(self, target: Any) -> str: + if isinstance(target, torch.nn.Module): + ret = torch.typename(target) + elif isinstance(target, str): + ret = target + else: + ret = _get_qualified_name(target) + + # Escape "{" and "}" to prevent dot files like: + # https://gist.github.com/SungMinCho/1a017aab662c75d805c5954d62c5aabc + # which triggers `Error: bad label format (...)` from dot + return ret.replace("{", r"\{").replace("}", r"\}") + + # shorten path to avoid drawing long boxes + # for full path = '/home/weif/pytorch/test.py' + # return short path = 'pytorch/test.py' + def _shorten_file_name( + self, + full_file_name: str, + truncate_to_last_n: int = 2, + ): + splits = full_file_name.split('/') + if len(splits) >= truncate_to_last_n: + return '/'.join(splits[-truncate_to_last_n:]) + return full_file_name + + + def _get_node_label( + self, + module: torch.fx.GraphModule, + node: torch.fx.Node, + skip_node_names_in_args: bool, + parse_stack_trace: bool, + ) -> str: + def _get_str_for_args_kwargs(arg): + if isinstance(arg, tuple): + prefix, suffix = r"|args=(\l", r",\n)\l" + arg_strs_list = [_format_arg(a, max_list_len=8) for a in arg] + elif isinstance(arg, dict): + prefix, suffix = r"|kwargs={\l", r",\n}\l" + arg_strs_list = [ + f"{k}: {_format_arg(v, max_list_len=8)}" + for k, v in arg.items() + ] + else: # Fall back to nothing in unexpected case. + return "" + + # Strip out node names if requested. + if skip_node_names_in_args: + arg_strs_list = [a for a in arg_strs_list if "%" not in a] + if len(arg_strs_list) == 0: + return "" + arg_strs = prefix + r",\n".join(arg_strs_list) + suffix + if len(arg_strs_list) == 1: + arg_strs = arg_strs.replace(r"\l", "").replace(r"\n", "") + return arg_strs.replace("{", r"\{").replace("}", r"\}") + + + label = "{" + f"name=%{node.name}|op_code={node.op}\n" + + if node.op == "call_module": + leaf_module = self._get_leaf_node(module, node) + label += r"\n" + self._typename(leaf_module) + r"\n|" + extra = "" + if hasattr(leaf_module, "__constants__"): + extra = r"\n".join( + [f"{c}: {getattr(leaf_module, c)}" for c in leaf_module.__constants__] # type: ignore[union-attr] + ) + label += extra + r"\n" + else: + label += f"|target={self._typename(node.target)}" + r"\n" + if len(node.args) > 0: + label += _get_str_for_args_kwargs(node.args) + if len(node.kwargs) > 0: + label += _get_str_for_args_kwargs(node.kwargs) + label += f"|num_users={len(node.users)}" + r"\n" + + tensor_meta = node.meta.get('tensor_meta') + label += self._tensor_meta_to_label(tensor_meta) + + # for original fx graph + # print buf=buf0, n_origin=6 + buf_meta = node.meta.get('buf_meta', None) + if buf_meta is not None: + label += f"|buf={buf_meta.name}" + r"\n" + label += f"|n_origin={buf_meta.n_origin}" + r"\n" + + # for original fx graph + # print file:lineno code + if parse_stack_trace and node.stack_trace is not None: + parsed_stack_trace = _parse_stack_trace(node.stack_trace) + fname = self._shorten_file_name(parsed_stack_trace.file) + label += f"|file={fname}:{parsed_stack_trace.lineno} {parsed_stack_trace.code}" + r"\n" + + + return label + "}" + + def _tensor_meta_to_label(self, tm) -> str: + if tm is None: + return "" + elif isinstance(tm, TensorMetadata): + return self._stringify_tensor_meta(tm) + elif isinstance(tm, list): + result = "" + for item in tm: + result += self._tensor_meta_to_label(item) + return result + elif isinstance(tm, dict): + result = "" + for v in tm.values(): + result += self._tensor_meta_to_label(v) + return result + elif isinstance(tm, tuple): + result = "" + for item in tm: + result += self._tensor_meta_to_label(item) + return result + else: + raise RuntimeError(f"Unsupported tensor meta type {type(tm)}") + + def _stringify_tensor_meta(self, tm: TensorMetadata) -> str: + result = "" + if not hasattr(tm, "dtype"): + print("tm", tm) + result += "|" + "dtype" + "=" + str(tm.dtype) + r"\n" + result += "|" + "shape" + "=" + str(tuple(tm.shape)) + r"\n" + result += "|" + "requires_grad" + "=" + str(tm.requires_grad) + r"\n" + result += "|" + "stride" + "=" + str(tm.stride) + r"\n" + if tm.is_quantized: + assert tm.qparams is not None + assert "qscheme" in tm.qparams + qscheme = tm.qparams["qscheme"] + if qscheme in { + torch.per_tensor_affine, + torch.per_tensor_symmetric, + }: + result += "|" + "q_scale" + "=" + str(tm.qparams["scale"]) + r"\n" + result += "|" + "q_zero_point" + "=" + str(tm.qparams["zero_point"]) + r"\n" + elif qscheme in { + torch.per_channel_affine, + torch.per_channel_symmetric, + torch.per_channel_affine_float_qparams, + }: + result += "|" + "q_per_channel_scale" + "=" + str(tm.qparams["scale"]) + r"\n" + result += "|" + "q_per_channel_zero_point" + "=" + str(tm.qparams["zero_point"]) + r"\n" + result += "|" + "q_per_channel_axis" + "=" + str(tm.qparams["axis"]) + r"\n" + else: + raise RuntimeError(f"Unsupported qscheme: {qscheme}") + result += "|" + "qscheme" + "=" + str(tm.qparams["qscheme"]) + r"\n" + return result + + def _get_tensor_label(self, t: torch.Tensor) -> str: + return str(t.dtype) + str(list(t.shape)) + r"\n" + + # when parse_stack_trace=True + # print file:lineno code + def _to_dot( + self, + graph_module: torch.fx.GraphModule, + name: str, + ignore_getattr: bool, + ignore_parameters_and_buffers: bool, + skip_node_names_in_args: bool, + parse_stack_trace: bool, + ) -> pydot.Dot: + """ + Actual interface to visualize a fx.Graph. Note that it takes in the GraphModule instead of the Graph. + If ignore_parameters_and_buffers is True, the parameters and buffers + created with the module will not be added as nodes and edges. + """ + + # "TB" means top-to-bottom rank direction in layout + dot_graph = pydot.Dot(name, rankdir="TB") + + + buf_name_to_subgraph = {} + + for node in graph_module.graph.nodes: + if ignore_getattr and node.op == "get_attr": + continue + + style = self._get_node_style(node) + dot_node = pydot.Node( + node.name, label=self._get_node_label(graph_module, node, skip_node_names_in_args, parse_stack_trace), **style + ) + + current_graph = dot_graph + + buf_meta = node.meta.get('buf_meta', None) + if buf_meta is not None and buf_meta.n_origin > 1: + buf_name = buf_meta.name + if buf_name not in buf_name_to_subgraph: + buf_name_to_subgraph[buf_name] = pydot.Cluster(buf_name, label=buf_name) + current_graph = buf_name_to_subgraph.get(buf_name) + + current_graph.add_node(dot_node) + + def get_module_params_or_buffers(): + for pname, ptensor in chain( + leaf_module.named_parameters(), leaf_module.named_buffers() + ): + pname1 = node.name + "." + pname + label1 = ( + pname1 + "|op_code=get_" + "parameter" + if isinstance(ptensor, torch.nn.Parameter) + else "buffer" + r"\l" + ) + dot_w_node = pydot.Node( + pname1, + label="{" + label1 + self._get_tensor_label(ptensor) + "}", + **_WEIGHT_TEMPLATE, + ) + dot_graph.add_node(dot_w_node) + dot_graph.add_edge(pydot.Edge(pname1, node.name)) + + if node.op == "call_module": + leaf_module = self._get_leaf_node(graph_module, node) + + if not ignore_parameters_and_buffers and not isinstance(leaf_module, torch.fx.GraphModule): + get_module_params_or_buffers() + + for subgraph in buf_name_to_subgraph.values(): + subgraph.set('color', 'royalblue') + subgraph.set('penwidth', '2') + dot_graph.add_subgraph(subgraph) + + for node in graph_module.graph.nodes: + if ignore_getattr and node.op == "get_attr": + continue + + for user in node.users: + dot_graph.add_edge(pydot.Edge(node.name, user.name)) + + return dot_graph + +else: + if not TYPE_CHECKING: + @compatibility(is_backward_compatible=False) + class FxGraphDrawer: + def __init__( + self, + graph_module: torch.fx.GraphModule, + name: str, + ignore_getattr: bool = False, + ignore_parameters_and_buffers: bool = False, + skip_node_names_in_args: bool = True, + parse_stack_trace: bool = False, + dot_graph_shape: Optional[str] = None, + ): + raise RuntimeError('FXGraphDrawer requires the pydot package to be installed. Please install ' + 'pydot through your favorite Python package manager.') diff --git a/shared/package-files/79/7932862661724f270235be82aae2c6bad07d77dd8f765965c56d569f45ba43e9/blob b/shared/package-files/79/7932862661724f270235be82aae2c6bad07d77dd8f765965c56d569f45ba43e9/blob new file mode 100644 index 0000000000000000000000000000000000000000..1fbcb2c506e4423406199549ee0f76b90d403fc2 --- /dev/null +++ b/shared/package-files/79/7932862661724f270235be82aae2c6bad07d77dd8f765965c56d569f45ba43e9/blob @@ -0,0 +1,2637 @@ +"""Plotting module for SymPy. + +A plot is represented by the ``Plot`` class that contains a reference to the +backend and a list of the data series to be plotted. The data series are +instances of classes meant to simplify getting points and meshes from SymPy +expressions. ``plot_backends`` is a dictionary with all the backends. + +This module gives only the essential. For all the fancy stuff use directly +the backend. You can get the backend wrapper for every plot from the +``_backend`` attribute. Moreover the data series classes have various useful +methods like ``get_points``, ``get_meshes``, etc, that may +be useful if you wish to use another plotting library. + +Especially if you need publication ready graphs and this module is not enough +for you - just get the ``_backend`` attribute and add whatever you want +directly to it. In the case of matplotlib (the common way to graph data in +python) just copy ``_backend.fig`` which is the figure and ``_backend.ax`` +which is the axis and work on them as you would on any other matplotlib object. + +Simplicity of code takes much greater importance than performance. Do not use it +if you care at all about performance. A new backend instance is initialized +every time you call ``show()`` and the old one is left to the garbage collector. +""" + + +from collections.abc import Callable + + +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.core.expr import Expr +from sympy.core.function import arity, Function +from sympy.core.symbol import (Dummy, Symbol) +from sympy.core.sympify import sympify +from sympy.external import import_module +from sympy.printing.latex import latex +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import is_sequence +from .experimental_lambdify import (vectorized_lambdify, lambdify) + +# N.B. +# When changing the minimum module version for matplotlib, please change +# the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py` + +# Backend specific imports - textplot +from sympy.plotting.textplot import textplot + +# Global variable +# Set to False when running tests / doctests so that the plots don't show. +_show = True + + +def unset_show(): + """ + Disable show(). For use in the tests. + """ + global _show + _show = False + +def _str_or_latex(label): + if isinstance(label, Basic): + return latex(label, mode='inline') + return str(label) + +############################################################################## +# The public interface +############################################################################## + + +class Plot: + """The central class of the plotting module. + + Explanation + =========== + + For interactive work the function :func:`plot()` is better suited. + + This class permits the plotting of SymPy expressions using numerous + backends (:external:mod:`matplotlib`, textplot, the old pyglet module for SymPy, Google + charts api, etc). + + The figure can contain an arbitrary number of plots of SymPy expressions, + lists of coordinates of points, etc. Plot has a private attribute _series that + contains all data series to be plotted (expressions for lines or surfaces, + lists of points, etc (all subclasses of BaseSeries)). Those data series are + instances of classes not imported by ``from sympy import *``. + + The customization of the figure is on two levels. Global options that + concern the figure as a whole (e.g. title, xlabel, scale, etc) and + per-data series options (e.g. name) and aesthetics (e.g. color, point shape, + line type, etc.). + + The difference between options and aesthetics is that an aesthetic can be + a function of the coordinates (or parameters in a parametric plot). The + supported values for an aesthetic are: + + - None (the backend uses default values) + - a constant + - a function of one variable (the first coordinate or parameter) + - a function of two variables (the first and second coordinate or parameters) + - a function of three variables (only in nonparametric 3D plots) + + Their implementation depends on the backend so they may not work in some + backends. + + If the plot is parametric and the arity of the aesthetic function permits + it the aesthetic is calculated over parameters and not over coordinates. + If the arity does not permit calculation over parameters the calculation is + done over coordinates. + + Only cartesian coordinates are supported for the moment, but you can use + the parametric plots to plot in polar, spherical and cylindrical + coordinates. + + The arguments for the constructor Plot must be subclasses of BaseSeries. + + Any global option can be specified as a keyword argument. + + The global options for a figure are: + + - title : str + - xlabel : str or Symbol + - ylabel : str or Symbol + - zlabel : str or Symbol + - legend : bool + - xscale : {'linear', 'log'} + - yscale : {'linear', 'log'} + - axis : bool + - axis_center : tuple of two floats or {'center', 'auto'} + - xlim : tuple of two floats + - ylim : tuple of two floats + - aspect_ratio : tuple of two floats or {'auto'} + - autoscale : bool + - margin : float in [0, 1] + - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend + - size : optional tuple of two floats, (width, height); default: None + + The per data series options and aesthetics are: + There are none in the base series. See below for options for subclasses. + + Some data series support additional aesthetics or options: + + :class:`~.LineOver1DRangeSeries`, :class:`~.Parametric2DLineSeries`, and + :class:`~.Parametric3DLineSeries` support the following: + + Aesthetics: + + - line_color : string, or float, or function, optional + Specifies the color for the plot, which depends on the backend being + used. + + For example, if ``MatplotlibBackend`` is being used, then + Matplotlib string colors are acceptable (``"red"``, ``"r"``, + ``"cyan"``, ``"c"``, ...). + Alternatively, we can use a float number, 0 < color < 1, wrapped in a + string (for example, ``line_color="0.5"``) to specify grayscale colors. + Alternatively, We can specify a function returning a single + float value: this will be used to apply a color-loop (for example, + ``line_color=lambda x: math.cos(x)``). + + Note that by setting line_color, it would be applied simultaneously + to all the series. + + Options: + + - label : str + - steps : bool + - integers_only : bool + + :class:`~.SurfaceOver2DRangeSeries` and :class:`~.ParametricSurfaceSeries` + support the following: + + Aesthetics: + + - surface_color : function which returns a float. + """ + + def __init__(self, *args, + title=None, xlabel=None, ylabel=None, zlabel=None, aspect_ratio='auto', + xlim=None, ylim=None, axis_center='auto', axis=True, + xscale='linear', yscale='linear', legend=False, autoscale=True, + margin=0, annotations=None, markers=None, rectangles=None, + fill=None, backend='default', size=None, **kwargs): + super().__init__() + + # Options for the graph as a whole. + # The possible values for each option are described in the docstring of + # Plot. They are based purely on convention, no checking is done. + self.title = title + self.xlabel = xlabel + self.ylabel = ylabel + self.zlabel = zlabel + self.aspect_ratio = aspect_ratio + self.axis_center = axis_center + self.axis = axis + self.xscale = xscale + self.yscale = yscale + self.legend = legend + self.autoscale = autoscale + self.margin = margin + self.annotations = annotations + self.markers = markers + self.rectangles = rectangles + self.fill = fill + + # Contains the data objects to be plotted. The backend should be smart + # enough to iterate over this list. + self._series = [] + self._series.extend(args) + + # The backend type. On every show() a new backend instance is created + # in self._backend which is tightly coupled to the Plot instance + # (thanks to the parent attribute of the backend). + if isinstance(backend, str): + self.backend = plot_backends[backend] + elif (type(backend) == type) and issubclass(backend, BaseBackend): + self.backend = backend + else: + raise TypeError( + "backend must be either a string or a subclass of BaseBackend") + + is_real = \ + lambda lim: all(getattr(i, 'is_real', True) for i in lim) + is_finite = \ + lambda lim: all(getattr(i, 'is_finite', True) for i in lim) + + # reduce code repetition + def check_and_set(t_name, t): + if t: + if not is_real(t): + raise ValueError( + "All numbers from {}={} must be real".format(t_name, t)) + if not is_finite(t): + raise ValueError( + "All numbers from {}={} must be finite".format(t_name, t)) + setattr(self, t_name, (float(t[0]), float(t[1]))) + + self.xlim = None + check_and_set("xlim", xlim) + self.ylim = None + check_and_set("ylim", ylim) + self.size = None + check_and_set("size", size) + + + def show(self): + # TODO move this to the backend (also for save) + if hasattr(self, '_backend'): + self._backend.close() + self._backend = self.backend(self) + self._backend.show() + + def save(self, path): + if hasattr(self, '_backend'): + self._backend.close() + self._backend = self.backend(self) + self._backend.save(path) + + def __str__(self): + series_strs = [('[%d]: ' % i) + str(s) + for i, s in enumerate(self._series)] + return 'Plot object containing:\n' + '\n'.join(series_strs) + + def __getitem__(self, index): + return self._series[index] + + def __setitem__(self, index, *args): + if len(args) == 1 and isinstance(args[0], BaseSeries): + self._series[index] = args + + def __delitem__(self, index): + del self._series[index] + + def append(self, arg): + """Adds an element from a plot's series to an existing plot. + + Examples + ======== + + Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the + second plot's first series object to the first, use the + ``append`` method, like so: + + .. plot:: + :format: doctest + :include-source: True + + >>> from sympy import symbols + >>> from sympy.plotting import plot + >>> x = symbols('x') + >>> p1 = plot(x*x, show=False) + >>> p2 = plot(x, show=False) + >>> p1.append(p2[0]) + >>> p1 + Plot object containing: + [0]: cartesian line: x**2 for x over (-10.0, 10.0) + [1]: cartesian line: x for x over (-10.0, 10.0) + >>> p1.show() + + See Also + ======== + + extend + + """ + if isinstance(arg, BaseSeries): + self._series.append(arg) + else: + raise TypeError('Must specify element of plot to append.') + + def extend(self, arg): + """Adds all series from another plot. + + Examples + ======== + + Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the + second plot to the first, use the ``extend`` method, like so: + + .. plot:: + :format: doctest + :include-source: True + + >>> from sympy import symbols + >>> from sympy.plotting import plot + >>> x = symbols('x') + >>> p1 = plot(x**2, show=False) + >>> p2 = plot(x, -x, show=False) + >>> p1.extend(p2) + >>> p1 + Plot object containing: + [0]: cartesian line: x**2 for x over (-10.0, 10.0) + [1]: cartesian line: x for x over (-10.0, 10.0) + [2]: cartesian line: -x for x over (-10.0, 10.0) + >>> p1.show() + + """ + if isinstance(arg, Plot): + self._series.extend(arg._series) + elif is_sequence(arg): + self._series.extend(arg) + else: + raise TypeError('Expecting Plot or sequence of BaseSeries') + + +class PlotGrid: + """This class helps to plot subplots from already created SymPy plots + in a single figure. + + Examples + ======== + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> from sympy import symbols + >>> from sympy.plotting import plot, plot3d, PlotGrid + >>> x, y = symbols('x, y') + >>> p1 = plot(x, x**2, x**3, (x, -5, 5)) + >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5))) + >>> p3 = plot(x**3, (x, -5, 5)) + >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5)) + + Plotting vertically in a single line: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> PlotGrid(2, 1, p1, p2) + PlotGrid object containing: + Plot[0]:Plot object containing: + [0]: cartesian line: x for x over (-5.0, 5.0) + [1]: cartesian line: x**2 for x over (-5.0, 5.0) + [2]: cartesian line: x**3 for x over (-5.0, 5.0) + Plot[1]:Plot object containing: + [0]: cartesian line: x**2 for x over (-6.0, 6.0) + [1]: cartesian line: x for x over (-5.0, 5.0) + + Plotting horizontally in a single line: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> PlotGrid(1, 3, p2, p3, p4) + PlotGrid object containing: + Plot[0]:Plot object containing: + [0]: cartesian line: x**2 for x over (-6.0, 6.0) + [1]: cartesian line: x for x over (-5.0, 5.0) + Plot[1]:Plot object containing: + [0]: cartesian line: x**3 for x over (-5.0, 5.0) + Plot[2]:Plot object containing: + [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) + + Plotting in a grid form: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> PlotGrid(2, 2, p1, p2, p3, p4) + PlotGrid object containing: + Plot[0]:Plot object containing: + [0]: cartesian line: x for x over (-5.0, 5.0) + [1]: cartesian line: x**2 for x over (-5.0, 5.0) + [2]: cartesian line: x**3 for x over (-5.0, 5.0) + Plot[1]:Plot object containing: + [0]: cartesian line: x**2 for x over (-6.0, 6.0) + [1]: cartesian line: x for x over (-5.0, 5.0) + Plot[2]:Plot object containing: + [0]: cartesian line: x**3 for x over (-5.0, 5.0) + Plot[3]:Plot object containing: + [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) + + """ + def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs): + """ + Parameters + ========== + + nrows : + The number of rows that should be in the grid of the + required subplot. + ncolumns : + The number of columns that should be in the grid + of the required subplot. + + nrows and ncolumns together define the required grid. + + Arguments + ========= + + A list of predefined plot objects entered in a row-wise sequence + i.e. plot objects which are to be in the top row of the required + grid are written first, then the second row objects and so on + + Keyword arguments + ================= + + show : Boolean + The default value is set to ``True``. Set show to ``False`` and + the function will not display the subplot. The returned instance + of the ``PlotGrid`` class can then be used to save or display the + plot by calling the ``save()`` and ``show()`` methods + respectively. + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of + the overall figure. The default value is set to ``None``, meaning + the size will be set by the default backend. + """ + self.nrows = nrows + self.ncolumns = ncolumns + self._series = [] + self.args = args + for arg in args: + self._series.append(arg._series) + self.backend = DefaultBackend + self.size = size + if show: + self.show() + + def show(self): + if hasattr(self, '_backend'): + self._backend.close() + self._backend = self.backend(self) + self._backend.show() + + def save(self, path): + if hasattr(self, '_backend'): + self._backend.close() + self._backend = self.backend(self) + self._backend.save(path) + + def __str__(self): + plot_strs = [('Plot[%d]:' % i) + str(plot) + for i, plot in enumerate(self.args)] + + return 'PlotGrid object containing:\n' + '\n'.join(plot_strs) + + +############################################################################## +# Data Series +############################################################################## +#TODO more general way to calculate aesthetics (see get_color_array) + +### The base class for all series +class BaseSeries: + """Base class for the data objects containing stuff to be plotted. + + Explanation + =========== + + The backend should check if it supports the data series that is given. + (e.g. TextBackend supports only LineOver1DRangeSeries). + It is the backend responsibility to know how to use the class of + data series that is given. + + Some data series classes are grouped (using a class attribute like is_2Dline) + according to the api they present (based only on convention). The backend is + not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the + is_2Dline group and presents the get_points method, but the + TextBackend does not use the get_points method). + """ + + # Some flags follow. The rationale for using flags instead of checking base + # classes is that setting multiple flags is simpler than multiple + # inheritance. + + is_2Dline = False + # Some of the backends expect: + # - get_points returning 1D np.arrays list_x, list_y + # - get_color_array returning 1D np.array (done in Line2DBaseSeries) + # with the colors calculated at the points from get_points + + is_3Dline = False + # Some of the backends expect: + # - get_points returning 1D np.arrays list_x, list_y, list_y + # - get_color_array returning 1D np.array (done in Line2DBaseSeries) + # with the colors calculated at the points from get_points + + is_3Dsurface = False + # Some of the backends expect: + # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays) + # - get_points an alias for get_meshes + + is_contour = False + # Some of the backends expect: + # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays) + # - get_points an alias for get_meshes + + is_implicit = False + # Some of the backends expect: + # - get_meshes returning mesh_x (1D array), mesh_y(1D array, + # mesh_z (2D np.arrays) + # - get_points an alias for get_meshes + # Different from is_contour as the colormap in backend will be + # different + + is_parametric = False + # The calculation of aesthetics expects: + # - get_parameter_points returning one or two np.arrays (1D or 2D) + # used for calculation aesthetics + + def __init__(self): + super().__init__() + + @property + def is_3D(self): + flags3D = [ + self.is_3Dline, + self.is_3Dsurface + ] + return any(flags3D) + + @property + def is_line(self): + flagslines = [ + self.is_2Dline, + self.is_3Dline + ] + return any(flagslines) + + +### 2D lines +class Line2DBaseSeries(BaseSeries): + """A base class for 2D lines. + + - adding the label, steps and only_integers options + - making is_2Dline true + - defining get_segments and get_color_array + """ + + is_2Dline = True + + _dim = 2 + + def __init__(self): + super().__init__() + self.label = None + self.steps = False + self.only_integers = False + self.line_color = None + + def get_data(self): + """ Return lists of coordinates for plotting the line. + + Returns + ======= + x : list + List of x-coordinates + + y : list + List of y-coordinates + + z : list + List of z-coordinates in case of Parametric3DLineSeries + """ + np = import_module('numpy') + points = self.get_points() + if self.steps is True: + if len(points) == 2: + x = np.array((points[0], points[0])).T.flatten()[1:] + y = np.array((points[1], points[1])).T.flatten()[:-1] + points = (x, y) + else: + x = np.repeat(points[0], 3)[2:] + y = np.repeat(points[1], 3)[:-2] + z = np.repeat(points[2], 3)[1:-1] + points = (x, y, z) + return points + + def get_segments(self): + sympy_deprecation_warning( + """ + The Line2DBaseSeries.get_segments() method is deprecated. + + Instead, use the MatplotlibBackend.get_segments() method, or use + The get_points() or get_data() methods. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-get-segments") + + np = import_module('numpy') + points = type(self).get_data(self) + points = np.ma.array(points).T.reshape(-1, 1, self._dim) + return np.ma.concatenate([points[:-1], points[1:]], axis=1) + + def get_color_array(self): + np = import_module('numpy') + c = self.line_color + if hasattr(c, '__call__'): + f = np.vectorize(c) + nargs = arity(c) + if nargs == 1 and self.is_parametric: + x = self.get_parameter_points() + return f(centers_of_segments(x)) + else: + variables = list(map(centers_of_segments, self.get_points())) + if nargs == 1: + return f(variables[0]) + elif nargs == 2: + return f(*variables[:2]) + else: # only if the line is 3D (otherwise raises an error) + return f(*variables) + else: + return c*np.ones(self.nb_of_points) + + +class List2DSeries(Line2DBaseSeries): + """Representation for a line consisting of list of points.""" + + def __init__(self, list_x, list_y): + np = import_module('numpy') + super().__init__() + self.list_x = np.array(list_x) + self.list_y = np.array(list_y) + self.label = 'list' + + def __str__(self): + return 'list plot' + + def get_points(self): + return (self.list_x, self.list_y) + + +class LineOver1DRangeSeries(Line2DBaseSeries): + """Representation for a line consisting of a SymPy expression over a range.""" + + def __init__(self, expr, var_start_end, **kwargs): + super().__init__() + self.expr = sympify(expr) + self.label = kwargs.get('label', None) or self.expr + self.var = sympify(var_start_end[0]) + self.start = float(var_start_end[1]) + self.end = float(var_start_end[2]) + self.nb_of_points = kwargs.get('nb_of_points', 300) + self.adaptive = kwargs.get('adaptive', True) + self.depth = kwargs.get('depth', 12) + self.line_color = kwargs.get('line_color', None) + self.xscale = kwargs.get('xscale', 'linear') + + def __str__(self): + return 'cartesian line: %s for %s over %s' % ( + str(self.expr), str(self.var), str((self.start, self.end))) + + def get_points(self): + """ Return lists of coordinates for plotting. Depending on the + ``adaptive`` option, this function will either use an adaptive algorithm + or it will uniformly sample the expression over the provided range. + + Returns + ======= + x : list + List of x-coordinates + + y : list + List of y-coordinates + + + Explanation + =========== + + The adaptive sampling is done by recursively checking if three + points are almost collinear. If they are not collinear, then more + points are added between those points. + + References + ========== + + .. [1] Adaptive polygonal approximation of parametric curves, + Luiz Henrique de Figueiredo. + + """ + if self.only_integers or not self.adaptive: + return self._uniform_sampling() + else: + f = lambdify([self.var], self.expr) + x_coords = [] + y_coords = [] + np = import_module('numpy') + def sample(p, q, depth): + """ Samples recursively if three points are almost collinear. + For depth < 6, points are added irrespective of whether they + satisfy the collinearity condition or not. The maximum depth + allowed is 12. + """ + # Randomly sample to avoid aliasing. + random = 0.45 + np.random.rand() * 0.1 + if self.xscale == 'log': + xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) - + np.log10(p[0]))) + else: + xnew = p[0] + random * (q[0] - p[0]) + ynew = f(xnew) + new_point = np.array([xnew, ynew]) + + # Maximum depth + if depth > self.depth: + x_coords.append(q[0]) + y_coords.append(q[1]) + + # Sample irrespective of whether the line is flat till the + # depth of 6. We are not using linspace to avoid aliasing. + elif depth < 6: + sample(p, new_point, depth + 1) + sample(new_point, q, depth + 1) + + # Sample ten points if complex values are encountered + # at both ends. If there is a real value in between, then + # sample those points further. + elif p[1] is None and q[1] is None: + if self.xscale == 'log': + xarray = np.logspace(p[0], q[0], 10) + else: + xarray = np.linspace(p[0], q[0], 10) + yarray = list(map(f, xarray)) + if not all(y is None for y in yarray): + for i in range(len(yarray) - 1): + if not (yarray[i] is None and yarray[i + 1] is None): + sample([xarray[i], yarray[i]], + [xarray[i + 1], yarray[i + 1]], depth + 1) + + # Sample further if one of the end points in None (i.e. a + # complex value) or the three points are not almost collinear. + elif (p[1] is None or q[1] is None or new_point[1] is None + or not flat(p, new_point, q)): + sample(p, new_point, depth + 1) + sample(new_point, q, depth + 1) + else: + x_coords.append(q[0]) + y_coords.append(q[1]) + + f_start = f(self.start) + f_end = f(self.end) + x_coords.append(self.start) + y_coords.append(f_start) + sample(np.array([self.start, f_start]), + np.array([self.end, f_end]), 0) + + return (x_coords, y_coords) + + def _uniform_sampling(self): + np = import_module('numpy') + if self.only_integers is True: + if self.xscale == 'log': + list_x = np.logspace(int(self.start), int(self.end), + num=int(self.end) - int(self.start) + 1) + else: + list_x = np.linspace(int(self.start), int(self.end), + num=int(self.end) - int(self.start) + 1) + else: + if self.xscale == 'log': + list_x = np.logspace(self.start, self.end, num=self.nb_of_points) + else: + list_x = np.linspace(self.start, self.end, num=self.nb_of_points) + f = vectorized_lambdify([self.var], self.expr) + list_y = f(list_x) + return (list_x, list_y) + + +class Parametric2DLineSeries(Line2DBaseSeries): + """Representation for a line consisting of two parametric SymPy expressions + over a range.""" + + is_parametric = True + + def __init__(self, expr_x, expr_y, var_start_end, **kwargs): + super().__init__() + self.expr_x = sympify(expr_x) + self.expr_y = sympify(expr_y) + self.label = kwargs.get('label', None) or \ + Tuple(self.expr_x, self.expr_y) + self.var = sympify(var_start_end[0]) + self.start = float(var_start_end[1]) + self.end = float(var_start_end[2]) + self.nb_of_points = kwargs.get('nb_of_points', 300) + self.adaptive = kwargs.get('adaptive', True) + self.depth = kwargs.get('depth', 12) + self.line_color = kwargs.get('line_color', None) + + def __str__(self): + return 'parametric cartesian line: (%s, %s) for %s over %s' % ( + str(self.expr_x), str(self.expr_y), str(self.var), + str((self.start, self.end))) + + def get_parameter_points(self): + np = import_module('numpy') + return np.linspace(self.start, self.end, num=self.nb_of_points) + + def _uniform_sampling(self): + param = self.get_parameter_points() + fx = vectorized_lambdify([self.var], self.expr_x) + fy = vectorized_lambdify([self.var], self.expr_y) + list_x = fx(param) + list_y = fy(param) + return (list_x, list_y) + + def get_points(self): + """ Return lists of coordinates for plotting. Depending on the + ``adaptive`` option, this function will either use an adaptive algorithm + or it will uniformly sample the expression over the provided range. + + Returns + ======= + x : list + List of x-coordinates + + y : list + List of y-coordinates + + + Explanation + =========== + + The adaptive sampling is done by recursively checking if three + points are almost collinear. If they are not collinear, then more + points are added between those points. + + References + ========== + + .. [1] Adaptive polygonal approximation of parametric curves, + Luiz Henrique de Figueiredo. + + """ + if not self.adaptive: + return self._uniform_sampling() + + f_x = lambdify([self.var], self.expr_x) + f_y = lambdify([self.var], self.expr_y) + x_coords = [] + y_coords = [] + + def sample(param_p, param_q, p, q, depth): + """ Samples recursively if three points are almost collinear. + For depth < 6, points are added irrespective of whether they + satisfy the collinearity condition or not. The maximum depth + allowed is 12. + """ + # Randomly sample to avoid aliasing. + np = import_module('numpy') + random = 0.45 + np.random.rand() * 0.1 + param_new = param_p + random * (param_q - param_p) + xnew = f_x(param_new) + ynew = f_y(param_new) + new_point = np.array([xnew, ynew]) + + # Maximum depth + if depth > self.depth: + x_coords.append(q[0]) + y_coords.append(q[1]) + + # Sample irrespective of whether the line is flat till the + # depth of 6. We are not using linspace to avoid aliasing. + elif depth < 6: + sample(param_p, param_new, p, new_point, depth + 1) + sample(param_new, param_q, new_point, q, depth + 1) + + # Sample ten points if complex values are encountered + # at both ends. If there is a real value in between, then + # sample those points further. + elif ((p[0] is None and q[1] is None) or + (p[1] is None and q[1] is None)): + param_array = np.linspace(param_p, param_q, 10) + x_array = list(map(f_x, param_array)) + y_array = list(map(f_y, param_array)) + if not all(x is None and y is None + for x, y in zip(x_array, y_array)): + for i in range(len(y_array) - 1): + if ((x_array[i] is not None and y_array[i] is not None) or + (x_array[i + 1] is not None and y_array[i + 1] is not None)): + point_a = [x_array[i], y_array[i]] + point_b = [x_array[i + 1], y_array[i + 1]] + sample(param_array[i], param_array[i], point_a, + point_b, depth + 1) + + # Sample further if one of the end points in None (i.e. a complex + # value) or the three points are not almost collinear. + elif (p[0] is None or p[1] is None + or q[1] is None or q[0] is None + or not flat(p, new_point, q)): + sample(param_p, param_new, p, new_point, depth + 1) + sample(param_new, param_q, new_point, q, depth + 1) + else: + x_coords.append(q[0]) + y_coords.append(q[1]) + + f_start_x = f_x(self.start) + f_start_y = f_y(self.start) + start = [f_start_x, f_start_y] + f_end_x = f_x(self.end) + f_end_y = f_y(self.end) + end = [f_end_x, f_end_y] + x_coords.append(f_start_x) + y_coords.append(f_start_y) + sample(self.start, self.end, start, end, 0) + + return x_coords, y_coords + + +### 3D lines +class Line3DBaseSeries(Line2DBaseSeries): + """A base class for 3D lines. + + Most of the stuff is derived from Line2DBaseSeries.""" + + is_2Dline = False + is_3Dline = True + _dim = 3 + + def __init__(self): + super().__init__() + + +class Parametric3DLineSeries(Line3DBaseSeries): + """Representation for a 3D line consisting of three parametric SymPy + expressions and a range.""" + + is_parametric = True + + def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs): + super().__init__() + self.expr_x = sympify(expr_x) + self.expr_y = sympify(expr_y) + self.expr_z = sympify(expr_z) + self.label = kwargs.get('label', None) or \ + Tuple(self.expr_x, self.expr_y) + self.var = sympify(var_start_end[0]) + self.start = float(var_start_end[1]) + self.end = float(var_start_end[2]) + self.nb_of_points = kwargs.get('nb_of_points', 300) + self.line_color = kwargs.get('line_color', None) + self._xlim = None + self._ylim = None + self._zlim = None + + def __str__(self): + return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % ( + str(self.expr_x), str(self.expr_y), str(self.expr_z), + str(self.var), str((self.start, self.end))) + + def get_parameter_points(self): + np = import_module('numpy') + return np.linspace(self.start, self.end, num=self.nb_of_points) + + def get_points(self): + np = import_module('numpy') + param = self.get_parameter_points() + fx = vectorized_lambdify([self.var], self.expr_x) + fy = vectorized_lambdify([self.var], self.expr_y) + fz = vectorized_lambdify([self.var], self.expr_z) + + list_x = fx(param) + list_y = fy(param) + list_z = fz(param) + + list_x = np.array(list_x, dtype=np.float64) + list_y = np.array(list_y, dtype=np.float64) + list_z = np.array(list_z, dtype=np.float64) + + list_x = np.ma.masked_invalid(list_x) + list_y = np.ma.masked_invalid(list_y) + list_z = np.ma.masked_invalid(list_z) + + self._xlim = (np.amin(list_x), np.amax(list_x)) + self._ylim = (np.amin(list_y), np.amax(list_y)) + self._zlim = (np.amin(list_z), np.amax(list_z)) + return list_x, list_y, list_z + + +### Surfaces +class SurfaceBaseSeries(BaseSeries): + """A base class for 3D surfaces.""" + + is_3Dsurface = True + + def __init__(self): + super().__init__() + self.surface_color = None + + def get_color_array(self): + np = import_module('numpy') + c = self.surface_color + if isinstance(c, Callable): + f = np.vectorize(c) + nargs = arity(c) + if self.is_parametric: + variables = list(map(centers_of_faces, self.get_parameter_meshes())) + if nargs == 1: + return f(variables[0]) + elif nargs == 2: + return f(*variables) + variables = list(map(centers_of_faces, self.get_meshes())) + if nargs == 1: + return f(variables[0]) + elif nargs == 2: + return f(*variables[:2]) + else: + return f(*variables) + else: + if isinstance(self, SurfaceOver2DRangeSeries): + return c*np.ones(min(self.nb_of_points_x, self.nb_of_points_y)) + else: + return c*np.ones(min(self.nb_of_points_u, self.nb_of_points_v)) + + +class SurfaceOver2DRangeSeries(SurfaceBaseSeries): + """Representation for a 3D surface consisting of a SymPy expression and 2D + range.""" + def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs): + super().__init__() + self.expr = sympify(expr) + self.var_x = sympify(var_start_end_x[0]) + self.start_x = float(var_start_end_x[1]) + self.end_x = float(var_start_end_x[2]) + self.var_y = sympify(var_start_end_y[0]) + self.start_y = float(var_start_end_y[1]) + self.end_y = float(var_start_end_y[2]) + self.nb_of_points_x = kwargs.get('nb_of_points_x', 50) + self.nb_of_points_y = kwargs.get('nb_of_points_y', 50) + self.surface_color = kwargs.get('surface_color', None) + + self._xlim = (self.start_x, self.end_x) + self._ylim = (self.start_y, self.end_y) + + def __str__(self): + return ('cartesian surface: %s for' + ' %s over %s and %s over %s') % ( + str(self.expr), + str(self.var_x), + str((self.start_x, self.end_x)), + str(self.var_y), + str((self.start_y, self.end_y))) + + def get_meshes(self): + np = import_module('numpy') + mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x, + num=self.nb_of_points_x), + np.linspace(self.start_y, self.end_y, + num=self.nb_of_points_y)) + f = vectorized_lambdify((self.var_x, self.var_y), self.expr) + mesh_z = f(mesh_x, mesh_y) + mesh_z = np.array(mesh_z, dtype=np.float64) + mesh_z = np.ma.masked_invalid(mesh_z) + self._zlim = (np.amin(mesh_z), np.amax(mesh_z)) + return mesh_x, mesh_y, mesh_z + + +class ParametricSurfaceSeries(SurfaceBaseSeries): + """Representation for a 3D surface consisting of three parametric SymPy + expressions and a range.""" + + is_parametric = True + + def __init__( + self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v, + **kwargs): + super().__init__() + self.expr_x = sympify(expr_x) + self.expr_y = sympify(expr_y) + self.expr_z = sympify(expr_z) + self.var_u = sympify(var_start_end_u[0]) + self.start_u = float(var_start_end_u[1]) + self.end_u = float(var_start_end_u[2]) + self.var_v = sympify(var_start_end_v[0]) + self.start_v = float(var_start_end_v[1]) + self.end_v = float(var_start_end_v[2]) + self.nb_of_points_u = kwargs.get('nb_of_points_u', 50) + self.nb_of_points_v = kwargs.get('nb_of_points_v', 50) + self.surface_color = kwargs.get('surface_color', None) + + def __str__(self): + return ('parametric cartesian surface: (%s, %s, %s) for' + ' %s over %s and %s over %s') % ( + str(self.expr_x), + str(self.expr_y), + str(self.expr_z), + str(self.var_u), + str((self.start_u, self.end_u)), + str(self.var_v), + str((self.start_v, self.end_v))) + + def get_parameter_meshes(self): + np = import_module('numpy') + return np.meshgrid(np.linspace(self.start_u, self.end_u, + num=self.nb_of_points_u), + np.linspace(self.start_v, self.end_v, + num=self.nb_of_points_v)) + + def get_meshes(self): + np = import_module('numpy') + + mesh_u, mesh_v = self.get_parameter_meshes() + fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x) + fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y) + fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z) + + mesh_x = fx(mesh_u, mesh_v) + mesh_y = fy(mesh_u, mesh_v) + mesh_z = fz(mesh_u, mesh_v) + + mesh_x = np.array(mesh_x, dtype=np.float64) + mesh_y = np.array(mesh_y, dtype=np.float64) + mesh_z = np.array(mesh_z, dtype=np.float64) + + mesh_x = np.ma.masked_invalid(mesh_x) + mesh_y = np.ma.masked_invalid(mesh_y) + mesh_z = np.ma.masked_invalid(mesh_z) + + self._xlim = (np.amin(mesh_x), np.amax(mesh_x)) + self._ylim = (np.amin(mesh_y), np.amax(mesh_y)) + self._zlim = (np.amin(mesh_z), np.amax(mesh_z)) + + return mesh_x, mesh_y, mesh_z + + +### Contours +class ContourSeries(BaseSeries): + """Representation for a contour plot.""" + # The code is mostly repetition of SurfaceOver2DRange. + # Presently used in contour_plot function + + is_contour = True + + def __init__(self, expr, var_start_end_x, var_start_end_y): + super().__init__() + self.nb_of_points_x = 50 + self.nb_of_points_y = 50 + self.expr = sympify(expr) + self.var_x = sympify(var_start_end_x[0]) + self.start_x = float(var_start_end_x[1]) + self.end_x = float(var_start_end_x[2]) + self.var_y = sympify(var_start_end_y[0]) + self.start_y = float(var_start_end_y[1]) + self.end_y = float(var_start_end_y[2]) + + self.get_points = self.get_meshes + + self._xlim = (self.start_x, self.end_x) + self._ylim = (self.start_y, self.end_y) + + def __str__(self): + return ('contour: %s for ' + '%s over %s and %s over %s') % ( + str(self.expr), + str(self.var_x), + str((self.start_x, self.end_x)), + str(self.var_y), + str((self.start_y, self.end_y))) + + def get_meshes(self): + np = import_module('numpy') + mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x, + num=self.nb_of_points_x), + np.linspace(self.start_y, self.end_y, + num=self.nb_of_points_y)) + f = vectorized_lambdify((self.var_x, self.var_y), self.expr) + return (mesh_x, mesh_y, f(mesh_x, mesh_y)) + + +############################################################################## +# Backends +############################################################################## + +class BaseBackend: + """Base class for all backends. A backend represents the plotting library, + which implements the necessary functionalities in order to use SymPy + plotting functions. + + How the plotting module works: + + 1. Whenever a plotting function is called, the provided expressions are + processed and a list of instances of the :class:`BaseSeries` class is + created, containing the necessary information to plot the expressions + (e.g. the expression, ranges, series name, ...). Eventually, these + objects will generate the numerical data to be plotted. + 2. A :class:`~.Plot` object is instantiated, which stores the list of + series and the main attributes of the plot (e.g. axis labels, title, ...). + 3. When the ``show`` command is executed, a new backend is instantiated, + which loops through each series object to generate and plot the + numerical data. The backend is also going to set the axis labels, title, + ..., according to the values stored in the Plot instance. + + The backend should check if it supports the data series that it is given + (e.g. :class:`TextBackend` supports only :class:`LineOver1DRangeSeries`). + + It is the backend responsibility to know how to use the class of data series + that it's given. Note that the current implementation of the ``*Series`` + classes is "matplotlib-centric": the numerical data returned by the + ``get_points`` and ``get_meshes`` methods is meant to be used directly by + Matplotlib. Therefore, the new backend will have to pre-process the + numerical data to make it compatible with the chosen plotting library. + Keep in mind that future SymPy versions may improve the ``*Series`` classes + in order to return numerical data "non-matplotlib-centric", hence if you code + a new backend you have the responsibility to check if its working on each + SymPy release. + + Please explore the :class:`MatplotlibBackend` source code to understand how a + backend should be coded. + + Methods + ======= + + In order to be used by SymPy plotting functions, a backend must implement + the following methods: + + * show(self): used to loop over the data series, generate the numerical + data, plot it and set the axis labels, title, ... + * save(self, path): used to save the current plot to the specified file + path. + * close(self): used to close the current plot backend (note: some plotting + library does not support this functionality. In that case, just raise a + warning). + + See also + ======== + + MatplotlibBackend + """ + def __init__(self, parent): + super().__init__() + self.parent = parent + + def show(self): + raise NotImplementedError + + def save(self, path): + raise NotImplementedError + + def close(self): + raise NotImplementedError + + +# Don't have to check for the success of importing matplotlib in each case; +# we will only be using this backend if we can successfully import matploblib +class MatplotlibBackend(BaseBackend): + """ This class implements the functionalities to use Matplotlib with SymPy + plotting functions. + """ + def __init__(self, parent): + super().__init__(parent) + self.matplotlib = import_module('matplotlib', + import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']}, + min_module_version='1.1.0', catch=(RuntimeError,)) + self.plt = self.matplotlib.pyplot + self.cm = self.matplotlib.cm + self.LineCollection = self.matplotlib.collections.LineCollection + aspect = getattr(self.parent, 'aspect_ratio', 'auto') + if aspect != 'auto': + aspect = float(aspect[1]) / aspect[0] + + if isinstance(self.parent, Plot): + nrows, ncolumns = 1, 1 + series_list = [self.parent._series] + elif isinstance(self.parent, PlotGrid): + nrows, ncolumns = self.parent.nrows, self.parent.ncolumns + series_list = self.parent._series + + self.ax = [] + self.fig = self.plt.figure(figsize=parent.size) + + for i, series in enumerate(series_list): + are_3D = [s.is_3D for s in series] + + if any(are_3D) and not all(are_3D): + raise ValueError('The matplotlib backend cannot mix 2D and 3D.') + elif all(are_3D): + # mpl_toolkits.mplot3d is necessary for + # projection='3d' + mpl_toolkits = import_module('mpl_toolkits', # noqa + import_kwargs={'fromlist': ['mplot3d']}) + self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect)) + + elif not any(are_3D): + self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect)) + self.ax[i].spines['left'].set_position('zero') + self.ax[i].spines['right'].set_color('none') + self.ax[i].spines['bottom'].set_position('zero') + self.ax[i].spines['top'].set_color('none') + self.ax[i].xaxis.set_ticks_position('bottom') + self.ax[i].yaxis.set_ticks_position('left') + + @staticmethod + def get_segments(x, y, z=None): + """ Convert two list of coordinates to a list of segments to be used + with Matplotlib's :external:class:`~matplotlib.collections.LineCollection`. + + Parameters + ========== + x : list + List of x-coordinates + + y : list + List of y-coordinates + + z : list + List of z-coordinates for a 3D line. + """ + np = import_module('numpy') + if z is not None: + dim = 3 + points = (x, y, z) + else: + dim = 2 + points = (x, y) + points = np.ma.array(points).T.reshape(-1, 1, dim) + return np.ma.concatenate([points[:-1], points[1:]], axis=1) + + def _process_series(self, series, ax, parent): + np = import_module('numpy') + mpl_toolkits = import_module( + 'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']}) + + # XXX Workaround for matplotlib issue + # https://github.com/matplotlib/matplotlib/issues/17130 + xlims, ylims, zlims = [], [], [] + + for s in series: + # Create the collections + if s.is_2Dline: + x, y = s.get_data() + if (isinstance(s.line_color, (int, float)) or + callable(s.line_color)): + segments = self.get_segments(x, y) + collection = self.LineCollection(segments) + collection.set_array(s.get_color_array()) + ax.add_collection(collection) + else: + lbl = _str_or_latex(s.label) + line, = ax.plot(x, y, label=lbl, color=s.line_color) + elif s.is_contour: + ax.contour(*s.get_meshes()) + elif s.is_3Dline: + x, y, z = s.get_data() + if (isinstance(s.line_color, (int, float)) or + callable(s.line_color)): + art3d = mpl_toolkits.mplot3d.art3d + segments = self.get_segments(x, y, z) + collection = art3d.Line3DCollection(segments) + collection.set_array(s.get_color_array()) + ax.add_collection(collection) + else: + lbl = _str_or_latex(s.label) + ax.plot(x, y, z, label=lbl, color=s.line_color) + + xlims.append(s._xlim) + ylims.append(s._ylim) + zlims.append(s._zlim) + elif s.is_3Dsurface: + x, y, z = s.get_meshes() + collection = ax.plot_surface(x, y, z, + cmap=getattr(self.cm, 'viridis', self.cm.jet), + rstride=1, cstride=1, linewidth=0.1) + if isinstance(s.surface_color, (float, int, Callable)): + color_array = s.get_color_array() + color_array = color_array.reshape(color_array.size) + collection.set_array(color_array) + else: + collection.set_color(s.surface_color) + + xlims.append(s._xlim) + ylims.append(s._ylim) + zlims.append(s._zlim) + elif s.is_implicit: + points = s.get_raster() + if len(points) == 2: + # interval math plotting + x, y = _matplotlib_list(points[0]) + ax.fill(x, y, facecolor=s.line_color, edgecolor='None') + else: + # use contourf or contour depending on whether it is + # an inequality or equality. + # XXX: ``contour`` plots multiple lines. Should be fixed. + ListedColormap = self.matplotlib.colors.ListedColormap + colormap = ListedColormap(["white", s.line_color]) + xarray, yarray, zarray, plot_type = points + if plot_type == 'contour': + ax.contour(xarray, yarray, zarray, cmap=colormap) + else: + ax.contourf(xarray, yarray, zarray, cmap=colormap) + else: + raise NotImplementedError( + '{} is not supported in the SymPy plotting module ' + 'with matplotlib backend. Please report this issue.' + .format(ax)) + + Axes3D = mpl_toolkits.mplot3d.Axes3D + if not isinstance(ax, Axes3D): + ax.autoscale_view( + scalex=ax.get_autoscalex_on(), + scaley=ax.get_autoscaley_on()) + else: + # XXX Workaround for matplotlib issue + # https://github.com/matplotlib/matplotlib/issues/17130 + if xlims: + xlims = np.array(xlims) + xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1])) + ax.set_xlim(xlim) + else: + ax.set_xlim([0, 1]) + + if ylims: + ylims = np.array(ylims) + ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1])) + ax.set_ylim(ylim) + else: + ax.set_ylim([0, 1]) + + if zlims: + zlims = np.array(zlims) + zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1])) + ax.set_zlim(zlim) + else: + ax.set_zlim([0, 1]) + + # Set global options. + # TODO The 3D stuff + # XXX The order of those is important. + if parent.xscale and not isinstance(ax, Axes3D): + ax.set_xscale(parent.xscale) + if parent.yscale and not isinstance(ax, Axes3D): + ax.set_yscale(parent.yscale) + if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check + ax.set_autoscale_on(parent.autoscale) + if parent.axis_center: + val = parent.axis_center + if isinstance(ax, Axes3D): + pass + elif val == 'center': + ax.spines['left'].set_position('center') + ax.spines['bottom'].set_position('center') + elif val == 'auto': + xl, xh = ax.get_xlim() + yl, yh = ax.get_ylim() + pos_left = ('data', 0) if xl*xh <= 0 else 'center' + pos_bottom = ('data', 0) if yl*yh <= 0 else 'center' + ax.spines['left'].set_position(pos_left) + ax.spines['bottom'].set_position(pos_bottom) + else: + ax.spines['left'].set_position(('data', val[0])) + ax.spines['bottom'].set_position(('data', val[1])) + if not parent.axis: + ax.set_axis_off() + if parent.legend: + if ax.legend(): + ax.legend_.set_visible(parent.legend) + if parent.margin: + ax.set_xmargin(parent.margin) + ax.set_ymargin(parent.margin) + if parent.title: + ax.set_title(parent.title) + if parent.xlabel: + xlbl = _str_or_latex(parent.xlabel) + ax.set_xlabel(xlbl, position=(1, 0)) + if parent.ylabel: + ylbl = _str_or_latex(parent.ylabel) + ax.set_ylabel(ylbl, position=(0, 1)) + if isinstance(ax, Axes3D) and parent.zlabel: + zlbl = _str_or_latex(parent.zlabel) + ax.set_zlabel(zlbl, position=(0, 1)) + if parent.annotations: + for a in parent.annotations: + ax.annotate(**a) + if parent.markers: + for marker in parent.markers: + # make a copy of the marker dictionary + # so that it doesn't get altered + m = marker.copy() + args = m.pop('args') + ax.plot(*args, **m) + if parent.rectangles: + for r in parent.rectangles: + rect = self.matplotlib.patches.Rectangle(**r) + ax.add_patch(rect) + if parent.fill: + ax.fill_between(**parent.fill) + + # xlim and ylim should always be set at last so that plot limits + # doesn't get altered during the process. + if parent.xlim: + ax.set_xlim(parent.xlim) + if parent.ylim: + ax.set_ylim(parent.ylim) + + + def process_series(self): + """ + Iterates over every ``Plot`` object and further calls + _process_series() + """ + parent = self.parent + if isinstance(parent, Plot): + series_list = [parent._series] + else: + series_list = parent._series + + for i, (series, ax) in enumerate(zip(series_list, self.ax)): + if isinstance(self.parent, PlotGrid): + parent = self.parent.args[i] + self._process_series(series, ax, parent) + + def show(self): + self.process_series() + #TODO after fixing https://github.com/ipython/ipython/issues/1255 + # you can uncomment the next line and remove the pyplot.show() call + #self.fig.show() + if _show: + self.fig.tight_layout() + self.plt.show() + else: + self.close() + + def save(self, path): + self.process_series() + self.fig.savefig(path) + + def close(self): + self.plt.close(self.fig) + + +class TextBackend(BaseBackend): + def __init__(self, parent): + super().__init__(parent) + + def show(self): + if not _show: + return + if len(self.parent._series) != 1: + raise ValueError( + 'The TextBackend supports only one graph per Plot.') + elif not isinstance(self.parent._series[0], LineOver1DRangeSeries): + raise ValueError( + 'The TextBackend supports only expressions over a 1D range') + else: + ser = self.parent._series[0] + textplot(ser.expr, ser.start, ser.end) + + def close(self): + pass + + +class DefaultBackend(BaseBackend): + def __new__(cls, parent): + matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) + if matplotlib: + return MatplotlibBackend(parent) + else: + return TextBackend(parent) + + +plot_backends = { + 'matplotlib': MatplotlibBackend, + 'text': TextBackend, + 'default': DefaultBackend +} + + +############################################################################## +# Finding the centers of line segments or mesh faces +############################################################################## + +def centers_of_segments(array): + np = import_module('numpy') + return np.mean(np.vstack((array[:-1], array[1:])), 0) + + +def centers_of_faces(array): + np = import_module('numpy') + return np.mean(np.dstack((array[:-1, :-1], + array[1:, :-1], + array[:-1, 1:], + array[:-1, :-1], + )), 2) + + +def flat(x, y, z, eps=1e-3): + """Checks whether three points are almost collinear""" + np = import_module('numpy') + # Workaround plotting piecewise (#8577): + # workaround for `lambdify` in `.experimental_lambdify` fails + # to return numerical values in some cases. Lower-level fix + # in `lambdify` is possible. + vector_a = (x - y).astype(np.float64) + vector_b = (z - y).astype(np.float64) + dot_product = np.dot(vector_a, vector_b) + vector_a_norm = np.linalg.norm(vector_a) + vector_b_norm = np.linalg.norm(vector_b) + cos_theta = dot_product / (vector_a_norm * vector_b_norm) + return abs(cos_theta + 1) < eps + + +def _matplotlib_list(interval_list): + """ + Returns lists for matplotlib ``fill`` command from a list of bounding + rectangular intervals + """ + xlist = [] + ylist = [] + if len(interval_list): + for intervals in interval_list: + intervalx = intervals[0] + intervaly = intervals[1] + xlist.extend([intervalx.start, intervalx.start, + intervalx.end, intervalx.end, None]) + ylist.extend([intervaly.start, intervaly.end, + intervaly.end, intervaly.start, None]) + else: + #XXX Ugly hack. Matplotlib does not accept empty lists for ``fill`` + xlist.extend((None, None, None, None)) + ylist.extend((None, None, None, None)) + return xlist, ylist + + +####New API for plotting module #### + +# TODO: Add color arrays for plots. +# TODO: Add more plotting options for 3d plots. +# TODO: Adaptive sampling for 3D plots. + +def plot(*args, show=True, **kwargs): + """Plots a function of a single variable as a curve. + + Parameters + ========== + + args : + The first argument is the expression representing the function + of single variable to be plotted. + + The last argument is a 3-tuple denoting the range of the free + variable. e.g. ``(x, 0, 5)`` + + Typical usage examples are in the following: + + - Plotting a single expression with a single range. + ``plot(expr, range, **kwargs)`` + - Plotting a single expression with the default range (-10, 10). + ``plot(expr, **kwargs)`` + - Plotting multiple expressions with a single range. + ``plot(expr1, expr2, ..., range, **kwargs)`` + - Plotting multiple expressions with multiple ranges. + ``plot((expr1, range1), (expr2, range2), ..., **kwargs)`` + + It is best practice to specify range explicitly because default + range may change in the future if a more advanced default range + detection algorithm is implemented. + + show : bool, optional + The default value is set to ``True``. Set show to ``False`` and + the function will not display the plot. The returned instance of + the ``Plot`` class can then be used to save or display the plot + by calling the ``save()`` and ``show()`` methods respectively. + + line_color : string, or float, or function, optional + Specifies the color for the plot. + See ``Plot`` to see how to set color for the plots. + Note that by setting ``line_color``, it would be applied simultaneously + to all the series. + + title : str, optional + Title of the plot. It is set to the latex representation of + the expression, if the plot has only one expression. + + label : str, optional + The label of the expression in the plot. It will be used when + called with ``legend``. Default is the name of the expression. + e.g. ``sin(x)`` + + xlabel : str or expression, optional + Label for the x-axis. + + ylabel : str or expression, optional + Label for the y-axis. + + xscale : 'linear' or 'log', optional + Sets the scaling of the x-axis. + + yscale : 'linear' or 'log', optional + Sets the scaling of the y-axis. + + axis_center : (float, float), optional + Tuple of two floats denoting the coordinates of the center or + {'center', 'auto'} + + xlim : (float, float), optional + Denotes the x-axis limits, ``(min, max)```. + + ylim : (float, float), optional + Denotes the y-axis limits, ``(min, max)```. + + annotations : list, optional + A list of dictionaries specifying the type of annotation + required. The keys in the dictionary should be equivalent + to the arguments of the :external:mod:`matplotlib`'s + :external:meth:`~matplotlib.axes.Axes.annotate` method. + + markers : list, optional + A list of dictionaries specifying the type the markers required. + The keys in the dictionary should be equivalent to the arguments + of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function + along with the marker related keyworded arguments. + + rectangles : list, optional + A list of dictionaries specifying the dimensions of the + rectangles to be plotted. The keys in the dictionary should be + equivalent to the arguments of the :external:mod:`matplotlib`'s + :external:class:`~matplotlib.patches.Rectangle` class. + + fill : dict, optional + A dictionary specifying the type of color filling required in + the plot. The keys in the dictionary should be equivalent to the + arguments of the :external:mod:`matplotlib`'s + :external:meth:`~matplotlib.axes.Axes.fill_between` method. + + adaptive : bool, optional + The default value is set to ``True``. Set adaptive to ``False`` + and specify ``nb_of_points`` if uniform sampling is required. + + The plotting uses an adaptive algorithm which samples + recursively to accurately plot. The adaptive algorithm uses a + random point near the midpoint of two points that has to be + further sampled. Hence the same plots can appear slightly + different. + + depth : int, optional + Recursion depth of the adaptive algorithm. A depth of value + `n` samples a maximum of `2^{n}` points. + + If the ``adaptive`` flag is set to ``False``, this will be + ignored. + + nb_of_points : int, optional + Used when the ``adaptive`` is set to ``False``. The function + is uniformly sampled at ``nb_of_points`` number of points. + + If the ``adaptive`` flag is set to ``True``, this will be + ignored. + + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of + the overall figure. The default value is set to ``None``, meaning + the size will be set by the default backend. + + Examples + ======== + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> from sympy import symbols + >>> from sympy.plotting import plot + >>> x = symbols('x') + + Single Plot + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot(x**2, (x, -5, 5)) + Plot object containing: + [0]: cartesian line: x**2 for x over (-5.0, 5.0) + + Multiple plots with single range. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot(x, x**2, x**3, (x, -5, 5)) + Plot object containing: + [0]: cartesian line: x for x over (-5.0, 5.0) + [1]: cartesian line: x**2 for x over (-5.0, 5.0) + [2]: cartesian line: x**3 for x over (-5.0, 5.0) + + Multiple plots with different ranges. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5))) + Plot object containing: + [0]: cartesian line: x**2 for x over (-6.0, 6.0) + [1]: cartesian line: x for x over (-5.0, 5.0) + + No adaptive sampling. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot(x**2, adaptive=False, nb_of_points=400) + Plot object containing: + [0]: cartesian line: x**2 for x over (-10.0, 10.0) + + See Also + ======== + + Plot, LineOver1DRangeSeries + + """ + args = list(map(sympify, args)) + free = set() + for a in args: + if isinstance(a, Expr): + free |= a.free_symbols + if len(free) > 1: + raise ValueError( + 'The same variable should be used in all ' + 'univariate expressions being plotted.') + x = free.pop() if free else Symbol('x') + kwargs.setdefault('xlabel', x) + kwargs.setdefault('ylabel', Function('f')(x)) + series = [] + plot_expr = check_arguments(args, 1, 1) + series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr] + + plots = Plot(*series, **kwargs) + if show: + plots.show() + return plots + + +def plot_parametric(*args, show=True, **kwargs): + """ + Plots a 2D parametric curve. + + Parameters + ========== + + args + Common specifications are: + + - Plotting a single parametric curve with a range + ``plot_parametric((expr_x, expr_y), range)`` + - Plotting multiple parametric curves with the same range + ``plot_parametric((expr_x, expr_y), ..., range)`` + - Plotting multiple parametric curves with different ranges + ``plot_parametric((expr_x, expr_y, range), ...)`` + + ``expr_x`` is the expression representing $x$ component of the + parametric function. + + ``expr_y`` is the expression representing $y$ component of the + parametric function. + + ``range`` is a 3-tuple denoting the parameter symbol, start and + stop. For example, ``(u, 0, 5)``. + + If the range is not specified, then a default range of (-10, 10) + is used. + + However, if the arguments are specified as + ``(expr_x, expr_y, range), ...``, you must specify the ranges + for each expressions manually. + + Default range may change in the future if a more advanced + algorithm is implemented. + + adaptive : bool, optional + Specifies whether to use the adaptive sampling or not. + + The default value is set to ``True``. Set adaptive to ``False`` + and specify ``nb_of_points`` if uniform sampling is required. + + depth : int, optional + The recursion depth of the adaptive algorithm. A depth of + value $n$ samples a maximum of $2^n$ points. + + nb_of_points : int, optional + Used when the ``adaptive`` flag is set to ``False``. + + Specifies the number of the points used for the uniform + sampling. + + line_color : string, or float, or function, optional + Specifies the color for the plot. + See ``Plot`` to see how to set color for the plots. + Note that by setting ``line_color``, it would be applied simultaneously + to all the series. + + label : str, optional + The label of the expression in the plot. It will be used when + called with ``legend``. Default is the name of the expression. + e.g. ``sin(x)`` + + xlabel : str, optional + Label for the x-axis. + + ylabel : str, optional + Label for the y-axis. + + xscale : 'linear' or 'log', optional + Sets the scaling of the x-axis. + + yscale : 'linear' or 'log', optional + Sets the scaling of the y-axis. + + axis_center : (float, float), optional + Tuple of two floats denoting the coordinates of the center or + {'center', 'auto'} + + xlim : (float, float), optional + Denotes the x-axis limits, ``(min, max)```. + + ylim : (float, float), optional + Denotes the y-axis limits, ``(min, max)```. + + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of + the overall figure. The default value is set to ``None``, meaning + the size will be set by the default backend. + + Examples + ======== + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import plot_parametric, symbols, cos, sin + >>> u = symbols('u') + + A parametric plot with a single expression: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot_parametric((cos(u), sin(u)), (u, -5, 5)) + Plot object containing: + [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0) + + A parametric plot with multiple expressions with the same range: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10)) + Plot object containing: + [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0) + [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0) + + A parametric plot with multiple expressions with different ranges + for each curve: + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot_parametric((cos(u), sin(u), (u, -5, 5)), + ... (cos(u), u, (u, -5, 5))) + Plot object containing: + [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0) + [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0) + + Notes + ===== + + The plotting uses an adaptive algorithm which samples recursively to + accurately plot the curve. The adaptive algorithm uses a random point + near the midpoint of two points that has to be further sampled. + Hence, repeating the same plot command can give slightly different + results because of the random sampling. + + If there are multiple plots, then the same optional arguments are + applied to all the plots drawn in the same canvas. If you want to + set these options separately, you can index the returned ``Plot`` + object and set it. + + For example, when you specify ``line_color`` once, it would be + applied simultaneously to both series. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> from sympy import pi + >>> expr1 = (u, cos(2*pi*u)/2 + 1/2) + >>> expr2 = (u, sin(2*pi*u)/2 + 1/2) + >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue') + + If you want to specify the line color for the specific series, you + should index each item and apply the property manually. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> p[0].line_color = 'red' + >>> p.show() + + See Also + ======== + + Plot, Parametric2DLineSeries + """ + args = list(map(sympify, args)) + series = [] + plot_expr = check_arguments(args, 2, 1) + series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr] + plots = Plot(*series, **kwargs) + if show: + plots.show() + return plots + + +def plot3d_parametric_line(*args, show=True, **kwargs): + """ + Plots a 3D parametric line plot. + + Usage + ===== + + Single plot: + + ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)`` + + If the range is not specified, then a default range of (-10, 10) is used. + + Multiple plots. + + ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)`` + + Ranges have to be specified for every expression. + + Default range may change in the future if a more advanced default range + detection algorithm is implemented. + + Arguments + ========= + + expr_x : Expression representing the function along x. + + expr_y : Expression representing the function along y. + + expr_z : Expression representing the function along z. + + range : (:class:`~.Symbol`, float, float) + A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5). + + Keyword Arguments + ================= + + Arguments for ``Parametric3DLineSeries`` class. + + nb_of_points : The range is uniformly sampled at ``nb_of_points`` + number of points. + + Aesthetics: + + line_color : string, or float, or function, optional + Specifies the color for the plot. + See ``Plot`` to see how to set color for the plots. + Note that by setting ``line_color``, it would be applied simultaneously + to all the series. + + label : str + The label to the plot. It will be used when called with ``legend=True`` + to denote the function with the given label in the plot. + + If there are multiple plots, then the same series arguments are applied to + all the plots. If you want to set these options separately, you can index + the returned ``Plot`` object and set it. + + Arguments for ``Plot`` class. + + title : str + Title of the plot. + + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of + the overall figure. The default value is set to ``None``, meaning + the size will be set by the default backend. + + Examples + ======== + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import symbols, cos, sin + >>> from sympy.plotting import plot3d_parametric_line + >>> u = symbols('u') + + Single plot. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5)) + Plot object containing: + [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0) + + + Multiple plots. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)), + ... (sin(u), u**2, u, (u, -5, 5))) + Plot object containing: + [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0) + [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0) + + + See Also + ======== + + Plot, Parametric3DLineSeries + + """ + args = list(map(sympify, args)) + series = [] + plot_expr = check_arguments(args, 3, 1) + series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr] + kwargs.setdefault("xlabel", "x") + kwargs.setdefault("ylabel", "y") + kwargs.setdefault("zlabel", "z") + plots = Plot(*series, **kwargs) + if show: + plots.show() + return plots + + +def plot3d(*args, show=True, **kwargs): + """ + Plots a 3D surface plot. + + Usage + ===== + + Single plot + + ``plot3d(expr, range_x, range_y, **kwargs)`` + + If the ranges are not specified, then a default range of (-10, 10) is used. + + Multiple plot with the same range. + + ``plot3d(expr1, expr2, range_x, range_y, **kwargs)`` + + If the ranges are not specified, then a default range of (-10, 10) is used. + + Multiple plots with different ranges. + + ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)`` + + Ranges have to be specified for every expression. + + Default range may change in the future if a more advanced default range + detection algorithm is implemented. + + Arguments + ========= + + expr : Expression representing the function along x. + + range_x : (:class:`~.Symbol`, float, float) + A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5). + + range_y : (:class:`~.Symbol`, float, float) + A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5). + + Keyword Arguments + ================= + + Arguments for ``SurfaceOver2DRangeSeries`` class: + + nb_of_points_x : int + The x range is sampled uniformly at ``nb_of_points_x`` of points. + + nb_of_points_y : int + The y range is sampled uniformly at ``nb_of_points_y`` of points. + + Aesthetics: + + surface_color : Function which returns a float + Specifies the color for the surface of the plot. + See :class:`~.Plot` for more details. + + If there are multiple plots, then the same series arguments are applied to + all the plots. If you want to set these options separately, you can index + the returned ``Plot`` object and set it. + + Arguments for ``Plot`` class: + + title : str + Title of the plot. + + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of the + overall figure. The default value is set to ``None``, meaning the size will + be set by the default backend. + + Examples + ======== + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import symbols + >>> from sympy.plotting import plot3d + >>> x, y = symbols('x y') + + Single plot + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot3d(x*y, (x, -5, 5), (y, -5, 5)) + Plot object containing: + [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) + + + Multiple plots with same range + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5)) + Plot object containing: + [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) + [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) + + + Multiple plots with different ranges. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)), + ... (x*y, (x, -3, 3), (y, -3, 3))) + Plot object containing: + [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0) + [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0) + + + See Also + ======== + + Plot, SurfaceOver2DRangeSeries + + """ + + args = list(map(sympify, args)) + series = [] + plot_expr = check_arguments(args, 1, 2) + series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr] + kwargs.setdefault("xlabel", series[0].var_x) + kwargs.setdefault("ylabel", series[0].var_y) + kwargs.setdefault("zlabel", Function('f')(series[0].var_x, series[0].var_y)) + plots = Plot(*series, **kwargs) + if show: + plots.show() + return plots + + +def plot3d_parametric_surface(*args, show=True, **kwargs): + """ + Plots a 3D parametric surface plot. + + Explanation + =========== + + Single plot. + + ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)`` + + If the ranges is not specified, then a default range of (-10, 10) is used. + + Multiple plots. + + ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)`` + + Ranges have to be specified for every expression. + + Default range may change in the future if a more advanced default range + detection algorithm is implemented. + + Arguments + ========= + + expr_x : Expression representing the function along ``x``. + + expr_y : Expression representing the function along ``y``. + + expr_z : Expression representing the function along ``z``. + + range_u : (:class:`~.Symbol`, float, float) + A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5). + + range_v : (:class:`~.Symbol`, float, float) + A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5). + + Keyword Arguments + ================= + + Arguments for ``ParametricSurfaceSeries`` class: + + nb_of_points_u : int + The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points + + nb_of_points_y : int + The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points + + Aesthetics: + + surface_color : Function which returns a float + Specifies the color for the surface of the plot. See + :class:`~Plot` for more details. + + If there are multiple plots, then the same series arguments are applied for + all the plots. If you want to set these options separately, you can index + the returned ``Plot`` object and set it. + + + Arguments for ``Plot`` class: + + title : str + Title of the plot. + + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of the + overall figure. The default value is set to ``None``, meaning the size will + be set by the default backend. + + Examples + ======== + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import symbols, cos, sin + >>> from sympy.plotting import plot3d_parametric_surface + >>> u, v = symbols('u v') + + Single plot. + + .. plot:: + :context: close-figs + :format: doctest + :include-source: True + + >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v, + ... (u, -5, 5), (v, -5, 5)) + Plot object containing: + [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0) + + + See Also + ======== + + Plot, ParametricSurfaceSeries + + """ + + args = list(map(sympify, args)) + series = [] + plot_expr = check_arguments(args, 3, 2) + series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr] + kwargs.setdefault("xlabel", "x") + kwargs.setdefault("ylabel", "y") + kwargs.setdefault("zlabel", "z") + plots = Plot(*series, **kwargs) + if show: + plots.show() + return plots + +def plot_contour(*args, show=True, **kwargs): + """ + Draws contour plot of a function + + Usage + ===== + + Single plot + + ``plot_contour(expr, range_x, range_y, **kwargs)`` + + If the ranges are not specified, then a default range of (-10, 10) is used. + + Multiple plot with the same range. + + ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)`` + + If the ranges are not specified, then a default range of (-10, 10) is used. + + Multiple plots with different ranges. + + ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)`` + + Ranges have to be specified for every expression. + + Default range may change in the future if a more advanced default range + detection algorithm is implemented. + + Arguments + ========= + + expr : Expression representing the function along x. + + range_x : (:class:`Symbol`, float, float) + A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5). + + range_y : (:class:`Symbol`, float, float) + A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5). + + Keyword Arguments + ================= + + Arguments for ``ContourSeries`` class: + + nb_of_points_x : int + The x range is sampled uniformly at ``nb_of_points_x`` of points. + + nb_of_points_y : int + The y range is sampled uniformly at ``nb_of_points_y`` of points. + + Aesthetics: + + surface_color : Function which returns a float + Specifies the color for the surface of the plot. See + :class:`sympy.plotting.Plot` for more details. + + If there are multiple plots, then the same series arguments are applied to + all the plots. If you want to set these options separately, you can index + the returned ``Plot`` object and set it. + + Arguments for ``Plot`` class: + + title : str + Title of the plot. + + size : (float, float), optional + A tuple in the form (width, height) in inches to specify the size of + the overall figure. The default value is set to ``None``, meaning + the size will be set by the default backend. + + See Also + ======== + + Plot, ContourSeries + + """ + + args = list(map(sympify, args)) + plot_expr = check_arguments(args, 1, 2) + series = [ContourSeries(*arg) for arg in plot_expr] + plot_contours = Plot(*series, **kwargs) + if len(plot_expr[0].free_symbols) > 2: + raise ValueError('Contour Plot cannot Plot for more than two variables.') + if show: + plot_contours.show() + return plot_contours + +def check_arguments(args, expr_len, nb_of_free_symbols): + """ + Checks the arguments and converts into tuples of the + form (exprs, ranges). + + Examples + ======== + + .. plot:: + :context: reset + :format: doctest + :include-source: True + + >>> from sympy import cos, sin, symbols + >>> from sympy.plotting.plot import check_arguments + >>> x = symbols('x') + >>> check_arguments([cos(x), sin(x)], 2, 1) + [(cos(x), sin(x), (x, -10, 10))] + + >>> check_arguments([x, x**2], 1, 1) + [(x, (x, -10, 10)), (x**2, (x, -10, 10))] + """ + if not args: + return [] + if expr_len > 1 and isinstance(args[0], Expr): + # Multiple expressions same range. + # The arguments are tuples when the expression length is + # greater than 1. + if len(args) < expr_len: + raise ValueError("len(args) should not be less than expr_len") + for i in range(len(args)): + if isinstance(args[i], Tuple): + break + else: + i = len(args) + 1 + + exprs = Tuple(*args[:i]) + free_symbols = list(set().union(*[e.free_symbols for e in exprs])) + if len(args) == expr_len + nb_of_free_symbols: + #Ranges given + plots = [exprs + Tuple(*args[expr_len:])] + else: + default_range = Tuple(-10, 10) + ranges = [] + for symbol in free_symbols: + ranges.append(Tuple(symbol) + default_range) + + for i in range(len(free_symbols) - nb_of_free_symbols): + ranges.append(Tuple(Dummy()) + default_range) + plots = [exprs + Tuple(*ranges)] + return plots + + if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and + len(args[0]) == expr_len and + expr_len != 3): + # Cannot handle expressions with number of expression = 3. It is + # not possible to differentiate between expressions and ranges. + #Series of plots with same range + for i in range(len(args)): + if isinstance(args[i], Tuple) and len(args[i]) != expr_len: + break + if not isinstance(args[i], Tuple): + args[i] = Tuple(args[i]) + else: + i = len(args) + 1 + + exprs = args[:i] + assert all(isinstance(e, Expr) for expr in exprs for e in expr) + free_symbols = list(set().union(*[e.free_symbols for expr in exprs + for e in expr])) + + if len(free_symbols) > nb_of_free_symbols: + raise ValueError("The number of free_symbols in the expression " + "is greater than %d" % nb_of_free_symbols) + if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple): + ranges = Tuple(*list(args[ + i:i + nb_of_free_symbols])) + plots = [expr + ranges for expr in exprs] + return plots + else: + # Use default ranges. + default_range = Tuple(-10, 10) + ranges = [] + for symbol in free_symbols: + ranges.append(Tuple(symbol) + default_range) + + for i in range(nb_of_free_symbols - len(free_symbols)): + ranges.append(Tuple(Dummy()) + default_range) + ranges = Tuple(*ranges) + plots = [expr + ranges for expr in exprs] + return plots + + elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols: + # Multiple plots with different ranges. + for arg in args: + for i in range(expr_len): + if not isinstance(arg[i], Expr): + raise ValueError("Expected an expression, given %s" % + str(arg[i])) + for i in range(nb_of_free_symbols): + if not len(arg[i + expr_len]) == 3: + raise ValueError("The ranges should be a tuple of " + "length 3, got %s" % str(arg[i + expr_len])) + return args diff --git a/shared/package-files/79/793303c287a191ae987b0d3586b665a2c2f28556e0d9e41610cade712ad5c9a3/blob b/shared/package-files/79/793303c287a191ae987b0d3586b665a2c2f28556e0d9e41610cade712ad5c9a3/blob new file mode 100644 index 0000000000000000000000000000000000000000..25dc56eef7aae040d6f74657b80c4394a95c478f --- /dev/null +++ b/shared/package-files/79/793303c287a191ae987b0d3586b665a2c2f28556e0d9e41610cade712ad5c9a3/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _foobar_out(at::Tensor & out, const at::Tensor & self, bool arg1=true, bool arg2=true, bool arg3=true); +TORCH_API at::Tensor & _foobar_outf(const at::Tensor & self, bool arg1, bool arg2, bool arg3, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/79/79331f16b5204e30849f497c222b8ac01483147779ad932b713b6d34ad00922b/blob b/shared/package-files/79/79331f16b5204e30849f497c222b8ac01483147779ad932b713b6d34ad00922b/blob new file mode 100644 index 0000000000000000000000000000000000000000..8db31fa9b3830b1e561a27a349154fc96ab071d3 --- /dev/null +++ b/shared/package-files/79/79331f16b5204e30849f497c222b8ac01483147779ad932b713b6d34ad00922b/blob @@ -0,0 +1,307 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* airy.c + * + * Airy function + * + * + * + * SYNOPSIS: + * + * double x, ai, aip, bi, bip; + * int airy(); + * + * airy( x, _&ai, _&aip, _&bi, _&bip ); + * + * + * + * DESCRIPTION: + * + * Solution of the differential equation + * + * y"(x) = xy. + * + * The function returns the two independent solutions Ai, Bi + * and their first derivatives Ai'(x), Bi'(x). + * + * Evaluation is by power series summation for small x, + * by rational minimax approximations for large x. + * + * + * + * ACCURACY: + * Error criterion is absolute when function <= 1, relative + * when function > 1, except * denotes relative error criterion. + * For large negative x, the absolute error increases as x^1.5. + * For large positive x, the relative error increases as x^1.5. + * + * Arithmetic domain function # trials peak rms + * IEEE -10, 0 Ai 10000 1.6e-15 2.7e-16 + * IEEE 0, 10 Ai 10000 2.3e-14* 1.8e-15* + * IEEE -10, 0 Ai' 10000 4.6e-15 7.6e-16 + * IEEE 0, 10 Ai' 10000 1.8e-14* 1.5e-15* + * IEEE -10, 10 Bi 30000 4.2e-15 5.3e-16 + * IEEE -10, 10 Bi' 30000 4.9e-15 7.3e-16 + * + */ +/* airy.c */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier + */ +#pragma once + +#include "../config.h" +#include "const.h" +#include "polevl.h" + +namespace xsf { +namespace cephes { + + namespace detail { + + constexpr double airy_c1 = 0.35502805388781723926; + constexpr double airy_c2 = 0.258819403792806798405; + constexpr double MAXAIRY = 103.892; + + constexpr double airy_AN[8] = { + 3.46538101525629032477E-1, 1.20075952739645805542E1, 7.62796053615234516538E1, 1.68089224934630576269E2, + 1.59756391350164413639E2, 7.05360906840444183113E1, 1.40264691163389668864E1, 9.99999999999999995305E-1, + }; + + constexpr double airy_AD[8] = { + 5.67594532638770212846E-1, 1.47562562584847203173E1, 8.45138970141474626562E1, 1.77318088145400459522E2, + 1.64234692871529701831E2, 7.14778400825575695274E1, 1.40959135607834029598E1, 1.00000000000000000470E0, + }; + + constexpr double airy_APN[8] = { + 6.13759184814035759225E-1, 1.47454670787755323881E1, 8.20584123476060982430E1, 1.71184781360976385540E2, + 1.59317847137141783523E2, 6.99778599330103016170E1, 1.39470856980481566958E1, 1.00000000000000000550E0, + }; + + constexpr double airy_APD[8] = { + 3.34203677749736953049E-1, 1.11810297306158156705E1, 7.11727352147859965283E1, 1.58778084372838313640E2, + 1.53206427475809220834E2, 6.86752304592780337944E1, 1.38498634758259442477E1, 9.99999999999999994502E-1, + }; + + constexpr double airy_BN16[5] = { + -2.53240795869364152689E-1, 5.75285167332467384228E-1, -3.29907036873225371650E-1, + 6.44404068948199951727E-2, -3.82519546641336734394E-3, + }; + + constexpr double airy_BD16[5] = { + /* 1.00000000000000000000E0, */ + -7.15685095054035237902E0, 1.06039580715664694291E1, -5.23246636471251500874E0, + 9.57395864378383833152E-1, -5.50828147163549611107E-2, + }; + + constexpr double airy_BPPN[5] = { + 4.65461162774651610328E-1, -1.08992173800493920734E0, 6.38800117371827987759E-1, + -1.26844349553102907034E-1, 7.62487844342109852105E-3, + }; + + constexpr double airy_BPPD[5] = { + /* 1.00000000000000000000E0, */ + -8.70622787633159124240E0, 1.38993162704553213172E1, -7.14116144616431159572E0, + 1.34008595960680518666E0, -7.84273211323341930448E-2, + }; + + constexpr double airy_AFN[9] = { + -1.31696323418331795333E-1, -6.26456544431912369773E-1, -6.93158036036933542233E-1, + -2.79779981545119124951E-1, -4.91900132609500318020E-2, -4.06265923594885404393E-3, + -1.59276496239262096340E-4, -2.77649108155232920844E-6, -1.67787698489114633780E-8, + }; + + constexpr double airy_AFD[9] = { + /* 1.00000000000000000000E0, */ + 1.33560420706553243746E1, 3.26825032795224613948E1, 2.67367040941499554804E1, + 9.18707402907259625840E0, 1.47529146771666414581E0, 1.15687173795188044134E-1, + 4.40291641615211203805E-3, 7.54720348287414296618E-5, 4.51850092970580378464E-7, + }; + + constexpr double airy_AGN[11] = { + 1.97339932091685679179E-2, 3.91103029615688277255E-1, 1.06579897599595591108E0, 9.39169229816650230044E-1, + 3.51465656105547619242E-1, 6.33888919628925490927E-2, 5.85804113048388458567E-3, 2.82851600836737019778E-4, + 6.98793669997260967291E-6, 8.11789239554389293311E-8, 3.41551784765923618484E-10, + }; + + constexpr double airy_AGD[10] = { + /* 1.00000000000000000000E0, */ + 9.30892908077441974853E0, 1.98352928718312140417E1, 1.55646628932864612953E1, 5.47686069422975497931E0, + 9.54293611618961883998E-1, 8.64580826352392193095E-2, 4.12656523824222607191E-3, 1.01259085116509135510E-4, + 1.17166733214413521882E-6, 4.91834570062930015649E-9, + }; + + constexpr double airy_APFN[9] = { + 1.85365624022535566142E-1, 8.86712188052584095637E-1, 9.87391981747398547272E-1, + 4.01241082318003734092E-1, 7.10304926289631174579E-2, 5.90618657995661810071E-3, + 2.33051409401776799569E-4, 4.08718778289035454598E-6, 2.48379932900442457853E-8, + }; + + constexpr double airy_APFD[9] = { + /* 1.00000000000000000000E0, */ + 1.47345854687502542552E1, 3.75423933435489594466E1, 3.14657751203046424330E1, + 1.09969125207298778536E1, 1.78885054766999417817E0, 1.41733275753662636873E-1, + 5.44066067017226003627E-3, 9.39421290654511171663E-5, 5.65978713036027009243E-7, + }; + + constexpr double airy_APGN[11] = { + -3.55615429033082288335E-2, -6.37311518129435504426E-1, -1.70856738884312371053E0, + -1.50221872117316635393E0, -5.63606665822102676611E-1, -1.02101031120216891789E-1, + -9.48396695961445269093E-3, -4.60325307486780994357E-4, -1.14300836484517375919E-5, + -1.33415518685547420648E-7, -5.63803833958893494476E-10, + }; + + constexpr double airy_APGD[11] = { + /* 1.00000000000000000000E0, */ + 9.85865801696130355144E0, 2.16401867356585941885E1, 1.73130776389749389525E1, 6.17872175280828766327E0, + 1.08848694396321495475E0, 9.95005543440888479402E-2, 4.78468199683886610842E-3, 1.18159633322838625562E-4, + 1.37480673554219441465E-6, 5.79912514929147598821E-9, + }; + + } // namespace detail + + XSF_HOST_DEVICE inline int airy(double x, double *ai, double *aip, double *bi, double *bip) { + double z, zz, t, f, g, uf, ug, k, zeta, theta; + int domflg; + + domflg = 0; + if (x > detail::MAXAIRY) { + *ai = 0; + *aip = 0; + *bi = std::numeric_limits::infinity(); + *bip = std::numeric_limits::infinity(); + return (-1); + } + + if (x < -2.09) { + domflg = 15; + t = std::sqrt(-x); + zeta = -2.0 * x * t / 3.0; + t = std::sqrt(t); + k = detail::SQRT1OPI / t; + z = 1.0 / zeta; + zz = z * z; + uf = 1.0 + zz * polevl(zz, detail::airy_AFN, 8) / p1evl(zz, detail::airy_AFD, 9); + ug = z * polevl(zz, detail::airy_AGN, 10) / p1evl(zz, detail::airy_AGD, 10); + theta = zeta + 0.25 * M_PI; + f = std::sin(theta); + g = std::cos(theta); + *ai = k * (f * uf - g * ug); + *bi = k * (g * uf + f * ug); + uf = 1.0 + zz * polevl(zz, detail::airy_APFN, 8) / p1evl(zz, detail::airy_APFD, 9); + ug = z * polevl(zz, detail::airy_APGN, 10) / p1evl(zz, detail::airy_APGD, 10); + k = detail::SQRT1OPI * t; + *aip = -k * (g * uf + f * ug); + *bip = k * (f * uf - g * ug); + return (0); + } + + if (x >= 2.09) { /* cbrt(9) */ + domflg = 5; + t = std::sqrt(x); + zeta = 2.0 * x * t / 3.0; + g = std::exp(zeta); + t = std::sqrt(t); + k = 2.0 * t * g; + z = 1.0 / zeta; + f = polevl(z, detail::airy_AN, 7) / polevl(z, detail::airy_AD, 7); + *ai = detail::SQRT1OPI * f / k; + k = -0.5 * detail::SQRT1OPI * t / g; + f = polevl(z, detail::airy_APN, 7) / polevl(z, detail::airy_APD, 7); + *aip = f * k; + + if (x > 8.3203353) { /* zeta > 16 */ + f = z * polevl(z, detail::airy_BN16, 4) / p1evl(z, detail::airy_BD16, 5); + k = detail::SQRT1OPI * g; + *bi = k * (1.0 + f) / t; + f = z * polevl(z, detail::airy_BPPN, 4) / p1evl(z, detail::airy_BPPD, 5); + *bip = k * t * (1.0 + f); + return (0); + } + } + + f = 1.0; + g = x; + t = 1.0; + uf = 1.0; + ug = x; + k = 1.0; + z = x * x * x; + while (t > detail::MACHEP) { + uf *= z; + k += 1.0; + uf /= k; + ug *= z; + k += 1.0; + ug /= k; + uf /= k; + f += uf; + k += 1.0; + ug /= k; + g += ug; + t = std::abs(uf / f); + } + uf = detail::airy_c1 * f; + ug = detail::airy_c2 * g; + if ((domflg & 1) == 0) { + *ai = uf - ug; + } + if ((domflg & 2) == 0) { + *bi = detail::SQRT3 * (uf + ug); + } + + /* the deriviative of ai */ + k = 4.0; + uf = x * x / 2.0; + ug = z / 3.0; + f = uf; + g = 1.0 + ug; + uf /= 3.0; + t = 1.0; + + while (t > detail::MACHEP) { + uf *= z; + ug /= k; + k += 1.0; + ug *= z; + uf /= k; + f += uf; + k += 1.0; + ug /= k; + uf /= k; + g += ug; + k += 1.0; + t = std::abs(ug / g); + } + + uf = detail::airy_c1 * f; + ug = detail::airy_c2 * g; + if ((domflg & 4) == 0) { + *aip = uf - ug; + } + if ((domflg & 8) == 0) { + *bip = detail::SQRT3 * (uf + ug); + }; + return (0); + } + + inline int airy(float xf, float *aif, float *aipf, float *bif, float *bipf) { + double ai; + double aip; + double bi; + double bip; + int res = cephes::airy(xf, &ai, &aip, &bi, &bip); + + *aif = ai; + *aipf = aip; + *bif = bi; + *bipf = bip; + return res; + } + +} // namespace cephes +} // namespace xsf diff --git a/shared/package-files/79/7935a1eb280fb2bc136955365da6ca7af6eedbc3ad5f8c262799233ae6749cef/blob b/shared/package-files/79/7935a1eb280fb2bc136955365da6ca7af6eedbc3ad5f8c262799233ae6749cef/blob new file mode 100644 index 0000000000000000000000000000000000000000..7234ee121436e58d1c4e7d7c7800852cdcbe6933 --- /dev/null +++ b/shared/package-files/79/7935a1eb280fb2bc136955365da6ca7af6eedbc3ad5f8c262799233ae6749cef/blob @@ -0,0 +1,75 @@ +# coding: utf-8 + +from ruamel.yaml.reader import Reader +from ruamel.yaml.scanner import Scanner, RoundTripScanner +from ruamel.yaml.parser import Parser, RoundTripParser +from ruamel.yaml.composer import Composer +from ruamel.yaml.constructor import ( + BaseConstructor, + SafeConstructor, + Constructor, + RoundTripConstructor, +) +from ruamel.yaml.resolver import VersionedResolver + +if False: # MYPY + from typing import Any, Dict, List, Union, Optional # NOQA + from ruamel.yaml.compat import StreamTextType, VersionType # NOQA + +__all__ = ['BaseLoader', 'SafeLoader', 'Loader', 'RoundTripLoader'] + + +class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, VersionedResolver): + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + self.comment_handling = None + Reader.__init__(self, stream, loader=self) + Scanner.__init__(self, loader=self) + Parser.__init__(self, loader=self) + Composer.__init__(self, loader=self) + BaseConstructor.__init__(self, loader=self) + VersionedResolver.__init__(self, version, loader=self) + + +class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, VersionedResolver): + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + self.comment_handling = None + Reader.__init__(self, stream, loader=self) + Scanner.__init__(self, loader=self) + Parser.__init__(self, loader=self) + Composer.__init__(self, loader=self) + SafeConstructor.__init__(self, loader=self) + VersionedResolver.__init__(self, version, loader=self) + + +class Loader(Reader, Scanner, Parser, Composer, Constructor, VersionedResolver): + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + self.comment_handling = None + Reader.__init__(self, stream, loader=self) + Scanner.__init__(self, loader=self) + Parser.__init__(self, loader=self) + Composer.__init__(self, loader=self) + Constructor.__init__(self, loader=self) + VersionedResolver.__init__(self, version, loader=self) + + +class RoundTripLoader( + Reader, + RoundTripScanner, + RoundTripParser, + Composer, + RoundTripConstructor, + VersionedResolver, +): + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + # self.reader = Reader.__init__(self, stream) + self.comment_handling = None # issue 385 + Reader.__init__(self, stream, loader=self) + RoundTripScanner.__init__(self, loader=self) + RoundTripParser.__init__(self, loader=self) + Composer.__init__(self, loader=self) + RoundTripConstructor.__init__(self, preserve_quotes=preserve_quotes, loader=self) + VersionedResolver.__init__(self, version, loader=self) diff --git a/shared/package-files/79/7938bc6f5e89ba669cf16231f0b2dfffd65e173038bb59e2a47314a1ce7e9723/blob b/shared/package-files/79/7938bc6f5e89ba669cf16231f0b2dfffd65e173038bb59e2a47314a1ce7e9723/blob new file mode 100644 index 0000000000000000000000000000000000000000..d4caec4bfd58a653c3d4af9e550dbda3dc50264a --- /dev/null +++ b/shared/package-files/79/7938bc6f5e89ba669cf16231f0b2dfffd65e173038bb59e2a47314a1ce7e9723/blob @@ -0,0 +1,1185 @@ +from __future__ import annotations + +from datetime import timedelta +import operator +from typing import ( + TYPE_CHECKING, + cast, +) + +import numpy as np + +from pandas._libs import ( + lib, + tslibs, +) +from pandas._libs.tslibs import ( + NaT, + NaTType, + Tick, + Timedelta, + astype_overflowsafe, + get_supported_dtype, + iNaT, + is_supported_dtype, + periods_per_second, +) +from pandas._libs.tslibs.conversion import cast_from_unit_vectorized +from pandas._libs.tslibs.fields import ( + get_timedelta_days, + get_timedelta_field, +) +from pandas._libs.tslibs.timedeltas import ( + array_to_timedelta64, + floordiv_object_array, + ints_to_pytimedelta, + parse_timedelta_unit, + truediv_object_array, +) +from pandas.compat.numpy import function as nv +from pandas.util._validators import validate_endpoints + +from pandas.core.dtypes.common import ( + TD64NS_DTYPE, + is_float_dtype, + is_integer_dtype, + is_object_dtype, + is_scalar, + is_string_dtype, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ExtensionDtype +from pandas.core.dtypes.missing import isna + +from pandas.core import ( + nanops, + roperator, +) +from pandas.core.array_algos import datetimelike_accumulations +from pandas.core.arrays import datetimelike as dtl +from pandas.core.arrays._ranges import generate_regular_range +import pandas.core.common as com +from pandas.core.ops.common import unpack_zerodim_and_defer + +if TYPE_CHECKING: + from collections.abc import Iterator + + from pandas._typing import ( + AxisInt, + DateTimeErrorChoices, + DtypeObj, + NpDtype, + Self, + npt, + ) + + from pandas import DataFrame + +import textwrap + + +def _field_accessor(name: str, alias: str, docstring: str): + def f(self) -> np.ndarray: + values = self.asi8 + if alias == "days": + result = get_timedelta_days(values, reso=self._creso) + else: + # error: Incompatible types in assignment ( + # expression has type "ndarray[Any, dtype[signedinteger[_32Bit]]]", + # variable has type "ndarray[Any, dtype[signedinteger[_64Bit]]] + result = get_timedelta_field(values, alias, reso=self._creso) # type: ignore[assignment] + if self._hasna: + result = self._maybe_mask_results( + result, fill_value=None, convert="float64" + ) + + return result + + f.__name__ = name + f.__doc__ = f"\n{docstring}\n" + return property(f) + + +class TimedeltaArray(dtl.TimelikeOps): + """ + Pandas ExtensionArray for timedelta data. + + .. warning:: + + TimedeltaArray is currently experimental, and its API may change + without warning. In particular, :attr:`TimedeltaArray.dtype` is + expected to change to be an instance of an ``ExtensionDtype`` + subclass. + + Parameters + ---------- + values : array-like + The timedelta data. + + dtype : numpy.dtype + Currently, only ``numpy.dtype("timedelta64[ns]")`` is accepted. + freq : Offset, optional + copy : bool, default False + Whether to copy the underlying array of data. + + Attributes + ---------- + None + + Methods + ------- + None + + Examples + -------- + >>> pd.arrays.TimedeltaArray._from_sequence(pd.TimedeltaIndex(['1h', '2h'])) + + ['0 days 01:00:00', '0 days 02:00:00'] + Length: 2, dtype: timedelta64[ns] + """ + + _typ = "timedeltaarray" + _internal_fill_value = np.timedelta64("NaT", "ns") + _recognized_scalars = (timedelta, np.timedelta64, Tick) + _is_recognized_dtype = lambda x: lib.is_np_dtype(x, "m") + _infer_matches = ("timedelta", "timedelta64") + + @property + def _scalar_type(self) -> type[Timedelta]: + return Timedelta + + __array_priority__ = 1000 + # define my properties & methods for delegation + _other_ops: list[str] = [] + _bool_ops: list[str] = [] + _object_ops: list[str] = ["freq"] + _field_ops: list[str] = ["days", "seconds", "microseconds", "nanoseconds"] + _datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops + ["unit"] + _datetimelike_methods: list[str] = [ + "to_pytimedelta", + "total_seconds", + "round", + "floor", + "ceil", + "as_unit", + ] + + # Note: ndim must be defined to ensure NaT.__richcmp__(TimedeltaArray) + # operates pointwise. + + def _box_func(self, x: np.timedelta64) -> Timedelta | NaTType: + y = x.view("i8") + if y == NaT._value: + return NaT + return Timedelta._from_value_and_reso(y, reso=self._creso) + + @property + # error: Return type "dtype" of "dtype" incompatible with return type + # "ExtensionDtype" in supertype "ExtensionArray" + def dtype(self) -> np.dtype[np.timedelta64]: # type: ignore[override] + """ + The dtype for the TimedeltaArray. + + .. warning:: + + A future version of pandas will change dtype to be an instance + of a :class:`pandas.api.extensions.ExtensionDtype` subclass, + not a ``numpy.dtype``. + + Returns + ------- + numpy.dtype + """ + return self._ndarray.dtype + + # ---------------------------------------------------------------- + # Constructors + + _freq = None + _default_dtype = TD64NS_DTYPE # used in TimeLikeOps.__init__ + + @classmethod + def _validate_dtype(cls, values, dtype): + # used in TimeLikeOps.__init__ + dtype = _validate_td64_dtype(dtype) + _validate_td64_dtype(values.dtype) + if dtype != values.dtype: + raise ValueError("Values resolution does not match dtype.") + return dtype + + # error: Signature of "_simple_new" incompatible with supertype "NDArrayBacked" + @classmethod + def _simple_new( # type: ignore[override] + cls, + values: npt.NDArray[np.timedelta64], + freq: Tick | None = None, + dtype: np.dtype[np.timedelta64] = TD64NS_DTYPE, + ) -> Self: + # Require td64 dtype, not unit-less, matching values.dtype + assert lib.is_np_dtype(dtype, "m") + assert not tslibs.is_unitless(dtype) + assert isinstance(values, np.ndarray), type(values) + assert dtype == values.dtype + assert freq is None or isinstance(freq, Tick) + + result = super()._simple_new(values=values, dtype=dtype) + result._freq = freq + return result + + @classmethod + def _from_sequence(cls, data, *, dtype=None, copy: bool = False) -> Self: + if dtype: + dtype = _validate_td64_dtype(dtype) + + data, freq = sequence_to_td64ns(data, copy=copy, unit=None) + + if dtype is not None: + data = astype_overflowsafe(data, dtype=dtype, copy=False) + + return cls._simple_new(data, dtype=data.dtype, freq=freq) + + @classmethod + def _from_sequence_not_strict( + cls, + data, + *, + dtype=None, + copy: bool = False, + freq=lib.no_default, + unit=None, + ) -> Self: + """ + _from_sequence_not_strict but without responsibility for finding the + result's `freq`. + """ + if dtype: + dtype = _validate_td64_dtype(dtype) + + assert unit not in ["Y", "y", "M"] # caller is responsible for checking + + data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=unit) + + if dtype is not None: + data = astype_overflowsafe(data, dtype=dtype, copy=False) + + result = cls._simple_new(data, dtype=data.dtype, freq=inferred_freq) + + result._maybe_pin_freq(freq, {}) + return result + + @classmethod + def _generate_range( + cls, start, end, periods, freq, closed=None, *, unit: str | None = None + ) -> Self: + periods = dtl.validate_periods(periods) + if freq is None and any(x is None for x in [periods, start, end]): + raise ValueError("Must provide freq argument if no data is supplied") + + if com.count_not_none(start, end, periods, freq) != 3: + raise ValueError( + "Of the four parameters: start, end, periods, " + "and freq, exactly three must be specified" + ) + + if start is not None: + start = Timedelta(start).as_unit("ns") + + if end is not None: + end = Timedelta(end).as_unit("ns") + + if unit is not None: + if unit not in ["s", "ms", "us", "ns"]: + raise ValueError("'unit' must be one of 's', 'ms', 'us', 'ns'") + else: + unit = "ns" + + if start is not None and unit is not None: + start = start.as_unit(unit, round_ok=False) + if end is not None and unit is not None: + end = end.as_unit(unit, round_ok=False) + + left_closed, right_closed = validate_endpoints(closed) + + if freq is not None: + index = generate_regular_range(start, end, periods, freq, unit=unit) + else: + index = np.linspace(start._value, end._value, periods).astype("i8") + + if not left_closed: + index = index[1:] + if not right_closed: + index = index[:-1] + + td64values = index.view(f"m8[{unit}]") + return cls._simple_new(td64values, dtype=td64values.dtype, freq=freq) + + # ---------------------------------------------------------------- + # DatetimeLike Interface + + def _unbox_scalar(self, value) -> np.timedelta64: + if not isinstance(value, self._scalar_type) and value is not NaT: + raise ValueError("'value' should be a Timedelta.") + self._check_compatible_with(value) + if value is NaT: + return np.timedelta64(value._value, self.unit) + else: + return value.as_unit(self.unit).asm8 + + def _scalar_from_string(self, value) -> Timedelta | NaTType: + return Timedelta(value) + + def _check_compatible_with(self, other) -> None: + # we don't have anything to validate. + pass + + # ---------------------------------------------------------------- + # Array-Like / EA-Interface Methods + + def astype(self, dtype, copy: bool = True): + # We handle + # --> timedelta64[ns] + # --> timedelta64 + # DatetimeLikeArrayMixin super call handles other cases + dtype = pandas_dtype(dtype) + + if lib.is_np_dtype(dtype, "m"): + if dtype == self.dtype: + if copy: + return self.copy() + return self + + if is_supported_dtype(dtype): + # unit conversion e.g. timedelta64[s] + res_values = astype_overflowsafe(self._ndarray, dtype, copy=False) + return type(self)._simple_new( + res_values, dtype=res_values.dtype, freq=self.freq + ) + else: + raise ValueError( + f"Cannot convert from {self.dtype} to {dtype}. " + "Supported resolutions are 's', 'ms', 'us', 'ns'" + ) + + return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy) + + def __iter__(self) -> Iterator: + if self.ndim > 1: + for i in range(len(self)): + yield self[i] + else: + # convert in chunks of 10k for efficiency + data = self._ndarray + length = len(self) + chunksize = 10000 + chunks = (length // chunksize) + 1 + for i in range(chunks): + start_i = i * chunksize + end_i = min((i + 1) * chunksize, length) + converted = ints_to_pytimedelta(data[start_i:end_i], box=True) + yield from converted + + # ---------------------------------------------------------------- + # Reductions + + def sum( + self, + *, + axis: AxisInt | None = None, + dtype: NpDtype | None = None, + out=None, + keepdims: bool = False, + initial=None, + skipna: bool = True, + min_count: int = 0, + ): + nv.validate_sum( + (), {"dtype": dtype, "out": out, "keepdims": keepdims, "initial": initial} + ) + + result = nanops.nansum( + self._ndarray, axis=axis, skipna=skipna, min_count=min_count + ) + return self._wrap_reduction_result(axis, result) + + def std( + self, + *, + axis: AxisInt | None = None, + dtype: NpDtype | None = None, + out=None, + ddof: int = 1, + keepdims: bool = False, + skipna: bool = True, + ): + nv.validate_stat_ddof_func( + (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="std" + ) + + result = nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) + if axis is None or self.ndim == 1: + return self._box_func(result) + return self._from_backing_data(result) + + # ---------------------------------------------------------------- + # Accumulations + + def _accumulate(self, name: str, *, skipna: bool = True, **kwargs): + if name == "cumsum": + op = getattr(datetimelike_accumulations, name) + result = op(self._ndarray.copy(), skipna=skipna, **kwargs) + + return type(self)._simple_new(result, freq=None, dtype=self.dtype) + elif name == "cumprod": + raise TypeError("cumprod not supported for Timedelta.") + + else: + return super()._accumulate(name, skipna=skipna, **kwargs) + + # ---------------------------------------------------------------- + # Rendering Methods + + def _formatter(self, boxed: bool = False): + from pandas.io.formats.format import get_format_timedelta64 + + return get_format_timedelta64(self, box=True) + + def _format_native_types( + self, *, na_rep: str | float = "NaT", date_format=None, **kwargs + ) -> npt.NDArray[np.object_]: + from pandas.io.formats.format import get_format_timedelta64 + + # Relies on TimeDelta._repr_base + formatter = get_format_timedelta64(self, na_rep) + # equiv: np.array([formatter(x) for x in self._ndarray]) + # but independent of dimension + return np.frompyfunc(formatter, 1, 1)(self._ndarray) + + # ---------------------------------------------------------------- + # Arithmetic Methods + + def _add_offset(self, other): + assert not isinstance(other, Tick) + raise TypeError( + f"cannot add the type {type(other).__name__} to a {type(self).__name__}" + ) + + @unpack_zerodim_and_defer("__mul__") + def __mul__(self, other) -> Self: + if is_scalar(other): + # numpy will accept float and int, raise TypeError for others + result = self._ndarray * other + if result.dtype.kind != "m": + # numpy >= 2.1 may not raise a TypeError + # and seems to dispatch to others.__rmul__? + raise TypeError(f"Cannot multiply with {type(other).__name__}") + freq = None + if self.freq is not None and not isna(other): + freq = self.freq * other + if freq.n == 0: + # GH#51575 Better to have no freq than an incorrect one + freq = None + return type(self)._simple_new(result, dtype=result.dtype, freq=freq) + + if not hasattr(other, "dtype"): + # list, tuple + other = np.array(other) + if len(other) != len(self) and not lib.is_np_dtype(other.dtype, "m"): + # Exclude timedelta64 here so we correctly raise TypeError + # for that instead of ValueError + raise ValueError("Cannot multiply with unequal lengths") + + if is_object_dtype(other.dtype): + # this multiplication will succeed only if all elements of other + # are int or float scalars, so we will end up with + # timedelta64[ns]-dtyped result + arr = self._ndarray + result = [arr[n] * other[n] for n in range(len(self))] + result = np.array(result) + return type(self)._simple_new(result, dtype=result.dtype) + + # numpy will accept float or int dtype, raise TypeError for others + result = self._ndarray * other + if result.dtype.kind != "m": + # numpy >= 2.1 may not raise a TypeError + # and seems to dispatch to others.__rmul__? + raise TypeError(f"Cannot multiply with {type(other).__name__}") + return type(self)._simple_new(result, dtype=result.dtype) + + __rmul__ = __mul__ + + def _scalar_divlike_op(self, other, op): + """ + Shared logic for __truediv__, __rtruediv__, __floordiv__, __rfloordiv__ + with scalar 'other'. + """ + if isinstance(other, self._recognized_scalars): + other = Timedelta(other) + # mypy assumes that __new__ returns an instance of the class + # github.com/python/mypy/issues/1020 + if cast("Timedelta | NaTType", other) is NaT: + # specifically timedelta64-NaT + res = np.empty(self.shape, dtype=np.float64) + res.fill(np.nan) + return res + + # otherwise, dispatch to Timedelta implementation + return op(self._ndarray, other) + + else: + # caller is responsible for checking lib.is_scalar(other) + # assume other is numeric, otherwise numpy will raise + + if op in [roperator.rtruediv, roperator.rfloordiv]: + raise TypeError( + f"Cannot divide {type(other).__name__} by {type(self).__name__}" + ) + + result = op(self._ndarray, other) + freq = None + + if self.freq is not None: + # Note: freq gets division, not floor-division, even if op + # is floordiv. + freq = self.freq / other + if freq.nanos == 0 and self.freq.nanos != 0: + # e.g. if self.freq is Nano(1) then dividing by 2 + # rounds down to zero + freq = None + + return type(self)._simple_new(result, dtype=result.dtype, freq=freq) + + def _cast_divlike_op(self, other): + if not hasattr(other, "dtype"): + # e.g. list, tuple + other = np.array(other) + + if len(other) != len(self): + raise ValueError("Cannot divide vectors with unequal lengths") + return other + + def _vector_divlike_op(self, other, op) -> np.ndarray | Self: + """ + Shared logic for __truediv__, __floordiv__, and their reversed versions + with timedelta64-dtype ndarray other. + """ + # Let numpy handle it + result = op(self._ndarray, np.asarray(other)) + + if (is_integer_dtype(other.dtype) or is_float_dtype(other.dtype)) and op in [ + operator.truediv, + operator.floordiv, + ]: + return type(self)._simple_new(result, dtype=result.dtype) + + if op in [operator.floordiv, roperator.rfloordiv]: + mask = self.isna() | isna(other) + if mask.any(): + result = result.astype(np.float64) + np.putmask(result, mask, np.nan) + + return result + + @unpack_zerodim_and_defer("__truediv__") + def __truediv__(self, other): + # timedelta / X is well-defined for timedelta-like or numeric X + op = operator.truediv + if is_scalar(other): + return self._scalar_divlike_op(other, op) + + other = self._cast_divlike_op(other) + if ( + lib.is_np_dtype(other.dtype, "m") + or is_integer_dtype(other.dtype) + or is_float_dtype(other.dtype) + ): + return self._vector_divlike_op(other, op) + + if is_object_dtype(other.dtype): + other = np.asarray(other) + if self.ndim > 1: + res_cols = [left / right for left, right in zip(self, other)] + res_cols2 = [x.reshape(1, -1) for x in res_cols] + result = np.concatenate(res_cols2, axis=0) + else: + result = truediv_object_array(self._ndarray, other) + + return result + + else: + return NotImplemented + + @unpack_zerodim_and_defer("__rtruediv__") + def __rtruediv__(self, other): + # X / timedelta is defined only for timedelta-like X + op = roperator.rtruediv + if is_scalar(other): + return self._scalar_divlike_op(other, op) + + other = self._cast_divlike_op(other) + if lib.is_np_dtype(other.dtype, "m"): + return self._vector_divlike_op(other, op) + + elif is_object_dtype(other.dtype): + # Note: unlike in __truediv__, we do not _need_ to do type + # inference on the result. It does not raise, a numeric array + # is returned. GH#23829 + result_list = [other[n] / self[n] for n in range(len(self))] + return np.array(result_list) + + else: + return NotImplemented + + @unpack_zerodim_and_defer("__floordiv__") + def __floordiv__(self, other): + op = operator.floordiv + if is_scalar(other): + return self._scalar_divlike_op(other, op) + + other = self._cast_divlike_op(other) + if ( + lib.is_np_dtype(other.dtype, "m") + or is_integer_dtype(other.dtype) + or is_float_dtype(other.dtype) + ): + return self._vector_divlike_op(other, op) + + elif is_object_dtype(other.dtype): + other = np.asarray(other) + if self.ndim > 1: + res_cols = [left // right for left, right in zip(self, other)] + res_cols2 = [x.reshape(1, -1) for x in res_cols] + result = np.concatenate(res_cols2, axis=0) + else: + result = floordiv_object_array(self._ndarray, other) + + assert result.dtype == object + return result + + else: + return NotImplemented + + @unpack_zerodim_and_defer("__rfloordiv__") + def __rfloordiv__(self, other): + op = roperator.rfloordiv + if is_scalar(other): + return self._scalar_divlike_op(other, op) + + other = self._cast_divlike_op(other) + if lib.is_np_dtype(other.dtype, "m"): + return self._vector_divlike_op(other, op) + + elif is_object_dtype(other.dtype): + result_list = [other[n] // self[n] for n in range(len(self))] + result = np.array(result_list) + return result + + else: + return NotImplemented + + @unpack_zerodim_and_defer("__mod__") + def __mod__(self, other): + # Note: This is a naive implementation, can likely be optimized + if isinstance(other, self._recognized_scalars): + other = Timedelta(other) + return self - (self // other) * other + + @unpack_zerodim_and_defer("__rmod__") + def __rmod__(self, other): + # Note: This is a naive implementation, can likely be optimized + if isinstance(other, self._recognized_scalars): + other = Timedelta(other) + return other - (other // self) * self + + @unpack_zerodim_and_defer("__divmod__") + def __divmod__(self, other): + # Note: This is a naive implementation, can likely be optimized + if isinstance(other, self._recognized_scalars): + other = Timedelta(other) + + res1 = self // other + res2 = self - res1 * other + return res1, res2 + + @unpack_zerodim_and_defer("__rdivmod__") + def __rdivmod__(self, other): + # Note: This is a naive implementation, can likely be optimized + if isinstance(other, self._recognized_scalars): + other = Timedelta(other) + + res1 = other // self + res2 = other - res1 * self + return res1, res2 + + def __neg__(self) -> TimedeltaArray: + freq = None + if self.freq is not None: + freq = -self.freq + return type(self)._simple_new(-self._ndarray, dtype=self.dtype, freq=freq) + + def __pos__(self) -> TimedeltaArray: + return type(self)._simple_new( + self._ndarray.copy(), dtype=self.dtype, freq=self.freq + ) + + def __abs__(self) -> TimedeltaArray: + # Note: freq is not preserved + return type(self)._simple_new(np.abs(self._ndarray), dtype=self.dtype) + + # ---------------------------------------------------------------- + # Conversion Methods - Vectorized analogues of Timedelta methods + + def total_seconds(self) -> npt.NDArray[np.float64]: + """ + Return total duration of each element expressed in seconds. + + This method is available directly on TimedeltaArray, TimedeltaIndex + and on Series containing timedelta values under the ``.dt`` namespace. + + Returns + ------- + ndarray, Index or Series + When the calling object is a TimedeltaArray, the return type + is ndarray. When the calling object is a TimedeltaIndex, + the return type is an Index with a float64 dtype. When the calling object + is a Series, the return type is Series of type `float64` whose + index is the same as the original. + + See Also + -------- + datetime.timedelta.total_seconds : Standard library version + of this method. + TimedeltaIndex.components : Return a DataFrame with components of + each Timedelta. + + Examples + -------- + **Series** + + >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d')) + >>> s + 0 0 days + 1 1 days + 2 2 days + 3 3 days + 4 4 days + dtype: timedelta64[ns] + + >>> s.dt.total_seconds() + 0 0.0 + 1 86400.0 + 2 172800.0 + 3 259200.0 + 4 345600.0 + dtype: float64 + + **TimedeltaIndex** + + >>> idx = pd.to_timedelta(np.arange(5), unit='d') + >>> idx + TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], + dtype='timedelta64[ns]', freq=None) + + >>> idx.total_seconds() + Index([0.0, 86400.0, 172800.0, 259200.0, 345600.0], dtype='float64') + """ + pps = periods_per_second(self._creso) + return self._maybe_mask_results(self.asi8 / pps, fill_value=None) + + def to_pytimedelta(self) -> npt.NDArray[np.object_]: + """ + Return an ndarray of datetime.timedelta objects. + + Returns + ------- + numpy.ndarray + + Examples + -------- + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='D') + >>> tdelta_idx + TimedeltaIndex(['1 days', '2 days', '3 days'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.to_pytimedelta() + array([datetime.timedelta(days=1), datetime.timedelta(days=2), + datetime.timedelta(days=3)], dtype=object) + """ + return ints_to_pytimedelta(self._ndarray) + + days_docstring = textwrap.dedent( + """Number of days for each element. + + Examples + -------- + For Series: + + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='d')) + >>> ser + 0 1 days + 1 2 days + 2 3 days + dtype: timedelta64[ns] + >>> ser.dt.days + 0 1 + 1 2 + 2 3 + dtype: int64 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta(["0 days", "10 days", "20 days"]) + >>> tdelta_idx + TimedeltaIndex(['0 days', '10 days', '20 days'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.days + Index([0, 10, 20], dtype='int64')""" + ) + days = _field_accessor("days", "days", days_docstring) + + seconds_docstring = textwrap.dedent( + """Number of seconds (>= 0 and less than 1 day) for each element. + + Examples + -------- + For Series: + + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='s')) + >>> ser + 0 0 days 00:00:01 + 1 0 days 00:00:02 + 2 0 days 00:00:03 + dtype: timedelta64[ns] + >>> ser.dt.seconds + 0 1 + 1 2 + 2 3 + dtype: int32 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='s') + >>> tdelta_idx + TimedeltaIndex(['0 days 00:00:01', '0 days 00:00:02', '0 days 00:00:03'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.seconds + Index([1, 2, 3], dtype='int32')""" + ) + seconds = _field_accessor( + "seconds", + "seconds", + seconds_docstring, + ) + + microseconds_docstring = textwrap.dedent( + """Number of microseconds (>= 0 and less than 1 second) for each element. + + Examples + -------- + For Series: + + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='us')) + >>> ser + 0 0 days 00:00:00.000001 + 1 0 days 00:00:00.000002 + 2 0 days 00:00:00.000003 + dtype: timedelta64[ns] + >>> ser.dt.microseconds + 0 1 + 1 2 + 2 3 + dtype: int32 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='us') + >>> tdelta_idx + TimedeltaIndex(['0 days 00:00:00.000001', '0 days 00:00:00.000002', + '0 days 00:00:00.000003'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.microseconds + Index([1, 2, 3], dtype='int32')""" + ) + microseconds = _field_accessor( + "microseconds", + "microseconds", + microseconds_docstring, + ) + + nanoseconds_docstring = textwrap.dedent( + """Number of nanoseconds (>= 0 and less than 1 microsecond) for each element. + + Examples + -------- + For Series: + + >>> ser = pd.Series(pd.to_timedelta([1, 2, 3], unit='ns')) + >>> ser + 0 0 days 00:00:00.000000001 + 1 0 days 00:00:00.000000002 + 2 0 days 00:00:00.000000003 + dtype: timedelta64[ns] + >>> ser.dt.nanoseconds + 0 1 + 1 2 + 2 3 + dtype: int32 + + For TimedeltaIndex: + + >>> tdelta_idx = pd.to_timedelta([1, 2, 3], unit='ns') + >>> tdelta_idx + TimedeltaIndex(['0 days 00:00:00.000000001', '0 days 00:00:00.000000002', + '0 days 00:00:00.000000003'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.nanoseconds + Index([1, 2, 3], dtype='int32')""" + ) + nanoseconds = _field_accessor( + "nanoseconds", + "nanoseconds", + nanoseconds_docstring, + ) + + @property + def components(self) -> DataFrame: + """ + Return a DataFrame of the individual resolution components of the Timedeltas. + + The components (days, hours, minutes seconds, milliseconds, microseconds, + nanoseconds) are returned as columns in a DataFrame. + + Returns + ------- + DataFrame + + Examples + -------- + >>> tdelta_idx = pd.to_timedelta(['1 day 3 min 2 us 42 ns']) + >>> tdelta_idx + TimedeltaIndex(['1 days 00:03:00.000002042'], + dtype='timedelta64[ns]', freq=None) + >>> tdelta_idx.components + days hours minutes seconds milliseconds microseconds nanoseconds + 0 1 0 3 0 0 2 42 + """ + from pandas import DataFrame + + columns = [ + "days", + "hours", + "minutes", + "seconds", + "milliseconds", + "microseconds", + "nanoseconds", + ] + hasnans = self._hasna + if hasnans: + + def f(x): + if isna(x): + return [np.nan] * len(columns) + return x.components + + else: + + def f(x): + return x.components + + result = DataFrame([f(x) for x in self], columns=columns) + if not hasnans: + result = result.astype("int64") + return result + + +# --------------------------------------------------------------------- +# Constructor Helpers + + +def sequence_to_td64ns( + data, + copy: bool = False, + unit=None, + errors: DateTimeErrorChoices = "raise", +) -> tuple[np.ndarray, Tick | None]: + """ + Parameters + ---------- + data : list-like + copy : bool, default False + unit : str, optional + The timedelta unit to treat integers as multiples of. For numeric + data this defaults to ``'ns'``. + Must be un-specified if the data contains a str and ``errors=="raise"``. + errors : {"raise", "coerce", "ignore"}, default "raise" + How to handle elements that cannot be converted to timedelta64[ns]. + See ``pandas.to_timedelta`` for details. + + Returns + ------- + converted : numpy.ndarray + The sequence converted to a numpy array with dtype ``timedelta64[ns]``. + inferred_freq : Tick or None + The inferred frequency of the sequence. + + Raises + ------ + ValueError : Data cannot be converted to timedelta64[ns]. + + Notes + ----- + Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause + errors to be ignored; they are caught and subsequently ignored at a + higher level. + """ + assert unit not in ["Y", "y", "M"] # caller is responsible for checking + + inferred_freq = None + if unit is not None: + unit = parse_timedelta_unit(unit) + + data, copy = dtl.ensure_arraylike_for_datetimelike( + data, copy, cls_name="TimedeltaArray" + ) + + if isinstance(data, TimedeltaArray): + inferred_freq = data.freq + + # Convert whatever we have into timedelta64[ns] dtype + if data.dtype == object or is_string_dtype(data.dtype): + # no need to make a copy, need to convert if string-dtyped + data = _objects_to_td64ns(data, unit=unit, errors=errors) + copy = False + + elif is_integer_dtype(data.dtype): + # treat as multiples of the given unit + data, copy_made = _ints_to_td64ns(data, unit=unit) + copy = copy and not copy_made + + elif is_float_dtype(data.dtype): + # cast the unit, multiply base/frac separately + # to avoid precision issues from float -> int + if isinstance(data.dtype, ExtensionDtype): + mask = data._mask + data = data._data + else: + mask = np.isnan(data) + + data = cast_from_unit_vectorized(data, unit or "ns") + data[mask] = iNaT + data = data.view("m8[ns]") + copy = False + + elif lib.is_np_dtype(data.dtype, "m"): + if not is_supported_dtype(data.dtype): + # cast to closest supported unit, i.e. s or ns + new_dtype = get_supported_dtype(data.dtype) + data = astype_overflowsafe(data, dtype=new_dtype, copy=False) + copy = False + + else: + # This includes datetime64-dtype, see GH#23539, GH#29794 + raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]") + + if not copy: + data = np.asarray(data) + else: + data = np.array(data, copy=copy) + + assert data.dtype.kind == "m" + assert data.dtype != "m8" # i.e. not unit-less + + return data, inferred_freq + + +def _ints_to_td64ns(data, unit: str = "ns"): + """ + Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating + the integers as multiples of the given timedelta unit. + + Parameters + ---------- + data : numpy.ndarray with integer-dtype + unit : str, default "ns" + The timedelta unit to treat integers as multiples of. + + Returns + ------- + numpy.ndarray : timedelta64[ns] array converted from data + bool : whether a copy was made + """ + copy_made = False + unit = unit if unit is not None else "ns" + + if data.dtype != np.int64: + # converting to int64 makes a copy, so we can avoid + # re-copying later + data = data.astype(np.int64) + copy_made = True + + if unit != "ns": + dtype_str = f"timedelta64[{unit}]" + data = data.view(dtype_str) + + data = astype_overflowsafe(data, dtype=TD64NS_DTYPE) + + # the astype conversion makes a copy, so we can avoid re-copying later + copy_made = True + + else: + data = data.view("timedelta64[ns]") + + return data, copy_made + + +def _objects_to_td64ns(data, unit=None, errors: DateTimeErrorChoices = "raise"): + """ + Convert a object-dtyped or string-dtyped array into an + timedelta64[ns]-dtyped array. + + Parameters + ---------- + data : ndarray or Index + unit : str, default "ns" + The timedelta unit to treat integers as multiples of. + Must not be specified if the data contains a str. + errors : {"raise", "coerce", "ignore"}, default "raise" + How to handle elements that cannot be converted to timedelta64[ns]. + See ``pandas.to_timedelta`` for details. + + Returns + ------- + numpy.ndarray : timedelta64[ns] array converted from data + + Raises + ------ + ValueError : Data cannot be converted to timedelta64[ns]. + + Notes + ----- + Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause + errors to be ignored; they are caught and subsequently ignored at a + higher level. + """ + # coerce Index to np.ndarray, converting string-dtype if necessary + values = np.asarray(data, dtype=np.object_) + + result = array_to_timedelta64(values, unit=unit, errors=errors) + return result.view("timedelta64[ns]") + + +def _validate_td64_dtype(dtype) -> DtypeObj: + dtype = pandas_dtype(dtype) + if dtype == np.dtype("m8"): + # no precision disallowed GH#24806 + msg = ( + "Passing in 'timedelta' dtype with no precision is not allowed. " + "Please pass in 'timedelta64[ns]' instead." + ) + raise ValueError(msg) + + if not lib.is_np_dtype(dtype, "m"): + raise ValueError(f"dtype '{dtype}' is invalid, should be np.timedelta64 dtype") + elif not is_supported_dtype(dtype): + raise ValueError("Supported timedelta64 resolutions are 's', 'ms', 'us', 'ns'") + + return dtype diff --git a/shared/package-files/79/793b444a7da9b68f1ae786f30619c080517e481f240747a9664f9c84a54c7f19/blob b/shared/package-files/79/793b444a7da9b68f1ae786f30619c080517e481f240747a9664f9c84a54c7f19/blob new file mode 100644 index 0000000000000000000000000000000000000000..40e827043df99239ef732e147bd447e1fb14b2f2 --- /dev/null +++ b/shared/package-files/79/793b444a7da9b68f1ae786f30619c080517e481f240747a9664f9c84a54c7f19/blob @@ -0,0 +1,235 @@ +import numba +import numpy as np +import heapq + +from scipy.sparse import coo_matrix +from scipy.sparse.csgraph import connected_components +from itertools import combinations + +import pynndescent.distances as pynnd_dist +import joblib + +from pynndescent.utils import ( + rejection_sample, + make_heap, + deheap_sort, + simple_heap_push, + has_been_visited, + mark_visited, +) + +FLOAT32_EPS = np.finfo(np.float32).eps + + +def create_component_search(index): + alternative_dot = pynnd_dist.alternative_dot + alternative_cosine = pynnd_dist.alternative_cosine + + data = index._raw_data + indptr = index._search_graph.indptr + indices = index._search_graph.indices + dist = index._distance_func + + @numba.njit( + fastmath=True, + nogil=True, + locals={ + "current_query": numba.types.float32[::1], + "i": numba.types.uint32, + "j": numba.types.uint32, + "heap_priorities": numba.types.float32[::1], + "heap_indices": numba.types.int32[::1], + "candidate": numba.types.int32, + "vertex": numba.types.int32, + "d": numba.types.float32, + "d_vertex": numba.types.float32, + "visited": numba.types.uint8[::1], + "indices": numba.types.int32[::1], + "indptr": numba.types.int32[::1], + "data": numba.types.float32[:, ::1], + "heap_size": numba.types.int16, + "distance_scale": numba.types.float32, + "distance_bound": numba.types.float32, + "seed_scale": numba.types.float32, + }, + ) + def custom_search_closure(query_points, candidate_indices, k, epsilon, visited): + result = make_heap(query_points.shape[0], k) + distance_scale = 1.0 + epsilon + + for i in range(query_points.shape[0]): + visited[:] = 0 + if dist == alternative_dot or dist == alternative_cosine: + norm = np.sqrt((query_points[i] ** 2).sum()) + if norm > 0.0: + current_query = query_points[i] / norm + else: + continue + else: + current_query = query_points[i] + + heap_priorities = result[1][i] + heap_indices = result[0][i] + seed_set = [(np.float32(np.inf), np.int32(-1)) for j in range(0)] + + ############ Init ################ + n_initial_points = candidate_indices.shape[0] + + for j in range(n_initial_points): + candidate = np.int32(candidate_indices[j]) + d = dist(data[candidate], current_query) + # indices are guaranteed different + simple_heap_push(heap_priorities, heap_indices, d, candidate) + heapq.heappush(seed_set, (d, candidate)) + mark_visited(visited, candidate) + + ############ Search ############## + distance_bound = distance_scale * heap_priorities[0] + + # Find smallest seed point + d_vertex, vertex = heapq.heappop(seed_set) + + while d_vertex < distance_bound: + + for j in range(indptr[vertex], indptr[vertex + 1]): + + candidate = indices[j] + + if has_been_visited(visited, candidate) == 0: + mark_visited(visited, candidate) + + d = dist(data[candidate], current_query) + + if d < distance_bound: + simple_heap_push( + heap_priorities, heap_indices, d, candidate + ) + heapq.heappush(seed_set, (d, candidate)) + # Update bound + distance_bound = distance_scale * heap_priorities[0] + + # find new smallest seed point + if len(seed_set) == 0: + break + else: + d_vertex, vertex = heapq.heappop(seed_set) + + return result + + return custom_search_closure + + +# @numba.njit(nogil=True) +def find_component_connection_edge( + component1, + component2, + search_closure, + raw_data, + visited, + rng_state, + search_size=10, + epsilon=0.0, +): + indices = [np.zeros(1, dtype=np.int64) for i in range(2)] + indices[0] = component1[ + rejection_sample(np.int64(search_size), component1.shape[0], rng_state) + ] + indices[1] = component2[ + rejection_sample(np.int64(search_size), component2.shape[0], rng_state) + ] + query_side = 0 + query_points = raw_data[indices[query_side]] + candidate_indices = indices[1 - query_side].copy() + changed = [True, True] + best_dist = np.inf + best_edge = (indices[0][0], indices[1][0]) + + while changed[0] or changed[1]: + inds, dists, _ = search_closure( + query_points, candidate_indices, search_size, epsilon, visited + ) + inds, dists = deheap_sort(inds, dists) + for i in range(dists.shape[0]): + for j in range(dists.shape[1]): + if dists[i, j] < best_dist: + best_dist = dists[i, j] + best_edge = (indices[query_side][i], inds[i, j]) + candidate_indices = indices[query_side] + new_indices = np.unique(inds[:, 0]) + if indices[1 - query_side].shape[0] == new_indices.shape[0]: + changed[1 - query_side] = np.any(indices[1 - query_side] != new_indices) + indices[1 - query_side] = new_indices + query_points = raw_data[indices[1 - query_side]] + query_side = 1 - query_side + + return best_edge[0], best_edge[1], best_dist + + +def adjacency_matrix_representation(neighbor_indices, neighbor_distances): + result = coo_matrix( + (neighbor_indices.shape[0], neighbor_indices.shape[0]), dtype=np.float32 + ) + + # Preserve any distance 0 points + neighbor_distances[neighbor_distances == 0.0] = FLOAT32_EPS + + result.row = np.repeat( + np.arange(neighbor_indices.shape[0], dtype=np.int32), neighbor_indices.shape[1] + ) + result.col = neighbor_indices.ravel() + result.data = neighbor_distances.ravel() + + # Get rid of any -1 index entries + result = result.tocsr() + result.data[result.indices == -1] = 0.0 + result.eliminate_zeros() + + # Symmetrize + result = result.maximum(result.T) + + return result + + +def connect_graph(graph, index, search_size=10, n_jobs=None): + + search_closure = create_component_search(index) + n_components, component_ids = connected_components(graph) + result = graph.tolil() + + # Translate component ids into internal vertex order + component_ids = component_ids[index._vertex_order] + + def new_edge(c1, c2): + component1 = np.where(component_ids == c1)[0] + component2 = np.where(component_ids == c2)[0] + + i, j, d = find_component_connection_edge( + component1, + component2, + search_closure, + index._raw_data, + index._visited, + index.rng_state, + search_size=search_size, + ) + + # Correct the distance if required + if index._distance_correction is not None: + d = index._distance_correction(d) + + # Convert indices to original data order + i = index._vertex_order[i] + j = index._vertex_order[j] + + return i, j, d + + new_edges = joblib.Parallel(n_jobs=n_jobs, prefer="threads")( + joblib.delayed(new_edge)(c1, c2) + for c1, c2 in combinations(range(n_components), 2) + ) + + for i, j, d in new_edges: + result[i, j] = d + result[j, i] = d + + return result.tocsr() diff --git a/shared/package-files/79/793b73c0bd280a48d31a20ff5926c403f5251ba844fcd96d381cf8c7fe946354/blob b/shared/package-files/79/793b73c0bd280a48d31a20ff5926c403f5251ba844fcd96d381cf8c7fe946354/blob new file mode 100644 index 0000000000000000000000000000000000000000..22fc58134566c67fd455bd5abbedbe0cc2a8df41 --- /dev/null +++ b/shared/package-files/79/793b73c0bd280a48d31a20ff5926c403f5251ba844fcd96d381cf8c7fe946354/blob @@ -0,0 +1,353 @@ +#pragma once + +#ifdef USE_C10D_UCC + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#ifdef USE_CUDA +#include +#include +#endif + +namespace c10d { + +#define TORCH_UCC_DEVICE_NOT_SET -2 + +#ifdef USE_CUDA +#define SAVE_TENSORS(_TENSORS, _DATA) \ + do { \ + if ((_TENSORS)[0].device().is_cuda()) { \ + for (const auto i : c10::irange((_TENSORS).size())) { \ + c10::cuda::CUDACachingAllocator::recordStream( \ + (_TENSORS)[i].storage().data_ptr(), (*stream)); \ + } \ + } else { \ + (_DATA) = (_TENSORS); \ + } \ + } while (0) + +#else +#define SAVE_TENSORS(_TENSORS, _DATA) (_DATA) = (_TENSORS); +#endif + +constexpr const char* UCC_BACKEND_NAME = "ucc"; + +struct event_pool_t { +#ifdef USE_CUDA + std::queue> event_pool; +#endif + std::mutex event_pool_mutex; +}; + +class Comm; + +// UCC does not support multiple CUDA devices per process. +class TORCH_API ProcessGroupUCC : public Backend { + private: + void set_timeout(ucc_coll_args_t& args); + + public: + class WorkData { + public: + std::vector src; + std::vector dst; + std::vector flat; + WorkData() {} + virtual ~WorkData() = default; + }; + class AlltoallWorkData : public WorkData { + public: + AlltoallWorkData(int size) + : send_lengths(size), + send_offsets(size), + recv_lengths(size), + recv_offsets(size) {} + std::vector send_lengths; + std::vector send_offsets; + std::vector recv_lengths; + std::vector recv_offsets; + }; + + class AllgathervWorkData : public WorkData { + public: + AllgathervWorkData(int size) : recv_lengths(size), recv_offsets(size) {} + std::vector recv_lengths; + std::vector recv_offsets; + }; + + class ScattervWorkData : public WorkData { + public: + ScattervWorkData(int size) : send_lengths(size), send_offsets(size) {} + std::vector send_lengths; + std::vector send_offsets; + }; + + class ProgressEntry { + friend class ProcessGroupUCC; + friend class Comm; + + public: + ProgressEntry(CommBase* comm, ucc_coll_req_h request) + : status_(UCC_INPROGRESS), comm_(comm), request_(request) {} + // Finalizes UCC status or exception of collective request. + void finalize(std::exception_ptr eptr = nullptr); + ucc_status_t status_; + CommBase* comm_; + ucc_coll_req_h request_; + std::unique_ptr data; + c10::intrusive_ptr future_; + std::exception_ptr eptr_; + }; + + class WorkUCC : public Work { + friend class ProcessGroupUCC; + friend class Comm; + + public: + WorkUCC( + OpType opType, + uint64_t seq, + const char* prof_title, + const c10::optional>& inputs, + const c10::intrusive_ptr& logger) + : Work(-1, opType, prof_title, inputs), logger_(logger), seq_(seq) {} + ~WorkUCC(); + void setException(); + void setAndThrowException(); + bool isCompleted() override; + bool isSuccess() const override; + bool wait(std::chrono::milliseconds timeout = kUnsetTimeout) override; + c10::intrusive_ptr getFuture() override; + std::vector result() override; + int sourceRank() const override; +#ifdef USE_CUDA + std::unique_ptr fence = nullptr; + event_pool_t* ep = nullptr; +#endif + int sourceRank_; + + protected: + std::shared_ptr entry_; + c10::intrusive_ptr logger_; + uint64_t seq_; + + private: + // The future returned by getFuture. + c10::intrusive_ptr future_; + // Store a reference to collective's outputs, used by result + std::shared_ptr> outputs_; + }; + + explicit ProcessGroupUCC( + const c10::intrusive_ptr& store, + int rank = -1, + int size = -1, + std::chrono::duration timeout = kBackendDefaultTimeout); + + void initComm(c10::Device dev); + + ~ProcessGroupUCC() override; + + const std::string getBackendName() const override { + return std::string(UCC_BACKEND_NAME); + } + +#ifdef USE_CUDA + std::unique_ptr getPooledEvent(); +#endif + + // Performs a health check by initializing dummy UCC & UCX communicators and + // then destroying them. This will help indicate and signal any + // UCC/UCX-related issues prior to the first collective. The actual + // initialization and subsequent destruction is ran on a separate thread and + // the main thread is signalled about timeouts/errors to report to the + // application. + void runHealthCheck(); + + template + c10::intrusive_ptr collective_post( + OpType opType, + PreProcess preproc, + PostProcess postproc, + ucc_coll_args_t& coll, + std::unique_ptr data, + c10::Device dev, + std::vector& inputTensors, + std::vector& outputTensors, + const char* prof_title); + + c10::intrusive_ptr broadcast( + std::vector& data, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputBuffer, + at::Tensor& inputBuffer, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + // Counting for the sequential number of UCC collective_post call. + uint64_t seq_{0}; + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. + void setSequenceNumberForGroup() override; + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + uint64_t getSequenceNumberForGroup() override; + + static c10::intrusive_ptr createProcessGroupUCC( + const c10::intrusive_ptr<::c10d::Store>& store, + int rank, + int size, + const std::chrono::duration& timeout); + + protected: + const std::chrono::duration timeout_; + std::shared_ptr oob; + std::shared_ptr comm = {nullptr}; + uint32_t comm_id; + ucc_team_h team{nullptr}; + ucc_ee_h cuda_ee{nullptr}; + ucc_ee_h cuda_ee_p2p[2]{nullptr, nullptr}; + +#ifdef USE_CUDA + std::unique_ptr stream = nullptr; + std::unique_ptr stream_p2p[2] = {nullptr, nullptr}; + event_pool_t ep; +#endif + c10::intrusive_ptr logger; +}; + +class Comm { + c10::intrusive_ptr logger; + std::shared_ptr oob; + CommUCC ucc_comm; + std::mutex mutex; + std::thread progress_thread; + std::condition_variable queue_produce_cv; + std::condition_variable queue_consume_cv; + std::deque> progress_queue; + bool stop_progress_loop; + bool collective_inprogress; + torch_ucc_phase_t finalize_phase; + + public: + c10::DeviceIndex cuda_device_index; + Comm( + const c10::intrusive_ptr& logger, + std::shared_ptr oob, + c10::Device dev, + bool is_health_check); + + ~Comm(); + + void ucc_create_team( + ucc_team_h& team, + std::shared_ptr oob); + + void ucc_destroy_team(ucc_team_h& team); + + c10::intrusive_ptr enqueue_p2p( + OpType opType, + ucc_coll_req_h request, + const char* prof_title); + +#ifdef USE_CUDA + void enqueue_cuda_collective( + std::unique_ptr data, + c10::intrusive_ptr work, + ucc_coll_args_t& coll, + ucc_team_h team, + ucc_ee_h ee); +#endif + + void enqueue_collective( + std::unique_ptr data, + c10::intrusive_ptr work, + ucc_coll_args_t& coll, + ucc_team_h team); + + static std::shared_ptr get_comm( + uint32_t& id, + c10::Device dev, + std::shared_ptr oob, + const c10::intrusive_ptr& logger, + bool is_health_check = false); + + void progress_loop(); +}; + +} // namespace c10d + +#endif // USE_C10D_UCC diff --git a/shared/package-files/79/793cc6c7e4a44f5c25a654edb9148f3733dd9e7ac941143d16667f9ef98a98fd/blob b/shared/package-files/79/793cc6c7e4a44f5c25a654edb9148f3733dd9e7ac941143d16667f9ef98a98fd/blob new file mode 100644 index 0000000000000000000000000000000000000000..b073bd94d9987612689047d288034e423b897b69 --- /dev/null +++ b/shared/package-files/79/793cc6c7e4a44f5c25a654edb9148f3733dd9e7ac941143d16667f9ef98a98fd/blob @@ -0,0 +1,14 @@ +"""prompt_toolkit input hook for GTK 3 +""" + +from gi.repository import Gtk, GLib + + +def _main_quit(*args, **kwargs): + Gtk.main_quit() + return False + + +def inputhook(context): + GLib.io_add_watch(context.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, _main_quit) + Gtk.main() diff --git a/shared/package-files/79/793ce3f752e686ff74cfe5a21e32b7b012599b485193472b158d5365a5ecb426/blob b/shared/package-files/79/793ce3f752e686ff74cfe5a21e32b7b012599b485193472b158d5365a5ecb426/blob new file mode 100644 index 0000000000000000000000000000000000000000..528b16d5b5b9ca6552254ee19f66828f78a86946 --- /dev/null +++ b/shared/package-files/79/793ce3f752e686ff74cfe5a21e32b7b012599b485193472b158d5365a5ecb426/blob @@ -0,0 +1,113 @@ +import pytest + +from bs4.element import Tag +from bs4.formatter import ( + Formatter, + HTMLFormatter, + XMLFormatter, +) +from . import SoupTest + +class TestFormatter(SoupTest): + + def test_default_attributes(self): + # Test the default behavior of Formatter.attributes(). + formatter = Formatter() + tag = Tag(name="tag") + tag['b'] = 1 + tag['a'] = 2 + + # Attributes come out sorted by name. In Python 3, attributes + # normally come out of a dictionary in the order they were + # added. + assert [('a', 2), ('b', 1)] == formatter.attributes(tag) + + # This works even if Tag.attrs is None, though this shouldn't + # normally happen. + tag.attrs = None + assert [] == formatter.attributes(tag) + + assert ' ' == formatter.indent + + def test_sort_attributes(self): + # Test the ability to override Formatter.attributes() to, + # e.g., disable the normal sorting of attributes. + class UnsortedFormatter(Formatter): + def attributes(self, tag): + self.called_with = tag + for k, v in sorted(tag.attrs.items()): + if k == 'ignore': + continue + yield k,v + + soup = self.soup('

') + formatter = UnsortedFormatter() + decoded = soup.decode(formatter=formatter) + + # attributes() was called on the

tag. It filtered out one + # attribute and sorted the other two. + assert formatter.called_with == soup.p + assert '

' == decoded + + def test_empty_attributes_are_booleans(self): + # Test the behavior of empty_attributes_are_booleans as well + # as which Formatters have it enabled. + + for name in ('html', 'minimal', None): + formatter = HTMLFormatter.REGISTRY[name] + assert False == formatter.empty_attributes_are_booleans + + formatter = XMLFormatter.REGISTRY[None] + assert False == formatter.empty_attributes_are_booleans + + formatter = HTMLFormatter.REGISTRY['html5'] + assert True == formatter.empty_attributes_are_booleans + + # Verify that the constructor sets the value. + formatter = Formatter(empty_attributes_are_booleans=True) + assert True == formatter.empty_attributes_are_booleans + + # Now demonstrate what it does to markup. + for markup in ( + "", + '' + ): + soup = self.soup(markup) + for formatter in ('html', 'minimal', 'xml', None): + assert b'' == soup.option.encode(formatter='html') + assert b'' == soup.option.encode(formatter='html5') + + @pytest.mark.parametrize( + "indent,expect", + [ + (None, '\n\ntext\n\n\n'), + (-1, '\n\ntext\n\n\n'), + (0, '\n\ntext\n\n\n'), + ("", '\n\ntext\n\n\n'), + + (1, '\n \n text\n \n\n'), + (2, '\n \n text\n \n\n'), + + ("\t", '\n\t\n\t\ttext\n\t\n\n'), + ('abc', '\nabc\nabcabctext\nabc\n\n'), + + # Some invalid inputs -- the default behavior is used. + (object(), '\n \n text\n \n\n'), + (b'bytes', '\n \n text\n \n\n'), + ] + ) + def test_indent(self, indent, expect): + # Pretty-print a tree with a Formatter set to + # indent in a certain way and verify the results. + soup = self.soup("text") + formatter = Formatter(indent=indent) + assert soup.prettify(formatter=formatter) == expect + + # Pretty-printing only happens with prettify(), not + # encode(). + assert soup.encode(formatter=formatter) != expect + + def test_default_indent_value(self): + formatter = Formatter() + assert formatter.indent == ' ' + diff --git a/shared/package-files/79/7942c974e81134caddea4946816e44968b6b7a3b0bf5ebff741cf72c6d8ff4bf/blob b/shared/package-files/79/7942c974e81134caddea4946816e44968b6b7a3b0bf5ebff741cf72c6d8ff4bf/blob new file mode 100644 index 0000000000000000000000000000000000000000..4e2fb069bd06b745ec128d993c8a4f75973c56f8 --- /dev/null +++ b/shared/package-files/79/7942c974e81134caddea4946816e44968b6b7a3b0bf5ebff741cf72c6d8ff4bf/blob @@ -0,0 +1,724 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import pytest +from datetime import timedelta +import pyarrow as pa +try: + import pyarrow.parquet as pq + import pyarrow.parquet.encryption as pe +except ImportError: + pq = None + pe = None +else: + from pyarrow.tests.parquet.encryption import (InMemoryKmsClient, + MockVersioningKmsClient, + verify_file_encrypted, + read_external_keys_to_dict, + parse_wrapped_key) + + +PARQUET_NAME = 'encrypted_table.in_mem.parquet' +FOOTER_KEY = b"0123456789112345" +FOOTER_KEY_NAME = "footer_key" +COL_KEY = b"1234567890123450" +COL_KEY_NAME = "col_key" + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet_encryption' +# Ignore these with pytest ... -m 'not parquet' +pytestmark = [ + pytest.mark.parquet_encryption, + pytest.mark.parquet +] + + +@pytest.fixture(scope='module') +def data_table(): + data_table = pa.Table.from_pydict({ + 'a': pa.array([1, 2, 3]), + 'b': pa.array(['a', 'b', 'c']), + 'c': pa.array(['x', 'y', 'z']) + }) + return data_table + + +@pytest.fixture(scope='module') +def basic_encryption_config(): + basic_encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }) + return basic_encryption_config + + +@pytest.fixture(scope='module') +def external_encryption_config(): + external_encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + internal_key_material=False) + return external_encryption_config + + +def setup_encryption_environment(custom_kms_conf): + """ + Sets up and returns the KMS connection configuration and crypto factory + based on provided KMS configuration parameters. + """ + kms_connection_config = pe.KmsConnectionConfig(custom_kms_conf=custom_kms_conf) + + def kms_factory(kms_connection_configuration): + return InMemoryKmsClient(kms_connection_configuration) + + # Create our CryptoFactory + crypto_factory = pe.CryptoFactory(kms_factory) + + return kms_connection_config, crypto_factory + + +def write_encrypted_file(path, data_table, footer_key_name, col_key_name, + footer_key, col_key, encryption_config): + """ + Writes an encrypted parquet file based on the provided parameters. + """ + # Setup the custom KMS configuration with provided keys + custom_kms_conf = { + footer_key_name: footer_key.decode("UTF-8"), + col_key_name: col_key.decode("UTF-8"), + } + + # Setup encryption environment + kms_connection_config, crypto_factory = setup_encryption_environment( + custom_kms_conf) + + # Write the encrypted parquet file + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + return kms_connection_config, crypto_factory + + +def test_encrypted_parquet_write_read(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, and then read it.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + encryption_algorithm="AES_GCM_V1", + cache_lifetime=timedelta(minutes=5.0), + data_key_length_bits=256) + assert encryption_config.uniform_encryption is False + + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + encryption_config) + + verify_file_encrypted(path) + + # Read with decryption properties + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + result_table = read_encrypted_parquet( + path, decryption_config, kms_connection_config, crypto_factory) + assert data_table.equals(result_table) + + +def test_uniform_encrypted_parquet_write_read(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, and then read it.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer and all columns with the footer key, + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + uniform_encryption=True, + encryption_algorithm="AES_GCM_V1", + cache_lifetime=timedelta(minutes=5.0), + data_key_length_bits=256) + assert encryption_config.uniform_encryption is True + + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, b"", + encryption_config) + + verify_file_encrypted(path) + + # Read with decryption properties + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + result_table = read_encrypted_parquet( + path, decryption_config, kms_connection_config, crypto_factory) + assert data_table.equals(result_table) + + +def write_encrypted_parquet(path, table, encryption_config, + kms_connection_config, crypto_factory): + if encryption_config.internal_key_material: + file_encryption_properties = crypto_factory.file_encryption_properties( + kms_connection_config, encryption_config) + else: + file_encryption_properties = crypto_factory.file_encryption_properties( + kms_connection_config, encryption_config, path) + assert file_encryption_properties is not None + with pq.ParquetWriter( + path, table.schema, + encryption_properties=file_encryption_properties) as writer: + writer.write_table(table) + + +def read_encrypted_parquet(path, decryption_config, + kms_connection_config, crypto_factory, + internal_key_material=True): + if internal_key_material: + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + else: + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config, path) + + assert file_decryption_properties is not None + meta = pq.read_metadata( + path, decryption_properties=file_decryption_properties) + assert meta.num_columns == 3 + schema = pq.read_schema( + path, decryption_properties=file_decryption_properties) + assert len(schema.names) == 3 + + result = pq.ParquetFile( + path, decryption_properties=file_decryption_properties) + return result.read(use_threads=True) + + +def test_encrypted_parquet_write_read_wrong_key(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + and then read it using wrong keys.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + encryption_algorithm="AES_GCM_V1", + cache_lifetime=timedelta(minutes=5.0), + data_key_length_bits=256) + + write_encrypted_file(path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, + FOOTER_KEY, COL_KEY, encryption_config) + + verify_file_encrypted(path) + + wrong_kms_connection_config, wrong_crypto_factory = setup_encryption_environment({ + FOOTER_KEY_NAME: COL_KEY.decode("UTF-8"), # Intentionally wrong + COL_KEY_NAME: FOOTER_KEY.decode("UTF-8"), # Intentionally wrong + }) + + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + with pytest.raises(ValueError, match=r"Incorrect master key used"): + read_encrypted_parquet( + path, decryption_config, wrong_kms_connection_config, + wrong_crypto_factory) + + +def test_encrypted_parquet_read_no_decryption_config(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + but then try to read it without decryption properties.""" + test_encrypted_parquet_write_read(tempdir, data_table) + # Read without decryption properties + with pytest.raises(IOError, match=r"no decryption"): + pq.ParquetFile(tempdir / PARQUET_NAME).read() + + +def test_encrypted_parquet_read_metadata_no_decryption_config( + tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + but then try to read its metadata without decryption properties.""" + test_encrypted_parquet_write_read(tempdir, data_table) + # Read metadata without decryption properties + with pytest.raises(IOError, match=r"no decryption"): + pq.read_metadata(tempdir / PARQUET_NAME) + + +def test_encrypted_parquet_read_schema_no_decryption_config( + tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + but then try to read its schema without decryption properties.""" + test_encrypted_parquet_write_read(tempdir, data_table) + with pytest.raises(IOError, match=r"no decryption"): + pq.read_schema(tempdir / PARQUET_NAME) + + +def test_encrypted_parquet_write_no_col_key(tempdir, data_table): + """Write an encrypted parquet, but give only footer key, + without column key.""" + path = tempdir / 'encrypted_table_no_col_key.in_mem.parquet' + + # Encrypt the footer with the footer key + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME) + + with pytest.raises(OSError, + match="Either column_keys or uniform_encryption " + "must be set"): + # Write with encryption properties + write_encrypted_file(path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, + FOOTER_KEY, b"", encryption_config) + + +def test_encrypted_parquet_write_col_key_and_uniform_encryption(tempdir, data_table): + """Write an encrypted parquet, but give only footer key, + without column key.""" + path = tempdir / 'encrypted_table_col_key_and_uniform_encryption.in_mem.parquet' + + # Encrypt the footer with the footer key + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + uniform_encryption=True) + + with pytest.raises(OSError, + match=r"Cannot set both column_keys and uniform_encryption"): + # Write with encryption properties + write_encrypted_file(path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, + FOOTER_KEY, b"", encryption_config) + + +def test_encrypted_parquet_write_kms_error(tempdir, data_table, + basic_encryption_config): + """Write an encrypted parquet, but raise KeyError in KmsClient.""" + path = tempdir / 'encrypted_table_kms_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + def kms_factory(kms_connection_configuration): + # Empty master keys map will cause KeyError to be raised + # on wrap/unwrap calls + return InMemoryKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(KeyError, match="footer_key"): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_write_kms_specific_error(tempdir, data_table, + basic_encryption_config): + """Write an encrypted parquet, but raise KeyError in KmsClient.""" + path = tempdir / 'encrypted_table_kms_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + class ThrowingKmsClient(pe.KmsClient): + """A KmsClient implementation that throws exception in + wrap/unwrap calls + """ + + def __init__(self, config): + """Create an InMemoryKmsClient instance.""" + pe.KmsClient.__init__(self) + self.config = config + + def wrap_key(self, key_bytes, master_key_identifier): + raise ValueError("Cannot Wrap Key") + + def unwrap_key(self, wrapped_key, master_key_identifier): + raise ValueError("Cannot Unwrap Key") + + def kms_factory(kms_connection_configuration): + # Exception thrown in wrap/unwrap calls + return ThrowingKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(ValueError, match="Cannot Wrap Key"): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_write_kms_factory_error(tempdir, data_table, + basic_encryption_config): + """Write an encrypted parquet, but raise ValueError in kms_factory.""" + path = tempdir / 'encrypted_table_kms_factory_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + def kms_factory(kms_connection_configuration): + raise ValueError('Cannot create KmsClient') + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(ValueError, + match="Cannot create KmsClient"): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_write_kms_factory_type_error( + tempdir, data_table, basic_encryption_config): + """Write an encrypted parquet, but use wrong KMS client type + that doesn't implement KmsClient.""" + path = tempdir / 'encrypted_table_kms_factory_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + class WrongTypeKmsClient(): + """This is not an implementation of KmsClient. + """ + + def __init__(self, config): + self.master_keys_map = config.custom_kms_conf + + def wrap_key(self, key_bytes, master_key_identifier): + return None + + def unwrap_key(self, wrapped_key, master_key_identifier): + return None + + def kms_factory(kms_connection_configuration): + return WrongTypeKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(TypeError): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_encryption_configuration(): + def validate_encryption_configuration(encryption_config): + assert FOOTER_KEY_NAME == encryption_config.footer_key + assert ["a", "b"] == encryption_config.column_keys[COL_KEY_NAME] + assert "AES_GCM_CTR_V1" == encryption_config.encryption_algorithm + assert encryption_config.plaintext_footer + assert not encryption_config.double_wrapping + assert timedelta(minutes=10.0) == encryption_config.cache_lifetime + assert not encryption_config.internal_key_material + assert 192 == encryption_config.data_key_length_bits + + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={COL_KEY_NAME: ["a", "b"], }, + encryption_algorithm="AES_GCM_CTR_V1", + plaintext_footer=True, + double_wrapping=False, + cache_lifetime=timedelta(minutes=10.0), + internal_key_material=False, + data_key_length_bits=192, + ) + validate_encryption_configuration(encryption_config) + + encryption_config_1 = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME) + encryption_config_1.column_keys = {COL_KEY_NAME: ["a", "b"], } + encryption_config_1.encryption_algorithm = "AES_GCM_CTR_V1" + encryption_config_1.plaintext_footer = True + encryption_config_1.double_wrapping = False + encryption_config_1.cache_lifetime = timedelta(minutes=10.0) + encryption_config_1.internal_key_material = False + encryption_config_1.data_key_length_bits = 192 + validate_encryption_configuration(encryption_config_1) + + +def test_encrypted_parquet_decryption_configuration(): + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=10.0)) + assert timedelta(minutes=10.0) == decryption_config.cache_lifetime + + decryption_config_1 = pe.DecryptionConfiguration() + decryption_config_1.cache_lifetime = timedelta(minutes=10.0) + assert timedelta(minutes=10.0) == decryption_config_1.cache_lifetime + + +def test_encrypted_parquet_kms_configuration(): + def validate_kms_connection_config(kms_connection_config): + assert "Instance1" == kms_connection_config.kms_instance_id + assert "URL1" == kms_connection_config.kms_instance_url + assert "MyToken" == kms_connection_config.key_access_token + assert ({"key1": "key_material_1", "key2": "key_material_2"} == + kms_connection_config.custom_kms_conf) + + kms_connection_config = pe.KmsConnectionConfig( + kms_instance_id="Instance1", + kms_instance_url="URL1", + key_access_token="MyToken", + custom_kms_conf={ + "key1": "key_material_1", + "key2": "key_material_2", + }) + validate_kms_connection_config(kms_connection_config) + + kms_connection_config_1 = pe.KmsConnectionConfig() + kms_connection_config_1.kms_instance_id = "Instance1" + kms_connection_config_1.kms_instance_url = "URL1" + kms_connection_config_1.key_access_token = "MyToken" + kms_connection_config_1.custom_kms_conf = { + "key1": "key_material_1", + "key2": "key_material_2", + } + validate_kms_connection_config(kms_connection_config_1) + + +@pytest.mark.xfail(reason="Plaintext footer - reading plaintext column subset" + " reads encrypted columns too") +def test_encrypted_parquet_write_read_plain_footer_single_wrapping( + tempdir, data_table): + """Write an encrypted parquet, with plaintext footer + and with single wrapping, + verify it's encrypted, and then read plaintext columns.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + plaintext_footer=True, + double_wrapping=False) + + kms_connection_config = pe.KmsConnectionConfig( + custom_kms_conf={ + FOOTER_KEY_NAME: FOOTER_KEY.decode("UTF-8"), + COL_KEY_NAME: COL_KEY.decode("UTF-8"), + } + ) + + def kms_factory(kms_connection_configuration): + return InMemoryKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + # # Read without decryption properties only the plaintext column + # result = pq.ParquetFile(path) + # result_table = result.read(columns='c', use_threads=False) + # assert table.num_rows == result_table.num_rows + + +def test_encrypted_parquet_write_read_external(tempdir, data_table, + external_encryption_config): + """Write an encrypted parquet file with external key material, verify + it's encrypted, then read both the table and external store. + """ + path = tempdir / PARQUET_NAME + + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + external_encryption_config) + + verify_file_encrypted(path) + + decryption_config = pe.DecryptionConfiguration() + result_table = read_encrypted_parquet( + path, decryption_config, kms_connection_config, crypto_factory, + internal_key_material=False) + store = pa._parquet_encryption.FileSystemKeyMaterialStore.for_file(path) + + assert len(key_ids := store.get_key_id_set()) == ( + len(external_encryption_config.column_keys[COL_KEY_NAME]) + 1) + assert all([store.get_key_material(k) is not None for k in key_ids]) + assert data_table.equals(result_table) + + +@pytest.mark.parametrize( + ("double_wrap_initial", "double_wrap_rotated"), [ + pytest.param(True, True, id="double wrapping"), + pytest.param(False, True, id="single to double wrapped"), + pytest.param(True, False, id="double to singe wrapped"), + pytest.param(False, False, id="single wrapping")]) +def test_external_key_material_rotation( + reusable_tempdir, + data_table, + double_wrap_initial, + double_wrap_rotated): + """Tests CryptoFactory.rotate_master_keys + + Note: The CryptoFactory.rotate_master_keys() double_wrapping keword arg + may be either True (the default) or False regardless of whether + EncryptionConfig.double_wrapping was set to true (also the default) when + the external key material store was written. This means double wrapping may + be set one way initially and then applied or removed during rotation. + """ + path = reusable_tempdir / PARQUET_NAME + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={COL_KEY_NAME: ["a", "b"]}, + internal_key_material=False, + double_wrapping=double_wrap_initial) + + # initial master key version - see MockVersioningKmsClient docstring + kms_connection_config = pe.KmsConnectionConfig(key_access_token="1") + + def kms_factory(kms_connection_configuration): + return MockVersioningKmsClient(kms_connection_configuration) + crypto_factory = pe.CryptoFactory(kms_factory) + write_encrypted_parquet( + path, + data_table, + encryption_config, + kms_connection_config, + crypto_factory) + before_keys = read_external_keys_to_dict(path) + + # "rotate" kms master key + kms_connection_config.refresh_key_access_token("2") + + crypto_factory.rotate_master_keys( + kms_connection_config, + path, + double_wrapping=double_wrap_rotated) + + after_keys = read_external_keys_to_dict(path) + verify_file_encrypted(path) + table_read_after_rotation = read_encrypted_parquet( + path, + pe.DecryptionConfiguration(), + kms_connection_config, + crypto_factory, + internal_key_material=False) + assert FOOTER_KEY_NAME in before_keys + assert COL_KEY_NAME in before_keys + assert FOOTER_KEY_NAME in after_keys + assert COL_KEY_NAME in after_keys + + def check_rotated_external_keys(master_key_id: str) -> None: + before_key_mat = before_keys[master_key_id] + if double_wrap_initial: + before_key_wrapped = before_key_mat.wrapped_kek + else: + before_key_wrapped = before_key_mat.wrapped_dek + _, before_ver, _ = parse_wrapped_key(before_key_wrapped) + + after_key_mat = after_keys[master_key_id] + if double_wrap_rotated: + after_key_wrapped = after_key_mat.wrapped_kek + else: + after_key_wrapped = after_key_mat.wrapped_dek + _, after_ver, _ = parse_wrapped_key(after_key_wrapped) + + # CryptoFactory rewrapped keys if after version is later than before + assert before_ver < after_ver + check_rotated_external_keys(FOOTER_KEY_NAME) + check_rotated_external_keys(COL_KEY_NAME) + assert data_table.equals(table_read_after_rotation) + + +def test_encrypted_parquet_loop(tempdir, data_table, basic_encryption_config): + """Write an encrypted parquet, verify it's encrypted, + and then read it multithreaded in a loop.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext, defined in basic_encryption_config + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + basic_encryption_config) + + verify_file_encrypted(path) + + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + + for i in range(50): + # Read with decryption properties + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + assert file_decryption_properties is not None + + result = pq.ParquetFile( + path, decryption_properties=file_decryption_properties) + result_table = result.read(use_threads=True) + assert data_table.equals(result_table) + + +def test_read_with_deleted_crypto_factory(tempdir, data_table, basic_encryption_config): + """ + Test that decryption properties can be used if the crypto factory is no longer alive + """ + path = tempdir / PARQUET_NAME + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + basic_encryption_config) + verify_file_encrypted(path) + + # Create decryption properties and delete the crypto factory that created + # the properties afterwards. + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + del crypto_factory + + result = pq.ParquetFile( + path, decryption_properties=file_decryption_properties) + result_table = result.read(use_threads=True) + assert data_table.equals(result_table) + + +def test_encrypted_parquet_read_table(tempdir, data_table, basic_encryption_config): + """Write an encrypted parquet then read it back using read_table.""" + path = tempdir / PARQUET_NAME + + # Write the encrypted parquet file using the utility function + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + basic_encryption_config) + + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + + # Read the encrypted parquet file using read_table + result_table = pq.read_table(path, decryption_properties=file_decryption_properties) + + # Assert that the read table matches the original data + assert data_table.equals(result_table) + + # Read the encrypted parquet folder using read_table + result_table = pq.read_table( + tempdir, decryption_properties=file_decryption_properties) + assert data_table.equals(result_table) diff --git a/shared/package-files/79/7945b3a3c691aa68666f1b2398962819d2a97f53ed4efc8dc5a7ebac36494a68/blob b/shared/package-files/79/7945b3a3c691aa68666f1b2398962819d2a97f53ed4efc8dc5a7ebac36494a68/blob new file mode 100644 index 0000000000000000000000000000000000000000..b6b8d8a5af6d4c083858766586228bcaa373804a --- /dev/null +++ b/shared/package-files/79/7945b3a3c691aa68666f1b2398962819d2a97f53ed4efc8dc5a7ebac36494a68/blob @@ -0,0 +1,195 @@ +"""Implementation of magic functions for IPython's own logging. +""" +#----------------------------------------------------------------------------- +# Copyright (c) 2012 The IPython Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Stdlib +import os +import sys + +# Our own packages +from IPython.core.magic import Magics, magics_class, line_magic +from warnings import warn +from traitlets import Bool + +#----------------------------------------------------------------------------- +# Magic implementation classes +#----------------------------------------------------------------------------- + +@magics_class +class LoggingMagics(Magics): + """Magics related to all logging machinery.""" + + quiet = Bool(False, help= + """ + Suppress output of log state when logging is enabled + """ + ).tag(config=True) + + @line_magic + def logstart(self, parameter_s=''): + """Start logging anywhere in a session. + + %logstart [-o|-r|-t|-q] [log_name [log_mode]] + + If no name is given, it defaults to a file named 'ipython_log.py' in your + current directory, in 'rotate' mode (see below). + + '%logstart name' saves to file 'name' in 'backup' mode. It saves your + history up to that point and then continues logging. + + %logstart takes a second optional parameter: logging mode. This can be one + of (note that the modes are given unquoted): + + append + Keep logging at the end of any existing file. + + backup + Rename any existing file to name~ and start name. + + global + Append to a single logfile in your home directory. + + over + Overwrite any existing log. + + rotate + Create rotating logs: name.1~, name.2~, etc. + + Options: + + -o + log also IPython's output. In this mode, all commands which + generate an Out[NN] prompt are recorded to the logfile, right after + their corresponding input line. The output lines are always + prepended with a '#[Out]# ' marker, so that the log remains valid + Python code. + + Since this marker is always the same, filtering only the output from + a log is very easy, using for example a simple awk call:: + + awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py + + -r + log 'raw' input. Normally, IPython's logs contain the processed + input, so that user lines are logged in their final form, converted + into valid Python. For example, %Exit is logged as + _ip.magic("Exit"). If the -r flag is given, all input is logged + exactly as typed, with no transformations applied. + + -t + put timestamps before each input line logged (these are put in + comments). + + -q + suppress output of logstate message when logging is invoked + """ + + opts,par = self.parse_options(parameter_s,'ortq') + log_output = 'o' in opts + log_raw_input = 'r' in opts + timestamp = 't' in opts + quiet = 'q' in opts + + logger = self.shell.logger + + # if no args are given, the defaults set in the logger constructor by + # ipython remain valid + if par: + try: + logfname,logmode = par.split() + except: + logfname = par + logmode = 'backup' + else: + logfname = logger.logfname + logmode = logger.logmode + # put logfname into rc struct as if it had been called on the command + # line, so it ends up saved in the log header Save it in case we need + # to restore it... + old_logfile = self.shell.logfile + if logfname: + logfname = os.path.expanduser(logfname) + self.shell.logfile = logfname + + loghead = u'# IPython log file\n\n' + try: + logger.logstart(logfname, loghead, logmode, log_output, timestamp, + log_raw_input) + except: + self.shell.logfile = old_logfile + warn("Couldn't start log: %s" % sys.exc_info()[1]) + else: + # log input history up to this point, optionally interleaving + # output if requested + + if timestamp: + # disable timestamping for the previous history, since we've + # lost those already (no time machine here). + logger.timestamp = False + + if log_raw_input: + input_hist = self.shell.history_manager.input_hist_raw + else: + input_hist = self.shell.history_manager.input_hist_parsed + + if log_output: + log_write = logger.log_write + output_hist = self.shell.history_manager.output_hist + for n in range(1,len(input_hist)-1): + log_write(input_hist[n].rstrip() + u'\n') + if n in output_hist: + log_write(repr(output_hist[n]),'output') + else: + logger.log_write(u'\n'.join(input_hist[1:])) + logger.log_write(u'\n') + if timestamp: + # re-enable timestamping + logger.timestamp = True + + if not (self.quiet or quiet): + print ('Activating auto-logging. ' + 'Current session state plus future input saved.') + logger.logstate() + + @line_magic + def logstop(self, parameter_s=''): + """Fully stop logging and close log file. + + In order to start logging again, a new %logstart call needs to be made, + possibly (though not necessarily) with a new filename, mode and other + options.""" + self.shell.logger.logstop() + + @line_magic + def logoff(self, parameter_s=''): + """Temporarily stop logging. + + You must have previously started logging.""" + self.shell.logger.switch_log(0) + + @line_magic + def logon(self, parameter_s=''): + """Restart logging. + + This function is for restarting logging which you've temporarily + stopped with %logoff. For starting logging for the first time, you + must use the %logstart function, which allows you to specify an + optional log filename.""" + + self.shell.logger.switch_log(1) + + @line_magic + def logstate(self, parameter_s=''): + """Print the status of the logging system.""" + + self.shell.logger.logstate() diff --git a/shared/package-files/79/79485d7d85cbe65159617ff0dfe73ee1528bd601d9fb273e24701933d5ed873b/blob b/shared/package-files/79/79485d7d85cbe65159617ff0dfe73ee1528bd601d9fb273e24701933d5ed873b/blob new file mode 100644 index 0000000000000000000000000000000000000000..1164daf58526c797f3b16f9646130512c1107659 --- /dev/null +++ b/shared/package-files/79/79485d7d85cbe65159617ff0dfe73ee1528bd601d9fb273e24701933d5ed873b/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _adaptive_avg_pool2d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size); +TORCH_API at::Tensor & _adaptive_avg_pool2d_outf(const at::Tensor & self, at::IntArrayRef output_size, at::Tensor & out); +TORCH_API at::Tensor & _adaptive_avg_pool2d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size); +TORCH_API at::Tensor & _adaptive_avg_pool2d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/79/7948dbd7922c91a0bb6fefcb9bf0c0038cecfca2fd5807233da3d24d9a2c5290/blob b/shared/package-files/79/7948dbd7922c91a0bb6fefcb9bf0c0038cecfca2fd5807233da3d24d9a2c5290/blob new file mode 100644 index 0000000000000000000000000000000000000000..60ed6671179b2c20fa0be176631d1415009ee87a --- /dev/null +++ b/shared/package-files/79/7948dbd7922c91a0bb6fefcb9bf0c0038cecfca2fd5807233da3d24d9a2c5290/blob @@ -0,0 +1,58 @@ +import unittest + +from ..pass_manager import ( + inplace_wrapper, + PassManager, + these_before_those_pass_constraint, + this_before_that_pass_constraint, +) + + +class TestPassManager(unittest.TestCase): + def test_pass_manager_builder(self) -> None: + passes = [lambda x: 2 * x for _ in range(10)] + pm = PassManager(passes) + pm.validate() + + def test_this_before_that_pass_constraint(self) -> None: + passes = [lambda x: 2 * x for _ in range(10)] + pm = PassManager(passes) + + # add unfulfillable constraint + pm.add_constraint(this_before_that_pass_constraint(passes[-1], passes[0])) + + self.assertRaises(RuntimeError, pm.validate) + + def test_these_before_those_pass_constraint(self) -> None: + passes = [lambda x: 2 * x for _ in range(10)] + constraint = these_before_those_pass_constraint(passes[-1], passes[0]) + pm = PassManager( + [inplace_wrapper(p) for p in passes] + ) + + # add unfulfillable constraint + pm.add_constraint(constraint) + + self.assertRaises(RuntimeError, pm.validate) + + def test_two_pass_managers(self) -> None: + """Make sure we can construct the PassManager twice and not share any + state between them""" + + passes = [lambda x: 2 * x for _ in range(3)] + constraint = these_before_those_pass_constraint(passes[0], passes[1]) + pm1 = PassManager() + for p in passes: + pm1.add_pass(p) + pm1.add_constraint(constraint) + output1 = pm1(1) + self.assertEqual(output1, 2 ** 3) + + passes = [lambda x: 3 * x for _ in range(3)] + constraint = these_before_those_pass_constraint(passes[0], passes[1]) + pm2 = PassManager() + for p in passes: + pm2.add_pass(p) + pm2.add_constraint(constraint) + output2 = pm2(1) + self.assertEqual(output2, 3 ** 3) diff --git a/shared/package-files/79/794d039ffdf277c047e26f2c7d58f81a5865d8a0eb7024a0fac1164fea4d27cf/blob b/shared/package-files/79/794d039ffdf277c047e26f2c7d58f81a5865d8a0eb7024a0fac1164fea4d27cf/blob new file mode 100644 index 0000000000000000000000000000000000000000..02123695d01e8b7776994129cff8b99f0dd85fcc --- /dev/null +++ b/shared/package-files/79/794d039ffdf277c047e26f2c7d58f81a5865d8a0eb7024a0fac1164fea4d27cf/blob @@ -0,0 +1,4635 @@ + +# Issuer: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA +# Subject: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA +# Label: "GlobalSign Root CA" +# Serial: 4835703278459707669005204 +# MD5 Fingerprint: 3e:45:52:15:09:51:92:e1:b7:5d:37:9f:b1:87:29:8a +# SHA1 Fingerprint: b1:bc:96:8b:d4:f4:9d:62:2a:a8:9a:81:f2:15:01:52:a4:1d:82:9c +# SHA256 Fingerprint: eb:d4:10:40:e4:bb:3e:c7:42:c9:e3:81:d3:1e:f2:a4:1a:48:b6:68:5c:96:e7:ce:f3:c1:df:6c:d4:33:1c:99 +-----BEGIN CERTIFICATE----- +MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG +A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv +b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw +MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i +YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT +aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ +jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp +xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp +1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG +snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ +U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8 +9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B +AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz +yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE +38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP +AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad +DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME +HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== +-----END CERTIFICATE----- + +# Issuer: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Subject: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Label: "Entrust.net Premium 2048 Secure Server CA" +# Serial: 946069240 +# MD5 Fingerprint: ee:29:31:bc:32:7e:9a:e6:e8:b5:f7:51:b4:34:71:90 +# SHA1 Fingerprint: 50:30:06:09:1d:97:d4:f5:ae:39:f7:cb:e7:92:7d:7d:65:2d:34:31 +# SHA256 Fingerprint: 6d:c4:71:72:e0:1c:bc:b0:bf:62:58:0d:89:5f:e2:b8:ac:9a:d4:f8:73:80:1e:0c:10:b9:c8:37:d2:1e:b1:77 +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML +RW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp +bmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5 +IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0yOTA3 +MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3 +LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp +YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG +A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq +K0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe +sYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX +MlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT +XTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/ +HoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH +4QIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJKoZIhvcNAQEFBQADggEBADub +j1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPyT/4xmf3IDExo +U8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf +zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5b +u/8j72gZyxKTJ1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+ +bYQLCIt+jerXmCHG8+c8eS9enNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/Er +fF6adulZkMV8gzURZVE= +-----END CERTIFICATE----- + +# Issuer: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust +# Subject: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust +# Label: "Baltimore CyberTrust Root" +# Serial: 33554617 +# MD5 Fingerprint: ac:b6:94:a5:9c:17:e0:d7:91:52:9b:b1:97:06:a6:e4 +# SHA1 Fingerprint: d4:de:20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74 +# SHA256 Fingerprint: 16:af:57:a9:f6:76:b0:ab:12:60:95:aa:5e:ba:de:f2:2a:b3:11:19:d6:44:ac:95:cd:4b:93:db:f3:f2:6a:eb +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ +RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD +VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX +DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y +ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy +VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr +mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr +IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK +mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu +XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy +dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye +jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1 +BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 +DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92 +9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx +jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0 +Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz +ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS +R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc. +# Subject: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc. +# Label: "Entrust Root Certification Authority" +# Serial: 1164660820 +# MD5 Fingerprint: d6:a5:c3:ed:5d:dd:3e:00:c1:3d:87:92:1f:1d:3f:e4 +# SHA1 Fingerprint: b3:1e:b1:b7:40:e3:6c:84:02:da:dc:37:d4:4d:f5:d4:67:49:52:f9 +# SHA256 Fingerprint: 73:c1:76:43:4f:1b:c6:d5:ad:f4:5b:0e:76:e7:27:28:7c:8d:e5:76:16:c1:e6:e6:14:1a:2b:2c:bc:7d:8e:4c +-----BEGIN CERTIFICATE----- +MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 +Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW +KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl +cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw +NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw +NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy +ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV +BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo +Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 +4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 +KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI +rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi +94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB +sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi +gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo +kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE +vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA +A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t +O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua +AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP +9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ +eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m +0vdXcDazv/wor3ElhVsT/h5/WrQ8 +-----END CERTIFICATE----- + +# Issuer: CN=AAA Certificate Services O=Comodo CA Limited +# Subject: CN=AAA Certificate Services O=Comodo CA Limited +# Label: "Comodo AAA Services root" +# Serial: 1 +# MD5 Fingerprint: 49:79:04:b0:eb:87:19:ac:47:b0:bc:11:51:9b:74:d0 +# SHA1 Fingerprint: d1:eb:23:a4:6d:17:d6:8f:d9:25:64:c2:f1:f1:60:17:64:d8:e3:49 +# SHA256 Fingerprint: d7:a7:a0:fb:5d:7e:27:31:d7:71:e9:48:4e:bc:de:f7:1d:5f:0c:3e:0a:29:48:78:2b:c8:3e:e0:ea:69:9e:f4 +-----BEGIN CERTIFICATE----- +MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb +MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow +GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj +YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM +GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua +BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe +3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4 +YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR +rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm +ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU +oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF +MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v +QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t +b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF +AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q +GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz +Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2 +G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi +l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3 +smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 2 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 2 O=QuoVadis Limited +# Label: "QuoVadis Root CA 2" +# Serial: 1289 +# MD5 Fingerprint: 5e:39:7b:dd:f8:ba:ec:82:e9:ac:62:ba:0c:54:00:2b +# SHA1 Fingerprint: ca:3a:fb:cf:12:40:36:4b:44:b2:16:20:88:80:48:39:19:93:7c:f7 +# SHA256 Fingerprint: 85:a0:dd:7d:d7:20:ad:b7:ff:05:f8:3d:54:2b:20:9d:c7:ff:45:28:f7:d6:77:b1:83:89:fe:a5:e5:c4:9e:86 +-----BEGIN CERTIFICATE----- +MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x +GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv +b3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV +BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W +YWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa +GMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg +Fyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J +WpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB +rrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp ++ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1 +ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i +Ucw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz +PtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og +/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH +oycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI +yV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud +EwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2 +A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL +MAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT +ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f +BluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn +g/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl +fF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K +WWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha +B0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc +hLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR +TUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD +mbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z +ohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y +4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza +8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 3" +# Serial: 1478 +# MD5 Fingerprint: 31:85:3c:62:94:97:63:b9:aa:fd:89:4e:af:6f:e0:cf +# SHA1 Fingerprint: 1f:49:14:f7:d8:74:95:1d:dd:ae:02:c0:be:fd:3a:2d:82:75:51:85 +# SHA256 Fingerprint: 18:f1:fc:7f:20:5d:f8:ad:dd:eb:7f:e0:07:dd:57:e3:af:37:5a:9c:4d:8d:73:54:6b:f4:f1:fe:d1:e1:8d:35 +-----BEGIN CERTIFICATE----- +MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x +GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv +b3QgQ0EgMzAeFw0wNjExMjQxOTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNV +BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W +YWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDM +V0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNggDhoB +4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUr +H556VOijKTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd +8lyyBTNvijbO0BNO/79KDDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9Cabwv +vWhDFlaJKjdhkf2mrk7AyxRllDdLkgbvBNDInIjbC3uBr7E9KsRlOni27tyAsdLT +mZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwpp5ijJUMv7/FfJuGITfhe +btfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8nT8KKdjc +T5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDt +WAEXMJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZ +c6tsgLjoC2SToJyMGf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A +4iLItLRkT9a6fUg+qGkM17uGcclzuD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYD +VR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHTBgkrBgEEAb5YAAMwgcUwgZMG +CCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0 +aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 +aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVu +dC4wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2Nw +czALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4G +A1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4ywLQoUmkRzBFMQswCQYDVQQGEwJC +TTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UEAxMSUXVvVmFkaXMg +Um9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZVqyM0 +7ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSem +d1o417+shvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd ++LJ2w/w4E6oM3kJpK27zPOuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B +4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadN +t54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp8kokUvd0/bpO5qgdAm6x +DYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBCbjPsMZ57 +k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6s +zHXug/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0j +Wy10QJLZYxkNc91pvGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeT +mJlglFwjz1onl14LBQaTNx47aTbrqZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK +4SVhM7JZG+Ju1zdXtg2pEto= +-----END CERTIFICATE----- + +# Issuer: O=SECOM Trust.net OU=Security Communication RootCA1 +# Subject: O=SECOM Trust.net OU=Security Communication RootCA1 +# Label: "Security Communication Root CA" +# Serial: 0 +# MD5 Fingerprint: f1:bc:63:6a:54:e0:b5:27:f5:cd:e7:1a:e3:4d:6e:4a +# SHA1 Fingerprint: 36:b1:2b:49:f9:81:9e:d7:4c:9e:bc:38:0f:c6:56:8f:5d:ac:b2:f7 +# SHA256 Fingerprint: e7:5e:72:ed:9f:56:0e:ec:6e:b4:80:00:73:a4:3f:c3:ad:19:19:5a:39:22:82:01:78:95:97:4a:99:02:6b:6c +-----BEGIN CERTIFICATE----- +MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEY +MBYGA1UEChMPU0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21t +dW5pY2F0aW9uIFJvb3RDQTEwHhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5 +WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMPU0VDT00gVHJ1c3QubmV0MScwJQYD +VQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw8yl8 +9f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJ +DKaVv0uMDPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9 +Ms+k2Y7CI9eNqPPYJayX5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/N +QV3Is00qVUarH9oe4kA92819uZKAnDfdDJZkndwi92SL32HeFZRSFaB9UslLqCHJ +xrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2JChzAgMBAAGjPzA9MB0G +A1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vG +kl3g0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfr +Uj94nK9NrvjVT8+amCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5 +Bw+SUEmK3TGXX8npN6o7WWWXlDLJs58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJU +JRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ6rBK+1YWc26sTfcioU+tHXot +RSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAiFL39vmwLAw== +-----END CERTIFICATE----- + +# Issuer: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com +# Subject: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com +# Label: "XRamp Global CA Root" +# Serial: 107108908803651509692980124233745014957 +# MD5 Fingerprint: a1:0b:44:b3:ca:10:d8:00:6e:9d:0f:d8:0f:92:0a:d1 +# SHA1 Fingerprint: b8:01:86:d1:eb:9c:86:a5:41:04:cf:30:54:f3:4c:52:b7:e5:58:c6 +# SHA256 Fingerprint: ce:cd:dc:90:50:99:d8:da:df:c5:b1:d2:09:b7:37:cb:e2:c1:8c:fb:2c:10:c0:ff:0b:cf:0d:32:86:fc:1a:a2 +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCB +gjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEk +MCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRY +UmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQxMTAxMTcx +NDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3 +dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2Vy +dmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS6 +38eMpSe2OAtp87ZOqCwuIR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCP +KZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMxfoArtYzAQDsRhtDLooY2YKTVMIJt2W7Q +DxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FEzG+gSqmUsE3a56k0enI4 +qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqsAxcZZPRa +JSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNVi +PvryxS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0P +BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASs +jVy16bYbMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0 +eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQEwDQYJKoZIhvcNAQEFBQAD +ggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc/Kh4ZzXxHfAR +vbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt +qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLa +IR9NmXmd4c8nnxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSy +i6mx5O+aGtA9aZnuqCij4Tyz8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQ +O+7ETPTsJ3xCwnR8gooJybQDJbw= +-----END CERTIFICATE----- + +# Issuer: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority +# Subject: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority +# Label: "Go Daddy Class 2 CA" +# Serial: 0 +# MD5 Fingerprint: 91:de:06:25:ab:da:fd:32:17:0c:bb:25:17:2a:84:67 +# SHA1 Fingerprint: 27:96:ba:e6:3f:18:01:e2:77:26:1b:a0:d7:77:70:02:8f:20:ee:e4 +# SHA256 Fingerprint: c3:84:6b:f2:4b:9e:93:ca:64:27:4c:0e:c6:7c:1e:cc:5e:02:4f:fc:ac:d2:d7:40:19:35:0e:81:fe:54:6a:e4 +-----BEGIN CERTIFICATE----- +MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh +MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE +YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3 +MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo +ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg +MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN +ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA +PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w +wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi +EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY +avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+ +YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE +sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h +/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5 +IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD +ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy +OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P +TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ +HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER +dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf +ReYNnyicsbkqWletNw+vHX/bvZ8= +-----END CERTIFICATE----- + +# Issuer: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority +# Subject: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority +# Label: "Starfield Class 2 CA" +# Serial: 0 +# MD5 Fingerprint: 32:4a:4b:bb:c8:63:69:9b:be:74:9a:c6:dd:1d:46:24 +# SHA1 Fingerprint: ad:7e:1c:28:b0:64:ef:8f:60:03:40:20:14:c3:d0:e3:37:0e:b5:8a +# SHA256 Fingerprint: 14:65:fa:20:53:97:b8:76:fa:a6:f0:a9:95:8e:55:90:e4:0f:cc:7f:aa:4f:b7:c2:c8:67:75:21:fb:5f:b6:58 +-----BEGIN CERTIFICATE----- +MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl +MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp +U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw +NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE +ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp +ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3 +DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf +8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN ++lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0 +X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa +K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA +1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G +A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR +zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0 +YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD +bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w +DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3 +L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D +eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl +xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp +VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY +WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root CA" +# Serial: 17154717934120587862167794914071425081 +# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72 +# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43 +# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c +-----BEGIN CERTIFICATE----- +MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c +JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP +mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+ +wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4 +VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/ +AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB +AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun +pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC +dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf +fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm +NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx +H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe ++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root CA" +# Serial: 10944719598952040374951832963794454346 +# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e +# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36 +# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61 +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD +QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB +CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 +nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt +43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P +T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 +gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR +TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw +DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr +hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg +06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF +PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls +YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk +CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert High Assurance EV Root CA" +# Serial: 3553400076410547919724730734378100087 +# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a +# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25 +# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j +ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL +MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 +LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug +RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm ++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW +PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM +xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB +Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 +hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg +EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA +FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec +nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z +eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF +hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 +Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep ++OkuE6N36B9K +-----END CERTIFICATE----- + +# Issuer: CN=SwissSign Gold CA - G2 O=SwissSign AG +# Subject: CN=SwissSign Gold CA - G2 O=SwissSign AG +# Label: "SwissSign Gold CA - G2" +# Serial: 13492815561806991280 +# MD5 Fingerprint: 24:77:d9:a8:91:d1:3b:fa:88:2d:c2:ff:f8:cd:33:93 +# SHA1 Fingerprint: d8:c5:38:8a:b7:30:1b:1b:6e:d4:7a:e6:45:25:3a:6f:9f:1a:27:61 +# SHA256 Fingerprint: 62:dd:0b:e9:b9:f5:0a:16:3e:a0:f8:e7:5c:05:3b:1e:ca:57:ea:55:c8:68:8f:64:7c:68:81:f2:c8:35:7b:95 +-----BEGIN CERTIFICATE----- +MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2ln +biBHb2xkIENBIC0gRzIwHhcNMDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBF +MQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dpc3NTaWduIEFHMR8wHQYDVQQDExZT +d2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUqt2/8 +76LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+ +bbqBHH5CjCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c +6bM8K8vzARO/Ws/BtQpgvd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqE +emA8atufK+ze3gE/bk3lUIbLtK/tREDFylqM2tIrfKjuvqblCqoOpd8FUrdVxyJd +MmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvRAiTysybUa9oEVeXBCsdt +MDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuendjIj3o02y +MszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69y +FGkOpeUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPi +aG59je883WX0XaxR7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxM +gI93e2CaHt+28kgeDrpOVG2Y4OGiGqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCB +qTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUWyV7 +lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64OfPAeGZe6Drn +8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov +L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe6 +45R88a7A3hfm5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczO +UYrHUDFu4Up+GC9pWbY9ZIEr44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5 +O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOfMke6UiI0HTJ6CVanfCU2qT1L2sCC +bwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6mGu6uLftIdxf+u+yv +GPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxpmo/a +77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCC +hdiDyyJkvC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid3 +92qgQmwLOM7XdVAyksLfKzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEpp +Ld6leNcG2mqeSz53OiATIgHQv2ieY2BrNU0LbbqhPcCT4H8js1WtciVORvnSFu+w +ZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6LqjviOvrv1vA+ACOzB2+htt +Qc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ +-----END CERTIFICATE----- + +# Issuer: CN=SwissSign Silver CA - G2 O=SwissSign AG +# Subject: CN=SwissSign Silver CA - G2 O=SwissSign AG +# Label: "SwissSign Silver CA - G2" +# Serial: 5700383053117599563 +# MD5 Fingerprint: e0:06:a1:c9:7d:cf:c9:fc:0d:c0:56:75:96:d8:62:13 +# SHA1 Fingerprint: 9b:aa:e5:9f:56:ee:21:cb:43:5a:be:25:93:df:a7:f0:40:d1:1d:cb +# SHA256 Fingerprint: be:6c:4d:a2:bb:b9:ba:59:b6:f3:93:97:68:37:42:46:c3:c0:05:99:3f:a9:8f:02:0d:1d:ed:be:d4:8a:81:d5 +-----BEGIN CERTIFICATE----- +MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UE +BhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWdu +IFNpbHZlciBDQSAtIEcyMB4XDTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0Nlow +RzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMY +U3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644N0Mv +Fz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7br +YT7QbNHm+/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieF +nbAVlDLaYQ1HTWBCrpJH6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH +6ATK72oxh9TAtvmUcXtnZLi2kUpCe2UuMGoM9ZDulebyzYLs2aFK7PayS+VFheZt +eJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5hqAaEuSh6XzjZG6k4sIN/ +c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5FZGkECwJ +MoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRH +HTBsROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTf +jNFusB3hB48IHpmccelM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb6 +5i/4z3GcRm25xBWNOHkDRUjvxF3XCO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOB +rDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU +F6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRBtjpbO8tFnb0c +wpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0 +cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIB +AHPGgeAn0i0P4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShp +WJHckRE1qTodvBqlYJ7YH39FkWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9 +xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L3XWgwF15kIwb4FDm3jH+mHtwX6WQ +2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx/uNncqCxv1yL5PqZ +IseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFaDGi8 +aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2X +em1ZqSqPe97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQR +dAtq/gsD/KNVV4n+SsuuWxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/ +OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJDIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+ +hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ubDgEj8Z+7fNzcbBGXJbLy +tGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u +-----END CERTIFICATE----- + +# Issuer: CN=SecureTrust CA O=SecureTrust Corporation +# Subject: CN=SecureTrust CA O=SecureTrust Corporation +# Label: "SecureTrust CA" +# Serial: 17199774589125277788362757014266862032 +# MD5 Fingerprint: dc:32:c3:a7:6d:25:57:c7:68:09:9d:ea:2d:a9:a2:d1 +# SHA1 Fingerprint: 87:82:c6:c3:04:35:3b:cf:d2:96:92:d2:59:3e:7d:44:d9:34:ff:11 +# SHA256 Fingerprint: f1:c1:b5:0a:e5:a2:0d:d8:03:0e:c9:f6:bc:24:82:3d:d3:67:b5:25:57:59:b4:e7:1b:61:fc:e9:f7:37:5d:73 +-----BEGIN CERTIFICATE----- +MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI +MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x +FzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz +MTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv +cnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz +Zum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO +0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao +wW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj +7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS +8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT +BgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg +JYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC +NxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3 +6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/ +3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm +D5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS +CPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR +3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= +-----END CERTIFICATE----- + +# Issuer: CN=Secure Global CA O=SecureTrust Corporation +# Subject: CN=Secure Global CA O=SecureTrust Corporation +# Label: "Secure Global CA" +# Serial: 9751836167731051554232119481456978597 +# MD5 Fingerprint: cf:f4:27:0d:d4:ed:dc:65:16:49:6d:3d:da:bf:6e:de +# SHA1 Fingerprint: 3a:44:73:5a:e5:81:90:1f:24:86:61:46:1e:3b:9c:c4:5f:f5:3a:1b +# SHA256 Fingerprint: 42:00:f5:04:3a:c8:59:0e:bb:52:7d:20:9e:d1:50:30:29:fb:cb:d4:1c:a1:b5:06:ec:27:f1:5a:de:7d:ac:69 +-----BEGIN CERTIFICATE----- +MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBK +MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x +GTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkx +MjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3Qg +Q29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jxYDiJ +iQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa +/FHtaMbQbqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJ +jnIFHovdRIWCQtBJwB1g8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnI +HmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYVHDGA76oYa8J719rO+TMg1fW9ajMtgQT7 +sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi0XPnj3pDAgMBAAGjgZ0w +gZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCsw +KaAnoCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsG +AQQBgjcVAQQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0L +URYD7xh8yOOvaliTFGCRsoTciE6+OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXO +H0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cnCDpOGR86p1hcF895P4vkp9Mm +I50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/53CYNv6ZHdAbY +iNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc +f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW +-----END CERTIFICATE----- + +# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO Certification Authority O=COMODO CA Limited +# Label: "COMODO Certification Authority" +# Serial: 104350513648249232941998508985834464573 +# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75 +# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b +# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66 +-----BEGIN CERTIFICATE----- +MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB +gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV +BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw +MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl +YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P +RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3 +UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI +2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8 +Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp ++2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+ +DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O +nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW +/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g +PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u +QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY +SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv +IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ +RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4 +zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd +BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB +ZQ== +-----END CERTIFICATE----- + +# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Label: "COMODO ECC Certification Authority" +# Serial: 41578283867086692638256921589707938090 +# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23 +# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11 +# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7 +-----BEGIN CERTIFICATE----- +MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT +IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw +MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy +ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N +T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR +FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J +cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW +BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm +fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv +GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= +-----END CERTIFICATE----- + +# Issuer: CN=Certigna O=Dhimyotis +# Subject: CN=Certigna O=Dhimyotis +# Label: "Certigna" +# Serial: 18364802974209362175 +# MD5 Fingerprint: ab:57:a6:5b:7d:42:82:19:b5:d8:58:26:28:5e:fd:ff +# SHA1 Fingerprint: b1:2e:13:63:45:86:a4:6f:1a:b2:60:68:37:58:2d:c4:ac:fd:94:97 +# SHA256 Fingerprint: e3:b6:a2:db:2e:d7:ce:48:84:2f:7a:c5:32:41:c7:b7:1d:54:14:4b:fb:40:c1:1f:3f:1d:0b:42:f5:ee:a1:2d +-----BEGIN CERTIFICATE----- +MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNV +BAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4X +DTA3MDYyOTE1MTMwNVoXDTI3MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQ +BgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwIQ2VydGlnbmEwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7qXOEm7RFHYeGifBZ4 +QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyHGxny +gQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbw +zBfsV1/pogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q +130yGLMLLGq/jj8UEYkgDncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2 +JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKfIrjxwo1p3Po6WAbfAgMBAAGjgbwwgbkw +DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQtCRZvgHyUtVF9lo53BEw +ZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJBgNVBAYT +AkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzj +AQ/JSP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG +9w0BAQUFAAOCAQEAhQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8h +bV6lUmPOEvjvKtpv6zf+EwLHyzs+ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFnc +fca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1kluPBS1xp81HlDQwY9qcEQCYsuu +HWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY1gkIl2PlwS6w +t0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw +WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== +-----END CERTIFICATE----- + +# Issuer: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority +# Subject: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority +# Label: "ePKI Root Certification Authority" +# Serial: 28956088682735189655030529057352760477 +# MD5 Fingerprint: 1b:2e:00:ca:26:06:90:3d:ad:fe:6f:15:68:d3:6b:b3 +# SHA1 Fingerprint: 67:65:0d:f1:7e:8e:7e:5b:82:40:a4:f4:56:4b:cf:e2:3d:69:c6:f0 +# SHA256 Fingerprint: c0:a6:f4:dc:63:a2:4b:fd:cf:54:ef:2a:6a:08:2a:0a:72:de:35:80:3e:2f:f5:ff:52:7a:e5:d8:72:06:df:d5 +-----BEGIN CERTIFICATE----- +MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe +Fw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw +IQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL +SSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH +SyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh +ijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X +DZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1 +TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ +fzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA +sgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU +WH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS +nT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH +dmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip +NiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC +AwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF +MAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH +ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGB +uvl2ICO1J2B01GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6Yl +PwZpVnPDimZI+ymBV3QGypzqKOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkP +JXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdVxrsStZf0X4OFunHB2WyBEXYKCrC/ +gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEPNXubrjlpC2JgQCA2 +j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+rGNm6 +5ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUB +o2M3IUxExJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS +/jQ6fbjpKdx2qcgw+BRxgMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2z +Gp1iro2C6pSe3VkQw63d4k3jMdXH7OjysP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTE +W9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D +hNQ+IIX3Sj0rnP0qCglN6oH4EZw= +-----END CERTIFICATE----- + +# Issuer: O=certSIGN OU=certSIGN ROOT CA +# Subject: O=certSIGN OU=certSIGN ROOT CA +# Label: "certSIGN ROOT CA" +# Serial: 35210227249154 +# MD5 Fingerprint: 18:98:c0:d6:e9:3a:fc:f9:b0:f5:0c:f7:4b:01:44:17 +# SHA1 Fingerprint: fa:b7:ee:36:97:26:62:fb:2d:b0:2a:f6:bf:03:fd:e8:7c:4b:2f:9b +# SHA256 Fingerprint: ea:a9:62:c4:fa:4a:6b:af:eb:e4:15:19:6d:35:1c:cd:88:8d:4f:53:f3:fa:8a:e6:d7:c4:66:a9:4e:60:42:bb +-----BEGIN CERTIFICATE----- +MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYT +AlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBD +QTAeFw0wNjA3MDQxNzIwMDRaFw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJP +MREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7IJUqOtdu0KBuqV5Do +0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHHrfAQ +UySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5d +RdY4zTW2ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQ +OA7+j0xbm0bqQfWwCHTD0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwv +JoIQ4uNllAoEwF73XVv4EOLQunpL+943AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08C +AwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAcYwHQYDVR0O +BBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IBAQA+0hyJ +LjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecY +MnQ8SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ +44gx+FkagQnIl6Z0x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6I +Jd1hJyMctTEHBDa0GpC9oHRxUIltvBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNw +i/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7NzTogVZ96edhBiIL5VaZVDADlN +9u6wWk5JRFRYX0KD +-----END CERTIFICATE----- + +# Issuer: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) +# Subject: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) +# Label: "NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny" +# Serial: 80544274841616 +# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88 +# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91 +# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98 +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG +EwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3 +MDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl +cnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR +dGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB +pzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM +b2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm +aWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz +IEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT +lF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz +AZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5 +VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG +ILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2 +BJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG +AQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M +U9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh +bvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C ++C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC +bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F +uLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2 +XjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= +-----END CERTIFICATE----- + +# Issuer: CN=SecureSign RootCA11 O=Japan Certification Services, Inc. +# Subject: CN=SecureSign RootCA11 O=Japan Certification Services, Inc. +# Label: "SecureSign RootCA11" +# Serial: 1 +# MD5 Fingerprint: b7:52:74:e2:92:b4:80:93:f2:75:e4:cc:d7:f2:ea:26 +# SHA1 Fingerprint: 3b:c4:9f:48:f8:f3:73:a0:9c:1e:bd:f8:5b:b1:c3:65:c7:d8:11:b3 +# SHA256 Fingerprint: bf:0f:ee:fb:9e:3a:58:1a:d5:f9:e9:db:75:89:98:57:43:d2:61:08:5c:4d:31:4f:6f:5d:72:59:aa:42:16:12 +-----BEGIN CERTIFICATE----- +MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDEr +MCkGA1UEChMiSmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoG +A1UEAxMTU2VjdXJlU2lnbiBSb290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0 +MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSswKQYDVQQKEyJKYXBhbiBDZXJ0aWZp +Y2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1cmVTaWduIFJvb3RD +QTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvLTJsz +i1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8 +h9uuywGOwvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOV +MdrAG/LuYpmGYz+/3ZMqg6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9 +UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rPO7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni +8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitAbpSACW22s293bzUIUPsC +h8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZXt94wDgYD +VR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB +AKChOBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xm +KbabfSVSSUOrTC4rbnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQ +X5Ucv+2rIrVls4W6ng+4reV6G4pQOh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWr +QbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01y8hSyn+B/tlr0/cR7SXf+Of5 +pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061lgeLKBObjBmN +QSdJQO7e5iNEOdyhIta6A/I= +-----END CERTIFICATE----- + +# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. +# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. +# Label: "Microsec e-Szigno Root CA 2009" +# Serial: 14014712776195784473 +# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1 +# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e +# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78 +-----BEGIN CERTIFICATE----- +MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD +VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0 +ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G +CSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y +OTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx +FjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp +Z25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o +dTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP +kd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc +cbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U +fIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7 +N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC +xkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1 ++rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM +Pcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG +SIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h +mLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk +ddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 +tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c +2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t +HMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Label: "GlobalSign Root CA - R3" +# Serial: 4835703278459759426209954 +# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28 +# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad +# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b +-----BEGIN CERTIFICATE----- +MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G +A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp +Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 +MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG +A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 +RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT +gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm +KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd +QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ +XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw +DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o +LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU +RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp +jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK +6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX +mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs +Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH +WD9f +-----END CERTIFICATE----- + +# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Label: "Autoridad de Certificacion Firmaprofesional CIF A62634068" +# Serial: 6047274297262753887 +# MD5 Fingerprint: 73:3a:74:7a:ec:bb:a3:96:a6:c2:e4:e2:c8:9b:c0:c3 +# SHA1 Fingerprint: ae:c5:fb:3f:c8:e1:bf:c4:e5:4f:03:07:5a:9a:e8:00:b7:f7:b6:fa +# SHA256 Fingerprint: 04:04:80:28:bf:1f:28:64:d4:8f:9a:d4:d8:32:94:36:6a:82:88:56:55:3f:3b:14:30:3f:90:14:7f:5d:40:ef +-----BEGIN CERTIFICATE----- +MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UE +BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h +cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEy +MzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg +Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9 +thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM +cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG +L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i +NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h +X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b +m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy +Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja +EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T +KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF +6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh +OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYD +VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNHDhpkLzCBpgYD +VR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp +cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBv +ACAAZABlACAAbABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBl +AGwAbwBuAGEAIAAwADgAMAAxADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF +661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx51tkljYyGOylMnfX40S2wBEqgLk9 +am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qkR71kMrv2JYSiJ0L1 +ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaPT481 +PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS +3a/DTg4fJl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5k +SeTy36LssUzAKh3ntLFlosS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF +3dvd6qJ2gHN99ZwExEWN57kci57q13XRcrHedUTnQn3iV2t93Jm8PYMo6oCTjcVM +ZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoRsaS8I8nkvof/uZS2+F0g +StRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTDKCOM/icz +Q0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQB +jLMi6Et8Vcad+qMUu2WFbm5PEn4KPJ2V +-----END CERTIFICATE----- + +# Issuer: CN=Izenpe.com O=IZENPE S.A. +# Subject: CN=Izenpe.com O=IZENPE S.A. +# Label: "Izenpe.com" +# Serial: 917563065490389241595536686991402621 +# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73 +# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19 +# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f +-----BEGIN CERTIFICATE----- +MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4 +MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6 +ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD +VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j +b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq +scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO +xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H +LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX +uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD +yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+ +JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q +rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN +BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L +hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB +QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+ +HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu +Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg +QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB +BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx +MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA +A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb +laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56 +awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo +JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw +LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT +VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk +LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb +UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/ +QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+ +naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls +QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== +-----END CERTIFICATE----- + +# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Label: "Go Daddy Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01 +# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b +# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT +EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp +ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz +NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH +EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE +AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD +E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH +/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy +DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh +GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR +tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA +AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX +WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu +9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr +gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo +2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI +4uJEvlz36hz1 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96 +# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e +# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5 +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs +ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw +MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 +b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj +aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp +Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg +nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1 +HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N +Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN +dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0 +HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G +CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU +sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3 +4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg +8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K +pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1 +mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Services Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2 +# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f +# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5 +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs +ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 +MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD +VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy +ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy +dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p +OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2 +8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K +Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe +hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk +6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw +DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q +AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI +bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB +ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z +qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd +iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn +0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN +sSi6 +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Commercial O=AffirmTrust +# Subject: CN=AffirmTrust Commercial O=AffirmTrust +# Label: "AffirmTrust Commercial" +# Serial: 8608355977964138876 +# MD5 Fingerprint: 82:92:ba:5b:ef:cd:8a:6f:a6:3d:55:f9:84:f6:d6:b7 +# SHA1 Fingerprint: f9:b5:b6:32:45:5f:9c:be:ec:57:5f:80:dc:e9:6e:2c:c7:b2:78:b7 +# SHA256 Fingerprint: 03:76:ab:1d:54:c5:f9:80:3c:e4:b2:e2:01:a0:ee:7e:ef:7b:57:b6:36:e8:a9:3c:9b:8d:48:60:c9:6f:5f:a7 +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz +dCBDb21tZXJjaWFsMB4XDTEwMDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDEL +MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp +cm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6EqdbDuKP +Hx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yr +ba0F8PrVC8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPAL +MeIrJmqbTFeurCA+ukV6BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1 +yHp52UKqK39c/s4mT6NmgTWvRLpUHhwwMmWd5jyTXlBOeuM61G7MGvv50jeuJCqr +VwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNVHQ4EFgQUnZPGU4teyq8/ +nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ +KoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYG +XUPGhi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNj +vbz4YYCanrHOQnDiqX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivt +Z8SOyUOyXGsViQK8YvxO8rUzqrJv0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9g +N53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0khsUlHRUe072o0EclNmsxZt9YC +nlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Networking O=AffirmTrust +# Subject: CN=AffirmTrust Networking O=AffirmTrust +# Label: "AffirmTrust Networking" +# Serial: 8957382827206547757 +# MD5 Fingerprint: 42:65:ca:be:01:9a:9a:4c:a9:8c:41:49:cd:c0:d5:7f +# SHA1 Fingerprint: 29:36:21:02:8b:20:ed:02:f5:66:c5:32:d1:d6:ed:90:9f:45:00:2f +# SHA256 Fingerprint: 0a:81:ec:5a:92:97:77:f1:45:90:4a:f3:8d:5d:50:9f:66:b5:e2:c5:8f:cd:b5:31:05:8b:0e:17:f3:f0:b4:1b +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz +dCBOZXR3b3JraW5nMB4XDTEwMDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDEL +MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp +cm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SEHi3y +YJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbua +kCNrmreIdIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRL +QESxG9fhwoXA3hA/Pe24/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp +6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gbh+0t+nvujArjqWaJGctB+d1ENmHP4ndG +yH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNVHQ4EFgQUBx/S55zawm6i +QLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ +KoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfO +tDIuUFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzu +QY0x2+c06lkh1QF612S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZ +Lgo/bNjR9eUJtGxUAArgFU2HdW23WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4u +olu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9/ZFvgrG+CJPbFEfxojfHRZ48 +x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Premium O=AffirmTrust +# Subject: CN=AffirmTrust Premium O=AffirmTrust +# Label: "AffirmTrust Premium" +# Serial: 7893706540734352110 +# MD5 Fingerprint: c4:5d:0e:48:b6:ac:28:30:4e:0a:bc:f9:38:16:87:57 +# SHA1 Fingerprint: d8:a6:33:2c:e0:03:6f:b1:85:f6:63:4f:7d:6a:06:65:26:32:28:27 +# SHA256 Fingerprint: 70:a7:3f:7f:37:6b:60:07:42:48:90:45:34:b1:14:82:d5:bf:0e:69:8e:cc:49:8d:f5:25:77:eb:f2:e9:3b:9a +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVz +dCBQcmVtaXVtMB4XDTEwMDEyOTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkG +A1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1U +cnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxBLf +qV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtnBKAQ +JG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ ++jjeRFcV5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrS +s8PhaJyJ+HoAVt70VZVs+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5 +HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmdGPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d7 +70O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5Rp9EixAqnOEhss/n/fauG +V+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NIS+LI+H+S +qHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S +5u046uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4Ia +C1nEWTJ3s7xgaVY5/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TX +OwF0lkLgAOIua+rF7nKsu7/+6qqo+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYE +FJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByvMiPIs0laUZx2 +KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg +Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B +8OWycvpEgjNC6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQ +MKSOyARiqcTtNd56l+0OOF6SL5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc +0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK+4w1IX2COPKpVJEZNZOUbWo6xbLQ +u4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmVBtWVyuEklut89pMF +u+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFgIxpH +YoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8 +GKa1qF60g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaO +RtGdFNrHF+QFlozEJLUbzxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6e +KeC2uAloGRwYQw== +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Premium ECC O=AffirmTrust +# Subject: CN=AffirmTrust Premium ECC O=AffirmTrust +# Label: "AffirmTrust Premium ECC" +# Serial: 8401224907861490260 +# MD5 Fingerprint: 64:b0:09:55:cf:b1:d5:99:e2:be:13:ab:a6:5d:ea:4d +# SHA1 Fingerprint: b8:23:6b:00:2f:1d:16:86:53:01:55:6c:11:a4:37:ca:eb:ff:c3:bb +# SHA256 Fingerprint: bd:71:fd:f6:da:97:e4:cf:62:d1:64:7a:dd:25:81:b0:7d:79:ad:f8:39:7e:b4:ec:ba:9c:5e:84:88:82:14:23 +-----BEGIN CERTIFICATE----- +MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMC +VVMxFDASBgNVBAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQ +cmVtaXVtIEVDQzAeFw0xMDAxMjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJ +BgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwXQWZmaXJt +VHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQNMF4bFZ0D +0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQN8O9 +ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0G +A1UdDgQWBBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4G +A1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/Vs +aobgxCd05DhT1wV/GzTjxi+zygk8N53X57hG8f2h4nECMEJZh0PUUd+60wkyWs6I +flc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKMeQ== +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Network CA" +# Serial: 279744 +# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78 +# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e +# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e +-----BEGIN CERTIFICATE----- +MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM +MSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D +ZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU +cnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3 +WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg +Uy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw +IAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH +UV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM +TXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU +BBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM +kUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x +AcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV +HQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y +sHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL +I9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8 +J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY +VoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI +03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= +-----END CERTIFICATE----- + +# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA +# Label: "TWCA Root Certification Authority" +# Serial: 1 +# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79 +# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48 +# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44 +-----BEGIN CERTIFICATE----- +MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES +MBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU +V0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz +WhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO +LUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE +AcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH +K3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX +RfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z +rX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx +3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq +hkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC +MErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls +XebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D +lhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn +aspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ +YiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== +-----END CERTIFICATE----- + +# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 +# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 +# Label: "Security Communication RootCA2" +# Serial: 0 +# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43 +# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74 +# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6 +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl +MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe +U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX +DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy +dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj +YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV +OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr +zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM +VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ +hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO +ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw +awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs +OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3 +DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF +coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc +okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8 +t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy +1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/ +SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 +-----END CERTIFICATE----- + +# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 +# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 +# Label: "Actalis Authentication Root CA" +# Serial: 6271844772424770508 +# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6 +# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac +# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 +-----BEGIN CERTIFICATE----- +MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE +BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w +MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 +IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC +SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1 +ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv +UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX +4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9 +KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/ +gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb +rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ +51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F +be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe +KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F +v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn +fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7 +jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz +ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt +ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL +e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70 +jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz +WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V +SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j +pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX +X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok +fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R +K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU +ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU +LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT +LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== +-----END CERTIFICATE----- + +# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 +# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 +# Label: "Buypass Class 2 Root CA" +# Serial: 2 +# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29 +# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99 +# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48 +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd +MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg +Q2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow +TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw +HgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB +BQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr +6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV +L4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91 +1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx +MlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ +QmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB +arcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr +Us3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi +FRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS +P/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN +9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP +AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz +uvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h +9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s +A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t +OluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo ++fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7 +KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2 +DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us +H8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ +I+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7 +5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h +3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz +Y11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA= +-----END CERTIFICATE----- + +# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 +# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 +# Label: "Buypass Class 3 Root CA" +# Serial: 2 +# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec +# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57 +# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd +MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg +Q2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow +TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw +HgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB +BQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y +ZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E +N3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9 +tznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX +0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c +/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X +KhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY +zIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS +O1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D +34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP +K9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3 +AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv +Tg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj +QTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV +cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS +IGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2 +HJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa +O5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv +033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u +dmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE +kbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41 +3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD +u79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq +4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc= +-----END CERTIFICATE----- + +# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Label: "T-TeleSec GlobalRoot Class 3" +# Serial: 1 +# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef +# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1 +# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx +KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd +BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl +YyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1 +OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy +aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 +ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN +8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/ +RLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4 +hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5 +ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM +EnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1 +A/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy +WL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ +1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30 +6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT +91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml +e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p +TpPDpFQUWw== +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH +# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH +# Label: "D-TRUST Root Class 3 CA 2 2009" +# Serial: 623603 +# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f +# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0 +# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1 +-----BEGIN CERTIFICATE----- +MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF +MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD +bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha +ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM +HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03 +UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42 +tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R +ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM +lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp +/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G +A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G +A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj +dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy +MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl +cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js +L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL +BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni +acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 +o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K +zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8 +PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y +Johw1+qRzT65ysCQblrGXnRl11z+o+I= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH +# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH +# Label: "D-TRUST Root Class 3 CA 2 EV 2009" +# Serial: 623604 +# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6 +# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83 +# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81 +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF +MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD +bGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw +NDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV +BAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn +ljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0 +3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z +qQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR +p75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8 +HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw +ggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea +HNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw +Oi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh +c3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E +RT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt +dHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku +Y3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp +3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 +nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF +CSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na +xpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX +KVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1 +-----END CERTIFICATE----- + +# Issuer: CN=CA Disig Root R2 O=Disig a.s. +# Subject: CN=CA Disig Root R2 O=Disig a.s. +# Label: "CA Disig Root R2" +# Serial: 10572350602393338211 +# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03 +# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71 +# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03 +-----BEGIN CERTIFICATE----- +MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV +BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu +MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy +MDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx +EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw +ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe +NcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH +PWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I +x2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe +QTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR +yyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO +QG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912 +H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ +QfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD +i/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs +nLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1 +rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud +DwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI +hvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM +tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf +GopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb +lvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka ++elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal +TFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i +nSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3 +gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr +G5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os +zMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x +L4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL +-----END CERTIFICATE----- + +# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV +# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV +# Label: "ACCVRAIZ1" +# Serial: 6828503384748696800 +# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02 +# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17 +# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13 +-----BEGIN CERTIFICATE----- +MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE +AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw +CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ +BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND +VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb +qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY +HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo +G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA +lHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr +IA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/ +0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH +k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47 +4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO +m3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa +cXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl +uUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI +KwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls +ZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG +AQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 +VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT +VfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG +CCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA +cgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA +QwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA +7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA +cgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA +QwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA +czAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu +aHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt +aW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud +DwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF +BQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp +D70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU +JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m +AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD +vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms +tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH +7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h +I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA +h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF +d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H +pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7 +-----END CERTIFICATE----- + +# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA +# Label: "TWCA Global Root CA" +# Serial: 3262 +# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96 +# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65 +# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx +EjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT +VFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5 +NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT +B1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF +10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz +0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh +MBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH +zIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc +46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2 +yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi +laLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP +oA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA +BDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE +qYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm +4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL +1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn +LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF +H6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo +RI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+ +nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh +15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW +6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW +nsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j +wa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz +aGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy +KwbQBM0= +-----END CERTIFICATE----- + +# Issuer: CN=TeliaSonera Root CA v1 O=TeliaSonera +# Subject: CN=TeliaSonera Root CA v1 O=TeliaSonera +# Label: "TeliaSonera Root CA v1" +# Serial: 199041966741090107964904287217786801558 +# MD5 Fingerprint: 37:41:49:1b:18:56:9a:26:f5:ad:c2:66:fb:40:a5:4c +# SHA1 Fingerprint: 43:13:bb:96:f1:d5:86:9b:c1:4e:6a:92:f6:cf:f6:34:69:87:82:37 +# SHA256 Fingerprint: dd:69:36:fe:21:f8:f0:77:c1:23:a1:a5:21:c1:22:24:f7:22:55:b7:3e:03:a7:26:06:93:e8:a2:4b:0f:a3:89 +-----BEGIN CERTIFICATE----- +MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAw +NzEUMBIGA1UECgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJv +b3QgQ0EgdjEwHhcNMDcxMDE4MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYD +VQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwWVGVsaWFTb25lcmEgUm9vdCBDQSB2 +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+6yfwIaPzaSZVfp3F +VRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA3GV1 +7CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+X +Z75Ljo1kB1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+ +/jXh7VB7qTCNGdMJjmhnXb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs +81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxHoLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkm +dtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3F0fUTPHSiXk+TT2YqGHe +Oh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJoWjiUIMu +sDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4 +pgd7gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fs +slESl1MpWtTwEhDcTwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQ +arMCpgKIv7NHfirZ1fpoeDVNAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYD +VR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qWDNXr+nuqF+gTEjANBgkqhkiG +9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNmzqjMDfz1mgbl +dxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx +0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1Tj +TQpgcmLNkQfWpb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBed +Y2gea+zDTYa4EzAvXUYNR0PVG6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7 +Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpcc41teyWRyu5FrgZLAMzTsVlQ2jqI +OylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOTJsjrDNYmiLbAJM+7 +vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2qReW +t88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcn +HL/EVlP6Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVx +SK236thZiNSQvxaz2emsWWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= +-----END CERTIFICATE----- + +# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Label: "T-TeleSec GlobalRoot Class 2" +# Serial: 1 +# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a +# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9 +# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52 +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx +KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd +BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl +YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1 +OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy +aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 +ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd +AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC +FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi +1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq +jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ +wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/ +WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy +NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC +uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw +IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6 +g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN +9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP +BSeOE6Fuwg== +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot 2011 O=Atos +# Subject: CN=Atos TrustedRoot 2011 O=Atos +# Label: "Atos TrustedRoot 2011" +# Serial: 6643877497813316402 +# MD5 Fingerprint: ae:b9:c4:32:4b:ac:7f:5d:66:cc:77:94:bb:2a:77:56 +# SHA1 Fingerprint: 2b:b1:f5:3e:55:0c:1d:c5:f1:d4:e6:b7:6a:46:4b:55:06:02:ac:21 +# SHA256 Fingerprint: f3:56:be:a2:44:b7:a9:1e:b3:5d:53:ca:9a:d7:86:4a:ce:01:8e:2d:35:d5:f8:f9:6d:df:68:a6:f4:1a:a4:74 +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE +AwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG +EwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM +FUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC +REUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp +Nb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM +VD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+ +SZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ +4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L +cp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi +eowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG +A1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3 +DQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j +vZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP +DpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc +maHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D +lmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv +KrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 1 G3" +# Serial: 687049649626669250736271037606554624078720034195 +# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab +# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67 +# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00 +MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV +wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe +rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341 +68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh +4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp +UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o +abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc +3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G +KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt +hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO +Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt +zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD +ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC +MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2 +cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN +qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5 +YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv +b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2 +8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k +NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj +ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp +q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt +nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 2 G3" +# Serial: 390156079458959257446133169266079962026824725800 +# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06 +# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 +# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00 +MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf +qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW +n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym +c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+ +O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1 +o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j +IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq +IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz +8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh +vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l +7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG +cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD +ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 +AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC +roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga +W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n +lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE ++V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV +csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd +dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg +KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM +HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4 +WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 3 G3" +# Serial: 268090761170461462463995952157327242137089239581 +# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7 +# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d +# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00 +MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR +/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu +FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR +U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c +ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR +FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k +A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw +eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl +sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp +VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q +A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+ +ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD +ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px +KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI +FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv +oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg +u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP +0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf +3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl +8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+ +DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN +PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ +ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0 +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root G2" +# Serial: 15385348160840213938643033620894905419 +# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d +# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f +# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85 +-----BEGIN CERTIFICATE----- +MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA +n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc +biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp +EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA +bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu +YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB +AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW +BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI +QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I +0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni +lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9 +B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv +ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo +IhNzbM8m9Yop5w== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root G3" +# Serial: 15459312981008553731928384953135426796 +# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb +# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89 +# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2 +-----BEGIN CERTIFICATE----- +MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw +CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu +ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg +RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu +Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf +Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q +RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD +AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY +JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv +6pZjamVFkpUBtA== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root G2" +# Serial: 4293743540046975378534879503202253541 +# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44 +# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4 +# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f +-----BEGIN CERTIFICATE----- +MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH +MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI +2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx +1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ +q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz +tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ +vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV +5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY +1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4 +NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG +Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91 +8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe +pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl +MrY= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root G3" +# Serial: 7089244469030293291760083333884364146 +# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca +# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e +# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0 +-----BEGIN CERTIFICATE----- +MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw +CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu +ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe +Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw +EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x +IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG +fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO +Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd +BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx +AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/ +oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8 +sycX +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Trusted Root G4" +# Serial: 7451500558977370777930084869016614236 +# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49 +# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4 +# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88 +-----BEGIN CERTIFICATE----- +MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg +RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu +Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y +ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If +xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV +ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO +DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ +jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/ +CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi +EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM +fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY +uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK +chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t +9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD +ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2 +SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd ++SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc +fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa +sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N +cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N +0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie +4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI +r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1 +/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm +gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+ +-----END CERTIFICATE----- + +# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited +# Label: "COMODO RSA Certification Authority" +# Serial: 101909084537582093308941363524873193117 +# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18 +# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4 +# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34 +-----BEGIN CERTIFICATE----- +MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB +hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV +BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5 +MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT +EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR +Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR +6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X +pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC +9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV +/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf +Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z ++pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w +qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah +SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC +u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf +Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq +crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E +FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB +/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl +wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM +4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV +2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna +FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ +CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK +boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke +jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL +S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb +QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl +0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB +NVOFBkpdn627G190 +-----END CERTIFICATE----- + +# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network +# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network +# Label: "USERTrust RSA Certification Authority" +# Serial: 2645093764781058787591871645665788717 +# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5 +# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e +# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2 +-----BEGIN CERTIFICATE----- +MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB +iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl +cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV +BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw +MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV +BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU +aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy +dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK +AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B +3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY +tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ +Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 +VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT +79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 +c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT +Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l +c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee +UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE +Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd +BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G +A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF +Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO +VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 +ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs +8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR +iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze +Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ +XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ +qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB +VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB +L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG +jjxDah2nGN59PRbxYvnKkKj9 +-----END CERTIFICATE----- + +# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network +# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network +# Label: "USERTrust ECC Certification Authority" +# Serial: 123013823720199481456569720443997572134 +# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1 +# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0 +# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a +-----BEGIN CERTIFICATE----- +MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL +MAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl +eSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT +JVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx +MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT +Ck5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg +VVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo +I+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng +o4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G +A1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB +zzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW +RNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg= +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 +# Label: "GlobalSign ECC Root CA - R5" +# Serial: 32785792099990507226680698011560947931244 +# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08 +# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa +# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24 +-----BEGIN CERTIFICATE----- +MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk +MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH +bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX +DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD +QSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc +8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke +hOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI +KoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg +515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO +xwy8p2Fp8fc74SrL+SvzZpA3 +-----END CERTIFICATE----- + +# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust +# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust +# Label: "IdenTrust Commercial Root CA 1" +# Serial: 13298821034946342390520003877796839426 +# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7 +# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25 +# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu +VHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw +MTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw +JQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT +3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU ++ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp +S0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1 +bVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi +T0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL +vYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK +Vsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK +dHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT +c+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv +l7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N +iGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD +ggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH +6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt +LRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93 +nAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3 ++wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK +W2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT +AwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq +l1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG +4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ +mUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A +7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H +-----END CERTIFICATE----- + +# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust +# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust +# Label: "IdenTrust Public Sector Root CA 1" +# Serial: 13298821034946342390521976156843933698 +# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba +# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd +# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu +VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN +MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0 +MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7 +ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy +RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS +bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF +/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R +3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw +EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy +9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V +GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ +2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV +WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD +W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN +AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj +t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV +DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9 +TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G +lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW +mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df +WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5 ++bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ +tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA +GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv +8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority - G2 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2009 Entrust, Inc. - for authorized use only +# Subject: CN=Entrust Root Certification Authority - G2 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2009 Entrust, Inc. - for authorized use only +# Label: "Entrust Root Certification Authority - G2" +# Serial: 1246989352 +# MD5 Fingerprint: 4b:e2:c9:91:96:65:0c:f4:0e:5a:93:92:a0:0a:fe:b2 +# SHA1 Fingerprint: 8c:f4:27:fd:79:0c:3a:d1:66:06:8d:e8:1e:57:ef:bb:93:22:72:d4 +# SHA256 Fingerprint: 43:df:57:74:b0:3e:7f:ef:5f:e4:0d:93:1a:7b:ed:f1:bb:2e:6b:42:73:8c:4e:6d:38:41:10:3d:3a:a7:f3:39 +-----BEGIN CERTIFICATE----- +MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50 +cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3Qs +IEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVz +dCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwHhcNMDkwNzA3MTcy +NTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUVu +dHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwt +dGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0 +aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP/vaCeb9zYQYKpSfYs1/T +RU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXzHHfV1IWN +cCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hW +wcKUs/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1 +U1+cPvQXLOZprE4yTGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0 +jaWvYkxN4FisZDQSA/i2jZRjJKRxAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ60B7vfec7aVHUbI2fkBJmqzAN +BgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5ZiXMRrEPR9RP/ +jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ +Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v +1fN2D807iDginWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4R +nAuknZoh8/CbCzB428Hch0P+vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmH +VHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xOe4pIb4tF9g== +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority - EC1 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2012 Entrust, Inc. - for authorized use only +# Subject: CN=Entrust Root Certification Authority - EC1 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2012 Entrust, Inc. - for authorized use only +# Label: "Entrust Root Certification Authority - EC1" +# Serial: 51543124481930649114116133369 +# MD5 Fingerprint: b6:7e:1d:f0:58:c5:49:6c:24:3b:3d:ed:98:18:ed:bc +# SHA1 Fingerprint: 20:d8:06:40:df:9b:25:f5:12:25:3a:11:ea:f7:59:8a:eb:14:b5:47 +# SHA256 Fingerprint: 02:ed:0e:b2:8c:14:da:45:16:5c:56:67:91:70:0d:64:51:d7:fb:56:f0:b2:ab:1d:3b:8e:b0:70:e5:6e:df:f5 +-----BEGIN CERTIFICATE----- +MIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkG +A1UEBhMCVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3 +d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVu +dHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEzMDEGA1UEAxMq +RW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRUMxMB4XDTEy +MTIxODE1MjUzNloXDTM3MTIxODE1NTUzNlowgb8xCzAJBgNVBAYTAlVTMRYwFAYD +VQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0 +L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxMiBFbnRydXN0LCBJbmMuIC0g +Zm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMzAxBgNVBAMTKkVudHJ1c3QgUm9vdCBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEVDMTB2MBAGByqGSM49AgEGBSuBBAAi +A2IABIQTydC6bUF74mzQ61VfZgIaJPRbiWlH47jCffHyAsWfoPZb1YsGGYZPUxBt +ByQnoaD41UcZYUx9ypMn6nQM72+WCf5j7HBdNq1nd67JnXxVRDqiY1Ef9eNi1KlH +Bz7MIKNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O +BBYEFLdj5xrdjekIplWDpOBqUEFlEUJJMAoGCCqGSM49BAMDA2cAMGQCMGF52OVC +R98crlOZF7ZvHH3hvxGU0QOIdeSNiaSKd0bebWHvAvX7td/M/k7//qnmpwIwW5nX +hTcGtXsI/esni0qU+eH6p44mCOh8kmhtc9hvJqwhAriZtyZBWyVgrtBIGu4G +-----END CERTIFICATE----- + +# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority +# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority +# Label: "CFCA EV ROOT" +# Serial: 407555286 +# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30 +# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83 +# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd +-----BEGIN CERTIFICATE----- +MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD +TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y +aXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx +MjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j +aWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP +T1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03 +sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL +TIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5 +/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp +7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz +EpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt +hxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP +a931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot +aK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg +TnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV +PKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv +cWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL +tbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd +BgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB +ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT +ej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL +jOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS +ESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy +P5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19 +xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d +Ci77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN +5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe +/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z +AAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ +5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su +-----END CERTIFICATE----- + +# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed +# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed +# Label: "OISTE WISeKey Global Root GB CA" +# Serial: 157768595616588414422159278966750757568 +# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d +# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed +# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6 +-----BEGIN CERTIFICATE----- +MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt +MQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg +Rm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i +YWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x +CzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG +b3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh +bCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3 +HEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx +WuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX +1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk +u7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P +99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r +M2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB +BAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh +cViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5 +gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO +ZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf +aPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic +Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM= +-----END CERTIFICATE----- + +# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. +# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. +# Label: "SZAFIR ROOT CA2" +# Serial: 357043034767186914217277344587386743377558296292 +# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99 +# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de +# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe +-----BEGIN CERTIFICATE----- +MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL +BQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6 +ZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw +NzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L +cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg +Uk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN +QLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT +3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw +3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6 +3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5 +BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN +XGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF +AAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw +8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG +nXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP +oky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy +d05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg +LvWpCz/UXeHPhJ/iGcJfitYgHuNztw== +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Network CA 2" +# Serial: 44979900017204383099463764357512596969 +# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2 +# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92 +# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 +-----BEGIN CERTIFICATE----- +MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB +gDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu +QS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG +A1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz +OTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ +VW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3 +b3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA +DGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn +0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB +OJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE +fktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E +Sv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m +o130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i +sx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW +OZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez +Tv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS +adgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n +3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ +F/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf +CVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29 +XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm +djWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/ +WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb +AoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq +P/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko +b7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj +XALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P +5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi +DrW5viSP +-----END CERTIFICATE----- + +# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Label: "Hellenic Academic and Research Institutions RootCA 2015" +# Serial: 0 +# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce +# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6 +# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36 +-----BEGIN CERTIFICATE----- +MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix +DzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k +IFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT +N0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v +dENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG +A1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh +ZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx +QDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 +dGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC +AQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA +4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0 +AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10 +4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C +ojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV +9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD +gfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6 +Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq +NhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko +LfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc +Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd +ctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I +XtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI +M4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot +9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V +Z5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea +j8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh +X9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ +l033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf +bzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4 +pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK +e7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0 +vm9qp/UsQu0yrbYhnr68 +-----END CERTIFICATE----- + +# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Label: "Hellenic Academic and Research Institutions ECC RootCA 2015" +# Serial: 0 +# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef +# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66 +# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33 +-----BEGIN CERTIFICATE----- +MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN +BgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl +c2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl +bGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv +b3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ +BgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj +YWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5 +MUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0 +dXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg +QehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa +jq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi +C4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep +lSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof +TUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR +-----END CERTIFICATE----- + +# Issuer: CN=ISRG Root X1 O=Internet Security Research Group +# Subject: CN=ISRG Root X1 O=Internet Security Research Group +# Label: "ISRG Root X1" +# Serial: 172886928669790476064670243504169061120 +# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e +# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8 +# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- + +# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM +# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM +# Label: "AC RAIZ FNMT-RCM" +# Serial: 485876308206448804701554682760554759 +# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d +# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20 +# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx +CzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ +WiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ +BgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG +Tk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/ +yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf +BBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz +WHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF +tBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z +374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC +IfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL +mbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7 +wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS +MKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2 +ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet +UqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H +YJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3 +LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD +nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1 +RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM +LVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf +77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N +JpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm +fZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp +6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp +1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B +9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok +RqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv +uu8wd+RU4riEmViAqhOLUTpPSPaLtrM= +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 1 O=Amazon +# Subject: CN=Amazon Root CA 1 O=Amazon +# Label: "Amazon Root CA 1" +# Serial: 143266978916655856878034712317230054538369994 +# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6 +# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16 +# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e +-----BEGIN CERTIFICATE----- +MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj +ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM +9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw +IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 +VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L +93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm +jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA +A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI +U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs +N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv +o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU +5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy +rqXRfboQnoZsG4q5WTP468SQvvG5 +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 2 O=Amazon +# Subject: CN=Amazon Root CA 2 O=Amazon +# Label: "Amazon Root CA 2" +# Serial: 143266982885963551818349160658925006970653239 +# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66 +# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a +# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4 +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK +gXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ +W0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg +1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K +8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r +2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me +z/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR +8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj +mUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz +7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6 ++XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI +0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB +Af8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm +UjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2 +LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY ++gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS +k5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl +7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm +btmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl +urR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+ +fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63 +n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE +76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H +9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT +4PsJYGw= +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 3 O=Amazon +# Subject: CN=Amazon Root CA 3 O=Amazon +# Label: "Amazon Root CA 3" +# Serial: 143266986699090766294700635381230934788665930 +# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87 +# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e +# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4 +-----BEGIN CERTIFICATE----- +MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5 +MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g +Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG +A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg +Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl +ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr +ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr +BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM +YyRIHN8wfdVoOw== +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 4 O=Amazon +# Subject: CN=Amazon Root CA 4 O=Amazon +# Label: "Amazon Root CA 4" +# Serial: 143266989758080763974105200630763877849284878 +# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd +# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be +# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92 +-----BEGIN CERTIFICATE----- +MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5 +MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g +Um9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG +A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg +Q0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi +9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk +M6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB +MAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw +CkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW +1KyLa2tJElMzrdfkviT8tQp21KW8EA== +-----END CERTIFICATE----- + +# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM +# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM +# Label: "TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1" +# Serial: 1 +# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49 +# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca +# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 +-----BEGIN CERTIFICATE----- +MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx +GDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp +bXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w +KwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0 +BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy +dW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG +EwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll +IEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU +QUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT +TTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg +LSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7 +a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr +LqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr +N3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X +YacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/ +iSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f +AJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH +V8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh +AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf +IPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4 +lzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c +8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf +lo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= +-----END CERTIFICATE----- + +# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. +# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. +# Label: "GDCA TrustAUTH R5 ROOT" +# Serial: 9009899650740120186 +# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4 +# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4 +# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93 +-----BEGIN CERTIFICATE----- +MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE +BhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ +IENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0 +MTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV +BAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w +HQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj +Dp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj +TnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u +KU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj +qcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm +MUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12 +ZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP +zgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk +L30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC +jGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA +HQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC +AwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg +p8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm +DRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5 +COmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry +L3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf +JWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg +IHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io +2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV +09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ +XR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq +T8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe +MTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g== +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation +# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation +# Label: "SSL.com Root Certification Authority RSA" +# Serial: 8875640296558310041 +# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29 +# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb +# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69 +-----BEGIN CERTIFICATE----- +MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE +BhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK +DA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz +OTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv +dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv +bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN +AQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R +xFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX +qhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC +C52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3 +6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh +/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF +YD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E +JNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc +US4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8 +ZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm ++Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi +M+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G +A1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV +cpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc +Hadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs +PgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/ +q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0 +cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr +a6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I +H37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y +K9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu +nLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf +oYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY +Ic2wBlX7Jz9TkHCpBB5XJ7k= +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation +# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation +# Label: "SSL.com Root Certification Authority ECC" +# Serial: 8495723813297216424 +# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e +# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a +# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65 +-----BEGIN CERTIFICATE----- +MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC +VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T +U0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz +WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0 +b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS +b290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI +7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg +CemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud +EwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD +VR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T +kdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+ +gA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation +# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation +# Label: "SSL.com EV Root Certification Authority RSA R2" +# Serial: 6248227494352943350 +# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95 +# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a +# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c +-----BEGIN CERTIFICATE----- +MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV +BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE +CgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy +dGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy +MDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G +A1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD +DC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq +M0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf +OePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa +4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9 +HSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR +aZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA +b9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ +Gp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV +PWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO +pgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu +UDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY +MBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV +HSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4 +9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW +s47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5 +Sm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg +cLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM +79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz +/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt +ll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm +Kf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK +QbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ +w/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi +S9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07 +mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w== +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation +# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation +# Label: "SSL.com EV Root Certification Authority ECC" +# Serial: 3182246526754555285 +# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90 +# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d +# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8 +-----BEGIN CERTIFICATE----- +MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC +VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T +U0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx +NTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv +dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv +bSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA +VIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku +WnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP +MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX +5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ +ytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg +h5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 +# Label: "GlobalSign Root CA - R6" +# Serial: 1417766617973444989252670301619537 +# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae +# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1 +# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69 +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg +MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh +bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx +MjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET +MBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI +xutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k +ZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD +aNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw +LnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw +1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX +k7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2 +SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h +bguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n +WUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY +rZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce +MgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu +bAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN +nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt +Ixg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61 +55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj +vUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf +cDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz +oHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp +nOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs +pA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v +JJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R +8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4 +5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA= +-----END CERTIFICATE----- + +# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed +# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed +# Label: "OISTE WISeKey Global Root GC CA" +# Serial: 44084345621038548146064804565436152554 +# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23 +# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31 +# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d +-----BEGIN CERTIFICATE----- +MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw +CQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91 +bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg +Um9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ +BgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu +ZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS +b290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni +eUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W +p2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T +rYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV +57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg +Mgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 +-----END CERTIFICATE----- + +# Issuer: CN=UCA Global G2 Root O=UniTrust +# Subject: CN=UCA Global G2 Root O=UniTrust +# Label: "UCA Global G2 Root" +# Serial: 124779693093741543919145257850076631279 +# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8 +# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a +# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9 +MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH +bG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x +CzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds +b2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr +b3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9 +kmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm +VHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R +VogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc +C/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj +tm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY +D0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv +j5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl +NaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6 +iIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP +O6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/ +BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV +ZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj +L3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5 +1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl +1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU +b3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV +PtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj +y88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb +EGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg +DMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI ++Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy +YiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX +UB+K+wb1whnw0A== +-----END CERTIFICATE----- + +# Issuer: CN=UCA Extended Validation Root O=UniTrust +# Subject: CN=UCA Extended Validation Root O=UniTrust +# Label: "UCA Extended Validation Root" +# Serial: 106100277556486529736699587978573607008 +# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2 +# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a +# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24 +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH +MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF +eHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx +MDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV +BAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog +D4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS +sPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop +O2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk +sHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi +c0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj +VMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz +KuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/ +TuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G +sx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs +1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD +fwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN +l8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR +ap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ +VBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5 +c6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp +4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s +t2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj +2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO +vpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C +xR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx +cmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM +fjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax +-----END CERTIFICATE----- + +# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 +# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 +# Label: "Certigna Root CA" +# Serial: 269714418870597844693661054334862075617 +# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77 +# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43 +# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68 +-----BEGIN CERTIFICATE----- +MIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw +WjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw +MiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x +MzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD +VQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX +BgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw +ggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO +ty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M +CiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu +I9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm +TLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh +C59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf +ePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz +IoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT +Co/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k +JWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5 +hwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB +GjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of +1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov +L3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo +dHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr +aHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq +hkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L +6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG +HVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6 +0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB +lA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi +o2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1 +gPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v +faci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63 +Nwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh +jWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw +3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0= +-----END CERTIFICATE----- + +# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI +# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI +# Label: "emSign Root CA - G1" +# Serial: 235931866688319308814040 +# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac +# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c +# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67 +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI +# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI +# Label: "emSign ECC Root CA - G3" +# Serial: 287880440101571086945156 +# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40 +# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1 +# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI +# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI +# Label: "emSign Root CA - C1" +# Serial: 825510296613316004955058 +# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68 +# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01 +# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f +-----BEGIN CERTIFICATE----- +MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG +A1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg +SW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw +MFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln +biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v +dCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ +BczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ +HdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH +3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH +GPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c +xSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1 +aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq +TbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87 +/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4 +kqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG +YQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT ++xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo +WXzhriKi4gp6D/piq1JM4fHfyr6DDUI= +-----END CERTIFICATE----- + +# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI +# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI +# Label: "emSign ECC Root CA - C3" +# Serial: 582948710642506000014504 +# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5 +# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66 +# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3 +-----BEGIN CERTIFICATE----- +MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG +EwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx +IDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw +MFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln +biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND +IFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci +MK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti +sIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O +BBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB +Af8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c +3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J +0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ== +-----END CERTIFICATE----- + +# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post +# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post +# Label: "Hongkong Post Root CA 3" +# Serial: 46170865288971385588281144162979347873371282084 +# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0 +# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02 +# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6 +-----BEGIN CERTIFICATE----- +MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL +BQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ +SG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n +a29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5 +NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT +CUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u +Z2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK +AoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO +dem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI +VoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV +9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY +2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY +vLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt +bNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb +x39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+ +l2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK +TE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj +Hno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e +i9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw +DQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG +7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk +MpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr +gZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk +GMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS +3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm +Ozj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+ +l6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c +JfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP +L5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa +LJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG +mpv0 +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority - G4 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2015 Entrust, Inc. - for authorized use only +# Subject: CN=Entrust Root Certification Authority - G4 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2015 Entrust, Inc. - for authorized use only +# Label: "Entrust Root Certification Authority - G4" +# Serial: 289383649854506086828220374796556676440 +# MD5 Fingerprint: 89:53:f1:83:23:b7:7c:8e:05:f1:8c:71:38:4e:1f:88 +# SHA1 Fingerprint: 14:88:4e:86:26:37:b0:26:af:59:62:5c:40:77:ec:35:29:ba:96:01 +# SHA256 Fingerprint: db:35:17:d1:f6:73:2a:2d:5a:b9:7c:53:3e:c7:07:79:ee:32:70:a6:2f:b4:ac:42:38:37:24:60:e6:f0:1e:88 +-----BEGIN CERTIFICATE----- +MIIGSzCCBDOgAwIBAgIRANm1Q3+vqTkPAAAAAFVlrVgwDQYJKoZIhvcNAQELBQAw +gb4xCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQL +Ex9TZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykg +MjAxNSBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMjAw +BgNVBAMTKUVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc0 +MB4XDTE1MDUyNzExMTExNloXDTM3MTIyNzExNDExNlowgb4xCzAJBgNVBAYTAlVT +MRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1 +c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxNSBFbnRydXN0LCBJ +bmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMjAwBgNVBAMTKUVudHJ1c3Qg +Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc0MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAsewsQu7i0TD/pZJH4i3DumSXbcr3DbVZwbPLqGgZ +2K+EbTBwXX7zLtJTmeH+H17ZSK9dE43b/2MzTdMAArzE+NEGCJR5WIoV3imz/f3E +T+iq4qA7ec2/a0My3dl0ELn39GjUu9CH1apLiipvKgS1sqbHoHrmSKvS0VnM1n4j +5pds8ELl3FFLFUHtSUrJ3hCX1nbB76W1NhSXNdh4IjVS70O92yfbYVaCNNzLiGAM +C1rlLAHGVK/XqsEQe9IFWrhAnoanw5CGAlZSCXqc0ieCU0plUmr1POeo8pyvi73T +DtTUXm6Hnmo9RR3RXRv06QqsYJn7ibT/mCzPfB3pAqoEmh643IhuJbNsZvc8kPNX +wbMv9W3y+8qh+CmdRouzavbmZwe+LGcKKh9asj5XxNMhIWNlUpEbsZmOeX7m640A +2Vqq6nPopIICR5b+W45UYaPrL0swsIsjdXJ8ITzI9vF01Bx7owVV7rtNOzK+mndm +nqxpkCIHH2E6lr7lmk/MBTwoWdPBDFSoWWG9yHJM6Nyfh3+9nEg2XpWjDrk4JFX8 +dWbrAuMINClKxuMrLzOg2qOGpRKX/YAr2hRC45K9PvJdXmd0LhyIRyk0X+IyqJwl +N4y6mACXi0mWHv0liqzc2thddG5msP9E36EYxr5ILzeUePiVSj9/E15dWf10hkNj +c0kCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFJ84xFYjwznooHFs6FRM5Og6sb9nMA0GCSqGSIb3DQEBCwUAA4ICAQAS +5UKme4sPDORGpbZgQIeMJX6tuGguW8ZAdjwD+MlZ9POrYs4QjbRaZIxowLByQzTS +Gwv2LFPSypBLhmb8qoMi9IsabyZIrHZ3CL/FmFz0Jomee8O5ZDIBf9PD3Vht7LGr +hFV0d4QEJ1JrhkzO3bll/9bGXp+aEJlLdWr+aumXIOTkdnrG0CSqkM0gkLpHZPt/ +B7NTeLUKYvJzQ85BK4FqLoUWlFPUa19yIqtRLULVAJyZv967lDtX/Zr1hstWO1uI +AeV8KEsD+UmDfLJ/fOPtjqF/YFOOVZ1QNBIPt5d7bIdKROf1beyAN/BYGW5KaHbw +H5Lk6rWS02FREAutp9lfx1/cH6NcjKF+m7ee01ZvZl4HliDtC3T7Zk6LERXpgUl+ +b7DUUH8i119lAg2m9IUe2K4GS0qn0jFmwvjO5QimpAKWRGhXxNUzzxkvFMSUHHuk +2fCfDrGA4tGeEWSpiBE6doLlYsKA2KSD7ZPvfC+QsDJMlhVoSFLUmQjAJOgc47Ol +IQ6SwJAfzyBfyjs4x7dtOvPmRLgOMWuIjnDrnBdSqEGULoe256YSxXXfW8AKbnuk +5F6G+TaU33fD6Q3AOfF5u0aOq0NZJ7cguyPpVkAh7DE9ZapD8j3fcEThuk0mEDuY +n/PIjhs4ViFqUZPTkcpG2om3PVODLAgfi49T3f+sHw== +-----END CERTIFICATE----- + +# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation +# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation +# Label: "Microsoft ECC Root Certificate Authority 2017" +# Serial: 136839042543790627607696632466672567020 +# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67 +# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5 +# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02 +-----BEGIN CERTIFICATE----- +MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw +CQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD +VQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw +MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV +UzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy +b3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR +ogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb +hGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3 +FQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV +L8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB +iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M= +-----END CERTIFICATE----- + +# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation +# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation +# Label: "Microsoft RSA Root Certificate Authority 2017" +# Serial: 40975477897264996090493496164228220339 +# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47 +# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74 +# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0 +-----BEGIN CERTIFICATE----- +MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl +MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw +NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 +IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG +EwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N +aWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ +Nt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0 +ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1 +HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm +gGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ +jEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc +aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG +YaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6 +W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K +UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH ++FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q +W5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC +NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC +LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC +gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6 +tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh +SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2 +TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3 +pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR +xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp +GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9 +dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN +AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB +RA+GsCyRxj3qrg+E +-----END CERTIFICATE----- + +# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd. +# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd. +# Label: "e-Szigno Root CA 2017" +# Serial: 411379200276854331539784714 +# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98 +# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1 +# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99 +-----BEGIN CERTIFICATE----- +MIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV +BAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk +LjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv +b3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ +BgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg +THRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v +IFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv +xie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H +Wyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB +eAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo +jbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ ++efcMQ== +-----END CERTIFICATE----- + +# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2 +# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2 +# Label: "certSIGN Root CA G2" +# Serial: 313609486401300475190 +# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7 +# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32 +# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05 +-----BEGIN CERTIFICATE----- +MIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV +BAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g +Uk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ +BgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ +R04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF +dRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw +vlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ +uIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp +n+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs +cpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW +xPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P +rCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF +DsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx +DTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy +LcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C +eWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ +d8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq +kX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC +b6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl +qiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0 +OJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c +NywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk +ltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO +pwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj +03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk +PuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE +1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX +QRBdJ3NghVdJIgc= +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global Certification Authority" +# Serial: 1846098327275375458322922162 +# MD5 Fingerprint: f8:1c:18:2d:2f:ba:5f:6d:a1:6c:bc:c7:ab:91:c7:0e +# SHA1 Fingerprint: 2f:8f:36:4f:e1:58:97:44:21:59:87:a5:2a:9a:d0:69:95:26:7f:b5 +# SHA256 Fingerprint: 97:55:20:15:f5:dd:fc:3c:87:88:c0:06:94:45:55:40:88:94:45:00:84:f1:00:86:70:86:bc:1a:2b:b5:8d:c8 +-----BEGIN CERTIFICATE----- +MIIF2jCCA8KgAwIBAgIMBfcOhtpJ80Y1LrqyMA0GCSqGSIb3DQEBCwUAMIGIMQsw +CQYDVQQGEwJVUzERMA8GA1UECAwISWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28x +ITAfBgNVBAoMGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1 +c3R3YXZlIEdsb2JhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0xNzA4MjMx +OTM0MTJaFw00MjA4MjMxOTM0MTJaMIGIMQswCQYDVQQGEwJVUzERMA8GA1UECAwI +SWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28xITAfBgNVBAoMGFRydXN0d2F2ZSBI +b2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1c3R3YXZlIEdsb2JhbCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB +ALldUShLPDeS0YLOvR29zd24q88KPuFd5dyqCblXAj7mY2Hf8g+CY66j96xz0Xzn +swuvCAAJWX/NKSqIk4cXGIDtiLK0thAfLdZfVaITXdHG6wZWiYj+rDKd/VzDBcdu +7oaJuogDnXIhhpCujwOl3J+IKMujkkkP7NAP4m1ET4BqstTnoApTAbqOl5F2brz8 +1Ws25kCI1nsvXwXoLG0R8+eyvpJETNKXpP7ScoFDB5zpET71ixpZfR9oWN0EACyW +80OzfpgZdNmcc9kYvkHHNHnZ9GLCQ7mzJ7Aiy/k9UscwR7PJPrhq4ufogXBeQotP +JqX+OsIgbrv4Fo7NDKm0G2x2EOFYeUY+VM6AqFcJNykbmROPDMjWLBz7BegIlT1l +RtzuzWniTY+HKE40Cz7PFNm73bZQmq131BnW2hqIyE4bJ3XYsgjxroMwuREOzYfw +hI0Vcnyh78zyiGG69Gm7DIwLdVcEuE4qFC49DxweMqZiNu5m4iK4BUBjECLzMx10 +coos9TkpoNPnG4CELcU9402x/RpvumUHO1jsQkUm+9jaJXLE9gCxInm943xZYkqc +BW89zubWR2OZxiRvchLIrH+QtAuRcOi35hYQcRfO3gZPSEF9NUqjifLJS3tBEW1n +twiYTOURGa5CgNz7kAXU+FDKvuStx8KU1xad5hePrzb7AgMBAAGjQjBAMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFJngGWcNYtt2s9o9uFvo/ULSMQ6HMA4GA1Ud +DwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAmHNw4rDT7TnsTGDZqRKGFx6W +0OhUKDtkLSGm+J1WE2pIPU/HPinbbViDVD2HfSMF1OQc3Og4ZYbFdada2zUFvXfe +uyk3QAUHw5RSn8pk3fEbK9xGChACMf1KaA0HZJDmHvUqoai7PF35owgLEQzxPy0Q +lG/+4jSHg9bP5Rs1bdID4bANqKCqRieCNqcVtgimQlRXtpla4gt5kNdXElE1GYhB +aCXUNxeEFfsBctyV3lImIJgm4nb1J2/6ADtKYdkNy1GTKv0WBpanI5ojSP5RvbbE +sLFUzt5sQa0WZ37b/TjNuThOssFgy50X31ieemKyJo90lZvkWx3SD92YHJtZuSPT +MaCm/zjdzyBP6VhWOmfD0faZmZ26NraAL4hHT4a/RDqA5Dccprrql5gR0IRiR2Qe +qu5AvzSxnI9O4fKSTx+O856X3vOmeWqJcU9LJxdI/uz0UA9PSX3MReO9ekDFQdxh +VicGaeVyQYHTtgGJoC86cnn+OjC/QezHYj6RS8fZMXZC+fc8Y+wmjHMMfRod6qh8 +h6jCJ3zhM0EPz8/8AKAigJ5Kp28AsEFFtyLKaEjFQqKu3R3y4G5OBVixwJAWKqQ9 +EEC+j2Jjg6mcgn0tAumDMHzLJ8n9HmYAsC7TIS+OMxZsmO0QqAfWzJPP29FpHOTK +yeC2nOnOcXHebD8WpHk= +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global ECC P256 Certification Authority" +# Serial: 4151900041497450638097112925 +# MD5 Fingerprint: 5b:44:e3:8d:5d:36:86:26:e8:0d:05:d2:59:a7:83:54 +# SHA1 Fingerprint: b4:90:82:dd:45:0c:be:8b:5b:b1:66:d3:e2:a4:08:26:cd:ed:42:cf +# SHA256 Fingerprint: 94:5b:bc:82:5e:a5:54:f4:89:d1:fd:51:a7:3d:df:2e:a6:24:ac:70:19:a0:52:05:22:5c:22:a7:8c:cf:a8:b4 +-----BEGIN CERTIFICATE----- +MIICYDCCAgegAwIBAgIMDWpfCD8oXD5Rld9dMAoGCCqGSM49BAMCMIGRMQswCQYD +VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf +BgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3 +YXZlIEdsb2JhbCBFQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x +NzA4MjMxOTM1MTBaFw00MjA4MjMxOTM1MTBaMIGRMQswCQYDVQQGEwJVUzERMA8G +A1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0 +d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF +Q0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTBZMBMGByqGSM49AgEGCCqG +SM49AwEHA0IABH77bOYj43MyCMpg5lOcunSNGLB4kFKA3TjASh3RqMyTpJcGOMoN +FWLGjgEqZZ2q3zSRLoHB5DOSMcT9CTqmP62jQzBBMA8GA1UdEwEB/wQFMAMBAf8w +DwYDVR0PAQH/BAUDAwcGADAdBgNVHQ4EFgQUo0EGrJBt0UrrdaVKEJmzsaGLSvcw +CgYIKoZIzj0EAwIDRwAwRAIgB+ZU2g6gWrKuEZ+Hxbb/ad4lvvigtwjzRM4q3wgh +DDcCIC0mA6AFvWvR9lz4ZcyGbbOcNEhjhAnFjXca4syc4XR7 +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global ECC P384 Certification Authority" +# Serial: 2704997926503831671788816187 +# MD5 Fingerprint: ea:cf:60:c4:3b:b9:15:29:40:a1:97:ed:78:27:93:d6 +# SHA1 Fingerprint: e7:f3:a3:c8:cf:6f:c3:04:2e:6d:0e:67:32:c5:9e:68:95:0d:5e:d2 +# SHA256 Fingerprint: 55:90:38:59:c8:c0:c3:eb:b8:75:9e:ce:4e:25:57:22:5f:f5:75:8b:bd:38:eb:d4:82:76:60:1e:1b:d5:80:97 +-----BEGIN CERTIFICATE----- +MIICnTCCAiSgAwIBAgIMCL2Fl2yZJ6SAaEc7MAoGCCqGSM49BAMDMIGRMQswCQYD +VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf +BgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3 +YXZlIEdsb2JhbCBFQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x +NzA4MjMxOTM2NDNaFw00MjA4MjMxOTM2NDNaMIGRMQswCQYDVQQGEwJVUzERMA8G +A1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0 +d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF +Q0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTB2MBAGByqGSM49AgEGBSuB +BAAiA2IABGvaDXU1CDFHBa5FmVXxERMuSvgQMSOjfoPTfygIOiYaOs+Xgh+AtycJ +j9GOMMQKmw6sWASr9zZ9lCOkmwqKi6vr/TklZvFe/oyujUF5nQlgziip04pt89ZF +1PKYhDhloKNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0G +A1UdDgQWBBRVqYSJ0sEyvRjLbKYHTsjnnb6CkDAKBggqhkjOPQQDAwNnADBkAjA3 +AZKXRRJ+oPM+rRk6ct30UJMDEr5E0k9BpIycnR+j9sKS50gU/k6bpZFXrsY3crsC +MGclCrEMXu6pY5Jv5ZAL/mYiykf9ijH3g/56vxC+GCsej/YpHpRZ744hN8tRmKVu +Sw== +-----END CERTIFICATE----- + +# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. +# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. +# Label: "NAVER Global Root Certification Authority" +# Serial: 9013692873798656336226253319739695165984492813 +# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b +# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1 +# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65 +-----BEGIN CERTIFICATE----- +MIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM +BQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG +T1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx +CzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD +b3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA +iQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH +38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE +HoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz +kVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP +szuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq +vC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf +nZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG +YQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo +0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a +CJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K +AQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I +36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB +Af8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN +qo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj +cu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm ++LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL +hr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe +lHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7 +p/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8 +piKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR +LBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX +5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO +dh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul +9XXeifdy +-----END CERTIFICATE----- + +# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres +# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres +# Label: "AC RAIZ FNMT-RCM SERVIDORES SEGUROS" +# Serial: 131542671362353147877283741781055151509 +# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb +# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a +# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb +-----BEGIN CERTIFICATE----- +MIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw +CQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw +FgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S +Q00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5 +MzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL +DAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS +QUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH +sbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK +Um8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu +SuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC +MQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy +v+c= +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa +# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa +# Label: "GlobalSign Root R46" +# Serial: 1552617688466950547958867513931858518042577 +# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef +# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90 +# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9 +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA +MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD +VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy +MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt +c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ +OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG +vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud +316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo +0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE +y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF +zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE ++cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN +I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs +x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa +ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC +4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4 +7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg +JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti +2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk +pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF +FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt +rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk +ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5 +u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP +4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6 +N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3 +vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6 +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa +# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa +# Label: "GlobalSign Root E46" +# Serial: 1552617690338932563915843282459653771421763 +# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f +# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84 +# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58 +-----BEGIN CERTIFICATE----- +MIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx +CzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD +ExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw +MDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex +HDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq +R+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd +yXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud +DgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ +7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8 ++RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A= +-----END CERTIFICATE----- + +# Issuer: CN=GLOBALTRUST 2020 O=e-commerce monitoring GmbH +# Subject: CN=GLOBALTRUST 2020 O=e-commerce monitoring GmbH +# Label: "GLOBALTRUST 2020" +# Serial: 109160994242082918454945253 +# MD5 Fingerprint: 8a:c7:6f:cb:6d:e3:cc:a2:f1:7c:83:fa:0e:78:d7:e8 +# SHA1 Fingerprint: d0:67:c1:13:51:01:0c:aa:d0:c7:6a:65:37:31:16:26:4f:53:71:a2 +# SHA256 Fingerprint: 9a:29:6a:51:82:d1:d4:51:a2:e3:7f:43:9b:74:da:af:a2:67:52:33:29:f9:0f:9a:0d:20:07:c3:34:e2:3c:9a +-----BEGIN CERTIFICATE----- +MIIFgjCCA2qgAwIBAgILWku9WvtPilv6ZeUwDQYJKoZIhvcNAQELBQAwTTELMAkG +A1UEBhMCQVQxIzAhBgNVBAoTGmUtY29tbWVyY2UgbW9uaXRvcmluZyBHbWJIMRkw +FwYDVQQDExBHTE9CQUxUUlVTVCAyMDIwMB4XDTIwMDIxMDAwMDAwMFoXDTQwMDYx +MDAwMDAwMFowTTELMAkGA1UEBhMCQVQxIzAhBgNVBAoTGmUtY29tbWVyY2UgbW9u +aXRvcmluZyBHbWJIMRkwFwYDVQQDExBHTE9CQUxUUlVTVCAyMDIwMIICIjANBgkq +hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAri5WrRsc7/aVj6B3GyvTY4+ETUWiD59b +RatZe1E0+eyLinjF3WuvvcTfk0Uev5E4C64OFudBc/jbu9G4UeDLgztzOG53ig9Z +YybNpyrOVPu44sB8R85gfD+yc/LAGbaKkoc1DZAoouQVBGM+uq/ufF7MpotQsjj3 +QWPKzv9pj2gOlTblzLmMCcpL3TGQlsjMH/1WljTbjhzqLL6FLmPdqqmV0/0plRPw +yJiT2S0WR5ARg6I6IqIoV6Lr/sCMKKCmfecqQjuCgGOlYx8ZzHyyZqjC0203b+J+ +BlHZRYQfEs4kUmSFC0iAToexIiIwquuuvuAC4EDosEKAA1GqtH6qRNdDYfOiaxaJ +SaSjpCuKAsR49GiKweR6NrFvG5Ybd0mN1MkGco/PU+PcF4UgStyYJ9ORJitHHmkH +r96i5OTUawuzXnzUJIBHKWk7buis/UDr2O1xcSvy6Fgd60GXIsUf1DnQJ4+H4xj0 +4KlGDfV0OoIu0G4skaMxXDtG6nsEEFZegB31pWXogvziB4xiRfUg3kZwhqG8k9Me +dKZssCz3AwyIDMvUclOGvGBG85hqwvG/Q/lwIHfKN0F5VVJjjVsSn8VoxIidrPIw +q7ejMZdnrY8XD2zHc+0klGvIg5rQmjdJBKuxFshsSUktq6HQjJLyQUp5ISXbY9e2 +nKd+Qmn7OmMCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFNwuH9FhN3nkq9XVsxJxaD1qaJwiMB8GA1UdIwQYMBaAFNwu +H9FhN3nkq9XVsxJxaD1qaJwiMA0GCSqGSIb3DQEBCwUAA4ICAQCR8EICaEDuw2jA +VC/f7GLDw56KoDEoqoOOpFaWEhCGVrqXctJUMHytGdUdaG/7FELYjQ7ztdGl4wJC +XtzoRlgHNQIw4Lx0SsFDKv/bGtCwr2zD/cuz9X9tAy5ZVp0tLTWMstZDFyySCstd +6IwPS3BD0IL/qMy/pJTAvoe9iuOTe8aPmxadJ2W8esVCgmxcB9CpwYhgROmYhRZf ++I/KARDOJcP5YBugxZfD0yyIMaK9MOzQ0MAS8cE54+X1+NZK3TTN+2/BT+MAi1bi +kvcoskJ3ciNnxz8RFbLEAwW+uxF7Cr+obuf/WEPPm2eggAe2HcqtbepBEX4tdJP7 +wry+UUTF72glJ4DjyKDUEuzZpTcdN3y0kcra1LGWge9oXHYQSa9+pTeAsRxSvTOB +TI/53WXZFM2KJVj04sWDpQmQ1GwUY7VA3+vA/MRYfg0UFodUJ25W5HCEuGwyEn6C +MUO+1918oa2u1qsgEu8KwxCMSZY13At1XrFP1U80DhEgB3VDRemjEdqso5nCtnkn +4rnvyOL2NSl6dPrFf4IFYqYK6miyeUcGbvJXqBUzxvd4Sj1Ce2t+/vdG6tHrju+I +aFvowdlxfv1k7/9nR4hYJS8+hge9+6jlgqispdNpQ80xiEmEU5LAsTkbOYMBMMTy +qfrQA71yN2BWHzZ8vTmR9W0Nv3vXkg== +-----END CERTIFICATE----- + +# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz +# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz +# Label: "ANF Secure Server Root CA" +# Serial: 996390341000653745 +# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96 +# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74 +# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99 +-----BEGIN CERTIFICATE----- +MIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV +BAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk +YWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV +BAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN +MzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF +UzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD +VQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v +dCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj +cqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q +yGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH +2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX +H1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL +zc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR +p1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz +W7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/ +SiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn +LNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3 +n5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B +u8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj +o1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC +AgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L +9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej +rw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK +pFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0 +vPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq +OknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ +/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9 +2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI ++PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2 +MjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo +tt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw= +-----END CERTIFICATE----- + +# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Label: "Certum EC-384 CA" +# Serial: 160250656287871593594747141429395092468 +# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1 +# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed +# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6 +-----BEGIN CERTIFICATE----- +MIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw +CQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw +JQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT +EENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0 +WjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT +LkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX +BgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE +KI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm +Fy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8 +EF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J +UG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn +nvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k= +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Root CA" +# Serial: 40870380103424195783807378461123655149 +# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29 +# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5 +# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd +-----BEGIN CERTIFICATE----- +MIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6 +MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu +MScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV +BAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw +MzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg +U3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo +b3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ +n0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q +p1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq +NwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF +8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3 +HAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa +mqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi +7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF +ytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P +qafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ +v3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6 +Tsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1 +vALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD +ggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4 +WxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo +zMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR +5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ +GfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf +5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq +0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D +P78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM +qJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP +0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf +E2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb +-----END CERTIFICATE----- + +# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique +# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique +# Label: "TunTrust Root CA" +# Serial: 108534058042236574382096126452369648152337120275 +# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4 +# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb +# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41 +-----BEGIN CERTIFICATE----- +MIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL +BQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg +Q2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv +b3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG +EwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u +IEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ +n56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd +2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF +VwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ +GoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF +li/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU +r8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2 +eY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb +MlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg +jwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB +7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW +5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE +ITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0 +90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z +xiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu +QEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4 +FstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH +22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP +xOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn +dFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5 +Xc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b +nV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ +CvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH +u/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj +d9qDRIueVSjAi1jTkD5OGwDxFa2DK5o= +-----END CERTIFICATE----- + +# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Label: "HARICA TLS RSA Root CA 2021" +# Serial: 76817823531813593706434026085292783742 +# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91 +# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d +# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d +-----BEGIN CERTIFICATE----- +MIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs +MQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl +c2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg +Um9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL +MAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl +YXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv +b3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l +mwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE +4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv +a9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M +pbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw +Kh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b +LW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY +AuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB +AGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq +E613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr +W2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ +CoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE +AwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU +X15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3 +f5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja +H6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP +JzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P +zzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt +jBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0 +/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT +BGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79 +aPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW +xw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU +63ZTGI0RmLo= +-----END CERTIFICATE----- + +# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Label: "HARICA TLS ECC Root CA 2021" +# Serial: 137515985548005187474074462014555733966 +# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0 +# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48 +# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01 +-----BEGIN CERTIFICATE----- +MIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw +CQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh +cmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v +dCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG +A1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj +aCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg +Q0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7 +KKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y +STHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD +AgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw +SaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN +nxS2PFOiTAZpffpskcYqSUXm7LcT4Tps +-----END CERTIFICATE----- + +# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Label: "Autoridad de Certificacion Firmaprofesional CIF A62634068" +# Serial: 1977337328857672817 +# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3 +# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe +# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a +-----BEGIN CERTIFICATE----- +MIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE +BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h +cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1 +MDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg +Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9 +thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM +cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG +L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i +NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h +X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b +m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy +Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja +EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T +KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF +6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh +OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc +tHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd +IAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j +b20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC +AG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw +ADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m +iWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF +Sa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ +hfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P +Vf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE +EAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV +1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t +CsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR +5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw +f9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9 +ivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK +GbqEZycPvEJdvSRUDewdcAZfpLz6IHxV +-----END CERTIFICATE----- + +# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. +# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. +# Label: "vTrus ECC Root CA" +# Serial: 630369271402956006249506845124680065938238527194 +# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85 +# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1 +# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3 +-----BEGIN CERTIFICATE----- +MIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw +RzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY +BgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz +MTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u +LEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0 +v/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd +e4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD +VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw +V53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA +AjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG +GJTO +-----END CERTIFICATE----- + +# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd. +# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd. +# Label: "vTrus Root CA" +# Serial: 387574501246983434957692974888460947164905180485 +# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc +# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7 +# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87 +-----BEGIN CERTIFICATE----- +MIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL +BQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x +FjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx +MDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s +THRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc +IrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU +AyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+ +GrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9 +8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH +flqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt +J8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim +0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN +pGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ +UqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW +OXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB +AAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet +8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd +nxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j +bhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM +Kar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv +TDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS +S8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr +I8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9 +b91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB +UvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P +Ti07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven +sBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s= +-----END CERTIFICATE----- + +# Issuer: CN=ISRG Root X2 O=Internet Security Research Group +# Subject: CN=ISRG Root X2 O=Internet Security Research Group +# Label: "ISRG Root X2" +# Serial: 87493402998870891108772069816698636114 +# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5 +# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af +# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70 +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- + +# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. +# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. +# Label: "HiPKI Root CA - G1" +# Serial: 60966262342023497858655262305426234976 +# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3 +# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60 +# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc +-----BEGIN CERTIFICATE----- +MIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa +Fw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3 +YSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw +qNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv +Vcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6 +lZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz +Qs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ +KILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK +FgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj +HluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr +y+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ +/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM +a/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6 +fsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG +SIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi +7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc +SE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza +ZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc +XzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg +iLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho +L5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF +Ne85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr +kkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+ +vhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU +YDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 +# Label: "GlobalSign ECC Root CA - R4" +# Serial: 159662223612894884239637590694 +# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc +# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28 +# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2 +-----BEGIN CERTIFICATE----- +MIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD +VQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh +bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw +MTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g +UjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx +uYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV +HQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/ ++wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147 +bmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R1 O=Google Trust Services LLC +# Subject: CN=GTS Root R1 O=Google Trust Services LLC +# Label: "GTS Root R1" +# Serial: 159662320309726417404178440727 +# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40 +# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a +# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo +27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w +Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw +TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl +qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH +szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8 +Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk +MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92 +wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p +aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN +VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb +C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe +QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy +h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4 +7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J +ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef +MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/ +Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT +6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ +0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm +2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb +bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R2 O=Google Trust Services LLC +# Subject: CN=GTS Root R2 O=Google Trust Services LLC +# Label: "GTS Root R2" +# Serial: 159662449406622349769042896298 +# MD5 Fingerprint: 1e:39:c0:53:e6:1e:29:82:0b:ca:52:55:36:5d:57:dc +# SHA1 Fingerprint: 9a:44:49:76:32:db:de:fa:d0:bc:fb:5a:7b:17:bd:9e:56:09:24:94 +# SHA256 Fingerprint: 8d:25:cd:97:22:9d:bf:70:35:6b:da:4e:b3:cc:73:40:31:e2:4c:f0:0f:af:cf:d3:2d:c7:6e:b5:84:1c:7e:a8 +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlrsWNBCUaqxElqjANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTukk3LvCvpt +nfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+cnfgLFuv5AS/T3KgGjSY +6Dlo7JUle3ah5mm5hRm9iYz+re026nO8/4Piy33B0s5Ks40FnotJk9/BW9BuXvAu +MC6C/Pq8tBcKSOWIm8Wba96wyrQD8Nr0kLhlZPdcTK3ofmZemde4wj7I0BOdre7k +RXuJVfeKH2JShBKzwkCX44ofR5GmdFrS+LFjKBC4swm4VndAoiaYecb+3yXuPuWg +f9RhD1FLPD+M2uFwdNjCaKH5wQzpoeJ/u1U8dgbuak7MkogwTZq9TwtImoS1mKPV ++3PBV2HdKFZ1E66HjucMUQkQdYhMvI35ezzUIkgfKtzra7tEscszcTJGr61K8Yzo +dDqs5xoic4DSMPclQsciOzsSrZYuxsN2B6ogtzVJV+mSSeh2FnIxZyuWfoqjx5RW +Ir9qS34BIbIjMt/kmkRtWVtd9QCgHJvGeJeNkP+byKq0rxFROV7Z+2et1VsRnTKa +G73VululycslaVNVJ1zgyjbLiGH7HrfQy+4W+9OmTN6SpdTi3/UGVN4unUu0kzCq +gc7dGtxRcw1PcOnlthYhGXmy5okLdWTK1au8CcEYof/UVKGFPP0UJAOyh9OktwID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQUu//KjiOfT5nK2+JopqUVJxce2Q4wDQYJKoZIhvcNAQEMBQADggIBAB/Kzt3H +vqGf2SdMC9wXmBFqiN495nFWcrKeGk6c1SuYJF2ba3uwM4IJvd8lRuqYnrYb/oM8 +0mJhwQTtzuDFycgTE1XnqGOtjHsB/ncw4c5omwX4Eu55MaBBRTUoCnGkJE+M3DyC +B19m3H0Q/gxhswWV7uGugQ+o+MePTagjAiZrHYNSVc61LwDKgEDg4XSsYPWHgJ2u +NmSRXbBoGOqKYcl3qJfEycel/FVL8/B/uWU9J2jQzGv6U53hkRrJXRqWbTKH7QMg +yALOWr7Z6v2yTcQvG99fevX4i8buMTolUVVnjWQye+mew4K6Ki3pHrTgSAai/Gev +HyICc/sgCq+dVEuhzf9gR7A/Xe8bVr2XIZYtCtFenTgCR2y59PYjJbigapordwj6 +xLEokCZYCDzifqrXPW+6MYgKBesntaFJ7qBFVHvmJ2WZICGoo7z7GJa7Um8M7YNR +TOlZ4iBgxcJlkoKM8xAfDoqXvneCbT+PHV28SSe9zE8P4c52hgQjxcCMElv924Sg +JPFI/2R80L5cFtHvma3AH/vLrrw4IgYmZNralw4/KBVEqE8AyvCazM90arQ+POuV +7LXTWtiBmelDGDfrs7vRWGJB82bSj6p4lVQgw1oudCvV0b4YacCs1aTPObpRhANl +6WLAYv7YTVWW4tAR+kg0Eeye7QUd5MjWHYbL +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R3 O=Google Trust Services LLC +# Subject: CN=GTS Root R3 O=Google Trust Services LLC +# Label: "GTS Root R3" +# Serial: 159662495401136852707857743206 +# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73 +# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46 +# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48 +-----BEGIN CERTIFICATE----- +MIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD +VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG +A1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw +WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz +IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G +jOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2 +4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7 +VKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm +ZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R4 O=Google Trust Services LLC +# Subject: CN=GTS Root R4 O=Google Trust Services LLC +# Label: "GTS Root R4" +# Serial: 159662532700760215368942768210 +# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8 +# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47 +# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d +-----BEGIN CERTIFICATE----- +MIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD +VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG +A1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw +WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz +IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi +QHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR +HYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D +9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8 +p/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD +-----END CERTIFICATE----- + +# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj +# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj +# Label: "Telia Root CA v2" +# Serial: 7288924052977061235122729490515358 +# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48 +# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd +# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx +CzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE +AwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1 +NTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ +MBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq +AMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9 +vVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9 +lRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD +n3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT +7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o +6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC +TEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6 +WT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R +DolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI +pEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj +YzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy +rOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ +8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi +0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM +A8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS +SRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K +TTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF +6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er +3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt +Ty3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT +VmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW +ysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA +rBPuUBQemMc= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH +# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH +# Label: "D-TRUST BR Root CA 1 2020" +# Serial: 165870826978392376648679885835942448534 +# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed +# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67 +# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44 +-----BEGIN CERTIFICATE----- +MIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw +CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS +VVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5 +NDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG +A1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB +BAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS +zuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0 +QVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/ +VbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g +PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf +Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l +dC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 +c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO +PQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW +wKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV +dWNbFJWcHwHP2NVypw87 +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH +# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH +# Label: "D-TRUST EV Root CA 1 2020" +# Serial: 126288379621884218666039612629459926992 +# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e +# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07 +# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db +-----BEGIN CERTIFICATE----- +MIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw +CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS +VVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5 +NTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG +A1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB +BAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC +/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD +wpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3 +OqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g +PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf +Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l +dC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 +c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO +PQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA +y/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb +gfM0agPnIjhQW+0ZT0MW +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. +# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. +# Label: "DigiCert TLS ECC P384 Root G5" +# Serial: 13129116028163249804115411775095713523 +# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed +# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee +# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05 +-----BEGIN CERTIFICATE----- +MIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp +Z2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2 +MDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ +bmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS +7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp +0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS +B4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 +BAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ +LgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4 +DXZDjC5Ty3zfDBeWUA== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. +# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. +# Label: "DigiCert TLS RSA4096 Root G5" +# Serial: 11930366277458970227240571539258396554 +# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1 +# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35 +# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75 +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN +MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT +HERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN +NDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs +IEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+ +ajWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0 +2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp +wgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM +pG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD +nU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po +sMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx +Zre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd +Lvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX +KyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe +XoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL +tgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv +TiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN +AQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw +GXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H +PNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF +O4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ +REtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik +AdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv +/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+ +p6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw +MUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF +qUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK +ovfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+ +-----END CERTIFICATE----- + +# Issuer: CN=Certainly Root R1 O=Certainly +# Subject: CN=Certainly Root R1 O=Certainly +# Label: "Certainly Root R1" +# Serial: 188833316161142517227353805653483829216 +# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12 +# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af +# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0 +-----BEGIN CERTIFICATE----- +MIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw +PTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy +dGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9 +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0 +YWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2 +1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT +vqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed +aFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0 +1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5 +r3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5 +cBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ +wHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ +6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA +2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH +Wyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR +eiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB +/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u +d0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr +PbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d +8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi +1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd +rRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di +taY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7 +lcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj +yTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn +Kx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy +yCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n +wXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6 +OV+KmalBWQewLK8= +-----END CERTIFICATE----- + +# Issuer: CN=Certainly Root E1 O=Certainly +# Subject: CN=Certainly Root E1 O=Certainly +# Label: "Certainly Root E1" +# Serial: 8168531406727139161245376702891150584 +# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9 +# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b +# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2 +-----BEGIN CERTIFICATE----- +MIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw +CQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu +bHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ +BgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s +eSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK ++IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2 +QNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4 +hevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm +ut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG +BtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR +-----END CERTIFICATE----- + +# Issuer: CN=Security Communication RootCA3 O=SECOM Trust Systems CO.,LTD. +# Subject: CN=Security Communication RootCA3 O=SECOM Trust Systems CO.,LTD. +# Label: "Security Communication RootCA3" +# Serial: 16247922307909811815 +# MD5 Fingerprint: 1c:9a:16:ff:9e:5c:e0:4d:8a:14:01:f4:35:5d:29:26 +# SHA1 Fingerprint: c3:03:c8:22:74:92:e5:61:a2:9c:5f:79:91:2b:1e:44:13:91:30:3a +# SHA256 Fingerprint: 24:a5:5c:2a:b0:51:44:2d:06:17:76:65:41:23:9a:4a:d0:32:d7:c5:51:75:aa:34:ff:de:2f:bc:4f:5c:52:94 +-----BEGIN CERTIFICATE----- +MIIFfzCCA2egAwIBAgIJAOF8N0D9G/5nMA0GCSqGSIb3DQEBDAUAMF0xCzAJBgNV +BAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMScw +JQYDVQQDEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTMwHhcNMTYwNjE2 +MDYxNzE2WhcNMzgwMTE4MDYxNzE2WjBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc +U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UEAxMeU2VjdXJpdHkg +Q29tbXVuaWNhdGlvbiBSb290Q0EzMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEA48lySfcw3gl8qUCBWNO0Ot26YQ+TUG5pPDXC7ltzkBtnTCHsXzW7OT4r +CmDvu20rhvtxosis5FaU+cmvsXLUIKx00rgVrVH+hXShuRD+BYD5UpOzQD11EKzA +lrenfna84xtSGc4RHwsENPXY9Wk8d/Nk9A2qhd7gCVAEF5aEt8iKvE1y/By7z/MG +TfmfZPd+pmaGNXHIEYBMwXFAWB6+oHP2/D5Q4eAvJj1+XCO1eXDe+uDRpdYMQXF7 +9+qMHIjH7Iv10S9VlkZ8WjtYO/u62C21Jdp6Ts9EriGmnpjKIG58u4iFW/vAEGK7 +8vknR+/RiTlDxN/e4UG/VHMgly1s2vPUB6PmudhvrvyMGS7TZ2crldtYXLVqAvO4 +g160a75BflcJdURQVc1aEWEhCmHCqYj9E7wtiS/NYeCVvsq1e+F7NGcLH7YMx3we +GVPKp7FKFSBWFHA9K4IsD50VHUeAR/94mQ4xr28+j+2GaR57GIgUssL8gjMunEst ++3A7caoreyYn8xrC3PsXuKHqy6C0rtOUfnrQq8PsOC0RLoi/1D+tEjtCrI8Cbn3M +0V9hvqG8OmpI6iZVIhZdXw3/JzOfGAN0iltSIEdrRU0id4xVJ/CvHozJgyJUt5rQ +T9nO/NkuHJYosQLTA70lUhw0Zk8jq/R3gpYd0VcwCBEF/VfR2ccCAwEAAaNCMEAw +HQYDVR0OBBYEFGQUfPxYchamCik0FW8qy7z8r6irMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDAUAA4ICAQDcAiMI4u8hOscNtybS +YpOnpSNyByCCYN8Y11StaSWSntkUz5m5UoHPrmyKO1o5yGwBQ8IibQLwYs1OY0PA +FNr0Y/Dq9HHuTofjcan0yVflLl8cebsjqodEV+m9NU1Bu0soo5iyG9kLFwfl9+qd +9XbXv8S2gVj/yP9kaWJ5rW4OH3/uHWnlt3Jxs/6lATWUVCvAUm2PVcTJ0rjLyjQI +UYWg9by0F1jqClx6vWPGOi//lkkZhOpn2ASxYfQAW0q3nHE3GYV5v4GwxxMOdnE+ +OoAGrgYWp421wsTL/0ClXI2lyTrtcoHKXJg80jQDdwj98ClZXSEIx2C/pHF7uNke +gr4Jr2VvKKu/S7XuPghHJ6APbw+LP6yVGPO5DtxnVW5inkYO0QR4ynKudtml+LLf +iAlhi+8kTtFZP1rUPcmTPCtk9YENFpb3ksP+MW/oKjJ0DvRMmEoYDjBU1cXrvMUV +nuiZIesnKwkK2/HmcBhWuwzkvvnoEKQTkrgc4NtnHVMDpCKn3F2SEDzq//wbEBrD +2NCcnWXL0CsnMQMeNuE9dnUM/0Umud1RvCPHX9jYhxBAEg09ODfnRDwYwFMJZI// +1ZqmfHAuc1Uh6N//g7kdPjIe1qZ9LPFm6Vwdp6POXiUyK+OVrCoHzrQoeIY8Laad +TdJ0MN1kURXbg4NR16/9M51NZg== +-----END CERTIFICATE----- + +# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. +# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. +# Label: "Security Communication ECC RootCA1" +# Serial: 15446673492073852651 +# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86 +# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41 +# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11 +-----BEGIN CERTIFICATE----- +MIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT +AkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD +VQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx +NjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT +HFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5 +IENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl +dB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK +ULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu +9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O +be0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k= +-----END CERTIFICATE----- + +# Issuer: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY +# Subject: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY +# Label: "BJCA Global Root CA1" +# Serial: 113562791157148395269083148143378328608 +# MD5 Fingerprint: 42:32:99:76:43:33:36:24:35:07:82:9b:28:f9:d0:90 +# SHA1 Fingerprint: d5:ec:8d:7b:4c:ba:79:f4:e7:e8:cb:9d:6b:ae:77:83:10:03:21:6a +# SHA256 Fingerprint: f3:89:6f:88:fe:7c:0a:88:27:66:a7:fa:6a:d2:74:9f:b5:7a:7f:3e:98:fb:76:9c:1f:a7:b0:9c:2c:44:d5:ae +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIQVW9l47TZkGobCdFsPsBsIDANBgkqhkiG9w0BAQsFADBU +MQswCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRI +T1JJVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0ExMB4XDTE5MTIxOTAz +MTYxN1oXDTQ0MTIxMjAzMTYxN1owVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJF +SUpJTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2Jh +bCBSb290IENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPFmCL3Z +xRVhy4QEQaVpN3cdwbB7+sN3SJATcmTRuHyQNZ0YeYjjlwE8R4HyDqKYDZ4/N+AZ +spDyRhySsTphzvq3Rp4Dhtczbu33RYx2N95ulpH3134rhxfVizXuhJFyV9xgw8O5 +58dnJCNPYwpj9mZ9S1WnP3hkSWkSl+BMDdMJoDIwOvqfwPKcxRIqLhy1BDPapDgR +at7GGPZHOiJBhyL8xIkoVNiMpTAK+BcWyqw3/XmnkRd4OJmtWO2y3syJfQOcs4ll +5+M7sSKGjwZteAf9kRJ/sGsciQ35uMt0WwfCyPQ10WRjeulumijWML3mG90Vr4Tq +nMfK9Q7q8l0ph49pczm+LiRvRSGsxdRpJQaDrXpIhRMsDQa4bHlW/KNnMoH1V6XK +V0Jp6VwkYe/iMBhORJhVb3rCk9gZtt58R4oRTklH2yiUAguUSiz5EtBP6DF+bHq/ +pj+bOT0CFqMYs2esWz8sgytnOYFcuX6U1WTdno9uruh8W7TXakdI136z1C2OVnZO +z2nxbkRs1CTqjSShGL+9V/6pmTW12xB3uD1IutbB5/EjPtffhZ0nPNRAvQoMvfXn +jSXWgXSHRtQpdaJCbPdzied9v3pKH9MiyRVVz99vfFXQpIsHETdfg6YmV6YBW37+ +WGgHqel62bno/1Afq8K0wM7o6v0PvY1NuLxxAgMBAAGjQjBAMB0GA1UdDgQWBBTF +7+3M2I0hxkjk49cULqcWk+WYATAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE +AwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAUoKsITQfI/Ki2Pm4rzc2IInRNwPWaZ+4 +YRC6ojGYWUfo0Q0lHhVBDOAqVdVXUsv45Mdpox1NcQJeXyFFYEhcCY5JEMEE3Kli +awLwQ8hOnThJdMkycFRtwUf8jrQ2ntScvd0g1lPJGKm1Vrl2i5VnZu69mP6u775u ++2D2/VnGKhs/I0qUJDAnyIm860Qkmss9vk/Ves6OF8tiwdneHg56/0OGNFK8YT88 +X7vZdrRTvJez/opMEi4r89fO4aL/3Xtw+zuhTaRjAv04l5U/BXCga99igUOLtFkN +SoxUnMW7gZ/NfaXvCyUeOiDbHPwfmGcCCtRzRBPbUYQaVQNW4AB+dAb/OMRyHdOo +P2gxXdMJxy6MW2Pg6Nwe0uxhHvLe5e/2mXZgLR6UcnHGCyoyx5JO1UbXHfmpGQrI ++pXObSOYqgs4rZpWDW+N8TEAiMEXnM0ZNjX+VVOg4DwzX5Ze4jLp3zO7Bkqp2IRz +znfSxqxx4VyjHQy7Ct9f4qNx2No3WqB4K/TUfet27fJhcKVlmtOJNBir+3I+17Q9 +eVzYH6Eze9mCUAyTF6ps3MKCuwJXNq+YJyo5UOGwifUll35HaBC07HPKs5fRJNz2 +YqAo07WjuGS3iGJCz51TzZm+ZGiPTx4SSPfSKcOYKMryMguTjClPPGAyzQWWYezy +r/6zcCwupvI= +-----END CERTIFICATE----- + +# Issuer: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY +# Subject: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY +# Label: "BJCA Global Root CA2" +# Serial: 58605626836079930195615843123109055211 +# MD5 Fingerprint: 5e:0a:f6:47:5f:a6:14:e8:11:01:95:3f:4d:01:eb:3c +# SHA1 Fingerprint: f4:27:86:eb:6e:b8:6d:88:31:67:02:fb:ba:66:a4:53:00:aa:7a:a6 +# SHA256 Fingerprint: 57:4d:f6:93:1e:27:80:39:66:7b:72:0a:fd:c1:60:0f:c2:7e:b6:6d:d3:09:29:79:fb:73:85:64:87:21:28:82 +-----BEGIN CERTIFICATE----- +MIICJTCCAaugAwIBAgIQLBcIfWQqwP6FGFkGz7RK6zAKBggqhkjOPQQDAzBUMQsw +CQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRIT1JJ +VFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0EyMB4XDTE5MTIxOTAzMTgy +MVoXDTQ0MTIxMjAzMTgyMVowVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJFSUpJ +TkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2JhbCBS +b290IENBMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABJ3LgJGNU2e1uVCxA/jlSR9B +IgmwUVJY1is0j8USRhTFiy8shP8sbqjV8QnjAyEUxEM9fMEsxEtqSs3ph+B99iK+ ++kpRuDCK/eHeGBIK9ke35xe/J4rUQUyWPGCWwf0VHKNCMEAwHQYDVR0OBBYEFNJK +sVF/BvDRgh9Obl+rg/xI1LCRMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMAoGCCqGSM49BAMDA2gAMGUCMBq8W9f+qdJUDkpd0m2xQNz0Q9XSSpkZElaA +94M04TVOSG0ED1cxMDAtsaqdAzjbBgIxAMvMh1PLet8gUXOQwKhbYdDFUDn9hf7B +43j4ptZLvZuHjw/l1lOWqzzIQNph91Oj9w== +-----END CERTIFICATE----- + +# Issuer: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited +# Subject: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited +# Label: "Sectigo Public Server Authentication Root E46" +# Serial: 88989738453351742415770396670917916916 +# MD5 Fingerprint: 28:23:f8:b2:98:5c:37:16:3b:3e:46:13:4e:b0:b3:01 +# SHA1 Fingerprint: ec:8a:39:6c:40:f0:2e:bc:42:75:d4:9f:ab:1c:1a:5b:67:be:d2:9a +# SHA256 Fingerprint: c9:0f:26:f0:fb:1b:40:18:b2:22:27:51:9b:5c:a2:b5:3e:2c:a5:b3:be:5c:f1:8e:fe:1b:ef:47:38:0c:53:83 +-----BEGIN CERTIFICATE----- +MIICOjCCAcGgAwIBAgIQQvLM2htpN0RfFf51KBC49DAKBggqhkjOPQQDAzBfMQsw +CQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1T +ZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwHhcN +MjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEYMBYG +A1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1YmxpYyBT +ZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAR2+pmpbiDt+dd34wc7qNs9Xzjoq1WmVk/WSOrsfy2qw7LFeeyZYX8QeccC +WvkEN/U0NSt3zn8gj1KjAIns1aeibVvjS5KToID1AZTc8GgHHs3u/iVStSBDHBv+ +6xnOQ6OjQjBAMB0GA1UdDgQWBBTRItpMWfFLXyY4qp3W7usNw/upYTAOBgNVHQ8B +Af8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNnADBkAjAn7qRa +qCG76UeXlImldCBteU/IvZNeWBj7LRoAasm4PdCkT0RHlAFWovgzJQxC36oCMB3q +4S6ILuH5px0CMk7yn2xVdOOurvulGu7t0vzCAxHrRVxgED1cf5kDW21USAGKcw== +-----END CERTIFICATE----- + +# Issuer: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited +# Subject: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited +# Label: "Sectigo Public Server Authentication Root R46" +# Serial: 156256931880233212765902055439220583700 +# MD5 Fingerprint: 32:10:09:52:00:d5:7e:6c:43:df:15:c0:b1:16:93:e5 +# SHA1 Fingerprint: ad:98:f9:f3:e4:7d:75:3b:65:d4:82:b3:a4:52:17:bb:6e:f5:e4:38 +# SHA256 Fingerprint: 7b:b6:47:a6:2a:ee:ac:88:bf:25:7a:a5:22:d0:1f:fe:a3:95:e0:ab:45:c7:3f:93:f6:56:54:ec:38:f2:5a:06 +-----BEGIN CERTIFICATE----- +MIIFijCCA3KgAwIBAgIQdY39i658BwD6qSWn4cetFDANBgkqhkiG9w0BAQwFADBf +MQswCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQD +Ey1TZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYw +HhcNMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEY +MBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1Ymxp +YyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCTvtU2UnXYASOgHEdCSe5jtrch/cSV1UgrJnwUUxDa +ef0rty2k1Cz66jLdScK5vQ9IPXtamFSvnl0xdE8H/FAh3aTPaE8bEmNtJZlMKpnz +SDBh+oF8HqcIStw+KxwfGExxqjWMrfhu6DtK2eWUAtaJhBOqbchPM8xQljeSM9xf +iOefVNlI8JhD1mb9nxc4Q8UBUQvX4yMPFF1bFOdLvt30yNoDN9HWOaEhUTCDsG3X +ME6WW5HwcCSrv0WBZEMNvSE6Lzzpng3LILVCJ8zab5vuZDCQOc2TZYEhMbUjUDM3 +IuM47fgxMMxF/mL50V0yeUKH32rMVhlATc6qu/m1dkmU8Sf4kaWD5QazYw6A3OAS +VYCmO2a0OYctyPDQ0RTp5A1NDvZdV3LFOxxHVp3i1fuBYYzMTYCQNFu31xR13NgE +SJ/AwSiItOkcyqex8Va3e0lMWeUgFaiEAin6OJRpmkkGj80feRQXEgyDet4fsZfu ++Zd4KKTIRJLpfSYFplhym3kT2BFfrsU4YjRosoYwjviQYZ4ybPUHNs2iTG7sijbt +8uaZFURww3y8nDnAtOFr94MlI1fZEoDlSfB1D++N6xybVCi0ITz8fAr/73trdf+L +HaAZBav6+CuBQug4urv7qv094PPK306Xlynt8xhW6aWWrL3DkJiy4Pmi1KZHQ3xt +zwIDAQABo0IwQDAdBgNVHQ4EFgQUVnNYZJX5khqwEioEYnmhQBWIIUkwDgYDVR0P +AQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAC9c +mTz8Bl6MlC5w6tIyMY208FHVvArzZJ8HXtXBc2hkeqK5Duj5XYUtqDdFqij0lgVQ +YKlJfp/imTYpE0RHap1VIDzYm/EDMrraQKFz6oOht0SmDpkBm+S8f74TlH7Kph52 +gDY9hAaLMyZlbcp+nv4fjFg4exqDsQ+8FxG75gbMY/qB8oFM2gsQa6H61SilzwZA +Fv97fRheORKkU55+MkIQpiGRqRxOF3yEvJ+M0ejf5lG5Nkc/kLnHvALcWxxPDkjB +JYOcCj+esQMzEhonrPcibCTRAUH4WAP+JWgiH5paPHxsnnVI84HxZmduTILA7rpX +DhjvLpr3Etiga+kFpaHpaPi8TD8SHkXoUsCjvxInebnMMTzD9joiFgOgyY9mpFui +TdaBJQbpdqQACj7LzTWb4OE4y2BThihCQRxEV+ioratF4yUQvNs+ZUH7G6aXD+u5 +dHn5HrwdVw1Hr8Mvn4dGp+smWg9WY7ViYG4A++MnESLn/pmPNPW56MORcr3Ywx65 +LvKRRFHQV80MNNVIIb/bE/FmJUNS0nAiNs2fxBx1IK1jcmMGDw4nztJqDby1ORrp +0XZ60Vzk50lJLVU3aPAaOpg+VBeHVOmmJ1CJeyAvP/+/oYtKR5j/K3tJPsMpRmAY +QqszKbrAKbkTidOIijlBO8n9pu0f9GBj39ItVQGL +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation +# Subject: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation +# Label: "SSL.com TLS RSA Root CA 2022" +# Serial: 148535279242832292258835760425842727825 +# MD5 Fingerprint: d8:4e:c6:59:30:d8:fe:a0:d6:7a:5a:2c:2c:69:78:da +# SHA1 Fingerprint: ec:2c:83:40:72:af:26:95:10:ff:0e:f2:03:ee:31:70:f6:78:9d:ca +# SHA256 Fingerprint: 8f:af:7d:2e:2c:b4:70:9b:b8:e0:b3:36:66:bf:75:a5:dd:45:b5:de:48:0f:8e:a8:d4:bf:e6:be:bc:17:f2:ed +-----BEGIN CERTIFICATE----- +MIIFiTCCA3GgAwIBAgIQb77arXO9CEDii02+1PdbkTANBgkqhkiG9w0BAQsFADBO +MQswCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQD +DBxTU0wuY29tIFRMUyBSU0EgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzQyMloX +DTQ2MDgxOTE2MzQyMVowTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jw +b3JhdGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgUlNBIFJvb3QgQ0EgMjAyMjCC +AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANCkCXJPQIgSYT41I57u9nTP +L3tYPc48DRAokC+X94xI2KDYJbFMsBFMF3NQ0CJKY7uB0ylu1bUJPiYYf7ISf5OY +t6/wNr/y7hienDtSxUcZXXTzZGbVXcdotL8bHAajvI9AI7YexoS9UcQbOcGV0ins +S657Lb85/bRi3pZ7QcacoOAGcvvwB5cJOYF0r/c0WRFXCsJbwST0MXMwgsadugL3 +PnxEX4MN8/HdIGkWCVDi1FW24IBydm5MR7d1VVm0U3TZlMZBrViKMWYPHqIbKUBO +L9975hYsLfy/7PO0+r4Y9ptJ1O4Fbtk085zx7AGL0SDGD6C1vBdOSHtRwvzpXGk3 +R2azaPgVKPC506QVzFpPulJwoxJF3ca6TvvC0PeoUidtbnm1jPx7jMEWTO6Af77w +dr5BUxIzrlo4QqvXDz5BjXYHMtWrifZOZ9mxQnUjbvPNQrL8VfVThxc7wDNY8VLS ++YCk8OjwO4s4zKTGkH8PnP2L0aPP2oOnaclQNtVcBdIKQXTbYxE3waWglksejBYS +d66UNHsef8JmAOSqg+qKkK3ONkRN0VHpvB/zagX9wHQfJRlAUW7qglFA35u5CCoG +AtUjHBPW6dvbxrB6y3snm/vg1UYk7RBLY0ulBY+6uB0rpvqR4pJSvezrZ5dtmi2f +gTIFZzL7SAg/2SW4BCUvAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j +BBgwFoAU+y437uOEeicuzRk1sTN8/9REQrkwHQYDVR0OBBYEFPsuN+7jhHonLs0Z +NbEzfP/UREK5MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAjYlt +hEUY8U+zoO9opMAdrDC8Z2awms22qyIZZtM7QbUQnRC6cm4pJCAcAZli05bg4vsM +QtfhWsSWTVTNj8pDU/0quOr4ZcoBwq1gaAafORpR2eCNJvkLTqVTJXojpBzOCBvf +R4iyrT7gJ4eLSYwfqUdYe5byiB0YrrPRpgqU+tvT5TgKa3kSM/tKWTcWQA673vWJ +DPFs0/dRa1419dvAJuoSc06pkZCmF8NsLzjUo3KUQyxi4U5cMj29TH0ZR6LDSeeW +P4+a0zvkEdiLA9z2tmBVGKaBUfPhqBVq6+AL8BQx1rmMRTqoENjwuSfr98t67wVy +lrXEj5ZzxOhWc5y8aVFjvO9nHEMaX3cZHxj4HCUp+UmZKbaSPaKDN7EgkaibMOlq +bLQjk2UEqxHzDh1TJElTHaE/nUiSEeJ9DU/1172iWD54nR4fK/4huxoTtrEoZP2w +AgDHbICivRZQIA9ygV/MlP+7mea6kMvq+cYMwq7FGc4zoWtcu358NFcXrfA/rs3q +r5nsLFR+jM4uElZI7xc7P0peYNLcdDa8pUNjyw9bowJWCZ4kLOGGgYz+qxcs+sji +Mho6/4UIyYOf8kpIEFR3N+2ivEC+5BB09+Rbu7nzifmPQdjH5FCQNYA+HLhNkNPU +98OwoX6EyneSMSy4kLGCenROmxMmtNVQZlR4rmA= +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation +# Subject: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation +# Label: "SSL.com TLS ECC Root CA 2022" +# Serial: 26605119622390491762507526719404364228 +# MD5 Fingerprint: 99:d7:5c:f1:51:36:cc:e9:ce:d9:19:2e:77:71:56:c5 +# SHA1 Fingerprint: 9f:5f:d9:1a:54:6d:f5:0c:71:f0:ee:7a:bd:17:49:98:84:73:e2:39 +# SHA256 Fingerprint: c3:2f:fd:9f:46:f9:36:d1:6c:36:73:99:09:59:43:4b:9a:d6:0a:af:bb:9e:7c:f3:36:54:f1:44:cc:1b:a1:43 +-----BEGIN CERTIFICATE----- +MIICOjCCAcCgAwIBAgIQFAP1q/s3ixdAW+JDsqXRxDAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQDDBxT +U0wuY29tIFRMUyBFQ0MgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzM0OFoXDTQ2 +MDgxOTE2MzM0N1owTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jwb3Jh +dGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgRUNDIFJvb3QgQ0EgMjAyMjB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABEUpNXP6wrgjzhR9qLFNoFs27iosU8NgCTWyJGYm +acCzldZdkkAZDsalE3D07xJRKF3nzL35PIXBz5SQySvOkkJYWWf9lCcQZIxPBLFN +SeR7T5v15wj4A4j3p8OSSxlUgaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSME +GDAWgBSJjy+j6CugFFR781a4Jl9nOAuc0DAdBgNVHQ4EFgQUiY8vo+groBRUe/NW +uCZfZzgLnNAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2gAMGUCMFXjIlbp +15IkWE8elDIPDAI2wv2sdDJO4fscgIijzPvX6yv/N33w7deedWo1dlJF4AIxAMeN +b0Igj762TVntd00pxCAgRWSGOlDGxK0tk/UYfXLtqc/ErFc2KAhl3zx5Zn6g6g== +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos +# Subject: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos +# Label: "Atos TrustedRoot Root CA ECC TLS 2021" +# Serial: 81873346711060652204712539181482831616 +# MD5 Fingerprint: 16:9f:ad:f1:70:ad:79:d6:ed:29:b4:d1:c5:79:70:a8 +# SHA1 Fingerprint: 9e:bc:75:10:42:b3:02:f3:81:f4:f7:30:62:d4:8f:c3:a7:51:b2:dd +# SHA256 Fingerprint: b2:fa:e5:3e:14:cc:d7:ab:92:12:06:47:01:ae:27:9c:1d:89:88:fa:cb:77:5f:a8:a0:08:91:4e:66:39:88:a8 +-----BEGIN CERTIFICATE----- +MIICFTCCAZugAwIBAgIQPZg7pmY9kGP3fiZXOATvADAKBggqhkjOPQQDAzBMMS4w +LAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgRUNDIFRMUyAyMDIxMQ0w +CwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTI2MjNaFw00MTA0 +MTcwOTI2MjJaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBDQSBF +Q0MgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMHYwEAYHKoZI +zj0CAQYFK4EEACIDYgAEloZYKDcKZ9Cg3iQZGeHkBQcfl+3oZIK59sRxUM6KDP/X +tXa7oWyTbIOiaG6l2b4siJVBzV3dscqDY4PMwL502eCdpO5KTlbgmClBk1IQ1SQ4 +AjJn8ZQSb+/Xxd4u/RmAo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR2 +KCXWfeBmmnoJsmo7jjPXNtNPojAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMD +aAAwZQIwW5kp85wxtolrbNa9d+F851F+uDrNozZffPc8dz7kUK2o59JZDCaOMDtu +CCrCp1rIAjEAmeMM56PDr9NJLkaCI2ZdyQAUEv049OGYa3cpetskz2VAv9LcjBHo +9H1/IISpQuQo +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos +# Subject: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos +# Label: "Atos TrustedRoot Root CA RSA TLS 2021" +# Serial: 111436099570196163832749341232207667876 +# MD5 Fingerprint: d4:d3:46:b8:9a:c0:9c:76:5d:9e:3a:c3:b9:99:31:d2 +# SHA1 Fingerprint: 18:52:3b:0d:06:37:e4:d6:3a:df:23:e4:98:fb:5b:16:fb:86:74:48 +# SHA256 Fingerprint: 81:a9:08:8e:a5:9f:b3:64:c5:48:a6:f8:55:59:09:9b:6f:04:05:ef:bf:18:e5:32:4e:c9:f4:57:ba:00:11:2f +-----BEGIN CERTIFICATE----- +MIIFZDCCA0ygAwIBAgIQU9XP5hmTC/srBRLYwiqipDANBgkqhkiG9w0BAQwFADBM +MS4wLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgUlNBIFRMUyAyMDIx +MQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTIxMTBaFw00 +MTA0MTcwOTIxMDlaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBD +QSBSU0EgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMIICIjAN +BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtoAOxHm9BYx9sKOdTSJNy/BBl01Z +4NH+VoyX8te9j2y3I49f1cTYQcvyAh5x5en2XssIKl4w8i1mx4QbZFc4nXUtVsYv +Ye+W/CBGvevUez8/fEc4BKkbqlLfEzfTFRVOvV98r61jx3ncCHvVoOX3W3WsgFWZ +kmGbzSoXfduP9LVq6hdKZChmFSlsAvFr1bqjM9xaZ6cF4r9lthawEO3NUDPJcFDs +GY6wx/J0W2tExn2WuZgIWWbeKQGb9Cpt0xU6kGpn8bRrZtkh68rZYnxGEFzedUln +nkL5/nWpo63/dgpnQOPF943HhZpZnmKaau1Fh5hnstVKPNe0OwANwI8f4UDErmwh +3El+fsqyjW22v5MvoVw+j8rtgI5Y4dtXz4U2OLJxpAmMkokIiEjxQGMYsluMWuPD +0xeqqxmjLBvk1cbiZnrXghmmOxYsL3GHX0WelXOTwkKBIROW1527k2gV+p2kHYzy +geBYBr3JtuP2iV2J+axEoctr+hbxx1A9JNr3w+SH1VbxT5Aw+kUJWdo0zuATHAR8 +ANSbhqRAvNncTFd+rrcztl524WWLZt+NyteYr842mIycg5kDcPOvdO3GDjbnvezB +c6eUWsuSZIKmAMFwoW4sKeFYV+xafJlrJaSQOoD0IJ2azsct+bJLKZWD6TWNp0lI +pw9MGZHQ9b8Q4HECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU +dEmZ0f+0emhFdcN+tNzMzjkz2ggwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB +DAUAA4ICAQAjQ1MkYlxt/T7Cz1UAbMVWiLkO3TriJQ2VSpfKgInuKs1l+NsW4AmS +4BjHeJi78+xCUvuppILXTdiK/ORO/auQxDh1MoSf/7OwKwIzNsAQkG8dnK/haZPs +o0UvFJ/1TCplQ3IM98P4lYsU84UgYt1UU90s3BiVaU+DR3BAM1h3Egyi61IxHkzJ +qM7F78PRreBrAwA0JrRUITWXAdxfG/F851X6LWh3e9NpzNMOa7pNdkTWwhWaJuyw +xfW70Xp0wmzNxbVe9kzmWy2B27O3Opee7c9GslA9hGCZcbUztVdF5kJHdWoOsAgM +rr3e97sPWD2PAzHoPYJQyi9eDF20l74gNAf0xBLh7tew2VktafcxBPTy+av5EzH4 +AXcOPUIjJsyacmdRIXrMPIWo6iFqO9taPKU0nprALN+AnCng33eU0aKAQv9qTFsR +0PXNor6uzFFcw9VUewyu1rkGd4Di7wcaaMxZUa1+XGdrudviB0JbuAEFWDlN5LuY +o7Ey7Nmj1m+UI/87tyll5gfp77YZ6ufCOB0yiJA8EytuzO+rdwY0d4RPcuSBhPm5 +dDTedk+SKlOxJTnbPP/lPqYO5Wue/9vsL3SD3460s6neFE3/MaNFcyT6lSnMEpcE +oji2jbDwN/zIIX8/syQbPYtuzE2wFg2WHYMfRsCbvUOZ58SWLs5fyQ== +-----END CERTIFICATE----- diff --git a/shared/package-files/79/7950309e6824e0e2df93ddcfdf7222ef6c6f4d125a8a6fb548e852ddb4ce2723/blob b/shared/package-files/79/7950309e6824e0e2df93ddcfdf7222ef6c6f4d125a8a6fb548e852ddb4ce2723/blob new file mode 100644 index 0000000000000000000000000000000000000000..d4ade834383a01bc71166c64fcd808457a051ac1 --- /dev/null +++ b/shared/package-files/79/7950309e6824e0e2df93ddcfdf7222ef6c6f4d125a8a6fb548e852ddb4ce2723/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7950309e6824e0e2df93ddcfdf7222ef6c6f4d125a8a6fb548e852ddb4ce2723 +size 622042 diff --git a/shared/package-files/79/7951e2f90d5bffcdc9d184135d100137e277843fbcbe9d4cb97ad82af0152bec/blob b/shared/package-files/79/7951e2f90d5bffcdc9d184135d100137e277843fbcbe9d4cb97ad82af0152bec/blob new file mode 100644 index 0000000000000000000000000000000000000000..c57ae0d092a6f06bb5fcbb5da5109fd2a5c24a22 --- /dev/null +++ b/shared/package-files/79/7951e2f90d5bffcdc9d184135d100137e277843fbcbe9d4cb97ad82af0152bec/blob @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::zero_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & zero_(at::Tensor & self) { + return at::_ops::zero_::call(self); +} + +// aten::zero.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & zero_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::zero_out::call(self, out); +} +// aten::zero.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & zero_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::zero_out::call(self, out); +} + +// aten::zero(Tensor self) -> Tensor +inline at::Tensor zero(const at::Tensor & self) { + return at::_ops::zero::call(self); +} + +} diff --git a/shared/package-files/79/795262e9a6f80e41c0d61a5160c536d3f8beb7a256979c781b077fdd095e9b97/blob b/shared/package-files/79/795262e9a6f80e41c0d61a5160c536d3f8beb7a256979c781b077fdd095e9b97/blob new file mode 100644 index 0000000000000000000000000000000000000000..5799d125ef94b3fd8cb9fb38fc7e2cf63e828f77 --- /dev/null +++ b/shared/package-files/79/795262e9a6f80e41c0d61a5160c536d3f8beb7a256979c781b077fdd095e9b97/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _test_optional_intlist_out(at::Tensor & out, const at::Tensor & values, at::OptionalIntArrayRef addends); +TORCH_API at::Tensor & _test_optional_intlist_outf(const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/79/7953fc3e395c4c8958eefd1f448ded1573e8816b692c967c9c5bd146b2e30eab/blob b/shared/package-files/79/7953fc3e395c4c8958eefd1f448ded1573e8816b692c967c9c5bd146b2e30eab/blob new file mode 100644 index 0000000000000000000000000000000000000000..e46ff04a00d14dd96a8a7b8052f11484a8c85d0e --- /dev/null +++ b/shared/package-files/79/7953fc3e395c4c8958eefd1f448ded1573e8816b692c967c9c5bd146b2e30eab/blob @@ -0,0 +1,30 @@ +from typing import Union, Any + +import numpy as np + +# NOTE: `_StrLike_co` and `_BytesLike_co` are pointless, as `np.str_` and +# `np.bytes_` are already subclasses of their builtin counterpart + +_CharLike_co = Union[str, bytes] + +# The 6 `Like_co` type-aliases below represent all scalars that can be +# coerced into `` (with the casting rule `same_kind`) +_BoolLike_co = Union[bool, np.bool_] +_UIntLike_co = Union[_BoolLike_co, np.unsignedinteger[Any]] +_IntLike_co = Union[_BoolLike_co, int, np.integer[Any]] +_FloatLike_co = Union[_IntLike_co, float, np.floating[Any]] +_ComplexLike_co = Union[_FloatLike_co, complex, np.complexfloating[Any, Any]] +_TD64Like_co = Union[_IntLike_co, np.timedelta64] + +_NumberLike_co = Union[int, float, complex, np.number[Any], np.bool_] +_ScalarLike_co = Union[ + int, + float, + complex, + str, + bytes, + np.generic, +] + +# `_VoidLike_co` is technically not a scalar, but it's close enough +_VoidLike_co = Union[tuple[Any, ...], np.void] diff --git a/shared/package-files/79/7954623ee8a7a483fcf5de9c56ff002b5c750e55e782fdf6891a4e462f3235cd/blob b/shared/package-files/79/7954623ee8a7a483fcf5de9c56ff002b5c750e55e782fdf6891a4e462f3235cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..e134d17415b0d2042236a972707a291b72f36b69 --- /dev/null +++ b/shared/package-files/79/7954623ee8a7a483fcf5de9c56ff002b5c750e55e782fdf6891a4e462f3235cd/blob @@ -0,0 +1,495 @@ +import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +from abc import ABCMeta, abstractmethod +from types import CodeType, FrameType, TracebackType + +# Definitions of special type checking related constructs. Their definitions +# are not used, so their value does not matter. + +overload = object() +Any = object() + +class TypeVar: + __name__: str + __bound__: Optional[Type[Any]] + __constraints__: Tuple[Type[Any], ...] + __covariant__: bool + __contravariant__: bool + def __init__( + self, + name: str, + *constraints: Type[Any], + bound: Optional[Type[Any]] = ..., + covariant: bool = ..., + contravariant: bool = ..., + ) -> None: ... + +_promote = object() + +class _SpecialForm(object): + def __getitem__(self, typeargs: Any) -> object: ... + +Union: _SpecialForm = ... +Optional: _SpecialForm = ... +Tuple: _SpecialForm = ... +Generic: _SpecialForm = ... +Protocol: _SpecialForm = ... +Callable: _SpecialForm = ... +Type: _SpecialForm = ... +ClassVar: _SpecialForm = ... +Final: _SpecialForm = ... +_F = TypeVar("_F", bound=Callable[..., Any]) + +def final(f: _F) -> _F: ... + +Literal: _SpecialForm = ... +# TypedDict is a (non-subscriptable) special form. +TypedDict: object = ... + +class GenericMeta(type): ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] + +# These type variables are used by the container types. +_T = TypeVar("_T") +_S = TypeVar("_S") +_KT = TypeVar("_KT") # Key type. +_VT = TypeVar("_VT") # Value type. +_T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. +_V_co = TypeVar("_V_co", covariant=True) # Any type covariant containers. +_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. +_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. +_T_contra = TypeVar("_T_contra", contravariant=True) # Ditto contravariant. +_TC = TypeVar("_TC", bound=Type[object]) +_C = TypeVar("_C", bound=Callable[..., Any]) + +no_type_check = object() + +def no_type_check_decorator(decorator: _C) -> _C: ... + +# Type aliases and type constructors + +class _Alias: + # Class for defining generic aliases for library types. + def __getitem__(self, typeargs: Any) -> Any: ... + +List = _Alias() +Dict = _Alias() +DefaultDict = _Alias() +Set = _Alias() +FrozenSet = _Alias() +Counter = _Alias() +Deque = _Alias() + +# Predefined type variables. +AnyStr = TypeVar("AnyStr", str, unicode) + +# Abstract base classes. + +def runtime_checkable(cls: _TC) -> _TC: ... +@runtime_checkable +class SupportsInt(Protocol, metaclass=ABCMeta): + @abstractmethod + def __int__(self) -> int: ... + +@runtime_checkable +class SupportsFloat(Protocol, metaclass=ABCMeta): + @abstractmethod + def __float__(self) -> float: ... + +@runtime_checkable +class SupportsComplex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime_checkable +class SupportsAbs(Protocol[_T_co]): + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime_checkable +class Reversible(Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime_checkable +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime_checkable +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def next(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + @abstractmethod + def next(self) -> _T_co: ... + @abstractmethod + def send(self, __value: _T_contra) -> _T_co: ... + @overload + @abstractmethod + def throw( + self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + ) -> _T_co: ... + @overload + @abstractmethod + def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ... + @abstractmethod + def close(self) -> None: ... + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + +@runtime_checkable +class Container(Protocol[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + +class Sequence(Iterable[_T_co], Container[_T_co], Reversible[_T_co], Generic[_T_co]): + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + # Mixin methods + def index(self, x: Any) -> int: ... + def count(self, x: Any) -> int: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableSequence(Sequence[_T], Generic[_T]): + @abstractmethod + def insert(self, index: int, object: _T) -> None: ... + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + @abstractmethod + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + @abstractmethod + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: int) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: slice) -> None: ... + # Mixin methods + def append(self, object: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def remove(self, object: _T) -> None: ... + def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + +class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + # Mixin methods + def __le__(self, s: AbstractSet[Any]) -> bool: ... + def __lt__(self, s: AbstractSet[Any]) -> bool: ... + def __gt__(self, s: AbstractSet[Any]) -> bool: ... + def __ge__(self, s: AbstractSet[Any]) -> bool: ... + def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + # TODO: argument can be any container? + def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableSet(AbstractSet[_T], Generic[_T]): + @abstractmethod + def add(self, x: _T) -> None: ... + @abstractmethod + def discard(self, x: _T) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + +class MappingView(object): + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + +class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + +class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): + def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + +@runtime_checkable +class ContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + def __exit__( + self, + __exc_type: Optional[Type[BaseException]], + __exc_value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> Optional[bool]: ... + +class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https: //github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, k: _KT) -> _VT_co: ... + # Mixin methods + @overload + def get(self, k: _KT) -> Optional[_VT_co]: ... + @overload + def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def keys(self) -> list[_KT]: ... + def values(self) -> list[_VT_co]: ... + def items(self) -> list[Tuple[_KT, _VT_co]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT_co]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT_co]]: ... + def __contains__(self, o: object) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): + @abstractmethod + def __setitem__(self, k: _KT, v: _VT) -> None: ... + @abstractmethod + def __delitem__(self, v: _KT) -> None: ... + def clear(self) -> None: ... + @overload + def pop(self, k: _KT) -> _VT: ... + @overload + def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + +Text = unicode + +TYPE_CHECKING = True + +class IO(Iterator[AnyStr], Generic[AnyStr]): + # TODO detach + # TODO use abstract properties + @property + def mode(self) -> str: ... + @property + def name(self) -> str: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + # TODO what if n is None? + @abstractmethod + def read(self, n: int = ...) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = ...) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = ...) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: Optional[int] = ...) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + # TODO buffer objects + @abstractmethod + def write(self, s: AnyStr) -> int: ... + @abstractmethod + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + @abstractmethod + def next(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__( + self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] + ) -> Optional[bool]: ... + +class BinaryIO(IO[str]): + # TODO readinto + # TODO read1? + # TODO peek? + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[unicode]): + # TODO use abstractproperty + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> Optional[str]: ... + @property + def line_buffering(self) -> bool: ... + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +class ByteString(Sequence[int], metaclass=ABCMeta): ... + +class Match(Generic[AnyStr]): + pos: int + endpos: int + lastindex: Optional[int] + string: AnyStr + + # The regular expression object whose match() or search() method produced + # this match instance. This should not be Pattern[AnyStr] because the type + # of the pattern is independent of the type of the matched string in + # Python 2. Strictly speaking Match should be generic over AnyStr twice: + # once for the type of the pattern and once for the type of the matched + # string. + re: Pattern[Any] + # Can be None if there are no groups or if the last group was unnamed; + # otherwise matches the type of the pattern. + lastgroup: Optional[Any] + def expand(self, template: Union[str, Text]) -> Any: ... + @overload + def group(self, group1: int = ...) -> AnyStr: ... + @overload + def group(self, group1: str) -> AnyStr: ... + @overload + def group(self, group1: int, group2: int, *groups: int) -> Tuple[AnyStr, ...]: ... + @overload + def group(self, group1: str, group2: str, *groups: str) -> Tuple[AnyStr, ...]: ... + def groups(self, default: AnyStr = ...) -> Tuple[AnyStr, ...]: ... + def groupdict(self, default: AnyStr = ...) -> Dict[str, AnyStr]: ... + def start(self, __group: Union[int, str] = ...) -> int: ... + def end(self, __group: Union[int, str] = ...) -> int: ... + def span(self, __group: Union[int, str] = ...) -> Tuple[int, int]: ... + @property + def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + +# We need a second TypeVar with the same definition as AnyStr, because +# Pattern is generic over AnyStr (determining the type of its .pattern +# attribute), but at the same time its methods take either bytes or +# Text and return the same type, regardless of the type of the pattern. +_AnyStr2 = TypeVar("_AnyStr2", bytes, Text) + +class Pattern(Generic[AnyStr]): + flags: int + groupindex: Dict[AnyStr, int] + groups: int + pattern: AnyStr + def search(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def match(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def split(self, string: _AnyStr2, maxsplit: int = ...) -> List[_AnyStr2]: ... + # Returns either a list of _AnyStr2 or a list of tuples, depending on + # whether there are groups in the pattern. + def findall(self, string: Union[bytes, Text], pos: int = ..., endpos: int = ...) -> List[Any]: ... + def finditer(self, string: _AnyStr2, pos: int = ..., endpos: int = ...) -> Iterator[Match[_AnyStr2]]: ... + @overload + def sub(self, repl: _AnyStr2, string: _AnyStr2, count: int = ...) -> _AnyStr2: ... + @overload + def sub(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> _AnyStr2: ... + @overload + def subn(self, repl: _AnyStr2, string: _AnyStr2, count: int = ...) -> Tuple[_AnyStr2, int]: ... + @overload + def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, count: int = ...) -> Tuple[_AnyStr2, int]: ... + +# Functions + +def get_type_hints( + obj: Callable[..., Any], globalns: Optional[Dict[Text, Any]] = ..., localns: Optional[Dict[Text, Any]] = ... +) -> None: ... +@overload +def cast(tp: Type[_T], obj: Any) -> _T: ... +@overload +def cast(tp: str, obj: Any) -> Any: ... +@overload +def cast(tp: object, obj: Any) -> Any: ... + +# Type constructors + +# NamedTuple is special-cased in the type checker +class NamedTuple(Tuple[Any, ...]): + _fields: Tuple[str, ...] + def __init__(self, typename: Text, fields: Iterable[Tuple[Text, Any]] = ..., **kwargs: Any) -> None: ... + @classmethod + def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... + def _asdict(self) -> Dict[str, Any]: ... + def _replace(self: _T, **kwargs: Any) -> _T: ... + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +class _TypedDict(Mapping[str, object], metaclass=ABCMeta): + def copy(self: _T) -> _T: ... + # Using NoReturn so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: NoReturn, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: NoReturn, default: _T = ...) -> object: ... + def update(self: _T, __m: _T) -> None: ... + def has_key(self, k: str) -> bool: ... + def viewitems(self) -> ItemsView[str, object]: ... + def viewkeys(self) -> KeysView[str]: ... + def viewvalues(self) -> ValuesView[object]: ... + def __delitem__(self, k: NoReturn) -> None: ... + +def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + +# This itself is only available during type checking +def type_check_only(func_or_cls: _C) -> _C: ... diff --git a/shared/package-files/79/795849fdcace1cbee7906e0a6f474ea3b34be161cccbf3f1ebae5a00dff777ef/blob b/shared/package-files/79/795849fdcace1cbee7906e0a6f474ea3b34be161cccbf3f1ebae5a00dff777ef/blob new file mode 100644 index 0000000000000000000000000000000000000000..fe33fcef1e18d2a4b92287e434cf6b1257e4274f --- /dev/null +++ b/shared/package-files/79/795849fdcace1cbee7906e0a6f474ea3b34be161cccbf3f1ebae5a00dff777ef/blob @@ -0,0 +1,5 @@ +from __future__ import annotations + +from contourpy.util._build_config import build_config + +__all__ = ["build_config"] diff --git a/shared/package-files/79/795961068f0cb1c59c9c64b559540fb5be80b025c1a8985f63dd30b87bf65d33/blob b/shared/package-files/79/795961068f0cb1c59c9c64b559540fb5be80b025c1a8985f63dd30b87bf65d33/blob new file mode 100644 index 0000000000000000000000000000000000000000..3bd017197577d973e5c77c3c51ad966a015b890b Binary files /dev/null and b/shared/package-files/79/795961068f0cb1c59c9c64b559540fb5be80b025c1a8985f63dd30b87bf65d33/blob differ diff --git a/shared/package-files/79/795bf5e90481c2029aa233941cc3c2cb8a2ef5978587e1e8095e03a6aad91b85/blob b/shared/package-files/79/795bf5e90481c2029aa233941cc3c2cb8a2ef5978587e1e8095e03a6aad91b85/blob new file mode 100644 index 0000000000000000000000000000000000000000..827505b842d4f1ad0e16dfe54ef28658364cc9ac --- /dev/null +++ b/shared/package-files/79/795bf5e90481c2029aa233941cc3c2cb8a2ef5978587e1e8095e03a6aad91b85/blob @@ -0,0 +1,73 @@ +from ._register_onnx_ops import _register_custom_op +from .boxes import ( + batched_nms, + box_area, + box_convert, + box_iou, + clip_boxes_to_image, + complete_box_iou, + distance_box_iou, + generalized_box_iou, + masks_to_boxes, + nms, + remove_small_boxes, +) +from .ciou_loss import complete_box_iou_loss +from .deform_conv import deform_conv2d, DeformConv2d +from .diou_loss import distance_box_iou_loss +from .drop_block import drop_block2d, drop_block3d, DropBlock2d, DropBlock3d +from .feature_pyramid_network import FeaturePyramidNetwork +from .focal_loss import sigmoid_focal_loss +from .giou_loss import generalized_box_iou_loss +from .misc import Conv2dNormActivation, Conv3dNormActivation, FrozenBatchNorm2d, MLP, Permute, SqueezeExcitation +from .poolers import MultiScaleRoIAlign +from .ps_roi_align import ps_roi_align, PSRoIAlign +from .ps_roi_pool import ps_roi_pool, PSRoIPool +from .roi_align import roi_align, RoIAlign +from .roi_pool import roi_pool, RoIPool +from .stochastic_depth import stochastic_depth, StochasticDepth + +_register_custom_op() + + +__all__ = [ + "masks_to_boxes", + "deform_conv2d", + "DeformConv2d", + "nms", + "batched_nms", + "remove_small_boxes", + "clip_boxes_to_image", + "box_convert", + "box_area", + "box_iou", + "generalized_box_iou", + "distance_box_iou", + "complete_box_iou", + "roi_align", + "RoIAlign", + "roi_pool", + "RoIPool", + "ps_roi_align", + "PSRoIAlign", + "ps_roi_pool", + "PSRoIPool", + "MultiScaleRoIAlign", + "FeaturePyramidNetwork", + "sigmoid_focal_loss", + "stochastic_depth", + "StochasticDepth", + "FrozenBatchNorm2d", + "Conv2dNormActivation", + "Conv3dNormActivation", + "SqueezeExcitation", + "MLP", + "Permute", + "generalized_box_iou_loss", + "distance_box_iou_loss", + "complete_box_iou_loss", + "drop_block2d", + "DropBlock2d", + "drop_block3d", + "DropBlock3d", +] diff --git a/shared/package-files/79/795cef408ecfbed636657148246e45c93b19ddbf4df2c403d254451ae516816f/blob b/shared/package-files/79/795cef408ecfbed636657148246e45c93b19ddbf4df2c403d254451ae516816f/blob new file mode 100644 index 0000000000000000000000000000000000000000..689b5fd9dbc79f9cb5c0892f12b8a3e05196717f --- /dev/null +++ b/shared/package-files/79/795cef408ecfbed636657148246e45c93b19ddbf4df2c403d254451ae516816f/blob @@ -0,0 +1,130 @@ +import functools + +from typing import Dict, Set, Tuple + +import torch +from torch._dynamo.utils import counters + +from torch._ops import OpOverload, OpOverloadPacket +from ..pattern_matcher import fwd_only, register_replacement + +aten = torch.ops.aten + + +@functools.lru_cache(None) +def _misc_patterns_init(): + from .joint_graph import patterns as joint_graph_patterns + from .post_grad import pass_patterns as post_grad_patterns_all + + post_grad_patterns = post_grad_patterns_all[1] # medium priority + + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + else: + device = "cpu" + + # These patterns do 2 things + # 1. Since we know that index is completely unique, we can codegen it using + # stores instead of atomic adds, which is quite a bit faster. + # 2. Also, since we are guaranteed that they are completely within bounds, + # we can use unsafe indexing and skip debug asserts + def randperm_index_add_pattern(x, y): + index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]] + return torch.index_add(x, dim=0, source=y, index=index), index + + def randperm_index_add_replacement(x, y): + index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]] + return ( + torch.ops.aten._unsafe_index_put( + x, (index,), aten._unsafe_index(x, (index,)) + y, accumulate=False + ), + index, + ) + + register_replacement( + randperm_index_add_pattern, + randperm_index_add_replacement, + [torch.empty(4, 8, device=device), torch.empty(2, 8, device=device)], + fwd_only, + [post_grad_patterns, joint_graph_patterns], + ) + + def randperm_index_pattern(x, slice_shape): + index = torch.randperm(x.shape[0], device=x.device)[:slice_shape] + return torch.ops.aten.index(x, (index,)), index + + def randperm_index_replacement(x, slice_shape): + index = torch.randperm(x.shape[0], device=x.device)[:slice_shape] + return torch.ops.aten._unsafe_index(x, (index,)), index + + pattern = register_replacement( + randperm_index_pattern, + randperm_index_replacement, + [torch.empty(4, 8, device=device)], + fwd_only, + [post_grad_patterns, joint_graph_patterns], + scalar_workaround={"slice_shape": 42}, + ) + + +class NumpyCompatNormalization: + numpy_compat: Dict[str, Tuple[str, ...]] = { + "dim": ("axis",), + "keepdim": ("keepdims",), + "input": ("x", "a", "x1"), + "other": ("x2",), + } + inverse_mapping: Dict[str, str] + cache: Dict["torch.fx.graph.Target", Set[str]] + + def __init__(self): + self.cache = {} # callable -> tuple of replaceable args e.g. ["axis"] + self.inverse_mapping = {} + for actual_kwarg, numpy_kwargs in self.numpy_compat.items(): + for numpy_kwarg in numpy_kwargs: + assert numpy_kwarg not in self.inverse_mapping + self.inverse_mapping[numpy_kwarg] = actual_kwarg + + def __call__(self, graph: torch.fx.Graph): + for node in graph.nodes: + if node.op != "call_function": + continue + if isinstance(node.target, (OpOverload, OpOverloadPacket)): + # only applies to torch ops; e.g. torch.stack(axis=1) works, torch.ops.aten.stack(axis=1) doesn't. + continue + kwargs = node.kwargs + + if node.target in self.cache: + replaceable_kwargs = self.cache[node.target] + else: + signatures = torch.fx.operator_schemas.get_signature_for_torch_op( + node.target + ) + signatures = () if signatures is None else signatures + replaceable_kwargs = set() + for sig in signatures: + for param_name in sig.parameters.keys(): + if param_name in self.numpy_compat: + replaceable_kwargs.update(self.numpy_compat[param_name]) + + self.cache[node.target] = replaceable_kwargs + + if not replaceable_kwargs: + continue + + new_kwargs = {} + kwargs_changed = False + for k, v in kwargs.items(): + if k in replaceable_kwargs: + kwargs_changed = True + new_kwargs[self.inverse_mapping[k]] = v + else: + new_kwargs[k] = v + + if kwargs_changed: + node.kwargs = torch.fx.immutable_collections.immutable_dict(new_kwargs) + counters["inductor"]["numpy_compat_normalization"] += 1 + + +numpy_compat_normalization = NumpyCompatNormalization() diff --git a/shared/package-files/79/7967dcd2f6620ec18ccf458d87780b19c54f2090bd72ea1d32164b8371483666/blob b/shared/package-files/79/7967dcd2f6620ec18ccf458d87780b19c54f2090bd72ea1d32164b8371483666/blob new file mode 100644 index 0000000000000000000000000000000000000000..d23c6f8e731767d3fb94a6abf193810731f82fdd --- /dev/null +++ b/shared/package-files/79/7967dcd2f6620ec18ccf458d87780b19c54f2090bd72ea1d32164b8371483666/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7967dcd2f6620ec18ccf458d87780b19c54f2090bd72ea1d32164b8371483666 +size 104608 diff --git a/shared/package-files/79/7969615d4540a247ad65ae6211ddeac3fecf83a61146197d2ca4841b51dcde25/blob b/shared/package-files/79/7969615d4540a247ad65ae6211ddeac3fecf83a61146197d2ca4841b51dcde25/blob new file mode 100644 index 0000000000000000000000000000000000000000..10a946cc407750504c06018e6f3399f66f320936 --- /dev/null +++ b/shared/package-files/79/7969615d4540a247ad65ae6211ddeac3fecf83a61146197d2ca4841b51dcde25/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor _embedding_bag_backward(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, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, bool sparse, const c10::optional & per_sample_weights, int64_t padding_idx=-1); +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 & per_sample_weights, int64_t padding_idx=-1); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/79/796c068a9244ce8eecbb3cbb4e3b82328b89d4ac14f5f94717f3af3c6389c6e3/blob b/shared/package-files/79/796c068a9244ce8eecbb3cbb4e3b82328b89d4ac14f5f94717f3af3c6389c6e3/blob new file mode 100644 index 0000000000000000000000000000000000000000..c8379f38810f70990969ca6b58afdb58748db87e --- /dev/null +++ b/shared/package-files/79/796c068a9244ce8eecbb3cbb4e3b82328b89d4ac14f5f94717f3af3c6389c6e3/blob @@ -0,0 +1,157 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace caffe2 { +namespace serialize { +class ReadAdapterInterface; +} // namespace serialize +} // namespace caffe2 + +namespace torch { +namespace jit { + +class DeserializationStorageContext; + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + const std::string& filename, + c10::optional device = c10::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::istream& in, + c10::optional device = c10::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::unique_ptr rai, + c10::optional device = c10::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + const std::string& filename, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true, + bool restore_shapes = false); + +// For reading unified serialization format from torch.Package +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::shared_ptr reader, + std::shared_ptr storage_context, + c10::optional device, + std::string ts_id /* torchscript identifier inside package */); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::istream& in, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true, + bool restore_shapes = false); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::unique_ptr rai, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::shared_ptr rai, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given `istream`. +/// +/// The istream must contain a serialized `Module`, exported via +/// `torch::jit::ExportModule` in C++. +TORCH_API Module load( + std::istream& in, + c10::optional device = c10::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + std::istream& in, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given `filename`. +/// +/// The file stored at the location given in `filename` must contain a +/// serialized `Module`, exported either via `ScriptModule.save()` in +/// Python or `torch::jit::ExportModule` in C++. +TORCH_API Module load( + const std::string& filename, + c10::optional device = c10::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + const std::string& filename, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given shared_ptr `rai`. +/// +/// The reader adapter, which is for customized input stream, must contain a +/// serialized `Module`, exported either via `ScriptModule.save()` in +/// Python or `torch::jit::ExportModule` in C++. +TORCH_API Module load( + std::shared_ptr rai, + c10::optional device = c10::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + std::shared_ptr rai, + c10::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +TORCH_API Module jitModuleFromSourceAndConstants( + const IValue& ivalue, + const ExtraFilesMap& source, + const std::vector& constants, + int32_t version); + +TORCH_API Module parse_and_initialize_jit_module( + std::shared_ptr data, + size_t size, + ExtraFilesMap& extra_files, + c10::optional device = c10::nullopt); + +TORCH_API Module load_jit_module_from_file( + const std::string& filename, + ExtraFilesMap& extra_files, + c10::optional device = c10::nullopt); + +TORCH_API Module load_jit_module_from_stream( + std::istream& in, + ExtraFilesMap& extra_files, + c10::optional device = c10::nullopt); + +TORCH_API Module parse_and_initialize_jit_module( + std::shared_ptr data, + size_t size, + ExtraFilesMap& extra_files, + c10::optional device); + +TORCH_API c10::intrusive_ptr ObjLoaderFunc( + const at::StrongTypePtr& type, + IValue input); + +} // namespace jit +} // namespace torch diff --git a/shared/package-files/79/796c3da0406291dd324c51901b51386be12b5f52e330afaf69584f57c06ad45c/blob b/shared/package-files/79/796c3da0406291dd324c51901b51386be12b5f52e330afaf69584f57c06ad45c/blob new file mode 100644 index 0000000000000000000000000000000000000000..0fcf4738a70fcb4797fdd9785963b375f17fbdf0 --- /dev/null +++ b/shared/package-files/79/796c3da0406291dd324c51901b51386be12b5f52e330afaf69584f57c06ad45c/blob @@ -0,0 +1,236 @@ +"income","foodexp" +420.157650843928,255.839424594576 +541.411706721205,310.958667059145 +901.157456651663,485.680014171085 +639.08022868883,402.997355544163 +750.875605828476,495.560774933776 +945.7989310482,633.797815132393 +829.397886847186,630.756567705217 +979.164835837914,700.440904266032 +1309.87894037831,830.95862150535 +1492.39874437426,815.360217290461 +502.838980218067,338.001387329587 +616.71684724229,412.361338428638 +790.922511291545,520.000617981121 +555.878641643074,452.401472907332 +713.44118368415,512.720057836885 +838.756132722629,658.839530303595 +535.076645900387,392.599496749012 +596.440805359932,443.558633799595 +924.561896582212,640.11637771341 +487.758301817955,333.839386975747 +692.639734238467,466.958318528848 +997.876977824175,543.396904263231 +506.999491179525,317.719843756484 +654.158711401758,424.320896352573 +933.919270183382,518.961656053407 +433.681329252018,338.001387329587 +587.596213341684,419.641174631375 +896.474635643808,476.320048933563 +454.478223782524,386.36016331012 +584.998919370362,423.278349805554 +800.799016617394,503.35717119023 +502.436869899465,354.638868545299 +713.519666530832,497.31816882899 +906.000628725279,588.519463958722 +880.596923786325,654.597144597117 +796.828919368547,550.727427597965 +854.87905261442,528.376976714303 +1167.37159427026,640.481348055373 +523.800035579844,401.320355546637 +670.779185433114,435.999021900918 +377.058368850099,276.560609645838 +851.543001748297,588.348818059025 +1121.09369365137,664.19780220393 +625.517933400268,444.860166410776 +805.537696174017,462.899514863823 +558.581201465033,377.779238546012 +884.400487319312,553.15043561635 +1257.49886576834,810.896154761447 +2051.17894099901,1067.95405614074 +1466.33299214604,1049.87879168732 +730.098896774438,522.701209676143 +800.799016617394,572.080662617684 +1245.69638760971,907.396944580766 +1201.00021368196,811.57759369573 +634.400209148622,427.797520201042 +956.231463138833,649.998464123521 +1148.60104702955,860.600154559902 +1768.82364982203,1143.42108582835 +2822.53303466609,2032.67919020832 +922.354832141967,590.618327009967 +2293.19197144236,1570.39113831708 +627.472597042135,483.480024661708 +889.980898378682,600.480399087121 +1162.19995392922,696.202105745481 +1197.07935707754,774.796179057776 +530.797185462728,390.598430399482 +1142.15259256708,612.56190089616 +1088.00388697846,708.762151593178 +484.661156316503,296.919185772441 +1536.02010067662,1071.46269646941 +678.897392141278,496.597580037315 +671.880165854403,503.39744137471 +690.468256477202,357.641110879089 +860.694825783725,430.337592716917 +873.309484596291,624.699041398883 +894.459835214087,582.54125094185 +1148.64699199033,580.221542246938 +926.876192988813,543.88074278423 +839.041358293354,588.637179622688 +829.49742056551,627.99989545798 +1264.00432957802,712.101174262357 +1937.97714636527,968.394940061335 +698.831741432851,482.581587621304 +920.419919363967,593.169385581544 +1897.57113999412,1033.56575426925 +891.682386298282,693.679473449282 +889.6783563083,693.679473449282 +1221.48181114807,761.279065822776 +544.599139402161,361.398056338879 +1031.44911476975,628.452218199356 +1462.94967217323,771.44856441849 +830.435282442915,757.118666447887 +975.04146665886,821.59699408795 +1337.99833996025,1022.3201704203 +867.64270523161,679.440727360101 +725.745933703277,538.749115686801 +989.005606041026,679.998097246959 +1525.00047421177,977.003270959677 +672.196023753147,561.201488176248 +923.397682201603,728.399746623589 +472.321548280698,372.318622584609 +590.760092419618,361.52095256921 +940.921768902254,517.919590751206 +643.357141462033,459.817650989876 +2551.66151377579,863.919851470995 +1795.32258882792,831.440717300088 +1165.77339020587,534.761043791083 +815.62117431089,392.050242021584 +1264.20658645087,934.975195444102 +1095.40561684263,813.308096301318 +447.447852411217,263.709996170628 +1178.97417954918,769.083849021127 +975.802295687602,630.586286420944 +1017.85220007186,645.987400679307 +423.879832013577,319.558386349475 +558.776739102636,348.451830104442 +943.248718270872,614.506803163417 +1348.30024452767,662.009562038758 +2340.61735387973,1504.37077491258 +587.179168098792,406.218015716283 +1540.97405699008,692.1688993212 +1115.84807481956,588.137050604953 +1044.68428590432,511.260885979623 +1389.79286912095,700.559989341702 +2497.78595383858,1301.14509754583 +1585.38094296753,879.066017413729 +1862.04383602348,912.885078250154 +2008.8546243469,1509.7811718462 +697.309947594492,484.060548936204 +571.251746766114,399.670317095029 +598.346489479165,444.100105563446 +461.097722534667,248.810111222236 +977.110747230569,527.801359578015 +883.984916757004,500.631349055309 +718.359399343153,436.810734740578 +543.897059451262,374.799044124691 +1587.34803468162,726.392135101241 +4957.81302447901,1827.1999644396 +969.68376220836,523.49108470832 +419.998021268147,334.99982183865 +561.998960360707,473.200883889103 +689.598814337616,581.202945705675 +1398.5202607169,929.75396743285 +820.816847571835,591.197416678028 +875.171616264683,637.548275219478 +1392.44991016741,674.950935444337 +1256.31737222348,776.758895179758 +1362.85902988814,959.516968477919 +1999.25521962472,1250.96433391432 +1209.47299210597,737.820079380279 +1125.0356465964,810.677242354166 +1827.40096749065,983.000864895715 +1014.15395295671,708.896829195949 +880.394409783857,633.120014158391 +2432.39099224122,1424.80465628899 +1177.85468592228,830.95862150535 +1222.5938655042,925.579474233555 +1519.58112468928,1162.00239672989 +687.663761691575,383.457962724518 +953.11922427465,621.117329201764 +953.11922427465,621.117329201764 +953.11922427465,621.117329201764 +939.04180595405,548.600231233027 +1283.40245730726,745.235294456105 +1511.57888086542,837.80049554801 +1342.58212809281,795.34024163682 +511.797991841133,418.597567936084 +689.798826994207,508.797449887606 +1532.30742618103,883.278011623353 +1056.08082482784,742.527569034242 +387.319525632704,242.32020192074 +387.319525632704,242.32020192074 +410.998678844171,266.00098186588 +832.755431984518,614.75880260907 +614.998605300573,385.318397885378 +887.465812960725,515.619969025557 +1024.81767735549,708.478703425954 +1006.43533940422,734.235630810297 +725.999989237198,433.000983776039 +494.417350707113,327.418772037758 +748.641327251627,429.039933638385 +987.64171960278,619.640827692018 +788.09607104789,400.798978053224 +831.79831368624,620.800640126449 +1139.49447493599,819.996440995918 +507.516894491359,360.878017655466 +576.197221195524,395.760804612775 +696.59905406528,442.000052121661 +650.817978373872,404.03843113149 +949.580207412905,670.799309110531 +497.119281341608,297.5701513364 +570.167398903935,353.488163131684 +724.730600295316,383.93758487932 +408.339934376479,284.800803268761 +638.671348198183,431.099964756245 +1225.78900333424,801.351758612919 +715.370077715236,448.451258996436 +800.470756318541,577.911070749254 +975.597398720442,570.521012300081 +1613.75654835121,865.320535878418 +608.501878790717,444.557764325978 +958.663378279956,680.419826789901 +835.942641428986,576.277894453487 +873.737511101673,631.798175131743 +951.44320976533,608.641850318947 +473.002181248345,300.999920310599 +601.003044352051,377.998414059123 +713.99788489267,397.001476569931 +829.29836507219,588.519463958722 +959.795268750367,681.761575036767 +1212.96129506839,807.360270100159 +958.874307424532,696.801097085781 +1129.44314702273,811.196241851397 +1943.04187331083,1305.72014134299 +539.638785503439,442.000052121661 +463.599021125583,353.601297444411 +562.640004501253,468.000797511221 +736.758383070776,526.75734679978 +1415.44606403432,890.239030266526 +2208.78970565549,1318.80328223672 +636.000913716338,331.000537750629 +759.401026863119,416.401525383919 +1078.83819961899,596.840554600565 +499.751012804117,408.499218009175 +1020.02253584507,775.020902533032 +1595.1610788589,1138.16204602323 +776.595792938105,485.519766208776 +1230.92352504251,772.761142353133 +1807.95201459536,993.96301727137 +415.440747985411,305.438973730216 +440.51742415637,306.519078570937 +541.200597324592,299.199327967538 +581.35989168777,468.000797511221 +743.077242789534,522.601905880464 +1057.67671146451,750.320163419201 diff --git a/shared/package-files/79/796e90cf37b6b74faca5e2669afb7524ccdb91269d20a744f385c773b254b467/blob b/shared/package-files/79/796e90cf37b6b74faca5e2669afb7524ccdb91269d20a744f385c773b254b467/blob new file mode 100644 index 0000000000000000000000000000000000000000..7ff9949ffa93e44835ab133998b89e440094f909 Binary files /dev/null and b/shared/package-files/79/796e90cf37b6b74faca5e2669afb7524ccdb91269d20a744f385c773b254b467/blob differ diff --git a/shared/package-files/79/797128a6210eeb5338315f80e110521d229c2b3835c452bc6096cd6cf183829f/blob b/shared/package-files/79/797128a6210eeb5338315f80e110521d229c2b3835c452bc6096cd6cf183829f/blob new file mode 100644 index 0000000000000000000000000000000000000000..2df99e709b7e83f06f6cf9780b6cee8aa50d8576 --- /dev/null +++ b/shared/package-files/79/797128a6210eeb5338315f80e110521d229c2b3835c452bc6096cd6cf183829f/blob @@ -0,0 +1,19 @@ +import torch + +__all__ = [ + "get_cpu_capability", +] + + +def get_cpu_capability() -> str: + r"""Return cpu capability as a string value. + + Possible values: + - "DEFAULT" + - "VSX" + - "Z VECTOR" + - "NO AVX" + - "AVX2" + - "AVX512" + """ + return torch._C._get_cpu_capability() diff --git a/shared/package-files/79/79738e029e8cbe935246323647fa98686a365724626b725916220c002f67cf5a/blob b/shared/package-files/79/79738e029e8cbe935246323647fa98686a365724626b725916220c002f67cf5a/blob new file mode 100644 index 0000000000000000000000000000000000000000..4518d07c42e2e0a74de087bcb6f390ceff4e2b40 --- /dev/null +++ b/shared/package-files/79/79738e029e8cbe935246323647fa98686a365724626b725916220c002f67cf5a/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::batch_norm_stats(Tensor input, float eps) -> (Tensor, Tensor) +inline ::std::tuple batch_norm_stats(const at::Tensor & input, double eps) { + return at::_ops::batch_norm_stats::call(input, eps); +} + +// aten::batch_norm_stats.out(Tensor input, float eps, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple batch_norm_stats_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & input, double eps) { + return at::_ops::batch_norm_stats_out::call(input, eps, out0, out1); +} +// aten::batch_norm_stats.out(Tensor input, float eps, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple batch_norm_stats_outf(const at::Tensor & input, double eps, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::batch_norm_stats_out::call(input, eps, out0, out1); +} + +} diff --git a/shared/package-files/79/7974974f78946d7435a092745ca24d0ee72a14893752c9667bafc87aac29da13/blob b/shared/package-files/79/7974974f78946d7435a092745ca24d0ee72a14893752c9667bafc87aac29da13/blob new file mode 100644 index 0000000000000000000000000000000000000000..e1ca0f7dbaefa2837f0147d9a26e32c2ab859646 --- /dev/null +++ b/shared/package-files/79/7974974f78946d7435a092745ca24d0ee72a14893752c9667bafc87aac29da13/blob @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor not_equal(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & not_equal_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & not_equal_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor not_equal(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & not_equal_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & not_equal_(at::Tensor & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/79/797534e839cf2c22cae9a9f9544e7d4e511b59110d07375cf2981a3460e77db2/blob b/shared/package-files/79/797534e839cf2c22cae9a9f9544e7d4e511b59110d07375cf2981a3460e77db2/blob new file mode 100644 index 0000000000000000000000000000000000000000..babb70eaf7cb11a937b5feacd40c4104fc3ae8d1 --- /dev/null +++ b/shared/package-files/79/797534e839cf2c22cae9a9f9544e7d4e511b59110d07375cf2981a3460e77db2/blob @@ -0,0 +1,127 @@ +import torch +from torch import Tensor + +aten = torch.ops.aten +import inspect +import warnings +from typing import Dict, List, Optional, Set + +from torch.types import Number + +decomposition_table: Dict[str, torch.jit.ScriptFunction] = {} +function_name_set: Set[str] = set() + + +def check_decomposition_has_type_annotations(f): + inspect_empty = inspect._empty # type: ignore[attr-defined] + sig = inspect.signature(f) + for param in sig.parameters.values(): + assert ( + param.annotation != inspect_empty + ), f"No signature on param {param.name} for function {f.name}" + + assert ( + sig.return_annotation != inspect_empty + ), f"No return annotation for function {f.name}" + + +def signatures_match(decomposition_sig, torch_op_sig): + decomp_params = decomposition_sig.parameters + op_params = torch_op_sig.parameters + + if len(decomp_params) != len(op_params): + return False + + for decomp_param, op_param in zip(decomp_params.values(), op_params.values()): + # can't check full equality yet because not all fields are correcly deduced + # in the torch_op_sig - like default value + # can't check 'kind' bc + # kwarg-only values with defaults not yet supported in TS + inspect_empty = inspect._empty # type: ignore[attr-defined] + for field in ["name", "annotation"]: + if field == "name" and decomp_param.name == "self": + warnings.warn("PyTorch uses 'input' instead of 'self' on public api") + + if getattr(decomp_param, field) != getattr(op_param, field): + return False + + decomp_default = decomp_param.default + op_default = op_param.default + # default value not always correctly inferred as being present on torch schema, + # but if specified on both they should be equal + if decomp_default != inspect_empty and op_default != inspect_empty: + if decomp_default != op_default: + return False + + return decomposition_sig.return_annotation == torch_op_sig.return_annotation + + +def register_decomposition(aten_op, registry=None): + def decomposition_decorator(f): + nonlocal registry + if registry is None: + registry = decomposition_table + + assert isinstance(aten_op, torch._ops.OpOverload) + + # Need unique name for jit function serialization + assert ( + f.__name__ not in function_name_set + ), f"Duplicated function name {f.__name__}" + function_name_set.add(f.__name__) + + scripted_func = torch.jit.script(f) + torch._C._jit_pass_inline(scripted_func.graph) + + for _ in range(2): + torch._C._jit_pass_peephole(scripted_func.graph) + torch._C._jit_pass_constant_propagation(scripted_func.graph) + + registry[str(aten_op._schema)] = scripted_func + return f + + return decomposition_decorator + + +# TODO: replace torch.sigmoid -> aten.sigmoid + + +@register_decomposition(aten.var.correction) +def var_decomposition( + input: Tensor, + dim: Optional[List[int]] = None, + correction: Optional[Number] = None, + keepdim: bool = False, +) -> Tensor: + if dim is None: + dim_i: List[int] = [] + dim = dim_i + + if isinstance(dim, (tuple, list)) and len(dim) == 0: + n = input.numel() + else: + n = 1 + for dim_i in dim: # type: ignore[assignment] + n *= input.shape[dim_i] # type: ignore[call-overload] + + mean = aten.mean(input, dim, True) + sub = input - mean + sq = sub * sub + sum = aten.sum(sq, dim, keepdim) + + if correction is None: + denom = float(n - 1) + else: + if isinstance(correction, int): + denom = float(n - correction) + elif isinstance(correction, float): + denom = float(n) - correction + else: + raise RuntimeError("correction must be int or float") + + return sum / max(0, denom) + + +@register_decomposition(aten.var.default) +def var(input: Tensor, unbiased: bool = True) -> Tensor: + return var_decomposition(input, correction=(1 if unbiased else 0)) diff --git a/shared/package-files/79/7976ab5c8924d5289044f6bb45dbbf47a803807766da5eb41e1d913ed3d37fb1/blob b/shared/package-files/79/7976ab5c8924d5289044f6bb45dbbf47a803807766da5eb41e1d913ed3d37fb1/blob new file mode 100644 index 0000000000000000000000000000000000000000..f34386245fd6849b4408a0c1745f55c0b3fce167 --- /dev/null +++ b/shared/package-files/79/7976ab5c8924d5289044f6bb45dbbf47a803807766da5eb41e1d913ed3d37fb1/blob @@ -0,0 +1,4857 @@ +from collections.abc import Iterable, Sequence +from contextlib import ExitStack +import functools +import inspect +import logging +from numbers import Real +from operator import attrgetter +import re +import types + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, _docstring, offsetbox +import matplotlib.artist as martist +import matplotlib.axis as maxis +from matplotlib.cbook import _OrderedSet, _check_1d, index_of +import matplotlib.collections as mcoll +import matplotlib.colors as mcolors +import matplotlib.font_manager as font_manager +from matplotlib.gridspec import SubplotSpec +import matplotlib.image as mimage +import matplotlib.lines as mlines +import matplotlib.patches as mpatches +from matplotlib.rcsetup import cycler, validate_axisbelow +import matplotlib.spines as mspines +import matplotlib.table as mtable +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms + +_log = logging.getLogger(__name__) + + +class _axis_method_wrapper: + """ + Helper to generate Axes methods wrapping Axis methods. + + After :: + + get_foo = _axis_method_wrapper("xaxis", "get_bar") + + (in the body of a class) ``get_foo`` is a method that forwards it arguments + to the ``get_bar`` method of the ``xaxis`` attribute, and gets its + signature and docstring from ``Axis.get_bar``. + + The docstring of ``get_foo`` is built by replacing "this Axis" by "the + {attr_name}" (i.e., "the xaxis", "the yaxis") in the wrapped method's + dedented docstring; additional replacements can be given in *doc_sub*. + """ + + def __init__(self, attr_name, method_name, *, doc_sub=None): + self.attr_name = attr_name + self.method_name = method_name + # Immediately put the docstring in ``self.__doc__`` so that docstring + # manipulations within the class body work as expected. + doc = inspect.getdoc(getattr(maxis.Axis, method_name)) + self._missing_subs = [] + if doc: + doc_sub = {"this Axis": f"the {self.attr_name}", **(doc_sub or {})} + for k, v in doc_sub.items(): + if k not in doc: # Delay raising error until we know qualname. + self._missing_subs.append(k) + doc = doc.replace(k, v) + self.__doc__ = doc + + def __set_name__(self, owner, name): + # This is called at the end of the class body as + # ``self.__set_name__(cls, name_under_which_self_is_assigned)``; we + # rely on that to give the wrapper the correct __name__/__qualname__. + get_method = attrgetter(f"{self.attr_name}.{self.method_name}") + + def wrapper(self, *args, **kwargs): + return get_method(self)(*args, **kwargs) + + wrapper.__module__ = owner.__module__ + wrapper.__name__ = name + wrapper.__qualname__ = f"{owner.__qualname__}.{name}" + wrapper.__doc__ = self.__doc__ + # Manually copy the signature instead of using functools.wraps because + # displaying the Axis method source when asking for the Axes method + # source would be confusing. + wrapper.__signature__ = inspect.signature( + getattr(maxis.Axis, self.method_name)) + + if self._missing_subs: + raise ValueError( + "The definition of {} expected that the docstring of Axis.{} " + "contains {!r} as substrings".format( + wrapper.__qualname__, self.method_name, + ", ".join(map(repr, self._missing_subs)))) + + setattr(owner, name, wrapper) + + +class _TransformedBoundsLocator: + """ + Axes locator for `.Axes.inset_axes` and similarly positioned Axes. + + The locator is a callable object used in `.Axes.set_aspect` to compute the + Axes location depending on the renderer. + """ + + def __init__(self, bounds, transform): + """ + *bounds* (a ``[l, b, w, h]`` rectangle) and *transform* together + specify the position of the inset Axes. + """ + self._bounds = bounds + self._transform = transform + + def __call__(self, ax, renderer): + # Subtracting transSubfigure will typically rely on inverted(), + # freezing the transform; thus, this needs to be delayed until draw + # time as transSubfigure may otherwise change after this is evaluated. + return mtransforms.TransformedBbox( + mtransforms.Bbox.from_bounds(*self._bounds), + self._transform - ax.get_figure(root=False).transSubfigure) + + +def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False): + """ + Convert a MATLAB style color/line style format string to a (*linestyle*, + *marker*, *color*) tuple. + + Example format strings include: + + * 'ko': black circles + * '.b': blue dots + * 'r--': red dashed lines + * 'C2--': the third color in the color cycle, dashed lines + + The format is absolute in the sense that if a linestyle or marker is not + defined in *fmt*, there is no line or marker. This is expressed by + returning 'None' for the respective quantity. + + See Also + -------- + matplotlib.Line2D.lineStyles, matplotlib.colors.cnames + All possible styles and color format strings. + """ + + linestyle = None + marker = None + color = None + + # First check whether fmt is just a colorspec, but specifically exclude the + # grayscale string "1" (not "1.0"), which is interpreted as the tri_down + # marker "1". The grayscale string "0" could be unambiguously understood + # as a color (black) but also excluded for consistency. + if fmt not in ["0", "1"]: + try: + color = mcolors.to_rgba(fmt) + return linestyle, marker, color + except ValueError: + pass + + errfmt = ("{!r} is neither a data key nor a valid format string ({})" + if ambiguous_fmt_datakey else + "{!r} is not a valid format string ({})") + + i = 0 + while i < len(fmt): + c = fmt[i] + if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles. + if linestyle is not None: + raise ValueError(errfmt.format(fmt, "two linestyle symbols")) + linestyle = fmt[i:i+2] + i += 2 + elif c in mlines.lineStyles: + if linestyle is not None: + raise ValueError(errfmt.format(fmt, "two linestyle symbols")) + linestyle = c + i += 1 + elif c in mlines.lineMarkers: + if marker is not None: + raise ValueError(errfmt.format(fmt, "two marker symbols")) + marker = c + i += 1 + elif c in mcolors.get_named_colors_mapping(): + if color is not None: + raise ValueError(errfmt.format(fmt, "two color symbols")) + color = c + i += 1 + elif c == "C": + cn_color = re.match(r"C\d+", fmt[i:]) + if not cn_color: + raise ValueError(errfmt.format(fmt, "'C' must be followed by a number")) + color = mcolors.to_rgba(cn_color[0]) + i += len(cn_color[0]) + else: + raise ValueError(errfmt.format(fmt, f"unrecognized character {c!r}")) + + if linestyle is None and marker is None: + linestyle = mpl.rcParams['lines.linestyle'] + if linestyle is None: + linestyle = 'None' + if marker is None: + marker = 'None' + + return linestyle, marker, color + + +class _process_plot_var_args: + """ + Process variable length arguments to `~.Axes.plot`, to support :: + + plot(t, s) + plot(t1, s1, t2, s2) + plot(t1, s1, 'ko', t2, s2) + plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3) + + an arbitrary number of *x*, *y*, *fmt* are allowed + """ + + def __init__(self, output='Line2D'): + _api.check_in_list(['Line2D', 'Polygon', 'coordinates'], output=output) + self.output = output + self.set_prop_cycle(None) + + def set_prop_cycle(self, cycler): + if cycler is None: + cycler = mpl.rcParams['axes.prop_cycle'] + self._idx = 0 + self._cycler_items = [*cycler] + + def __call__(self, axes, *args, data=None, return_kwargs=False, **kwargs): + axes._process_unit_info(kwargs=kwargs) + + for pos_only in "xy": + if pos_only in kwargs: + raise _api.kwarg_error(inspect.stack()[1].function, pos_only) + + if not args: + return + + if data is None: # Process dict views + args = [cbook.sanitize_sequence(a) for a in args] + else: # Process the 'data' kwarg. + replaced = [mpl._replacer(data, arg) for arg in args] + if len(args) == 1: + label_namer_idx = 0 + elif len(args) == 2: # Can be x, y or y, c. + # Figure out what the second argument is. + # 1) If the second argument cannot be a format shorthand, the + # second argument is the label_namer. + # 2) Otherwise (it could have been a format shorthand), + # a) if we did perform a substitution, emit a warning, and + # use it as label_namer. + # b) otherwise, it is indeed a format shorthand; use the + # first argument as label_namer. + try: + _process_plot_format(args[1]) + except ValueError: # case 1) + label_namer_idx = 1 + else: + if replaced[1] is not args[1]: # case 2a) + _api.warn_external( + f"Second argument {args[1]!r} is ambiguous: could " + f"be a format string but is in 'data'; using as " + f"data. If it was intended as data, set the " + f"format string to an empty string to suppress " + f"this warning. If it was intended as a format " + f"string, explicitly pass the x-values as well. " + f"Alternatively, rename the entry in 'data'.", + RuntimeWarning) + label_namer_idx = 1 + else: # case 2b) + label_namer_idx = 0 + elif len(args) == 3: + label_namer_idx = 1 + else: + raise ValueError( + "Using arbitrary long args with data is not supported due " + "to ambiguity of arguments; use multiple plotting calls " + "instead") + if kwargs.get("label") is None: + kwargs["label"] = mpl._label_from_arg( + replaced[label_namer_idx], args[label_namer_idx]) + args = replaced + ambiguous_fmt_datakey = data is not None and len(args) == 2 + + if len(args) >= 4 and not cbook.is_scalar_or_string( + kwargs.get("label")): + raise ValueError("plot() with multiple groups of data (i.e., " + "pairs of x and y) does not support multiple " + "labels") + + # Repeatedly grab (x, y) or (x, y, format) from the front of args and + # massage them into arguments to plot() or fill(). + + while args: + this, args = args[:2], args[2:] + if args and isinstance(args[0], str): + this += args[0], + args = args[1:] + yield from self._plot_args( + axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey, + return_kwargs=return_kwargs + ) + + def get_next_color(self): + """Return the next color in the cycle.""" + entry = self._cycler_items[self._idx] + if "color" in entry: + self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler. + return entry["color"] + else: + return "k" + + def _getdefaults(self, kw, ignore=frozenset()): + """ + If some keys in the property cycle (excluding those in the set + *ignore*) are absent or set to None in the dict *kw*, return a copy + of the next entry in the property cycle, excluding keys in *ignore*. + Otherwise, don't advance the property cycle, and return an empty dict. + """ + defaults = self._cycler_items[self._idx] + if any(kw.get(k, None) is None for k in {*defaults} - ignore): + self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler. + # Return a new dict to avoid exposing _cycler_items entries to mutation. + return {k: v for k, v in defaults.items() if k not in ignore} + else: + return {} + + def _setdefaults(self, defaults, kw): + """ + Add to the dict *kw* the entries in the dict *default* that are absent + or set to None in *kw*. + """ + for k in defaults: + if kw.get(k, None) is None: + kw[k] = defaults[k] + + def _make_line(self, axes, x, y, kw, kwargs): + kw = {**kw, **kwargs} # Don't modify the original kw. + self._setdefaults(self._getdefaults(kw), kw) + seg = mlines.Line2D(x, y, **kw) + return seg, kw + + def _make_coordinates(self, axes, x, y, kw, kwargs): + kw = {**kw, **kwargs} # Don't modify the original kw. + self._setdefaults(self._getdefaults(kw), kw) + return (x, y), kw + + def _make_polygon(self, axes, x, y, kw, kwargs): + # Polygon doesn't directly support unitized inputs. + x = axes.convert_xunits(x) + y = axes.convert_yunits(y) + + kw = kw.copy() # Don't modify the original kw. + kwargs = kwargs.copy() + + # Ignore 'marker'-related properties as they aren't Polygon + # properties, but they are Line2D properties, and so they are + # likely to appear in the default cycler construction. + # This is done here to the defaults dictionary as opposed to the + # other two dictionaries because we do want to capture when a + # *user* explicitly specifies a marker which should be an error. + # We also want to prevent advancing the cycler if there are no + # defaults needed after ignoring the given properties. + ignores = ({'marker', 'markersize', 'markeredgecolor', + 'markerfacecolor', 'markeredgewidth'} + # Also ignore anything provided by *kwargs*. + | {k for k, v in kwargs.items() if v is not None}) + + # Only using the first dictionary to use as basis + # for getting defaults for back-compat reasons. + # Doing it with both seems to mess things up in + # various places (probably due to logic bugs elsewhere). + default_dict = self._getdefaults(kw, ignores) + self._setdefaults(default_dict, kw) + + # Looks like we don't want "color" to be interpreted to + # mean both facecolor and edgecolor for some reason. + # So the "kw" dictionary is thrown out, and only its + # 'color' value is kept and translated as a 'facecolor'. + # This design should probably be revisited as it increases + # complexity. + facecolor = kw.get('color', None) + + # Throw out 'color' as it is now handled as a facecolor + default_dict.pop('color', None) + + # To get other properties set from the cycler + # modify the kwargs dictionary. + self._setdefaults(default_dict, kwargs) + + seg = mpatches.Polygon(np.column_stack((x, y)), + facecolor=facecolor, + fill=kwargs.get('fill', True), + closed=kw['closed']) + seg.set(**kwargs) + return seg, kwargs + + def _plot_args(self, axes, tup, kwargs, *, + return_kwargs=False, ambiguous_fmt_datakey=False): + """ + Process the arguments of ``plot([x], y, [fmt], **kwargs)`` calls. + + This processes a single set of ([x], y, [fmt]) parameters; i.e. for + ``plot(x, y, x2, y2)`` it will be called twice. Once for (x, y) and + once for (x2, y2). + + x and y may be 2D and thus can still represent multiple datasets. + + For multiple datasets, if the keyword argument *label* is a list, this + will unpack the list and assign the individual labels to the datasets. + + Parameters + ---------- + tup : tuple + A tuple of the positional parameters. This can be one of + + - (y,) + - (x, y) + - (y, fmt) + - (x, y, fmt) + + kwargs : dict + The keyword arguments passed to ``plot()``. + + return_kwargs : bool + Whether to also return the effective keyword arguments after label + unpacking as well. + + ambiguous_fmt_datakey : bool + Whether the format string in *tup* could also have been a + misspelled data key. + + Returns + ------- + result + If *return_kwargs* is false, a list of Artists representing the + dataset(s). + If *return_kwargs* is true, a list of (Artist, effective_kwargs) + representing the dataset(s). See *return_kwargs*. + The Artist is either `.Line2D` (if called from ``plot()``) or + `.Polygon` otherwise. + """ + if len(tup) > 1 and isinstance(tup[-1], str): + # xy is tup with fmt stripped (could still be (y,) only) + *xy, fmt = tup + linestyle, marker, color = _process_plot_format( + fmt, ambiguous_fmt_datakey=ambiguous_fmt_datakey) + elif len(tup) == 3: + raise ValueError('third arg must be a format string') + else: + xy = tup + linestyle, marker, color = None, None, None + + # Don't allow any None value; these would be up-converted to one + # element array of None which causes problems downstream. + if any(v is None for v in tup): + raise ValueError("x, y, and format string must not be None") + + kw = {} + for prop_name, val in zip(('linestyle', 'marker', 'color'), + (linestyle, marker, color)): + if val is not None: + # check for conflicts between fmt and kwargs + if (fmt.lower() != 'none' + and prop_name in kwargs + and val != 'None'): + # Technically ``plot(x, y, 'o', ls='--')`` is a conflict + # because 'o' implicitly unsets the linestyle + # (linestyle='None'). + # We'll gracefully not warn in this case because an + # explicit set via kwargs can be seen as intention to + # override an implicit unset. + # Note: We don't val.lower() != 'none' because val is not + # necessarily a string (can be a tuple for colors). This + # is safe, because *val* comes from _process_plot_format() + # which only returns 'None'. + _api.warn_external( + f"{prop_name} is redundantly defined by the " + f"'{prop_name}' keyword argument and the fmt string " + f'"{fmt}" (-> {prop_name}={val!r}). The keyword ' + f"argument will take precedence.") + kw[prop_name] = val + + if len(xy) == 2: + x = _check_1d(xy[0]) + y = _check_1d(xy[1]) + else: + x, y = index_of(xy[-1]) + + if axes.xaxis is not None: + axes.xaxis.update_units(x) + if axes.yaxis is not None: + axes.yaxis.update_units(y) + + if x.shape[0] != y.shape[0]: + raise ValueError(f"x and y must have same first dimension, but " + f"have shapes {x.shape} and {y.shape}") + if x.ndim > 2 or y.ndim > 2: + raise ValueError(f"x and y can be no greater than 2D, but have " + f"shapes {x.shape} and {y.shape}") + if x.ndim == 1: + x = x[:, np.newaxis] + if y.ndim == 1: + y = y[:, np.newaxis] + + if self.output == 'Line2D': + make_artist = self._make_line + elif self.output == 'Polygon': + kw['closed'] = kwargs.get('closed', True) + make_artist = self._make_polygon + elif self.output == 'coordinates': + make_artist = self._make_coordinates + else: + _api.check_in_list(['Line2D', 'Polygon', 'coordinates'], output=self.output) + + ncx, ncy = x.shape[1], y.shape[1] + if ncx > 1 and ncy > 1 and ncx != ncy: + raise ValueError(f"x has {ncx} columns but y has {ncy} columns") + if ncx == 0 or ncy == 0: + return [] + + label = kwargs.get('label') + n_datasets = max(ncx, ncy) + + if cbook.is_scalar_or_string(label): + labels = [label] * n_datasets + elif len(label) == n_datasets: + labels = label + elif n_datasets == 1: + msg = (f'Passing label as a length {len(label)} sequence when ' + 'plotting a single dataset is deprecated in Matplotlib 3.9 ' + 'and will error in 3.11. To keep the current behavior, ' + 'cast the sequence to string before passing.') + _api.warn_deprecated('3.9', message=msg) + labels = [label] + else: + raise ValueError( + f"label must be scalar or have the same length as the input " + f"data, but found {len(label)} for {n_datasets} datasets.") + + result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw, + {**kwargs, 'label': label}) + for j, label in enumerate(labels)) + + if return_kwargs: + return list(result) + else: + return [l[0] for l in result] + + +@_api.define_aliases({"facecolor": ["fc"]}) +class _AxesBase(martist.Artist): + name = "rectilinear" + + # axis names are the prefixes for the attributes that contain the + # respective axis; e.g. 'x' <-> self.xaxis, containing an XAxis. + # Note that PolarAxes uses these attributes as well, so that we have + # 'x' <-> self.xaxis, containing a ThetaAxis. In particular we do not + # have 'theta' in _axis_names. + # In practice, this is ('x', 'y') for all 2D Axes and ('x', 'y', 'z') + # for Axes3D. + _axis_names = ("x", "y") + _shared_axes = {name: cbook.Grouper() for name in _axis_names} + _twinned_axes = cbook.Grouper() + + _subclass_uses_cla = False + + dataLim: mtransforms.Bbox + """The bounding `.Bbox` enclosing all data displayed in the Axes.""" + + spines: mspines.Spines + """ + The `.Spines` container for the Axes' spines, i.e. the lines denoting the + data area boundaries. + """ + + xaxis: maxis.XAxis + """ + The `.XAxis` instance. + + Common axis-related configuration can be achieved through high-level wrapper + methods on Axes; e.g. `ax.set_xticks <.Axes.set_xticks>` is a shortcut for + `ax.xaxis.set_ticks <.Axis.set_ticks>`. The *xaxis* attribute gives direct + direct access to the underlying `~.axis.Axis` if you need more control. + + See also + + - :ref:`Axis wrapper methods on Axes ` + - :doc:`Axis API ` + """ + + yaxis: maxis.YAxis + """ + The `.YAxis` instance. + + Common axis-related configuration can be achieved through high-level wrapper + methods on Axes; e.g. `ax.set_yticks <.Axes.set_yticks>` is a shortcut for + `ax.yaxis.set_ticks <.Axis.set_ticks>`. The *yaxis* attribute gives direct + access to the underlying `~.axis.Axis` if you need more control. + + See also + + - :ref:`Axis wrapper methods on Axes ` + - :doc:`Axis API ` + """ + + @property + def _axis_map(self): + """A mapping of axis names, e.g. 'x', to `Axis` instances.""" + return {name: getattr(self, f"{name}axis") + for name in self._axis_names} + + def __str__(self): + return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format( + type(self).__name__, self._position.bounds) + + def __init__(self, fig, + *args, + facecolor=None, # defaults to rc axes.facecolor + frameon=True, + sharex=None, # use Axes instance's xaxis info + sharey=None, # use Axes instance's yaxis info + label='', + xscale=None, + yscale=None, + box_aspect=None, + forward_navigation_events="auto", + **kwargs + ): + """ + Build an Axes in a figure. + + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + The Axes is built in the `.Figure` *fig*. + + *args + ``*args`` can be a single ``(left, bottom, width, height)`` + rectangle or a single `.Bbox`. This specifies the rectangle (in + figure coordinates) where the Axes is positioned. + + ``*args`` can also consist of three numbers or a single three-digit + number; in the latter case, the digits are considered as + independent numbers. The numbers are interpreted as ``(nrows, + ncols, index)``: ``(nrows, ncols)`` specifies the size of an array + of subplots, and ``index`` is the 1-based index of the subplot + being created. Finally, ``*args`` can also directly be a + `.SubplotSpec` instance. + + sharex, sharey : `~matplotlib.axes.Axes`, optional + The x- or y-`~.matplotlib.axis` is shared with the x- or y-axis in + the input `~.axes.Axes`. Note that it is not possible to unshare + axes. + + frameon : bool, default: True + Whether the Axes frame is visible. + + box_aspect : float, optional + Set a fixed aspect for the Axes box, i.e. the ratio of height to + width. See `~.axes.Axes.set_box_aspect` for details. + + forward_navigation_events : bool or "auto", default: "auto" + Control whether pan/zoom events are passed through to Axes below + this one. "auto" is *True* for axes with an invisible patch and + *False* otherwise. + + **kwargs + Other optional keyword arguments: + + %(Axes:kwdoc)s + + Returns + ------- + `~.axes.Axes` + The new `~.axes.Axes` object. + """ + + super().__init__() + if "rect" in kwargs: + if args: + raise TypeError( + "'rect' cannot be used together with positional arguments") + rect = kwargs.pop("rect") + _api.check_isinstance((mtransforms.Bbox, Iterable), rect=rect) + args = (rect,) + subplotspec = None + if len(args) == 1 and isinstance(args[0], mtransforms.Bbox): + self._position = args[0].frozen() + elif len(args) == 1 and np.iterable(args[0]): + self._position = mtransforms.Bbox.from_bounds(*args[0]) + else: + self._position = self._originalPosition = mtransforms.Bbox.unit() + subplotspec = SubplotSpec._from_subplot_args(fig, args) + if self._position.width < 0 or self._position.height < 0: + raise ValueError('Width and height specified must be non-negative') + self._originalPosition = self._position.frozen() + self.axes = self + self._aspect = 'auto' + self._adjustable = 'box' + self._anchor = 'C' + self._stale_viewlims = dict.fromkeys(self._axis_names, False) + self._forward_navigation_events = forward_navigation_events + self._sharex = sharex + self._sharey = sharey + self.set_label(label) + self.set_figure(fig) + # The subplotspec needs to be set after the figure (so that + # figure-level subplotpars are taken into account), but the figure + # needs to be set after self._position is initialized. + if subplotspec: + self.set_subplotspec(subplotspec) + else: + self._subplotspec = None + self.set_box_aspect(box_aspect) + self._axes_locator = None # Optionally set via update(kwargs). + + self._children = [] + + # placeholder for any colorbars added that use this Axes. + # (see colorbar.py): + self._colorbars = [] + self.spines = mspines.Spines.from_dict(self._gen_axes_spines()) + + # this call may differ for non-sep axes, e.g., polar + self._init_axis() + if facecolor is None: + facecolor = mpl.rcParams['axes.facecolor'] + self._facecolor = facecolor + self._frameon = frameon + self.set_axisbelow(mpl.rcParams['axes.axisbelow']) + + self._rasterization_zorder = None + self.clear() + + # funcs used to format x and y - fall back on major formatters + self.fmt_xdata = None + self.fmt_ydata = None + + self.set_navigate(True) + self.set_navigate_mode(None) + + if xscale: + self.set_xscale(xscale) + if yscale: + self.set_yscale(yscale) + + self._internal_update(kwargs) + + for name, axis in self._axis_map.items(): + axis.callbacks._connect_picklable( + 'units', self._unit_change_handler(name)) + + rcParams = mpl.rcParams + self.tick_params( + top=rcParams['xtick.top'] and rcParams['xtick.minor.top'], + bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'], + labeltop=(rcParams['xtick.labeltop'] and + rcParams['xtick.minor.top']), + labelbottom=(rcParams['xtick.labelbottom'] and + rcParams['xtick.minor.bottom']), + left=rcParams['ytick.left'] and rcParams['ytick.minor.left'], + right=rcParams['ytick.right'] and rcParams['ytick.minor.right'], + labelleft=(rcParams['ytick.labelleft'] and + rcParams['ytick.minor.left']), + labelright=(rcParams['ytick.labelright'] and + rcParams['ytick.minor.right']), + which='minor') + + self.tick_params( + top=rcParams['xtick.top'] and rcParams['xtick.major.top'], + bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'], + labeltop=(rcParams['xtick.labeltop'] and + rcParams['xtick.major.top']), + labelbottom=(rcParams['xtick.labelbottom'] and + rcParams['xtick.major.bottom']), + left=rcParams['ytick.left'] and rcParams['ytick.major.left'], + right=rcParams['ytick.right'] and rcParams['ytick.major.right'], + labelleft=(rcParams['ytick.labelleft'] and + rcParams['ytick.major.left']), + labelright=(rcParams['ytick.labelright'] and + rcParams['ytick.major.right']), + which='major') + + def __init_subclass__(cls, **kwargs): + parent_uses_cla = super(cls, cls)._subclass_uses_cla + if 'cla' in cls.__dict__: + _api.warn_deprecated( + '3.6', + pending=True, + message=f'Overriding `Axes.cla` in {cls.__qualname__} is ' + 'pending deprecation in %(since)s and will be fully ' + 'deprecated in favor of `Axes.clear` in the future. ' + 'Please report ' + f'this to the {cls.__module__!r} author.') + cls._subclass_uses_cla = 'cla' in cls.__dict__ or parent_uses_cla + super().__init_subclass__(**kwargs) + + def __getstate__(self): + state = super().__getstate__() + # Prune the sharing & twinning info to only contain the current group. + state["_shared_axes"] = { + name: self._shared_axes[name].get_siblings(self) + for name in self._axis_names if self in self._shared_axes[name]} + state["_twinned_axes"] = (self._twinned_axes.get_siblings(self) + if self in self._twinned_axes else None) + return state + + def __setstate__(self, state): + # Merge the grouping info back into the global groupers. + shared_axes = state.pop("_shared_axes") + for name, shared_siblings in shared_axes.items(): + self._shared_axes[name].join(*shared_siblings) + twinned_siblings = state.pop("_twinned_axes") + if twinned_siblings: + self._twinned_axes.join(*twinned_siblings) + self.__dict__ = state + self._stale = True + + def __repr__(self): + fields = [] + if self.get_label(): + fields += [f"label={self.get_label()!r}"] + if hasattr(self, "get_title"): + titles = {} + for k in ["left", "center", "right"]: + title = self.get_title(loc=k) + if title: + titles[k] = title + if titles: + fields += [f"title={titles}"] + for name, axis in self._axis_map.items(): + if axis.label and axis.label.get_text(): + fields += [f"{name}label={axis.label.get_text()!r}"] + return f"<{self.__class__.__name__}: " + ", ".join(fields) + ">" + + def get_subplotspec(self): + """Return the `.SubplotSpec` associated with the subplot, or None.""" + return self._subplotspec + + def set_subplotspec(self, subplotspec): + """Set the `.SubplotSpec`. associated with the subplot.""" + self._subplotspec = subplotspec + self._set_position(subplotspec.get_position(self.get_figure(root=False))) + + def get_gridspec(self): + """Return the `.GridSpec` associated with the subplot, or None.""" + return self._subplotspec.get_gridspec() if self._subplotspec else None + + def get_window_extent(self, renderer=None): + """ + Return the Axes bounding box in display space. + + This bounding box does not include the spines, ticks, ticklabels, + or other labels. For a bounding box including these elements use + `~matplotlib.axes.Axes.get_tightbbox`. + + See Also + -------- + matplotlib.axes.Axes.get_tightbbox + matplotlib.axis.Axis.get_tightbbox + matplotlib.spines.Spine.get_window_extent + """ + return self.bbox + + def _init_axis(self): + # This is moved out of __init__ because non-separable axes don't use it + self.xaxis = maxis.XAxis(self, clear=False) + self.spines.bottom.register_axis(self.xaxis) + self.spines.top.register_axis(self.xaxis) + self.yaxis = maxis.YAxis(self, clear=False) + self.spines.left.register_axis(self.yaxis) + self.spines.right.register_axis(self.yaxis) + + def set_figure(self, fig): + # docstring inherited + super().set_figure(fig) + + self.bbox = mtransforms.TransformedBbox(self._position, + fig.transSubfigure) + # these will be updated later as data is added + self.dataLim = mtransforms.Bbox.null() + self._viewLim = mtransforms.Bbox.unit() + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + self._set_lim_and_transforms() + + def _unstale_viewLim(self): + # We should arrange to store this information once per share-group + # instead of on every axis. + need_scale = { + name: any(ax._stale_viewlims[name] + for ax in self._shared_axes[name].get_siblings(self)) + for name in self._axis_names} + if any(need_scale.values()): + for name in need_scale: + for ax in self._shared_axes[name].get_siblings(self): + ax._stale_viewlims[name] = False + self.autoscale_view(**{f"scale{name}": scale + for name, scale in need_scale.items()}) + + @property + def viewLim(self): + """The view limits as `.Bbox` in data coordinates.""" + self._unstale_viewLim() + return self._viewLim + + def _request_autoscale_view(self, axis="all", tight=None): + """ + Mark a single axis, or all of them, as stale wrt. autoscaling. + + No computation is performed until the next autoscaling; thus, separate + calls to control individual axises incur negligible performance cost. + + Parameters + ---------- + axis : str, default: "all" + Either an element of ``self._axis_names``, or "all". + tight : bool or None, default: None + """ + axis_names = _api.check_getitem( + {**{k: [k] for k in self._axis_names}, "all": self._axis_names}, + axis=axis) + for name in axis_names: + self._stale_viewlims[name] = True + if tight is not None: + self._tight = tight + + def _set_lim_and_transforms(self): + """ + Set the *_xaxis_transform*, *_yaxis_transform*, *transScale*, + *transData*, *transLimits* and *transAxes* transformations. + + .. note:: + + This method is primarily used by rectilinear projections of the + `~matplotlib.axes.Axes` class, and is meant to be overridden by + new kinds of projection Axes that need different transformations + and limits. (See `~matplotlib.projections.polar.PolarAxes` for an + example.) + """ + self.transAxes = mtransforms.BboxTransformTo(self.bbox) + + # Transforms the x and y axis separately by a scale factor. + # It is assumed that this part will have non-linear components + # (e.g., for a log scale). + self.transScale = mtransforms.TransformWrapper( + mtransforms.IdentityTransform()) + + # An affine transformation on the data, generally to limit the + # range of the axes + self.transLimits = mtransforms.BboxTransformFrom( + mtransforms.TransformedBbox(self._viewLim, self.transScale)) + + # The parentheses are important for efficiency here -- they + # group the last two (which are usually affines) separately + # from the first (which, with log-scaling can be non-affine). + self.transData = self.transScale + (self.transLimits + self.transAxes) + + self._xaxis_transform = mtransforms.blended_transform_factory( + self.transData, self.transAxes) + self._yaxis_transform = mtransforms.blended_transform_factory( + self.transAxes, self.transData) + + def get_xaxis_transform(self, which='grid'): + """ + Get the transformation used for drawing x-axis labels, ticks + and gridlines. The x-direction is in data coordinates and the + y-direction is in axis coordinates. + + .. note:: + + This transformation is primarily used by the + `~matplotlib.axis.Axis` class, and is meant to be + overridden by new kinds of projections that may need to + place axis elements in different locations. + + Parameters + ---------- + which : {'grid', 'tick1', 'tick2'} + """ + if which == 'grid': + return self._xaxis_transform + elif which == 'tick1': + # for cartesian projection, this is bottom spine + return self.spines.bottom.get_spine_transform() + elif which == 'tick2': + # for cartesian projection, this is top spine + return self.spines.top.get_spine_transform() + else: + raise ValueError(f'unknown value for which: {which!r}') + + def get_xaxis_text1_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing x-axis labels, which will add + *pad_points* of padding (in points) between the axis and the label. + The x-direction is in data coordinates and the y-direction is in + axis coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["xtick.alignment"] + return (self.get_xaxis_transform(which='tick1') + + mtransforms.ScaledTranslation( + 0, -1 * pad_points / 72, + self.get_figure(root=False).dpi_scale_trans), + "top", labels_align) + + def get_xaxis_text2_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing secondary x-axis labels, which will + add *pad_points* of padding (in points) between the axis and the + label. The x-direction is in data coordinates and the y-direction + is in axis coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["xtick.alignment"] + return (self.get_xaxis_transform(which='tick2') + + mtransforms.ScaledTranslation( + 0, pad_points / 72, + self.get_figure(root=False).dpi_scale_trans), + "bottom", labels_align) + + def get_yaxis_transform(self, which='grid'): + """ + Get the transformation used for drawing y-axis labels, ticks + and gridlines. The x-direction is in axis coordinates and the + y-direction is in data coordinates. + + .. note:: + + This transformation is primarily used by the + `~matplotlib.axis.Axis` class, and is meant to be + overridden by new kinds of projections that may need to + place axis elements in different locations. + + Parameters + ---------- + which : {'grid', 'tick1', 'tick2'} + """ + if which == 'grid': + return self._yaxis_transform + elif which == 'tick1': + # for cartesian projection, this is bottom spine + return self.spines.left.get_spine_transform() + elif which == 'tick2': + # for cartesian projection, this is top spine + return self.spines.right.get_spine_transform() + else: + raise ValueError(f'unknown value for which: {which!r}') + + def get_yaxis_text1_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing y-axis labels, which will add + *pad_points* of padding (in points) between the axis and the label. + The x-direction is in axis coordinates and the y-direction is in + data coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["ytick.alignment"] + return (self.get_yaxis_transform(which='tick1') + + mtransforms.ScaledTranslation( + -1 * pad_points / 72, 0, + self.get_figure(root=False).dpi_scale_trans), + labels_align, "right") + + def get_yaxis_text2_transform(self, pad_points): + """ + Returns + ------- + transform : Transform + The transform used for drawing secondart y-axis labels, which will + add *pad_points* of padding (in points) between the axis and the + label. The x-direction is in axis coordinates and the y-direction + is in data coordinates + valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} + The text vertical alignment. + halign : {'center', 'left', 'right'} + The text horizontal alignment. + + Notes + ----- + This transformation is primarily used by the `~matplotlib.axis.Axis` + class, and is meant to be overridden by new kinds of projections that + may need to place axis elements in different locations. + """ + labels_align = mpl.rcParams["ytick.alignment"] + return (self.get_yaxis_transform(which='tick2') + + mtransforms.ScaledTranslation( + pad_points / 72, 0, + self.get_figure(root=False).dpi_scale_trans), + labels_align, "left") + + def _update_transScale(self): + self.transScale.set( + mtransforms.blended_transform_factory( + self.xaxis.get_transform(), self.yaxis.get_transform())) + + def get_position(self, original=False): + """ + Return the position of the Axes within the figure as a `.Bbox`. + + Parameters + ---------- + original : bool + If ``True``, return the original position. Otherwise, return the + active position. For an explanation of the positions see + `.set_position`. + + Returns + ------- + `.Bbox` + + """ + if original: + return self._originalPosition.frozen() + else: + locator = self.get_axes_locator() + if not locator: + self.apply_aspect() + return self._position.frozen() + + def set_position(self, pos, which='both'): + """ + Set the Axes position. + + Axes have two position attributes. The 'original' position is the + position allocated for the Axes. The 'active' position is the + position the Axes is actually drawn at. These positions are usually + the same unless a fixed aspect is set to the Axes. See + `.Axes.set_aspect` for details. + + Parameters + ---------- + pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox` + The new position of the Axes in `.Figure` coordinates. + + which : {'both', 'active', 'original'}, default: 'both' + Determines which position variables to change. + + See Also + -------- + matplotlib.transforms.Bbox.from_bounds + matplotlib.transforms.Bbox.from_extents + """ + self._set_position(pos, which=which) + # because this is being called externally to the library we + # don't let it be in the layout. + self.set_in_layout(False) + + def _set_position(self, pos, which='both'): + """ + Private version of set_position. + + Call this internally to get the same functionality of `set_position`, + but not to take the axis out of the constrained_layout hierarchy. + """ + if not isinstance(pos, mtransforms.BboxBase): + pos = mtransforms.Bbox.from_bounds(*pos) + for ax in self._twinned_axes.get_siblings(self): + if which in ('both', 'active'): + ax._position.set(pos) + if which in ('both', 'original'): + ax._originalPosition.set(pos) + self.stale = True + + def reset_position(self): + """ + Reset the active position to the original position. + + This undoes changes to the active position (as defined in + `.set_position`) which may have been performed to satisfy fixed-aspect + constraints. + """ + for ax in self._twinned_axes.get_siblings(self): + pos = ax.get_position(original=True) + ax.set_position(pos, which='active') + + def set_axes_locator(self, locator): + """ + Set the Axes locator. + + Parameters + ---------- + locator : Callable[[Axes, Renderer], Bbox] + """ + self._axes_locator = locator + self.stale = True + + def get_axes_locator(self): + """ + Return the axes_locator. + """ + return self._axes_locator + + def _set_artist_props(self, a): + """Set the boilerplate props for artists added to Axes.""" + a.set_figure(self.get_figure(root=False)) + if not a.is_transform_set(): + a.set_transform(self.transData) + + a.axes = self + if a.get_mouseover(): + self._mouseover_set.add(a) + + def _gen_axes_patch(self): + """ + Returns + ------- + Patch + The patch used to draw the background of the Axes. It is also used + as the clipping path for any data elements on the Axes. + + In the standard Axes, this is a rectangle, but in other projections + it may not be. + + Notes + ----- + Intended to be overridden by new projection types. + """ + return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0) + + def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'): + """ + Returns + ------- + dict + Mapping of spine names to `.Line2D` or `.Patch` instances that are + used to draw Axes spines. + + In the standard Axes, spines are single line segments, but in other + projections they may not be. + + Notes + ----- + Intended to be overridden by new projection types. + """ + return {side: mspines.Spine.linear_spine(self, side) + for side in ['left', 'right', 'bottom', 'top']} + + def sharex(self, other): + """ + Share the x-axis with *other*. + + This is equivalent to passing ``sharex=other`` when constructing the + Axes, and cannot be used if the x-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(_AxesBase, other=other) + if self._sharex is not None and other is not self._sharex: + raise ValueError("x-axis is already shared") + self._shared_axes["x"].join(self, other) + self._sharex = other + self.xaxis.major = other.xaxis.major # Ticker instances holding + self.xaxis.minor = other.xaxis.minor # locator and formatter. + x0, x1 = other.get_xlim() + self.set_xlim(x0, x1, emit=False, auto=other.get_autoscalex_on()) + self.xaxis._scale = other.xaxis._scale + + def sharey(self, other): + """ + Share the y-axis with *other*. + + This is equivalent to passing ``sharey=other`` when constructing the + Axes, and cannot be used if the y-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(_AxesBase, other=other) + if self._sharey is not None and other is not self._sharey: + raise ValueError("y-axis is already shared") + self._shared_axes["y"].join(self, other) + self._sharey = other + self.yaxis.major = other.yaxis.major # Ticker instances holding + self.yaxis.minor = other.yaxis.minor # locator and formatter. + y0, y1 = other.get_ylim() + self.set_ylim(y0, y1, emit=False, auto=other.get_autoscaley_on()) + self.yaxis._scale = other.yaxis._scale + + def __clear(self): + """Clear the Axes.""" + # The actual implementation of clear() as long as clear() has to be + # an adapter delegating to the correct implementation. + # The implementation can move back into clear() when the + # deprecation on cla() subclassing expires. + + # stash the current visibility state + if hasattr(self, 'patch'): + patch_visible = self.patch.get_visible() + else: + patch_visible = True + + xaxis_visible = self.xaxis.get_visible() + yaxis_visible = self.yaxis.get_visible() + + for axis in self._axis_map.values(): + axis.clear() # Also resets the scale to linear. + for spine in self.spines.values(): + spine._clear() # Use _clear to not clear Axis again + + self.ignore_existing_data_limits = True + self.callbacks = cbook.CallbackRegistry( + signals=["xlim_changed", "ylim_changed", "zlim_changed"]) + + # update the minor locator for x and y axis based on rcParams + if mpl.rcParams['xtick.minor.visible']: + self.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + if mpl.rcParams['ytick.minor.visible']: + self.yaxis.set_minor_locator(mticker.AutoMinorLocator()) + + self._xmargin = mpl.rcParams['axes.xmargin'] + self._ymargin = mpl.rcParams['axes.ymargin'] + self._tight = None + self._use_sticky_edges = True + + self._get_lines = _process_plot_var_args() + self._get_patches_for_fill = _process_plot_var_args('Polygon') + + self._gridOn = mpl.rcParams['axes.grid'] + # Swap children to minimize time we spend in an invalid state + old_children, self._children = self._children, [] + for chld in old_children: + chld._remove_method = None + chld._parent_figure = None + chld.axes = None + # Use list.clear to break the `artist._remove_method` reference cycle + old_children.clear() + self._mouseover_set = _OrderedSet() + self.child_axes = [] + self._current_image = None # strictly for pyplot via _sci, _gci + self._projection_init = None # strictly for pyplot.subplot + self.legend_ = None + self.containers = [] + + self.grid(False) # Disable grid on init to use rcParameter + self.grid(self._gridOn, which=mpl.rcParams['axes.grid.which'], + axis=mpl.rcParams['axes.grid.axis']) + props = font_manager.FontProperties( + size=mpl.rcParams['axes.titlesize'], + weight=mpl.rcParams['axes.titleweight']) + + y = mpl.rcParams['axes.titley'] + if y is None: + y = 1.0 + self._autotitlepos = True + else: + self._autotitlepos = False + + self.title = mtext.Text( + x=0.5, y=y, text='', + fontproperties=props, + verticalalignment='baseline', + horizontalalignment='center', + ) + self._left_title = mtext.Text( + x=0.0, y=y, text='', + fontproperties=props.copy(), + verticalalignment='baseline', + horizontalalignment='left', ) + self._right_title = mtext.Text( + x=1.0, y=y, text='', + fontproperties=props.copy(), + verticalalignment='baseline', + horizontalalignment='right', + ) + title_offset_points = mpl.rcParams['axes.titlepad'] + # refactor this out so it can be called in ax.set_title if + # pad argument used... + self._set_title_offset_trans(title_offset_points) + + for _title in (self.title, self._left_title, self._right_title): + self._set_artist_props(_title) + + # The patch draws the background of the Axes. We want this to be below + # the other artists. We use the frame to draw the edges so we are + # setting the edgecolor to None. + self.patch = self._gen_axes_patch() + self.patch.set_figure(self.get_figure(root=False)) + self.patch.set_facecolor(self._facecolor) + self.patch.set_edgecolor('none') + self.patch.set_linewidth(0) + self.patch.set_transform(self.transAxes) + + self.set_axis_on() + + self.xaxis.set_clip_path(self.patch) + self.yaxis.set_clip_path(self.patch) + + if self._sharex is not None: + self.xaxis.set_visible(xaxis_visible) + self.patch.set_visible(patch_visible) + if self._sharey is not None: + self.yaxis.set_visible(yaxis_visible) + self.patch.set_visible(patch_visible) + + # This comes last, as the call to _set_lim may trigger an autoscale (in + # case of shared axes), requiring children to be already set up. + for name, axis in self._axis_map.items(): + share = getattr(self, f"_share{name}") + if share is not None: + getattr(self, f"share{name}")(share) + else: + # Although the scale was set to linear as part of clear, + # polar requires that _set_scale is called again + if self.name == "polar": + axis._set_scale("linear") + axis._set_lim(0, 1, auto=True) + self._update_transScale() + + self.stale = True + + def clear(self): + """Clear the Axes.""" + # Act as an alias, or as the superclass implementation depending on the + # subclass implementation. + if self._subclass_uses_cla: + self.cla() + else: + self.__clear() + + def cla(self): + """Clear the Axes.""" + # Act as an alias, or as the superclass implementation depending on the + # subclass implementation. + if self._subclass_uses_cla: + self.__clear() + else: + self.clear() + + class ArtistList(Sequence): + """ + A sublist of Axes children based on their type. + + The type-specific children sublists were made immutable in Matplotlib + 3.7. In the future these artist lists may be replaced by tuples. Use + as if this is a tuple already. + """ + def __init__(self, axes, prop_name, + valid_types=None, invalid_types=None): + """ + Parameters + ---------- + axes : `~matplotlib.axes.Axes` + The Axes from which this sublist will pull the children + Artists. + prop_name : str + The property name used to access this sublist from the Axes; + used to generate deprecation warnings. + valid_types : list of type, optional + A list of types that determine which children will be returned + by this sublist. If specified, then the Artists in the sublist + must be instances of any of these types. If unspecified, then + any type of Artist is valid (unless limited by + *invalid_types*.) + invalid_types : tuple, optional + A list of types that determine which children will *not* be + returned by this sublist. If specified, then Artists in the + sublist will never be an instance of these types. Otherwise, no + types will be excluded. + """ + self._axes = axes + self._prop_name = prop_name + self._type_check = lambda artist: ( + (not valid_types or isinstance(artist, valid_types)) and + (not invalid_types or not isinstance(artist, invalid_types)) + ) + + def __repr__(self): + return f'' + + def __len__(self): + return sum(self._type_check(artist) + for artist in self._axes._children) + + def __iter__(self): + for artist in list(self._axes._children): + if self._type_check(artist): + yield artist + + def __getitem__(self, key): + return [artist + for artist in self._axes._children + if self._type_check(artist)][key] + + def __add__(self, other): + if isinstance(other, (list, _AxesBase.ArtistList)): + return [*self, *other] + if isinstance(other, (tuple, _AxesBase.ArtistList)): + return (*self, *other) + return NotImplemented + + def __radd__(self, other): + if isinstance(other, list): + return other + list(self) + if isinstance(other, tuple): + return other + tuple(self) + return NotImplemented + + @property + def artists(self): + return self.ArtistList(self, 'artists', invalid_types=( + mcoll.Collection, mimage.AxesImage, mlines.Line2D, mpatches.Patch, + mtable.Table, mtext.Text)) + + @property + def collections(self): + return self.ArtistList(self, 'collections', + valid_types=mcoll.Collection) + + @property + def images(self): + return self.ArtistList(self, 'images', valid_types=mimage.AxesImage) + + @property + def lines(self): + return self.ArtistList(self, 'lines', valid_types=mlines.Line2D) + + @property + def patches(self): + return self.ArtistList(self, 'patches', valid_types=mpatches.Patch) + + @property + def tables(self): + return self.ArtistList(self, 'tables', valid_types=mtable.Table) + + @property + def texts(self): + return self.ArtistList(self, 'texts', valid_types=mtext.Text) + + def get_facecolor(self): + """Get the facecolor of the Axes.""" + return self.patch.get_facecolor() + + def set_facecolor(self, color): + """ + Set the facecolor of the Axes. + + Parameters + ---------- + color : :mpltype:`color` + """ + self._facecolor = color + self.stale = True + return self.patch.set_facecolor(color) + + def _set_title_offset_trans(self, title_offset_points): + """ + Set the offset for the title either from :rc:`axes.titlepad` + or from set_title kwarg ``pad``. + """ + self.titleOffsetTrans = mtransforms.ScaledTranslation( + 0.0, title_offset_points / 72, + self.get_figure(root=False).dpi_scale_trans) + for _title in (self.title, self._left_title, self._right_title): + _title.set_transform(self.transAxes + self.titleOffsetTrans) + _title.set_clip_box(None) + + def set_prop_cycle(self, *args, **kwargs): + """ + Set the property cycle of the Axes. + + The property cycle controls the style properties such as color, + marker and linestyle of future plot commands. The style properties + of data already added to the Axes are not modified. + + Call signatures:: + + set_prop_cycle(cycler) + set_prop_cycle(label=values, label2=values2, ...) + set_prop_cycle(label, values) + + Form 1 sets given `~cycler.Cycler` object. + + Form 2 creates a `~cycler.Cycler` which cycles over one or more + properties simultaneously and set it as the property cycle of the + Axes. If multiple properties are given, their value lists must have + the same length. This is just a shortcut for explicitly creating a + cycler and passing it to the function, i.e. it's short for + ``set_prop_cycle(cycler(label=values, label2=values2, ...))``. + + Form 3 creates a `~cycler.Cycler` for a single property and set it + as the property cycle of the Axes. This form exists for compatibility + with the original `cycler.cycler` interface. Its use is discouraged + in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``. + + Parameters + ---------- + cycler : `~cycler.Cycler` or ``None`` + Set the given Cycler. *None* resets to the cycle defined by the + current style. + + .. ACCEPTS: `~cycler.Cycler` + + label : str + The property key. Must be a valid `.Artist` property. + For example, 'color' or 'linestyle'. Aliases are allowed, + such as 'c' for 'color' and 'lw' for 'linewidth'. + + values : iterable + Finite-length iterable of the property values. These values + are validated and will raise a ValueError if invalid. + + See Also + -------- + matplotlib.rcsetup.cycler + Convenience function for creating validated cyclers for properties. + cycler.cycler + The original function for creating unvalidated cyclers. + + Examples + -------- + Setting the property cycle for a single property: + + >>> ax.set_prop_cycle(color=['red', 'green', 'blue']) + + Setting the property cycle for simultaneously cycling over multiple + properties (e.g. red circle, green plus, blue cross): + + >>> ax.set_prop_cycle(color=['red', 'green', 'blue'], + ... marker=['o', '+', 'x']) + + """ + if args and kwargs: + raise TypeError("Cannot supply both positional and keyword " + "arguments to this method.") + # Can't do `args == (None,)` as that crashes cycler. + if len(args) == 1 and args[0] is None: + prop_cycle = None + else: + prop_cycle = cycler(*args, **kwargs) + self._get_lines.set_prop_cycle(prop_cycle) + self._get_patches_for_fill.set_prop_cycle(prop_cycle) + + def get_aspect(self): + """ + Return the aspect ratio of the Axes scaling. + + This is either "auto" or a float giving the ratio of y/x-scale. + """ + return self._aspect + + def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): + """ + Set the aspect ratio of the Axes scaling, i.e. y/x-scale. + + Parameters + ---------- + aspect : {'auto', 'equal'} or float + Possible values: + + - 'auto': fill the position rectangle with data. + - 'equal': same as ``aspect=1``, i.e. same scaling for x and y. + - *float*: The displayed size of 1 unit in y-data coordinates will + be *aspect* times the displayed size of 1 unit in x-data + coordinates; e.g. for ``aspect=2`` a square in data coordinates + will be rendered with a height of twice its width. + + adjustable : None or {'box', 'datalim'}, optional + If not ``None``, this defines which parameter will be adjusted to + meet the required aspect. See `.set_adjustable` for further + details. + + anchor : None or str or (float, float), optional + If not ``None``, this defines where the Axes will be drawn if there + is extra space due to aspect constraints. The most common way + to specify the anchor are abbreviations of cardinal directions: + + ===== ===================== + value description + ===== ===================== + 'C' centered + 'SW' lower left corner + 'S' middle of bottom edge + 'SE' lower right corner + etc. + ===== ===================== + + See `~.Axes.set_anchor` for further details. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_anchor + Set the position in case of extra space. + """ + if cbook._str_equal(aspect, 'equal'): + aspect = 1 + if not cbook._str_equal(aspect, 'auto'): + aspect = float(aspect) # raise ValueError if necessary + if aspect <= 0 or not np.isfinite(aspect): + raise ValueError("aspect must be finite and positive ") + + if share: + axes = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axes = [self] + + for ax in axes: + ax._aspect = aspect + + if adjustable is None: + adjustable = self._adjustable + self.set_adjustable(adjustable, share=share) # Handle sharing. + + if anchor is not None: + self.set_anchor(anchor, share=share) + self.stale = True + + def get_adjustable(self): + """ + Return whether the Axes will adjust its physical dimension ('box') or + its data limits ('datalim') to achieve the desired aspect ratio. + + See Also + -------- + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_aspect + For a description of aspect handling. + """ + return self._adjustable + + def set_adjustable(self, adjustable, share=False): + """ + Set how the Axes adjusts to achieve the required aspect ratio. + + Parameters + ---------- + adjustable : {'box', 'datalim'} + If 'box', change the physical dimensions of the Axes. + If 'datalim', change the ``x`` or ``y`` data limits. This + may ignore explicitly defined axis limits. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + For a description of aspect handling. + + Notes + ----- + Shared Axes (of which twinned Axes are a special case) + impose restrictions on how aspect ratios can be imposed. + For twinned Axes, use 'datalim'. For Axes that share both + x and y, use 'box'. Otherwise, either 'datalim' or 'box' + may be used. These limitations are partly a requirement + to avoid over-specification, and partly a result of the + particular implementation we are currently using, in + which the adjustments for aspect ratios are done sequentially + and independently on each Axes as it is drawn. + """ + _api.check_in_list(["box", "datalim"], adjustable=adjustable) + if share: + axs = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axs = [self] + if (adjustable == "datalim" + and any(getattr(ax.get_data_ratio, "__func__", None) + != _AxesBase.get_data_ratio + for ax in axs)): + # Limits adjustment by apply_aspect assumes that the axes' aspect + # ratio can be computed from the data limits and scales. + raise ValueError("Cannot set Axes adjustable to 'datalim' for " + "Axes which override 'get_data_ratio'") + for ax in axs: + ax._adjustable = adjustable + self.stale = True + + def get_box_aspect(self): + """ + Return the Axes box aspect, i.e. the ratio of height to width. + + The box aspect is ``None`` (i.e. chosen depending on the available + figure space) unless explicitly specified. + + See Also + -------- + matplotlib.axes.Axes.set_box_aspect + for a description of box aspect. + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + return self._box_aspect + + def set_box_aspect(self, aspect=None): + """ + Set the Axes box aspect, i.e. the ratio of height to width. + + This defines the aspect of the Axes in figure space and is not to be + confused with the data aspect (see `~.Axes.set_aspect`). + + Parameters + ---------- + aspect : float or None + Changes the physical dimensions of the Axes, such that the ratio + of the Axes height to the Axes width in physical units is equal to + *aspect*. Defining a box aspect will change the *adjustable* + property to 'datalim' (see `~.Axes.set_adjustable`). + + *None* will disable a fixed box aspect so that height and width + of the Axes are chosen independently. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + axs = {*self._twinned_axes.get_siblings(self), + *self._twinned_axes.get_siblings(self)} + + if aspect is not None: + aspect = float(aspect) + # when box_aspect is set to other than ´None`, + # adjustable must be "datalim" + for ax in axs: + ax.set_adjustable("datalim") + + for ax in axs: + ax._box_aspect = aspect + ax.stale = True + + def get_anchor(self): + """ + Get the anchor location. + + See Also + -------- + matplotlib.axes.Axes.set_anchor + for a description of the anchor. + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + return self._anchor + + def set_anchor(self, anchor, share=False): + """ + Define the anchor location. + + The actual drawing area (active position) of the Axes may be smaller + than the Bbox (original position) when a fixed aspect is required. The + anchor defines where the drawing area will be located within the + available space. + + Parameters + ---------- + anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} + Either an (*x*, *y*) pair of relative coordinates (0 is left or + bottom, 1 is right or top), 'C' (center), or a cardinal direction + ('SW', southwest, is bottom left, etc.). str inputs are shorthands + for (*x*, *y*) coordinates, as shown in the following diagram:: + + ┌─────────────────┬─────────────────┬─────────────────┐ + │ 'NW' (0.0, 1.0) │ 'N' (0.5, 1.0) │ 'NE' (1.0, 1.0) │ + ├─────────────────┼─────────────────┼─────────────────┤ + │ 'W' (0.0, 0.5) │ 'C' (0.5, 0.5) │ 'E' (1.0, 0.5) │ + ├─────────────────┼─────────────────┼─────────────────┤ + │ 'SW' (0.0, 0.0) │ 'S' (0.5, 0.0) │ 'SE' (1.0, 0.0) │ + └─────────────────┴─────────────────┴─────────────────┘ + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + for a description of aspect handling. + """ + if not (anchor in mtransforms.Bbox.coefs or len(anchor) == 2): + raise ValueError('argument must be among %s' % + ', '.join(mtransforms.Bbox.coefs)) + if share: + axes = {sibling for name in self._axis_names + for sibling in self._shared_axes[name].get_siblings(self)} + else: + axes = [self] + for ax in axes: + ax._anchor = anchor + + self.stale = True + + def get_data_ratio(self): + """ + Return the aspect ratio of the scaled data. + + Notes + ----- + This method is intended to be overridden by new projection types. + """ + txmin, txmax = self.xaxis.get_transform().transform(self.get_xbound()) + tymin, tymax = self.yaxis.get_transform().transform(self.get_ybound()) + xsize = max(abs(txmax - txmin), 1e-30) + ysize = max(abs(tymax - tymin), 1e-30) + return ysize / xsize + + def apply_aspect(self, position=None): + """ + Adjust the Axes for a specified data aspect ratio. + + Depending on `.get_adjustable` this will modify either the + Axes box (position) or the view limits. In the former case, + `~matplotlib.axes.Axes.get_anchor` will affect the position. + + Parameters + ---------- + position : None or .Bbox + + .. note:: + This parameter exists for historic reasons and is considered + internal. End users should not use it. + + If not ``None``, this defines the position of the + Axes within the figure as a Bbox. See `~.Axes.get_position` + for further details. + + Notes + ----- + This is called automatically when each Axes is drawn. You may need + to call it yourself if you need to update the Axes position and/or + view limits before the Figure is drawn. + + An alternative with a broader scope is `.Figure.draw_without_rendering`, + which updates all stale components of a figure, not only the positioning / + view limits of a single Axes. + + See Also + -------- + matplotlib.axes.Axes.set_aspect + For a description of aspect ratio handling. + matplotlib.axes.Axes.set_adjustable + Set how the Axes adjusts to achieve the required aspect ratio. + matplotlib.axes.Axes.set_anchor + Set the position in case of extra space. + matplotlib.figure.Figure.draw_without_rendering + Update all stale components of a figure. + + Examples + -------- + A typical usage example would be the following. `~.Axes.imshow` sets the + aspect to 1, but adapting the Axes position and extent to reflect this is + deferred until rendering for performance reasons. If you want to know the + Axes size before, you need to call `.apply_aspect` to get the correct + values. + + >>> fig, ax = plt.subplots() + >>> ax.imshow(np.zeros((3, 3))) + >>> ax.bbox.width, ax.bbox.height + (496.0, 369.59999999999997) + >>> ax.apply_aspect() + >>> ax.bbox.width, ax.bbox.height + (369.59999999999997, 369.59999999999997) + """ + if position is None: + position = self.get_position(original=True) + + aspect = self.get_aspect() + + if aspect == 'auto' and self._box_aspect is None: + self._set_position(position, which='active') + return + + trans = self.get_figure(root=False).transSubfigure + bb = mtransforms.Bbox.unit().transformed(trans) + # this is the physical aspect of the panel (or figure): + fig_aspect = bb.height / bb.width + + if self._adjustable == 'box': + if self in self._twinned_axes: + raise RuntimeError("Adjustable 'box' is not allowed in a " + "twinned Axes; use 'datalim' instead") + box_aspect = aspect * self.get_data_ratio() + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + return + + # The following is only seen if self._adjustable == 'datalim' + if self._box_aspect is not None: + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(self._box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + if aspect == "auto": + return + + # reset active to original in case it had been changed by prior use + # of 'box' + if self._box_aspect is None: + self._set_position(position, which='active') + else: + position = pb1.anchored(self.get_anchor(), pb) + + x_trf = self.xaxis.get_transform() + y_trf = self.yaxis.get_transform() + xmin, xmax = x_trf.transform(self.get_xbound()) + ymin, ymax = y_trf.transform(self.get_ybound()) + xsize = max(abs(xmax - xmin), 1e-30) + ysize = max(abs(ymax - ymin), 1e-30) + + box_aspect = fig_aspect * (position.height / position.width) + data_ratio = box_aspect / aspect + + y_expander = data_ratio * xsize / ysize - 1 + # If y_expander > 0, the dy/dx viewLim ratio needs to increase + if abs(y_expander) < 0.005: + return + + dL = self.dataLim + x0, x1 = x_trf.transform(dL.intervalx) + y0, y1 = y_trf.transform(dL.intervaly) + xr = 1.05 * (x1 - x0) + yr = 1.05 * (y1 - y0) + + xmarg = xsize - xr + ymarg = ysize - yr + Ysize = data_ratio * xsize + Xsize = ysize / data_ratio + Xmarg = Xsize - xr + Ymarg = Ysize - yr + # Setting these targets to, e.g., 0.05*xr does not seem to help. + xm = 0 + ym = 0 + + shared_x = self in self._shared_axes["x"] + shared_y = self in self._shared_axes["y"] + + if shared_x and shared_y: + raise RuntimeError("set_aspect(..., adjustable='datalim') or " + "axis('equal') are not allowed when both axes " + "are shared. Try set_aspect(..., " + "adjustable='box').") + + # If y is shared, then we are only allowed to change x, etc. + if shared_y: + adjust_y = False + else: + if xmarg > xm and ymarg > ym: + adjy = ((Ymarg > 0 and y_expander < 0) or + (Xmarg < 0 and y_expander > 0)) + else: + adjy = y_expander > 0 + adjust_y = shared_x or adjy # (Ymarg > xmarg) + + if adjust_y: + yc = 0.5 * (ymin + ymax) + y0 = yc - Ysize / 2.0 + y1 = yc + Ysize / 2.0 + if not self.get_autoscaley_on(): + _log.warning("Ignoring fixed y limits to fulfill fixed data aspect " + "with adjustable data limits.") + self.set_ybound(y_trf.inverted().transform([y0, y1])) + else: + xc = 0.5 * (xmin + xmax) + x0 = xc - Xsize / 2.0 + x1 = xc + Xsize / 2.0 + if not self.get_autoscalex_on(): + _log.warning("Ignoring fixed x limits to fulfill fixed data aspect " + "with adjustable data limits.") + self.set_xbound(x_trf.inverted().transform([x0, x1])) + + def axis(self, arg=None, /, *, emit=True, **kwargs): + """ + Convenience method to get or set some axis properties. + + Call signatures:: + + xmin, xmax, ymin, ymax = axis() + xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax]) + xmin, xmax, ymin, ymax = axis(option) + xmin, xmax, ymin, ymax = axis(**kwargs) + + Parameters + ---------- + xmin, xmax, ymin, ymax : float, optional + The axis limits to be set. This can also be achieved using :: + + ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax)) + + option : bool or str + If a bool, turns axis lines and labels on or off. If a string, + possible values are: + + ================ =========================================================== + Value Description + ================ =========================================================== + 'off' or `False` Hide all axis decorations, i.e. axis labels, spines, + tick marks, tick labels, and grid lines. + This is the same as `~.Axes.set_axis_off()`. + 'on' or `True` Do not hide all axis decorations, i.e. axis labels, spines, + tick marks, tick labels, and grid lines. + This is the same as `~.Axes.set_axis_on()`. + 'equal' Set equal scaling (i.e., make circles circular) by + changing the axis limits. This is the same as + ``ax.set_aspect('equal', adjustable='datalim')``. + Explicit data limits may not be respected in this case. + 'scaled' Set equal scaling (i.e., make circles circular) by + changing dimensions of the plot box. This is the same as + ``ax.set_aspect('equal', adjustable='box', anchor='C')``. + Additionally, further autoscaling will be disabled. + 'tight' Set limits just large enough to show all data, then + disable further autoscaling. + 'auto' Automatic scaling (fill plot box with data). + 'image' 'scaled' with axis limits equal to data limits. + 'square' Square plot; similar to 'scaled', but initially forcing + ``xmax-xmin == ymax-ymin``. + ================ =========================================================== + + emit : bool, default: True + Whether observers are notified of the axis limit change. + This option is passed on to `~.Axes.set_xlim` and + `~.Axes.set_ylim`. + + Returns + ------- + xmin, xmax, ymin, ymax : float + The axis limits. + + See Also + -------- + matplotlib.axes.Axes.set_xlim + matplotlib.axes.Axes.set_ylim + + Notes + ----- + For 3D Axes, this method additionally takes *zmin*, *zmax* as + parameters and likewise returns them. + """ + if isinstance(arg, (str, bool)): + if arg is True: + arg = 'on' + if arg is False: + arg = 'off' + arg = arg.lower() + if arg == 'on': + self.set_axis_on() + elif arg == 'off': + self.set_axis_off() + elif arg in [ + 'equal', 'tight', 'scaled', 'auto', 'image', 'square']: + self.set_autoscale_on(True) + self.set_aspect('auto') + self.autoscale_view(tight=False) + if arg == 'equal': + self.set_aspect('equal', adjustable='datalim') + elif arg == 'scaled': + self.set_aspect('equal', adjustable='box', anchor='C') + self.set_autoscale_on(False) # Req. by Mark Bakker + elif arg == 'tight': + self.autoscale_view(tight=True) + self.set_autoscale_on(False) + elif arg == 'image': + self.autoscale_view(tight=True) + self.set_autoscale_on(False) + self.set_aspect('equal', adjustable='box', anchor='C') + elif arg == 'square': + self.set_aspect('equal', adjustable='box', anchor='C') + self.set_autoscale_on(False) + xlim = self.get_xlim() + ylim = self.get_ylim() + edge_size = max(np.diff(xlim), np.diff(ylim))[0] + self.set_xlim([xlim[0], xlim[0] + edge_size], + emit=emit, auto=False) + self.set_ylim([ylim[0], ylim[0] + edge_size], + emit=emit, auto=False) + else: + raise ValueError(f"Unrecognized string {arg!r} to axis; " + "try 'on' or 'off'") + else: + if arg is not None: + if len(arg) != 2*len(self._axis_names): + raise TypeError( + "The first argument to axis() must be an iterable of the form " + "[{}]".format(", ".join( + f"{name}min, {name}max" for name in self._axis_names))) + limits = { + name: arg[2*i:2*(i+1)] + for i, name in enumerate(self._axis_names) + } + else: + limits = {} + for name in self._axis_names: + ax_min = kwargs.pop(f'{name}min', None) + ax_max = kwargs.pop(f'{name}max', None) + limits[name] = (ax_min, ax_max) + for name, (ax_min, ax_max) in limits.items(): + ax_auto = (None # Keep autoscale state as is. + if ax_min is None and ax_max is None + else False) # Turn off autoscale. + set_ax_lim = getattr(self, f'set_{name}lim') + set_ax_lim(ax_min, ax_max, emit=emit, auto=ax_auto) + if kwargs: + raise _api.kwarg_error("axis", kwargs) + lims = () + for name in self._axis_names: + get_ax_lim = getattr(self, f'get_{name}lim') + lims += get_ax_lim() + return lims + + def get_legend(self): + """Return the `.Legend` instance, or None if no legend is defined.""" + return self.legend_ + + def get_images(self): + r"""Return a list of `.AxesImage`\s contained by the Axes.""" + return cbook.silent_list('AxesImage', self.images) + + def get_lines(self): + """Return a list of lines contained by the Axes.""" + return cbook.silent_list('Line2D', self.lines) + + def get_xaxis(self): + """ + [*Discouraged*] Return the XAxis instance. + + .. admonition:: Discouraged + + The use of this function is discouraged. You should instead + directly access the attribute `~.Axes.xaxis`. + """ + return self.xaxis + + def get_yaxis(self): + """ + [*Discouraged*] Return the YAxis instance. + + .. admonition:: Discouraged + + The use of this function is discouraged. You should instead + directly access the attribute `~.Axes.yaxis`. + """ + return self.yaxis + + get_xgridlines = _axis_method_wrapper("xaxis", "get_gridlines") + get_xticklines = _axis_method_wrapper("xaxis", "get_ticklines") + get_ygridlines = _axis_method_wrapper("yaxis", "get_gridlines") + get_yticklines = _axis_method_wrapper("yaxis", "get_ticklines") + + # Adding and tracking artists + + def _sci(self, im): + """ + Set the current image. + + This image will be the target of colormap functions like + ``pyplot.viridis``, and other functions such as `~.pyplot.clim`. The + current image is an attribute of the current Axes. + """ + _api.check_isinstance((mcoll.Collection, mimage.AxesImage), im=im) + if im not in self._children: + raise ValueError("Argument must be an image or collection in this Axes") + self._current_image = im + + def _gci(self): + """Helper for `~matplotlib.pyplot.gci`; do not use elsewhere.""" + return self._current_image + + def has_data(self): + """ + Return whether any artists have been added to the Axes. + + This should not be used to determine whether the *dataLim* + need to be updated, and may not actually be useful for + anything. + """ + return any(isinstance(a, (mcoll.Collection, mimage.AxesImage, + mlines.Line2D, mpatches.Patch)) + for a in self._children) + + def add_artist(self, a): + """ + Add an `.Artist` to the Axes; return the artist. + + Use `add_artist` only for artists for which there is no dedicated + "add" method; and if necessary, use a method such as `update_datalim` + to manually update the `~.Axes.dataLim` if the artist is to be included + in autoscaling. + + If no ``transform`` has been specified when creating the artist (e.g. + ``artist.get_transform() == None``) then the transform is set to + ``ax.transData``. + """ + a.axes = self + self._children.append(a) + a._remove_method = self._children.remove + self._set_artist_props(a) + if a.get_clip_path() is None: + a.set_clip_path(self.patch) + self.stale = True + return a + + def add_child_axes(self, ax): + """ + Add an `.Axes` to the Axes' children; return the child Axes. + + This is the lowlevel version. See `.axes.Axes.inset_axes`. + """ + + # normally Axes have themselves as the Axes, but these need to have + # their parent... + # Need to bypass the getter... + ax._axes = self + ax.stale_callback = martist._stale_axes_callback + + self.child_axes.append(ax) + ax._remove_method = functools.partial( + self.get_figure(root=False)._remove_axes, owners=[self.child_axes]) + self.stale = True + return ax + + def add_collection(self, collection, autolim=True): + """ + Add a `.Collection` to the Axes; return the collection. + """ + _api.check_isinstance(mcoll.Collection, collection=collection) + if not collection.get_label(): + collection.set_label(f'_child{len(self._children)}') + self._children.append(collection) + collection._remove_method = self._children.remove + self._set_artist_props(collection) + + if collection.get_clip_path() is None: + collection.set_clip_path(self.patch) + + if autolim: + # Make sure viewLim is not stale (mostly to match + # pre-lazy-autoscale behavior, which is not really better). + self._unstale_viewLim() + datalim = collection.get_datalim(self.transData) + points = datalim.get_points() + if not np.isinf(datalim.minpos).all(): + # By definition, if minpos (minimum positive value) is set + # (i.e., non-inf), then min(points) <= minpos <= max(points), + # and minpos would be superfluous. However, we add minpos to + # the call so that self.dataLim will update its own minpos. + # This ensures that log scales see the correct minimum. + points = np.concatenate([points, [datalim.minpos]]) + # only update the dataLim for x/y if the collection uses transData + # in this direction. + x_is_data, y_is_data = (collection.get_transform() + .contains_branch_seperately(self.transData)) + ox_is_data, oy_is_data = (collection.get_offset_transform() + .contains_branch_seperately(self.transData)) + self.update_datalim( + points, + updatex=x_is_data or ox_is_data, + updatey=y_is_data or oy_is_data, + ) + + self.stale = True + return collection + + def add_image(self, image): + """ + Add an `.AxesImage` to the Axes; return the image. + """ + _api.check_isinstance(mimage.AxesImage, image=image) + self._set_artist_props(image) + if not image.get_label(): + image.set_label(f'_child{len(self._children)}') + self._children.append(image) + image._remove_method = self._children.remove + self.stale = True + return image + + def _update_image_limits(self, image): + xmin, xmax, ymin, ymax = image.get_extent() + self.axes.update_datalim(((xmin, ymin), (xmax, ymax))) + + def add_line(self, line): + """ + Add a `.Line2D` to the Axes; return the line. + """ + _api.check_isinstance(mlines.Line2D, line=line) + self._set_artist_props(line) + if line.get_clip_path() is None: + line.set_clip_path(self.patch) + + self._update_line_limits(line) + if not line.get_label(): + line.set_label(f'_child{len(self._children)}') + self._children.append(line) + line._remove_method = self._children.remove + self.stale = True + return line + + def _add_text(self, txt): + """ + Add a `.Text` to the Axes; return the text. + """ + _api.check_isinstance(mtext.Text, txt=txt) + self._set_artist_props(txt) + self._children.append(txt) + txt._remove_method = self._children.remove + self.stale = True + return txt + + def _update_line_limits(self, line): + """ + Figures out the data limit of the given line, updating `.Axes.dataLim`. + """ + path = line.get_path() + if path.vertices.size == 0: + return + + line_trf = line.get_transform() + + if line_trf == self.transData: + data_path = path + elif any(line_trf.contains_branch_seperately(self.transData)): + # Compute the transform from line coordinates to data coordinates. + trf_to_data = line_trf - self.transData + # If transData is affine we can use the cached non-affine component + # of line's path (since the non-affine part of line_trf is + # entirely encapsulated in trf_to_data). + if self.transData.is_affine: + line_trans_path = line._get_transformed_path() + na_path, _ = line_trans_path.get_transformed_path_and_affine() + data_path = trf_to_data.transform_path_affine(na_path) + else: + data_path = trf_to_data.transform_path(path) + else: + # For backwards compatibility we update the dataLim with the + # coordinate range of the given path, even though the coordinate + # systems are completely different. This may occur in situations + # such as when ax.transAxes is passed through for absolute + # positioning. + data_path = path + + if not data_path.vertices.size: + return + + updatex, updatey = line_trf.contains_branch_seperately(self.transData) + if self.name != "rectilinear": + # This block is mostly intended to handle axvline in polar plots, + # for which updatey would otherwise be True. + if updatex and line_trf == self.get_yaxis_transform(): + updatex = False + if updatey and line_trf == self.get_xaxis_transform(): + updatey = False + self.dataLim.update_from_path(data_path, + self.ignore_existing_data_limits, + updatex=updatex, updatey=updatey) + self.ignore_existing_data_limits = False + + def add_patch(self, p): + """ + Add a `.Patch` to the Axes; return the patch. + """ + _api.check_isinstance(mpatches.Patch, p=p) + self._set_artist_props(p) + if p.get_clip_path() is None: + p.set_clip_path(self.patch) + self._update_patch_limits(p) + self._children.append(p) + p._remove_method = self._children.remove + return p + + def _update_patch_limits(self, patch): + """Update the data limits for the given patch.""" + # hist can add zero height Rectangles, which is useful to keep + # the bins, counts and patches lined up, but it throws off log + # scaling. We'll ignore rects with zero height or width in + # the auto-scaling + + # cannot check for '==0' since unitized data may not compare to zero + # issue #2150 - we update the limits if patch has non zero width + # or height. + if (isinstance(patch, mpatches.Rectangle) and + ((not patch.get_width()) and (not patch.get_height()))): + return + p = patch.get_path() + # Get all vertices on the path + # Loop through each segment to get extrema for Bezier curve sections + vertices = [] + for curve, code in p.iter_bezier(simplify=False): + # Get distance along the curve of any extrema + _, dzeros = curve.axis_aligned_extrema() + # Calculate vertices of start, end and any extrema in between + vertices.append(curve([0, *dzeros, 1])) + + if len(vertices): + vertices = np.vstack(vertices) + + patch_trf = patch.get_transform() + updatex, updatey = patch_trf.contains_branch_seperately(self.transData) + if not (updatex or updatey): + return + if self.name != "rectilinear": + # As in _update_line_limits, but for axvspan. + if updatex and patch_trf == self.get_yaxis_transform(): + updatex = False + if updatey and patch_trf == self.get_xaxis_transform(): + updatey = False + trf_to_data = patch_trf - self.transData + xys = trf_to_data.transform(vertices) + self.update_datalim(xys, updatex=updatex, updatey=updatey) + + def add_table(self, tab): + """ + Add a `.Table` to the Axes; return the table. + """ + _api.check_isinstance(mtable.Table, tab=tab) + self._set_artist_props(tab) + self._children.append(tab) + if tab.get_clip_path() is None: + tab.set_clip_path(self.patch) + tab._remove_method = self._children.remove + return tab + + def add_container(self, container): + """ + Add a `.Container` to the Axes' containers; return the container. + """ + label = container.get_label() + if not label: + container.set_label('_container%d' % len(self.containers)) + self.containers.append(container) + container._remove_method = self.containers.remove + return container + + def _unit_change_handler(self, axis_name, event=None): + """ + Process axis units changes: requests updates to data and view limits. + """ + if event is None: # Allow connecting `self._unit_change_handler(name)` + return functools.partial( + self._unit_change_handler, axis_name, event=object()) + _api.check_in_list(self._axis_map, axis_name=axis_name) + for line in self.lines: + line.recache_always() + self.relim() + self._request_autoscale_view(axis_name) + + def relim(self, visible_only=False): + """ + Recompute the data limits based on current artists. + + At present, `.Collection` instances are not supported. + + Parameters + ---------- + visible_only : bool, default: False + Whether to exclude invisible artists. + """ + # Collections are deliberately not supported (yet); see + # the TODO note in artists.py. + self.dataLim.ignore(True) + self.dataLim.set_points(mtransforms.Bbox.null().get_points()) + self.ignore_existing_data_limits = True + + for artist in self._children: + if not visible_only or artist.get_visible(): + if isinstance(artist, mlines.Line2D): + self._update_line_limits(artist) + elif isinstance(artist, mpatches.Patch): + self._update_patch_limits(artist) + elif isinstance(artist, mimage.AxesImage): + self._update_image_limits(artist) + + def update_datalim(self, xys, updatex=True, updatey=True): + """ + Extend the `~.Axes.dataLim` Bbox to include the given points. + + If no data is set currently, the Bbox will ignore its limits and set + the bound to be the bounds of the xydata (*xys*). Otherwise, it will + compute the bounds of the union of its current data and the data in + *xys*. + + Parameters + ---------- + xys : 2D array-like + The points to include in the data limits Bbox. This can be either + a list of (x, y) tuples or a (N, 2) array. + + updatex, updatey : bool, default: True + Whether to update the x/y limits. + """ + xys = np.asarray(xys) + if not np.any(np.isfinite(xys)): + return + self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits, + updatex=updatex, updatey=updatey) + self.ignore_existing_data_limits = False + + def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True): + """ + Set axis units based on *datasets* and *kwargs*, and optionally apply + unit conversions to *datasets*. + + Parameters + ---------- + datasets : list + List of (axis_name, dataset) pairs (where the axis name is defined + as in `._axis_map`). Individual datasets can also be None + (which gets passed through). + kwargs : dict + Other parameters from which unit info (i.e., the *xunits*, + *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for + polar) entries) is popped, if present. Note that this dict is + mutated in-place! + convert : bool, default: True + Whether to return the original datasets or the converted ones. + + Returns + ------- + list + Either the original datasets if *convert* is False, or the + converted ones if *convert* is True (the default). + """ + # The API makes datasets a list of pairs rather than an axis_name to + # dataset mapping because it is sometimes necessary to process multiple + # datasets for a single axis, and concatenating them may be tricky + # (e.g. if some are scalars, etc.). + datasets = datasets or [] + kwargs = kwargs or {} + axis_map = self._axis_map + for axis_name, data in datasets: + try: + axis = axis_map[axis_name] + except KeyError: + raise ValueError(f"Invalid axis name: {axis_name!r}") from None + # Update from data if axis is already set but no unit is set yet. + if axis is not None and data is not None and not axis.have_units(): + axis.update_units(data) + for axis_name, axis in axis_map.items(): + # Return if no axis is set. + if axis is None: + continue + # Check for units in the kwargs, and if present update axis. + units = kwargs.pop(f"{axis_name}units", axis.units) + if self.name == "polar": + # Special case: polar supports "thetaunits"/"runits". + polar_units = {"x": "thetaunits", "y": "runits"} + units = kwargs.pop(polar_units[axis_name], units) + if units != axis.units and units is not None: + axis.set_units(units) + # If the units being set imply a different converter, + # we need to update again. + for dataset_axis_name, data in datasets: + if dataset_axis_name == axis_name and data is not None: + axis.update_units(data) + return [axis_map[axis_name].convert_units(data) + if convert and data is not None else data + for axis_name, data in datasets] + + def in_axes(self, mouseevent): + """ + Return whether the given event (in display coords) is in the Axes. + """ + return self.patch.contains(mouseevent)[0] + + get_autoscalex_on = _axis_method_wrapper("xaxis", "_get_autoscale_on") + get_autoscaley_on = _axis_method_wrapper("yaxis", "_get_autoscale_on") + set_autoscalex_on = _axis_method_wrapper("xaxis", "_set_autoscale_on") + set_autoscaley_on = _axis_method_wrapper("yaxis", "_set_autoscale_on") + + def get_autoscale_on(self): + """Return True if each axis is autoscaled, False otherwise.""" + return all(axis._get_autoscale_on() + for axis in self._axis_map.values()) + + def set_autoscale_on(self, b): + """ + Set whether autoscaling is applied to each axis on the next draw or + call to `.Axes.autoscale_view`. + + Parameters + ---------- + b : bool + """ + for axis in self._axis_map.values(): + axis._set_autoscale_on(b) + + @property + def use_sticky_edges(self): + """ + When autoscaling, whether to obey all `.Artist.sticky_edges`. + + Default is ``True``. + + Setting this to ``False`` ensures that the specified margins + will be applied, even if the plot includes an image, for + example, which would otherwise force a view limit to coincide + with its data limit. + + The changing this property does not change the plot until + `autoscale` or `autoscale_view` is called. + """ + return self._use_sticky_edges + + @use_sticky_edges.setter + def use_sticky_edges(self, b): + self._use_sticky_edges = bool(b) + # No effect until next autoscaling, which will mark the Axes as stale. + + def get_xmargin(self): + """ + Retrieve autoscaling margin of the x-axis. + + .. versionadded:: 3.9 + + Returns + ------- + xmargin : float + + See Also + -------- + matplotlib.axes.Axes.set_xmargin + """ + return self._xmargin + + def get_ymargin(self): + """ + Retrieve autoscaling margin of the y-axis. + + .. versionadded:: 3.9 + + Returns + ------- + ymargin : float + + See Also + -------- + matplotlib.axes.Axes.set_ymargin + """ + return self._ymargin + + def set_xmargin(self, m): + """ + Set padding of X data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._xmargin = m + self._request_autoscale_view("x") + self.stale = True + + def set_ymargin(self, m): + """ + Set padding of Y data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._ymargin = m + self._request_autoscale_view("y") + self.stale = True + + def margins(self, *margins, x=None, y=None, tight=True): + """ + Set or retrieve margins around the data for autoscaling axis limits. + + This allows to configure the padding around the data without having to + set explicit limits using `~.Axes.set_xlim` / `~.Axes.set_ylim`. + + Autoscaling determines the axis limits by adding *margin* times the + data interval as padding around the data. See the following illustration: + + .. plot:: _embedded_plots/axes_margins.py + + All input parameters must be floats greater than -0.5. Passing both + positional and keyword arguments is invalid and will raise a TypeError. + If no arguments (positional or otherwise) are provided, the current + margins will remain unchanged and simply be returned. + + The default margins are :rc:`axes.xmargin` and :rc:`axes.ymargin`. + + Parameters + ---------- + *margins : float, optional + If a single positional argument is provided, it specifies + both margins of the x-axis and y-axis limits. If two + positional arguments are provided, they will be interpreted + as *xmargin*, *ymargin*. If setting the margin on a single + axis is desired, use the keyword arguments described below. + + x, y : float, optional + Specific margin values for the x-axis and y-axis, + respectively. These cannot be used with positional + arguments, but can be used individually to alter on e.g., + only the y-axis. + + tight : bool or None, default: True + The *tight* parameter is passed to `~.axes.Axes.autoscale_view`, + which is executed after a margin is changed; the default + here is *True*, on the assumption that when margins are + specified, no additional padding to match tick marks is + usually desired. Setting *tight* to *None* preserves + the previous setting. + + Returns + ------- + xmargin, ymargin : float + + Notes + ----- + If a previously used Axes method such as :meth:`pcolor` has set + `~.Axes.use_sticky_edges` to `True`, only the limits not set by + the "sticky artists" will be modified. To force all + margins to be set, set `~.Axes.use_sticky_edges` to `False` + before calling :meth:`margins`. + + See Also + -------- + .Axes.set_xmargin, .Axes.set_ymargin + """ + + if margins and (x is not None or y is not None): + raise TypeError('Cannot pass both positional and keyword ' + 'arguments for x and/or y.') + elif len(margins) == 1: + x = y = margins[0] + elif len(margins) == 2: + x, y = margins + elif margins: + raise TypeError('Must pass a single positional argument for all ' + 'margins, or one for each margin (x, y).') + + if x is None and y is None: + if tight is not True: + _api.warn_external(f'ignoring tight={tight!r} in get mode') + return self._xmargin, self._ymargin + + if tight is not None: + self._tight = tight + if x is not None: + self.set_xmargin(x) + if y is not None: + self.set_ymargin(y) + + def set_rasterization_zorder(self, z): + """ + Set the zorder threshold for rasterization for vector graphics output. + + All artists with a zorder below the given value will be rasterized if + they support rasterization. + + This setting is ignored for pixel-based output. + + See also :doc:`/gallery/misc/rasterization_demo`. + + Parameters + ---------- + z : float or None + The zorder below which artists are rasterized. + If ``None`` rasterization based on zorder is deactivated. + """ + self._rasterization_zorder = z + self.stale = True + + def get_rasterization_zorder(self): + """Return the zorder value below which artists will be rasterized.""" + return self._rasterization_zorder + + def autoscale(self, enable=True, axis='both', tight=None): + """ + Autoscale the axis view to the data (toggle). + + Convenience method for simple axis view autoscaling. + It turns autoscaling on or off, and then, + if autoscaling for either axis is on, it performs + the autoscaling on the specified axis or Axes. + + Parameters + ---------- + enable : bool or None, default: True + True turns autoscaling on, False turns it off. + None leaves the autoscaling state unchanged. + axis : {'both', 'x', 'y'}, default: 'both' + The axis on which to operate. (For 3D Axes, *axis* can also be set + to 'z', and 'both' refers to all three Axes.) + tight : bool or None, default: None + If True, first set the margins to zero. Then, this argument is + forwarded to `~.axes.Axes.autoscale_view` (regardless of + its value); see the description of its behavior there. + """ + if enable is None: + scalex = True + scaley = True + else: + if axis in ['x', 'both']: + self.set_autoscalex_on(bool(enable)) + scalex = self.get_autoscalex_on() + else: + scalex = False + if axis in ['y', 'both']: + self.set_autoscaley_on(bool(enable)) + scaley = self.get_autoscaley_on() + else: + scaley = False + if tight and scalex: + self._xmargin = 0 + if tight and scaley: + self._ymargin = 0 + if scalex: + self._request_autoscale_view("x", tight=tight) + if scaley: + self._request_autoscale_view("y", tight=tight) + + def autoscale_view(self, tight=None, scalex=True, scaley=True): + """ + Autoscale the view limits using the data limits. + + Parameters + ---------- + tight : bool or None + If *True*, only expand the axis limits using the margins. Note + that unlike for `autoscale`, ``tight=True`` does *not* set the + margins to zero. + + If *False* and :rc:`axes.autolimit_mode` is 'round_numbers', then + after expansion by the margins, further expand the axis limits + using the axis major locator. + + If None (the default), reuse the value set in the previous call to + `autoscale_view` (the initial value is False, but the default style + sets :rc:`axes.autolimit_mode` to 'data', in which case this + behaves like True). + + scalex : bool, default: True + Whether to autoscale the x-axis. + + scaley : bool, default: True + Whether to autoscale the y-axis. + + Notes + ----- + The autoscaling preserves any preexisting axis direction reversal. + + The data limits are not updated automatically when artist data are + changed after the artist has been added to an Axes instance. In that + case, use :meth:`matplotlib.axes.Axes.relim` prior to calling + autoscale_view. + + If the views of the Axes are fixed, e.g. via `set_xlim`, they will + not be changed by autoscale_view(). + See :meth:`matplotlib.axes.Axes.autoscale` for an alternative. + """ + if tight is not None: + self._tight = bool(tight) + + x_stickies = y_stickies = np.array([]) + if self.use_sticky_edges: + if self._xmargin and scalex and self.get_autoscalex_on(): + x_stickies = np.sort(np.concatenate([ + artist.sticky_edges.x + for ax in self._shared_axes["x"].get_siblings(self) + for artist in ax.get_children()])) + if self._ymargin and scaley and self.get_autoscaley_on(): + y_stickies = np.sort(np.concatenate([ + artist.sticky_edges.y + for ax in self._shared_axes["y"].get_siblings(self) + for artist in ax.get_children()])) + if self.get_xscale() == 'log': + x_stickies = x_stickies[x_stickies > 0] + if self.get_yscale() == 'log': + y_stickies = y_stickies[y_stickies > 0] + + def handle_single_axis( + scale, shared_axes, name, axis, margin, stickies, set_bound): + + if not (scale and axis._get_autoscale_on()): + return # nothing to do... + + shared = shared_axes.get_siblings(self) + # Base autoscaling on finite data limits when there is at least one + # finite data limit among all the shared_axes and intervals. + values = [val for ax in shared + for val in getattr(ax.dataLim, f"interval{name}") + if np.isfinite(val)] + if values: + x0, x1 = (min(values), max(values)) + elif getattr(self._viewLim, f"mutated{name}")(): + # No data, but explicit viewLims already set: + # in mutatedx or mutatedy. + return + else: + x0, x1 = (-np.inf, np.inf) + # If x0 and x1 are nonfinite, get default limits from the locator. + locator = axis.get_major_locator() + x0, x1 = locator.nonsingular(x0, x1) + # Find the minimum minpos for use in the margin calculation. + minimum_minpos = min( + getattr(ax.dataLim, f"minpos{name}") for ax in shared) + + # Prevent margin addition from crossing a sticky value. A small + # tolerance must be added due to floating point issues with + # streamplot; it is defined relative to x1-x0 but has + # no absolute term (e.g. "+1e-8") to avoid issues when working with + # datasets where all values are tiny (less than 1e-8). + tol = 1e-5 * abs(x1 - x0) + # Index of largest element < x0 + tol, if any. + i0 = stickies.searchsorted(x0 + tol) - 1 + x0bound = stickies[i0] if i0 != -1 else None + # Index of smallest element > x1 - tol, if any. + i1 = stickies.searchsorted(x1 - tol) + x1bound = stickies[i1] if i1 != len(stickies) else None + + # Add the margin in figure space and then transform back, to handle + # non-linear scales. + transform = axis.get_transform() + inverse_trans = transform.inverted() + x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minimum_minpos) + x0t, x1t = transform.transform([x0, x1]) + delta = (x1t - x0t) * margin + if not np.isfinite(delta): + delta = 0 # If a bound isn't finite, set margin to zero. + x0, x1 = inverse_trans.transform([x0t - delta, x1t + delta]) + + # Apply sticky bounds. + if x0bound is not None: + x0 = max(x0, x0bound) + if x1bound is not None: + x1 = min(x1, x1bound) + + if not self._tight: + x0, x1 = locator.view_limits(x0, x1) + set_bound(x0, x1) + # End of definition of internal function 'handle_single_axis'. + + handle_single_axis( + scalex, self._shared_axes["x"], 'x', self.xaxis, self._xmargin, + x_stickies, self.set_xbound) + handle_single_axis( + scaley, self._shared_axes["y"], 'y', self.yaxis, self._ymargin, + y_stickies, self.set_ybound) + + def _update_title_position(self, renderer): + """ + Update the title position based on the bounding box enclosing + all the ticklabels and x-axis spine and xlabel... + """ + if self._autotitlepos is not None and not self._autotitlepos: + _log.debug('title position was updated manually, not adjusting') + return + + titles = (self.title, self._left_title, self._right_title) + + if not any(title.get_text() for title in titles): + # If the titles are all empty, there is no need to update their positions. + return + + # Need to check all our twins too, aligned axes, and all the children + # as well. + axs = set() + axs.update(self.child_axes) + axs.update(self._twinned_axes.get_siblings(self)) + axs.update( + self.get_figure(root=False)._align_label_groups['title'].get_siblings(self)) + + for ax in self.child_axes: # Child positions must be updated first. + locator = ax.get_axes_locator() + ax.apply_aspect(locator(self, renderer) if locator else None) + + top = -np.inf + for ax in axs: + bb = None + if (ax.xaxis.get_ticks_position() in ['top', 'unknown'] or + ax.xaxis.get_label_position() == 'top'): + bb = ax.xaxis.get_tightbbox(renderer) + if bb is None: + # Extent of the outline for colorbars, of the axes otherwise. + bb = ax.spines.get("outline", ax).get_window_extent() + top = max(top, bb.ymax) + + for title in titles: + x, _ = title.get_position() + # need to start again in case of window resizing + title.set_position((x, 1.0)) + if title.get_text(): + for ax in axs: + ax.yaxis.get_tightbbox(renderer) # update offsetText + if ax.yaxis.offsetText.get_text(): + bb = ax.yaxis.offsetText.get_tightbbox(renderer) + if bb.intersection(title.get_tightbbox(renderer), bb): + top = bb.ymax + if top < 0: + # the top of Axes is not even on the figure, so don't try and + # automatically place it. + _log.debug('top of Axes not in the figure, so title not moved') + return + if title.get_window_extent(renderer).ymin < top: + _, y = self.transAxes.inverted().transform((0, top)) + title.set_position((x, y)) + # empirically, this doesn't always get the min to top, + # so we need to adjust again. + if title.get_window_extent(renderer).ymin < top: + _, y = self.transAxes.inverted().transform( + (0., 2 * top - title.get_window_extent(renderer).ymin)) + title.set_position((x, y)) + + ymax = max(title.get_position()[1] for title in titles) + for title in titles: + # now line up all the titles at the highest baseline. + x, _ = title.get_position() + title.set_position((x, ymax)) + + # Drawing + @martist.allow_rasterization + def draw(self, renderer): + # docstring inherited + if renderer is None: + raise RuntimeError('No renderer defined') + if not self.get_visible(): + return + self._unstale_viewLim() + + renderer.open_group('axes', gid=self.get_gid()) + + # prevent triggering call backs during the draw process + self._stale = True + + # loop over self and child Axes... + locator = self.get_axes_locator() + self.apply_aspect(locator(self, renderer) if locator else None) + + artists = self.get_children() + artists.remove(self.patch) + + # the frame draws the edges around the Axes patch -- we + # decouple these so the patch can be in the background and the + # frame in the foreground. Do this before drawing the axis + # objects so that the spine has the opportunity to update them. + if not (self.axison and self._frameon): + for spine in self.spines.values(): + artists.remove(spine) + + self._update_title_position(renderer) + + if not self.axison: + for _axis in self._axis_map.values(): + artists.remove(_axis) + + if not self.get_figure(root=True).canvas.is_saving(): + artists = [ + a for a in artists + if not a.get_animated() or isinstance(a, mimage.AxesImage)] + artists = sorted(artists, key=attrgetter('zorder')) + + # rasterize artists with negative zorder + # if the minimum zorder is negative, start rasterization + rasterization_zorder = self._rasterization_zorder + + if (rasterization_zorder is not None and + artists and artists[0].zorder < rasterization_zorder): + split_index = np.searchsorted( + [art.zorder for art in artists], + rasterization_zorder, side='right' + ) + artists_rasterized = artists[:split_index] + artists = artists[split_index:] + else: + artists_rasterized = [] + + if self.axison and self._frameon: + if artists_rasterized: + artists_rasterized = [self.patch] + artists_rasterized + else: + artists = [self.patch] + artists + + if artists_rasterized: + _draw_rasterized(self.get_figure(root=True), artists_rasterized, renderer) + + mimage._draw_list_compositing_images( + renderer, self, artists, self.get_figure(root=True).suppressComposite) + + renderer.close_group('axes') + self.stale = False + + def draw_artist(self, a): + """ + Efficiently redraw a single artist. + """ + a.draw(self.get_figure(root=True).canvas.get_renderer()) + + def redraw_in_frame(self): + """ + Efficiently redraw Axes data, but not axis ticks, labels, etc. + """ + with ExitStack() as stack: + for artist in [*self._axis_map.values(), + self.title, self._left_title, self._right_title]: + stack.enter_context(artist._cm_set(visible=False)) + self.draw(self.get_figure(root=True).canvas.get_renderer()) + + # Axes rectangle characteristics + + def get_frame_on(self): + """Get whether the Axes rectangle patch is drawn.""" + return self._frameon + + def set_frame_on(self, b): + """ + Set whether the Axes rectangle patch is drawn. + + Parameters + ---------- + b : bool + """ + self._frameon = b + self.stale = True + + def get_axisbelow(self): + """ + Get whether axis ticks and gridlines are above or below most artists. + + Returns + ------- + bool or 'line' + + See Also + -------- + set_axisbelow + """ + return self._axisbelow + + def set_axisbelow(self, b): + """ + Set whether axis ticks and gridlines are above or below most artists. + + This controls the zorder of the ticks and gridlines. For more + information on the zorder see :doc:`/gallery/misc/zorder_demo`. + + Parameters + ---------- + b : bool or 'line' + Possible values: + + - *True* (zorder = 0.5): Ticks and gridlines are below patches and + lines, though still above images. + - 'line' (zorder = 1.5): Ticks and gridlines are above patches + (e.g. rectangles, with default zorder = 1) but still below lines + and markers (with their default zorder = 2). + - *False* (zorder = 2.5): Ticks and gridlines are above patches + and lines / markers. + + Notes + ----- + For more control, call the `~.Artist.set_zorder` method of each axis. + + See Also + -------- + get_axisbelow + """ + # Check that b is True, False or 'line' + self._axisbelow = axisbelow = validate_axisbelow(b) + zorder = { + True: 0.5, + 'line': 1.5, + False: 2.5, + }[axisbelow] + for axis in self._axis_map.values(): + axis.set_zorder(zorder) + self.stale = True + + @_docstring.interpd + def grid(self, visible=None, which='major', axis='both', **kwargs): + """ + Configure the grid lines. + + Parameters + ---------- + visible : bool or None, optional + Whether to show the grid lines. If any *kwargs* are supplied, it + is assumed you want the grid on and *visible* will be set to True. + + If *visible* is *None* and there are no *kwargs*, this toggles the + visibility of the lines. + + which : {'major', 'minor', 'both'}, optional + The grid lines to apply the changes on. + + axis : {'both', 'x', 'y'}, optional + The axis to apply the changes on. + + **kwargs : `~matplotlib.lines.Line2D` properties + Define the line properties of the grid, e.g.:: + + grid(color='r', linestyle='-', linewidth=2) + + Valid keyword arguments are: + + %(Line2D:kwdoc)s + + Notes + ----- + The axis is drawn as a unit, so the effective zorder for drawing the + grid is determined by the zorder of each axis, not by the zorder of the + `.Line2D` objects comprising the grid. Therefore, to set grid zorder, + use `.set_axisbelow` or, for more control, call the + `~.Artist.set_zorder` method of each axis. + """ + _api.check_in_list(['x', 'y', 'both'], axis=axis) + if axis in ['x', 'both']: + self.xaxis.grid(visible, which=which, **kwargs) + if axis in ['y', 'both']: + self.yaxis.grid(visible, which=which, **kwargs) + + def ticklabel_format(self, *, axis='both', style=None, scilimits=None, + useOffset=None, useLocale=None, useMathText=None): + r""" + Configure the `.ScalarFormatter` used by default for linear Axes. + + If a parameter is not set, the corresponding property of the formatter + is left unchanged. + + Parameters + ---------- + axis : {'x', 'y', 'both'}, default: 'both' + The axis to configure. Only major ticks are affected. + + style : {'sci', 'scientific', 'plain'} + Whether to use scientific notation. + The formatter default is to use scientific notation. + 'sci' is equivalent to 'scientific'. + + scilimits : pair of ints (m, n) + Scientific notation is used only for numbers outside the range + 10\ :sup:`m` to 10\ :sup:`n` (and only if the formatter is + configured to use scientific notation at all). Use (0, 0) to + include all numbers. Use (m, m) where m != 0 to fix the order of + magnitude to 10\ :sup:`m`. + The formatter default is :rc:`axes.formatter.limits`. + + useOffset : bool or float + If True, the offset is calculated as needed. + If False, no offset is used. + If a numeric value, it sets the offset. + The formatter default is :rc:`axes.formatter.useoffset`. + + useLocale : bool + Whether to format the number using the current locale or using the + C (English) locale. This affects e.g. the decimal separator. The + formatter default is :rc:`axes.formatter.use_locale`. + + useMathText : bool + Render the offset and scientific notation in mathtext. + The formatter default is :rc:`axes.formatter.use_mathtext`. + + Raises + ------ + AttributeError + If the current formatter is not a `.ScalarFormatter`. + """ + if isinstance(style, str): + style = style.lower() + axis = axis.lower() + if scilimits is not None: + try: + m, n = scilimits + m + n + 1 # check that both are numbers + except (ValueError, TypeError) as err: + raise ValueError("scilimits must be a sequence of 2 integers" + ) from err + STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None, None: None} + # The '' option is included for backwards-compatibility. + is_sci_style = _api.check_getitem(STYLES, style=style) + axis_map = {**{k: [v] for k, v in self._axis_map.items()}, + 'both': list(self._axis_map.values())} + axises = _api.check_getitem(axis_map, axis=axis) + try: + for axis in axises: + if is_sci_style is not None: + axis.major.formatter.set_scientific(is_sci_style) + if scilimits is not None: + axis.major.formatter.set_powerlimits(scilimits) + if useOffset is not None: + axis.major.formatter.set_useOffset(useOffset) + if useLocale is not None: + axis.major.formatter.set_useLocale(useLocale) + if useMathText is not None: + axis.major.formatter.set_useMathText(useMathText) + except AttributeError as err: + raise AttributeError( + "This method only works with the ScalarFormatter") from err + + def locator_params(self, axis='both', tight=None, **kwargs): + """ + Control behavior of major tick locators. + + Because the locator is involved in autoscaling, `~.Axes.autoscale_view` + is called automatically after the parameters are changed. + + Parameters + ---------- + axis : {'both', 'x', 'y'}, default: 'both' + The axis on which to operate. (For 3D Axes, *axis* can also be + set to 'z', and 'both' refers to all three axes.) + tight : bool or None, optional + Parameter passed to `~.Axes.autoscale_view`. + Default is None, for no change. + + Other Parameters + ---------------- + **kwargs + Remaining keyword arguments are passed to directly to the + ``set_params()`` method of the locator. Supported keywords depend + on the type of the locator. See for example + `~.ticker.MaxNLocator.set_params` for the `.ticker.MaxNLocator` + used by default for linear. + + Examples + -------- + When plotting small subplots, one might want to reduce the maximum + number of ticks and use tight bounds, for example:: + + ax.locator_params(tight=True, nbins=4) + + """ + _api.check_in_list([*self._axis_names, "both"], axis=axis) + for name in self._axis_names: + if axis in [name, "both"]: + loc = self._axis_map[name].get_major_locator() + loc.set_params(**kwargs) + self._request_autoscale_view(name, tight=tight) + self.stale = True + + def tick_params(self, axis='both', **kwargs): + """ + Change the appearance of ticks, tick labels, and gridlines. + + Tick properties that are not explicitly set using the keyword + arguments remain unchanged unless *reset* is True. For the current + style settings, see `.Axis.get_tick_params`. + + Parameters + ---------- + axis : {'x', 'y', 'both'}, default: 'both' + The axis to which the parameters are applied. + which : {'major', 'minor', 'both'}, default: 'major' + The group of ticks to which the parameters are applied. + reset : bool, default: False + Whether to reset the ticks to defaults before updating them. + + Other Parameters + ---------------- + direction : {'in', 'out', 'inout'} + Puts ticks inside the Axes, outside the Axes, or both. + length : float + Tick length in points. + width : float + Tick width in points. + color : :mpltype:`color` + Tick color. + pad : float + Distance in points between tick and label. + labelsize : float or str + Tick label font size in points or as a string (e.g., 'large'). + labelcolor : :mpltype:`color` + Tick label color. + labelfontfamily : str + Tick label font. + colors : :mpltype:`color` + Tick color and label color. + zorder : float + Tick and label zorder. + bottom, top, left, right : bool + Whether to draw the respective ticks. + labelbottom, labeltop, labelleft, labelright : bool + Whether to draw the respective tick labels. + labelrotation : float + Tick label rotation + grid_color : :mpltype:`color` + Gridline color. + grid_alpha : float + Transparency of gridlines: 0 (transparent) to 1 (opaque). + grid_linewidth : float + Width of gridlines in points. + grid_linestyle : str + Any valid `.Line2D` line style spec. + + Examples + -------- + :: + + ax.tick_params(direction='out', length=6, width=2, colors='r', + grid_color='r', grid_alpha=0.5) + + This will make all major ticks be red, pointing out of the box, + and with dimensions 6 points by 2 points. Tick labels will + also be red. Gridlines will be red and translucent. + + """ + _api.check_in_list(['x', 'y', 'both'], axis=axis) + if axis in ['x', 'both']: + xkw = dict(kwargs) + xkw.pop('left', None) + xkw.pop('right', None) + xkw.pop('labelleft', None) + xkw.pop('labelright', None) + self.xaxis.set_tick_params(**xkw) + if axis in ['y', 'both']: + ykw = dict(kwargs) + ykw.pop('top', None) + ykw.pop('bottom', None) + ykw.pop('labeltop', None) + ykw.pop('labelbottom', None) + self.yaxis.set_tick_params(**ykw) + + def set_axis_off(self): + """ + Hide all visual components of the x- and y-axis. + + This sets a flag to suppress drawing of all axis decorations, i.e. + axis labels, axis spines, and the axis tick component (tick markers, + tick labels, and grid lines). Individual visibility settings of these + components are ignored as long as `set_axis_off()` is in effect. + """ + self.axison = False + self.stale = True + + def set_axis_on(self): + """ + Do not hide all visual components of the x- and y-axis. + + This reverts the effect of a prior `.set_axis_off()` call. Whether the + individual axis decorations are drawn is controlled by their respective + visibility settings. + + This is on by default. + """ + self.axison = True + self.stale = True + + # data limits, ticks, tick labels, and formatting + + def get_xlabel(self): + """ + Get the xlabel text string. + """ + label = self.xaxis.label + return label.get_text() + + def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, + loc=None, **kwargs): + """ + Set the label for the x-axis. + + Parameters + ---------- + xlabel : str + The label text. + + labelpad : float, default: :rc:`axes.labelpad` + Spacing in points from the Axes bounding box including ticks + and tick labels. If None, the previous value is left as is. + + loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation` + The label position. This is a high-level alternative for passing + parameters *x* and *horizontalalignment*. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + `.Text` properties control the appearance of the label. + + See Also + -------- + text : Documents the properties supported by `.Text`. + """ + if labelpad is not None: + self.xaxis.labelpad = labelpad + protected_kw = ['x', 'horizontalalignment', 'ha'] + if {*kwargs} & {*protected_kw}: + if loc is not None: + raise TypeError(f"Specifying 'loc' is disallowed when any of " + f"its corresponding low level keyword " + f"arguments ({protected_kw}) are also " + f"supplied") + + else: + loc = (loc if loc is not None + else mpl.rcParams['xaxis.labellocation']) + _api.check_in_list(('left', 'center', 'right'), loc=loc) + + x = { + 'left': 0, + 'center': 0.5, + 'right': 1, + }[loc] + kwargs.update(x=x, horizontalalignment=loc) + + return self.xaxis.set_label_text(xlabel, fontdict, **kwargs) + + def invert_xaxis(self): + """ + Invert the x-axis. + + See Also + -------- + xaxis_inverted + get_xlim, set_xlim + get_xbound, set_xbound + """ + self.xaxis.set_inverted(not self.xaxis.get_inverted()) + + xaxis_inverted = _axis_method_wrapper("xaxis", "get_inverted") + + def get_xbound(self): + """ + Return the lower and upper x-axis bounds, in increasing order. + + See Also + -------- + set_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + left, right = self.get_xlim() + if left < right: + return left, right + else: + return right, left + + def set_xbound(self, lower=None, upper=None): + """ + Set the lower and upper numerical bounds of the x-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscalex_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + + .. ACCEPTS: (lower: float, upper: float) + + See Also + -------- + get_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = self.get_xbound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + self.set_xlim(sorted((lower, upper), + reverse=bool(self.xaxis_inverted())), + auto=None) + + def get_xlim(self): + """ + Return the x-axis view limits. + + Returns + ------- + left, right : (float, float) + The current x-axis limits in data coordinates. + + See Also + -------- + .Axes.set_xlim + .Axes.set_xbound, .Axes.get_xbound + .Axes.invert_xaxis, .Axes.xaxis_inverted + + Notes + ----- + The x-axis may be inverted, in which case the *left* value will + be greater than the *right* value. + """ + return tuple(self.viewLim.intervalx) + + def _validate_converted_limits(self, limit, convert): + """ + Raise ValueError if converted limits are non-finite. + + Note that this function also accepts None as a limit argument. + + Returns + ------- + The limit value after call to convert(), or None if limit is None. + """ + if limit is not None: + converted_limit = convert(limit) + if isinstance(converted_limit, np.ndarray): + converted_limit = converted_limit.squeeze() + if (isinstance(converted_limit, Real) + and not np.isfinite(converted_limit)): + raise ValueError("Axis limits cannot be NaN or Inf") + return converted_limit + + def set_xlim(self, left=None, right=None, *, emit=True, auto=False, + xmin=None, xmax=None): + """ + Set the x-axis view limits. + + Parameters + ---------- + left : float, optional + The left xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + The left and right xlims may also be passed as the tuple + (*left*, *right*) as the first positional argument (or as + the *left* keyword argument). + + .. ACCEPTS: (left: float, right: float) + + right : float, optional + The right xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the x-axis. True turns on, + False turns off, None leaves unchanged. + + xmin, xmax : float, optional + They are equivalent to left and right respectively, and it is an + error to pass both *xmin* and *left* or *xmax* and *right*. + + Returns + ------- + left, right : (float, float) + The new x-axis limits in data coordinates. + + See Also + -------- + get_xlim + set_xbound, get_xbound + invert_xaxis, xaxis_inverted + + Notes + ----- + The *left* value may be greater than the *right* value, in which + case the x-axis values will decrease from left to right. + + Examples + -------- + >>> set_xlim(left, right) + >>> set_xlim((left, right)) + >>> left, right = set_xlim(left, right) + + One limit may be left unchanged. + + >>> set_xlim(right=right_lim) + + Limits may be passed in reverse order to flip the direction of + the x-axis. For example, suppose *x* represents the number of + years before present. The x-axis limits might be set like the + following so 5000 years ago is on the left of the plot and the + present is on the right. + + >>> set_xlim(5000, 0) + """ + if right is None and np.iterable(left): + left, right = left + if xmin is not None: + if left is not None: + raise TypeError("Cannot pass both 'left' and 'xmin'") + left = xmin + if xmax is not None: + if right is not None: + raise TypeError("Cannot pass both 'right' and 'xmax'") + right = xmax + return self.xaxis._set_lim(left, right, emit=emit, auto=auto) + + get_xscale = _axis_method_wrapper("xaxis", "get_scale") + set_xscale = _axis_method_wrapper("xaxis", "_set_axes_scale") + get_xticks = _axis_method_wrapper("xaxis", "get_ticklocs") + set_xticks = _axis_method_wrapper("xaxis", "set_ticks", + doc_sub={'set_ticks': 'set_xticks'}) + get_xmajorticklabels = _axis_method_wrapper("xaxis", "get_majorticklabels") + get_xminorticklabels = _axis_method_wrapper("xaxis", "get_minorticklabels") + get_xticklabels = _axis_method_wrapper("xaxis", "get_ticklabels") + set_xticklabels = _axis_method_wrapper( + "xaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes.set_xticks"}) + + def get_ylabel(self): + """ + Get the ylabel text string. + """ + label = self.yaxis.label + return label.get_text() + + def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *, + loc=None, **kwargs): + """ + Set the label for the y-axis. + + Parameters + ---------- + ylabel : str + The label text. + + labelpad : float, default: :rc:`axes.labelpad` + Spacing in points from the Axes bounding box including ticks + and tick labels. If None, the previous value is left as is. + + loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation` + The label position. This is a high-level alternative for passing + parameters *y* and *horizontalalignment*. + + Other Parameters + ---------------- + **kwargs : `~matplotlib.text.Text` properties + `.Text` properties control the appearance of the label. + + See Also + -------- + text : Documents the properties supported by `.Text`. + """ + if labelpad is not None: + self.yaxis.labelpad = labelpad + protected_kw = ['y', 'horizontalalignment', 'ha'] + if {*kwargs} & {*protected_kw}: + if loc is not None: + raise TypeError(f"Specifying 'loc' is disallowed when any of " + f"its corresponding low level keyword " + f"arguments ({protected_kw}) are also " + f"supplied") + + else: + loc = (loc if loc is not None + else mpl.rcParams['yaxis.labellocation']) + _api.check_in_list(('bottom', 'center', 'top'), loc=loc) + + y, ha = { + 'bottom': (0, 'left'), + 'center': (0.5, 'center'), + 'top': (1, 'right') + }[loc] + kwargs.update(y=y, horizontalalignment=ha) + + return self.yaxis.set_label_text(ylabel, fontdict, **kwargs) + + def invert_yaxis(self): + """ + Invert the y-axis. + + See Also + -------- + yaxis_inverted + get_ylim, set_ylim + get_ybound, set_ybound + """ + self.yaxis.set_inverted(not self.yaxis.get_inverted()) + + yaxis_inverted = _axis_method_wrapper("yaxis", "get_inverted") + + def get_ybound(self): + """ + Return the lower and upper y-axis bounds, in increasing order. + + See Also + -------- + set_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + bottom, top = self.get_ylim() + if bottom < top: + return bottom, top + else: + return top, bottom + + def set_ybound(self, lower=None, upper=None): + """ + Set the lower and upper numerical bounds of the y-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscaley_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + + .. ACCEPTS: (lower: float, upper: float) + + See Also + -------- + get_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = self.get_ybound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + self.set_ylim(sorted((lower, upper), + reverse=bool(self.yaxis_inverted())), + auto=None) + + def get_ylim(self): + """ + Return the y-axis view limits. + + Returns + ------- + bottom, top : (float, float) + The current y-axis limits in data coordinates. + + See Also + -------- + .Axes.set_ylim + .Axes.set_ybound, .Axes.get_ybound + .Axes.invert_yaxis, .Axes.yaxis_inverted + + Notes + ----- + The y-axis may be inverted, in which case the *bottom* value + will be greater than the *top* value. + """ + return tuple(self.viewLim.intervaly) + + def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False, + ymin=None, ymax=None): + """ + Set the y-axis view limits. + + Parameters + ---------- + bottom : float, optional + The bottom ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + The bottom and top ylims may also be passed as the tuple + (*bottom*, *top*) as the first positional argument (or as + the *bottom* keyword argument). + + .. ACCEPTS: (bottom: float, top: float) + + top : float, optional + The top ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the y-axis. *True* turns on, + *False* turns off, *None* leaves unchanged. + + ymin, ymax : float, optional + They are equivalent to bottom and top respectively, and it is an + error to pass both *ymin* and *bottom* or *ymax* and *top*. + + Returns + ------- + bottom, top : (float, float) + The new y-axis limits in data coordinates. + + See Also + -------- + get_ylim + set_ybound, get_ybound + invert_yaxis, yaxis_inverted + + Notes + ----- + The *bottom* value may be greater than the *top* value, in which + case the y-axis values will decrease from *bottom* to *top*. + + Examples + -------- + >>> set_ylim(bottom, top) + >>> set_ylim((bottom, top)) + >>> bottom, top = set_ylim(bottom, top) + + One limit may be left unchanged. + + >>> set_ylim(top=top_lim) + + Limits may be passed in reverse order to flip the direction of + the y-axis. For example, suppose ``y`` represents depth of the + ocean in m. The y-axis limits might be set like the following + so 5000 m depth is at the bottom of the plot and the surface, + 0 m, is at the top. + + >>> set_ylim(5000, 0) + """ + if top is None and np.iterable(bottom): + bottom, top = bottom + if ymin is not None: + if bottom is not None: + raise TypeError("Cannot pass both 'bottom' and 'ymin'") + bottom = ymin + if ymax is not None: + if top is not None: + raise TypeError("Cannot pass both 'top' and 'ymax'") + top = ymax + return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto) + + get_yscale = _axis_method_wrapper("yaxis", "get_scale") + set_yscale = _axis_method_wrapper("yaxis", "_set_axes_scale") + get_yticks = _axis_method_wrapper("yaxis", "get_ticklocs") + set_yticks = _axis_method_wrapper("yaxis", "set_ticks", + doc_sub={'set_ticks': 'set_yticks'}) + get_ymajorticklabels = _axis_method_wrapper("yaxis", "get_majorticklabels") + get_yminorticklabels = _axis_method_wrapper("yaxis", "get_minorticklabels") + get_yticklabels = _axis_method_wrapper("yaxis", "get_ticklabels") + set_yticklabels = _axis_method_wrapper( + "yaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes.set_yticks"}) + + xaxis_date = _axis_method_wrapper("xaxis", "axis_date") + yaxis_date = _axis_method_wrapper("yaxis", "axis_date") + + def format_xdata(self, x): + """ + Return *x* formatted as an x-value. + + This function will use the `.fmt_xdata` attribute if it is not None, + else will fall back on the xaxis major formatter. + """ + return (self.fmt_xdata if self.fmt_xdata is not None + else self.xaxis.get_major_formatter().format_data_short)(x) + + def format_ydata(self, y): + """ + Return *y* formatted as a y-value. + + This function will use the `.fmt_ydata` attribute if it is not None, + else will fall back on the yaxis major formatter. + """ + return (self.fmt_ydata if self.fmt_ydata is not None + else self.yaxis.get_major_formatter().format_data_short)(y) + + def format_coord(self, x, y): + """Return a format string formatting the *x*, *y* coordinates.""" + twins = self._twinned_axes.get_siblings(self) + if len(twins) == 1: + return "(x, y) = ({}, {})".format( + "???" if x is None else self.format_xdata(x), + "???" if y is None else self.format_ydata(y)) + screen_xy = self.transData.transform((x, y)) + xy_strs = [] + # Retrieve twins in the order of self.figure.axes to sort tied zorders (which is + # the common case) by the order in which they are added to the figure. + for ax in sorted(twins, key=attrgetter("zorder")): + data_x, data_y = ax.transData.inverted().transform(screen_xy) + xy_strs.append( + "({}, {})".format(ax.format_xdata(data_x), ax.format_ydata(data_y))) + return "(x, y) = {}".format(" | ".join(xy_strs)) + + def minorticks_on(self): + """ + Display minor ticks on the Axes. + + Displaying minor ticks may reduce performance; you may turn them off + using `minorticks_off()` if drawing speed is a problem. + """ + self.xaxis.minorticks_on() + self.yaxis.minorticks_on() + + def minorticks_off(self): + """Remove minor ticks from the Axes.""" + self.xaxis.minorticks_off() + self.yaxis.minorticks_off() + + # Interactive manipulation + + def can_zoom(self): + """ + Return whether this Axes supports the zoom box button functionality. + """ + return True + + def can_pan(self): + """ + Return whether this Axes supports any pan/zoom button functionality. + """ + return True + + def get_navigate(self): + """ + Get whether the Axes responds to navigation commands. + """ + return self._navigate + + def set_navigate(self, b): + """ + Set whether the Axes responds to navigation toolbar commands. + + Parameters + ---------- + b : bool + + See Also + -------- + matplotlib.axes.Axes.set_forward_navigation_events + + """ + self._navigate = b + + def get_navigate_mode(self): + """ + Get the navigation toolbar button status: 'PAN', 'ZOOM', or None. + """ + return self._navigate_mode + + def set_navigate_mode(self, b): + """ + Set the navigation toolbar button status. + + .. warning:: + This is not a user-API function. + + """ + self._navigate_mode = b + + def _get_view(self): + """ + Save information required to reproduce the current view. + + This method is called before a view is changed, such as during a pan or zoom + initiated by the user. It returns an opaque object that describes the current + view, in a format compatible with :meth:`_set_view`. + + The default implementation saves the view limits and autoscaling state. + Subclasses may override this as needed, as long as :meth:`_set_view` is also + adjusted accordingly. + """ + return { + "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(), + "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(), + } + + def _set_view(self, view): + """ + Apply a previously saved view. + + This method is called when restoring a view (with the return value of + :meth:`_get_view` as argument), such as with the navigation buttons. + + Subclasses that override :meth:`_get_view` also need to override this method + accordingly. + """ + self.set(**view) + + def _prepare_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Helper function to prepare the new bounds from a bbox. + + This helper function returns the new x and y bounds from the zoom + bbox. This a convenience method to abstract the bbox logic + out of the base setter. + """ + if len(bbox) == 3: + xp, yp, scl = bbox # Zooming code + if scl == 0: # Should not happen + scl = 1. + if scl > 1: + direction = 'in' + else: + direction = 'out' + scl = 1/scl + # get the limits of the axes + (xmin, ymin), (xmax, ymax) = self.transData.transform( + np.transpose([self.get_xlim(), self.get_ylim()])) + # set the range + xwidth = xmax - xmin + ywidth = ymax - ymin + xcen = (xmax + xmin)*.5 + ycen = (ymax + ymin)*.5 + xzc = (xp*(scl - 1) + xcen)/scl + yzc = (yp*(scl - 1) + ycen)/scl + bbox = [xzc - xwidth/2./scl, yzc - ywidth/2./scl, + xzc + xwidth/2./scl, yzc + ywidth/2./scl] + elif len(bbox) != 4: + # should be len 3 or 4 but nothing else + _api.warn_external( + "Warning in _set_view_from_bbox: bounding box is not a tuple " + "of length 3 or 4. Ignoring the view change.") + return + + # Original limits. + xmin0, xmax0 = self.get_xbound() + ymin0, ymax0 = self.get_ybound() + # The zoom box in screen coords. + startx, starty, stopx, stopy = bbox + # Convert to data coords. + (startx, starty), (stopx, stopy) = self.transData.inverted().transform( + [(startx, starty), (stopx, stopy)]) + # Clip to axes limits. + xmin, xmax = np.clip(sorted([startx, stopx]), xmin0, xmax0) + ymin, ymax = np.clip(sorted([starty, stopy]), ymin0, ymax0) + # Don't double-zoom twinned axes or if zooming only the other axis. + if twinx or mode == "y": + xmin, xmax = xmin0, xmax0 + if twiny or mode == "x": + ymin, ymax = ymin0, ymax0 + + if direction == "in": + new_xbound = xmin, xmax + new_ybound = ymin, ymax + + elif direction == "out": + x_trf = self.xaxis.get_transform() + sxmin0, sxmax0, sxmin, sxmax = x_trf.transform( + [xmin0, xmax0, xmin, xmax]) # To screen space. + factor = (sxmax0 - sxmin0) / (sxmax - sxmin) # Unzoom factor. + # Move original bounds away by + # (factor) x (distance between unzoom box and Axes bbox). + sxmin1 = sxmin0 - factor * (sxmin - sxmin0) + sxmax1 = sxmax0 + factor * (sxmax0 - sxmax) + # And back to data space. + new_xbound = x_trf.inverted().transform([sxmin1, sxmax1]) + + y_trf = self.yaxis.get_transform() + symin0, symax0, symin, symax = y_trf.transform( + [ymin0, ymax0, ymin, ymax]) + factor = (symax0 - symin0) / (symax - symin) + symin1 = symin0 - factor * (symin - symin0) + symax1 = symax0 + factor * (symax0 - symax) + new_ybound = y_trf.inverted().transform([symin1, symax1]) + + return new_xbound, new_ybound + + def _set_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Update view from a selection bbox. + + .. note:: + + Intended to be overridden by new projection types, but if not, the + default implementation sets the view limits to the bbox directly. + + Parameters + ---------- + bbox : 4-tuple or 3 tuple + * If bbox is a 4 tuple, it is the selected bounding box limits, + in *display* coordinates. + * If bbox is a 3 tuple, it is an (xp, yp, scl) triple, where + (xp, yp) is the center of zooming and scl the scale factor to + zoom by. + + direction : str + The direction to apply the bounding box. + * `'in'` - The bounding box describes the view directly, i.e., + it zooms in. + * `'out'` - The bounding box describes the size to make the + existing view, i.e., it zooms out. + + mode : str or None + The selection mode, whether to apply the bounding box in only the + `'x'` direction, `'y'` direction or both (`None`). + + twinx : bool + Whether this axis is twinned in the *x*-direction. + + twiny : bool + Whether this axis is twinned in the *y*-direction. + """ + new_xbound, new_ybound = self._prepare_view_from_bbox( + bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) + if not twinx and mode != "y": + self.set_xbound(new_xbound) + self.set_autoscalex_on(False) + if not twiny and mode != "x": + self.set_ybound(new_ybound) + self.set_autoscaley_on(False) + + def start_pan(self, x, y, button): + """ + Called when a pan operation has started. + + Parameters + ---------- + x, y : float + The mouse coordinates in display coords. + button : `.MouseButton` + The pressed mouse button. + + Notes + ----- + This is intended to be overridden by new projection types. + """ + self._pan_start = types.SimpleNamespace( + lim=self.viewLim.frozen(), + trans=self.transData.frozen(), + trans_inverse=self.transData.inverted().frozen(), + bbox=self.bbox.frozen(), + x=x, + y=y) + + def end_pan(self): + """ + Called when a pan operation completes (when the mouse button is up.) + + Notes + ----- + This is intended to be overridden by new projection types. + """ + del self._pan_start + + def _get_pan_points(self, button, key, x, y): + """ + Helper function to return the new points after a pan. + + This helper function returns the points on the axis after a pan has + occurred. This is a convenience method to abstract the pan logic + out of the base setter. + """ + def format_deltas(key, dx, dy): + if key == 'control': + if abs(dx) > abs(dy): + dy = dx + else: + dx = dy + elif key == 'x': + dy = 0 + elif key == 'y': + dx = 0 + elif key == 'shift': + if 2 * abs(dx) < abs(dy): + dx = 0 + elif 2 * abs(dy) < abs(dx): + dy = 0 + elif abs(dx) > abs(dy): + dy = dy / abs(dy) * abs(dx) + else: + dx = dx / abs(dx) * abs(dy) + return dx, dy + + p = self._pan_start + dx = x - p.x + dy = y - p.y + if dx == dy == 0: + return + if button == 1: + dx, dy = format_deltas(key, dx, dy) + result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse) + elif button == 3: + try: + dx = -dx / self.bbox.width + dy = -dy / self.bbox.height + dx, dy = format_deltas(key, dx, dy) + if self.get_aspect() != 'auto': + dx = dy = 0.5 * (dx + dy) + alpha = np.power(10.0, (dx, dy)) + start = np.array([p.x, p.y]) + oldpoints = p.lim.transformed(p.trans) + newpoints = start + alpha * (oldpoints - start) + result = (mtransforms.Bbox(newpoints) + .transformed(p.trans_inverse)) + except OverflowError: + _api.warn_external('Overflow while panning') + return + else: + return + + valid = np.isfinite(result.transformed(p.trans)) + points = result.get_points().astype(object) + # Just ignore invalid limits (typically, underflow in log-scale). + points[~valid] = None + return points + + def drag_pan(self, button, key, x, y): + """ + Called when the mouse moves during a pan operation. + + Parameters + ---------- + button : `.MouseButton` + The pressed mouse button. + key : str or None + The pressed key, if any. + x, y : float + The mouse coordinates in display coords. + + Notes + ----- + This is intended to be overridden by new projection types. + """ + points = self._get_pan_points(button, key, x, y) + if points is not None: + self.set_xlim(points[:, 0]) + self.set_ylim(points[:, 1]) + + def get_children(self): + # docstring inherited. + return [ + *self._children, + *self.spines.values(), + *self._axis_map.values(), + self.title, self._left_title, self._right_title, + *self.child_axes, + *([self.legend_] if self.legend_ is not None else []), + self.patch, + ] + + def contains(self, mouseevent): + # docstring inherited. + return self.patch.contains(mouseevent) + + def contains_point(self, point): + """ + Return whether *point* (pair of pixel coordinates) is inside the Axes + patch. + """ + return self.patch.contains_point(point, radius=1.0) + + def get_default_bbox_extra_artists(self): + """ + Return a default list of artists that are used for the bounding box + calculation. + + Artists are excluded either by not being visible or + ``artist.set_in_layout(False)``. + """ + + artists = self.get_children() + + for axis in self._axis_map.values(): + # axis tight bboxes are calculated separately inside + # Axes.get_tightbbox() using for_layout_only=True + artists.remove(axis) + if not (self.axison and self._frameon): + # don't do bbox on spines if frame not on. + for spine in self.spines.values(): + artists.remove(spine) + + artists.remove(self.title) + artists.remove(self._left_title) + artists.remove(self._right_title) + + # always include types that do not internally implement clipping + # to Axes. may have clip_on set to True and clip_box equivalent + # to ax.bbox but then ignore these properties during draws. + noclip = (_AxesBase, maxis.Axis, + offsetbox.AnnotationBbox, offsetbox.OffsetBox) + return [a for a in artists if a.get_visible() and a.get_in_layout() + and (isinstance(a, noclip) or not a._fully_clipped_to_axes())] + + def get_tightbbox(self, renderer=None, *, call_axes_locator=True, + bbox_extra_artists=None, for_layout_only=False): + """ + Return the tight bounding box of the Axes, including axis and their + decorators (xlabel, title, etc). + + Artists that have ``artist.set_in_layout(False)`` are not included + in the bbox. + + Parameters + ---------- + renderer : `.RendererBase` subclass + renderer that will be used to draw the figures (i.e. + ``fig.canvas.get_renderer()``) + + bbox_extra_artists : list of `.Artist` or ``None`` + List of artists to include in the tight bounding box. If + ``None`` (default), then all artist children of the Axes are + included in the tight bounding box. + + call_axes_locator : bool, default: True + If *call_axes_locator* is ``False``, it does not call the + ``_axes_locator`` attribute, which is necessary to get the correct + bounding box. ``call_axes_locator=False`` can be used if the + caller is only interested in the relative size of the tightbbox + compared to the Axes bbox. + + for_layout_only : default: False + The bounding box will *not* include the x-extent of the title and + the xlabel, or the y-extent of the ylabel. + + Returns + ------- + `.BboxBase` + Bounding box in figure pixel coordinates. + + See Also + -------- + matplotlib.axes.Axes.get_window_extent + matplotlib.axis.Axis.get_tightbbox + matplotlib.spines.Spine.get_window_extent + """ + + bb = [] + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + + if not self.get_visible(): + return None + + locator = self.get_axes_locator() + self.apply_aspect( + locator(self, renderer) if locator and call_axes_locator else None) + + for axis in self._axis_map.values(): + if self.axison and axis.get_visible(): + ba = martist._get_tightbbox_for_layout_only(axis, renderer) + if ba: + bb.append(ba) + self._update_title_position(renderer) + axbbox = self.get_window_extent(renderer) + bb.append(axbbox) + + for title in [self.title, self._left_title, self._right_title]: + if title.get_visible(): + bt = title.get_window_extent(renderer) + if for_layout_only and bt.width > 0: + # make the title bbox 1 pixel wide so its width + # is not accounted for in bbox calculations in + # tight/constrained_layout + bt.x0 = (bt.x0 + bt.x1) / 2 - 0.5 + bt.x1 = bt.x0 + 1.0 + bb.append(bt) + + bbox_artists = bbox_extra_artists + if bbox_artists is None: + bbox_artists = self.get_default_bbox_extra_artists() + + for a in bbox_artists: + bbox = a.get_tightbbox(renderer) + if (bbox is not None + and 0 < bbox.width < np.inf + and 0 < bbox.height < np.inf): + bb.append(bbox) + return mtransforms.Bbox.union( + [b for b in bb if b.width != 0 or b.height != 0]) + + def _make_twin_axes(self, *args, **kwargs): + """Make a twinx Axes of self. This is used for twinx and twiny.""" + if 'sharex' in kwargs and 'sharey' in kwargs: + # The following line is added in v2.2 to avoid breaking Seaborn, + # which currently uses this internal API. + if kwargs["sharex"] is not self and kwargs["sharey"] is not self: + raise ValueError("Twinned Axes may share only one axis") + ss = self.get_subplotspec() + if ss: + twin = self.get_figure(root=False).add_subplot(ss, *args, **kwargs) + else: + twin = self.get_figure(root=False).add_axes( + self.get_position(True), *args, **kwargs, + axes_locator=_TransformedBoundsLocator( + [0, 0, 1, 1], self.transAxes)) + self.set_adjustable('datalim') + twin.set_adjustable('datalim') + twin.set_zorder(self.zorder) + + self._twinned_axes.join(self, twin) + return twin + + def twinx(self): + """ + Create a twin Axes sharing the xaxis. + + Create a new Axes with an invisible x-axis and an independent + y-axis positioned opposite to the original one (i.e. at right). The + x-axis autoscale setting will be inherited from the original + Axes. To ensure that the tick marks of both y-axes align, see + `~matplotlib.ticker.LinearLocator`. + + Returns + ------- + Axes + The newly created Axes instance + + Notes + ----- + For those who are 'picking' artists while using twinx, pick + events are only called for the artists in the top-most Axes. + """ + ax2 = self._make_twin_axes(sharex=self) + ax2.yaxis.tick_right() + ax2.yaxis.set_label_position('right') + ax2.yaxis.set_offset_position('right') + ax2.set_autoscalex_on(self.get_autoscalex_on()) + self.yaxis.tick_left() + ax2.xaxis.set_visible(False) + ax2.patch.set_visible(False) + ax2.xaxis.units = self.xaxis.units + return ax2 + + def twiny(self): + """ + Create a twin Axes sharing the yaxis. + + Create a new Axes with an invisible y-axis and an independent + x-axis positioned opposite to the original one (i.e. at top). The + y-axis autoscale setting will be inherited from the original Axes. + To ensure that the tick marks of both x-axes align, see + `~matplotlib.ticker.LinearLocator`. + + Returns + ------- + Axes + The newly created Axes instance + + Notes + ----- + For those who are 'picking' artists while using twiny, pick + events are only called for the artists in the top-most Axes. + """ + ax2 = self._make_twin_axes(sharey=self) + ax2.xaxis.tick_top() + ax2.xaxis.set_label_position('top') + ax2.set_autoscaley_on(self.get_autoscaley_on()) + self.xaxis.tick_bottom() + ax2.yaxis.set_visible(False) + ax2.patch.set_visible(False) + ax2.yaxis.units = self.yaxis.units + return ax2 + + def get_shared_x_axes(self): + """Return an immutable view on the shared x-axes Grouper.""" + return cbook.GrouperView(self._shared_axes["x"]) + + def get_shared_y_axes(self): + """Return an immutable view on the shared y-axes Grouper.""" + return cbook.GrouperView(self._shared_axes["y"]) + + def label_outer(self, remove_inner_ticks=False): + """ + Only show "outer" labels and tick labels. + + x-labels are only kept for subplots on the last row (or first row, if + labels are on the top side); y-labels only for subplots on the first + column (or last column, if labels are on the right side). + + Parameters + ---------- + remove_inner_ticks : bool, default: False + If True, remove the inner ticks as well (not only tick labels). + + .. versionadded:: 3.8 + """ + self._label_outer_xaxis(skip_non_rectangular_axes=False, + remove_inner_ticks=remove_inner_ticks) + self._label_outer_yaxis(skip_non_rectangular_axes=False, + remove_inner_ticks=remove_inner_ticks) + + def _get_subplotspec_with_optional_colorbar(self): + """ + Return the subplotspec for this Axes, except that if this Axes has been + moved to a subgridspec to make room for a colorbar, then return the + subplotspec that encloses both this Axes and the colorbar Axes. + """ + ss = self.get_subplotspec() + if any(cax.get_subplotspec() for cax in self._colorbars): + ss = ss.get_gridspec()._subplot_spec + return ss + + def _label_outer_xaxis(self, *, skip_non_rectangular_axes, + remove_inner_ticks=False): + # see documentation in label_outer. + if skip_non_rectangular_axes and not isinstance(self.patch, + mpl.patches.Rectangle): + return + ss = self._get_subplotspec_with_optional_colorbar() + if ss is None: + return + label_position = self.xaxis.get_label_position() + if not ss.is_first_row(): # Remove top label/ticklabels/offsettext. + if label_position == "top": + self.set_xlabel("") + top_kw = {'top': False} if remove_inner_ticks else {} + self.xaxis.set_tick_params( + which="both", labeltop=False, **top_kw) + if self.xaxis.offsetText.get_position()[1] == 1: + self.xaxis.offsetText.set_visible(False) + if not ss.is_last_row(): # Remove bottom label/ticklabels/offsettext. + if label_position == "bottom": + self.set_xlabel("") + bottom_kw = {'bottom': False} if remove_inner_ticks else {} + self.xaxis.set_tick_params( + which="both", labelbottom=False, **bottom_kw) + if self.xaxis.offsetText.get_position()[1] == 0: + self.xaxis.offsetText.set_visible(False) + + def _label_outer_yaxis(self, *, skip_non_rectangular_axes, + remove_inner_ticks=False): + # see documentation in label_outer. + if skip_non_rectangular_axes and not isinstance(self.patch, + mpl.patches.Rectangle): + return + ss = self._get_subplotspec_with_optional_colorbar() + if ss is None: + return + label_position = self.yaxis.get_label_position() + if not ss.is_first_col(): # Remove left label/ticklabels/offsettext. + if label_position == "left": + self.set_ylabel("") + left_kw = {'left': False} if remove_inner_ticks else {} + self.yaxis.set_tick_params( + which="both", labelleft=False, **left_kw) + if self.yaxis.offsetText.get_position()[0] == 0: + self.yaxis.offsetText.set_visible(False) + if not ss.is_last_col(): # Remove right label/ticklabels/offsettext. + if label_position == "right": + self.set_ylabel("") + right_kw = {'right': False} if remove_inner_ticks else {} + self.yaxis.set_tick_params( + which="both", labelright=False, **right_kw) + if self.yaxis.offsetText.get_position()[0] == 1: + self.yaxis.offsetText.set_visible(False) + + def set_forward_navigation_events(self, forward): + """ + Set how pan/zoom events are forwarded to Axes below this one. + + Parameters + ---------- + forward : bool or "auto" + Possible values: + + - True: Forward events to other axes with lower or equal zorder. + - False: Events are only executed on this axes. + - "auto": Default behaviour (*True* for axes with an invisible + patch and *False* otherwise) + + See Also + -------- + matplotlib.axes.Axes.set_navigate + + """ + self._forward_navigation_events = forward + + def get_forward_navigation_events(self): + """Get how pan/zoom events are forwarded to Axes below this one.""" + return self._forward_navigation_events + + +def _draw_rasterized(figure, artists, renderer): + """ + A helper function for rasterizing the list of artists. + + The bookkeeping to track if we are or are not in rasterizing mode + with the mixed-mode backends is relatively complicated and is now + handled in the matplotlib.artist.allow_rasterization decorator. + + This helper defines the absolute minimum methods and attributes on a + shim class to be compatible with that decorator and then uses it to + rasterize the list of artists. + + This is maybe too-clever, but allows us to reuse the same code that is + used on normal artists to participate in the "are we rasterizing" + accounting. + + Please do not use this outside of the "rasterize below a given zorder" + functionality of Axes. + + Parameters + ---------- + figure : matplotlib.figure.Figure + The figure all of the artists belong to (not checked). We need this + because we can at the figure level suppress composition and insert each + rasterized artist as its own image. + + artists : List[matplotlib.artist.Artist] + The list of Artists to be rasterized. These are assumed to all + be in the same Figure. + + renderer : matplotlib.backendbases.RendererBase + The currently active renderer + + Returns + ------- + None + + """ + class _MinimalArtist: + def get_rasterized(self): + return True + + def get_agg_filter(self): + return None + + def __init__(self, figure, artists): + self.figure = figure + self.artists = artists + + def get_figure(self, root=False): + if root: + return self.figure.get_figure(root=True) + else: + return self.figure + + @martist.allow_rasterization + def draw(self, renderer): + for a in self.artists: + a.draw(renderer) + + return _MinimalArtist(figure, artists).draw(renderer) diff --git a/shared/package-files/79/7976dc5e214633f224aa07a56b5ccdd448252198a567175ec98007c19530535e/blob b/shared/package-files/79/7976dc5e214633f224aa07a56b5ccdd448252198a567175ec98007c19530535e/blob new file mode 100644 index 0000000000000000000000000000000000000000..35164c499520db75db623591e1af6cf3027b56f5 --- /dev/null +++ b/shared/package-files/79/7976dc5e214633f224aa07a56b5ccdd448252198a567175ec98007c19530535e/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API ::std::tuple linalg_lu_factor_ex(const at::Tensor & A, bool pivot=true, bool check_errors=false); +TORCH_API ::std::tuple linalg_lu_factor_ex_out(at::Tensor & LU, at::Tensor & pivots, at::Tensor & info, const at::Tensor & A, bool pivot=true, bool check_errors=false); +TORCH_API ::std::tuple linalg_lu_factor_ex_outf(const at::Tensor & A, bool pivot, bool check_errors, at::Tensor & LU, at::Tensor & pivots, at::Tensor & info); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/79/7977284ccf2f2ae878b509e5f769707436aab2c181e86f5ba121e1dc53829278/blob b/shared/package-files/79/7977284ccf2f2ae878b509e5f769707436aab2c181e86f5ba121e1dc53829278/blob new file mode 100644 index 0000000000000000000000000000000000000000..9ce65f91116f68332d1c16e21319e965541d0d73 Binary files /dev/null and b/shared/package-files/79/7977284ccf2f2ae878b509e5f769707436aab2c181e86f5ba121e1dc53829278/blob differ diff --git a/shared/package-files/79/7978f92f93163ed40782b1cfb09dfaaaaae6047a9cb7d528ba38c90af1e71759/blob b/shared/package-files/79/7978f92f93163ed40782b1cfb09dfaaaaae6047a9cb7d528ba38c90af1e71759/blob new file mode 100644 index 0000000000000000000000000000000000000000..429764e67eccc7855d363da20d432fdb45e66971 --- /dev/null +++ b/shared/package-files/79/7978f92f93163ed40782b1cfb09dfaaaaae6047a9cb7d528ba38c90af1e71759/blob @@ -0,0 +1,36 @@ +from __future__ import annotations + +from typing import Any + +import numpy as np + +AR_LIKE_b = [True, True, True] +AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)] +AR_LIKE_i = [1, 2, 3] +AR_LIKE_f = [1.0, 2.0, 3.0] +AR_LIKE_c = [1j, 2j, 3j] +AR_LIKE_U = ["1", "2", "3"] + +OUT_f: np.ndarray[Any, np.dtype[np.float64]] = np.empty(3, dtype=np.float64) +OUT_c: np.ndarray[Any, np.dtype[np.complex128]] = np.empty(3, dtype=np.complex128) + +np.einsum("i,i->i", AR_LIKE_b, AR_LIKE_b) +np.einsum("i,i->i", AR_LIKE_u, AR_LIKE_u) +np.einsum("i,i->i", AR_LIKE_i, AR_LIKE_i) +np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f) +np.einsum("i,i->i", AR_LIKE_c, AR_LIKE_c) +np.einsum("i,i->i", AR_LIKE_b, AR_LIKE_i) +np.einsum("i,i,i,i->i", AR_LIKE_b, AR_LIKE_u, AR_LIKE_i, AR_LIKE_c) + +np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f, dtype="c16") +np.einsum("i,i->i", AR_LIKE_U, AR_LIKE_U, dtype=bool, casting="unsafe") +np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f, out=OUT_c) +np.einsum("i,i->i", AR_LIKE_U, AR_LIKE_U, dtype=int, casting="unsafe", out=OUT_f) + +np.einsum_path("i,i->i", AR_LIKE_b, AR_LIKE_b) +np.einsum_path("i,i->i", AR_LIKE_u, AR_LIKE_u) +np.einsum_path("i,i->i", AR_LIKE_i, AR_LIKE_i) +np.einsum_path("i,i->i", AR_LIKE_f, AR_LIKE_f) +np.einsum_path("i,i->i", AR_LIKE_c, AR_LIKE_c) +np.einsum_path("i,i->i", AR_LIKE_b, AR_LIKE_i) +np.einsum_path("i,i,i,i->i", AR_LIKE_b, AR_LIKE_u, AR_LIKE_i, AR_LIKE_c) diff --git a/shared/package-files/79/797956d3d4fb6d708a3884c6ef59bd081e95920f35156246161df955c3e018c4/blob b/shared/package-files/79/797956d3d4fb6d708a3884c6ef59bd081e95920f35156246161df955c3e018c4/blob new file mode 100644 index 0000000000000000000000000000000000000000..76f6eda52027e41d81b2e6ee5ec66afb6e9d0d3d --- /dev/null +++ b/shared/package-files/79/797956d3d4fb6d708a3884c6ef59bd081e95920f35156246161df955c3e018c4/blob @@ -0,0 +1,59 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._constants import GET_CATEGORIES_DEPRECATION_TEMPLATE +from narwhals._exceptions import issue_deprecation_warning +from narwhals._expression_parsing import ExprKind, ExprNode +from narwhals._utils import Version +from narwhals.dtypes import String + +if TYPE_CHECKING: + from narwhals.expr import Expr + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprCatNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def get_categories(self) -> ExprT: + """Get unique categories from column. + + Warning: + This is deprecated and it will be removed in a future version, as Polars + removed its own `cat.get_categories`. + To get the distinct values present in a Categorical column, use + [`Expr.unique`][narwhals.Expr.unique]. + For the fixed category list of an Enum, use its `dtype.categories`. + + Until it is removed, it is implemented as + `unique().drop_nulls().cast(String)`, so it returns only the values which + are actually present, in no guaranteed order. + + Note: + In `narwhals.stable.v1` and `narwhals.stable.v2` this stays available, and + keeps dispatching to each backend's native implementation. + + Examples: + >>> import pandas as pd + >>> import narwhals.stable.v1 as nw + >>> df_native = pd.DataFrame( + ... {"fruits": ["apple", "mango", "mango"]}, dtype="category" + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("fruits").cat.get_categories()).to_native() + fruits + 0 apple + 1 mango + """ + if self._expr._version in {Version.V1, Version.V2}: + return self._expr._append_node( + ExprNode(ExprKind.FILTRATION, "cat.get_categories") + ) + + issue_deprecation_warning( + GET_CATEGORIES_DEPRECATION_TEMPLATE.format(cls="Expr"), _version="2.26.0" + ) + return self._expr.unique().drop_nulls().cast(String) diff --git a/shared/package-files/79/7979b8ffd96551e4fe6220de93782a94d2e17a0dd5814ca0a7b0f191431ba7d0/blob b/shared/package-files/79/7979b8ffd96551e4fe6220de93782a94d2e17a0dd5814ca0a7b0f191431ba7d0/blob new file mode 100644 index 0000000000000000000000000000000000000000..f55fc6bd109dd49263b7934ad802301bdb4cbc3c --- /dev/null +++ b/shared/package-files/79/7979b8ffd96551e4fe6220de93782a94d2e17a0dd5814ca0a7b0f191431ba7d0/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_functional_assert_scalar(Scalar self, str assert_msg, Tensor dep_token) -> Tensor +inline at::Tensor _functional_assert_scalar(const at::Scalar & self, c10::string_view assert_msg, const at::Tensor & dep_token) { + return at::_ops::_functional_assert_scalar::call(self, assert_msg, dep_token); +} + +} diff --git a/shared/package-files/79/7979ef9b348acc8659cc1cfa64527ebcc37244082a6c2881f803b92095ee5323/blob b/shared/package-files/79/7979ef9b348acc8659cc1cfa64527ebcc37244082a6c2881f803b92095ee5323/blob new file mode 100644 index 0000000000000000000000000000000000000000..7db28d41ac65a8669f9ae2f6ed231304091df940 --- /dev/null +++ b/shared/package-files/79/7979ef9b348acc8659cc1cfa64527ebcc37244082a6c2881f803b92095ee5323/blob @@ -0,0 +1,9 @@ +''' +The compiler is not implemented in the simulator. This module provides a stub +to allow tests to import successfully. +''' + +compile = None +compile_for_current_device = None +compile_ptx = None +compile_ptx_for_current_device = None diff --git a/shared/package-files/79/797cd05f1964d57c4c6c248ac7f7ea6a38019ada32a9ab7e6c28d060f87b03de/blob b/shared/package-files/79/797cd05f1964d57c4c6c248ac7f7ea6a38019ada32a9ab7e6c28d060f87b03de/blob new file mode 100644 index 0000000000000000000000000000000000000000..2aaa55805ed5305d9f7a55db870db7fd398ae751 Binary files /dev/null and b/shared/package-files/79/797cd05f1964d57c4c6c248ac7f7ea6a38019ada32a9ab7e6c28d060f87b03de/blob differ diff --git a/shared/package-files/79/797eb6794feef2a4a0da3ee47f5a905366ea7c8aedb0ed499bf26422bc1fd0bb/blob b/shared/package-files/79/797eb6794feef2a4a0da3ee47f5a905366ea7c8aedb0ed499bf26422bc1fd0bb/blob new file mode 100644 index 0000000000000000000000000000000000000000..88b3b769d246f5f2f30e10b1b4a5ad4fc8c30512 --- /dev/null +++ b/shared/package-files/79/797eb6794feef2a4a0da3ee47f5a905366ea7c8aedb0ed499bf26422bc1fd0bb/blob @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API result_type_Tensor { + using schema = at::ScalarType (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::result_type") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "result_type.Tensor(Tensor tensor, Tensor other) -> ScalarType") + static at::ScalarType call(const at::Tensor & tensor, const at::Tensor & other); + static at::ScalarType redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & tensor, const at::Tensor & other); +}; + +struct TORCH_API result_type_Scalar { + using schema = at::ScalarType (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::result_type") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "result_type.Scalar(Tensor tensor, Scalar other) -> ScalarType") + static at::ScalarType call(const at::Tensor & tensor, const at::Scalar & other); + static at::ScalarType redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & tensor, const at::Scalar & other); +}; + +struct TORCH_API result_type_Scalar_Tensor { + using schema = at::ScalarType (const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::result_type") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "result_type.Scalar_Tensor(Scalar scalar, Tensor tensor) -> ScalarType") + static at::ScalarType call(const at::Scalar & scalar, const at::Tensor & tensor); + static at::ScalarType redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & scalar, const at::Tensor & tensor); +}; + +struct TORCH_API result_type_Scalar_Scalar { + using schema = at::ScalarType (const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::result_type") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "result_type.Scalar_Scalar(Scalar scalar1, Scalar scalar2) -> ScalarType") + static at::ScalarType call(const at::Scalar & scalar1, const at::Scalar & scalar2); + static at::ScalarType redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & scalar1, const at::Scalar & scalar2); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/79/7987ec592cc10e89b91cac8ea6deb1b81e50e7898e3f5b748986025b3299cb25/blob b/shared/package-files/79/7987ec592cc10e89b91cac8ea6deb1b81e50e7898e3f5b748986025b3299cb25/blob new file mode 100644 index 0000000000000000000000000000000000000000..bf8d0ac16e11cd4a9486cb5feb01163ee1f09cf2 --- /dev/null +++ b/shared/package-files/79/7987ec592cc10e89b91cac8ea6deb1b81e50e7898e3f5b748986025b3299cb25/blob @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::vector _foreach_mul(at::TensorList self, const at::Scalar & scalar); +TORCH_API void _foreach_mul_(at::TensorList self, const at::Scalar & scalar); +TORCH_API ::std::vector _foreach_mul(at::TensorList self, at::TensorList other); +TORCH_API void _foreach_mul_(at::TensorList self, at::TensorList other); +TORCH_API ::std::vector _foreach_mul(at::TensorList self, at::ArrayRef scalars); +TORCH_API void _foreach_mul_(at::TensorList self, at::ArrayRef scalars); +TORCH_API ::std::vector _foreach_mul(at::TensorList self, const at::Tensor & other); +TORCH_API void _foreach_mul_(at::TensorList self, const at::Tensor & other); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/79/79881ac42d4a6d3b732d50014e2e6866cee437387bb5177bbf47e7d4e336ea35/blob b/shared/package-files/79/79881ac42d4a6d3b732d50014e2e6866cee437387bb5177bbf47e7d4e336ea35/blob new file mode 100644 index 0000000000000000000000000000000000000000..4470aa5a8840cc84915f7ecad14610b87ec8291d --- /dev/null +++ b/shared/package-files/79/79881ac42d4a6d3b732d50014e2e6866cee437387bb5177bbf47e7d4e336ea35/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79881ac42d4a6d3b732d50014e2e6866cee437387bb5177bbf47e7d4e336ea35 +size 549649 diff --git a/shared/package-files/79/79890b8c8893c7d8971da00a7505e918159ae269a867466e42548b1b14aee775/blob b/shared/package-files/79/79890b8c8893c7d8971da00a7505e918159ae269a867466e42548b1b14aee775/blob new file mode 100644 index 0000000000000000000000000000000000000000..77cf165a0fc303a2ee425dff7083889908dcf887 --- /dev/null +++ b/shared/package-files/79/79890b8c8893c7d8971da00a7505e918159ae269a867466e42548b1b14aee775/blob @@ -0,0 +1,843 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * Original header with Copyright information appears below. + */ + +/* Implementation of Wright's generalized Bessel function Phi, see + * https://dlmf.nist.gov/10.46.E1 + * + * Copyright: Christian Lorentzen + * + * Distributed under the same license as SciPy + * + * + * Implementation Overview: + * + * First, different functions are implemented valid for certain domains of the + * three arguments. + * Finally they are put together in wright_bessel. See the docstring of + * that function for more details. + */ + +#pragma once + +#include "cephes/lanczos.h" +#include "cephes/polevl.h" +#include "cephes/rgamma.h" +#include "config.h" +#include "digamma.h" +#include "error.h" + +namespace xsf { + +namespace detail { + // rgamma_zero: smallest value x for which rgamma(x) == 0 as x gets large + constexpr double rgamma_zero = 178.47241115886637; + + XSF_HOST_DEVICE inline double exp_rgamma(double x, double y) { + /* Compute exp(x) / gamma(y) = exp(x) * rgamma(y). + * + * This helper function avoids overflow by using the lanczos + * approximation of the gamma function. + */ + return std::exp(x + (1 - std::log(y + cephes::lanczos_g - 0.5)) * (y - 0.5)) / + cephes::lanczos_sum_expg_scaled(y); + } + + XSF_HOST_DEVICE inline double wb_series(double a, double b, double x, unsigned int nstart, unsigned int nstop) { + /* 1. Taylor series expansion in x=0 for x <= 1. + * + * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b) + * + * Note that every term, and therefore also Phi(a, b, x) is + * monotone decreasing with increasing a or b. + */ + double xk_k = std::pow(x, nstart) * cephes::rgamma(nstart + 1); // x^k/k! + double res = xk_k * cephes::rgamma(nstart * a + b); + // term k=nstart+1, +2, +3, ... + if (nstop > nstart) { + // series expansion until term k such that a*k+b <= rgamma_zero + unsigned int k_max = std::floor((rgamma_zero - b) / a); + if (nstop > k_max) { + nstop = k_max; + } + for (unsigned int k = nstart + 1; k < nstop; k++) { + xk_k *= x / k; + res += xk_k * cephes::rgamma(a * k + b); + } + } + return res; + } + + template + XSF_HOST_DEVICE inline double wb_large_a(double a, double b, double x, int n) { + /* 2. Taylor series expansion in x=0, for large a. + * + * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b) + * + * Use Stirling's formula to find k=k_max, the maximum term. + * Then use n terms of Taylor series around k_max. + */ + int k_max = static_cast(std::pow(std::pow(a, -a) * x, 1.0 / (1 + a))); + + int nstart = k_max - n / 2; + if (nstart < 0) { + nstart = 0; + } + + double res = 0; + double lnx = std::log(x); + // For numerical stability, we factor out the maximum term exp(..) with k=k_max + // but only if it is larger than 0. + double max_exponent = std::fmax(0, k_max * lnx - cephes::lgam(k_max + 1) - cephes::lgam(a * k_max + b)); + for (int k = nstart; k < nstart + n; k++) { + res += std::exp(k * lnx - cephes::lgam(k + 1) - cephes::lgam(a * k + b) - max_exponent); + } + + if (!log_wb) { + res *= std::exp(max_exponent); + } else { + // logarithm of Wright's function + res = max_exponent + std::log(res); + } + return res; + } + + template + XSF_HOST_DEVICE inline double wb_small_a(double a, double b, double x, int order) { + /* 3. Taylor series in a=0 up to order 5, for tiny a and not too large x + * + * Phi(a, b, x) = exp(x)/Gamma(b) + * (1 - a*x * Psi(b) + a^2/2*x*(1+x) * (Psi(b)^2 - Psi'(b) + + ... ) + + O(a^6)) + * + * where Psi is the digamma function. + * + * Parameter order takes effect only when b > 1e-3 and 2 <= order <= 5, + * otherwise it defaults to 2, or if b <= 1e-3, to 5. The lower order is, + * the fewer polygamma functions have to be computed. + * + * Call: python _precompute/wright_bessel.py 1 + * + * For small b, i.e. b <= 1e-3, cancellation of poles of digamma(b)/Gamma(b) + * and polygamma needs to be carried out => series expansion in a=0 to order 5 + * and in b=0 to order 4. + * Call: python _precompute/wright_bessel.py 2 + */ + double A[6]; // coefficients of a^k (1, -x * Psi(b), ...) + double B[6]; // powers of b^k/k! or terms in polygamma functions + constexpr double C[5] = { // coefficients of a^k1 * b^k2 + 1.0000000000000000, // C[0] + 1.1544313298030657, // C[1] + -3.9352684291215233, // C[2] + -1.0080632408182857, // C[3] + 19.984633365874979, // C[4] + }; + double X[6] = { // polynomials in x; + 1, // X[0] + x, // X[1] + x * (x + 1), // X[2] + x * (x * (x + 3) + 1), // X[3] + x * (x * (x * (x + 6) + 7) + 1), // X[4] + x * (x * (x * (x * (x + 10) + 25) + 15) + 1), // X[5] + }; + double res; + + if (b <= 1E-3) { + /* Series expansion of both a and b up to order 5: + * M_PI = pi + * M_EG = Euler Gamma aka Euler Mascheroni constant + * M_Z3 = zeta(3) + * C[0] = 1 + * C[1] = 2*M_EG + * C[2] = 3*M_EG^2 - M_PI^2/2 + * C[3] = 4*M_EG^3 - 2*M_EG*M_PI^2 + 8*M_Z3 + * C[4] = 5*M_EG^4 - 5*M_EG^2*M_PI^2 + 40*M_EG*M_Z3 + M_PI^4/12 + */ + B[0] = 1.; + for (int k = 1; k < 5; k++) { + B[k] = b / k * B[k - 1]; + } + // Note that polevl assumes inverse ordering => A[5] = 0th term + A[5] = cephes::rgamma(b); + A[4] = X[1] * (C[0] + C[1] * b + C[2] * B[2] + C[3] * B[3] + C[4] * B[4]); + A[3] = X[2] / 2. * (C[1] + C[2] * b + C[3] * B[2] + C[4] * B[3]); + A[2] = X[3] / 6. * (C[2] + C[3] * b + C[4] * B[2]); + A[1] = X[4] / 24. * (C[3] + C[4] * b); + A[0] = X[5] / 120. * C[4]; + // res = exp(x) * (A[5] + A[4] * a + A[3] * a^2 + A[2] * a^3 + ...) + if (!log_wb) { + res = exp(x) * cephes::polevl(a, A, 5); + } else { + // logarithm of Wright's function + res = x + std::log(cephes::polevl(a, A, 5)); + } + } else { + /* Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5) + * A[n] = a^n/n! + * But here, we repurpose A[n] = X[n] * B[n] / n! + * Note that polevl assumes inverse ordering => A[order] = 0th term */ + double dg = digamma(b); + // pg1 = polygamma(1, b) + double pg1 = cephes::zeta(2, b); + if (order <= 2) { + res = 1 + a * x * (-dg + 0.5 * a * (1 + x) * (dg * dg - pg1)); + } else { + if (order > 5) { + order = 5; + } + // pg2 = polygamma(2, b) + double pg2 = -2 * cephes::zeta(3, b); + B[0] = 1; + B[1] = -dg; + B[2] = dg * dg - pg1; + B[3] = (-dg * dg + 3 * pg1) * dg - pg2; + A[order] = 1; + A[order - 1] = X[1] * B[1]; + A[order - 2] = X[2] * B[2] / 2.; + A[order - 3] = X[3] * B[3] / 6.; + if (order >= 4) { + // double pg3 = polygamma(3, b) + double pg3 = 6 * cephes::zeta(4, b); + B[4] = ((dg * dg - 6 * pg1) * dg + 4 * pg2) * dg + 3 * pg1 * pg1 - pg3; + A[order - 4] = X[4] * B[4] / 24.; + if (order >= 5) { + // pg4 = polygamma(4, b) + double pg4 = -24 * cephes::zeta(5, b); + B[5] = + ((((-dg * dg + 10 * pg1) * dg - 10 * pg2) * dg - 15 * pg1 * pg1 + 5 * pg3) * dg + + 10 * pg1 * pg2 - pg4); + A[order - 5] = X[5] * B[5] / 120.; + } + } + res = cephes::polevl(a, A, order); + } + // res *= exp(x) * rgamma(b) + if (!log_wb) { + res *= exp_rgamma(x, b); + } else { + // logarithm of Wright's function + res = x - cephes::lgam(b) + std::log(res); + } + } + return res; + } + + template + XSF_HOST_DEVICE inline double wb_asymptotic(double a, double b, double x) { + /* 4. Asymptotic expansion for large x up to order 8 + * + * Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k + * + * with Z = (a*x)^(1/(1+a)). + * Call: python _precompute/wright_bessel.py 3 + */ + double A[15]; // powers of a + double B[17]; // powers of b + double Ap1[9]; // powers of (1+a) + double C[9]; // coefficients of asymptotic series a_k + + A[0] = 1.; + B[0] = 1.; + Ap1[0] = 1.; + for (int k = 1; k < 15; k++) { + A[k] = A[k - 1] * a; + } + for (int k = 1; k < 17; k++) { + B[k] = B[k - 1] * b; + } + for (int k = 1; k < 9; k++) { + Ap1[k] = Ap1[k - 1] * (1 + a); + } + + C[0] = 1. / std::sqrt(2. * M_PI * Ap1[1]); + + C[1] = C[0] / (24 * Ap1[1]); + C[1] *= (2 * a + 1) * (2 + a) - 12 * b * (1 + a - b); + + C[2] = C[0] / (1152 * Ap1[2]); + C[2] *= + (144 * B[4] - 96 * B[3] * (5 * a + 1) + 24 * B[2] * (20 * A[2] + 5 * a - 4) - + 24 * b * Ap1[1] * (6 * A[2] - 7 * a - 2) + (a + 2) * (2 * a + 1) * (2 * A[2] - 19 * a + 2)); + + C[3] = C[0] / (414720 * Ap1[3]); + C[3] *= + (8640 * B[6] - 8640 * B[5] * (7 * a - 1) + 10800 * B[4] * (14 * A[2] - 7 * a - 2) - + 1440 * B[3] * (112 * A[3] - 147 * A[2] - 63 * a + 8) + + 180 * B[2] * (364 * A[4] - 1288 * A[3] - 567 * A[2] + 392 * a + 76) - + 180 * b * Ap1[1] * (20 * A[4] - 516 * A[3] + 417 * A[2] + 172 * a - 12) - + (a + 2) * (2 * a + 1) * (556 * A[4] + 1628 * A[3] - 9093 * A[2] + 1628 * a + 556)); + + C[4] = C[0] / (39813120 * Ap1[4]); + C[4] *= + (103680 * B[8] - 414720 * B[7] * (3 * a - 1) + 725760 * B[6] * a * (8 * a - 7) - + 48384 * B[5] * (274 * A[3] - 489 * A[2] + 39 * a + 26) + + 30240 * B[4] * (500 * A[4] - 1740 * A[3] + 495 * A[2] + 340 * a - 12) - + 2880 * B[3] * (2588 * A[5] - 19780 * A[4] + 14453 * A[3] + 9697 * A[2] - 1892 * a - 404) + + 48 * B[2] * + (11488 * A[6] - 547836 * A[5] + 1007484 * A[4] + 593353 * A[3] - 411276 * A[2] - 114396 * a + 4288) + + 48 * b * Ap1[1] * + (7784 * A[6] + 48180 * A[5] - 491202 * A[4] + 336347 * A[3] + 163734 * A[2] - 28908 * a - 5560) - + (a + 2) * (2 * a + 1) * + (4568 * A[6] - 226668 * A[5] - 465702 * A[4] + 2013479 * A[3] - 465702 * A[2] - 226668 * a + 4568)); + + C[5] = C[0] / (6688604160. * Ap1[5]); + C[5] *= + (1741824 * B[10] - 2903040 * B[9] * (11 * a - 5) + 2177280 * B[8] * (110 * A[2] - 121 * a + 14) - + 580608 * B[7] * (1628 * A[3] - 3333 * A[2] + 1023 * a + 52) + + 169344 * B[6] * (12364 * A[4] - 43648 * A[3] + 26763 * A[2] + 1232 * a - 788) - + 24192 * B[5] * (104852 * A[5] - 646624 * A[4] + 721391 * A[3] - 16841 * A[2] - 74096 * a + 148) + + 2016 * B[4] * + (710248 * A[6] - 8878716 * A[5] + 17928834 * A[4] - 3333407 * A[3] - 4339566 * A[2] + 287364 * a + + 89128) - + 1344 * B[3] * + (87824 * A[7] - 7150220 * A[6] + 29202756 * A[5] - 15113527 * A[4] - 14223011 * A[3] + 3462492 * A[2] + + 1137092 * a - 18896) - + 84 * B[2] * + (1690480 * A[8] + 14139136 * A[7] - 232575464 * A[6] + 296712592 * A[5] + 215856619 * A[4] - + 152181392 * A[3] - 47718440 * A[2] + 5813632 * a + 943216) + + 84 * b * Ap1[1] * + (82224 * A[8] - 5628896 * A[7] - 26466520 * A[6] + 168779208 * A[5] - 104808005 * A[4] - + 56259736 * A[3] + 15879912 * A[2] + 4020640 * a - 63952) + + (a + 2) * (2 * a + 1) * + (2622064 * A[8] + 12598624 * A[7] - 167685080 * A[6] - 302008904 * A[5] + 1115235367. * A[4] - + 302008904 * A[3] - 167685080 * A[2] + 12598624 * a + 2622064)); + + C[6] = C[0] / (4815794995200. * Ap1[6]); + C[6] *= + (104509440 * B[12] - 209018880 * B[11] * (13 * a - 7) + 574801920 * B[10] * (52 * A[2] - 65 * a + 12) - + 63866880 * B[9] * (2834 * A[3] - 6279 * A[2] + 2769 * a - 134) + + 23950080 * B[8] * (27404 * A[4] - 98228 * A[3] + 78663 * A[2] - 10868 * a - 1012) - + 13685760 * B[7] * (105612 * A[5] - 599196 * A[4] + 791843 * A[3] - 224913 * A[2] - 27612 * a + 4540) + + 2661120 * B[6] * + (693680 * A[6] - 6473532 * A[5] + 13736424 * A[4] - 7047469 * A[3] - 723840 * A[2] + 471588 * a + 7376 + ) - + 2661120 * B[5] * + (432536 * A[7] - 7850804 * A[6] + 27531114 * A[5] - 24234457 * A[4] - 703001 * A[3] + 3633474 * A[2] - + 36244 * a - 45128) + + 166320 * B[4] * + (548912 * A[8] - 75660832 * A[7] + 502902712 * A[6] - 764807992 * A[5] + 91248287 * A[4] + + 217811464 * A[3] - 20365384 * A[2] - 9776416 * a + 37936) + + 10080 * B[3] * + (18759728 * A[9] + 165932208 * A[8] - 4710418440. * A[7] + 13686052536. * A[6] - 5456818809. * A[5] - + 6834514245. * A[4] + 1919299512. * A[3] + 752176152 * A[2] - 45661200 * a - 8616848) - + 360 * B[2] * + (32743360 * A[10] - 3381871792. * A[9] - 21488827776. * A[8] + 200389923864. * A[7] - + 198708005340. * A[6] - 171633799779. * A[5] + 123124874028. * A[4] + 40072774872. * A[3] - + 9137993280. * A[2] - 1895843248. * a + 18929728) - + 360 * b * Ap1[1] * + (57685408 * A[10] + 406929456 * A[9] - 6125375760. * A[8] - 27094918920. * A[7] + + 128752249410. * A[6] - 74866710561. * A[5] - 42917416470. * A[4] + 16256951352. * A[3] + + 4375268400. * A[2] - 316500688 * a - 47197152) + + (a + 2) * (2 * a + 1) * + (167898208 * A[10] - 22774946512. * A[9] - 88280004528. * A[8] + 611863976472. * A[7] + + 1041430242126. * A[6] - 3446851131657. * A[5] + 1041430242126. * A[4] + 611863976472. * A[3] - + 88280004528. * A[2] - 22774946512. * a + 167898208)); + + C[7] = C[0] / (115579079884800. * Ap1[7]); + C[7] *= + (179159040 * B[14] - 1254113280. * B[13] * (5 * a - 3) + 1358622720. * B[12] * (70 * A[2] - 95 * a + 22) - + 905748480 * B[11] * (904 * A[3] - 2109 * A[2] + 1119 * a - 112) + + 1245404160. * B[10] * (3532 * A[4] - 12824 * A[3] + 11829 * A[2] - 2824 * a + 44) - + 59304960 * B[9] * (256820 * A[5] - 1397680 * A[4] + 2025545 * A[3] - 869495 * A[2] + 52000 * a + 8788) + + 14826240 * B[8] * + (2274536 * A[6] - 18601572 * A[5] + 40698318 * A[4] - 28230079 * A[3] + 3916398 * A[2] + 832668 * a - + 65176) - + 59304960 * B[7] * + (760224 * A[7] - 9849164 * A[6] + 32495784 * A[5] - 34813869 * A[4] + 9175207 * A[3] + 1898688 * A[2] - + 469788 * a - 13184) + + 25945920 * B[6] * + (1167504 * A[8] - 28779840 * A[7] + 149752856 * A[6] - 246026112 * A[5] + 111944073 * A[4] + + 18341600 * A[3] - 12131496 * A[2] - 274368 * a + 102800) - + 157248 * B[5] * + (12341872 * A[9] - 3122991216. * A[8] + 29900054232. * A[7] - 78024816720. * A[6] + + 58914656739. * A[5] + 4637150811. * A[4] - 11523402480. * A[3] + 236218968 * A[2] + 337923216 * a + + 1592048) - + 28080 * B[4] * + (265154912 * A[10] + 2276098704. * A[9] - 105569461008. * A[8] + 496560666360. * A[7] - + 627891462858. * A[6] + 41935358025. * A[5] + 203913875814. * A[4] - 23984801544. * A[3] - + 13869306000. * A[2] + 372786832 * a + 103532640) + + 1440 * B[3] * + (310292864 * A[11] - 55169117872. * A[10] - 358957020112. * A[9] + 5714152556088. * A[8] - + 13241597459352. * A[7] + 4220720097141. * A[6] + 6845418090249. * A[5] - 2129559215808. * A[4] - + 909225098472. * A[3] + 107518582576. * A[2] + 25619444368. * a - 113832704) + + 12 * B[2] * + (135319651136. * A[12] + 1119107842176. * A[11] - 22193518174320. * A[10] - 133421793595520. * A[9] + + 860103051087996. * A[8] - 703353374803080. * A[7] - 704240127687381. * A[6] + + 513111704637960. * A[5] + 166909061348316. * A[4] - 57671564069120. * A[3] - 12453426246000. * A[2] + + 695901207936. * a + 93786157376.) - + 12 * b * Ap1[1] * + (4365353408. * A[12] - 720248637504. * A[11] - 4222331152560. * A[10] + 29413934270560. * A[9] + + 132123980710980. * A[8] - 511247376962820. * A[7] + 283403639131779. * A[6] + + 170415792320940. * A[5] - 79274388426588. * A[4] - 21009953050400. * A[3] + 3284035340880. * A[2] + + 589294339776. * a - 3693760576.) - + (a + 2) * (2 * a + 1) * + (34221025984. * A[12] + 226022948160. * A[11] - 5067505612464. * A[10] - 18868361443936. * A[9] + + 86215425028308. * A[8] + 143500920544692. * A[7] - 437682618704613. * A[6] + 143500920544692. * A[5] + + 86215425028308. * A[4] - 18868361443936. * A[3] - 5067505612464. * A[2] + 226022948160. * a + + 34221025984.)); + + C[8] = C[0] / (22191183337881600. * Ap1[8]); + C[8] *= + (2149908480. * B[16] - 5733089280. * B[15] * (17 * a - 11) + + 7166361600. * B[14] * (272 * A[2] - 391 * a + 104) - + 3344302080. * B[13] * (6766 * A[3] - 16371 * A[2] + 9741 * a - 1306) + + 1811496960. * B[12] * (93092 * A[4] - 341564 * A[3] + 344199 * A[2] - 104924 * a + 6308) - + 517570560 * B[11] * + (1626220 * A[5] - 8641508 * A[4] + 13274773 * A[3] - 6952303 * A[2] + 1007420 * a + 5564) + + 284663808 * B[10] * + (9979136 * A[6] - 75766892 * A[5] + 169256148 * A[4] - 136824959 * A[3] + 35714348 * A[2] - + 463692 * a - 293664) - + 1423319040. * B[9] * + (4466648 * A[7] - 49231116 * A[6] + 157507414 * A[5] - 187114257 * A[4] + 78372295 * A[3] - + 4470082 * A[2] - 1913996 * a + 82424) + + 266872320 * B[8] * + (33133136 * A[8] - 564264544 * A[7] + 2618606424. * A[6] - 4491310104. * A[5] + 2853943765. * A[4] - + 374694552 * A[3] - 135365288 * A[2] + 17623968 * a + 696912) - + 2156544 * B[7] * + (2914256144. * A[9] - 93491712432. * A[8] + 664876176984. * A[7] - 1661362937880. * A[6] + + 1563719627313. * A[5] - 382840842843. * A[4] - 115399415640. * A[3] + 34565562936. * A[2] + + 1609337232. * a - 217321904) + + 179712 * B[6] * + (1266018560. * A[10] - 789261834512. * A[9] + 10186841596896. * A[8] - 38877799073352. * A[7] + + 54334425968952. * A[6] - 22529574889533. * A[5] - 5132942328000. * A[4] + 3438377465592. * A[3] + + 84287641248. * A[2] - 72493479440. * a - 807415936) + + 13824 * B[5] * + (156356794976. * A[11] + 1180898077328. * A[10] - 90615270907936. * A[9] + 609258947056248. * A[8] - + 1312655191366722. * A[7] + 885900509321745. * A[6] + 112162151855265. * A[5] - + 212803071513258. * A[4] + 6805217831352. * A[3] + 10051742651296. * A[2] - 55035924848. * a - + 52946379296.) - + 576 * B[4] * + (143943926464. * A[12] - 60115486481856. * A[11] - 376366989757200. * A[10] + + 9534223075576160. * A[9] - 35603777465262396. * A[8] + 39375990156664980. * A[7] - + 868175004137259. * A[6] - 14279180718355020. * A[5] + 1985747535239364. * A[4] + + 1264001337603680. * A[3] - 75972792514320. * A[2] - 23855850572736. * a - 4996648256.) - + 384 * B[3] * + (2038525473856. * A[13] + 16057322146112. * A[12] - 502133360559024. * A[11] - + 2985686417468080. * A[10] + 32418922182093292. * A[9] - 63665380623022452. * A[8] + + 16481208821092575. * A[7] + 34161547357596099. * A[6] - 11490298497454932. * A[5] - + 5117272758337156. * A[4] + 933703210750480. * A[3] + 234855186762000. * A[2] - 7860524600000. * a - + 1226607567040.) + + 96 * B[2] * + (324439754752. * A[14] - 77231415197120. * A[13] - 539102931841856. * A[12] + + 4618258299956336. * A[11] + 28588485529469792. * A[10] - 141383982651179428. * A[9] + + 98783147840417772. * A[8] + 112831723492305801. * A[7] - 83329761150975036. * A[6] - + 26553582937192900. * A[5] + 12469117738765952. * A[4] + 2587165396642160. * A[3] - + 340406368038080. * A[2] - 53659641606080. * a + 219671272960.) + + 96 * b * Ap1[1] * + (1026630779520. * A[14] + 8781958472768. * A[13] - 210659786204384. * A[12] - + 1222283505284208. * A[11] + 5064251967491416. * A[10] + 24013052207628140. * A[9] - + 79710880160087370. * A[8] + 42596558293213227. * A[7] + 26570293386695790. * A[6] - + 14407831324576884. * A[5] - 3617322833922440. * A[4] + 950664948554384. * A[3] + + 172358006894496. * A[2] - 7430887938496. * a - 889746675584.) - + (a + 2) * (2 * a + 1) * + (573840801152. * A[14] - 156998277198784. * A[13] - 898376974770592. * A[12] + + 8622589006459984. * A[11] + 32874204024803560. * A[10] - 111492707520083828. * A[9] - + 184768503480287646. * A[8] + 528612016938984183. * A[7] - 184768503480287646. * A[6] - + 111492707520083828. * A[5] + 32874204024803560. * A[4] + 8622589006459984. * A[3] - + 898376974770592. * A[2] - 156998277198784. * a + 573840801152.)); + + double Z = std::pow(a * x, 1 / Ap1[1]); + double Zp = 1.; + double res = C[0]; + for (int k = 1; k < 9; k++) { + Zp /= Z; + res += (k % 2 == 0 ? 1 : -1) * C[k] * Zp; + } + if (!log_wb) { + res *= std::pow(Z, 0.5 - b) * std::exp(Ap1[1] / a * Z); + } else { + // logarithm of Wright's function + res = std::log(Z) * (0.5 - b) + Ap1[1] / a * Z + std::log(res); + } + return res; + } + + XSF_HOST_DEVICE inline double wb_Kmod(double exp_term, double eps, double a, double b, double x, double r) { + /* Compute integrand Kmod(eps, a, b, x, r) for Gauss-Laguerre quadrature. + * + * K(a, b, x, r+eps) = exp(-r-eps) * Kmod(eps, a, b, x, r) + * + * Kmod(eps, a, b, x, r) = exp(x * (r+eps)^(-a) * cos(pi*a)) * (r+eps)^(-b) + * * sin(x * (r+eps)^(-a) * sin(pi*a) + pi * b) + * + * Note that we additionally factor out exp(exp_term) which helps with large + * terms in the exponent of exp(...) + */ + double x_r_a = x * std::pow(r + eps, -a); + return std::exp(x_r_a * cephes::cospi(a) + exp_term) * std::pow(r + eps, -b) * + std::sin(x_r_a * cephes::sinpi(a) + M_PI * b); + } + + XSF_HOST_DEVICE inline double wb_P(double exp_term, double eps, double a, double b, double x, double phi) { + /* Compute integrand P for Gauss-Legendre quadrature. + * + * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi)) + * * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi) + * + (1-b)*phi) + * + * Note that we additionally factor out exp(exp_term) which helps with large + * terms in the exponent of exp(...) + */ + double x_eps_a = x * std::pow(eps, -a); + return std::exp(eps * std::cos(phi) + x_eps_a * std::cos(a * phi) + exp_term) * + std::cos(eps * std::sin(phi) - x_eps_a * std::sin(a * phi) + (1 - b) * phi); + } + + /* roots of laguerre polynomial of order 50 + * scipy.special.roots_laguerre(50)[0] or + * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[0] */ + constexpr double wb_x_laguerre[] = { + 0.02863051833937908, 0.1508829356769337, 0.3709487815348964, 0.6890906998810479, 1.105625023539913, + 1.620961751102501, 2.23561037591518, 2.950183366641835, 3.765399774405782, 4.682089387559285, + 5.70119757478489, 6.823790909794551, 8.051063669390792, 9.384345308258407, 10.82510903154915, + 12.37498160875746, 14.03575459982991, 15.80939719784467, 17.69807093335025, 19.70414653546156, + 21.83022330657825, 24.0791514444115, 26.45405784125298, 28.95837601193738, 31.59588095662286, + 34.37072996309045, 37.28751061055049, 40.35129757358607, 43.56772026999502, 46.94304399160304, + 50.48426796312992, 54.19924488016862, 58.09682801724853, 62.18705417568891, 66.48137387844482, + 70.99294482661949, 75.73701154772731, 80.73140480247769, 85.99721113646323, 91.55969041253388, + 97.44956561485056, 103.7048912366923, 110.3738588076403, 117.5191982031112, 125.2254701334734, + 133.6120279227287, 142.8583254892541, 153.2603719726036, 165.3856433166825, 180.6983437092145 + }; + /* weights for laguerre polynomial of order 50 + * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[1] */ + constexpr double wb_w_laguerre[] = { + 0.07140472613518988, 0.1471486069645884, 0.1856716275748313, 0.1843853825273539, + 0.1542011686063556, 0.1116853699022688, 0.07105288549019586, 0.04002027691150833, + 0.02005062308007171, 0.008960851203646281, 0.00357811241531566, 0.00127761715678905, + 0.0004080302449837189, 0.0001165288322309724, 2.974170493694165e-5, 6.777842526542028e-6, + 1.37747950317136e-6, 2.492886181720092e-7, 4.010354350427827e-8, 5.723331748141425e-9, + 7.229434249182665e-10, 8.061710142281779e-11, 7.913393099943723e-12, 6.81573661767678e-13, + 5.13242671658949e-14, 3.365624762437814e-15, 1.913476326965035e-16, 9.385589781827253e-18, + 3.950069964503411e-19, 1.417749517827512e-20, 4.309970276292175e-22, 1.101257519845548e-23, + 2.344617755608987e-25, 4.11854415463823e-27, 5.902246763596448e-29, 6.812008916553065e-31, + 6.237449498812102e-33, 4.452440579683377e-35, 2.426862352250487e-37, 9.852971481049686e-40, + 2.891078872318428e-42, 5.906162708112361e-45, 8.01287459750397e-48, 6.789575424396417e-51, + 3.308173010849252e-54, 8.250964876440456e-58, 8.848728128298018e-62, 3.064894889844417e-66, + 1.988708229330752e-71, 6.049567152238783e-78 + }; + /* roots of legendre polynomial of order 50 + * sympy.integrals.quadrature.import gauss_legendre(50, 16)[0] */ + constexpr double wb_x_legendre[] = { + -0.998866404420071, -0.9940319694320907, -0.9853540840480059, -0.9728643851066921, -0.9566109552428079, + -0.9366566189448779, -0.9130785566557919, -0.885967979523613, -0.8554297694299461, -0.8215820708593359, + -0.7845558329003993, -0.7444943022260685, -0.7015524687068223, -0.6558964656854394, -0.6077029271849502, + -0.5571583045146501, -0.5044581449074642, -0.4498063349740388, -0.3934143118975651, -0.3355002454194374, + -0.276288193779532, -0.2160072368760418, -0.1548905899981459, -0.09317470156008614, -0.03109833832718888, + 0.03109833832718888, 0.09317470156008614, 0.1548905899981459, 0.2160072368760418, 0.276288193779532, + 0.3355002454194374, 0.3934143118975651, 0.4498063349740388, 0.5044581449074642, 0.5571583045146501, + 0.6077029271849502, 0.6558964656854394, 0.7015524687068223, 0.7444943022260685, 0.7845558329003993, + 0.8215820708593359, 0.8554297694299461, 0.885967979523613, 0.9130785566557919, 0.9366566189448779, + 0.9566109552428079, 0.9728643851066921, 0.9853540840480059, 0.9940319694320907, 0.998866404420071 + }; + /* weights for legendre polynomial of order 50 + * sympy.integrals.quadrature.import gauss_legendre(50, 16)[1] */ + constexpr double wb_w_legendre[] = { + 0.002908622553155141, 0.006759799195745401, 0.01059054838365097, 0.01438082276148557, 0.01811556071348939, + 0.02178024317012479, 0.02536067357001239, 0.0288429935805352, 0.03221372822357802, 0.03545983561514615, + 0.03856875661258768, 0.0415284630901477, 0.04432750433880328, 0.04695505130394843, 0.04940093844946632, + 0.05165570306958114, 0.05371062188899625, 0.05555774480621252, 0.05718992564772838, 0.05860084981322245, + 0.05978505870426546, 0.06073797084177022, 0.06145589959031666, 0.06193606742068324, 0.06217661665534726, + 0.06217661665534726, 0.06193606742068324, 0.06145589959031666, 0.06073797084177022, 0.05978505870426546, + 0.05860084981322245, 0.05718992564772838, 0.05555774480621252, 0.05371062188899625, 0.05165570306958114, + 0.04940093844946632, 0.04695505130394843, 0.04432750433880328, 0.0415284630901477, 0.03856875661258768, + 0.03545983561514615, 0.03221372822357802, 0.0288429935805352, 0.02536067357001239, 0.02178024317012479, + 0.01811556071348939, 0.01438082276148557, 0.01059054838365097, 0.006759799195745401, 0.002908622553155141 + }; + /* Fitted parameters for optimal choice of eps + * Call: python _precompute/wright_bessel.py 4 */ + constexpr double wb_A[] = {0.41037, 0.30833, 6.9952, 18.382, -2.8566, 2.1122}; + + template + XSF_HOST_DEVICE inline double wright_bessel_integral(double a, double b, double x) { + /* 5. Integral representation + * + * K(a, b, x, r) = exp(-r + x * r^(-a) * cos(pi*a)) * r^(-b) + * * sin(x * r^(-a) * sin(pi*a) + pi * b) + * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi)) + * * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi) + * + (1-b)*phi) + * + * Phi(a, b, x) = 1/pi * int_eps^inf K(a, b, x, r) * dr + * + eps^(1-b)/pi * int_0^pi P(eps, a, b, x, phi) * dphi + * + * for any eps > 0. + * + * Note that P has a misprint in Luchko (2008) Eq. 9, the cos(phi(beta-1)) at + * the end of the first line should be removed and the −sin(phi(beta−1)) at + * the end of the second line should read +(1-b)*phi. + * This integral representation introduced the free parameter eps (from the + * radius of complex contour integration). We try to choose eps such that + * the integrand behaves smoothly. Note that this is quite diffrent from how + * Luchko (2008) deals with eps: he is either looking for the limit eps -> 0 + * or he sets (silently) eps=1. But having the freedom to set eps is much more + * powerful for numerical evaluation. + * + * As K has a leading exp(-r), we factor this out and apply Gauss-Laguerre + * quadrature rule: + * + * int_0^inf K(a, b, x, r+eps) dr = exp(-eps) int_0^inf exp(-r) Kmod(.., r) dr + * + * Note the shift r -> r+eps to have integation from 0 to infinity. + * The integral over P is done via a Gauss-Legendre quadrature rule. + * + * Note: Hardest argument range is large z, large b and small eps. + */ + + /* We use the free choice of eps to make the integral better behaved. + * 1. Concern is oscillatory behaviour of P. Therefore, we'd like to + * make the change in the argument of cosine small, i.e. make arc length + * int_0^phi sqrt(1 + f'(phi)^2) dphi small, with + * f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a*phi) + (1-b)*phi + * Proxy, make |f'(phi)| small. + * 2. Concern is int_0 K ~ int_0 (r+eps)^(-b) .. dr + * This is difficult as r -> 0 for large b. It behaves better for larger + * values of eps. + */ + + // Minimize oscillatory behavoir of P + double eps = + (wb_A[0] * b * std::exp(-0.5 * a) + + std::exp( + wb_A[1] + 1 / (1 + a) * std::log(x) - wb_A[2] * std::exp(-wb_A[3] * a) + + wb_A[4] / (1 + std::exp(wb_A[5] * a)) + )); + + if (a >= 4 && x >= 100) { + eps += 1; // This part is hard to fit + } + + // Large b + if (b >= 8) { + /* Make P small compared to K by setting eps large enough. + * int K ~ exp(-eps) and int P ~ eps^(1-b) */ + eps = std::fmax(eps, std::pow(b, -b / (1. - b)) + 0.1 * b); + } + + // safeguard, higher better for larger a, lower better for tiny a. + eps = std::fmin(eps, 150.); + eps = std::fmax(eps, 3.); // 3 seems to be a pretty good choice in general. + + // We factor out exp(-exp_term) from wb_Kmod and wb_P to avoid overflow of + // exp(..). + double exp_term = 0; + // From the exponent of K: + double r = wb_x_laguerre[50-1]; // largest value of x used in wb_Kmod + double x_r_a = x * std::pow(r + eps, -a); + exp_term = std::fmax(exp_term, x_r_a * cephes::cospi(a)); + // From the exponent of P: + double x_eps_a = x * std::pow(eps, -a); + // phi = 0 => cos(phi) = cos(a * phi) = 1 + exp_term = std::fmax(exp_term, eps + x_eps_a); + // phi = pi => cos(phi) = -1 + exp_term = std::fmax(exp_term, -eps + x_eps_a * cephes::cospi(a)); + + double res1 = 0; + double res2 = 0; + + double y; + for (int k = 0; k < 50; k++) { + res1 += wb_w_laguerre[k] * wb_Kmod(-exp_term, eps, a, b, x, wb_x_laguerre[k]); + // y = (b-a)*(x+1)/2.0 + a for integration from a=0 to b=pi + y = M_PI * (wb_x_legendre[k] + 1) / 2.0; + res2 += wb_w_legendre[k] * wb_P(-exp_term, eps, a, b, x, y); + } + res1 *= std::exp(-eps); + // (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1) + res2 *= M_PI / 2.0; + res2 *= std::pow(eps, 1 - b); + + if (!log_wb) { + // Remember the factored out exp_term from wb_Kmod and wb_P + return std::exp(exp_term) / M_PI * (res1 + res2); + } else { + // logarithm of Wright's function + return exp_term + std::log((res1 + res2) / M_PI); + } + } +} // namespace detail + +template +XSF_HOST_DEVICE inline double wright_bessel_t(double a, double b, double x) { + /* Compute Wright's generalized Bessel function for scalar arguments. + * + * According to [1], it is an entire function defined as + * + * .. math:: \Phi(a, b; x) = \sum_{k=0}^\infty \frac{x^k}{k! \Gamma(a k + b)} + * + * So far, only non-negative values of rho=a, beta=b and z=x are implemented. + * There are 5 different approaches depending on the ranges of the arguments: + * + * 1. Taylor series expansion in x=0 [1], for x <= 1. + * Involves gamma funtions in each term. + * 2. Taylor series expansion in x=0 [2], for large a. + * 3. Taylor series in a=0, for tiny a and not too large x. + * 4. Asymptotic expansion for large x [3, 4]. + * Suitable for large x while still small a and b. + * 5. Integral representation [5], in principle for all arguments. + * + * References + * ---------- + * [1] https://dlmf.nist.gov/10.46.E1 + * [2] P. K. Dunn, G. K. Smyth (2005), Series evaluation of Tweedie exponential + * dispersion model densities. Statistics and Computing 15 (2005): 267-280. + * [3] E. M. Wright (1935), The asymptotic expansion of the generalized Bessel + * function. Proc. London Math. Soc. (2) 38, pp. 257-270. + * https://doi.org/10.1112/plms/s2-38.1.257 + * [4] R. B. Paris (2017), The asymptotics of the generalised Bessel function, + * Mathematica Aeterna, Vol. 7, 2017, no. 4, 381 - 406, + * https://arxiv.org/abs/1711.03006 + * [5] Y. F. Luchko (2008), Algorithms for Evaluation of the Wright Function for + * the Real Arguments' Values, Fractional Calculus and Applied Analysis 11(1) + * http://sci-gems.math.bas.bg/jspui/bitstream/10525/1298/1/fcaa-vol11-num1-2008-57p-75p.pdf + */ + if (std::isnan(a) || std::isnan(b) || std::isnan(x)) { + return std::numeric_limits::quiet_NaN(); + } + if (a < 0 || b < 0 || x < 0) { + set_error("wright_bessel", SF_ERROR_DOMAIN, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (std::isinf(x)) { + if (std::isinf(a) || std::isinf(b)) { + return std::numeric_limits::quiet_NaN(); + } + return std::numeric_limits::infinity(); + } + if (std::isinf(a) || std::isinf(b)) { + return std::numeric_limits::quiet_NaN(); // or 0 + } + if (a >= detail::rgamma_zero || b >= detail::rgamma_zero) { + set_error("wright_bessel", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::quiet_NaN(); + } + if (x == 0) { + // return rgamma(b) + if (!log_wb) { + return cephes::rgamma(b); + } else { + // logarithm of Wright's function + return -cephes::lgam(b); + } + } + if (a == 0) { + // return exp(x) * rgamma(b) + if (!log_wb) { + return detail::exp_rgamma(x, b); + } else { + // logarithm of Wright's function + return x - cephes::lgam(b); + } + } + + constexpr double exp_inf = 709.78271289338403; + int order; + if ((a <= 1e-3 && b <= 50 && x <= 9) || (a <= 1e-4 && b <= 70 && x <= 100) || + (a <= 1e-5 && b <= 170 && (x < exp_inf || (log_wb && x <= 1e3)))) { + /* Taylor Series expansion in a=0 to order=order => precision <= 1e-11 + * If beta is also small => precision <= 1e-11. + * max order = 5 */ + if (a <= 1e-5) { + if (x <= 1) { + order = 2; + } else if (x <= 10) { + order = 3; + } else if (x <= 100) { + order = 4; + } else { // x < exp_inf + order = 5; + } + } else if (a <= 1e-4) { + if (x <= 1e-2) { + order = 2; + } else if (x <= 1) { + order = 3; + } else if (x <= 10) { + order = 4; + } else { // x <= 100 + order = 5; + } + } else { // a <= 1e-3 + if (x <= 1e-5) { + order = 2; + } else if (x <= 1e-1) { + order = 3; + } else if (x <= 1) { + order = 4; + } else { // x <= 9 + order = 5; + } + } + + return detail::wb_small_a(a, b, x, order); + } + + if (x <= 1) { + // 18 term Taylor Series => error mostly smaller 5e-14 + double res = detail::wb_series(a, b, x, 0, 18); + if (log_wb) res = std::log(res); + return res; + } + if (x <= 2) { + // 20 term Taylor Series => error mostly smaller 1e-12 to 1e-13 + double res = detail::wb_series(a, b, x, 0, 20); + if (log_wb) res = std::log(res); + return res; + } + if (a >= 5) { + /* Taylor series around the approximate maximum term. + * Set number of terms=order. */ + if (a >= 10) { + if (x <= 1e11) { + order = 6; + } else { + order = static_cast(std::fmin(std::log10(x) - 5 + b / 10, 30)); + } + } else { + if (x <= 1e4) { + order = 6; + } else if (x <= 1e8) { + order = static_cast(2 * std::log10(x)); + } else if (x <= 1e10) { + order = static_cast(4 * std::log10(x) - 16); + } else { + order = static_cast(std::fmin(6 * std::log10(x) - 36, 100)); + } + } + return detail::wb_large_a(a, b, x, order); + } + if (std::pow(a * x, 1 / (1. + a)) >= 14 + b * b / (2 * (1 + a))) { + /* Asymptotic expansion in Z = (a*x)^(1/(1+a)) up to 8th term 1/Z^8. + * For 1/Z^k, the highest term in b is b^(2*k) * a0 / (2^k k! (1+a)^k). + * As a0 is a common factor to all orders, this explains a bit the + * domain of good convergence set above. + * => precision ~ 1e-11 but can go down to ~1e-8 or 1e-7 + * Note: We ensured a <= 5 as this is a bad approximation for large a. */ + return detail::wb_asymptotic(a, b, x); + } + if (0.5 <= a && a <= 1.8 && 100 <= b && 1e5 <= x) { + // This is a very hard domain. This condition is placed after wb_asymptotic. + // TODO: Explore ways to cover this domain. + return std::numeric_limits::quiet_NaN(); + } + return detail::wright_bessel_integral(a, b, x); +} + + +XSF_HOST_DEVICE inline double wright_bessel(double a, double b, double x) { + return wright_bessel_t(a, b, x); +} + +XSF_HOST_DEVICE inline float wright_bessel(float a, float b, float x) { + return wright_bessel(static_cast(a), static_cast(b), static_cast(x)); +} + +XSF_HOST_DEVICE inline double log_wright_bessel(double a, double b, double x) { + return wright_bessel_t(a, b, x); +} + +XSF_HOST_DEVICE inline float log_wright_bessel(float a, float b, float x) { + return log_wright_bessel(static_cast(a), static_cast(b), static_cast(x)); +} + +} // namespace xsf diff --git a/shared/package-files/79/798a3738699fa1b276704f3e55ea7444763df1ed187b54cb6f67cdac09aa9e90/blob b/shared/package-files/79/798a3738699fa1b276704f3e55ea7444763df1ed187b54cb6f67cdac09aa9e90/blob new file mode 100644 index 0000000000000000000000000000000000000000..5609045bda0865839f0243c9244db0703fcafe2e --- /dev/null +++ b/shared/package-files/79/798a3738699fa1b276704f3e55ea7444763df1ed187b54cb6f67cdac09aa9e90/blob @@ -0,0 +1,563 @@ +Metadata-Version: 2.1 +Name: jedi +Version: 0.18.1 +Summary: An autocompletion tool for Python that can be used for text editors. +Home-page: https://github.com/davidhalter/jedi +Author: David Halter +Author-email: davidhalter88@gmail.com +Maintainer: David Halter +Maintainer-email: davidhalter88@gmail.com +License: MIT +Keywords: python completion refactoring vim +Platform: any +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Plugins +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Editors :: Integrated Development Environments (IDE) +Classifier: Topic :: Utilities +Requires-Python: >=3.6 +License-File: LICENSE.txt +License-File: AUTHORS.txt +Requires-Dist: parso (<0.9.0,>=0.8.0) +Provides-Extra: qa +Requires-Dist: flake8 (==3.8.3) ; extra == 'qa' +Requires-Dist: mypy (==0.782) ; extra == 'qa' +Provides-Extra: testing +Requires-Dist: pytest (<7.0.0) ; extra == 'testing' +Requires-Dist: docopt ; extra == 'testing' +Requires-Dist: colorama ; extra == 'testing' +Requires-Dist: Django (<3.1) ; extra == 'testing' + +#################################################################################### +Jedi - an awesome autocompletion, static analysis and refactoring library for Python +#################################################################################### + +.. image:: http://isitmaintained.com/badge/open/davidhalter/jedi.svg + :target: https://github.com/davidhalter/jedi/issues + :alt: The percentage of open issues and pull requests + +.. image:: http://isitmaintained.com/badge/resolution/davidhalter/jedi.svg + :target: https://github.com/davidhalter/jedi/issues + :alt: The resolution time is the median time an issue or pull request stays open. + +.. image:: https://github.com/davidhalter/jedi/workflows/ci/badge.svg?branch=master + :target: https://github.com/davidhalter/jedi/actions + :alt: Tests + +.. image:: https://pepy.tech/badge/jedi + :target: https://pepy.tech/project/jedi + :alt: PyPI Downloads + + +Jedi is a static analysis tool for Python that is typically used in +IDEs/editors plugins. Jedi has a focus on autocompletion and goto +functionality. Other features include refactoring, code search and finding +references. + +Jedi has a simple API to work with. There is a reference implementation as a +`VIM-Plugin `_. Autocompletion in your +REPL is also possible, IPython uses it natively and for the CPython REPL you +can install it. Jedi is well tested and bugs should be rare. + +Jedi can currently be used with the following editors/projects: + +- Vim (jedi-vim_, YouCompleteMe_, deoplete-jedi_, completor.vim_) +- `Visual Studio Code`_ (via `Python Extension `_) +- Emacs (Jedi.el_, company-mode_, elpy_, anaconda-mode_, ycmd_) +- Sublime Text (SublimeJEDI_ [ST2 + ST3], anaconda_ [only ST3]) +- TextMate_ (Not sure if it's actually working) +- Kate_ version 4.13+ supports it natively, you have to enable it, though. [`see + `_] +- Atom_ (autocomplete-python-jedi_) +- `GNOME Builder`_ (with support for GObject Introspection) +- Gedit (gedi_) +- wdb_ - Web Debugger +- `Eric IDE`_ (Available as a plugin) +- `IPython 6.0.0+ `_ +- `xonsh shell `_ has `jedi extension `_ + +and many more! + +There are a few language servers that use Jedi: + +- `jedi-language-server `_ +- `python-language-server `_ +- `anakin-language-server `_ + +Here are some pictures taken from jedi-vim_: + +.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_complete.png + +Completion for almost anything: + +.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_function.png + +Documentation: + +.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_pydoc.png + + +Get the latest version from `github `_ +(master branch should always be kind of stable/working). + +Docs are available at `https://jedi.readthedocs.org/en/latest/ +`_. Pull requests with enhancements +and/or fixes are awesome and most welcome. Jedi uses `semantic versioning +`_. + +If you want to stay **up-to-date** with releases, please **subscribe** to this +mailing list: https://groups.google.com/g/jedi-announce. To subscribe you can +simply send an empty email to ``jedi-announce+subscribe@googlegroups.com``. + +Issues & Questions +================== + +You can file issues and questions in the `issue tracker +`. Alternatively you can also ask on +`Stack Overflow `_ with +the label ``python-jedi``. + +Installation +============ + +`Check out the docs `_. + +Features and Limitations +======================== + +Jedi's features are listed here: +`Features `_. + +You can run Jedi on Python 3.6+ but it should also +understand code that is older than those versions. Additionally you should be +able to use `Virtualenvs `_ +very well. + +Tips on how to use Jedi efficiently can be found `here +`_. + +API +--- + +You can find a comprehensive documentation for the +`API here `_. + +Autocompletion / Goto / Documentation +------------------------------------- + +There are the following commands: + +- ``jedi.Script.goto`` +- ``jedi.Script.infer`` +- ``jedi.Script.help`` +- ``jedi.Script.complete`` +- ``jedi.Script.get_references`` +- ``jedi.Script.get_signatures`` +- ``jedi.Script.get_context`` + +The returned objects are very powerful and are really all you might need. + +Autocompletion in your REPL (IPython, etc.) +------------------------------------------- + +Jedi is a dependency of IPython. Autocompletion in IPython with Jedi is +therefore possible without additional configuration. + +Here is an `example video `_ how REPL completion +can look like. +For the ``python`` shell you can enable tab completion in a `REPL +`_. + +Static Analysis +--------------- + +For a lot of forms of static analysis, you can try to use +``jedi.Script(...).get_names``. It will return a list of names that you can +then filter and work with. There is also a way to list the syntax errors in a +file: ``jedi.Script.get_syntax_errors``. + + +Refactoring +----------- + +Jedi supports the following refactorings: + +- ``jedi.Script.inline`` +- ``jedi.Script.rename`` +- ``jedi.Script.extract_function`` +- ``jedi.Script.extract_variable`` + +Code Search +----------- + +There is support for module search with ``jedi.Script.search``, and project +search for ``jedi.Project.search``. The way to search is either by providing a +name like ``foo`` or by using dotted syntax like ``foo.bar``. Additionally you +can provide the API type like ``class foo.bar.Bar``. There are also the +functions ``jedi.Script.complete_search`` and ``jedi.Project.complete_search``. + +Development +=========== + +There's a pretty good and extensive `development documentation +`_. + +Testing +======= + +The test suite uses ``pytest``:: + + pip install pytest + +If you want to test only a specific Python version (e.g. Python 3.8), it is as +easy as:: + + python3.8 -m pytest + +For more detailed information visit the `testing documentation +`_. + +Acknowledgements +================ + +Thanks a lot to all the +`contributors `_! + + +.. _jedi-vim: https://github.com/davidhalter/jedi-vim +.. _youcompleteme: https://github.com/ycm-core/YouCompleteMe +.. _deoplete-jedi: https://github.com/zchee/deoplete-jedi +.. _completor.vim: https://github.com/maralla/completor.vim +.. _Jedi.el: https://github.com/tkf/emacs-jedi +.. _company-mode: https://github.com/syohex/emacs-company-jedi +.. _elpy: https://github.com/jorgenschaefer/elpy +.. _anaconda-mode: https://github.com/proofit404/anaconda-mode +.. _ycmd: https://github.com/abingham/emacs-ycmd +.. _sublimejedi: https://github.com/srusskih/SublimeJEDI +.. _anaconda: https://github.com/DamnWidget/anaconda +.. _wdb: https://github.com/Kozea/wdb +.. _TextMate: https://github.com/lawrenceakka/python-jedi.tmbundle +.. _Kate: https://kate-editor.org +.. _Atom: https://atom.io/ +.. _autocomplete-python-jedi: https://atom.io/packages/autocomplete-python-jedi +.. _GNOME Builder: https://wiki.gnome.org/Apps/Builder +.. _Visual Studio Code: https://code.visualstudio.com/ +.. _gedi: https://github.com/isamert/gedi +.. _Eric IDE: https://eric-ide.python-projects.org + + +.. :changelog: + +Changelog +--------- + +Unreleased +++++++++++ + +0.18.1 (2021-11-17) ++++++++++++++++++++ + +- Implict namespaces are now a separate types in ``Name().type`` +- Python 3.10 support +- Mostly bugfixes + +0.18.0 (2020-12-25) ++++++++++++++++++++ + +- Dropped Python 2 and Python 3.5 +- Using ``pathlib.Path()`` as an output instead of ``str`` in most places: + - ``Project.path`` + - ``Script.path`` + - ``Definition.module_path`` + - ``Refactoring.get_renames`` + - ``Refactoring.get_changed_files`` +- Functions with ``@property`` now return ``property`` instead of ``function`` + in ``Name().type`` +- Started using annotations +- Better support for the walrus operator +- Project attributes are now read accessible +- Removed all deprecations + +This is likely going to be the last minor release before 1.0. + +0.17.2 (2020-07-17) ++++++++++++++++++++ + +- Added an option to pass environment variables to ``Environment`` +- ``Project(...).path`` exists now +- Support for Python 3.9 +- A few bugfixes + +This will be the last release that supports Python 2 and Python 3.5. +``0.18.0`` will be Python 3.6+. + +0.17.1 (2020-06-20) ++++++++++++++++++++ + +- Django ``Model`` meta class support +- Django Manager support (completion on Managers/QuerySets) +- Added Django Stubs to Jedi, thanks to all contributors of the + `Django Stubs `_ project +- Added ``SyntaxError.get_message`` +- Python 3.9 support +- Bugfixes (mostly towards Generics) + +0.17.0 (2020-04-14) ++++++++++++++++++++ + +- Added ``Project`` support. This allows a user to specify which folders Jedi + should work with. +- Added support for Refactoring. The following refactorings have been + implemented: ``Script.rename``, ``Script.inline``, + ``Script.extract_variable`` and ``Script.extract_function``. +- Added ``Script.get_syntax_errors`` to display syntax errors in the current + script. +- Added code search capabilities both for individual files and projects. The + new functions are ``Project.search``, ``Project.complete_search``, + ``Script.search`` and ``Script.complete_search``. +- Added ``Script.help`` to make it easier to display a help window to people. + Now returns pydoc information as well for Python keywords/operators. This + means that on the class keyword it will now return the docstring of Python's + builtin function ``help('class')``. +- The API documentation is now way more readable and complete. Check it out + under https://jedi.readthedocs.io. A lot of it has been rewritten. +- Removed Python 3.4 support +- Many bugfixes + +This is likely going to be the last minor version that supports Python 2 and +Python3.5. Bugfixes will be provided in 0.17.1+. The next minor/major version +will probably be Jedi 1.0.0. + +0.16.0 (2020-01-26) ++++++++++++++++++++ + +- **Added** ``Script.get_context`` to get information where you currently are. +- Completions/type inference of **Pytest fixtures**. +- Tensorflow, Numpy and Pandas completions should now be about **4-10x faster** + after the first time they are used. +- Dict key completions are working now. e.g. ``d = {1000: 3}; d[10`` will + expand to ``1000``. +- Completion for "proxies" works now. These are classes that have a + ``__getattr__(self, name)`` method that does a ``return getattr(x, name)``. + after loading them initially. +- Goto on a function/attribute in a class now goes to the definition in its + super class. +- Big **Script API Changes**: + - The line and column parameters of ``jedi.Script`` are now deprecated + - ``completions`` deprecated, use ``complete`` instead + - ``goto_assignments`` deprecated, use ``goto`` instead + - ``goto_definitions`` deprecated, use ``infer`` instead + - ``call_signatures`` deprecated, use ``get_signatures`` instead + - ``usages`` deprecated, use ``get_references`` instead + - ``jedi.names`` deprecated, use ``jedi.Script(...).get_names()`` +- ``BaseName.goto_assignments`` renamed to ``BaseName.goto`` +- Add follow_imports to ``Name.goto``. Now its signature matches + ``Script.goto``. +- **Python 2 support deprecated**. For this release it is best effort. Python 2 + has reached the end of its life and now it's just about a smooth transition. + Bugs for Python 2 will not be fixed anymore and a third of the tests are + already skipped. +- Removed ``settings.no_completion_duplicates``. It wasn't tested and nobody + was probably using it anyway. +- Removed ``settings.use_filesystem_cache`` and + ``settings.additional_dynamic_modules``, they have no usage anymore. Pretty + much nobody was probably using them. + +0.15.2 (2019-12-20) ++++++++++++++++++++ + +- Signatures are now detected a lot better +- Add fuzzy completions with ``Script(...).completions(fuzzy=True)`` +- Files bigger than one MB (about 20kLOC) get cropped to avoid getting + stuck completely. +- Many small Bugfixes +- A big refactoring around contexts/values + +0.15.1 (2019-08-13) ++++++++++++++++++++ + +- Small bugfix and removal of a print statement + +0.15.0 (2019-08-11) ++++++++++++++++++++ + +- Added file path completions, there's a **new** ``Completion.type`` now: + ``path``. Example: ``'/ho`` -> ``'/home/`` +- ``*args``/``**kwargs`` resolving. If possible Jedi replaces the parameters + with the actual alternatives. +- Better support for enums/dataclasses +- When using Interpreter, properties are now executed, since a lot of people + have complained about this. Discussion in #1299, #1347. + +New APIs: + +- ``Name.get_signatures() -> List[Signature]``. Signatures are similar to + ``CallSignature``. ``Name.params`` is therefore deprecated. +- ``Signature.to_string()`` to format signatures. +- ``Signature.params -> List[ParamName]``, ParamName has the + following additional attributes ``infer_default()``, ``infer_annotation()``, + ``to_string()``, and ``kind``. +- ``Name.execute() -> List[Name]``, makes it possible to infer + return values of functions. + + +0.14.1 (2019-07-13) ++++++++++++++++++++ + +- CallSignature.index should now be working a lot better +- A couple of smaller bugfixes + +0.14.0 (2019-06-20) ++++++++++++++++++++ + +- Added ``goto_*(prefer_stubs=True)`` as well as ``goto_*(prefer_stubs=True)`` +- Stubs are used now for type inference +- Typeshed is used for better type inference +- Reworked Name.full_name, should have more correct return values + +0.13.3 (2019-02-24) ++++++++++++++++++++ + +- Fixed an issue with embedded Python, see https://github.com/davidhalter/jedi-vim/issues/870 + +0.13.2 (2018-12-15) ++++++++++++++++++++ + +- Fixed a bug that led to Jedi spawning a lot of subprocesses. + +0.13.1 (2018-10-02) ++++++++++++++++++++ + +- Bugfixes, because tensorflow completions were still slow. + +0.13.0 (2018-10-02) ++++++++++++++++++++ + +- A small release. Some bug fixes. +- Remove Python 3.3 support. Python 3.3 support has been dropped by the Python + foundation. +- Default environments are now using the same Python version as the Python + process. In 0.12.x, we used to load the latest Python version on the system. +- Added ``include_builtins`` as a parameter to usages. +- ``goto_assignments`` has a new ``follow_builtin_imports`` parameter that + changes the previous behavior slightly. + +0.12.1 (2018-06-30) ++++++++++++++++++++ + +- This release forces you to upgrade parso. If you don't, nothing will work + anymore. Otherwise changes should be limited to bug fixes. Unfortunately Jedi + still uses a few internals of parso that make it hard to keep compatibility + over multiple releases. Parso >=0.3.0 is going to be needed. + +0.12.0 (2018-04-15) ++++++++++++++++++++ + +- Virtualenv/Environment support +- F-String Completion/Goto Support +- Cannot crash with segfaults anymore +- Cleaned up import logic +- Understand async/await and autocomplete it (including async generators) +- Better namespace completions +- Passing tests for Windows (including CI for Windows) +- Remove Python 2.6 support + +0.11.1 (2017-12-14) ++++++++++++++++++++ + +- Parso update - the caching layer was broken +- Better usages - a lot of internal code was ripped out and improved. + +0.11.0 (2017-09-20) ++++++++++++++++++++ + +- Split Jedi's parser into a separate project called ``parso``. +- Avoiding side effects in REPL completion. +- Numpy docstring support should be much better. +- Moved the `settings.*recursion*` away, they are no longer usable. + +0.10.2 (2017-04-05) ++++++++++++++++++++ + +- Python Packaging sucks. Some files were not included in 0.10.1. + +0.10.1 (2017-04-05) ++++++++++++++++++++ + +- Fixed a few very annoying bugs. +- Prepared the parser to be factored out of Jedi. + +0.10.0 (2017-02-03) ++++++++++++++++++++ + +- Actual semantic completions for the complete Python syntax. +- Basic type inference for ``yield from`` PEP 380. +- PEP 484 support (most of the important features of it). Thanks Claude! (@reinhrst) +- Added ``get_line_code`` to ``Name`` and ``Completion`` objects. +- Completely rewritten the type inference engine. +- A new and better parser for (fast) parsing diffs of Python code. + +0.9.0 (2015-04-10) +++++++++++++++++++ + +- The import logic has been rewritten to look more like Python's. There is now + an ``InferState.modules`` import cache, which resembles ``sys.modules``. +- Integrated the parser of 2to3. This will make refactoring possible. It will + also be possible to check for error messages (like compiling an AST would give) + in the future. +- With the new parser, the type inference also completely changed. It's now + simpler and more readable. +- Completely rewritten REPL completion. +- Added ``jedi.names``, a command to do static analysis. Thanks to that + sourcegraph guys for sponsoring this! +- Alpha version of the linter. + + +0.8.1 (2014-07-23) ++++++++++++++++++++ + +- Bugfix release, the last release forgot to include files that improve + autocompletion for builtin libraries. Fixed. + +0.8.0 (2014-05-05) ++++++++++++++++++++ + +- Memory Consumption for compiled modules (e.g. builtins, sys) has been reduced + drastically. Loading times are down as well (it takes basically as long as an + import). +- REPL completion is starting to become usable. +- Various small API changes. Generally this release focuses on stability and + refactoring of internal APIs. +- Introducing operator precedence, which makes calculating correct Array + indices and ``__getattr__`` strings possible. + +0.7.0 (2013-08-09) +++++++++++++++++++ + +- Switched from LGPL to MIT license. +- Added an Interpreter class to the API to make autocompletion in REPL + possible. +- Added autocompletion support for namespace packages. +- Add sith.py, a new random testing method. + +0.6.0 (2013-05-14) +++++++++++++++++++ + +- Much faster parser with builtin part caching. +- A test suite, thanks @tkf. + +0.5 versions (2012) ++++++++++++++++++++ + +- Initial development. + + diff --git a/shared/package-files/79/798a49c0160b2863b155b2a012a7e7cb5ce789bf9beee621c5c45721feeec178/blob b/shared/package-files/79/798a49c0160b2863b155b2a012a7e7cb5ce789bf9beee621c5c45721feeec178/blob new file mode 100644 index 0000000000000000000000000000000000000000..46bef7cb91122281ddac7d0f0474c2c01b2a5e6f --- /dev/null +++ b/shared/package-files/79/798a49c0160b2863b155b2a012a7e7cb5ce789bf9beee621c5c45721feeec178/blob @@ -0,0 +1,10 @@ +module foo + public + integer, private :: a + integer :: b +contains + subroutine setA(v) + integer, intent(in) :: v + a = v + end subroutine setA +end module foo diff --git a/shared/package-files/79/7990ba4278c07a1f5e83e9d3eef8a4a30cef73a13d706474911268513ba46bcf/blob b/shared/package-files/79/7990ba4278c07a1f5e83e9d3eef8a4a30cef73a13d706474911268513ba46bcf/blob new file mode 100644 index 0000000000000000000000000000000000000000..6db7ff6f065f45d7cce75531a1f9778705022afb Binary files /dev/null and b/shared/package-files/79/7990ba4278c07a1f5e83e9d3eef8a4a30cef73a13d706474911268513ba46bcf/blob differ diff --git a/shared/package-files/79/799344079bb16edf36bc9dff8a4026cd292c50c3689f0e016c99609077c0db1f/blob b/shared/package-files/79/799344079bb16edf36bc9dff8a4026cd292c50c3689f0e016c99609077c0db1f/blob new file mode 100644 index 0000000000000000000000000000000000000000..c1f031ee4a133e7621e2739bc0f447d5de516c24 --- /dev/null +++ b/shared/package-files/79/799344079bb16edf36bc9dff8a4026cd292c50c3689f0e016c99609077c0db1f/blob @@ -0,0 +1,264 @@ +import collections +from typing import Any, Callable, Dict, Optional + +import torch +import torch.utils._pytree as pytree + +aten = torch.ops.aten + +# We would like to split modules into two subgraphs for runtime weight updates to work correctly. +# The use case and more information could be found at: +# https://docs.google.com/document/d/1inZC-8KarJ6gKB7G9egmYLx1V_dKX_apxon0w4zPC0Q/edit?usp=sharing +META_TAG = "MODULE_TYPE" +MODULE_TAG = "_MAIN_MODULE" +CONST_MODULE_TAG = "_CONST_MODULE" + + +def replace_node_with_constant(gm, node, constant, name=None): + g = gm.graph + + if name: + qualname = name + else: + if not hasattr(gm, "_frozen_param_count"): + gm._frozen_param_count = 0 + i = gm._frozen_param_count + + while True: + qualname = f"_frozen_param{i}" + if not hasattr(gm, qualname): + break + i += 1 + + gm._frozen_param_count = i + 1 + + with g.inserting_before(node): + new_input_node = g.create_node("get_attr", qualname, (), {}) + node.replace_all_uses_with(new_input_node) + new_input_node.meta.update(node.meta) + g.erase_node(node) + + # needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning + gm.register_buffer(qualname, constant) + setattr(gm, qualname, constant) + + +class ConstantFolder(torch.fx.Interpreter): + def __init__( + self, + gm, + skip_constructors=False, + ): + super().__init__(gm) + self.node_replacements: Dict[torch.fx.Node, Any] = {} + self.replaced_uses: Dict[torch.fx.Node, int] = collections.Counter() + self.unknown_value = object() + self.skip_constructors: bool = skip_constructors + + # overwrite this to deallocate env values if their only remaining use + # is the output + self.user_to_last_uses = self.node_to_last_non_output_use() + + def is_impure(self, node: torch.fx.node.Node): + if node.target in [ + torch.ops.quantized_decomposed.dequantize_per_channel.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + ]: + # For the pattern fp32_weight -> q -> dq + # We only folding fp32_weight -> q + # int8_weight and leave dq in graph to be fused + return True + return False + + def node_to_last_non_output_use(self): + last_non_output_use = collections.defaultdict(list) + seen_uses = set() + output_node = next(iter(reversed(self.module.graph.nodes))) + + for node in reversed(self.module.graph.nodes): + if node.target == "output": + continue + + def add_use(inp): + if inp in seen_uses: + return + + seen_uses.add(inp) + last_non_output_use[node].append(inp) + + pytree.tree_map_only(torch.fx.Node, add_use, (node.args, node.kwargs)) + + # if this node is only used in output, we want to gc it right away + if len(node.users) == 1 and output_node in node.users: + last_non_output_use[node].append(node) + + return last_non_output_use + + def run_node(self, node): + if node.target == "output": + # because we remove nodes from env on last non output use, + # re-define them now or we'll get error in interpreter + def set_env(arg): + self.env[arg] = self.unknown_value + + pytree.tree_map_only(torch.fx.Node, set_env, node.args) + return super().run_node(node) + + args, kwargs = self.fetch_args_kwargs_from_env(node) + flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs) + + if self.unknown_value in flattened_inputs: + return self.unknown_value + + # TODO - fix errors with this + if ( + node.op == "call_function" + and node.target == aten._efficientzerotensor.default + ): + return self.unknown_value + + # TODO - constant folding triton kernel returns the inputs -- fix this + if ( + node.op == "call_function" + and node.name == "triton_kernel_wrapper_functional_proxy" + ): + return self.unknown_value + + # skip constructors, since inductor generates optimal code for them already + # and turning into tensor would result in an additional global memory read + # TODO - more complicated strategy + if ( + self.skip_constructors + and node.op != "get_attr" + and not any(isinstance(e, torch.Tensor) for e in flattened_inputs) + ): + return self.unknown_value + + # All mutations should either be removed or on inputs which we did not make constant + if ( + isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + return self.unknown_value + + out = super().run_node(node) + + if node.op != "get_attr" and isinstance(out, torch.Tensor): + if not self.insertable_tensor_check(out): + return out + + if self.is_impure(node): + return self.unknown_value + + self.add_node_replacement(node, out) + + flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs) + + for n in flattened_node_inps: + if not isinstance(n, torch.fx.Node): + continue + + self.replaced_uses[n] += 1 + + for to_delete in self.user_to_last_uses.get(node, []): + if self.replaced_uses[to_delete] == len(to_delete.users): + self.node_replacements.pop(to_delete, None) + + return out + + def insertable_tensor_check(self, tensor: torch.Tensor) -> bool: + return True + + def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None: + self.node_replacements[node] = tensor + + def run(self): + env = {} + for n in self.module.graph.nodes: + if n.op == "placeholder": + env[n] = self.unknown_value + return super().run(initial_env=env) + + +@torch.utils._python_dispatch._disable_current_modes() +def constant_fold(gm, constraint_fn: Optional[Callable[[torch.fx.Node], bool]] = None): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node, constant in cf.node_replacements.items(): + if constraint_fn is not None and not constraint_fn(node): + continue + replace_node_with_constant(gm, node, constant) + + erased_params = [] + for node in gm.graph.nodes: + if node.op == "get_attr" and len(node.users) == 0: + if hasattr(gm, node.target): + delattr(gm, node.target) + erased_params.append(node) + + for node in erased_params: + gm.graph.erase_node(node) + + gm.graph.eliminate_dead_code() + gm.graph.lint() + gm.recompile() + + +@torch.utils._python_dispatch._disable_current_modes() +def constant_graph_tag(gm: torch.fx.GraphModule): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node in gm.graph.nodes: + if ( + node.op == "get_attr" + or node in cf.node_replacements + or node in cf.replaced_uses + ): + node.meta[META_TAG] = CONST_MODULE_TAG + else: + node.meta[META_TAG] = MODULE_TAG + + +def run_and_get_constant_graph(gm: torch.fx.GraphModule) -> torch.fx.GraphModule: + """ + Construct a GraphModule which corresponds to the part which could be + constant folded in provided gm. + """ + + constant_graph_tag(gm) + # We rewrite the tags, if it's a constant being directly consumed, without + # any folding opportunity, we keep it in main gm. + for node in gm.graph.nodes: + if node.op == "get_attr": + used_to_fold = False + for u in node.users: + if u.meta[META_TAG] == CONST_MODULE_TAG: + used_to_fold = True + break + if not used_to_fold: + node.meta[META_TAG] = MODULE_TAG + + new_graph = torch.fx.Graph() + + node_remapping: Dict[torch.fx.Node, torch.fx.Node] = {} + output_nodes = [] + for node in gm.graph.nodes: + if node.meta[META_TAG] == MODULE_TAG: + continue + + new_node = new_graph.node_copy(node, lambda x: node_remapping[x]) + node_remapping[node] = new_node + + for user in node.users: + if user.meta[META_TAG] == MODULE_TAG: + output_nodes.append(new_node) + break + + new_graph.output(tuple(output_nodes)) + new_graph.lint() + new_gm = torch.fx.GraphModule(gm, new_graph) + + return new_gm diff --git a/shared/package-files/79/799367cc6ac8e248bfe78a606373a3d13fb1de5c5d5d3621e3faf20c1db8c015/blob b/shared/package-files/79/799367cc6ac8e248bfe78a606373a3d13fb1de5c5d5d3621e3faf20c1db8c015/blob new file mode 100644 index 0000000000000000000000000000000000000000..91cd0db31c14e30d4c1e2e9f36382b7a5e022870 --- /dev/null +++ b/shared/package-files/79/799367cc6ac8e248bfe78a606373a3d13fb1de5c5d5d3621e3faf20c1db8c015/blob @@ -0,0 +1,42 @@ +from typing import TYPE_CHECKING + +from .measure import Measurement +from .segment import Segment +from .style import StyleType + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderResult, RenderableType + + +class Styled: + """Apply a style to a renderable. + + Args: + renderable (RenderableType): Any renderable. + style (StyleType): A style to apply across the entire renderable. + """ + + def __init__(self, renderable: "RenderableType", style: "StyleType") -> None: + self.renderable = renderable + self.style = style + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + style = console.get_style(self.style) + rendered_segments = console.render(self.renderable, options) + segments = Segment.apply_style(rendered_segments, style) + return segments + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + return Measurement.get(console, options, self.renderable) + + +if __name__ == "__main__": # pragma: no cover + from pip._vendor.rich import print + from pip._vendor.rich.panel import Panel + + panel = Styled(Panel("hello"), "on blue") + print(panel) diff --git a/shared/package-files/79/799476be8f84f450f1870c08dca2d56e1e03e9ddf0560d3a5268656a61fc7254/blob b/shared/package-files/79/799476be8f84f450f1870c08dca2d56e1e03e9ddf0560d3a5268656a61fc7254/blob new file mode 100644 index 0000000000000000000000000000000000000000..912a42505a09a237a6d84215d546f7e3a1f071e2 --- /dev/null +++ b/shared/package-files/79/799476be8f84f450f1870c08dca2d56e1e03e9ddf0560d3a5268656a61fc7254/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _fake_quantize_learnable_per_tensor_affine_backward(const at::Tensor & grad, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t quant_min, int64_t quant_max, double grad_factor=1.0); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/79/7994d8277ccde4b12df2d9792a10038351f072ba1f85242cc1a80fff3731a0cc/blob b/shared/package-files/79/7994d8277ccde4b12df2d9792a10038351f072ba1f85242cc1a80fff3731a0cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..afa611cca1cc6e3417cadc61f63508d743f679ba --- /dev/null +++ b/shared/package-files/79/7994d8277ccde4b12df2d9792a10038351f072ba1f85242cc1a80fff3731a0cc/blob @@ -0,0 +1,359 @@ +from sympy.core import (S, pi, oo, symbols, Rational, Integer, + GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, + Eq, Ne, Le, Lt, Gt, Ge, Mod) +from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt, + sign, floor) +from sympy.logic import ITE +from sympy.testing.pytest import raises +from sympy.utilities.lambdify import implemented_function +from sympy.tensor import IndexedBase, Idx +from sympy.matrices import MatrixSymbol, SparseMatrix, Matrix + +from sympy.printing.rust import rust_code + +x, y, z = symbols('x,y,z') + + +def test_Integer(): + assert rust_code(Integer(42)) == "42" + assert rust_code(Integer(-56)) == "-56" + + +def test_Relational(): + assert rust_code(Eq(x, y)) == "x == y" + assert rust_code(Ne(x, y)) == "x != y" + assert rust_code(Le(x, y)) == "x <= y" + assert rust_code(Lt(x, y)) == "x < y" + assert rust_code(Gt(x, y)) == "x > y" + assert rust_code(Ge(x, y)) == "x >= y" + + +def test_Rational(): + assert rust_code(Rational(3, 7)) == "3_f64/7.0" + assert rust_code(Rational(18, 9)) == "2" + assert rust_code(Rational(3, -7)) == "-3_f64/7.0" + assert rust_code(Rational(-3, -7)) == "3_f64/7.0" + assert rust_code(x + Rational(3, 7)) == "x + 3_f64/7.0" + assert rust_code(Rational(3, 7)*x) == "(3_f64/7.0)*x" + + +def test_basic_ops(): + assert rust_code(x + y) == "x + y" + assert rust_code(x - y) == "x - y" + assert rust_code(x * y) == "x*y" + assert rust_code(x / y) == "x/y" + assert rust_code(-x) == "-x" + + +def test_printmethod(): + class fabs(Abs): + def _rust_code(self, printer): + return "%s.fabs()" % printer._print(self.args[0]) + assert rust_code(fabs(x)) == "x.fabs()" + a = MatrixSymbol("a", 1, 3) + assert rust_code(a[0,0]) == 'a[0]' + + +def test_Functions(): + assert rust_code(sin(x) ** cos(x)) == "x.sin().powf(x.cos())" + assert rust_code(abs(x)) == "x.abs()" + assert rust_code(ceiling(x)) == "x.ceil()" + assert rust_code(floor(x)) == "x.floor()" + + # Automatic rewrite + assert rust_code(Mod(x, 3)) == 'x - 3*((1_f64/3.0)*x).floor()' + + +def test_Pow(): + assert rust_code(1/x) == "x.recip()" + assert rust_code(x**-1) == rust_code(x**-1.0) == "x.recip()" + assert rust_code(sqrt(x)) == "x.sqrt()" + assert rust_code(x**S.Half) == rust_code(x**0.5) == "x.sqrt()" + + assert rust_code(1/sqrt(x)) == "x.sqrt().recip()" + assert rust_code(x**-S.Half) == rust_code(x**-0.5) == "x.sqrt().recip()" + + assert rust_code(1/pi) == "PI.recip()" + assert rust_code(pi**-1) == rust_code(pi**-1.0) == "PI.recip()" + assert rust_code(pi**-0.5) == "PI.sqrt().recip()" + + assert rust_code(x**Rational(1, 3)) == "x.cbrt()" + assert rust_code(2**x) == "x.exp2()" + assert rust_code(exp(x)) == "x.exp()" + assert rust_code(x**3) == "x.powi(3)" + assert rust_code(x**(y**3)) == "x.powf(y.powi(3))" + assert rust_code(x**Rational(2, 3)) == "x.powf(2_f64/3.0)" + + g = implemented_function('g', Lambda(x, 2*x)) + assert rust_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ + "(3.5*2*x).powf(-x + y.powf(x))/(x.powi(2) + y)" + _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi", 1), + (lambda base, exp: not exp.is_integer, "pow", 1)] + assert rust_code(x**3, user_functions={'Pow': _cond_cfunc}) == 'x.dpowi(3)' + assert rust_code(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'x.pow(3.2)' + + +def test_constants(): + assert rust_code(pi) == "PI" + assert rust_code(oo) == "INFINITY" + assert rust_code(S.Infinity) == "INFINITY" + assert rust_code(-oo) == "NEG_INFINITY" + assert rust_code(S.NegativeInfinity) == "NEG_INFINITY" + assert rust_code(S.NaN) == "NAN" + assert rust_code(exp(1)) == "E" + assert rust_code(S.Exp1) == "E" + + +def test_constants_other(): + assert rust_code(2*GoldenRatio) == "const GoldenRatio: f64 = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) + assert rust_code( + 2*Catalan) == "const Catalan: f64 = %s;\n2*Catalan" % Catalan.evalf(17) + assert rust_code(2*EulerGamma) == "const EulerGamma: f64 = %s;\n2*EulerGamma" % EulerGamma.evalf(17) + + +def test_boolean(): + assert rust_code(True) == "true" + assert rust_code(S.true) == "true" + assert rust_code(False) == "false" + assert rust_code(S.false) == "false" + assert rust_code(x & y) == "x && y" + assert rust_code(x | y) == "x || y" + assert rust_code(~x) == "!x" + assert rust_code(x & y & z) == "x && y && z" + assert rust_code(x | y | z) == "x || y || z" + assert rust_code((x & y) | z) == "z || x && y" + assert rust_code((x | y) & z) == "z && (x || y)" + + +def test_Piecewise(): + expr = Piecewise((x, x < 1), (x + 2, True)) + assert rust_code(expr) == ( + "if (x < 1) {\n" + " x\n" + "} else {\n" + " x + 2\n" + "}") + assert rust_code(expr, assign_to="r") == ( + "r = if (x < 1) {\n" + " x\n" + "} else {\n" + " x + 2\n" + "};") + assert rust_code(expr, assign_to="r", inline=True) == ( + "r = if (x < 1) { x } else { x + 2 };") + expr = Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) + assert rust_code(expr, inline=True) == ( + "if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }") + assert rust_code(expr, assign_to="r", inline=True) == ( + "r = if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 };") + assert rust_code(expr, assign_to="r") == ( + "r = if (x < 1) {\n" + " x\n" + "} else if (x < 5) {\n" + " x + 1\n" + "} else {\n" + " x + 2\n" + "};") + expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) + assert rust_code(expr, inline=True) == ( + "2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }") + expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) - 42 + assert rust_code(expr, inline=True) == ( + "2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 } - 42") + # Check that Piecewise without a True (default) condition error + expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) + raises(ValueError, lambda: rust_code(expr)) + + +def test_dereference_printing(): + expr = x + y + sin(z) + z + assert rust_code(expr, dereference=[z]) == "x + y + (*z) + (*z).sin()" + + +def test_sign(): + expr = sign(x) * y + assert rust_code(expr) == "y*x.signum()" + assert rust_code(expr, assign_to='r') == "r = y*x.signum();" + + expr = sign(x + y) + 42 + assert rust_code(expr) == "(x + y).signum() + 42" + assert rust_code(expr, assign_to='r') == "r = (x + y).signum() + 42;" + + expr = sign(cos(x)) + assert rust_code(expr) == "x.cos().signum()" + + +def test_reserved_words(): + + x, y = symbols("x if") + + expr = sin(y) + assert rust_code(expr) == "if_.sin()" + assert rust_code(expr, dereference=[y]) == "(*if_).sin()" + assert rust_code(expr, reserved_word_suffix='_unreserved') == "if_unreserved.sin()" + + with raises(ValueError): + rust_code(expr, error_on_reserved=True) + + +def test_ITE(): + expr = ITE(x < 1, y, z) + assert rust_code(expr) == ( + "if (x < 1) {\n" + " y\n" + "} else {\n" + " z\n" + "}") + + +def test_Indexed(): + n, m, o = symbols('n m o', integer=True) + i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) + + x = IndexedBase('x')[j] + assert rust_code(x) == "x[j]" + + A = IndexedBase('A')[i, j] + assert rust_code(A) == "A[m*i + j]" + + B = IndexedBase('B')[i, j, k] + assert rust_code(B) == "B[m*o*i + o*j + k]" + + +def test_dummy_loops(): + i, m = symbols('i m', integer=True, cls=Dummy) + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx(i, m) + + assert rust_code(x[i], assign_to=y[i]) == ( + "for i in 0..m {\n" + " y[i] = x[i];\n" + "}") + + +def test_loops(): + m, n = symbols('m n', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + z = IndexedBase('z') + i = Idx('i', m) + j = Idx('j', n) + + assert rust_code(A[i, j]*x[j], assign_to=y[i]) == ( + "for i in 0..m {\n" + " y[i] = 0;\n" + "}\n" + "for i in 0..m {\n" + " for j in 0..n {\n" + " y[i] = A[n*i + j]*x[j] + y[i];\n" + " }\n" + "}") + + assert rust_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == ( + "for i in 0..m {\n" + " y[i] = x[i] + z[i];\n" + "}\n" + "for i in 0..m {\n" + " for j in 0..n {\n" + " y[i] = A[n*i + j]*x[j] + y[i];\n" + " }\n" + "}") + + +def test_loops_multiple_contractions(): + n, m, o, p = symbols('n m o p', integer=True) + a = IndexedBase('a') + b = IndexedBase('b') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + k = Idx('k', o) + l = Idx('l', p) + + assert rust_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == ( + "for i in 0..m {\n" + " y[i] = 0;\n" + "}\n" + "for i in 0..m {\n" + " for j in 0..n {\n" + " for k in 0..o {\n" + " for l in 0..p {\n" + " y[i] = a[%s]*b[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ + " }\n" + " }\n" + " }\n" + "}") + + +def test_loops_addfactor(): + m, n, o, p = symbols('m n o p', integer=True) + a = IndexedBase('a') + b = IndexedBase('b') + c = IndexedBase('c') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + k = Idx('k', o) + l = Idx('l', p) + + code = rust_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) + assert code == ( + "for i in 0..m {\n" + " y[i] = 0;\n" + "}\n" + "for i in 0..m {\n" + " for j in 0..n {\n" + " for k in 0..o {\n" + " for l in 0..p {\n" + " y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ + " }\n" + " }\n" + " }\n" + "}") + + +def test_settings(): + raises(TypeError, lambda: rust_code(sin(x), method="garbage")) + + +def test_inline_function(): + x = symbols('x') + g = implemented_function('g', Lambda(x, 2*x)) + assert rust_code(g(x)) == "2*x" + + g = implemented_function('g', Lambda(x, 2*x/Catalan)) + assert rust_code(g(x)) == ( + "const Catalan: f64 = %s;\n2*x/Catalan" % Catalan.evalf(17)) + + A = IndexedBase('A') + i = Idx('i', symbols('n', integer=True)) + g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) + assert rust_code(g(A[i]), assign_to=A[i]) == ( + "for i in 0..n {\n" + " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" + "}") + + +def test_user_functions(): + x = symbols('x', integer=False) + n = symbols('n', integer=True) + custom_functions = { + "ceiling": "ceil", + "Abs": [(lambda x: not x.is_integer, "fabs", 4), (lambda x: x.is_integer, "abs", 4)], + } + assert rust_code(ceiling(x), user_functions=custom_functions) == "x.ceil()" + assert rust_code(Abs(x), user_functions=custom_functions) == "fabs(x)" + assert rust_code(Abs(n), user_functions=custom_functions) == "abs(n)" + + +def test_matrix(): + assert rust_code(Matrix([1, 2, 3])) == '[1, 2, 3]' + with raises(ValueError): + rust_code(Matrix([[1, 2, 3]])) + + +def test_sparse_matrix(): + # gh-15791 + assert 'Not supported in Rust' in rust_code(SparseMatrix([[1, 2, 3]])) diff --git a/shared/package-files/79/79972f52a54b6dedeee3c4ae9cb75e9e268f955e3e93aa70065ebb396e234b2f/blob b/shared/package-files/79/79972f52a54b6dedeee3c4ae9cb75e9e268f955e3e93aa70065ebb396e234b2f/blob new file mode 100644 index 0000000000000000000000000000000000000000..b4babf44f79b1fa6ed1920d55c1d641e5904d6ab --- /dev/null +++ b/shared/package-files/79/79972f52a54b6dedeee3c4ae9cb75e9e268f955e3e93aa70065ebb396e234b2f/blob @@ -0,0 +1,113 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives._asymmetric import ( + AsymmetricPadding as AsymmetricPadding, +) +from cryptography.hazmat.primitives.asymmetric import rsa + + +class PKCS1v15(AsymmetricPadding): + name = "EMSA-PKCS1-v1_5" + + +class _MaxLength: + "Sentinel value for `MAX_LENGTH`." + + +class _Auto: + "Sentinel value for `AUTO`." + + +class _DigestLength: + "Sentinel value for `DIGEST_LENGTH`." + + +class PSS(AsymmetricPadding): + MAX_LENGTH = _MaxLength() + AUTO = _Auto() + DIGEST_LENGTH = _DigestLength() + name = "EMSA-PSS" + _salt_length: int | _MaxLength | _Auto | _DigestLength + + def __init__( + self, + mgf: MGF, + salt_length: int | _MaxLength | _Auto | _DigestLength, + ) -> None: + self._mgf = mgf + + if not isinstance( + salt_length, (int, _MaxLength, _Auto, _DigestLength) + ): + raise TypeError( + "salt_length must be an integer, MAX_LENGTH, " + "DIGEST_LENGTH, or AUTO" + ) + + if isinstance(salt_length, int) and salt_length < 0: + raise ValueError("salt_length must be zero or greater.") + + self._salt_length = salt_length + + @property + def mgf(self) -> MGF: + return self._mgf + + +class OAEP(AsymmetricPadding): + name = "EME-OAEP" + + def __init__( + self, + mgf: MGF, + algorithm: hashes.HashAlgorithm, + label: bytes | None, + ): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._mgf = mgf + self._algorithm = algorithm + self._label = label + + @property + def algorithm(self) -> hashes.HashAlgorithm: + return self._algorithm + + @property + def mgf(self) -> MGF: + return self._mgf + + +class MGF(metaclass=abc.ABCMeta): + _algorithm: hashes.HashAlgorithm + + +class MGF1(MGF): + MAX_LENGTH = _MaxLength() + + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._algorithm = algorithm + + +def calculate_max_pss_salt_length( + key: rsa.RSAPrivateKey | rsa.RSAPublicKey, + hash_algorithm: hashes.HashAlgorithm, +) -> int: + if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + raise TypeError("key must be an RSA public or private key") + # bit length - 1 per RFC 3447 + emlen = (key.key_size + 6) // 8 + salt_length = emlen - hash_algorithm.digest_size - 2 + assert salt_length >= 0 + return salt_length diff --git a/shared/package-files/79/799912aa17998f85ae4d5cb4723029402417b3dacec683465d9dcf72ec438865/blob b/shared/package-files/79/799912aa17998f85ae4d5cb4723029402417b3dacec683465d9dcf72ec438865/blob new file mode 100644 index 0000000000000000000000000000000000000000..ceb0de4e3fcc66dfefa32d6c5b99752aac0f8757 --- /dev/null +++ b/shared/package-files/79/799912aa17998f85ae4d5cb4723029402417b3dacec683465d9dcf72ec438865/blob @@ -0,0 +1,46 @@ +import logging +import warnings + +from importlib import metadata as importlib_metadata + + +_already_initialized = False +logger = logging.getLogger(__name__) + + +def init_all(): + """Execute all `numba_extensions` entry points with the name `init` + + If extensions have already been initialized, this function does nothing. + """ + global _already_initialized + if _already_initialized: + return + + # Must put this here to avoid extensions re-triggering initialization + _already_initialized = True + + def load_ep(entry_point): + """Loads a given entry point. Warns and logs on failure. + """ + logger.debug('Loading extension: %s', entry_point) + try: + func = entry_point.load() + func() + except Exception as e: + msg = (f"Numba extension module '{entry_point.module}' " + f"failed to load due to '{type(e).__name__}({str(e)})'.") + warnings.warn(msg, stacklevel=3) + logger.debug('Extension loading failed for: %s', entry_point) + + eps = importlib_metadata.entry_points() + # Split, Python 3.10+ and importlib_metadata 3.6+ have the "selectable" + # interface, versions prior to that do not. See "compatibility note" in: + # https://docs.python.org/3.10/library/importlib.metadata.html#entry-points + if hasattr(eps, 'select'): + for entry_point in eps.select(group="numba_extensions", name="init"): + load_ep(entry_point) + else: + for entry_point in eps.get("numba_extensions", ()): + if entry_point.name == "init": + load_ep(entry_point) diff --git a/shared/package-files/79/7999514cb5242f373ff4eb77a5d7e1c8c6f76a1534fc88a9c74bd26f33951b2f/blob b/shared/package-files/79/7999514cb5242f373ff4eb77a5d7e1c8c6f76a1534fc88a9c74bd26f33951b2f/blob new file mode 100644 index 0000000000000000000000000000000000000000..7719201a0ea2d4b8f28a3012ad63c1de8bbf10ef --- /dev/null +++ b/shared/package-files/79/7999514cb5242f373ff4eb77a5d7e1c8c6f76a1534fc88a9c74bd26f33951b2f/blob @@ -0,0 +1,91 @@ +This folder is a subpackage of ttLib. Each module here is a +specialized TT/OT table converter: they can convert raw data +to Python objects and vice versa. Usually you don't need to +use the modules directly: they are imported and used +automatically when needed by ttLib. + +If you are writing you own table converter the following is +important. + +The modules here have pretty strange names: this is due to the +fact that we need to map TT table tags (which are case sensitive) +to filenames (which on Mac and Win aren't case sensitive) as well +as to Python identifiers. The latter means it can only contain +[A-Za-z0-9_] and cannot start with a number. + +ttLib provides functions to expand a tag into the format used here: + +>>> from fontTools import ttLib +>>> ttLib.tagToIdentifier("FOO ") +'F_O_O_' +>>> ttLib.tagToIdentifier("cvt ") +'_c_v_t' +>>> ttLib.tagToIdentifier("OS/2") +'O_S_2f_2' +>>> ttLib.tagToIdentifier("glyf") +'_g_l_y_f' +>>> + +And vice versa: + +>>> ttLib.identifierToTag("F_O_O_") +'FOO ' +>>> ttLib.identifierToTag("_c_v_t") +'cvt ' +>>> ttLib.identifierToTag("O_S_2f_2") +'OS/2' +>>> ttLib.identifierToTag("_g_l_y_f") +'glyf' +>>> + +Eg. the 'glyf' table converter lives in a Python file called: + + _g_l_y_f.py + +The converter itself is a class, named "table_" + expandedtag. Eg: + + class table__g_l_y_f: + etc. + +Note that if you _do_ need to use such modules or classes manually, +there are two convenient API functions that let you find them by tag: + +>>> ttLib.getTableModule('glyf') + +>>> ttLib.getTableClass('glyf') + +>>> + +You must subclass from DefaultTable.DefaultTable. It provides some default +behavior, as well as a constructor method (__init__) that you don't need to +override. + +Your converter should minimally provide two methods: + +class table_F_O_O_(DefaultTable.DefaultTable): # converter for table 'FOO ' + + def decompile(self, data, ttFont): + # 'data' is the raw table data. Unpack it into a + # Python data structure. + # 'ttFont' is a ttLib.TTfile instance, enabling you to + # refer to other tables. Do ***not*** keep a reference to + # it: it will cause a circular reference (ttFont saves + # a reference to us), and that means we'll be leaking + # memory. If you need to use it in other methods, just + # pass it around as a method argument. + + def compile(self, ttFont): + # Return the raw data, as converted from the Python + # data structure. + # Again, 'ttFont' is there so you can access other tables. + # Same warning applies. + +If you want to support TTX import/export as well, you need to provide two +additional methods: + + def toXML(self, writer, ttFont): + # XXX + + def fromXML(self, (name, attrs, content), ttFont): + # XXX + diff --git a/shared/package-files/79/799f4aa301e59cd07265f514fbc641d8d865181959846fb937fb22a578551a01/blob b/shared/package-files/79/799f4aa301e59cd07265f514fbc641d8d865181959846fb937fb22a578551a01/blob new file mode 100644 index 0000000000000000000000000000000000000000..75d24eb88ea6bf8dacb95f9f4036f769eddc84a1 --- /dev/null +++ b/shared/package-files/79/799f4aa301e59cd07265f514fbc641d8d865181959846fb937fb22a578551a01/blob @@ -0,0 +1,244 @@ +from typing import List +from dataclasses import dataclass, field +from numba import cuda, float32 +from numba.cuda.compiler import compile_ptx_for_current_device, compile_ptx +from math import cos, sin, tan, exp, log, log10, log2, pow, tanh +from operator import truediv +import numpy as np +from numba.cuda.testing import (CUDATestCase, skip_on_cudasim, + skip_unless_cc_75) +import unittest + + +@dataclass +class FastMathCriterion: + fast_expected: List[str] = field(default_factory=list) + fast_unexpected: List[str] = field(default_factory=list) + prec_expected: List[str] = field(default_factory=list) + prec_unexpected: List[str] = field(default_factory=list) + + def check(self, test: CUDATestCase, fast: str, prec: str): + test.assertTrue(all(i in fast for i in self.fast_expected)) + test.assertTrue(all(i not in fast for i in self.fast_unexpected)) + test.assertTrue(all(i in prec for i in self.prec_expected)) + test.assertTrue(all(i not in prec for i in self.prec_unexpected)) + + +@skip_on_cudasim('Fastmath and PTX inspection not available on cudasim') +class TestFastMathOption(CUDATestCase): + def _test_fast_math_common(self, pyfunc, sig, device, criterion): + + # Test jit code path + fastver = cuda.jit(sig, device=device, fastmath=True)(pyfunc) + precver = cuda.jit(sig, device=device)(pyfunc) + + criterion.check( + self, fastver.inspect_asm(sig), precver.inspect_asm(sig) + ) + + # Test compile_ptx code path + fastptx, _ = compile_ptx_for_current_device( + pyfunc, sig, device=device, fastmath=True + ) + precptx, _ = compile_ptx_for_current_device( + pyfunc, sig, device=device + ) + + criterion.check(self, fastptx, precptx) + + def _test_fast_math_unary(self, op, criterion: FastMathCriterion): + def kernel(r, x): + r[0] = op(x) + + def device_function(x): + return op(x) + + self._test_fast_math_common( + kernel, (float32[::1], float32), device=False, criterion=criterion + ) + self._test_fast_math_common( + device_function, (float32,), device=True, criterion=criterion + ) + + def _test_fast_math_binary(self, op, criterion: FastMathCriterion): + def kernel(r, x, y): + r[0] = op(x, y) + + def device(x, y): + return op(x, y) + + self._test_fast_math_common( + kernel, + (float32[::1], float32, float32), device=False, criterion=criterion + ) + self._test_fast_math_common( + device, (float32, float32), device=True, criterion=criterion + ) + + def test_cosf(self): + self._test_fast_math_unary( + cos, + FastMathCriterion( + fast_expected=['cos.approx.ftz.f32 '], + prec_unexpected=['cos.approx.ftz.f32 '] + ) + ) + + def test_sinf(self): + self._test_fast_math_unary( + sin, + FastMathCriterion( + fast_expected=['sin.approx.ftz.f32 '], + prec_unexpected=['sin.approx.ftz.f32 '] + ) + ) + + def test_tanf(self): + self._test_fast_math_unary( + tan, + FastMathCriterion(fast_expected=[ + 'sin.approx.ftz.f32 ', + 'cos.approx.ftz.f32 ', + 'div.approx.ftz.f32 ' + ], prec_unexpected=['sin.approx.ftz.f32 ']) + ) + + @skip_unless_cc_75 + def test_tanhf(self): + + self._test_fast_math_unary( + tanh, + FastMathCriterion( + fast_expected=['tanh.approx.f32 '], + prec_unexpected=['tanh.approx.f32 '] + ) + ) + + def test_tanhf_compile_ptx(self): + def tanh_kernel(r, x): + r[0] = tanh(x) + + def tanh_common_test(cc, criterion): + fastptx, _ = compile_ptx(tanh_kernel, (float32[::1], float32), + fastmath=True, cc=cc) + precptx, _ = compile_ptx(tanh_kernel, (float32[::1], float32), + cc=cc) + criterion.check(self, fastptx, precptx) + + tanh_common_test(cc=(7, 5), criterion=FastMathCriterion( + fast_expected=['tanh.approx.f32 '], + prec_unexpected=['tanh.approx.f32 '] + )) + + tanh_common_test(cc=(7, 0), + criterion=FastMathCriterion( + fast_expected=['ex2.approx.ftz.f32 ', + 'rcp.approx.ftz.f32 '], + prec_unexpected=['tanh.approx.f32 '])) + + def test_expf(self): + self._test_fast_math_unary( + exp, + FastMathCriterion( + fast_unexpected=['fma.rn.f32 '], + prec_expected=['fma.rn.f32 '] + ) + ) + + def test_logf(self): + # Look for constant used to convert from log base 2 to log base e + self._test_fast_math_unary( + log, FastMathCriterion( + fast_expected=['lg2.approx.ftz.f32 ', '0f3F317218'], + prec_unexpected=['lg2.approx.ftz.f32 '], + ) + ) + + def test_log10f(self): + # Look for constant used to convert from log base 2 to log base 10 + self._test_fast_math_unary( + log10, FastMathCriterion( + fast_expected=['lg2.approx.ftz.f32 ', '0f3E9A209B'], + prec_unexpected=['lg2.approx.ftz.f32 '] + ) + ) + + def test_log2f(self): + self._test_fast_math_unary( + log2, FastMathCriterion( + fast_expected=['lg2.approx.ftz.f32 '], + prec_unexpected=['lg2.approx.ftz.f32 '] + ) + ) + + def test_powf(self): + self._test_fast_math_binary( + pow, FastMathCriterion( + fast_expected=['lg2.approx.ftz.f32 '], + prec_unexpected=['lg2.approx.ftz.f32 '], + ) + ) + + def test_divf(self): + self._test_fast_math_binary( + truediv, FastMathCriterion( + fast_expected=['div.approx.ftz.f32 '], + fast_unexpected=['div.rn.f32'], + prec_expected=['div.rn.f32'], + prec_unexpected=['div.approx.ftz.f32 '], + ) + ) + + def test_divf_exception(self): + # LTO optimizes away the exception status due to an oversight + # in the way we generate it (it is not added to the used list). + self.skip_if_lto("Exceptions not supported with LTO") + + def f10(r, x, y): + r[0] = x / y + + sig = (float32[::1], float32, float32) + fastver = cuda.jit(sig, fastmath=True, debug=True)(f10) + precver = cuda.jit(sig, debug=True)(f10) + nelem = 10 + ary = np.empty(nelem, dtype=np.float32) + with self.assertRaises(ZeroDivisionError): + precver[1, nelem](ary, 10.0, 0.0) + + try: + fastver[1, nelem](ary, 10.0, 0.0) + except ZeroDivisionError: + self.fail("Divide in fastmath should not throw ZeroDivisionError") + + @unittest.expectedFailure + def test_device_fastmath_propagation(self): + # The fastmath option doesn't presently propagate to device functions + # from their callees - arguably it should do, so this test is presently + # an xfail. + @cuda.jit("float32(float32, float32)", device=True) + def foo(a, b): + return a / b + + def bar(arr, val): + i = cuda.grid(1) + if i < arr.size: + arr[i] = foo(i, val) + + sig = (float32[::1], float32) + fastver = cuda.jit(sig, fastmath=True)(bar) + precver = cuda.jit(sig)(bar) + + # Variants of the div instruction are further documented at: + # https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#floating-point-instructions-div + + # The fast version should use the "fast, approximate divide" variant + self.assertIn('div.approx.f32', fastver.inspect_asm(sig)) + # The precise version should use the "IEEE 754 compliant rounding" + # variant, and neither of the "approximate divide" variants. + self.assertIn('div.rn.f32', precver.inspect_asm(sig)) + self.assertNotIn('div.approx.f32', precver.inspect_asm(sig)) + self.assertNotIn('div.full.f32', precver.inspect_asm(sig)) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/79/79a3ce663311bb9bbc4692abb00f6e93bb9c3d94b9b64286e03fe190e4d0dc79/blob b/shared/package-files/79/79a3ce663311bb9bbc4692abb00f6e93bb9c3d94b9b64286e03fe190e4d0dc79/blob new file mode 100644 index 0000000000000000000000000000000000000000..804c340845fa0694e8db1083cfe7c290c04f36b1 --- /dev/null +++ b/shared/package-files/79/79a3ce663311bb9bbc4692abb00f6e93bb9c3d94b9b64286e03fe190e4d0dc79/blob @@ -0,0 +1,2653 @@ +[ + { + "description": "Petstore", + "schema": { + "title": "A JSON Schema for Swagger 2.0 API.", + "id": "http://swagger.io/v2/schema.json#", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "required": [ + "swagger", + "info", + "paths" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "swagger": { + "type": "string", + "enum": [ + "2.0" + ], + "description": "The Swagger version of this document." + }, + "info": { + "$ref": "#/definitions/info" + }, + "host": { + "type": "string", + "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$", + "description": "The host (name or ip) of the API. Example: 'swagger.io'" + }, + "basePath": { + "type": "string", + "pattern": "^/", + "description": "The base path to the API. Example: '/api'." + }, + "schemes": { + "$ref": "#/definitions/schemesList" + }, + "consumes": { + "description": "A list of MIME types accepted by the API.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "produces": { + "description": "A list of MIME types the API can produce.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "paths": { + "$ref": "#/definitions/paths" + }, + "definitions": { + "$ref": "#/definitions/definitions" + }, + "parameters": { + "$ref": "#/definitions/parameterDefinitions" + }, + "responses": { + "$ref": "#/definitions/responseDefinitions" + }, + "security": { + "$ref": "#/definitions/security" + }, + "securityDefinitions": { + "$ref": "#/definitions/securityDefinitions" + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/definitions/tag" + }, + "uniqueItems": true + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + } + }, + "definitions": { + "info": { + "type": "object", + "description": "General information about the API.", + "required": [ + "version", + "title" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "title": { + "type": "string", + "description": "A unique and precise title of the API." + }, + "version": { + "type": "string", + "description": "A semantic version number of the API." + }, + "description": { + "type": "string", + "description": "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed." + }, + "termsOfService": { + "type": "string", + "description": "The terms of service for the API." + }, + "contact": { + "$ref": "#/definitions/contact" + }, + "license": { + "$ref": "#/definitions/license" + } + } + }, + "contact": { + "type": "object", + "description": "Contact information for the owners of the API.", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "The identifying name of the contact person/organization." + }, + "url": { + "type": "string", + "description": "The URL pointing to the contact information.", + "format": "uri" + }, + "email": { + "type": "string", + "description": "The email address of the contact person/organization.", + "format": "email" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "license": { + "type": "object", + "required": [ + "name" + ], + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "The name of the license type. It's encouraged to use an OSI compatible license." + }, + "url": { + "type": "string", + "description": "The URL pointing to the license.", + "format": "uri" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "paths": { + "type": "object", + "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + }, + "^/": { + "$ref": "#/definitions/pathItem" + } + }, + "additionalProperties": false + }, + "definitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/schema" + }, + "description": "One or more JSON objects describing the schemas being consumed and produced by the API." + }, + "parameterDefinitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/parameter" + }, + "description": "One or more JSON representations for parameters" + }, + "responseDefinitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/response" + }, + "description": "One or more JSON representations for parameters" + }, + "externalDocs": { + "type": "object", + "additionalProperties": false, + "description": "information about external documentation", + "required": [ + "url" + ], + "properties": { + "description": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "examples": { + "type": "object", + "additionalProperties": true + }, + "mimeType": { + "type": "string", + "description": "The MIME type of the HTTP message." + }, + "operation": { + "type": "object", + "required": [ + "responses" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "summary": { + "type": "string", + "description": "A brief summary of the operation." + }, + "description": { + "type": "string", + "description": "A longer description of the operation, GitHub Flavored Markdown is allowed." + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "operationId": { + "type": "string", + "description": "A unique identifier of the operation." + }, + "produces": { + "description": "A list of MIME types the API can produce.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "consumes": { + "description": "A list of MIME types the API can consume.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "parameters": { + "$ref": "#/definitions/parametersList" + }, + "responses": { + "$ref": "#/definitions/responses" + }, + "schemes": { + "$ref": "#/definitions/schemesList" + }, + "deprecated": { + "type": "boolean", + "default": false + }, + "security": { + "$ref": "#/definitions/security" + } + } + }, + "pathItem": { + "type": "object", + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "$ref": { + "type": "string" + }, + "get": { + "$ref": "#/definitions/operation" + }, + "put": { + "$ref": "#/definitions/operation" + }, + "post": { + "$ref": "#/definitions/operation" + }, + "delete": { + "$ref": "#/definitions/operation" + }, + "options": { + "$ref": "#/definitions/operation" + }, + "head": { + "$ref": "#/definitions/operation" + }, + "patch": { + "$ref": "#/definitions/operation" + }, + "parameters": { + "$ref": "#/definitions/parametersList" + } + } + }, + "responses": { + "type": "object", + "description": "Response objects names can either be any valid HTTP status code or 'default'.", + "minProperties": 1, + "additionalProperties": false, + "patternProperties": { + "^([0-9]{3})$|^(default)$": { + "$ref": "#/definitions/responseValue" + }, + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "not": { + "type": "object", + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + } + }, + "responseValue": { + "oneOf": [ + { + "$ref": "#/definitions/response" + }, + { + "$ref": "#/definitions/jsonReference" + } + ] + }, + "response": { + "type": "object", + "required": [ + "description" + ], + "properties": { + "description": { + "type": "string" + }, + "schema": { + "oneOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "$ref": "#/definitions/fileSchema" + } + ] + }, + "headers": { + "$ref": "#/definitions/headers" + }, + "examples": { + "$ref": "#/definitions/examples" + } + }, + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/header" + } + }, + "header": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "vendorExtension": { + "description": "Any property starting with x- is valid.", + "additionalProperties": true, + "additionalItems": true + }, + "bodyParameter": { + "type": "object", + "required": [ + "name", + "in", + "schema" + ], + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "body" + ] + }, + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "schema": { + "$ref": "#/definitions/schema" + } + }, + "additionalProperties": false + }, + "headerParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "header" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "queryParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "query" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "allowEmptyValue": { + "type": "boolean", + "default": false, + "description": "allows sending a parameter by name only or with an empty value." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormatWithMulti" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "formDataParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "formData" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "allowEmptyValue": { + "type": "boolean", + "default": false, + "description": "allows sending a parameter by name only or with an empty value." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array", + "file" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormatWithMulti" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "pathParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "required": [ + "required" + ], + "properties": { + "required": { + "type": "boolean", + "enum": [ + true + ], + "description": "Determines whether or not this parameter is required or optional." + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "path" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "nonBodyParameter": { + "type": "object", + "required": [ + "name", + "in", + "type" + ], + "oneOf": [ + { + "$ref": "#/definitions/headerParameterSubSchema" + }, + { + "$ref": "#/definitions/formDataParameterSubSchema" + }, + { + "$ref": "#/definitions/queryParameterSubSchema" + }, + { + "$ref": "#/definitions/pathParameterSubSchema" + } + ] + }, + "parameter": { + "oneOf": [ + { + "$ref": "#/definitions/bodyParameter" + }, + { + "$ref": "#/definitions/nonBodyParameter" + } + ] + }, + "schema": { + "type": "object", + "description": "A deterministic version of a JSON Schema object.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "$ref": { + "type": "string" + }, + "format": { + "type": "string" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "multipleOf": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + "maximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + "exclusiveMaximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + "minimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + "exclusiveMinimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + "maxLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + "maxItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "maxProperties": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minProperties": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "required": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "enum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" + }, + "additionalProperties": { + "anyOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "type": "boolean" + } + ], + "default": {} + }, + "type": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/type" + }, + "items": { + "anyOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/schema" + } + } + ], + "default": {} + }, + "allOf": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/schema" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/schema" + }, + "default": {} + }, + "discriminator": { + "type": "string" + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "xml": { + "$ref": "#/definitions/xml" + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "example": {} + }, + "additionalProperties": false + }, + "fileSchema": { + "type": "object", + "description": "A deterministic version of a JSON Schema object.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "required": [ + "type" + ], + "properties": { + "format": { + "type": "string" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "required": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "type": { + "type": "string", + "enum": [ + "file" + ] + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "example": {} + }, + "additionalProperties": false + }, + "primitivesItems": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "security": { + "type": "array", + "items": { + "$ref": "#/definitions/securityRequirement" + }, + "uniqueItems": true + }, + "securityRequirement": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + } + }, + "xml": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "prefix": { + "type": "string" + }, + "attribute": { + "type": "boolean", + "default": false + }, + "wrapped": { + "type": "boolean", + "default": false + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "tag": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "securityDefinitions": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "$ref": "#/definitions/basicAuthenticationSecurity" + }, + { + "$ref": "#/definitions/apiKeySecurity" + }, + { + "$ref": "#/definitions/oauth2ImplicitSecurity" + }, + { + "$ref": "#/definitions/oauth2PasswordSecurity" + }, + { + "$ref": "#/definitions/oauth2ApplicationSecurity" + }, + { + "$ref": "#/definitions/oauth2AccessCodeSecurity" + } + ] + } + }, + "basicAuthenticationSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "basic" + ] + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "apiKeySecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "name", + "in" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "apiKey" + ] + }, + "name": { + "type": "string" + }, + "in": { + "type": "string", + "enum": [ + "header", + "query" + ] + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2ImplicitSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "authorizationUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "implicit" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "authorizationUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2PasswordSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "password" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2ApplicationSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "application" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2AccessCodeSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "authorizationUrl", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "accessCode" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "authorizationUrl": { + "type": "string", + "format": "uri" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2Scopes": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "mediaTypeList": { + "type": "array", + "items": { + "$ref": "#/definitions/mimeType" + }, + "uniqueItems": true + }, + "parametersList": { + "type": "array", + "description": "The parameters needed to send a valid API call.", + "additionalItems": false, + "items": { + "oneOf": [ + { + "$ref": "#/definitions/parameter" + }, + { + "$ref": "#/definitions/jsonReference" + } + ] + }, + "uniqueItems": true + }, + "schemesList": { + "type": "array", + "description": "The transfer protocol of the API.", + "items": { + "type": "string", + "enum": [ + "http", + "https", + "ws", + "wss" + ] + }, + "uniqueItems": true + }, + "collectionFormat": { + "type": "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes" + ], + "default": "csv" + }, + "collectionFormatWithMulti": { + "type": "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes", + "multi" + ], + "default": "csv" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "multipleOf": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + "maximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + "exclusiveMaximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + "minimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + "exclusiveMinimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + "maxLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + "maxItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "enum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" + }, + "jsonReference": { + "type": "object", + "required": [ + "$ref" + ], + "additionalProperties": false, + "properties": { + "$ref": { + "type": "string" + } + } + } + } + }, + "tests": [ + { + "description": "Example petsore", + "data": { + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "tags": [ + { + "name": "pet", + "description": "Everything about your Pets", + "externalDocs": { + "description": "Find out more", + "url": "http://swagger.io" + } + }, + { + "name": "store", + "description": "Access to Petstore orders" + }, + { + "name": "user", + "description": "Operations about user", + "externalDocs": { + "description": "Find out more about our store", + "url": "http://swagger.io" + } + } + ], + "schemes": [ + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + }, + "405": { + "description": "Validation exception" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma separated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": true, + "type": "array", + "items": { + "type": "string", + "enum": [ + "available", + "pending", + "sold" + ], + "default": "available" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ], + "deprecated": true + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a single pet", + "operationId": "getPetById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to return", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": true, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "maximum": 10.0, + "minimum": 1.0, + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "integer", + "minimum": 1.0, + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when token expires" + } + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be updated", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + } + } + }, + "securityDefinitions": { + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + } + }, + "definitions": { + "Order": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Pet": { + "type": "object", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "ApiResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + }, + "externalDocs": { + "description": "Find out more about Swagger", + "url": "http://swagger.io" + } + }, + "valid": true + } + ] + } +] diff --git a/shared/package-files/79/79a475c15474ac4ae70f710f00daae0aecaaa5bc72e557c556131e9d69413c31/blob b/shared/package-files/79/79a475c15474ac4ae70f710f00daae0aecaaa5bc72e557c556131e9d69413c31/blob new file mode 100644 index 0000000000000000000000000000000000000000..22ccb39211e113e68a3c4121d0a68181d6d9c9f8 --- /dev/null +++ b/shared/package-files/79/79a475c15474ac4ae70f710f00daae0aecaaa5bc72e557c556131e9d69413c31/blob @@ -0,0 +1,1283 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2001-2017 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""DNS Names. +""" + +import copy +import encodings.idna # type: ignore +import functools +import struct +from typing import Any, Callable, Dict, Iterable, Optional, Tuple, Union + +import dns._features +import dns.enum +import dns.exception +import dns.immutable +import dns.wire + +if dns._features.have("idna"): + import idna # type: ignore + + have_idna_2008 = True +else: # pragma: no cover + have_idna_2008 = False + +CompressType = Dict["Name", int] + + +class NameRelation(dns.enum.IntEnum): + """Name relation result from fullcompare().""" + + # This is an IntEnum for backwards compatibility in case anyone + # has hardwired the constants. + + #: The compared names have no relationship to each other. + NONE = 0 + #: the first name is a superdomain of the second. + SUPERDOMAIN = 1 + #: The first name is a subdomain of the second. + SUBDOMAIN = 2 + #: The compared names are equal. + EQUAL = 3 + #: The compared names have a common ancestor. + COMMONANCESTOR = 4 + + @classmethod + def _maximum(cls): + return cls.COMMONANCESTOR + + @classmethod + def _short_name(cls): + return cls.__name__ + + +# Backwards compatibility +NAMERELN_NONE = NameRelation.NONE +NAMERELN_SUPERDOMAIN = NameRelation.SUPERDOMAIN +NAMERELN_SUBDOMAIN = NameRelation.SUBDOMAIN +NAMERELN_EQUAL = NameRelation.EQUAL +NAMERELN_COMMONANCESTOR = NameRelation.COMMONANCESTOR + + +class EmptyLabel(dns.exception.SyntaxError): + """A DNS label is empty.""" + + +class BadEscape(dns.exception.SyntaxError): + """An escaped code in a text format of DNS name is invalid.""" + + +class BadPointer(dns.exception.FormError): + """A DNS compression pointer points forward instead of backward.""" + + +class BadLabelType(dns.exception.FormError): + """The label type in DNS name wire format is unknown.""" + + +class NeedAbsoluteNameOrOrigin(dns.exception.DNSException): + """An attempt was made to convert a non-absolute name to + wire when there was also a non-absolute (or missing) origin.""" + + +class NameTooLong(dns.exception.FormError): + """A DNS name is > 255 octets long.""" + + +class LabelTooLong(dns.exception.SyntaxError): + """A DNS label is > 63 octets long.""" + + +class AbsoluteConcatenation(dns.exception.DNSException): + """An attempt was made to append anything other than the + empty name to an absolute DNS name.""" + + +class NoParent(dns.exception.DNSException): + """An attempt was made to get the parent of the root name + or the empty name.""" + + +class NoIDNA2008(dns.exception.DNSException): + """IDNA 2008 processing was requested but the idna module is not + available.""" + + +class IDNAException(dns.exception.DNSException): + """IDNA processing raised an exception.""" + + supp_kwargs = {"idna_exception"} + fmt = "IDNA processing exception: {idna_exception}" + + # We do this as otherwise mypy complains about unexpected keyword argument + # idna_exception + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +class NeedSubdomainOfOrigin(dns.exception.DNSException): + """An absolute name was provided that is not a subdomain of the specified origin.""" + + +_escaped = b'"().;\\@$' +_escaped_text = '"().;\\@$' + + +def _escapify(label: Union[bytes, str]) -> str: + """Escape the characters in label which need it. + @returns: the escaped string + @rtype: string""" + if isinstance(label, bytes): + # Ordinary DNS label mode. Escape special characters and values + # < 0x20 or > 0x7f. + text = "" + for c in label: + if c in _escaped: + text += "\\" + chr(c) + elif c > 0x20 and c < 0x7F: + text += chr(c) + else: + text += "\\%03d" % c + return text + + # Unicode label mode. Escape only special characters and values < 0x20 + text = "" + for uc in label: + if uc in _escaped_text: + text += "\\" + uc + elif uc <= "\x20": + text += "\\%03d" % ord(uc) + else: + text += uc + return text + + +class IDNACodec: + """Abstract base class for IDNA encoder/decoders.""" + + def __init__(self): + pass + + def is_idna(self, label: bytes) -> bool: + return label.lower().startswith(b"xn--") + + def encode(self, label: str) -> bytes: + raise NotImplementedError # pragma: no cover + + def decode(self, label: bytes) -> str: + # We do not apply any IDNA policy on decode. + if self.is_idna(label): + try: + slabel = label[4:].decode("punycode") + return _escapify(slabel) + except Exception as e: + raise IDNAException(idna_exception=e) + else: + return _escapify(label) + + +class IDNA2003Codec(IDNACodec): + """IDNA 2003 encoder/decoder.""" + + def __init__(self, strict_decode: bool = False): + """Initialize the IDNA 2003 encoder/decoder. + + *strict_decode* is a ``bool``. If `True`, then IDNA2003 checking + is done when decoding. This can cause failures if the name + was encoded with IDNA2008. The default is `False`. + """ + + super().__init__() + self.strict_decode = strict_decode + + def encode(self, label: str) -> bytes: + """Encode *label*.""" + + if label == "": + return b"" + try: + return encodings.idna.ToASCII(label) + except UnicodeError: + raise LabelTooLong + + def decode(self, label: bytes) -> str: + """Decode *label*.""" + if not self.strict_decode: + return super().decode(label) + if label == b"": + return "" + try: + return _escapify(encodings.idna.ToUnicode(label)) + except Exception as e: + raise IDNAException(idna_exception=e) + + +class IDNA2008Codec(IDNACodec): + """IDNA 2008 encoder/decoder.""" + + def __init__( + self, + uts_46: bool = False, + transitional: bool = False, + allow_pure_ascii: bool = False, + strict_decode: bool = False, + ): + """Initialize the IDNA 2008 encoder/decoder. + + *uts_46* is a ``bool``. If True, apply Unicode IDNA + compatibility processing as described in Unicode Technical + Standard #46 (https://unicode.org/reports/tr46/). + If False, do not apply the mapping. The default is False. + + *transitional* is a ``bool``: If True, use the + "transitional" mode described in Unicode Technical Standard + #46. The default is False. + + *allow_pure_ascii* is a ``bool``. If True, then a label which + consists of only ASCII characters is allowed. This is less + strict than regular IDNA 2008, but is also necessary for mixed + names, e.g. a name with starting with "_sip._tcp." and ending + in an IDN suffix which would otherwise be disallowed. The + default is False. + + *strict_decode* is a ``bool``: If True, then IDNA2008 checking + is done when decoding. This can cause failures if the name + was encoded with IDNA2003. The default is False. + """ + super().__init__() + self.uts_46 = uts_46 + self.transitional = transitional + self.allow_pure_ascii = allow_pure_ascii + self.strict_decode = strict_decode + + def encode(self, label: str) -> bytes: + if label == "": + return b"" + if self.allow_pure_ascii and is_all_ascii(label): + encoded = label.encode("ascii") + if len(encoded) > 63: + raise LabelTooLong + return encoded + if not have_idna_2008: + raise NoIDNA2008 + try: + if self.uts_46: + label = idna.uts46_remap(label, False, self.transitional) + return idna.alabel(label) + except idna.IDNAError as e: + if e.args[0] == "Label too long": + raise LabelTooLong + else: + raise IDNAException(idna_exception=e) + + def decode(self, label: bytes) -> str: + if not self.strict_decode: + return super().decode(label) + if label == b"": + return "" + if not have_idna_2008: + raise NoIDNA2008 + try: + ulabel = idna.ulabel(label) + if self.uts_46: + ulabel = idna.uts46_remap(ulabel, False, self.transitional) + return _escapify(ulabel) + except (idna.IDNAError, UnicodeError) as e: + raise IDNAException(idna_exception=e) + + +IDNA_2003_Practical = IDNA2003Codec(False) +IDNA_2003_Strict = IDNA2003Codec(True) +IDNA_2003 = IDNA_2003_Practical +IDNA_2008_Practical = IDNA2008Codec(True, False, True, False) +IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False) +IDNA_2008_Strict = IDNA2008Codec(False, False, False, True) +IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False) +IDNA_2008 = IDNA_2008_Practical + + +def _validate_labels(labels: Tuple[bytes, ...]) -> None: + """Check for empty labels in the middle of a label sequence, + labels that are too long, and for too many labels. + + Raises ``dns.name.NameTooLong`` if the name as a whole is too long. + + Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root + label) and appears in a position other than the end of the label + sequence + + """ + + l = len(labels) + total = 0 + i = -1 + j = 0 + for label in labels: + ll = len(label) + total += ll + 1 + if ll > 63: + raise LabelTooLong + if i < 0 and label == b"": + i = j + j += 1 + if total > 255: + raise NameTooLong + if i >= 0 and i != l - 1: + raise EmptyLabel + + +def _maybe_convert_to_binary(label: Union[bytes, str]) -> bytes: + """If label is ``str``, convert it to ``bytes``. If it is already + ``bytes`` just return it. + + """ + + if isinstance(label, bytes): + return label + if isinstance(label, str): + return label.encode() + raise ValueError # pragma: no cover + + +@dns.immutable.immutable +class Name: + """A DNS name. + + The dns.name.Name class represents a DNS name as a tuple of + labels. Each label is a ``bytes`` in DNS wire format. Instances + of the class are immutable. + """ + + __slots__ = ["labels"] + + def __init__(self, labels: Iterable[Union[bytes, str]]): + """*labels* is any iterable whose values are ``str`` or ``bytes``.""" + + blabels = [_maybe_convert_to_binary(x) for x in labels] + self.labels = tuple(blabels) + _validate_labels(self.labels) + + def __copy__(self): + return Name(self.labels) + + def __deepcopy__(self, memo): + return Name(copy.deepcopy(self.labels, memo)) + + def __getstate__(self): + # Names can be pickled + return {"labels": self.labels} + + def __setstate__(self, state): + super().__setattr__("labels", state["labels"]) + _validate_labels(self.labels) + + def is_absolute(self) -> bool: + """Is the most significant label of this name the root label? + + Returns a ``bool``. + """ + + return len(self.labels) > 0 and self.labels[-1] == b"" + + def is_wild(self) -> bool: + """Is this name wild? (I.e. Is the least significant label '*'?) + + Returns a ``bool``. + """ + + return len(self.labels) > 0 and self.labels[0] == b"*" + + def __hash__(self) -> int: + """Return a case-insensitive hash of the name. + + Returns an ``int``. + """ + + h = 0 + for label in self.labels: + for c in label.lower(): + h += (h << 3) + c + return h + + def fullcompare(self, other: "Name") -> Tuple[NameRelation, int, int]: + """Compare two names, returning a 3-tuple + ``(relation, order, nlabels)``. + + *relation* describes the relation ship between the names, + and is one of: ``dns.name.NameRelation.NONE``, + ``dns.name.NameRelation.SUPERDOMAIN``, ``dns.name.NameRelation.SUBDOMAIN``, + ``dns.name.NameRelation.EQUAL``, or ``dns.name.NameRelation.COMMONANCESTOR``. + + *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and == + 0 if *self* == *other*. A relative name is always less than an + absolute name. If both names have the same relativity, then + the DNSSEC order relation is used to order them. + + *nlabels* is the number of significant labels that the two names + have in common. + + Here are some examples. Names ending in "." are absolute names, + those not ending in "." are relative names. + + ============= ============= =========== ===== ======= + self other relation order nlabels + ============= ============= =========== ===== ======= + www.example. www.example. equal 0 3 + www.example. example. subdomain > 0 2 + example. www.example. superdomain < 0 2 + example1.com. example2.com. common anc. < 0 2 + example1 example2. none < 0 0 + example1. example2 none > 0 0 + ============= ============= =========== ===== ======= + """ + + sabs = self.is_absolute() + oabs = other.is_absolute() + if sabs != oabs: + if sabs: + return (NameRelation.NONE, 1, 0) + else: + return (NameRelation.NONE, -1, 0) + l1 = len(self.labels) + l2 = len(other.labels) + ldiff = l1 - l2 + if ldiff < 0: + l = l1 + else: + l = l2 + + order = 0 + nlabels = 0 + namereln = NameRelation.NONE + while l > 0: + l -= 1 + l1 -= 1 + l2 -= 1 + label1 = self.labels[l1].lower() + label2 = other.labels[l2].lower() + if label1 < label2: + order = -1 + if nlabels > 0: + namereln = NameRelation.COMMONANCESTOR + return (namereln, order, nlabels) + elif label1 > label2: + order = 1 + if nlabels > 0: + namereln = NameRelation.COMMONANCESTOR + return (namereln, order, nlabels) + nlabels += 1 + order = ldiff + if ldiff < 0: + namereln = NameRelation.SUPERDOMAIN + elif ldiff > 0: + namereln = NameRelation.SUBDOMAIN + else: + namereln = NameRelation.EQUAL + return (namereln, order, nlabels) + + def is_subdomain(self, other: "Name") -> bool: + """Is self a subdomain of other? + + Note that the notion of subdomain includes equality, e.g. + "dnspython.org" is a subdomain of itself. + + Returns a ``bool``. + """ + + (nr, _, _) = self.fullcompare(other) + if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL: + return True + return False + + def is_superdomain(self, other: "Name") -> bool: + """Is self a superdomain of other? + + Note that the notion of superdomain includes equality, e.g. + "dnspython.org" is a superdomain of itself. + + Returns a ``bool``. + """ + + (nr, _, _) = self.fullcompare(other) + if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL: + return True + return False + + def canonicalize(self) -> "Name": + """Return a name which is equal to the current name, but is in + DNSSEC canonical form. + """ + + return Name([x.lower() for x in self.labels]) + + def __eq__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] == 0 + else: + return False + + def __ne__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] != 0 + else: + return True + + def __lt__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] < 0 + else: + return NotImplemented + + def __le__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] <= 0 + else: + return NotImplemented + + def __ge__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] >= 0 + else: + return NotImplemented + + def __gt__(self, other): + if isinstance(other, Name): + return self.fullcompare(other)[1] > 0 + else: + return NotImplemented + + def __repr__(self): + return "" + + def __str__(self): + return self.to_text(False) + + def to_text(self, omit_final_dot: bool = False) -> str: + """Convert name to DNS text format. + + *omit_final_dot* is a ``bool``. If True, don't emit the final + dot (denoting the root label) for absolute names. The default + is False. + + Returns a ``str``. + """ + + if len(self.labels) == 0: + return "@" + if len(self.labels) == 1 and self.labels[0] == b"": + return "." + if omit_final_dot and self.is_absolute(): + l = self.labels[:-1] + else: + l = self.labels + s = ".".join(map(_escapify, l)) + return s + + def to_unicode( + self, omit_final_dot: bool = False, idna_codec: Optional[IDNACodec] = None + ) -> str: + """Convert name to Unicode text format. + + IDN ACE labels are converted to Unicode. + + *omit_final_dot* is a ``bool``. If True, don't emit the final + dot (denoting the root label) for absolute names. The default + is False. + *idna_codec* specifies the IDNA encoder/decoder. If None, the + dns.name.IDNA_2003_Practical encoder/decoder is used. + The IDNA_2003_Practical decoder does + not impose any policy, it just decodes punycode, so if you + don't want checking for compliance, you can use this decoder + for IDNA2008 as well. + + Returns a ``str``. + """ + + if len(self.labels) == 0: + return "@" + if len(self.labels) == 1 and self.labels[0] == b"": + return "." + if omit_final_dot and self.is_absolute(): + l = self.labels[:-1] + else: + l = self.labels + if idna_codec is None: + idna_codec = IDNA_2003_Practical + return ".".join([idna_codec.decode(x) for x in l]) + + def to_digestable(self, origin: Optional["Name"] = None) -> bytes: + """Convert name to a format suitable for digesting in hashes. + + The name is canonicalized and converted to uncompressed wire + format. All names in wire format are absolute. If the name + is a relative name, then an origin must be supplied. + + *origin* is a ``dns.name.Name`` or ``None``. If the name is + relative and origin is not ``None``, then origin will be appended + to the name. + + Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is + relative and no origin was provided. + + Returns a ``bytes``. + """ + + digest = self.to_wire(origin=origin, canonicalize=True) + assert digest is not None + return digest + + def to_wire( + self, + file: Optional[Any] = None, + compress: Optional[CompressType] = None, + origin: Optional["Name"] = None, + canonicalize: bool = False, + ) -> Optional[bytes]: + """Convert name to wire format, possibly compressing it. + + *file* is the file where the name is emitted (typically an + io.BytesIO file). If ``None`` (the default), a ``bytes`` + containing the wire name will be returned. + + *compress*, a ``dict``, is the compression table to use. If + ``None`` (the default), names will not be compressed. Note that + the compression code assumes that compression offset 0 is the + start of *file*, and thus compression will not be correct + if this is not the case. + + *origin* is a ``dns.name.Name`` or ``None``. If the name is + relative and origin is not ``None``, then *origin* will be appended + to it. + + *canonicalize*, a ``bool``, indicates whether the name should + be canonicalized; that is, converted to a format suitable for + digesting in hashes. + + Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is + relative and no origin was provided. + + Returns a ``bytes`` or ``None``. + """ + + if file is None: + out = bytearray() + for label in self.labels: + out.append(len(label)) + if canonicalize: + out += label.lower() + else: + out += label + if not self.is_absolute(): + if origin is None or not origin.is_absolute(): + raise NeedAbsoluteNameOrOrigin + for label in origin.labels: + out.append(len(label)) + if canonicalize: + out += label.lower() + else: + out += label + return bytes(out) + + labels: Iterable[bytes] + if not self.is_absolute(): + if origin is None or not origin.is_absolute(): + raise NeedAbsoluteNameOrOrigin + labels = list(self.labels) + labels.extend(list(origin.labels)) + else: + labels = self.labels + i = 0 + for label in labels: + n = Name(labels[i:]) + i += 1 + if compress is not None: + pos = compress.get(n) + else: + pos = None + if pos is not None: + value = 0xC000 + pos + s = struct.pack("!H", value) + file.write(s) + break + else: + if compress is not None and len(n) > 1: + pos = file.tell() + if pos <= 0x3FFF: + compress[n] = pos + l = len(label) + file.write(struct.pack("!B", l)) + if l > 0: + if canonicalize: + file.write(label.lower()) + else: + file.write(label) + return None + + def __len__(self) -> int: + """The length of the name (in labels). + + Returns an ``int``. + """ + + return len(self.labels) + + def __getitem__(self, index): + return self.labels[index] + + def __add__(self, other): + return self.concatenate(other) + + def __sub__(self, other): + return self.relativize(other) + + def split(self, depth: int) -> Tuple["Name", "Name"]: + """Split a name into a prefix and suffix names at the specified depth. + + *depth* is an ``int`` specifying the number of labels in the suffix + + Raises ``ValueError`` if *depth* was not >= 0 and <= the length of the + name. + + Returns the tuple ``(prefix, suffix)``. + """ + + l = len(self.labels) + if depth == 0: + return (self, dns.name.empty) + elif depth == l: + return (dns.name.empty, self) + elif depth < 0 or depth > l: + raise ValueError("depth must be >= 0 and <= the length of the name") + return (Name(self[:-depth]), Name(self[-depth:])) + + def concatenate(self, other: "Name") -> "Name": + """Return a new name which is the concatenation of self and other. + + Raises ``dns.name.AbsoluteConcatenation`` if the name is + absolute and *other* is not the empty name. + + Returns a ``dns.name.Name``. + """ + + if self.is_absolute() and len(other) > 0: + raise AbsoluteConcatenation + labels = list(self.labels) + labels.extend(list(other.labels)) + return Name(labels) + + def relativize(self, origin: "Name") -> "Name": + """If the name is a subdomain of *origin*, return a new name which is + the name relative to origin. Otherwise return the name. + + For example, relativizing ``www.dnspython.org.`` to origin + ``dnspython.org.`` returns the name ``www``. Relativizing ``example.`` + to origin ``dnspython.org.`` returns ``example.``. + + Returns a ``dns.name.Name``. + """ + + if origin is not None and self.is_subdomain(origin): + return Name(self[: -len(origin)]) + else: + return self + + def derelativize(self, origin: "Name") -> "Name": + """If the name is a relative name, return a new name which is the + concatenation of the name and origin. Otherwise return the name. + + For example, derelativizing ``www`` to origin ``dnspython.org.`` + returns the name ``www.dnspython.org.``. Derelativizing ``example.`` + to origin ``dnspython.org.`` returns ``example.``. + + Returns a ``dns.name.Name``. + """ + + if not self.is_absolute(): + return self.concatenate(origin) + else: + return self + + def choose_relativity( + self, origin: Optional["Name"] = None, relativize: bool = True + ) -> "Name": + """Return a name with the relativity desired by the caller. + + If *origin* is ``None``, then the name is returned. + Otherwise, if *relativize* is ``True`` the name is + relativized, and if *relativize* is ``False`` the name is + derelativized. + + Returns a ``dns.name.Name``. + """ + + if origin: + if relativize: + return self.relativize(origin) + else: + return self.derelativize(origin) + else: + return self + + def parent(self) -> "Name": + """Return the parent of the name. + + For example, the parent of ``www.dnspython.org.`` is ``dnspython.org``. + + Raises ``dns.name.NoParent`` if the name is either the root name or the + empty name, and thus has no parent. + + Returns a ``dns.name.Name``. + """ + + if self == root or self == empty: + raise NoParent + return Name(self.labels[1:]) + + def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name": + """Return the maximal predecessor of *name* in the DNSSEC ordering in the zone + whose origin is *origin*, or return the longest name under *origin* if the + name is origin (i.e. wrap around to the longest name, which may still be + *origin* due to length considerations. + + The relativity of the name is preserved, so if this name is relative + then the method will return a relative name, and likewise if this name + is absolute then the predecessor will be absolute. + + *prefix_ok* indicates if prefixing labels is allowed, and + defaults to ``True``. Normally it is good to allow this, but if computing + a maximal predecessor at a zone cut point then ``False`` must be specified. + """ + return _handle_relativity_and_call( + _absolute_predecessor, self, origin, prefix_ok + ) + + def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name": + """Return the minimal successor of *name* in the DNSSEC ordering in the zone + whose origin is *origin*, or return *origin* if the successor cannot be + computed due to name length limitations. + + Note that *origin* is returned in the "too long" cases because wrapping + around to the origin is how NSEC records express "end of the zone". + + The relativity of the name is preserved, so if this name is relative + then the method will return a relative name, and likewise if this name + is absolute then the successor will be absolute. + + *prefix_ok* indicates if prefixing a new minimal label is allowed, and + defaults to ``True``. Normally it is good to allow this, but if computing + a minimal successor at a zone cut point then ``False`` must be specified. + """ + return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok) + + +#: The root name, '.' +root = Name([b""]) + +#: The empty name. +empty = Name([]) + + +def from_unicode( + text: str, origin: Optional[Name] = root, idna_codec: Optional[IDNACodec] = None +) -> Name: + """Convert unicode text into a Name object. + + Labels are encoded in IDN ACE form according to rules specified by + the IDNA codec. + + *text*, a ``str``, is the text to convert into a name. + + *origin*, a ``dns.name.Name``, specifies the origin to + append to non-absolute names. The default is the root name. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + Returns a ``dns.name.Name``. + """ + + if not isinstance(text, str): + raise ValueError("input to from_unicode() must be a unicode string") + if not (origin is None or isinstance(origin, Name)): + raise ValueError("origin must be a Name or None") + labels = [] + label = "" + escaping = False + edigits = 0 + total = 0 + if idna_codec is None: + idna_codec = IDNA_2003 + if text == "@": + text = "" + if text: + if text in [".", "\u3002", "\uff0e", "\uff61"]: + return Name([b""]) # no Unicode "u" on this constant! + for c in text: + if escaping: + if edigits == 0: + if c.isdigit(): + total = int(c) + edigits += 1 + else: + label += c + escaping = False + else: + if not c.isdigit(): + raise BadEscape + total *= 10 + total += int(c) + edigits += 1 + if edigits == 3: + escaping = False + label += chr(total) + elif c in [".", "\u3002", "\uff0e", "\uff61"]: + if len(label) == 0: + raise EmptyLabel + labels.append(idna_codec.encode(label)) + label = "" + elif c == "\\": + escaping = True + edigits = 0 + total = 0 + else: + label += c + if escaping: + raise BadEscape + if len(label) > 0: + labels.append(idna_codec.encode(label)) + else: + labels.append(b"") + + if (len(labels) == 0 or labels[-1] != b"") and origin is not None: + labels.extend(list(origin.labels)) + return Name(labels) + + +def is_all_ascii(text: str) -> bool: + for c in text: + if ord(c) > 0x7F: + return False + return True + + +def from_text( + text: Union[bytes, str], + origin: Optional[Name] = root, + idna_codec: Optional[IDNACodec] = None, +) -> Name: + """Convert text into a Name object. + + *text*, a ``bytes`` or ``str``, is the text to convert into a name. + + *origin*, a ``dns.name.Name``, specifies the origin to + append to non-absolute names. The default is the root name. + + *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA + encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder + is used. + + Returns a ``dns.name.Name``. + """ + + if isinstance(text, str): + if not is_all_ascii(text): + # Some codepoint in the input text is > 127, so IDNA applies. + return from_unicode(text, origin, idna_codec) + # The input is all ASCII, so treat this like an ordinary non-IDNA + # domain name. Note that "all ASCII" is about the input text, + # not the codepoints in the domain name. E.g. if text has value + # + # r'\150\151\152\153\154\155\156\157\158\159' + # + # then it's still "all ASCII" even though the domain name has + # codepoints > 127. + text = text.encode("ascii") + if not isinstance(text, bytes): + raise ValueError("input to from_text() must be a string") + if not (origin is None or isinstance(origin, Name)): + raise ValueError("origin must be a Name or None") + labels = [] + label = b"" + escaping = False + edigits = 0 + total = 0 + if text == b"@": + text = b"" + if text: + if text == b".": + return Name([b""]) + for c in text: + byte_ = struct.pack("!B", c) + if escaping: + if edigits == 0: + if byte_.isdigit(): + total = int(byte_) + edigits += 1 + else: + label += byte_ + escaping = False + else: + if not byte_.isdigit(): + raise BadEscape + total *= 10 + total += int(byte_) + edigits += 1 + if edigits == 3: + escaping = False + label += struct.pack("!B", total) + elif byte_ == b".": + if len(label) == 0: + raise EmptyLabel + labels.append(label) + label = b"" + elif byte_ == b"\\": + escaping = True + edigits = 0 + total = 0 + else: + label += byte_ + if escaping: + raise BadEscape + if len(label) > 0: + labels.append(label) + else: + labels.append(b"") + if (len(labels) == 0 or labels[-1] != b"") and origin is not None: + labels.extend(list(origin.labels)) + return Name(labels) + + +# we need 'dns.wire.Parser' quoted as dns.name and dns.wire depend on each other. + + +def from_wire_parser(parser: "dns.wire.Parser") -> Name: + """Convert possibly compressed wire format into a Name. + + *parser* is a dns.wire.Parser. + + Raises ``dns.name.BadPointer`` if a compression pointer did not + point backwards in the message. + + Raises ``dns.name.BadLabelType`` if an invalid label type was encountered. + + Returns a ``dns.name.Name`` + """ + + labels = [] + biggest_pointer = parser.current + with parser.restore_furthest(): + count = parser.get_uint8() + while count != 0: + if count < 64: + labels.append(parser.get_bytes(count)) + elif count >= 192: + current = (count & 0x3F) * 256 + parser.get_uint8() + if current >= biggest_pointer: + raise BadPointer + biggest_pointer = current + parser.seek(current) + else: + raise BadLabelType + count = parser.get_uint8() + labels.append(b"") + return Name(labels) + + +def from_wire(message: bytes, current: int) -> Tuple[Name, int]: + """Convert possibly compressed wire format into a Name. + + *message* is a ``bytes`` containing an entire DNS message in DNS + wire form. + + *current*, an ``int``, is the offset of the beginning of the name + from the start of the message + + Raises ``dns.name.BadPointer`` if a compression pointer did not + point backwards in the message. + + Raises ``dns.name.BadLabelType`` if an invalid label type was encountered. + + Returns a ``(dns.name.Name, int)`` tuple consisting of the name + that was read and the number of bytes of the wire format message + which were consumed reading it. + """ + + if not isinstance(message, bytes): + raise ValueError("input to from_wire() must be a byte string") + parser = dns.wire.Parser(message, current) + name = from_wire_parser(parser) + return (name, parser.current - current) + + +# RFC 4471 Support + +_MINIMAL_OCTET = b"\x00" +_MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET) +_SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET]) +_MAXIMAL_OCTET = b"\xff" +_MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET) +_AT_SIGN_VALUE = ord("@") +_LEFT_SQUARE_BRACKET_VALUE = ord("[") + + +def _wire_length(labels): + return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0) + + +def _pad_to_max_name(name): + needed = 255 - _wire_length(name.labels) + new_labels = [] + while needed > 64: + new_labels.append(_MAXIMAL_OCTET * 63) + needed -= 64 + if needed >= 2: + new_labels.append(_MAXIMAL_OCTET * (needed - 1)) + # Note we're already maximal in the needed == 1 case as while we'd like + # to add one more byte as a new label, we can't, as adding a new non-empty + # label requires at least 2 bytes. + new_labels = list(reversed(new_labels)) + new_labels.extend(name.labels) + return Name(new_labels) + + +def _pad_to_max_label(label, suffix_labels): + length = len(label) + # We have to subtract one here to account for the length byte of label. + remaining = 255 - _wire_length(suffix_labels) - length - 1 + if remaining <= 0: + # Shouldn't happen! + return label + needed = min(63 - length, remaining) + return label + _MAXIMAL_OCTET * needed + + +def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name: + # This is the RFC 4471 predecessor algorithm using the "absolute method" of section + # 3.1.1. + # + # Our caller must ensure that the name and origin are absolute, and that name is a + # subdomain of origin. + if name == origin: + return _pad_to_max_name(name) + least_significant_label = name[0] + if least_significant_label == _MINIMAL_OCTET: + return name.parent() + least_octet = least_significant_label[-1] + suffix_labels = name.labels[1:] + if least_octet == _MINIMAL_OCTET_VALUE: + new_labels = [least_significant_label[:-1]] + else: + octets = bytearray(least_significant_label) + octet = octets[-1] + if octet == _LEFT_SQUARE_BRACKET_VALUE: + octet = _AT_SIGN_VALUE + else: + octet -= 1 + octets[-1] = octet + least_significant_label = bytes(octets) + new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)] + new_labels.extend(suffix_labels) + name = Name(new_labels) + if prefix_ok: + return _pad_to_max_name(name) + else: + return name + + +def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name: + # This is the RFC 4471 successor algorithm using the "absolute method" of section + # 3.1.2. + # + # Our caller must ensure that the name and origin are absolute, and that name is a + # subdomain of origin. + if prefix_ok: + # Try prefixing \000 as new label + try: + return _SUCCESSOR_PREFIX.concatenate(name) + except NameTooLong: + pass + while name != origin: + # Try extending the least significant label. + least_significant_label = name[0] + if len(least_significant_label) < 63: + # We may be able to extend the least label with a minimal additional byte. + # This is only "may" because we could have a maximal length name even though + # the least significant label isn't maximally long. + new_labels = [least_significant_label + _MINIMAL_OCTET] + new_labels.extend(name.labels[1:]) + try: + return dns.name.Name(new_labels) + except dns.name.NameTooLong: + pass + # We can't extend the label either, so we'll try to increment the least + # signficant non-maximal byte in it. + octets = bytearray(least_significant_label) + # We do this reversed iteration with an explicit indexing variable because + # if we find something to increment, we're going to want to truncate everything + # to the right of it. + for i in range(len(octets) - 1, -1, -1): + octet = octets[i] + if octet == _MAXIMAL_OCTET_VALUE: + # We can't increment this, so keep looking. + continue + # Finally, something we can increment. We have to apply a special rule for + # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when + # comparing names, uppercase letters compare as if they were their + # lower-case equivalents. If we increment "@" to "A", then it would compare + # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have + # skipped the most minimal successor, namely "[". + if octet == _AT_SIGN_VALUE: + octet = _LEFT_SQUARE_BRACKET_VALUE + else: + octet += 1 + octets[i] = octet + # We can now truncate all of the maximal values we skipped (if any) + new_labels = [bytes(octets[: i + 1])] + new_labels.extend(name.labels[1:]) + # We haven't changed the length of the name, so the Name constructor will + # always work. + return Name(new_labels) + # We couldn't increment, so chop off the least significant label and try + # again. + name = name.parent() + + # We couldn't increment at all, so return the origin, as wrapping around is the + # DNSSEC way. + return origin + + +def _handle_relativity_and_call( + function: Callable[[Name, Name, bool], Name], + name: Name, + origin: Name, + prefix_ok: bool, +) -> Name: + # Make "name" absolute if needed, ensure that the origin is absolute, + # call function(), and then relativize the result if needed. + if not origin.is_absolute(): + raise NeedAbsoluteNameOrOrigin + relative = not name.is_absolute() + if relative: + name = name.derelativize(origin) + elif not name.is_subdomain(origin): + raise NeedSubdomainOfOrigin + result_name = function(name, origin, prefix_ok) + if relative: + result_name = result_name.relativize(origin) + return result_name diff --git a/shared/package-files/79/79a56868a10be9477478422598c81e6a7ab62003adffe1ff07674bf655a08bd2/blob b/shared/package-files/79/79a56868a10be9477478422598c81e6a7ab62003adffe1ff07674bf655a08bd2/blob new file mode 100644 index 0000000000000000000000000000000000000000..fad2b920cfccaf5644c47e53c7f48eab94b6c6a2 --- /dev/null +++ b/shared/package-files/79/79a56868a10be9477478422598c81e6a7ab62003adffe1ff07674bf655a08bd2/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79a56868a10be9477478422598c81e6a7ab62003adffe1ff07674bf655a08bd2 +size 415194 diff --git a/shared/package-files/79/79a7201a0d136905ce906ee269e628bed5b28cf818098e749873e83e39c73132/blob b/shared/package-files/79/79a7201a0d136905ce906ee269e628bed5b28cf818098e749873e83e39c73132/blob new file mode 100644 index 0000000000000000000000000000000000000000..b3f27114c4a4ed10c1a2526058f4d0dbbd0e5638 --- /dev/null +++ b/shared/package-files/79/79a7201a0d136905ce906ee269e628bed5b28cf818098e749873e83e39c73132/blob @@ -0,0 +1,179 @@ +""" Testing mio5_utils Cython module + +""" +import sys + +from io import BytesIO + +import numpy as np + +from numpy.testing import assert_array_equal, assert_equal, assert_ +from pytest import raises as assert_raises + +import scipy.io.matlab._byteordercodes as boc +import scipy.io.matlab._streams as streams +import scipy.io.matlab._mio5_params as mio5p +import scipy.io.matlab._mio5_utils as m5u + + +def test_byteswap(): + for val in ( + 1, + 0x100, + 0x10000): + a = np.array(val, dtype=np.uint32) + b = a.byteswap() + c = m5u.byteswap_u4(a) + assert_equal(b.item(), c) + d = m5u.byteswap_u4(c) + assert_equal(a.item(), d) + + +def _make_tag(base_dt, val, mdtype, sde=False): + ''' Makes a simple matlab tag, full or sde ''' + base_dt = np.dtype(base_dt) + bo = boc.to_numpy_code(base_dt.byteorder) + byte_count = base_dt.itemsize + if not sde: + udt = bo + 'u4' + padding = 8 - (byte_count % 8) + all_dt = [('mdtype', udt), + ('byte_count', udt), + ('val', base_dt)] + if padding: + all_dt.append(('padding', 'u1', padding)) + else: # is sde + udt = bo + 'u2' + padding = 4-byte_count + if bo == '<': # little endian + all_dt = [('mdtype', udt), + ('byte_count', udt), + ('val', base_dt)] + else: # big endian + all_dt = [('byte_count', udt), + ('mdtype', udt), + ('val', base_dt)] + if padding: + all_dt.append(('padding', 'u1', padding)) + tag = np.zeros((1,), dtype=all_dt) + tag['mdtype'] = mdtype + tag['byte_count'] = byte_count + tag['val'] = val + return tag + + +def _write_stream(stream, *strings): + stream.truncate(0) + stream.seek(0) + for s in strings: + stream.write(s) + stream.seek(0) + + +def _make_readerlike(stream, byte_order=boc.native_code): + class R: + pass + r = R() + r.mat_stream = stream + r.byte_order = byte_order + r.struct_as_record = True + r.uint16_codec = sys.getdefaultencoding() + r.chars_as_strings = False + r.mat_dtype = False + r.squeeze_me = False + return r + + +def test_read_tag(): + # mainly to test errors + # make reader-like thing + str_io = BytesIO() + r = _make_readerlike(str_io) + c_reader = m5u.VarReader5(r) + # This works for StringIO but _not_ BytesIO + assert_raises(OSError, c_reader.read_tag) + # bad SDE + tag = _make_tag('i4', 1, mio5p.miINT32, sde=True) + tag['byte_count'] = 5 + _write_stream(str_io, tag.tobytes()) + assert_raises(ValueError, c_reader.read_tag) + + +def test_read_stream(): + tag = _make_tag('i4', 1, mio5p.miINT32, sde=True) + tag_str = tag.tobytes() + str_io = BytesIO(tag_str) + st = streams.make_stream(str_io) + s = streams._read_into(st, tag.itemsize) + assert_equal(s, tag.tobytes()) + + +def test_read_numeric(): + # make reader-like thing + str_io = BytesIO() + r = _make_readerlike(str_io) + # check simplest of tags + for base_dt, val, mdtype in (('u2', 30, mio5p.miUINT16), + ('i4', 1, mio5p.miINT32), + ('i2', -1, mio5p.miINT16)): + for byte_code in ('<', '>'): + r.byte_order = byte_code + c_reader = m5u.VarReader5(r) + assert_equal(c_reader.little_endian, byte_code == '<') + assert_equal(c_reader.is_swapped, byte_code != boc.native_code) + for sde_f in (False, True): + dt = np.dtype(base_dt).newbyteorder(byte_code) + a = _make_tag(dt, val, mdtype, sde_f) + a_str = a.tobytes() + _write_stream(str_io, a_str) + el = c_reader.read_numeric() + assert_equal(el, val) + # two sequential reads + _write_stream(str_io, a_str, a_str) + el = c_reader.read_numeric() + assert_equal(el, val) + el = c_reader.read_numeric() + assert_equal(el, val) + + +def test_read_numeric_writeable(): + # make reader-like thing + str_io = BytesIO() + r = _make_readerlike(str_io, '<') + c_reader = m5u.VarReader5(r) + dt = np.dtype('>> import parso +>>> module = parso.parse('hello + 1', version="3.9") +>>> expr = module.children[0] +>>> expr +PythonNode(arith_expr, [, , ]) +>>> print(expr.get_code()) +hello + 1 +>>> name = expr.children[0] +>>> name + +>>> name.end_pos +(1, 5) +>>> expr.end_pos +(1, 9) + +To list multiple issues: + +>>> grammar = parso.load_grammar() +>>> module = grammar.parse('foo +\nbar\ncontinue') +>>> error1, error2 = grammar.iter_errors(module) +>>> error1.message +'SyntaxError: invalid syntax' +>>> error2.message +"SyntaxError: 'continue' not properly in loop" +""" + +from parso.parser import ParserSyntaxError +from parso.grammar import Grammar, load_grammar +from parso.utils import split_lines, python_bytes_to_unicode + + +__version__ = '0.8.3' + + +def parse(code=None, **kwargs): + """ + A utility function to avoid loading grammars. + Params are documented in :py:meth:`parso.Grammar.parse`. + + :param str version: The version used by :py:func:`parso.load_grammar`. + """ + version = kwargs.pop('version', None) + grammar = load_grammar(version=version) + return grammar.parse(code, **kwargs) diff --git a/shared/package-files/79/79ab520e444b811afa5f7fa1a0393f49042fd3ae51d0174bd8aedf439e028153/blob b/shared/package-files/79/79ab520e444b811afa5f7fa1a0393f49042fd3ae51d0174bd8aedf439e028153/blob new file mode 100644 index 0000000000000000000000000000000000000000..20b4f2863cc7193ad4b779a30375c865495fa50c --- /dev/null +++ b/shared/package-files/79/79ab520e444b811afa5f7fa1a0393f49042fd3ae51d0174bd8aedf439e028153/blob @@ -0,0 +1,3494 @@ +# ----------------------------------------------------------------------------- +# ply: yacc.py +# +# Copyright (C) 2001-2017 +# David M. Beazley (Dabeaz LLC) +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the David Beazley or Dabeaz LLC may be used to +# endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------------------------- +# +# This implements an LR parser that is constructed from grammar rules defined +# as Python functions. The grammer is specified by supplying the BNF inside +# Python documentation strings. The inspiration for this technique was borrowed +# from John Aycock's Spark parsing system. PLY might be viewed as cross between +# Spark and the GNU bison utility. +# +# The current implementation is only somewhat object-oriented. The +# LR parser itself is defined in terms of an object (which allows multiple +# parsers to co-exist). However, most of the variables used during table +# construction are defined in terms of global variables. Users shouldn't +# notice unless they are trying to define multiple parsers at the same +# time using threads (in which case they should have their head examined). +# +# This implementation supports both SLR and LALR(1) parsing. LALR(1) +# support was originally implemented by Elias Ioup (ezioup@alumni.uchicago.edu), +# using the algorithm found in Aho, Sethi, and Ullman "Compilers: Principles, +# Techniques, and Tools" (The Dragon Book). LALR(1) has since been replaced +# by the more efficient DeRemer and Pennello algorithm. +# +# :::::::: WARNING ::::::: +# +# Construction of LR parsing tables is fairly complicated and expensive. +# To make this module run fast, a *LOT* of work has been put into +# optimization---often at the expensive of readability and what might +# consider to be good Python "coding style." Modify the code at your +# own risk! +# ---------------------------------------------------------------------------- + +import re +import types +import sys +import os.path +import inspect +import base64 +import warnings + +__version__ = '3.10' +__tabversion__ = '3.10' + +#----------------------------------------------------------------------------- +# === User configurable parameters === +# +# Change these to modify the default behavior of yacc (if you wish) +#----------------------------------------------------------------------------- + +yaccdebug = True # Debugging mode. If set, yacc generates a + # a 'parser.out' file in the current directory + +debug_file = 'parser.out' # Default name of the debugging file +tab_module = 'parsetab' # Default name of the table module +default_lr = 'LALR' # Default LR table generation method + +error_count = 3 # Number of symbols that must be shifted to leave recovery mode + +yaccdevel = False # Set to True if developing yacc. This turns off optimized + # implementations of certain functions. + +resultlimit = 40 # Size limit of results when running in debug mode. + +pickle_protocol = 0 # Protocol to use when writing pickle files + +# String type-checking compatibility +if sys.version_info[0] < 3: + string_types = basestring +else: + string_types = str + +MAXINT = sys.maxsize + +# This object is a stand-in for a logging object created by the +# logging module. PLY will use this by default to create things +# such as the parser.out file. If a user wants more detailed +# information, they can create their own logging object and pass +# it into PLY. + +class PlyLogger(object): + def __init__(self, f): + self.f = f + + def debug(self, msg, *args, **kwargs): + self.f.write((msg % args) + '\n') + + info = debug + + def warning(self, msg, *args, **kwargs): + self.f.write('WARNING: ' + (msg % args) + '\n') + + def error(self, msg, *args, **kwargs): + self.f.write('ERROR: ' + (msg % args) + '\n') + + critical = debug + +# Null logger is used when no output is generated. Does nothing. +class NullLogger(object): + def __getattribute__(self, name): + return self + + def __call__(self, *args, **kwargs): + return self + +# Exception raised for yacc-related errors +class YaccError(Exception): + pass + +# Format the result message that the parser produces when running in debug mode. +def format_result(r): + repr_str = repr(r) + if '\n' in repr_str: + repr_str = repr(repr_str) + if len(repr_str) > resultlimit: + repr_str = repr_str[:resultlimit] + ' ...' + result = '<%s @ 0x%x> (%s)' % (type(r).__name__, id(r), repr_str) + return result + +# Format stack entries when the parser is running in debug mode +def format_stack_entry(r): + repr_str = repr(r) + if '\n' in repr_str: + repr_str = repr(repr_str) + if len(repr_str) < 16: + return repr_str + else: + return '<%s @ 0x%x>' % (type(r).__name__, id(r)) + +# Panic mode error recovery support. This feature is being reworked--much of the +# code here is to offer a deprecation/backwards compatible transition + +_errok = None +_token = None +_restart = None +_warnmsg = '''PLY: Don't use global functions errok(), token(), and restart() in p_error(). +Instead, invoke the methods on the associated parser instance: + + def p_error(p): + ... + # Use parser.errok(), parser.token(), parser.restart() + ... + + parser = yacc.yacc() +''' + +def errok(): + warnings.warn(_warnmsg) + return _errok() + +def restart(): + warnings.warn(_warnmsg) + return _restart() + +def token(): + warnings.warn(_warnmsg) + return _token() + +# Utility function to call the p_error() function with some deprecation hacks +def call_errorfunc(errorfunc, token, parser): + global _errok, _token, _restart + _errok = parser.errok + _token = parser.token + _restart = parser.restart + r = errorfunc(token) + try: + del _errok, _token, _restart + except NameError: + pass + return r + +#----------------------------------------------------------------------------- +# === LR Parsing Engine === +# +# The following classes are used for the LR parser itself. These are not +# used during table construction and are independent of the actual LR +# table generation algorithm +#----------------------------------------------------------------------------- + +# This class is used to hold non-terminal grammar symbols during parsing. +# It normally has the following attributes set: +# .type = Grammar symbol type +# .value = Symbol value +# .lineno = Starting line number +# .endlineno = Ending line number (optional, set automatically) +# .lexpos = Starting lex position +# .endlexpos = Ending lex position (optional, set automatically) + +class YaccSymbol: + def __str__(self): + return self.type + + def __repr__(self): + return str(self) + +# This class is a wrapper around the objects actually passed to each +# grammar rule. Index lookup and assignment actually assign the +# .value attribute of the underlying YaccSymbol object. +# The lineno() method returns the line number of a given +# item (or 0 if not defined). The linespan() method returns +# a tuple of (startline,endline) representing the range of lines +# for a symbol. The lexspan() method returns a tuple (lexpos,endlexpos) +# representing the range of positional information for a symbol. + +class YaccProduction: + def __init__(self, s, stack=None): + self.slice = s + self.stack = stack + self.lexer = None + self.parser = None + + def __getitem__(self, n): + if isinstance(n, slice): + return [s.value for s in self.slice[n]] + elif n >= 0: + return self.slice[n].value + else: + return self.stack[n].value + + def __setitem__(self, n, v): + self.slice[n].value = v + + def __getslice__(self, i, j): + return [s.value for s in self.slice[i:j]] + + def __len__(self): + return len(self.slice) + + def lineno(self, n): + return getattr(self.slice[n], 'lineno', 0) + + def set_lineno(self, n, lineno): + self.slice[n].lineno = lineno + + def linespan(self, n): + startline = getattr(self.slice[n], 'lineno', 0) + endline = getattr(self.slice[n], 'endlineno', startline) + return startline, endline + + def lexpos(self, n): + return getattr(self.slice[n], 'lexpos', 0) + + def lexspan(self, n): + startpos = getattr(self.slice[n], 'lexpos', 0) + endpos = getattr(self.slice[n], 'endlexpos', startpos) + return startpos, endpos + + def error(self): + raise SyntaxError + +# ----------------------------------------------------------------------------- +# == LRParser == +# +# The LR Parsing engine. +# ----------------------------------------------------------------------------- + +class LRParser: + def __init__(self, lrtab, errorf): + self.productions = lrtab.lr_productions + self.action = lrtab.lr_action + self.goto = lrtab.lr_goto + self.errorfunc = errorf + self.set_defaulted_states() + self.errorok = True + + def errok(self): + self.errorok = True + + def restart(self): + del self.statestack[:] + del self.symstack[:] + sym = YaccSymbol() + sym.type = '$end' + self.symstack.append(sym) + self.statestack.append(0) + + # Defaulted state support. + # This method identifies parser states where there is only one possible reduction action. + # For such states, the parser can make a choose to make a rule reduction without consuming + # the next look-ahead token. This delayed invocation of the tokenizer can be useful in + # certain kinds of advanced parsing situations where the lexer and parser interact with + # each other or change states (i.e., manipulation of scope, lexer states, etc.). + # + # See: https://www.gnu.org/software/bison/manual/html_node/Default-Reductions.html#Default-Reductions + def set_defaulted_states(self): + self.defaulted_states = {} + for state, actions in self.action.items(): + rules = list(actions.values()) + if len(rules) == 1 and rules[0] < 0: + self.defaulted_states[state] = rules[0] + + def disable_defaulted_states(self): + self.defaulted_states = {} + + def parse(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + if debug or yaccdevel: + if isinstance(debug, int): + debug = PlyLogger(sys.stderr) + return self.parsedebug(input, lexer, debug, tracking, tokenfunc) + elif tracking: + return self.parseopt(input, lexer, debug, tracking, tokenfunc) + else: + return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc) + + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # parsedebug(). + # + # This is the debugging enabled version of parse(). All changes made to the + # parsing engine should be made here. Optimized versions of this function + # are automatically created by the ply/ygen.py script. This script cuts out + # sections enclosed in markers such as this: + # + # #--! DEBUG + # statements + # #--! DEBUG + # + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + def parsedebug(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + #--! parsedebug-start + lookahead = None # Current lookahead symbol + lookaheadstack = [] # Stack of lookahead symbols + actions = self.action # Local reference to action table (to avoid lookup on self.) + goto = self.goto # Local reference to goto table (to avoid lookup on self.) + prod = self.productions # Local reference to production list (to avoid lookup on self.) + defaulted_states = self.defaulted_states # Local reference to defaulted states + pslice = YaccProduction(None) # Production object passed to grammar rules + errorcount = 0 # Used during error recovery + + #--! DEBUG + debug.info('PLY: PARSE DEBUG START') + #--! DEBUG + + # If no lexer was given, we will try to use the lex module + if not lexer: + from . import lex + lexer = lex.lexer + + # Set up the lexer and parser objects on pslice + pslice.lexer = lexer + pslice.parser = self + + # If input was supplied, pass to lexer + if input is not None: + lexer.input(input) + + if tokenfunc is None: + # Tokenize function + get_token = lexer.token + else: + get_token = tokenfunc + + # Set the parser() token method (sometimes used in error recovery) + self.token = get_token + + # Set up the state and symbol stacks + + statestack = [] # Stack of parsing states + self.statestack = statestack + symstack = [] # Stack of grammar symbols + self.symstack = symstack + + pslice.stack = symstack # Put in the production + errtoken = None # Err token + + # The start state is assumed to be (0,$end) + + statestack.append(0) + sym = YaccSymbol() + sym.type = '$end' + symstack.append(sym) + state = 0 + while True: + # Get the next symbol on the input. If a lookahead symbol + # is already set, we just use that. Otherwise, we'll pull + # the next token off of the lookaheadstack or from the lexer + + #--! DEBUG + debug.debug('') + debug.debug('State : %s', state) + #--! DEBUG + + if state not in defaulted_states: + if not lookahead: + if not lookaheadstack: + lookahead = get_token() # Get the next token + else: + lookahead = lookaheadstack.pop() + if not lookahead: + lookahead = YaccSymbol() + lookahead.type = '$end' + + # Check the action table + ltype = lookahead.type + t = actions[state].get(ltype) + else: + t = defaulted_states[state] + #--! DEBUG + debug.debug('Defaulted state %s: Reduce using %d', state, -t) + #--! DEBUG + + #--! DEBUG + debug.debug('Stack : %s', + ('%s . %s' % (' '.join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()) + #--! DEBUG + + if t is not None: + if t > 0: + # shift a symbol on the stack + statestack.append(t) + state = t + + #--! DEBUG + debug.debug('Action : Shift and goto state %s', t) + #--! DEBUG + + symstack.append(lookahead) + lookahead = None + + # Decrease error count on successful shift + if errorcount: + errorcount -= 1 + continue + + if t < 0: + # reduce a symbol on the stack, emit a production + p = prod[-t] + pname = p.name + plen = p.len + + # Get production function + sym = YaccSymbol() + sym.type = pname # Production name + sym.value = None + + #--! DEBUG + if plen: + debug.info('Action : Reduce rule [%s] with %s and goto state %d', p.str, + '['+','.join([format_stack_entry(_v.value) for _v in symstack[-plen:]])+']', + goto[statestack[-1-plen]][pname]) + else: + debug.info('Action : Reduce rule [%s] with %s and goto state %d', p.str, [], + goto[statestack[-1]][pname]) + + #--! DEBUG + + if plen: + targ = symstack[-plen-1:] + targ[0] = sym + + #--! TRACKING + if tracking: + t1 = targ[1] + sym.lineno = t1.lineno + sym.lexpos = t1.lexpos + t1 = targ[-1] + sym.endlineno = getattr(t1, 'endlineno', t1.lineno) + sym.endlexpos = getattr(t1, 'endlexpos', t1.lexpos) + #--! TRACKING + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # below as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + del symstack[-plen:] + self.state = state + p.callable(pslice) + del statestack[-plen:] + #--! DEBUG + debug.info('Result : %s', format_result(pslice[0])) + #--! DEBUG + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + symstack.extend(targ[1:-1]) # Put the production slice back on the stack + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + else: + + #--! TRACKING + if tracking: + sym.lineno = lexer.lineno + sym.lexpos = lexer.lexpos + #--! TRACKING + + targ = [sym] + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # above as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + self.state = state + p.callable(pslice) + #--! DEBUG + debug.info('Result : %s', format_result(pslice[0])) + #--! DEBUG + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + if t == 0: + n = symstack[-1] + result = getattr(n, 'value', None) + #--! DEBUG + debug.info('Done : Returning %s', format_result(result)) + debug.info('PLY: PARSE DEBUG END') + #--! DEBUG + return result + + if t is None: + + #--! DEBUG + debug.error('Error : %s', + ('%s . %s' % (' '.join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()) + #--! DEBUG + + # We have some kind of parsing error here. To handle + # this, we are going to push the current token onto + # the tokenstack and replace it with an 'error' token. + # If there are any synchronization rules, they may + # catch it. + # + # In addition to pushing the error token, we call call + # the user defined p_error() function if this is the + # first syntax error. This function is only called if + # errorcount == 0. + if errorcount == 0 or self.errorok: + errorcount = error_count + self.errorok = False + errtoken = lookahead + if errtoken.type == '$end': + errtoken = None # End of file! + if self.errorfunc: + if errtoken and not hasattr(errtoken, 'lexer'): + errtoken.lexer = lexer + self.state = state + tok = call_errorfunc(self.errorfunc, errtoken, self) + if self.errorok: + # User must have done some kind of panic + # mode recovery on their own. The + # returned token is the next lookahead + lookahead = tok + errtoken = None + continue + else: + if errtoken: + if hasattr(errtoken, 'lineno'): + lineno = lookahead.lineno + else: + lineno = 0 + if lineno: + sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type)) + else: + sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type) + else: + sys.stderr.write('yacc: Parse error in input. EOF\n') + return + + else: + errorcount = error_count + + # case 1: the statestack only has 1 entry on it. If we're in this state, the + # entire parse has been rolled back and we're completely hosed. The token is + # discarded and we just keep going. + + if len(statestack) <= 1 and lookahead.type != '$end': + lookahead = None + errtoken = None + state = 0 + # Nuke the pushback stack + del lookaheadstack[:] + continue + + # case 2: the statestack has a couple of entries on it, but we're + # at the end of the file. nuke the top entry and generate an error token + + # Start nuking entries on the stack + if lookahead.type == '$end': + # Whoa. We're really hosed here. Bail out + return + + if lookahead.type != 'error': + sym = symstack[-1] + if sym.type == 'error': + # Hmmm. Error is on top of stack, we'll just nuke input + # symbol and continue + #--! TRACKING + if tracking: + sym.endlineno = getattr(lookahead, 'lineno', sym.lineno) + sym.endlexpos = getattr(lookahead, 'lexpos', sym.lexpos) + #--! TRACKING + lookahead = None + continue + + # Create the error symbol for the first time and make it the new lookahead symbol + t = YaccSymbol() + t.type = 'error' + + if hasattr(lookahead, 'lineno'): + t.lineno = t.endlineno = lookahead.lineno + if hasattr(lookahead, 'lexpos'): + t.lexpos = t.endlexpos = lookahead.lexpos + t.value = lookahead + lookaheadstack.append(lookahead) + lookahead = t + else: + sym = symstack.pop() + #--! TRACKING + if tracking: + lookahead.lineno = sym.lineno + lookahead.lexpos = sym.lexpos + #--! TRACKING + statestack.pop() + state = statestack[-1] + + continue + + # Call an error function here + raise RuntimeError('yacc: internal parser error!!!\n') + + #--! parsedebug-end + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # parseopt(). + # + # Optimized version of parse() method. DO NOT EDIT THIS CODE DIRECTLY! + # This code is automatically generated by the ply/ygen.py script. Make + # changes to the parsedebug() method instead. + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + def parseopt(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + #--! parseopt-start + lookahead = None # Current lookahead symbol + lookaheadstack = [] # Stack of lookahead symbols + actions = self.action # Local reference to action table (to avoid lookup on self.) + goto = self.goto # Local reference to goto table (to avoid lookup on self.) + prod = self.productions # Local reference to production list (to avoid lookup on self.) + defaulted_states = self.defaulted_states # Local reference to defaulted states + pslice = YaccProduction(None) # Production object passed to grammar rules + errorcount = 0 # Used during error recovery + + + # If no lexer was given, we will try to use the lex module + if not lexer: + from . import lex + lexer = lex.lexer + + # Set up the lexer and parser objects on pslice + pslice.lexer = lexer + pslice.parser = self + + # If input was supplied, pass to lexer + if input is not None: + lexer.input(input) + + if tokenfunc is None: + # Tokenize function + get_token = lexer.token + else: + get_token = tokenfunc + + # Set the parser() token method (sometimes used in error recovery) + self.token = get_token + + # Set up the state and symbol stacks + + statestack = [] # Stack of parsing states + self.statestack = statestack + symstack = [] # Stack of grammar symbols + self.symstack = symstack + + pslice.stack = symstack # Put in the production + errtoken = None # Err token + + # The start state is assumed to be (0,$end) + + statestack.append(0) + sym = YaccSymbol() + sym.type = '$end' + symstack.append(sym) + state = 0 + while True: + # Get the next symbol on the input. If a lookahead symbol + # is already set, we just use that. Otherwise, we'll pull + # the next token off of the lookaheadstack or from the lexer + + + if state not in defaulted_states: + if not lookahead: + if not lookaheadstack: + lookahead = get_token() # Get the next token + else: + lookahead = lookaheadstack.pop() + if not lookahead: + lookahead = YaccSymbol() + lookahead.type = '$end' + + # Check the action table + ltype = lookahead.type + t = actions[state].get(ltype) + else: + t = defaulted_states[state] + + + if t is not None: + if t > 0: + # shift a symbol on the stack + statestack.append(t) + state = t + + + symstack.append(lookahead) + lookahead = None + + # Decrease error count on successful shift + if errorcount: + errorcount -= 1 + continue + + if t < 0: + # reduce a symbol on the stack, emit a production + p = prod[-t] + pname = p.name + plen = p.len + + # Get production function + sym = YaccSymbol() + sym.type = pname # Production name + sym.value = None + + + if plen: + targ = symstack[-plen-1:] + targ[0] = sym + + #--! TRACKING + if tracking: + t1 = targ[1] + sym.lineno = t1.lineno + sym.lexpos = t1.lexpos + t1 = targ[-1] + sym.endlineno = getattr(t1, 'endlineno', t1.lineno) + sym.endlexpos = getattr(t1, 'endlexpos', t1.lexpos) + #--! TRACKING + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # below as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + del symstack[-plen:] + self.state = state + p.callable(pslice) + del statestack[-plen:] + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + symstack.extend(targ[1:-1]) # Put the production slice back on the stack + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + else: + + #--! TRACKING + if tracking: + sym.lineno = lexer.lineno + sym.lexpos = lexer.lexpos + #--! TRACKING + + targ = [sym] + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # above as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + self.state = state + p.callable(pslice) + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + if t == 0: + n = symstack[-1] + result = getattr(n, 'value', None) + return result + + if t is None: + + + # We have some kind of parsing error here. To handle + # this, we are going to push the current token onto + # the tokenstack and replace it with an 'error' token. + # If there are any synchronization rules, they may + # catch it. + # + # In addition to pushing the error token, we call call + # the user defined p_error() function if this is the + # first syntax error. This function is only called if + # errorcount == 0. + if errorcount == 0 or self.errorok: + errorcount = error_count + self.errorok = False + errtoken = lookahead + if errtoken.type == '$end': + errtoken = None # End of file! + if self.errorfunc: + if errtoken and not hasattr(errtoken, 'lexer'): + errtoken.lexer = lexer + self.state = state + tok = call_errorfunc(self.errorfunc, errtoken, self) + if self.errorok: + # User must have done some kind of panic + # mode recovery on their own. The + # returned token is the next lookahead + lookahead = tok + errtoken = None + continue + else: + if errtoken: + if hasattr(errtoken, 'lineno'): + lineno = lookahead.lineno + else: + lineno = 0 + if lineno: + sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type)) + else: + sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type) + else: + sys.stderr.write('yacc: Parse error in input. EOF\n') + return + + else: + errorcount = error_count + + # case 1: the statestack only has 1 entry on it. If we're in this state, the + # entire parse has been rolled back and we're completely hosed. The token is + # discarded and we just keep going. + + if len(statestack) <= 1 and lookahead.type != '$end': + lookahead = None + errtoken = None + state = 0 + # Nuke the pushback stack + del lookaheadstack[:] + continue + + # case 2: the statestack has a couple of entries on it, but we're + # at the end of the file. nuke the top entry and generate an error token + + # Start nuking entries on the stack + if lookahead.type == '$end': + # Whoa. We're really hosed here. Bail out + return + + if lookahead.type != 'error': + sym = symstack[-1] + if sym.type == 'error': + # Hmmm. Error is on top of stack, we'll just nuke input + # symbol and continue + #--! TRACKING + if tracking: + sym.endlineno = getattr(lookahead, 'lineno', sym.lineno) + sym.endlexpos = getattr(lookahead, 'lexpos', sym.lexpos) + #--! TRACKING + lookahead = None + continue + + # Create the error symbol for the first time and make it the new lookahead symbol + t = YaccSymbol() + t.type = 'error' + + if hasattr(lookahead, 'lineno'): + t.lineno = t.endlineno = lookahead.lineno + if hasattr(lookahead, 'lexpos'): + t.lexpos = t.endlexpos = lookahead.lexpos + t.value = lookahead + lookaheadstack.append(lookahead) + lookahead = t + else: + sym = symstack.pop() + #--! TRACKING + if tracking: + lookahead.lineno = sym.lineno + lookahead.lexpos = sym.lexpos + #--! TRACKING + statestack.pop() + state = statestack[-1] + + continue + + # Call an error function here + raise RuntimeError('yacc: internal parser error!!!\n') + + #--! parseopt-end + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # parseopt_notrack(). + # + # Optimized version of parseopt() with line number tracking removed. + # DO NOT EDIT THIS CODE DIRECTLY. This code is automatically generated + # by the ply/ygen.py script. Make changes to the parsedebug() method instead. + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + def parseopt_notrack(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + #--! parseopt-notrack-start + lookahead = None # Current lookahead symbol + lookaheadstack = [] # Stack of lookahead symbols + actions = self.action # Local reference to action table (to avoid lookup on self.) + goto = self.goto # Local reference to goto table (to avoid lookup on self.) + prod = self.productions # Local reference to production list (to avoid lookup on self.) + defaulted_states = self.defaulted_states # Local reference to defaulted states + pslice = YaccProduction(None) # Production object passed to grammar rules + errorcount = 0 # Used during error recovery + + + # If no lexer was given, we will try to use the lex module + if not lexer: + from . import lex + lexer = lex.lexer + + # Set up the lexer and parser objects on pslice + pslice.lexer = lexer + pslice.parser = self + + # If input was supplied, pass to lexer + if input is not None: + lexer.input(input) + + if tokenfunc is None: + # Tokenize function + get_token = lexer.token + else: + get_token = tokenfunc + + # Set the parser() token method (sometimes used in error recovery) + self.token = get_token + + # Set up the state and symbol stacks + + statestack = [] # Stack of parsing states + self.statestack = statestack + symstack = [] # Stack of grammar symbols + self.symstack = symstack + + pslice.stack = symstack # Put in the production + errtoken = None # Err token + + # The start state is assumed to be (0,$end) + + statestack.append(0) + sym = YaccSymbol() + sym.type = '$end' + symstack.append(sym) + state = 0 + while True: + # Get the next symbol on the input. If a lookahead symbol + # is already set, we just use that. Otherwise, we'll pull + # the next token off of the lookaheadstack or from the lexer + + + if state not in defaulted_states: + if not lookahead: + if not lookaheadstack: + lookahead = get_token() # Get the next token + else: + lookahead = lookaheadstack.pop() + if not lookahead: + lookahead = YaccSymbol() + lookahead.type = '$end' + + # Check the action table + ltype = lookahead.type + t = actions[state].get(ltype) + else: + t = defaulted_states[state] + + + if t is not None: + if t > 0: + # shift a symbol on the stack + statestack.append(t) + state = t + + + symstack.append(lookahead) + lookahead = None + + # Decrease error count on successful shift + if errorcount: + errorcount -= 1 + continue + + if t < 0: + # reduce a symbol on the stack, emit a production + p = prod[-t] + pname = p.name + plen = p.len + + # Get production function + sym = YaccSymbol() + sym.type = pname # Production name + sym.value = None + + + if plen: + targ = symstack[-plen-1:] + targ[0] = sym + + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # below as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + del symstack[-plen:] + self.state = state + p.callable(pslice) + del statestack[-plen:] + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + symstack.extend(targ[1:-1]) # Put the production slice back on the stack + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + else: + + + targ = [sym] + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # above as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + self.state = state + p.callable(pslice) + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + if t == 0: + n = symstack[-1] + result = getattr(n, 'value', None) + return result + + if t is None: + + + # We have some kind of parsing error here. To handle + # this, we are going to push the current token onto + # the tokenstack and replace it with an 'error' token. + # If there are any synchronization rules, they may + # catch it. + # + # In addition to pushing the error token, we call call + # the user defined p_error() function if this is the + # first syntax error. This function is only called if + # errorcount == 0. + if errorcount == 0 or self.errorok: + errorcount = error_count + self.errorok = False + errtoken = lookahead + if errtoken.type == '$end': + errtoken = None # End of file! + if self.errorfunc: + if errtoken and not hasattr(errtoken, 'lexer'): + errtoken.lexer = lexer + self.state = state + tok = call_errorfunc(self.errorfunc, errtoken, self) + if self.errorok: + # User must have done some kind of panic + # mode recovery on their own. The + # returned token is the next lookahead + lookahead = tok + errtoken = None + continue + else: + if errtoken: + if hasattr(errtoken, 'lineno'): + lineno = lookahead.lineno + else: + lineno = 0 + if lineno: + sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type)) + else: + sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type) + else: + sys.stderr.write('yacc: Parse error in input. EOF\n') + return + + else: + errorcount = error_count + + # case 1: the statestack only has 1 entry on it. If we're in this state, the + # entire parse has been rolled back and we're completely hosed. The token is + # discarded and we just keep going. + + if len(statestack) <= 1 and lookahead.type != '$end': + lookahead = None + errtoken = None + state = 0 + # Nuke the pushback stack + del lookaheadstack[:] + continue + + # case 2: the statestack has a couple of entries on it, but we're + # at the end of the file. nuke the top entry and generate an error token + + # Start nuking entries on the stack + if lookahead.type == '$end': + # Whoa. We're really hosed here. Bail out + return + + if lookahead.type != 'error': + sym = symstack[-1] + if sym.type == 'error': + # Hmmm. Error is on top of stack, we'll just nuke input + # symbol and continue + lookahead = None + continue + + # Create the error symbol for the first time and make it the new lookahead symbol + t = YaccSymbol() + t.type = 'error' + + if hasattr(lookahead, 'lineno'): + t.lineno = t.endlineno = lookahead.lineno + if hasattr(lookahead, 'lexpos'): + t.lexpos = t.endlexpos = lookahead.lexpos + t.value = lookahead + lookaheadstack.append(lookahead) + lookahead = t + else: + sym = symstack.pop() + statestack.pop() + state = statestack[-1] + + continue + + # Call an error function here + raise RuntimeError('yacc: internal parser error!!!\n') + + #--! parseopt-notrack-end + +# ----------------------------------------------------------------------------- +# === Grammar Representation === +# +# The following functions, classes, and variables are used to represent and +# manipulate the rules that make up a grammar. +# ----------------------------------------------------------------------------- + +# regex matching identifiers +_is_identifier = re.compile(r'^[a-zA-Z0-9_-]+$') + +# ----------------------------------------------------------------------------- +# class Production: +# +# This class stores the raw information about a single production or grammar rule. +# A grammar rule refers to a specification such as this: +# +# expr : expr PLUS term +# +# Here are the basic attributes defined on all productions +# +# name - Name of the production. For example 'expr' +# prod - A list of symbols on the right side ['expr','PLUS','term'] +# prec - Production precedence level +# number - Production number. +# func - Function that executes on reduce +# file - File where production function is defined +# lineno - Line number where production function is defined +# +# The following attributes are defined or optional. +# +# len - Length of the production (number of symbols on right hand side) +# usyms - Set of unique symbols found in the production +# ----------------------------------------------------------------------------- + +class Production(object): + reduced = 0 + def __init__(self, number, name, prod, precedence=('right', 0), func=None, file='', line=0): + self.name = name + self.prod = tuple(prod) + self.number = number + self.func = func + self.callable = None + self.file = file + self.line = line + self.prec = precedence + + # Internal settings used during table construction + + self.len = len(self.prod) # Length of the production + + # Create a list of unique production symbols used in the production + self.usyms = [] + for s in self.prod: + if s not in self.usyms: + self.usyms.append(s) + + # List of all LR items for the production + self.lr_items = [] + self.lr_next = None + + # Create a string representation + if self.prod: + self.str = '%s -> %s' % (self.name, ' '.join(self.prod)) + else: + self.str = '%s -> ' % self.name + + def __str__(self): + return self.str + + def __repr__(self): + return 'Production(' + str(self) + ')' + + def __len__(self): + return len(self.prod) + + def __nonzero__(self): + return 1 + + def __getitem__(self, index): + return self.prod[index] + + # Return the nth lr_item from the production (or None if at the end) + def lr_item(self, n): + if n > len(self.prod): + return None + p = LRItem(self, n) + # Precompute the list of productions immediately following. + try: + p.lr_after = Prodnames[p.prod[n+1]] + except (IndexError, KeyError): + p.lr_after = [] + try: + p.lr_before = p.prod[n-1] + except IndexError: + p.lr_before = None + return p + + # Bind the production function name to a callable + def bind(self, pdict): + if self.func: + self.callable = pdict[self.func] + +# This class serves as a minimal standin for Production objects when +# reading table data from files. It only contains information +# actually used by the LR parsing engine, plus some additional +# debugging information. +class MiniProduction(object): + def __init__(self, str, name, len, func, file, line): + self.name = name + self.len = len + self.func = func + self.callable = None + self.file = file + self.line = line + self.str = str + + def __str__(self): + return self.str + + def __repr__(self): + return 'MiniProduction(%s)' % self.str + + # Bind the production function name to a callable + def bind(self, pdict): + if self.func: + self.callable = pdict[self.func] + + +# ----------------------------------------------------------------------------- +# class LRItem +# +# This class represents a specific stage of parsing a production rule. For +# example: +# +# expr : expr . PLUS term +# +# In the above, the "." represents the current location of the parse. Here +# basic attributes: +# +# name - Name of the production. For example 'expr' +# prod - A list of symbols on the right side ['expr','.', 'PLUS','term'] +# number - Production number. +# +# lr_next Next LR item. Example, if we are ' expr -> expr . PLUS term' +# then lr_next refers to 'expr -> expr PLUS . term' +# lr_index - LR item index (location of the ".") in the prod list. +# lookaheads - LALR lookahead symbols for this item +# len - Length of the production (number of symbols on right hand side) +# lr_after - List of all productions that immediately follow +# lr_before - Grammar symbol immediately before +# ----------------------------------------------------------------------------- + +class LRItem(object): + def __init__(self, p, n): + self.name = p.name + self.prod = list(p.prod) + self.number = p.number + self.lr_index = n + self.lookaheads = {} + self.prod.insert(n, '.') + self.prod = tuple(self.prod) + self.len = len(self.prod) + self.usyms = p.usyms + + def __str__(self): + if self.prod: + s = '%s -> %s' % (self.name, ' '.join(self.prod)) + else: + s = '%s -> ' % self.name + return s + + def __repr__(self): + return 'LRItem(' + str(self) + ')' + +# ----------------------------------------------------------------------------- +# rightmost_terminal() +# +# Return the rightmost terminal from a list of symbols. Used in add_production() +# ----------------------------------------------------------------------------- +def rightmost_terminal(symbols, terminals): + i = len(symbols) - 1 + while i >= 0: + if symbols[i] in terminals: + return symbols[i] + i -= 1 + return None + +# ----------------------------------------------------------------------------- +# === GRAMMAR CLASS === +# +# The following class represents the contents of the specified grammar along +# with various computed properties such as first sets, follow sets, LR items, etc. +# This data is used for critical parts of the table generation process later. +# ----------------------------------------------------------------------------- + +class GrammarError(YaccError): + pass + +class Grammar(object): + def __init__(self, terminals): + self.Productions = [None] # A list of all of the productions. The first + # entry is always reserved for the purpose of + # building an augmented grammar + + self.Prodnames = {} # A dictionary mapping the names of nonterminals to a list of all + # productions of that nonterminal. + + self.Prodmap = {} # A dictionary that is only used to detect duplicate + # productions. + + self.Terminals = {} # A dictionary mapping the names of terminal symbols to a + # list of the rules where they are used. + + for term in terminals: + self.Terminals[term] = [] + + self.Terminals['error'] = [] + + self.Nonterminals = {} # A dictionary mapping names of nonterminals to a list + # of rule numbers where they are used. + + self.First = {} # A dictionary of precomputed FIRST(x) symbols + + self.Follow = {} # A dictionary of precomputed FOLLOW(x) symbols + + self.Precedence = {} # Precedence rules for each terminal. Contains tuples of the + # form ('right',level) or ('nonassoc', level) or ('left',level) + + self.UsedPrecedence = set() # Precedence rules that were actually used by the grammer. + # This is only used to provide error checking and to generate + # a warning about unused precedence rules. + + self.Start = None # Starting symbol for the grammar + + + def __len__(self): + return len(self.Productions) + + def __getitem__(self, index): + return self.Productions[index] + + # ----------------------------------------------------------------------------- + # set_precedence() + # + # Sets the precedence for a given terminal. assoc is the associativity such as + # 'left','right', or 'nonassoc'. level is a numeric level. + # + # ----------------------------------------------------------------------------- + + def set_precedence(self, term, assoc, level): + assert self.Productions == [None], 'Must call set_precedence() before add_production()' + if term in self.Precedence: + raise GrammarError('Precedence already specified for terminal %r' % term) + if assoc not in ['left', 'right', 'nonassoc']: + raise GrammarError("Associativity must be one of 'left','right', or 'nonassoc'") + self.Precedence[term] = (assoc, level) + + # ----------------------------------------------------------------------------- + # add_production() + # + # Given an action function, this function assembles a production rule and + # computes its precedence level. + # + # The production rule is supplied as a list of symbols. For example, + # a rule such as 'expr : expr PLUS term' has a production name of 'expr' and + # symbols ['expr','PLUS','term']. + # + # Precedence is determined by the precedence of the right-most non-terminal + # or the precedence of a terminal specified by %prec. + # + # A variety of error checks are performed to make sure production symbols + # are valid and that %prec is used correctly. + # ----------------------------------------------------------------------------- + + def add_production(self, prodname, syms, func=None, file='', line=0): + + if prodname in self.Terminals: + raise GrammarError('%s:%d: Illegal rule name %r. Already defined as a token' % (file, line, prodname)) + if prodname == 'error': + raise GrammarError('%s:%d: Illegal rule name %r. error is a reserved word' % (file, line, prodname)) + if not _is_identifier.match(prodname): + raise GrammarError('%s:%d: Illegal rule name %r' % (file, line, prodname)) + + # Look for literal tokens + for n, s in enumerate(syms): + if s[0] in "'\"": + try: + c = eval(s) + if (len(c) > 1): + raise GrammarError('%s:%d: Literal token %s in rule %r may only be a single character' % + (file, line, s, prodname)) + if c not in self.Terminals: + self.Terminals[c] = [] + syms[n] = c + continue + except SyntaxError: + pass + if not _is_identifier.match(s) and s != '%prec': + raise GrammarError('%s:%d: Illegal name %r in rule %r' % (file, line, s, prodname)) + + # Determine the precedence level + if '%prec' in syms: + if syms[-1] == '%prec': + raise GrammarError('%s:%d: Syntax error. Nothing follows %%prec' % (file, line)) + if syms[-2] != '%prec': + raise GrammarError('%s:%d: Syntax error. %%prec can only appear at the end of a grammar rule' % + (file, line)) + precname = syms[-1] + prodprec = self.Precedence.get(precname) + if not prodprec: + raise GrammarError('%s:%d: Nothing known about the precedence of %r' % (file, line, precname)) + else: + self.UsedPrecedence.add(precname) + del syms[-2:] # Drop %prec from the rule + else: + # If no %prec, precedence is determined by the rightmost terminal symbol + precname = rightmost_terminal(syms, self.Terminals) + prodprec = self.Precedence.get(precname, ('right', 0)) + + # See if the rule is already in the rulemap + map = '%s -> %s' % (prodname, syms) + if map in self.Prodmap: + m = self.Prodmap[map] + raise GrammarError('%s:%d: Duplicate rule %s. ' % (file, line, m) + + 'Previous definition at %s:%d' % (m.file, m.line)) + + # From this point on, everything is valid. Create a new Production instance + pnumber = len(self.Productions) + if prodname not in self.Nonterminals: + self.Nonterminals[prodname] = [] + + # Add the production number to Terminals and Nonterminals + for t in syms: + if t in self.Terminals: + self.Terminals[t].append(pnumber) + else: + if t not in self.Nonterminals: + self.Nonterminals[t] = [] + self.Nonterminals[t].append(pnumber) + + # Create a production and add it to the list of productions + p = Production(pnumber, prodname, syms, prodprec, func, file, line) + self.Productions.append(p) + self.Prodmap[map] = p + + # Add to the global productions list + try: + self.Prodnames[prodname].append(p) + except KeyError: + self.Prodnames[prodname] = [p] + + # ----------------------------------------------------------------------------- + # set_start() + # + # Sets the starting symbol and creates the augmented grammar. Production + # rule 0 is S' -> start where start is the start symbol. + # ----------------------------------------------------------------------------- + + def set_start(self, start=None): + if not start: + start = self.Productions[1].name + if start not in self.Nonterminals: + raise GrammarError('start symbol %s undefined' % start) + self.Productions[0] = Production(0, "S'", [start]) + self.Nonterminals[start].append(0) + self.Start = start + + # ----------------------------------------------------------------------------- + # find_unreachable() + # + # Find all of the nonterminal symbols that can't be reached from the starting + # symbol. Returns a list of nonterminals that can't be reached. + # ----------------------------------------------------------------------------- + + def find_unreachable(self): + + # Mark all symbols that are reachable from a symbol s + def mark_reachable_from(s): + if s in reachable: + return + reachable.add(s) + for p in self.Prodnames.get(s, []): + for r in p.prod: + mark_reachable_from(r) + + reachable = set() + mark_reachable_from(self.Productions[0].prod[0]) + return [s for s in self.Nonterminals if s not in reachable] + + # ----------------------------------------------------------------------------- + # infinite_cycles() + # + # This function looks at the various parsing rules and tries to detect + # infinite recursion cycles (grammar rules where there is no possible way + # to derive a string of only terminals). + # ----------------------------------------------------------------------------- + + def infinite_cycles(self): + terminates = {} + + # Terminals: + for t in self.Terminals: + terminates[t] = True + + terminates['$end'] = True + + # Nonterminals: + + # Initialize to false: + for n in self.Nonterminals: + terminates[n] = False + + # Then propagate termination until no change: + while True: + some_change = False + for (n, pl) in self.Prodnames.items(): + # Nonterminal n terminates iff any of its productions terminates. + for p in pl: + # Production p terminates iff all of its rhs symbols terminate. + for s in p.prod: + if not terminates[s]: + # The symbol s does not terminate, + # so production p does not terminate. + p_terminates = False + break + else: + # didn't break from the loop, + # so every symbol s terminates + # so production p terminates. + p_terminates = True + + if p_terminates: + # symbol n terminates! + if not terminates[n]: + terminates[n] = True + some_change = True + # Don't need to consider any more productions for this n. + break + + if not some_change: + break + + infinite = [] + for (s, term) in terminates.items(): + if not term: + if s not in self.Prodnames and s not in self.Terminals and s != 'error': + # s is used-but-not-defined, and we've already warned of that, + # so it would be overkill to say that it's also non-terminating. + pass + else: + infinite.append(s) + + return infinite + + # ----------------------------------------------------------------------------- + # undefined_symbols() + # + # Find all symbols that were used the grammar, but not defined as tokens or + # grammar rules. Returns a list of tuples (sym, prod) where sym in the symbol + # and prod is the production where the symbol was used. + # ----------------------------------------------------------------------------- + def undefined_symbols(self): + result = [] + for p in self.Productions: + if not p: + continue + + for s in p.prod: + if s not in self.Prodnames and s not in self.Terminals and s != 'error': + result.append((s, p)) + return result + + # ----------------------------------------------------------------------------- + # unused_terminals() + # + # Find all terminals that were defined, but not used by the grammar. Returns + # a list of all symbols. + # ----------------------------------------------------------------------------- + def unused_terminals(self): + unused_tok = [] + for s, v in self.Terminals.items(): + if s != 'error' and not v: + unused_tok.append(s) + + return unused_tok + + # ------------------------------------------------------------------------------ + # unused_rules() + # + # Find all grammar rules that were defined, but not used (maybe not reachable) + # Returns a list of productions. + # ------------------------------------------------------------------------------ + + def unused_rules(self): + unused_prod = [] + for s, v in self.Nonterminals.items(): + if not v: + p = self.Prodnames[s][0] + unused_prod.append(p) + return unused_prod + + # ----------------------------------------------------------------------------- + # unused_precedence() + # + # Returns a list of tuples (term,precedence) corresponding to precedence + # rules that were never used by the grammar. term is the name of the terminal + # on which precedence was applied and precedence is a string such as 'left' or + # 'right' corresponding to the type of precedence. + # ----------------------------------------------------------------------------- + + def unused_precedence(self): + unused = [] + for termname in self.Precedence: + if not (termname in self.Terminals or termname in self.UsedPrecedence): + unused.append((termname, self.Precedence[termname][0])) + + return unused + + # ------------------------------------------------------------------------- + # _first() + # + # Compute the value of FIRST1(beta) where beta is a tuple of symbols. + # + # During execution of compute_first1, the result may be incomplete. + # Afterward (e.g., when called from compute_follow()), it will be complete. + # ------------------------------------------------------------------------- + def _first(self, beta): + + # We are computing First(x1,x2,x3,...,xn) + result = [] + for x in beta: + x_produces_empty = False + + # Add all the non- symbols of First[x] to the result. + for f in self.First[x]: + if f == '': + x_produces_empty = True + else: + if f not in result: + result.append(f) + + if x_produces_empty: + # We have to consider the next x in beta, + # i.e. stay in the loop. + pass + else: + # We don't have to consider any further symbols in beta. + break + else: + # There was no 'break' from the loop, + # so x_produces_empty was true for all x in beta, + # so beta produces empty as well. + result.append('') + + return result + + # ------------------------------------------------------------------------- + # compute_first() + # + # Compute the value of FIRST1(X) for all symbols + # ------------------------------------------------------------------------- + def compute_first(self): + if self.First: + return self.First + + # Terminals: + for t in self.Terminals: + self.First[t] = [t] + + self.First['$end'] = ['$end'] + + # Nonterminals: + + # Initialize to the empty set: + for n in self.Nonterminals: + self.First[n] = [] + + # Then propagate symbols until no change: + while True: + some_change = False + for n in self.Nonterminals: + for p in self.Prodnames[n]: + for f in self._first(p.prod): + if f not in self.First[n]: + self.First[n].append(f) + some_change = True + if not some_change: + break + + return self.First + + # --------------------------------------------------------------------- + # compute_follow() + # + # Computes all of the follow sets for every non-terminal symbol. The + # follow set is the set of all symbols that might follow a given + # non-terminal. See the Dragon book, 2nd Ed. p. 189. + # --------------------------------------------------------------------- + def compute_follow(self, start=None): + # If already computed, return the result + if self.Follow: + return self.Follow + + # If first sets not computed yet, do that first. + if not self.First: + self.compute_first() + + # Add '$end' to the follow list of the start symbol + for k in self.Nonterminals: + self.Follow[k] = [] + + if not start: + start = self.Productions[1].name + + self.Follow[start] = ['$end'] + + while True: + didadd = False + for p in self.Productions[1:]: + # Here is the production set + for i, B in enumerate(p.prod): + if B in self.Nonterminals: + # Okay. We got a non-terminal in a production + fst = self._first(p.prod[i+1:]) + hasempty = False + for f in fst: + if f != '' and f not in self.Follow[B]: + self.Follow[B].append(f) + didadd = True + if f == '': + hasempty = True + if hasempty or i == (len(p.prod)-1): + # Add elements of follow(a) to follow(b) + for f in self.Follow[p.name]: + if f not in self.Follow[B]: + self.Follow[B].append(f) + didadd = True + if not didadd: + break + return self.Follow + + + # ----------------------------------------------------------------------------- + # build_lritems() + # + # This function walks the list of productions and builds a complete set of the + # LR items. The LR items are stored in two ways: First, they are uniquely + # numbered and placed in the list _lritems. Second, a linked list of LR items + # is built for each production. For example: + # + # E -> E PLUS E + # + # Creates the list + # + # [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ] + # ----------------------------------------------------------------------------- + + def build_lritems(self): + for p in self.Productions: + lastlri = p + i = 0 + lr_items = [] + while True: + if i > len(p): + lri = None + else: + lri = LRItem(p, i) + # Precompute the list of productions immediately following + try: + lri.lr_after = self.Prodnames[lri.prod[i+1]] + except (IndexError, KeyError): + lri.lr_after = [] + try: + lri.lr_before = lri.prod[i-1] + except IndexError: + lri.lr_before = None + + lastlri.lr_next = lri + if not lri: + break + lr_items.append(lri) + lastlri = lri + i += 1 + p.lr_items = lr_items + +# ----------------------------------------------------------------------------- +# == Class LRTable == +# +# This basic class represents a basic table of LR parsing information. +# Methods for generating the tables are not defined here. They are defined +# in the derived class LRGeneratedTable. +# ----------------------------------------------------------------------------- + +class VersionError(YaccError): + pass + +class LRTable(object): + def __init__(self): + self.lr_action = None + self.lr_goto = None + self.lr_productions = None + self.lr_method = None + + def read_table(self, module): + if isinstance(module, types.ModuleType): + parsetab = module + else: + exec('import %s' % module) + parsetab = sys.modules[module] + + if parsetab._tabversion != __tabversion__: + raise VersionError('yacc table file version is out of date') + + self.lr_action = parsetab._lr_action + self.lr_goto = parsetab._lr_goto + + self.lr_productions = [] + for p in parsetab._lr_productions: + self.lr_productions.append(MiniProduction(*p)) + + self.lr_method = parsetab._lr_method + return parsetab._lr_signature + + def read_pickle(self, filename): + try: + import cPickle as pickle + except ImportError: + import pickle + + if not os.path.exists(filename): + raise ImportError + + in_f = open(filename, 'rb') + + tabversion = pickle.load(in_f) + if tabversion != __tabversion__: + raise VersionError('yacc table file version is out of date') + self.lr_method = pickle.load(in_f) + signature = pickle.load(in_f) + self.lr_action = pickle.load(in_f) + self.lr_goto = pickle.load(in_f) + productions = pickle.load(in_f) + + self.lr_productions = [] + for p in productions: + self.lr_productions.append(MiniProduction(*p)) + + in_f.close() + return signature + + # Bind all production function names to callable objects in pdict + def bind_callables(self, pdict): + for p in self.lr_productions: + p.bind(pdict) + + +# ----------------------------------------------------------------------------- +# === LR Generator === +# +# The following classes and functions are used to generate LR parsing tables on +# a grammar. +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# digraph() +# traverse() +# +# The following two functions are used to compute set valued functions +# of the form: +# +# F(x) = F'(x) U U{F(y) | x R y} +# +# This is used to compute the values of Read() sets as well as FOLLOW sets +# in LALR(1) generation. +# +# Inputs: X - An input set +# R - A relation +# FP - Set-valued function +# ------------------------------------------------------------------------------ + +def digraph(X, R, FP): + N = {} + for x in X: + N[x] = 0 + stack = [] + F = {} + for x in X: + if N[x] == 0: + traverse(x, N, stack, F, X, R, FP) + return F + +def traverse(x, N, stack, F, X, R, FP): + stack.append(x) + d = len(stack) + N[x] = d + F[x] = FP(x) # F(X) <- F'(x) + + rel = R(x) # Get y's related to x + for y in rel: + if N[y] == 0: + traverse(y, N, stack, F, X, R, FP) + N[x] = min(N[x], N[y]) + for a in F.get(y, []): + if a not in F[x]: + F[x].append(a) + if N[x] == d: + N[stack[-1]] = MAXINT + F[stack[-1]] = F[x] + element = stack.pop() + while element != x: + N[stack[-1]] = MAXINT + F[stack[-1]] = F[x] + element = stack.pop() + +class LALRError(YaccError): + pass + +# ----------------------------------------------------------------------------- +# == LRGeneratedTable == +# +# This class implements the LR table generation algorithm. There are no +# public methods except for write() +# ----------------------------------------------------------------------------- + +class LRGeneratedTable(LRTable): + def __init__(self, grammar, method='LALR', log=None): + if method not in ['SLR', 'LALR']: + raise LALRError('Unsupported method %s' % method) + + self.grammar = grammar + self.lr_method = method + + # Set up the logger + if not log: + log = NullLogger() + self.log = log + + # Internal attributes + self.lr_action = {} # Action table + self.lr_goto = {} # Goto table + self.lr_productions = grammar.Productions # Copy of grammar Production array + self.lr_goto_cache = {} # Cache of computed gotos + self.lr0_cidhash = {} # Cache of closures + + self._add_count = 0 # Internal counter used to detect cycles + + # Diagonistic information filled in by the table generator + self.sr_conflict = 0 + self.rr_conflict = 0 + self.conflicts = [] # List of conflicts + + self.sr_conflicts = [] + self.rr_conflicts = [] + + # Build the tables + self.grammar.build_lritems() + self.grammar.compute_first() + self.grammar.compute_follow() + self.lr_parse_table() + + # Compute the LR(0) closure operation on I, where I is a set of LR(0) items. + + def lr0_closure(self, I): + self._add_count += 1 + + # Add everything in I to J + J = I[:] + didadd = True + while didadd: + didadd = False + for j in J: + for x in j.lr_after: + if getattr(x, 'lr0_added', 0) == self._add_count: + continue + # Add B --> .G to J + J.append(x.lr_next) + x.lr0_added = self._add_count + didadd = True + + return J + + # Compute the LR(0) goto function goto(I,X) where I is a set + # of LR(0) items and X is a grammar symbol. This function is written + # in a way that guarantees uniqueness of the generated goto sets + # (i.e. the same goto set will never be returned as two different Python + # objects). With uniqueness, we can later do fast set comparisons using + # id(obj) instead of element-wise comparison. + + def lr0_goto(self, I, x): + # First we look for a previously cached entry + g = self.lr_goto_cache.get((id(I), x)) + if g: + return g + + # Now we generate the goto set in a way that guarantees uniqueness + # of the result + + s = self.lr_goto_cache.get(x) + if not s: + s = {} + self.lr_goto_cache[x] = s + + gs = [] + for p in I: + n = p.lr_next + if n and n.lr_before == x: + s1 = s.get(id(n)) + if not s1: + s1 = {} + s[id(n)] = s1 + gs.append(n) + s = s1 + g = s.get('$end') + if not g: + if gs: + g = self.lr0_closure(gs) + s['$end'] = g + else: + s['$end'] = gs + self.lr_goto_cache[(id(I), x)] = g + return g + + # Compute the LR(0) sets of item function + def lr0_items(self): + C = [self.lr0_closure([self.grammar.Productions[0].lr_next])] + i = 0 + for I in C: + self.lr0_cidhash[id(I)] = i + i += 1 + + # Loop over the items in C and each grammar symbols + i = 0 + while i < len(C): + I = C[i] + i += 1 + + # Collect all of the symbols that could possibly be in the goto(I,X) sets + asyms = {} + for ii in I: + for s in ii.usyms: + asyms[s] = None + + for x in asyms: + g = self.lr0_goto(I, x) + if not g or id(g) in self.lr0_cidhash: + continue + self.lr0_cidhash[id(g)] = len(C) + C.append(g) + + return C + + # ----------------------------------------------------------------------------- + # ==== LALR(1) Parsing ==== + # + # LALR(1) parsing is almost exactly the same as SLR except that instead of + # relying upon Follow() sets when performing reductions, a more selective + # lookahead set that incorporates the state of the LR(0) machine is utilized. + # Thus, we mainly just have to focus on calculating the lookahead sets. + # + # The method used here is due to DeRemer and Pennelo (1982). + # + # DeRemer, F. L., and T. J. Pennelo: "Efficient Computation of LALR(1) + # Lookahead Sets", ACM Transactions on Programming Languages and Systems, + # Vol. 4, No. 4, Oct. 1982, pp. 615-649 + # + # Further details can also be found in: + # + # J. Tremblay and P. Sorenson, "The Theory and Practice of Compiler Writing", + # McGraw-Hill Book Company, (1985). + # + # ----------------------------------------------------------------------------- + + # ----------------------------------------------------------------------------- + # compute_nullable_nonterminals() + # + # Creates a dictionary containing all of the non-terminals that might produce + # an empty production. + # ----------------------------------------------------------------------------- + + def compute_nullable_nonterminals(self): + nullable = set() + num_nullable = 0 + while True: + for p in self.grammar.Productions[1:]: + if p.len == 0: + nullable.add(p.name) + continue + for t in p.prod: + if t not in nullable: + break + else: + nullable.add(p.name) + if len(nullable) == num_nullable: + break + num_nullable = len(nullable) + return nullable + + # ----------------------------------------------------------------------------- + # find_nonterminal_trans(C) + # + # Given a set of LR(0) items, this functions finds all of the non-terminal + # transitions. These are transitions in which a dot appears immediately before + # a non-terminal. Returns a list of tuples of the form (state,N) where state + # is the state number and N is the nonterminal symbol. + # + # The input C is the set of LR(0) items. + # ----------------------------------------------------------------------------- + + def find_nonterminal_transitions(self, C): + trans = [] + for stateno, state in enumerate(C): + for p in state: + if p.lr_index < p.len - 1: + t = (stateno, p.prod[p.lr_index+1]) + if t[1] in self.grammar.Nonterminals: + if t not in trans: + trans.append(t) + return trans + + # ----------------------------------------------------------------------------- + # dr_relation() + # + # Computes the DR(p,A) relationships for non-terminal transitions. The input + # is a tuple (state,N) where state is a number and N is a nonterminal symbol. + # + # Returns a list of terminals. + # ----------------------------------------------------------------------------- + + def dr_relation(self, C, trans, nullable): + dr_set = {} + state, N = trans + terms = [] + + g = self.lr0_goto(C[state], N) + for p in g: + if p.lr_index < p.len - 1: + a = p.prod[p.lr_index+1] + if a in self.grammar.Terminals: + if a not in terms: + terms.append(a) + + # This extra bit is to handle the start state + if state == 0 and N == self.grammar.Productions[0].prod[0]: + terms.append('$end') + + return terms + + # ----------------------------------------------------------------------------- + # reads_relation() + # + # Computes the READS() relation (p,A) READS (t,C). + # ----------------------------------------------------------------------------- + + def reads_relation(self, C, trans, empty): + # Look for empty transitions + rel = [] + state, N = trans + + g = self.lr0_goto(C[state], N) + j = self.lr0_cidhash.get(id(g), -1) + for p in g: + if p.lr_index < p.len - 1: + a = p.prod[p.lr_index + 1] + if a in empty: + rel.append((j, a)) + + return rel + + # ----------------------------------------------------------------------------- + # compute_lookback_includes() + # + # Determines the lookback and includes relations + # + # LOOKBACK: + # + # This relation is determined by running the LR(0) state machine forward. + # For example, starting with a production "N : . A B C", we run it forward + # to obtain "N : A B C ." We then build a relationship between this final + # state and the starting state. These relationships are stored in a dictionary + # lookdict. + # + # INCLUDES: + # + # Computes the INCLUDE() relation (p,A) INCLUDES (p',B). + # + # This relation is used to determine non-terminal transitions that occur + # inside of other non-terminal transition states. (p,A) INCLUDES (p', B) + # if the following holds: + # + # B -> LAT, where T -> epsilon and p' -L-> p + # + # L is essentially a prefix (which may be empty), T is a suffix that must be + # able to derive an empty string. State p' must lead to state p with the string L. + # + # ----------------------------------------------------------------------------- + + def compute_lookback_includes(self, C, trans, nullable): + lookdict = {} # Dictionary of lookback relations + includedict = {} # Dictionary of include relations + + # Make a dictionary of non-terminal transitions + dtrans = {} + for t in trans: + dtrans[t] = 1 + + # Loop over all transitions and compute lookbacks and includes + for state, N in trans: + lookb = [] + includes = [] + for p in C[state]: + if p.name != N: + continue + + # Okay, we have a name match. We now follow the production all the way + # through the state machine until we get the . on the right hand side + + lr_index = p.lr_index + j = state + while lr_index < p.len - 1: + lr_index = lr_index + 1 + t = p.prod[lr_index] + + # Check to see if this symbol and state are a non-terminal transition + if (j, t) in dtrans: + # Yes. Okay, there is some chance that this is an includes relation + # the only way to know for certain is whether the rest of the + # production derives empty + + li = lr_index + 1 + while li < p.len: + if p.prod[li] in self.grammar.Terminals: + break # No forget it + if p.prod[li] not in nullable: + break + li = li + 1 + else: + # Appears to be a relation between (j,t) and (state,N) + includes.append((j, t)) + + g = self.lr0_goto(C[j], t) # Go to next set + j = self.lr0_cidhash.get(id(g), -1) # Go to next state + + # When we get here, j is the final state, now we have to locate the production + for r in C[j]: + if r.name != p.name: + continue + if r.len != p.len: + continue + i = 0 + # This look is comparing a production ". A B C" with "A B C ." + while i < r.lr_index: + if r.prod[i] != p.prod[i+1]: + break + i = i + 1 + else: + lookb.append((j, r)) + for i in includes: + if i not in includedict: + includedict[i] = [] + includedict[i].append((state, N)) + lookdict[(state, N)] = lookb + + return lookdict, includedict + + # ----------------------------------------------------------------------------- + # compute_read_sets() + # + # Given a set of LR(0) items, this function computes the read sets. + # + # Inputs: C = Set of LR(0) items + # ntrans = Set of nonterminal transitions + # nullable = Set of empty transitions + # + # Returns a set containing the read sets + # ----------------------------------------------------------------------------- + + def compute_read_sets(self, C, ntrans, nullable): + FP = lambda x: self.dr_relation(C, x, nullable) + R = lambda x: self.reads_relation(C, x, nullable) + F = digraph(ntrans, R, FP) + return F + + # ----------------------------------------------------------------------------- + # compute_follow_sets() + # + # Given a set of LR(0) items, a set of non-terminal transitions, a readset, + # and an include set, this function computes the follow sets + # + # Follow(p,A) = Read(p,A) U U {Follow(p',B) | (p,A) INCLUDES (p',B)} + # + # Inputs: + # ntrans = Set of nonterminal transitions + # readsets = Readset (previously computed) + # inclsets = Include sets (previously computed) + # + # Returns a set containing the follow sets + # ----------------------------------------------------------------------------- + + def compute_follow_sets(self, ntrans, readsets, inclsets): + FP = lambda x: readsets[x] + R = lambda x: inclsets.get(x, []) + F = digraph(ntrans, R, FP) + return F + + # ----------------------------------------------------------------------------- + # add_lookaheads() + # + # Attaches the lookahead symbols to grammar rules. + # + # Inputs: lookbacks - Set of lookback relations + # followset - Computed follow set + # + # This function directly attaches the lookaheads to productions contained + # in the lookbacks set + # ----------------------------------------------------------------------------- + + def add_lookaheads(self, lookbacks, followset): + for trans, lb in lookbacks.items(): + # Loop over productions in lookback + for state, p in lb: + if state not in p.lookaheads: + p.lookaheads[state] = [] + f = followset.get(trans, []) + for a in f: + if a not in p.lookaheads[state]: + p.lookaheads[state].append(a) + + # ----------------------------------------------------------------------------- + # add_lalr_lookaheads() + # + # This function does all of the work of adding lookahead information for use + # with LALR parsing + # ----------------------------------------------------------------------------- + + def add_lalr_lookaheads(self, C): + # Determine all of the nullable nonterminals + nullable = self.compute_nullable_nonterminals() + + # Find all non-terminal transitions + trans = self.find_nonterminal_transitions(C) + + # Compute read sets + readsets = self.compute_read_sets(C, trans, nullable) + + # Compute lookback/includes relations + lookd, included = self.compute_lookback_includes(C, trans, nullable) + + # Compute LALR FOLLOW sets + followsets = self.compute_follow_sets(trans, readsets, included) + + # Add all of the lookaheads + self.add_lookaheads(lookd, followsets) + + # ----------------------------------------------------------------------------- + # lr_parse_table() + # + # This function constructs the parse tables for SLR or LALR + # ----------------------------------------------------------------------------- + def lr_parse_table(self): + Productions = self.grammar.Productions + Precedence = self.grammar.Precedence + goto = self.lr_goto # Goto array + action = self.lr_action # Action array + log = self.log # Logger for output + + actionp = {} # Action production array (temporary) + + log.info('Parsing method: %s', self.lr_method) + + # Step 1: Construct C = { I0, I1, ... IN}, collection of LR(0) items + # This determines the number of states + + C = self.lr0_items() + + if self.lr_method == 'LALR': + self.add_lalr_lookaheads(C) + + # Build the parser table, state by state + st = 0 + for I in C: + # Loop over each production in I + actlist = [] # List of actions + st_action = {} + st_actionp = {} + st_goto = {} + log.info('') + log.info('state %d', st) + log.info('') + for p in I: + log.info(' (%d) %s', p.number, p) + log.info('') + + for p in I: + if p.len == p.lr_index + 1: + if p.name == "S'": + # Start symbol. Accept! + st_action['$end'] = 0 + st_actionp['$end'] = p + else: + # We are at the end of a production. Reduce! + if self.lr_method == 'LALR': + laheads = p.lookaheads[st] + else: + laheads = self.grammar.Follow[p.name] + for a in laheads: + actlist.append((a, p, 'reduce using rule %d (%s)' % (p.number, p))) + r = st_action.get(a) + if r is not None: + # Whoa. Have a shift/reduce or reduce/reduce conflict + if r > 0: + # Need to decide on shift or reduce here + # By default we favor shifting. Need to add + # some precedence rules here. + + # Shift precedence comes from the token + sprec, slevel = Precedence.get(a, ('right', 0)) + + # Reduce precedence comes from rule being reduced (p) + rprec, rlevel = Productions[p.number].prec + + if (slevel < rlevel) or ((slevel == rlevel) and (rprec == 'left')): + # We really need to reduce here. + st_action[a] = -p.number + st_actionp[a] = p + if not slevel and not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as reduce', a) + self.sr_conflicts.append((st, a, 'reduce')) + Productions[p.number].reduced += 1 + elif (slevel == rlevel) and (rprec == 'nonassoc'): + st_action[a] = None + else: + # Hmmm. Guess we'll keep the shift + if not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as shift', a) + self.sr_conflicts.append((st, a, 'shift')) + elif r < 0: + # Reduce/reduce conflict. In this case, we favor the rule + # that was defined first in the grammar file + oldp = Productions[-r] + pp = Productions[p.number] + if oldp.line > pp.line: + st_action[a] = -p.number + st_actionp[a] = p + chosenp, rejectp = pp, oldp + Productions[p.number].reduced += 1 + Productions[oldp.number].reduced -= 1 + else: + chosenp, rejectp = oldp, pp + self.rr_conflicts.append((st, chosenp, rejectp)) + log.info(' ! reduce/reduce conflict for %s resolved using rule %d (%s)', + a, st_actionp[a].number, st_actionp[a]) + else: + raise LALRError('Unknown conflict in state %d' % st) + else: + st_action[a] = -p.number + st_actionp[a] = p + Productions[p.number].reduced += 1 + else: + i = p.lr_index + a = p.prod[i+1] # Get symbol right after the "." + if a in self.grammar.Terminals: + g = self.lr0_goto(I, a) + j = self.lr0_cidhash.get(id(g), -1) + if j >= 0: + # We are in a shift state + actlist.append((a, p, 'shift and go to state %d' % j)) + r = st_action.get(a) + if r is not None: + # Whoa have a shift/reduce or shift/shift conflict + if r > 0: + if r != j: + raise LALRError('Shift/shift conflict in state %d' % st) + elif r < 0: + # Do a precedence check. + # - if precedence of reduce rule is higher, we reduce. + # - if precedence of reduce is same and left assoc, we reduce. + # - otherwise we shift + + # Shift precedence comes from the token + sprec, slevel = Precedence.get(a, ('right', 0)) + + # Reduce precedence comes from the rule that could have been reduced + rprec, rlevel = Productions[st_actionp[a].number].prec + + if (slevel > rlevel) or ((slevel == rlevel) and (rprec == 'right')): + # We decide to shift here... highest precedence to shift + Productions[st_actionp[a].number].reduced -= 1 + st_action[a] = j + st_actionp[a] = p + if not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as shift', a) + self.sr_conflicts.append((st, a, 'shift')) + elif (slevel == rlevel) and (rprec == 'nonassoc'): + st_action[a] = None + else: + # Hmmm. Guess we'll keep the reduce + if not slevel and not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as reduce', a) + self.sr_conflicts.append((st, a, 'reduce')) + + else: + raise LALRError('Unknown conflict in state %d' % st) + else: + st_action[a] = j + st_actionp[a] = p + + # Print the actions associated with each terminal + _actprint = {} + for a, p, m in actlist: + if a in st_action: + if p is st_actionp[a]: + log.info(' %-15s %s', a, m) + _actprint[(a, m)] = 1 + log.info('') + # Print the actions that were not used. (debugging) + not_used = 0 + for a, p, m in actlist: + if a in st_action: + if p is not st_actionp[a]: + if not (a, m) in _actprint: + log.debug(' ! %-15s [ %s ]', a, m) + not_used = 1 + _actprint[(a, m)] = 1 + if not_used: + log.debug('') + + # Construct the goto table for this state + + nkeys = {} + for ii in I: + for s in ii.usyms: + if s in self.grammar.Nonterminals: + nkeys[s] = None + for n in nkeys: + g = self.lr0_goto(I, n) + j = self.lr0_cidhash.get(id(g), -1) + if j >= 0: + st_goto[n] = j + log.info(' %-30s shift and go to state %d', n, j) + + action[st] = st_action + actionp[st] = st_actionp + goto[st] = st_goto + st += 1 + + # ----------------------------------------------------------------------------- + # write() + # + # This function writes the LR parsing tables to a file + # ----------------------------------------------------------------------------- + + def write_table(self, tabmodule, outputdir='', signature=''): + if isinstance(tabmodule, types.ModuleType): + raise IOError("Won't overwrite existing tabmodule") + + basemodulename = tabmodule.split('.')[-1] + filename = os.path.join(outputdir, basemodulename) + '.py' + try: + f = open(filename, 'w') + + f.write(''' +# %s +# This file is automatically generated. Do not edit. +_tabversion = %r + +_lr_method = %r + +_lr_signature = %r + ''' % (os.path.basename(filename), __tabversion__, self.lr_method, signature)) + + # Change smaller to 0 to go back to original tables + smaller = 1 + + # Factor out names to try and make smaller + if smaller: + items = {} + + for s, nd in self.lr_action.items(): + for name, v in nd.items(): + i = items.get(name) + if not i: + i = ([], []) + items[name] = i + i[0].append(s) + i[1].append(v) + + f.write('\n_lr_action_items = {') + for k, v in items.items(): + f.write('%r:([' % k) + for i in v[0]: + f.write('%r,' % i) + f.write('],[') + for i in v[1]: + f.write('%r,' % i) + + f.write(']),') + f.write('}\n') + + f.write(''' +_lr_action = {} +for _k, _v in _lr_action_items.items(): + for _x,_y in zip(_v[0],_v[1]): + if not _x in _lr_action: _lr_action[_x] = {} + _lr_action[_x][_k] = _y +del _lr_action_items +''') + + else: + f.write('\n_lr_action = { ') + for k, v in self.lr_action.items(): + f.write('(%r,%r):%r,' % (k[0], k[1], v)) + f.write('}\n') + + if smaller: + # Factor out names to try and make smaller + items = {} + + for s, nd in self.lr_goto.items(): + for name, v in nd.items(): + i = items.get(name) + if not i: + i = ([], []) + items[name] = i + i[0].append(s) + i[1].append(v) + + f.write('\n_lr_goto_items = {') + for k, v in items.items(): + f.write('%r:([' % k) + for i in v[0]: + f.write('%r,' % i) + f.write('],[') + for i in v[1]: + f.write('%r,' % i) + + f.write(']),') + f.write('}\n') + + f.write(''' +_lr_goto = {} +for _k, _v in _lr_goto_items.items(): + for _x, _y in zip(_v[0], _v[1]): + if not _x in _lr_goto: _lr_goto[_x] = {} + _lr_goto[_x][_k] = _y +del _lr_goto_items +''') + else: + f.write('\n_lr_goto = { ') + for k, v in self.lr_goto.items(): + f.write('(%r,%r):%r,' % (k[0], k[1], v)) + f.write('}\n') + + # Write production table + f.write('_lr_productions = [\n') + for p in self.lr_productions: + if p.func: + f.write(' (%r,%r,%d,%r,%r,%d),\n' % (p.str, p.name, p.len, + p.func, os.path.basename(p.file), p.line)) + else: + f.write(' (%r,%r,%d,None,None,None),\n' % (str(p), p.name, p.len)) + f.write(']\n') + f.close() + + except IOError as e: + raise + + + # ----------------------------------------------------------------------------- + # pickle_table() + # + # This function pickles the LR parsing tables to a supplied file object + # ----------------------------------------------------------------------------- + + def pickle_table(self, filename, signature=''): + try: + import cPickle as pickle + except ImportError: + import pickle + with open(filename, 'wb') as outf: + pickle.dump(__tabversion__, outf, pickle_protocol) + pickle.dump(self.lr_method, outf, pickle_protocol) + pickle.dump(signature, outf, pickle_protocol) + pickle.dump(self.lr_action, outf, pickle_protocol) + pickle.dump(self.lr_goto, outf, pickle_protocol) + + outp = [] + for p in self.lr_productions: + if p.func: + outp.append((p.str, p.name, p.len, p.func, os.path.basename(p.file), p.line)) + else: + outp.append((str(p), p.name, p.len, None, None, None)) + pickle.dump(outp, outf, pickle_protocol) + +# ----------------------------------------------------------------------------- +# === INTROSPECTION === +# +# The following functions and classes are used to implement the PLY +# introspection features followed by the yacc() function itself. +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# get_caller_module_dict() +# +# This function returns a dictionary containing all of the symbols defined within +# a caller further down the call stack. This is used to get the environment +# associated with the yacc() call if none was provided. +# ----------------------------------------------------------------------------- + +def get_caller_module_dict(levels): + f = sys._getframe(levels) + ldict = f.f_globals.copy() + if f.f_globals != f.f_locals: + ldict.update(f.f_locals) + return ldict + +# ----------------------------------------------------------------------------- +# parse_grammar() +# +# This takes a raw grammar rule string and parses it into production data +# ----------------------------------------------------------------------------- +def parse_grammar(doc, file, line): + grammar = [] + # Split the doc string into lines + pstrings = doc.splitlines() + lastp = None + dline = line + for ps in pstrings: + dline += 1 + p = ps.split() + if not p: + continue + try: + if p[0] == '|': + # This is a continuation of a previous rule + if not lastp: + raise SyntaxError("%s:%d: Misplaced '|'" % (file, dline)) + prodname = lastp + syms = p[1:] + else: + prodname = p[0] + lastp = prodname + syms = p[2:] + assign = p[1] + if assign != ':' and assign != '::=': + raise SyntaxError("%s:%d: Syntax error. Expected ':'" % (file, dline)) + + grammar.append((file, dline, prodname, syms)) + except SyntaxError: + raise + except Exception: + raise SyntaxError('%s:%d: Syntax error in rule %r' % (file, dline, ps.strip())) + + return grammar + +# ----------------------------------------------------------------------------- +# ParserReflect() +# +# This class represents information extracted for building a parser including +# start symbol, error function, tokens, precedence list, action functions, +# etc. +# ----------------------------------------------------------------------------- +class ParserReflect(object): + def __init__(self, pdict, log=None): + self.pdict = pdict + self.start = None + self.error_func = None + self.tokens = None + self.modules = set() + self.grammar = [] + self.error = False + + if log is None: + self.log = PlyLogger(sys.stderr) + else: + self.log = log + + # Get all of the basic information + def get_all(self): + self.get_start() + self.get_error_func() + self.get_tokens() + self.get_precedence() + self.get_pfunctions() + + # Validate all of the information + def validate_all(self): + self.validate_start() + self.validate_error_func() + self.validate_tokens() + self.validate_precedence() + self.validate_pfunctions() + self.validate_modules() + return self.error + + # Compute a signature over the grammar + def signature(self): + parts = [] + try: + if self.start: + parts.append(self.start) + if self.prec: + parts.append(''.join([''.join(p) for p in self.prec])) + if self.tokens: + parts.append(' '.join(self.tokens)) + for f in self.pfuncs: + if f[3]: + parts.append(f[3]) + except (TypeError, ValueError): + pass + return ''.join(parts) + + # ----------------------------------------------------------------------------- + # validate_modules() + # + # This method checks to see if there are duplicated p_rulename() functions + # in the parser module file. Without this function, it is really easy for + # users to make mistakes by cutting and pasting code fragments (and it's a real + # bugger to try and figure out why the resulting parser doesn't work). Therefore, + # we just do a little regular expression pattern matching of def statements + # to try and detect duplicates. + # ----------------------------------------------------------------------------- + + def validate_modules(self): + # Match def p_funcname( + fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(') + + for module in self.modules: + try: + lines, linen = inspect.getsourcelines(module) + except IOError: + continue + + counthash = {} + for linen, line in enumerate(lines): + linen += 1 + m = fre.match(line) + if m: + name = m.group(1) + prev = counthash.get(name) + if not prev: + counthash[name] = linen + else: + filename = inspect.getsourcefile(module) + self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d', + filename, linen, name, prev) + + # Get the start symbol + def get_start(self): + self.start = self.pdict.get('start') + + # Validate the start symbol + def validate_start(self): + if self.start is not None: + if not isinstance(self.start, string_types): + self.log.error("'start' must be a string") + + # Look for error handler + def get_error_func(self): + self.error_func = self.pdict.get('p_error') + + # Validate the error function + def validate_error_func(self): + if self.error_func: + if isinstance(self.error_func, types.FunctionType): + ismethod = 0 + elif isinstance(self.error_func, types.MethodType): + ismethod = 1 + else: + self.log.error("'p_error' defined, but is not a function or method") + self.error = True + return + + eline = self.error_func.__code__.co_firstlineno + efile = self.error_func.__code__.co_filename + module = inspect.getmodule(self.error_func) + self.modules.add(module) + + argcount = self.error_func.__code__.co_argcount - ismethod + if argcount != 1: + self.log.error('%s:%d: p_error() requires 1 argument', efile, eline) + self.error = True + + # Get the tokens map + def get_tokens(self): + tokens = self.pdict.get('tokens') + if not tokens: + self.log.error('No token list is defined') + self.error = True + return + + if not isinstance(tokens, (list, tuple)): + self.log.error('tokens must be a list or tuple') + self.error = True + return + + if not tokens: + self.log.error('tokens is empty') + self.error = True + return + + self.tokens = tokens + + # Validate the tokens + def validate_tokens(self): + # Validate the tokens. + if 'error' in self.tokens: + self.log.error("Illegal token name 'error'. Is a reserved word") + self.error = True + return + + terminals = set() + for n in self.tokens: + if n in terminals: + self.log.warning('Token %r multiply defined', n) + terminals.add(n) + + # Get the precedence map (if any) + def get_precedence(self): + self.prec = self.pdict.get('precedence') + + # Validate and parse the precedence map + def validate_precedence(self): + preclist = [] + if self.prec: + if not isinstance(self.prec, (list, tuple)): + self.log.error('precedence must be a list or tuple') + self.error = True + return + for level, p in enumerate(self.prec): + if not isinstance(p, (list, tuple)): + self.log.error('Bad precedence table') + self.error = True + return + + if len(p) < 2: + self.log.error('Malformed precedence entry %s. Must be (assoc, term, ..., term)', p) + self.error = True + return + assoc = p[0] + if not isinstance(assoc, string_types): + self.log.error('precedence associativity must be a string') + self.error = True + return + for term in p[1:]: + if not isinstance(term, string_types): + self.log.error('precedence items must be strings') + self.error = True + return + preclist.append((term, assoc, level+1)) + self.preclist = preclist + + # Get all p_functions from the grammar + def get_pfunctions(self): + p_functions = [] + for name, item in self.pdict.items(): + if not name.startswith('p_') or name == 'p_error': + continue + if isinstance(item, (types.FunctionType, types.MethodType)): + line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno) + module = inspect.getmodule(item) + p_functions.append((line, module, name, item.__doc__)) + + # Sort all of the actions by line number; make sure to stringify + # modules to make them sortable, since `line` may not uniquely sort all + # p functions + p_functions.sort(key=lambda p_function: ( + p_function[0], + str(p_function[1]), + p_function[2], + p_function[3])) + self.pfuncs = p_functions + + # Validate all of the p_functions + def validate_pfunctions(self): + grammar = [] + # Check for non-empty symbols + if len(self.pfuncs) == 0: + self.log.error('no rules of the form p_rulename are defined') + self.error = True + return + + for line, module, name, doc in self.pfuncs: + file = inspect.getsourcefile(module) + func = self.pdict[name] + if isinstance(func, types.MethodType): + reqargs = 2 + else: + reqargs = 1 + if func.__code__.co_argcount > reqargs: + self.log.error('%s:%d: Rule %r has too many arguments', file, line, func.__name__) + self.error = True + elif func.__code__.co_argcount < reqargs: + self.log.error('%s:%d: Rule %r requires an argument', file, line, func.__name__) + self.error = True + elif not func.__doc__: + self.log.warning('%s:%d: No documentation string specified in function %r (ignored)', + file, line, func.__name__) + else: + try: + parsed_g = parse_grammar(doc, file, line) + for g in parsed_g: + grammar.append((name, g)) + except SyntaxError as e: + self.log.error(str(e)) + self.error = True + + # Looks like a valid grammar rule + # Mark the file in which defined. + self.modules.add(module) + + # Secondary validation step that looks for p_ definitions that are not functions + # or functions that look like they might be grammar rules. + + for n, v in self.pdict.items(): + if n.startswith('p_') and isinstance(v, (types.FunctionType, types.MethodType)): + continue + if n.startswith('t_'): + continue + if n.startswith('p_') and n != 'p_error': + self.log.warning('%r not defined as a function', n) + if ((isinstance(v, types.FunctionType) and v.__code__.co_argcount == 1) or + (isinstance(v, types.MethodType) and v.__func__.__code__.co_argcount == 2)): + if v.__doc__: + try: + doc = v.__doc__.split(' ') + if doc[1] == ':': + self.log.warning('%s:%d: Possible grammar rule %r defined without p_ prefix', + v.__code__.co_filename, v.__code__.co_firstlineno, n) + except IndexError: + pass + + self.grammar = grammar + +# ----------------------------------------------------------------------------- +# yacc(module) +# +# Build a parser +# ----------------------------------------------------------------------------- + +def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, start=None, + check_recursion=True, optimize=False, write_tables=True, debugfile=debug_file, + outputdir=None, debuglog=None, errorlog=None, picklefile=None): + + if tabmodule is None: + tabmodule = tab_module + + # Reference to the parsing method of the last built parser + global parse + + # If pickling is enabled, table files are not created + if picklefile: + write_tables = 0 + + if errorlog is None: + errorlog = PlyLogger(sys.stderr) + + # Get the module dictionary used for the parser + if module: + _items = [(k, getattr(module, k)) for k in dir(module)] + pdict = dict(_items) + # If no __file__ attribute is available, try to obtain it from the __module__ instead + if '__file__' not in pdict: + pdict['__file__'] = sys.modules[pdict['__module__']].__file__ + else: + pdict = get_caller_module_dict(2) + + if outputdir is None: + # If no output directory is set, the location of the output files + # is determined according to the following rules: + # - If tabmodule specifies a package, files go into that package directory + # - Otherwise, files go in the same directory as the specifying module + if isinstance(tabmodule, types.ModuleType): + srcfile = tabmodule.__file__ + else: + if '.' not in tabmodule: + srcfile = pdict['__file__'] + else: + parts = tabmodule.split('.') + pkgname = '.'.join(parts[:-1]) + exec('import %s' % pkgname) + srcfile = getattr(sys.modules[pkgname], '__file__', '') + outputdir = os.path.dirname(srcfile) + + # Determine if the module is package of a package or not. + # If so, fix the tabmodule setting so that tables load correctly + pkg = pdict.get('__package__') + if pkg and isinstance(tabmodule, str): + if '.' not in tabmodule: + tabmodule = pkg + '.' + tabmodule + + + + # Set start symbol if it's specified directly using an argument + if start is not None: + pdict['start'] = start + + # Collect parser information from the dictionary + pinfo = ParserReflect(pdict, log=errorlog) + pinfo.get_all() + + if pinfo.error: + raise YaccError('Unable to build parser') + + # Check signature against table files (if any) + signature = pinfo.signature() + + # Read the tables + try: + lr = LRTable() + if picklefile: + read_signature = lr.read_pickle(picklefile) + else: + read_signature = lr.read_table(tabmodule) + if optimize or (read_signature == signature): + try: + lr.bind_callables(pinfo.pdict) + parser = LRParser(lr, pinfo.error_func) + parse = parser.parse + return parser + except Exception as e: + errorlog.warning('There was a problem loading the table file: %r', e) + except VersionError as e: + errorlog.warning(str(e)) + except ImportError: + pass + + if debuglog is None: + if debug: + try: + debuglog = PlyLogger(open(os.path.join(outputdir, debugfile), 'w')) + except IOError as e: + errorlog.warning("Couldn't open %r. %s" % (debugfile, e)) + debuglog = NullLogger() + else: + debuglog = NullLogger() + + debuglog.info('Created by PLY version %s (http://www.dabeaz.com/ply)', __version__) + + errors = False + + # Validate the parser information + if pinfo.validate_all(): + raise YaccError('Unable to build parser') + + if not pinfo.error_func: + errorlog.warning('no p_error() function is defined') + + # Create a grammar object + grammar = Grammar(pinfo.tokens) + + # Set precedence level for terminals + for term, assoc, level in pinfo.preclist: + try: + grammar.set_precedence(term, assoc, level) + except GrammarError as e: + errorlog.warning('%s', e) + + # Add productions to the grammar + for funcname, gram in pinfo.grammar: + file, line, prodname, syms = gram + try: + grammar.add_production(prodname, syms, funcname, file, line) + except GrammarError as e: + errorlog.error('%s', e) + errors = True + + # Set the grammar start symbols + try: + if start is None: + grammar.set_start(pinfo.start) + else: + grammar.set_start(start) + except GrammarError as e: + errorlog.error(str(e)) + errors = True + + if errors: + raise YaccError('Unable to build parser') + + # Verify the grammar structure + undefined_symbols = grammar.undefined_symbols() + for sym, prod in undefined_symbols: + errorlog.error('%s:%d: Symbol %r used, but not defined as a token or a rule', prod.file, prod.line, sym) + errors = True + + unused_terminals = grammar.unused_terminals() + if unused_terminals: + debuglog.info('') + debuglog.info('Unused terminals:') + debuglog.info('') + for term in unused_terminals: + errorlog.warning('Token %r defined, but not used', term) + debuglog.info(' %s', term) + + # Print out all productions to the debug log + if debug: + debuglog.info('') + debuglog.info('Grammar') + debuglog.info('') + for n, p in enumerate(grammar.Productions): + debuglog.info('Rule %-5d %s', n, p) + + # Find unused non-terminals + unused_rules = grammar.unused_rules() + for prod in unused_rules: + errorlog.warning('%s:%d: Rule %r defined, but not used', prod.file, prod.line, prod.name) + + if len(unused_terminals) == 1: + errorlog.warning('There is 1 unused token') + if len(unused_terminals) > 1: + errorlog.warning('There are %d unused tokens', len(unused_terminals)) + + if len(unused_rules) == 1: + errorlog.warning('There is 1 unused rule') + if len(unused_rules) > 1: + errorlog.warning('There are %d unused rules', len(unused_rules)) + + if debug: + debuglog.info('') + debuglog.info('Terminals, with rules where they appear') + debuglog.info('') + terms = list(grammar.Terminals) + terms.sort() + for term in terms: + debuglog.info('%-20s : %s', term, ' '.join([str(s) for s in grammar.Terminals[term]])) + + debuglog.info('') + debuglog.info('Nonterminals, with rules where they appear') + debuglog.info('') + nonterms = list(grammar.Nonterminals) + nonterms.sort() + for nonterm in nonterms: + debuglog.info('%-20s : %s', nonterm, ' '.join([str(s) for s in grammar.Nonterminals[nonterm]])) + debuglog.info('') + + if check_recursion: + unreachable = grammar.find_unreachable() + for u in unreachable: + errorlog.warning('Symbol %r is unreachable', u) + + infinite = grammar.infinite_cycles() + for inf in infinite: + errorlog.error('Infinite recursion detected for symbol %r', inf) + errors = True + + unused_prec = grammar.unused_precedence() + for term, assoc in unused_prec: + errorlog.error('Precedence rule %r defined for unknown symbol %r', assoc, term) + errors = True + + if errors: + raise YaccError('Unable to build parser') + + # Run the LRGeneratedTable on the grammar + if debug: + errorlog.debug('Generating %s tables', method) + + lr = LRGeneratedTable(grammar, method, debuglog) + + if debug: + num_sr = len(lr.sr_conflicts) + + # Report shift/reduce and reduce/reduce conflicts + if num_sr == 1: + errorlog.warning('1 shift/reduce conflict') + elif num_sr > 1: + errorlog.warning('%d shift/reduce conflicts', num_sr) + + num_rr = len(lr.rr_conflicts) + if num_rr == 1: + errorlog.warning('1 reduce/reduce conflict') + elif num_rr > 1: + errorlog.warning('%d reduce/reduce conflicts', num_rr) + + # Write out conflicts to the output file + if debug and (lr.sr_conflicts or lr.rr_conflicts): + debuglog.warning('') + debuglog.warning('Conflicts:') + debuglog.warning('') + + for state, tok, resolution in lr.sr_conflicts: + debuglog.warning('shift/reduce conflict for %s in state %d resolved as %s', tok, state, resolution) + + already_reported = set() + for state, rule, rejected in lr.rr_conflicts: + if (state, id(rule), id(rejected)) in already_reported: + continue + debuglog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule) + debuglog.warning('rejected rule (%s) in state %d', rejected, state) + errorlog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule) + errorlog.warning('rejected rule (%s) in state %d', rejected, state) + already_reported.add((state, id(rule), id(rejected))) + + warned_never = [] + for state, rule, rejected in lr.rr_conflicts: + if not rejected.reduced and (rejected not in warned_never): + debuglog.warning('Rule (%s) is never reduced', rejected) + errorlog.warning('Rule (%s) is never reduced', rejected) + warned_never.append(rejected) + + # Write the table file if requested + if write_tables: + try: + lr.write_table(tabmodule, outputdir, signature) + except IOError as e: + errorlog.warning("Couldn't create %r. %s" % (tabmodule, e)) + + # Write a pickled version of the tables + if picklefile: + try: + lr.pickle_table(picklefile, signature) + except IOError as e: + errorlog.warning("Couldn't create %r. %s" % (picklefile, e)) + + # Build the parser + lr.bind_callables(pinfo.pdict) + parser = LRParser(lr, pinfo.error_func) + + parse = parser.parse + return parser diff --git a/shared/package-files/79/79ab9ec4b5fbdd9437671e1305b759cdd3407a5017cd5f1af650068a3a17a94d/blob b/shared/package-files/79/79ab9ec4b5fbdd9437671e1305b759cdd3407a5017cd5f1af650068a3a17a94d/blob new file mode 100644 index 0000000000000000000000000000000000000000..a8f9e0974d4c756597ddfaa3942c20bdfeb91a21 --- /dev/null +++ b/shared/package-files/79/79ab9ec4b5fbdd9437671e1305b759cdd3407a5017cd5f1af650068a3a17a94d/blob @@ -0,0 +1,310 @@ +/* +Expose all functions as pointers in a dedicated C extension. +*/ +#include "cext/cext.h" +/* Import _pymodule.h first, for a recent _POSIX_C_SOURCE */ +#include "_pymodule.h" + +#include +#ifdef _MSC_VER + #define false 0 + #define true 1 + #define bool int +#else + #include +#endif + +/* +Include C-extension here +*/ +#include "cext/cext.h" + +/* Numba C helpers */ +#include "_helperlib.c" + +static PyObject * +build_c_helpers_dict(void) +{ + PyObject *dct = PyDict_New(); + if (dct == NULL) + goto error; + +#define _declpointer(name, value) do { \ + PyObject *o = PyLong_FromVoidPtr(value); \ + if (o == NULL) goto error; \ + if (PyDict_SetItemString(dct, name, o)) { \ + Py_DECREF(o); \ + goto error; \ + } \ + Py_DECREF(o); \ +} while (0) + +#define declmethod(func) _declpointer(#func, &numba_##func) + +#define declpointer(ptr) _declpointer(#ptr, &numba_##ptr) + + declmethod(fixed_fmod); + declmethod(fixed_fmodf); + declmethod(set_fnclex); + + declmethod(sdiv); + declmethod(srem); + declmethod(udiv); + declmethod(urem); + declmethod(frexp); + declmethod(frexpf); + declmethod(ldexp); + declmethod(ldexpf); + declmethod(cpow); + declmethod(cpowf); + declmethod(erf); + declmethod(erff); + declmethod(erfc); + declmethod(erfcf); + declmethod(gamma); + declmethod(gammaf); + declmethod(lgamma); + declmethod(lgammaf); + declmethod(nextafter); + declmethod(nextafterf); + declmethod(complex_adaptor); + declmethod(adapt_ndarray); + declmethod(ndarray_new); + declmethod(extract_record_data); + declmethod(get_buffer); + declmethod(adapt_buffer); + declmethod(release_buffer); + declmethod(extract_np_datetime); + declmethod(create_np_datetime); + declmethod(extract_np_timedelta); + declmethod(create_np_timedelta); + declmethod(recreate_record); + declmethod(fptoui); + declmethod(fptouif); + declmethod(gil_ensure); + declmethod(gil_release); + declmethod(fatal_error); + declmethod(py_type); + declmethod(unpack_slice); + declmethod(do_raise); + declmethod(unpickle); + declmethod(runtime_build_excinfo_struct); + declmethod(attempt_nocopy_reshape); + declmethod(get_pyobject_private_data); + declmethod(set_pyobject_private_data); + declmethod(reset_pyobject_private_data); + + /* + * BLAS / LAPACK + * Compiled for a single Fortran integer width, fixed at build time -- + * see NUMBA_LAPACK_BUILD_ILP64 below and numba/_lapack.c. + */ + declmethod(xxgemm); + declmethod(xxgemv); + declmethod(xxdot); + declmethod(xxgetrf); + declmethod(ez_xxgetri); + declmethod(xxpotrf); + declmethod(ez_rgeev); + declmethod(ez_cgeev); + declmethod(ez_xxxevd); + declmethod(ez_gesdd); + declmethod(ez_geqrf); + declmethod(ez_xxgqr); + declmethod(ez_gelsd); + declmethod(xgesv); + declmethod(xxnrm2); + + /* PRNG support */ + declmethod(get_py_random_state); + declmethod(get_np_random_state); + declmethod(get_internal_random_state); + declmethod(rnd_shuffle); + declmethod(rnd_init); + declmethod(poisson_ptrs); + + /* Unicode string support */ + declmethod(extract_unicode); + declmethod(gettyperecord); + declmethod(get_PyUnicode_ExtendedCase); + + /* for gdb breakpoint */ + declmethod(gdb_breakpoint); + + /* for dictionary support */ + declmethod(test_dict); + declmethod(dict_new_sized); + declmethod(dict_set_method_table); + declmethod(dict_free); + declmethod(dict_length); + declmethod(dict_lookup); + declmethod(dict_insert); + declmethod(dict_insert_ez); + declmethod(dict_delitem); + declmethod(dict_popitem); + declmethod(dict_iter_sizeof); + declmethod(dict_iter); + declmethod(dict_iter_next); + declmethod(dict_dump); + + /* for list support */ + declmethod(test_list); + declmethod(list_new); + declmethod(list_set_method_table); + declmethod(list_free); + declmethod(list_base_ptr); + declmethod(list_size_address); + declmethod(list_length); + declmethod(list_allocated); + declmethod(list_is_mutable); + declmethod(list_set_is_mutable); + declmethod(list_setitem); + declmethod(list_getitem); + declmethod(list_append); + declmethod(list_delitem); + declmethod(list_delete_slice); + declmethod(list_iter_sizeof); + declmethod(list_iter); + declmethod(list_iter_next); + + /* for set support */ + declmethod(test_set); + declmethod(set_new); + declmethod(set_new_sized); + declmethod(set_set_method_table); + declmethod(set_free); + declmethod(set_length); + declmethod(set_add); + declmethod(set_contains); + declmethod(set_discard); + declmethod(set_iter_sizeof); + declmethod(set_iter); + declmethod(set_iter_next); + declmethod(set_dump); + +#define MATH_UNARY(F, R, A) declmethod(F); +#define MATH_BINARY(F, R, A, B) declmethod(F); + #include "mathnames.h" +#undef MATH_UNARY +#undef MATH_BINARY + +#undef declmethod + return dct; +error: + Py_XDECREF(dct); + return NULL; +} + + +/* + * Helper to deal with flushing stdout + */ +PyAPI_FUNC(void) _numba_flush_stdout(void) ; + +void +_numba_flush_stdout(void) { + fflush(stdout); +} + + +static PyMethodDef ext_methods[] = { + { "rnd_get_state", (PyCFunction) _numba_rnd_get_state, METH_O, NULL }, + { "rnd_get_py_state_ptr", (PyCFunction) _numba_rnd_get_py_state_ptr, METH_NOARGS, NULL }, + { "rnd_get_np_state_ptr", (PyCFunction) _numba_rnd_get_np_state_ptr, METH_NOARGS, NULL }, + { "rnd_seed", (PyCFunction) _numba_rnd_seed, METH_VARARGS, NULL }, + { "rnd_set_state", (PyCFunction) _numba_rnd_set_state, METH_VARARGS, NULL }, + { "rnd_shuffle", (PyCFunction) _numba_rnd_shuffle, METH_O, NULL }, + { "_import_cython_function", (PyCFunction) _numba_import_cython_function, METH_VARARGS, NULL }, + { NULL }, +}; + +/* + * These functions are exported by the module's DLL, to exercise ctypes / cffi + * without relying on libc availability (see https://bugs.python.org/issue23606) + */ + +PyAPI_FUNC(double) _numba_test_sin(double x); +PyAPI_FUNC(double) _numba_test_cos(double x); +PyAPI_FUNC(double) _numba_test_exp(double x); +PyAPI_FUNC(void) _numba_test_vsquare(int n, double *x, double *out); +PyAPI_FUNC(double) _numba_test_funcptr(double (*func)(double)); +PyAPI_FUNC(bool) _numba_test_boolean(void); + +double _numba_test_sin(double x) +{ + return sin(x); +} + +double _numba_test_cos(double x) +{ + return cos(x); +} + +double _numba_test_exp(double x) +{ + return exp(x); +} + +void _numba_test_vsquare(int n, double *x, double *out) +{ + int i; + for (i = 0; i < n; i++) + out[i] = pow(x[i], 2.0); +} + +void _numba_test_vcube(int n, double *x, double *out) +{ + int i; + for (i = 0; i < n; i++) + out[i] = pow(x[i], 3.0); +} + +double _numba_test_funcptr(double (*func)(double)) +{ + return func(1.5); +} + +bool _numba_test_boolean() +{ + return true; +} + +MOD_INIT(_helperlib) { + PyObject *m; + MOD_DEF(m, "_helperlib", "No docs", ext_methods) + if (m == NULL) + return MOD_ERROR_VAL; + + import_array(); + + PyModule_AddObject(m, "c_helpers", build_c_helpers_dict()); +#ifndef NUMBA_LAPACK_BUILD_ILP64 +#define NUMBA_LAPACK_BUILD_ILP64 0 +#endif + /* + * Which Fortran integer width numba/_lapack.c was built to target (see + * NUMBA_LAPACK_ILP64 in setup.py and the "Build time environment + * variables" docs). Baked in as a compile-time macro (set via + * Extension(define_macros=...) in setup.py, and used directly by + * numba/_lapack.c to fix F_INT) rather than a loose generated .py + * file, so it can't drift from the actual compiled binary. + * numba.np.linalg reads this once and checks it against the scipy + * actually installed at runtime. + */ + PyModule_AddIntConstant(m, "LAPACK_BUILD_ILP64", NUMBA_LAPACK_BUILD_ILP64); + PyModule_AddIntConstant(m, "long_min", LONG_MIN); + PyModule_AddIntConstant(m, "long_max", LONG_MAX); + PyModule_AddIntConstant(m, "py_buffer_size", sizeof(Py_buffer)); + PyModule_AddIntConstant(m, "py_gil_state_size", sizeof(PyGILState_STATE)); + PyModule_AddIntConstant(m, "py_unicode_1byte_kind", PyUnicode_1BYTE_KIND); + PyModule_AddIntConstant(m, "py_unicode_2byte_kind", PyUnicode_2BYTE_KIND); + PyModule_AddIntConstant(m, "py_unicode_4byte_kind", PyUnicode_4BYTE_KIND); +#if (PY_MAJOR_VERSION == 3) +#if ((PY_MINOR_VERSION == 10) || (PY_MINOR_VERSION == 11)) + PyModule_AddIntConstant(m, "py_unicode_wchar_kind", PyUnicode_WCHAR_KIND); +#endif +#endif + numba_rnd_ensure_global_init(); + + return MOD_SUCCESS_VAL(m); +} diff --git a/shared/package-files/79/79ac63ae025a874200da2cb0523344e88fe7b984bace79b7dce55fdbe688d5fa/blob b/shared/package-files/79/79ac63ae025a874200da2cb0523344e88fe7b984bace79b7dce55fdbe688d5fa/blob new file mode 100644 index 0000000000000000000000000000000000000000..802765f6e9f659eed094decea969a7725b7408bf --- /dev/null +++ b/shared/package-files/79/79ac63ae025a874200da2cb0523344e88fe7b984bace79b7dce55fdbe688d5fa/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79ac63ae025a874200da2cb0523344e88fe7b984bace79b7dce55fdbe688d5fa +size 211992 diff --git a/shared/package-files/79/79acb8fe67eb37bbe0d991a85e6674e9c53d08b41804928c47f74aeacd96ca27/blob b/shared/package-files/79/79acb8fe67eb37bbe0d991a85e6674e9c53d08b41804928c47f74aeacd96ca27/blob new file mode 100644 index 0000000000000000000000000000000000000000..0b19792475e06369fb26e526e2644a3285f4223f --- /dev/null +++ b/shared/package-files/79/79acb8fe67eb37bbe0d991a85e6674e9c53d08b41804928c47f74aeacd96ca27/blob @@ -0,0 +1,25 @@ +import numpy as np +import pytest + +from sklearn.utils._weight_vector import ( + WeightVector32, + WeightVector64, +) + + +@pytest.mark.parametrize( + "dtype, WeightVector", + [ + (np.float32, WeightVector32), + (np.float64, WeightVector64), + ], +) +def test_type_invariance(dtype, WeightVector): + """Check the `dtype` consistency of `WeightVector`.""" + weights = np.random.rand(100).astype(dtype) + average_weights = np.random.rand(100).astype(dtype) + + weight_vector = WeightVector(weights, average_weights) + + assert np.asarray(weight_vector.w).dtype is np.dtype(dtype) + assert np.asarray(weight_vector.aw).dtype is np.dtype(dtype) diff --git a/shared/package-files/79/79adf698cdb4b87c92972822f4cb55c6bdba3bec9d4d91c2510225c5a20c8d3e/blob b/shared/package-files/79/79adf698cdb4b87c92972822f4cb55c6bdba3bec9d4d91c2510225c5a20c8d3e/blob new file mode 100644 index 0000000000000000000000000000000000000000..c2eb62fc29accb670f5d53e326381d68a6534335 --- /dev/null +++ b/shared/package-files/79/79adf698cdb4b87c92972822f4cb55c6bdba3bec9d4d91c2510225c5a20c8d3e/blob @@ -0,0 +1,42 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/status.h" + +#include "arrow/python/visibility.h" + +namespace arrow { +namespace py { +namespace testing { + +struct TestCase { + std::string name; + std::function func; +}; + +ARROW_PYTHON_EXPORT +std::vector GetCppTestCases(); + +} // namespace testing +} // namespace py +} // namespace arrow diff --git a/shared/package-files/79/79ae0103ba4c18c8608a04dea3557b895ccc33aafefbd53ffb0d3748c24db743/blob b/shared/package-files/79/79ae0103ba4c18c8608a04dea3557b895ccc33aafefbd53ffb0d3748c24db743/blob new file mode 100644 index 0000000000000000000000000000000000000000..0f21d8cc04cb86a6960cc711ab3b2c9a844db6a2 --- /dev/null +++ b/shared/package-files/79/79ae0103ba4c18c8608a04dea3557b895ccc33aafefbd53ffb0d3748c24db743/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void miopen_rnn_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const c10::optional & cx, const at::Tensor & output, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask); +TORCH_API void miopen_rnn_backward_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const c10::optional & cx, const at::Tensor & output, const c10::optional & grad_output, const c10::optional & grad_hy, const c10::optional & grad_cy, int64_t mode, int64_t hidden_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const c10::optional & dropout_state, const at::Tensor & reserve, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/79/79b1d6a0b78874153c60e550e28e9f1d7bdf1d54c48a403047e33d9c177fb925/blob b/shared/package-files/79/79b1d6a0b78874153c60e550e28e9f1d7bdf1d54c48a403047e33d9c177fb925/blob new file mode 100644 index 0000000000000000000000000000000000000000..4624d7c018f7625c70cd3eb9d900c6198ba4a4b5 Binary files /dev/null and b/shared/package-files/79/79b1d6a0b78874153c60e550e28e9f1d7bdf1d54c48a403047e33d9c177fb925/blob differ diff --git a/shared/package-files/79/79b9c4b76b089aaa5831a8bb96fe4a55da4e60f5fcbebcee178effc2ece69dc4/blob b/shared/package-files/79/79b9c4b76b089aaa5831a8bb96fe4a55da4e60f5fcbebcee178effc2ece69dc4/blob new file mode 100644 index 0000000000000000000000000000000000000000..e6a9bbe7ecc8fe4c8359a56e834048b0d5251324 --- /dev/null +++ b/shared/package-files/79/79b9c4b76b089aaa5831a8bb96fe4a55da4e60f5fcbebcee178effc2ece69dc4/blob @@ -0,0 +1,12 @@ +from contextlib import contextmanager + +from torch.distributed._tensor.api import DTensor + + +@contextmanager +def implicit_replication(): + try: + DTensor._op_dispatcher._allow_implicit_replication = True + yield + finally: + DTensor._op_dispatcher._allow_implicit_replication = False diff --git a/shared/package-files/79/79b9c944fc9864e8ca139c743df5d76e211603dc38999b4bd63d7d2e1e3a5ad2/blob b/shared/package-files/79/79b9c944fc9864e8ca139c743df5d76e211603dc38999b4bd63d7d2e1e3a5ad2/blob new file mode 100644 index 0000000000000000000000000000000000000000..23837f03dedb6f518e0c5a81997ffe005a70e82a --- /dev/null +++ b/shared/package-files/79/79b9c944fc9864e8ca139c743df5d76e211603dc38999b4bd63d7d2e1e3a5ad2/blob @@ -0,0 +1,154 @@ +"""Unit tests for the :mod:`networkx.algorithms.boundary` module.""" + +from itertools import combinations + +import pytest + +import networkx as nx +from networkx import convert_node_labels_to_integers as cnlti +from networkx.utils import edges_equal + + +class TestNodeBoundary: + """Unit tests for the :func:`~networkx.node_boundary` function.""" + + def test_null_graph(self): + """Tests that the null graph has empty node boundaries.""" + null = nx.null_graph() + assert nx.node_boundary(null, []) == set() + assert nx.node_boundary(null, [], []) == set() + assert nx.node_boundary(null, [1, 2, 3]) == set() + assert nx.node_boundary(null, [1, 2, 3], [4, 5, 6]) == set() + assert nx.node_boundary(null, [1, 2, 3], [3, 4, 5]) == set() + + def test_path_graph(self): + P10 = cnlti(nx.path_graph(10), first_label=1) + assert nx.node_boundary(P10, []) == set() + assert nx.node_boundary(P10, [], []) == set() + assert nx.node_boundary(P10, [1, 2, 3]) == {4} + assert nx.node_boundary(P10, [4, 5, 6]) == {3, 7} + assert nx.node_boundary(P10, [3, 4, 5, 6, 7]) == {2, 8} + assert nx.node_boundary(P10, [8, 9, 10]) == {7} + assert nx.node_boundary(P10, [4, 5, 6], [9, 10]) == set() + + def test_complete_graph(self): + K10 = cnlti(nx.complete_graph(10), first_label=1) + assert nx.node_boundary(K10, []) == set() + assert nx.node_boundary(K10, [], []) == set() + assert nx.node_boundary(K10, [1, 2, 3]) == {4, 5, 6, 7, 8, 9, 10} + assert nx.node_boundary(K10, [4, 5, 6]) == {1, 2, 3, 7, 8, 9, 10} + assert nx.node_boundary(K10, [3, 4, 5, 6, 7]) == {1, 2, 8, 9, 10} + assert nx.node_boundary(K10, [4, 5, 6], []) == set() + assert nx.node_boundary(K10, K10) == set() + assert nx.node_boundary(K10, [1, 2, 3], [3, 4, 5]) == {4, 5} + + def test_petersen(self): + """Check boundaries in the petersen graph + + cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0 +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Python Software Foundation License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development +Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues +Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md +Project-URL: Documentation, https://typing-extensions.readthedocs.io/ +Project-URL: Home, https://github.com/python/typing_extensions +Project-URL: Q & A, https://github.com/python/typing/discussions +Project-URL: Repository, https://github.com/python/typing_extensions + +# Typing Extensions + +[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing) + +[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) – +[PyPI](https://pypi.org/project/typing-extensions/) + +## Overview + +The `typing_extensions` module serves two related purposes: + +- Enable use of new type system features on older Python versions. For example, + `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows + users on previous Python versions to use it too. +- Enable experimentation with new type system PEPs before they are accepted and + added to the `typing` module. + +`typing_extensions` is treated specially by static type checkers such as +mypy and pyright. Objects defined in `typing_extensions` are treated the same +way as equivalent forms in `typing`. + +`typing_extensions` uses +[Semantic Versioning](https://semver.org/). The +major version will be incremented only for backwards-incompatible changes. +Therefore, it's safe to depend +on `typing_extensions` like this: `typing_extensions >=x.y, <(x+1)`, +where `x.y` is the first version that includes all features you need. + +## Included items + +See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a +complete listing of module contents. + +## Contributing + +See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md) +for how to contribute to `typing_extensions`. + diff --git a/shared/package-files/79/79be71160f381d1ad11e7d6e6d4ee5ceed80b679929ddc4e968de516939e453c/blob b/shared/package-files/79/79be71160f381d1ad11e7d6e6d4ee5ceed80b679929ddc4e968de516939e453c/blob new file mode 100644 index 0000000000000000000000000000000000000000..a932f8ef0efeb98ec395ba59ced02b0c00b726fc --- /dev/null +++ b/shared/package-files/79/79be71160f381d1ad11e7d6e6d4ee5ceed80b679929ddc4e968de516939e453c/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor bitwise_left_shift(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_left_shift_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_left_shift_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & bitwise_left_shift_(at::Tensor & self, const at::Tensor & other); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/79/79bedf5ca0d141caf4a1cd0fe3daa9c44d7f86c9256af5e845211423cc0f0f4d/blob b/shared/package-files/79/79bedf5ca0d141caf4a1cd0fe3daa9c44d7f86c9256af5e845211423cc0f0f4d/blob new file mode 100644 index 0000000000000000000000000000000000000000..6bfa4b9f85bd6fc8bb8524926210b1e931e2bd50 --- /dev/null +++ b/shared/package-files/79/79bedf5ca0d141caf4a1cd0fe3daa9c44d7f86c9256af5e845211423cc0f0f4d/blob @@ -0,0 +1,121 @@ +from typing import Any + +import torch +import enum + +from torch._C import _from_dlpack +from torch._C import _to_dlpack as to_dlpack + + +class DLDeviceType(enum.IntEnum): + # Enums as in DLPack specification (aten/src/ATen/dlpack.h) + kDLCPU = 1, + kDLGPU = 2, + kDLCPUPinned = 3, + kDLOpenCL = 4, + kDLVulkan = 7, + kDLMetal = 8, + kDLVPI = 9, + kDLROCM = 10, + kDLExtDev = 12, + kDLOneAPI = 14, + + +torch._C._add_docstr(to_dlpack, r"""to_dlpack(tensor) -> PyCapsule + +Returns an opaque object (a "DLPack capsule") representing the tensor. + +.. note:: + ``to_dlpack`` is a legacy DLPack interface. The capsule it returns + cannot be used for anything in Python other than use it as input to + ``from_dlpack``. The more idiomatic use of DLPack is to call + ``from_dlpack`` directly on the tensor object - this works when that + object has a ``__dlpack__`` method, which PyTorch and most other + libraries indeed have now. + +.. warning:: + Only call ``from_dlpack`` once per capsule produced with ``to_dlpack``. + Behavior when a capsule is consumed multiple times is undefined. + +Args: + tensor: a tensor to be exported + +The DLPack capsule shares the tensor's memory. +""") + + +# TODO: add a typing.Protocol to be able to tell Mypy that only objects with +# __dlpack__ and __dlpack_device__ methods are accepted. +def from_dlpack(ext_tensor: Any) -> 'torch.Tensor': + """from_dlpack(ext_tensor) -> Tensor + + Converts a tensor from an external library into a ``torch.Tensor``. + + The returned PyTorch tensor will share the memory with the input tensor + (which may have come from another library). Note that in-place operations + will therefore also affect the data of the input tensor. This may lead to + unexpected issues (e.g., other libraries may have read-only flags or + immutable data structures), so the user should only do this if they know + for sure that this is fine. + + Args: + ext_tensor (object with ``__dlpack__`` attribute, or a DLPack capsule): + The tensor or DLPack capsule to convert. + + If ``ext_tensor`` is a tensor (or ndarray) object, it must support + the ``__dlpack__`` protocol (i.e., have a ``ext_tensor.__dlpack__`` + method). Otherwise ``ext_tensor`` may be a DLPack capsule, which is + an opaque ``PyCapsule`` instance, typically produced by a + ``to_dlpack`` function or method. + + Examples:: + + >>> import torch.utils.dlpack + >>> t = torch.arange(4) + + # Convert a tensor directly (supported in PyTorch >= 1.10) + >>> t2 = torch.from_dlpack(t) + >>> t2[:2] = -1 # show that memory is shared + >>> t2 + tensor([-1, -1, 2, 3]) + >>> t + tensor([-1, -1, 2, 3]) + + # The old-style DLPack usage, with an intermediate capsule object + >>> capsule = torch.utils.dlpack.to_dlpack(t) + >>> capsule + + >>> t3 = torch.from_dlpack(capsule) + >>> t3 + tensor([-1, -1, 2, 3]) + >>> t3[0] = -9 # now we're sharing memory between 3 tensors + >>> t3 + tensor([-9, -1, 2, 3]) + >>> t2 + tensor([-9, -1, 2, 3]) + >>> t + tensor([-9, -1, 2, 3]) + + """ + if hasattr(ext_tensor, '__dlpack__'): + device = ext_tensor.__dlpack_device__() + # device is either CUDA or ROCm, we need to pass the current + # stream + if device[0] in (DLDeviceType.kDLGPU, DLDeviceType.kDLROCM): + stream = torch.cuda.current_stream(f'cuda:{device[1]}') + # cuda_stream is the pointer to the stream and it is a public + # attribute, but it is not documented + # The array API specify that the default legacy stream must be passed + # with a value of 1 for CUDA + # https://data-apis.org/array-api/latest/API_specification/array_object.html?dlpack-self-stream-none#dlpack-self-stream-none + is_cuda = device[0] == DLDeviceType.kDLGPU + # Since pytorch is not using PTDS by default, lets directly pass + # the legacy stream + stream_ptr = 1 if is_cuda and stream.cuda_stream == 0 else stream.cuda_stream + dlpack = ext_tensor.__dlpack__(stream=stream_ptr) + else: + dlpack = ext_tensor.__dlpack__() + else: + # Old versions just call the converter + dlpack = ext_tensor + return _from_dlpack(dlpack) diff --git a/shared/package-files/79/79c167022321ce4edfc31007bef5576a87a94190e386f5b8535e62c672f4a113/blob b/shared/package-files/79/79c167022321ce4edfc31007bef5576a87a94190e386f5b8535e62c672f4a113/blob new file mode 100644 index 0000000000000000000000000000000000000000..a069591946a845e3456d4499ca94845025e165c8 --- /dev/null +++ b/shared/package-files/79/79c167022321ce4edfc31007bef5576a87a94190e386f5b8535e62c672f4a113/blob @@ -0,0 +1,212 @@ +""" +Tests for practical lowering specific errors. +""" + +import numpy as np +from numba import njit +from numba.core import types, ir +from numba.core.compiler import CompilerBase, DefaultPassBuilder +from numba.core.typed_passes import NopythonTypeInference +from numba.core.compiler_machinery import register_pass, FunctionPass + +from numba.tests.support import MemoryLeakMixin, TestCase + + +def issue7507_lround(a): + """Dummy function used in test""" + pass + + +class TestLowering(MemoryLeakMixin, TestCase): + def test_issue4156_loop_vars_leak(self): + """Test issues with zero-filling of refct'ed variables inside loops. + + Before the fix, the in-loop variables are always zero-filled at their + definition location. As a result, their state from the previous + iteration is erased. No decref is applied. To fix this, the + zero-filling must only happen once after the alloca at the function + entry block. The loop variables are technically defined once per + function (one alloca per definition per function), but semantically + defined once per assignment. Semantically, their lifetime stop only + when the variable is re-assigned or when the function ends. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for n in range(N): + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant1(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding an outer loop. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for x in range(N): + for y in range(N): + n = x + y + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant2(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding deeper outer loop. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for z in range(N): + for x in range(N): + for y in range(N): + n = x + y + z + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant3(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding inner loop around allocation + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for z in range(N): + for x in range(N): + n = x + z + if n >= 0: + for y in range(N): + # `vec` would leak without the fix. + vec = np.ones(y) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant4(self): + """Variant of test_issue4156_loop_vars_leak. + + Interleaves loops and allocations + """ + @njit + def udt(N): + sum_vec = 0 + + for n in range(N): + vec = np.zeros(7) + for n in range(N): + z = np.zeros(7) + sum_vec += vec[0] + z[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue_with_literal_in_static_getitem(self): + """Test an issue with literal type used as index of static_getitem + """ + + @register_pass(mutates_CFG=False, analysis_only=False) + class ForceStaticGetitemLiteral(FunctionPass): + + _name = "force_static_getitem_literal" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + repl = {} + # Force the static_getitem to have a literal type as + # index to replicate the problem. + for inst, sig in state.calltypes.items(): + if (isinstance(inst, ir.Expr) and + inst.op == 'static_getitem'): + [obj, idx] = sig.args + new_sig = sig.replace(args=(obj, + types.literal(inst.index))) + repl[inst] = new_sig + state.calltypes.update(repl) + return True + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(ForceStaticGetitemLiteral, + NopythonTypeInference) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomPipeline) + def foo(arr): + return arr[4] # force static_getitem + + arr = np.arange(10) + got = foo(arr) + expect = foo.py_func(arr) + self.assertEqual(got, expect) + + def test_issue7507(self): + """ + Test a problem with BaseContext.get_function() because of changes + related to the new style error handling. + """ + from numba.core.typing.templates import AbstractTemplate, infer_global + from numba.core.imputils import lower_builtin + + @infer_global(issue7507_lround) + class lroundTemplate(AbstractTemplate): + key = issue7507_lround + + def generic(self, args, kws): + signature = types.int64(types.float64) + + # insert a new builtin during the compilation process + @lower_builtin(issue7507_lround, types.float64) + def codegen(context, builder, sig, args): + # Simply truncate with the cast to integer. + return context.cast(builder, args[0], sig.args[0], + sig.return_type) + + return signature + + @njit('int64(float64)') + def foo(a): + return issue7507_lround(a) + + self.assertEqual(foo(3.4), 3) diff --git a/shared/package-files/79/79c35e4ab55dda648fb1d22a9b794cf75d5be263f02c8564a33dcc9c91591378/blob b/shared/package-files/79/79c35e4ab55dda648fb1d22a9b794cf75d5be263f02c8564a33dcc9c91591378/blob new file mode 100644 index 0000000000000000000000000000000000000000..927a9f4961f6ff7ae51f74aceb0cb36dc6754c21 --- /dev/null +++ b/shared/package-files/79/79c35e4ab55dda648fb1d22a9b794cf75d5be263f02c8564a33dcc9c91591378/blob @@ -0,0 +1,429 @@ +"""Tests formatting as writer-agnostic ExcelCells + +ExcelFormatter is tested implicitly in pandas/tests/io/excel +""" +import string + +import pytest + +from pandas.errors import CSSWarning + +import pandas._testing as tm + +from pandas.io.formats.excel import ( + CssExcelCell, + CSSToExcelConverter, +) + + +@pytest.mark.parametrize( + "css,expected", + [ + # FONT + # - name + ("font-family: foo,bar", {"font": {"name": "foo"}}), + ('font-family: "foo bar",baz', {"font": {"name": "foo bar"}}), + ("font-family: foo,\nbar", {"font": {"name": "foo"}}), + ("font-family: foo, bar, baz", {"font": {"name": "foo"}}), + ("font-family: bar, foo", {"font": {"name": "bar"}}), + ("font-family: 'foo bar', baz", {"font": {"name": "foo bar"}}), + ("font-family: 'foo \\'bar', baz", {"font": {"name": "foo 'bar"}}), + ('font-family: "foo \\"bar", baz', {"font": {"name": 'foo "bar'}}), + ('font-family: "foo ,bar", baz', {"font": {"name": "foo ,bar"}}), + # - family + ("font-family: serif", {"font": {"name": "serif", "family": 1}}), + ("font-family: Serif", {"font": {"name": "serif", "family": 1}}), + ("font-family: roman, serif", {"font": {"name": "roman", "family": 1}}), + ("font-family: roman, sans-serif", {"font": {"name": "roman", "family": 2}}), + ("font-family: roman, sans serif", {"font": {"name": "roman"}}), + ("font-family: roman, sansserif", {"font": {"name": "roman"}}), + ("font-family: roman, cursive", {"font": {"name": "roman", "family": 4}}), + ("font-family: roman, fantasy", {"font": {"name": "roman", "family": 5}}), + # - size + ("font-size: 1em", {"font": {"size": 12}}), + ("font-size: xx-small", {"font": {"size": 6}}), + ("font-size: x-small", {"font": {"size": 7.5}}), + ("font-size: small", {"font": {"size": 9.6}}), + ("font-size: medium", {"font": {"size": 12}}), + ("font-size: large", {"font": {"size": 13.5}}), + ("font-size: x-large", {"font": {"size": 18}}), + ("font-size: xx-large", {"font": {"size": 24}}), + ("font-size: 50%", {"font": {"size": 6}}), + # - bold + ("font-weight: 100", {"font": {"bold": False}}), + ("font-weight: 200", {"font": {"bold": False}}), + ("font-weight: 300", {"font": {"bold": False}}), + ("font-weight: 400", {"font": {"bold": False}}), + ("font-weight: normal", {"font": {"bold": False}}), + ("font-weight: lighter", {"font": {"bold": False}}), + ("font-weight: bold", {"font": {"bold": True}}), + ("font-weight: bolder", {"font": {"bold": True}}), + ("font-weight: 700", {"font": {"bold": True}}), + ("font-weight: 800", {"font": {"bold": True}}), + ("font-weight: 900", {"font": {"bold": True}}), + # - italic + ("font-style: italic", {"font": {"italic": True}}), + ("font-style: oblique", {"font": {"italic": True}}), + # - underline + ("text-decoration: underline", {"font": {"underline": "single"}}), + ("text-decoration: overline", {}), + ("text-decoration: none", {}), + # - strike + ("text-decoration: line-through", {"font": {"strike": True}}), + ( + "text-decoration: underline line-through", + {"font": {"strike": True, "underline": "single"}}, + ), + ( + "text-decoration: underline; text-decoration: line-through", + {"font": {"strike": True}}, + ), + # - color + ("color: red", {"font": {"color": "FF0000"}}), + ("color: #ff0000", {"font": {"color": "FF0000"}}), + ("color: #f0a", {"font": {"color": "FF00AA"}}), + # - shadow + ("text-shadow: none", {"font": {"shadow": False}}), + ("text-shadow: 0px -0em 0px #CCC", {"font": {"shadow": False}}), + ("text-shadow: 0px -0em 0px #999", {"font": {"shadow": False}}), + ("text-shadow: 0px -0em 0px", {"font": {"shadow": False}}), + ("text-shadow: 2px -0em 0px #CCC", {"font": {"shadow": True}}), + ("text-shadow: 0px -2em 0px #CCC", {"font": {"shadow": True}}), + ("text-shadow: 0px -0em 2px #CCC", {"font": {"shadow": True}}), + ("text-shadow: 0px -0em 2px", {"font": {"shadow": True}}), + ("text-shadow: 0px -2em", {"font": {"shadow": True}}), + # FILL + # - color, fillType + ( + "background-color: red", + {"fill": {"fgColor": "FF0000", "patternType": "solid"}}, + ), + ( + "background-color: #ff0000", + {"fill": {"fgColor": "FF0000", "patternType": "solid"}}, + ), + ( + "background-color: #f0a", + {"fill": {"fgColor": "FF00AA", "patternType": "solid"}}, + ), + # BORDER + # - style + ( + "border-style: solid", + { + "border": { + "top": {"style": "medium"}, + "bottom": {"style": "medium"}, + "left": {"style": "medium"}, + "right": {"style": "medium"}, + } + }, + ), + ( + "border-style: solid; border-width: thin", + { + "border": { + "top": {"style": "thin"}, + "bottom": {"style": "thin"}, + "left": {"style": "thin"}, + "right": {"style": "thin"}, + } + }, + ), + ( + "border-top-style: solid; border-top-width: thin", + {"border": {"top": {"style": "thin"}}}, + ), + ( + "border-top-style: solid; border-top-width: 1pt", + {"border": {"top": {"style": "thin"}}}, + ), + ("border-top-style: solid", {"border": {"top": {"style": "medium"}}}), + ( + "border-top-style: solid; border-top-width: medium", + {"border": {"top": {"style": "medium"}}}, + ), + ( + "border-top-style: solid; border-top-width: 2pt", + {"border": {"top": {"style": "medium"}}}, + ), + ( + "border-top-style: solid; border-top-width: thick", + {"border": {"top": {"style": "thick"}}}, + ), + ( + "border-top-style: solid; border-top-width: 4pt", + {"border": {"top": {"style": "thick"}}}, + ), + ( + "border-top-style: dotted", + {"border": {"top": {"style": "mediumDashDotDot"}}}, + ), + ( + "border-top-style: dotted; border-top-width: thin", + {"border": {"top": {"style": "dotted"}}}, + ), + ("border-top-style: dashed", {"border": {"top": {"style": "mediumDashed"}}}), + ( + "border-top-style: dashed; border-top-width: thin", + {"border": {"top": {"style": "dashed"}}}, + ), + ("border-top-style: double", {"border": {"top": {"style": "double"}}}), + # - color + ( + "border-style: solid; border-color: #0000ff", + { + "border": { + "top": {"style": "medium", "color": "0000FF"}, + "right": {"style": "medium", "color": "0000FF"}, + "bottom": {"style": "medium", "color": "0000FF"}, + "left": {"style": "medium", "color": "0000FF"}, + } + }, + ), + ( + "border-top-style: double; border-top-color: blue", + {"border": {"top": {"style": "double", "color": "0000FF"}}}, + ), + ( + "border-top-style: solid; border-top-color: #06c", + {"border": {"top": {"style": "medium", "color": "0066CC"}}}, + ), + ( + "border-top-color: blue", + {"border": {"top": {"color": "0000FF", "style": "none"}}}, + ), + # ALIGNMENT + # - horizontal + ("text-align: center", {"alignment": {"horizontal": "center"}}), + ("text-align: left", {"alignment": {"horizontal": "left"}}), + ("text-align: right", {"alignment": {"horizontal": "right"}}), + ("text-align: justify", {"alignment": {"horizontal": "justify"}}), + # - vertical + ("vertical-align: top", {"alignment": {"vertical": "top"}}), + ("vertical-align: text-top", {"alignment": {"vertical": "top"}}), + ("vertical-align: middle", {"alignment": {"vertical": "center"}}), + ("vertical-align: bottom", {"alignment": {"vertical": "bottom"}}), + ("vertical-align: text-bottom", {"alignment": {"vertical": "bottom"}}), + # - wrap_text + ("white-space: nowrap", {"alignment": {"wrap_text": False}}), + ("white-space: pre", {"alignment": {"wrap_text": False}}), + ("white-space: pre-line", {"alignment": {"wrap_text": False}}), + ("white-space: normal", {"alignment": {"wrap_text": True}}), + # NUMBER FORMAT + ("number-format: 0%", {"number_format": {"format_code": "0%"}}), + ( + "number-format: 0§[Red](0)§-§@;", + {"number_format": {"format_code": "0;[red](0);-;@"}}, # GH 46152 + ), + ], +) +def test_css_to_excel(css, expected): + convert = CSSToExcelConverter() + assert expected == convert(css) + + +def test_css_to_excel_multiple(): + convert = CSSToExcelConverter() + actual = convert( + """ + font-weight: bold; + text-decoration: underline; + color: red; + border-width: thin; + text-align: center; + vertical-align: top; + unused: something; + """ + ) + assert { + "font": {"bold": True, "underline": "single", "color": "FF0000"}, + "border": { + "top": {"style": "thin"}, + "right": {"style": "thin"}, + "bottom": {"style": "thin"}, + "left": {"style": "thin"}, + }, + "alignment": {"horizontal": "center", "vertical": "top"}, + } == actual + + +@pytest.mark.parametrize( + "css,inherited,expected", + [ + ("font-weight: bold", "", {"font": {"bold": True}}), + ("", "font-weight: bold", {"font": {"bold": True}}), + ( + "font-weight: bold", + "font-style: italic", + {"font": {"bold": True, "italic": True}}, + ), + ("font-style: normal", "font-style: italic", {"font": {"italic": False}}), + ("font-style: inherit", "", {}), + ( + "font-style: normal; font-style: inherit", + "font-style: italic", + {"font": {"italic": True}}, + ), + ], +) +def test_css_to_excel_inherited(css, inherited, expected): + convert = CSSToExcelConverter(inherited) + assert expected == convert(css) + + +@pytest.mark.parametrize( + "input_color,output_color", + ( + list(CSSToExcelConverter.NAMED_COLORS.items()) + + [("#" + rgb, rgb) for rgb in CSSToExcelConverter.NAMED_COLORS.values()] + + [("#F0F", "FF00FF"), ("#ABC", "AABBCC")] + ), +) +def test_css_to_excel_good_colors(input_color, output_color): + # see gh-18392 + css = ( + f"border-top-color: {input_color}; " + f"border-right-color: {input_color}; " + f"border-bottom-color: {input_color}; " + f"border-left-color: {input_color}; " + f"background-color: {input_color}; " + f"color: {input_color}" + ) + + expected = {} + + expected["fill"] = {"patternType": "solid", "fgColor": output_color} + + expected["font"] = {"color": output_color} + + expected["border"] = { + k: {"color": output_color, "style": "none"} + for k in ("top", "right", "bottom", "left") + } + + with tm.assert_produces_warning(None): + convert = CSSToExcelConverter() + assert expected == convert(css) + + +@pytest.mark.parametrize("input_color", [None, "not-a-color"]) +def test_css_to_excel_bad_colors(input_color): + # see gh-18392 + css = ( + f"border-top-color: {input_color}; " + f"border-right-color: {input_color}; " + f"border-bottom-color: {input_color}; " + f"border-left-color: {input_color}; " + f"background-color: {input_color}; " + f"color: {input_color}" + ) + + expected = {} + + if input_color is not None: + expected["fill"] = {"patternType": "solid"} + + with tm.assert_produces_warning(CSSWarning): + convert = CSSToExcelConverter() + assert expected == convert(css) + + +def tests_css_named_colors_valid(): + upper_hexs = set(map(str.upper, string.hexdigits)) + for color in CSSToExcelConverter.NAMED_COLORS.values(): + assert len(color) == 6 and all(c in upper_hexs for c in color) + + +def test_css_named_colors_from_mpl_present(): + mpl_colors = pytest.importorskip("matplotlib.colors") + + pd_colors = CSSToExcelConverter.NAMED_COLORS + for name, color in mpl_colors.CSS4_COLORS.items(): + assert name in pd_colors and pd_colors[name] == color[1:] + + +@pytest.mark.parametrize( + "styles,expected", + [ + ([("color", "green"), ("color", "red")], "color: red;"), + ([("font-weight", "bold"), ("font-weight", "normal")], "font-weight: normal;"), + ([("text-align", "center"), ("TEXT-ALIGN", "right")], "text-align: right;"), + ], +) +def test_css_excel_cell_precedence(styles, expected): + """It applies favors latter declarations over former declarations""" + # See GH 47371 + converter = CSSToExcelConverter() + converter._call_cached.cache_clear() + css_styles = {(0, 0): styles} + cell = CssExcelCell( + row=0, + col=0, + val="", + style=None, + css_styles=css_styles, + css_row=0, + css_col=0, + css_converter=converter, + ) + converter._call_cached.cache_clear() + + assert cell.style == converter(expected) + + +@pytest.mark.parametrize( + "styles,cache_hits,cache_misses", + [ + ([[("color", "green"), ("color", "red"), ("color", "green")]], 0, 1), + ( + [ + [("font-weight", "bold")], + [("font-weight", "normal"), ("font-weight", "bold")], + ], + 1, + 1, + ), + ([[("text-align", "center")], [("TEXT-ALIGN", "center")]], 1, 1), + ( + [ + [("font-weight", "bold"), ("text-align", "center")], + [("font-weight", "bold"), ("text-align", "left")], + ], + 0, + 2, + ), + ( + [ + [("font-weight", "bold"), ("text-align", "center")], + [("font-weight", "bold"), ("text-align", "left")], + [("font-weight", "bold"), ("text-align", "center")], + ], + 1, + 2, + ), + ], +) +def test_css_excel_cell_cache(styles, cache_hits, cache_misses): + """It caches unique cell styles""" + # See GH 47371 + converter = CSSToExcelConverter() + converter._call_cached.cache_clear() + + css_styles = {(0, i): _style for i, _style in enumerate(styles)} + for css_row, css_col in css_styles: + CssExcelCell( + row=0, + col=0, + val="", + style=None, + css_styles=css_styles, + css_row=css_row, + css_col=css_col, + css_converter=converter, + ) + cache_info = converter._call_cached.cache_info() + converter._call_cached.cache_clear() + + assert cache_info.hits == cache_hits + assert cache_info.misses == cache_misses diff --git a/shared/package-files/79/79c3dd27e08cf076da699a0651fc1ca0eba8d1e233eda12afb1f302f43d959b1/blob b/shared/package-files/79/79c3dd27e08cf076da699a0651fc1ca0eba8d1e233eda12afb1f302f43d959b1/blob new file mode 100644 index 0000000000000000000000000000000000000000..3c21cd0d5ca648dcf0f1ac412dd232221c031c6f --- /dev/null +++ b/shared/package-files/79/79c3dd27e08cf076da699a0651fc1ca0eba8d1e233eda12afb1f302f43d959b1/blob @@ -0,0 +1,69 @@ +import numpy as np +import pytest + +from pandas import Series +import pandas._testing as tm + + +def test_mask(): + # compare with tested results in test_where + s = Series(np.random.default_rng(2).standard_normal(5)) + cond = s > 0 + + rs = s.where(~cond, np.nan) + tm.assert_series_equal(rs, s.mask(cond)) + + rs = s.where(~cond) + rs2 = s.mask(cond) + tm.assert_series_equal(rs, rs2) + + rs = s.where(~cond, -s) + rs2 = s.mask(cond, -s) + tm.assert_series_equal(rs, rs2) + + cond = Series([True, False, False, True, False], index=s.index) + s2 = -(s.abs()) + rs = s2.where(~cond[:3]) + rs2 = s2.mask(cond[:3]) + tm.assert_series_equal(rs, rs2) + + rs = s2.where(~cond[:3], -s2) + rs2 = s2.mask(cond[:3], -s2) + tm.assert_series_equal(rs, rs2) + + msg = "Array conditional must be same shape as self" + with pytest.raises(ValueError, match=msg): + s.mask(1) + with pytest.raises(ValueError, match=msg): + s.mask(cond[:3].values, -s) + + +def test_mask_casts(): + # dtype changes + ser = Series([1, 2, 3, 4]) + result = ser.mask(ser > 2, np.nan) + expected = Series([1, 2, np.nan, np.nan]) + tm.assert_series_equal(result, expected) + + +def test_mask_casts2(): + # see gh-21891 + ser = Series([1, 2]) + res = ser.mask([True, False]) + + exp = Series([np.nan, 2]) + tm.assert_series_equal(res, exp) + + +def test_mask_inplace(): + s = Series(np.random.default_rng(2).standard_normal(5)) + cond = s > 0 + + rs = s.copy() + rs.mask(cond, inplace=True) + tm.assert_series_equal(rs.dropna(), s[~cond]) + tm.assert_series_equal(rs, s.mask(cond)) + + rs = s.copy() + rs.mask(cond, -s, inplace=True) + tm.assert_series_equal(rs, s.mask(cond, -s)) diff --git a/shared/package-files/79/79c6091294f409737edafb5a65f1820a10fea2221a27244322c4c713c7941b93/blob b/shared/package-files/79/79c6091294f409737edafb5a65f1820a10fea2221a27244322c4c713c7941b93/blob new file mode 100644 index 0000000000000000000000000000000000000000..d35f8da68b34d3a587f3a99326770d8550a2135c --- /dev/null +++ b/shared/package-files/79/79c6091294f409737edafb5a65f1820a10fea2221a27244322c4c713c7941b93/blob @@ -0,0 +1,11 @@ +# Public Cython API declarations +# +# See doc/source/dev/contributor/public_cython_api.rst for guidelines + + +# The following cimport statement provides legacy ABI +# support. Changing it causes an ABI forward-compatibility break +# (gh-11793), so we currently leave it as is (no further cimport +# statements should be used in this file). +from scipy.optimize.cython_optimize._zeros cimport ( + brentq, brenth, ridder, bisect, zeros_full_output) diff --git a/shared/package-files/79/79c7377839f9a9bd248e84d1ff96bdeb005eccda5674357f16e780224972f432/blob b/shared/package-files/79/79c7377839f9a9bd248e84d1ff96bdeb005eccda5674357f16e780224972f432/blob new file mode 100644 index 0000000000000000000000000000000000000000..c345b4a6bbc98cbece296a63424140b648e79373 --- /dev/null +++ b/shared/package-files/79/79c7377839f9a9bd248e84d1ff96bdeb005eccda5674357f16e780224972f432/blob @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API masked_fill__Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_fill_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_fill_.Scalar(Tensor(a!) self, Tensor mask, Scalar value) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); +}; + +struct TORCH_API masked_fill_Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value); +}; + +struct TORCH_API masked_fill__Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_fill_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_fill_.Tensor(Tensor(a!) self, Tensor mask, Tensor value) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); +}; + +struct TORCH_API masked_fill_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value); +}; + +struct TORCH_API masked_fill_Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_fill.Scalar_out(Tensor self, Tensor mask, Scalar value, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, const at::Scalar & value, at::Tensor & out); +}; + +struct TORCH_API masked_fill_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::masked_fill") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "masked_fill.Tensor_out(Tensor self, Tensor mask, Tensor value, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, const at::Tensor & value, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/79/79c7824b8edb39ac2091674b50c20fb7a5d7fc7f84b564b6b7e7aecf906091b8/blob b/shared/package-files/79/79c7824b8edb39ac2091674b50c20fb7a5d7fc7f84b564b6b7e7aecf906091b8/blob new file mode 100644 index 0000000000000000000000000000000000000000..ff2a1a40bf947005692ccaf2b95977e57a1747b6 --- /dev/null +++ b/shared/package-files/79/79c7824b8edb39ac2091674b50c20fb7a5d7fc7f84b564b6b7e7aecf906091b8/blob @@ -0,0 +1,83 @@ +from collections.abc import Callable, Iterator, MutableMapping +from typing import Literal, TypeVar, overload + +import matplotlib.patches as mpatches +from matplotlib.axes import Axes +from matplotlib.axis import Axis +from matplotlib.path import Path +from matplotlib.transforms import Transform +from matplotlib.typing import ColorType + +class Spine(mpatches.Patch): + axes: Axes + spine_type: str + axis: Axis | None + def __init__(self, axes: Axes, spine_type: str, path: Path, **kwargs) -> None: ... + def set_patch_arc( + self, center: tuple[float, float], radius: float, theta1: float, theta2: float + ) -> None: ... + def set_patch_circle(self, center: tuple[float, float], radius: float) -> None: ... + def set_patch_line(self) -> None: ... + def get_patch_transform(self) -> Transform: ... + def get_path(self) -> Path: ... + def register_axis(self, axis: Axis) -> None: ... + def clear(self) -> None: ... + def set_position( + self, + position: Literal["center", "zero"] + | tuple[Literal["outward", "axes", "data"], float], + ) -> None: ... + def get_position( + self, + ) -> Literal["center", "zero"] | tuple[ + Literal["outward", "axes", "data"], float + ]: ... + def get_spine_transform(self) -> Transform: ... + def set_bounds(self, low: float | None = ..., high: float | None = ...) -> None: ... + def get_bounds(self) -> tuple[float, float]: ... + + _T = TypeVar("_T", bound=Spine) + @classmethod + def linear_spine( + cls: type[_T], + axes: Axes, + spine_type: Literal["left", "right", "bottom", "top"], + **kwargs + ) -> _T: ... + @classmethod + def arc_spine( + cls: type[_T], + axes: Axes, + spine_type: Literal["left", "right", "bottom", "top"], + center: tuple[float, float], + radius: float, + theta1: float, + theta2: float, + **kwargs + ) -> _T: ... + @classmethod + def circular_spine( + cls: type[_T], axes: Axes, center: tuple[float, float], radius: float, **kwargs + ) -> _T: ... + def set_color(self, c: ColorType | None) -> None: ... + +class SpinesProxy: + def __init__(self, spine_dict: dict[str, Spine]) -> None: ... + def __getattr__(self, name: str) -> Callable[..., None]: ... + def __dir__(self) -> list[str]: ... + +class Spines(MutableMapping[str, Spine]): + def __init__(self, **kwargs: Spine) -> None: ... + @classmethod + def from_dict(cls, d: dict[str, Spine]) -> Spines: ... + def __getattr__(self, name: str) -> Spine: ... + @overload + def __getitem__(self, key: str) -> Spine: ... + @overload + def __getitem__(self, key: list[str]) -> SpinesProxy: ... + @overload + def __getitem__(self, key: slice) -> SpinesProxy: ... + def __setitem__(self, key: str, value: Spine) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... diff --git a/shared/package-files/79/79c88b21908b3259812811795dc26a5516177f6677335de4437749ffea24e378/blob b/shared/package-files/79/79c88b21908b3259812811795dc26a5516177f6677335de4437749ffea24e378/blob new file mode 100644 index 0000000000000000000000000000000000000000..68c89874c97f78de2d3d97184f5db94177112a4e --- /dev/null +++ b/shared/package-files/79/79c88b21908b3259812811795dc26a5516177f6677335de4437749ffea24e378/blob @@ -0,0 +1,945 @@ +from __future__ import annotations + +from .assumptions import StdFactKB, _assume_defined +from .basic import Basic, Atom +from .cache import cacheit +from .containers import Tuple +from .expr import Expr, AtomicExpr +from .function import AppliedUndef, FunctionClass +from .kind import NumberKind, UndefinedKind +from .logic import fuzzy_bool +from .singleton import S +from .sorting import ordered +from .sympify import sympify +from sympy.logic.boolalg import Boolean +from sympy.utilities.iterables import sift, is_sequence +from sympy.utilities.misc import filldedent + +import string +import re as _re +import random +from itertools import product +from typing import Any + + +class Str(Atom): + """ + Represents string in SymPy. + + Explanation + =========== + + Previously, ``Symbol`` was used where string is needed in ``args`` of SymPy + objects, e.g. denoting the name of the instance. However, since ``Symbol`` + represents mathematical scalar, this class should be used instead. + + """ + __slots__ = ('name',) + + def __new__(cls, name, **kwargs): + if not isinstance(name, str): + raise TypeError("name should be a string, not %s" % repr(type(name))) + obj = Expr.__new__(cls, **kwargs) + obj.name = name + return obj + + def __getnewargs__(self): + return (self.name,) + + def _hashable_content(self): + return (self.name,) + + +def _filter_assumptions(kwargs): + """Split the given dict into assumptions and non-assumptions. + Keys are taken as assumptions if they correspond to an + entry in ``_assume_defined``. + """ + assumptions, nonassumptions = map(dict, sift(kwargs.items(), + lambda i: i[0] in _assume_defined, + binary=True)) + Symbol._sanitize(assumptions) + return assumptions, nonassumptions + +def _symbol(s, matching_symbol=None, **assumptions): + """Return s if s is a Symbol, else if s is a string, return either + the matching_symbol if the names are the same or else a new symbol + with the same assumptions as the matching symbol (or the + assumptions as provided). + + Examples + ======== + + >>> from sympy import Symbol + >>> from sympy.core.symbol import _symbol + >>> _symbol('y') + y + >>> _.is_real is None + True + >>> _symbol('y', real=True).is_real + True + + >>> x = Symbol('x') + >>> _symbol(x, real=True) + x + >>> _.is_real is None # ignore attribute if s is a Symbol + True + + Below, the variable sym has the name 'foo': + + >>> sym = Symbol('foo', real=True) + + Since 'x' is not the same as sym's name, a new symbol is created: + + >>> _symbol('x', sym).name + 'x' + + It will acquire any assumptions give: + + >>> _symbol('x', sym, real=False).is_real + False + + Since 'foo' is the same as sym's name, sym is returned + + >>> _symbol('foo', sym) + foo + + Any assumptions given are ignored: + + >>> _symbol('foo', sym, real=False).is_real + True + + NB: the symbol here may not be the same as a symbol with the same + name defined elsewhere as a result of different assumptions. + + See Also + ======== + + sympy.core.symbol.Symbol + + """ + if isinstance(s, str): + if matching_symbol and matching_symbol.name == s: + return matching_symbol + return Symbol(s, **assumptions) + elif isinstance(s, Symbol): + return s + else: + raise ValueError('symbol must be string for symbol name or Symbol') + +def uniquely_named_symbol(xname, exprs=(), compare=str, modify=None, **assumptions): + """ + Return a symbol whose name is derivated from *xname* but is unique + from any other symbols in *exprs*. + + *xname* and symbol names in *exprs* are passed to *compare* to be + converted to comparable forms. If ``compare(xname)`` is not unique, + it is recursively passed to *modify* until unique name is acquired. + + Parameters + ========== + + xname : str or Symbol + Base name for the new symbol. + + exprs : Expr or iterable of Expr + Expressions whose symbols are compared to *xname*. + + compare : function + Unary function which transforms *xname* and symbol names from + *exprs* to comparable form. + + modify : function + Unary function which modifies the string. Default is appending + the number, or increasing the number if exists. + + Examples + ======== + + By default, a number is appended to *xname* to generate unique name. + If the number already exists, it is recursively increased. + + >>> from sympy.core.symbol import uniquely_named_symbol, Symbol + >>> uniquely_named_symbol('x', Symbol('x')) + x0 + >>> uniquely_named_symbol('x', (Symbol('x'), Symbol('x0'))) + x1 + >>> uniquely_named_symbol('x0', (Symbol('x1'), Symbol('x0'))) + x2 + + Name generation can be controlled by passing *modify* parameter. + + >>> from sympy.abc import x + >>> uniquely_named_symbol('x', x, modify=lambda s: 2*s) + xx + + """ + def numbered_string_incr(s, start=0): + if not s: + return str(start) + i = len(s) - 1 + while i != -1: + if not s[i].isdigit(): + break + i -= 1 + n = str(int(s[i + 1:] or start - 1) + 1) + return s[:i + 1] + n + + default = None + if is_sequence(xname): + xname, default = xname + x = compare(xname) + if not exprs: + return _symbol(x, default, **assumptions) + if not is_sequence(exprs): + exprs = [exprs] + names = set().union( + [i.name for e in exprs for i in e.atoms(Symbol)] + + [i.func.name for e in exprs for i in e.atoms(AppliedUndef)]) + if modify is None: + modify = numbered_string_incr + while any(x == compare(s) for s in names): + x = modify(x) + return _symbol(x, default, **assumptions) +_uniquely_named_symbol = uniquely_named_symbol + +class Symbol(AtomicExpr, Boolean): + """ + Assumptions: + commutative = True + + You can override the default assumptions in the constructor. + + Examples + ======== + + >>> from sympy import symbols + >>> A,B = symbols('A,B', commutative = False) + >>> bool(A*B != B*A) + True + >>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative + True + + """ + + is_comparable = False + + __slots__ = ('name', '_assumptions_orig', '_assumptions0') + + name: str + + is_Symbol = True + is_symbol = True + + @property + def kind(self): + if self.is_commutative: + return NumberKind + return UndefinedKind + + @property + def _diff_wrt(self): + """Allow derivatives wrt Symbols. + + Examples + ======== + + >>> from sympy import Symbol + >>> x = Symbol('x') + >>> x._diff_wrt + True + """ + return True + + @staticmethod + def _sanitize(assumptions, obj=None): + """Remove None, convert values to bool, check commutativity *in place*. + """ + + # be strict about commutativity: cannot be None + is_commutative = fuzzy_bool(assumptions.get('commutative', True)) + if is_commutative is None: + whose = '%s ' % obj.__name__ if obj else '' + raise ValueError( + '%scommutativity must be True or False.' % whose) + + # sanitize other assumptions so 1 -> True and 0 -> False + for key in list(assumptions.keys()): + v = assumptions[key] + if v is None: + assumptions.pop(key) + continue + assumptions[key] = bool(v) + + def _merge(self, assumptions): + base = self.assumptions0 + for k in set(assumptions) & set(base): + if assumptions[k] != base[k]: + raise ValueError(filldedent(''' + non-matching assumptions for %s: existing value + is %s and new value is %s''' % ( + k, base[k], assumptions[k]))) + base.update(assumptions) + return base + + def __new__(cls, name, **assumptions): + """Symbols are identified by name and assumptions:: + + >>> from sympy import Symbol + >>> Symbol("x") == Symbol("x") + True + >>> Symbol("x", real=True) == Symbol("x", real=False) + False + + """ + cls._sanitize(assumptions, cls) + return Symbol.__xnew_cached_(cls, name, **assumptions) + + @staticmethod + def __xnew__(cls, name, **assumptions): # never cached (e.g. dummy) + if not isinstance(name, str): + raise TypeError("name should be a string, not %s" % repr(type(name))) + + # This is retained purely so that srepr can include commutative=True if + # that was explicitly specified but not if it was not. Ideally srepr + # should not distinguish these cases because the symbols otherwise + # compare equal and are considered equivalent. + # + # See https://github.com/sympy/sympy/issues/8873 + # + assumptions_orig = assumptions.copy() + + # The only assumption that is assumed by default is comutative=True: + assumptions.setdefault('commutative', True) + + assumptions_kb = StdFactKB(assumptions) + assumptions0 = dict(assumptions_kb) + + obj = Expr.__new__(cls) + obj.name = name + + obj._assumptions = assumptions_kb + obj._assumptions_orig = assumptions_orig + obj._assumptions0 = assumptions0 + + # The three assumptions dicts are all a little different: + # + # >>> from sympy import Symbol + # >>> x = Symbol('x', finite=True) + # >>> x.is_positive # query an assumption + # >>> x._assumptions + # {'finite': True, 'infinite': False, 'commutative': True, 'positive': None} + # >>> x._assumptions0 + # {'finite': True, 'infinite': False, 'commutative': True} + # >>> x._assumptions_orig + # {'finite': True} + # + # Two symbols with the same name are equal if their _assumptions0 are + # the same. Arguably it should be _assumptions_orig that is being + # compared because that is more transparent to the user (it is + # what was passed to the constructor modulo changes made by _sanitize). + + return obj + + @staticmethod + @cacheit + def __xnew_cached_(cls, name, **assumptions): # symbols are always cached + return Symbol.__xnew__(cls, name, **assumptions) + + def __getnewargs_ex__(self): + return ((self.name,), self._assumptions_orig) + + # NOTE: __setstate__ is not needed for pickles created by __getnewargs_ex__ + # but was used before Symbol was changed to use __getnewargs_ex__ in v1.9. + # Pickles created in previous SymPy versions will still need __setstate__ + # so that they can be unpickled in SymPy > v1.9. + + def __setstate__(self, state): + for name, value in state.items(): + setattr(self, name, value) + + def _hashable_content(self): + # Note: user-specified assumptions not hashed, just derived ones + return (self.name,) + tuple(sorted(self.assumptions0.items())) + + def _eval_subs(self, old, new): + if old.is_Pow: + from sympy.core.power import Pow + return Pow(self, S.One, evaluate=False)._eval_subs(old, new) + + def _eval_refine(self, assumptions): + return self + + @property + def assumptions0(self): + return self._assumptions0.copy() + + @cacheit + def sort_key(self, order=None): + return self.class_key(), (1, (self.name,)), S.One.sort_key(), S.One + + def as_dummy(self): + # only put commutativity in explicitly if it is False + return Dummy(self.name) if self.is_commutative is not False \ + else Dummy(self.name, commutative=self.is_commutative) + + def as_real_imag(self, deep=True, **hints): + if hints.get('ignore') == self: + return None + else: + from sympy.functions.elementary.complexes import im, re + return (re(self), im(self)) + + def is_constant(self, *wrt, **flags): + if not wrt: + return False + return self not in wrt + + @property + def free_symbols(self): + return {self} + + binary_symbols = free_symbols # in this case, not always + + def as_set(self): + return S.UniversalSet + + +class Dummy(Symbol): + """Dummy symbols are each unique, even if they have the same name: + + Examples + ======== + + >>> from sympy import Dummy + >>> Dummy("x") == Dummy("x") + False + + If a name is not supplied then a string value of an internal count will be + used. This is useful when a temporary variable is needed and the name + of the variable used in the expression is not important. + + >>> Dummy() #doctest: +SKIP + _Dummy_10 + + """ + + # In the rare event that a Dummy object needs to be recreated, both the + # `name` and `dummy_index` should be passed. This is used by `srepr` for + # example: + # >>> d1 = Dummy() + # >>> d2 = eval(srepr(d1)) + # >>> d2 == d1 + # True + # + # If a new session is started between `srepr` and `eval`, there is a very + # small chance that `d2` will be equal to a previously-created Dummy. + + _count = 0 + _prng = random.Random() + _base_dummy_index = _prng.randint(10**6, 9*10**6) + + __slots__ = ('dummy_index',) + + is_Dummy = True + + def __new__(cls, name=None, dummy_index=None, **assumptions): + if dummy_index is not None: + assert name is not None, "If you specify a dummy_index, you must also provide a name" + + if name is None: + name = "Dummy_" + str(Dummy._count) + + if dummy_index is None: + dummy_index = Dummy._base_dummy_index + Dummy._count + Dummy._count += 1 + + cls._sanitize(assumptions, cls) + obj = Symbol.__xnew__(cls, name, **assumptions) + + obj.dummy_index = dummy_index + + return obj + + def __getnewargs_ex__(self): + return ((self.name, self.dummy_index), self._assumptions_orig) + + @cacheit + def sort_key(self, order=None): + return self.class_key(), ( + 2, (self.name, self.dummy_index)), S.One.sort_key(), S.One + + def _hashable_content(self): + return Symbol._hashable_content(self) + (self.dummy_index,) + + +class Wild(Symbol): + """ + A Wild symbol matches anything, or anything + without whatever is explicitly excluded. + + Parameters + ========== + + name : str + Name of the Wild instance. + + exclude : iterable, optional + Instances in ``exclude`` will not be matched. + + properties : iterable of functions, optional + Functions, each taking an expressions as input + and returns a ``bool``. All functions in ``properties`` + need to return ``True`` in order for the Wild instance + to match the expression. + + Examples + ======== + + >>> from sympy import Wild, WildFunction, cos, pi + >>> from sympy.abc import x, y, z + >>> a = Wild('a') + >>> x.match(a) + {a_: x} + >>> pi.match(a) + {a_: pi} + >>> (3*x**2).match(a*x) + {a_: 3*x} + >>> cos(x).match(a) + {a_: cos(x)} + >>> b = Wild('b', exclude=[x]) + >>> (3*x**2).match(b*x) + >>> b.match(a) + {a_: b_} + >>> A = WildFunction('A') + >>> A.match(a) + {a_: A_} + + Tips + ==== + + When using Wild, be sure to use the exclude + keyword to make the pattern more precise. + Without the exclude pattern, you may get matches + that are technically correct, but not what you + wanted. For example, using the above without + exclude: + + >>> from sympy import symbols + >>> a, b = symbols('a b', cls=Wild) + >>> (2 + 3*y).match(a*x + b*y) + {a_: 2/x, b_: 3} + + This is technically correct, because + (2/x)*x + 3*y == 2 + 3*y, but you probably + wanted it to not match at all. The issue is that + you really did not want a and b to include x and y, + and the exclude parameter lets you specify exactly + this. With the exclude parameter, the pattern will + not match. + + >>> a = Wild('a', exclude=[x, y]) + >>> b = Wild('b', exclude=[x, y]) + >>> (2 + 3*y).match(a*x + b*y) + + Exclude also helps remove ambiguity from matches. + + >>> E = 2*x**3*y*z + >>> a, b = symbols('a b', cls=Wild) + >>> E.match(a*b) + {a_: 2*y*z, b_: x**3} + >>> a = Wild('a', exclude=[x, y]) + >>> E.match(a*b) + {a_: z, b_: 2*x**3*y} + >>> a = Wild('a', exclude=[x, y, z]) + >>> E.match(a*b) + {a_: 2, b_: x**3*y*z} + + Wild also accepts a ``properties`` parameter: + + >>> a = Wild('a', properties=[lambda k: k.is_Integer]) + >>> E.match(a*b) + {a_: 2, b_: x**3*y*z} + + """ + is_Wild = True + + __slots__ = ('exclude', 'properties') + + def __new__(cls, name, exclude=(), properties=(), **assumptions): + exclude = tuple([sympify(x) for x in exclude]) + properties = tuple(properties) + cls._sanitize(assumptions, cls) + return Wild.__xnew__(cls, name, exclude, properties, **assumptions) + + def __getnewargs__(self): + return (self.name, self.exclude, self.properties) + + @staticmethod + @cacheit + def __xnew__(cls, name, exclude, properties, **assumptions): + obj = Symbol.__xnew__(cls, name, **assumptions) + obj.exclude = exclude + obj.properties = properties + return obj + + def _hashable_content(self): + return super()._hashable_content() + (self.exclude, self.properties) + + # TODO add check against another Wild + def matches(self, expr, repl_dict=None, old=False): + if any(expr.has(x) for x in self.exclude): + return None + if not all(f(expr) for f in self.properties): + return None + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + repl_dict[self] = expr + return repl_dict + + +_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])') + + +def symbols(names, *, cls=Symbol, **args) -> Any: + r""" + Transform strings into instances of :class:`Symbol` class. + + :func:`symbols` function returns a sequence of symbols with names taken + from ``names`` argument, which can be a comma or whitespace delimited + string, or a sequence of strings:: + + >>> from sympy import symbols, Function + + >>> x, y, z = symbols('x,y,z') + >>> a, b, c = symbols('a b c') + + The type of output is dependent on the properties of input arguments:: + + >>> symbols('x') + x + >>> symbols('x,') + (x,) + >>> symbols('x,y') + (x, y) + >>> symbols(('a', 'b', 'c')) + (a, b, c) + >>> symbols(['a', 'b', 'c']) + [a, b, c] + >>> symbols({'a', 'b', 'c'}) + {a, b, c} + + If an iterable container is needed for a single symbol, set the ``seq`` + argument to ``True`` or terminate the symbol name with a comma:: + + >>> symbols('x', seq=True) + (x,) + + To reduce typing, range syntax is supported to create indexed symbols. + Ranges are indicated by a colon and the type of range is determined by + the character to the right of the colon. If the character is a digit + then all contiguous digits to the left are taken as the nonnegative + starting value (or 0 if there is no digit left of the colon) and all + contiguous digits to the right are taken as 1 greater than the ending + value:: + + >>> symbols('x:10') + (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) + + >>> symbols('x5:10') + (x5, x6, x7, x8, x9) + >>> symbols('x5(:2)') + (x50, x51) + + >>> symbols('x5:10,y:5') + (x5, x6, x7, x8, x9, y0, y1, y2, y3, y4) + + >>> symbols(('x5:10', 'y:5')) + ((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4)) + + If the character to the right of the colon is a letter, then the single + letter to the left (or 'a' if there is none) is taken as the start + and all characters in the lexicographic range *through* the letter to + the right are used as the range:: + + >>> symbols('x:z') + (x, y, z) + >>> symbols('x:c') # null range + () + >>> symbols('x(:c)') + (xa, xb, xc) + + >>> symbols(':c') + (a, b, c) + + >>> symbols('a:d, x:z') + (a, b, c, d, x, y, z) + + >>> symbols(('a:d', 'x:z')) + ((a, b, c, d), (x, y, z)) + + Multiple ranges are supported; contiguous numerical ranges should be + separated by parentheses to disambiguate the ending number of one + range from the starting number of the next:: + + >>> symbols('x:2(1:3)') + (x01, x02, x11, x12) + >>> symbols(':3:2') # parsing is from left to right + (00, 01, 10, 11, 20, 21) + + Only one pair of parentheses surrounding ranges are removed, so to + include parentheses around ranges, double them. And to include spaces, + commas, or colons, escape them with a backslash:: + + >>> symbols('x((a:b))') + (x(a), x(b)) + >>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))' + (x(0,0), x(0,1)) + + All newly created symbols have assumptions set according to ``args``:: + + >>> a = symbols('a', integer=True) + >>> a.is_integer + True + + >>> x, y, z = symbols('x,y,z', real=True) + >>> x.is_real and y.is_real and z.is_real + True + + Despite its name, :func:`symbols` can create symbol-like objects like + instances of Function or Wild classes. To achieve this, set ``cls`` + keyword argument to the desired type:: + + >>> symbols('f,g,h', cls=Function) + (f, g, h) + + >>> type(_[0]) + + + """ + result = [] + + if isinstance(names, str): + marker = 0 + splitters = r'\,', r'\:', r'\ ' + literals: list[tuple[str, str]] = [] + for splitter in splitters: + if splitter in names: + while chr(marker) in names: + marker += 1 + lit_char = chr(marker) + marker += 1 + names = names.replace(splitter, lit_char) + literals.append((lit_char, splitter[1:])) + def literal(s): + if literals: + for c, l in literals: + s = s.replace(c, l) + return s + + names = names.strip() + as_seq = names.endswith(',') + if as_seq: + names = names[:-1].rstrip() + if not names: + raise ValueError('no symbols given') + + # split on commas + names = [n.strip() for n in names.split(',')] + if not all(n for n in names): + raise ValueError('missing symbol between commas') + # split on spaces + for i in range(len(names) - 1, -1, -1): + names[i: i + 1] = names[i].split() + + seq = args.pop('seq', as_seq) + + for name in names: + if not name: + raise ValueError('missing symbol') + + if ':' not in name: + symbol = cls(literal(name), **args) + result.append(symbol) + continue + + split: list[str] = _range.split(name) + split_list: list[list[str]] = [] + # remove 1 layer of bounding parentheses around ranges + for i in range(len(split) - 1): + if i and ':' in split[i] and split[i] != ':' and \ + split[i - 1].endswith('(') and \ + split[i + 1].startswith(')'): + split[i - 1] = split[i - 1][:-1] + split[i + 1] = split[i + 1][1:] + for s in split: + if ':' in s: + if s.endswith(':'): + raise ValueError('missing end range') + a, b = s.split(':') + if b[-1] in string.digits: + a_i = 0 if not a else int(a) + b_i = int(b) + split_list.append([str(c) for c in range(a_i, b_i)]) + else: + a = a or 'a' + split_list.append([string.ascii_letters[c] for c in range( + string.ascii_letters.index(a), + string.ascii_letters.index(b) + 1)]) # inclusive + if not split_list[-1]: + break + else: + split_list.append([s]) + else: + seq = True + if len(split_list) == 1: + names = split_list[0] + else: + names = [''.join(s) for s in product(*split_list)] + if literals: + result.extend([cls(literal(s), **args) for s in names]) + else: + result.extend([cls(s, **args) for s in names]) + + if not seq and len(result) <= 1: + if not result: + return () + return result[0] + + return tuple(result) + else: + for name in names: + result.append(symbols(name, cls=cls, **args)) + + return type(names)(result) + + +def var(names, **args): + """ + Create symbols and inject them into the global namespace. + + Explanation + =========== + + This calls :func:`symbols` with the same arguments and puts the results + into the *global* namespace. It's recommended not to use :func:`var` in + library code, where :func:`symbols` has to be used:: + + Examples + ======== + + >>> from sympy import var + + >>> var('x') + x + >>> x # noqa: F821 + x + + >>> var('a,ab,abc') + (a, ab, abc) + >>> abc # noqa: F821 + abc + + >>> var('x,y', real=True) + (x, y) + >>> x.is_real and y.is_real # noqa: F821 + True + + See :func:`symbols` documentation for more details on what kinds of + arguments can be passed to :func:`var`. + + """ + def traverse(symbols, frame): + """Recursively inject symbols to the global namespace. """ + for symbol in symbols: + if isinstance(symbol, Basic): + frame.f_globals[symbol.name] = symbol + elif isinstance(symbol, FunctionClass): + frame.f_globals[symbol.__name__] = symbol + else: + traverse(symbol, frame) + + from inspect import currentframe + frame = currentframe().f_back + + try: + syms = symbols(names, **args) + + if syms is not None: + if isinstance(syms, Basic): + frame.f_globals[syms.name] = syms + elif isinstance(syms, FunctionClass): + frame.f_globals[syms.__name__] = syms + else: + traverse(syms, frame) + finally: + del frame # break cyclic dependencies as stated in inspect docs + + return syms + +def disambiguate(*iter): + """ + Return a Tuple containing the passed expressions with symbols + that appear the same when printed replaced with numerically + subscripted symbols, and all Dummy symbols replaced with Symbols. + + Parameters + ========== + + iter: list of symbols or expressions. + + Examples + ======== + + >>> from sympy.core.symbol import disambiguate + >>> from sympy import Dummy, Symbol, Tuple + >>> from sympy.abc import y + + >>> tup = Symbol('_x'), Dummy('x'), Dummy('x') + >>> disambiguate(*tup) + (x_2, x, x_1) + + >>> eqs = Tuple(Symbol('x')/y, Dummy('x')/y) + >>> disambiguate(*eqs) + (x_1/y, x/y) + + >>> ix = Symbol('x', integer=True) + >>> vx = Symbol('x') + >>> disambiguate(vx + ix) + (x + x_1,) + + To make your own mapping of symbols to use, pass only the free symbols + of the expressions and create a dictionary: + + >>> free = eqs.free_symbols + >>> mapping = dict(zip(free, disambiguate(*free))) + >>> eqs.xreplace(mapping) + (x_1/y, x/y) + + """ + new_iter = Tuple(*iter) + key = lambda x:tuple(sorted(x.assumptions0.items())) + syms = ordered(new_iter.free_symbols, keys=key) + mapping = {} + for s in syms: + mapping.setdefault(str(s).lstrip('_'), []).append(s) + reps = {} + for k in mapping: + # the first or only symbol doesn't get subscripted but make + # sure that it's a Symbol, not a Dummy + mapk0 = Symbol("%s" % (k), **mapping[k][0].assumptions0) + if mapping[k][0] != mapk0: + reps[mapping[k][0]] = mapk0 + # the others get subscripts (and are made into Symbols) + skip = 0 + for i in range(1, len(mapping[k])): + while True: + name = "%s_%i" % (k, i + skip) + if name not in mapping: + break + skip += 1 + ki = mapping[k][i] + reps[ki] = Symbol(name, **ki.assumptions0) + return new_iter.xreplace(reps) diff --git a/shared/package-files/79/79ca0a38ce95a2ac9607ec7b69b98f0197e7a06d2191323143a73727125b75d2/blob b/shared/package-files/79/79ca0a38ce95a2ac9607ec7b69b98f0197e7a06d2191323143a73727125b75d2/blob new file mode 100644 index 0000000000000000000000000000000000000000..7db3a22ebe3da96ce714320016469daba3f55ecf --- /dev/null +++ b/shared/package-files/79/79ca0a38ce95a2ac9607ec7b69b98f0197e7a06d2191323143a73727125b75d2/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _nested_view_from_jagged_copy { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_view_from_jagged_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_view_from_jagged_copy(Tensor self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & offsets, const at::Tensor & dummy, const c10::optional & lengths, int64_t ragged_idx); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & offsets, const at::Tensor & dummy, const c10::optional & lengths, int64_t ragged_idx); +}; + +struct TORCH_API _nested_view_from_jagged_copy_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const c10::optional &, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_view_from_jagged_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_view_from_jagged_copy.out(Tensor self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & offsets, const at::Tensor & dummy, const c10::optional & lengths, int64_t ragged_idx, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & offsets, const at::Tensor & dummy, const c10::optional & lengths, int64_t ragged_idx, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/79/79ca3a2c0194b686cbb8f69fba19a02a09304512ff598f0a27861e0c21e9725b/blob b/shared/package-files/79/79ca3a2c0194b686cbb8f69fba19a02a09304512ff598f0a27861e0c21e9725b/blob new file mode 100644 index 0000000000000000000000000000000000000000..dba3191e58474c95a66e86ed67b266198f3e7aac --- /dev/null +++ b/shared/package-files/79/79ca3a2c0194b686cbb8f69fba19a02a09304512ff598f0a27861e0c21e9725b/blob @@ -0,0 +1,403 @@ +"""distutils.cmd + +Provides the Command class, the base class for the command classes +in the distutils.command package. +""" + +import sys, os, re +from distutils.errors import DistutilsOptionError +from distutils import util, dir_util, file_util, archive_util, dep_util +from distutils import log + +class Command: + """Abstract base class for defining command classes, the "worker bees" + of the Distutils. A useful analogy for command classes is to think of + them as subroutines with local variables called "options". The options + are "declared" in 'initialize_options()' and "defined" (given their + final values, aka "finalized") in 'finalize_options()', both of which + must be defined by every command class. The distinction between the + two is necessary because option values might come from the outside + world (command line, config file, ...), and any options dependent on + other options must be computed *after* these outside influences have + been processed -- hence 'finalize_options()'. The "body" of the + subroutine, where it does all its work based on the values of its + options, is the 'run()' method, which must also be implemented by every + command class. + """ + + # 'sub_commands' formalizes the notion of a "family" of commands, + # eg. "install" as the parent with sub-commands "install_lib", + # "install_headers", etc. The parent of a family of commands + # defines 'sub_commands' as a class attribute; it's a list of + # (command_name : string, predicate : unbound_method | string | None) + # tuples, where 'predicate' is a method of the parent command that + # determines whether the corresponding command is applicable in the + # current situation. (Eg. we "install_headers" is only applicable if + # we have any C header files to install.) If 'predicate' is None, + # that command is always applicable. + # + # 'sub_commands' is usually defined at the *end* of a class, because + # predicates can be unbound methods, so they must already have been + # defined. The canonical example is the "install" command. + sub_commands = [] + + + # -- Creation/initialization methods ------------------------------- + + def __init__(self, dist): + """Create and initialize a new Command object. Most importantly, + invokes the 'initialize_options()' method, which is the real + initializer and depends on the actual command being + instantiated. + """ + # late import because of mutual dependence between these classes + from distutils.dist import Distribution + + if not isinstance(dist, Distribution): + raise TypeError("dist must be a Distribution instance") + if self.__class__ is Command: + raise RuntimeError("Command is an abstract class") + + self.distribution = dist + self.initialize_options() + + # Per-command versions of the global flags, so that the user can + # customize Distutils' behaviour command-by-command and let some + # commands fall back on the Distribution's behaviour. None means + # "not defined, check self.distribution's copy", while 0 or 1 mean + # false and true (duh). Note that this means figuring out the real + # value of each flag is a touch complicated -- hence "self._dry_run" + # will be handled by __getattr__, below. + # XXX This needs to be fixed. + self._dry_run = None + + # verbose is largely ignored, but needs to be set for + # backwards compatibility (I think)? + self.verbose = dist.verbose + + # Some commands define a 'self.force' option to ignore file + # timestamps, but methods defined *here* assume that + # 'self.force' exists for all commands. So define it here + # just to be safe. + self.force = None + + # The 'help' flag is just used for command-line parsing, so + # none of that complicated bureaucracy is needed. + self.help = 0 + + # 'finalized' records whether or not 'finalize_options()' has been + # called. 'finalize_options()' itself should not pay attention to + # this flag: it is the business of 'ensure_finalized()', which + # always calls 'finalize_options()', to respect/update it. + self.finalized = 0 + + # XXX A more explicit way to customize dry_run would be better. + def __getattr__(self, attr): + if attr == 'dry_run': + myval = getattr(self, "_" + attr) + if myval is None: + return getattr(self.distribution, attr) + else: + return myval + else: + raise AttributeError(attr) + + def ensure_finalized(self): + if not self.finalized: + self.finalize_options() + self.finalized = 1 + + # Subclasses must define: + # initialize_options() + # provide default values for all options; may be customized by + # setup script, by options from config file(s), or by command-line + # options + # finalize_options() + # decide on the final values for all options; this is called + # after all possible intervention from the outside world + # (command-line, option file, etc.) has been processed + # run() + # run the command: do whatever it is we're here to do, + # controlled by the command's various option values + + def initialize_options(self): + """Set default values for all the options that this command + supports. Note that these defaults may be overridden by other + commands, by the setup script, by config files, or by the + command-line. Thus, this is not the place to code dependencies + between options; generally, 'initialize_options()' implementations + are just a bunch of "self.foo = None" assignments. + + This method must be implemented by all command classes. + """ + raise RuntimeError("abstract method -- subclass %s must override" + % self.__class__) + + def finalize_options(self): + """Set final values for all the options that this command supports. + This is always called as late as possible, ie. after any option + assignments from the command-line or from other commands have been + done. Thus, this is the place to code option dependencies: if + 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as + long as 'foo' still has the same value it was assigned in + 'initialize_options()'. + + This method must be implemented by all command classes. + """ + raise RuntimeError("abstract method -- subclass %s must override" + % self.__class__) + + + def dump_options(self, header=None, indent=""): + from distutils.fancy_getopt import longopt_xlate + if header is None: + header = "command options for '%s':" % self.get_command_name() + self.announce(indent + header, level=log.INFO) + indent = indent + " " + for (option, _, _) in self.user_options: + option = option.translate(longopt_xlate) + if option[-1] == "=": + option = option[:-1] + value = getattr(self, option) + self.announce(indent + "%s = %s" % (option, value), + level=log.INFO) + + def run(self): + """A command's raison d'etre: carry out the action it exists to + perform, controlled by the options initialized in + 'initialize_options()', customized by other commands, the setup + script, the command-line, and config files, and finalized in + 'finalize_options()'. All terminal output and filesystem + interaction should be done by 'run()'. + + This method must be implemented by all command classes. + """ + raise RuntimeError("abstract method -- subclass %s must override" + % self.__class__) + + def announce(self, msg, level=1): + """If the current verbosity level is of greater than or equal to + 'level' print 'msg' to stdout. + """ + log.log(level, msg) + + def debug_print(self, msg): + """Print 'msg' to stdout if the global DEBUG (taken from the + DISTUTILS_DEBUG environment variable) flag is true. + """ + from distutils.debug import DEBUG + if DEBUG: + print(msg) + sys.stdout.flush() + + + # -- Option validation methods ------------------------------------- + # (these are very handy in writing the 'finalize_options()' method) + # + # NB. the general philosophy here is to ensure that a particular option + # value meets certain type and value constraints. If not, we try to + # force it into conformance (eg. if we expect a list but have a string, + # split the string on comma and/or whitespace). If we can't force the + # option into conformance, raise DistutilsOptionError. Thus, command + # classes need do nothing more than (eg.) + # self.ensure_string_list('foo') + # and they can be guaranteed that thereafter, self.foo will be + # a list of strings. + + def _ensure_stringlike(self, option, what, default=None): + val = getattr(self, option) + if val is None: + setattr(self, option, default) + return default + elif not isinstance(val, str): + raise DistutilsOptionError("'%s' must be a %s (got `%s`)" + % (option, what, val)) + return val + + def ensure_string(self, option, default=None): + """Ensure that 'option' is a string; if not defined, set it to + 'default'. + """ + self._ensure_stringlike(option, "string", default) + + def ensure_string_list(self, option): + r"""Ensure that 'option' is a list of strings. If 'option' is + currently a string, we split it either on /,\s*/ or /\s+/, so + "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become + ["foo", "bar", "baz"]. + """ + val = getattr(self, option) + if val is None: + return + elif isinstance(val, str): + setattr(self, option, re.split(r',\s*|\s+', val)) + else: + if isinstance(val, list): + ok = all(isinstance(v, str) for v in val) + else: + ok = False + if not ok: + raise DistutilsOptionError( + "'%s' must be a list of strings (got %r)" + % (option, val)) + + def _ensure_tested_string(self, option, tester, what, error_fmt, + default=None): + val = self._ensure_stringlike(option, what, default) + if val is not None and not tester(val): + raise DistutilsOptionError(("error in '%s' option: " + error_fmt) + % (option, val)) + + def ensure_filename(self, option): + """Ensure that 'option' is the name of an existing file.""" + self._ensure_tested_string(option, os.path.isfile, + "filename", + "'%s' does not exist or is not a file") + + def ensure_dirname(self, option): + self._ensure_tested_string(option, os.path.isdir, + "directory name", + "'%s' does not exist or is not a directory") + + + # -- Convenience methods for commands ------------------------------ + + def get_command_name(self): + if hasattr(self, 'command_name'): + return self.command_name + else: + return self.__class__.__name__ + + def set_undefined_options(self, src_cmd, *option_pairs): + """Set the values of any "undefined" options from corresponding + option values in some other command object. "Undefined" here means + "is None", which is the convention used to indicate that an option + has not been changed between 'initialize_options()' and + 'finalize_options()'. Usually called from 'finalize_options()' for + options that depend on some other command rather than another + option of the same command. 'src_cmd' is the other command from + which option values will be taken (a command object will be created + for it if necessary); the remaining arguments are + '(src_option,dst_option)' tuples which mean "take the value of + 'src_option' in the 'src_cmd' command object, and copy it to + 'dst_option' in the current command object". + """ + # Option_pairs: list of (src_option, dst_option) tuples + src_cmd_obj = self.distribution.get_command_obj(src_cmd) + src_cmd_obj.ensure_finalized() + for (src_option, dst_option) in option_pairs: + if getattr(self, dst_option) is None: + setattr(self, dst_option, getattr(src_cmd_obj, src_option)) + + def get_finalized_command(self, command, create=1): + """Wrapper around Distribution's 'get_command_obj()' method: find + (create if necessary and 'create' is true) the command object for + 'command', call its 'ensure_finalized()' method, and return the + finalized command object. + """ + cmd_obj = self.distribution.get_command_obj(command, create) + cmd_obj.ensure_finalized() + return cmd_obj + + # XXX rename to 'get_reinitialized_command()'? (should do the + # same in dist.py, if so) + def reinitialize_command(self, command, reinit_subcommands=0): + return self.distribution.reinitialize_command(command, + reinit_subcommands) + + def run_command(self, command): + """Run some other command: uses the 'run_command()' method of + Distribution, which creates and finalizes the command object if + necessary and then invokes its 'run()' method. + """ + self.distribution.run_command(command) + + def get_sub_commands(self): + """Determine the sub-commands that are relevant in the current + distribution (ie., that need to be run). This is based on the + 'sub_commands' class attribute: each tuple in that list may include + a method that we call to determine if the subcommand needs to be + run for the current distribution. Return a list of command names. + """ + commands = [] + for (cmd_name, method) in self.sub_commands: + if method is None or method(self): + commands.append(cmd_name) + return commands + + + # -- External world manipulation ----------------------------------- + + def warn(self, msg): + log.warn("warning: %s: %s\n", self.get_command_name(), msg) + + def execute(self, func, args, msg=None, level=1): + util.execute(func, args, msg, dry_run=self.dry_run) + + def mkpath(self, name, mode=0o777): + dir_util.mkpath(name, mode, dry_run=self.dry_run) + + def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, + link=None, level=1): + """Copy a file respecting verbose, dry-run and force flags. (The + former two default to whatever is in the Distribution object, and + the latter defaults to false for commands that don't define it.)""" + return file_util.copy_file(infile, outfile, preserve_mode, + preserve_times, not self.force, link, + dry_run=self.dry_run) + + def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, + preserve_symlinks=0, level=1): + """Copy an entire directory tree respecting verbose, dry-run, + and force flags. + """ + return dir_util.copy_tree(infile, outfile, preserve_mode, + preserve_times, preserve_symlinks, + not self.force, dry_run=self.dry_run) + + def move_file (self, src, dst, level=1): + """Move a file respecting dry-run flag.""" + return file_util.move_file(src, dst, dry_run=self.dry_run) + + def spawn(self, cmd, search_path=1, level=1): + """Spawn an external command respecting dry-run flag.""" + from distutils.spawn import spawn + spawn(cmd, search_path, dry_run=self.dry_run) + + def make_archive(self, base_name, format, root_dir=None, base_dir=None, + owner=None, group=None): + return archive_util.make_archive(base_name, format, root_dir, base_dir, + dry_run=self.dry_run, + owner=owner, group=group) + + def make_file(self, infiles, outfile, func, args, + exec_msg=None, skip_msg=None, level=1): + """Special case of 'execute()' for operations that process one or + more input files and generate one output file. Works just like + 'execute()', except the operation is skipped and a different + message printed if 'outfile' already exists and is newer than all + files listed in 'infiles'. If the command defined 'self.force', + and it is true, then the command is unconditionally run -- does no + timestamp checks. + """ + if skip_msg is None: + skip_msg = "skipping %s (inputs unchanged)" % outfile + + # Allow 'infiles' to be a single string + if isinstance(infiles, str): + infiles = (infiles,) + elif not isinstance(infiles, (list, tuple)): + raise TypeError( + "'infiles' must be a string, or a list or tuple of strings") + + if exec_msg is None: + exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles)) + + # If 'outfile' must be regenerated (either because it doesn't + # exist, is out-of-date, or the 'force' flag is true) then + # perform the action that presumably regenerates it + if self.force or dep_util.newer_group(infiles, outfile): + self.execute(func, args, exec_msg, level) + # Otherwise, print the "skip" message + else: + log.debug(skip_msg) diff --git a/shared/package-files/79/79cb4331aadd14d2b53c0b90ea0878c9c3365cb9b56f20676b04b42d43e472c5/blob b/shared/package-files/79/79cb4331aadd14d2b53c0b90ea0878c9c3365cb9b56f20676b04b42d43e472c5/blob new file mode 100644 index 0000000000000000000000000000000000000000..70158141d0ceedbe39f29c2869a855647b4d1a1e --- /dev/null +++ b/shared/package-files/79/79cb4331aadd14d2b53c0b90ea0878c9c3365cb9b56f20676b04b42d43e472c5/blob @@ -0,0 +1,495 @@ +import numpy as np +import pytest + +from pandas.compat import WARNING_CHECK_DISABLED + +from pandas import ( + Categorical, + DataFrame, + option_context, +) +import pandas._testing as tm +from pandas.tests.copy_view.util import get_array + + +@pytest.mark.parametrize( + "replace_kwargs", + [ + {"to_replace": {"a": 1, "b": 4}, "value": -1}, + # Test CoW splits blocks to avoid copying unchanged columns + {"to_replace": {"a": 1}, "value": -1}, + {"to_replace": {"b": 4}, "value": -1}, + {"to_replace": {"b": {4: 1}}}, + # TODO: Add these in a further optimization + # We would need to see which columns got replaced in the mask + # which could be expensive + # {"to_replace": {"b": 1}}, + # 1 + ], +) +def test_replace(using_copy_on_write, replace_kwargs): + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) + df_orig = df.copy() + + df_replaced = df.replace(**replace_kwargs) + + if using_copy_on_write: + if (df_replaced["b"] == df["b"]).all(): + assert np.shares_memory(get_array(df_replaced, "b"), get_array(df, "b")) + assert tm.shares_memory(get_array(df_replaced, "c"), get_array(df, "c")) + + # mutating squeezed df triggers a copy-on-write for that column/block + df_replaced.loc[0, "c"] = -1 + if using_copy_on_write: + assert not np.shares_memory(get_array(df_replaced, "c"), get_array(df, "c")) + + if "a" in replace_kwargs["to_replace"]: + arr = get_array(df_replaced, "a") + df_replaced.loc[0, "a"] = 100 + assert np.shares_memory(get_array(df_replaced, "a"), arr) + tm.assert_frame_equal(df, df_orig) + + +def test_replace_regex_inplace_refs(using_copy_on_write, warn_copy_on_write): + df = DataFrame({"a": ["aaa", "bbb"]}) + df_orig = df.copy() + view = df[:] + arr = get_array(df, "a") + with tm.assert_cow_warning(warn_copy_on_write): + df.replace(to_replace=r"^a.*$", value="new", inplace=True, regex=True) + if using_copy_on_write: + assert not tm.shares_memory(arr, get_array(df, "a")) + assert df._mgr._has_no_reference(0) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(arr, get_array(df, "a")) + + +def test_replace_regex_inplace(using_copy_on_write): + df = DataFrame({"a": ["aaa", "bbb"]}) + arr = get_array(df, "a") + df.replace(to_replace=r"^a.*$", value="new", inplace=True, regex=True) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + assert tm.shares_memory(arr, get_array(df, "a")) + + df_orig = df.copy() + df2 = df.replace(to_replace=r"^b.*$", value="new", regex=True) + tm.assert_frame_equal(df_orig, df) + assert not tm.shares_memory(get_array(df2, "a"), get_array(df, "a")) + + +def test_replace_regex_inplace_no_op(using_copy_on_write): + df = DataFrame({"a": [1, 2]}) + arr = get_array(df, "a") + df.replace(to_replace=r"^a.$", value="new", inplace=True, regex=True) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + assert np.shares_memory(arr, get_array(df, "a")) + + df_orig = df.copy() + df2 = df.replace(to_replace=r"^x.$", value="new", regex=True) + tm.assert_frame_equal(df_orig, df) + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + else: + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + + +def test_replace_mask_all_false_second_block(using_copy_on_write): + df = DataFrame({"a": [1.5, 2, 3], "b": 100.5, "c": 1, "d": 2}) + df_orig = df.copy() + + df2 = df.replace(to_replace=1.5, value=55.5) + + if using_copy_on_write: + # TODO: Block splitting would allow us to avoid copying b + assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + else: + assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + df2.loc[0, "c"] = 1 + tm.assert_frame_equal(df, df_orig) # Original is unchanged + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + # TODO: This should split and not copy the whole block + # assert np.shares_memory(get_array(df, "d"), get_array(df2, "d")) + + +def test_replace_coerce_single_column(using_copy_on_write, using_array_manager): + df = DataFrame({"a": [1.5, 2, 3], "b": 100.5}) + df_orig = df.copy() + + df2 = df.replace(to_replace=1.5, value="a") + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + elif not using_array_manager: + assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + if using_copy_on_write: + df2.loc[0, "b"] = 0.5 + tm.assert_frame_equal(df, df_orig) # Original is unchanged + assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + + +def test_replace_to_replace_wrong_dtype(using_copy_on_write): + df = DataFrame({"a": [1.5, 2, 3], "b": 100.5}) + df_orig = df.copy() + + df2 = df.replace(to_replace="xxx", value=1.5) + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + else: + assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + df2.loc[0, "b"] = 0.5 + tm.assert_frame_equal(df, df_orig) # Original is unchanged + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + + +def test_replace_list_categorical(using_copy_on_write): + df = DataFrame({"a": ["a", "b", "c"]}, dtype="category") + arr = get_array(df, "a") + msg = ( + r"The behavior of Series\.replace \(and DataFrame.replace\) " + "with CategoricalDtype" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + df.replace(["c"], value="a", inplace=True) + assert np.shares_memory(arr.codes, get_array(df, "a").codes) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + df_orig = df.copy() + with tm.assert_produces_warning(FutureWarning, match=msg): + df2 = df.replace(["b"], value="a") + assert not np.shares_memory(arr.codes, get_array(df2, "a").codes) + + tm.assert_frame_equal(df, df_orig) + + +def test_replace_list_inplace_refs_categorical(using_copy_on_write): + df = DataFrame({"a": ["a", "b", "c"]}, dtype="category") + view = df[:] + df_orig = df.copy() + msg = ( + r"The behavior of Series\.replace \(and DataFrame.replace\) " + "with CategoricalDtype" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + df.replace(["c"], value="a", inplace=True) + if using_copy_on_write: + assert not np.shares_memory( + get_array(view, "a").codes, get_array(df, "a").codes + ) + tm.assert_frame_equal(df_orig, view) + else: + # This could be inplace + assert not np.shares_memory( + get_array(view, "a").codes, get_array(df, "a").codes + ) + + +@pytest.mark.parametrize("to_replace", [1.5, [1.5], []]) +def test_replace_inplace(using_copy_on_write, to_replace): + df = DataFrame({"a": [1.5, 2, 3]}) + arr_a = get_array(df, "a") + df.replace(to_replace=1.5, value=15.5, inplace=True) + + assert np.shares_memory(get_array(df, "a"), arr_a) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + +@pytest.mark.parametrize("to_replace", [1.5, [1.5]]) +def test_replace_inplace_reference(using_copy_on_write, to_replace, warn_copy_on_write): + df = DataFrame({"a": [1.5, 2, 3]}) + arr_a = get_array(df, "a") + view = df[:] + with tm.assert_cow_warning(warn_copy_on_write): + df.replace(to_replace=to_replace, value=15.5, inplace=True) + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), arr_a) + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + else: + assert np.shares_memory(get_array(df, "a"), arr_a) + + +@pytest.mark.parametrize("to_replace", ["a", 100.5]) +def test_replace_inplace_reference_no_op(using_copy_on_write, to_replace): + df = DataFrame({"a": [1.5, 2, 3]}) + arr_a = get_array(df, "a") + view = df[:] + df.replace(to_replace=to_replace, value=15.5, inplace=True) + + assert np.shares_memory(get_array(df, "a"), arr_a) + if using_copy_on_write: + assert not df._mgr._has_no_reference(0) + assert not view._mgr._has_no_reference(0) + + +@pytest.mark.parametrize("to_replace", [1, [1]]) +@pytest.mark.parametrize("val", [1, 1.5]) +def test_replace_categorical_inplace_reference(using_copy_on_write, val, to_replace): + df = DataFrame({"a": Categorical([1, 2, 3])}) + df_orig = df.copy() + arr_a = get_array(df, "a") + view = df[:] + msg = ( + r"The behavior of Series\.replace \(and DataFrame.replace\) " + "with CategoricalDtype" + ) + warn = FutureWarning if val == 1.5 else None + with tm.assert_produces_warning(warn, match=msg): + df.replace(to_replace=to_replace, value=val, inplace=True) + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a").codes, arr_a.codes) + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(get_array(df, "a").codes, arr_a.codes) + + +@pytest.mark.parametrize("val", [1, 1.5]) +def test_replace_categorical_inplace(using_copy_on_write, val): + df = DataFrame({"a": Categorical([1, 2, 3])}) + arr_a = get_array(df, "a") + msg = ( + r"The behavior of Series\.replace \(and DataFrame.replace\) " + "with CategoricalDtype" + ) + warn = FutureWarning if val == 1.5 else None + with tm.assert_produces_warning(warn, match=msg): + df.replace(to_replace=1, value=val, inplace=True) + + assert np.shares_memory(get_array(df, "a").codes, arr_a.codes) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + expected = DataFrame({"a": Categorical([val, 2, 3])}) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize("val", [1, 1.5]) +def test_replace_categorical(using_copy_on_write, val): + df = DataFrame({"a": Categorical([1, 2, 3])}) + df_orig = df.copy() + msg = ( + r"The behavior of Series\.replace \(and DataFrame.replace\) " + "with CategoricalDtype" + ) + warn = FutureWarning if val == 1.5 else None + with tm.assert_produces_warning(warn, match=msg): + df2 = df.replace(to_replace=1, value=val) + + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + assert df2._mgr._has_no_reference(0) + assert not np.shares_memory(get_array(df, "a").codes, get_array(df2, "a").codes) + tm.assert_frame_equal(df, df_orig) + + arr_a = get_array(df2, "a").codes + df2.iloc[0, 0] = 2.0 + assert np.shares_memory(get_array(df2, "a").codes, arr_a) + + +@pytest.mark.parametrize("method", ["where", "mask"]) +def test_masking_inplace(using_copy_on_write, method, warn_copy_on_write): + df = DataFrame({"a": [1.5, 2, 3]}) + df_orig = df.copy() + arr_a = get_array(df, "a") + view = df[:] + + method = getattr(df, method) + if warn_copy_on_write: + with tm.assert_cow_warning(): + method(df["a"] > 1.6, -1, inplace=True) + else: + method(df["a"] > 1.6, -1, inplace=True) + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), arr_a) + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(get_array(df, "a"), arr_a) + + +def test_replace_empty_list(using_copy_on_write): + df = DataFrame({"a": [1, 2]}) + + df2 = df.replace([], []) + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not df._mgr._has_no_reference(0) + else: + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + + arr_a = get_array(df, "a") + df.replace([], []) + if using_copy_on_write: + assert np.shares_memory(get_array(df, "a"), arr_a) + assert not df._mgr._has_no_reference(0) + assert not df2._mgr._has_no_reference(0) + + +@pytest.mark.parametrize("value", ["d", None]) +def test_replace_object_list_inplace(using_copy_on_write, value): + df = DataFrame({"a": ["a", "b", "c"]}, dtype=object) + arr = get_array(df, "a") + df.replace(["c"], value, inplace=True) + if using_copy_on_write or value is None: + assert tm.shares_memory(arr, get_array(df, "a")) + else: + # This could be inplace + assert not np.shares_memory(arr, get_array(df, "a")) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + +def test_replace_list_multiple_elements_inplace(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3]}) + arr = get_array(df, "a") + df.replace([1, 2], 4, inplace=True) + if using_copy_on_write: + assert np.shares_memory(arr, get_array(df, "a")) + assert df._mgr._has_no_reference(0) + else: + assert np.shares_memory(arr, get_array(df, "a")) + + +def test_replace_list_none(using_copy_on_write): + df = DataFrame({"a": ["a", "b", "c"]}) + + df_orig = df.copy() + df2 = df.replace(["b"], value=None) + tm.assert_frame_equal(df, df_orig) + + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + # replace multiple values that don't actually replace anything with None + # https://github.com/pandas-dev/pandas/issues/59770 + df3 = df.replace(["d", "e", "f"], value=None) + tm.assert_frame_equal(df3, df_orig) + if using_copy_on_write: + assert tm.shares_memory(get_array(df, "a"), get_array(df3, "a")) + else: + assert not tm.shares_memory(get_array(df, "a"), get_array(df3, "a")) + + +def test_replace_list_none_inplace_refs(using_copy_on_write, warn_copy_on_write): + df = DataFrame({"a": ["a", "b", "c"]}) + arr = get_array(df, "a") + df_orig = df.copy() + view = df[:] + with tm.assert_cow_warning(warn_copy_on_write): + df.replace(["a"], value=None, inplace=True) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + assert not np.shares_memory(arr, get_array(df, "a")) + tm.assert_frame_equal(df_orig, view) + else: + assert np.shares_memory(arr, get_array(df, "a")) + + +def test_replace_columnwise_no_op_inplace(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]}) + view = df[:] + df_orig = df.copy() + df.replace({"a": 10}, 100, inplace=True) + if using_copy_on_write: + assert np.shares_memory(get_array(view, "a"), get_array(df, "a")) + df.iloc[0, 0] = 100 + tm.assert_frame_equal(view, df_orig) + + +def test_replace_columnwise_no_op(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]}) + df_orig = df.copy() + df2 = df.replace({"a": 10}, 100) + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + df2.iloc[0, 0] = 100 + tm.assert_frame_equal(df, df_orig) + + +def test_replace_chained_assignment(using_copy_on_write): + df = DataFrame({"a": [1, np.nan, 2], "b": 1}) + df_orig = df.copy() + if using_copy_on_write: + with tm.raises_chained_assignment_error(): + df["a"].replace(1, 100, inplace=True) + tm.assert_frame_equal(df, df_orig) + + with tm.raises_chained_assignment_error(): + df[["a"]].replace(1, 100, inplace=True) + tm.assert_frame_equal(df, df_orig) + else: + with tm.assert_produces_warning(None): + with option_context("mode.chained_assignment", None): + df[["a"]].replace(1, 100, inplace=True) + + with tm.assert_produces_warning(None): + with option_context("mode.chained_assignment", None): + df[df.a > 5].replace(1, 100, inplace=True) + + with tm.assert_produces_warning( + FutureWarning if not WARNING_CHECK_DISABLED else None, + match="inplace method", + ): + df["a"].replace(1, 100, inplace=True) + + +def test_replace_listlike(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]}) + df_orig = df.copy() + + result = df.replace([200, 201], [11, 11]) + if using_copy_on_write: + assert np.shares_memory(get_array(result, "a"), get_array(df, "a")) + else: + assert not np.shares_memory(get_array(result, "a"), get_array(df, "a")) + + result.iloc[0, 0] = 100 + tm.assert_frame_equal(df, df) + + result = df.replace([200, 2], [10, 10]) + assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) + tm.assert_frame_equal(df, df_orig) + + +def test_replace_listlike_inplace(using_copy_on_write, warn_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]}) + arr = get_array(df, "a") + df.replace([200, 2], [10, 11], inplace=True) + assert np.shares_memory(get_array(df, "a"), arr) + + view = df[:] + df_orig = df.copy() + with tm.assert_cow_warning(warn_copy_on_write): + df.replace([200, 3], [10, 11], inplace=True) + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), arr) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(get_array(df, "a"), arr) + tm.assert_frame_equal(df, view) diff --git a/shared/package-files/79/79cd5eaf620d5d5dbf48dd13a1ce086dc99389d6badc47fe67d976d0e6a8a4f5/blob b/shared/package-files/79/79cd5eaf620d5d5dbf48dd13a1ce086dc99389d6badc47fe67d976d0e6a8a4f5/blob new file mode 100644 index 0000000000000000000000000000000000000000..aef9b50ca1ad3cd122240094412b6d1fe5c84ea6 --- /dev/null +++ b/shared/package-files/79/79cd5eaf620d5d5dbf48dd13a1ce086dc99389d6badc47fe67d976d0e6a8a4f5/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API bool is_inference(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/79/79ce018ec37398ebc7a6d709de674fc542c5dd2d7f535114a1cbaa7c8a70f8d9/blob b/shared/package-files/79/79ce018ec37398ebc7a6d709de674fc542c5dd2d7f535114a1cbaa7c8a70f8d9/blob new file mode 100644 index 0000000000000000000000000000000000000000..612e21813e198296fe9ab95dbb73f8509f97e678 --- /dev/null +++ b/shared/package-files/79/79ce018ec37398ebc7a6d709de674fc542c5dd2d7f535114a1cbaa7c8a70f8d9/blob @@ -0,0 +1,30 @@ +# Seaborn common parameters +# .15 = dark_gray +# .8 = light_gray +figure.facecolor: white +text.color: .15 +axes.labelcolor: .15 +legend.frameon: False +legend.numpoints: 1 +legend.scatterpoints: 1 +xtick.direction: out +ytick.direction: out +xtick.color: .15 +ytick.color: .15 +axes.axisbelow: True +image.cmap: Greys +font.family: sans-serif +font.sans-serif: Arial, Liberation Sans, DejaVu Sans, Bitstream Vera Sans, sans-serif +grid.linestyle: - +lines.solid_capstyle: round + +# Seaborn whitegrid parameters +axes.grid: True +axes.facecolor: white +axes.edgecolor: .8 +axes.linewidth: 1 +grid.color: .8 +xtick.major.size: 0 +ytick.major.size: 0 +xtick.minor.size: 0 +ytick.minor.size: 0 diff --git a/shared/package-files/79/79d0ed4a1fb118026aed7ec85a9fbf8684c6a5cfb368615f7044ebdd61fb6179/blob b/shared/package-files/79/79d0ed4a1fb118026aed7ec85a9fbf8684c6a5cfb368615f7044ebdd61fb6179/blob new file mode 100644 index 0000000000000000000000000000000000000000..c4cb22067cf376294e16067fe6c62dfbe215fb90 --- /dev/null +++ b/shared/package-files/79/79d0ed4a1fb118026aed7ec85a9fbf8684c6a5cfb368615f7044ebdd61fb6179/blob @@ -0,0 +1,1201 @@ +"""This module contains routines and data structures to: + +- Find the best possible split of a node. For a given node, a split is + characterized by a feature and a bin. +- Apply a split to a node, i.e. split the indices of the samples at the node + into the newly created left and right children. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +cimport cython +from cython.parallel import prange +import numpy as np +from libc.math cimport INFINITY, ceil +from libc.stdlib cimport malloc, free, qsort +from libc.string cimport memcpy + +from ...utils._typedefs cimport uint8_t +from .common cimport X_BINNED_DTYPE_C +from .common cimport Y_DTYPE_C +from .common cimport hist_struct +from .common cimport BITSET_INNER_DTYPE_C +from .common cimport BITSET_DTYPE_C +from .common cimport MonotonicConstraint +from ._bitset cimport init_bitset +from ._bitset cimport set_bitset +from ._bitset cimport in_bitset + + +cdef struct split_info_struct: + # Same as the SplitInfo class, but we need a C struct to use it in the + # nogil sections and to use in arrays. + Y_DTYPE_C gain + int feature_idx + unsigned int bin_idx + uint8_t missing_go_to_left + Y_DTYPE_C sum_gradient_left + Y_DTYPE_C sum_gradient_right + Y_DTYPE_C sum_hessian_left + Y_DTYPE_C sum_hessian_right + unsigned int n_samples_left + unsigned int n_samples_right + Y_DTYPE_C value_left + Y_DTYPE_C value_right + uint8_t is_categorical + BITSET_DTYPE_C left_cat_bitset + + +# used in categorical splits for sorting categories by increasing values of +# sum_gradients / sum_hessians +cdef struct categorical_info: + X_BINNED_DTYPE_C bin_idx + Y_DTYPE_C value + + +class SplitInfo: + """Pure data class to store information about a potential split. + + Parameters + ---------- + gain : float + The gain of the split. + feature_idx : int + The index of the feature to be split. + bin_idx : int + The index of the bin on which the split is made. Should be ignored if + `is_categorical` is True: `left_cat_bitset` will be used to determine + the split. + missing_go_to_left : bool + Whether missing values should go to the left child. This is used + whether the split is categorical or not. + sum_gradient_left : float + The sum of the gradients of all the samples in the left child. + sum_hessian_left : float + The sum of the hessians of all the samples in the left child. + sum_gradient_right : float + The sum of the gradients of all the samples in the right child. + sum_hessian_right : float + The sum of the hessians of all the samples in the right child. + n_samples_left : int, default=0 + The number of samples in the left child. + n_samples_right : int + The number of samples in the right child. + is_categorical : bool + Whether the split is done on a categorical feature. + left_cat_bitset : ndarray of shape=(8,), dtype=uint32 or None + Bitset representing the categories that go to the left. This is used + only when `is_categorical` is True. + Note that missing values are part of that bitset if there are missing + values in the training data. For missing values, we rely on that + bitset for splitting, but at prediction time, we rely on + missing_go_to_left. + """ + def __init__(self, gain, feature_idx, bin_idx, + missing_go_to_left, sum_gradient_left, sum_hessian_left, + sum_gradient_right, sum_hessian_right, n_samples_left, + n_samples_right, value_left, value_right, + is_categorical, left_cat_bitset): + self.gain = gain + self.feature_idx = feature_idx + self.bin_idx = bin_idx + self.missing_go_to_left = missing_go_to_left + self.sum_gradient_left = sum_gradient_left + self.sum_hessian_left = sum_hessian_left + self.sum_gradient_right = sum_gradient_right + self.sum_hessian_right = sum_hessian_right + self.n_samples_left = n_samples_left + self.n_samples_right = n_samples_right + self.value_left = value_left + self.value_right = value_right + self.is_categorical = is_categorical + self.left_cat_bitset = left_cat_bitset + + +@cython.final +cdef class Splitter: + """Splitter used to find the best possible split at each node. + + A split (see SplitInfo) is characterized by a feature and a bin. + + The Splitter is also responsible for partitioning the samples among the + leaves of the tree (see split_indices() and the partition attribute). + + Parameters + ---------- + X_binned : ndarray of int, shape (n_samples, n_features) + The binned input samples. Must be Fortran-aligned. + n_bins_non_missing : ndarray, shape (n_features,) + For each feature, gives the number of bins actually used for + non-missing values. + missing_values_bin_idx : uint8 + Index of the bin that is used for missing values. This is the index of + the last bin and is always equal to max_bins (as passed to the GBDT + classes), or equivalently to n_bins - 1. + has_missing_values : ndarray, shape (n_features,) + Whether missing values were observed in the training data, for each + feature. + is_categorical : ndarray of bool of shape (n_features,) + Indicates categorical features. + monotonic_cst : ndarray of int of shape (n_features,), dtype=int + Indicates the monotonic constraint to enforce on each feature. + - 1: monotonic increase + - 0: no constraint + - -1: monotonic decrease + + Read more in the :ref:`User Guide `. + l2_regularization : float + The L2 regularization parameter. + min_hessian_to_split : float, default=1e-3 + The minimum sum of hessians needed in each node. Splits that result in + at least one child having a sum of hessians less than + min_hessian_to_split are discarded. + min_samples_leaf : int, default=20 + The minimum number of samples per leaf. + min_gain_to_split : float, default=0.0 + The minimum gain needed to split a node. Splits with lower gain will + be ignored. + hessians_are_constant: bool, default is False + Whether hessians are constant. + feature_fraction_per_split : float, default=1 + Proportion of randomly chosen features in each and every node split. + This is a form of regularization, smaller values make the trees weaker + learners and might prevent overfitting. + rng : Generator + n_threads : int, default=1 + Number of OpenMP threads to use. + """ + cdef public: + const X_BINNED_DTYPE_C [::1, :] X_binned + unsigned int n_features + const unsigned int [::1] n_bins_non_missing + uint8_t missing_values_bin_idx + const uint8_t [::1] has_missing_values + const uint8_t [::1] is_categorical + const signed char [::1] monotonic_cst + uint8_t hessians_are_constant + Y_DTYPE_C l2_regularization + Y_DTYPE_C min_hessian_to_split + unsigned int min_samples_leaf + Y_DTYPE_C min_gain_to_split + Y_DTYPE_C feature_fraction_per_split + rng + + unsigned int [::1] partition + unsigned int [::1] left_indices_buffer + unsigned int [::1] right_indices_buffer + int n_threads + + def __init__(self, + const X_BINNED_DTYPE_C [::1, :] X_binned, + const unsigned int [::1] n_bins_non_missing, + const uint8_t missing_values_bin_idx, + const uint8_t [::1] has_missing_values, + const uint8_t [::1] is_categorical, + const signed char [::1] monotonic_cst, + Y_DTYPE_C l2_regularization, + Y_DTYPE_C min_hessian_to_split=1e-3, + unsigned int min_samples_leaf=20, + Y_DTYPE_C min_gain_to_split=0., + uint8_t hessians_are_constant=False, + Y_DTYPE_C feature_fraction_per_split=1.0, + rng=np.random.RandomState(), + unsigned int n_threads=1): + + self.X_binned = X_binned + self.n_features = X_binned.shape[1] + self.n_bins_non_missing = n_bins_non_missing + self.missing_values_bin_idx = missing_values_bin_idx + self.has_missing_values = has_missing_values + self.is_categorical = is_categorical + self.monotonic_cst = monotonic_cst + self.l2_regularization = l2_regularization + self.min_hessian_to_split = min_hessian_to_split + self.min_samples_leaf = min_samples_leaf + self.min_gain_to_split = min_gain_to_split + self.hessians_are_constant = hessians_are_constant + self.feature_fraction_per_split = feature_fraction_per_split + self.rng = rng + self.n_threads = n_threads + + # The partition array maps each sample index into the leaves of the + # tree (a leaf in this context is a node that isn't split yet, not + # necessarily a 'finalized' leaf). Initially, the root contains all + # the indices, e.g.: + # partition = [abcdefghijkl] + # After a call to split_indices, it may look e.g. like this: + # partition = [cef|abdghijkl] + # we have 2 leaves, the left one is at position 0 and the second one at + # position 3. The order of the samples is irrelevant. + self.partition = np.arange(X_binned.shape[0], dtype=np.uint32) + # buffers used in split_indices to support parallel splitting. + self.left_indices_buffer = np.empty_like(self.partition) + self.right_indices_buffer = np.empty_like(self.partition) + + def split_indices(Splitter self, split_info, unsigned int [::1] + sample_indices): + """Split samples into left and right arrays. + + The split is performed according to the best possible split + (split_info). + + Ultimately, this is nothing but a partition of the sample_indices + array with a given pivot, exactly like a quicksort subroutine. + + Parameters + ---------- + split_info : SplitInfo + The SplitInfo of the node to split. + sample_indices : ndarray of unsigned int, shape (n_samples_at_node,) + The indices of the samples at the node to split. This is a view + on self.partition, and it is modified inplace by placing the + indices of the left child at the beginning, and the indices of + the right child at the end. + + Returns + ------- + left_indices : ndarray of int, shape (n_left_samples,) + The indices of the samples in the left child. This is a view on + self.partition. + right_indices : ndarray of int, shape (n_right_samples,) + The indices of the samples in the right child. This is a view on + self.partition. + right_child_position : int + The position of the right child in ``sample_indices``. + """ + # This is a multi-threaded implementation inspired by lightgbm. Here + # is a quick break down. Let's suppose we want to split a node with 24 + # samples named from a to x. self.partition looks like this (the * are + # indices in other leaves that we don't care about): + # partition = [*************abcdefghijklmnopqrstuvwx****************] + # ^ ^ + # node_position node_position + node.n_samples + + # Ultimately, we want to reorder the samples inside the boundaries of + # the leaf (which becomes a node) to now represent the samples in its + # left and right child. For example: + # partition = [*************abefilmnopqrtuxcdghjksvw*****************] + # ^ ^ + # left_child_pos right_child_pos + # Note that left_child_pos always takes the value of node_position, + # and right_child_pos = left_child_pos + left_child.n_samples. The + # order of the samples inside a leaf is irrelevant. + + # 1. sample_indices is a view on this region a..x. We conceptually + # divide it into n_threads regions. Each thread will be responsible + # for its own region. Here is an example with 4 threads: + # sample_indices = [abcdef|ghijkl|mnopqr|stuvwx] + # 2. Each thread processes 6 = 24 // 4 entries and maps them into + # left_indices_buffer or right_indices_buffer. For example, we could + # have the following mapping ('.' denotes an undefined entry): + # - left_indices_buffer = [abef..|il....|mnopqr|tux...] + # - right_indices_buffer = [cd....|ghjk..|......|svw...] + # 3. We keep track of the start positions of the regions (the '|') in + # ``offset_in_buffers`` as well as the size of each region. We also + # keep track of the number of samples put into the left/right child + # by each thread. Concretely: + # - left_counts = [4, 2, 6, 3] + # - right_counts = [2, 4, 0, 3] + # 4. Finally, we put left/right_indices_buffer back into the + # sample_indices, without any undefined entries and the partition + # looks as expected + # partition = [*************abefilmnopqrtuxcdghjksvw***************] + + # Note: We here show left/right_indices_buffer as being the same size + # as sample_indices for simplicity, but in reality they are of the + # same size as partition. + + cdef: + int n_samples = sample_indices.shape[0] + X_BINNED_DTYPE_C bin_idx = split_info.bin_idx + uint8_t missing_go_to_left = split_info.missing_go_to_left + uint8_t missing_values_bin_idx = self.missing_values_bin_idx + int feature_idx = split_info.feature_idx + const X_BINNED_DTYPE_C [::1] X_binned = \ + self.X_binned[:, feature_idx] + unsigned int [::1] left_indices_buffer = self.left_indices_buffer + unsigned int [::1] right_indices_buffer = self.right_indices_buffer + uint8_t is_categorical = split_info.is_categorical + # Cython is unhappy if we set left_cat_bitset to + # split_info.left_cat_bitset directly, so we need a tmp var + BITSET_INNER_DTYPE_C [:] cat_bitset_tmp = split_info.left_cat_bitset + BITSET_DTYPE_C left_cat_bitset + int n_threads = self.n_threads + + int [:] sizes = np.full(n_threads, n_samples // n_threads, + dtype=np.int32) + int [:] offset_in_buffers = np.zeros(n_threads, dtype=np.int32) + int [:] left_counts = np.empty(n_threads, dtype=np.int32) + int [:] right_counts = np.empty(n_threads, dtype=np.int32) + int left_count + int right_count + int start + int stop + int i + int thread_idx + int sample_idx + int right_child_position + uint8_t turn_left + int [:] left_offset = np.zeros(n_threads, dtype=np.int32) + int [:] right_offset = np.zeros(n_threads, dtype=np.int32) + + # only set left_cat_bitset when is_categorical is True + if is_categorical: + left_cat_bitset = &cat_bitset_tmp[0] + + with nogil: + for thread_idx in range(n_samples % n_threads): + sizes[thread_idx] += 1 + + for thread_idx in range(1, n_threads): + offset_in_buffers[thread_idx] = \ + offset_in_buffers[thread_idx - 1] + sizes[thread_idx - 1] + + # map indices from sample_indices to left/right_indices_buffer + for thread_idx in prange(n_threads, schedule='static', + chunksize=1, num_threads=n_threads): + left_count = 0 + right_count = 0 + + start = offset_in_buffers[thread_idx] + stop = start + sizes[thread_idx] + for i in range(start, stop): + sample_idx = sample_indices[i] + turn_left = sample_goes_left( + missing_go_to_left, + missing_values_bin_idx, bin_idx, + X_binned[sample_idx], is_categorical, + left_cat_bitset) + + if turn_left: + left_indices_buffer[start + left_count] = sample_idx + left_count = left_count + 1 + else: + right_indices_buffer[start + right_count] = sample_idx + right_count = right_count + 1 + + left_counts[thread_idx] = left_count + right_counts[thread_idx] = right_count + + # position of right child = just after the left child + right_child_position = 0 + for thread_idx in range(n_threads): + right_child_position += left_counts[thread_idx] + + # offset of each thread in sample_indices for left and right + # child, i.e. where each thread will start to write. + right_offset[0] = right_child_position + for thread_idx in range(1, n_threads): + left_offset[thread_idx] = \ + left_offset[thread_idx - 1] + left_counts[thread_idx - 1] + right_offset[thread_idx] = \ + right_offset[thread_idx - 1] + right_counts[thread_idx - 1] + + # map indices in left/right_indices_buffer back into + # sample_indices. This also updates self.partition since + # sample_indices is a view. + for thread_idx in prange(n_threads, schedule='static', + chunksize=1, num_threads=n_threads): + memcpy( + &sample_indices[left_offset[thread_idx]], + &left_indices_buffer[offset_in_buffers[thread_idx]], + sizeof(unsigned int) * left_counts[thread_idx] + ) + if right_counts[thread_idx] > 0: + # If we're splitting the rightmost node of the tree, i.e. the + # rightmost node in the partition array, and if n_threads >= 2, one + # might have right_counts[-1] = 0 and right_offset[-1] = len(sample_indices) + # leading to evaluating + # + # &sample_indices[right_offset[-1]] = &samples_indices[n_samples_at_node] + # = &partition[n_samples_in_tree] + # + # which is an out-of-bounds read access that can cause a segmentation fault. + # When boundscheck=True, removing this check produces this exception: + # + # IndexError: Out of bounds on buffer access + # + memcpy( + &sample_indices[right_offset[thread_idx]], + &right_indices_buffer[offset_in_buffers[thread_idx]], + sizeof(unsigned int) * right_counts[thread_idx] + ) + + return (sample_indices[:right_child_position], + sample_indices[right_child_position:], + right_child_position) + + def find_node_split( + Splitter self, + unsigned int n_samples, + hist_struct [:, ::1] histograms, # IN + const Y_DTYPE_C sum_gradients, + const Y_DTYPE_C sum_hessians, + const Y_DTYPE_C value, + const Y_DTYPE_C lower_bound=-INFINITY, + const Y_DTYPE_C upper_bound=INFINITY, + const unsigned int [:] allowed_features=None, + ): + """For each feature, find the best bin to split on at a given node. + + Return the best split info among all features. + + Parameters + ---------- + n_samples : int + The number of samples at the node. + histograms : ndarray of HISTOGRAM_DTYPE of \ + shape (n_features, max_bins) + The histograms of the current node. + sum_gradients : float + The sum of the gradients for each sample at the node. + sum_hessians : float + The sum of the hessians for each sample at the node. + value : float + The bounded value of the current node. We directly pass the value + instead of re-computing it from sum_gradients and sum_hessians, + because we need to compute the loss and the gain based on the + *bounded* value: computing the value from + sum_gradients / sum_hessians would give the unbounded value, and + the interaction with min_gain_to_split would not be correct + anymore. Side note: we can't use the lower_bound / upper_bound + parameters either because these refer to the bounds of the + children, not the bounds of the current node. + lower_bound : float + Lower bound for the children values for respecting the monotonic + constraints. + upper_bound : float + Upper bound for the children values for respecting the monotonic + constraints. + allowed_features : None or ndarray, dtype=np.uint32 + Indices of the features that are allowed by interaction constraints to be + split. + + Returns + ------- + best_split_info : SplitInfo + The info about the best possible split among all features. + """ + cdef: + int feature_idx + int split_info_idx + int best_split_info_idx + int n_allowed_features + split_info_struct split_info + split_info_struct * split_infos + const uint8_t [::1] has_missing_values = self.has_missing_values + const uint8_t [::1] is_categorical = self.is_categorical + const signed char [::1] monotonic_cst = self.monotonic_cst + int n_threads = self.n_threads + bint has_interaction_cst = False + Y_DTYPE_C feature_fraction_per_split = self.feature_fraction_per_split + uint8_t [:] subsample_mask # same as npy_bool + int n_subsampled_features + + has_interaction_cst = allowed_features is not None + if has_interaction_cst: + n_allowed_features = allowed_features.shape[0] + else: + n_allowed_features = self.n_features + + if feature_fraction_per_split < 1.0: + # We do all random sampling before the nogil and make sure that we sample + # exactly n_subsampled_features >= 1 features. + n_subsampled_features = max( + 1, + int(ceil(feature_fraction_per_split * n_allowed_features)), + ) + subsample_mask_arr = np.full(n_allowed_features, False) + subsample_mask_arr[:n_subsampled_features] = True + self.rng.shuffle(subsample_mask_arr) + # https://github.com/numpy/numpy/issues/18273 + subsample_mask = subsample_mask_arr + + with nogil: + + split_infos = malloc( + n_allowed_features * sizeof(split_info_struct)) + + # split_info_idx is index of split_infos of size n_allowed_features. + # features_idx is the index of the feature column in X. + for split_info_idx in prange(n_allowed_features, schedule='static', + num_threads=n_threads): + if has_interaction_cst: + feature_idx = allowed_features[split_info_idx] + else: + feature_idx = split_info_idx + + split_infos[split_info_idx].feature_idx = feature_idx + + # For each feature, find best bin to split on + # Start with a gain of -1 if no better split is found, that + # means one of the constraints isn't respected + # (min_samples_leaf, etc.) and the grower will later turn the + # node into a leaf. + split_infos[split_info_idx].gain = -1 + split_infos[split_info_idx].is_categorical = is_categorical[feature_idx] + + # Note that subsample_mask is indexed by split_info_idx and not by + # feature_idx because we only need to exclude the same features again + # and again. We do NOT need to access the features directly by using + # allowed_features. + if feature_fraction_per_split < 1.0 and not subsample_mask[split_info_idx]: + continue + + if is_categorical[feature_idx]: + self._find_best_bin_to_split_category( + feature_idx, has_missing_values[feature_idx], + histograms, n_samples, sum_gradients, sum_hessians, + value, monotonic_cst[feature_idx], lower_bound, + upper_bound, &split_infos[split_info_idx]) + else: + # We will scan bins from left to right (in all cases), and + # if there are any missing values, we will also scan bins + # from right to left. This way, we can consider whichever + # case yields the best gain: either missing values go to + # the right (left to right scan) or to the left (right to + # left case). See algo 3 from the XGBoost paper + # https://arxiv.org/abs/1603.02754 + # Note: for the categorical features above, this isn't + # needed since missing values are considered a native + # category. + self._find_best_bin_to_split_left_to_right( + feature_idx, has_missing_values[feature_idx], + histograms, n_samples, sum_gradients, sum_hessians, + value, monotonic_cst[feature_idx], + lower_bound, upper_bound, &split_infos[split_info_idx]) + + if has_missing_values[feature_idx]: + # We need to explore both directions to check whether + # sending the nans to the left child would lead to a higher + # gain + self._find_best_bin_to_split_right_to_left( + feature_idx, histograms, n_samples, + sum_gradients, sum_hessians, + value, monotonic_cst[feature_idx], + lower_bound, upper_bound, &split_infos[split_info_idx]) + + # then compute best possible split among all features + # split_info is set to the best of split_infos + best_split_info_idx = self._find_best_feature_to_split_helper( + split_infos, n_allowed_features + ) + split_info = split_infos[best_split_info_idx] + + out = SplitInfo( + split_info.gain, + split_info.feature_idx, + split_info.bin_idx, + split_info.missing_go_to_left, + split_info.sum_gradient_left, + split_info.sum_hessian_left, + split_info.sum_gradient_right, + split_info.sum_hessian_right, + split_info.n_samples_left, + split_info.n_samples_right, + split_info.value_left, + split_info.value_right, + split_info.is_categorical, + None, # left_cat_bitset will only be set if the split is categorical + ) + # Only set bitset if the split is categorical + if split_info.is_categorical: + out.left_cat_bitset = np.asarray(split_info.left_cat_bitset, dtype=np.uint32) + + free(split_infos) + return out + + cdef int _find_best_feature_to_split_helper( + self, + split_info_struct * split_infos, # IN + int n_allowed_features, + ) noexcept nogil: + """Return the index of split_infos with the best feature split.""" + cdef: + int split_info_idx + int best_split_info_idx = 0 + + for split_info_idx in range(1, n_allowed_features): + if (split_infos[split_info_idx].gain > split_infos[best_split_info_idx].gain): + best_split_info_idx = split_info_idx + return best_split_info_idx + + cdef void _find_best_bin_to_split_left_to_right( + Splitter self, + unsigned int feature_idx, + uint8_t has_missing_values, + const hist_struct [:, ::1] histograms, # IN + unsigned int n_samples, + Y_DTYPE_C sum_gradients, + Y_DTYPE_C sum_hessians, + Y_DTYPE_C value, + signed char monotonic_cst, + Y_DTYPE_C lower_bound, + Y_DTYPE_C upper_bound, + split_info_struct * split_info) noexcept nogil: # OUT + """Find best bin to split on for a given feature. + + Splits that do not satisfy the splitting constraints + (min_gain_to_split, etc.) are discarded here. + + We scan node from left to right. This version is called whether there + are missing values or not. If any, missing values are assigned to the + right node. + """ + cdef: + unsigned int bin_idx + unsigned int n_samples_left + unsigned int n_samples_right + unsigned int n_samples_ = n_samples + # We set the 'end' variable such that the last non-missing-values + # bin never goes to the left child (which would result in and + # empty right child), unless there are missing values, since these + # would go to the right child. + unsigned int end = \ + self.n_bins_non_missing[feature_idx] - 1 + has_missing_values + Y_DTYPE_C sum_hessian_left + Y_DTYPE_C sum_hessian_right + Y_DTYPE_C sum_gradient_left + Y_DTYPE_C sum_gradient_right + Y_DTYPE_C loss_current_node + Y_DTYPE_C gain + uint8_t found_better_split = False + + Y_DTYPE_C best_sum_hessian_left + Y_DTYPE_C best_sum_gradient_left + unsigned int best_bin_idx + unsigned int best_n_samples_left + Y_DTYPE_C best_gain = -1 + hist_struct hist + + sum_gradient_left, sum_hessian_left = 0., 0. + n_samples_left = 0 + + loss_current_node = _loss_from_value(value, sum_gradients) + + for bin_idx in range(end): + hist = histograms[feature_idx, bin_idx] + n_samples_left += hist.count + n_samples_right = n_samples_ - n_samples_left + + if self.hessians_are_constant: + sum_hessian_left += hist.count + else: + sum_hessian_left += \ + hist.sum_hessians + sum_hessian_right = sum_hessians - sum_hessian_left + + sum_gradient_left += hist.sum_gradients + sum_gradient_right = sum_gradients - sum_gradient_left + + if n_samples_left < self.min_samples_leaf: + continue + if n_samples_right < self.min_samples_leaf: + # won't get any better + break + + if sum_hessian_left < self.min_hessian_to_split: + continue + if sum_hessian_right < self.min_hessian_to_split: + # won't get any better (hessians are > 0 since loss is convex) + break + + gain = _split_gain(sum_gradient_left, sum_hessian_left, + sum_gradient_right, sum_hessian_right, + loss_current_node, + monotonic_cst, + lower_bound, + upper_bound, + self.l2_regularization) + + if gain > best_gain and gain > self.min_gain_to_split: + found_better_split = True + best_gain = gain + best_bin_idx = bin_idx + best_sum_gradient_left = sum_gradient_left + best_sum_hessian_left = sum_hessian_left + best_n_samples_left = n_samples_left + + if found_better_split: + split_info.gain = best_gain + split_info.bin_idx = best_bin_idx + # we scan from left to right so missing values go to the right + split_info.missing_go_to_left = False + split_info.sum_gradient_left = best_sum_gradient_left + split_info.sum_gradient_right = sum_gradients - best_sum_gradient_left + split_info.sum_hessian_left = best_sum_hessian_left + split_info.sum_hessian_right = sum_hessians - best_sum_hessian_left + split_info.n_samples_left = best_n_samples_left + split_info.n_samples_right = n_samples - best_n_samples_left + + # We recompute best values here but it's cheap + split_info.value_left = compute_node_value( + split_info.sum_gradient_left, split_info.sum_hessian_left, + lower_bound, upper_bound, self.l2_regularization) + + split_info.value_right = compute_node_value( + split_info.sum_gradient_right, split_info.sum_hessian_right, + lower_bound, upper_bound, self.l2_regularization) + + cdef void _find_best_bin_to_split_right_to_left( + self, + unsigned int feature_idx, + const hist_struct [:, ::1] histograms, # IN + unsigned int n_samples, + Y_DTYPE_C sum_gradients, + Y_DTYPE_C sum_hessians, + Y_DTYPE_C value, + signed char monotonic_cst, + Y_DTYPE_C lower_bound, + Y_DTYPE_C upper_bound, + split_info_struct * split_info) noexcept nogil: # OUT + """Find best bin to split on for a given feature. + + Splits that do not satisfy the splitting constraints + (min_gain_to_split, etc.) are discarded here. + + We scan node from right to left. This version is only called when + there are missing values. Missing values are assigned to the left + child. + + If no missing value are present in the data this method isn't called + since only calling _find_best_bin_to_split_left_to_right is enough. + """ + + cdef: + unsigned int bin_idx + unsigned int n_samples_left + unsigned int n_samples_right + unsigned int n_samples_ = n_samples + Y_DTYPE_C sum_hessian_left + Y_DTYPE_C sum_hessian_right + Y_DTYPE_C sum_gradient_left + Y_DTYPE_C sum_gradient_right + Y_DTYPE_C loss_current_node + Y_DTYPE_C gain + unsigned int start = self.n_bins_non_missing[feature_idx] - 2 + uint8_t found_better_split = False + + Y_DTYPE_C best_sum_hessian_left + Y_DTYPE_C best_sum_gradient_left + unsigned int best_bin_idx + unsigned int best_n_samples_left + Y_DTYPE_C best_gain = split_info.gain # computed during previous scan + hist_struct hist + + sum_gradient_right, sum_hessian_right = 0., 0. + n_samples_right = 0 + + loss_current_node = _loss_from_value(value, sum_gradients) + + for bin_idx in range(start, -1, -1): + hist = histograms[feature_idx, bin_idx + 1] + n_samples_right += hist.count + n_samples_left = n_samples_ - n_samples_right + + if self.hessians_are_constant: + sum_hessian_right += hist.count + else: + sum_hessian_right += \ + hist.sum_hessians + sum_hessian_left = sum_hessians - sum_hessian_right + + sum_gradient_right += \ + hist.sum_gradients + sum_gradient_left = sum_gradients - sum_gradient_right + + if n_samples_right < self.min_samples_leaf: + continue + if n_samples_left < self.min_samples_leaf: + # won't get any better + break + + if sum_hessian_right < self.min_hessian_to_split: + continue + if sum_hessian_left < self.min_hessian_to_split: + # won't get any better (hessians are > 0 since loss is convex) + break + + gain = _split_gain(sum_gradient_left, sum_hessian_left, + sum_gradient_right, sum_hessian_right, + loss_current_node, + monotonic_cst, + lower_bound, + upper_bound, + self.l2_regularization) + + if gain > best_gain and gain > self.min_gain_to_split: + found_better_split = True + best_gain = gain + best_bin_idx = bin_idx + best_sum_gradient_left = sum_gradient_left + best_sum_hessian_left = sum_hessian_left + best_n_samples_left = n_samples_left + + if found_better_split: + split_info.gain = best_gain + split_info.bin_idx = best_bin_idx + # we scan from right to left so missing values go to the left + split_info.missing_go_to_left = True + split_info.sum_gradient_left = best_sum_gradient_left + split_info.sum_gradient_right = sum_gradients - best_sum_gradient_left + split_info.sum_hessian_left = best_sum_hessian_left + split_info.sum_hessian_right = sum_hessians - best_sum_hessian_left + split_info.n_samples_left = best_n_samples_left + split_info.n_samples_right = n_samples - best_n_samples_left + + # We recompute best values here but it's cheap + split_info.value_left = compute_node_value( + split_info.sum_gradient_left, split_info.sum_hessian_left, + lower_bound, upper_bound, self.l2_regularization) + + split_info.value_right = compute_node_value( + split_info.sum_gradient_right, split_info.sum_hessian_right, + lower_bound, upper_bound, self.l2_regularization) + + cdef void _find_best_bin_to_split_category( + self, + unsigned int feature_idx, + uint8_t has_missing_values, + const hist_struct [:, ::1] histograms, # IN + unsigned int n_samples, + Y_DTYPE_C sum_gradients, + Y_DTYPE_C sum_hessians, + Y_DTYPE_C value, + char monotonic_cst, + Y_DTYPE_C lower_bound, + Y_DTYPE_C upper_bound, + split_info_struct * split_info) noexcept nogil: # OUT + """Find best split for categorical features. + + Categories are first sorted according to their variance, and then + a scan is performed as if categories were ordered quantities. + + Ref: "On Grouping for Maximum Homogeneity", Walter D. Fisher + """ + + cdef: + unsigned int bin_idx + unsigned int n_bins_non_missing = self.n_bins_non_missing[feature_idx] + unsigned int missing_values_bin_idx = self.missing_values_bin_idx + categorical_info * cat_infos + unsigned int sorted_cat_idx + unsigned int n_used_bins = 0 + int [2] scan_direction + int direction = 0 + int best_direction = 0 + unsigned int middle + unsigned int i + const hist_struct[::1] feature_hist = histograms[feature_idx, :] + hist_struct hist + Y_DTYPE_C sum_gradients_bin + Y_DTYPE_C sum_hessians_bin + Y_DTYPE_C loss_current_node + Y_DTYPE_C sum_gradient_left, sum_hessian_left + Y_DTYPE_C sum_gradient_right, sum_hessian_right + unsigned int n_samples_left, n_samples_right + Y_DTYPE_C gain + Y_DTYPE_C best_gain = -1.0 + uint8_t found_better_split = False + Y_DTYPE_C best_sum_hessian_left + Y_DTYPE_C best_sum_gradient_left + unsigned int best_n_samples_left + unsigned int best_cat_infos_thresh + # Reduces the effect of noises in categorical features, + # especially for categories with few data. Called cat_smooth in + # LightGBM. TODO: Make this user adjustable? + Y_DTYPE_C MIN_CAT_SUPPORT = 10. + # this is equal to 1 for losses where hessians are constant + Y_DTYPE_C support_factor = n_samples / sum_hessians + + # Details on the split finding: + # We first order categories by their sum_gradients / sum_hessians + # values, and we exclude categories that don't respect MIN_CAT_SUPPORT + # from this sorted array. Missing values are treated just like any + # other category. The low-support categories will always be mapped to + # the right child. We scan the sorted categories array from left to + # right and from right to left, and we stop at the middle. + + # Considering ordered categories A B C D, with E being a low-support + # category: A B C D + # ^ + # midpoint + # The scans will consider the following split-points: + # * left to right: + # A - B C D E + # A B - C D E + # * right to left: + # D - A B C E + # C D - A B E + + # Note that since we stop at the middle and since low-support + # categories (E) are always mapped to the right, the following splits + # aren't considered: + # A E - B C D + # D E - A B C + # Basically, we're forcing E to always be mapped to the child that has + # *at least half of the categories* (and this child is always the right + # child, by convention). + + # Also note that if we scanned in only one direction (e.g. left to + # right), we would only consider the following splits: + # A - B C D E + # A B - C D E + # A B C - D E + # and thus we would be missing on D - A B C E and on C D - A B E + + cat_infos = malloc( + (n_bins_non_missing + has_missing_values) * sizeof(categorical_info)) + + # fill cat_infos while filtering out categories based on MIN_CAT_SUPPORT + for bin_idx in range(n_bins_non_missing): + hist = feature_hist[bin_idx] + if self.hessians_are_constant: + sum_hessians_bin = hist.count + else: + sum_hessians_bin = hist.sum_hessians + if sum_hessians_bin * support_factor >= MIN_CAT_SUPPORT: + cat_infos[n_used_bins].bin_idx = bin_idx + sum_gradients_bin = hist.sum_gradients + + cat_infos[n_used_bins].value = ( + sum_gradients_bin / (sum_hessians_bin + MIN_CAT_SUPPORT) + ) + n_used_bins += 1 + + # Also add missing values bin so that nans are considered as a category + if has_missing_values: + hist = feature_hist[missing_values_bin_idx] + if self.hessians_are_constant: + sum_hessians_bin = hist.count + else: + sum_hessians_bin = hist.sum_hessians + if sum_hessians_bin * support_factor >= MIN_CAT_SUPPORT: + cat_infos[n_used_bins].bin_idx = missing_values_bin_idx + sum_gradients_bin = ( + hist.sum_gradients + ) + + cat_infos[n_used_bins].value = ( + sum_gradients_bin / (sum_hessians_bin + MIN_CAT_SUPPORT) + ) + n_used_bins += 1 + + # not enough categories to form a split + if n_used_bins <= 1: + free(cat_infos) + return + + qsort(cat_infos, n_used_bins, sizeof(categorical_info), + compare_cat_infos) + + loss_current_node = _loss_from_value(value, sum_gradients) + + scan_direction[0], scan_direction[1] = 1, -1 + for direction in scan_direction: + if direction == 1: + middle = (n_used_bins + 1) // 2 + else: + middle = (n_used_bins + 1) // 2 - 1 + + # The categories we'll consider will go to the left child + sum_gradient_left, sum_hessian_left = 0., 0. + n_samples_left = 0 + + for i in range(middle): + sorted_cat_idx = i if direction == 1 else n_used_bins - 1 - i + bin_idx = cat_infos[sorted_cat_idx].bin_idx + hist = feature_hist[bin_idx] + + n_samples_left += hist.count + n_samples_right = n_samples - n_samples_left + + if self.hessians_are_constant: + sum_hessian_left += hist.count + else: + sum_hessian_left += hist.sum_hessians + sum_hessian_right = sum_hessians - sum_hessian_left + + sum_gradient_left += hist.sum_gradients + sum_gradient_right = sum_gradients - sum_gradient_left + + if ( + n_samples_left < self.min_samples_leaf or + sum_hessian_left < self.min_hessian_to_split + ): + continue + if ( + n_samples_right < self.min_samples_leaf or + sum_hessian_right < self.min_hessian_to_split + ): + break + + gain = _split_gain(sum_gradient_left, sum_hessian_left, + sum_gradient_right, sum_hessian_right, + loss_current_node, monotonic_cst, + lower_bound, upper_bound, + self.l2_regularization) + if gain > best_gain and gain > self.min_gain_to_split: + found_better_split = True + best_gain = gain + best_cat_infos_thresh = sorted_cat_idx + best_sum_gradient_left = sum_gradient_left + best_sum_hessian_left = sum_hessian_left + best_n_samples_left = n_samples_left + best_direction = direction + + if found_better_split: + split_info.gain = best_gain + + # split_info.bin_idx is unused for categorical splits: left_cat_bitset + # is used instead and set below + split_info.bin_idx = 0 + + split_info.sum_gradient_left = best_sum_gradient_left + split_info.sum_gradient_right = sum_gradients - best_sum_gradient_left + split_info.sum_hessian_left = best_sum_hessian_left + split_info.sum_hessian_right = sum_hessians - best_sum_hessian_left + split_info.n_samples_left = best_n_samples_left + split_info.n_samples_right = n_samples - best_n_samples_left + + # We recompute best values here but it's cheap + split_info.value_left = compute_node_value( + split_info.sum_gradient_left, split_info.sum_hessian_left, + lower_bound, upper_bound, self.l2_regularization) + + split_info.value_right = compute_node_value( + split_info.sum_gradient_right, split_info.sum_hessian_right, + lower_bound, upper_bound, self.l2_regularization) + + # create bitset with values from best_cat_infos_thresh + init_bitset(split_info.left_cat_bitset) + if best_direction == 1: + for sorted_cat_idx in range(best_cat_infos_thresh + 1): + bin_idx = cat_infos[sorted_cat_idx].bin_idx + set_bitset(split_info.left_cat_bitset, bin_idx) + else: + for sorted_cat_idx in range(n_used_bins - 1, best_cat_infos_thresh - 1, -1): + bin_idx = cat_infos[sorted_cat_idx].bin_idx + set_bitset(split_info.left_cat_bitset, bin_idx) + + if has_missing_values: + split_info.missing_go_to_left = in_bitset( + split_info.left_cat_bitset, missing_values_bin_idx) + + free(cat_infos) + + +cdef int compare_cat_infos(const void * a, const void * b) noexcept nogil: + return -1 if (a).value < (b).value else 1 + +cdef inline Y_DTYPE_C _split_gain( + Y_DTYPE_C sum_gradient_left, + Y_DTYPE_C sum_hessian_left, + Y_DTYPE_C sum_gradient_right, + Y_DTYPE_C sum_hessian_right, + Y_DTYPE_C loss_current_node, + signed char monotonic_cst, + Y_DTYPE_C lower_bound, + Y_DTYPE_C upper_bound, + Y_DTYPE_C l2_regularization) noexcept nogil: + """Loss reduction + + Compute the reduction in loss after taking a split, compared to keeping + the node a leaf of the tree. + + See Equation 7 of: + :arxiv:`T. Chen, C. Guestrin, (2016) XGBoost: A Scalable Tree Boosting System, + <1603.02754>.` + """ + cdef: + Y_DTYPE_C gain + Y_DTYPE_C value_left + Y_DTYPE_C value_right + + # Compute values of potential left and right children + value_left = compute_node_value(sum_gradient_left, sum_hessian_left, + lower_bound, upper_bound, + l2_regularization) + value_right = compute_node_value(sum_gradient_right, sum_hessian_right, + lower_bound, upper_bound, + l2_regularization) + + if ((monotonic_cst == MonotonicConstraint.POS and value_left > value_right) or + (monotonic_cst == MonotonicConstraint.NEG and value_left < value_right)): + # don't consider this split since it does not respect the monotonic + # constraints. Note that these comparisons need to be done on values + # that have already been clipped to take the monotonic constraints into + # account (if any). + return -1 + + gain = loss_current_node + gain -= _loss_from_value(value_left, sum_gradient_left) + gain -= _loss_from_value(value_right, sum_gradient_right) + # Note that for the gain to be correct (and for min_gain_to_split to work + # as expected), we need all values to be bounded (current node, left child + # and right child). + + return gain + +cdef inline Y_DTYPE_C _loss_from_value( + Y_DTYPE_C value, + Y_DTYPE_C sum_gradient) noexcept nogil: + """Return loss of a node from its (bounded) value + + See Equation 6 of: + :arxiv:`T. Chen, C. Guestrin, (2016) XGBoost: A Scalable Tree Boosting System, + <1603.02754>.` + """ + return sum_gradient * value + +cdef inline uint8_t sample_goes_left( + uint8_t missing_go_to_left, + uint8_t missing_values_bin_idx, + X_BINNED_DTYPE_C split_bin_idx, + X_BINNED_DTYPE_C bin_value, + uint8_t is_categorical, + BITSET_DTYPE_C left_cat_bitset) noexcept nogil: + """Helper to decide whether sample should go to left or right child.""" + + if is_categorical: + # note: if any, missing values are encoded in left_cat_bitset + return in_bitset(left_cat_bitset, bin_value) + else: + return ( + ( + missing_go_to_left and + bin_value == missing_values_bin_idx + ) + or ( + bin_value <= split_bin_idx + )) + + +cpdef inline Y_DTYPE_C compute_node_value( + Y_DTYPE_C sum_gradient, + Y_DTYPE_C sum_hessian, + Y_DTYPE_C lower_bound, + Y_DTYPE_C upper_bound, + Y_DTYPE_C l2_regularization) noexcept nogil: + """Compute a node's value. + + The value is capped in the [lower_bound, upper_bound] interval to respect + monotonic constraints. Shrinkage is ignored. + + See Equation 5 of: + :arxiv:`T. Chen, C. Guestrin, (2016) XGBoost: A Scalable Tree Boosting System, + <1603.02754>.` + """ + + cdef: + Y_DTYPE_C value + + value = -sum_gradient / (sum_hessian + l2_regularization + 1e-15) + + if value < lower_bound: + value = lower_bound + elif value > upper_bound: + value = upper_bound + + return value diff --git a/shared/package-files/79/79d210510630052adafcc7c4ad8cf16acd2fd8e9adb46deea952cd81bfbea661/blob b/shared/package-files/79/79d210510630052adafcc7c4ad8cf16acd2fd8e9adb46deea952cd81bfbea661/blob new file mode 100644 index 0000000000000000000000000000000000000000..ff76ba340470729f7e44ec2ce19afc7cc1ca931a --- /dev/null +++ b/shared/package-files/79/79d210510630052adafcc7c4ad8cf16acd2fd8e9adb46deea952cd81bfbea661/blob @@ -0,0 +1,281 @@ +"Utility functions used by the btm_matcher module" + +from . import pytree +from .pgen2 import grammar, token +from .pygram import pattern_symbols, python_symbols + +syms = pattern_symbols +pysyms = python_symbols +tokens = grammar.opmap +token_labels = token + +TYPE_ANY = -1 +TYPE_ALTERNATIVES = -2 +TYPE_GROUP = -3 + +class MinNode(object): + """This class serves as an intermediate representation of the + pattern tree during the conversion to sets of leaf-to-root + subpatterns""" + + def __init__(self, type=None, name=None): + self.type = type + self.name = name + self.children = [] + self.leaf = False + self.parent = None + self.alternatives = [] + self.group = [] + + def __repr__(self): + return str(self.type) + ' ' + str(self.name) + + def leaf_to_root(self): + """Internal method. Returns a characteristic path of the + pattern tree. This method must be run for all leaves until the + linear subpatterns are merged into a single""" + node = self + subp = [] + while node: + if node.type == TYPE_ALTERNATIVES: + node.alternatives.append(subp) + if len(node.alternatives) == len(node.children): + #last alternative + subp = [tuple(node.alternatives)] + node.alternatives = [] + node = node.parent + continue + else: + node = node.parent + subp = None + break + + if node.type == TYPE_GROUP: + node.group.append(subp) + #probably should check the number of leaves + if len(node.group) == len(node.children): + subp = get_characteristic_subpattern(node.group) + node.group = [] + node = node.parent + continue + else: + node = node.parent + subp = None + break + + if node.type == token_labels.NAME and node.name: + #in case of type=name, use the name instead + subp.append(node.name) + else: + subp.append(node.type) + + node = node.parent + return subp + + def get_linear_subpattern(self): + """Drives the leaf_to_root method. The reason that + leaf_to_root must be run multiple times is because we need to + reject 'group' matches; for example the alternative form + (a | b c) creates a group [b c] that needs to be matched. Since + matching multiple linear patterns overcomes the automaton's + capabilities, leaf_to_root merges each group into a single + choice based on 'characteristic'ity, + + i.e. (a|b c) -> (a|b) if b more characteristic than c + + Returns: The most 'characteristic'(as defined by + get_characteristic_subpattern) path for the compiled pattern + tree. + """ + + for l in self.leaves(): + subp = l.leaf_to_root() + if subp: + return subp + + def leaves(self): + "Generator that returns the leaves of the tree" + for child in self.children: + yield from child.leaves() + if not self.children: + yield self + +def reduce_tree(node, parent=None): + """ + Internal function. Reduces a compiled pattern tree to an + intermediate representation suitable for feeding the + automaton. This also trims off any optional pattern elements(like + [a], a*). + """ + + new_node = None + #switch on the node type + if node.type == syms.Matcher: + #skip + node = node.children[0] + + if node.type == syms.Alternatives : + #2 cases + if len(node.children) <= 2: + #just a single 'Alternative', skip this node + new_node = reduce_tree(node.children[0], parent) + else: + #real alternatives + new_node = MinNode(type=TYPE_ALTERNATIVES) + #skip odd children('|' tokens) + for child in node.children: + if node.children.index(child)%2: + continue + reduced = reduce_tree(child, new_node) + if reduced is not None: + new_node.children.append(reduced) + elif node.type == syms.Alternative: + if len(node.children) > 1: + + new_node = MinNode(type=TYPE_GROUP) + for child in node.children: + reduced = reduce_tree(child, new_node) + if reduced: + new_node.children.append(reduced) + if not new_node.children: + # delete the group if all of the children were reduced to None + new_node = None + + else: + new_node = reduce_tree(node.children[0], parent) + + elif node.type == syms.Unit: + if (isinstance(node.children[0], pytree.Leaf) and + node.children[0].value == '('): + #skip parentheses + return reduce_tree(node.children[1], parent) + if ((isinstance(node.children[0], pytree.Leaf) and + node.children[0].value == '[') + or + (len(node.children)>1 and + hasattr(node.children[1], "value") and + node.children[1].value == '[')): + #skip whole unit if its optional + return None + + leaf = True + details_node = None + alternatives_node = None + has_repeater = False + repeater_node = None + has_variable_name = False + + for child in node.children: + if child.type == syms.Details: + leaf = False + details_node = child + elif child.type == syms.Repeater: + has_repeater = True + repeater_node = child + elif child.type == syms.Alternatives: + alternatives_node = child + if hasattr(child, 'value') and child.value == '=': # variable name + has_variable_name = True + + #skip variable name + if has_variable_name: + #skip variable name, '=' + name_leaf = node.children[2] + if hasattr(name_leaf, 'value') and name_leaf.value == '(': + # skip parenthesis + name_leaf = node.children[3] + else: + name_leaf = node.children[0] + + #set node type + if name_leaf.type == token_labels.NAME: + #(python) non-name or wildcard + if name_leaf.value == 'any': + new_node = MinNode(type=TYPE_ANY) + else: + if hasattr(token_labels, name_leaf.value): + new_node = MinNode(type=getattr(token_labels, name_leaf.value)) + else: + new_node = MinNode(type=getattr(pysyms, name_leaf.value)) + + elif name_leaf.type == token_labels.STRING: + #(python) name or character; remove the apostrophes from + #the string value + name = name_leaf.value.strip("'") + if name in tokens: + new_node = MinNode(type=tokens[name]) + else: + new_node = MinNode(type=token_labels.NAME, name=name) + elif name_leaf.type == syms.Alternatives: + new_node = reduce_tree(alternatives_node, parent) + + #handle repeaters + if has_repeater: + if repeater_node.children[0].value == '*': + #reduce to None + new_node = None + elif repeater_node.children[0].value == '+': + #reduce to a single occurrence i.e. do nothing + pass + else: + #TODO: handle {min, max} repeaters + raise NotImplementedError + pass + + #add children + if details_node and new_node is not None: + for child in details_node.children[1:-1]: + #skip '<', '>' markers + reduced = reduce_tree(child, new_node) + if reduced is not None: + new_node.children.append(reduced) + if new_node: + new_node.parent = parent + return new_node + + +def get_characteristic_subpattern(subpatterns): + """Picks the most characteristic from a list of linear patterns + Current order used is: + names > common_names > common_chars + """ + if not isinstance(subpatterns, list): + return subpatterns + if len(subpatterns)==1: + return subpatterns[0] + + # first pick out the ones containing variable names + subpatterns_with_names = [] + subpatterns_with_common_names = [] + common_names = ['in', 'for', 'if' , 'not', 'None'] + subpatterns_with_common_chars = [] + common_chars = "[]().,:" + for subpattern in subpatterns: + if any(rec_test(subpattern, lambda x: type(x) is str)): + if any(rec_test(subpattern, + lambda x: isinstance(x, str) and x in common_chars)): + subpatterns_with_common_chars.append(subpattern) + elif any(rec_test(subpattern, + lambda x: isinstance(x, str) and x in common_names)): + subpatterns_with_common_names.append(subpattern) + + else: + subpatterns_with_names.append(subpattern) + + if subpatterns_with_names: + subpatterns = subpatterns_with_names + elif subpatterns_with_common_names: + subpatterns = subpatterns_with_common_names + elif subpatterns_with_common_chars: + subpatterns = subpatterns_with_common_chars + # of the remaining subpatterns pick out the longest one + return max(subpatterns, key=len) + +def rec_test(sequence, test_func): + """Tests test_func on all items of sequence and items of included + sub-iterables""" + for x in sequence: + if isinstance(x, (list, tuple)): + yield from rec_test(x, test_func) + else: + yield test_func(x) diff --git a/shared/package-files/79/79d62935bc7eb8fc0cbab5f7a668236d14c697287e7173d455be21ba9d6fd0a5/blob b/shared/package-files/79/79d62935bc7eb8fc0cbab5f7a668236d14c697287e7173d455be21ba9d6fd0a5/blob new file mode 100644 index 0000000000000000000000000000000000000000..18eef869028c4ec0effcba10682a5b0aed7fd6cd --- /dev/null +++ b/shared/package-files/79/79d62935bc7eb8fc0cbab5f7a668236d14c697287e7173d455be21ba9d6fd0a5/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor diag(const at::Tensor & self, int64_t diagonal=0); +TORCH_API at::Tensor & diag_out(at::Tensor & out, const at::Tensor & self, int64_t diagonal=0); +TORCH_API at::Tensor & diag_outf(const at::Tensor & self, int64_t diagonal, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/79/79d7a09c800a6a435d497bbae0e2c1afb3ce80d41417634394e84aeb2e407edc/blob b/shared/package-files/79/79d7a09c800a6a435d497bbae0e2c1afb3ce80d41417634394e84aeb2e407edc/blob new file mode 100644 index 0000000000000000000000000000000000000000..657b6a93014f428eece18ec896136c81bc3949f3 --- /dev/null +++ b/shared/package-files/79/79d7a09c800a6a435d497bbae0e2c1afb3ce80d41417634394e84aeb2e407edc/blob @@ -0,0 +1,2 @@ + +from . import pass_manager diff --git a/shared/package-files/79/79d8b62522a92c26a9aa2af4016fc28e91ed8a7444de17fa683939f951e080b9/blob b/shared/package-files/79/79d8b62522a92c26a9aa2af4016fc28e91ed8a7444de17fa683939f951e080b9/blob new file mode 100644 index 0000000000000000000000000000000000000000..aef2821b83f6ac1730d063d8ce939134cc2105a7 --- /dev/null +++ b/shared/package-files/79/79d8b62522a92c26a9aa2af4016fc28e91ed8a7444de17fa683939f951e080b9/blob @@ -0,0 +1,342 @@ +""" +Utilities for determining application-specific dirs. See for details and +usage. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +if sys.version_info >= (3, 8): # pragma: no cover (py38+) + from typing import Literal +else: # pragma: no cover (py38+) + from ..typing_extensions import Literal + +from .api import PlatformDirsABC +from .version import __version__ +from .version import __version_tuple__ as __version_info__ + + +def _set_platform_dir_class() -> type[PlatformDirsABC]: + if sys.platform == "win32": + from .windows import Windows as Result + elif sys.platform == "darwin": + from .macos import MacOS as Result + else: + from .unix import Unix as Result + + if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system": + + if os.getenv("SHELL") or os.getenv("PREFIX"): + return Result + + from .android import _android_folder + + if _android_folder() is not None: + from .android import Android + + return Android # return to avoid redefinition of result + + return Result + + +PlatformDirs = _set_platform_dir_class() #: Currently active platform +AppDirs = PlatformDirs #: Backwards compatibility with appdirs + + +def user_data_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param roaming: See `roaming `. + :returns: data directory tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_data_dir + + +def site_data_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + multipath: bool = False, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param multipath: See `roaming `. + :returns: data directory shared by users + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_data_dir + + +def user_config_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param roaming: See `roaming `. + :returns: config directory tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_config_dir + + +def site_config_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + multipath: bool = False, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param multipath: See `roaming `. + :returns: config directory shared by the users + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_config_dir + + +def user_cache_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + opinion: bool = True, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param opinion: See `roaming `. + :returns: cache directory tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_cache_dir + + +def user_state_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param roaming: See `roaming `. + :returns: state directory tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_state_dir + + +def user_log_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + opinion: bool = True, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param opinion: See `roaming `. + :returns: log directory tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_log_dir + + +def user_documents_dir() -> str: + """ + :returns: documents directory tied to the user + """ + return PlatformDirs().user_documents_dir + + +def user_runtime_dir( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + opinion: bool = True, +) -> str: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param opinion: See `opinion `. + :returns: runtime directory tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_runtime_dir + + +def user_data_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param roaming: See `roaming `. + :returns: data path tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_data_path + + +def site_data_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + multipath: bool = False, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param multipath: See `multipath `. + :returns: data path shared by users + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_data_path + + +def user_config_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param roaming: See `roaming `. + :returns: config path tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_config_path + + +def site_config_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + multipath: bool = False, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param multipath: See `roaming `. + :returns: config path shared by the users + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_config_path + + +def user_cache_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + opinion: bool = True, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param opinion: See `roaming `. + :returns: cache path tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_cache_path + + +def user_state_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param roaming: See `roaming `. + :returns: state path tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_state_path + + +def user_log_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + opinion: bool = True, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param opinion: See `roaming `. + :returns: log path tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_log_path + + +def user_documents_path() -> Path: + """ + :returns: documents path tied to the user + """ + return PlatformDirs().user_documents_path + + +def user_runtime_path( + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + opinion: bool = True, +) -> Path: + """ + :param appname: See `appname `. + :param appauthor: See `appauthor `. + :param version: See `version `. + :param opinion: See `opinion `. + :returns: runtime path tied to the user + """ + return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_runtime_path + + +__all__ = [ + "__version__", + "__version_info__", + "PlatformDirs", + "AppDirs", + "PlatformDirsABC", + "user_data_dir", + "user_config_dir", + "user_cache_dir", + "user_state_dir", + "user_log_dir", + "user_documents_dir", + "user_runtime_dir", + "site_data_dir", + "site_config_dir", + "user_data_path", + "user_config_path", + "user_cache_path", + "user_state_path", + "user_log_path", + "user_documents_path", + "user_runtime_path", + "site_data_path", + "site_config_path", +] diff --git a/shared/package-files/79/79d96dc55fc2f7d63d091f73a58fb8610899ff0597e1351afce7e4fabdde33f1/blob b/shared/package-files/79/79d96dc55fc2f7d63d091f73a58fb8610899ff0597e1351afce7e4fabdde33f1/blob new file mode 100644 index 0000000000000000000000000000000000000000..bfaf5b93d667bf6286561cf72c3fb5c487cc1704 --- /dev/null +++ b/shared/package-files/79/79d96dc55fc2f7d63d091f73a58fb8610899ff0597e1351afce7e4fabdde33f1/blob @@ -0,0 +1,411 @@ +#pragma once + +#include +#include +#include +#include +#include + +#ifdef USE_FBGEMM +#include +#include +#include + +// The struct for the packed weight matrix (PackBMatrix) and the corresponding +// column offsets used for the fully connect layer, which are both prepared in +// the prepacking step to save the computations in the inference. Note the +// column offsets include the sum of the B columns as well as the scalar term +// B_zero_point * K, whereas the row offsets created by +// PackAWithQuantRowOffset/PackAWithIm2Col/PackAWithRowOffset are only the sum +// of the A rows. The column offsets are needed for the asymmetric quantization +// (affine quantization) of input matrix. +// Note that in JIT mode we can think of a way to fuse col_offsets with bias. +struct TORCH_API PackedLinearWeight : public LinearPackedParamsBase { + PackedLinearWeight( + std::unique_ptr> w, + c10::optional bias, + std::vector col_offsets, + std::vector w_scale, + std::vector w_zp, + c10::QScheme q_scheme) + : w(std::move(w)), + bias_(std::move(bias)), + col_offsets(std::move(col_offsets)), + w_scale(std::move(w_scale)), + w_zp(std::move(w_zp)), + q_scheme(std::move(q_scheme)) {} + std::unique_ptr> w; + c10::optional bias_; + std::vector col_offsets; + std::vector w_scale; + std::vector w_zp; + c10::QScheme q_scheme; + + at::Tensor apply( + at::Tensor input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_relu( + at::Tensor input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor& apply_out( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point, + at::Tensor& output) override; + + at::Tensor& apply_relu_out( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point, + at::Tensor& output) override; + + at::Tensor apply_with_input_q_dq_qweight_dq_output_fp32( + at::Tensor input, + double input_scale, + int64_t input_zero_point) override; + + at::Tensor apply_with_input_q_dq_qweight_dq_relu_output_fp32( + at::Tensor input, + double input_scale, + int64_t input_zero_point) override; + + at::Tensor apply_dynamic(at::Tensor input, bool reduce_range = false) + override; + + at::Tensor apply_dynamic_relu(at::Tensor input, bool reduce_range = false) + override; + + std::tuple> unpack() override; + + c10::optional bias() override { + return bias_; + } + + static c10::intrusive_ptr prepack( + at::Tensor weight, + c10::optional bias); + + private: + template + at::Tensor& apply_impl( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point, + at::Tensor& output); + + template + at::Tensor apply_with_input_q_dq_qweight_dq_output_fp32_impl( + const at::Tensor& input, + double input_scale, + int64_t input_zero_point); + + template + at::Tensor apply_dynamic_impl(at::Tensor input, bool reduce_range = false); +}; + +struct TORCH_API PackedLinearWeightFp16 : public LinearPackedParamsBase { + PackedLinearWeightFp16( + std::unique_ptr w, + c10::optional bias) + : w(std::move(w)), bias_(std::move(bias)) {} + + std::unique_ptr w; + c10::optional bias_; + + at::Tensor apply( + at::Tensor /*input*/, + double /*output_scale*/, + int64_t /*output_zero_point*/) override { + TORCH_INTERNAL_ASSERT(false); + } + at::Tensor apply_relu( + at::Tensor /*input*/, + double /*output_scale*/, + int64_t /*output_zero_point*/) override { + TORCH_INTERNAL_ASSERT(false); + } + + at::Tensor apply_dynamic(at::Tensor input, bool reduce_range = false) + override; + at::Tensor apply_dynamic_relu(at::Tensor input, bool reduce_range = false) + override; + + at::Tensor& apply_dynamic_out( + const at::Tensor& input, + at::Tensor& output, + bool reduce_range = false) override; + at::Tensor& apply_dynamic_relu_out( + const at::Tensor& input, + at::Tensor& output, + bool reduce_range = false) override; + + std::tuple> unpack() override; + + c10::optional bias() override { + return bias_; + } + + static c10::intrusive_ptr prepack( + at::Tensor weight, + c10::optional bias); + + void set_bias(c10::optional bias) override; + + private: + template + at::Tensor& apply_dynamic_impl(const at::Tensor& input, at::Tensor& output); +}; + +template +struct TORCH_API PackedConvWeight : public ConvPackedParamsBase { + PackedConvWeight( + std::unique_ptr> w, + c10::optional bias, + torch::List stride, + torch::List padding, + torch::List output_padding, + torch::List dilation, + int64_t groups, + uint8_t transpose, + std::vector col_offsets, + std::vector kernel, + std::vector w_scale, + std::vector w_zp, + c10::QScheme q_scheme) + : w(std::move(w)), + bias(std::move(bias)), + stride_(std::move(stride)), + padding_(std::move(padding)), + output_padding_(std::move(output_padding)), + dilation_(std::move(dilation)), + groups_(groups), + transpose_(transpose), + col_offsets(std::move(col_offsets)), + kernel(std::move(kernel)), + w_scale(std::move(w_scale)), + w_zp(std::move(w_zp)), + q_scheme(q_scheme) {} + + std::unique_ptr> w; + c10::optional bias; + torch::List stride_; + torch::List padding_; + torch::List output_padding_; + torch::List dilation_; + int64_t groups_; + uint8_t transpose_; + std::vector col_offsets; + std::vector kernel; + std::vector w_scale; + std::vector w_zp; + c10::QScheme q_scheme; + + at::Tensor apply( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_relu( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_dynamic( + const at::Tensor& input, + bool reduce_range) override; + + std::tuple> unpack() override; + + static c10::intrusive_ptr> prepack( + at::Tensor weight, + c10::optional bias, + torch::List stride, + torch::List padding, + torch::List output_padding, + torch::List dilation, + int64_t groups, + bool transpose); + + const float* GetBiasData(at::Tensor* bias); + + void GetQuantizationParams( + float act_scale, + float out_scale, + std::vector* output_multiplier_float, + std::vector* act_times_w_scale); + + torch::List stride() const override { + return stride_; + } + + torch::List padding() const override { + return padding_; + } + + torch::List output_padding() const override { + return output_padding_; + } + + torch::List dilation() const override { + return dilation_; + } + + int64_t groups() const override { + return groups_; + } + + bool transpose() const override { + return (bool)transpose_; + } + + private: + template + at::Tensor apply_impl( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point); +}; + +// PackWeight: Convert the weight from uint8 to int8. +inline void convert_uint8_int8( + int len, + const uint8_t* src_uint8, + int8_t* dst_int8) { + for (const auto i : c10::irange(len)) { + dst_int8[i] = static_cast(static_cast(src_uint8[i]) - 128); + } +} + +// UnpackWeight: Convert the weight from int8 to uint8. +inline void convert_int8_uint8( + int len, + const int8_t* src_int8, + uint8_t* dst_uint8) { + for (const auto i : c10::irange(len)) { + dst_uint8[i] = + static_cast(static_cast(src_int8[i]) + 128); + } +} + +namespace at { +namespace native { +namespace fbgemm_utils { + +template +fbgemm::conv_param_t MakeFbgemmConvParam( + int N, + int C, + int M, + const std::vector& image_shape, + int groups, + const std::vector& kernels, + const std::vector& strides, + const std::vector& pads, + const std::vector& dilations, + const std::vector& output_padding = std::vector(kSpatialDim, 0), + bool transposed = false); + +// TODO: Remove functions below when ChannelsLast3d is ready. +Tensor MakeStridedQTensorCPU( + const IntArrayRef& sizes, + const IntArrayRef& strides, + const TensorOptions& options, + QuantizerPtr quantizer); + +Tensor MakeEmptyAffineQuantizedChannelsLast3dTensor( + int64_t N, + int64_t C, + int64_t D, + int64_t H, + int64_t W, + const TensorOptions& options, + double scale, + int64_t zero_point); + +Tensor MakeEmptyPerChannelAffineQuantizedChannelsLast3dTensor( + int64_t N, + int64_t C, + int64_t D, + int64_t H, + int64_t W, + const TensorOptions& options, + const Tensor& scales, + const Tensor& zero_points); + +Tensor ConvertToChannelsLast3dTensor(const Tensor& src); + +template +Tensor TransposeConvTensorUnpackConversion(const Tensor& src, int groups); + +template +Tensor ConvertConvWeightsToChannelLastTensor( + const at::Tensor& src, + int groups, + bool transpose); +} // namespace fbgemm_utils +} // namespace native +} // namespace at + +#endif // USE_FBGEMM + +struct TORCH_API PackedEmbeddingBagWeight : public EmbeddingPackedParamsBase { + PackedEmbeddingBagWeight( + at::Tensor packed_w, + std::vector w_scale, + std::vector w_zp, + int64_t bit_rate, + c10::QScheme q_scheme, + int64_t version) + : packed_w(std::move(packed_w)), + w_scale(std::move(w_scale)), + w_zp(std::move(w_zp)), + bit_rate_(bit_rate), + q_scheme(q_scheme), + version_(version) { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.Move) + if (!packed_w.is_contiguous()) { + packed_w = packed_w.contiguous(); + } + } + + at::Tensor packed_w; + std::vector w_scale; + std::vector w_zp; + int64_t bit_rate_; + c10::QScheme q_scheme; + int64_t version_; + + at::Tensor unpack() override; + static c10::intrusive_ptr prepack( + at::Tensor weight); + + int64_t bit_rate() const override { + return bit_rate_; + } + + int64_t version() const override { + return version_; + } + + at::Tensor embeddingbag_byte( + const at::Tensor& indices, + const c10::optional& offsets, + bool pruned_weights, + const c10::optional& per_sample_weights_, + const c10::optional& compressed_indices_mapping, + bool include_last_offset, + bool is_embedding_op) override; + + at::Tensor embeddingbag_4bit( + const at::Tensor& indices, + const c10::optional& offsets, + bool pruned_weights, + const c10::optional& per_sample_weights_, + const c10::optional& compressed_indices_mapping, + bool include_last_offset, + bool is_embedding_op) override; +}; diff --git a/shared/package-files/79/79d990707cadcc65f8d2b78abf94825f80c3999ccab001eba6b3c55ea09b4158/blob b/shared/package-files/79/79d990707cadcc65f8d2b78abf94825f80c3999ccab001eba6b3c55ea09b4158/blob new file mode 100644 index 0000000000000000000000000000000000000000..67bf8e6c780f89f6609ead91b4675ccf97af1ed1 --- /dev/null +++ b/shared/package-files/79/79d990707cadcc65f8d2b78abf94825f80c3999ccab001eba6b3c55ea09b4158/blob @@ -0,0 +1,105 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API bitwise_right_shift_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_right_shift__Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_right_shift_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API bitwise_right_shift_Tensor_Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API bitwise_right_shift__Tensor_Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API bitwise_right_shift_Tensor_Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +struct TORCH_API bitwise_right_shift_Scalar_Tensor { + using schema = at::Tensor (const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor") + static at::Tensor call(const at::Scalar & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other); +}; + +struct TORCH_API bitwise_right_shift_Scalar_Tensor_out { + using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_right_shift") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_right_shift.Scalar_Tensor_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/79/79dc96a251c4a774f3b751f208b6dfaf54fdbc2b45e797b5f560fe5a3b8db0dc/blob b/shared/package-files/79/79dc96a251c4a774f3b751f208b6dfaf54fdbc2b45e797b5f560fe5a3b8db0dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..5e3a67d5363fdd7333217df1256c29df58df8665 --- /dev/null +++ b/shared/package-files/79/79dc96a251c4a774f3b751f208b6dfaf54fdbc2b45e797b5f560fe5a3b8db0dc/blob @@ -0,0 +1,2394 @@ +from __future__ import annotations + +from collections.abc import ( + Hashable, + Sequence, +) +import itertools +from typing import ( + TYPE_CHECKING, + Callable, + Literal, + cast, +) +import warnings + +import numpy as np + +from pandas._config import ( + using_copy_on_write, + warn_copy_on_write, +) + +from pandas._libs import ( + internals as libinternals, + lib, +) +from pandas._libs.internals import ( + BlockPlacement, + BlockValuesRefs, +) +from pandas._libs.tslibs import Timestamp +from pandas.errors import PerformanceWarning +from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.cast import infer_dtype_from_scalar +from pandas.core.dtypes.common import ( + ensure_platform_int, + is_1d_only_ea_dtype, + is_list_like, +) +from pandas.core.dtypes.dtypes import ( + DatetimeTZDtype, + ExtensionDtype, +) +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCSeries, +) +from pandas.core.dtypes.missing import ( + array_equals, + isna, +) + +import pandas.core.algorithms as algos +from pandas.core.arrays import ( + ArrowExtensionArray, + ArrowStringArray, + DatetimeArray, +) +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, +) +from pandas.core.indexers import maybe_convert_indices +from pandas.core.indexes.api import ( + Index, + ensure_index, +) +from pandas.core.internals.base import ( + DataManager, + SingleDataManager, + ensure_np_dtype, + interleaved_dtype, +) +from pandas.core.internals.blocks import ( + COW_WARNING_GENERAL_MSG, + COW_WARNING_SETITEM_MSG, + Block, + NumpyBlock, + ensure_block_shape, + extend_blocks, + get_block_type, + maybe_coerce_values, + new_block, + new_block_2d, +) +from pandas.core.internals.ops import ( + blockwise_all, + operate_blockwise, +) + +if TYPE_CHECKING: + from pandas._typing import ( + ArrayLike, + AxisInt, + DtypeObj, + QuantileInterpolation, + Self, + Shape, + npt, + ) + + from pandas.api.extensions import ExtensionArray + + +class BaseBlockManager(DataManager): + """ + Core internal data structure to implement DataFrame, Series, etc. + + Manage a bunch of labeled 2D mixed-type ndarrays. Essentially it's a + lightweight blocked set of labeled data to be manipulated by the DataFrame + public API class + + Attributes + ---------- + shape + ndim + axes + values + items + + Methods + ------- + set_axis(axis, new_labels) + copy(deep=True) + + get_dtypes + + apply(func, axes, block_filter_fn) + + get_bool_data + get_numeric_data + + get_slice(slice_like, axis) + get(label) + iget(loc) + + take(indexer, axis) + reindex_axis(new_labels, axis) + reindex_indexer(new_labels, indexer, axis) + + delete(label) + insert(loc, label, value) + set(label, value) + + Parameters + ---------- + blocks: Sequence of Block + axes: Sequence of Index + verify_integrity: bool, default True + + Notes + ----- + This is *not* a public API class + """ + + __slots__ = () + + _blknos: npt.NDArray[np.intp] + _blklocs: npt.NDArray[np.intp] + blocks: tuple[Block, ...] + axes: list[Index] + + @property + def ndim(self) -> int: + raise NotImplementedError + + _known_consolidated: bool + _is_consolidated: bool + + def __init__(self, blocks, axes, verify_integrity: bool = True) -> None: + raise NotImplementedError + + @classmethod + def from_blocks(cls, blocks: list[Block], axes: list[Index]) -> Self: + raise NotImplementedError + + @property + def blknos(self) -> npt.NDArray[np.intp]: + """ + Suppose we want to find the array corresponding to our i'th column. + + blknos[i] identifies the block from self.blocks that contains this column. + + blklocs[i] identifies the column of interest within + self.blocks[self.blknos[i]] + """ + if self._blknos is None: + # Note: these can be altered by other BlockManager methods. + self._rebuild_blknos_and_blklocs() + + return self._blknos + + @property + def blklocs(self) -> npt.NDArray[np.intp]: + """ + See blknos.__doc__ + """ + if self._blklocs is None: + # Note: these can be altered by other BlockManager methods. + self._rebuild_blknos_and_blklocs() + + return self._blklocs + + def make_empty(self, axes=None) -> Self: + """return an empty BlockManager with the items axis of len 0""" + if axes is None: + axes = [Index([])] + self.axes[1:] + + # preserve dtype if possible + if self.ndim == 1: + assert isinstance(self, SingleBlockManager) # for mypy + blk = self.blocks[0] + arr = blk.values[:0] + bp = BlockPlacement(slice(0, 0)) + nb = blk.make_block_same_class(arr, placement=bp) + blocks = [nb] + else: + blocks = [] + return type(self).from_blocks(blocks, axes) + + def __nonzero__(self) -> bool: + return True + + # Python3 compat + __bool__ = __nonzero__ + + def _normalize_axis(self, axis: AxisInt) -> int: + # switch axis to follow BlockManager logic + if self.ndim == 2: + axis = 1 if axis == 0 else 0 + return axis + + def set_axis(self, axis: AxisInt, new_labels: Index) -> None: + # Caller is responsible for ensuring we have an Index object. + self._validate_set_axis(axis, new_labels) + self.axes[axis] = new_labels + + @property + def is_single_block(self) -> bool: + # Assumes we are 2D; overridden by SingleBlockManager + return len(self.blocks) == 1 + + @property + def items(self) -> Index: + return self.axes[0] + + def _has_no_reference(self, i: int) -> bool: + """ + Check for column `i` if it has references. + (whether it references another array or is itself being referenced) + Returns True if the column has no references. + """ + blkno = self.blknos[i] + return self._has_no_reference_block(blkno) + + def _has_no_reference_block(self, blkno: int) -> bool: + """ + Check for block `i` if it has references. + (whether it references another array or is itself being referenced) + Returns True if the block has no references. + """ + return not self.blocks[blkno].refs.has_reference() + + def add_references(self, mgr: BaseBlockManager) -> None: + """ + Adds the references from one manager to another. We assume that both + managers have the same block structure. + """ + if len(self.blocks) != len(mgr.blocks): + # If block structure changes, then we made a copy + return + for i, blk in enumerate(self.blocks): + blk.refs = mgr.blocks[i].refs + blk.refs.add_reference(blk) + + def references_same_values(self, mgr: BaseBlockManager, blkno: int) -> bool: + """ + Checks if two blocks from two different block managers reference the + same underlying values. + """ + blk = self.blocks[blkno] + return any(blk is ref() for ref in mgr.blocks[blkno].refs.referenced_blocks) + + def get_dtypes(self) -> npt.NDArray[np.object_]: + dtypes = np.array([blk.dtype for blk in self.blocks], dtype=object) + return dtypes.take(self.blknos) + + @property + def arrays(self) -> list[ArrayLike]: + """ + Quick access to the backing arrays of the Blocks. + + Only for compatibility with ArrayManager for testing convenience. + Not to be used in actual code, and return value is not the same as the + ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs). + + Warning! The returned arrays don't handle Copy-on-Write, so this should + be used with caution (only in read-mode). + """ + return [blk.values for blk in self.blocks] + + def __repr__(self) -> str: + output = type(self).__name__ + for i, ax in enumerate(self.axes): + if i == 0: + output += f"\nItems: {ax}" + else: + output += f"\nAxis {i}: {ax}" + + for block in self.blocks: + output += f"\n{block}" + return output + + def apply( + self, + f, + align_keys: list[str] | None = None, + **kwargs, + ) -> Self: + """ + Iterate over the blocks, collect and create a new BlockManager. + + Parameters + ---------- + f : str or callable + Name of the Block method to apply. + align_keys: List[str] or None, default None + **kwargs + Keywords to pass to `f` + + Returns + ------- + BlockManager + """ + assert "filter" not in kwargs + + align_keys = align_keys or [] + result_blocks: list[Block] = [] + # fillna: Series/DataFrame is responsible for making sure value is aligned + + aligned_args = {k: kwargs[k] for k in align_keys} + + for b in self.blocks: + if aligned_args: + for k, obj in aligned_args.items(): + if isinstance(obj, (ABCSeries, ABCDataFrame)): + # The caller is responsible for ensuring that + # obj.axes[-1].equals(self.items) + if obj.ndim == 1: + kwargs[k] = obj.iloc[b.mgr_locs.indexer]._values + else: + kwargs[k] = obj.iloc[:, b.mgr_locs.indexer]._values + else: + # otherwise we have an ndarray + kwargs[k] = obj[b.mgr_locs.indexer] + + if callable(f): + applied = b.apply(f, **kwargs) + else: + applied = getattr(b, f)(**kwargs) + result_blocks = extend_blocks(applied, result_blocks) + + out = type(self).from_blocks(result_blocks, self.axes) + return out + + # Alias so we can share code with ArrayManager + apply_with_block = apply + + def setitem(self, indexer, value, warn: bool = True) -> Self: + """ + Set values with indexer. + + For SingleBlockManager, this backs s[indexer] = value + """ + if isinstance(indexer, np.ndarray) and indexer.ndim > self.ndim: + raise ValueError(f"Cannot set values with ndim > {self.ndim}") + + if warn and warn_copy_on_write() and not self._has_no_reference(0): + warnings.warn( + COW_WARNING_GENERAL_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + + elif using_copy_on_write() and not self._has_no_reference(0): + # this method is only called if there is a single block -> hardcoded 0 + # Split blocks to only copy the columns we want to modify + if self.ndim == 2 and isinstance(indexer, tuple): + blk_loc = self.blklocs[indexer[1]] + if is_list_like(blk_loc) and blk_loc.ndim == 2: + blk_loc = np.squeeze(blk_loc, axis=0) + elif not is_list_like(blk_loc): + # Keep dimension and copy data later + blk_loc = [blk_loc] # type: ignore[assignment] + if len(blk_loc) == 0: + return self.copy(deep=False) + + values = self.blocks[0].values + if values.ndim == 2: + values = values[blk_loc] + # "T" has no attribute "_iset_split_block" + self._iset_split_block( # type: ignore[attr-defined] + 0, blk_loc, values + ) + + indexer = list(indexer) + # first block equals values we are setting to -> set to all columns + if lib.is_integer(indexer[1]): + col_indexer = 0 + elif len(blk_loc) > 1: + col_indexer = slice(None) # type: ignore[assignment] + else: + col_indexer = np.arange(len(blk_loc)) # type: ignore[assignment] + indexer[1] = col_indexer + + row_indexer = indexer[0] + if isinstance(row_indexer, np.ndarray) and row_indexer.ndim == 2: + # numpy cannot handle a 2d indexer in combo with a slice + row_indexer = np.squeeze(row_indexer, axis=1) + if isinstance(row_indexer, np.ndarray) and len(row_indexer) == 0: + # numpy does not like empty indexer combined with slice + # and we are setting nothing anyway + return self + indexer[0] = row_indexer + self.blocks[0].setitem(tuple(indexer), value) + return self + # No need to split if we either set all columns or on a single block + # manager + self = self.copy() + + return self.apply("setitem", indexer=indexer, value=value) + + def diff(self, n: int) -> Self: + # only reached with self.ndim == 2 + return self.apply("diff", n=n) + + def astype(self, dtype, copy: bool | None = False, errors: str = "raise") -> Self: + if copy is None: + if using_copy_on_write(): + copy = False + else: + copy = True + elif using_copy_on_write(): + copy = False + + return self.apply( + "astype", + dtype=dtype, + copy=copy, + errors=errors, + using_cow=using_copy_on_write(), + ) + + def convert(self, copy: bool | None) -> Self: + if copy is None: + if using_copy_on_write(): + copy = False + else: + copy = True + elif using_copy_on_write(): + copy = False + + return self.apply("convert", copy=copy, using_cow=using_copy_on_write()) + + def convert_dtypes(self, **kwargs): + if using_copy_on_write(): + copy = False + else: + copy = True + + return self.apply( + "convert_dtypes", copy=copy, using_cow=using_copy_on_write(), **kwargs + ) + + def get_values_for_csv( + self, *, float_format, date_format, decimal, na_rep: str = "nan", quoting=None + ) -> Self: + """ + Convert values to native types (strings / python objects) that are used + in formatting (repr / csv). + """ + return self.apply( + "get_values_for_csv", + na_rep=na_rep, + quoting=quoting, + float_format=float_format, + date_format=date_format, + decimal=decimal, + ) + + @property + def any_extension_types(self) -> bool: + """Whether any of the blocks in this manager are extension blocks""" + return any(block.is_extension for block in self.blocks) + + @property + def is_view(self) -> bool: + """return a boolean if we are a single block and are a view""" + if len(self.blocks) == 1: + return self.blocks[0].is_view + + # It is technically possible to figure out which blocks are views + # e.g. [ b.values.base is not None for b in self.blocks ] + # but then we have the case of possibly some blocks being a view + # and some blocks not. setting in theory is possible on the non-view + # blocks w/o causing a SettingWithCopy raise/warn. But this is a bit + # complicated + + return False + + def _get_data_subset(self, predicate: Callable) -> Self: + blocks = [blk for blk in self.blocks if predicate(blk.values)] + return self._combine(blocks) + + def get_bool_data(self) -> Self: + """ + Select blocks that are bool-dtype and columns from object-dtype blocks + that are all-bool. + """ + + new_blocks = [] + + for blk in self.blocks: + if blk.dtype == bool: + new_blocks.append(blk) + + elif blk.is_object: + nbs = blk._split() + new_blocks.extend(nb for nb in nbs if nb.is_bool) + + return self._combine(new_blocks) + + def get_numeric_data(self) -> Self: + numeric_blocks = [blk for blk in self.blocks if blk.is_numeric] + if len(numeric_blocks) == len(self.blocks): + # Avoid somewhat expensive _combine + return self + return self._combine(numeric_blocks) + + def _combine(self, blocks: list[Block], index: Index | None = None) -> Self: + """return a new manager with the blocks""" + if len(blocks) == 0: + if self.ndim == 2: + # retain our own Index dtype + if index is not None: + axes = [self.items[:0], index] + else: + axes = [self.items[:0]] + self.axes[1:] + return self.make_empty(axes) + return self.make_empty() + + # FIXME: optimization potential + indexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks])) + inv_indexer = lib.get_reverse_indexer(indexer, self.shape[0]) + + new_blocks: list[Block] = [] + for b in blocks: + nb = b.copy(deep=False) + nb.mgr_locs = BlockPlacement(inv_indexer[nb.mgr_locs.indexer]) + new_blocks.append(nb) + + axes = list(self.axes) + if index is not None: + axes[-1] = index + axes[0] = self.items.take(indexer) + + return type(self).from_blocks(new_blocks, axes) + + @property + def nblocks(self) -> int: + return len(self.blocks) + + def copy(self, deep: bool | None | Literal["all"] = True) -> Self: + """ + Make deep or shallow copy of BlockManager + + Parameters + ---------- + deep : bool, string or None, default True + If False or None, return a shallow copy (do not copy data) + If 'all', copy data and a deep copy of the index + + Returns + ------- + BlockManager + """ + if deep is None: + if using_copy_on_write(): + # use shallow copy + deep = False + else: + # preserve deep copy for BlockManager with copy=None + deep = True + + # this preserves the notion of view copying of axes + if deep: + # hit in e.g. tests.io.json.test_pandas + + def copy_func(ax): + return ax.copy(deep=True) if deep == "all" else ax.view() + + new_axes = [copy_func(ax) for ax in self.axes] + else: + if using_copy_on_write(): + new_axes = [ax.view() for ax in self.axes] + else: + new_axes = list(self.axes) + + res = self.apply("copy", deep=deep) + res.axes = new_axes + + if self.ndim > 1: + # Avoid needing to re-compute these + blknos = self._blknos + if blknos is not None: + res._blknos = blknos.copy() + res._blklocs = self._blklocs.copy() + + if deep: + res._consolidate_inplace() + return res + + def consolidate(self) -> Self: + """ + Join together blocks having same dtype + + Returns + ------- + y : BlockManager + """ + if self.is_consolidated(): + return self + + bm = type(self)(self.blocks, self.axes, verify_integrity=False) + bm._is_consolidated = False + bm._consolidate_inplace() + return bm + + def reindex_indexer( + self, + new_axis: Index, + indexer: npt.NDArray[np.intp] | None, + axis: AxisInt, + fill_value=None, + allow_dups: bool = False, + copy: bool | None = True, + only_slice: bool = False, + *, + use_na_proxy: bool = False, + ) -> Self: + """ + Parameters + ---------- + new_axis : Index + indexer : ndarray[intp] or None + axis : int + fill_value : object, default None + allow_dups : bool, default False + copy : bool or None, default True + If None, regard as False to get shallow copy. + only_slice : bool, default False + Whether to take views, not copies, along columns. + use_na_proxy : bool, default False + Whether to use a np.void ndarray for newly introduced columns. + + pandas-indexer with -1's only. + """ + if copy is None: + if using_copy_on_write(): + # use shallow copy + copy = False + else: + # preserve deep copy for BlockManager with copy=None + copy = True + + if indexer is None: + if new_axis is self.axes[axis] and not copy: + return self + + result = self.copy(deep=copy) + result.axes = list(self.axes) + result.axes[axis] = new_axis + return result + + # Should be intp, but in some cases we get int64 on 32bit builds + assert isinstance(indexer, np.ndarray) + + # some axes don't allow reindexing with dups + if not allow_dups: + self.axes[axis]._validate_can_reindex(indexer) + + if axis >= self.ndim: + raise IndexError("Requested axis not found in manager") + + if axis == 0: + new_blocks = self._slice_take_blocks_ax0( + indexer, + fill_value=fill_value, + only_slice=only_slice, + use_na_proxy=use_na_proxy, + ) + else: + new_blocks = [ + blk.take_nd( + indexer, + axis=1, + fill_value=( + fill_value if fill_value is not None else blk.fill_value + ), + ) + for blk in self.blocks + ] + + new_axes = list(self.axes) + new_axes[axis] = new_axis + + new_mgr = type(self).from_blocks(new_blocks, new_axes) + if axis == 1: + # We can avoid the need to rebuild these + new_mgr._blknos = self.blknos.copy() + new_mgr._blklocs = self.blklocs.copy() + return new_mgr + + def _slice_take_blocks_ax0( + self, + slice_or_indexer: slice | np.ndarray, + fill_value=lib.no_default, + only_slice: bool = False, + *, + use_na_proxy: bool = False, + ref_inplace_op: bool = False, + ) -> list[Block]: + """ + Slice/take blocks along axis=0. + + Overloaded for SingleBlock + + Parameters + ---------- + slice_or_indexer : slice or np.ndarray[int64] + fill_value : scalar, default lib.no_default + only_slice : bool, default False + If True, we always return views on existing arrays, never copies. + This is used when called from ops.blockwise.operate_blockwise. + use_na_proxy : bool, default False + Whether to use a np.void ndarray for newly introduced columns. + ref_inplace_op: bool, default False + Don't track refs if True because we operate inplace + + Returns + ------- + new_blocks : list of Block + """ + allow_fill = fill_value is not lib.no_default + + sl_type, slobj, sllen = _preprocess_slice_or_indexer( + slice_or_indexer, self.shape[0], allow_fill=allow_fill + ) + + if self.is_single_block: + blk = self.blocks[0] + + if sl_type == "slice": + # GH#32959 EABlock would fail since we can't make 0-width + # TODO(EA2D): special casing unnecessary with 2D EAs + if sllen == 0: + return [] + bp = BlockPlacement(slice(0, sllen)) + return [blk.getitem_block_columns(slobj, new_mgr_locs=bp)] + elif not allow_fill or self.ndim == 1: + if allow_fill and fill_value is None: + fill_value = blk.fill_value + + if not allow_fill and only_slice: + # GH#33597 slice instead of take, so we get + # views instead of copies + blocks = [ + blk.getitem_block_columns( + slice(ml, ml + 1), + new_mgr_locs=BlockPlacement(i), + ref_inplace_op=ref_inplace_op, + ) + for i, ml in enumerate(slobj) + ] + return blocks + else: + bp = BlockPlacement(slice(0, sllen)) + return [ + blk.take_nd( + slobj, + axis=0, + new_mgr_locs=bp, + fill_value=fill_value, + ) + ] + + if sl_type == "slice": + blknos = self.blknos[slobj] + blklocs = self.blklocs[slobj] + else: + blknos = algos.take_nd( + self.blknos, slobj, fill_value=-1, allow_fill=allow_fill + ) + blklocs = algos.take_nd( + self.blklocs, slobj, fill_value=-1, allow_fill=allow_fill + ) + + # When filling blknos, make sure blknos is updated before appending to + # blocks list, that way new blkno is exactly len(blocks). + blocks = [] + group = not only_slice + for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=group): + if blkno == -1: + # If we've got here, fill_value was not lib.no_default + + blocks.append( + self._make_na_block( + placement=mgr_locs, + fill_value=fill_value, + use_na_proxy=use_na_proxy, + ) + ) + else: + blk = self.blocks[blkno] + + # Otherwise, slicing along items axis is necessary. + if not blk._can_consolidate and not blk._validate_ndim: + # i.e. we dont go through here for DatetimeTZBlock + # A non-consolidatable block, it's easy, because there's + # only one item and each mgr loc is a copy of that single + # item. + deep = not (only_slice or using_copy_on_write()) + for mgr_loc in mgr_locs: + newblk = blk.copy(deep=deep) + newblk.mgr_locs = BlockPlacement(slice(mgr_loc, mgr_loc + 1)) + blocks.append(newblk) + + else: + # GH#32779 to avoid the performance penalty of copying, + # we may try to only slice + taker = blklocs[mgr_locs.indexer] + max_len = max(len(mgr_locs), taker.max() + 1) + if only_slice or using_copy_on_write(): + taker = lib.maybe_indices_to_slice(taker, max_len) + + if isinstance(taker, slice): + nb = blk.getitem_block_columns(taker, new_mgr_locs=mgr_locs) + blocks.append(nb) + elif only_slice: + # GH#33597 slice instead of take, so we get + # views instead of copies + for i, ml in zip(taker, mgr_locs): + slc = slice(i, i + 1) + bp = BlockPlacement(ml) + nb = blk.getitem_block_columns(slc, new_mgr_locs=bp) + # We have np.shares_memory(nb.values, blk.values) + blocks.append(nb) + else: + nb = blk.take_nd(taker, axis=0, new_mgr_locs=mgr_locs) + blocks.append(nb) + + return blocks + + def _make_na_block( + self, placement: BlockPlacement, fill_value=None, use_na_proxy: bool = False + ) -> Block: + # Note: we only get here with self.ndim == 2 + + if use_na_proxy: + assert fill_value is None + shape = (len(placement), self.shape[1]) + vals = np.empty(shape, dtype=np.void) + nb = NumpyBlock(vals, placement, ndim=2) + return nb + + if fill_value is None: + fill_value = np.nan + + shape = (len(placement), self.shape[1]) + + dtype, fill_value = infer_dtype_from_scalar(fill_value) + block_values = make_na_array(dtype, shape, fill_value) + return new_block_2d(block_values, placement=placement) + + def take( + self, + indexer: npt.NDArray[np.intp], + axis: AxisInt = 1, + verify: bool = True, + ) -> Self: + """ + Take items along any axis. + + indexer : np.ndarray[np.intp] + axis : int, default 1 + verify : bool, default True + Check that all entries are between 0 and len(self) - 1, inclusive. + Pass verify=False if this check has been done by the caller. + + Returns + ------- + BlockManager + """ + # Caller is responsible for ensuring indexer annotation is accurate + + n = self.shape[axis] + indexer = maybe_convert_indices(indexer, n, verify=verify) + + new_labels = self.axes[axis].take(indexer) + return self.reindex_indexer( + new_axis=new_labels, + indexer=indexer, + axis=axis, + allow_dups=True, + copy=None, + ) + + +class BlockManager(libinternals.BlockManager, BaseBlockManager): + """ + BaseBlockManager that holds 2D blocks. + """ + + ndim = 2 + + # ---------------------------------------------------------------- + # Constructors + + def __init__( + self, + blocks: Sequence[Block], + axes: Sequence[Index], + verify_integrity: bool = True, + ) -> None: + if verify_integrity: + # Assertion disabled for performance + # assert all(isinstance(x, Index) for x in axes) + + for block in blocks: + if self.ndim != block.ndim: + raise AssertionError( + f"Number of Block dimensions ({block.ndim}) must equal " + f"number of axes ({self.ndim})" + ) + # As of 2.0, the caller is responsible for ensuring that + # DatetimeTZBlock with block.ndim == 2 has block.values.ndim ==2; + # previously there was a special check for fastparquet compat. + + self._verify_integrity() + + def _verify_integrity(self) -> None: + mgr_shape = self.shape + tot_items = sum(len(x.mgr_locs) for x in self.blocks) + for block in self.blocks: + if block.shape[1:] != mgr_shape[1:]: + raise_construction_error(tot_items, block.shape[1:], self.axes) + if len(self.items) != tot_items: + raise AssertionError( + "Number of manager items must equal union of " + f"block items\n# manager items: {len(self.items)}, # " + f"tot_items: {tot_items}" + ) + + @classmethod + def from_blocks(cls, blocks: list[Block], axes: list[Index]) -> Self: + """ + Constructor for BlockManager and SingleBlockManager with same signature. + """ + return cls(blocks, axes, verify_integrity=False) + + # ---------------------------------------------------------------- + # Indexing + + def fast_xs(self, loc: int) -> SingleBlockManager: + """ + Return the array corresponding to `frame.iloc[loc]`. + + Parameters + ---------- + loc : int + + Returns + ------- + np.ndarray or ExtensionArray + """ + if len(self.blocks) == 1: + # TODO: this could be wrong if blk.mgr_locs is not slice(None)-like; + # is this ruled out in the general case? + result = self.blocks[0].iget((slice(None), loc)) + # in the case of a single block, the new block is a view + bp = BlockPlacement(slice(0, len(result))) + block = new_block( + result, + placement=bp, + ndim=1, + refs=self.blocks[0].refs, + ) + return SingleBlockManager(block, self.axes[0]) + + dtype = interleaved_dtype([blk.dtype for blk in self.blocks]) + + n = len(self) + + if isinstance(dtype, ExtensionDtype): + # TODO: use object dtype as workaround for non-performant + # EA.__setitem__ methods. (primarily ArrowExtensionArray.__setitem__ + # when iteratively setting individual values) + # https://github.com/pandas-dev/pandas/pull/54508#issuecomment-1675827918 + result = np.empty(n, dtype=object) + else: + result = np.empty(n, dtype=dtype) + result = ensure_wrapped_if_datetimelike(result) + + for blk in self.blocks: + # Such assignment may incorrectly coerce NaT to None + # result[blk.mgr_locs] = blk._slice((slice(None), loc)) + for i, rl in enumerate(blk.mgr_locs): + result[rl] = blk.iget((i, loc)) + + if isinstance(dtype, ExtensionDtype): + cls = dtype.construct_array_type() + result = cls._from_sequence(result, dtype=dtype) + + bp = BlockPlacement(slice(0, len(result))) + block = new_block(result, placement=bp, ndim=1) + return SingleBlockManager(block, self.axes[0]) + + def iget(self, i: int, track_ref: bool = True) -> SingleBlockManager: + """ + Return the data as a SingleBlockManager. + """ + block = self.blocks[self.blknos[i]] + values = block.iget(self.blklocs[i]) + + # shortcut for select a single-dim from a 2-dim BM + bp = BlockPlacement(slice(0, len(values))) + nb = type(block)( + values, placement=bp, ndim=1, refs=block.refs if track_ref else None + ) + return SingleBlockManager(nb, self.axes[1]) + + def iget_values(self, i: int) -> ArrayLike: + """ + Return the data for column i as the values (ndarray or ExtensionArray). + + Warning! The returned array is a view but doesn't handle Copy-on-Write, + so this should be used with caution. + """ + # TODO(CoW) making the arrays read-only might make this safer to use? + block = self.blocks[self.blknos[i]] + values = block.iget(self.blklocs[i]) + return values + + @property + def column_arrays(self) -> list[np.ndarray]: + """ + Used in the JSON C code to access column arrays. + This optimizes compared to using `iget_values` by converting each + + Warning! This doesn't handle Copy-on-Write, so should be used with + caution (current use case of consuming this in the JSON code is fine). + """ + # This is an optimized equivalent to + # result = [self.iget_values(i) for i in range(len(self.items))] + result: list[np.ndarray | None] = [None] * len(self.items) + + for blk in self.blocks: + mgr_locs = blk._mgr_locs + values = blk.array_values._values_for_json() + if values.ndim == 1: + # TODO(EA2D): special casing not needed with 2D EAs + result[mgr_locs[0]] = values + + else: + for i, loc in enumerate(mgr_locs): + result[loc] = values[i] + + # error: Incompatible return value type (got "List[None]", + # expected "List[ndarray[Any, Any]]") + return result # type: ignore[return-value] + + def iset( + self, + loc: int | slice | np.ndarray, + value: ArrayLike, + inplace: bool = False, + refs: BlockValuesRefs | None = None, + ) -> None: + """ + Set new item in-place. Does not consolidate. Adds new Block if not + contained in the current set of items + """ + + # FIXME: refactor, clearly separate broadcasting & zip-like assignment + # can prob also fix the various if tests for sparse/categorical + if self._blklocs is None and self.ndim > 1: + self._rebuild_blknos_and_blklocs() + + # Note: we exclude DTA/TDA here + value_is_extension_type = is_1d_only_ea_dtype(value.dtype) + if not value_is_extension_type: + if value.ndim == 2: + value = value.T + else: + value = ensure_block_shape(value, ndim=2) + + if value.shape[1:] != self.shape[1:]: + raise AssertionError( + "Shape of new values must be compatible with manager shape" + ) + + if lib.is_integer(loc): + # We have 6 tests where loc is _not_ an int. + # In this case, get_blkno_placements will yield only one tuple, + # containing (self._blknos[loc], BlockPlacement(slice(0, 1, 1))) + + # Check if we can use _iset_single fastpath + loc = cast(int, loc) + blkno = self.blknos[loc] + blk = self.blocks[blkno] + if len(blk._mgr_locs) == 1: # TODO: fastest way to check this? + return self._iset_single( + loc, + value, + inplace=inplace, + blkno=blkno, + blk=blk, + refs=refs, + ) + + # error: Incompatible types in assignment (expression has type + # "List[Union[int, slice, ndarray]]", variable has type "Union[int, + # slice, ndarray]") + loc = [loc] # type: ignore[assignment] + + # categorical/sparse/datetimetz + if value_is_extension_type: + + def value_getitem(placement): + return value + + else: + + def value_getitem(placement): + return value[placement.indexer] + + # Accessing public blknos ensures the public versions are initialized + blknos = self.blknos[loc] + blklocs = self.blklocs[loc].copy() + + unfit_mgr_locs = [] + unfit_val_locs = [] + removed_blknos = [] + for blkno_l, val_locs in libinternals.get_blkno_placements(blknos, group=True): + blk = self.blocks[blkno_l] + blk_locs = blklocs[val_locs.indexer] + if inplace and blk.should_store(value): + # Updating inplace -> check if we need to do Copy-on-Write + if using_copy_on_write() and not self._has_no_reference_block(blkno_l): + self._iset_split_block( + blkno_l, blk_locs, value_getitem(val_locs), refs=refs + ) + else: + blk.set_inplace(blk_locs, value_getitem(val_locs)) + continue + else: + unfit_mgr_locs.append(blk.mgr_locs.as_array[blk_locs]) + unfit_val_locs.append(val_locs) + + # If all block items are unfit, schedule the block for removal. + if len(val_locs) == len(blk.mgr_locs): + removed_blknos.append(blkno_l) + continue + else: + # Defer setting the new values to enable consolidation + self._iset_split_block(blkno_l, blk_locs, refs=refs) + + if len(removed_blknos): + # Remove blocks & update blknos accordingly + is_deleted = np.zeros(self.nblocks, dtype=np.bool_) + is_deleted[removed_blknos] = True + + new_blknos = np.empty(self.nblocks, dtype=np.intp) + new_blknos.fill(-1) + new_blknos[~is_deleted] = np.arange(self.nblocks - len(removed_blknos)) + self._blknos = new_blknos[self._blknos] + self.blocks = tuple( + blk for i, blk in enumerate(self.blocks) if i not in set(removed_blknos) + ) + + if unfit_val_locs: + unfit_idxr = np.concatenate(unfit_mgr_locs) + unfit_count = len(unfit_idxr) + + new_blocks: list[Block] = [] + if value_is_extension_type: + # This code (ab-)uses the fact that EA blocks contain only + # one item. + # TODO(EA2D): special casing unnecessary with 2D EAs + new_blocks.extend( + new_block_2d( + values=value, + placement=BlockPlacement(slice(mgr_loc, mgr_loc + 1)), + refs=refs, + ) + for mgr_loc in unfit_idxr + ) + + self._blknos[unfit_idxr] = np.arange(unfit_count) + len(self.blocks) + self._blklocs[unfit_idxr] = 0 + + else: + # unfit_val_locs contains BlockPlacement objects + unfit_val_items = unfit_val_locs[0].append(unfit_val_locs[1:]) + + new_blocks.append( + new_block_2d( + values=value_getitem(unfit_val_items), + placement=BlockPlacement(unfit_idxr), + refs=refs, + ) + ) + + self._blknos[unfit_idxr] = len(self.blocks) + self._blklocs[unfit_idxr] = np.arange(unfit_count) + + self.blocks += tuple(new_blocks) + + # Newly created block's dtype may already be present. + self._known_consolidated = False + + def _iset_split_block( + self, + blkno_l: int, + blk_locs: np.ndarray | list[int], + value: ArrayLike | None = None, + refs: BlockValuesRefs | None = None, + ) -> None: + """Removes columns from a block by splitting the block. + + Avoids copying the whole block through slicing and updates the manager + after determinint the new block structure. Optionally adds a new block, + otherwise has to be done by the caller. + + Parameters + ---------- + blkno_l: The block number to operate on, relevant for updating the manager + blk_locs: The locations of our block that should be deleted. + value: The value to set as a replacement. + refs: The reference tracking object of the value to set. + """ + blk = self.blocks[blkno_l] + + if self._blklocs is None: + self._rebuild_blknos_and_blklocs() + + nbs_tup = tuple(blk.delete(blk_locs)) + if value is not None: + locs = blk.mgr_locs.as_array[blk_locs] + first_nb = new_block_2d(value, BlockPlacement(locs), refs=refs) + else: + first_nb = nbs_tup[0] + nbs_tup = tuple(nbs_tup[1:]) + + nr_blocks = len(self.blocks) + blocks_tup = ( + self.blocks[:blkno_l] + (first_nb,) + self.blocks[blkno_l + 1 :] + nbs_tup + ) + self.blocks = blocks_tup + + if not nbs_tup and value is not None: + # No need to update anything if split did not happen + return + + self._blklocs[first_nb.mgr_locs.indexer] = np.arange(len(first_nb)) + + for i, nb in enumerate(nbs_tup): + self._blklocs[nb.mgr_locs.indexer] = np.arange(len(nb)) + self._blknos[nb.mgr_locs.indexer] = i + nr_blocks + + def _iset_single( + self, + loc: int, + value: ArrayLike, + inplace: bool, + blkno: int, + blk: Block, + refs: BlockValuesRefs | None = None, + ) -> None: + """ + Fastpath for iset when we are only setting a single position and + the Block currently in that position is itself single-column. + + In this case we can swap out the entire Block and blklocs and blknos + are unaffected. + """ + # Caller is responsible for verifying value.shape + + if inplace and blk.should_store(value): + copy = False + if using_copy_on_write() and not self._has_no_reference_block(blkno): + # perform Copy-on-Write and clear the reference + copy = True + iloc = self.blklocs[loc] + blk.set_inplace(slice(iloc, iloc + 1), value, copy=copy) + return + + nb = new_block_2d(value, placement=blk._mgr_locs, refs=refs) + old_blocks = self.blocks + new_blocks = old_blocks[:blkno] + (nb,) + old_blocks[blkno + 1 :] + self.blocks = new_blocks + return + + def column_setitem( + self, loc: int, idx: int | slice | np.ndarray, value, inplace_only: bool = False + ) -> None: + """ + Set values ("setitem") into a single column (not setting the full column). + + This is a method on the BlockManager level, to avoid creating an + intermediate Series at the DataFrame level (`s = df[loc]; s[idx] = value`) + """ + needs_to_warn = False + if warn_copy_on_write() and not self._has_no_reference(loc): + if not isinstance( + self.blocks[self.blknos[loc]].values, + (ArrowExtensionArray, ArrowStringArray), + ): + # We might raise if we are in an expansion case, so defer + # warning till we actually updated + needs_to_warn = True + + elif using_copy_on_write() and not self._has_no_reference(loc): + blkno = self.blknos[loc] + # Split blocks to only copy the column we want to modify + blk_loc = self.blklocs[loc] + # Copy our values + values = self.blocks[blkno].values + if values.ndim == 1: + values = values.copy() + else: + # Use [blk_loc] as indexer to keep ndim=2, this already results in a + # copy + values = values[[blk_loc]] + self._iset_split_block(blkno, [blk_loc], values) + + # this manager is only created temporarily to mutate the values in place + # so don't track references, otherwise the `setitem` would perform CoW again + col_mgr = self.iget(loc, track_ref=False) + if inplace_only: + col_mgr.setitem_inplace(idx, value) + else: + new_mgr = col_mgr.setitem((idx,), value) + self.iset(loc, new_mgr._block.values, inplace=True) + + if needs_to_warn: + warnings.warn( + COW_WARNING_GENERAL_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + + def insert(self, loc: int, item: Hashable, value: ArrayLike, refs=None) -> None: + """ + Insert item at selected position. + + Parameters + ---------- + loc : int + item : hashable + value : np.ndarray or ExtensionArray + refs : The reference tracking object of the value to set. + """ + with warnings.catch_warnings(): + # TODO: re-issue this with setitem-specific message? + warnings.filterwarnings( + "ignore", + "The behavior of Index.insert with object-dtype is deprecated", + category=FutureWarning, + ) + new_axis = self.items.insert(loc, item) + + if value.ndim == 2: + value = value.T + if len(value) > 1: + raise ValueError( + f"Expected a 1D array, got an array with shape {value.T.shape}" + ) + else: + value = ensure_block_shape(value, ndim=self.ndim) + + bp = BlockPlacement(slice(loc, loc + 1)) + block = new_block_2d(values=value, placement=bp, refs=refs) + + if not len(self.blocks): + # Fastpath + self._blklocs = np.array([0], dtype=np.intp) + self._blknos = np.array([0], dtype=np.intp) + else: + self._insert_update_mgr_locs(loc) + self._insert_update_blklocs_and_blknos(loc) + + self.axes[0] = new_axis + self.blocks += (block,) + + self._known_consolidated = False + + if sum(not block.is_extension for block in self.blocks) > 100: + warnings.warn( + "DataFrame is highly fragmented. This is usually the result " + "of calling `frame.insert` many times, which has poor performance. " + "Consider joining all columns at once using pd.concat(axis=1) " + "instead. To get a de-fragmented frame, use `newframe = frame.copy()`", + PerformanceWarning, + stacklevel=find_stack_level(), + ) + + def _insert_update_mgr_locs(self, loc) -> None: + """ + When inserting a new Block at location 'loc', we increment + all of the mgr_locs of blocks above that by one. + """ + for blkno, count in _fast_count_smallints(self.blknos[loc:]): + # .620 this way, .326 of which is in increment_above + blk = self.blocks[blkno] + blk._mgr_locs = blk._mgr_locs.increment_above(loc) + + def _insert_update_blklocs_and_blknos(self, loc) -> None: + """ + When inserting a new Block at location 'loc', we update our + _blklocs and _blknos. + """ + + # Accessing public blklocs ensures the public versions are initialized + if loc == self.blklocs.shape[0]: + # np.append is a lot faster, let's use it if we can. + self._blklocs = np.append(self._blklocs, 0) + self._blknos = np.append(self._blknos, len(self.blocks)) + elif loc == 0: + # np.append is a lot faster, let's use it if we can. + self._blklocs = np.append(self._blklocs[::-1], 0)[::-1] + self._blknos = np.append(self._blknos[::-1], len(self.blocks))[::-1] + else: + new_blklocs, new_blknos = libinternals.update_blklocs_and_blknos( + self.blklocs, self.blknos, loc, len(self.blocks) + ) + self._blklocs = new_blklocs + self._blknos = new_blknos + + def idelete(self, indexer) -> BlockManager: + """ + Delete selected locations, returning a new BlockManager. + """ + is_deleted = np.zeros(self.shape[0], dtype=np.bool_) + is_deleted[indexer] = True + taker = (~is_deleted).nonzero()[0] + + nbs = self._slice_take_blocks_ax0(taker, only_slice=True, ref_inplace_op=True) + new_columns = self.items[~is_deleted] + axes = [new_columns, self.axes[1]] + return type(self)(tuple(nbs), axes, verify_integrity=False) + + # ---------------------------------------------------------------- + # Block-wise Operation + + def grouped_reduce(self, func: Callable) -> Self: + """ + Apply grouped reduction function blockwise, returning a new BlockManager. + + Parameters + ---------- + func : grouped reduction function + + Returns + ------- + BlockManager + """ + result_blocks: list[Block] = [] + + for blk in self.blocks: + if blk.is_object: + # split on object-dtype blocks bc some columns may raise + # while others do not. + for sb in blk._split(): + applied = sb.apply(func) + result_blocks = extend_blocks(applied, result_blocks) + else: + applied = blk.apply(func) + result_blocks = extend_blocks(applied, result_blocks) + + if len(result_blocks) == 0: + nrows = 0 + else: + nrows = result_blocks[0].values.shape[-1] + index = Index(range(nrows)) + + return type(self).from_blocks(result_blocks, [self.axes[0], index]) + + def reduce(self, func: Callable) -> Self: + """ + Apply reduction function blockwise, returning a single-row BlockManager. + + Parameters + ---------- + func : reduction function + + Returns + ------- + BlockManager + """ + # If 2D, we assume that we're operating column-wise + assert self.ndim == 2 + + res_blocks: list[Block] = [] + for blk in self.blocks: + nbs = blk.reduce(func) + res_blocks.extend(nbs) + + index = Index([None]) # placeholder + new_mgr = type(self).from_blocks(res_blocks, [self.items, index]) + return new_mgr + + def operate_blockwise(self, other: BlockManager, array_op) -> BlockManager: + """ + Apply array_op blockwise with another (aligned) BlockManager. + """ + return operate_blockwise(self, other, array_op) + + def _equal_values(self: BlockManager, other: BlockManager) -> bool: + """ + Used in .equals defined in base class. Only check the column values + assuming shape and indexes have already been checked. + """ + return blockwise_all(self, other, array_equals) + + def quantile( + self, + *, + qs: Index, # with dtype float 64 + interpolation: QuantileInterpolation = "linear", + ) -> Self: + """ + Iterate over blocks applying quantile reduction. + This routine is intended for reduction type operations and + will do inference on the generated blocks. + + Parameters + ---------- + interpolation : type of interpolation, default 'linear' + qs : list of the quantiles to be computed + + Returns + ------- + BlockManager + """ + # Series dispatches to DataFrame for quantile, which allows us to + # simplify some of the code here and in the blocks + assert self.ndim >= 2 + assert is_list_like(qs) # caller is responsible for this + + new_axes = list(self.axes) + new_axes[1] = Index(qs, dtype=np.float64) + + blocks = [ + blk.quantile(qs=qs, interpolation=interpolation) for blk in self.blocks + ] + + return type(self)(blocks, new_axes) + + # ---------------------------------------------------------------- + + def unstack(self, unstacker, fill_value) -> BlockManager: + """ + Return a BlockManager with all blocks unstacked. + + Parameters + ---------- + unstacker : reshape._Unstacker + fill_value : Any + fill_value for newly introduced missing values. + + Returns + ------- + unstacked : BlockManager + """ + new_columns = unstacker.get_new_columns(self.items) + new_index = unstacker.new_index + + allow_fill = not unstacker.mask_all + if allow_fill: + # calculating the full mask once and passing it to Block._unstack is + # faster than letting calculating it in each repeated call + new_mask2D = (~unstacker.mask).reshape(*unstacker.full_shape) + needs_masking = new_mask2D.any(axis=0) + else: + needs_masking = np.zeros(unstacker.full_shape[1], dtype=bool) + + new_blocks: list[Block] = [] + columns_mask: list[np.ndarray] = [] + + if len(self.items) == 0: + factor = 1 + else: + fac = len(new_columns) / len(self.items) + assert fac == int(fac) + factor = int(fac) + + for blk in self.blocks: + mgr_locs = blk.mgr_locs + new_placement = mgr_locs.tile_for_unstack(factor) + + blocks, mask = blk._unstack( + unstacker, + fill_value, + new_placement=new_placement, + needs_masking=needs_masking, + ) + + new_blocks.extend(blocks) + columns_mask.extend(mask) + + # Block._unstack should ensure this holds, + assert mask.sum() == sum(len(nb._mgr_locs) for nb in blocks) + # In turn this ensures that in the BlockManager call below + # we have len(new_columns) == sum(x.shape[0] for x in new_blocks) + # which suffices to allow us to pass verify_inegrity=False + + new_columns = new_columns[columns_mask] + + bm = BlockManager(new_blocks, [new_columns, new_index], verify_integrity=False) + return bm + + def to_dict(self) -> dict[str, Self]: + """ + Return a dict of str(dtype) -> BlockManager + + Returns + ------- + values : a dict of dtype -> BlockManager + """ + + bd: dict[str, list[Block]] = {} + for b in self.blocks: + bd.setdefault(str(b.dtype), []).append(b) + + # TODO(EA2D): the combine will be unnecessary with 2D EAs + return {dtype: self._combine(blocks) for dtype, blocks in bd.items()} + + def as_array( + self, + dtype: np.dtype | None = None, + copy: bool = False, + na_value: object = lib.no_default, + ) -> np.ndarray: + """ + Convert the blockmanager data into an numpy array. + + Parameters + ---------- + dtype : np.dtype or None, default None + Data type of the return array. + copy : bool, default False + If True then guarantee that a copy is returned. A value of + False does not guarantee that the underlying data is not + copied. + na_value : object, default lib.no_default + Value to be used as the missing value sentinel. + + Returns + ------- + arr : ndarray + """ + passed_nan = lib.is_float(na_value) and isna(na_value) + + if len(self.blocks) == 0: + arr = np.empty(self.shape, dtype=float) + return arr.transpose() + + if self.is_single_block: + blk = self.blocks[0] + + if na_value is not lib.no_default: + # We want to copy when na_value is provided to avoid + # mutating the original object + if lib.is_np_dtype(blk.dtype, "f") and passed_nan: + # We are already numpy-float and na_value=np.nan + pass + else: + copy = True + + if blk.is_extension: + # Avoid implicit conversion of extension blocks to object + + # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no + # attribute "to_numpy" + arr = blk.values.to_numpy( # type: ignore[union-attr] + dtype=dtype, + na_value=na_value, + copy=copy, + ).reshape(blk.shape) + elif not copy: + arr = np.asarray(blk.values, dtype=dtype) + else: + arr = np.array(blk.values, dtype=dtype, copy=copy) + + if using_copy_on_write() and not copy: + arr = arr.view() + arr.flags.writeable = False + else: + arr = self._interleave(dtype=dtype, na_value=na_value) + # The underlying data was copied within _interleave, so no need + # to further copy if copy=True or setting na_value + + if na_value is lib.no_default: + pass + elif arr.dtype.kind == "f" and passed_nan: + pass + else: + arr[isna(arr)] = na_value + + return arr.transpose() + + def _interleave( + self, + dtype: np.dtype | None = None, + na_value: object = lib.no_default, + ) -> np.ndarray: + """ + Return ndarray from blocks with specified item order + Items must be contained in the blocks + """ + if not dtype: + # Incompatible types in assignment (expression has type + # "Optional[Union[dtype[Any], ExtensionDtype]]", variable has + # type "Optional[dtype[Any]]") + dtype = interleaved_dtype( # type: ignore[assignment] + [blk.dtype for blk in self.blocks] + ) + + # error: Argument 1 to "ensure_np_dtype" has incompatible type + # "Optional[dtype[Any]]"; expected "Union[dtype[Any], ExtensionDtype]" + dtype = ensure_np_dtype(dtype) # type: ignore[arg-type] + result = np.empty(self.shape, dtype=dtype) + + itemmask = np.zeros(self.shape[0]) + + if dtype == np.dtype("object") and na_value is lib.no_default: + # much more performant than using to_numpy below + for blk in self.blocks: + rl = blk.mgr_locs + arr = blk.get_values(dtype) + result[rl.indexer] = arr + itemmask[rl.indexer] = 1 + return result + + for blk in self.blocks: + rl = blk.mgr_locs + if blk.is_extension: + # Avoid implicit conversion of extension blocks to object + + # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no + # attribute "to_numpy" + arr = blk.values.to_numpy( # type: ignore[union-attr] + dtype=dtype, + na_value=na_value, + ) + else: + arr = blk.get_values(dtype) + result[rl.indexer] = arr + itemmask[rl.indexer] = 1 + + if not itemmask.all(): + raise AssertionError("Some items were not contained in blocks") + + return result + + # ---------------------------------------------------------------- + # Consolidation + + def is_consolidated(self) -> bool: + """ + Return True if more than one block with the same dtype + """ + if not self._known_consolidated: + self._consolidate_check() + return self._is_consolidated + + def _consolidate_check(self) -> None: + if len(self.blocks) == 1: + # fastpath + self._is_consolidated = True + self._known_consolidated = True + return + dtypes = [blk.dtype for blk in self.blocks if blk._can_consolidate] + self._is_consolidated = len(dtypes) == len(set(dtypes)) + self._known_consolidated = True + + def _consolidate_inplace(self) -> None: + # In general, _consolidate_inplace should only be called via + # DataFrame._consolidate_inplace, otherwise we will fail to invalidate + # the DataFrame's _item_cache. The exception is for newly-created + # BlockManager objects not yet attached to a DataFrame. + if not self.is_consolidated(): + self.blocks = _consolidate(self.blocks) + self._is_consolidated = True + self._known_consolidated = True + self._rebuild_blknos_and_blklocs() + + # ---------------------------------------------------------------- + # Concatenation + + @classmethod + def concat_horizontal(cls, mgrs: list[Self], axes: list[Index]) -> Self: + """ + Concatenate uniformly-indexed BlockManagers horizontally. + """ + offset = 0 + blocks: list[Block] = [] + for mgr in mgrs: + for blk in mgr.blocks: + # We need to do getitem_block here otherwise we would be altering + # blk.mgr_locs in place, which would render it invalid. This is only + # relevant in the copy=False case. + nb = blk.slice_block_columns(slice(None)) + nb._mgr_locs = nb._mgr_locs.add(offset) + blocks.append(nb) + + offset += len(mgr.items) + + new_mgr = cls(tuple(blocks), axes) + return new_mgr + + @classmethod + def concat_vertical(cls, mgrs: list[Self], axes: list[Index]) -> Self: + """ + Concatenate uniformly-indexed BlockManagers vertically. + """ + raise NotImplementedError("This logic lives (for now) in internals.concat") + + +class SingleBlockManager(BaseBlockManager, SingleDataManager): + """manage a single block with""" + + @property + def ndim(self) -> Literal[1]: + return 1 + + _is_consolidated = True + _known_consolidated = True + __slots__ = () + is_single_block = True + + def __init__( + self, + block: Block, + axis: Index, + verify_integrity: bool = False, + ) -> None: + # Assertions disabled for performance + # assert isinstance(block, Block), type(block) + # assert isinstance(axis, Index), type(axis) + + self.axes = [axis] + self.blocks = (block,) + + @classmethod + def from_blocks( + cls, + blocks: list[Block], + axes: list[Index], + ) -> Self: + """ + Constructor for BlockManager and SingleBlockManager with same signature. + """ + assert len(blocks) == 1 + assert len(axes) == 1 + return cls(blocks[0], axes[0], verify_integrity=False) + + @classmethod + def from_array( + cls, array: ArrayLike, index: Index, refs: BlockValuesRefs | None = None + ) -> SingleBlockManager: + """ + Constructor for if we have an array that is not yet a Block. + """ + array = maybe_coerce_values(array) + bp = BlockPlacement(slice(0, len(index))) + block = new_block(array, placement=bp, ndim=1, refs=refs) + return cls(block, index) + + def to_2d_mgr(self, columns: Index) -> BlockManager: + """ + Manager analogue of Series.to_frame + """ + blk = self.blocks[0] + arr = ensure_block_shape(blk.values, ndim=2) + bp = BlockPlacement(0) + new_blk = type(blk)(arr, placement=bp, ndim=2, refs=blk.refs) + axes = [columns, self.axes[0]] + return BlockManager([new_blk], axes=axes, verify_integrity=False) + + def _has_no_reference(self, i: int = 0) -> bool: + """ + Check for column `i` if it has references. + (whether it references another array or is itself being referenced) + Returns True if the column has no references. + """ + return not self.blocks[0].refs.has_reference() + + def __getstate__(self): + block_values = [b.values for b in self.blocks] + block_items = [self.items[b.mgr_locs.indexer] for b in self.blocks] + axes_array = list(self.axes) + + extra_state = { + "0.14.1": { + "axes": axes_array, + "blocks": [ + {"values": b.values, "mgr_locs": b.mgr_locs.indexer} + for b in self.blocks + ], + } + } + + # First three elements of the state are to maintain forward + # compatibility with 0.13.1. + return axes_array, block_values, block_items, extra_state + + def __setstate__(self, state) -> None: + def unpickle_block(values, mgr_locs, ndim: int) -> Block: + # TODO(EA2D): ndim would be unnecessary with 2D EAs + # older pickles may store e.g. DatetimeIndex instead of DatetimeArray + values = extract_array(values, extract_numpy=True) + if not isinstance(mgr_locs, BlockPlacement): + mgr_locs = BlockPlacement(mgr_locs) + + values = maybe_coerce_values(values) + return new_block(values, placement=mgr_locs, ndim=ndim) + + if isinstance(state, tuple) and len(state) >= 4 and "0.14.1" in state[3]: + state = state[3]["0.14.1"] + self.axes = [ensure_index(ax) for ax in state["axes"]] + ndim = len(self.axes) + self.blocks = tuple( + unpickle_block(b["values"], b["mgr_locs"], ndim=ndim) + for b in state["blocks"] + ) + else: + raise NotImplementedError("pre-0.14.1 pickles are no longer supported") + + self._post_setstate() + + def _post_setstate(self) -> None: + pass + + @cache_readonly + def _block(self) -> Block: + return self.blocks[0] + + @property + def _blknos(self): + """compat with BlockManager""" + return None + + @property + def _blklocs(self): + """compat with BlockManager""" + return None + + def get_rows_with_mask(self, indexer: npt.NDArray[np.bool_]) -> Self: + # similar to get_slice, but not restricted to slice indexer + blk = self._block + if using_copy_on_write() and len(indexer) > 0 and indexer.all(): + return type(self)(blk.copy(deep=False), self.index) + array = blk.values[indexer] + + if isinstance(indexer, np.ndarray) and indexer.dtype.kind == "b": + # boolean indexing always gives a copy with numpy + refs = None + else: + # TODO(CoW) in theory only need to track reference if new_array is a view + refs = blk.refs + + bp = BlockPlacement(slice(0, len(array))) + block = type(blk)(array, placement=bp, ndim=1, refs=refs) + + new_idx = self.index[indexer] + return type(self)(block, new_idx) + + def get_slice(self, slobj: slice, axis: AxisInt = 0) -> SingleBlockManager: + # Assertion disabled for performance + # assert isinstance(slobj, slice), type(slobj) + if axis >= self.ndim: + raise IndexError("Requested axis not found in manager") + + blk = self._block + array = blk.values[slobj] + bp = BlockPlacement(slice(0, len(array))) + # TODO this method is only used in groupby SeriesSplitter at the moment, + # so passing refs is not yet covered by the tests + block = type(blk)(array, placement=bp, ndim=1, refs=blk.refs) + new_index = self.index._getitem_slice(slobj) + return type(self)(block, new_index) + + @property + def index(self) -> Index: + return self.axes[0] + + @property + def dtype(self) -> DtypeObj: + return self._block.dtype + + def get_dtypes(self) -> npt.NDArray[np.object_]: + return np.array([self._block.dtype], dtype=object) + + def external_values(self): + """The array that Series.values returns""" + return self._block.external_values() + + def internal_values(self): + """The array that Series._values returns""" + return self._block.values + + def array_values(self) -> ExtensionArray: + """The array that Series.array returns""" + return self._block.array_values + + def get_numeric_data(self) -> Self: + if self._block.is_numeric: + return self.copy(deep=False) + return self.make_empty() + + @property + def _can_hold_na(self) -> bool: + return self._block._can_hold_na + + def setitem_inplace(self, indexer, value, warn: bool = True) -> None: + """ + Set values with indexer. + + For Single[Block/Array]Manager, this backs s[indexer] = value + + This is an inplace version of `setitem()`, mutating the manager/values + in place, not returning a new Manager (and Block), and thus never changing + the dtype. + """ + using_cow = using_copy_on_write() + warn_cow = warn_copy_on_write() + if (using_cow or warn_cow) and not self._has_no_reference(0): + if using_cow: + self.blocks = (self._block.copy(),) + self._cache.clear() + elif warn_cow and warn: + warnings.warn( + COW_WARNING_SETITEM_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + + super().setitem_inplace(indexer, value) + + def idelete(self, indexer) -> SingleBlockManager: + """ + Delete single location from SingleBlockManager. + + Ensures that self.blocks doesn't become empty. + """ + nb = self._block.delete(indexer)[0] + self.blocks = (nb,) + self.axes[0] = self.axes[0].delete(indexer) + self._cache.clear() + return self + + def fast_xs(self, loc): + """ + fast path for getting a cross-section + return a view of the data + """ + raise NotImplementedError("Use series._values[loc] instead") + + def set_values(self, values: ArrayLike) -> None: + """ + Set the values of the single block in place. + + Use at your own risk! This does not check if the passed values are + valid for the current Block/SingleBlockManager (length, dtype, etc), + and this does not properly keep track of references. + """ + # NOTE(CoW) Currently this is only used for FrameColumnApply.series_generator + # which handles CoW by setting the refs manually if necessary + self.blocks[0].values = values + self.blocks[0]._mgr_locs = BlockPlacement(slice(len(values))) + + def _equal_values(self, other: Self) -> bool: + """ + Used in .equals defined in base class. Only check the column values + assuming shape and indexes have already been checked. + """ + # For SingleBlockManager (i.e.Series) + if other.ndim != 1: + return False + left = self.blocks[0].values + right = other.blocks[0].values + return array_equals(left, right) + + +# -------------------------------------------------------------------- +# Constructor Helpers + + +def create_block_manager_from_blocks( + blocks: list[Block], + axes: list[Index], + consolidate: bool = True, + verify_integrity: bool = True, +) -> BlockManager: + # If verify_integrity=False, then caller is responsible for checking + # all(x.shape[-1] == len(axes[1]) for x in blocks) + # sum(x.shape[0] for x in blocks) == len(axes[0]) + # set(x for blk in blocks for x in blk.mgr_locs) == set(range(len(axes[0]))) + # all(blk.ndim == 2 for blk in blocks) + # This allows us to safely pass verify_integrity=False + + try: + mgr = BlockManager(blocks, axes, verify_integrity=verify_integrity) + + except ValueError as err: + arrays = [blk.values for blk in blocks] + tot_items = sum(arr.shape[0] for arr in arrays) + raise_construction_error(tot_items, arrays[0].shape[1:], axes, err) + + if consolidate: + mgr._consolidate_inplace() + return mgr + + +def create_block_manager_from_column_arrays( + arrays: list[ArrayLike], + axes: list[Index], + consolidate: bool, + refs: list, +) -> BlockManager: + # Assertions disabled for performance (caller is responsible for verifying) + # assert isinstance(axes, list) + # assert all(isinstance(x, Index) for x in axes) + # assert all(isinstance(x, (np.ndarray, ExtensionArray)) for x in arrays) + # assert all(type(x) is not NumpyExtensionArray for x in arrays) + # assert all(x.ndim == 1 for x in arrays) + # assert all(len(x) == len(axes[1]) for x in arrays) + # assert len(arrays) == len(axes[0]) + # These last three are sufficient to allow us to safely pass + # verify_integrity=False below. + + try: + blocks = _form_blocks(arrays, consolidate, refs) + mgr = BlockManager(blocks, axes, verify_integrity=False) + except ValueError as e: + raise_construction_error(len(arrays), arrays[0].shape, axes, e) + if consolidate: + mgr._consolidate_inplace() + return mgr + + +def raise_construction_error( + tot_items: int, + block_shape: Shape, + axes: list[Index], + e: ValueError | None = None, +): + """raise a helpful message about our construction""" + passed = tuple(map(int, [tot_items] + list(block_shape))) + # Correcting the user facing error message during dataframe construction + if len(passed) <= 2: + passed = passed[::-1] + + implied = tuple(len(ax) for ax in axes) + # Correcting the user facing error message during dataframe construction + if len(implied) <= 2: + implied = implied[::-1] + + # We return the exception object instead of raising it so that we + # can raise it in the caller; mypy plays better with that + if passed == implied and e is not None: + raise e + if block_shape[0] == 0: + raise ValueError("Empty data passed with indices specified.") + raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}") + + +# ----------------------------------------------------------------------- + + +def _grouping_func(tup: tuple[int, ArrayLike]) -> tuple[int, DtypeObj]: + dtype = tup[1].dtype + + if is_1d_only_ea_dtype(dtype): + # We know these won't be consolidated, so don't need to group these. + # This avoids expensive comparisons of CategoricalDtype objects + sep = id(dtype) + else: + sep = 0 + + return sep, dtype + + +def _form_blocks(arrays: list[ArrayLike], consolidate: bool, refs: list) -> list[Block]: + tuples = list(enumerate(arrays)) + + if not consolidate: + return _tuples_to_blocks_no_consolidate(tuples, refs) + + # when consolidating, we can ignore refs (either stacking always copies, + # or the EA is already copied in the calling dict_to_mgr) + + # group by dtype + grouper = itertools.groupby(tuples, _grouping_func) + + nbs: list[Block] = [] + for (_, dtype), tup_block in grouper: + block_type = get_block_type(dtype) + + if isinstance(dtype, np.dtype): + is_dtlike = dtype.kind in "mM" + + if issubclass(dtype.type, (str, bytes)): + dtype = np.dtype(object) + + values, placement = _stack_arrays(list(tup_block), dtype) + if is_dtlike: + values = ensure_wrapped_if_datetimelike(values) + blk = block_type(values, placement=BlockPlacement(placement), ndim=2) + nbs.append(blk) + + elif is_1d_only_ea_dtype(dtype): + dtype_blocks = [ + block_type(x[1], placement=BlockPlacement(x[0]), ndim=2) + for x in tup_block + ] + nbs.extend(dtype_blocks) + + else: + dtype_blocks = [ + block_type( + ensure_block_shape(x[1], 2), placement=BlockPlacement(x[0]), ndim=2 + ) + for x in tup_block + ] + nbs.extend(dtype_blocks) + return nbs + + +def _tuples_to_blocks_no_consolidate(tuples, refs) -> list[Block]: + # tuples produced within _form_blocks are of the form (placement, array) + return [ + new_block_2d( + ensure_block_shape(arr, ndim=2), placement=BlockPlacement(i), refs=ref + ) + for ((i, arr), ref) in zip(tuples, refs) + ] + + +def _stack_arrays(tuples, dtype: np.dtype): + placement, arrays = zip(*tuples) + + first = arrays[0] + shape = (len(arrays),) + first.shape + + stacked = np.empty(shape, dtype=dtype) + for i, arr in enumerate(arrays): + stacked[i] = arr + + return stacked, placement + + +def _consolidate(blocks: tuple[Block, ...]) -> tuple[Block, ...]: + """ + Merge blocks having same dtype, exclude non-consolidating blocks + """ + # sort by _can_consolidate, dtype + gkey = lambda x: x._consolidate_key + grouper = itertools.groupby(sorted(blocks, key=gkey), gkey) + + new_blocks: list[Block] = [] + for (_can_consolidate, dtype), group_blocks in grouper: + merged_blocks, _ = _merge_blocks( + list(group_blocks), dtype=dtype, can_consolidate=_can_consolidate + ) + new_blocks = extend_blocks(merged_blocks, new_blocks) + return tuple(new_blocks) + + +def _merge_blocks( + blocks: list[Block], dtype: DtypeObj, can_consolidate: bool +) -> tuple[list[Block], bool]: + if len(blocks) == 1: + return blocks, False + + if can_consolidate: + # TODO: optimization potential in case all mgrs contain slices and + # combination of those slices is a slice, too. + new_mgr_locs = np.concatenate([b.mgr_locs.as_array for b in blocks]) + + new_values: ArrayLike + + if isinstance(blocks[0].dtype, np.dtype): + # error: List comprehension has incompatible type List[Union[ndarray, + # ExtensionArray]]; expected List[Union[complex, generic, + # Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], SupportsArray]] + new_values = np.vstack([b.values for b in blocks]) # type: ignore[misc] + else: + bvals = [blk.values for blk in blocks] + bvals2 = cast(Sequence[NDArrayBackedExtensionArray], bvals) + new_values = bvals2[0]._concat_same_type(bvals2, axis=0) + + argsort = np.argsort(new_mgr_locs) + new_values = new_values[argsort] + new_mgr_locs = new_mgr_locs[argsort] + + bp = BlockPlacement(new_mgr_locs) + return [new_block_2d(new_values, placement=bp)], True + + # can't consolidate --> no merge + return blocks, False + + +def _fast_count_smallints(arr: npt.NDArray[np.intp]): + """Faster version of set(arr) for sequences of small numbers.""" + counts = np.bincount(arr) + nz = counts.nonzero()[0] + # Note: list(zip(...) outperforms list(np.c_[nz, counts[nz]]) here, + # in one benchmark by a factor of 11 + return zip(nz, counts[nz]) + + +def _preprocess_slice_or_indexer( + slice_or_indexer: slice | np.ndarray, length: int, allow_fill: bool +): + if isinstance(slice_or_indexer, slice): + return ( + "slice", + slice_or_indexer, + libinternals.slice_len(slice_or_indexer, length), + ) + else: + if ( + not isinstance(slice_or_indexer, np.ndarray) + or slice_or_indexer.dtype.kind != "i" + ): + dtype = getattr(slice_or_indexer, "dtype", None) + raise TypeError(type(slice_or_indexer), dtype) + + indexer = ensure_platform_int(slice_or_indexer) + if not allow_fill: + indexer = maybe_convert_indices(indexer, length) + return "fancy", indexer, len(indexer) + + +def make_na_array(dtype: DtypeObj, shape: Shape, fill_value) -> ArrayLike: + if isinstance(dtype, DatetimeTZDtype): + # NB: exclude e.g. pyarrow[dt64tz] dtypes + ts = Timestamp(fill_value).as_unit(dtype.unit) + i8values = np.full(shape, ts._value) + dt64values = i8values.view(f"M8[{dtype.unit}]") + return DatetimeArray._simple_new(dt64values, dtype=dtype) + + elif is_1d_only_ea_dtype(dtype): + dtype = cast(ExtensionDtype, dtype) + cls = dtype.construct_array_type() + + missing_arr = cls._from_sequence([], dtype=dtype) + ncols, nrows = shape + assert ncols == 1, ncols + empty_arr = -1 * np.ones((nrows,), dtype=np.intp) + return missing_arr.take(empty_arr, allow_fill=True, fill_value=fill_value) + elif isinstance(dtype, ExtensionDtype): + # TODO: no tests get here, a handful would if we disabled + # the dt64tz special-case above (which is faster) + cls = dtype.construct_array_type() + missing_arr = cls._empty(shape=shape, dtype=dtype) + missing_arr[:] = fill_value + return missing_arr + else: + # NB: we should never get here with dtype integer or bool; + # if we did, the missing_arr.fill would cast to gibberish + missing_arr = np.empty(shape, dtype=dtype) + missing_arr.fill(fill_value) + + if dtype.kind in "mM": + missing_arr = ensure_wrapped_if_datetimelike(missing_arr) + return missing_arr diff --git a/shared/package-files/79/79dd20ec129d82a9fd768d1ae05ee25c16bb3790b8249f575287bf57452f6eaf/blob b/shared/package-files/79/79dd20ec129d82a9fd768d1ae05ee25c16bb3790b8249f575287bf57452f6eaf/blob new file mode 100644 index 0000000000000000000000000000000000000000..fef5ddc949bd2c88083f351605cca1fd5afd5909 --- /dev/null +++ b/shared/package-files/79/79dd20ec129d82a9fd768d1ae05ee25c16bb3790b8249f575287bf57452f6eaf/blob @@ -0,0 +1,3955 @@ +# -*- coding: utf-8 -*- +"""Main IPython class.""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2001 Janko Hauser +# Copyright (C) 2001-2007 Fernando Perez. +# Copyright (C) 2008-2011 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + + +import abc +import ast +import atexit +import bdb +import builtins as builtin_mod +import functools +import inspect +import os +import re +import runpy +import shutil +import subprocess +import sys +import tempfile +import traceback +import types +import warnings +from ast import stmt +from io import open as io_open +from logging import error +from pathlib import Path +from typing import Callable +from typing import List as ListType, Dict as DictType, Any as AnyType +from typing import Optional, Sequence, Tuple +from warnings import warn + +try: + from pickleshare import PickleShareDB +except ModuleNotFoundError: + + class PickleShareDB: # type: ignore [no-redef] + _mock = True + + def __init__(self, path): + pass + + def get(self, key, default): + warn( + f"using {key} requires you to install the `pickleshare` library.", + stacklevel=2, + ) + return default + + def __setitem__(self, key, value): + warn( + f"using {key} requires you to install the `pickleshare` library.", + stacklevel=2, + ) + + +from tempfile import TemporaryDirectory +from traitlets import ( + Any, + Bool, + CaselessStrEnum, + Dict, + Enum, + Instance, + Integer, + List, + Type, + Unicode, + default, + observe, + validate, +) +from traitlets.config.configurable import SingletonConfigurable +from traitlets.utils.importstring import import_item + +import IPython.core.hooks +from IPython.core import magic, oinspect, page, prefilter, ultratb +from IPython.core.alias import Alias, AliasManager +from IPython.core.autocall import ExitAutocall +from IPython.core.builtin_trap import BuiltinTrap +from IPython.core.compilerop import CachingCompiler +from IPython.core.debugger import InterruptiblePdb +from IPython.core.display_trap import DisplayTrap +from IPython.core.displayhook import DisplayHook +from IPython.core.displaypub import DisplayPublisher +from IPython.core.error import InputRejected, UsageError +from IPython.core.events import EventManager, available_events +from IPython.core.extensions import ExtensionManager +from IPython.core.formatters import DisplayFormatter +from IPython.core.history import HistoryManager +from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2 +from IPython.core.logger import Logger +from IPython.core.macro import Macro +from IPython.core.payload import PayloadManager +from IPython.core.prefilter import PrefilterManager +from IPython.core.profiledir import ProfileDir +from IPython.core.usage import default_banner +from IPython.display import display +from IPython.paths import get_ipython_dir +from IPython.testing.skipdoctest import skip_doctest +from IPython.utils import PyColorize, io, openpy, py3compat +from IPython.utils.decorators import undoc +from IPython.utils.io import ask_yes_no +from IPython.utils.ipstruct import Struct +from IPython.utils.path import ensure_dir_exists, get_home_dir, get_py_filename +from IPython.utils.process import getoutput, system +from IPython.utils.strdispatch import StrDispatch +from IPython.utils.syspathcontext import prepended_to_syspath +from IPython.utils.text import DollarFormatter, LSString, SList, format_screen +from IPython.core.oinspect import OInfo + + +sphinxify: Optional[Callable] + +try: + import docrepr.sphinxify as sphx + + def sphinxify(oinfo): + wrapped_docstring = sphx.wrap_main_docstring(oinfo) + + def sphinxify_docstring(docstring): + with TemporaryDirectory() as dirname: + return { + "text/html": sphx.sphinxify(wrapped_docstring, dirname), + "text/plain": docstring, + } + + return sphinxify_docstring +except ImportError: + sphinxify = None + +if sys.version_info[:2] < (3, 11): + from exceptiongroup import BaseExceptionGroup + +class ProvisionalWarning(DeprecationWarning): + """ + Warning class for unstable features + """ + pass + +from ast import Module + +_assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign) +_single_targets_nodes = (ast.AugAssign, ast.AnnAssign) + +#----------------------------------------------------------------------------- +# Await Helpers +#----------------------------------------------------------------------------- + +# we still need to run things using the asyncio eventloop, but there is no +# async integration +from .async_helpers import ( + _asyncio_runner, + _curio_runner, + _pseudo_sync_runner, + _should_be_async, + _trio_runner, +) + +#----------------------------------------------------------------------------- +# Globals +#----------------------------------------------------------------------------- + +# compiled regexps for autoindent management +dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') + +#----------------------------------------------------------------------------- +# Utilities +#----------------------------------------------------------------------------- + + +def is_integer_string(s: str): + """ + Variant of "str.isnumeric()" that allow negative values and other ints. + """ + try: + int(s) + return True + except ValueError: + return False + raise ValueError("Unexpected error") + + +@undoc +def softspace(file, newvalue): + """Copied from code.py, to remove the dependency""" + + oldvalue = 0 + try: + oldvalue = file.softspace + except AttributeError: + pass + try: + file.softspace = newvalue + except (AttributeError, TypeError): + # "attribute-less object" or "read-only attributes" + pass + return oldvalue + +@undoc +def no_op(*a, **kw): + pass + + +class SpaceInInput(Exception): pass + + +class SeparateUnicode(Unicode): + r"""A Unicode subclass to validate separate_in, separate_out, etc. + + This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. + """ + + def validate(self, obj, value): + if value == '0': value = '' + value = value.replace('\\n','\n') + return super(SeparateUnicode, self).validate(obj, value) + + +@undoc +class DummyMod(object): + """A dummy module used for IPython's interactive module when + a namespace must be assigned to the module's __dict__.""" + __spec__ = None + + +class ExecutionInfo(object): + """The arguments used for a call to :meth:`InteractiveShell.run_cell` + + Stores information about what is going to happen. + """ + raw_cell = None + store_history = False + silent = False + shell_futures = True + cell_id = None + + def __init__(self, raw_cell, store_history, silent, shell_futures, cell_id): + self.raw_cell = raw_cell + self.store_history = store_history + self.silent = silent + self.shell_futures = shell_futures + self.cell_id = cell_id + + def __repr__(self): + name = self.__class__.__qualname__ + raw_cell = ( + (self.raw_cell[:50] + "..") if len(self.raw_cell) > 50 else self.raw_cell + ) + return ( + '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>' + % ( + name, + id(self), + raw_cell, + self.store_history, + self.silent, + self.shell_futures, + self.cell_id, + ) + ) + + +class ExecutionResult(object): + """The result of a call to :meth:`InteractiveShell.run_cell` + + Stores information about what took place. + """ + execution_count = None + error_before_exec = None + error_in_exec: Optional[BaseException] = None + info = None + result = None + + def __init__(self, info): + self.info = info + + @property + def success(self): + return (self.error_before_exec is None) and (self.error_in_exec is None) + + def raise_error(self): + """Reraises error if `success` is `False`, otherwise does nothing""" + if self.error_before_exec is not None: + raise self.error_before_exec + if self.error_in_exec is not None: + raise self.error_in_exec + + def __repr__(self): + name = self.__class__.__qualname__ + return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\ + (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result)) + +@functools.wraps(io_open) +def _modified_open(file, *args, **kwargs): + if file in {0, 1, 2}: + raise ValueError( + f"IPython won't let you open fd={file} by default " + "as it is likely to crash IPython. If you know what you are doing, " + "you can use builtins' open." + ) + + return io_open(file, *args, **kwargs) + +class InteractiveShell(SingletonConfigurable): + """An enhanced, interactive shell for Python.""" + + _instance = None + + ast_transformers = List([], help= + """ + A list of ast.NodeTransformer subclass instances, which will be applied + to user input before code is run. + """ + ).tag(config=True) + + autocall = Enum((0,1,2), default_value=0, help= + """ + Make IPython automatically call any callable object even if you didn't + type explicit parentheses. For example, 'str 43' becomes 'str(43)' + automatically. The value can be '0' to disable the feature, '1' for + 'smart' autocall, where it is not applied if there are no more + arguments on the line, and '2' for 'full' autocall, where all callable + objects are automatically called (even if no arguments are present). + """ + ).tag(config=True) + + autoindent = Bool(True, help= + """ + Autoindent IPython code entered interactively. + """ + ).tag(config=True) + + autoawait = Bool(True, help= + """ + Automatically run await statement in the top level repl. + """ + ).tag(config=True) + + loop_runner_map ={ + 'asyncio':(_asyncio_runner, True), + 'curio':(_curio_runner, True), + 'trio':(_trio_runner, True), + 'sync': (_pseudo_sync_runner, False) + } + + loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner", + allow_none=True, + help="""Select the loop runner that will be used to execute top-level asynchronous code""" + ).tag(config=True) + + @default('loop_runner') + def _default_loop_runner(self): + return import_item("IPython.core.interactiveshell._asyncio_runner") + + @validate('loop_runner') + def _import_runner(self, proposal): + if isinstance(proposal.value, str): + if proposal.value in self.loop_runner_map: + runner, autoawait = self.loop_runner_map[proposal.value] + self.autoawait = autoawait + return runner + runner = import_item(proposal.value) + if not callable(runner): + raise ValueError('loop_runner must be callable') + return runner + if not callable(proposal.value): + raise ValueError('loop_runner must be callable') + return proposal.value + + automagic = Bool(True, help= + """ + Enable magic commands to be called without the leading %. + """ + ).tag(config=True) + + banner1 = Unicode(default_banner, + help="""The part of the banner to be printed before the profile""" + ).tag(config=True) + banner2 = Unicode('', + help="""The part of the banner to be printed after the profile""" + ).tag(config=True) + + cache_size = Integer(1000, help= + """ + Set the size of the output cache. The default is 1000, you can + change it permanently in your config file. Setting it to 0 completely + disables the caching system, and the minimum value accepted is 3 (if + you provide a value less than 3, it is reset to 0 and a warning is + issued). This limit is defined because otherwise you'll spend more + time re-flushing a too small cache than working + """ + ).tag(config=True) + color_info = Bool(True, help= + """ + Use colors for displaying information about objects. Because this + information is passed through a pager (like 'less'), and some pagers + get confused with color codes, this capability can be turned off. + """ + ).tag(config=True) + colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), + default_value='Neutral', + help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." + ).tag(config=True) + debug = Bool(False).tag(config=True) + disable_failing_post_execute = Bool(False, + help="Don't call post-execute functions that have failed in the past." + ).tag(config=True) + display_formatter = Instance(DisplayFormatter, allow_none=True) + displayhook_class = Type(DisplayHook) + display_pub_class = Type(DisplayPublisher) + compiler_class = Type(CachingCompiler) + inspector_class = Type( + oinspect.Inspector, help="Class to use to instantiate the shell inspector" + ).tag(config=True) + + sphinxify_docstring = Bool(False, help= + """ + Enables rich html representation of docstrings. (This requires the + docrepr module). + """).tag(config=True) + + @observe("sphinxify_docstring") + def _sphinxify_docstring_changed(self, change): + if change['new']: + warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) + + enable_html_pager = Bool(False, help= + """ + (Provisional API) enables html representation in mime bundles sent + to pagers. + """).tag(config=True) + + @observe("enable_html_pager") + def _enable_html_pager_changed(self, change): + if change['new']: + warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) + + data_pub_class = None + + exit_now = Bool(False) + exiter = Instance(ExitAutocall) + @default('exiter') + def _exiter_default(self): + return ExitAutocall(self) + # Monotonically increasing execution counter + execution_count = Integer(1) + filename = Unicode("") + ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ + + # Used to transform cells before running them, and check whether code is complete + input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', + ()) + + @property + def input_transformers_cleanup(self): + return self.input_transformer_manager.cleanup_transforms + + input_transformers_post = List([], + help="A list of string input transformers, to be applied after IPython's " + "own input transformations." + ) + + @property + def input_splitter(self): + """Make this available for backward compatibility (pre-7.0 release) with existing code. + + For example, ipykernel ipykernel currently uses + `shell.input_splitter.check_complete` + """ + from warnings import warn + warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.", + DeprecationWarning, stacklevel=2 + ) + return self.input_transformer_manager + + logstart = Bool(False, help= + """ + Start logging to the default log file in overwrite mode. + Use `logappend` to specify a log file to **append** logs to. + """ + ).tag(config=True) + logfile = Unicode('', help= + """ + The name of the logfile to use. + """ + ).tag(config=True) + logappend = Unicode('', help= + """ + Start logging to the given file in append mode. + Use `logfile` to specify a log file to **overwrite** logs to. + """ + ).tag(config=True) + object_info_string_level = Enum((0,1,2), default_value=0, + ).tag(config=True) + pdb = Bool(False, help= + """ + Automatically call the pdb debugger after every exception. + """ + ).tag(config=True) + display_page = Bool(False, + help="""If True, anything that would be passed to the pager + will be displayed as regular output instead.""" + ).tag(config=True) + + + show_rewritten_input = Bool(True, + help="Show rewritten input, e.g. for autocall." + ).tag(config=True) + + quiet = Bool(False).tag(config=True) + + history_length = Integer(10000, + help='Total length of command history' + ).tag(config=True) + + history_load_length = Integer(1000, help= + """ + The number of saved history entries to be loaded + into the history buffer at startup. + """ + ).tag(config=True) + + ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], + default_value='last_expr', + help=""" + 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying + which nodes should be run interactively (displaying output from expressions). + """ + ).tag(config=True) + + warn_venv = Bool( + True, + help="Warn if running in a virtual environment with no IPython installed (so IPython from the global environment is used).", + ).tag(config=True) + + # TODO: this part of prompt management should be moved to the frontends. + # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' + separate_in = SeparateUnicode('\n').tag(config=True) + separate_out = SeparateUnicode('').tag(config=True) + separate_out2 = SeparateUnicode('').tag(config=True) + wildcards_case_sensitive = Bool(True).tag(config=True) + xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'), + default_value='Context', + help="Switch modes for the IPython exception handlers." + ).tag(config=True) + + # Subcomponents of InteractiveShell + alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) + prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) + builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) + display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) + extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) + payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) + history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) + magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) + + profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) + @property + def profile(self): + if self.profile_dir is not None: + name = os.path.basename(self.profile_dir.location) + return name.replace('profile_','') + + + # Private interface + _post_execute = Dict() + + # Tracks any GUI loop loaded for pylab + pylab_gui_select = None + + last_execution_succeeded = Bool(True, help='Did last executed command succeeded') + + last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) + + def __init__(self, ipython_dir=None, profile_dir=None, + user_module=None, user_ns=None, + custom_exceptions=((), None), **kwargs): + # This is where traits with a config_key argument are updated + # from the values on config. + super(InteractiveShell, self).__init__(**kwargs) + if 'PromptManager' in self.config: + warn('As of IPython 5.0 `PromptManager` config will have no effect' + ' and has been replaced by TerminalInteractiveShell.prompts_class') + self.configurables = [self] + + # These are relatively independent and stateless + self.init_ipython_dir(ipython_dir) + self.init_profile_dir(profile_dir) + self.init_instance_attrs() + self.init_environment() + + # Check if we're in a virtualenv, and set up sys.path. + self.init_virtualenv() + + # Create namespaces (user_ns, user_global_ns, etc.) + self.init_create_namespaces(user_module, user_ns) + # This has to be done after init_create_namespaces because it uses + # something in self.user_ns, but before init_sys_modules, which + # is the first thing to modify sys. + # TODO: When we override sys.stdout and sys.stderr before this class + # is created, we are saving the overridden ones here. Not sure if this + # is what we want to do. + self.save_sys_module_state() + self.init_sys_modules() + + # While we're trying to have each part of the code directly access what + # it needs without keeping redundant references to objects, we have too + # much legacy code that expects ip.db to exist. + self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) + + self.init_history() + self.init_encoding() + self.init_prefilter() + + self.init_syntax_highlighting() + self.init_hooks() + self.init_events() + self.init_pushd_popd_magic() + self.init_user_ns() + self.init_logger() + self.init_builtins() + + # The following was in post_config_initialization + self.init_inspector() + self.raw_input_original = input + self.init_completer() + # TODO: init_io() needs to happen before init_traceback handlers + # because the traceback handlers hardcode the stdout/stderr streams. + # This logic in in debugger.Pdb and should eventually be changed. + self.init_io() + self.init_traceback_handlers(custom_exceptions) + self.init_prompts() + self.init_display_formatter() + self.init_display_pub() + self.init_data_pub() + self.init_displayhook() + self.init_magics() + self.init_alias() + self.init_logstart() + self.init_pdb() + self.init_extension_manager() + self.init_payload() + self.events.trigger('shell_initialized', self) + atexit.register(self.atexit_operations) + + # The trio runner is used for running Trio in the foreground thread. It + # is different from `_trio_runner(async_fn)` in `async_helpers.py` + # which calls `trio.run()` for every cell. This runner runs all cells + # inside a single Trio event loop. If used, it is set from + # `ipykernel.kernelapp`. + self.trio_runner = None + + def get_ipython(self): + """Return the currently running IPython instance.""" + return self + + #------------------------------------------------------------------------- + # Trait changed handlers + #------------------------------------------------------------------------- + @observe('ipython_dir') + def _ipython_dir_changed(self, change): + ensure_dir_exists(change['new']) + + def set_autoindent(self,value=None): + """Set the autoindent flag. + + If called with no arguments, it acts as a toggle.""" + if value is None: + self.autoindent = not self.autoindent + else: + self.autoindent = value + + def set_trio_runner(self, tr): + self.trio_runner = tr + + #------------------------------------------------------------------------- + # init_* methods called by __init__ + #------------------------------------------------------------------------- + + def init_ipython_dir(self, ipython_dir): + if ipython_dir is not None: + self.ipython_dir = ipython_dir + return + + self.ipython_dir = get_ipython_dir() + + def init_profile_dir(self, profile_dir): + if profile_dir is not None: + self.profile_dir = profile_dir + return + self.profile_dir = ProfileDir.create_profile_dir_by_name( + self.ipython_dir, "default" + ) + + def init_instance_attrs(self): + self.more = False + + # command compiler + self.compile = self.compiler_class() + + # Make an empty namespace, which extension writers can rely on both + # existing and NEVER being used by ipython itself. This gives them a + # convenient location for storing additional information and state + # their extensions may require, without fear of collisions with other + # ipython names that may develop later. + self.meta = Struct() + + # Temporary files used for various purposes. Deleted at exit. + # The files here are stored with Path from Pathlib + self.tempfiles = [] + self.tempdirs = [] + + # keep track of where we started running (mainly for crash post-mortem) + # This is not being used anywhere currently. + self.starting_dir = os.getcwd() + + # Indentation management + self.indent_current_nsp = 0 + + # Dict to track post-execution functions that have been registered + self._post_execute = {} + + def init_environment(self): + """Any changes we need to make to the user's environment.""" + pass + + def init_encoding(self): + # Get system encoding at startup time. Certain terminals (like Emacs + # under Win32 have it set to None, and we need to have a known valid + # encoding to use in the raw_input() method + try: + self.stdin_encoding = sys.stdin.encoding or 'ascii' + except AttributeError: + self.stdin_encoding = 'ascii' + + + @observe('colors') + def init_syntax_highlighting(self, changes=None): + # Python source parser/formatter for syntax highlighting + pyformat = PyColorize.Parser(style=self.colors, parent=self).format + self.pycolorize = lambda src: pyformat(src,'str') + + def refresh_style(self): + # No-op here, used in subclass + pass + + def init_pushd_popd_magic(self): + # for pushd/popd management + self.home_dir = get_home_dir() + + self.dir_stack = [] + + def init_logger(self): + self.logger = Logger(self.home_dir, logfname='ipython_log.py', + logmode='rotate') + + def init_logstart(self): + """Initialize logging in case it was requested at the command line. + """ + if self.logappend: + self.magic('logstart %s append' % self.logappend) + elif self.logfile: + self.magic('logstart %s' % self.logfile) + elif self.logstart: + self.magic('logstart') + + + def init_builtins(self): + # A single, static flag that we set to True. Its presence indicates + # that an IPython shell has been created, and we make no attempts at + # removing on exit or representing the existence of more than one + # IPython at a time. + builtin_mod.__dict__['__IPYTHON__'] = True + builtin_mod.__dict__['display'] = display + + self.builtin_trap = BuiltinTrap(shell=self) + + @observe('colors') + def init_inspector(self, changes=None): + # Object inspector + self.inspector = self.inspector_class( + oinspect.InspectColors, + PyColorize.ANSICodeColors, + self.colors, + self.object_info_string_level, + ) + + def init_io(self): + # implemented in subclasses, TerminalInteractiveShell does call + # colorama.init(). + pass + + def init_prompts(self): + # Set system prompts, so that scripts can decide if they are running + # interactively. + sys.ps1 = 'In : ' + sys.ps2 = '...: ' + sys.ps3 = 'Out: ' + + def init_display_formatter(self): + self.display_formatter = DisplayFormatter(parent=self) + self.configurables.append(self.display_formatter) + + def init_display_pub(self): + self.display_pub = self.display_pub_class(parent=self, shell=self) + self.configurables.append(self.display_pub) + + def init_data_pub(self): + if not self.data_pub_class: + self.data_pub = None + return + self.data_pub = self.data_pub_class(parent=self) + self.configurables.append(self.data_pub) + + def init_displayhook(self): + # Initialize displayhook, set in/out prompts and printing system + self.displayhook = self.displayhook_class( + parent=self, + shell=self, + cache_size=self.cache_size, + ) + self.configurables.append(self.displayhook) + # This is a context manager that installs/revmoes the displayhook at + # the appropriate time. + self.display_trap = DisplayTrap(hook=self.displayhook) + + @staticmethod + def get_path_links(p: Path): + """Gets path links including all symlinks + + Examples + -------- + In [1]: from IPython.core.interactiveshell import InteractiveShell + + In [2]: import sys, pathlib + + In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable)) + + In [4]: len(paths) == len(set(paths)) + Out[4]: True + + In [5]: bool(paths) + Out[5]: True + """ + paths = [p] + while p.is_symlink(): + new_path = Path(os.readlink(p)) + if not new_path.is_absolute(): + new_path = p.parent / new_path + p = new_path + paths.append(p) + return paths + + def init_virtualenv(self): + """Add the current virtualenv to sys.path so the user can import modules from it. + This isn't perfect: it doesn't use the Python interpreter with which the + virtualenv was built, and it ignores the --no-site-packages option. A + warning will appear suggesting the user installs IPython in the + virtualenv, but for many cases, it probably works well enough. + + Adapted from code snippets online. + + http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv + """ + if 'VIRTUAL_ENV' not in os.environ: + # Not in a virtualenv + return + elif os.environ["VIRTUAL_ENV"] == "": + warn("Virtual env path set to '', please check if this is intended.") + return + + p = Path(sys.executable) + p_venv = Path(os.environ["VIRTUAL_ENV"]) + + # fallback venv detection: + # stdlib venv may symlink sys.executable, so we can't use realpath. + # but others can symlink *to* the venv Python, so we can't just use sys.executable. + # So we just check every item in the symlink tree (generally <= 3) + paths = self.get_path_links(p) + + # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible + if p_venv.parts[1] == "cygdrive": + drive_name = p_venv.parts[2] + p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:]) + + if any(p_venv == p.parents[1] for p in paths): + # Our exe is inside or has access to the virtualenv, don't need to do anything. + return + + if sys.platform == "win32": + virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages")) + else: + virtual_env_path = Path( + os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages" + ) + p_ver = sys.version_info[:2] + + # Predict version from py[thon]-x.x in the $VIRTUAL_ENV + re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"]) + if re_m: + predicted_path = Path(str(virtual_env_path).format(*re_m.groups())) + if predicted_path.exists(): + p_ver = re_m.groups() + + virtual_env = str(virtual_env_path).format(*p_ver) + if self.warn_venv: + warn( + "Attempting to work in a virtualenv. If you encounter problems, " + "please install IPython inside the virtualenv." + ) + import site + sys.path.insert(0, virtual_env) + site.addsitedir(virtual_env) + + #------------------------------------------------------------------------- + # Things related to injections into the sys module + #------------------------------------------------------------------------- + + def save_sys_module_state(self): + """Save the state of hooks in the sys module. + + This has to be called after self.user_module is created. + """ + self._orig_sys_module_state = {'stdin': sys.stdin, + 'stdout': sys.stdout, + 'stderr': sys.stderr, + 'excepthook': sys.excepthook} + self._orig_sys_modules_main_name = self.user_module.__name__ + self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) + + def restore_sys_module_state(self): + """Restore the state of the sys module.""" + try: + for k, v in self._orig_sys_module_state.items(): + setattr(sys, k, v) + except AttributeError: + pass + # Reset what what done in self.init_sys_modules + if self._orig_sys_modules_main_mod is not None: + sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod + + #------------------------------------------------------------------------- + # Things related to the banner + #------------------------------------------------------------------------- + + @property + def banner(self): + banner = self.banner1 + if self.profile and self.profile != 'default': + banner += '\nIPython profile: %s\n' % self.profile + if self.banner2: + banner += '\n' + self.banner2 + return banner + + def show_banner(self, banner=None): + if banner is None: + banner = self.banner + sys.stdout.write(banner) + + #------------------------------------------------------------------------- + # Things related to hooks + #------------------------------------------------------------------------- + + def init_hooks(self): + # hooks holds pointers used for user-side customizations + self.hooks = Struct() + + self.strdispatchers = {} + + # Set all default hooks, defined in the IPython.hooks module. + hooks = IPython.core.hooks + for hook_name in hooks.__all__: + # default hooks have priority 100, i.e. low; user hooks should have + # 0-100 priority + self.set_hook(hook_name, getattr(hooks, hook_name), 100) + + if self.display_page: + self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) + + def set_hook(self, name, hook, priority=50, str_key=None, re_key=None): + """set_hook(name,hook) -> sets an internal IPython hook. + + IPython exposes some of its internal API as user-modifiable hooks. By + adding your function to one of these hooks, you can modify IPython's + behavior to call at runtime your own routines.""" + + # At some point in the future, this should validate the hook before it + # accepts it. Probably at least check that the hook takes the number + # of args it's supposed to. + + f = types.MethodType(hook,self) + + # check if the hook is for strdispatcher first + if str_key is not None: + sdp = self.strdispatchers.get(name, StrDispatch()) + sdp.add_s(str_key, f, priority ) + self.strdispatchers[name] = sdp + return + if re_key is not None: + sdp = self.strdispatchers.get(name, StrDispatch()) + sdp.add_re(re.compile(re_key), f, priority ) + self.strdispatchers[name] = sdp + return + + dp = getattr(self.hooks, name, None) + if name not in IPython.core.hooks.__all__: + print("Warning! Hook '%s' is not one of %s" % \ + (name, IPython.core.hooks.__all__ )) + + if name in IPython.core.hooks.deprecated: + alternative = IPython.core.hooks.deprecated[name] + raise ValueError( + "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format( + name, alternative + ) + ) + + if not dp: + dp = IPython.core.hooks.CommandChainDispatcher() + + try: + dp.add(f,priority) + except AttributeError: + # it was not commandchain, plain old func - replace + dp = f + + setattr(self.hooks,name, dp) + + #------------------------------------------------------------------------- + # Things related to events + #------------------------------------------------------------------------- + + def init_events(self): + self.events = EventManager(self, available_events) + + self.events.register("pre_execute", self._clear_warning_registry) + + def register_post_execute(self, func): + """DEPRECATED: Use ip.events.register('post_run_cell', func) + + Register a function for calling after code execution. + """ + raise ValueError( + "ip.register_post_execute is deprecated since IPython 1.0, use " + "ip.events.register('post_run_cell', func) instead." + ) + + def _clear_warning_registry(self): + # clear the warning registry, so that different code blocks with + # overlapping line number ranges don't cause spurious suppression of + # warnings (see gh-6611 for details) + if "__warningregistry__" in self.user_global_ns: + del self.user_global_ns["__warningregistry__"] + + #------------------------------------------------------------------------- + # Things related to the "main" module + #------------------------------------------------------------------------- + + def new_main_mod(self, filename, modname): + """Return a new 'main' module object for user code execution. + + ``filename`` should be the path of the script which will be run in the + module. Requests with the same filename will get the same module, with + its namespace cleared. + + ``modname`` should be the module name - normally either '__main__' or + the basename of the file without the extension. + + When scripts are executed via %run, we must keep a reference to their + __main__ module around so that Python doesn't + clear it, rendering references to module globals useless. + + This method keeps said reference in a private dict, keyed by the + absolute path of the script. This way, for multiple executions of the + same script we only keep one copy of the namespace (the last one), + thus preventing memory leaks from old references while allowing the + objects from the last execution to be accessible. + """ + filename = os.path.abspath(filename) + try: + main_mod = self._main_mod_cache[filename] + except KeyError: + main_mod = self._main_mod_cache[filename] = types.ModuleType( + modname, + doc="Module created for script run in IPython") + else: + main_mod.__dict__.clear() + main_mod.__name__ = modname + + main_mod.__file__ = filename + # It seems pydoc (and perhaps others) needs any module instance to + # implement a __nonzero__ method + main_mod.__nonzero__ = lambda : True + + return main_mod + + def clear_main_mod_cache(self): + """Clear the cache of main modules. + + Mainly for use by utilities like %reset. + + Examples + -------- + In [15]: import IPython + + In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') + + In [17]: len(_ip._main_mod_cache) > 0 + Out[17]: True + + In [18]: _ip.clear_main_mod_cache() + + In [19]: len(_ip._main_mod_cache) == 0 + Out[19]: True + """ + self._main_mod_cache.clear() + + #------------------------------------------------------------------------- + # Things related to debugging + #------------------------------------------------------------------------- + + def init_pdb(self): + # Set calling of pdb on exceptions + # self.call_pdb is a property + self.call_pdb = self.pdb + + def _get_call_pdb(self): + return self._call_pdb + + def _set_call_pdb(self,val): + + if val not in (0,1,False,True): + raise ValueError('new call_pdb value must be boolean') + + # store value in instance + self._call_pdb = val + + # notify the actual exception handlers + self.InteractiveTB.call_pdb = val + + call_pdb = property(_get_call_pdb,_set_call_pdb,None, + 'Control auto-activation of pdb at exceptions') + + def debugger(self,force=False): + """Call the pdb debugger. + + Keywords: + + - force(False): by default, this routine checks the instance call_pdb + flag and does not actually invoke the debugger if the flag is false. + The 'force' option forces the debugger to activate even if the flag + is false. + """ + + if not (force or self.call_pdb): + return + + if not hasattr(sys,'last_traceback'): + error('No traceback has been produced, nothing to debug.') + return + + self.InteractiveTB.debugger(force=True) + + #------------------------------------------------------------------------- + # Things related to IPython's various namespaces + #------------------------------------------------------------------------- + default_user_namespaces = True + + def init_create_namespaces(self, user_module=None, user_ns=None): + # Create the namespace where the user will operate. user_ns is + # normally the only one used, and it is passed to the exec calls as + # the locals argument. But we do carry a user_global_ns namespace + # given as the exec 'globals' argument, This is useful in embedding + # situations where the ipython shell opens in a context where the + # distinction between locals and globals is meaningful. For + # non-embedded contexts, it is just the same object as the user_ns dict. + + # FIXME. For some strange reason, __builtins__ is showing up at user + # level as a dict instead of a module. This is a manual fix, but I + # should really track down where the problem is coming from. Alex + # Schmolck reported this problem first. + + # A useful post by Alex Martelli on this topic: + # Re: inconsistent value from __builtins__ + # Von: Alex Martelli + # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends + # Gruppen: comp.lang.python + + # Michael Hohn wrote: + # > >>> print type(builtin_check.get_global_binding('__builtins__')) + # > + # > >>> print type(__builtins__) + # > + # > Is this difference in return value intentional? + + # Well, it's documented that '__builtins__' can be either a dictionary + # or a module, and it's been that way for a long time. Whether it's + # intentional (or sensible), I don't know. In any case, the idea is + # that if you need to access the built-in namespace directly, you + # should start with "import __builtin__" (note, no 's') which will + # definitely give you a module. Yeah, it's somewhat confusing:-(. + + # These routines return a properly built module and dict as needed by + # the rest of the code, and can also be used by extension writers to + # generate properly initialized namespaces. + if (user_ns is not None) or (user_module is not None): + self.default_user_namespaces = False + self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) + + # A record of hidden variables we have added to the user namespace, so + # we can list later only variables defined in actual interactive use. + self.user_ns_hidden = {} + + # Now that FakeModule produces a real module, we've run into a nasty + # problem: after script execution (via %run), the module where the user + # code ran is deleted. Now that this object is a true module (needed + # so doctest and other tools work correctly), the Python module + # teardown mechanism runs over it, and sets to None every variable + # present in that module. Top-level references to objects from the + # script survive, because the user_ns is updated with them. However, + # calling functions defined in the script that use other things from + # the script will fail, because the function's closure had references + # to the original objects, which are now all None. So we must protect + # these modules from deletion by keeping a cache. + # + # To avoid keeping stale modules around (we only need the one from the + # last run), we use a dict keyed with the full path to the script, so + # only the last version of the module is held in the cache. Note, + # however, that we must cache the module *namespace contents* (their + # __dict__). Because if we try to cache the actual modules, old ones + # (uncached) could be destroyed while still holding references (such as + # those held by GUI objects that tend to be long-lived)> + # + # The %reset command will flush this cache. See the cache_main_mod() + # and clear_main_mod_cache() methods for details on use. + + # This is the cache used for 'main' namespaces + self._main_mod_cache = {} + + # A table holding all the namespaces IPython deals with, so that + # introspection facilities can search easily. + self.ns_table = {'user_global':self.user_module.__dict__, + 'user_local':self.user_ns, + 'builtin':builtin_mod.__dict__ + } + + @property + def user_global_ns(self): + return self.user_module.__dict__ + + def prepare_user_module(self, user_module=None, user_ns=None): + """Prepare the module and namespace in which user code will be run. + + When IPython is started normally, both parameters are None: a new module + is created automatically, and its __dict__ used as the namespace. + + If only user_module is provided, its __dict__ is used as the namespace. + If only user_ns is provided, a dummy module is created, and user_ns + becomes the global namespace. If both are provided (as they may be + when embedding), user_ns is the local namespace, and user_module + provides the global namespace. + + Parameters + ---------- + user_module : module, optional + The current user module in which IPython is being run. If None, + a clean module will be created. + user_ns : dict, optional + A namespace in which to run interactive commands. + + Returns + ------- + A tuple of user_module and user_ns, each properly initialised. + """ + if user_module is None and user_ns is not None: + user_ns.setdefault("__name__", "__main__") + user_module = DummyMod() + user_module.__dict__ = user_ns + + if user_module is None: + user_module = types.ModuleType("__main__", + doc="Automatically created module for IPython interactive environment") + + # We must ensure that __builtin__ (without the final 's') is always + # available and pointing to the __builtin__ *module*. For more details: + # http://mail.python.org/pipermail/python-dev/2001-April/014068.html + user_module.__dict__.setdefault('__builtin__', builtin_mod) + user_module.__dict__.setdefault('__builtins__', builtin_mod) + + if user_ns is None: + user_ns = user_module.__dict__ + + return user_module, user_ns + + def init_sys_modules(self): + # We need to insert into sys.modules something that looks like a + # module but which accesses the IPython namespace, for shelve and + # pickle to work interactively. Normally they rely on getting + # everything out of __main__, but for embedding purposes each IPython + # instance has its own private namespace, so we can't go shoving + # everything into __main__. + + # note, however, that we should only do this for non-embedded + # ipythons, which really mimic the __main__.__dict__ with their own + # namespace. Embedded instances, on the other hand, should not do + # this because they need to manage the user local/global namespaces + # only, but they live within a 'normal' __main__ (meaning, they + # shouldn't overtake the execution environment of the script they're + # embedded in). + + # This is overridden in the InteractiveShellEmbed subclass to a no-op. + main_name = self.user_module.__name__ + sys.modules[main_name] = self.user_module + + def init_user_ns(self): + """Initialize all user-visible namespaces to their minimum defaults. + + Certain history lists are also initialized here, as they effectively + act as user namespaces. + + Notes + ----- + All data structures here are only filled in, they are NOT reset by this + method. If they were not empty before, data will simply be added to + them. + """ + # This function works in two parts: first we put a few things in + # user_ns, and we sync that contents into user_ns_hidden so that these + # initial variables aren't shown by %who. After the sync, we add the + # rest of what we *do* want the user to see with %who even on a new + # session (probably nothing, so they really only see their own stuff) + + # The user dict must *always* have a __builtin__ reference to the + # Python standard __builtin__ namespace, which must be imported. + # This is so that certain operations in prompt evaluation can be + # reliably executed with builtins. Note that we can NOT use + # __builtins__ (note the 's'), because that can either be a dict or a + # module, and can even mutate at runtime, depending on the context + # (Python makes no guarantees on it). In contrast, __builtin__ is + # always a module object, though it must be explicitly imported. + + # For more details: + # http://mail.python.org/pipermail/python-dev/2001-April/014068.html + ns = {} + + # make global variables for user access to the histories + ns['_ih'] = self.history_manager.input_hist_parsed + ns['_oh'] = self.history_manager.output_hist + ns['_dh'] = self.history_manager.dir_hist + + # user aliases to input and output histories. These shouldn't show up + # in %who, as they can have very large reprs. + ns['In'] = self.history_manager.input_hist_parsed + ns['Out'] = self.history_manager.output_hist + + # Store myself as the public api!!! + ns['get_ipython'] = self.get_ipython + + ns['exit'] = self.exiter + ns['quit'] = self.exiter + ns["open"] = _modified_open + + # Sync what we've added so far to user_ns_hidden so these aren't seen + # by %who + self.user_ns_hidden.update(ns) + + # Anything put into ns now would show up in %who. Think twice before + # putting anything here, as we really want %who to show the user their + # stuff, not our variables. + + # Finally, update the real user's namespace + self.user_ns.update(ns) + + @property + def all_ns_refs(self): + """Get a list of references to all the namespace dictionaries in which + IPython might store a user-created object. + + Note that this does not include the displayhook, which also caches + objects from the output.""" + return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ + [m.__dict__ for m in self._main_mod_cache.values()] + + def reset(self, new_session=True, aggressive=False): + """Clear all internal namespaces, and attempt to release references to + user objects. + + If new_session is True, a new history session will be opened. + """ + # Clear histories + self.history_manager.reset(new_session) + # Reset counter used to index all histories + if new_session: + self.execution_count = 1 + + # Reset last execution result + self.last_execution_succeeded = True + self.last_execution_result = None + + # Flush cached output items + if self.displayhook.do_full_cache: + self.displayhook.flush() + + # The main execution namespaces must be cleared very carefully, + # skipping the deletion of the builtin-related keys, because doing so + # would cause errors in many object's __del__ methods. + if self.user_ns is not self.user_global_ns: + self.user_ns.clear() + ns = self.user_global_ns + drop_keys = set(ns.keys()) + drop_keys.discard('__builtin__') + drop_keys.discard('__builtins__') + drop_keys.discard('__name__') + for k in drop_keys: + del ns[k] + + self.user_ns_hidden.clear() + + # Restore the user namespaces to minimal usability + self.init_user_ns() + if aggressive and not hasattr(self, "_sys_modules_keys"): + print("Cannot restore sys.module, no snapshot") + elif aggressive: + print("culling sys module...") + current_keys = set(sys.modules.keys()) + for k in current_keys - self._sys_modules_keys: + if k.startswith("multiprocessing"): + continue + del sys.modules[k] + + # Restore the default and user aliases + self.alias_manager.clear_aliases() + self.alias_manager.init_aliases() + + # Now define aliases that only make sense on the terminal, because they + # need direct access to the console in a way that we can't emulate in + # GUI or web frontend + if os.name == 'posix': + for cmd in ('clear', 'more', 'less', 'man'): + if cmd not in self.magics_manager.magics['line']: + self.alias_manager.soft_define_alias(cmd, cmd) + + # Flush the private list of module references kept for script + # execution protection + self.clear_main_mod_cache() + + def del_var(self, varname, by_name=False): + """Delete a variable from the various namespaces, so that, as + far as possible, we're not keeping any hidden references to it. + + Parameters + ---------- + varname : str + The name of the variable to delete. + by_name : bool + If True, delete variables with the given name in each + namespace. If False (default), find the variable in the user + namespace, and delete references to it. + """ + if varname in ('__builtin__', '__builtins__'): + raise ValueError("Refusing to delete %s" % varname) + + ns_refs = self.all_ns_refs + + if by_name: # Delete by name + for ns in ns_refs: + try: + del ns[varname] + except KeyError: + pass + else: # Delete by object + try: + obj = self.user_ns[varname] + except KeyError as e: + raise NameError("name '%s' is not defined" % varname) from e + # Also check in output history + ns_refs.append(self.history_manager.output_hist) + for ns in ns_refs: + to_delete = [n for n, o in ns.items() if o is obj] + for name in to_delete: + del ns[name] + + # Ensure it is removed from the last execution result + if self.last_execution_result.result is obj: + self.last_execution_result = None + + # displayhook keeps extra references, but not in a dictionary + for name in ('_', '__', '___'): + if getattr(self.displayhook, name) is obj: + setattr(self.displayhook, name, None) + + def reset_selective(self, regex=None): + """Clear selective variables from internal namespaces based on a + specified regular expression. + + Parameters + ---------- + regex : string or compiled pattern, optional + A regular expression pattern that will be used in searching + variable names in the users namespaces. + """ + if regex is not None: + try: + m = re.compile(regex) + except TypeError as e: + raise TypeError('regex must be a string or compiled pattern') from e + # Search for keys in each namespace that match the given regex + # If a match is found, delete the key/value pair. + for ns in self.all_ns_refs: + for var in ns: + if m.search(var): + del ns[var] + + def push(self, variables, interactive=True): + """Inject a group of variables into the IPython user namespace. + + Parameters + ---------- + variables : dict, str or list/tuple of str + The variables to inject into the user's namespace. If a dict, a + simple update is done. If a str, the string is assumed to have + variable names separated by spaces. A list/tuple of str can also + be used to give the variable names. If just the variable names are + give (list/tuple/str) then the variable values looked up in the + callers frame. + interactive : bool + If True (default), the variables will be listed with the ``who`` + magic. + """ + vdict = None + + # We need a dict of name/value pairs to do namespace updates. + if isinstance(variables, dict): + vdict = variables + elif isinstance(variables, (str, list, tuple)): + if isinstance(variables, str): + vlist = variables.split() + else: + vlist = variables + vdict = {} + cf = sys._getframe(1) + for name in vlist: + try: + vdict[name] = eval(name, cf.f_globals, cf.f_locals) + except: + print('Could not get variable %s from %s' % + (name,cf.f_code.co_name)) + else: + raise ValueError('variables must be a dict/str/list/tuple') + + # Propagate variables to user namespace + self.user_ns.update(vdict) + + # And configure interactive visibility + user_ns_hidden = self.user_ns_hidden + if interactive: + for name in vdict: + user_ns_hidden.pop(name, None) + else: + user_ns_hidden.update(vdict) + + def drop_by_id(self, variables): + """Remove a dict of variables from the user namespace, if they are the + same as the values in the dictionary. + + This is intended for use by extensions: variables that they've added can + be taken back out if they are unloaded, without removing any that the + user has overwritten. + + Parameters + ---------- + variables : dict + A dictionary mapping object names (as strings) to the objects. + """ + for name, obj in variables.items(): + if name in self.user_ns and self.user_ns[name] is obj: + del self.user_ns[name] + self.user_ns_hidden.pop(name, None) + + #------------------------------------------------------------------------- + # Things related to object introspection + #------------------------------------------------------------------------- + @staticmethod + def _find_parts(oname: str) -> Tuple[bool, ListType[str]]: + """ + Given an object name, return a list of parts of this object name. + + Basically split on docs when using attribute access, + and extract the value when using square bracket. + + + For example foo.bar[3].baz[x] -> foo, bar, 3, baz, x + + + Returns + ------- + parts_ok: bool + wether we were properly able to parse parts. + parts: list of str + extracted parts + + + + """ + raw_parts = oname.split(".") + parts = [] + parts_ok = True + for p in raw_parts: + if p.endswith("]"): + var, *indices = p.split("[") + if not var.isidentifier(): + parts_ok = False + break + parts.append(var) + for ind in indices: + if ind[-1] != "]" and not is_integer_string(ind[:-1]): + parts_ok = False + break + parts.append(ind[:-1]) + continue + + if not p.isidentifier(): + parts_ok = False + parts.append(p) + + return parts_ok, parts + + def _ofind( + self, oname: str, namespaces: Optional[Sequence[Tuple[str, AnyType]]] = None + ) -> OInfo: + """Find an object in the available namespaces. + + + Returns + ------- + OInfo with fields: + - ismagic + - isalias + - found + - obj + - namespac + - parent + + Has special code to detect magic functions. + """ + oname = oname.strip() + parts_ok, parts = self._find_parts(oname) + + if ( + not oname.startswith(ESC_MAGIC) + and not oname.startswith(ESC_MAGIC2) + and not parts_ok + ): + return OInfo( + ismagic=False, + isalias=False, + found=False, + obj=None, + namespace=None, + parent=None, + ) + + if namespaces is None: + # Namespaces to search in: + # Put them in a list. The order is important so that we + # find things in the same order that Python finds them. + namespaces = [ ('Interactive', self.user_ns), + ('Interactive (global)', self.user_global_ns), + ('Python builtin', builtin_mod.__dict__), + ] + + ismagic = False + isalias = False + found = False + ospace = None + parent = None + obj = None + + + # Look for the given name by splitting it in parts. If the head is + # found, then we look for all the remaining parts as members, and only + # declare success if we can find them all. + oname_parts = parts + oname_head, oname_rest = oname_parts[0],oname_parts[1:] + for nsname,ns in namespaces: + try: + obj = ns[oname_head] + except KeyError: + continue + else: + for idx, part in enumerate(oname_rest): + try: + parent = obj + # The last part is looked up in a special way to avoid + # descriptor invocation as it may raise or have side + # effects. + if idx == len(oname_rest) - 1: + obj = self._getattr_property(obj, part) + else: + if is_integer_string(part): + obj = obj[int(part)] + else: + obj = getattr(obj, part) + except: + # Blanket except b/c some badly implemented objects + # allow __getattr__ to raise exceptions other than + # AttributeError, which then crashes IPython. + break + else: + # If we finish the for loop (no break), we got all members + found = True + ospace = nsname + break # namespace loop + + # Try to see if it's magic + if not found: + obj = None + if oname.startswith(ESC_MAGIC2): + oname = oname.lstrip(ESC_MAGIC2) + obj = self.find_cell_magic(oname) + elif oname.startswith(ESC_MAGIC): + oname = oname.lstrip(ESC_MAGIC) + obj = self.find_line_magic(oname) + else: + # search without prefix, so run? will find %run? + obj = self.find_line_magic(oname) + if obj is None: + obj = self.find_cell_magic(oname) + if obj is not None: + found = True + ospace = 'IPython internal' + ismagic = True + isalias = isinstance(obj, Alias) + + # Last try: special-case some literals like '', [], {}, etc: + if not found and oname_head in ["''",'""','[]','{}','()']: + obj = eval(oname_head) + found = True + ospace = 'Interactive' + + return OInfo( + obj=obj, + found=found, + parent=parent, + ismagic=ismagic, + isalias=isalias, + namespace=ospace, + ) + + @staticmethod + def _getattr_property(obj, attrname): + """Property-aware getattr to use in object finding. + + If attrname represents a property, return it unevaluated (in case it has + side effects or raises an error. + + """ + if not isinstance(obj, type): + try: + # `getattr(type(obj), attrname)` is not guaranteed to return + # `obj`, but does so for property: + # + # property.__get__(self, None, cls) -> self + # + # The universal alternative is to traverse the mro manually + # searching for attrname in class dicts. + if is_integer_string(attrname): + return obj[int(attrname)] + else: + attr = getattr(type(obj), attrname) + except AttributeError: + pass + else: + # This relies on the fact that data descriptors (with both + # __get__ & __set__ magic methods) take precedence over + # instance-level attributes: + # + # class A(object): + # @property + # def foobar(self): return 123 + # a = A() + # a.__dict__['foobar'] = 345 + # a.foobar # == 123 + # + # So, a property may be returned right away. + if isinstance(attr, property): + return attr + + # Nothing helped, fall back. + return getattr(obj, attrname) + + def _object_find(self, oname, namespaces=None) -> OInfo: + """Find an object and return a struct with info about it.""" + return self._ofind(oname, namespaces) + + def _inspect(self, meth, oname, namespaces=None, **kw): + """Generic interface to the inspector system. + + This function is meant to be called by pdef, pdoc & friends. + """ + info: OInfo = self._object_find(oname, namespaces) + if self.sphinxify_docstring: + if sphinxify is None: + raise ImportError("Module ``docrepr`` required but missing") + docformat = sphinxify(self.object_inspect(oname)) + else: + docformat = None + if info.found or hasattr(info.parent, oinspect.HOOK_NAME): + pmethod = getattr(self.inspector, meth) + # TODO: only apply format_screen to the plain/text repr of the mime + # bundle. + formatter = format_screen if info.ismagic else docformat + if meth == 'pdoc': + pmethod(info.obj, oname, formatter) + elif meth == 'pinfo': + pmethod( + info.obj, + oname, + formatter, + info, + enable_html_pager=self.enable_html_pager, + **kw, + ) + else: + pmethod(info.obj, oname) + else: + print('Object `%s` not found.' % oname) + return 'not found' # so callers can take other action + + def object_inspect(self, oname, detail_level=0): + """Get object info about oname""" + with self.builtin_trap: + info = self._object_find(oname) + if info.found: + return self.inspector.info(info.obj, oname, info=info, + detail_level=detail_level + ) + else: + return oinspect.object_info(name=oname, found=False) + + def object_inspect_text(self, oname, detail_level=0): + """Get object info as formatted text""" + return self.object_inspect_mime(oname, detail_level)['text/plain'] + + def object_inspect_mime(self, oname, detail_level=0, omit_sections=()): + """Get object info as a mimebundle of formatted representations. + + A mimebundle is a dictionary, keyed by mime-type. + It must always have the key `'text/plain'`. + """ + with self.builtin_trap: + info = self._object_find(oname) + if info.found: + docformat = ( + sphinxify(self.object_inspect(oname)) + if self.sphinxify_docstring + else None + ) + return self.inspector._get_info( + info.obj, + oname, + info=info, + detail_level=detail_level, + formatter=docformat, + omit_sections=omit_sections, + ) + else: + raise KeyError(oname) + + #------------------------------------------------------------------------- + # Things related to history management + #------------------------------------------------------------------------- + + def init_history(self): + """Sets up the command history, and starts regular autosaves.""" + self.history_manager = HistoryManager(shell=self, parent=self) + self.configurables.append(self.history_manager) + + #------------------------------------------------------------------------- + # Things related to exception handling and tracebacks (not debugging) + #------------------------------------------------------------------------- + + debugger_cls = InterruptiblePdb + + def init_traceback_handlers(self, custom_exceptions): + # Syntax error handler. + self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) + + # The interactive one is initialized with an offset, meaning we always + # want to remove the topmost item in the traceback, which is our own + # internal code. Valid modes: ['Plain','Context','Verbose','Minimal'] + self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', + color_scheme='NoColor', + tb_offset = 1, + debugger_cls=self.debugger_cls, parent=self) + + # The instance will store a pointer to the system-wide exception hook, + # so that runtime code (such as magics) can access it. This is because + # during the read-eval loop, it may get temporarily overwritten. + self.sys_excepthook = sys.excepthook + + # and add any custom exception handlers the user may have specified + self.set_custom_exc(*custom_exceptions) + + # Set the exception mode + self.InteractiveTB.set_mode(mode=self.xmode) + + def set_custom_exc(self, exc_tuple, handler): + """set_custom_exc(exc_tuple, handler) + + Set a custom exception handler, which will be called if any of the + exceptions in exc_tuple occur in the mainloop (specifically, in the + run_code() method). + + Parameters + ---------- + exc_tuple : tuple of exception classes + A *tuple* of exception classes, for which to call the defined + handler. It is very important that you use a tuple, and NOT A + LIST here, because of the way Python's except statement works. If + you only want to trap a single exception, use a singleton tuple:: + + exc_tuple == (MyCustomException,) + + handler : callable + handler must have the following signature:: + + def my_handler(self, etype, value, tb, tb_offset=None): + ... + return structured_traceback + + Your handler must return a structured traceback (a list of strings), + or None. + + This will be made into an instance method (via types.MethodType) + of IPython itself, and it will be called if any of the exceptions + listed in the exc_tuple are caught. If the handler is None, an + internal basic one is used, which just prints basic info. + + To protect IPython from crashes, if your handler ever raises an + exception or returns an invalid result, it will be immediately + disabled. + + Notes + ----- + WARNING: by putting in your own exception handler into IPython's main + execution loop, you run a very good chance of nasty crashes. This + facility should only be used if you really know what you are doing. + """ + + if not isinstance(exc_tuple, tuple): + raise TypeError("The custom exceptions must be given as a tuple.") + + def dummy_handler(self, etype, value, tb, tb_offset=None): + print('*** Simple custom exception handler ***') + print('Exception type :', etype) + print('Exception value:', value) + print('Traceback :', tb) + + def validate_stb(stb): + """validate structured traceback return type + + return type of CustomTB *should* be a list of strings, but allow + single strings or None, which are harmless. + + This function will *always* return a list of strings, + and will raise a TypeError if stb is inappropriate. + """ + msg = "CustomTB must return list of strings, not %r" % stb + if stb is None: + return [] + elif isinstance(stb, str): + return [stb] + elif not isinstance(stb, list): + raise TypeError(msg) + # it's a list + for line in stb: + # check every element + if not isinstance(line, str): + raise TypeError(msg) + return stb + + if handler is None: + wrapped = dummy_handler + else: + def wrapped(self,etype,value,tb,tb_offset=None): + """wrap CustomTB handler, to protect IPython from user code + + This makes it harder (but not impossible) for custom exception + handlers to crash IPython. + """ + try: + stb = handler(self,etype,value,tb,tb_offset=tb_offset) + return validate_stb(stb) + except: + # clear custom handler immediately + self.set_custom_exc((), None) + print("Custom TB Handler failed, unregistering", file=sys.stderr) + # show the exception in handler first + stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) + print(self.InteractiveTB.stb2text(stb)) + print("The original exception:") + stb = self.InteractiveTB.structured_traceback( + (etype,value,tb), tb_offset=tb_offset + ) + return stb + + self.CustomTB = types.MethodType(wrapped,self) + self.custom_exceptions = exc_tuple + + def excepthook(self, etype, value, tb): + """One more defense for GUI apps that call sys.excepthook. + + GUI frameworks like wxPython trap exceptions and call + sys.excepthook themselves. I guess this is a feature that + enables them to keep running after exceptions that would + otherwise kill their mainloop. This is a bother for IPython + which expects to catch all of the program exceptions with a try: + except: statement. + + Normally, IPython sets sys.excepthook to a CrashHandler instance, so if + any app directly invokes sys.excepthook, it will look to the user like + IPython crashed. In order to work around this, we can disable the + CrashHandler and replace it with this excepthook instead, which prints a + regular traceback using our InteractiveTB. In this fashion, apps which + call sys.excepthook will generate a regular-looking exception from + IPython, and the CrashHandler will only be triggered by real IPython + crashes. + + This hook should be used sparingly, only in places which are not likely + to be true IPython errors. + """ + self.showtraceback((etype, value, tb), tb_offset=0) + + def _get_exc_info(self, exc_tuple=None): + """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. + + Ensures sys.last_type,value,traceback hold the exc_info we found, + from whichever source. + + raises ValueError if none of these contain any information + """ + if exc_tuple is None: + etype, value, tb = sys.exc_info() + else: + etype, value, tb = exc_tuple + + if etype is None: + if hasattr(sys, 'last_type'): + etype, value, tb = sys.last_type, sys.last_value, \ + sys.last_traceback + + if etype is None: + raise ValueError("No exception to find") + + # Now store the exception info in sys.last_type etc. + # WARNING: these variables are somewhat deprecated and not + # necessarily safe to use in a threaded environment, but tools + # like pdb depend on their existence, so let's set them. If we + # find problems in the field, we'll need to revisit their use. + sys.last_type = etype + sys.last_value = value + sys.last_traceback = tb + + return etype, value, tb + + def show_usage_error(self, exc): + """Show a short message for UsageErrors + + These are special exceptions that shouldn't show a traceback. + """ + print("UsageError: %s" % exc, file=sys.stderr) + + def get_exception_only(self, exc_tuple=None): + """ + Return as a string (ending with a newline) the exception that + just occurred, without any traceback. + """ + etype, value, tb = self._get_exc_info(exc_tuple) + msg = traceback.format_exception_only(etype, value) + return ''.join(msg) + + def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, + exception_only=False, running_compiled_code=False): + """Display the exception that just occurred. + + If nothing is known about the exception, this is the method which + should be used throughout the code for presenting user tracebacks, + rather than directly invoking the InteractiveTB object. + + A specific showsyntaxerror() also exists, but this method can take + care of calling it if needed, so unless you are explicitly catching a + SyntaxError exception, don't try to analyze the stack manually and + simply call this method.""" + + try: + try: + etype, value, tb = self._get_exc_info(exc_tuple) + except ValueError: + print('No traceback available to show.', file=sys.stderr) + return + + if issubclass(etype, SyntaxError): + # Though this won't be called by syntax errors in the input + # line, there may be SyntaxError cases with imported code. + self.showsyntaxerror(filename, running_compiled_code) + elif etype is UsageError: + self.show_usage_error(value) + else: + if exception_only: + stb = ['An exception has occurred, use %tb to see ' + 'the full traceback.\n'] + stb.extend(self.InteractiveTB.get_exception_only(etype, + value)) + else: + + def contains_exceptiongroup(val): + if val is None: + return False + return isinstance( + val, BaseExceptionGroup + ) or contains_exceptiongroup(val.__context__) + + if contains_exceptiongroup(value): + # fall back to native exception formatting until ultratb + # supports exception groups + traceback.print_exc() + else: + try: + # Exception classes can customise their traceback - we + # use this in IPython.parallel for exceptions occurring + # in the engines. This should return a list of strings. + if hasattr(value, "_render_traceback_"): + stb = value._render_traceback_() + else: + stb = self.InteractiveTB.structured_traceback( + etype, value, tb, tb_offset=tb_offset + ) + + except Exception: + print( + "Unexpected exception formatting exception. Falling back to standard exception" + ) + traceback.print_exc() + return None + + self._showtraceback(etype, value, stb) + if self.call_pdb: + # drop into debugger + self.debugger(force=True) + return + + # Actually show the traceback + self._showtraceback(etype, value, stb) + + except KeyboardInterrupt: + print('\n' + self.get_exception_only(), file=sys.stderr) + + def _showtraceback(self, etype, evalue, stb: str): + """Actually show a traceback. + + Subclasses may override this method to put the traceback on a different + place, like a side channel. + """ + val = self.InteractiveTB.stb2text(stb) + try: + print(val) + except UnicodeEncodeError: + print(val.encode("utf-8", "backslashreplace").decode()) + + def showsyntaxerror(self, filename=None, running_compiled_code=False): + """Display the syntax error that just occurred. + + This doesn't display a stack trace because there isn't one. + + If a filename is given, it is stuffed in the exception instead + of what was there before (because Python's parser always uses + "" when reading from a string). + + If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), + longer stack trace will be displayed. + """ + etype, value, last_traceback = self._get_exc_info() + + if filename and issubclass(etype, SyntaxError): + try: + value.filename = filename + except: + # Not the format we expect; leave it alone + pass + + # If the error occurred when executing compiled code, we should provide full stacktrace. + elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] + stb = self.SyntaxTB.structured_traceback(etype, value, elist) + self._showtraceback(etype, value, stb) + + # This is overridden in TerminalInteractiveShell to show a message about + # the %paste magic. + def showindentationerror(self): + """Called by _run_cell when there's an IndentationError in code entered + at the prompt. + + This is overridden in TerminalInteractiveShell to show a message about + the %paste magic.""" + self.showsyntaxerror() + + @skip_doctest + def set_next_input(self, s, replace=False): + """ Sets the 'default' input string for the next command line. + + Example:: + + In [1]: _ip.set_next_input("Hello Word") + In [2]: Hello Word_ # cursor is here + """ + self.rl_next_input = s + + def _indent_current_str(self): + """return the current level of indentation as a string""" + return self.input_splitter.get_indent_spaces() * ' ' + + #------------------------------------------------------------------------- + # Things related to text completion + #------------------------------------------------------------------------- + + def init_completer(self): + """Initialize the completion machinery. + + This creates completion machinery that can be used by client code, + either interactively in-process (typically triggered by the readline + library), programmatically (such as in test suites) or out-of-process + (typically over the network by remote frontends). + """ + from IPython.core.completer import IPCompleter + from IPython.core.completerlib import ( + cd_completer, + magic_run_completer, + module_completer, + reset_completer, + ) + + self.Completer = IPCompleter(shell=self, + namespace=self.user_ns, + global_namespace=self.user_global_ns, + parent=self, + ) + self.configurables.append(self.Completer) + + # Add custom completers to the basic ones built into IPCompleter + sdisp = self.strdispatchers.get('complete_command', StrDispatch()) + self.strdispatchers['complete_command'] = sdisp + self.Completer.custom_completers = sdisp + + self.set_hook('complete_command', module_completer, str_key = 'import') + self.set_hook('complete_command', module_completer, str_key = 'from') + self.set_hook('complete_command', module_completer, str_key = '%aimport') + self.set_hook('complete_command', magic_run_completer, str_key = '%run') + self.set_hook('complete_command', cd_completer, str_key = '%cd') + self.set_hook('complete_command', reset_completer, str_key = '%reset') + + @skip_doctest + def complete(self, text, line=None, cursor_pos=None): + """Return the completed text and a list of completions. + + Parameters + ---------- + text : string + A string of text to be completed on. It can be given as empty and + instead a line/position pair are given. In this case, the + completer itself will split the line like readline does. + line : string, optional + The complete line that text is part of. + cursor_pos : int, optional + The position of the cursor on the input line. + + Returns + ------- + text : string + The actual text that was completed. + matches : list + A sorted list with all possible completions. + + Notes + ----- + The optional arguments allow the completion to take more context into + account, and are part of the low-level completion API. + + This is a wrapper around the completion mechanism, similar to what + readline does at the command line when the TAB key is hit. By + exposing it as a method, it can be used by other non-readline + environments (such as GUIs) for text completion. + + Examples + -------- + In [1]: x = 'hello' + + In [2]: _ip.complete('x.l') + Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) + """ + + # Inject names into __builtin__ so we can complete on the added names. + with self.builtin_trap: + return self.Completer.complete(text, line, cursor_pos) + + def set_custom_completer(self, completer, pos=0) -> None: + """Adds a new custom completer function. + + The position argument (defaults to 0) is the index in the completers + list where you want the completer to be inserted. + + `completer` should have the following signature:: + + def completion(self: Completer, text: string) -> List[str]: + raise NotImplementedError + + It will be bound to the current Completer instance and pass some text + and return a list with current completions to suggest to the user. + """ + + newcomp = types.MethodType(completer, self.Completer) + self.Completer.custom_matchers.insert(pos,newcomp) + + def set_completer_frame(self, frame=None): + """Set the frame of the completer.""" + if frame: + self.Completer.namespace = frame.f_locals + self.Completer.global_namespace = frame.f_globals + else: + self.Completer.namespace = self.user_ns + self.Completer.global_namespace = self.user_global_ns + + #------------------------------------------------------------------------- + # Things related to magics + #------------------------------------------------------------------------- + + def init_magics(self): + from IPython.core import magics as m + self.magics_manager = magic.MagicsManager(shell=self, + parent=self, + user_magics=m.UserMagics(self)) + self.configurables.append(self.magics_manager) + + # Expose as public API from the magics manager + self.register_magics = self.magics_manager.register + + self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, + m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, + m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, + m.NamespaceMagics, m.OSMagics, m.PackagingMagics, + m.PylabMagics, m.ScriptMagics, + ) + self.register_magics(m.AsyncMagics) + + # Register Magic Aliases + mman = self.magics_manager + # FIXME: magic aliases should be defined by the Magics classes + # or in MagicsManager, not here + mman.register_alias('ed', 'edit') + mman.register_alias('hist', 'history') + mman.register_alias('rep', 'recall') + mman.register_alias('SVG', 'svg', 'cell') + mman.register_alias('HTML', 'html', 'cell') + mman.register_alias('file', 'writefile', 'cell') + + # FIXME: Move the color initialization to the DisplayHook, which + # should be split into a prompt manager and displayhook. We probably + # even need a centralize colors management object. + self.run_line_magic('colors', self.colors) + + # Defined here so that it's included in the documentation + @functools.wraps(magic.MagicsManager.register_function) + def register_magic_function(self, func, magic_kind='line', magic_name=None): + self.magics_manager.register_function( + func, magic_kind=magic_kind, magic_name=magic_name + ) + + def _find_with_lazy_load(self, /, type_, magic_name: str): + """ + Try to find a magic potentially lazy-loading it. + + Parameters + ---------- + + type_: "line"|"cell" + the type of magics we are trying to find/lazy load. + magic_name: str + The name of the magic we are trying to find/lazy load + + + Note that this may have any side effects + """ + finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_] + fn = finder(magic_name) + if fn is not None: + return fn + lazy = self.magics_manager.lazy_magics.get(magic_name) + if lazy is None: + return None + + self.run_line_magic("load_ext", lazy) + res = finder(magic_name) + return res + + def run_line_magic(self, magic_name: str, line, _stack_depth=1): + """Execute the given line magic. + + Parameters + ---------- + magic_name : str + Name of the desired magic function, without '%' prefix. + line : str + The rest of the input line as a single string. + _stack_depth : int + If run_line_magic() is called from magic() then _stack_depth=2. + This is added to ensure backward compatibility for use of 'get_ipython().magic()' + """ + fn = self._find_with_lazy_load("line", magic_name) + if fn is None: + lazy = self.magics_manager.lazy_magics.get(magic_name) + if lazy: + self.run_line_magic("load_ext", lazy) + fn = self.find_line_magic(magic_name) + if fn is None: + cm = self.find_cell_magic(magic_name) + etpl = "Line magic function `%%%s` not found%s." + extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' + 'did you mean that instead?)' % magic_name ) + raise UsageError(etpl % (magic_name, extra)) + else: + # Note: this is the distance in the stack to the user's frame. + # This will need to be updated if the internal calling logic gets + # refactored, or else we'll be expanding the wrong variables. + + # Determine stack_depth depending on where run_line_magic() has been called + stack_depth = _stack_depth + if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): + # magic has opted out of var_expand + magic_arg_s = line + else: + magic_arg_s = self.var_expand(line, stack_depth) + # Put magic args in a list so we can call with f(*a) syntax + args = [magic_arg_s] + kwargs = {} + # Grab local namespace if we need it: + if getattr(fn, "needs_local_scope", False): + kwargs['local_ns'] = self.get_local_scope(stack_depth) + with self.builtin_trap: + result = fn(*args, **kwargs) + + # The code below prevents the output from being displayed + # when using magics with decorator @output_can_be_silenced + # when the last Python token in the expression is a ';'. + if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): + if DisplayHook.semicolon_at_end_of_expression(magic_arg_s): + return None + + return result + + def get_local_scope(self, stack_depth): + """Get local scope at given stack depth. + + Parameters + ---------- + stack_depth : int + Depth relative to calling frame + """ + return sys._getframe(stack_depth + 1).f_locals + + def run_cell_magic(self, magic_name, line, cell): + """Execute the given cell magic. + + Parameters + ---------- + magic_name : str + Name of the desired magic function, without '%' prefix. + line : str + The rest of the first input line as a single string. + cell : str + The body of the cell as a (possibly multiline) string. + """ + fn = self._find_with_lazy_load("cell", magic_name) + if fn is None: + lm = self.find_line_magic(magic_name) + etpl = "Cell magic `%%{0}` not found{1}." + extra = '' if lm is None else (' (But line magic `%{0}` exists, ' + 'did you mean that instead?)'.format(magic_name)) + raise UsageError(etpl.format(magic_name, extra)) + elif cell == '': + message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) + if self.find_line_magic(magic_name) is not None: + message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) + raise UsageError(message) + else: + # Note: this is the distance in the stack to the user's frame. + # This will need to be updated if the internal calling logic gets + # refactored, or else we'll be expanding the wrong variables. + stack_depth = 2 + if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): + # magic has opted out of var_expand + magic_arg_s = line + else: + magic_arg_s = self.var_expand(line, stack_depth) + kwargs = {} + if getattr(fn, "needs_local_scope", False): + kwargs['local_ns'] = self.user_ns + + with self.builtin_trap: + args = (magic_arg_s, cell) + result = fn(*args, **kwargs) + + # The code below prevents the output from being displayed + # when using magics with decorator @output_can_be_silenced + # when the last Python token in the expression is a ';'. + if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): + if DisplayHook.semicolon_at_end_of_expression(cell): + return None + + return result + + def find_line_magic(self, magic_name): + """Find and return a line magic by name. + + Returns None if the magic isn't found.""" + return self.magics_manager.magics['line'].get(magic_name) + + def find_cell_magic(self, magic_name): + """Find and return a cell magic by name. + + Returns None if the magic isn't found.""" + return self.magics_manager.magics['cell'].get(magic_name) + + def find_magic(self, magic_name, magic_kind='line'): + """Find and return a magic of the given type by name. + + Returns None if the magic isn't found.""" + return self.magics_manager.magics[magic_kind].get(magic_name) + + def magic(self, arg_s): + """ + DEPRECATED + + Deprecated since IPython 0.13 (warning added in + 8.1), use run_line_magic(magic_name, parameter_s). + + Call a magic function by name. + + Input: a string containing the name of the magic function to call and + any additional arguments to be passed to the magic. + + magic('name -opt foo bar') is equivalent to typing at the ipython + prompt: + + In[1]: %name -opt foo bar + + To call a magic without arguments, simply use magic('name'). + + This provides a proper Python function to call IPython's magics in any + valid Python code you can type at the interpreter, including loops and + compound statements. + """ + warnings.warn( + "`magic(...)` is deprecated since IPython 0.13 (warning added in " + "8.1), use run_line_magic(magic_name, parameter_s).", + DeprecationWarning, + stacklevel=2, + ) + # TODO: should we issue a loud deprecation warning here? + magic_name, _, magic_arg_s = arg_s.partition(' ') + magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) + return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) + + #------------------------------------------------------------------------- + # Things related to macros + #------------------------------------------------------------------------- + + def define_macro(self, name, themacro): + """Define a new macro + + Parameters + ---------- + name : str + The name of the macro. + themacro : str or Macro + The action to do upon invoking the macro. If a string, a new + Macro object is created by passing the string to it. + """ + + from IPython.core import macro + + if isinstance(themacro, str): + themacro = macro.Macro(themacro) + if not isinstance(themacro, macro.Macro): + raise ValueError('A macro must be a string or a Macro instance.') + self.user_ns[name] = themacro + + #------------------------------------------------------------------------- + # Things related to the running of system commands + #------------------------------------------------------------------------- + + def system_piped(self, cmd): + """Call the given cmd in a subprocess, piping stdout/err + + Parameters + ---------- + cmd : str + Command to execute (can not end in '&', as background processes are + not supported. Should not be a command that expects input + other than simple text. + """ + if cmd.rstrip().endswith('&'): + # this is *far* from a rigorous test + # We do not support backgrounding processes because we either use + # pexpect or pipes to read from. Users can always just call + # os.system() or use ip.system=ip.system_raw + # if they really want a background process. + raise OSError("Background processes not supported.") + + # we explicitly do NOT return the subprocess status code, because + # a non-None value would trigger :func:`sys.displayhook` calls. + # Instead, we store the exit_code in user_ns. + self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) + + def system_raw(self, cmd): + """Call the given cmd in a subprocess using os.system on Windows or + subprocess.call using the system shell on other platforms. + + Parameters + ---------- + cmd : str + Command to execute. + """ + cmd = self.var_expand(cmd, depth=1) + # warn if there is an IPython magic alternative. + if cmd == "": + main_cmd = "" + else: + main_cmd = cmd.split()[0] + has_magic_alternatives = ("pip", "conda", "cd") + + if main_cmd in has_magic_alternatives: + warnings.warn( + ( + "You executed the system command !{0} which may not work " + "as expected. Try the IPython magic %{0} instead." + ).format(main_cmd) + ) + + # protect os.system from UNC paths on Windows, which it can't handle: + if sys.platform == 'win32': + from IPython.utils._process_win32 import AvoidUNCPath + with AvoidUNCPath() as path: + if path is not None: + cmd = '"pushd %s &&"%s' % (path, cmd) + try: + ec = os.system(cmd) + except KeyboardInterrupt: + print('\n' + self.get_exception_only(), file=sys.stderr) + ec = -2 + else: + # For posix the result of the subprocess.call() below is an exit + # code, which by convention is zero for success, positive for + # program failure. Exit codes above 128 are reserved for signals, + # and the formula for converting a signal to an exit code is usually + # signal_number+128. To more easily differentiate between exit + # codes and signals, ipython uses negative numbers. For instance + # since control-c is signal 2 but exit code 130, ipython's + # _exit_code variable will read -2. Note that some shells like + # csh and fish don't follow sh/bash conventions for exit codes. + executable = os.environ.get('SHELL', None) + try: + # Use env shell instead of default /bin/sh + ec = subprocess.call(cmd, shell=True, executable=executable) + except KeyboardInterrupt: + # intercept control-C; a long traceback is not useful here + print('\n' + self.get_exception_only(), file=sys.stderr) + ec = 130 + if ec > 128: + ec = -(ec - 128) + + # We explicitly do NOT return the subprocess status code, because + # a non-None value would trigger :func:`sys.displayhook` calls. + # Instead, we store the exit_code in user_ns. Note the semantics + # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, + # but raising SystemExit(_exit_code) will give status 254! + self.user_ns['_exit_code'] = ec + + # use piped system by default, because it is better behaved + system = system_piped + + def getoutput(self, cmd, split=True, depth=0): + """Get output (possibly including stderr) from a subprocess. + + Parameters + ---------- + cmd : str + Command to execute (can not end in '&', as background processes are + not supported. + split : bool, optional + If True, split the output into an IPython SList. Otherwise, an + IPython LSString is returned. These are objects similar to normal + lists and strings, with a few convenience attributes for easier + manipulation of line-based output. You can use '?' on them for + details. + depth : int, optional + How many frames above the caller are the local variables which should + be expanded in the command string? The default (0) assumes that the + expansion variables are in the stack frame calling this function. + """ + if cmd.rstrip().endswith('&'): + # this is *far* from a rigorous test + raise OSError("Background processes not supported.") + out = getoutput(self.var_expand(cmd, depth=depth+1)) + if split: + out = SList(out.splitlines()) + else: + out = LSString(out) + return out + + #------------------------------------------------------------------------- + # Things related to aliases + #------------------------------------------------------------------------- + + def init_alias(self): + self.alias_manager = AliasManager(shell=self, parent=self) + self.configurables.append(self.alias_manager) + + #------------------------------------------------------------------------- + # Things related to extensions + #------------------------------------------------------------------------- + + def init_extension_manager(self): + self.extension_manager = ExtensionManager(shell=self, parent=self) + self.configurables.append(self.extension_manager) + + #------------------------------------------------------------------------- + # Things related to payloads + #------------------------------------------------------------------------- + + def init_payload(self): + self.payload_manager = PayloadManager(parent=self) + self.configurables.append(self.payload_manager) + + #------------------------------------------------------------------------- + # Things related to the prefilter + #------------------------------------------------------------------------- + + def init_prefilter(self): + self.prefilter_manager = PrefilterManager(shell=self, parent=self) + self.configurables.append(self.prefilter_manager) + # Ultimately this will be refactored in the new interpreter code, but + # for now, we should expose the main prefilter method (there's legacy + # code out there that may rely on this). + self.prefilter = self.prefilter_manager.prefilter_lines + + def auto_rewrite_input(self, cmd): + """Print to the screen the rewritten form of the user's command. + + This shows visual feedback by rewriting input lines that cause + automatic calling to kick in, like:: + + /f x + + into:: + + ------> f(x) + + after the user's input prompt. This helps the user understand that the + input line was transformed automatically by IPython. + """ + if not self.show_rewritten_input: + return + + # This is overridden in TerminalInteractiveShell to use fancy prompts + print("------> " + cmd) + + #------------------------------------------------------------------------- + # Things related to extracting values/expressions from kernel and user_ns + #------------------------------------------------------------------------- + + def _user_obj_error(self): + """return simple exception dict + + for use in user_expressions + """ + + etype, evalue, tb = self._get_exc_info() + stb = self.InteractiveTB.get_exception_only(etype, evalue) + + exc_info = { + "status": "error", + "traceback": stb, + "ename": etype.__name__, + "evalue": py3compat.safe_unicode(evalue), + } + + return exc_info + + def _format_user_obj(self, obj): + """format a user object to display dict + + for use in user_expressions + """ + + data, md = self.display_formatter.format(obj) + value = { + 'status' : 'ok', + 'data' : data, + 'metadata' : md, + } + return value + + def user_expressions(self, expressions): + """Evaluate a dict of expressions in the user's namespace. + + Parameters + ---------- + expressions : dict + A dict with string keys and string values. The expression values + should be valid Python expressions, each of which will be evaluated + in the user namespace. + + Returns + ------- + A dict, keyed like the input expressions dict, with the rich mime-typed + display_data of each value. + """ + out = {} + user_ns = self.user_ns + global_ns = self.user_global_ns + + for key, expr in expressions.items(): + try: + value = self._format_user_obj(eval(expr, global_ns, user_ns)) + except: + value = self._user_obj_error() + out[key] = value + return out + + #------------------------------------------------------------------------- + # Things related to the running of code + #------------------------------------------------------------------------- + + def ex(self, cmd): + """Execute a normal python statement in user namespace.""" + with self.builtin_trap: + exec(cmd, self.user_global_ns, self.user_ns) + + def ev(self, expr): + """Evaluate python expression expr in user namespace. + + Returns the result of evaluation + """ + with self.builtin_trap: + return eval(expr, self.user_global_ns, self.user_ns) + + def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): + """A safe version of the builtin execfile(). + + This version will never throw an exception, but instead print + helpful error messages to the screen. This only works on pure + Python files with the .py extension. + + Parameters + ---------- + fname : string + The name of the file to be executed. + *where : tuple + One or two namespaces, passed to execfile() as (globals,locals). + If only one is given, it is passed as both. + exit_ignore : bool (False) + If True, then silence SystemExit for non-zero status (it is always + silenced for zero status, as it is so common). + raise_exceptions : bool (False) + If True raise exceptions everywhere. Meant for testing. + shell_futures : bool (False) + If True, the code will share future statements with the interactive + shell. It will both be affected by previous __future__ imports, and + any __future__ imports in the code will affect the shell. If False, + __future__ imports are not shared in either direction. + + """ + fname = Path(fname).expanduser().resolve() + + # Make sure we can open the file + try: + with fname.open("rb"): + pass + except: + warn('Could not open file <%s> for safe execution.' % fname) + return + + # Find things also in current directory. This is needed to mimic the + # behavior of running a script from the system command line, where + # Python inserts the script's directory into sys.path + dname = str(fname.parent) + + with prepended_to_syspath(dname), self.builtin_trap: + try: + glob, loc = (where + (None, ))[:2] + py3compat.execfile( + fname, glob, loc, + self.compile if shell_futures else None) + except SystemExit as status: + # If the call was made with 0 or None exit status (sys.exit(0) + # or sys.exit() ), don't bother showing a traceback, as both of + # these are considered normal by the OS: + # > python -c'import sys;sys.exit(0)'; echo $? + # 0 + # > python -c'import sys;sys.exit()'; echo $? + # 0 + # For other exit status, we show the exception unless + # explicitly silenced, but only in short form. + if status.code: + if raise_exceptions: + raise + if not exit_ignore: + self.showtraceback(exception_only=True) + except: + if raise_exceptions: + raise + # tb offset is 2 because we wrap execfile + self.showtraceback(tb_offset=2) + + def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): + """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. + + Parameters + ---------- + fname : str + The name of the file to execute. The filename must have a + .ipy or .ipynb extension. + shell_futures : bool (False) + If True, the code will share future statements with the interactive + shell. It will both be affected by previous __future__ imports, and + any __future__ imports in the code will affect the shell. If False, + __future__ imports are not shared in either direction. + raise_exceptions : bool (False) + If True raise exceptions everywhere. Meant for testing. + """ + fname = Path(fname).expanduser().resolve() + + # Make sure we can open the file + try: + with fname.open("rb"): + pass + except: + warn('Could not open file <%s> for safe execution.' % fname) + return + + # Find things also in current directory. This is needed to mimic the + # behavior of running a script from the system command line, where + # Python inserts the script's directory into sys.path + dname = str(fname.parent) + + def get_cells(): + """generator for sequence of code blocks to run""" + if fname.suffix == ".ipynb": + from nbformat import read + nb = read(fname, as_version=4) + if not nb.cells: + return + for cell in nb.cells: + if cell.cell_type == 'code': + yield cell.source + else: + yield fname.read_text(encoding="utf-8") + + with prepended_to_syspath(dname): + try: + for cell in get_cells(): + result = self.run_cell(cell, silent=True, shell_futures=shell_futures) + if raise_exceptions: + result.raise_error() + elif not result.success: + break + except: + if raise_exceptions: + raise + self.showtraceback() + warn('Unknown failure executing file: <%s>' % fname) + + def safe_run_module(self, mod_name, where): + """A safe version of runpy.run_module(). + + This version will never throw an exception, but instead print + helpful error messages to the screen. + + `SystemExit` exceptions with status code 0 or None are ignored. + + Parameters + ---------- + mod_name : string + The name of the module to be executed. + where : dict + The globals namespace. + """ + try: + try: + where.update( + runpy.run_module(str(mod_name), run_name="__main__", + alter_sys=True) + ) + except SystemExit as status: + if status.code: + raise + except: + self.showtraceback() + warn('Unknown failure executing module: <%s>' % mod_name) + + def run_cell( + self, + raw_cell, + store_history=False, + silent=False, + shell_futures=True, + cell_id=None, + ): + """Run a complete IPython cell. + + Parameters + ---------- + raw_cell : str + The code (including IPython code such as %magic functions) to run. + store_history : bool + If True, the raw and translated cell will be stored in IPython's + history. For user code calling back into IPython's machinery, this + should be set to False. + silent : bool + If True, avoid side-effects, such as implicit displayhooks and + and logging. silent=True forces store_history=False. + shell_futures : bool + If True, the code will share future statements with the interactive + shell. It will both be affected by previous __future__ imports, and + any __future__ imports in the code will affect the shell. If False, + __future__ imports are not shared in either direction. + + Returns + ------- + result : :class:`ExecutionResult` + """ + result = None + try: + result = self._run_cell( + raw_cell, store_history, silent, shell_futures, cell_id + ) + finally: + self.events.trigger('post_execute') + if not silent: + self.events.trigger('post_run_cell', result) + return result + + def _run_cell( + self, + raw_cell: str, + store_history: bool, + silent: bool, + shell_futures: bool, + cell_id: str, + ) -> ExecutionResult: + """Internal method to run a complete IPython cell.""" + + # we need to avoid calling self.transform_cell multiple time on the same thing + # so we need to store some results: + preprocessing_exc_tuple = None + try: + transformed_cell = self.transform_cell(raw_cell) + except Exception: + transformed_cell = raw_cell + preprocessing_exc_tuple = sys.exc_info() + + assert transformed_cell is not None + coro = self.run_cell_async( + raw_cell, + store_history=store_history, + silent=silent, + shell_futures=shell_futures, + transformed_cell=transformed_cell, + preprocessing_exc_tuple=preprocessing_exc_tuple, + cell_id=cell_id, + ) + + # run_cell_async is async, but may not actually need an eventloop. + # when this is the case, we want to run it using the pseudo_sync_runner + # so that code can invoke eventloops (for example via the %run , and + # `%paste` magic. + if self.trio_runner: + runner = self.trio_runner + elif self.should_run_async( + raw_cell, + transformed_cell=transformed_cell, + preprocessing_exc_tuple=preprocessing_exc_tuple, + ): + runner = self.loop_runner + else: + runner = _pseudo_sync_runner + + try: + result = runner(coro) + except BaseException as e: + info = ExecutionInfo( + raw_cell, store_history, silent, shell_futures, cell_id + ) + result = ExecutionResult(info) + result.error_in_exec = e + self.showtraceback(running_compiled_code=True) + finally: + return result + + def should_run_async( + self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None + ) -> bool: + """Return whether a cell should be run asynchronously via a coroutine runner + + Parameters + ---------- + raw_cell : str + The code to be executed + + Returns + ------- + result: bool + Whether the code needs to be run with a coroutine runner or not + .. versionadded:: 7.0 + """ + if not self.autoawait: + return False + if preprocessing_exc_tuple is not None: + return False + assert preprocessing_exc_tuple is None + if transformed_cell is None: + warnings.warn( + "`should_run_async` will not call `transform_cell`" + " automatically in the future. Please pass the result to" + " `transformed_cell` argument and any exception that happen" + " during the" + "transform in `preprocessing_exc_tuple` in" + " IPython 7.17 and above.", + DeprecationWarning, + stacklevel=2, + ) + try: + cell = self.transform_cell(raw_cell) + except Exception: + # any exception during transform will be raised + # prior to execution + return False + else: + cell = transformed_cell + return _should_be_async(cell) + + async def run_cell_async( + self, + raw_cell: str, + store_history=False, + silent=False, + shell_futures=True, + *, + transformed_cell: Optional[str] = None, + preprocessing_exc_tuple: Optional[AnyType] = None, + cell_id=None, + ) -> ExecutionResult: + """Run a complete IPython cell asynchronously. + + Parameters + ---------- + raw_cell : str + The code (including IPython code such as %magic functions) to run. + store_history : bool + If True, the raw and translated cell will be stored in IPython's + history. For user code calling back into IPython's machinery, this + should be set to False. + silent : bool + If True, avoid side-effects, such as implicit displayhooks and + and logging. silent=True forces store_history=False. + shell_futures : bool + If True, the code will share future statements with the interactive + shell. It will both be affected by previous __future__ imports, and + any __future__ imports in the code will affect the shell. If False, + __future__ imports are not shared in either direction. + transformed_cell: str + cell that was passed through transformers + preprocessing_exc_tuple: + trace if the transformation failed. + + Returns + ------- + result : :class:`ExecutionResult` + + .. versionadded:: 7.0 + """ + info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id) + result = ExecutionResult(info) + + if (not raw_cell) or raw_cell.isspace(): + self.last_execution_succeeded = True + self.last_execution_result = result + return result + + if silent: + store_history = False + + if store_history: + result.execution_count = self.execution_count + + def error_before_exec(value): + if store_history: + self.execution_count += 1 + result.error_before_exec = value + self.last_execution_succeeded = False + self.last_execution_result = result + return result + + self.events.trigger('pre_execute') + if not silent: + self.events.trigger('pre_run_cell', info) + + if transformed_cell is None: + warnings.warn( + "`run_cell_async` will not call `transform_cell`" + " automatically in the future. Please pass the result to" + " `transformed_cell` argument and any exception that happen" + " during the" + "transform in `preprocessing_exc_tuple` in" + " IPython 7.17 and above.", + DeprecationWarning, + stacklevel=2, + ) + # If any of our input transformation (input_transformer_manager or + # prefilter_manager) raises an exception, we store it in this variable + # so that we can display the error after logging the input and storing + # it in the history. + try: + cell = self.transform_cell(raw_cell) + except Exception: + preprocessing_exc_tuple = sys.exc_info() + cell = raw_cell # cell has to exist so it can be stored/logged + else: + preprocessing_exc_tuple = None + else: + if preprocessing_exc_tuple is None: + cell = transformed_cell + else: + cell = raw_cell + + # Do NOT store paste/cpaste magic history + if "get_ipython().run_line_magic(" in cell and "paste" in cell: + store_history = False + + # Store raw and processed history + if store_history: + self.history_manager.store_inputs(self.execution_count, cell, raw_cell) + if not silent: + self.logger.log(cell, raw_cell) + + # Display the exception if input processing failed. + if preprocessing_exc_tuple is not None: + self.showtraceback(preprocessing_exc_tuple) + if store_history: + self.execution_count += 1 + return error_before_exec(preprocessing_exc_tuple[1]) + + # Our own compiler remembers the __future__ environment. If we want to + # run code with a separate __future__ environment, use the default + # compiler + compiler = self.compile if shell_futures else self.compiler_class() + + _run_async = False + + with self.builtin_trap: + cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell) + + with self.display_trap: + # Compile to bytecode + try: + code_ast = compiler.ast_parse(cell, filename=cell_name) + except self.custom_exceptions as e: + etype, value, tb = sys.exc_info() + self.CustomTB(etype, value, tb) + return error_before_exec(e) + except IndentationError as e: + self.showindentationerror() + return error_before_exec(e) + except (OverflowError, SyntaxError, ValueError, TypeError, + MemoryError) as e: + self.showsyntaxerror() + return error_before_exec(e) + + # Apply AST transformations + try: + code_ast = self.transform_ast(code_ast) + except InputRejected as e: + self.showtraceback() + return error_before_exec(e) + + # Give the displayhook a reference to our ExecutionResult so it + # can fill in the output value. + self.displayhook.exec_result = result + + # Execute the user code + interactivity = "none" if silent else self.ast_node_interactivity + + + has_raised = await self.run_ast_nodes(code_ast.body, cell_name, + interactivity=interactivity, compiler=compiler, result=result) + + self.last_execution_succeeded = not has_raised + self.last_execution_result = result + + # Reset this so later displayed values do not modify the + # ExecutionResult + self.displayhook.exec_result = None + + if store_history: + # Write output to the database. Does nothing unless + # history output logging is enabled. + self.history_manager.store_output(self.execution_count) + # Each cell is a *single* input, regardless of how many lines it has + self.execution_count += 1 + + return result + + def transform_cell(self, raw_cell): + """Transform an input cell before parsing it. + + Static transformations, implemented in IPython.core.inputtransformer2, + deal with things like ``%magic`` and ``!system`` commands. + These run on all input. + Dynamic transformations, for things like unescaped magics and the exit + autocall, depend on the state of the interpreter. + These only apply to single line inputs. + + These string-based transformations are followed by AST transformations; + see :meth:`transform_ast`. + """ + # Static input transformations + cell = self.input_transformer_manager.transform_cell(raw_cell) + + if len(cell.splitlines()) == 1: + # Dynamic transformations - only applied for single line commands + with self.builtin_trap: + # use prefilter_lines to handle trailing newlines + # restore trailing newline for ast.parse + cell = self.prefilter_manager.prefilter_lines(cell) + '\n' + + lines = cell.splitlines(keepends=True) + for transform in self.input_transformers_post: + lines = transform(lines) + cell = ''.join(lines) + + return cell + + def transform_ast(self, node): + """Apply the AST transformations from self.ast_transformers + + Parameters + ---------- + node : ast.Node + The root node to be transformed. Typically called with the ast.Module + produced by parsing user input. + + Returns + ------- + An ast.Node corresponding to the node it was called with. Note that it + may also modify the passed object, so don't rely on references to the + original AST. + """ + for transformer in self.ast_transformers: + try: + node = transformer.visit(node) + except InputRejected: + # User-supplied AST transformers can reject an input by raising + # an InputRejected. Short-circuit in this case so that we + # don't unregister the transform. + raise + except Exception as e: + warn( + "AST transformer %r threw an error. It will be unregistered. %s" + % (transformer, e) + ) + self.ast_transformers.remove(transformer) + + if self.ast_transformers: + ast.fix_missing_locations(node) + return node + + async def run_ast_nodes( + self, + nodelist: ListType[stmt], + cell_name: str, + interactivity="last_expr", + compiler=compile, + result=None, + ): + """Run a sequence of AST nodes. The execution mode depends on the + interactivity parameter. + + Parameters + ---------- + nodelist : list + A sequence of AST nodes to run. + cell_name : str + Will be passed to the compiler as the filename of the cell. Typically + the value returned by ip.compile.cache(cell). + interactivity : str + 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', + specifying which nodes should be run interactively (displaying output + from expressions). 'last_expr' will run the last node interactively + only if it is an expression (i.e. expressions in loops or other blocks + are not displayed) 'last_expr_or_assign' will run the last expression + or the last assignment. Other values for this parameter will raise a + ValueError. + + compiler : callable + A function with the same interface as the built-in compile(), to turn + the AST nodes into code objects. Default is the built-in compile(). + result : ExecutionResult, optional + An object to store exceptions that occur during execution. + + Returns + ------- + True if an exception occurred while running code, False if it finished + running. + """ + if not nodelist: + return + + + if interactivity == 'last_expr_or_assign': + if isinstance(nodelist[-1], _assign_nodes): + asg = nodelist[-1] + if isinstance(asg, ast.Assign) and len(asg.targets) == 1: + target = asg.targets[0] + elif isinstance(asg, _single_targets_nodes): + target = asg.target + else: + target = None + if isinstance(target, ast.Name): + nnode = ast.Expr(ast.Name(target.id, ast.Load())) + ast.fix_missing_locations(nnode) + nodelist.append(nnode) + interactivity = 'last_expr' + + _async = False + if interactivity == 'last_expr': + if isinstance(nodelist[-1], ast.Expr): + interactivity = "last" + else: + interactivity = "none" + + if interactivity == 'none': + to_run_exec, to_run_interactive = nodelist, [] + elif interactivity == 'last': + to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] + elif interactivity == 'all': + to_run_exec, to_run_interactive = [], nodelist + else: + raise ValueError("Interactivity was %r" % interactivity) + + try: + + def compare(code): + is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE + return is_async + + # refactor that to just change the mod constructor. + to_run = [] + for node in to_run_exec: + to_run.append((node, "exec")) + + for node in to_run_interactive: + to_run.append((node, "single")) + + for node, mode in to_run: + if mode == "exec": + mod = Module([node], []) + elif mode == "single": + mod = ast.Interactive([node]) # type: ignore + with compiler.extra_flags( + getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0) + if self.autoawait + else 0x0 + ): + code = compiler(mod, cell_name, mode) + asy = compare(code) + if await self.run_code(code, result, async_=asy): + return True + + # Flush softspace + if softspace(sys.stdout, 0): + print() + + except: + # It's possible to have exceptions raised here, typically by + # compilation of odd code (such as a naked 'return' outside a + # function) that did parse but isn't valid. Typically the exception + # is a SyntaxError, but it's safest just to catch anything and show + # the user a traceback. + + # We do only one try/except outside the loop to minimize the impact + # on runtime, and also because if any node in the node list is + # broken, we should stop execution completely. + if result: + result.error_before_exec = sys.exc_info()[1] + self.showtraceback() + return True + + return False + + async def run_code(self, code_obj, result=None, *, async_=False): + """Execute a code object. + + When an exception occurs, self.showtraceback() is called to display a + traceback. + + Parameters + ---------- + code_obj : code object + A compiled code object, to be executed + result : ExecutionResult, optional + An object to store exceptions that occur during execution. + async_ : Bool (Experimental) + Attempt to run top-level asynchronous code in a default loop. + + Returns + ------- + False : successful execution. + True : an error occurred. + """ + # special value to say that anything above is IPython and should be + # hidden. + __tracebackhide__ = "__ipython_bottom__" + # Set our own excepthook in case the user code tries to call it + # directly, so that the IPython crash handler doesn't get triggered + old_excepthook, sys.excepthook = sys.excepthook, self.excepthook + + # we save the original sys.excepthook in the instance, in case config + # code (such as magics) needs access to it. + self.sys_excepthook = old_excepthook + outflag = True # happens in more places, so it's easier as default + try: + try: + if async_: + await eval(code_obj, self.user_global_ns, self.user_ns) + else: + exec(code_obj, self.user_global_ns, self.user_ns) + finally: + # Reset our crash handler in place + sys.excepthook = old_excepthook + except SystemExit as e: + if result is not None: + result.error_in_exec = e + self.showtraceback(exception_only=True) + warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) + except bdb.BdbQuit: + etype, value, tb = sys.exc_info() + if result is not None: + result.error_in_exec = value + # the BdbQuit stops here + except self.custom_exceptions: + etype, value, tb = sys.exc_info() + if result is not None: + result.error_in_exec = value + self.CustomTB(etype, value, tb) + except: + if result is not None: + result.error_in_exec = sys.exc_info()[1] + self.showtraceback(running_compiled_code=True) + else: + outflag = False + return outflag + + # For backwards compatibility + runcode = run_code + + def check_complete(self, code: str) -> Tuple[str, str]: + """Return whether a block of code is ready to execute, or should be continued + + Parameters + ---------- + code : string + Python input code, which can be multiline. + + Returns + ------- + status : str + One of 'complete', 'incomplete', or 'invalid' if source is not a + prefix of valid code. + indent : str + When status is 'incomplete', this is some whitespace to insert on + the next line of the prompt. + """ + status, nspaces = self.input_transformer_manager.check_complete(code) + return status, ' ' * (nspaces or 0) + + #------------------------------------------------------------------------- + # Things related to GUI support and pylab + #------------------------------------------------------------------------- + + active_eventloop: Optional[str] = None + + def enable_gui(self, gui=None): + raise NotImplementedError('Implement enable_gui in a subclass') + + def enable_matplotlib(self, gui=None): + """Enable interactive matplotlib and inline figure support. + + This takes the following steps: + + 1. select the appropriate eventloop and matplotlib backend + 2. set up matplotlib for interactive use with that backend + 3. configure formatters for inline figure display + 4. enable the selected gui eventloop + + Parameters + ---------- + gui : optional, string + If given, dictates the choice of matplotlib GUI backend to use + (should be one of IPython's supported backends, 'qt', 'osx', 'tk', + 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by + matplotlib (as dictated by the matplotlib build-time options plus the + user's matplotlibrc configuration file). Note that not all backends + make sense in all contexts, for example a terminal ipython can't + display figures inline. + """ + from matplotlib_inline.backend_inline import configure_inline_support + + from IPython.core import pylabtools as pt + gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) + + if gui != 'inline': + # If we have our first gui selection, store it + if self.pylab_gui_select is None: + self.pylab_gui_select = gui + # Otherwise if they are different + elif gui != self.pylab_gui_select: + print('Warning: Cannot change to a different GUI toolkit: %s.' + ' Using %s instead.' % (gui, self.pylab_gui_select)) + gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) + + pt.activate_matplotlib(backend) + configure_inline_support(self, backend) + + # Now we must activate the gui pylab wants to use, and fix %run to take + # plot updates into account + self.enable_gui(gui) + self.magics_manager.registry['ExecutionMagics'].default_runner = \ + pt.mpl_runner(self.safe_execfile) + + return gui, backend + + def enable_pylab(self, gui=None, import_all=True, welcome_message=False): + """Activate pylab support at runtime. + + This turns on support for matplotlib, preloads into the interactive + namespace all of numpy and pylab, and configures IPython to correctly + interact with the GUI event loop. The GUI backend to be used can be + optionally selected with the optional ``gui`` argument. + + This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. + + Parameters + ---------- + gui : optional, string + If given, dictates the choice of matplotlib GUI backend to use + (should be one of IPython's supported backends, 'qt', 'osx', 'tk', + 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by + matplotlib (as dictated by the matplotlib build-time options plus the + user's matplotlibrc configuration file). Note that not all backends + make sense in all contexts, for example a terminal ipython can't + display figures inline. + import_all : optional, bool, default: True + Whether to do `from numpy import *` and `from pylab import *` + in addition to module imports. + welcome_message : deprecated + This argument is ignored, no welcome message will be displayed. + """ + from IPython.core.pylabtools import import_pylab + + gui, backend = self.enable_matplotlib(gui) + + # We want to prevent the loading of pylab to pollute the user's + # namespace as shown by the %who* magics, so we execute the activation + # code in an empty namespace, and we update *both* user_ns and + # user_ns_hidden with this information. + ns = {} + import_pylab(ns, import_all) + # warn about clobbered names + ignored = {"__builtins__"} + both = set(ns).intersection(self.user_ns).difference(ignored) + clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] + self.user_ns.update(ns) + self.user_ns_hidden.update(ns) + return gui, backend, clobbered + + #------------------------------------------------------------------------- + # Utilities + #------------------------------------------------------------------------- + + def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): + """Expand python variables in a string. + + The depth argument indicates how many frames above the caller should + be walked to look for the local namespace where to expand variables. + + The global namespace for expansion is always the user's interactive + namespace. + """ + ns = self.user_ns.copy() + try: + frame = sys._getframe(depth+1) + except ValueError: + # This is thrown if there aren't that many frames on the stack, + # e.g. if a script called run_line_magic() directly. + pass + else: + ns.update(frame.f_locals) + + try: + # We have to use .vformat() here, because 'self' is a valid and common + # name, and expanding **ns for .format() would make it collide with + # the 'self' argument of the method. + cmd = formatter.vformat(cmd, args=[], kwargs=ns) + except Exception: + # if formatter couldn't format, just let it go untransformed + pass + return cmd + + def mktempfile(self, data=None, prefix='ipython_edit_'): + """Make a new tempfile and return its filename. + + This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), + but it registers the created filename internally so ipython cleans it up + at exit time. + + Optional inputs: + + - data(None): if data is given, it gets written out to the temp file + immediately, and the file is closed again.""" + + dir_path = Path(tempfile.mkdtemp(prefix=prefix)) + self.tempdirs.append(dir_path) + + handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path)) + os.close(handle) # On Windows, there can only be one open handle on a file + + file_path = Path(filename) + self.tempfiles.append(file_path) + + if data: + file_path.write_text(data, encoding="utf-8") + return filename + + def ask_yes_no(self, prompt, default=None, interrupt=None): + if self.quiet: + return True + return ask_yes_no(prompt,default,interrupt) + + def show_usage(self): + """Show a usage message""" + page.page(IPython.core.usage.interactive_usage) + + def extract_input_lines(self, range_str, raw=False): + """Return as a string a set of input history slices. + + Parameters + ---------- + range_str : str + The set of slices is given as a string, like "~5/6-~4/2 4:8 9", + since this function is for use by magic functions which get their + arguments as strings. The number before the / is the session + number: ~n goes n back from the current session. + + If empty string is given, returns history of current session + without the last input. + + raw : bool, optional + By default, the processed input is used. If this is true, the raw + input history is used instead. + + Notes + ----- + Slices can be described with two notations: + + * ``N:M`` -> standard python form, means including items N...(M-1). + * ``N-M`` -> include items N..M (closed endpoint). + """ + lines = self.history_manager.get_range_by_str(range_str, raw=raw) + text = "\n".join(x for _, _, x in lines) + + # Skip the last line, as it's probably the magic that called this + if not range_str: + if "\n" not in text: + text = "" + else: + text = text[: text.rfind("\n")] + + return text + + def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): + """Get a code string from history, file, url, or a string or macro. + + This is mainly used by magic functions. + + Parameters + ---------- + target : str + A string specifying code to retrieve. This will be tried respectively + as: ranges of input history (see %history for syntax), url, + corresponding .py file, filename, or an expression evaluating to a + string or Macro in the user namespace. + + If empty string is given, returns complete history of current + session, without the last line. + + raw : bool + If true (default), retrieve raw history. Has no effect on the other + retrieval mechanisms. + + py_only : bool (default False) + Only try to fetch python code, do not try alternative methods to decode file + if unicode fails. + + Returns + ------- + A string of code. + ValueError is raised if nothing is found, and TypeError if it evaluates + to an object of another type. In each case, .args[0] is a printable + message. + """ + code = self.extract_input_lines(target, raw=raw) # Grab history + if code: + return code + try: + if target.startswith(('http://', 'https://')): + return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) + except UnicodeDecodeError as e: + if not py_only : + # Deferred import + from urllib.request import urlopen + response = urlopen(target) + return response.read().decode('latin1') + raise ValueError(("'%s' seem to be unreadable.") % target) from e + + potential_target = [target] + try : + potential_target.insert(0,get_py_filename(target)) + except IOError: + pass + + for tgt in potential_target : + if os.path.isfile(tgt): # Read file + try : + return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) + except UnicodeDecodeError as e: + if not py_only : + with io_open(tgt,'r', encoding='latin1') as f : + return f.read() + raise ValueError(("'%s' seem to be unreadable.") % target) from e + elif os.path.isdir(os.path.expanduser(tgt)): + raise ValueError("'%s' is a directory, not a regular file." % target) + + if search_ns: + # Inspect namespace to load object source + object_info = self.object_inspect(target, detail_level=1) + if object_info['found'] and object_info['source']: + return object_info['source'] + + try: # User namespace + codeobj = eval(target, self.user_ns) + except Exception as e: + raise ValueError(("'%s' was not found in history, as a file, url, " + "nor in the user namespace.") % target) from e + + if isinstance(codeobj, str): + return codeobj + elif isinstance(codeobj, Macro): + return codeobj.value + + raise TypeError("%s is neither a string nor a macro." % target, + codeobj) + + def _atexit_once(self): + """ + At exist operation that need to be called at most once. + Second call to this function per instance will do nothing. + """ + + if not getattr(self, "_atexit_once_called", False): + self._atexit_once_called = True + # Clear all user namespaces to release all references cleanly. + self.reset(new_session=False) + # Close the history session (this stores the end time and line count) + # this must be *before* the tempfile cleanup, in case of temporary + # history db + self.history_manager.end_session() + self.history_manager = None + + #------------------------------------------------------------------------- + # Things related to IPython exiting + #------------------------------------------------------------------------- + def atexit_operations(self): + """This will be executed at the time of exit. + + Cleanup operations and saving of persistent data that is done + unconditionally by IPython should be performed here. + + For things that may depend on startup flags or platform specifics (such + as having readline or not), register a separate atexit function in the + code that has the appropriate information, rather than trying to + clutter + """ + self._atexit_once() + + # Cleanup all tempfiles and folders left around + for tfile in self.tempfiles: + try: + tfile.unlink() + self.tempfiles.remove(tfile) + except FileNotFoundError: + pass + del self.tempfiles + for tdir in self.tempdirs: + try: + shutil.rmtree(tdir) + self.tempdirs.remove(tdir) + except FileNotFoundError: + pass + del self.tempdirs + + # Restore user's cursor + if hasattr(self, "editing_mode") and self.editing_mode == "vi": + sys.stdout.write("\x1b[0 q") + sys.stdout.flush() + + def cleanup(self): + self.restore_sys_module_state() + + + # Overridden in terminal subclass to change prompts + def switch_doctest_mode(self, mode): + pass + + +class InteractiveShellABC(metaclass=abc.ABCMeta): + """An abstract base class for InteractiveShell.""" + +InteractiveShellABC.register(InteractiveShell) diff --git a/shared/package-files/79/79e0eb96acb96f53de2ccf6279a237ef404997f1ded9f469c2236389feae0ea2/blob b/shared/package-files/79/79e0eb96acb96f53de2ccf6279a237ef404997f1ded9f469c2236389feae0ea2/blob new file mode 100644 index 0000000000000000000000000000000000000000..3aef78a65226d3568ece5d4ff2acff777a0437f6 --- /dev/null +++ b/shared/package-files/79/79e0eb96acb96f53de2ccf6279a237ef404997f1ded9f469c2236389feae0ea2/blob @@ -0,0 +1,90 @@ +library(lme4) +library(R2nparray) + +files = list.files(path="results", pattern="lme...csv") + +rslt = list() + +# Check the code with a sequence of data files with different +# dimensions and random effects structures. +for (file in files) { + + # Fit a model with independent random effects (irf=TRUE) or + # dependent random effects (irf=FALSE). + for (irf in c(FALSE, TRUE)) { + + if (irf) { + rf = "irf" + } else { + rf = "drf" + } + + # Use REML or ML estimation + for (reml in c(FALSE, TRUE)) { + + if (reml) { + meth = "reml" + } else { + meth = "ml" + } + + data = read.csv(paste("results", file, sep="/")) + + exog_fe_ix = grep("exog_fe", names(data)) + exog_re_ix = grep("exog_re", names(data)) + + # No need to check independent random effects when there is + # only one of them. + if (irf & (length(exog_re_ix) == 1)) { + next + } + + pr = length(exog_re_ix) + fml_fe = paste(names(data)[exog_fe_ix], collapse="+") + + if (irf) { + st = NULL + for (ik in exog_re_ix) { + st[length(st) + 1] = sprintf("(0 + %s | groups)", names(data)[ik]) + } + fml_re = paste(st, collapse="+") + + fml = sprintf("endog ~ 0 + %s + %s", fml_fe, fml_re) + } else { + fml_re = paste(names(data)[exog_re_ix], collapse="+") + fml = sprintf("endog ~ 0 + %s + (0 + %s | groups)", fml_fe, fml_re) + } + + md = lmer(as.formula(fml), data=data, REML=reml) + + ds_ix = as.integer(substr(file, 4, 6)) + rslt[[sprintf("coef_%s_%s_%d", meth, rf, ds_ix)]] = as.vector(fixef(md)) + rslt[[sprintf("vcov_%s_%s_%d", meth, rf, ds_ix)]] = as.matrix(vcov(md)) + if (irf) { + rev = NULL + for (k in 1:length(exog_re_ix)) { + rev[k] = as.numeric(VarCorr(md)[[k]]) + } + rev = diag(rev) + rslt[[sprintf("cov_re_%s_%s_%d", meth, rf, ds_ix)]] = rev + } else { + rslt[[sprintf("cov_re_%s_%s_%d", meth, rf, ds_ix)]] = array(as.numeric(VarCorr(md)$groups), + c(pr, pr)) + } + rslt[[sprintf("scale_%s_%s_%d", meth, rf, ds_ix)]] = attr(VarCorr(md), "sc")^2 + rslt[[sprintf("loglike_%s_%s_%d", meth, rf, ds_ix)]] = as.numeric(logLik(md)) + + # Apparently lmer does not support these things when the random effects + # are independent. + if (!irf) { + reo = ranef(md, condVar=TRUE) + re = as.matrix(reo$groups) + condvar = attr(reo$groups, "postVar") + rslt[[sprintf("ranef_mean_%s_%s_%d", meth, rf, ds_ix)]] = re[1,] + rslt[[sprintf("ranef_condvar_%s_%s_%d", meth, rf, ds_ix)]] = condvar[,,1] + } + } + } +} + +R2nparray(rslt, fname="lme_r_results.py") diff --git a/shared/package-files/79/79e2b33fec758c92063be4422c83fe56ce565389c26c2111defe0815ee2dd254/blob b/shared/package-files/79/79e2b33fec758c92063be4422c83fe56ce565389c26c2111defe0815ee2dd254/blob new file mode 100644 index 0000000000000000000000000000000000000000..ecaf853e24ef523c1e5e04fbc7bd6462636e381c --- /dev/null +++ b/shared/package-files/79/79e2b33fec758c92063be4422c83fe56ce565389c26c2111defe0815ee2dd254/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79e2b33fec758c92063be4422c83fe56ce565389c26c2111defe0815ee2dd254 +size 828890 diff --git a/shared/package-files/79/79e5e9c47d5d548a1d928e842a71bb9bc341840ddf9073555252c54e0e1ecad4/blob b/shared/package-files/79/79e5e9c47d5d548a1d928e842a71bb9bc341840ddf9073555252c54e0e1ecad4/blob new file mode 100644 index 0000000000000000000000000000000000000000..1b72658c62e9f6fcfd200c26d6f57e65ed5716b0 Binary files /dev/null and b/shared/package-files/79/79e5e9c47d5d548a1d928e842a71bb9bc341840ddf9073555252c54e0e1ecad4/blob differ diff --git a/shared/package-files/79/79e84440d98b1b2ddefd78cd87ab79bd0202f65fce444784e2d61145a15974db/blob b/shared/package-files/79/79e84440d98b1b2ddefd78cd87ab79bd0202f65fce444784e2d61145a15974db/blob new file mode 100644 index 0000000000000000000000000000000000000000..a07250bbeb06542721480c42005307992558fced --- /dev/null +++ b/shared/package-files/79/79e84440d98b1b2ddefd78cd87ab79bd0202f65fce444784e2d61145a15974db/blob @@ -0,0 +1,133 @@ +""" +Cython optimize root finding API +================================ +The underlying C functions for the following root finders can be accessed +directly using Cython: + +- `~scipy.optimize.bisect` +- `~scipy.optimize.ridder` +- `~scipy.optimize.brenth` +- `~scipy.optimize.brentq` + +The Cython API for the root finding functions is similar except there is no +``disp`` argument. Import the root finding functions using ``cimport`` from +`scipy.optimize.cython_optimize`. :: + + from scipy.optimize.cython_optimize cimport bisect, ridder, brentq, brenth + + +Callback signature +------------------ +The zeros functions in `~scipy.optimize.cython_optimize` expect a callback that +takes a double for the scalar independent variable as the 1st argument and a +user defined ``struct`` with any extra parameters as the 2nd argument. :: + + double (*callback_type)(double, void*) noexcept + + +Examples +-------- +Usage of `~scipy.optimize.cython_optimize` requires Cython to write callbacks +that are compiled into C. For more information on compiling Cython, see the +`Cython Documentation `_. + +These are the basic steps: + +1. Create a Cython ``.pyx`` file, for example: ``myexample.pyx``. +2. Import the desired root finder from `~scipy.optimize.cython_optimize`. +3. Write the callback function, and call the selected root finding function + passing the callback, any extra arguments, and the other solver + parameters. :: + + from scipy.optimize.cython_optimize cimport brentq + + # import math from Cython + from libc cimport math + + myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments + XLO, XHI = 0.5, 1.0 # lower and upper search boundaries + XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters + + # user-defined struct for extra parameters + ctypedef struct test_params: + double C0 + double C1 + + + # user-defined callback + cdef double f(double x, void *args) noexcept: + cdef test_params *myargs = args + return myargs.C0 - math.exp(-(x - myargs.C1)) + + + # Cython wrapper function + cdef double brentq_wrapper_example(dict args, double xa, double xb, + double xtol, double rtol, int mitr): + # Cython automatically casts dictionary to struct + cdef test_params myargs = args + return brentq( + f, xa, xb, &myargs, xtol, rtol, mitr, NULL) + + + # Python function + def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL, + mitr=MITR): + '''Calls Cython wrapper from Python.''' + return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr) + +4. If you want to call your function from Python, create a Cython wrapper, and + a Python function that calls the wrapper, or use ``cpdef``. Then, in Python, + you can import and run the example. :: + + from myexample import brentq_example + + x = brentq_example() + # 0.6999942848231314 + +5. Create a Cython ``.pxd`` file if you need to export any Cython functions. + + +Full output +----------- +The functions in `~scipy.optimize.cython_optimize` can also copy the full +output from the solver to a C ``struct`` that is passed as its last argument. +If you don't want the full output, just pass ``NULL``. The full output +``struct`` must be type ``zeros_full_output``, which is defined in +`scipy.optimize.cython_optimize` with the following fields: + +- ``int funcalls``: number of function calls +- ``int iterations``: number of iterations +- ``int error_num``: error number +- ``double root``: root of function + +The root is copied by `~scipy.optimize.cython_optimize` to the full output +``struct``. An error number of -1 means a sign error, -2 means a convergence +error, and 0 means the solver converged. Continuing from the previous example:: + + from scipy.optimize.cython_optimize cimport zeros_full_output + + + # cython brentq solver with full output + cdef zeros_full_output brentq_full_output_wrapper_example( + dict args, double xa, double xb, double xtol, double rtol, + int mitr): + cdef test_params myargs = args + cdef zeros_full_output my_full_output + # use my_full_output instead of NULL + brentq(f, xa, xb, &myargs, xtol, rtol, mitr, &my_full_output) + return my_full_output + + + # Python function + def brent_full_output_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, + rtol=RTOL, mitr=MITR): + '''Returns full output''' + return brentq_full_output_wrapper_example(args, xa, xb, xtol, rtol, + mitr) + + result = brent_full_output_example() + # {'error_num': 0, + # 'funcalls': 6, + # 'iterations': 5, + # 'root': 0.6999942848231314} +""" diff --git a/shared/package-files/79/79e9d5d43881714be2258e128aa0ab4ced7c73da3f4a2acd19bef1c44f476b01/blob b/shared/package-files/79/79e9d5d43881714be2258e128aa0ab4ced7c73da3f4a2acd19bef1c44f476b01/blob new file mode 100644 index 0000000000000000000000000000000000000000..3f4d295e4faed2284e6eb64bf5a831ba1e7ce83f --- /dev/null +++ b/shared/package-files/79/79e9d5d43881714be2258e128aa0ab4ced7c73da3f4a2acd19bef1c44f476b01/blob @@ -0,0 +1,6367 @@ +"V1","V2","V3","V4" +-0.519169169314285,-1.28597017046844,-1.83732558009613,-0.823711600363306 +2.55470518335245,3.46019223842148,2.14470065506344,3.77879183101721 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +3.9285319711191,11.1150262546776,6.23229817948523,5.32224747458835 +0.456427735358922,0.936212452453672,0.754061752268104,1.15333574263992 +1.43034023535892,2.93387591473929,1.8409025549039,3.6142906965945 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +1.21160151370958,2.52314642036336,1.93144919501018,1.53678822927528 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +0.822924947354005,2.97421786691875,2.27892772058348,1.52907233851526 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +1.43034023535892,2.93387591473929,1.8409025549039,3.6142906965945 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +1.46683159848559,2.25286218301195,1.54587851717011,2.55174637186151 +6.84292485811198,15.3360638586038,7.93131450916863,6.86302362161176 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +-0.1159118288809,-0.146663808077221,-0.153141534122139,-0.157033579737052 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +3.94861661590271,10.0019177844573,5.84589038108785,4.63788746640781 +-0.621731886290424,-1.29474960667264,-1.79670790333476,-0.788601065453334 +0.122455121883439,0.211869646618993,0.199759999993878,0.248423207212782 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +10.4116004137096,12.5181315494737,5.14236136002463,13.2060126887081 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.33750639232285,0.700500862135012,0.589090553001156,0.865919874743029 +0.5951989711191,1.68400110763546,1.42983134173056,0.806356227772743 +5.79900459941364,5.03163247473894,2.90585179904735,4.82849859090418 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +3.94861661590271,10.0019177844573,5.84589038108785,4.63788746640781 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +3.80292775811198,6.60185281703142,4.08141010801567,3.8140975644743 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.194688027928922,1.00923617504171,0.891559695168648,0.57613530044108 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +1.08678718468928,2.12521303182019,1.45414807030024,2.5820296997667 +0.41002351470978,0.975325571652453,0.883273662226039,0.444080258290533 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.08678718468928,2.12521303182019,1.45414807030024,2.5820296997667 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +6.07669051470978,6.46432172777775,3.38918036936393,6.58142325138111 +0.101222957714638,0.252039029503179,0.242297511704601,0.161685167931112 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +26.0286070159027,29.4852107195965,8.68245008981054,30.572162858488 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.21160151370958,3.25736802203672,2.49349018877338,1.53678822927528 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.0497249765587228,-0.180656633006219,-0.185215938777091,-0.0930180565272886 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.0497249765587228,-0.139936026202998,-0.143467649267169,-0.0930180565272886 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +0.930411673264803,3.18482640756811,2.41563047092612,1.61171721467986 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.258608530685715,0.369831773437915,0.337157061380252,0.410307197093554 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +0.365027973264803,1.24950144345829,1.0927439406395,0.632324255225828 +0.831627383352449,1.95096216375177,1.55459616837316,1.23010153310082 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.3492452288809,-0.988122259630304,-1.15121359640526,-0.473146088943221 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +4.67630102188344,18.0916946513655,8.38037231397769,9.48675465657108 +1.24050575814607,2.27802917317876,1.53936339465726,2.71764655814944 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.343981115310721,-0.672655290067114,-0.955644031925754,-0.817243217810937 +1.4396422711191,3.15508029473595,2.30135603732428,1.9503805742458 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +2.18057742344128,3.54295661200706,2.14933632888494,4.07909843449104 +0.266243683352449,0.360610818292528,0.329832896214191,0.393814308699183 +5.95816251213034,12.9063180155395,7.07696872859033,5.71889817894107 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +10.202928358112,17.7122037565111,7.98721446128919,10.2328959886686 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.413928542285362,-0.595050085851487,-0.759014224848206,-0.661175166008914 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +6.7934669534005,9.2316570143695,4.18370788341175,10.09130193834 +-0.205065186290424,-0.427045926301025,-0.460301270949546,-0.260103475407846 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.519169169314285,-0.742455224089781,-1.06078041825749,-0.823711600363306 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +3.9934657534005,5.42672929549919,2.94155472452071,5.9320622260204 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.79811139232285,1.65649519866614,1.19559729037625,2.04766645192929 +1.43034023535892,2.93387591473929,1.8409025549039,3.6142906965945 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.79811139232285,2.86913384658365,2.07083525232335,2.04766645192929 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +10.4116004137096,12.5181315494737,5.14236136002463,13.2060126887081 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +4.2396434711191,5.36444176894973,2.93750912830946,5.74373122662683 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +2.18057742344128,3.54295661200706,2.14933632888494,4.07909843449104 +-0.326981311521292,-0.418641632552171,-0.483106798916473,-0.449779528495782 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.519169169314285,-0.742455224089781,-1.06078041825749,-0.823711600363306 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +0.192699323441277,0.542294425066919,0.499362671384097,0.360473102274126 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.116374457714638,0.16729610060636,0.159942613217704,0.185886918968801 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +6.67826871370958,8.02945204954952,3.86894974952154,8.47067673243792 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.183818427928922,0.952889651606598,0.846760862787146,0.543969171232762 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.48816532792892,5.97558419687284,3.54605151026428,4.40388958393141 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +3.77816723535892,7.74967632151879,3.58178811392836,9.54695557837628 +-0.241391469314285,-0.345209939334061,-0.38824088969558,-0.382990680601358 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +0.5951989711191,1.68400110763546,1.42983134173056,0.806356227772743 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +3.87826751370958,10.4266497170204,5.98805049555438,4.91917168937959 +-0.519169169314285,-0.742455224089781,-1.06078041825749,-0.823711600363306 +0.514252827928922,2.06493258114397,1.58364101587791,1.52181523781047 +0.41002351470978,0.436178855681745,0.395011990294522,0.444080258290533 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +0.365027973264803,1.24950144345829,1.0927439406395,0.632324255225828 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +2.25868755814607,4.14778901005858,2.37786473480038,4.94823536934186 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +2.77008958335245,8.38954204318069,5.08304920985784,4.09737763753305 +0.430147421883439,0.744233322925142,0.625200275230135,0.872634810819172 +2.3729766711191,3.00253907150698,1.94403268340376,3.21483169488449 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.205065186290424,-0.427045926301025,-0.460301270949546,-0.260103475407846 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +1.08678718468928,2.12521303182019,1.45414807030024,2.5820296997667 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.730830430685715,2.33702306084496,1.88067653931448,1.15953245923567 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +4.26994507840119,6.98351582670726,3.42330355155261,8.05567753255396 +0.00990542792892218,0.0513483869628928,0.0509652403659611,0.029312879464322 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.402928158111979,0.699480128177213,0.638466345730688,0.404111622482144 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +-0.322452176558723,-1.17150632446919,-1.44857709919189,-0.603195352964424 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.5951989711191,1.68400110763546,1.42983134173056,0.806356227772743 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +24.602919358112,24.6589044710358,7.93177802569779,24.6751820627063 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.54861701590271,1.07642359876609,0.939379698178225,0.644383648608929 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +-0.243571864641078,-1.11715776725399,-1.3901101099406,-0.615475606825472 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +1.5765660732648,4.18021305101833,2.82133160680209,2.73102622567584 +0.345797173264803,1.18367385182485,1.04134229137205,0.599011462294818 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +2.55470518335245,3.46019223842148,2.14470065506344,3.77879183101721 +-0.243571864641078,-1.11715776725399,-1.3901101099406,-0.615475606825472 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +2.8688738732648,4.39174452245752,2.514446153392,4.96964251540533 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.183818427928922,0.952889651606598,0.846760862787146,0.543969171232762 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +1.25326751370958,2.60991539313312,1.98490133504304,1.58963713845578 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.514252827928922,2.66581649927057,2.04447176028872,1.52181523781047 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +1.5765660732648,2.41344713027542,1.62889656266039,2.73102622567584 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.6270229288809,-1.77404088041842,-2.59608025396518,-0.849470291772813 +0.502172684689279,0.981999004736992,0.786524961857392,1.19308067351752 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +1.60990472792892,6.46441700403761,3.74829539516386,4.76414987595165 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +10.202928358112,10.2261456067632,4.61142041930058,10.2328959886686 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +1.21160151370958,3.25736802203672,2.49349018877338,1.53678822927528 +2.34861721590271,2.66051400554222,1.79119219920575,2.7585920357919 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.544934513709576,1.13481994867196,0.982312129951437,0.691191730052151 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +6.54335771470978,15.5647270819163,7.96493290666894,7.0868520457721 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.599140916647551,-0.811499801626456,-1.23516250894671,-0.886219206900784 +-0.3492452288809,-0.988122259630304,-1.15121359640526,-0.473146088943221 +15.2618659711191,19.3109141948611,6.67039742615329,20.676280152343 +4.2396434711191,5.36444176894973,2.93750912830946,5.74373122662683 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.194688027928922,1.00923617504171,0.891559695168648,0.57613530044108 +3.90292815811198,6.77545272858273,4.1584638889832,3.91439168162467 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.223698778116561,-0.3870395973618,-0.447365711609579,-0.453814973637393 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +1.3684657534005,1.85961108782322,1.34434200205067,2.03277666684313 +10.202928358112,22.8663567245333,10.3114495303867,10.2328959886686 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +-0.621731886290424,-1.29474960667264,-1.79670790333476,-0.788601065453334 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +0.544934513709576,1.46504625405015,1.26815950669315,0.691191730052151 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +-0.205065186290424,-0.427045926301025,-0.460301270949546,-0.260103475407846 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +0.958162512130339,0.928205613165108,0.774005983074296,0.919685193983162 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.402928158111979,0.699480128177213,0.638466345730688,0.404111622482144 +2.32538449232285,4.82637922931352,2.61139909795933,5.96609929211482 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +4.07301788847871,5.21477772021197,2.87785669772671,5.60264455760968 +0.365027973264803,1.24950144345829,1.0927439406395,0.632324255225828 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.703052730685715,2.24819653864291,1.82061140155762,1.11546047832118 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.958162512130339,0.928205613165108,0.774005983074296,0.919685193983162 +-0.75664288529022,-1.39414332851747,-1.98452223344043,-0.819489994790195 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +2.34861721590271,5.94909017148265,4.0052275181914,2.7585920357919 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.0950820923228503,0.197344670088632,0.186247147328048,0.243946412119357 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.0381048732648031,0.130434097204455,0.128281592098255,0.0660076415298784 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +4.03638573068571,5.77236833255576,3.05327309043773,6.40411246742201 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +5.36171775814607,9.84610461596033,4.22389754654562,11.7462202134161 +0.183818427928922,0.952889651606598,0.846760862787146,0.543969171232762 +0.207850823441277,0.58493377550504,0.535546278902363,0.388816264624516 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +2.18057742344128,3.54295661200706,2.14933632888494,4.07909843449104 +15.802916358112,35.4168048671292,13.5765297200171,15.8493320480507 +4.17301828847871,5.34281051363706,2.92622873277125,5.7402002257062 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +4.2396434711191,5.36444176894973,2.93750912830946,5.74373122662683 +0.365027973264803,0.967859656315214,0.846435816753171,0.632324255225828 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +3.75060899954069,3.36697095067696,2.17145253764333,3.2631283029824 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +1.21160151370958,3.25736802203672,2.49349018877338,1.53678822927528 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +3.87826751370958,8.07644814215165,4.63832396910623,4.91917168937959 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.192699323441277,0.700099092341768,0.644674436662752,0.360473102274126 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +-0.326981311521292,-0.936111148598142,-1.08025964276956,-0.449779528495782 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +0.258608530685715,0.369831773437915,0.337157061380252,0.410307197093554 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +0.5951989711191,1.3044216489734,1.10754259488157,0.806356227772743 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +6.67826871370958,8.02945204954952,3.86894974952154,8.47067673243792 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +3.87826751370958,10.4266497170204,5.98805049555438,4.91917168937959 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +0.449378221883439,0.777506106762464,0.649154062145139,0.911648099441065 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +3.83599232792892,19.8852608746016,8.63771143817338,11.351753961717 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.247012883352449,0.579481627260966,0.533074015545376,0.365369073445633 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.194688027928922,1.00923617504171,0.891559695168648,0.57613530044108 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +2.77008958335245,8.38954204318069,5.08304920985784,4.09737763753305 +1.5765660732648,4.18021305101833,2.82133160680209,2.73102622567584 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.241391469314285,-0.345209939334061,-0.38824088969558,-0.382990680601358 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +1.60990472792892,8.34552646652591,4.83902854737853,4.76414987595165 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +0.653304323441277,1.83852898986583,1.46662474265277,1.22210411533563 +-0.294442372071078,-1.52634908535677,-2.28451526565964,-0.871335779094169 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +0.544934513709576,1.46504625405015,1.26815950669315,0.691191730052151 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +0.502172684689279,0.981999004736992,0.786524961857392,1.19308067351752 +0.122455121883439,0.366968992525759,0.345994469309356,0.248423207212782 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.47778178335245,2.00156522566986,1.42384705298044,2.18586072762818 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +17.1930168884787,22.0126117459196,7.20373291281237,23.6498746473968 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.183818427928922,0.952889651606598,0.846760862787146,0.543969171232762 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.192699323441277,0.542294425066919,0.499362671384097,0.360473102274126 +0.33750639232285,0.700500862135012,0.589090553001156,0.865919874743029 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +15.802916358112,35.4168048671292,13.5765297200171,15.8493320480507 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +3.9934657534005,5.42672929549919,2.94155472452071,5.9320622260204 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +2.20292835811198,3.82426638415563,2.71388270245909,2.20939871062859 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +2.58381792792892,13.3941596220761,6.68270214355247,7.64622629356468 +2.55470518335245,3.46019223842148,2.14470065506344,3.77879183101721 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +6.83638593068571,16.9335717532756,7.47800135223483,10.8465808998327 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.703052730685715,2.24819653864291,1.82061140155762,1.11546047832118 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.35265789232285,0.731948085221933,0.611771922752704,0.904793168051259 +1.08678718468928,3.68097694802007,2.51865833948826,2.5820296997667 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +-0.416006378116561,-0.719766743662219,-1.04766693691979,-0.843947048381208 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.544934513709576,1.46504625405015,1.26815950669315,0.691191730052151 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +2.55470518335245,3.46019223842148,2.14470065506344,3.77879183101721 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +5.79900459941364,11.2510722513118,6.49768215520993,4.82849859090418 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.5951989711191,1.3044216489734,1.10754259488157,0.806356227772743 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +1.16239562344128,4.22311872392887,3.00773214920361,2.17443605389426 +0.449378221883439,0.777506106762464,0.649154062145139,0.911648099441065 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.519169169314285,-1.28597017046844,-1.83732558009613,-0.823711600363306 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +2.18057742344128,7.92229182578012,4.80606213789658,4.07909843449104 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +2.55470518335245,3.46019223842148,2.14470065506344,3.77879183101721 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +2.47826601370958,5.16096088560877,3.36120753301299,3.14341802629572 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +37.5486113159027,95.1113161479578,23.9754567845153,44.1031000836305 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +0.456427735358922,0.936212452453672,0.754061752268104,1.15333574263992 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +3.94861661590271,10.0019177844573,5.84589038108785,4.63788746640781 +-0.322452176558723,-0.907444896929164,-1.12206299617353,-0.603195352964424 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +0.00990542792892218,0.0513483869628928,0.0509652403659611,0.029312879464322 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.473967276558723,-1.72197833491398,-2.62223590729172,-0.886627163533382 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +2.25868755814607,4.14778901005858,2.37786473480038,4.94823536934186 +0.270809458146069,0.861360500825945,0.758568311589007,0.593277690983777 +0.429341010781951,1.75380417127865,1.45914699062054,0.934268471865579 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +2.25868755814607,4.14778901005858,2.37786473480038,4.94823536934186 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +-0.0479196646410777,-0.17024594786461,-0.175926622274847,-0.12108699302073 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +6.54335771470978,15.5647270819163,7.96493290666894,7.0868520457721 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +2.20292835811198,4.93710667243187,3.50360750339482,2.20939871062859 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +10.4116004137096,12.5181315494737,5.14236136002463,13.2060126887081 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.395857141853931,-1.25909821723772,-1.87621508822346,-0.867226767803147 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +-0.500356626735197,-1.7127353878055,-2.55089674082185,-0.866749001502204 +2.34861721590271,2.66051400554222,1.79119219920575,2.7585920357919 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +15.802916358112,15.8388766457493,6.0716086705009,15.8493320480507 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +1.25326751370958,2.60991539313312,1.98490133504304,1.58963713845578 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +6.67826871370958,17.9544006048677,8.65123464146094,8.47067673243792 +1.11835651470978,1.18969631577255,0.950469461133994,1.21124772627918 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +15.9486052159027,18.0665828635101,6.48950596922976,18.7325950915625 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +1.16239562344128,4.22311872392887,3.00773214920361,2.17443605389426 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.125993335358922,0.577876403852594,0.536773642248726,0.318369384125165 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.395857141853931,-0.726940694658375,-1.08323328624345,-0.867226767803147 +1.11835651470978,2.66024183464848,2.12531432563321,1.21124772627918 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +10.202928358112,10.2261456067632,4.61142041930058,10.2328959886686 +0.514252827928922,2.06493258114397,1.58364101587791,1.52181523781047 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +3.61626295814607,6.64080151377456,3.27381177873561,7.9223530540128 +-0.519169169314285,-1.66018035131459,-2.3719771244244,-0.823711600363306 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.35265789232285,0.731948085221933,0.611771922752704,0.904793168051259 +-0.406833316647551,-1.23214253975519,-1.52245156456212,-0.601767446025224 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +6.7285321711191,14.7460655271621,6.92688088410752,9.11559677220187 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +2.34861721590271,5.94909017148265,4.0052275181914,2.7585920357919 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +0.54861701590271,1.07642359876609,0.939379698178225,0.644383648608929 +0.247012883352449,0.334563873489561,0.307770426373117,0.365369073445633 +0.831627383352449,1.12638853042086,0.897546516291406,1.23010153310082 +-0.17764510767715,-0.36870576057971,-0.426512214869939,-0.455773380556783 +0.730830430685715,1.04514848580679,0.841064117119248,1.15953245923567 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +-0.506533646599499,-0.688329673746886,-0.929910348150405,-0.752426412732505 +2.77008958335245,8.38954204318069,5.08304920985784,4.09737763753305 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.01476192188344,3.04100109819442,2.19231356468988,2.05863509271296 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.430147421883439,1.66415630118117,1.39799031496616,0.872634810819172 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.17764510767715,-0.36870576057971,-0.426512214869939,-0.455773380556783 +2.25868755814607,4.14778901005858,2.37786473480038,4.94823536934186 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.930411673264803,3.18482640756811,2.41563047092612,1.61171721467986 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.3492452288809,-0.988122259630304,-1.15121359640526,-0.473146088943221 +1.60990472792892,6.46441700403761,3.74829539516386,4.76414987595165 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.731414458146069,2.32640147908061,1.76654113276376,1.60235127625046 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +3.74335651470978,8.9043462182711,5.41119755040082,4.0542814455471 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.79811139232285,1.65649519866614,1.19559729037625,2.04766645192929 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +-0.241391469314285,-0.771912890859539,-0.868133021004313,-0.382990680601358 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.33750639232285,1.21330308396364,1.02033476805685,0.865919874743029 +0.33750639232285,0.700500862135012,0.589090553001156,0.865919874743029 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +3.94861661590271,10.0019177844573,5.84589038108785,4.63788746640781 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +-0.395857141853931,-0.726940694658375,-1.08323328624345,-0.867226767803147 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +0.521403484689279,1.76600739758199,1.40553866093218,1.23876992846073 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +1.5765660732648,2.41344713027542,1.62889656266039,2.73102622567584 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.183818427928922,0.952889651606598,0.846760862787146,0.543969171232762 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +-0.223698778116561,-0.3870395973618,-0.447365711609579,-0.453814973637393 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +4.07301788847871,11.6605974699453,6.43508320561999,5.60264455760968 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +8.27080875814607,33.9620172410753,12.3596594813099,18.1193314155026 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.11835651470978,1.18969631577255,0.950469461133994,1.21124772627918 +0.270809458146069,1.11201162492659,0.979307479248301,0.593277690983777 +-0.6270229288809,-1.37416615707034,-2.01091511780501,-0.849470291772813 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +16.7706075995407,15.0551946683247,5.95654225134269,14.5908689290125 +56.602919358112,56.7317219927082,12.8122392217629,56.7691711748665 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +6.7285321711191,19.0370887362608,8.94256476843698,9.11559677220187 +-0.565443642285362,-0.812863220372279,-1.26346801598109,-0.903192836117525 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +1.5765660732648,2.41344713027542,1.62889656266039,2.73102622567584 +6.67826871370958,17.9544006048677,8.65123464146094,8.47067673243792 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.703052730685715,1.74144555063303,1.4102395276296,1.11546047832118 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.322452176558723,-1.17150632446919,-1.44857709919189,-0.603195352964424 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.207850823441277,0.755146257055083,0.691387273104067,0.388816264624516 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.243571864641078,-0.865346685532193,-1.0767746610389,-0.615475606825472 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +10.2766894147098,10.932237952932,4.78285165297844,11.1302760108433 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.33750639232285,0.700500862135012,0.589090553001156,0.865919874743029 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.0283851581460693,0.116556585762907,0.114741127479072,0.0621849812720575 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +-0.322452176558723,-0.907444896929164,-1.12206299617353,-0.603195352964424 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +-0.519169169314285,-0.742455224089781,-1.06078041825749,-0.823711600363306 +3.74335651470978,3.98214468784947,2.41996111247532,4.0542814455471 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +6.21160151370958,16.6997745607327,8.24813632193256,7.87875880246349 +0.456427735358922,0.936212452453672,0.754061752268104,1.15333574263992 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.5951989711191,1.68400110763546,1.42983134173056,0.806356227772743 +-0.75664288529022,-1.39414332851747,-1.98452223344043,-0.819489994790195 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +0.247012883352449,0.334563873489561,0.307770426373117,0.365369073445633 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.0381048732648031,0.0583319015865953,0.0573692720387198,0.0660076415298784 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.185746772071078,-0.745848230016744,-0.898606430832638,-0.549675670720755 +0.0283851581460693,0.116556585762907,0.114741127479072,0.0621849812720575 +16.922926758112,16.9614356826735,6.3321522089606,16.9726320975228 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.0691427946102015,0.12548249370348,0.120981864323789,0.149186366906642 +6.84292485811198,15.3360638586038,7.93131450916863,6.86302362161176 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.194688027928922,0.781750979665326,0.690599170307587,0.57613530044108 +6.69060569954069,6.00624459535663,3.27516438375989,5.8210026224915 +0.456427735358922,0.936212452453672,0.754061752268104,1.15333574263992 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +2.25868755814607,4.14778901005858,2.37786473480038,4.94823536934186 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +3.65060859954069,3.27719927842392,2.12860572643799,3.17612532944143 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +2.20292835811198,4.93710667243187,3.50360750339482,2.20939871062859 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.183818427928922,0.738105150289148,0.655898143958968,0.543969171232762 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +1.55207963535892,7.1187114431013,4.36678757834312,3.92191091865906 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +10.3486172159027,11.7229154476423,4.9662045157507,12.1550727125517 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +1.24050575814607,5.09382808595536,3.44212119252846,2.71764655814944 +6.21160151370958,12.9355897518272,6.38897892241866,7.87875880246349 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +3.9285319711191,11.1150262546776,6.23229817948523,5.32224747458835 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +3.9934657534005,5.42672929549919,2.94155472452071,5.9320622260204 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +6.7285321711191,19.0370887362608,8.94256476843698,9.11559677220187 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.41002351470978,0.436178855681745,0.395011990294522,0.444080258290533 +-0.0479196646410777,-0.17024594786461,-0.175926622274847,-0.12108699302073 +0.00990542792892218,0.0513483869628928,0.0509652403659611,0.029312879464322 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +-0.223698778116561,-0.3870395973618,-0.447365711609579,-0.453814973637393 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.194688027928922,1.00923617504171,0.891559695168648,0.57613530044108 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +-0.0479196646410777,-0.0982915438280757,-0.101571282728004,-0.12108699302073 +2.20292835811198,4.93710667243187,3.50360750339482,2.20939871062859 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +-0.47555495798835,-0.922126208508661,-1.11122167892189,-0.550128280288605 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +10.202928358112,22.8663567245333,10.3114495303867,10.2328959886686 +-0.416006378116561,-0.719766743662219,-1.04766693691979,-0.843947048381208 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +2.20292835811198,4.93710667243187,3.50360750339482,2.20939871062859 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.185746772071078,-0.745848230016744,-0.898606430832638,-0.549675670720755 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +6.54335771470978,6.96075756127935,3.56202628310735,7.0868520457721 +-0.0898669465994985,-0.122120389136501,-0.126644188416478,-0.133492147475344 +1.11835651470978,2.06061446449556,1.64626139772669,1.21124772627918 +0.258608530685715,0.369831773437915,0.337157061380252,0.410307197093554 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +0.456427735358922,0.936212452453672,0.754061752268104,1.15333574263992 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +-0.322452176558723,-1.17150632446919,-1.44857709919189,-0.603195352964424 +0.1507547711191,0.330389998430346,0.314563528688958,0.204237665817496 +-0.352267464641078,-0.722561670648513,-1.1049215932355,-0.890135779369786 +-0.352267464641078,-0.722561670648513,-1.1049215932355,-0.890135779369786 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.821645235358922,1.68533689180248,1.212723119888,2.07619464002126 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.0381048732648031,0.0583319015865953,0.0573692720387198,0.0660076415298784 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +3.53815282344128,5.74871674142153,3.00847521486117,6.61864765173656 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +3.80292775811198,6.60185281703142,4.08141010801567,3.8140975644743 +8.27080875814607,33.9620172410753,12.3596594813099,18.1193314155026 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +3.74335651470978,3.98214468784947,2.41996111247532,4.0542814455471 +0.730830430685715,1.04514848580679,0.841064117119248,1.15953245923567 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +15.9486052159027,40.3981074039415,14.5109764875884,18.7325950915625 +1.11835651470978,1.18969631577255,0.950469461133994,1.21124772627918 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.125993335358922,0.258434184321504,0.240052470519661,0.318369384125165 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +25.882918158112,58.0076639668583,18.2761313721713,25.9589404236681 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +10.4116004137096,21.6820398595194,8.90683114644164,13.2060126887081 +10.202928358112,10.2261456067632,4.61142041930058,10.2328959886686 +2.18057742344128,3.54295661200706,2.14933632888494,4.07909843449104 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.365027973264803,1.24950144345829,1.0927439406395,0.632324255225828 +0.673018288478708,0.861680668278338,0.717853580568967,0.925771100044292 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +1.11039243993158,2.10575729183059,1.67377644435763,1.24818233316968 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.8688738732648,4.39174452245752,2.514446153392,4.96964251540533 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.41002351470978,0.975325571652453,0.883273662226039,0.444080258290533 +2.8688738732648,4.39174452245752,2.514446153392,4.96964251540533 +-0.0479196646410777,-0.0982915438280757,-0.101571282728004,-0.12108699302073 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +6.07669051470978,14.4546628117399,7.57843769390559,6.58142325138111 +4.67630102188344,8.09085181372453,3.74781643416226,9.48675465657108 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +6.84292485811198,11.8792639841492,6.14356980150867,6.86302362161176 +4.49316648335245,6.08571975073446,3.18055697875676,6.64606660421456 +1.60990472792892,8.34552646652591,4.83902854737853,4.76414987595165 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +2.05060919954069,4.11628542801612,3.05915173243963,1.78408384296971 +15.802916358112,15.8388766457493,6.0716086705009,15.8493320480507 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.125993335358922,0.577876403852594,0.536773642248726,0.318369384125165 +0.00990542792892218,0.0397742895123796,0.039477505434565,0.029312879464322 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +10.202928358112,10.2261456067632,4.61142041930058,10.2328959886686 +5.36171775814607,9.84610461596033,4.22389754654562,11.7462202134161 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.192699323441277,0.542294425066919,0.499362671384097,0.360473102274126 +2.34861721590271,5.94909017148265,4.0052275181914,2.7585920357919 +-0.17764510767715,-0.36870576057971,-0.426512214869939,-0.455773380556783 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +2.34861721590271,2.66051400554222,1.79119219920575,2.7585920357919 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.779242449016484,1.12760829209335,0.895413728548781,1.25530966140602 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.266243683352449,0.806350303123918,0.737528777150565,0.393814308699183 +4.34749723068571,6.21728373220188,3.21005820137408,6.89772065277497 +-0.3492452288809,-0.765396211113002,-0.891726217361026,-0.473146088943221 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +1.4396422711191,4.07319114581984,2.97103786875028,1.9503805742458 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +0.247012883352449,0.748107563938298,0.688195594834384,0.365369073445633 +22.9581625121303,22.240376806578,7.48886673045191,22.036222327798 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +-0.75664288529022,-1.39414332851747,-1.98452223344043,-0.819489994790195 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +1.4396422711191,4.07319114581984,2.97103786875028,1.9503805742458 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.17764510767715,-0.36870576057971,-0.426512214869939,-0.455773380556783 +0.285960958146069,1.17422748788211,1.02797880161664,0.626470944264067 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +-0.241391469314285,-0.345209939334061,-0.38824088969558,-0.382990680601358 +2.44468732792892,9.81640593884679,4.98913603724007,7.23450066829504 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +2.38686223535892,4.8958684451487,2.63987443463448,6.03130203433432 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.519169169314285,-1.66018035131459,-2.3719771244244,-0.823711600363306 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +0.930411673264803,2.46695592741458,1.87113931689761,1.61171721467986 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +-0.0898669465994985,-0.122120389136501,-0.126644188416478,-0.133492147475344 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +2.3729766711191,5.20055022356078,3.36716337922977,3.21483169488449 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +0.116374457714638,0.16729610060636,0.159942613217704,0.185886918968801 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +2.52599283535892,11.5856259515338,6.1347456233349,6.38286764142599 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.247012883352449,0.748107563938298,0.688195594834384,0.365369073445633 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.33997618529022,-0.626419067424891,-0.700695272477752,-0.36821476515359 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +2.55470518335245,7.7372250603276,4.79569645611018,3.77879183101721 +0.821645235358922,1.68533689180248,1.212723119888,2.07619464002126 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +3.74335651470978,3.98214468784947,2.41996111247532,4.0542814455471 +0.33750639232285,0.700500862135012,0.589090553001156,0.865919874743029 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +3.61626295814607,11.5022056248379,5.67040833518751,7.9223530540128 +3.65060859954069,3.27719927842392,2.12860572643799,3.17612532944143 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +0.502172684689279,0.981999004736992,0.786524961857392,1.19308067351752 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +4.2396434711191,5.36444176894973,2.93750912830946,5.74373122662683 +-0.599140916647551,-0.811499801626456,-1.23516250894671,-0.886219206900784 +-0.599140916647551,-1.40555888674909,-2.13936422109995,-0.886219206900784 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +3.9285319711191,11.1150262546776,6.23229817948523,5.32224747458835 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.473967276558723,-1.72197833491398,-2.62223590729172,-0.886627163533382 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.17764510767715,-0.36870576057971,-0.426512214869939,-0.455773380556783 +1.3267997534005,1.80299106982663,1.31217501921,1.97088423556363 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +0.79811139232285,3.7040358686195,2.67343681499585,2.04766645192929 +0.183818427928922,0.738105150289148,0.655898143958968,0.543969171232762 +-0.395857141853931,-0.726940694658375,-1.08323328624345,-0.867226767803147 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.34335501470978,5.57415364561272,3.82986239269816,2.53799517068018 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.514252827928922,2.06493258114397,1.58364101587791,1.52181523781047 +3.80292775811198,8.5229553381584,5.26907779246244,3.8140975644743 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.33750639232285,1.5663675460311,1.31724652141353,0.865919874743029 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +2.55470518335245,3.46019223842148,2.14470065506344,3.77879183101721 +-0.500356626735197,-1.7127353878055,-2.55089674082185,-0.866749001502204 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +1.43034023535892,5.08162214743106,3.1885367568769,3.6142906965945 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.449378221883439,0.777506106762464,0.649154062145139,0.911648099441065 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +6.98861371590271,17.7022857909971,8.62217354244057,8.20854671735228 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.502172684689279,0.981999004736992,0.786524961857392,1.19308067351752 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +4.49316648335245,10.5407758088975,5.50888628357447,6.64606660421456 +0.258608530685715,0.369831773437915,0.337157061380252,0.410307197093554 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.456427735358922,0.936212452453672,0.754061752268104,1.15333574263992 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +6.67826871370958,17.9544006048677,8.65123464146094,8.47067673243792 +0.35265789232285,0.731948085221933,0.611771922752704,0.904793168051259 +0.79811139232285,1.65649519866614,1.19559729037625,2.04766645192929 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +3.53815282344128,12.8545214172096,6.72715508905287,6.61864765173656 +15.6505971995407,14.0497466246289,5.70574189818379,13.6164304747982 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +6.84292485811198,11.8792639841492,6.14356980150867,6.86302362161176 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.243571864641078,-1.11715776725399,-1.3901101099406,-0.615475606825472 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +1.55207963535892,3.18358453979603,1.95288677369538,3.92191091865906 +5.95816251213034,12.9063180155395,7.07696872859033,5.71889817894107 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +14.9581625121303,14.4904963726097,5.76828468958384,14.3574815518653 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +16.922926758112,29.3780683717022,10.9676093471793,16.9726320975228 +0.266243683352449,0.360610818292528,0.329832896214191,0.393814308699183 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.243571864641078,-1.11715776725399,-1.3901101099406,-0.615475606825472 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +15.9486052159027,31.2922394387528,11.2401540547275,18.7325950915625 +0.270809458146069,1.11201162492659,0.979307479248301,0.593277690983777 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.35265789232285,0.731948085221933,0.611771922752704,0.904793168051259 +0.41002351470978,0.436178855681745,0.395011990294522,0.444080258290533 +1.55207963535892,3.18358453979603,1.95288677369538,3.92191091865906 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +-0.3492452288809,-0.765396211113002,-0.891726217361026,-0.473146088943221 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.406833316647551,-1.23214253975519,-1.52245156456212,-0.601767446025224 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.673018288478708,0.861680668278338,0.717853580568967,0.925771100044292 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +3.80292775811198,6.60185281703142,4.08141010801567,3.8140975644743 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.125993335358922,0.577876403852594,0.536773642248726,0.318369384125165 +16.922926758112,16.9614356826735,6.3321522089606,16.9726320975228 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +1.48816532792892,7.71444602611624,4.5779328146824,4.40388958393141 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +2.77008958335245,6.49851132310915,3.93731298754644,4.09737763753305 +-0.413928542285362,-0.595050085851487,-0.759014224848206,-0.661175166008914 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.207850823441277,0.755146257055083,0.691387273104067,0.388816264624516 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.473967276558723,-1.72197833491398,-2.62223590729172,-0.886627163533382 +1.21160151370958,2.52314642036336,1.93144919501018,1.53678822927528 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +2.01088062344128,7.305763580991,4.53397621246307,3.76165501616668 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.77008958335245,8.38954204318069,5.08304920985784,4.09737763753305 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.00990542792892218,0.0397742895123796,0.039477505434565,0.029312879464322 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.730830430685715,1.04514848580679,0.841064117119248,1.15953245923567 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.0497249765587228,-0.180656633006219,-0.185215938777091,-0.0930180565272886 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.519169169314285,-0.742455224089781,-1.06078041825749,-0.823711600363306 +0.0283851581460693,0.116556585762907,0.114741127479072,0.0621849812720575 +-0.0898669465994985,-0.122120389136501,-0.126644188416478,-0.133492147475344 +-0.0479196646410777,-0.17024594786461,-0.175926622274847,-0.12108699302073 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.258608530685715,0.369831773437915,0.337157061380252,0.410307197093554 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.514252827928922,2.06493258114397,1.58364101587791,1.52181523781047 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.0381048732648031,0.0583319015865953,0.0573692720387198,0.0660076415298784 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +10.202928358112,22.8663567245333,10.3114495303867,10.2328959886686 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +1.55207963535892,3.18358453979603,1.95288677369538,3.92191091865906 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +1.11835651470978,2.66024183464848,2.12531432563321,1.21124772627918 +15.3697197306857,21.9799814421095,7.10413978614879,24.3855320862372 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +0.183818427928922,0.738105150289148,0.655898143958968,0.543969171232762 +-0.599140916647551,-0.811499801626456,-1.23516250894671,-0.886219206900784 +0.730830430685715,2.33702306084496,1.88067653931448,1.15953245923567 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +1.11835651470978,2.66024183464848,2.12531432563321,1.21124772627918 +-0.500356626735197,-0.765958550920511,-1.14079570321206,-0.866749001502204 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +1.91940425771464,2.75927255953617,1.80871215070141,3.06589736896617 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +0.250608999540694,0.389668112773407,0.369861398787759,0.218036409416041 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +0.456427735358922,2.0934346850682,1.68613333730409,1.15333574263992 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.831627383352449,1.12638853042086,0.897546516291406,1.23010153310082 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.125993335358922,0.577876403852594,0.536773642248726,0.318369384125165 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.6229766711191,1.36529849015906,1.15218858663939,0.843988553221976 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +0.125993335358922,0.258434184321504,0.240052470519661,0.318369384125165 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +1.07669051470978,2.56113065245875,2.0591041092176,1.16612092896603 +25.882918158112,25.941815969172,8.17333442277831,25.9589404236681 +6.67826871370958,8.02945204954952,3.86894974952154,8.47067673243792 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +2.44468732792892,5.66750461126784,2.88047903412422,7.23450066829504 +0.365027973264803,1.24950144345829,1.0927439406395,0.632324255225828 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +2.58381792792892,10.3750714305489,5.17639882192867,7.64622629356468 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +16.922926758112,16.9614356826735,6.3321522089606,16.9726320975228 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +0.266243683352449,0.360610818292528,0.329832896214191,0.393814308699183 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.270809458146069,1.11201162492659,0.979307479248301,0.593277690983777 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +23.7403790225008,29.3781884529986,8.57179233495263,31.2529270856336 +-0.500356626735197,-1.32667912668616,-1.97591611901956,-0.866749001502204 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.821645235358922,1.68533689180248,1.212723119888,2.07619464002126 +-0.241391469314285,-0.345209939334061,-0.38824088969558,-0.382990680601358 +1.63959054735401,2.65010421913564,1.73999286849157,3.0465142179869 +1.24050575814607,2.27802917317876,1.53936339465726,2.71764655814944 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +0.125993335358922,0.258434184321504,0.240052470519661,0.318369384125165 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +-0.205065186290424,-0.427045926301025,-0.460301270949546,-0.260103475407846 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.544934513709576,1.46504625405015,1.26815950669315,0.691191730052151 +2.25868755814607,4.14778901005858,2.37786473480038,4.94823536934186 +0.247012883352449,0.334563873489561,0.307770426373117,0.365369073445633 +-0.352267464641078,-0.722561670648513,-1.1049215932355,-0.890135779369786 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +0.6229766711191,1.76259277166273,1.48746906924821,0.843988553221976 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.599140916647551,-0.811499801626456,-1.23516250894671,-0.886219206900784 +4.34749723068571,6.21728373220188,3.21005820137408,6.89772065277497 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +0.402928158111979,0.699480128177213,0.638466345730688,0.404111622482144 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +-0.17764510767715,-0.824451144351993,-0.953710305683181,-0.455773380556783 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +2.3729766711191,3.00253907150698,1.94403268340376,3.21483169488449 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.247012883352449,0.334563873489561,0.307770426373117,0.365369073445633 +0.365027973264803,1.24950144345829,1.0927439406395,0.632324255225828 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.244342041853931,-0.777175896975556,-0.930189306283492,-0.535294015924552 +6.21160151370958,16.6997745607327,8.24813632193256,7.87875880246349 +2.8688738732648,4.39174452245752,2.514446153392,4.96964251540533 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +2.58381792792892,13.3941596220761,6.68270214355247,7.64622629356468 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +3.87826751370958,4.66293950896731,2.67793759215218,4.91917168937959 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.413928542285362,-1.030656981743,-1.3146512011046,-0.661175166008914 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.125993335358922,0.577876403852594,0.536773642248726,0.318369384125165 +0.79811139232285,1.65649519866614,1.19559729037625,2.04766645192929 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +6.11039243993158,6.69021836828077,3.45903547552821,6.86863816609388 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +2.58381792792892,10.3750714305489,5.17639882192867,7.64622629356468 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.151673515310721,-0.29659765578896,-0.330823018103502,-0.360351618713897 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +1.11835651470978,1.18969631577255,0.950469461133994,1.21124772627918 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +10.2766894147098,24.4452272089591,10.694781422357,11.1302760108433 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +0.456427735358922,1.62156753432842,1.30607326697277,1.15333574263992 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.45138258409729,-1.14336030428846,-1.36530628992118,-0.530175966162011 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +0.703052730685715,2.24819653864291,1.82061140155762,1.11546047832118 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.285960958146069,1.17422748788211,1.02797880161664,0.626470944264067 +0.456427735358922,1.62156753432842,1.30607326697277,1.15333574263992 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +2.18057742344128,3.54295661200706,2.14933632888494,4.07909843449104 +3.65060859954069,3.27719927842392,2.12860572643799,3.17612532944143 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.456427735358922,2.0934346850682,1.68613333730409,1.15333574263992 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +2.3729766711191,5.20055022356078,3.36716337922977,3.21483169488449 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.195179476558723,-0.709109777565692,-0.79229815703036,-0.36511260215609 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +4.5919507732648,7.02947412356279,3.46066972250574,7.95446394633423 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +-0.519169169314285,-1.66018035131459,-2.3719771244244,-0.823711600363306 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +1.5765660732648,4.18021305101833,2.82133160680209,2.73102622567584 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +1.21160151370958,3.25736802203672,2.49349018877338,1.53678822927528 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.207850823441277,0.755146257055083,0.691387273104067,0.388816264624516 +1.24050575814607,2.27802917317876,1.53936339465726,2.71764655814944 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.449378221883439,0.777506106762464,0.649154062145139,0.911648099441065 +-0.205065186290424,-0.427045926301025,-0.460301270949546,-0.260103475407846 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +2.34861721590271,2.66051400554222,1.79119219920575,2.7585920357919 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +-0.223698778116561,-0.3870395973618,-0.447365711609579,-0.453814973637393 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +-0.75664288529022,-0.80490902600848,-1.14576444568963,-0.819489994790195 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.136862935358922,0.486237963730219,0.449088449793435,0.345835502454588 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +0.192699323441277,0.700099092341768,0.644674436662752,0.360473102274126 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.73783972188344,4.73696098173036,2.62124235110018,5.55422193930149 +4.04861701590271,10.2552206184637,5.94961478792257,4.75534394469134 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +0.653304323441277,1.83852898986583,1.46662474265277,1.22210411533563 +-0.352267464641078,-0.722561670648513,-1.1049215932355,-0.890135779369786 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +1.5765660732648,5.39663184339763,3.64232344242437,2.73102622567584 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +1.60990472792892,8.34552646652591,4.83902854737853,4.76414987595165 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +1.55207963535892,3.18358453979603,1.95288677369538,3.92191091865906 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.519169169314285,-1.28597017046844,-1.83732558009613,-0.823711600363306 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +16.922926758112,16.9614356826735,6.3321522089606,16.9726320975228 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +1.21160151370958,3.25736802203672,2.49349018877338,1.53678822927528 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +1.25326751370958,2.60991539313312,1.98490133504304,1.58963713845578 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +0.0283851581460693,0.116556585762907,0.114741127479072,0.0621849812720575 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.730830430685715,1.04514848580679,0.841064117119248,1.15953245923567 +-0.519169169314285,-1.66018035131459,-2.3719771244244,-0.823711600363306 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +1.5765660732648,2.41344713027542,1.62889656266039,2.73102622567584 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.413928542285362,-0.595050085851487,-0.759014224848206,-0.661175166008914 +4.17301828847871,9.25401926483255,5.06837683972769,5.7402002257062 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +0.673018288478708,0.861680668278338,0.717853580568967,0.925771100044292 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.33997618529022,-0.626419067424891,-0.700695272477752,-0.36821476515359 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +2.77008958335245,8.38954204318069,5.08304920985784,4.09737763753305 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +2.34861721590271,2.66051400554222,1.79119219920575,2.7585920357919 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +-0.0479196646410777,-0.0982915438280757,-0.101571282728004,-0.12108699302073 +5.92294832792892,13.7311371386199,5.06240393644057,17.5276294629383 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +0.54861701590271,1.07642359876609,0.939379698178225,0.644383648608929 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +23.4581625121303,22.7247443337011,7.58590577595428,22.5161436262937 +0.250608999540694,0.503059370439827,0.477489012636656,0.218036409416041 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.0497249765587228,-0.0807921023976277,-0.082831085924403,-0.0930180565272886 +0.456427735358922,1.62156753432842,1.30607326697277,1.15333574263992 +0.194688027928922,1.00923617504171,0.891559695168648,0.57613530044108 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +-0.597071441888021,-1.33813039757238,-1.65095611335372,-0.598825136097998 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +-0.413928542285362,-0.595050085851487,-0.759014224848206,-0.661175166008914 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.345797173264803,1.18367385182485,1.04134229137205,0.599011462294818 +0.0381048732648031,0.0583319015865953,0.0573692720387198,0.0660076415298784 +1.08678718468928,3.68097694802007,2.51865833948826,2.5820296997667 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +0.35265789232285,0.731948085221933,0.611771922752704,0.904793168051259 +0.514252827928922,2.66581649927057,2.04447176028872,1.52181523781047 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +2.47826601370958,5.16096088560877,3.36120753301299,3.14341802629572 +1.5765660732648,2.41344713027542,1.62889656266039,2.73102622567584 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +3.94861661590271,10.0019177844573,5.84589038108785,4.63788746640781 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.0582731946102014,0.105756005625457,0.102524446321683,0.125733509051093 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.0479196646410777,-0.0982915438280757,-0.101571282728004,-0.12108699302073 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +3.53815282344128,9.95706947446389,5.21083192545125,6.61864765173656 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +1.16239562344128,4.22311872392887,3.00773214920361,2.17443605389426 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +2.20292835811198,4.93710667243187,3.50360750339482,2.20939871062859 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +1.43034023535892,2.93387591473929,1.8409025549039,3.6142906965945 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +-0.33997618529022,-0.626419067424891,-0.700695272477752,-0.36821476515359 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +6.84292485811198,15.3360638586038,7.93131450916863,6.86302362161176 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +1.55207963535892,3.18358453979603,1.95288677369538,3.92191091865906 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +0.402928158111979,0.699480128177213,0.638466345730688,0.404111622482144 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.194688027928922,1.00923617504171,0.891559695168648,0.57613530044108 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +5.95816251213034,5.77188088439532,3.16491663035365,5.71889817894107 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.11835651470978,2.06061446449556,1.64626139772669,1.21124772627918 +2.44468732792892,5.66750461126784,2.88047903412422,7.23450066829504 +1.11835651470978,1.18969631577255,0.950469461133994,1.21124772627918 +-0.6270229288809,-1.77404088041842,-2.59608025396518,-0.849470291772813 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +0.122455121883439,0.211869646618993,0.199759999993878,0.248423207212782 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.223698778116561,-0.865446849685133,-1.00034014196158,-0.453814973637393 +3.74335651470978,3.98214468784947,2.41996111247532,4.0542814455471 +15.9486052159027,18.0665828635101,6.48950596922976,18.7325950915625 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +0.41002351470978,0.436178855681745,0.395011990294522,0.444080258290533 +-0.519169169314285,-1.28597017046844,-1.83732558009613,-0.823711600363306 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +4.2396434711191,5.36444176894973,2.93750912830946,5.74373122662683 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +16.0730064884787,46.0152309480704,15.4738370844025,22.1092430214528 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +1.11835651470978,2.66024183464848,2.12531432563321,1.21124772627918 +-0.621731886290424,-0.747524033945609,-1.03732979164545,-0.788601065453334 +6.69060569954069,6.00624459535663,3.27516438375989,5.8210026224915 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +-0.416006378116561,-0.719766743662219,-1.04766693691979,-0.843947048381208 +2.18057742344128,7.92229182578012,4.80606213789658,4.07909843449104 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +1.43034023535892,2.93387591473929,1.8409025549039,3.6142906965945 +-0.243571864641078,-1.11715776725399,-1.3901101099406,-0.615475606825472 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.0381048732648031,0.0583319015865953,0.0573692720387198,0.0660076415298784 +6.98861371590271,17.7022857909971,8.62217354244057,8.20854671735228 +0.730830430685715,1.81025027887104,1.4567657832736,1.15953245923567 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +-0.17764510767715,-0.36870576057971,-0.426512214869939,-0.455773380556783 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +3.94861661590271,10.0019177844573,5.84589038108785,4.63788746640781 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +1.24050575814607,2.27802917317876,1.53936339465726,2.71764655814944 +1.25326751370958,2.60991539313312,1.98490133504304,1.58963713845578 +0.192699323441277,0.700099092341768,0.644674436662752,0.360473102274126 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.730830430685715,2.33702306084496,1.88067653931448,1.15953245923567 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +-0.473967276558723,-1.72197833491398,-2.62223590729172,-0.886627163533382 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +1.60990472792892,6.46441700403761,3.74829539516386,4.76414987595165 +0.703052730685715,1.00542405743706,0.814202170898802,1.11546047832118 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +-0.0944424720710778,-0.489576890209687,-0.531055465549125,-0.279481191524184 +0.136862935358922,0.280729619249858,0.259281337378191,0.345835502454588 +3.34421362344128,5.43360838361648,2.89582691996817,6.25585517365157 +6.3729766711191,8.06375877594004,3.86000417983789,8.63390173297022 +0.430147421883439,0.744233322925142,0.625200275230135,0.872634810819172 +-0.322452176558723,-1.17150632446919,-1.44857709919189,-0.603195352964424 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.205065186290424,-0.427045926301025,-0.460301270949546,-0.260103475407846 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +-0.205065186290424,-0.551313920209864,-0.594246385541899,-0.260103475407846 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +2.3729766711191,6.71388146898872,4.34698923057213,3.21483169488449 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +0.122455121883439,0.366968992525759,0.345994469309356,0.248423207212782 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +15.802916358112,15.8388766457493,6.0716086705009,15.8493320480507 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +1.24050575814607,2.27802917317876,1.53936339465726,2.71764655814944 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +-0.621731886290424,-1.67151455471724,-2.31953992920492,-0.788601065453334 +6.83638593068571,16.9335717532756,7.47800135223483,10.8465808998327 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +17.0686156159027,19.335330846526,6.76133604249464,20.0481146017338 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +2.34335501470978,5.57415364561272,3.82986239269816,2.53799517068018 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +10.3486172159027,20.3046851681505,8.60171854205821,12.1550727125517 +-0.3492452288809,-0.988122259630304,-1.15121359640526,-0.473146088943221 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +-0.0479196646410777,-0.0982915438280757,-0.101571282728004,-0.12108699302073 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +0.831627383352449,2.51868132309713,2.00697502339571,1.23010153310082 +3.9285319711191,4.9707908554308,2.78716847707543,5.32224747458835 +0.266243683352449,0.624596259041647,0.571287334250572,0.393814308699183 +6.07669051470978,6.46432172777775,3.38918036936393,6.58142325138111 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.514252827928922,2.66581649927057,2.04447176028872,1.52181523781047 +2.34861721590271,2.66051400554222,1.79119219920575,2.7585920357919 +-0.294442372071078,-0.682604062450473,-1.02166628593019,-0.871335779094169 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +10.202928358112,22.8663567245333,10.3114495303867,10.2328959886686 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.149296952645995,-0.241311762104115,-0.261577558797885,-0.27740785019294 +1.48816532792892,3.45000514462981,2.04731379401136,4.40388958393141 +0.731414458146069,2.32640147908061,1.76654113276376,1.60235127625046 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.32916020767715,-0.683178199000802,-0.994943257780143,-0.844506570203084 +1.01476192188344,1.75572280264849,1.26573282672177,2.05863509271296 +-0.241391469314285,-0.771912890859539,-0.868133021004313,-0.382990680601358 +24.602919358112,24.6589044710358,7.93177802569779,24.6751820627063 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.258608530685715,0.82696898564648,0.753906108340313,0.410307197093554 +0.79811139232285,1.65649519866614,1.19559729037625,2.04766645192929 +3.61626295814607,6.64080151377456,3.27381177873561,7.9223530540128 +-0.244342041853931,-0.777175896975556,-0.930189306283492,-0.535294015924552 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.192699323441277,0.700099092341768,0.644674436662752,0.360473102274126 +1.54749603068571,2.2130484245787,1.53258601351772,2.45525063376856 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +2.3729766711191,6.71388146898872,4.34698923057213,3.21483169488449 +2.3729766711191,3.00253907150698,1.94403268340376,3.21483169488449 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.41002351470978,0.436178855681745,0.395011990294522,0.444080258290533 +-0.17764510767715,-0.824451144351993,-0.953710305683181,-0.455773380556783 +1.54749603068571,3.83311231098056,2.65451684238214,2.45525063376856 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +0.731414458146069,1.34314852019034,1.0199129985357,1.60235127625046 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +0.930411673264803,3.18482640756811,2.41563047092612,1.61171721467986 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.0084988984855866,0.0130532005277249,0.0130037157735761,0.0147849510453725 +15.802916358112,35.4168048671292,13.5765297200171,15.8493320480507 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +1.25326751370958,2.60991539313312,1.98490133504304,1.58963713845578 +2.47826601370958,6.66277185346354,4.33930026616874,3.14341802629572 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +0.33750639232285,0.700500862135012,0.589090553001156,0.865919874743029 +1.16239562344128,4.22311872392887,3.00773214920361,2.17443605389426 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +2.08899075814607,3.83616267664049,2.2509867523765,4.57647093260261 +2.34335501470978,2.49283729372366,1.71276653090862,2.53799517068018 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +38.1581442121303,64.0254865649426,17.4740270602233,36.6258122369505 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.731414458146069,3.00337139502384,2.28059479586148,1.60235127625046 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.514252827928922,2.66581649927057,2.04447176028872,1.52181523781047 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.514252827928922,2.06493258114397,1.58364101587791,1.52181523781047 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +6.07669051470978,6.46432172777775,3.38918036936393,6.58142325138111 +0.0381048732648031,0.0583319015865953,0.0573692720387198,0.0660076415298784 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.322452176558723,-1.17150632446919,-1.44857709919189,-0.603195352964424 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +0.544934513709576,0.655188602847511,0.567138172655697,0.691191730052151 +0.54861701590271,1.38965689049524,1.2127339756032,0.644383648608929 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +-0.3492452288809,-0.765396211113002,-0.891726217361026,-0.473146088943221 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +0.6229766711191,1.76259277166273,1.48746906924821,0.843988553221976 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.6229766711191,1.76259277166273,1.48746906924821,0.843988553221976 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +0.879470327928922,2.03887101719182,1.3923951535434,2.60259404237908 +0.285960958146069,0.525130496790642,0.459726095968714,0.626470944264067 +4.04861701590271,4.58627408542844,2.66074862114657,4.75534394469134 +0.285960958146069,1.17422748788211,1.02797880161664,0.626470944264067 +0.930411673264803,2.46695592741458,1.87113931689761,1.61171721467986 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +6.98861371590271,7.91670287715962,3.85595323093946,8.20854671735228 +0.00990542792892218,0.0229636967567985,0.022792348389581,0.029312879464322 +1.4396422711191,4.07319114581984,2.97103786875028,1.9503805742458 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +2.8688738732648,4.39174452245752,2.514446153392,4.96964251540533 +-0.519169169314285,-0.742455224089781,-1.06078041825749,-0.823711600363306 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.958162512130339,0.928205613165108,0.774005983074296,0.919685193983162 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +-0.33997618529022,-0.626419067424891,-0.700695272477752,-0.36821476515359 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +1.07669051470978,1.14537244763123,0.920859352191939,1.16612092896603 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.75664288529022,-1.79983129785811,-2.56200718676437,-0.819489994790195 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +0.0283851581460693,0.0521256897982289,0.0513137921716348,0.0621849812720575 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.456427735358922,2.0934346850682,1.68613333730409,1.15333574263992 +-0.406833316647551,-0.551030895372367,-0.680861038162364,-0.601767446025224 +0.6229766711191,1.36529849015906,1.15218858663939,0.843988553221976 +-0.308049026735197,-0.47156922387567,-0.56398587372986,-0.533621765097082 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +0.41002351470978,0.975325571652453,0.883273662226039,0.444080258290533 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +2.58381792792892,5.990050283289,2.98859525327338,7.64622629356468 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.831627383352449,1.12638853042086,0.897546516291406,1.23010153310082 +-0.185746772071078,-0.962885924551043,-1.16009591380323,-0.549675670720755 +0.183818427928922,0.426145207209689,0.378682969975686,0.543969171232762 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +6.21160151370958,7.46836622534402,3.68867870070526,7.87875880246349 +0.194688027928922,0.451344138549029,0.398717616879218,0.57613530044108 +0.365027973264803,0.967859656315214,0.846435816753171,0.632324255225828 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +1.25326751370958,1.50683535478755,1.14598332010195,1.58963713845578 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.402928158111979,0.903024962477792,0.824256508042954,0.404111622482144 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +2.20292835811198,2.20794122634509,1.56686090881383,2.20939871062859 +-0.3492452288809,-0.441901708522811,-0.514838371636835,-0.473146088943221 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +3.77816723535892,17.3288030585365,8.00912170374458,9.54695557837628 +0.5951989711191,0.753108190171567,0.639440015293852,0.806356227772743 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.621731886290424,-1.29474960667264,-1.79670790333476,-0.788601065453334 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +3.94861661590271,4.47299361428212,2.61436165622492,4.63788746640781 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +0.365027973264803,0.558794033111367,0.488689946654184,0.632324255225828 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.308049026735197,-1.05446084068282,-1.26111075200958,-0.533621765097082 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.125993335358922,0.258434184321504,0.240052470519661,0.318369384125165 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +2.15568769232285,4.47417033074,2.47909078248831,5.53071840706263 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +-0.597071441888021,-1.03651134897035,-1.27882510646766,-0.598825136097998 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.0606794166475514,-0.0821865661384358,-0.0841843910937643,-0.0897539510362449 +1.25326751370958,3.36938628420498,2.56249660482886,1.58963713845578 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.514252827928922,1.1921893815819,0.914315566816845,1.52181523781047 +-0.33997618529022,-0.361663217203275,-0.404546604184928,-0.36821476515359 +-0.322452176558723,-0.523913555516805,-0.647823372888505,-0.603195352964424 +-0.244342041853931,-1.00332976868671,-1.2008692306854,-0.535294015924552 +3.90292815811198,3.91180945672882,2.40089024571979,3.91439168162467 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.395857141853931,-0.726940694658375,-1.08323328624345,-0.867226767803147 +0.365027973264803,0.967859656315214,0.846435816753171,0.632324255225828 +-0.243571864641078,-1.11715776725399,-1.3901101099406,-0.615475606825472 +0.6229766711191,0.788255450817524,0.665216390653467,0.843988553221976 +-0.6270229288809,-0.793375200695834,-1.16100238458221,-0.849470291772813 +2.15568769232285,4.47417033074,2.47909078248831,5.53071840706263 +3.53815282344128,5.74871674142153,3.00847521486117,6.61864765173656 +1.21160151370958,3.25736802203672,2.49349018877338,1.53678822927528 +1.60990472792892,3.73223289743511,2.16407935540009,4.76414987595165 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +1.07669051470978,2.56113065245875,2.0591041092176,1.16612092896603 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +-0.243571864641078,-0.865346685532193,-1.0767746610389,-0.615475606825472 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +-0.473967276558723,-0.770092122529914,-1.17269954834902,-0.886627163533382 +0.653304323441277,2.37353071975664,1.8934044011433,1.22210411533563 +0.1507547711191,0.19075075453132,0.181613337965809,0.204237665817496 +1.16239562344128,1.88863610875142,1.34509870874616,2.17443605389426 +1.4396422711191,1.82158645748068,1.32868852765034,1.9503805742458 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +0.456427735358922,2.0934346850682,1.68613333730409,1.15333574263992 +0.266243683352449,0.360610818292528,0.329832896214191,0.393814308699183 +0.192699323441277,0.313093832292419,0.288307172746859,0.360473102274126 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +-0.0898669465994985,-0.122120389136501,-0.126644188416478,-0.133492147475344 +3.90292815811198,6.77545272858273,4.1584638889832,3.91439168162467 +3.80292775811198,3.81158150106338,2.35640322453611,3.8140975644743 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +1.08678718468928,2.12521303182019,1.45414807030024,2.5820296997667 +6.84292485811198,6.85849625902316,3.54699167868629,6.86302362161176 +0.879470327928922,4.55905419179506,3.11349021486431,2.60259404237908 +4.24701258335245,5.75231931776573,3.0615872307781,6.28196809588007 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +-0.597071441888021,-0.598430106346134,-0.738330019465555,-0.598825136097998 +-0.185746772071078,-0.430615676374773,-0.518810664736753,-0.549675670720755 +1.54749603068571,4.94852671485678,3.42696650759104,2.45525063376856 +2.01088062344128,3.26723679892763,2.02765580388689,3.76165501616668 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +-0.244342041853931,-0.777175896975556,-0.930189306283492,-0.535294015924552 +0.207850823441277,0.337711672745939,0.309197788287781,0.388816264624516 +0.753925094610201,3.05949264358027,2.31635831469048,1.62671101766615 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +3.53815282344128,5.74871674142153,3.00847521486117,6.61864765173656 +0.54861701590271,0.621473454509669,0.542351121614467,0.644383648608929 +2.47826601370958,2.97968215658335,1.94059407398725,3.14341802629572 +-0.599140916647551,-1.81456872016435,-2.76190733326404,-0.886219206900784 +-0.244342041853931,-0.448702713326526,-0.537045046380086,-0.535294015924552 +0.270809458146069,0.49730671702117,0.437959618894633,0.593277690983777 +2.6534894732648,4.06202864761973,2.38044875234785,4.59654020464499 +1.21160151370958,1.45673926500163,1.11512271266521,1.53678822927528 +23.1103924399316,56.5800741334215,17.8209369047534,25.9781879980362 +3.90292815811198,6.77545272858273,4.1584638889832,3.91439168162467 +-0.243571864641078,-0.499608141834362,-0.62167614040738,-0.615475606825472 +0.653304323441277,1.06147520721197,0.846756189970741,1.22210411533563 +0.345797173264803,0.529355039173874,0.465702430270659,0.599011462294818 +0.930411673264803,3.18482640756811,2.41563047092612,1.61171721467986 +-0.205065186290424,-0.24655508050623,-0.265755062691047,-0.260103475407846 +0.402928158111979,0.403845040295908,0.36861871657613,0.404111622482144 +0.753925094610201,1.36824670554121,1.03590693037895,1.62671101766615 +0.125993335358922,0.258434184321504,0.240052470519661,0.318369384125165 +3.90292815811198,8.74707186027217,5.36855379594562,3.91439168162467 +0.930411673264803,1.42429766877175,1.08030278830213,1.61171721467986 +-0.45138258409729,-0.511326272632766,-0.610583534874359,-0.530175966162011 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.673200246599499,-1.58450307845687,-3.34042579164813,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.420904215310721,-1.84045938985433,-3.88002907532231,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.459547789218049,-0.839507157588421,-1.76983648666221,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.626049742285362,-2.012435600104,-4.24258676049096,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.490841455916781,-0.852043520265558,-1.79626545975133,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.78716992183572,-3.76768501249731,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.759620977499219,-0.940013982450407,-1.98172347796589,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.626049742285362,-1.55882591290355,-3.28629357364431,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.463465905389799,-0.841112336906796,-1.77322050179492,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.463465905389799,-0.841112336906796,-1.77322050179492,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.574834401514413,-0.882870730357297,-1.86125492495028,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.759620977499219,-0.940013982450407,-1.98172347796589,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.648627614419656,-2.02854186394464,-4.27654174604565,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.420904215310721,-1.42561371325538,-3.00545759830478,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.14939060045931,-1.78716992183572,-3.76768501249731,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.459547789218049,-0.839507157588421,-1.76983648666221,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.20099540058636,-1.80491780771741,-3.8051008411899,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.459547789218049,-0.839507157588421,-1.76983648666221,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.395745764641078,-1.40598047418243,-2.96406709609335,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.86444375798835,-2.16396767603721,-4.56204442617263,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.574834401514413,-0.882870730357297,-1.86125492495028,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.490841455916781,-0.852043520265558,-1.79626545975133,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.889607560068417,-1.68705904247431,-3.55663274760104,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.648627614419656,-1.57130177122843,-3.31259499235912,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.395745764641078,-1.40598047418243,-2.96406709609335,-1 +-0.86444375798835,-2.16396767603721,-4.56204442617263,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.420904215310721,-1.84045938985433,-3.88002907532231,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.759620977499219,-0.940013982450407,-1.98172347796589,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.574834401514413,-1.9741589684238,-4.1618925356451,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.676064016647551,-1.5860171792761,-3.34361779644539,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.86444375798835,-0.967755764946288,-2.0402082906592,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.463465905389799,-1.8807843620373,-3.96504158110973,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.86444375798835,-0.967755764946288,-2.0402082906592,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.14939060045931,-1.78716992183572,-3.76768501249731,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.420904215310721,-1.84045938985433,-3.88002907532231,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.889607560068417,-1.68705904247431,-3.55663274760104,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.420904215310721,-1.84045938985433,-3.88002907532231,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.889607560068417,-1.68705904247431,-3.55663274760104,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.459547789218049,-1.87719507196534,-3.95747469323611,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.86444375798835,-0.967755764946288,-2.0402082906592,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.574834401514413,-0.882870730357297,-1.86125492495028,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.538185752645995,-1.9451125967047,-4.10065740738093,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.459547789218049,-1.45406905026088,-3.06544671598815,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.673200246599499,-1.58450307845687,-3.34042579164813,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.420904215310721,-1.42561371325538,-3.00545759830478,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.538185752645995,-1.9451125967047,-4.10065740738093,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.626049742285362,-2.012435600104,-4.24258676049096,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.630280269314285,-1.56118982651361,-3.29127714111076,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.395745764641078,-1.40598047418243,-2.96406709609335,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.395745764641078,-1.81511298720045,-3.82659416673698,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.463465905389799,-0.841112336906796,-1.77322050179492,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.420904215310721,-1.84045938985433,-3.88002907532231,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.492929478116561,-1.90704780573556,-4.02040978196713,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.463465905389799,-0.841112336906796,-1.77322050179492,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.574834401514413,-0.882870730357297,-1.86125492495028,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.14939060045931,-1.78716992183572,-3.76768501249731,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.420904215310721,-1.84045938985433,-3.88002907532231,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.889607560068417,-1.68705904247431,-3.55663274760104,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.574834401514413,-0.882870730357297,-1.86125492495028,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-2.25678401882814,-4.75771845771016,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-1.61767417928472,-3.41035661238887,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.530054121598813,-0.866906079406237,-1.82759848558033,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.86444375798835,-2.16396767603721,-4.56204442617263,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.673200246599499,-2.04558467829262,-4.31247115343165,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.726981311521292,-2.08126668576674,-4.38769543016856,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.20099540058636,-1.80491780771741,-3.8051008411899,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.92330948529022,-2.19628221125372,-4.63016944804856,-1 +-0.38976630767715,-1.40117246335719,-2.95393091927837,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.38976630767715,-1.80890587191561,-3.81350841873743,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.889607560068417,-2.17798385852388,-4.59159313334492,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-1.04183748786966,-1.74809738418168,-3.68531287053101,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.456463241853931,-1.87435267131424,-3.95148238651597,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-1.73090821758812,-3.64907492552053,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.534573376558723,-0.868563646821903,-1.83109294451952,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.20099540058636,-2.33013887018758,-4.91236406285611,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.420904215310721,-0.823078461108413,-1.73520175341927,-1 +-0.395745764641078,-1.40598047418243,-2.96406709609335,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.630280269314285,-0.901353366593738,-1.90021974339796,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.626049742285362,-0.899988560434626,-1.89734247937968,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.38976630767715,-0.808967298900367,-1.70545281141292,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.538185752645995,-0.86988079802457,-1.83386974306836,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.534573376558723,-1.94216735707889,-4.0944482970659,-1 +-0.456463241853931,-1.45186733618389,-3.06080509516166,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-1.20099540058636,-1.0420697821508,-2.19687599495466,-1 +-0.92330948529022,-0.982207264427374,-2.07067472663585,-1 +-0.92330948529022,-1.70123288555145,-3.58651383248209,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.337920672071078,-1.75173466071087,-3.69298092273909,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.726981311521292,-0.930770757736024,-1.96223704928442,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.85138258409729,-1.6704700702599,-3.52166012344187,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-0.676064016647551,-0.915687445394429,-1.93043863484497,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-1.47719287840705,-3.11419602609762,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.395745764641078,-0.811743205244581,-1.71130493582561,-1 +-0.630280269314285,-2.01548739945189,-4.24902051842504,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.492929478116561,-0.852857705993306,-1.79798191397672,-1 +-1.14939060045931,-2.30722644803752,-4.86406043571912,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.788398486290424,-1.64183091222219,-3.46128347699607,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.620757150983516,-0.898271021693848,-1.89372158978605,-1 +-0.85138258409729,-2.15656758748485,-4.5464436696977,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.85138258409729,-0.964446344737769,-2.03323142026353,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.337920672071078,-1.3568878335815,-2.86057072232604,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.676064016647551,-2.04753937404507,-4.31659201390525,-1 +-0.7381340288809,-0.933964622871142,-1.96897030819533,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-1.14939060045931,-1.03182303545946,-2.17527395618704,-1 +-0.534573376558723,-1.50439636590285,-3.17154601328871,-1 +-0.7381340288809,-2.08840838531983,-4.40275145480347,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.889607560068417,-0.974023992311335,-2.0534228742361,-1 +-0.456463241853931,-0.838235997373393,-1.76715664562856,-1 +-0.577279726735197,-1.97604541203633,-4.1658695079738,-1 +-1.04183748786966,-1.00926449532698,-2.12771637784907,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.337920672071078,-0.783399555978409,-1.6515512765709,-1 +-0.788398486290424,-2.11959459344169,-4.46849775430289,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-1.53063819443325,-3.22686864537116,-1 +-0.788398486290424,-0.947911519135329,-1.99837294718528,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.577279726735197,-0.883714373587962,-1.8630334810446,-1 +-0.997071441888021,-0.999340325367039,-2.10679439054239,-1 +-0.673200246599499,-0.914813278878867,-1.92859573001602,-1 +-0.997071441888021,-2.23459290017746,-4.71093547186803,-1 diff --git a/shared/package-files/79/79eb9ea7db7e5c4e60f73f2e70d78cf311be84c2df404362a64ceba527e96d55/blob b/shared/package-files/79/79eb9ea7db7e5c4e60f73f2e70d78cf311be84c2df404362a64ceba527e96d55/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d1646d329975a1ed4d5932ad221bce6cd75131b --- /dev/null +++ b/shared/package-files/79/79eb9ea7db7e5c4e60f73f2e70d78cf311be84c2df404362a64ceba527e96d55/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor fill(const at::Tensor & self, const at::Scalar & value); +TORCH_API at::Tensor & fill_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & value); +TORCH_API at::Tensor & fill_outf(const at::Tensor & self, const at::Scalar & value, at::Tensor & out); +TORCH_API at::Tensor fill(const at::Tensor & self, const at::Tensor & value); +TORCH_API at::Tensor & fill_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & value); +TORCH_API at::Tensor & fill_outf(const at::Tensor & self, const at::Tensor & value, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/79/79ebef3b4a74b16da5418cf2c551948047bbc8b0ec9e26be4e7aaad226e0c14e/blob b/shared/package-files/79/79ebef3b4a74b16da5418cf2c551948047bbc8b0ec9e26be4e7aaad226e0c14e/blob new file mode 100644 index 0000000000000000000000000000000000000000..f34c112ed0122cdb5832d9a97b9963c1fdae747c --- /dev/null +++ b/shared/package-files/79/79ebef3b4a74b16da5418cf2c551948047bbc8b0ec9e26be4e7aaad226e0c14e/blob @@ -0,0 +1,65 @@ +from typing import Any, List, Optional + +class Rule: + id: Any + prefix: Any + status: Any + expiration: Any + transition: Any + def __init__( + self, + id: Optional[Any] = ..., + prefix: Optional[Any] = ..., + status: Optional[Any] = ..., + expiration: Optional[Any] = ..., + transition: Optional[Any] = ..., + ) -> None: ... + def startElement(self, name, attrs, connection): ... + def endElement(self, name, value, connection): ... + def to_xml(self): ... + +class Expiration: + days: Any + date: Any + def __init__(self, days: Optional[Any] = ..., date: Optional[Any] = ...) -> None: ... + def startElement(self, name, attrs, connection): ... + def endElement(self, name, value, connection): ... + def to_xml(self): ... + +class Transition: + days: Any + date: Any + storage_class: Any + def __init__(self, days: Optional[Any] = ..., date: Optional[Any] = ..., storage_class: Optional[Any] = ...) -> None: ... + def to_xml(self): ... + +class Transitions(List[Transition]): + transition_properties: int + current_transition_property: int + temp_days: Any + temp_date: Any + temp_storage_class: Any + def __init__(self) -> None: ... + def startElement(self, name, attrs, connection): ... + def endElement(self, name, value, connection): ... + def to_xml(self): ... + def add_transition(self, days: Optional[Any] = ..., date: Optional[Any] = ..., storage_class: Optional[Any] = ...): ... + @property + def days(self): ... + @property + def date(self): ... + @property + def storage_class(self): ... + +class Lifecycle(List[Rule]): + def startElement(self, name, attrs, connection): ... + def endElement(self, name, value, connection): ... + def to_xml(self): ... + def add_rule( + self, + id: Optional[Any] = ..., + prefix: str = ..., + status: str = ..., + expiration: Optional[Any] = ..., + transition: Optional[Any] = ..., + ): ... diff --git a/shared/package-files/79/79edbece9a7374e4d37c6a918a41dd28367404578277cfb250faef881161dfa0/blob b/shared/package-files/79/79edbece9a7374e4d37c6a918a41dd28367404578277cfb250faef881161dfa0/blob new file mode 100644 index 0000000000000000000000000000000000000000..a7170ea2a17eb0fe03c890a1fb0f278a46ef9c38 --- /dev/null +++ b/shared/package-files/79/79edbece9a7374e4d37c6a918a41dd28367404578277cfb250faef881161dfa0/blob @@ -0,0 +1,1060 @@ +import dataclasses +import functools +import inspect +import logging +import re +import time +import warnings +from contextlib import contextmanager, nullcontext +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +import torch +import torch._dynamo +import torch.fx + +import torch.utils._pytree as pytree +from torch._dynamo.exc import UserError, UserErrorType +from torch._export.non_strict_utils import ( + make_constraints, + make_fake_inputs, + make_fake_params_buffers, +) +from torch._export.passes.add_runtime_assertions_for_constraints_pass import ( + _AddRuntimeAssertionsForInlineConstraintsPass, +) +from torch._export.passes.collect_tracepoints_pass import CollectTracepointsPass +from torch._export.passes.lift_constants_pass import ( + ConstantAttrMap, + lift_constants_pass, + rewrite_script_object_meta, +) +from torch._export.wrappers import _wrap_submodules +from torch._functorch.aot_autograd import aot_export_module +from torch._guards import detect_fake_mode +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch._utils_internal import log_export_usage +from torch.export.exported_program import OutputKind +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + free_unbacked_symbols, + GuardOnDataDependentSymNode, + ShapeEnv, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo +from torch.utils._sympy.value_ranges import ValueRangeError + +from ._safeguard import AutogradStateOpsFailSafeguard + +from .dynamic_shapes import _process_constraints, Constraint +from .exported_program import ( + _disable_prexisiting_fake_mode, + ExportedProgram, + InputKind, + ModuleCallEntry, + ModuleCallSignature, +) +from .graph_signature import ( + _sig_to_specs, + ArgumentSpec, + ConstantArgument, + CustomObjArgument, + ExportGraphSignature, + SymIntArgument, + TensorArgument, +) + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass +class ExportDynamoConfig: + """ + Manage Export-specific configurations of Dynamo. + """ + + allow_rnn: bool = True + reorderable_logging_functions: Set[Callable] = dataclasses.field( + default_factory=set + ) + + +DEFAULT_EXPORT_DYNAMO_CONFIG = ExportDynamoConfig() +DEFAULT_EXPORT_DYNAMO_CONFIG.reorderable_logging_functions = { + logging.critical, + logging.debug, + logging.error, + logging.exception, + logging.info, + logging.log, + logging.warning, + print, + warnings.warn, +} + + +@contextmanager +def _ignore_backend_decomps(): + orig_mkldnn_flag = torch.backends.mkldnn.set_flags(False) + orig_nnpack_flag = torch.backends.nnpack.set_flags(False) + try: + yield + finally: + torch.backends.mkldnn.set_flags(*orig_mkldnn_flag) + torch.backends.nnpack.set_flags(*orig_nnpack_flag) + + +def _convert_input_to_fake(gm, args, kwargs): + params_buffers = _get_params_buffers(gm) + fake_inps: List[torch.Tensor] = [] + for node in gm.graph.nodes: + if node.op == "placeholder" and "val" in node.meta: + fake_val = node.meta["val"] + if fake_val is not None and isinstance(fake_val, torch.Tensor): + fake_inps.append(fake_val) + + if detected_fake_mode := detect_fake_mode(fake_inps): + fake_mode = detected_fake_mode + else: + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + + if len(args) == 0 and len(kwargs) == 0: + return (), {}, params_buffers, fake_mode + + count = 0 + + def convert_to_fake(x): + nonlocal count + val = fake_inps[count] + count += 1 + return val + + fake_args = pytree.tree_map_only(torch.Tensor, convert_to_fake, args) + # TODO properly use the cached fake tensor + fake_kwargs = pytree.tree_map_only(torch.Tensor, fake_mode.from_tensor, kwargs) + fake_params_buffers = pytree.tree_map_only( + torch.Tensor, + functools.partial(fake_mode.from_tensor, static_shapes=True), + params_buffers, + ) + return fake_args, fake_kwargs, fake_params_buffers, fake_mode + + +def _replace_param_buffer_names(param_buffer_table, sig): + for spec in sig.input_specs: + if spec.kind in ( + InputKind.PARAMETER, + InputKind.BUFFER, + ): + spec.target = param_buffer_table[spec.target] + for spec in sig.output_specs: + if spec.kind in ( + OutputKind.BUFFER_MUTATION, + OutputKind.GRADIENT_TO_PARAMETER, + ): + spec.target = param_buffer_table[spec.target] + + +def _convert_to_positional_args(orig_arg_names, args, kwargs): + assert len(orig_arg_names) == len(args) + len(kwargs), ( + f"Total number of arg names is expected to be {len(orig_arg_names)} " + f"but got {len(args)} positional args, {len(kwargs)} kwargs." + ) + reordered_kwargs = [kwargs[kw_name] for kw_name in orig_arg_names[len(args) :]] + return ( + *args, + *reordered_kwargs, + ) + + +def _normalize_nn_module_stack(gm_torch_level, root_cls): + # Append a root module to every nn_module_stack. + root = "L['self']" + root_key = re.sub(r"[^a-zA-Z0-9]", "_", root) + for gm in gm_torch_level.modules(): + if not isinstance(gm, torch.fx.GraphModule): + continue + for node in gm.graph.nodes: + if node.op in ["placeholder", "output"]: + continue + add_root = True + if nn_module_stack := node.meta.get("nn_module_stack", {}): + path, ty = next(iter(nn_module_stack.values())) + # After deserializing the class `ty` might not exist anymore so + # it could be a string + if inspect.isclass(ty) and issubclass(ty, torch.nn.Module): + # TODO Figure out why sometimes we have root sometimes we don't. + if path == root and ty is root_cls: + add_root = False + else: + assert isinstance(ty, str) + if add_root: + + def normalize_path(path): + try: + parts = [] + + class Path: + def __getattr__(self, name): + parts.append(name) + return self + + def __getitem__(self, idx): + parts.append(str(idx)) + return self + + eval(path, {"L": {"self": Path()}}) + return ".".join(parts) + except Exception: # TODO(zhxchen17) Remove this. + return path + + nn_module_stack = {root_key: (root, root_cls), **nn_module_stack} + node.meta["nn_module_stack"] = { + key: (normalize_path(path), ty) + for key, (path, ty) in nn_module_stack.items() + } + + +def _get_param_buffer_mapping( + original_module: torch.nn.Module, + traced_module: torch.nn.Module, +) -> Dict[str, str]: + """ + Returns a mapping of parameter/buffer names from the new module to the + original model. This is to help with restoring the FQN for parameter/buffers + of a traced module to what the original module contains. + """ + + param_lookup: Dict[int, List[str]] = {} + buffer_lookup: Dict[int, List[str]] = {} + for name, param in original_module.named_parameters(remove_duplicate=False): + param_lookup.setdefault(id(param), []).append(name) + for name, buffer in original_module.named_buffers(remove_duplicate=False): + buffer_lookup.setdefault(id(buffer), []).append(name) + + param_buffer_table: Dict[str, str] = {} + for dynamo_name, dynamo_param in traced_module.named_parameters( + remove_duplicate=False + ): + assert dynamo_name not in param_buffer_table + if id(dynamo_param) in param_lookup: + param_buffer_table[dynamo_name] = param_lookup[id(dynamo_param)].pop() + + for dynamo_name, dynamo_buffer in traced_module.named_buffers( + remove_duplicate=False + ): + assert dynamo_name not in param_buffer_table + if id(dynamo_buffer) in buffer_lookup: + param_buffer_table[dynamo_name] = buffer_lookup[id(dynamo_buffer)].pop() + + return param_buffer_table + + +def _remap_constants( + orig_constant_attrs: ConstantAttrMap, + graph_signature: ExportGraphSignature, + constants: Dict[str, Union[torch.Tensor, torch.ScriptObject]], +) -> None: + """Rewrite the graph signature and constants table to use the FQN from the original module.""" + remap_table: Dict[str, str] = {} + for name, value in constants.items(): + if value in orig_constant_attrs: + remap_table[name] = orig_constant_attrs[value] + + for spec in graph_signature.input_specs: + if spec.kind in ( + InputKind.CONSTANT_TENSOR, + InputKind.CUSTOM_OBJ, + ): + orig_target = spec.target + assert orig_target is not None + spec.target = remap_table.get(orig_target, orig_target) + + constant = constants[orig_target] + del constants[orig_target] + constants[spec.target] = constant + + +def _restore_state_dict( + original_module: torch.nn.Module, traced_module: torch.fx.GraphModule +) -> None: + """ + Restores the state dict of the traced module to that of the original module. + """ + param_buffer_table = _get_param_buffer_mapping(original_module, traced_module) + # Since the graph module is flattened (no module heirarchy), we + # need to noramlize the module by replacing "." with "_". If we + # don't, it will try to save the weight to a submodule which no + # longer exists. + for name, fqn in param_buffer_table.items(): + param_buffer_table[name] = fqn.replace(".", "_") + + # Replace state dict attr names with the fqn + for name, fqn in param_buffer_table.items(): + if not hasattr(traced_module, name): + continue + + attr = getattr(traced_module, name) + if isinstance(attr, torch.Tensor) and not isinstance(attr, torch.nn.Parameter): + traced_module.register_buffer(fqn, attr) + else: + setattr(traced_module, fqn, attr) + delattr(traced_module, name) + + # Replace graph getattr nodes with the correct name + for node in traced_module.graph.nodes: + if node.op == "get_attr": + attr_name = node.target + if attr_name in param_buffer_table: + node.target = param_buffer_table[attr_name] + + traced_module.recompile() + + +def _export_to_torch_ir( + f: Callable, + args: Tuple[Any, ...], + kwargs: Optional[Dict[str, Any]] = None, + constraints: Optional[List[Constraint]] = None, + *, + preserve_module_call_signature: Tuple[str, ...] = (), + disable_constraint_solver: bool = False, + restore_fqn: bool = True, + _log_export_usage: bool = True, +) -> torch.fx.GraphModule: + """ + Traces either an nn.Module's forward function or just a callable with PyTorch + operations inside and produce a torch.fx.GraphModule in torch IR. + """ + + if _log_export_usage: + log_export_usage(event="export.private_api", flags={"_export_to_torch_ir"}) + + kwargs = kwargs or {} + + if not isinstance(args, tuple): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expecting `args` to be a tuple of example positional inputs, got {type(args)}", + ) + + with torch._dynamo.config.patch(dataclasses.asdict(DEFAULT_EXPORT_DYNAMO_CONFIG)): + try: + module_call_specs: Dict[str, Dict[str, pytree.TreeSpec]] = {} + with _wrap_submodules( + f, preserve_module_call_signature, module_call_specs + ), _ignore_backend_decomps(): + gm_torch_level, _ = torch._dynamo.export( + f, + constraints=constraints, # type: ignore[arg-type] + assume_static_by_default=True, + tracing_mode="symbolic", + disable_constraint_solver=disable_constraint_solver, + _log_export_usage=_log_export_usage, + )( + *args, + **kwargs, + ) + except (ConstraintViolationError, ValueRangeError) as e: + raise UserError(UserErrorType.CONSTRAINT_VIOLATION, str(e)) # noqa: TRY200 + except GuardOnDataDependentSymNode as e: + raise UserError( # noqa: TRY200 + UserErrorType.ANTI_PATTERN, + f"Consider annotating your code using torch._constrain_as_*(). {str(e)}", + case_name="constrain_as_size_example", + ) + + gm_torch_level.meta["module_call_specs"] = module_call_specs + + if isinstance(f, torch.nn.Module) and restore_fqn: + _restore_state_dict(f, gm_torch_level) + + return gm_torch_level + + +def _gather_constant_attrs(m: torch.nn.Module) -> ConstantAttrMap: + """Search the module hierarchy, gathering up all tensor and ScriptObject constants. + + Returns a dictionary mapping hash(value) to the name of the constant. We + have to abuse `hash` here unfortunately, see: [ScriptObject hash]. + """ + constants = ConstantAttrMap() + buffers_parameters = set(m.buffers()) + buffers_parameters.update(m.parameters()) + + def inner(m: torch.nn.Module, prefix_atoms: List[str], constants): + for k, v in m.__dict__.items(): + if isinstance(v, (torch.Tensor, torch.ScriptObject)): + if v in buffers_parameters: + # filter out buffers and parameters, leaving only constants + continue + + fqn = ".".join(prefix_atoms + [k]) + if v in constants: + raise ValueError( + f"Duplicate reference to constant attribute found: '{constants[v]}' and '{fqn}'." + ) + + constants[v] = fqn + for k, v in m.named_children(): + inner(v, prefix_atoms + [k], constants) + + inner(m, [], constants) + return constants + + +def _export_non_strict( + mod: torch.nn.Module, + fake_args, + fake_kwargs, + fake_params_buffers, + constant_attrs: ConstantAttrMap, + *, + transform=lambda x: x, # TODO(zhxchen17) Revisit if this is needed later. + pre_dispatch=False, +): + # [NOTE] If the user is exporting under training mode, we want to detect if there is any + # state change in the autograd global state and error. If the user is exporting under inference + # mode, we don't care. + is_grad_enabled = torch._C.is_grad_enabled() + grad_safe_guard = ( + AutogradStateOpsFailSafeguard() if is_grad_enabled else nullcontext() + ) + + @contextmanager + def _compiling_state_context(): + old_value = torch.compiler._is_compiling_flag + try: + torch.compiler._is_compiling_flag = True + yield + finally: + torch.compiler._is_compiling_flag = old_value + + # This _reparametrize_module makes sure inputs and module.params/buffers have the same fake_mode, + # otherwise aot_export_module will error out because it sees a mix of fake_modes. + # And we want aot_export_module to use the fake_tensor mode in dynamo to keep the pipeline easy to reason about. + with torch.nn.utils.stateless._reparametrize_module( + mod, fake_params_buffers + ), grad_safe_guard, _ignore_backend_decomps(), _compiling_state_context(): # type: ignore[attr-defined] + gm, graph_signature = transform(aot_export_module)( + mod, + fake_args, + trace_joint=False, + pre_dispatch=pre_dispatch, + kwargs=fake_kwargs, + ) + # TODO unfortunately preserving graph-level metadata is not + # working well with aot_export. So we manually copy it. + # (The node-level meta is addressed above.) + if isinstance(mod, torch.fx.GraphModule) and hasattr(mod, "meta"): + gm.meta.update(mod.meta) + + if pre_dispatch: + from torch._export.passes.replace_set_grad_with_hop_pass import ( + replace_set_grad_with_hop_pass, + ) + + gm = replace_set_grad_with_hop_pass(gm) + + # NOTE: aot_export adds symint metadata for placeholders with int values; + # since these become specialized, we replace such metadata with the original values + flat_args = pytree.tree_leaves((fake_args, fake_kwargs)) + index = 0 + total_non_user_inputs = ( + len(graph_signature.parameters) + + len(graph_signature.buffers) + + len(graph_signature.input_tokens) + ) + for node in gm.graph.nodes: + if node.op == "placeholder": + if index >= total_non_user_inputs: + user_arg = flat_args[index - total_non_user_inputs] + if not isinstance(user_arg, torch.Tensor): + node.meta["val"] = user_arg + index += 1 + + is_joint = graph_signature.backward_signature is not None + + def make_argument_spec(node) -> ArgumentSpec: + if isinstance(node, (int, bool, float, type(None))): + # For const outputs we just directly return this + return ConstantArgument(value=node) + + assert ( + "val" in node.meta + ), f"{node} is not a constant or a node with a 'val' metadata field" + val = node.meta["val"] + if isinstance(val, FakeTensor): + return TensorArgument(name=node.name) + elif isinstance(val, torch.SymInt): + return SymIntArgument(name=node.name) + elif isinstance(val, torch.ScriptObject): + return CustomObjArgument( + name=node.name, class_fqn=val._type().qualified_name() # type: ignore[attr-defined] + ) + else: + # TODO: this branch is likely wrong, all permissible ConstantArgument type + # should have been handled already + return ConstantArgument(value=val) + + input_specs, output_specs = _sig_to_specs( + user_inputs=set(graph_signature.user_inputs), + inputs_to_parameters=graph_signature.inputs_to_parameters, # type: ignore[arg-type] + inputs_to_buffers=graph_signature.inputs_to_buffers, # type: ignore[arg-type] + user_outputs=set(graph_signature.user_outputs), # type: ignore[arg-type] + buffer_mutations=graph_signature.buffers_to_mutate, # type: ignore[arg-type] + user_input_mutations=graph_signature.user_inputs_to_mutate, # type: ignore[arg-type] + grad_params=graph_signature.backward_signature.gradients_to_parameters if is_joint else {}, # type: ignore[arg-type, union-attr] + grad_user_inputs=graph_signature.backward_signature.gradients_to_user_inputs if is_joint else {}, # type: ignore[arg-type, union-attr] + loss_output=graph_signature.backward_signature.loss_output if is_joint else None, # type: ignore[arg-type, union-attr] + inputs=[ + make_argument_spec(node) + for node in gm.graph.nodes + if node.op == "placeholder" + ], + outputs=[ + make_argument_spec(node) + for node in pytree.tree_leaves(next(iter(reversed(gm.graph.nodes))).args) + ], + input_tokens=graph_signature.input_tokens, + output_tokens=graph_signature.output_tokens, + ) + export_graph_signature = ExportGraphSignature( + input_specs=input_specs, output_specs=output_specs + ) + + constants = rewrite_script_object_meta(gm) + constants.update(lift_constants_pass(gm, export_graph_signature, constant_attrs)) + + @dataclasses.dataclass + class _ExportedProgramNonStrict: + gm: torch.fx.GraphModule + sig: ExportGraphSignature + constants: Dict[str, Union[torch.Tensor, torch._C.ScriptObject]] + + return _ExportedProgramNonStrict( + gm, + export_graph_signature, + constants, + ) + + +def _get_params_buffers(mod: torch.nn.Module) -> Dict[str, torch.Tensor]: + params_buffers: Dict[str, torch.Tensor] = {} + for name, param in mod.named_parameters(remove_duplicate=False): + params_buffers[name] = param + + for name, buffer in mod.named_buffers(remove_duplicate=False): + params_buffers[name] = buffer + return params_buffers + + +def _rewrite_dynamo_tensor_constants( + orig_mod_buffers: Set[torch.Tensor], + traced_mod_buffers: Dict[str, torch.Tensor], + graph_signature: ExportGraphSignature, + constants: Dict[str, Union[torch.Tensor, torch.ScriptObject]], +): + """Dynamo erroneously marks tensor attributes on modules as a buffers. + + Rewrite them to be tensor constants. + """ + for spec in graph_signature.input_specs: + if spec.kind == InputKind.BUFFER: + assert spec.target is not None + value = traced_mod_buffers[spec.target] + if value not in orig_mod_buffers: + # This was a tensor constant erroneously marked as a buffer. + # Convert it int oa constant in the graph signature, and add its + # value to the constants table. + spec.kind = InputKind.CONSTANT_TENSOR + constants[spec.target] = value + + +def _rewrite_non_persistent_buffers( + orig_mod: torch.nn.Module, + graph_signature: ExportGraphSignature, + constants: Dict[str, Union[torch.Tensor, torch.ScriptObject]], +): + """Dynamo erroneously drops the persistent flag on buffers. + + Rewrite non-persistent buffers to reflect the original module. + """ + state_dict = orig_mod.state_dict() + for spec in graph_signature.input_specs: + if spec.kind == InputKind.BUFFER: + assert spec.target is not None + if spec.target not in state_dict: + assert spec.target not in constants + spec.persistent = False + constants[spec.target] = orig_mod.get_buffer(spec.target) + + +def get_ep_stats(ep: ExportedProgram) -> Dict[str, Any]: + op_count = 0 + op_set = set() + for m in ep.graph_module.modules(): + if not isinstance(m, torch.fx.GraphModule): + continue + for node in m.graph.nodes: + if node.op != "call_function": + continue + op_count += 1 + assert hasattr(node.target, "__module__") + assert hasattr(node.target, "__name__") + op_set.add(f"{node.target.__module__}.{node.target.__name__}") + return {"op_count": op_count, "op_set": op_set} + + +_EXPORT_FLAGS: Optional[Set[str]] = None + + +def _log_export_wrapper(fn): + @functools.wraps(fn) + def wrapper(*args, **kwargs): + global _EXPORT_FLAGS + try: + start = time.time() + ep = fn(*args, **kwargs) + end = time.time() + log_export_usage( + event="export.time", + metrics=end - start, + flags=_EXPORT_FLAGS, + **get_ep_stats(ep), + ) + except Exception as e: + t = type(e) + error_type = t.__module__ + "." + t.__qualname__ + log_export_usage( + event="export.error", + type=error_type, + message=str(e), + flags=_EXPORT_FLAGS, + ) + raise e + finally: + _EXPORT_FLAGS = None + + return ep + + return wrapper + + +@_log_export_wrapper +@_disable_prexisiting_fake_mode +def _export( + mod: torch.nn.Module, + args: Tuple[Any, ...], + kwargs: Optional[Dict[str, Any]] = None, + dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any], List[Any]]] = None, + *, + strict: bool = True, + preserve_module_call_signature: Tuple[str, ...] = (), + pre_dispatch: bool = False, +) -> ExportedProgram: + """ + Traces either an nn.Module's forward function or just a callable with PyTorch + operations inside and produce a ExportedProgram. + + Args: + f: the `nn.Module` to trace. + + args: example positional inputs. + + kwargs: optional example keyword inputs. + + dynamic_shapes: + An optional argument where the type should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + preserve_module_call_signature: A list of submodule paths for which the original + calling conventions are preserved as metadata. + + Returns: + An ExportedProgram containing the traced method. + """ + from .dynamic_shapes import _process_dynamic_shapes + + global _EXPORT_FLAGS + flags = set() + flags.add("strict" if strict else "non_strict") + flags.add("pre_dispatch" if pre_dispatch else "aot_dispatch") + log_export_usage(event="export.enter", flags=flags) + _EXPORT_FLAGS = flags + + constraints = _process_dynamic_shapes(mod, args, kwargs, dynamic_shapes) or [] + + kwargs = kwargs or {} + + constant_attrs = _gather_constant_attrs(mod) + + flat_args, orig_in_spec = pytree.tree_flatten((args, kwargs)) + + if not strict: + out_spec = None + + module_call_specs: Dict[str, Dict[str, pytree.TreeSpec]] = {} + + def strip_root(x): + if isinstance(x, str) and x.startswith("_export_root"): + stripped = x[len("_export_root") :] + return stripped[1:] if stripped.startswith(".") else stripped + return x + + def fixup_key(x): + return "L__self__" + strip_root(x) + + def _tuplify_outputs(aot_export): + def _aot_export_non_strict(mod, args, kwargs=None, **flags): + kwargs = kwargs or {} + + class Wrapper(torch.nn.Module): + def __init__(self, mod): + super().__init__() + self._export_root = mod + + def forward(self, *args, **kwargs): + nonlocal out_spec + if isinstance(self._export_root, torch.fx.GraphModule): + with torch.fx.traceback.preserve_node_meta(): + tree_out = torch.fx.Interpreter(self._export_root).run( + *args, **kwargs + ) + else: + tree_out = self._export_root(*args, **kwargs) + flat_outs, out_spec = pytree.tree_flatten(tree_out) + return tuple(flat_outs) + + wrapped_mod = Wrapper(mod) + # Patch export_root to the signatures so that wrapper module correctly populates the + # in/out spec + new_preserved_call_signatures = [ + "_export_root." + i for i in preserve_module_call_signature + ] + with _wrap_submodules( + wrapped_mod, new_preserved_call_signatures, module_call_specs + ): + gm, sig = aot_export(wrapped_mod, args, kwargs=kwargs, **flags) + + sig.parameters = pytree.tree_map(strip_root, sig.parameters) + sig.buffers = pytree.tree_map(strip_root, sig.buffers) + sig.inputs_to_buffers = pytree.tree_map( + strip_root, sig.inputs_to_buffers + ) + sig.inputs_to_parameters = pytree.tree_map( + strip_root, sig.inputs_to_parameters + ) + sig.buffers_to_mutate = pytree.tree_map( + strip_root, sig.buffers_to_mutate + ) + for node in gm.graph.nodes: + if "nn_module_stack" in node.meta: + nn_module_stack = node.meta["nn_module_stack"] + node.meta["nn_module_stack"] = { + fixup_key(key): val + for key, val in pytree.tree_map( + strip_root, nn_module_stack + ).items() + } + + return gm, sig + + return _aot_export_non_strict + + ( + fake_mode, + fake_args, + fake_kwargs, + equalities_inputs, + original_signature, + ) = make_fake_inputs(mod, args, kwargs, constraints) + + fake_params_buffers = make_fake_params_buffers( + fake_mode, _get_params_buffers(mod) + ) + with fake_mode: + ep_non_strict = _export_non_strict( + mod, + fake_args, + fake_kwargs, + fake_params_buffers, + constant_attrs, + pre_dispatch=pre_dispatch, + transform=_tuplify_outputs, + ) + try: + range_constraints = make_constraints( + fake_mode, + equalities_inputs, + original_signature, + ep_non_strict.gm, + ) + except (ConstraintViolationError, ValueRangeError) as e: + raise UserError(UserErrorType.CONSTRAINT_VIOLATION, str(e)) # noqa: TRY200 + + assert out_spec is not None + + gm = ep_non_strict.gm + + module_call_signatures = { + strip_root(fqn): ModuleCallSignature(inputs=[], outputs=[], **specs) + for fqn, specs in module_call_specs.items() + } + + if len(preserve_module_call_signature) > 0: + for node in gm.graph.nodes: + if node.target == torch.ops.higher_order._export_tracepoint: + if "path" in node.kwargs: + path = strip_root(node.kwargs["path"]) + with gm.graph.inserting_before(node): + new_node = gm.graph.create_node( + "call_function", + torch.ops.higher_order._export_tracepoint, + args=node.args, + kwargs={ + "path": path, + "kind": node.kwargs["kind"], + }, + ) + node.replace_all_uses_with(new_node) + gm.graph.erase_node(node) + + res = CollectTracepointsPass(module_call_signatures, ep_non_strict.sig)(gm) + assert res is not None + gm = res.graph_module + + _rewrite_non_persistent_buffers(mod, ep_non_strict.sig, ep_non_strict.constants) + return ExportedProgram( + root=gm, + graph=gm.graph, + graph_signature=ep_non_strict.sig, + state_dict=mod.state_dict(keep_vars=True), + range_constraints=range_constraints, + module_call_graph=[ + ModuleCallEntry( + "", + ModuleCallSignature( + inputs=[], outputs=[], in_spec=orig_in_spec, out_spec=out_spec + ), + ) + ] + + [ + ModuleCallEntry(fqn, sig) for fqn, sig in module_call_signatures.items() + ], + example_inputs=(args, kwargs), + constants=ep_non_strict.constants, + ) + + gm_torch_level = _export_to_torch_ir( + mod, + args, + kwargs, + constraints, + preserve_module_call_signature=preserve_module_call_signature, + restore_fqn=False, # don't need to restore because we will do it later + _log_export_usage=False, + ) + + # We detect the fake_mode by looking at gm_torch_level's placeholders, this is the fake_mode created in dynamo. + ( + fake_args, + fake_kwargs, + fake_params_buffers, + dynamo_fake_mode, + ) = _convert_input_to_fake(gm_torch_level, args, kwargs) + + # First, we want to pass through the graph to try populating + # val field for getattr if there is anything missing. + # This can happen when quantization adds extra params and forgets + # to update "val" + for node in gm_torch_level.graph.nodes: + if node.op == "get_attr" and "val" not in node.meta: + attr = getattr(gm_torch_level, node.target) + # Checks if it is not a HigherOrderOp branch or a module + if not isinstance(attr, torch.nn.Module): + assert ( + dynamo_fake_mode is not None + ), "Cannot find dynamo_fake_mode. This could be due to the exported graph module have no placeholders." + node.meta["val"] = dynamo_fake_mode.from_tensor( + attr, static_shapes=True + ) + + # When aot_export lifts the params, we lose the nn_module_stack + # and source_fn from the param nodes as they are treated as fresh inputs + # Therefore, we manually extract them before calling into aot_export + params_buffers_to_node_meta = {} + for node in gm_torch_level.graph.nodes: + target = node.target + meta = node.meta + if node.op == "call_module": + submodule = getattr(gm_torch_level, target) + if isinstance(submodule, torch.nn.Module): + for name, _ in submodule.named_parameters( + recurse=True, remove_duplicate=False + ): + params_buffers_to_node_meta[target + "." + name] = meta + + for name, _ in submodule.named_buffers( + recurse=True, remove_duplicate=False + ): + params_buffers_to_node_meta[target + "." + name] = meta + + if node.op == "get_attr": + submodule = getattr(gm_torch_level, target) + if not isinstance(submodule, torch.fx.GraphModule): + params_buffers_to_node_meta[target] = meta + + # If the call_function uses param as input, we also need to update params' meta + # with this call_function node's meta. + # This is basically the same flow as torch.fx.traceback.preserve_meta() + if node.op == "call_function" and not isinstance( + node.target, torch._ops.HigherOrderOperator + ): + for arg in node._input_nodes: + if arg.op == "get_attr": + for entry in torch.fx.proxy._COPY_META_FIELDS: + if entry in meta: + params_buffers_to_node_meta[arg.target][entry] = meta[entry] + + # Fix the graph output signature to be tuple if scalar + out_spec = orig_out_spec = gm_torch_level._out_spec + assert out_spec is not None + # aot_export expect the return type to always be a tuple. + if out_spec.type not in (list, tuple): + out_spec = pytree.TreeSpec(tuple, None, [out_spec]) + + orig_arg_names = gm_torch_level.graph._codegen.pytree_info.orig_args # type: ignore[attr-defined] + + gm_torch_level.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + orig_arg_names, + gm_torch_level._in_spec, + out_spec, + ) + ) + gm_torch_level.recompile() + + _normalize_nn_module_stack(gm_torch_level, type(mod)) + + # NOTE: graph module expects only positional args + ep_non_strict = _export_non_strict( + gm_torch_level, + _convert_to_positional_args(orig_arg_names, fake_args, fake_kwargs), + {}, + fake_params_buffers, + constant_attrs, + pre_dispatch=pre_dispatch, + ) + + gm = ep_non_strict.gm + export_graph_signature = ep_non_strict.sig + constants = ep_non_strict.constants + + # After aot_export, set the param/buffer metadata back into placeholders + # Technically, users can still construct this data from param names + # without relying on this metadata + for node in gm.graph.nodes: + if node.op == "placeholder": + if node.target in export_graph_signature.inputs_to_parameters: + param_name = export_graph_signature.inputs_to_parameters[node.target] + if param_name in params_buffers_to_node_meta: + for k, v in params_buffers_to_node_meta[param_name].items(): + node.meta[k] = v + if node.target in export_graph_signature.inputs_to_buffers: + buffer_name = export_graph_signature.inputs_to_buffers[node.target] + if buffer_name in params_buffers_to_node_meta: + for k, v in params_buffers_to_node_meta[buffer_name].items(): + node.meta[k] = v + + # The unbacked symint symbols are updated in aot_export + # so we serialize them here instead of inside dynamo + + gm.meta["inline_constraints"] = { + k: v + for k, v in dynamo_fake_mode.shape_env.var_to_range.items() + if free_unbacked_symbols(k) + } + + num_lifted = next( + ( + i + for i, s in enumerate(export_graph_signature.input_specs) + if s.kind == InputKind.USER_INPUT + ), + len(export_graph_signature.input_specs), + ) + range_constraints = _process_constraints( + dynamo_fake_mode, + gm, + num_lifted, + flat_args, + ) + + # Do some cleanups on the graph module to restore the state dict to the + # expected form. Each of these steps should probably get fixed upstream. + # 1. Remove tensor constants that were added as buffers. + _rewrite_dynamo_tensor_constants( + orig_mod_buffers=set(mod.buffers()), + traced_mod_buffers=dict(gm_torch_level.named_buffers()), + graph_signature=ep_non_strict.sig, + constants=ep_non_strict.constants, + ) + # 2. Restore FQN of param/buffers + param_buffer_table: Dict[str, str] = _get_param_buffer_mapping(mod, gm_torch_level) + _replace_param_buffer_names(param_buffer_table, export_graph_signature) + + # 3. Remove non-persistent buffers from the graph signature + _rewrite_non_persistent_buffers(mod, ep_non_strict.sig, ep_non_strict.constants) + + # 4. Rewrite constants to have the same FQN as the original module. + _remap_constants(constant_attrs, export_graph_signature, constants) + + module_call_signatures = { + fqn: ModuleCallSignature(inputs=[], outputs=[], **specs) + for fqn, specs in gm_torch_level.meta["module_call_specs"].items() + } + + if len(preserve_module_call_signature) > 0: + res = CollectTracepointsPass(module_call_signatures, export_graph_signature)(gm) + assert res is not None + gm = res.graph_module + + assert orig_out_spec is not None + exported_program = ExportedProgram( + root=gm, + graph=gm.graph, + graph_signature=export_graph_signature, + state_dict=mod.state_dict(keep_vars=True), + range_constraints=range_constraints, + module_call_graph=[ + ModuleCallEntry( + "", + ModuleCallSignature( + inputs=[], outputs=[], in_spec=orig_in_spec, out_spec=orig_out_spec + ), + ) + ] + + [ModuleCallEntry(fqn, sig) for fqn, sig in module_call_signatures.items()], + example_inputs=(args, kwargs), + constants=constants, + ) + log.debug("Exported program from AOTAutograd:\n%s", exported_program) + + if len(range_constraints) > 0: + exported_program = exported_program._transform_do_not_use( + _AddRuntimeAssertionsForInlineConstraintsPass(range_constraints) + ) + + return exported_program diff --git a/shared/package-files/79/79f0351be9305c2cfd11c7f2594d46daf3a5a2203ed62d1bdf78045917f44781/blob b/shared/package-files/79/79f0351be9305c2cfd11c7f2594d46daf3a5a2203ed62d1bdf78045917f44781/blob new file mode 100644 index 0000000000000000000000000000000000000000..c30ff25cfe416220f7f697bb844350ed7587a243 Binary files /dev/null and b/shared/package-files/79/79f0351be9305c2cfd11c7f2594d46daf3a5a2203ed62d1bdf78045917f44781/blob differ diff --git a/shared/package-files/79/79f15a3a9b569c42b96a9b7a06eb9587b987595e08e7a2bfacd98f36f0f69da9/blob b/shared/package-files/79/79f15a3a9b569c42b96a9b7a06eb9587b987595e08e7a2bfacd98f36f0f69da9/blob new file mode 100644 index 0000000000000000000000000000000000000000..a33816939c8f06039351cb3367f50d4b62f79c13 Binary files /dev/null and b/shared/package-files/79/79f15a3a9b569c42b96a9b7a06eb9587b987595e08e7a2bfacd98f36f0f69da9/blob differ diff --git a/shared/package-files/79/79f493bf2464a5501cc6d030cd8ca60db9ce40f03e7495bb600962455039fdc7/blob b/shared/package-files/79/79f493bf2464a5501cc6d030cd8ca60db9ce40f03e7495bb600962455039fdc7/blob new file mode 100644 index 0000000000000000000000000000000000000000..a4620e510f60c700467cc319e99b9119e27dd4b7 --- /dev/null +++ b/shared/package-files/79/79f493bf2464a5501cc6d030cd8ca60db9ce40f03e7495bb600962455039fdc7/blob @@ -0,0 +1,23 @@ +from abc import ABCMeta, abstractmethod + +from cryptography.hazmat.primitives.serialization import Encoding, KeySerializationEncryption, PrivateFormat, PublicFormat + +class X448PrivateKey(metaclass=ABCMeta): + @classmethod + def from_private_bytes(cls, data: bytes) -> X448PrivateKey: ... + @classmethod + def generate(cls) -> X448PrivateKey: ... + @abstractmethod + def exchange(self, peer_public_key: X448PublicKey) -> bytes: ... + @abstractmethod + def private_bytes( + self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption + ) -> bytes: ... + @abstractmethod + def public_key(self) -> X448PublicKey: ... + +class X448PublicKey(metaclass=ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X448PublicKey: ... + @abstractmethod + def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ... diff --git a/shared/package-files/79/79f6470d9bebd30832b3a9ca59cd1fdca28c5be6373bd01d949eee1ba51aa7a8/blob b/shared/package-files/79/79f6470d9bebd30832b3a9ca59cd1fdca28c5be6373bd01d949eee1ba51aa7a8/blob new file mode 100644 index 0000000000000000000000000000000000000000..934b3b920ba5ad3a777cc582c2456f90774b02fb --- /dev/null +++ b/shared/package-files/79/79f6470d9bebd30832b3a9ca59cd1fdca28c5be6373bd01d949eee1ba51aa7a8/blob @@ -0,0 +1,20 @@ +# Encoding file: iso8859-10, single-byte +S +003F 0 1 +00 +0000000100020003000400050006000700080009000A000B000C000D000E000F +0010001100120013001400150016001700180019001A001B001C001D001E001F +0020002100220023002400250026002700280029002A002B002C002D002E002F +0030003100320033003400350036003700380039003A003B003C003D003E003F +0040004100420043004400450046004700480049004A004B004C004D004E004F +0050005100520053005400550056005700580059005A005B005C005D005E005F +0060006100620063006400650066006700680069006A006B006C006D006E006F +0070007100720073007400750076007700780079007A007B007C007D007E007F +0080008100820083008400850086008700880089008A008B008C008D008E008F +0090009100920093009400950096009700980099009A009B009C009D009E009F +00A0010401120122012A0128013600A7013B011001600166017D00AD016A014A +00B0010501130123012B0129013700B7013C011101610167017E2015016B014B +010000C100C200C300C400C500C6012E010C00C9011800CB011600CD00CE00CF +00D00145014C00D300D400D500D6016800D8017200DA00DB00DC00DD00DE00DF +010100E100E200E300E400E500E6012F010D00E9011900EB011700ED00EE00EF +00F00146014D00F300F400F500F6016900F8017300FA00FB00FC00FD00FE0138 diff --git a/shared/package-files/79/79f69a4fc8851eb71c729f9564a34cbed4ee3cb3631b957d247e4a287847dd22/blob b/shared/package-files/79/79f69a4fc8851eb71c729f9564a34cbed4ee3cb3631b957d247e4a287847dd22/blob new file mode 100644 index 0000000000000000000000000000000000000000..d21e7eeed5408affb3277bde903d6f5f2090ea61 Binary files /dev/null and b/shared/package-files/79/79f69a4fc8851eb71c729f9564a34cbed4ee3cb3631b957d247e4a287847dd22/blob differ diff --git a/shared/package-files/79/79f943daf034a3dc616e9f15dc782bc16afed2f3cf629a451478bc7931b4351a/blob b/shared/package-files/79/79f943daf034a3dc616e9f15dc782bc16afed2f3cf629a451478bc7931b4351a/blob new file mode 100644 index 0000000000000000000000000000000000000000..95cbe60455dad48eb736d2d146599ba720013440 --- /dev/null +++ b/shared/package-files/79/79f943daf034a3dc616e9f15dc782bc16afed2f3cf629a451478bc7931b4351a/blob @@ -0,0 +1,35 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::__or__.Scalar(Tensor self, Scalar other) -> Tensor +inline at::Tensor __or__(const at::Tensor & self, const at::Scalar & other) { + return at::_ops::__or___Scalar::call(self, other); +} + +// aten::__or__.Tensor(Tensor self, Tensor other) -> Tensor +inline at::Tensor __or__(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::__or___Tensor::call(self, other); +} + +} diff --git a/shared/package-files/7a/7a09c1f04c5dbdc11af6d7751c29f305fad350ef6bce4b150aa7441dc17a1118/blob b/shared/package-files/7a/7a09c1f04c5dbdc11af6d7751c29f305fad350ef6bce4b150aa7441dc17a1118/blob new file mode 100644 index 0000000000000000000000000000000000000000..8507790faf07d7e31d1acd44284dc7db6cd688f6 --- /dev/null +++ b/shared/package-files/7a/7a09c1f04c5dbdc11af6d7751c29f305fad350ef6bce4b150aa7441dc17a1118/blob @@ -0,0 +1,369 @@ +import platform + +import llvmlite.binding as ll +from llvmlite import ir + +from numba import _dynfunc +from numba.core.callwrapper import PyCallWrapper +from numba.core.base import BaseContext +from numba.core import (utils, types, config, cgutils, callconv, codegen, + externals, fastmathpass, intrinsics) +from numba.core.options import TargetOptions, include_default_options +from numba.core.runtime import rtsys +from numba.core.compiler_lock import global_compiler_lock +import numba.core.entrypoints +# Re-export these options, they are used from the cpu module throughout the code +# base. +from numba.core.cpu_options import (ParallelOptions, # noqa F401 + FastMathOptions, InlineOptions) # noqa F401 +from numba.np import ufunc_db + +# Keep those structures in sync with _dynfunc.c. + + +class ClosureBody(cgutils.Structure): + _fields = [('env', types.pyobject)] + + +class EnvBody(cgutils.Structure): + _fields = [ + ('globals', types.pyobject), + ('consts', types.pyobject), + ] + + +class CPUContext(BaseContext): + """ + Changes BaseContext calling convention + """ + allow_dynamic_globals = True + + def __init__(self, typingctx, target='cpu'): + super().__init__(typingctx, target) + + def __repr__(self): + # Deterministic repr so it does not embed a process-specific + # object address into emitted binaries (see issue #10610). + return f"<{type(self).__module__}.{type(self).__name__}>" + + # Overrides + def create_module(self, name): + return self._internal_codegen._create_empty_module(name) + + @global_compiler_lock + def init(self): + self.is32bit = (utils.MACHINE_BITS == 32) + self._internal_codegen = codegen.JITCPUCodegen("numba.exec") + + # Add s390x ABI functions from libgcc_s + if platform.machine() == 's390x': + ll.load_library_permanently('libgcc_s.so.1') + + # Map external C functions. + externals.c_math_functions.install(self) + + def apply_target_attributes(self, llvm_func, argtypes=None, restype=None): + """ + Implementation of caller Type Promotions for s390x ABI requirement. + See https://github.com/numba/numba/issues/9640 + + On s390x, the ABI requires that any integer argument or return + value smaller than 64 bits must be promoted to 64 bits by the caller. + The callee can then safely assume the high-order bits of the register + are correctly filled (sign-extended or zero-extended). + Without these attributes, LLVM may leave garbage in the high bits, + leading to undefined behavior (e.g., segfaults) when the callee + performs 64-bit operations on 32-bit values. + """ + if self.address_size == 64 and platform.machine() == 's390x': + def get_ext_attr(numba_ty): + """ + Map Numba types to LLVM extension attributes. + Signed integers -> signext (sign extension) + Unsigned/Booleans -> zeroext (zero extension) + """ + if isinstance(numba_ty, types.Integer): + return 'signext' if numba_ty.signed else 'zeroext' + return 'signext' # Default fallback + + # Handle Arguments: i32 and smaller must be extended to 64-bit + for i, arg in enumerate(llvm_func.args): + if isinstance(arg.type, ir.IntType) and arg.type.width < 64: + n_ty = None + if argtypes and i < len(argtypes): + n_ty = argtypes[i] + arg.add_attribute(get_ext_attr(n_ty)) + + # Handle Return Value + retty = llvm_func.return_value.type + if isinstance(retty, ir.IntType) and retty.width < 64: + llvm_func.return_value.add_attribute(get_ext_attr(restype)) + + def load_additional_registries(self): + # Only initialize the NRT once something is about to be compiled. The + # "initialized" state doesn't need to be threadsafe, there's a lock + # around the internal compilation and the rtsys.initialize call can be + # made multiple times, worse case init just gets called a bit more often + # than optimal. + rtsys.initialize(self) + + # Add implementations that work via import + from numba.cpython import (builtins, charseq, enumimpl, # noqa F401 + hashing, heapq, iterators, # noqa F401 + listobj, numbers, rangeobj, # noqa F401 + setobj, slicing, tupleobj, # noqa F401 + unicode,) # noqa F401 + from numba.core import optional, inline_closurecall # noqa F401 + from numba.misc import gdb_hook, literal # noqa F401 + from numba.np import linalg, arraymath, arrayobj # noqa F401 + from numba.np.random import generator_core, generator_methods, legacy # noqa F401 + from numba.np.polynomial import polynomial_core, polynomial_functions # noqa F401 + from numba.typed import typeddict, dictimpl # noqa F401 + from numba.typed import typedlist, listobject # noqa F401 + from numba.typed import typedset, setobject # noqa F401 + from numba.experimental import jitclass, function_type # noqa F401 + from numba.np.types import datetime_registry # noqa F401 + from numba.np import npdatetime # noqa F401 + + # Add target specific implementations + from numba.np import npyimpl + from numba.cpython import cmathimpl, mathimpl, printimpl, randomimpl + from numba.misc import cffiimpl + from numba.experimental.jitclass.base import ClassBuilder as \ + jitclassimpl + self.install_registry(cmathimpl.registry) + self.install_registry(cffiimpl.registry) + self.install_registry(mathimpl.registry) + self.install_registry(npyimpl.registry) + self.install_registry(printimpl.registry) + self.install_registry(randomimpl.registry) + self.install_registry(jitclassimpl.class_impl_registry) + + # load 3rd party extensions + numba.core.entrypoints.init_all() + + # fix for #8940 + from numba.np.unsafe import ndarray # noqa F401 + + @property + def target_data(self): + return self._internal_codegen.target_data + + def with_aot_codegen(self, name, **aot_options): + aot_codegen = codegen.AOTCPUCodegen(name, **aot_options) + return self.subtarget(_internal_codegen=aot_codegen, + aot_mode=True) + + def codegen(self): + return self._internal_codegen + + @property + def call_conv(self): + return callconv.CPUCallConv(self) + + def get_env_body(self, builder, envptr): + """ + From the given *envptr* (a pointer to a _dynfunc.Environment object), + get a EnvBody allowing structured access to environment fields. + """ + body_ptr = cgutils.pointer_add( + builder, envptr, _dynfunc._impl_info['offsetof_env_body']) + return EnvBody(self, builder, ref=body_ptr, cast_ref=True) + + def get_env_manager(self, builder, return_pyobject=False): + envgv = self.declare_env_global(builder.module, + self.get_env_name(self.fndesc)) + envarg = builder.load(envgv) + pyapi = self.get_python_api(builder) + pyapi.emit_environment_sentry( + envarg, + return_pyobject=return_pyobject, + debug_msg=self.fndesc.env_name, + ) + env_body = self.get_env_body(builder, envarg) + return pyapi.get_env_manager(self.environment, env_body, envarg) + + def get_generator_state(self, builder, genptr, return_type): + """ + From the given *genptr* (a pointer to a _dynfunc.Generator object), + get a pointer to its state area. + """ + return cgutils.pointer_add( + builder, genptr, _dynfunc._impl_info['offsetof_generator_state'], + return_type=return_type) + + def build_list(self, builder, list_type, items): + """ + Build a list from the Numba *list_type* and its initial *items*. + """ + from numba.cpython import listobj + return listobj.build_list(self, builder, list_type, items) + + def build_set(self, builder, set_type, items): + """ + Build a set from the Numba *set_type* and its initial *items*. + """ + from numba.cpython import setobj + return setobj.build_set(self, builder, set_type, items) + + def build_map(self, builder, dict_type, item_types, items): + from numba.typed import dictobject + + return dictobject.build_map(self, builder, dict_type, item_types, items) + + def post_lowering(self, mod, library): + if self.fastmath: + fastmathpass.rewrite_module(mod, self.fastmath) + + if self.is32bit: + # 32-bit machine needs to replace all 64-bit div/rem to avoid + # calls to compiler-rt + intrinsics.fix_divmod(mod) + + library.add_linking_library(rtsys.library) + + def create_cpython_wrapper(self, library, fndesc, env, call_helper, + release_gil=False): + wrapper_module = self.create_module("wrapper") + fnty = self.call_conv.get_function_type(fndesc.restype, fndesc.argtypes) + wrapper_callee = ir.Function(wrapper_module, fnty, + fndesc.llvm_func_name) + builder = PyCallWrapper(self, wrapper_module, wrapper_callee, + fndesc, env, call_helper=call_helper, + release_gil=release_gil) + builder.build() + library.add_ir_module(wrapper_module) + + def create_cfunc_wrapper(self, library, fndesc, env, call_helper): + wrapper_module = self.create_module("cfunc_wrapper") + fnty = self.call_conv.get_function_type(fndesc.restype, fndesc.argtypes) + wrapper_callee = ir.Function(wrapper_module, fnty, + fndesc.llvm_func_name) + + ll_argtypes = [self.get_value_type(ty) for ty in fndesc.argtypes] + ll_return_type = self.get_value_type(fndesc.restype) + wrapty = ir.FunctionType(ll_return_type, ll_argtypes) + wrapfn = ir.Function(wrapper_module, wrapty, + fndesc.llvm_cfunc_wrapper_name) + builder = ir.IRBuilder(wrapfn.append_basic_block('entry')) + + status, out = self.call_conv.call_function( + builder, wrapper_callee, fndesc.restype, fndesc.argtypes, + wrapfn.args, attrs=('noinline',)) + + with builder.if_then(status.is_error, likely=False): + # If (and only if) an error occurred, acquire the GIL + # and use the interpreter to write out the exception. + pyapi = self.get_python_api(builder) + gil_state = pyapi.gil_ensure() + self.call_conv.raise_error(builder, pyapi, status) + cstr = self.insert_const_string(builder.module, repr(self)) + strobj = pyapi.string_from_string(cstr) + pyapi.err_write_unraisable(strobj) + pyapi.decref(strobj) + pyapi.gil_release(gil_state) + + builder.ret(out) + library.add_ir_module(wrapper_module) + + def get_executable(self, library, fndesc, env): + """ + Returns + ------- + (cfunc, fnptr) + + - cfunc + callable function (Can be None) + - fnptr + callable function address + - env + an execution environment (from _dynfunc) + """ + # Code generation + fnptr = library.get_pointer_to_function( + fndesc.llvm_cpython_wrapper_name) + + # Note: we avoid reusing the original docstring to avoid encoding + # issues on Python 2, see issue #1908 + doc = "compiled wrapper for %r" % (fndesc.qualname,) + cfunc = _dynfunc.make_function(fndesc.lookup_module(), + fndesc.qualname.split('.')[-1], + doc, fnptr, env, + # objects to keepalive with the function + (library,) + ) + library.codegen.set_env(self.get_env_name(fndesc), env) + return cfunc + + def calc_array_sizeof(self, ndim): + ''' + Calculate the size of an array struct on the CPU target + ''' + aryty = types.Array(types.int32, ndim, 'A') + return self.get_abi_sizeof(self.get_value_type(aryty)) + + # Overrides + def get_ufunc_info(self, ufunc_key): + return ufunc_db.get_ufunc_info(ufunc_key) + + +# ---------------------------------------------------------------------------- +# TargetOptions + +_options_mixin = include_default_options( + "nopython", + "forceobj", + "looplift", + "_nrt", + "debug", + "boundscheck", + "nogil", + "no_rewrites", + "no_cpython_wrapper", + "no_cfunc_wrapper", + "parallel", + "fastmath", + "error_model", + "inline", + "forceinline", + "_dbg_extend_lifetimes", + "_dbg_optnone", +) + + +class CPUTargetOptions(_options_mixin, TargetOptions): + def finalize(self, flags, options): + if not flags.is_set("enable_pyobject"): + flags.enable_pyobject = True + + if not flags.is_set("enable_looplift"): + flags.enable_looplift = True + + flags.inherit_if_not_set("nrt", default=True) + + if not flags.is_set("debuginfo"): + flags.debuginfo = config.DEBUGINFO_DEFAULT + + if not flags.is_set("dbg_extend_lifetimes"): + if flags.debuginfo: + # auto turn on extend-lifetimes if debuginfo is on and + # dbg_extend_lifetimes is not set + flags.dbg_extend_lifetimes = True + else: + # set flag using env-var config + flags.dbg_extend_lifetimes = config.EXTEND_VARIABLE_LIFETIMES + + if not flags.is_set("boundscheck"): + flags.boundscheck = flags.debuginfo + + flags.enable_pyobject_looplift = True + + flags.inherit_if_not_set("fastmath") + + flags.inherit_if_not_set("error_model", default="python") + + flags.inherit_if_not_set("forceinline") + + if flags.forceinline: + # forceinline turns off optnone, just like clang. + flags.dbg_optnone = False diff --git a/shared/package-files/7a/7a0de2d91385534d300a456d844164d8ce3a144f5d1fa4bca43235bc4283f981/blob b/shared/package-files/7a/7a0de2d91385534d300a456d844164d8ce3a144f5d1fa4bca43235bc4283f981/blob new file mode 100644 index 0000000000000000000000000000000000000000..7e17b3c75876de1ff7ab70a261cc5f883586fe8c --- /dev/null +++ b/shared/package-files/7a/7a0de2d91385534d300a456d844164d8ce3a144f5d1fa4bca43235bc4283f981/blob @@ -0,0 +1,42 @@ +try: + import matplotlib # noqa: F401 +except ImportError: + raise ImportError( + "matplotlib is not installed so plotting is not available! Run `pip install matplotlib` to fix this." + ) + +from ._bar import bar +from ._beeswarm import beeswarm +from ._benchmark import benchmark +from ._decision import decision +from ._embedding import embedding +from ._force import force, initjs +from ._group_difference import group_difference +from ._heatmap import heatmap +from ._image import image, image_to_text +from ._monitoring import monitoring +from ._partial_dependence import partial_dependence +from ._scatter import scatter +from ._text import text +from ._violin import violin +from ._waterfall import waterfall + +__all__ = [ + "bar", + "beeswarm", + "benchmark", + "decision", + "embedding", + "force", + "initjs", + "group_difference", + "heatmap", + "image", + "image_to_text", + "monitoring", + "partial_dependence", + "scatter", + "text", + "violin", + "waterfall", +] diff --git a/shared/package-files/7a/7a0df9546b5b22be164f3d866a63a296054e7470bd6ff8bb4040851302e0175b/blob b/shared/package-files/7a/7a0df9546b5b22be164f3d866a63a296054e7470bd6ff8bb4040851302e0175b/blob new file mode 100644 index 0000000000000000000000000000000000000000..6d85e94b432bf846e6f43230c41992e72c5515a2 --- /dev/null +++ b/shared/package-files/7a/7a0df9546b5b22be164f3d866a63a296054e7470bd6ff8bb4040851302e0175b/blob @@ -0,0 +1,3 @@ +__all__ = ["ARIMA"] + +from statsmodels.tsa.arima.model import ARIMA diff --git a/shared/package-files/7a/7a0f492dccca9cc8027800815be42053c3a9bd74569d48b7113696e5c3f699aa/blob b/shared/package-files/7a/7a0f492dccca9cc8027800815be42053c3a9bd74569d48b7113696e5c3f699aa/blob new file mode 100644 index 0000000000000000000000000000000000000000..69a260f5b12c079813d9760d45e1dff689527861 --- /dev/null +++ b/shared/package-files/7a/7a0f492dccca9cc8027800815be42053c3a9bd74569d48b7113696e5c3f699aa/blob @@ -0,0 +1,993 @@ +r"""XML-RPC Servers. + +This module can be used to create simple XML-RPC servers +by creating a server and either installing functions, a +class instance, or by extending the SimpleXMLRPCServer +class. + +It can also be used to handle XML-RPC requests in a CGI +environment using CGIXMLRPCRequestHandler. + +The Doc* classes can be used to create XML-RPC servers that +serve pydoc-style documentation in response to HTTP +GET requests. This documentation is dynamically generated +based on the functions and methods registered with the +server. + +A list of possible usage patterns follows: + +1. Install functions: + +server = SimpleXMLRPCServer(("localhost", 8000)) +server.register_function(pow) +server.register_function(lambda x,y: x+y, 'add') +server.serve_forever() + +2. Install an instance: + +class MyFuncs: + def __init__(self): + # make all of the sys functions available through sys.func_name + import sys + self.sys = sys + def _listMethods(self): + # implement this method so that system.listMethods + # knows to advertise the sys methods + return list_public_methods(self) + \ + ['sys.' + method for method in list_public_methods(self.sys)] + def pow(self, x, y): return pow(x, y) + def add(self, x, y) : return x + y + +server = SimpleXMLRPCServer(("localhost", 8000)) +server.register_introspection_functions() +server.register_instance(MyFuncs()) +server.serve_forever() + +3. Install an instance with custom dispatch method: + +class Math: + def _listMethods(self): + # this method must be present for system.listMethods + # to work + return ['add', 'pow'] + def _methodHelp(self, method): + # this method must be present for system.methodHelp + # to work + if method == 'add': + return "add(2,3) => 5" + elif method == 'pow': + return "pow(x, y[, z]) => number" + else: + # By convention, return empty + # string if no help is available + return "" + def _dispatch(self, method, params): + if method == 'pow': + return pow(*params) + elif method == 'add': + return params[0] + params[1] + else: + raise ValueError('bad method') + +server = SimpleXMLRPCServer(("localhost", 8000)) +server.register_introspection_functions() +server.register_instance(Math()) +server.serve_forever() + +4. Subclass SimpleXMLRPCServer: + +class MathServer(SimpleXMLRPCServer): + def _dispatch(self, method, params): + try: + # We are forcing the 'export_' prefix on methods that are + # callable through XML-RPC to prevent potential security + # problems + func = getattr(self, 'export_' + method) + except AttributeError: + raise Exception('method "%s" is not supported' % method) + else: + return func(*params) + + def export_add(self, x, y): + return x + y + +server = MathServer(("localhost", 8000)) +server.serve_forever() + +5. CGI script: + +server = CGIXMLRPCRequestHandler() +server.register_function(pow) +server.handle_request() +""" + +# Written by Brian Quinlan (brian@sweetapp.com). +# Based on code written by Fredrik Lundh. + +from xmlrpc.client import Fault, dumps, loads, gzip_encode, gzip_decode +from http.server import BaseHTTPRequestHandler +from functools import partial +from inspect import signature +import html +import http.server +import socketserver +import sys +import os +import re +import pydoc +import traceback +try: + import fcntl +except ImportError: + fcntl = None + +def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): + """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d + + Resolves a dotted attribute name to an object. Raises + an AttributeError if any attribute in the chain starts with a '_'. + + If the optional allow_dotted_names argument is false, dots are not + supported and this function operates similar to getattr(obj, attr). + """ + + if allow_dotted_names: + attrs = attr.split('.') + else: + attrs = [attr] + + for i in attrs: + if i.startswith('_'): + raise AttributeError( + 'attempt to access private attribute "%s"' % i + ) + else: + obj = getattr(obj,i) + return obj + +def list_public_methods(obj): + """Returns a list of attribute strings, found in the specified + object, which represent callable attributes""" + + return [member for member in dir(obj) + if not member.startswith('_') and + callable(getattr(obj, member))] + +class SimpleXMLRPCDispatcher: + """Mix-in class that dispatches XML-RPC requests. + + This class is used to register XML-RPC method handlers + and then to dispatch them. This class doesn't need to be + instanced directly when used by SimpleXMLRPCServer but it + can be instanced when used by the MultiPathXMLRPCServer + """ + + def __init__(self, allow_none=False, encoding=None, + use_builtin_types=False): + self.funcs = {} + self.instance = None + self.allow_none = allow_none + self.encoding = encoding or 'utf-8' + self.use_builtin_types = use_builtin_types + + def register_instance(self, instance, allow_dotted_names=False): + """Registers an instance to respond to XML-RPC requests. + + Only one instance can be installed at a time. + + If the registered instance has a _dispatch method then that + method will be called with the name of the XML-RPC method and + its parameters as a tuple + e.g. instance._dispatch('add',(2,3)) + + If the registered instance does not have a _dispatch method + then the instance will be searched to find a matching method + and, if found, will be called. Methods beginning with an '_' + are considered private and will not be called by + SimpleXMLRPCServer. + + If a registered function matches an XML-RPC request, then it + will be called instead of the registered instance. + + If the optional allow_dotted_names argument is true and the + instance does not have a _dispatch method, method names + containing dots are supported and resolved, as long as none of + the name segments start with an '_'. + + *** SECURITY WARNING: *** + + Enabling the allow_dotted_names options allows intruders + to access your module's global variables and may allow + intruders to execute arbitrary code on your machine. Only + use this option on a secure, closed network. + + """ + + self.instance = instance + self.allow_dotted_names = allow_dotted_names + + def register_function(self, function=None, name=None): + """Registers a function to respond to XML-RPC requests. + + The optional name argument can be used to set a Unicode name + for the function. + """ + # decorator factory + if function is None: + return partial(self.register_function, name=name) + + if name is None: + name = function.__name__ + self.funcs[name] = function + + return function + + def register_introspection_functions(self): + """Registers the XML-RPC introspection methods in the system + namespace. + + see http://xmlrpc.usefulinc.com/doc/reserved.html + """ + + self.funcs.update({'system.listMethods' : self.system_listMethods, + 'system.methodSignature' : self.system_methodSignature, + 'system.methodHelp' : self.system_methodHelp}) + + def register_multicall_functions(self): + """Registers the XML-RPC multicall method in the system + namespace. + + see http://www.xmlrpc.com/discuss/msgReader$1208""" + + self.funcs.update({'system.multicall' : self.system_multicall}) + + def _marshaled_dispatch(self, data, dispatch_method = None, path = None): + """Dispatches an XML-RPC method from marshalled (XML) data. + + XML-RPC methods are dispatched from the marshalled (XML) data + using the _dispatch method and the result is returned as + marshalled data. For backwards compatibility, a dispatch + function can be provided as an argument (see comment in + SimpleXMLRPCRequestHandler.do_POST) but overriding the + existing method through subclassing is the preferred means + of changing method dispatch behavior. + """ + + try: + params, method = loads(data, use_builtin_types=self.use_builtin_types) + + # generate response + if dispatch_method is not None: + response = dispatch_method(method, params) + else: + response = self._dispatch(method, params) + # wrap response in a singleton tuple + response = (response,) + response = dumps(response, methodresponse=1, + allow_none=self.allow_none, encoding=self.encoding) + except Fault as fault: + response = dumps(fault, allow_none=self.allow_none, + encoding=self.encoding) + except: + # report exception back to server + exc_type, exc_value, exc_tb = sys.exc_info() + try: + response = dumps( + Fault(1, "%s:%s" % (exc_type, exc_value)), + encoding=self.encoding, allow_none=self.allow_none, + ) + finally: + # Break reference cycle + exc_type = exc_value = exc_tb = None + + return response.encode(self.encoding, 'xmlcharrefreplace') + + def system_listMethods(self): + """system.listMethods() => ['add', 'subtract', 'multiple'] + + Returns a list of the methods supported by the server.""" + + methods = set(self.funcs.keys()) + if self.instance is not None: + # Instance can implement _listMethod to return a list of + # methods + if hasattr(self.instance, '_listMethods'): + methods |= set(self.instance._listMethods()) + # if the instance has a _dispatch method then we + # don't have enough information to provide a list + # of methods + elif not hasattr(self.instance, '_dispatch'): + methods |= set(list_public_methods(self.instance)) + return sorted(methods) + + def system_methodSignature(self, method_name): + """system.methodSignature('add') => [double, int, int] + + Returns a list describing the signature of the method. In the + above example, the add method takes two integers as arguments + and returns a double result. + + This server does NOT support system.methodSignature.""" + + # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html + + return 'signatures not supported' + + def system_methodHelp(self, method_name): + """system.methodHelp('add') => "Adds two integers together" + + Returns a string containing documentation for the specified method.""" + + method = None + if method_name in self.funcs: + method = self.funcs[method_name] + elif self.instance is not None: + # Instance can implement _methodHelp to return help for a method + if hasattr(self.instance, '_methodHelp'): + return self.instance._methodHelp(method_name) + # if the instance has a _dispatch method then we + # don't have enough information to provide help + elif not hasattr(self.instance, '_dispatch'): + try: + method = resolve_dotted_attribute( + self.instance, + method_name, + self.allow_dotted_names + ) + except AttributeError: + pass + + # Note that we aren't checking that the method actually + # be a callable object of some kind + if method is None: + return "" + else: + return pydoc.getdoc(method) + + def system_multicall(self, call_list): + """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ +[[4], ...] + + Allows the caller to package multiple XML-RPC calls into a single + request. + + See http://www.xmlrpc.com/discuss/msgReader$1208 + """ + + results = [] + for call in call_list: + method_name = call['methodName'] + params = call['params'] + + try: + # XXX A marshalling error in any response will fail the entire + # multicall. If someone cares they should fix this. + results.append([self._dispatch(method_name, params)]) + except Fault as fault: + results.append( + {'faultCode' : fault.faultCode, + 'faultString' : fault.faultString} + ) + except: + exc_type, exc_value, exc_tb = sys.exc_info() + try: + results.append( + {'faultCode' : 1, + 'faultString' : "%s:%s" % (exc_type, exc_value)} + ) + finally: + # Break reference cycle + exc_type = exc_value = exc_tb = None + return results + + def _dispatch(self, method, params): + """Dispatches the XML-RPC method. + + XML-RPC calls are forwarded to a registered function that + matches the called XML-RPC method name. If no such function + exists then the call is forwarded to the registered instance, + if available. + + If the registered instance has a _dispatch method then that + method will be called with the name of the XML-RPC method and + its parameters as a tuple + e.g. instance._dispatch('add',(2,3)) + + If the registered instance does not have a _dispatch method + then the instance will be searched to find a matching method + and, if found, will be called. + + Methods beginning with an '_' are considered private and will + not be called. + """ + + try: + # call the matching registered function + func = self.funcs[method] + except KeyError: + pass + else: + if func is not None: + return func(*params) + raise Exception('method "%s" is not supported' % method) + + if self.instance is not None: + if hasattr(self.instance, '_dispatch'): + # call the `_dispatch` method on the instance + return self.instance._dispatch(method, params) + + # call the instance's method directly + try: + func = resolve_dotted_attribute( + self.instance, + method, + self.allow_dotted_names + ) + except AttributeError: + pass + else: + if func is not None: + return func(*params) + + raise Exception('method "%s" is not supported' % method) + +class SimpleXMLRPCRequestHandler(BaseHTTPRequestHandler): + """Simple XML-RPC request handler class. + + Handles all HTTP POST requests and attempts to decode them as + XML-RPC requests. + """ + + # Class attribute listing the accessible path components; + # paths not on this list will result in a 404 error. + rpc_paths = ('/', '/RPC2') + + #if not None, encode responses larger than this, if possible + encode_threshold = 1400 #a common MTU + + #Override form StreamRequestHandler: full buffering of output + #and no Nagle. + wbufsize = -1 + disable_nagle_algorithm = True + + # a re to match a gzip Accept-Encoding + aepattern = re.compile(r""" + \s* ([^\s;]+) \s* #content-coding + (;\s* q \s*=\s* ([0-9\.]+))? #q + """, re.VERBOSE | re.IGNORECASE) + + def accept_encodings(self): + r = {} + ae = self.headers.get("Accept-Encoding", "") + for e in ae.split(","): + match = self.aepattern.match(e) + if match: + v = match.group(3) + v = float(v) if v else 1.0 + r[match.group(1)] = v + return r + + def is_rpc_path_valid(self): + if self.rpc_paths: + return self.path in self.rpc_paths + else: + # If .rpc_paths is empty, just assume all paths are legal + return True + + def do_POST(self): + """Handles the HTTP POST request. + + Attempts to interpret all HTTP POST requests as XML-RPC calls, + which are forwarded to the server's _dispatch method for handling. + """ + + # Check that the path is legal + if not self.is_rpc_path_valid(): + self.report_404() + return + + try: + # Get arguments by reading body of request. + # We read this in chunks to avoid straining + # socket.read(); around the 10 or 15Mb mark, some platforms + # begin to have problems (bug #792570). + max_chunk_size = 10*1024*1024 + size_remaining = int(self.headers["content-length"]) + L = [] + while size_remaining: + chunk_size = min(size_remaining, max_chunk_size) + chunk = self.rfile.read(chunk_size) + if not chunk: + break + L.append(chunk) + size_remaining -= len(L[-1]) + data = b''.join(L) + + data = self.decode_request_content(data) + if data is None: + return #response has been sent + + # In previous versions of SimpleXMLRPCServer, _dispatch + # could be overridden in this class, instead of in + # SimpleXMLRPCDispatcher. To maintain backwards compatibility, + # check to see if a subclass implements _dispatch and dispatch + # using that method if present. + response = self.server._marshaled_dispatch( + data, getattr(self, '_dispatch', None), self.path + ) + except Exception as e: # This should only happen if the module is buggy + # internal error, report as HTTP server error + self.send_response(500) + + # Send information about the exception if requested + if hasattr(self.server, '_send_traceback_header') and \ + self.server._send_traceback_header: + self.send_header("X-exception", str(e)) + trace = traceback.format_exc() + trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII') + self.send_header("X-traceback", trace) + + self.send_header("Content-length", "0") + self.end_headers() + else: + self.send_response(200) + self.send_header("Content-type", "text/xml") + if self.encode_threshold is not None: + if len(response) > self.encode_threshold: + q = self.accept_encodings().get("gzip", 0) + if q: + try: + response = gzip_encode(response) + self.send_header("Content-Encoding", "gzip") + except NotImplementedError: + pass + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + + def decode_request_content(self, data): + #support gzip encoding of request + encoding = self.headers.get("content-encoding", "identity").lower() + if encoding == "identity": + return data + if encoding == "gzip": + try: + return gzip_decode(data) + except NotImplementedError: + self.send_response(501, "encoding %r not supported" % encoding) + except ValueError: + self.send_response(400, "error decoding gzip content") + else: + self.send_response(501, "encoding %r not supported" % encoding) + self.send_header("Content-length", "0") + self.end_headers() + + def report_404 (self): + # Report a 404 error + self.send_response(404) + response = b'No such page' + self.send_header("Content-type", "text/plain") + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + + def log_request(self, code='-', size='-'): + """Selectively log an accepted request.""" + + if self.server.logRequests: + BaseHTTPRequestHandler.log_request(self, code, size) + +class SimpleXMLRPCServer(socketserver.TCPServer, + SimpleXMLRPCDispatcher): + """Simple XML-RPC server. + + Simple XML-RPC server that allows functions and a single instance + to be installed to handle requests. The default implementation + attempts to dispatch XML-RPC calls to the functions or instance + installed in the server. Override the _dispatch method inherited + from SimpleXMLRPCDispatcher to change this behavior. + """ + + allow_reuse_address = True + + # Warning: this is for debugging purposes only! Never set this to True in + # production code, as will be sending out sensitive information (exception + # and stack trace details) when exceptions are raised inside + # SimpleXMLRPCRequestHandler.do_POST + _send_traceback_header = False + + def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True, use_builtin_types=False): + self.logRequests = logRequests + + SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) + socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) + + +class MultiPathXMLRPCServer(SimpleXMLRPCServer): + """Multipath XML-RPC Server + This specialization of SimpleXMLRPCServer allows the user to create + multiple Dispatcher instances and assign them to different + HTTP request paths. This makes it possible to run two or more + 'virtual XML-RPC servers' at the same port. + Make sure that the requestHandler accepts the paths in question. + """ + def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True, use_builtin_types=False): + + SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none, + encoding, bind_and_activate, use_builtin_types) + self.dispatchers = {} + self.allow_none = allow_none + self.encoding = encoding or 'utf-8' + + def add_dispatcher(self, path, dispatcher): + self.dispatchers[path] = dispatcher + return dispatcher + + def get_dispatcher(self, path): + return self.dispatchers[path] + + def _marshaled_dispatch(self, data, dispatch_method = None, path = None): + try: + response = self.dispatchers[path]._marshaled_dispatch( + data, dispatch_method, path) + except: + # report low level exception back to server + # (each dispatcher should have handled their own + # exceptions) + exc_type, exc_value = sys.exc_info()[:2] + try: + response = dumps( + Fault(1, "%s:%s" % (exc_type, exc_value)), + encoding=self.encoding, allow_none=self.allow_none) + response = response.encode(self.encoding, 'xmlcharrefreplace') + finally: + # Break reference cycle + exc_type = exc_value = None + return response + +class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): + """Simple handler for XML-RPC data passed through CGI.""" + + def __init__(self, allow_none=False, encoding=None, use_builtin_types=False): + SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) + + def handle_xmlrpc(self, request_text): + """Handle a single XML-RPC request""" + + response = self._marshaled_dispatch(request_text) + + print('Content-Type: text/xml') + print('Content-Length: %d' % len(response)) + print() + sys.stdout.flush() + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + + def handle_get(self): + """Handle a single HTTP GET request. + + Default implementation indicates an error because + XML-RPC uses the POST method. + """ + + code = 400 + message, explain = BaseHTTPRequestHandler.responses[code] + + response = http.server.DEFAULT_ERROR_MESSAGE % \ + { + 'code' : code, + 'message' : message, + 'explain' : explain + } + response = response.encode('utf-8') + print('Status: %d %s' % (code, message)) + print('Content-Type: %s' % http.server.DEFAULT_ERROR_CONTENT_TYPE) + print('Content-Length: %d' % len(response)) + print() + sys.stdout.flush() + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + + def handle_request(self, request_text=None): + """Handle a single XML-RPC request passed through a CGI post method. + + If no XML data is given then it is read from stdin. The resulting + XML-RPC response is printed to stdout along with the correct HTTP + headers. + """ + + if request_text is None and \ + os.environ.get('REQUEST_METHOD', None) == 'GET': + self.handle_get() + else: + # POST data is normally available through stdin + try: + length = int(os.environ.get('CONTENT_LENGTH', None)) + except (ValueError, TypeError): + length = -1 + if request_text is None: + request_text = sys.stdin.read(length) + + self.handle_xmlrpc(request_text) + + +# ----------------------------------------------------------------------------- +# Self documenting XML-RPC Server. + +class ServerHTMLDoc(pydoc.HTMLDoc): + """Class used to generate pydoc HTML document for a server""" + + def markup(self, text, escape=None, funcs={}, classes={}, methods={}): + """Mark up some plain text, given a context of symbols to look for. + Each context dictionary maps object names to anchor names.""" + escape = escape or self.escape + results = [] + here = 0 + + # XXX Note that this regular expression does not allow for the + # hyperlinking of arbitrary strings being used as method + # names. Only methods with names consisting of word characters + # and '.'s are hyperlinked. + pattern = re.compile(r'\b((http|https|ftp)://\S+[\w/]|' + r'RFC[- ]?(\d+)|' + r'PEP[- ]?(\d+)|' + r'(self\.)?((?:\w|\.)+))\b') + while 1: + match = pattern.search(text, here) + if not match: break + start, end = match.span() + results.append(escape(text[here:start])) + + all, scheme, rfc, pep, selfdot, name = match.groups() + if scheme: + url = escape(all).replace('"', '"') + results.append('%s' % (url, url)) + elif rfc: + url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) + results.append('%s' % (url, escape(all))) + elif pep: + url = 'https://www.python.org/dev/peps/pep-%04d/' % int(pep) + results.append('%s' % (url, escape(all))) + elif text[end:end+1] == '(': + results.append(self.namelink(name, methods, funcs, classes)) + elif selfdot: + results.append('self.%s' % name) + else: + results.append(self.namelink(name, classes)) + here = end + results.append(escape(text[here:])) + return ''.join(results) + + def docroutine(self, object, name, mod=None, + funcs={}, classes={}, methods={}, cl=None): + """Produce HTML documentation for a function or method object.""" + + anchor = (cl and cl.__name__ or '') + '-' + name + note = '' + + title = '%s' % ( + self.escape(anchor), self.escape(name)) + + if callable(object): + argspec = str(signature(object)) + else: + argspec = '(...)' + + if isinstance(object, tuple): + argspec = object[0] or argspec + docstring = object[1] or "" + else: + docstring = pydoc.getdoc(object) + + decl = title + argspec + (note and self.grey( + '%s' % note)) + + doc = self.markup( + docstring, self.preformat, funcs, classes, methods) + doc = doc and '
%s
' % doc + return '
%s
%s
\n' % (decl, doc) + + def docserver(self, server_name, package_documentation, methods): + """Produce HTML documentation for an XML-RPC server.""" + + fdict = {} + for key, value in methods.items(): + fdict[key] = '#-' + key + fdict[value] = fdict[key] + + server_name = self.escape(server_name) + head = '%s' % server_name + result = self.heading(head, '#ffffff', '#7799ee') + + doc = self.markup(package_documentation, self.preformat, fdict) + doc = doc and '%s' % doc + result = result + '

%s

\n' % doc + + contents = [] + method_items = sorted(methods.items()) + for key, value in method_items: + contents.append(self.docroutine(value, key, funcs=fdict)) + result = result + self.bigsection( + 'Methods', '#ffffff', '#eeaa77', ''.join(contents)) + + return result + +class XMLRPCDocGenerator: + """Generates documentation for an XML-RPC server. + + This class is designed as mix-in and should not + be constructed directly. + """ + + def __init__(self): + # setup variables used for HTML documentation + self.server_name = 'XML-RPC Server Documentation' + self.server_documentation = \ + "This server exports the following methods through the XML-RPC "\ + "protocol." + self.server_title = 'XML-RPC Server Documentation' + + def set_server_title(self, server_title): + """Set the HTML title of the generated server documentation""" + + self.server_title = server_title + + def set_server_name(self, server_name): + """Set the name of the generated HTML server documentation""" + + self.server_name = server_name + + def set_server_documentation(self, server_documentation): + """Set the documentation string for the entire server.""" + + self.server_documentation = server_documentation + + def generate_html_documentation(self): + """generate_html_documentation() => html documentation for the server + + Generates HTML documentation for the server using introspection for + installed functions and instances that do not implement the + _dispatch method. Alternatively, instances can choose to implement + the _get_method_argstring(method_name) method to provide the + argument string used in the documentation and the + _methodHelp(method_name) method to provide the help text used + in the documentation.""" + + methods = {} + + for method_name in self.system_listMethods(): + if method_name in self.funcs: + method = self.funcs[method_name] + elif self.instance is not None: + method_info = [None, None] # argspec, documentation + if hasattr(self.instance, '_get_method_argstring'): + method_info[0] = self.instance._get_method_argstring(method_name) + if hasattr(self.instance, '_methodHelp'): + method_info[1] = self.instance._methodHelp(method_name) + + method_info = tuple(method_info) + if method_info != (None, None): + method = method_info + elif not hasattr(self.instance, '_dispatch'): + try: + method = resolve_dotted_attribute( + self.instance, + method_name + ) + except AttributeError: + method = method_info + else: + method = method_info + else: + assert 0, "Could not find method in self.functions and no "\ + "instance installed" + + methods[method_name] = method + + documenter = ServerHTMLDoc() + documentation = documenter.docserver( + self.server_name, + self.server_documentation, + methods + ) + + return documenter.page(html.escape(self.server_title), documentation) + +class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): + """XML-RPC and documentation request handler class. + + Handles all HTTP POST requests and attempts to decode them as + XML-RPC requests. + + Handles all HTTP GET requests and interprets them as requests + for documentation. + """ + + def do_GET(self): + """Handles the HTTP GET request. + + Interpret all HTTP GET requests as requests for server + documentation. + """ + # Check that the path is legal + if not self.is_rpc_path_valid(): + self.report_404() + return + + response = self.server.generate_html_documentation().encode('utf-8') + self.send_response(200) + self.send_header("Content-type", "text/html") + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + +class DocXMLRPCServer( SimpleXMLRPCServer, + XMLRPCDocGenerator): + """XML-RPC and HTML documentation server. + + Adds the ability to serve server documentation to the capabilities + of SimpleXMLRPCServer. + """ + + def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler, + logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True, use_builtin_types=False): + SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, + allow_none, encoding, bind_and_activate, + use_builtin_types) + XMLRPCDocGenerator.__init__(self) + +class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler, + XMLRPCDocGenerator): + """Handler for XML-RPC data and documentation requests passed through + CGI""" + + def handle_get(self): + """Handles the HTTP GET request. + + Interpret all HTTP GET requests as requests for server + documentation. + """ + + response = self.generate_html_documentation().encode('utf-8') + + print('Content-Type: text/html') + print('Content-Length: %d' % len(response)) + print() + sys.stdout.flush() + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + + def __init__(self): + CGIXMLRPCRequestHandler.__init__(self) + XMLRPCDocGenerator.__init__(self) + + +if __name__ == '__main__': + import datetime + + class ExampleService: + def getData(self): + return '42' + + class currentTime: + @staticmethod + def getCurrentTime(): + return datetime.datetime.now() + + with SimpleXMLRPCServer(("localhost", 8000)) as server: + server.register_function(pow) + server.register_function(lambda x,y: x+y, 'add') + server.register_instance(ExampleService(), allow_dotted_names=True) + server.register_multicall_functions() + print('Serving XML-RPC on localhost port 8000') + print('It is advisable to run this example server within a secure, closed network.') + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nKeyboard interrupt received, exiting.") + sys.exit(0) diff --git a/shared/package-files/7a/7a1030288821832a2b25b9661034d88bb95db97997d9fbc8e327adeb57ddbe85/blob b/shared/package-files/7a/7a1030288821832a2b25b9661034d88bb95db97997d9fbc8e327adeb57ddbe85/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d45ee4063c95aaffa5de4bd98b38334408670ee --- /dev/null +++ b/shared/package-files/7a/7a1030288821832a2b25b9661034d88bb95db97997d9fbc8e327adeb57ddbe85/blob @@ -0,0 +1,29 @@ +Copyright (c) 2011, Roger Lew [see LICENSE.txt] +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the organizations affiliated with the + contributors or the names of its contributors themselves may be + used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/shared/package-files/7a/7a108332570bbc6bfbbf779aa75260e64dd474076d816c2064cbd088d309709a/blob b/shared/package-files/7a/7a108332570bbc6bfbbf779aa75260e64dd474076d816c2064cbd088d309709a/blob new file mode 100644 index 0000000000000000000000000000000000000000..eed452c935c64a89d2a9c7b007013933baed69b8 --- /dev/null +++ b/shared/package-files/7a/7a108332570bbc6bfbbf779aa75260e64dd474076d816c2064cbd088d309709a/blob @@ -0,0 +1,338 @@ +# encoding: utf-8 +""" +The :class:`~traitlets.config.application.Application` object for the command +line :command:`ipython` program. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +import logging +import os +import sys +import warnings + +from traitlets.config.loader import Config +from traitlets.config.application import boolean_flag, catch_config_error +from IPython.core import release +from IPython.core import usage +from IPython.core.completer import IPCompleter +from IPython.core.crashhandler import CrashHandler +from IPython.core.formatters import PlainTextFormatter +from IPython.core.history import HistoryManager +from IPython.core.application import ( + ProfileDir, BaseIPythonApplication, base_flags, base_aliases +) +from IPython.core.magic import MagicsManager +from IPython.core.magics import ( + ScriptMagics, LoggingMagics +) +from IPython.core.shellapp import ( + InteractiveShellApp, shell_flags, shell_aliases +) +from IPython.extensions.storemagic import StoreMagics +from .interactiveshell import TerminalInteractiveShell +from IPython.paths import get_ipython_dir +from traitlets import ( + Bool, List, default, observe, Type +) + +#----------------------------------------------------------------------------- +# Globals, utilities and helpers +#----------------------------------------------------------------------------- + +_examples = """ +ipython --matplotlib # enable matplotlib integration +ipython --matplotlib=qt # enable matplotlib integration with qt4 backend + +ipython --log-level=DEBUG # set logging to DEBUG +ipython --profile=foo # start with profile foo + +ipython profile create foo # create profile foo w/ default config files +ipython help profile # show the help for the profile subcmd + +ipython locate # print the path to the IPython directory +ipython locate profile foo # print the path to the directory for profile `foo` +""" + +#----------------------------------------------------------------------------- +# Crash handler for this application +#----------------------------------------------------------------------------- + +class IPAppCrashHandler(CrashHandler): + """sys.excepthook for IPython itself, leaves a detailed report on disk.""" + + def __init__(self, app): + contact_name = release.author + contact_email = release.author_email + bug_tracker = 'https://github.com/ipython/ipython/issues' + super(IPAppCrashHandler,self).__init__( + app, contact_name, contact_email, bug_tracker + ) + + def make_report(self,traceback): + """Return a string containing a crash report.""" + + sec_sep = self.section_sep + # Start with parent report + report = [super(IPAppCrashHandler, self).make_report(traceback)] + # Add interactive-specific info we may have + rpt_add = report.append + try: + rpt_add(sec_sep+"History of session input:") + for line in self.app.shell.user_ns['_ih']: + rpt_add(line) + rpt_add('\n*** Last line of input (may not be in above history):\n') + rpt_add(self.app.shell._last_input_line+'\n') + except: + pass + + return ''.join(report) + +#----------------------------------------------------------------------------- +# Aliases and Flags +#----------------------------------------------------------------------------- +flags = dict(base_flags) +flags.update(shell_flags) +frontend_flags = {} +addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) +addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', + 'Turn on auto editing of files with syntax errors.', + 'Turn off auto editing of files with syntax errors.' +) +addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt', + "Force simple minimal prompt using `raw_input`", + "Use a rich interactive prompt with prompt_toolkit", +) + +addflag('banner', 'TerminalIPythonApp.display_banner', + "Display a banner upon starting IPython.", + "Don't display a banner upon starting IPython." +) +addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', + """Set to confirm when you try to exit IPython with an EOF (Control-D + in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', + you can force a direct exit without any confirmation.""", + "Don't prompt the user when exiting." +) +addflag('term-title', 'TerminalInteractiveShell.term_title', + "Enable auto setting the terminal title.", + "Disable auto setting the terminal title." +) +classic_config = Config() +classic_config.InteractiveShell.cache_size = 0 +classic_config.PlainTextFormatter.pprint = False +classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts' +classic_config.InteractiveShell.separate_in = '' +classic_config.InteractiveShell.separate_out = '' +classic_config.InteractiveShell.separate_out2 = '' +classic_config.InteractiveShell.colors = 'NoColor' +classic_config.InteractiveShell.xmode = 'Plain' + +frontend_flags['classic']=( + classic_config, + "Gives IPython a similar feel to the classic Python prompt." +) +# # log doesn't make so much sense this way anymore +# paa('--log','-l', +# action='store_true', dest='InteractiveShell.logstart', +# help="Start logging to the default log file (./ipython_log.py).") +# +# # quick is harder to implement +frontend_flags['quick']=( + {'TerminalIPythonApp' : {'quick' : True}}, + "Enable quick startup with no config files." +) + +frontend_flags['i'] = ( + {'TerminalIPythonApp' : {'force_interact' : True}}, + """If running code from the command line, become interactive afterwards. + It is often useful to follow this with `--` to treat remaining flags as + script arguments. + """ +) +flags.update(frontend_flags) + +aliases = dict(base_aliases) +aliases.update(shell_aliases) # type: ignore[arg-type] + +#----------------------------------------------------------------------------- +# Main classes and functions +#----------------------------------------------------------------------------- + + +class LocateIPythonApp(BaseIPythonApplication): + description = """print the path to the IPython dir""" + subcommands = dict( + profile=('IPython.core.profileapp.ProfileLocate', + "print the path to an IPython profile directory", + ), + ) + def start(self): + if self.subapp is not None: + return self.subapp.start() + else: + print(self.ipython_dir) + + +class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): + name = u'ipython' + description = usage.cl_usage + crash_handler_class = IPAppCrashHandler # typing: ignore[assignment] + examples = _examples + + flags = flags + aliases = aliases + classes = List() + + interactive_shell_class = Type( + klass=object, # use default_value otherwise which only allow subclasses. + default_value=TerminalInteractiveShell, + help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" + ).tag(config=True) + + @default('classes') + def _classes_default(self): + """This has to be in a method, for TerminalIPythonApp to be available.""" + return [ + InteractiveShellApp, # ShellApp comes before TerminalApp, because + self.__class__, # it will also affect subclasses (e.g. QtConsole) + TerminalInteractiveShell, + HistoryManager, + MagicsManager, + ProfileDir, + PlainTextFormatter, + IPCompleter, + ScriptMagics, + LoggingMagics, + StoreMagics, + ] + + subcommands = dict( + profile = ("IPython.core.profileapp.ProfileApp", + "Create and manage IPython profiles." + ), + kernel = ("ipykernel.kernelapp.IPKernelApp", + "Start a kernel without an attached frontend." + ), + locate=('IPython.terminal.ipapp.LocateIPythonApp', + LocateIPythonApp.description + ), + history=('IPython.core.historyapp.HistoryApp', + "Manage the IPython history database." + ), + ) + + + # *do* autocreate requested profile, but don't create the config file. + auto_create=Bool(True) + # configurables + quick = Bool(False, + help="""Start IPython quickly by skipping the loading of config files.""" + ).tag(config=True) + @observe('quick') + def _quick_changed(self, change): + if change['new']: + self.load_config_file = lambda *a, **kw: None + + display_banner = Bool(True, + help="Whether to display a banner upon starting IPython." + ).tag(config=True) + + # if there is code of files to run from the cmd line, don't interact + # unless the --i flag (App.force_interact) is true. + force_interact = Bool(False, + help="""If a command or file is given via the command-line, + e.g. 'ipython foo.py', start an interactive shell after executing the + file or command.""" + ).tag(config=True) + @observe('force_interact') + def _force_interact_changed(self, change): + if change['new']: + self.interact = True + + @observe('file_to_run', 'code_to_run', 'module_to_run') + def _file_to_run_changed(self, change): + new = change['new'] + if new: + self.something_to_run = True + if new and not self.force_interact: + self.interact = False + + # internal, not-configurable + something_to_run=Bool(False) + + @catch_config_error + def initialize(self, argv=None): + """Do actions after construct, but before starting the app.""" + super(TerminalIPythonApp, self).initialize(argv) + if self.subapp is not None: + # don't bother initializing further, starting subapp + return + # print self.extra_args + if self.extra_args and not self.something_to_run: + self.file_to_run = self.extra_args[0] + self.init_path() + # create the shell + self.init_shell() + # and draw the banner + self.init_banner() + # Now a variety of things that happen after the banner is printed. + self.init_gui_pylab() + self.init_extensions() + self.init_code() + + def init_shell(self): + """initialize the InteractiveShell instance""" + # Create an InteractiveShell instance. + # shell.display_banner should always be False for the terminal + # based app, because we call shell.show_banner() by hand below + # so the banner shows *before* all extension loading stuff. + self.shell = self.interactive_shell_class.instance(parent=self, + profile_dir=self.profile_dir, + ipython_dir=self.ipython_dir, user_ns=self.user_ns) + self.shell.configurables.append(self) + + def init_banner(self): + """optionally display the banner""" + if self.display_banner and self.interact: + self.shell.show_banner() + # Make sure there is a space below the banner. + if self.log_level <= logging.INFO: print() + + def _pylab_changed(self, name, old, new): + """Replace --pylab='inline' with --pylab='auto'""" + if new == 'inline': + warnings.warn("'inline' not available as pylab backend, " + "using 'auto' instead.") + self.pylab = 'auto' + + def start(self): + if self.subapp is not None: + return self.subapp.start() + # perform any prexec steps: + if self.interact: + self.log.debug("Starting IPython's mainloop...") + self.shell.mainloop() + else: + self.log.debug("IPython not interactive...") + self.shell.restore_term_title() + if not self.shell.last_execution_succeeded: + sys.exit(1) + +def load_default_config(ipython_dir=None): + """Load the default config file from the default ipython_dir. + + This is useful for embedded shells. + """ + if ipython_dir is None: + ipython_dir = get_ipython_dir() + + profile_dir = os.path.join(ipython_dir, 'profile_default') + app = TerminalIPythonApp() + app.config_file_paths.append(profile_dir) + app.load_config_file() + return app.config + +launch_new_instance = TerminalIPythonApp.launch_instance diff --git a/shared/package-files/7a/7a130af741256014ea982d6b69b90bb0ae932061fcff8759fddf605e854b305d/blob b/shared/package-files/7a/7a130af741256014ea982d6b69b90bb0ae932061fcff8759fddf605e854b305d/blob new file mode 100644 index 0000000000000000000000000000000000000000..b7e1630d3dcd22d77d4426a14533266d64651539 --- /dev/null +++ b/shared/package-files/7a/7a130af741256014ea982d6b69b90bb0ae932061fcff8759fddf605e854b305d/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor special_zeta(const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & special_zeta_out(at::Tensor & out, const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor & special_zeta_outf(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor special_zeta(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & special_zeta_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & special_zeta_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/7a/7a14c058e8813dd0cab568a4d078abc22289c65824d35e079c2b128aa4e52a4b/blob b/shared/package-files/7a/7a14c058e8813dd0cab568a4d078abc22289c65824d35e079c2b128aa4e52a4b/blob new file mode 100644 index 0000000000000000000000000000000000000000..212cceb4ef32143576fe49577c73fba10ab918cd --- /dev/null +++ b/shared/package-files/7a/7a14c058e8813dd0cab568a4d078abc22289c65824d35e079c2b128aa4e52a4b/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API broadcast_tensors { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::broadcast_tensors") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "broadcast_tensors(Tensor[] tensors) -> Tensor[]") + static ::std::vector call(at::TensorList tensors); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7a/7a1c32d2cf6e486901cac865da5f749dddb90f4328a7744d634f494d190750c1/blob b/shared/package-files/7a/7a1c32d2cf6e486901cac865da5f749dddb90f4328a7744d634f494d190750c1/blob new file mode 100644 index 0000000000000000000000000000000000000000..d5f6af8e023c036c51496350952165e0aa45df0e --- /dev/null +++ b/shared/package-files/7a/7a1c32d2cf6e486901cac865da5f749dddb90f4328a7744d634f494d190750c1/blob @@ -0,0 +1,2574 @@ +/* + pybind11/pytypes.h: Convenience wrapper classes for basic Python types + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "detail/common.h" +#include "buffer_info.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(PYBIND11_HAS_OPTIONAL) +# include +#endif + +#ifdef PYBIND11_HAS_STRING_VIEW +# include +#endif + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +PYBIND11_WARNING_DISABLE_MSVC(4127) + +/* A few forward declarations */ +class handle; +class object; +class str; +class iterator; +class type; +struct arg; +struct arg_v; + +PYBIND11_NAMESPACE_BEGIN(detail) +class args_proxy; +bool isinstance_generic(handle obj, const std::type_info &tp); + +// Accessor forward declarations +template +class accessor; +namespace accessor_policies { +struct obj_attr; +struct str_attr; +struct generic_item; +struct sequence_item; +struct list_item; +struct tuple_item; +} // namespace accessor_policies +// PLEASE KEEP handle_type_name SPECIALIZATIONS IN SYNC. +using obj_attr_accessor = accessor; +using str_attr_accessor = accessor; +using item_accessor = accessor; +using sequence_accessor = accessor; +using list_accessor = accessor; +using tuple_accessor = accessor; + +/// Tag and check to identify a class which implements the Python object API +class pyobject_tag {}; +template +using is_pyobject = std::is_base_of>; + +/** \rst + A mixin class which adds common functions to `handle`, `object` and various accessors. + The only requirement for `Derived` is to implement ``PyObject *Derived::ptr() const``. +\endrst */ +template +class object_api : public pyobject_tag { + const Derived &derived() const { return static_cast(*this); } + +public: + /** \rst + Return an iterator equivalent to calling ``iter()`` in Python. The object + must be a collection which supports the iteration protocol. + \endrst */ + iterator begin() const; + /// Return a sentinel which ends iteration. + iterator end() const; + + /** \rst + Return an internal functor to invoke the object's sequence protocol. Casting + the returned ``detail::item_accessor`` instance to a `handle` or `object` + subclass causes a corresponding call to ``__getitem__``. Assigning a `handle` + or `object` subclass causes a call to ``__setitem__``. + \endrst */ + item_accessor operator[](handle key) const; + /// See above (the only difference is that the key's reference is stolen) + item_accessor operator[](object &&key) const; + /// See above (the only difference is that the key is provided as a string literal) + item_accessor operator[](const char *key) const; + + /** \rst + Return an internal functor to access the object's attributes. Casting the + returned ``detail::obj_attr_accessor`` instance to a `handle` or `object` + subclass causes a corresponding call to ``getattr``. Assigning a `handle` + or `object` subclass causes a call to ``setattr``. + \endrst */ + obj_attr_accessor attr(handle key) const; + /// See above (the only difference is that the key's reference is stolen) + obj_attr_accessor attr(object &&key) const; + /// See above (the only difference is that the key is provided as a string literal) + str_attr_accessor attr(const char *key) const; + + /** \rst + Matches * unpacking in Python, e.g. to unpack arguments out of a ``tuple`` + or ``list`` for a function call. Applying another * to the result yields + ** unpacking, e.g. to unpack a dict as function keyword arguments. + See :ref:`calling_python_functions`. + \endrst */ + args_proxy operator*() const; + + /// Check if the given item is contained within this object, i.e. ``item in obj``. + template + bool contains(T &&item) const; + + /** \rst + Assuming the Python object is a function or implements the ``__call__`` + protocol, ``operator()`` invokes the underlying function, passing an + arbitrary set of parameters. The result is returned as a `object` and + may need to be converted back into a Python object using `handle::cast()`. + + When some of the arguments cannot be converted to Python objects, the + function will throw a `cast_error` exception. When the Python function + call fails, a `error_already_set` exception is thrown. + \endrst */ + template + object operator()(Args &&...args) const; + template + PYBIND11_DEPRECATED("call(...) was deprecated in favor of operator()(...)") + object call(Args &&...args) const; + + /// Equivalent to ``obj is other`` in Python. + bool is(object_api const &other) const { return derived().ptr() == other.derived().ptr(); } + /// Equivalent to ``obj is None`` in Python. + bool is_none() const { return derived().ptr() == Py_None; } + /// Equivalent to obj == other in Python + bool equal(object_api const &other) const { return rich_compare(other, Py_EQ); } + bool not_equal(object_api const &other) const { return rich_compare(other, Py_NE); } + bool operator<(object_api const &other) const { return rich_compare(other, Py_LT); } + bool operator<=(object_api const &other) const { return rich_compare(other, Py_LE); } + bool operator>(object_api const &other) const { return rich_compare(other, Py_GT); } + bool operator>=(object_api const &other) const { return rich_compare(other, Py_GE); } + + object operator-() const; + object operator~() const; + object operator+(object_api const &other) const; + object operator+=(object_api const &other); + object operator-(object_api const &other) const; + object operator-=(object_api const &other); + object operator*(object_api const &other) const; + object operator*=(object_api const &other); + object operator/(object_api const &other) const; + object operator/=(object_api const &other); + object operator|(object_api const &other) const; + object operator|=(object_api const &other); + object operator&(object_api const &other) const; + object operator&=(object_api const &other); + object operator^(object_api const &other) const; + object operator^=(object_api const &other); + object operator<<(object_api const &other) const; + object operator<<=(object_api const &other); + object operator>>(object_api const &other) const; + object operator>>=(object_api const &other); + + PYBIND11_DEPRECATED("Use py::str(obj) instead") + pybind11::str str() const; + + /// Get or set the object's docstring, i.e. ``obj.__doc__``. + str_attr_accessor doc() const; + + /// Return the object's current reference count + int ref_count() const { return static_cast(Py_REFCNT(derived().ptr())); } + + // TODO PYBIND11_DEPRECATED( + // "Call py::type::handle_of(h) or py::type::of(h) instead of h.get_type()") + handle get_type() const; + +private: + bool rich_compare(object_api const &other, int value) const; +}; + +template +using is_pyobj_ptr_or_nullptr_t = detail::any_of, + std::is_same, + std::is_same>; + +PYBIND11_NAMESPACE_END(detail) + +#if !defined(PYBIND11_HANDLE_REF_DEBUG) && !defined(NDEBUG) +# define PYBIND11_HANDLE_REF_DEBUG +#endif + +/** \rst + Holds a reference to a Python object (no reference counting) + + The `handle` class is a thin wrapper around an arbitrary Python object (i.e. a + ``PyObject *`` in Python's C API). It does not perform any automatic reference + counting and merely provides a basic C++ interface to various Python API functions. + + .. seealso:: + The `object` class inherits from `handle` and adds automatic reference + counting features. +\endrst */ +class handle : public detail::object_api { +public: + /// The default constructor creates a handle with a ``nullptr``-valued pointer + handle() = default; + + /// Enable implicit conversion from ``PyObject *`` and ``nullptr``. + /// Not using ``handle(PyObject *ptr)`` to avoid implicit conversion from ``0``. + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + handle(T ptr) : m_ptr(ptr) {} + + /// Enable implicit conversion through ``T::operator PyObject *()``. + template < + typename T, + detail::enable_if_t, + detail::is_pyobj_ptr_or_nullptr_t>, + std::is_convertible>::value, + int> + = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + handle(T &obj) : m_ptr(obj) {} + + /// Return the underlying ``PyObject *`` pointer + PyObject *ptr() const { return m_ptr; } + PyObject *&ptr() { return m_ptr; } + + /** \rst + Manually increase the reference count of the Python object. Usually, it is + preferable to use the `object` class which derives from `handle` and calls + this function automatically. Returns a reference to itself. + \endrst */ + const handle &inc_ref() const & { +#ifdef PYBIND11_HANDLE_REF_DEBUG + inc_ref_counter(1); +#endif +#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF + if (m_ptr != nullptr && !PyGILState_Check()) { + throw_gilstate_error("pybind11::handle::inc_ref()"); + } +#endif + Py_XINCREF(m_ptr); + return *this; + } + + /** \rst + Manually decrease the reference count of the Python object. Usually, it is + preferable to use the `object` class which derives from `handle` and calls + this function automatically. Returns a reference to itself. + \endrst */ + const handle &dec_ref() const & { +#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF + if (m_ptr != nullptr && !PyGILState_Check()) { + throw_gilstate_error("pybind11::handle::dec_ref()"); + } +#endif + Py_XDECREF(m_ptr); + return *this; + } + + /** \rst + Attempt to cast the Python object into the given C++ type. A `cast_error` + will be throw upon failure. + \endrst */ + template + T cast() const; + /// Return ``true`` when the `handle` wraps a valid Python object + explicit operator bool() const { return m_ptr != nullptr; } + /** \rst + Deprecated: Check that the underlying pointers are the same. + Equivalent to ``obj1 is obj2`` in Python. + \endrst */ + PYBIND11_DEPRECATED("Use obj1.is(obj2) instead") + bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } + PYBIND11_DEPRECATED("Use !obj1.is(obj2) instead") + bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } + PYBIND11_DEPRECATED("Use handle::operator bool() instead") + bool check() const { return m_ptr != nullptr; } + +protected: + PyObject *m_ptr = nullptr; + +private: +#ifdef PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF + void throw_gilstate_error(const std::string &function_name) const { + fprintf( + stderr, + "%s is being called while the GIL is either not held or invalid. Please see " + "https://pybind11.readthedocs.io/en/stable/advanced/" + "misc.html#common-sources-of-global-interpreter-lock-errors for debugging advice.\n" + "If you are convinced there is no bug in your code, you can #define " + "PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF " + "to disable this check. In that case you have to ensure this #define is consistently " + "used for all translation units linked into a given pybind11 extension, otherwise " + "there will be ODR violations.", + function_name.c_str()); + if (Py_TYPE(m_ptr)->tp_name != nullptr) { + fprintf(stderr, + " The failing %s call was triggered on a %s object.", + function_name.c_str(), + Py_TYPE(m_ptr)->tp_name); + } + fprintf(stderr, "\n"); + fflush(stderr); + throw std::runtime_error(function_name + " PyGILState_Check() failure."); + } +#endif + +#ifdef PYBIND11_HANDLE_REF_DEBUG + static std::size_t inc_ref_counter(std::size_t add) { + thread_local std::size_t counter = 0; + counter += add; + return counter; + } + +public: + static std::size_t inc_ref_counter() { return inc_ref_counter(0); } +#endif +}; + +inline void set_error(const handle &type, const char *message) { + PyErr_SetString(type.ptr(), message); +} + +inline void set_error(const handle &type, const handle &value) { + PyErr_SetObject(type.ptr(), value.ptr()); +} + +/** \rst + Holds a reference to a Python object (with reference counting) + + Like `handle`, the `object` class is a thin wrapper around an arbitrary Python + object (i.e. a ``PyObject *`` in Python's C API). In contrast to `handle`, it + optionally increases the object's reference count upon construction, and it + *always* decreases the reference count when the `object` instance goes out of + scope and is destructed. When using `object` instances consistently, it is much + easier to get reference counting right at the first attempt. +\endrst */ +class object : public handle { +public: + object() = default; + PYBIND11_DEPRECATED("Use reinterpret_borrow() or reinterpret_steal()") + object(handle h, bool is_borrowed) : handle(h) { + if (is_borrowed) { + inc_ref(); + } + } + /// Copy constructor; always increases the reference count + object(const object &o) : handle(o) { inc_ref(); } + /// Move constructor; steals the object from ``other`` and preserves its reference count + object(object &&other) noexcept : handle(other) { other.m_ptr = nullptr; } + /// Destructor; automatically calls `handle::dec_ref()` + ~object() { dec_ref(); } + + /** \rst + Resets the internal pointer to ``nullptr`` without decreasing the + object's reference count. The function returns a raw handle to the original + Python object. + \endrst */ + handle release() { + PyObject *tmp = m_ptr; + m_ptr = nullptr; + return handle(tmp); + } + + object &operator=(const object &other) { + // Skip inc_ref and dec_ref if both objects are the same + if (!this->is(other)) { + other.inc_ref(); + // Use temporary variable to ensure `*this` remains valid while + // `Py_XDECREF` executes, in case `*this` is accessible from Python. + handle temp(m_ptr); + m_ptr = other.m_ptr; + temp.dec_ref(); + } + return *this; + } + + object &operator=(object &&other) noexcept { + if (this != &other) { + handle temp(m_ptr); + m_ptr = other.m_ptr; + other.m_ptr = nullptr; + temp.dec_ref(); + } + return *this; + } + +#define PYBIND11_INPLACE_OP(iop) \ + object iop(object_api const &other) { return operator=(handle::iop(other)); } + + PYBIND11_INPLACE_OP(operator+=) + PYBIND11_INPLACE_OP(operator-=) + PYBIND11_INPLACE_OP(operator*=) + PYBIND11_INPLACE_OP(operator/=) + PYBIND11_INPLACE_OP(operator|=) + PYBIND11_INPLACE_OP(operator&=) + PYBIND11_INPLACE_OP(operator^=) + PYBIND11_INPLACE_OP(operator<<=) + PYBIND11_INPLACE_OP(operator>>=) +#undef PYBIND11_INPLACE_OP + + // Calling cast() on an object lvalue just copies (via handle::cast) + template + T cast() const &; + // Calling on an object rvalue does a move, if needed and/or possible + template + T cast() &&; + +protected: + // Tags for choosing constructors from raw PyObject * + struct borrowed_t {}; + struct stolen_t {}; + + /// @cond BROKEN + template + friend T reinterpret_borrow(handle); + template + friend T reinterpret_steal(handle); + /// @endcond + +public: + // Only accessible from derived classes and the reinterpret_* functions + object(handle h, borrowed_t) : handle(h) { inc_ref(); } + object(handle h, stolen_t) : handle(h) {} +}; + +/** \rst + Declare that a `handle` or ``PyObject *`` is a certain type and borrow the reference. + The target type ``T`` must be `object` or one of its derived classes. The function + doesn't do any conversions or checks. It's up to the user to make sure that the + target type is correct. + + .. code-block:: cpp + + PyObject *p = PyList_GetItem(obj, index); + py::object o = reinterpret_borrow(p); + // or + py::tuple t = reinterpret_borrow(p); // <-- `p` must be already be a `tuple` +\endrst */ +template +T reinterpret_borrow(handle h) { + return {h, object::borrowed_t{}}; +} + +/** \rst + Like `reinterpret_borrow`, but steals the reference. + + .. code-block:: cpp + + PyObject *p = PyObject_Str(obj); + py::str s = reinterpret_steal(p); // <-- `p` must be already be a `str` +\endrst */ +template +T reinterpret_steal(handle h) { + return {h, object::stolen_t{}}; +} + +PYBIND11_NAMESPACE_BEGIN(detail) + +// Equivalent to obj.__class__.__name__ (or obj.__name__ if obj is a class). +inline const char *obj_class_name(PyObject *obj) { + if (PyType_Check(obj)) { + return reinterpret_cast(obj)->tp_name; + } + return Py_TYPE(obj)->tp_name; +} + +std::string error_string(); + +// The code in this struct is very unusual, to minimize the chances of +// masking bugs (elsewhere) by errors during the error handling (here). +// This is meant to be a lifeline for troubleshooting long-running processes +// that crash under conditions that are virtually impossible to reproduce. +// Low-level implementation alternatives are preferred to higher-level ones +// that might raise cascading exceptions. Last-ditch-kind-of attempts are made +// to report as much of the original error as possible, even if there are +// secondary issues obtaining some of the details. +struct error_fetch_and_normalize { + // This comment only applies to Python <= 3.11: + // Immediate normalization is long-established behavior (starting with + // https://github.com/pybind/pybind11/commit/135ba8deafb8bf64a15b24d1513899eb600e2011 + // from Sep 2016) and safest. Normalization could be deferred, but this could mask + // errors elsewhere, the performance gain is very minor in typical situations + // (usually the dominant bottleneck is EH unwinding), and the implementation here + // would be more complex. + // Starting with Python 3.12, PyErr_Fetch() normalizes exceptions immediately. + // Any errors during normalization are tracked under __notes__. + explicit error_fetch_and_normalize(const char *called) { + PyErr_Fetch(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); + if (!m_type) { + pybind11_fail("Internal error: " + std::string(called) + + " called while " + "Python error indicator not set."); + } + const char *exc_type_name_orig = detail::obj_class_name(m_type.ptr()); + if (exc_type_name_orig == nullptr) { + pybind11_fail("Internal error: " + std::string(called) + + " failed to obtain the name " + "of the original active exception type."); + } + m_lazy_error_string = exc_type_name_orig; +#if PY_VERSION_HEX >= 0x030C0000 + // The presence of __notes__ is likely due to exception normalization + // errors, although that is not necessarily true, therefore insert a + // hint only: + if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) { + m_lazy_error_string += "[WITH __notes__]"; + } +#else + // PyErr_NormalizeException() may change the exception type if there are cascading + // failures. This can potentially be extremely confusing. + PyErr_NormalizeException(&m_type.ptr(), &m_value.ptr(), &m_trace.ptr()); + if (m_type.ptr() == nullptr) { + pybind11_fail("Internal error: " + std::string(called) + + " failed to normalize the " + "active exception."); + } + const char *exc_type_name_norm = detail::obj_class_name(m_type.ptr()); + if (exc_type_name_norm == nullptr) { + pybind11_fail("Internal error: " + std::string(called) + + " failed to obtain the name " + "of the normalized active exception type."); + } +# if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x07030a00 + // This behavior runs the risk of masking errors in the error handling, but avoids a + // conflict with PyPy, which relies on the normalization here to change OSError to + // FileNotFoundError (https://github.com/pybind/pybind11/issues/4075). + m_lazy_error_string = exc_type_name_norm; +# else + if (exc_type_name_norm != m_lazy_error_string) { + std::string msg = std::string(called) + + ": MISMATCH of original and normalized " + "active exception types: "; + msg += "ORIGINAL "; + msg += m_lazy_error_string; + msg += " REPLACED BY "; + msg += exc_type_name_norm; + msg += ": " + format_value_and_trace(); + pybind11_fail(msg); + } +# endif +#endif + } + + error_fetch_and_normalize(const error_fetch_and_normalize &) = delete; + error_fetch_and_normalize(error_fetch_and_normalize &&) = delete; + + std::string format_value_and_trace() const { + std::string result; + std::string message_error_string; + if (m_value) { + auto value_str = reinterpret_steal(PyObject_Str(m_value.ptr())); + constexpr const char *message_unavailable_exc + = ""; + if (!value_str) { + message_error_string = detail::error_string(); + result = message_unavailable_exc; + } else { + // Not using `value_str.cast()`, to not potentially throw a secondary + // error_already_set that will then result in process termination (#4288). + auto value_bytes = reinterpret_steal( + PyUnicode_AsEncodedString(value_str.ptr(), "utf-8", "backslashreplace")); + if (!value_bytes) { + message_error_string = detail::error_string(); + result = message_unavailable_exc; + } else { + char *buffer = nullptr; + Py_ssize_t length = 0; + if (PyBytes_AsStringAndSize(value_bytes.ptr(), &buffer, &length) == -1) { + message_error_string = detail::error_string(); + result = message_unavailable_exc; + } else { + result = std::string(buffer, static_cast(length)); + } + } + } +#if PY_VERSION_HEX >= 0x030B0000 + auto notes + = reinterpret_steal(PyObject_GetAttrString(m_value.ptr(), "__notes__")); + if (!notes) { + PyErr_Clear(); // No notes is good news. + } else { + auto len_notes = PyList_Size(notes.ptr()); + if (len_notes < 0) { + result += "\nFAILURE obtaining len(__notes__): " + detail::error_string(); + } else { + result += "\n__notes__ (len=" + std::to_string(len_notes) + "):"; + for (ssize_t i = 0; i < len_notes; i++) { + PyObject *note = PyList_GET_ITEM(notes.ptr(), i); + auto note_bytes = reinterpret_steal( + PyUnicode_AsEncodedString(note, "utf-8", "backslashreplace")); + if (!note_bytes) { + result += "\nFAILURE obtaining __notes__[" + std::to_string(i) + + "]: " + detail::error_string(); + } else { + char *buffer = nullptr; + Py_ssize_t length = 0; + if (PyBytes_AsStringAndSize(note_bytes.ptr(), &buffer, &length) + == -1) { + result += "\nFAILURE formatting __notes__[" + std::to_string(i) + + "]: " + detail::error_string(); + } else { + result += '\n'; + result += std::string(buffer, static_cast(length)); + } + } + } + } + } +#endif + } else { + result = ""; + } + if (result.empty()) { + result = ""; + } + + bool have_trace = false; + if (m_trace) { +#if !defined(PYPY_VERSION) + auto *tb = reinterpret_cast(m_trace.ptr()); + + // Get the deepest trace possible. + while (tb->tb_next) { + tb = tb->tb_next; + } + + PyFrameObject *frame = tb->tb_frame; + Py_XINCREF(frame); + result += "\n\nAt:\n"; + while (frame) { +# if PY_VERSION_HEX >= 0x030900B1 + PyCodeObject *f_code = PyFrame_GetCode(frame); +# else + PyCodeObject *f_code = frame->f_code; + Py_INCREF(f_code); +# endif + int lineno = PyFrame_GetLineNumber(frame); + result += " "; + result += handle(f_code->co_filename).cast(); + result += '('; + result += std::to_string(lineno); + result += "): "; + result += handle(f_code->co_name).cast(); + result += '\n'; + Py_DECREF(f_code); +# if PY_VERSION_HEX >= 0x030900B1 + auto *b_frame = PyFrame_GetBack(frame); +# else + auto *b_frame = frame->f_back; + Py_XINCREF(b_frame); +# endif + Py_DECREF(frame); + frame = b_frame; + } + + have_trace = true; +#endif //! defined(PYPY_VERSION) + } + + if (!message_error_string.empty()) { + if (!have_trace) { + result += '\n'; + } + result += "\nMESSAGE UNAVAILABLE DUE TO EXCEPTION: " + message_error_string; + } + + return result; + } + + std::string const &error_string() const { + if (!m_lazy_error_string_completed) { + m_lazy_error_string += ": " + format_value_and_trace(); + m_lazy_error_string_completed = true; + } + return m_lazy_error_string; + } + + void restore() { + if (m_restore_called) { + pybind11_fail("Internal error: pybind11::detail::error_fetch_and_normalize::restore() " + "called a second time. ORIGINAL ERROR: " + + error_string()); + } + PyErr_Restore(m_type.inc_ref().ptr(), m_value.inc_ref().ptr(), m_trace.inc_ref().ptr()); + m_restore_called = true; + } + + bool matches(handle exc) const { + return (PyErr_GivenExceptionMatches(m_type.ptr(), exc.ptr()) != 0); + } + + // Not protecting these for simplicity. + object m_type, m_value, m_trace; + +private: + // Only protecting invariants. + mutable std::string m_lazy_error_string; + mutable bool m_lazy_error_string_completed = false; + mutable bool m_restore_called = false; +}; + +inline std::string error_string() { + return error_fetch_and_normalize("pybind11::detail::error_string").error_string(); +} + +PYBIND11_NAMESPACE_END(detail) + +/// Fetch and hold an error which was already set in Python. An instance of this is typically +/// thrown to propagate python-side errors back through C++ which can either be caught manually or +/// else falls back to the function dispatcher (which then raises the captured error back to +/// python). +class PYBIND11_EXPORT_EXCEPTION error_already_set : public std::exception { +public: + /// Fetches the current Python exception (using PyErr_Fetch()), which will clear the + /// current Python error indicator. + error_already_set() + : m_fetched_error{new detail::error_fetch_and_normalize("pybind11::error_already_set"), + m_fetched_error_deleter} {} + + /// The what() result is built lazily on demand. + /// WARNING: This member function needs to acquire the Python GIL. This can lead to + /// crashes (undefined behavior) if the Python interpreter is finalizing. + const char *what() const noexcept override; + + /// Restores the currently-held Python error (which will clear the Python error indicator first + /// if already set). + /// NOTE: This member function will always restore the normalized exception, which may or may + /// not be the original Python exception. + /// WARNING: The GIL must be held when this member function is called! + void restore() { m_fetched_error->restore(); } + + /// If it is impossible to raise the currently-held error, such as in a destructor, we can + /// write it out using Python's unraisable hook (`sys.unraisablehook`). The error context + /// should be some object whose `repr()` helps identify the location of the error. Python + /// already knows the type and value of the error, so there is no need to repeat that. + void discard_as_unraisable(object err_context) { + restore(); + PyErr_WriteUnraisable(err_context.ptr()); + } + /// An alternate version of `discard_as_unraisable()`, where a string provides information on + /// the location of the error. For example, `__func__` could be helpful. + /// WARNING: The GIL must be held when this member function is called! + void discard_as_unraisable(const char *err_context) { + discard_as_unraisable(reinterpret_steal(PYBIND11_FROM_STRING(err_context))); + } + + // Does nothing; provided for backwards compatibility. + PYBIND11_DEPRECATED("Use of error_already_set.clear() is deprecated") + void clear() {} + + /// Check if the currently trapped error type matches the given Python exception class (or a + /// subclass thereof). May also be passed a tuple to search for any exception class matches in + /// the given tuple. + bool matches(handle exc) const { return m_fetched_error->matches(exc); } + + const object &type() const { return m_fetched_error->m_type; } + const object &value() const { return m_fetched_error->m_value; } + const object &trace() const { return m_fetched_error->m_trace; } + +private: + std::shared_ptr m_fetched_error; + + /// WARNING: This custom deleter needs to acquire the Python GIL. This can lead to + /// crashes (undefined behavior) if the Python interpreter is finalizing. + static void m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr); +}; + +/// Replaces the current Python error indicator with the chosen error, performing a +/// 'raise from' to indicate that the chosen error was caused by the original error. +inline void raise_from(PyObject *type, const char *message) { + // Based on _PyErr_FormatVFromCause: + // https://github.com/python/cpython/blob/467ab194fc6189d9f7310c89937c51abeac56839/Python/errors.c#L405 + // See https://github.com/pybind/pybind11/pull/2112 for details. + PyObject *exc = nullptr, *val = nullptr, *val2 = nullptr, *tb = nullptr; + + assert(PyErr_Occurred()); + PyErr_Fetch(&exc, &val, &tb); + PyErr_NormalizeException(&exc, &val, &tb); + if (tb != nullptr) { + PyException_SetTraceback(val, tb); + Py_DECREF(tb); + } + Py_DECREF(exc); + assert(!PyErr_Occurred()); + + PyErr_SetString(type, message); + + PyErr_Fetch(&exc, &val2, &tb); + PyErr_NormalizeException(&exc, &val2, &tb); + Py_INCREF(val); + PyException_SetCause(val2, val); + PyException_SetContext(val2, val); + PyErr_Restore(exc, val2, tb); +} + +/// Sets the current Python error indicator with the chosen error, performing a 'raise from' +/// from the error contained in error_already_set to indicate that the chosen error was +/// caused by the original error. +inline void raise_from(error_already_set &err, PyObject *type, const char *message) { + err.restore(); + raise_from(type, message); +} + +/** \defgroup python_builtins const_name + Unless stated otherwise, the following C++ functions behave the same + as their Python counterparts. + */ + +/** \ingroup python_builtins + \rst + Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of + `object` or a class which was exposed to Python as ``py::class_``. +\endrst */ +template ::value, int> = 0> +bool isinstance(handle obj) { + return T::check_(obj); +} + +template ::value, int> = 0> +bool isinstance(handle obj) { + return detail::isinstance_generic(obj, typeid(T)); +} + +template <> +inline bool isinstance(handle) = delete; +template <> +inline bool isinstance(handle obj) { + return obj.ptr() != nullptr; +} + +/// \ingroup python_builtins +/// Return true if ``obj`` is an instance of the ``type``. +inline bool isinstance(handle obj, handle type) { + const auto result = PyObject_IsInstance(obj.ptr(), type.ptr()); + if (result == -1) { + throw error_already_set(); + } + return result != 0; +} + +/// \addtogroup python_builtins +/// @{ +inline bool hasattr(handle obj, handle name) { + return PyObject_HasAttr(obj.ptr(), name.ptr()) == 1; +} + +inline bool hasattr(handle obj, const char *name) { + return PyObject_HasAttrString(obj.ptr(), name) == 1; +} + +inline void delattr(handle obj, handle name) { + if (PyObject_DelAttr(obj.ptr(), name.ptr()) != 0) { + throw error_already_set(); + } +} + +inline void delattr(handle obj, const char *name) { + if (PyObject_DelAttrString(obj.ptr(), name) != 0) { + throw error_already_set(); + } +} + +inline object getattr(handle obj, handle name) { + PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr()); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); +} + +inline object getattr(handle obj, const char *name) { + PyObject *result = PyObject_GetAttrString(obj.ptr(), name); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); +} + +inline object getattr(handle obj, handle name, handle default_) { + if (PyObject *result = PyObject_GetAttr(obj.ptr(), name.ptr())) { + return reinterpret_steal(result); + } + PyErr_Clear(); + return reinterpret_borrow(default_); +} + +inline object getattr(handle obj, const char *name, handle default_) { + if (PyObject *result = PyObject_GetAttrString(obj.ptr(), name)) { + return reinterpret_steal(result); + } + PyErr_Clear(); + return reinterpret_borrow(default_); +} + +inline void setattr(handle obj, handle name, handle value) { + if (PyObject_SetAttr(obj.ptr(), name.ptr(), value.ptr()) != 0) { + throw error_already_set(); + } +} + +inline void setattr(handle obj, const char *name, handle value) { + if (PyObject_SetAttrString(obj.ptr(), name, value.ptr()) != 0) { + throw error_already_set(); + } +} + +inline ssize_t hash(handle obj) { + auto h = PyObject_Hash(obj.ptr()); + if (h == -1) { + throw error_already_set(); + } + return h; +} + +/// @} python_builtins + +PYBIND11_NAMESPACE_BEGIN(detail) +inline handle get_function(handle value) { + if (value) { + if (PyInstanceMethod_Check(value.ptr())) { + value = PyInstanceMethod_GET_FUNCTION(value.ptr()); + } else if (PyMethod_Check(value.ptr())) { + value = PyMethod_GET_FUNCTION(value.ptr()); + } + } + return value; +} + +// Reimplementation of python's dict helper functions to ensure that exceptions +// aren't swallowed (see #2862) + +// copied from cpython _PyDict_GetItemStringWithError +inline PyObject *dict_getitemstring(PyObject *v, const char *key) { + PyObject *kv = nullptr, *rv = nullptr; + kv = PyUnicode_FromString(key); + if (kv == nullptr) { + throw error_already_set(); + } + + rv = PyDict_GetItemWithError(v, kv); + Py_DECREF(kv); + if (rv == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + return rv; +} + +inline PyObject *dict_getitem(PyObject *v, PyObject *key) { + PyObject *rv = PyDict_GetItemWithError(v, key); + if (rv == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + return rv; +} + +// Helper aliases/functions to support implicit casting of values given to python +// accessors/methods. When given a pyobject, this simply returns the pyobject as-is; for other C++ +// type, the value goes through pybind11::cast(obj) to convert it to an `object`. +template ::value, int> = 0> +auto object_or_cast(T &&o) -> decltype(std::forward(o)) { + return std::forward(o); +} +// The following casting version is implemented in cast.h: +template ::value, int> = 0> +object object_or_cast(T &&o); +// Match a PyObject*, which we want to convert directly to handle via its converting constructor +inline handle object_or_cast(PyObject *ptr) { return ptr; } + +PYBIND11_WARNING_PUSH +PYBIND11_WARNING_DISABLE_MSVC(4522) // warning C4522: multiple assignment operators specified +template +class accessor : public object_api> { + using key_type = typename Policy::key_type; + +public: + accessor(handle obj, key_type key) : obj(obj), key(std::move(key)) {} + accessor(const accessor &) = default; + accessor(accessor &&) noexcept = default; + + // accessor overload required to override default assignment operator (templates are not + // allowed to replace default compiler-generated assignments). + void operator=(const accessor &a) && { std::move(*this).operator=(handle(a)); } + void operator=(const accessor &a) & { operator=(handle(a)); } + + template + void operator=(T &&value) && { + Policy::set(obj, key, object_or_cast(std::forward(value))); + } + template + void operator=(T &&value) & { + get_cache() = ensure_object(object_or_cast(std::forward(value))); + } + + template + PYBIND11_DEPRECATED( + "Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") + explicit + operator enable_if_t::value + || std::is_same::value, + bool>() const { + return hasattr(obj, key); + } + template + PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") + explicit + operator enable_if_t::value, bool>() const { + return obj.contains(key); + } + + // NOLINTNEXTLINE(google-explicit-constructor) + operator object() const { return get_cache(); } + PyObject *ptr() const { return get_cache().ptr(); } + template + T cast() const { + return get_cache().template cast(); + } + +private: + static object ensure_object(object &&o) { return std::move(o); } + static object ensure_object(handle h) { return reinterpret_borrow(h); } + + object &get_cache() const { + if (!cache) { + cache = Policy::get(obj, key); + } + return cache; + } + +private: + handle obj; + key_type key; + mutable object cache; +}; +PYBIND11_WARNING_POP + +PYBIND11_NAMESPACE_BEGIN(accessor_policies) +struct obj_attr { + using key_type = object; + static object get(handle obj, handle key) { return getattr(obj, key); } + static void set(handle obj, handle key, handle val) { setattr(obj, key, val); } +}; + +struct str_attr { + using key_type = const char *; + static object get(handle obj, const char *key) { return getattr(obj, key); } + static void set(handle obj, const char *key, handle val) { setattr(obj, key, val); } +}; + +struct generic_item { + using key_type = object; + + static object get(handle obj, handle key) { + PyObject *result = PyObject_GetItem(obj.ptr(), key.ptr()); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); + } + + static void set(handle obj, handle key, handle val) { + if (PyObject_SetItem(obj.ptr(), key.ptr(), val.ptr()) != 0) { + throw error_already_set(); + } + } +}; + +struct sequence_item { + using key_type = size_t; + + template ::value, int> = 0> + static object get(handle obj, const IdxType &index) { + PyObject *result = PySequence_GetItem(obj.ptr(), ssize_t_cast(index)); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); + } + + template ::value, int> = 0> + static void set(handle obj, const IdxType &index, handle val) { + // PySequence_SetItem does not steal a reference to 'val' + if (PySequence_SetItem(obj.ptr(), ssize_t_cast(index), val.ptr()) != 0) { + throw error_already_set(); + } + } +}; + +struct list_item { + using key_type = size_t; + + template ::value, int> = 0> + static object get(handle obj, const IdxType &index) { + PyObject *result = PyList_GetItem(obj.ptr(), ssize_t_cast(index)); + if (!result) { + throw error_already_set(); + } + return reinterpret_borrow(result); + } + + template ::value, int> = 0> + static void set(handle obj, const IdxType &index, handle val) { + // PyList_SetItem steals a reference to 'val' + if (PyList_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { + throw error_already_set(); + } + } +}; + +struct tuple_item { + using key_type = size_t; + + template ::value, int> = 0> + static object get(handle obj, const IdxType &index) { + PyObject *result = PyTuple_GetItem(obj.ptr(), ssize_t_cast(index)); + if (!result) { + throw error_already_set(); + } + return reinterpret_borrow(result); + } + + template ::value, int> = 0> + static void set(handle obj, const IdxType &index, handle val) { + // PyTuple_SetItem steals a reference to 'val' + if (PyTuple_SetItem(obj.ptr(), ssize_t_cast(index), val.inc_ref().ptr()) != 0) { + throw error_already_set(); + } + } +}; +PYBIND11_NAMESPACE_END(accessor_policies) + +/// STL iterator template used for tuple, list, sequence and dict +template +class generic_iterator : public Policy { + using It = generic_iterator; + +public: + using difference_type = ssize_t; + using iterator_category = typename Policy::iterator_category; + using value_type = typename Policy::value_type; + using reference = typename Policy::reference; + using pointer = typename Policy::pointer; + + generic_iterator() = default; + generic_iterator(handle seq, ssize_t index) : Policy(seq, index) {} + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference operator*() const { return Policy::dereference(); } + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference operator[](difference_type n) const { return *(*this + n); } + pointer operator->() const { return **this; } + + It &operator++() { + Policy::increment(); + return *this; + } + It operator++(int) { + auto copy = *this; + Policy::increment(); + return copy; + } + It &operator--() { + Policy::decrement(); + return *this; + } + It operator--(int) { + auto copy = *this; + Policy::decrement(); + return copy; + } + It &operator+=(difference_type n) { + Policy::advance(n); + return *this; + } + It &operator-=(difference_type n) { + Policy::advance(-n); + return *this; + } + + friend It operator+(const It &a, difference_type n) { + auto copy = a; + return copy += n; + } + friend It operator+(difference_type n, const It &b) { return b + n; } + friend It operator-(const It &a, difference_type n) { + auto copy = a; + return copy -= n; + } + friend difference_type operator-(const It &a, const It &b) { return a.distance_to(b); } + + friend bool operator==(const It &a, const It &b) { return a.equal(b); } + friend bool operator!=(const It &a, const It &b) { return !(a == b); } + friend bool operator<(const It &a, const It &b) { return b - a > 0; } + friend bool operator>(const It &a, const It &b) { return b < a; } + friend bool operator>=(const It &a, const It &b) { return !(a < b); } + friend bool operator<=(const It &a, const It &b) { return !(a > b); } +}; + +PYBIND11_NAMESPACE_BEGIN(iterator_policies) +/// Quick proxy class needed to implement ``operator->`` for iterators which can't return pointers +template +struct arrow_proxy { + T value; + + // NOLINTNEXTLINE(google-explicit-constructor) + arrow_proxy(T &&value) noexcept : value(std::move(value)) {} + T *operator->() const { return &value; } +}; + +/// Lightweight iterator policy using just a simple pointer: see ``PySequence_Fast_ITEMS`` +class sequence_fast_readonly { +protected: + using iterator_category = std::random_access_iterator_tag; + using value_type = handle; + using reference = const handle; // PR #3263 + using pointer = arrow_proxy; + + sequence_fast_readonly(handle obj, ssize_t n) : ptr(PySequence_Fast_ITEMS(obj.ptr()) + n) {} + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference dereference() const { return *ptr; } + void increment() { ++ptr; } + void decrement() { --ptr; } + void advance(ssize_t n) { ptr += n; } + bool equal(const sequence_fast_readonly &b) const { return ptr == b.ptr; } + ssize_t distance_to(const sequence_fast_readonly &b) const { return ptr - b.ptr; } + +private: + PyObject **ptr; +}; + +/// Full read and write access using the sequence protocol: see ``detail::sequence_accessor`` +class sequence_slow_readwrite { +protected: + using iterator_category = std::random_access_iterator_tag; + using value_type = object; + using reference = sequence_accessor; + using pointer = arrow_proxy; + + sequence_slow_readwrite(handle obj, ssize_t index) : obj(obj), index(index) {} + + reference dereference() const { return {obj, static_cast(index)}; } + void increment() { ++index; } + void decrement() { --index; } + void advance(ssize_t n) { index += n; } + bool equal(const sequence_slow_readwrite &b) const { return index == b.index; } + ssize_t distance_to(const sequence_slow_readwrite &b) const { return index - b.index; } + +private: + handle obj; + ssize_t index; +}; + +/// Python's dictionary protocol permits this to be a forward iterator +class dict_readonly { +protected: + using iterator_category = std::forward_iterator_tag; + using value_type = std::pair; + using reference = const value_type; // PR #3263 + using pointer = arrow_proxy; + + dict_readonly() = default; + dict_readonly(handle obj, ssize_t pos) : obj(obj), pos(pos) { increment(); } + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference dereference() const { return {key, value}; } + void increment() { + if (PyDict_Next(obj.ptr(), &pos, &key, &value) == 0) { + pos = -1; + } + } + bool equal(const dict_readonly &b) const { return pos == b.pos; } + +private: + handle obj; + PyObject *key = nullptr, *value = nullptr; + ssize_t pos = -1; +}; +PYBIND11_NAMESPACE_END(iterator_policies) + +#if !defined(PYPY_VERSION) +using tuple_iterator = generic_iterator; +using list_iterator = generic_iterator; +#else +using tuple_iterator = generic_iterator; +using list_iterator = generic_iterator; +#endif + +using sequence_iterator = generic_iterator; +using dict_iterator = generic_iterator; + +inline bool PyIterable_Check(PyObject *obj) { + PyObject *iter = PyObject_GetIter(obj); + if (iter) { + Py_DECREF(iter); + return true; + } + PyErr_Clear(); + return false; +} + +inline bool PyNone_Check(PyObject *o) { return o == Py_None; } +inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; } + +#ifdef PYBIND11_STR_LEGACY_PERMISSIVE +inline bool PyUnicode_Check_Permissive(PyObject *o) { + return PyUnicode_Check(o) || PYBIND11_BYTES_CHECK(o); +} +# define PYBIND11_STR_CHECK_FUN detail::PyUnicode_Check_Permissive +#else +# define PYBIND11_STR_CHECK_FUN PyUnicode_Check +#endif + +inline bool PyStaticMethod_Check(PyObject *o) { return o->ob_type == &PyStaticMethod_Type; } + +class kwargs_proxy : public handle { +public: + explicit kwargs_proxy(handle h) : handle(h) {} +}; + +class args_proxy : public handle { +public: + explicit args_proxy(handle h) : handle(h) {} + kwargs_proxy operator*() const { return kwargs_proxy(*this); } +}; + +/// Python argument categories (using PEP 448 terms) +template +using is_keyword = std::is_base_of; +template +using is_s_unpacking = std::is_same; // * unpacking +template +using is_ds_unpacking = std::is_same; // ** unpacking +template +using is_positional = satisfies_none_of; +template +using is_keyword_or_ds = satisfies_any_of; + +// Call argument collector forward declarations +template +class simple_collector; +template +class unpacking_collector; + +PYBIND11_NAMESPACE_END(detail) + +// TODO: After the deprecated constructors are removed, this macro can be simplified by +// inheriting ctors: `using Parent::Parent`. It's not an option right now because +// the `using` statement triggers the parent deprecation warning even if the ctor +// isn't even used. +#define PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ +public: \ + PYBIND11_DEPRECATED("Use reinterpret_borrow<" #Name ">() or reinterpret_steal<" #Name ">()") \ + Name(handle h, bool is_borrowed) \ + : Parent(is_borrowed ? Parent(h, borrowed_t{}) : Parent(h, stolen_t{})) {} \ + Name(handle h, borrowed_t) : Parent(h, borrowed_t{}) {} \ + Name(handle h, stolen_t) : Parent(h, stolen_t{}) {} \ + PYBIND11_DEPRECATED("Use py::isinstance(obj) instead") \ + bool check() const { return m_ptr != nullptr && (CheckFun(m_ptr) != 0); } \ + static bool check_(handle h) { return h.ptr() != nullptr && CheckFun(h.ptr()); } \ + template /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(const ::pybind11::detail::accessor &a) : Name(object(a)) {} + +#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ + PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ + /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(const object &o) \ + : Parent(check_(o) ? o.inc_ref().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \ + if (!m_ptr) \ + throw ::pybind11::error_already_set(); \ + } \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(object &&o) : Parent(check_(o) ? o.release().ptr() : ConvertFun(o.ptr()), stolen_t{}) { \ + if (!m_ptr) \ + throw ::pybind11::error_already_set(); \ + } + +#define PYBIND11_OBJECT_CVT_DEFAULT(Name, Parent, CheckFun, ConvertFun) \ + PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun) \ + Name() = default; + +#define PYBIND11_OBJECT_CHECK_FAILED(Name, o_ptr) \ + ::pybind11::type_error("Object of type '" \ + + ::pybind11::detail::get_fully_qualified_tp_name(Py_TYPE(o_ptr)) \ + + "' is not an instance of '" #Name "'") + +#define PYBIND11_OBJECT(Name, Parent, CheckFun) \ + PYBIND11_OBJECT_COMMON(Name, Parent, CheckFun) \ + /* This is deliberately not 'explicit' to allow implicit conversion from object: */ \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(const object &o) : Parent(o) { \ + if (m_ptr && !check_(m_ptr)) \ + throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \ + } \ + /* NOLINTNEXTLINE(google-explicit-constructor) */ \ + Name(object &&o) : Parent(std::move(o)) { \ + if (m_ptr && !check_(m_ptr)) \ + throw PYBIND11_OBJECT_CHECK_FAILED(Name, m_ptr); \ + } + +#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun) \ + PYBIND11_OBJECT(Name, Parent, CheckFun) \ + Name() = default; + +/// \addtogroup pytypes +/// @{ + +/** \rst + Wraps a Python iterator so that it can also be used as a C++ input iterator + + Caveat: copying an iterator does not (and cannot) clone the internal + state of the Python iterable. This also applies to the post-increment + operator. This iterator should only be used to retrieve the current + value using ``operator*()``. +\endrst */ +class iterator : public object { +public: + using iterator_category = std::input_iterator_tag; + using difference_type = ssize_t; + using value_type = handle; + using reference = const handle; // PR #3263 + using pointer = const handle *; + + PYBIND11_OBJECT_DEFAULT(iterator, object, PyIter_Check) + + iterator &operator++() { + advance(); + return *this; + } + + iterator operator++(int) { + auto rv = *this; + advance(); + return rv; + } + + // NOLINTNEXTLINE(readability-const-return-type) // PR #3263 + reference operator*() const { + if (m_ptr && !value.ptr()) { + auto &self = const_cast(*this); + self.advance(); + } + return value; + } + + pointer operator->() const { + operator*(); + return &value; + } + + /** \rst + The value which marks the end of the iteration. ``it == iterator::sentinel()`` + is equivalent to catching ``StopIteration`` in Python. + + .. code-block:: cpp + + void foo(py::iterator it) { + while (it != py::iterator::sentinel()) { + // use `*it` + ++it; + } + } + \endrst */ + static iterator sentinel() { return {}; } + + friend bool operator==(const iterator &a, const iterator &b) { return a->ptr() == b->ptr(); } + friend bool operator!=(const iterator &a, const iterator &b) { return a->ptr() != b->ptr(); } + +private: + void advance() { + value = reinterpret_steal(PyIter_Next(m_ptr)); + if (value.ptr() == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + } + +private: + object value = {}; +}; + +class type : public object { +public: + PYBIND11_OBJECT(type, object, PyType_Check) + + /// Return a type handle from a handle or an object + static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); } + + /// Return a type object from a handle or an object + static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); } + + // Defined in pybind11/cast.h + /// Convert C++ type to handle if previously registered. Does not convert + /// standard types, like int, float. etc. yet. + /// See https://github.com/pybind/pybind11/issues/2486 + template + static handle handle_of(); + + /// Convert C++ type to type if previously registered. Does not convert + /// standard types, like int, float. etc. yet. + /// See https://github.com/pybind/pybind11/issues/2486 + template + static type of() { + return type(type::handle_of(), borrowed_t{}); + } +}; + +class iterable : public object { +public: + PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check) +}; + +class bytes; + +class str : public object { +public: + PYBIND11_OBJECT_CVT(str, object, PYBIND11_STR_CHECK_FUN, raw_str) + + template ::value, int> = 0> + str(const char *c, const SzType &n) + : object(PyUnicode_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { + if (!m_ptr) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate string object!"); + } + } + + // 'explicit' is explicitly omitted from the following constructors to allow implicit + // conversion to py::str from C++ string-like objects + // NOLINTNEXTLINE(google-explicit-constructor) + str(const char *c = "") : object(PyUnicode_FromString(c), stolen_t{}) { + if (!m_ptr) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate string object!"); + } + } + + // NOLINTNEXTLINE(google-explicit-constructor) + str(const std::string &s) : str(s.data(), s.size()) {} + +#ifdef PYBIND11_HAS_STRING_VIEW + // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + str(T s) : str(s.data(), s.size()) {} + +# ifdef PYBIND11_HAS_U8STRING + // reinterpret_cast here is safe (C++20 guarantees char8_t has the same size/alignment as char) + // NOLINTNEXTLINE(google-explicit-constructor) + str(std::u8string_view s) : str(reinterpret_cast(s.data()), s.size()) {} +# endif + +#endif + + explicit str(const bytes &b); + + /** \rst + Return a string representation of the object. This is analogous to + the ``str()`` function in Python. + \endrst */ + explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::string() const { + object temp = *this; + if (PyUnicode_Check(m_ptr)) { + temp = reinterpret_steal(PyUnicode_AsUTF8String(m_ptr)); + if (!temp) { + throw error_already_set(); + } + } + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) { + throw error_already_set(); + } + return std::string(buffer, (size_t) length); + } + + template + str format(Args &&...args) const { + return attr("format")(std::forward(args)...); + } + +private: + /// Return string representation -- always returns a new reference, even if already a str + static PyObject *raw_str(PyObject *op) { + PyObject *str_value = PyObject_Str(op); + return str_value; + } +}; +/// @} pytypes + +inline namespace literals { +/** \rst + String literal version of `str` + \endrst */ +inline str +#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5 +operator"" _s // gcc 4.8.5 insists on having a space (hard error). +#else +operator""_s // clang 17 generates a deprecation warning if there is a space. +#endif + (const char *s, size_t size) { + return {s, size}; +} +} // namespace literals + +/// \addtogroup pytypes +/// @{ +class bytes : public object { +public: + PYBIND11_OBJECT(bytes, object, PYBIND11_BYTES_CHECK) + + // Allow implicit conversion: + // NOLINTNEXTLINE(google-explicit-constructor) + bytes(const char *c = "") : object(PYBIND11_BYTES_FROM_STRING(c), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate bytes object!"); + } + } + + template ::value, int> = 0> + bytes(const char *c, const SzType &n) + : object(PYBIND11_BYTES_FROM_STRING_AND_SIZE(c, ssize_t_cast(n)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate bytes object!"); + } + } + + // Allow implicit conversion: + // NOLINTNEXTLINE(google-explicit-constructor) + bytes(const std::string &s) : bytes(s.data(), s.size()) {} + + explicit bytes(const pybind11::str &s); + + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::string() const { return string_op(); } + +#ifdef PYBIND11_HAS_STRING_VIEW + // enable_if is needed to avoid "ambiguous conversion" errors (see PR #3521). + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + bytes(T s) : bytes(s.data(), s.size()) {} + + // Obtain a string view that views the current `bytes` buffer value. Note that this is only + // valid so long as the `bytes` instance remains alive and so generally should not outlive the + // lifetime of the `bytes` instance. + // NOLINTNEXTLINE(google-explicit-constructor) + operator std::string_view() const { return string_op(); } +#endif +private: + template + T string_op() const { + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(m_ptr, &buffer, &length) != 0) { + throw error_already_set(); + } + return {buffer, static_cast(length)}; + } +}; +// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors +// are included in the doxygen group; close here and reopen after as a workaround +/// @} pytypes + +inline bytes::bytes(const pybind11::str &s) { + object temp = s; + if (PyUnicode_Check(s.ptr())) { + temp = reinterpret_steal(PyUnicode_AsUTF8String(s.ptr())); + if (!temp) { + throw error_already_set(); + } + } + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) { + throw error_already_set(); + } + auto obj = reinterpret_steal(PYBIND11_BYTES_FROM_STRING_AND_SIZE(buffer, length)); + if (!obj) { + pybind11_fail("Could not allocate bytes object!"); + } + m_ptr = obj.release().ptr(); +} + +inline str::str(const bytes &b) { + char *buffer = nullptr; + ssize_t length = 0; + if (PyBytes_AsStringAndSize(b.ptr(), &buffer, &length) != 0) { + throw error_already_set(); + } + auto obj = reinterpret_steal(PyUnicode_FromStringAndSize(buffer, length)); + if (!obj) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate string object!"); + } + m_ptr = obj.release().ptr(); +} + +/// \addtogroup pytypes +/// @{ +class bytearray : public object { +public: + PYBIND11_OBJECT_CVT(bytearray, object, PyByteArray_Check, PyByteArray_FromObject) + + template ::value, int> = 0> + bytearray(const char *c, const SzType &n) + : object(PyByteArray_FromStringAndSize(c, ssize_t_cast(n)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate bytearray object!"); + } + } + + bytearray() : bytearray("", 0) {} + + explicit bytearray(const std::string &s) : bytearray(s.data(), s.size()) {} + + size_t size() const { return static_cast(PyByteArray_Size(m_ptr)); } + + explicit operator std::string() const { + char *buffer = PyByteArray_AS_STRING(m_ptr); + ssize_t size = PyByteArray_GET_SIZE(m_ptr); + return std::string(buffer, static_cast(size)); + } +}; +// Note: breathe >= 4.17.0 will fail to build docs if the below two constructors +// are included in the doxygen group; close here and reopen after as a workaround +/// @} pytypes + +/// \addtogroup pytypes +/// @{ +class none : public object { +public: + PYBIND11_OBJECT(none, object, detail::PyNone_Check) + none() : object(Py_None, borrowed_t{}) {} +}; + +class ellipsis : public object { +public: + PYBIND11_OBJECT(ellipsis, object, detail::PyEllipsis_Check) + ellipsis() : object(Py_Ellipsis, borrowed_t{}) {} +}; + +class bool_ : public object { +public: + PYBIND11_OBJECT_CVT(bool_, object, PyBool_Check, raw_bool) + bool_() : object(Py_False, borrowed_t{}) {} + // Allow implicit conversion from and to `bool`: + // NOLINTNEXTLINE(google-explicit-constructor) + bool_(bool value) : object(value ? Py_True : Py_False, borrowed_t{}) {} + // NOLINTNEXTLINE(google-explicit-constructor) + operator bool() const { return (m_ptr != nullptr) && PyLong_AsLong(m_ptr) != 0; } + +private: + /// Return the truth value of an object -- always returns a new reference + static PyObject *raw_bool(PyObject *op) { + const auto value = PyObject_IsTrue(op); + if (value == -1) { + return nullptr; + } + return handle(value != 0 ? Py_True : Py_False).inc_ref().ptr(); + } +}; + +PYBIND11_NAMESPACE_BEGIN(detail) +// Converts a value to the given unsigned type. If an error occurs, you get back (Unsigned) -1; +// otherwise you get back the unsigned long or unsigned long long value cast to (Unsigned). +// (The distinction is critically important when casting a returned -1 error value to some other +// unsigned type: (A)-1 != (B)-1 when A and B are unsigned types of different sizes). +template +Unsigned as_unsigned(PyObject *o) { + if (sizeof(Unsigned) <= sizeof(unsigned long)) { + unsigned long v = PyLong_AsUnsignedLong(o); + return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; + } + unsigned long long v = PyLong_AsUnsignedLongLong(o); + return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v; +} +PYBIND11_NAMESPACE_END(detail) + +class int_ : public object { +public: + PYBIND11_OBJECT_CVT(int_, object, PYBIND11_LONG_CHECK, PyNumber_Long) + int_() : object(PyLong_FromLong(0), stolen_t{}) {} + // Allow implicit conversion from C++ integral types: + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + int_(T value) { + if (sizeof(T) <= sizeof(long)) { + if (std::is_signed::value) { + m_ptr = PyLong_FromLong((long) value); + } else { + m_ptr = PyLong_FromUnsignedLong((unsigned long) value); + } + } else { + if (std::is_signed::value) { + m_ptr = PyLong_FromLongLong((long long) value); + } else { + m_ptr = PyLong_FromUnsignedLongLong((unsigned long long) value); + } + } + if (!m_ptr) { + pybind11_fail("Could not allocate int object!"); + } + } + + template ::value, int> = 0> + // NOLINTNEXTLINE(google-explicit-constructor) + operator T() const { + return std::is_unsigned::value ? detail::as_unsigned(m_ptr) + : sizeof(T) <= sizeof(long) ? (T) PyLong_AsLong(m_ptr) + : (T) PYBIND11_LONG_AS_LONGLONG(m_ptr); + } +}; + +class float_ : public object { +public: + PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float) + // Allow implicit conversion from float/double: + // NOLINTNEXTLINE(google-explicit-constructor) + float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate float object!"); + } + } + // NOLINTNEXTLINE(google-explicit-constructor) + float_(double value = .0) : object(PyFloat_FromDouble((double) value), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate float object!"); + } + } + // NOLINTNEXTLINE(google-explicit-constructor) + operator float() const { return (float) PyFloat_AsDouble(m_ptr); } + // NOLINTNEXTLINE(google-explicit-constructor) + operator double() const { return (double) PyFloat_AsDouble(m_ptr); } +}; + +class weakref : public object { +public: + PYBIND11_OBJECT_CVT_DEFAULT(weakref, object, PyWeakref_Check, raw_weakref) + explicit weakref(handle obj, handle callback = {}) + : object(PyWeakref_NewRef(obj.ptr(), callback.ptr()), stolen_t{}) { + if (!m_ptr) { + if (PyErr_Occurred()) { + throw error_already_set(); + } + pybind11_fail("Could not allocate weak reference!"); + } + } + +private: + static PyObject *raw_weakref(PyObject *o) { return PyWeakref_NewRef(o, nullptr); } +}; + +class slice : public object { +public: + PYBIND11_OBJECT_DEFAULT(slice, object, PySlice_Check) + slice(handle start, handle stop, handle step) + : object(PySlice_New(start.ptr(), stop.ptr(), step.ptr()), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate slice object!"); + } + } + +#ifdef PYBIND11_HAS_OPTIONAL + slice(std::optional start, std::optional stop, std::optional step) + : slice(index_to_object(start), index_to_object(stop), index_to_object(step)) {} +#else + slice(ssize_t start_, ssize_t stop_, ssize_t step_) + : slice(int_(start_), int_(stop_), int_(step_)) {} +#endif + + bool + compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const { + return PySlice_GetIndicesEx((PYBIND11_SLICE_OBJECT *) m_ptr, + (ssize_t) length, + (ssize_t *) start, + (ssize_t *) stop, + (ssize_t *) step, + (ssize_t *) slicelength) + == 0; + } + bool compute( + ssize_t length, ssize_t *start, ssize_t *stop, ssize_t *step, ssize_t *slicelength) const { + return PySlice_GetIndicesEx( + (PYBIND11_SLICE_OBJECT *) m_ptr, length, start, stop, step, slicelength) + == 0; + } + +private: + template + static object index_to_object(T index) { + return index ? object(int_(*index)) : object(none()); + } +}; + +class capsule : public object { +public: + PYBIND11_OBJECT_DEFAULT(capsule, object, PyCapsule_CheckExact) + PYBIND11_DEPRECATED("Use reinterpret_borrow() or reinterpret_steal()") + capsule(PyObject *ptr, bool is_borrowed) + : object(is_borrowed ? object(ptr, borrowed_t{}) : object(ptr, stolen_t{})) {} + + explicit capsule(const void *value, + const char *name = nullptr, + PyCapsule_Destructor destructor = nullptr) + : object(PyCapsule_New(const_cast(value), name, destructor), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + PYBIND11_DEPRECATED("Please use the ctor with value, name, destructor args") + capsule(const void *value, PyCapsule_Destructor destructor) + : object(PyCapsule_New(const_cast(value), nullptr, destructor), stolen_t{}) { + if (!m_ptr) { + throw error_already_set(); + } + } + + /// Capsule name is nullptr. + capsule(const void *value, void (*destructor)(void *)) { + initialize_with_void_ptr_destructor(value, nullptr, destructor); + } + + capsule(const void *value, const char *name, void (*destructor)(void *)) { + initialize_with_void_ptr_destructor(value, name, destructor); + } + + explicit capsule(void (*destructor)()) { + m_ptr = PyCapsule_New(reinterpret_cast(destructor), nullptr, [](PyObject *o) { + const char *name = get_name_in_error_scope(o); + auto destructor = reinterpret_cast(PyCapsule_GetPointer(o, name)); + if (destructor == nullptr) { + throw error_already_set(); + } + destructor(); + }); + + if (!m_ptr) { + throw error_already_set(); + } + } + + template + operator T *() const { // NOLINT(google-explicit-constructor) + return get_pointer(); + } + + /// Get the pointer the capsule holds. + template + T *get_pointer() const { + const auto *name = this->name(); + T *result = static_cast(PyCapsule_GetPointer(m_ptr, name)); + if (!result) { + throw error_already_set(); + } + return result; + } + + /// Replaces a capsule's pointer *without* calling the destructor on the existing one. + void set_pointer(const void *value) { + if (PyCapsule_SetPointer(m_ptr, const_cast(value)) != 0) { + throw error_already_set(); + } + } + + const char *name() const { + const char *name = PyCapsule_GetName(m_ptr); + if ((name == nullptr) && PyErr_Occurred()) { + throw error_already_set(); + } + return name; + } + + /// Replaces a capsule's name *without* calling the destructor on the existing one. + void set_name(const char *new_name) { + if (PyCapsule_SetName(m_ptr, new_name) != 0) { + throw error_already_set(); + } + } + +private: + static const char *get_name_in_error_scope(PyObject *o) { + error_scope error_guard; + + const char *name = PyCapsule_GetName(o); + if ((name == nullptr) && PyErr_Occurred()) { + // write out and consume error raised by call to PyCapsule_GetName + PyErr_WriteUnraisable(o); + } + + return name; + } + + void initialize_with_void_ptr_destructor(const void *value, + const char *name, + void (*destructor)(void *)) { + m_ptr = PyCapsule_New(const_cast(value), name, [](PyObject *o) { + // guard if destructor called while err indicator is set + error_scope error_guard; + auto destructor = reinterpret_cast(PyCapsule_GetContext(o)); + if (destructor == nullptr && PyErr_Occurred()) { + throw error_already_set(); + } + const char *name = get_name_in_error_scope(o); + void *ptr = PyCapsule_GetPointer(o, name); + if (ptr == nullptr) { + throw error_already_set(); + } + + if (destructor != nullptr) { + destructor(ptr); + } + }); + + if (!m_ptr || PyCapsule_SetContext(m_ptr, reinterpret_cast(destructor)) != 0) { + throw error_already_set(); + } + } +}; + +class tuple : public object { +public: + PYBIND11_OBJECT_CVT(tuple, object, PyTuple_Check, PySequence_Tuple) + template ::value, int> = 0> + // Some compilers generate link errors when using `const SzType &` here: + explicit tuple(SzType size = 0) : object(PyTuple_New(ssize_t_cast(size)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate tuple object!"); + } + } + size_t size() const { return (size_t) PyTuple_Size(m_ptr); } + bool empty() const { return size() == 0; } + detail::tuple_accessor operator[](size_t index) const { return {*this, index}; } + template ::value, int> = 0> + detail::item_accessor operator[](T &&o) const { + return object::operator[](std::forward(o)); + } + detail::tuple_iterator begin() const { return {*this, 0}; } + detail::tuple_iterator end() const { return {*this, PyTuple_GET_SIZE(m_ptr)}; } +}; + +// We need to put this into a separate function because the Intel compiler +// fails to compile enable_if_t...>::value> part below +// (tested with ICC 2021.1 Beta 20200827). +template +constexpr bool args_are_all_keyword_or_ds() { + return detail::all_of...>::value; +} + +class dict : public object { +public: + PYBIND11_OBJECT_CVT(dict, object, PyDict_Check, raw_dict) + dict() : object(PyDict_New(), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate dict object!"); + } + } + template ()>, + // MSVC workaround: it can't compile an out-of-line definition, so defer the + // collector + typename collector = detail::deferred_t, Args...>> + explicit dict(Args &&...args) : dict(collector(std::forward(args)...).kwargs()) {} + + size_t size() const { return (size_t) PyDict_Size(m_ptr); } + bool empty() const { return size() == 0; } + detail::dict_iterator begin() const { return {*this, 0}; } + detail::dict_iterator end() const { return {}; } + void clear() /* py-non-const */ { PyDict_Clear(ptr()); } + template + bool contains(T &&key) const { + auto result = PyDict_Contains(m_ptr, detail::object_or_cast(std::forward(key)).ptr()); + if (result == -1) { + throw error_already_set(); + } + return result == 1; + } + +private: + /// Call the `dict` Python type -- always returns a new reference + static PyObject *raw_dict(PyObject *op) { + if (PyDict_Check(op)) { + return handle(op).inc_ref().ptr(); + } + return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr); + } +}; + +class sequence : public object { +public: + PYBIND11_OBJECT_DEFAULT(sequence, object, PySequence_Check) + size_t size() const { + ssize_t result = PySequence_Size(m_ptr); + if (result == -1) { + throw error_already_set(); + } + return (size_t) result; + } + bool empty() const { return size() == 0; } + detail::sequence_accessor operator[](size_t index) const { return {*this, index}; } + template ::value, int> = 0> + detail::item_accessor operator[](T &&o) const { + return object::operator[](std::forward(o)); + } + detail::sequence_iterator begin() const { return {*this, 0}; } + detail::sequence_iterator end() const { return {*this, PySequence_Size(m_ptr)}; } +}; + +class list : public object { +public: + PYBIND11_OBJECT_CVT(list, object, PyList_Check, PySequence_List) + template ::value, int> = 0> + // Some compilers generate link errors when using `const SzType &` here: + explicit list(SzType size = 0) : object(PyList_New(ssize_t_cast(size)), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate list object!"); + } + } + size_t size() const { return (size_t) PyList_Size(m_ptr); } + bool empty() const { return size() == 0; } + detail::list_accessor operator[](size_t index) const { return {*this, index}; } + template ::value, int> = 0> + detail::item_accessor operator[](T &&o) const { + return object::operator[](std::forward(o)); + } + detail::list_iterator begin() const { return {*this, 0}; } + detail::list_iterator end() const { return {*this, PyList_GET_SIZE(m_ptr)}; } + template + void append(T &&val) /* py-non-const */ { + if (PyList_Append(m_ptr, detail::object_or_cast(std::forward(val)).ptr()) != 0) { + throw error_already_set(); + } + } + template ::value, int> = 0> + void insert(const IdxType &index, ValType &&val) /* py-non-const */ { + if (PyList_Insert(m_ptr, + ssize_t_cast(index), + detail::object_or_cast(std::forward(val)).ptr()) + != 0) { + throw error_already_set(); + } + } +}; + +class args : public tuple { + PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) +}; +class kwargs : public dict { + PYBIND11_OBJECT_DEFAULT(kwargs, dict, PyDict_Check) +}; + +class anyset : public object { +public: + PYBIND11_OBJECT(anyset, object, PyAnySet_Check) + size_t size() const { return static_cast(PySet_Size(m_ptr)); } + bool empty() const { return size() == 0; } + template + bool contains(T &&val) const { + auto result = PySet_Contains(m_ptr, detail::object_or_cast(std::forward(val)).ptr()); + if (result == -1) { + throw error_already_set(); + } + return result == 1; + } +}; + +class set : public anyset { +public: + PYBIND11_OBJECT_CVT(set, anyset, PySet_Check, PySet_New) + set() : anyset(PySet_New(nullptr), stolen_t{}) { + if (!m_ptr) { + pybind11_fail("Could not allocate set object!"); + } + } + template + bool add(T &&val) /* py-non-const */ { + return PySet_Add(m_ptr, detail::object_or_cast(std::forward(val)).ptr()) == 0; + } + void clear() /* py-non-const */ { PySet_Clear(m_ptr); } +}; + +class frozenset : public anyset { +public: + PYBIND11_OBJECT_CVT(frozenset, anyset, PyFrozenSet_Check, PyFrozenSet_New) +}; + +class function : public object { +public: + PYBIND11_OBJECT_DEFAULT(function, object, PyCallable_Check) + handle cpp_function() const { + handle fun = detail::get_function(m_ptr); + if (fun && PyCFunction_Check(fun.ptr())) { + return fun; + } + return handle(); + } + bool is_cpp_function() const { return (bool) cpp_function(); } +}; + +class staticmethod : public object { +public: + PYBIND11_OBJECT_CVT(staticmethod, object, detail::PyStaticMethod_Check, PyStaticMethod_New) +}; + +class buffer : public object { +public: + PYBIND11_OBJECT_DEFAULT(buffer, object, PyObject_CheckBuffer) + + buffer_info request(bool writable = false) const { + int flags = PyBUF_STRIDES | PyBUF_FORMAT; + if (writable) { + flags |= PyBUF_WRITABLE; + } + auto *view = new Py_buffer(); + if (PyObject_GetBuffer(m_ptr, view, flags) != 0) { + delete view; + throw error_already_set(); + } + return buffer_info(view); + } +}; + +class memoryview : public object { +public: + PYBIND11_OBJECT_CVT(memoryview, object, PyMemoryView_Check, PyMemoryView_FromObject) + + /** \rst + Creates ``memoryview`` from ``buffer_info``. + + ``buffer_info`` must be created from ``buffer::request()``. Otherwise + throws an exception. + + For creating a ``memoryview`` from objects that support buffer protocol, + use ``memoryview(const object& obj)`` instead of this constructor. + \endrst */ + explicit memoryview(const buffer_info &info) { + if (!info.view()) { + pybind11_fail("Prohibited to create memoryview without Py_buffer"); + } + // Note: PyMemoryView_FromBuffer never increments obj reference. + m_ptr = (info.view()->obj) ? PyMemoryView_FromObject(info.view()->obj) + : PyMemoryView_FromBuffer(info.view()); + if (!m_ptr) { + pybind11_fail("Unable to create memoryview from buffer descriptor"); + } + } + + /** \rst + Creates ``memoryview`` from static buffer. + + This method is meant for providing a ``memoryview`` for C/C++ buffer not + managed by Python. The caller is responsible for managing the lifetime + of ``ptr`` and ``format``, which MUST outlive the memoryview constructed + here. + + See also: Python C API documentation for `PyMemoryView_FromBuffer`_. + + .. _PyMemoryView_FromBuffer: + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromBuffer + + :param ptr: Pointer to the buffer. + :param itemsize: Byte size of an element. + :param format: Pointer to the null-terminated format string. For + homogeneous Buffers, this should be set to + ``format_descriptor::value``. + :param shape: Shape of the tensor (1 entry per dimension). + :param strides: Number of bytes between adjacent entries (for each + per dimension). + :param readonly: Flag to indicate if the underlying storage may be + written to. + \endrst */ + static memoryview from_buffer(void *ptr, + ssize_t itemsize, + const char *format, + detail::any_container shape, + detail::any_container strides, + bool readonly = false); + + static memoryview from_buffer(const void *ptr, + ssize_t itemsize, + const char *format, + detail::any_container shape, + detail::any_container strides) { + return memoryview::from_buffer( + const_cast(ptr), itemsize, format, std::move(shape), std::move(strides), true); + } + + template + static memoryview from_buffer(T *ptr, + detail::any_container shape, + detail::any_container strides, + bool readonly = false) { + return memoryview::from_buffer(reinterpret_cast(ptr), + sizeof(T), + format_descriptor::value, + std::move(shape), + std::move(strides), + readonly); + } + + template + static memoryview from_buffer(const T *ptr, + detail::any_container shape, + detail::any_container strides) { + return memoryview::from_buffer( + const_cast(ptr), std::move(shape), std::move(strides), true); + } + + /** \rst + Creates ``memoryview`` from static memory. + + This method is meant for providing a ``memoryview`` for C/C++ buffer not + managed by Python. The caller is responsible for managing the lifetime + of ``mem``, which MUST outlive the memoryview constructed here. + + See also: Python C API documentation for `PyMemoryView_FromBuffer`_. + + .. _PyMemoryView_FromMemory: + https://docs.python.org/c-api/memoryview.html#c.PyMemoryView_FromMemory + \endrst */ + static memoryview from_memory(void *mem, ssize_t size, bool readonly = false) { + PyObject *ptr = PyMemoryView_FromMemory( + reinterpret_cast(mem), size, (readonly) ? PyBUF_READ : PyBUF_WRITE); + if (!ptr) { + pybind11_fail("Could not allocate memoryview object!"); + } + return memoryview(object(ptr, stolen_t{})); + } + + static memoryview from_memory(const void *mem, ssize_t size) { + return memoryview::from_memory(const_cast(mem), size, true); + } + +#ifdef PYBIND11_HAS_STRING_VIEW + static memoryview from_memory(std::string_view mem) { + return from_memory(const_cast(mem.data()), static_cast(mem.size()), true); + } +#endif +}; + +/// @cond DUPLICATE +inline memoryview memoryview::from_buffer(void *ptr, + ssize_t itemsize, + const char *format, + detail::any_container shape, + detail::any_container strides, + bool readonly) { + size_t ndim = shape->size(); + if (ndim != strides->size()) { + pybind11_fail("memoryview: shape length doesn't match strides length"); + } + ssize_t size = ndim != 0u ? 1 : 0; + for (size_t i = 0; i < ndim; ++i) { + size *= (*shape)[i]; + } + Py_buffer view; + view.buf = ptr; + view.obj = nullptr; + view.len = size * itemsize; + view.readonly = static_cast(readonly); + view.itemsize = itemsize; + view.format = const_cast(format); + view.ndim = static_cast(ndim); + view.shape = shape->data(); + view.strides = strides->data(); + view.suboffsets = nullptr; + view.internal = nullptr; + PyObject *obj = PyMemoryView_FromBuffer(&view); + if (!obj) { + throw error_already_set(); + } + return memoryview(object(obj, stolen_t{})); +} +/// @endcond +/// @} pytypes + +/// \addtogroup python_builtins +/// @{ + +/// Get the length of a Python object. +inline size_t len(handle h) { + ssize_t result = PyObject_Length(h.ptr()); + if (result < 0) { + throw error_already_set(); + } + return (size_t) result; +} + +/// Get the length hint of a Python object. +/// Returns 0 when this cannot be determined. +inline size_t len_hint(handle h) { + ssize_t result = PyObject_LengthHint(h.ptr(), 0); + if (result < 0) { + // Sometimes a length can't be determined at all (eg generators) + // In which case simply return 0 + PyErr_Clear(); + return 0; + } + return (size_t) result; +} + +inline str repr(handle h) { + PyObject *str_value = PyObject_Repr(h.ptr()); + if (!str_value) { + throw error_already_set(); + } + return reinterpret_steal(str_value); +} + +inline iterator iter(handle obj) { + PyObject *result = PyObject_GetIter(obj.ptr()); + if (!result) { + throw error_already_set(); + } + return reinterpret_steal(result); +} +/// @} python_builtins + +PYBIND11_NAMESPACE_BEGIN(detail) +template +iterator object_api::begin() const { + return iter(derived()); +} +template +iterator object_api::end() const { + return iterator::sentinel(); +} +template +item_accessor object_api::operator[](handle key) const { + return {derived(), reinterpret_borrow(key)}; +} +template +item_accessor object_api::operator[](object &&key) const { + return {derived(), std::move(key)}; +} +template +item_accessor object_api::operator[](const char *key) const { + return {derived(), pybind11::str(key)}; +} +template +obj_attr_accessor object_api::attr(handle key) const { + return {derived(), reinterpret_borrow(key)}; +} +template +obj_attr_accessor object_api::attr(object &&key) const { + return {derived(), std::move(key)}; +} +template +str_attr_accessor object_api::attr(const char *key) const { + return {derived(), key}; +} +template +args_proxy object_api::operator*() const { + return args_proxy(derived().ptr()); +} +template +template +bool object_api::contains(T &&item) const { + return attr("__contains__")(std::forward(item)).template cast(); +} + +template +pybind11::str object_api::str() const { + return pybind11::str(derived()); +} + +template +str_attr_accessor object_api::doc() const { + return attr("__doc__"); +} + +template +handle object_api::get_type() const { + return type::handle_of(derived()); +} + +template +bool object_api::rich_compare(object_api const &other, int value) const { + int rv = PyObject_RichCompareBool(derived().ptr(), other.derived().ptr(), value); + if (rv == -1) { + throw error_already_set(); + } + return rv == 1; +} + +#define PYBIND11_MATH_OPERATOR_UNARY(op, fn) \ + template \ + object object_api::op() const { \ + object result = reinterpret_steal(fn(derived().ptr())); \ + if (!result.ptr()) \ + throw error_already_set(); \ + return result; \ + } + +#define PYBIND11_MATH_OPERATOR_BINARY(op, fn) \ + template \ + object object_api::op(object_api const &other) const { \ + object result = reinterpret_steal(fn(derived().ptr(), other.derived().ptr())); \ + if (!result.ptr()) \ + throw error_already_set(); \ + return result; \ + } + +#define PYBIND11_MATH_OPERATOR_BINARY_INPLACE(iop, fn) \ + template \ + object object_api::iop(object_api const &other) { \ + object result = reinterpret_steal(fn(derived().ptr(), other.derived().ptr())); \ + if (!result.ptr()) \ + throw error_already_set(); \ + return result; \ + } + +PYBIND11_MATH_OPERATOR_UNARY(operator~, PyNumber_Invert) +PYBIND11_MATH_OPERATOR_UNARY(operator-, PyNumber_Negative) +PYBIND11_MATH_OPERATOR_BINARY(operator+, PyNumber_Add) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator+=, PyNumber_InPlaceAdd) +PYBIND11_MATH_OPERATOR_BINARY(operator-, PyNumber_Subtract) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator-=, PyNumber_InPlaceSubtract) +PYBIND11_MATH_OPERATOR_BINARY(operator*, PyNumber_Multiply) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator*=, PyNumber_InPlaceMultiply) +PYBIND11_MATH_OPERATOR_BINARY(operator/, PyNumber_TrueDivide) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator/=, PyNumber_InPlaceTrueDivide) +PYBIND11_MATH_OPERATOR_BINARY(operator|, PyNumber_Or) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator|=, PyNumber_InPlaceOr) +PYBIND11_MATH_OPERATOR_BINARY(operator&, PyNumber_And) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator&=, PyNumber_InPlaceAnd) +PYBIND11_MATH_OPERATOR_BINARY(operator^, PyNumber_Xor) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator^=, PyNumber_InPlaceXor) +PYBIND11_MATH_OPERATOR_BINARY(operator<<, PyNumber_Lshift) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator<<=, PyNumber_InPlaceLshift) +PYBIND11_MATH_OPERATOR_BINARY(operator>>, PyNumber_Rshift) +PYBIND11_MATH_OPERATOR_BINARY_INPLACE(operator>>=, PyNumber_InPlaceRshift) + +#undef PYBIND11_MATH_OPERATOR_UNARY +#undef PYBIND11_MATH_OPERATOR_BINARY +#undef PYBIND11_MATH_OPERATOR_BINARY_INPLACE + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/shared/package-files/7a/7a1e4a18ff065bbc298d131a57ca32d5b23c1881fbbf2f22de39e47458d5b367/blob b/shared/package-files/7a/7a1e4a18ff065bbc298d131a57ca32d5b23c1881fbbf2f22de39e47458d5b367/blob new file mode 100644 index 0000000000000000000000000000000000000000..9997a1ae01c7ab8c2df2ddd09a8f4ef8b85ad690 --- /dev/null +++ b/shared/package-files/7a/7a1e4a18ff065bbc298d131a57ca32d5b23c1881fbbf2f22de39e47458d5b367/blob @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _amp_update_scale(const at::Tensor & self, const at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval); +TORCH_API at::Tensor & _amp_update_scale_out(const at::Tensor & self, at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval, at::Tensor & out); +TORCH_API at::Tensor & _amp_update_scale_cpu_(at::Tensor & self, at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval); +TORCH_API at::Tensor & _amp_update_scale_cuda_(at::Tensor & self, at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval); +} // namespace native +} // namespace at diff --git a/shared/package-files/7a/7a1fb5af83c85dc33b85f48a08d4d4f3df50c51616859060e96ef1d130d5531a/blob b/shared/package-files/7a/7a1fb5af83c85dc33b85f48a08d4d4f3df50c51616859060e96ef1d130d5531a/blob new file mode 100644 index 0000000000000000000000000000000000000000..f13839d6b3b68a6ce7e2f7d21e7ba68088e05f95 --- /dev/null +++ b/shared/package-files/7a/7a1fb5af83c85dc33b85f48a08d4d4f3df50c51616859060e96ef1d130d5531a/blob @@ -0,0 +1,41 @@ +import warnings + +import pytest + +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import check_figures_equal + + +@pytest.mark.xfail( + strict=True, reason="testing that warnings fail tests" +) +def test_warn_to_fail(): + warnings.warn("This should fail the test") + + +@pytest.mark.parametrize("a", [1]) +@check_figures_equal(extensions=["png"]) +@pytest.mark.parametrize("b", [1]) +def test_parametrize_with_check_figure_equal(a, fig_ref, b, fig_test): + assert a == b + + +def test_wrap_failure(): + with pytest.raises(ValueError, match="^The decorated function"): + @check_figures_equal() + def should_fail(test, ref): + pass + + +@pytest.mark.xfail(raises=RuntimeError, strict=True, + reason='Test for check_figures_equal test creating ' + 'new figures') +@check_figures_equal() +def test_check_figures_equal_extra_fig(fig_test, fig_ref): + plt.figure() + + +@check_figures_equal() +def test_check_figures_equal_closed_fig(fig_test, fig_ref): + fig = plt.figure() + plt.close(fig) diff --git a/shared/package-files/7a/7a20c7231ab9446379bf4a8abab27edcc2155734357d4d88e7861c15d9693c01/blob b/shared/package-files/7a/7a20c7231ab9446379bf4a8abab27edcc2155734357d4d88e7861c15d9693c01/blob new file mode 100644 index 0000000000000000000000000000000000000000..d4a667176d3807fb5263010d902a0d3e7b93b4e0 --- /dev/null +++ b/shared/package-files/7a/7a20c7231ab9446379bf4a8abab27edcc2155734357d4d88e7861c15d9693c01/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a20c7231ab9446379bf4a8abab27edcc2155734357d4d88e7861c15d9693c01 +size 247056 diff --git a/shared/package-files/7a/7a2ad8d934362305a37bee615bf92abd2d129c0db11332de1b9b04d0fdf3baf2/blob b/shared/package-files/7a/7a2ad8d934362305a37bee615bf92abd2d129c0db11332de1b9b04d0fdf3baf2/blob new file mode 100644 index 0000000000000000000000000000000000000000..36e4692cd9717a221cc683a663e8ee23a81aa5b6 --- /dev/null +++ b/shared/package-files/7a/7a2ad8d934362305a37bee615bf92abd2d129c0db11332de1b9b04d0fdf3baf2/blob @@ -0,0 +1,46 @@ +import os +import platform +import sysconfig + +import numpy as np +import pytest + +from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython +from scipy.linalg.blas import cdotu # type: ignore[attr-defined] +from scipy.linalg.lapack import dgtsv # type: ignore[attr-defined] + + +@pytest.mark.fail_slow(120) +# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247 +@pytest.mark.skipif(IS_EDITABLE, + reason='Editable install cannot find .pxd headers.') +@pytest.mark.skipif((platform.system() == 'Windows' and + sysconfig.get_config_var('Py_GIL_DISABLED')), + reason='gh-22039') +@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"], + reason="Can't start subprocess") +@pytest.mark.skipif(cython is None, reason="requires cython") +def test_cython(tmp_path): + srcdir = os.path.dirname(os.path.dirname(__file__)) + extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir) + # actually test the cython c-extensions + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x = np.ones(9) + _, _, _, x, _ = dgtsv(a, b, c, x) + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x_c = np.ones(9) + extensions.tridiag(a, b, c, x_c) + a = np.ones(8) * 3 + b = np.ones(9) + c = np.ones(8) * 4 + x_cpp = np.ones(9) + extensions_cpp.tridiag(a, b, c, x_cpp) + np.testing.assert_array_equal(x, x_cpp) + cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64) + cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64) + np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy)) + np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy)) diff --git a/shared/package-files/7a/7a31cbf2498d03219c431cb13a22eb868c4fc0f5f45f369fc3acb317edd5e1c1/blob b/shared/package-files/7a/7a31cbf2498d03219c431cb13a22eb868c4fc0f5f45f369fc3acb317edd5e1c1/blob new file mode 100644 index 0000000000000000000000000000000000000000..d69e8e88b0ca458b31c247d98f3747f2f11ebe67 --- /dev/null +++ b/shared/package-files/7a/7a31cbf2498d03219c431cb13a22eb868c4fc0f5f45f369fc3acb317edd5e1c1/blob @@ -0,0 +1,67 @@ +/* -*- C -*- *********************************************** +Copyright (c) 2000, BeOpen.com. +Copyright (c) 1995-2000, Corporation for National Research Initiatives. +Copyright (c) 1990-1995, Stichting Mathematisch Centrum. +All rights reserved. + +See the file "Misc/COPYRIGHT" for information on usage and +redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. +******************************************************************/ + +/* Module configuration */ + +/* !!! !!! !!! This file is edited by the makesetup script !!! !!! !!! */ + +/* This file contains the table of built-in modules. + See create_builtin() in import.c. */ + +#include "Python.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/* -- ADDMODULE MARKER 1 -- */ + +extern PyObject* PyMarshal_Init(void); +extern PyObject* PyInit__imp(void); +extern PyObject* PyInit_gc(void); +extern PyObject* PyInit__ast(void); +extern PyObject* _PyWarnings_Init(void); +extern PyObject* PyInit__string(void); + +struct _inittab _PyImport_Inittab[] = { + +/* -- ADDMODULE MARKER 2 -- */ + + /* This module lives in marshal.c */ + {"marshal", PyMarshal_Init}, + + /* This lives in import.c */ + {"_imp", PyInit__imp}, + + /* This lives in Python/Python-ast.c */ + {"_ast", PyInit__ast}, + + /* These entries are here for sys.builtin_module_names */ + {"builtins", NULL}, + {"sys", NULL}, + + /* This lives in gcmodule.c */ + {"gc", PyInit_gc}, + + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, + + /* This lives in Objects/unicodeobject.c */ + {"_string", PyInit__string}, + + /* Sentinel */ + {0, 0} +}; + + +#ifdef __cplusplus +} +#endif diff --git a/shared/package-files/7a/7a347ca8fef6e29f82b6e4785355a6635c17fa755e0940f65f15aa8fc7bd7f92/blob b/shared/package-files/7a/7a347ca8fef6e29f82b6e4785355a6635c17fa755e0940f65f15aa8fc7bd7f92/blob new file mode 100644 index 0000000000000000000000000000000000000000..fac3c31909bf46d527df7c89352e2a4e9d31c906 --- /dev/null +++ b/shared/package-files/7a/7a347ca8fef6e29f82b6e4785355a6635c17fa755e0940f65f15aa8fc7bd7f92/blob @@ -0,0 +1,4814 @@ + +# Issuer: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA +# Subject: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA +# Label: "GlobalSign Root CA" +# Serial: 4835703278459707669005204 +# MD5 Fingerprint: 3e:45:52:15:09:51:92:e1:b7:5d:37:9f:b1:87:29:8a +# SHA1 Fingerprint: b1:bc:96:8b:d4:f4:9d:62:2a:a8:9a:81:f2:15:01:52:a4:1d:82:9c +# SHA256 Fingerprint: eb:d4:10:40:e4:bb:3e:c7:42:c9:e3:81:d3:1e:f2:a4:1a:48:b6:68:5c:96:e7:ce:f3:c1:df:6c:d4:33:1c:99 +-----BEGIN CERTIFICATE----- +MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG +A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv +b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw +MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i +YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT +aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ +jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp +xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp +1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG +snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ +U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8 +9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B +AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz +yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE +38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP +AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad +DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME +HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== +-----END CERTIFICATE----- + +# Issuer: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Subject: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Label: "Entrust.net Premium 2048 Secure Server CA" +# Serial: 946069240 +# MD5 Fingerprint: ee:29:31:bc:32:7e:9a:e6:e8:b5:f7:51:b4:34:71:90 +# SHA1 Fingerprint: 50:30:06:09:1d:97:d4:f5:ae:39:f7:cb:e7:92:7d:7d:65:2d:34:31 +# SHA256 Fingerprint: 6d:c4:71:72:e0:1c:bc:b0:bf:62:58:0d:89:5f:e2:b8:ac:9a:d4:f8:73:80:1e:0c:10:b9:c8:37:d2:1e:b1:77 +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML +RW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp +bmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5 +IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0yOTA3 +MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3 +LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp +YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG +A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq +K0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe +sYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX +MlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT +XTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/ +HoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH +4QIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJKoZIhvcNAQEFBQADggEBADub +j1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPyT/4xmf3IDExo +U8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf +zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5b +u/8j72gZyxKTJ1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+ +bYQLCIt+jerXmCHG8+c8eS9enNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/Er +fF6adulZkMV8gzURZVE= +-----END CERTIFICATE----- + +# Issuer: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust +# Subject: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust +# Label: "Baltimore CyberTrust Root" +# Serial: 33554617 +# MD5 Fingerprint: ac:b6:94:a5:9c:17:e0:d7:91:52:9b:b1:97:06:a6:e4 +# SHA1 Fingerprint: d4:de:20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74 +# SHA256 Fingerprint: 16:af:57:a9:f6:76:b0:ab:12:60:95:aa:5e:ba:de:f2:2a:b3:11:19:d6:44:ac:95:cd:4b:93:db:f3:f2:6a:eb +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ +RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD +VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX +DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y +ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy +VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr +mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr +IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK +mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu +XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy +dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye +jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1 +BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 +DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92 +9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx +jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0 +Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz +ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS +R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc. +# Subject: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc. +# Label: "Entrust Root Certification Authority" +# Serial: 1164660820 +# MD5 Fingerprint: d6:a5:c3:ed:5d:dd:3e:00:c1:3d:87:92:1f:1d:3f:e4 +# SHA1 Fingerprint: b3:1e:b1:b7:40:e3:6c:84:02:da:dc:37:d4:4d:f5:d4:67:49:52:f9 +# SHA256 Fingerprint: 73:c1:76:43:4f:1b:c6:d5:ad:f4:5b:0e:76:e7:27:28:7c:8d:e5:76:16:c1:e6:e6:14:1a:2b:2c:bc:7d:8e:4c +-----BEGIN CERTIFICATE----- +MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 +Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW +KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl +cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw +NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw +NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy +ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV +BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo +Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 +4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 +KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI +rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi +94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB +sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi +gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo +kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE +vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA +A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t +O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua +AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP +9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ +eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m +0vdXcDazv/wor3ElhVsT/h5/WrQ8 +-----END CERTIFICATE----- + +# Issuer: CN=AAA Certificate Services O=Comodo CA Limited +# Subject: CN=AAA Certificate Services O=Comodo CA Limited +# Label: "Comodo AAA Services root" +# Serial: 1 +# MD5 Fingerprint: 49:79:04:b0:eb:87:19:ac:47:b0:bc:11:51:9b:74:d0 +# SHA1 Fingerprint: d1:eb:23:a4:6d:17:d6:8f:d9:25:64:c2:f1:f1:60:17:64:d8:e3:49 +# SHA256 Fingerprint: d7:a7:a0:fb:5d:7e:27:31:d7:71:e9:48:4e:bc:de:f7:1d:5f:0c:3e:0a:29:48:78:2b:c8:3e:e0:ea:69:9e:f4 +-----BEGIN CERTIFICATE----- +MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb +MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow +GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj +YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM +GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua +BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe +3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4 +YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR +rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm +ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU +oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF +MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v +QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t +b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF +AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q +GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz +Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2 +G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi +l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3 +smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 2 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 2 O=QuoVadis Limited +# Label: "QuoVadis Root CA 2" +# Serial: 1289 +# MD5 Fingerprint: 5e:39:7b:dd:f8:ba:ec:82:e9:ac:62:ba:0c:54:00:2b +# SHA1 Fingerprint: ca:3a:fb:cf:12:40:36:4b:44:b2:16:20:88:80:48:39:19:93:7c:f7 +# SHA256 Fingerprint: 85:a0:dd:7d:d7:20:ad:b7:ff:05:f8:3d:54:2b:20:9d:c7:ff:45:28:f7:d6:77:b1:83:89:fe:a5:e5:c4:9e:86 +-----BEGIN CERTIFICATE----- +MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x +GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv +b3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV +BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W +YWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa +GMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg +Fyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J +WpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB +rrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp ++ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1 +ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i +Ucw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz +PtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og +/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH +oycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI +yV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud +EwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2 +A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL +MAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT +ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f +BluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn +g/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl +fF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K +WWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha +B0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc +hLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR +TUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD +mbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z +ohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y +4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza +8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 3" +# Serial: 1478 +# MD5 Fingerprint: 31:85:3c:62:94:97:63:b9:aa:fd:89:4e:af:6f:e0:cf +# SHA1 Fingerprint: 1f:49:14:f7:d8:74:95:1d:dd:ae:02:c0:be:fd:3a:2d:82:75:51:85 +# SHA256 Fingerprint: 18:f1:fc:7f:20:5d:f8:ad:dd:eb:7f:e0:07:dd:57:e3:af:37:5a:9c:4d:8d:73:54:6b:f4:f1:fe:d1:e1:8d:35 +-----BEGIN CERTIFICATE----- +MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x +GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv +b3QgQ0EgMzAeFw0wNjExMjQxOTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNV +BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W +YWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDM +V0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNggDhoB +4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUr +H556VOijKTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd +8lyyBTNvijbO0BNO/79KDDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9Cabwv +vWhDFlaJKjdhkf2mrk7AyxRllDdLkgbvBNDInIjbC3uBr7E9KsRlOni27tyAsdLT +mZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwpp5ijJUMv7/FfJuGITfhe +btfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8nT8KKdjc +T5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDt +WAEXMJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZ +c6tsgLjoC2SToJyMGf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A +4iLItLRkT9a6fUg+qGkM17uGcclzuD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYD +VR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHTBgkrBgEEAb5YAAMwgcUwgZMG +CCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0 +aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 +aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVu +dC4wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2Nw +czALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4G +A1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4ywLQoUmkRzBFMQswCQYDVQQGEwJC +TTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UEAxMSUXVvVmFkaXMg +Um9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZVqyM0 +7ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSem +d1o417+shvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd ++LJ2w/w4E6oM3kJpK27zPOuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B +4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadN +t54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp8kokUvd0/bpO5qgdAm6x +DYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBCbjPsMZ57 +k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6s +zHXug/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0j +Wy10QJLZYxkNc91pvGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeT +mJlglFwjz1onl14LBQaTNx47aTbrqZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK +4SVhM7JZG+Ju1zdXtg2pEto= +-----END CERTIFICATE----- + +# Issuer: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com +# Subject: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com +# Label: "XRamp Global CA Root" +# Serial: 107108908803651509692980124233745014957 +# MD5 Fingerprint: a1:0b:44:b3:ca:10:d8:00:6e:9d:0f:d8:0f:92:0a:d1 +# SHA1 Fingerprint: b8:01:86:d1:eb:9c:86:a5:41:04:cf:30:54:f3:4c:52:b7:e5:58:c6 +# SHA256 Fingerprint: ce:cd:dc:90:50:99:d8:da:df:c5:b1:d2:09:b7:37:cb:e2:c1:8c:fb:2c:10:c0:ff:0b:cf:0d:32:86:fc:1a:a2 +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCB +gjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEk +MCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRY +UmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQxMTAxMTcx +NDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3 +dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2Vy +dmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS6 +38eMpSe2OAtp87ZOqCwuIR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCP +KZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMxfoArtYzAQDsRhtDLooY2YKTVMIJt2W7Q +DxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FEzG+gSqmUsE3a56k0enI4 +qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqsAxcZZPRa +JSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNVi +PvryxS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0P +BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASs +jVy16bYbMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0 +eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQEwDQYJKoZIhvcNAQEFBQAD +ggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc/Kh4ZzXxHfAR +vbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt +qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLa +IR9NmXmd4c8nnxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSy +i6mx5O+aGtA9aZnuqCij4Tyz8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQ +O+7ETPTsJ3xCwnR8gooJybQDJbw= +-----END CERTIFICATE----- + +# Issuer: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority +# Subject: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority +# Label: "Go Daddy Class 2 CA" +# Serial: 0 +# MD5 Fingerprint: 91:de:06:25:ab:da:fd:32:17:0c:bb:25:17:2a:84:67 +# SHA1 Fingerprint: 27:96:ba:e6:3f:18:01:e2:77:26:1b:a0:d7:77:70:02:8f:20:ee:e4 +# SHA256 Fingerprint: c3:84:6b:f2:4b:9e:93:ca:64:27:4c:0e:c6:7c:1e:cc:5e:02:4f:fc:ac:d2:d7:40:19:35:0e:81:fe:54:6a:e4 +-----BEGIN CERTIFICATE----- +MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh +MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE +YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3 +MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo +ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg +MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN +ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA +PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w +wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi +EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY +avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+ +YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE +sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h +/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5 +IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD +ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy +OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P +TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ +HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER +dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf +ReYNnyicsbkqWletNw+vHX/bvZ8= +-----END CERTIFICATE----- + +# Issuer: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority +# Subject: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority +# Label: "Starfield Class 2 CA" +# Serial: 0 +# MD5 Fingerprint: 32:4a:4b:bb:c8:63:69:9b:be:74:9a:c6:dd:1d:46:24 +# SHA1 Fingerprint: ad:7e:1c:28:b0:64:ef:8f:60:03:40:20:14:c3:d0:e3:37:0e:b5:8a +# SHA256 Fingerprint: 14:65:fa:20:53:97:b8:76:fa:a6:f0:a9:95:8e:55:90:e4:0f:cc:7f:aa:4f:b7:c2:c8:67:75:21:fb:5f:b6:58 +-----BEGIN CERTIFICATE----- +MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl +MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp +U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw +NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE +ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp +ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3 +DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf +8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN ++lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0 +X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa +K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA +1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G +A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR +zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0 +YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD +bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w +DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3 +L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D +eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl +xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp +VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY +WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root CA" +# Serial: 17154717934120587862167794914071425081 +# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72 +# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43 +# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c +-----BEGIN CERTIFICATE----- +MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c +JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP +mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+ +wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4 +VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/ +AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB +AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun +pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC +dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf +fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm +NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx +H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe ++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root CA" +# Serial: 10944719598952040374951832963794454346 +# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e +# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36 +# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61 +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD +QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB +CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 +nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt +43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P +T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 +gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR +TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw +DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr +hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg +06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF +PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls +YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk +CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert High Assurance EV Root CA" +# Serial: 3553400076410547919724730734378100087 +# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a +# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25 +# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j +ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL +MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 +LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug +RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm ++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW +PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM +xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB +Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 +hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg +EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA +FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec +nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z +eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF +hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 +Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep ++OkuE6N36B9K +-----END CERTIFICATE----- + +# Issuer: CN=SwissSign Gold CA - G2 O=SwissSign AG +# Subject: CN=SwissSign Gold CA - G2 O=SwissSign AG +# Label: "SwissSign Gold CA - G2" +# Serial: 13492815561806991280 +# MD5 Fingerprint: 24:77:d9:a8:91:d1:3b:fa:88:2d:c2:ff:f8:cd:33:93 +# SHA1 Fingerprint: d8:c5:38:8a:b7:30:1b:1b:6e:d4:7a:e6:45:25:3a:6f:9f:1a:27:61 +# SHA256 Fingerprint: 62:dd:0b:e9:b9:f5:0a:16:3e:a0:f8:e7:5c:05:3b:1e:ca:57:ea:55:c8:68:8f:64:7c:68:81:f2:c8:35:7b:95 +-----BEGIN CERTIFICATE----- +MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2ln +biBHb2xkIENBIC0gRzIwHhcNMDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBF +MQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dpc3NTaWduIEFHMR8wHQYDVQQDExZT +d2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUqt2/8 +76LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+ +bbqBHH5CjCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c +6bM8K8vzARO/Ws/BtQpgvd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqE +emA8atufK+ze3gE/bk3lUIbLtK/tREDFylqM2tIrfKjuvqblCqoOpd8FUrdVxyJd +MmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvRAiTysybUa9oEVeXBCsdt +MDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuendjIj3o02y +MszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69y +FGkOpeUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPi +aG59je883WX0XaxR7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxM +gI93e2CaHt+28kgeDrpOVG2Y4OGiGqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCB +qTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUWyV7 +lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64OfPAeGZe6Drn +8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov +L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe6 +45R88a7A3hfm5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczO +UYrHUDFu4Up+GC9pWbY9ZIEr44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5 +O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOfMke6UiI0HTJ6CVanfCU2qT1L2sCC +bwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6mGu6uLftIdxf+u+yv +GPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxpmo/a +77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCC +hdiDyyJkvC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid3 +92qgQmwLOM7XdVAyksLfKzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEpp +Ld6leNcG2mqeSz53OiATIgHQv2ieY2BrNU0LbbqhPcCT4H8js1WtciVORvnSFu+w +ZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6LqjviOvrv1vA+ACOzB2+htt +Qc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ +-----END CERTIFICATE----- + +# Issuer: CN=SwissSign Silver CA - G2 O=SwissSign AG +# Subject: CN=SwissSign Silver CA - G2 O=SwissSign AG +# Label: "SwissSign Silver CA - G2" +# Serial: 5700383053117599563 +# MD5 Fingerprint: e0:06:a1:c9:7d:cf:c9:fc:0d:c0:56:75:96:d8:62:13 +# SHA1 Fingerprint: 9b:aa:e5:9f:56:ee:21:cb:43:5a:be:25:93:df:a7:f0:40:d1:1d:cb +# SHA256 Fingerprint: be:6c:4d:a2:bb:b9:ba:59:b6:f3:93:97:68:37:42:46:c3:c0:05:99:3f:a9:8f:02:0d:1d:ed:be:d4:8a:81:d5 +-----BEGIN CERTIFICATE----- +MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UE +BhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWdu +IFNpbHZlciBDQSAtIEcyMB4XDTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0Nlow +RzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMY +U3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644N0Mv +Fz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7br +YT7QbNHm+/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieF +nbAVlDLaYQ1HTWBCrpJH6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH +6ATK72oxh9TAtvmUcXtnZLi2kUpCe2UuMGoM9ZDulebyzYLs2aFK7PayS+VFheZt +eJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5hqAaEuSh6XzjZG6k4sIN/ +c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5FZGkECwJ +MoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRH +HTBsROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTf +jNFusB3hB48IHpmccelM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb6 +5i/4z3GcRm25xBWNOHkDRUjvxF3XCO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOB +rDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU +F6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRBtjpbO8tFnb0c +wpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0 +cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIB +AHPGgeAn0i0P4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShp +WJHckRE1qTodvBqlYJ7YH39FkWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9 +xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L3XWgwF15kIwb4FDm3jH+mHtwX6WQ +2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx/uNncqCxv1yL5PqZ +IseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFaDGi8 +aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2X +em1ZqSqPe97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQR +dAtq/gsD/KNVV4n+SsuuWxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/ +OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJDIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+ +hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ubDgEj8Z+7fNzcbBGXJbLy +tGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u +-----END CERTIFICATE----- + +# Issuer: CN=SecureTrust CA O=SecureTrust Corporation +# Subject: CN=SecureTrust CA O=SecureTrust Corporation +# Label: "SecureTrust CA" +# Serial: 17199774589125277788362757014266862032 +# MD5 Fingerprint: dc:32:c3:a7:6d:25:57:c7:68:09:9d:ea:2d:a9:a2:d1 +# SHA1 Fingerprint: 87:82:c6:c3:04:35:3b:cf:d2:96:92:d2:59:3e:7d:44:d9:34:ff:11 +# SHA256 Fingerprint: f1:c1:b5:0a:e5:a2:0d:d8:03:0e:c9:f6:bc:24:82:3d:d3:67:b5:25:57:59:b4:e7:1b:61:fc:e9:f7:37:5d:73 +-----BEGIN CERTIFICATE----- +MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI +MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x +FzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz +MTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv +cnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz +Zum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO +0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao +wW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj +7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS +8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT +BgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg +JYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC +NxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3 +6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/ +3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm +D5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS +CPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR +3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= +-----END CERTIFICATE----- + +# Issuer: CN=Secure Global CA O=SecureTrust Corporation +# Subject: CN=Secure Global CA O=SecureTrust Corporation +# Label: "Secure Global CA" +# Serial: 9751836167731051554232119481456978597 +# MD5 Fingerprint: cf:f4:27:0d:d4:ed:dc:65:16:49:6d:3d:da:bf:6e:de +# SHA1 Fingerprint: 3a:44:73:5a:e5:81:90:1f:24:86:61:46:1e:3b:9c:c4:5f:f5:3a:1b +# SHA256 Fingerprint: 42:00:f5:04:3a:c8:59:0e:bb:52:7d:20:9e:d1:50:30:29:fb:cb:d4:1c:a1:b5:06:ec:27:f1:5a:de:7d:ac:69 +-----BEGIN CERTIFICATE----- +MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBK +MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x +GTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkx +MjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3Qg +Q29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jxYDiJ +iQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa +/FHtaMbQbqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJ +jnIFHovdRIWCQtBJwB1g8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnI +HmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYVHDGA76oYa8J719rO+TMg1fW9ajMtgQT7 +sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi0XPnj3pDAgMBAAGjgZ0w +gZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCsw +KaAnoCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsG +AQQBgjcVAQQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0L +URYD7xh8yOOvaliTFGCRsoTciE6+OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXO +H0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cnCDpOGR86p1hcF895P4vkp9Mm +I50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/53CYNv6ZHdAbY +iNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc +f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW +-----END CERTIFICATE----- + +# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO Certification Authority O=COMODO CA Limited +# Label: "COMODO Certification Authority" +# Serial: 104350513648249232941998508985834464573 +# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75 +# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b +# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66 +-----BEGIN CERTIFICATE----- +MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB +gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV +BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw +MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl +YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P +RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3 +UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI +2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8 +Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp ++2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+ +DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O +nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW +/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g +PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u +QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY +SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv +IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ +RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4 +zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd +BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB +ZQ== +-----END CERTIFICATE----- + +# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Label: "COMODO ECC Certification Authority" +# Serial: 41578283867086692638256921589707938090 +# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23 +# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11 +# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7 +-----BEGIN CERTIFICATE----- +MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT +IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw +MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy +ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N +T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR +FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J +cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW +BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm +fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv +GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= +-----END CERTIFICATE----- + +# Issuer: CN=Certigna O=Dhimyotis +# Subject: CN=Certigna O=Dhimyotis +# Label: "Certigna" +# Serial: 18364802974209362175 +# MD5 Fingerprint: ab:57:a6:5b:7d:42:82:19:b5:d8:58:26:28:5e:fd:ff +# SHA1 Fingerprint: b1:2e:13:63:45:86:a4:6f:1a:b2:60:68:37:58:2d:c4:ac:fd:94:97 +# SHA256 Fingerprint: e3:b6:a2:db:2e:d7:ce:48:84:2f:7a:c5:32:41:c7:b7:1d:54:14:4b:fb:40:c1:1f:3f:1d:0b:42:f5:ee:a1:2d +-----BEGIN CERTIFICATE----- +MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNV +BAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4X +DTA3MDYyOTE1MTMwNVoXDTI3MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQ +BgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwIQ2VydGlnbmEwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7qXOEm7RFHYeGifBZ4 +QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyHGxny +gQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbw +zBfsV1/pogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q +130yGLMLLGq/jj8UEYkgDncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2 +JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKfIrjxwo1p3Po6WAbfAgMBAAGjgbwwgbkw +DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQtCRZvgHyUtVF9lo53BEw +ZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJBgNVBAYT +AkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzj +AQ/JSP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG +9w0BAQUFAAOCAQEAhQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8h +bV6lUmPOEvjvKtpv6zf+EwLHyzs+ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFnc +fca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1kluPBS1xp81HlDQwY9qcEQCYsuu +HWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY1gkIl2PlwS6w +t0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw +WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== +-----END CERTIFICATE----- + +# Issuer: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority +# Subject: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority +# Label: "ePKI Root Certification Authority" +# Serial: 28956088682735189655030529057352760477 +# MD5 Fingerprint: 1b:2e:00:ca:26:06:90:3d:ad:fe:6f:15:68:d3:6b:b3 +# SHA1 Fingerprint: 67:65:0d:f1:7e:8e:7e:5b:82:40:a4:f4:56:4b:cf:e2:3d:69:c6:f0 +# SHA256 Fingerprint: c0:a6:f4:dc:63:a2:4b:fd:cf:54:ef:2a:6a:08:2a:0a:72:de:35:80:3e:2f:f5:ff:52:7a:e5:d8:72:06:df:d5 +-----BEGIN CERTIFICATE----- +MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe +Fw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw +IQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL +SSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH +SyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh +ijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X +DZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1 +TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ +fzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA +sgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU +WH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS +nT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH +dmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip +NiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC +AwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF +MAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH +ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGB +uvl2ICO1J2B01GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6Yl +PwZpVnPDimZI+ymBV3QGypzqKOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkP +JXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdVxrsStZf0X4OFunHB2WyBEXYKCrC/ +gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEPNXubrjlpC2JgQCA2 +j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+rGNm6 +5ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUB +o2M3IUxExJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS +/jQ6fbjpKdx2qcgw+BRxgMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2z +Gp1iro2C6pSe3VkQw63d4k3jMdXH7OjysP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTE +W9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D +hNQ+IIX3Sj0rnP0qCglN6oH4EZw= +-----END CERTIFICATE----- + +# Issuer: O=certSIGN OU=certSIGN ROOT CA +# Subject: O=certSIGN OU=certSIGN ROOT CA +# Label: "certSIGN ROOT CA" +# Serial: 35210227249154 +# MD5 Fingerprint: 18:98:c0:d6:e9:3a:fc:f9:b0:f5:0c:f7:4b:01:44:17 +# SHA1 Fingerprint: fa:b7:ee:36:97:26:62:fb:2d:b0:2a:f6:bf:03:fd:e8:7c:4b:2f:9b +# SHA256 Fingerprint: ea:a9:62:c4:fa:4a:6b:af:eb:e4:15:19:6d:35:1c:cd:88:8d:4f:53:f3:fa:8a:e6:d7:c4:66:a9:4e:60:42:bb +-----BEGIN CERTIFICATE----- +MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYT +AlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBD +QTAeFw0wNjA3MDQxNzIwMDRaFw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJP +MREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7IJUqOtdu0KBuqV5Do +0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHHrfAQ +UySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5d +RdY4zTW2ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQ +OA7+j0xbm0bqQfWwCHTD0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwv +JoIQ4uNllAoEwF73XVv4EOLQunpL+943AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08C +AwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAcYwHQYDVR0O +BBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IBAQA+0hyJ +LjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecY +MnQ8SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ +44gx+FkagQnIl6Z0x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6I +Jd1hJyMctTEHBDa0GpC9oHRxUIltvBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNw +i/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7NzTogVZ96edhBiIL5VaZVDADlN +9u6wWk5JRFRYX0KD +-----END CERTIFICATE----- + +# Issuer: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) +# Subject: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) +# Label: "NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny" +# Serial: 80544274841616 +# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88 +# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91 +# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98 +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG +EwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3 +MDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl +cnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR +dGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB +pzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM +b2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm +aWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz +IEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT +lF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz +AZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5 +VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG +ILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2 +BJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG +AQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M +U9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh +bvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C ++C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC +bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F +uLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2 +XjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= +-----END CERTIFICATE----- + +# Issuer: CN=SecureSign RootCA11 O=Japan Certification Services, Inc. +# Subject: CN=SecureSign RootCA11 O=Japan Certification Services, Inc. +# Label: "SecureSign RootCA11" +# Serial: 1 +# MD5 Fingerprint: b7:52:74:e2:92:b4:80:93:f2:75:e4:cc:d7:f2:ea:26 +# SHA1 Fingerprint: 3b:c4:9f:48:f8:f3:73:a0:9c:1e:bd:f8:5b:b1:c3:65:c7:d8:11:b3 +# SHA256 Fingerprint: bf:0f:ee:fb:9e:3a:58:1a:d5:f9:e9:db:75:89:98:57:43:d2:61:08:5c:4d:31:4f:6f:5d:72:59:aa:42:16:12 +-----BEGIN CERTIFICATE----- +MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDEr +MCkGA1UEChMiSmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoG +A1UEAxMTU2VjdXJlU2lnbiBSb290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0 +MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSswKQYDVQQKEyJKYXBhbiBDZXJ0aWZp +Y2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1cmVTaWduIFJvb3RD +QTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvLTJsz +i1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8 +h9uuywGOwvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOV +MdrAG/LuYpmGYz+/3ZMqg6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9 +UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rPO7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni +8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitAbpSACW22s293bzUIUPsC +h8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZXt94wDgYD +VR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB +AKChOBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xm +KbabfSVSSUOrTC4rbnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQ +X5Ucv+2rIrVls4W6ng+4reV6G4pQOh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWr +QbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01y8hSyn+B/tlr0/cR7SXf+Of5 +pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061lgeLKBObjBmN +QSdJQO7e5iNEOdyhIta6A/I= +-----END CERTIFICATE----- + +# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. +# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. +# Label: "Microsec e-Szigno Root CA 2009" +# Serial: 14014712776195784473 +# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1 +# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e +# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78 +-----BEGIN CERTIFICATE----- +MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD +VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0 +ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G +CSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y +OTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx +FjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp +Z25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o +dTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP +kd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc +cbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U +fIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7 +N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC +xkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1 ++rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM +Pcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG +SIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h +mLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk +ddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 +tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c +2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t +HMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Label: "GlobalSign Root CA - R3" +# Serial: 4835703278459759426209954 +# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28 +# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad +# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b +-----BEGIN CERTIFICATE----- +MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G +A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp +Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 +MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG +A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 +RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT +gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm +KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd +QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ +XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw +DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o +LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU +RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp +jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK +6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX +mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs +Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH +WD9f +-----END CERTIFICATE----- + +# Issuer: CN=Izenpe.com O=IZENPE S.A. +# Subject: CN=Izenpe.com O=IZENPE S.A. +# Label: "Izenpe.com" +# Serial: 917563065490389241595536686991402621 +# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73 +# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19 +# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f +-----BEGIN CERTIFICATE----- +MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4 +MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6 +ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD +VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j +b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq +scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO +xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H +LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX +uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD +yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+ +JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q +rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN +BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L +hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB +QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+ +HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu +Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg +QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB +BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx +MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA +A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb +laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56 +awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo +JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw +LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT +VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk +LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb +UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/ +QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+ +naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls +QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== +-----END CERTIFICATE----- + +# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Label: "Go Daddy Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01 +# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b +# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT +EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp +ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz +NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH +EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE +AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD +E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH +/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy +DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh +GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR +tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA +AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX +WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu +9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr +gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo +2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI +4uJEvlz36hz1 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96 +# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e +# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5 +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs +ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw +MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 +b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj +aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp +Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg +nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1 +HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N +Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN +dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0 +HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G +CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU +sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3 +4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg +8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K +pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1 +mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Services Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2 +# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f +# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5 +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs +ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 +MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD +VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy +ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy +dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p +OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2 +8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K +Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe +hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk +6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw +DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q +AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI +bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB +ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z +qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd +iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn +0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN +sSi6 +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Commercial O=AffirmTrust +# Subject: CN=AffirmTrust Commercial O=AffirmTrust +# Label: "AffirmTrust Commercial" +# Serial: 8608355977964138876 +# MD5 Fingerprint: 82:92:ba:5b:ef:cd:8a:6f:a6:3d:55:f9:84:f6:d6:b7 +# SHA1 Fingerprint: f9:b5:b6:32:45:5f:9c:be:ec:57:5f:80:dc:e9:6e:2c:c7:b2:78:b7 +# SHA256 Fingerprint: 03:76:ab:1d:54:c5:f9:80:3c:e4:b2:e2:01:a0:ee:7e:ef:7b:57:b6:36:e8:a9:3c:9b:8d:48:60:c9:6f:5f:a7 +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz +dCBDb21tZXJjaWFsMB4XDTEwMDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDEL +MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp +cm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6EqdbDuKP +Hx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yr +ba0F8PrVC8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPAL +MeIrJmqbTFeurCA+ukV6BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1 +yHp52UKqK39c/s4mT6NmgTWvRLpUHhwwMmWd5jyTXlBOeuM61G7MGvv50jeuJCqr +VwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNVHQ4EFgQUnZPGU4teyq8/ +nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ +KoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYG +XUPGhi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNj +vbz4YYCanrHOQnDiqX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivt +Z8SOyUOyXGsViQK8YvxO8rUzqrJv0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9g +N53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0khsUlHRUe072o0EclNmsxZt9YC +nlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Networking O=AffirmTrust +# Subject: CN=AffirmTrust Networking O=AffirmTrust +# Label: "AffirmTrust Networking" +# Serial: 8957382827206547757 +# MD5 Fingerprint: 42:65:ca:be:01:9a:9a:4c:a9:8c:41:49:cd:c0:d5:7f +# SHA1 Fingerprint: 29:36:21:02:8b:20:ed:02:f5:66:c5:32:d1:d6:ed:90:9f:45:00:2f +# SHA256 Fingerprint: 0a:81:ec:5a:92:97:77:f1:45:90:4a:f3:8d:5d:50:9f:66:b5:e2:c5:8f:cd:b5:31:05:8b:0e:17:f3:f0:b4:1b +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz +dCBOZXR3b3JraW5nMB4XDTEwMDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDEL +MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp +cm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SEHi3y +YJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbua +kCNrmreIdIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRL +QESxG9fhwoXA3hA/Pe24/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp +6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gbh+0t+nvujArjqWaJGctB+d1ENmHP4ndG +yH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNVHQ4EFgQUBx/S55zawm6i +QLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ +KoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfO +tDIuUFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzu +QY0x2+c06lkh1QF612S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZ +Lgo/bNjR9eUJtGxUAArgFU2HdW23WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4u +olu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9/ZFvgrG+CJPbFEfxojfHRZ48 +x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Premium O=AffirmTrust +# Subject: CN=AffirmTrust Premium O=AffirmTrust +# Label: "AffirmTrust Premium" +# Serial: 7893706540734352110 +# MD5 Fingerprint: c4:5d:0e:48:b6:ac:28:30:4e:0a:bc:f9:38:16:87:57 +# SHA1 Fingerprint: d8:a6:33:2c:e0:03:6f:b1:85:f6:63:4f:7d:6a:06:65:26:32:28:27 +# SHA256 Fingerprint: 70:a7:3f:7f:37:6b:60:07:42:48:90:45:34:b1:14:82:d5:bf:0e:69:8e:cc:49:8d:f5:25:77:eb:f2:e9:3b:9a +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVz +dCBQcmVtaXVtMB4XDTEwMDEyOTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkG +A1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1U +cnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxBLf +qV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtnBKAQ +JG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ ++jjeRFcV5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrS +s8PhaJyJ+HoAVt70VZVs+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5 +HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmdGPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d7 +70O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5Rp9EixAqnOEhss/n/fauG +V+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NIS+LI+H+S +qHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S +5u046uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4Ia +C1nEWTJ3s7xgaVY5/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TX +OwF0lkLgAOIua+rF7nKsu7/+6qqo+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYE +FJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByvMiPIs0laUZx2 +KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg +Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B +8OWycvpEgjNC6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQ +MKSOyARiqcTtNd56l+0OOF6SL5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc +0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK+4w1IX2COPKpVJEZNZOUbWo6xbLQ +u4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmVBtWVyuEklut89pMF +u+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFgIxpH +YoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8 +GKa1qF60g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaO +RtGdFNrHF+QFlozEJLUbzxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6e +KeC2uAloGRwYQw== +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Premium ECC O=AffirmTrust +# Subject: CN=AffirmTrust Premium ECC O=AffirmTrust +# Label: "AffirmTrust Premium ECC" +# Serial: 8401224907861490260 +# MD5 Fingerprint: 64:b0:09:55:cf:b1:d5:99:e2:be:13:ab:a6:5d:ea:4d +# SHA1 Fingerprint: b8:23:6b:00:2f:1d:16:86:53:01:55:6c:11:a4:37:ca:eb:ff:c3:bb +# SHA256 Fingerprint: bd:71:fd:f6:da:97:e4:cf:62:d1:64:7a:dd:25:81:b0:7d:79:ad:f8:39:7e:b4:ec:ba:9c:5e:84:88:82:14:23 +-----BEGIN CERTIFICATE----- +MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMC +VVMxFDASBgNVBAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQ +cmVtaXVtIEVDQzAeFw0xMDAxMjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJ +BgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwXQWZmaXJt +VHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQNMF4bFZ0D +0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQN8O9 +ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0G +A1UdDgQWBBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4G +A1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/Vs +aobgxCd05DhT1wV/GzTjxi+zygk8N53X57hG8f2h4nECMEJZh0PUUd+60wkyWs6I +flc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKMeQ== +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Network CA" +# Serial: 279744 +# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78 +# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e +# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e +-----BEGIN CERTIFICATE----- +MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM +MSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D +ZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU +cnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3 +WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg +Uy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw +IAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH +UV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM +TXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU +BBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM +kUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x +AcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV +HQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y +sHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL +I9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8 +J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY +VoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI +03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= +-----END CERTIFICATE----- + +# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA +# Label: "TWCA Root Certification Authority" +# Serial: 1 +# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79 +# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48 +# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44 +-----BEGIN CERTIFICATE----- +MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES +MBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU +V0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz +WhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO +LUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE +AcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH +K3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX +RfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z +rX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx +3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq +hkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC +MErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls +XebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D +lhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn +aspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ +YiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== +-----END CERTIFICATE----- + +# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 +# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 +# Label: "Security Communication RootCA2" +# Serial: 0 +# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43 +# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74 +# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6 +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl +MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe +U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX +DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy +dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj +YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV +OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr +zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM +VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ +hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO +ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw +awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs +OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3 +DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF +coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc +okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8 +t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy +1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/ +SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 +-----END CERTIFICATE----- + +# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 +# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 +# Label: "Actalis Authentication Root CA" +# Serial: 6271844772424770508 +# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6 +# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac +# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 +-----BEGIN CERTIFICATE----- +MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE +BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w +MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 +IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC +SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1 +ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv +UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX +4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9 +KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/ +gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb +rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ +51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F +be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe +KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F +v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn +fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7 +jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz +ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt +ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL +e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70 +jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz +WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V +SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j +pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX +X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok +fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R +K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU +ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU +LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT +LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== +-----END CERTIFICATE----- + +# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 +# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 +# Label: "Buypass Class 2 Root CA" +# Serial: 2 +# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29 +# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99 +# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48 +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd +MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg +Q2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow +TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw +HgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB +BQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr +6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV +L4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91 +1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx +MlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ +QmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB +arcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr +Us3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi +FRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS +P/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN +9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP +AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz +uvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h +9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s +A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t +OluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo ++fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7 +KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2 +DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us +H8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ +I+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7 +5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h +3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz +Y11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA= +-----END CERTIFICATE----- + +# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 +# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 +# Label: "Buypass Class 3 Root CA" +# Serial: 2 +# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec +# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57 +# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd +MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg +Q2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow +TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw +HgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB +BQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y +ZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E +N3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9 +tznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX +0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c +/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X +KhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY +zIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS +O1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D +34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP +K9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3 +AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv +Tg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj +QTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV +cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS +IGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2 +HJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa +O5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv +033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u +dmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE +kbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41 +3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD +u79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq +4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc= +-----END CERTIFICATE----- + +# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Label: "T-TeleSec GlobalRoot Class 3" +# Serial: 1 +# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef +# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1 +# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx +KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd +BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl +YyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1 +OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy +aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 +ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN +8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/ +RLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4 +hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5 +ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM +EnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1 +A/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy +WL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ +1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30 +6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT +91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml +e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p +TpPDpFQUWw== +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH +# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH +# Label: "D-TRUST Root Class 3 CA 2 2009" +# Serial: 623603 +# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f +# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0 +# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1 +-----BEGIN CERTIFICATE----- +MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF +MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD +bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha +ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM +HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03 +UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42 +tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R +ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM +lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp +/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G +A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G +A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj +dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy +MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl +cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js +L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL +BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni +acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 +o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K +zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8 +PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y +Johw1+qRzT65ysCQblrGXnRl11z+o+I= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH +# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH +# Label: "D-TRUST Root Class 3 CA 2 EV 2009" +# Serial: 623604 +# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6 +# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83 +# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81 +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF +MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD +bGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw +NDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV +BAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn +ljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0 +3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z +qQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR +p75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8 +HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw +ggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea +HNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw +Oi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh +c3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E +RT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt +dHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku +Y3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp +3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 +nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF +CSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na +xpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX +KVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1 +-----END CERTIFICATE----- + +# Issuer: CN=CA Disig Root R2 O=Disig a.s. +# Subject: CN=CA Disig Root R2 O=Disig a.s. +# Label: "CA Disig Root R2" +# Serial: 10572350602393338211 +# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03 +# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71 +# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03 +-----BEGIN CERTIFICATE----- +MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV +BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu +MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy +MDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx +EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw +ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe +NcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH +PWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I +x2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe +QTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR +yyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO +QG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912 +H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ +QfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD +i/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs +nLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1 +rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud +DwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI +hvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM +tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf +GopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb +lvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka ++elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal +TFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i +nSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3 +gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr +G5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os +zMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x +L4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL +-----END CERTIFICATE----- + +# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV +# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV +# Label: "ACCVRAIZ1" +# Serial: 6828503384748696800 +# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02 +# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17 +# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13 +-----BEGIN CERTIFICATE----- +MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE +AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw +CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ +BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND +VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb +qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY +HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo +G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA +lHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr +IA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/ +0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH +k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47 +4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO +m3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa +cXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl +uUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI +KwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls +ZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG +AQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 +VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT +VfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG +CCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA +cgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA +QwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA +7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA +cgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA +QwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA +czAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu +aHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt +aW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud +DwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF +BQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp +D70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU +JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m +AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD +vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms +tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH +7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h +I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA +h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF +d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H +pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7 +-----END CERTIFICATE----- + +# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA +# Label: "TWCA Global Root CA" +# Serial: 3262 +# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96 +# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65 +# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx +EjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT +VFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5 +NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT +B1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF +10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz +0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh +MBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH +zIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc +46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2 +yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi +laLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP +oA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA +BDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE +qYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm +4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL +1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn +LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF +H6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo +RI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+ +nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh +15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW +6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW +nsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j +wa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz +aGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy +KwbQBM0= +-----END CERTIFICATE----- + +# Issuer: CN=TeliaSonera Root CA v1 O=TeliaSonera +# Subject: CN=TeliaSonera Root CA v1 O=TeliaSonera +# Label: "TeliaSonera Root CA v1" +# Serial: 199041966741090107964904287217786801558 +# MD5 Fingerprint: 37:41:49:1b:18:56:9a:26:f5:ad:c2:66:fb:40:a5:4c +# SHA1 Fingerprint: 43:13:bb:96:f1:d5:86:9b:c1:4e:6a:92:f6:cf:f6:34:69:87:82:37 +# SHA256 Fingerprint: dd:69:36:fe:21:f8:f0:77:c1:23:a1:a5:21:c1:22:24:f7:22:55:b7:3e:03:a7:26:06:93:e8:a2:4b:0f:a3:89 +-----BEGIN CERTIFICATE----- +MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAw +NzEUMBIGA1UECgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJv +b3QgQ0EgdjEwHhcNMDcxMDE4MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYD +VQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwWVGVsaWFTb25lcmEgUm9vdCBDQSB2 +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+6yfwIaPzaSZVfp3F +VRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA3GV1 +7CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+X +Z75Ljo1kB1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+ +/jXh7VB7qTCNGdMJjmhnXb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs +81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxHoLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkm +dtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3F0fUTPHSiXk+TT2YqGHe +Oh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJoWjiUIMu +sDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4 +pgd7gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fs +slESl1MpWtTwEhDcTwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQ +arMCpgKIv7NHfirZ1fpoeDVNAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYD +VR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qWDNXr+nuqF+gTEjANBgkqhkiG +9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNmzqjMDfz1mgbl +dxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx +0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1Tj +TQpgcmLNkQfWpb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBed +Y2gea+zDTYa4EzAvXUYNR0PVG6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7 +Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpcc41teyWRyu5FrgZLAMzTsVlQ2jqI +OylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOTJsjrDNYmiLbAJM+7 +vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2qReW +t88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcn +HL/EVlP6Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVx +SK236thZiNSQvxaz2emsWWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= +-----END CERTIFICATE----- + +# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Label: "T-TeleSec GlobalRoot Class 2" +# Serial: 1 +# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a +# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9 +# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52 +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx +KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd +BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl +YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1 +OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy +aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 +ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd +AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC +FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi +1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq +jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ +wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/ +WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy +NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC +uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw +IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6 +g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN +9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP +BSeOE6Fuwg== +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot 2011 O=Atos +# Subject: CN=Atos TrustedRoot 2011 O=Atos +# Label: "Atos TrustedRoot 2011" +# Serial: 6643877497813316402 +# MD5 Fingerprint: ae:b9:c4:32:4b:ac:7f:5d:66:cc:77:94:bb:2a:77:56 +# SHA1 Fingerprint: 2b:b1:f5:3e:55:0c:1d:c5:f1:d4:e6:b7:6a:46:4b:55:06:02:ac:21 +# SHA256 Fingerprint: f3:56:be:a2:44:b7:a9:1e:b3:5d:53:ca:9a:d7:86:4a:ce:01:8e:2d:35:d5:f8:f9:6d:df:68:a6:f4:1a:a4:74 +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE +AwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG +EwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM +FUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC +REUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp +Nb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM +VD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+ +SZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ +4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L +cp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi +eowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG +A1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3 +DQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j +vZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP +DpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc +maHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D +lmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv +KrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 1 G3" +# Serial: 687049649626669250736271037606554624078720034195 +# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab +# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67 +# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00 +MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV +wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe +rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341 +68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh +4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp +UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o +abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc +3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G +KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt +hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO +Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt +zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD +ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC +MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2 +cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN +qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5 +YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv +b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2 +8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k +NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj +ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp +q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt +nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 2 G3" +# Serial: 390156079458959257446133169266079962026824725800 +# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06 +# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 +# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00 +MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf +qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW +n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym +c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+ +O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1 +o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j +IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq +IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz +8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh +vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l +7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG +cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD +ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 +AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC +roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga +W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n +lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE ++V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV +csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd +dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg +KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM +HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4 +WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 3 G3" +# Serial: 268090761170461462463995952157327242137089239581 +# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7 +# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d +# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00 +MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR +/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu +FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR +U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c +ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR +FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k +A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw +eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl +sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp +VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q +A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+ +ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD +ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px +KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI +FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv +oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg +u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP +0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf +3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl +8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+ +DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN +PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ +ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0 +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root G2" +# Serial: 15385348160840213938643033620894905419 +# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d +# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f +# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85 +-----BEGIN CERTIFICATE----- +MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA +n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc +biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp +EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA +bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu +YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB +AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW +BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI +QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I +0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni +lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9 +B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv +ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo +IhNzbM8m9Yop5w== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root G3" +# Serial: 15459312981008553731928384953135426796 +# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb +# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89 +# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2 +-----BEGIN CERTIFICATE----- +MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw +CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu +ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg +RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu +Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf +Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q +RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD +AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY +JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv +6pZjamVFkpUBtA== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root G2" +# Serial: 4293743540046975378534879503202253541 +# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44 +# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4 +# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f +-----BEGIN CERTIFICATE----- +MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH +MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI +2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx +1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ +q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz +tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ +vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV +5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY +1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4 +NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG +Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91 +8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe +pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl +MrY= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root G3" +# Serial: 7089244469030293291760083333884364146 +# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca +# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e +# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0 +-----BEGIN CERTIFICATE----- +MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw +CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu +ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe +Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw +EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x +IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG +fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO +Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd +BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx +AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/ +oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8 +sycX +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Trusted Root G4" +# Serial: 7451500558977370777930084869016614236 +# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49 +# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4 +# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88 +-----BEGIN CERTIFICATE----- +MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg +RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu +Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y +ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If +xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV +ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO +DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ +jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/ +CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi +EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM +fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY +uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK +chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t +9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD +ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2 +SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd ++SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc +fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa +sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N +cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N +0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie +4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI +r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1 +/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm +gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+ +-----END CERTIFICATE----- + +# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited +# Label: "COMODO RSA Certification Authority" +# Serial: 101909084537582093308941363524873193117 +# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18 +# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4 +# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34 +-----BEGIN CERTIFICATE----- +MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB +hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV +BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5 +MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT +EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR +Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR +6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X +pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC +9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV +/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf +Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z ++pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w +qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah +SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC +u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf +Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq +crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E +FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB +/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl +wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM +4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV +2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna +FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ +CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK +boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke +jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL +S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb +QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl +0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB +NVOFBkpdn627G190 +-----END CERTIFICATE----- + +# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network +# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network +# Label: "USERTrust RSA Certification Authority" +# Serial: 2645093764781058787591871645665788717 +# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5 +# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e +# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2 +-----BEGIN CERTIFICATE----- +MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB +iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl +cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV +BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw +MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV +BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU +aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy +dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK +AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B +3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY +tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ +Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 +VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT +79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 +c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT +Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l +c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee +UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE +Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd +BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G +A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF +Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO +VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 +ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs +8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR +iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze +Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ +XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ +qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB +VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB +L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG +jjxDah2nGN59PRbxYvnKkKj9 +-----END CERTIFICATE----- + +# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network +# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network +# Label: "USERTrust ECC Certification Authority" +# Serial: 123013823720199481456569720443997572134 +# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1 +# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0 +# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a +-----BEGIN CERTIFICATE----- +MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL +MAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl +eSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT +JVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx +MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT +Ck5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg +VVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo +I+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng +o4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G +A1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB +zzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW +RNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg= +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 +# Label: "GlobalSign ECC Root CA - R5" +# Serial: 32785792099990507226680698011560947931244 +# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08 +# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa +# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24 +-----BEGIN CERTIFICATE----- +MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk +MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH +bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX +DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD +QSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc +8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke +hOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI +KoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg +515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO +xwy8p2Fp8fc74SrL+SvzZpA3 +-----END CERTIFICATE----- + +# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust +# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust +# Label: "IdenTrust Commercial Root CA 1" +# Serial: 13298821034946342390520003877796839426 +# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7 +# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25 +# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu +VHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw +MTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw +JQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT +3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU ++ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp +S0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1 +bVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi +T0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL +vYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK +Vsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK +dHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT +c+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv +l7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N +iGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD +ggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH +6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt +LRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93 +nAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3 ++wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK +W2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT +AwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq +l1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG +4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ +mUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A +7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H +-----END CERTIFICATE----- + +# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust +# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust +# Label: "IdenTrust Public Sector Root CA 1" +# Serial: 13298821034946342390521976156843933698 +# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba +# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd +# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu +VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN +MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0 +MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7 +ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy +RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS +bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF +/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R +3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw +EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy +9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V +GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ +2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV +WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD +W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN +AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj +t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV +DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9 +TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G +lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW +mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df +WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5 ++bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ +tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA +GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv +8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority - G2 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2009 Entrust, Inc. - for authorized use only +# Subject: CN=Entrust Root Certification Authority - G2 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2009 Entrust, Inc. - for authorized use only +# Label: "Entrust Root Certification Authority - G2" +# Serial: 1246989352 +# MD5 Fingerprint: 4b:e2:c9:91:96:65:0c:f4:0e:5a:93:92:a0:0a:fe:b2 +# SHA1 Fingerprint: 8c:f4:27:fd:79:0c:3a:d1:66:06:8d:e8:1e:57:ef:bb:93:22:72:d4 +# SHA256 Fingerprint: 43:df:57:74:b0:3e:7f:ef:5f:e4:0d:93:1a:7b:ed:f1:bb:2e:6b:42:73:8c:4e:6d:38:41:10:3d:3a:a7:f3:39 +-----BEGIN CERTIFICATE----- +MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50 +cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3Qs +IEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVz +dCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwHhcNMDkwNzA3MTcy +NTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUVu +dHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwt +dGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0 +aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP/vaCeb9zYQYKpSfYs1/T +RU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXzHHfV1IWN +cCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hW +wcKUs/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1 +U1+cPvQXLOZprE4yTGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0 +jaWvYkxN4FisZDQSA/i2jZRjJKRxAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ60B7vfec7aVHUbI2fkBJmqzAN +BgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5ZiXMRrEPR9RP/ +jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ +Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v +1fN2D807iDginWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4R +nAuknZoh8/CbCzB428Hch0P+vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmH +VHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xOe4pIb4tF9g== +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority - EC1 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2012 Entrust, Inc. - for authorized use only +# Subject: CN=Entrust Root Certification Authority - EC1 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2012 Entrust, Inc. - for authorized use only +# Label: "Entrust Root Certification Authority - EC1" +# Serial: 51543124481930649114116133369 +# MD5 Fingerprint: b6:7e:1d:f0:58:c5:49:6c:24:3b:3d:ed:98:18:ed:bc +# SHA1 Fingerprint: 20:d8:06:40:df:9b:25:f5:12:25:3a:11:ea:f7:59:8a:eb:14:b5:47 +# SHA256 Fingerprint: 02:ed:0e:b2:8c:14:da:45:16:5c:56:67:91:70:0d:64:51:d7:fb:56:f0:b2:ab:1d:3b:8e:b0:70:e5:6e:df:f5 +-----BEGIN CERTIFICATE----- +MIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkG +A1UEBhMCVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3 +d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVu +dHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEzMDEGA1UEAxMq +RW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRUMxMB4XDTEy +MTIxODE1MjUzNloXDTM3MTIxODE1NTUzNlowgb8xCzAJBgNVBAYTAlVTMRYwFAYD +VQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0 +L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxMiBFbnRydXN0LCBJbmMuIC0g +Zm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMzAxBgNVBAMTKkVudHJ1c3QgUm9vdCBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEVDMTB2MBAGByqGSM49AgEGBSuBBAAi +A2IABIQTydC6bUF74mzQ61VfZgIaJPRbiWlH47jCffHyAsWfoPZb1YsGGYZPUxBt +ByQnoaD41UcZYUx9ypMn6nQM72+WCf5j7HBdNq1nd67JnXxVRDqiY1Ef9eNi1KlH +Bz7MIKNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O +BBYEFLdj5xrdjekIplWDpOBqUEFlEUJJMAoGCCqGSM49BAMDA2cAMGQCMGF52OVC +R98crlOZF7ZvHH3hvxGU0QOIdeSNiaSKd0bebWHvAvX7td/M/k7//qnmpwIwW5nX +hTcGtXsI/esni0qU+eH6p44mCOh8kmhtc9hvJqwhAriZtyZBWyVgrtBIGu4G +-----END CERTIFICATE----- + +# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority +# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority +# Label: "CFCA EV ROOT" +# Serial: 407555286 +# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30 +# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83 +# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd +-----BEGIN CERTIFICATE----- +MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD +TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y +aXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx +MjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j +aWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP +T1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03 +sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL +TIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5 +/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp +7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz +EpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt +hxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP +a931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot +aK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg +TnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV +PKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv +cWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL +tbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd +BgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB +ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT +ej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL +jOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS +ESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy +P5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19 +xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d +Ci77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN +5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe +/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z +AAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ +5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su +-----END CERTIFICATE----- + +# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed +# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed +# Label: "OISTE WISeKey Global Root GB CA" +# Serial: 157768595616588414422159278966750757568 +# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d +# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed +# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6 +-----BEGIN CERTIFICATE----- +MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt +MQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg +Rm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i +YWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x +CzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG +b3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh +bCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3 +HEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx +WuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX +1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk +u7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P +99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r +M2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB +BAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh +cViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5 +gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO +ZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf +aPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic +Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM= +-----END CERTIFICATE----- + +# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. +# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. +# Label: "SZAFIR ROOT CA2" +# Serial: 357043034767186914217277344587386743377558296292 +# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99 +# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de +# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe +-----BEGIN CERTIFICATE----- +MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL +BQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6 +ZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw +NzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L +cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg +Uk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN +QLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT +3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw +3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6 +3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5 +BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN +XGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF +AAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw +8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG +nXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP +oky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy +d05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg +LvWpCz/UXeHPhJ/iGcJfitYgHuNztw== +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Network CA 2" +# Serial: 44979900017204383099463764357512596969 +# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2 +# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92 +# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 +-----BEGIN CERTIFICATE----- +MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB +gDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu +QS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG +A1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz +OTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ +VW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3 +b3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA +DGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn +0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB +OJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE +fktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E +Sv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m +o130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i +sx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW +OZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez +Tv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS +adgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n +3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ +F/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf +CVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29 +XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm +djWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/ +WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb +AoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq +P/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko +b7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj +XALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P +5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi +DrW5viSP +-----END CERTIFICATE----- + +# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Label: "Hellenic Academic and Research Institutions RootCA 2015" +# Serial: 0 +# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce +# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6 +# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36 +-----BEGIN CERTIFICATE----- +MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix +DzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k +IFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT +N0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v +dENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG +A1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh +ZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx +QDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 +dGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC +AQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA +4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0 +AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10 +4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C +ojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV +9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD +gfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6 +Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq +NhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko +LfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc +Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd +ctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I +XtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI +M4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot +9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V +Z5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea +j8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh +X9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ +l033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf +bzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4 +pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK +e7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0 +vm9qp/UsQu0yrbYhnr68 +-----END CERTIFICATE----- + +# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Label: "Hellenic Academic and Research Institutions ECC RootCA 2015" +# Serial: 0 +# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef +# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66 +# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33 +-----BEGIN CERTIFICATE----- +MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN +BgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl +c2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl +bGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv +b3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ +BgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj +YWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5 +MUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0 +dXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg +QehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa +jq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi +C4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep +lSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof +TUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR +-----END CERTIFICATE----- + +# Issuer: CN=ISRG Root X1 O=Internet Security Research Group +# Subject: CN=ISRG Root X1 O=Internet Security Research Group +# Label: "ISRG Root X1" +# Serial: 172886928669790476064670243504169061120 +# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e +# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8 +# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- + +# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM +# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM +# Label: "AC RAIZ FNMT-RCM" +# Serial: 485876308206448804701554682760554759 +# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d +# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20 +# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx +CzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ +WiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ +BgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG +Tk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/ +yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf +BBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz +WHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF +tBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z +374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC +IfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL +mbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7 +wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS +MKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2 +ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet +UqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H +YJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3 +LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD +nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1 +RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM +LVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf +77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N +JpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm +fZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp +6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp +1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B +9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok +RqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv +uu8wd+RU4riEmViAqhOLUTpPSPaLtrM= +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 1 O=Amazon +# Subject: CN=Amazon Root CA 1 O=Amazon +# Label: "Amazon Root CA 1" +# Serial: 143266978916655856878034712317230054538369994 +# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6 +# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16 +# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e +-----BEGIN CERTIFICATE----- +MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj +ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM +9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw +IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 +VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L +93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm +jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA +A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI +U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs +N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv +o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU +5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy +rqXRfboQnoZsG4q5WTP468SQvvG5 +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 2 O=Amazon +# Subject: CN=Amazon Root CA 2 O=Amazon +# Label: "Amazon Root CA 2" +# Serial: 143266982885963551818349160658925006970653239 +# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66 +# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a +# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4 +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK +gXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ +W0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg +1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K +8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r +2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me +z/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR +8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj +mUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz +7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6 ++XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI +0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB +Af8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm +UjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2 +LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY ++gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS +k5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl +7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm +btmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl +urR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+ +fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63 +n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE +76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H +9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT +4PsJYGw= +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 3 O=Amazon +# Subject: CN=Amazon Root CA 3 O=Amazon +# Label: "Amazon Root CA 3" +# Serial: 143266986699090766294700635381230934788665930 +# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87 +# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e +# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4 +-----BEGIN CERTIFICATE----- +MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5 +MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g +Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG +A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg +Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl +ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr +ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr +BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM +YyRIHN8wfdVoOw== +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 4 O=Amazon +# Subject: CN=Amazon Root CA 4 O=Amazon +# Label: "Amazon Root CA 4" +# Serial: 143266989758080763974105200630763877849284878 +# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd +# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be +# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92 +-----BEGIN CERTIFICATE----- +MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5 +MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g +Um9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG +A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg +Q0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi +9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk +M6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB +MAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw +CkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW +1KyLa2tJElMzrdfkviT8tQp21KW8EA== +-----END CERTIFICATE----- + +# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM +# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM +# Label: "TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1" +# Serial: 1 +# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49 +# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca +# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 +-----BEGIN CERTIFICATE----- +MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx +GDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp +bXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w +KwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0 +BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy +dW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG +EwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll +IEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU +QUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT +TTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg +LSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7 +a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr +LqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr +N3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X +YacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/ +iSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f +AJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH +V8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh +AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf +IPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4 +lzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c +8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf +lo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= +-----END CERTIFICATE----- + +# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. +# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. +# Label: "GDCA TrustAUTH R5 ROOT" +# Serial: 9009899650740120186 +# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4 +# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4 +# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93 +-----BEGIN CERTIFICATE----- +MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE +BhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ +IENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0 +MTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV +BAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w +HQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj +Dp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj +TnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u +KU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj +qcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm +MUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12 +ZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP +zgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk +L30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC +jGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA +HQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC +AwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg +p8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm +DRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5 +COmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry +L3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf +JWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg +IHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io +2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV +09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ +XR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq +T8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe +MTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g== +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation +# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation +# Label: "SSL.com Root Certification Authority RSA" +# Serial: 8875640296558310041 +# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29 +# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb +# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69 +-----BEGIN CERTIFICATE----- +MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE +BhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK +DA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz +OTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv +dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv +bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN +AQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R +xFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX +qhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC +C52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3 +6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh +/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF +YD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E +JNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc +US4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8 +ZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm ++Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi +M+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G +A1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV +cpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc +Hadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs +PgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/ +q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0 +cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr +a6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I +H37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y +K9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu +nLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf +oYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY +Ic2wBlX7Jz9TkHCpBB5XJ7k= +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation +# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation +# Label: "SSL.com Root Certification Authority ECC" +# Serial: 8495723813297216424 +# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e +# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a +# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65 +-----BEGIN CERTIFICATE----- +MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC +VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T +U0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz +WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0 +b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS +b290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI +7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg +CemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud +EwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD +VR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T +kdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+ +gA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation +# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation +# Label: "SSL.com EV Root Certification Authority RSA R2" +# Serial: 6248227494352943350 +# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95 +# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a +# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c +-----BEGIN CERTIFICATE----- +MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV +BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE +CgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy +dGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy +MDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G +A1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD +DC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq +M0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf +OePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa +4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9 +HSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR +aZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA +b9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ +Gp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV +PWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO +pgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu +UDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY +MBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV +HSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4 +9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW +s47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5 +Sm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg +cLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM +79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz +/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt +ll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm +Kf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK +QbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ +w/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi +S9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07 +mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w== +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation +# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation +# Label: "SSL.com EV Root Certification Authority ECC" +# Serial: 3182246526754555285 +# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90 +# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d +# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8 +-----BEGIN CERTIFICATE----- +MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC +VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T +U0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx +NTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv +dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv +bSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA +VIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku +WnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP +MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX +5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ +ytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg +h5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 +# Label: "GlobalSign Root CA - R6" +# Serial: 1417766617973444989252670301619537 +# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae +# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1 +# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69 +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg +MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh +bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx +MjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET +MBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI +xutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k +ZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD +aNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw +LnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw +1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX +k7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2 +SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h +bguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n +WUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY +rZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce +MgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu +bAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN +nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt +Ixg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61 +55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj +vUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf +cDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz +oHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp +nOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs +pA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v +JJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R +8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4 +5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA= +-----END CERTIFICATE----- + +# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed +# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed +# Label: "OISTE WISeKey Global Root GC CA" +# Serial: 44084345621038548146064804565436152554 +# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23 +# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31 +# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d +-----BEGIN CERTIFICATE----- +MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw +CQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91 +bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg +Um9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ +BgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu +ZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS +b290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni +eUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W +p2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T +rYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV +57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg +Mgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 +-----END CERTIFICATE----- + +# Issuer: CN=UCA Global G2 Root O=UniTrust +# Subject: CN=UCA Global G2 Root O=UniTrust +# Label: "UCA Global G2 Root" +# Serial: 124779693093741543919145257850076631279 +# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8 +# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a +# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9 +MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH +bG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x +CzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds +b2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr +b3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9 +kmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm +VHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R +VogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc +C/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj +tm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY +D0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv +j5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl +NaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6 +iIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP +O6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/ +BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV +ZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj +L3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5 +1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl +1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU +b3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV +PtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj +y88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb +EGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg +DMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI ++Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy +YiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX +UB+K+wb1whnw0A== +-----END CERTIFICATE----- + +# Issuer: CN=UCA Extended Validation Root O=UniTrust +# Subject: CN=UCA Extended Validation Root O=UniTrust +# Label: "UCA Extended Validation Root" +# Serial: 106100277556486529736699587978573607008 +# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2 +# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a +# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24 +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH +MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF +eHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx +MDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV +BAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog +D4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS +sPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop +O2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk +sHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi +c0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj +VMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz +KuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/ +TuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G +sx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs +1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD +fwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN +l8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR +ap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ +VBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5 +c6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp +4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s +t2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj +2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO +vpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C +xR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx +cmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM +fjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax +-----END CERTIFICATE----- + +# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 +# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 +# Label: "Certigna Root CA" +# Serial: 269714418870597844693661054334862075617 +# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77 +# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43 +# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68 +-----BEGIN CERTIFICATE----- +MIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw +WjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw +MiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x +MzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD +VQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX +BgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw +ggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO +ty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M +CiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu +I9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm +TLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh +C59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf +ePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz +IoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT +Co/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k +JWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5 +hwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB +GjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of +1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov +L3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo +dHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr +aHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq +hkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L +6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG +HVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6 +0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB +lA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi +o2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1 +gPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v +faci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63 +Nwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh +jWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw +3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0= +-----END CERTIFICATE----- + +# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI +# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI +# Label: "emSign Root CA - G1" +# Serial: 235931866688319308814040 +# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac +# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c +# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67 +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI +# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI +# Label: "emSign ECC Root CA - G3" +# Serial: 287880440101571086945156 +# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40 +# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1 +# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI +# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI +# Label: "emSign Root CA - C1" +# Serial: 825510296613316004955058 +# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68 +# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01 +# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f +-----BEGIN CERTIFICATE----- +MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG +A1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg +SW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw +MFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln +biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v +dCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ +BczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ +HdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH +3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH +GPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c +xSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1 +aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq +TbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87 +/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4 +kqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG +YQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT ++xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo +WXzhriKi4gp6D/piq1JM4fHfyr6DDUI= +-----END CERTIFICATE----- + +# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI +# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI +# Label: "emSign ECC Root CA - C3" +# Serial: 582948710642506000014504 +# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5 +# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66 +# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3 +-----BEGIN CERTIFICATE----- +MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG +EwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx +IDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw +MFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln +biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND +IFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci +MK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti +sIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O +BBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB +Af8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c +3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J +0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ== +-----END CERTIFICATE----- + +# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post +# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post +# Label: "Hongkong Post Root CA 3" +# Serial: 46170865288971385588281144162979347873371282084 +# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0 +# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02 +# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6 +-----BEGIN CERTIFICATE----- +MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL +BQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ +SG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n +a29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5 +NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT +CUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u +Z2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK +AoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO +dem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI +VoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV +9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY +2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY +vLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt +bNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb +x39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+ +l2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK +TE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj +Hno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e +i9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw +DQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG +7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk +MpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr +gZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk +GMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS +3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm +Ozj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+ +l6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c +JfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP +L5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa +LJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG +mpv0 +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority - G4 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2015 Entrust, Inc. - for authorized use only +# Subject: CN=Entrust Root Certification Authority - G4 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2015 Entrust, Inc. - for authorized use only +# Label: "Entrust Root Certification Authority - G4" +# Serial: 289383649854506086828220374796556676440 +# MD5 Fingerprint: 89:53:f1:83:23:b7:7c:8e:05:f1:8c:71:38:4e:1f:88 +# SHA1 Fingerprint: 14:88:4e:86:26:37:b0:26:af:59:62:5c:40:77:ec:35:29:ba:96:01 +# SHA256 Fingerprint: db:35:17:d1:f6:73:2a:2d:5a:b9:7c:53:3e:c7:07:79:ee:32:70:a6:2f:b4:ac:42:38:37:24:60:e6:f0:1e:88 +-----BEGIN CERTIFICATE----- +MIIGSzCCBDOgAwIBAgIRANm1Q3+vqTkPAAAAAFVlrVgwDQYJKoZIhvcNAQELBQAw +gb4xCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQL +Ex9TZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykg +MjAxNSBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMjAw +BgNVBAMTKUVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc0 +MB4XDTE1MDUyNzExMTExNloXDTM3MTIyNzExNDExNlowgb4xCzAJBgNVBAYTAlVT +MRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1 +c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxNSBFbnRydXN0LCBJ +bmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMjAwBgNVBAMTKUVudHJ1c3Qg +Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc0MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAsewsQu7i0TD/pZJH4i3DumSXbcr3DbVZwbPLqGgZ +2K+EbTBwXX7zLtJTmeH+H17ZSK9dE43b/2MzTdMAArzE+NEGCJR5WIoV3imz/f3E +T+iq4qA7ec2/a0My3dl0ELn39GjUu9CH1apLiipvKgS1sqbHoHrmSKvS0VnM1n4j +5pds8ELl3FFLFUHtSUrJ3hCX1nbB76W1NhSXNdh4IjVS70O92yfbYVaCNNzLiGAM +C1rlLAHGVK/XqsEQe9IFWrhAnoanw5CGAlZSCXqc0ieCU0plUmr1POeo8pyvi73T +DtTUXm6Hnmo9RR3RXRv06QqsYJn7ibT/mCzPfB3pAqoEmh643IhuJbNsZvc8kPNX +wbMv9W3y+8qh+CmdRouzavbmZwe+LGcKKh9asj5XxNMhIWNlUpEbsZmOeX7m640A +2Vqq6nPopIICR5b+W45UYaPrL0swsIsjdXJ8ITzI9vF01Bx7owVV7rtNOzK+mndm +nqxpkCIHH2E6lr7lmk/MBTwoWdPBDFSoWWG9yHJM6Nyfh3+9nEg2XpWjDrk4JFX8 +dWbrAuMINClKxuMrLzOg2qOGpRKX/YAr2hRC45K9PvJdXmd0LhyIRyk0X+IyqJwl +N4y6mACXi0mWHv0liqzc2thddG5msP9E36EYxr5ILzeUePiVSj9/E15dWf10hkNj +c0kCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFJ84xFYjwznooHFs6FRM5Og6sb9nMA0GCSqGSIb3DQEBCwUAA4ICAQAS +5UKme4sPDORGpbZgQIeMJX6tuGguW8ZAdjwD+MlZ9POrYs4QjbRaZIxowLByQzTS +Gwv2LFPSypBLhmb8qoMi9IsabyZIrHZ3CL/FmFz0Jomee8O5ZDIBf9PD3Vht7LGr +hFV0d4QEJ1JrhkzO3bll/9bGXp+aEJlLdWr+aumXIOTkdnrG0CSqkM0gkLpHZPt/ +B7NTeLUKYvJzQ85BK4FqLoUWlFPUa19yIqtRLULVAJyZv967lDtX/Zr1hstWO1uI +AeV8KEsD+UmDfLJ/fOPtjqF/YFOOVZ1QNBIPt5d7bIdKROf1beyAN/BYGW5KaHbw +H5Lk6rWS02FREAutp9lfx1/cH6NcjKF+m7ee01ZvZl4HliDtC3T7Zk6LERXpgUl+ +b7DUUH8i119lAg2m9IUe2K4GS0qn0jFmwvjO5QimpAKWRGhXxNUzzxkvFMSUHHuk +2fCfDrGA4tGeEWSpiBE6doLlYsKA2KSD7ZPvfC+QsDJMlhVoSFLUmQjAJOgc47Ol +IQ6SwJAfzyBfyjs4x7dtOvPmRLgOMWuIjnDrnBdSqEGULoe256YSxXXfW8AKbnuk +5F6G+TaU33fD6Q3AOfF5u0aOq0NZJ7cguyPpVkAh7DE9ZapD8j3fcEThuk0mEDuY +n/PIjhs4ViFqUZPTkcpG2om3PVODLAgfi49T3f+sHw== +-----END CERTIFICATE----- + +# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation +# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation +# Label: "Microsoft ECC Root Certificate Authority 2017" +# Serial: 136839042543790627607696632466672567020 +# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67 +# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5 +# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02 +-----BEGIN CERTIFICATE----- +MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw +CQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD +VQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw +MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV +UzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy +b3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR +ogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb +hGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3 +FQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV +L8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB +iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M= +-----END CERTIFICATE----- + +# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation +# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation +# Label: "Microsoft RSA Root Certificate Authority 2017" +# Serial: 40975477897264996090493496164228220339 +# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47 +# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74 +# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0 +-----BEGIN CERTIFICATE----- +MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl +MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw +NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 +IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG +EwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N +aWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ +Nt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0 +ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1 +HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm +gGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ +jEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc +aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG +YaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6 +W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K +UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH ++FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q +W5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC +NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC +LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC +gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6 +tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh +SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2 +TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3 +pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR +xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp +GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9 +dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN +AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB +RA+GsCyRxj3qrg+E +-----END CERTIFICATE----- + +# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd. +# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd. +# Label: "e-Szigno Root CA 2017" +# Serial: 411379200276854331539784714 +# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98 +# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1 +# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99 +-----BEGIN CERTIFICATE----- +MIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV +BAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk +LjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv +b3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ +BgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg +THRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v +IFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv +xie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H +Wyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB +eAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo +jbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ ++efcMQ== +-----END CERTIFICATE----- + +# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2 +# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2 +# Label: "certSIGN Root CA G2" +# Serial: 313609486401300475190 +# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7 +# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32 +# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05 +-----BEGIN CERTIFICATE----- +MIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV +BAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g +Uk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ +BgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ +R04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF +dRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw +vlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ +uIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp +n+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs +cpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW +xPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P +rCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF +DsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx +DTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy +LcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C +eWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ +d8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq +kX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC +b6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl +qiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0 +OJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c +NywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk +ltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO +pwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj +03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk +PuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE +1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX +QRBdJ3NghVdJIgc= +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global Certification Authority" +# Serial: 1846098327275375458322922162 +# MD5 Fingerprint: f8:1c:18:2d:2f:ba:5f:6d:a1:6c:bc:c7:ab:91:c7:0e +# SHA1 Fingerprint: 2f:8f:36:4f:e1:58:97:44:21:59:87:a5:2a:9a:d0:69:95:26:7f:b5 +# SHA256 Fingerprint: 97:55:20:15:f5:dd:fc:3c:87:88:c0:06:94:45:55:40:88:94:45:00:84:f1:00:86:70:86:bc:1a:2b:b5:8d:c8 +-----BEGIN CERTIFICATE----- +MIIF2jCCA8KgAwIBAgIMBfcOhtpJ80Y1LrqyMA0GCSqGSIb3DQEBCwUAMIGIMQsw +CQYDVQQGEwJVUzERMA8GA1UECAwISWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28x +ITAfBgNVBAoMGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1 +c3R3YXZlIEdsb2JhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0xNzA4MjMx +OTM0MTJaFw00MjA4MjMxOTM0MTJaMIGIMQswCQYDVQQGEwJVUzERMA8GA1UECAwI +SWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28xITAfBgNVBAoMGFRydXN0d2F2ZSBI +b2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1c3R3YXZlIEdsb2JhbCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB +ALldUShLPDeS0YLOvR29zd24q88KPuFd5dyqCblXAj7mY2Hf8g+CY66j96xz0Xzn +swuvCAAJWX/NKSqIk4cXGIDtiLK0thAfLdZfVaITXdHG6wZWiYj+rDKd/VzDBcdu +7oaJuogDnXIhhpCujwOl3J+IKMujkkkP7NAP4m1ET4BqstTnoApTAbqOl5F2brz8 +1Ws25kCI1nsvXwXoLG0R8+eyvpJETNKXpP7ScoFDB5zpET71ixpZfR9oWN0EACyW +80OzfpgZdNmcc9kYvkHHNHnZ9GLCQ7mzJ7Aiy/k9UscwR7PJPrhq4ufogXBeQotP +JqX+OsIgbrv4Fo7NDKm0G2x2EOFYeUY+VM6AqFcJNykbmROPDMjWLBz7BegIlT1l +RtzuzWniTY+HKE40Cz7PFNm73bZQmq131BnW2hqIyE4bJ3XYsgjxroMwuREOzYfw +hI0Vcnyh78zyiGG69Gm7DIwLdVcEuE4qFC49DxweMqZiNu5m4iK4BUBjECLzMx10 +coos9TkpoNPnG4CELcU9402x/RpvumUHO1jsQkUm+9jaJXLE9gCxInm943xZYkqc +BW89zubWR2OZxiRvchLIrH+QtAuRcOi35hYQcRfO3gZPSEF9NUqjifLJS3tBEW1n +twiYTOURGa5CgNz7kAXU+FDKvuStx8KU1xad5hePrzb7AgMBAAGjQjBAMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFJngGWcNYtt2s9o9uFvo/ULSMQ6HMA4GA1Ud +DwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAmHNw4rDT7TnsTGDZqRKGFx6W +0OhUKDtkLSGm+J1WE2pIPU/HPinbbViDVD2HfSMF1OQc3Og4ZYbFdada2zUFvXfe +uyk3QAUHw5RSn8pk3fEbK9xGChACMf1KaA0HZJDmHvUqoai7PF35owgLEQzxPy0Q +lG/+4jSHg9bP5Rs1bdID4bANqKCqRieCNqcVtgimQlRXtpla4gt5kNdXElE1GYhB +aCXUNxeEFfsBctyV3lImIJgm4nb1J2/6ADtKYdkNy1GTKv0WBpanI5ojSP5RvbbE +sLFUzt5sQa0WZ37b/TjNuThOssFgy50X31ieemKyJo90lZvkWx3SD92YHJtZuSPT +MaCm/zjdzyBP6VhWOmfD0faZmZ26NraAL4hHT4a/RDqA5Dccprrql5gR0IRiR2Qe +qu5AvzSxnI9O4fKSTx+O856X3vOmeWqJcU9LJxdI/uz0UA9PSX3MReO9ekDFQdxh +VicGaeVyQYHTtgGJoC86cnn+OjC/QezHYj6RS8fZMXZC+fc8Y+wmjHMMfRod6qh8 +h6jCJ3zhM0EPz8/8AKAigJ5Kp28AsEFFtyLKaEjFQqKu3R3y4G5OBVixwJAWKqQ9 +EEC+j2Jjg6mcgn0tAumDMHzLJ8n9HmYAsC7TIS+OMxZsmO0QqAfWzJPP29FpHOTK +yeC2nOnOcXHebD8WpHk= +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global ECC P256 Certification Authority" +# Serial: 4151900041497450638097112925 +# MD5 Fingerprint: 5b:44:e3:8d:5d:36:86:26:e8:0d:05:d2:59:a7:83:54 +# SHA1 Fingerprint: b4:90:82:dd:45:0c:be:8b:5b:b1:66:d3:e2:a4:08:26:cd:ed:42:cf +# SHA256 Fingerprint: 94:5b:bc:82:5e:a5:54:f4:89:d1:fd:51:a7:3d:df:2e:a6:24:ac:70:19:a0:52:05:22:5c:22:a7:8c:cf:a8:b4 +-----BEGIN CERTIFICATE----- +MIICYDCCAgegAwIBAgIMDWpfCD8oXD5Rld9dMAoGCCqGSM49BAMCMIGRMQswCQYD +VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf +BgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3 +YXZlIEdsb2JhbCBFQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x +NzA4MjMxOTM1MTBaFw00MjA4MjMxOTM1MTBaMIGRMQswCQYDVQQGEwJVUzERMA8G +A1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0 +d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF +Q0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTBZMBMGByqGSM49AgEGCCqG +SM49AwEHA0IABH77bOYj43MyCMpg5lOcunSNGLB4kFKA3TjASh3RqMyTpJcGOMoN +FWLGjgEqZZ2q3zSRLoHB5DOSMcT9CTqmP62jQzBBMA8GA1UdEwEB/wQFMAMBAf8w +DwYDVR0PAQH/BAUDAwcGADAdBgNVHQ4EFgQUo0EGrJBt0UrrdaVKEJmzsaGLSvcw +CgYIKoZIzj0EAwIDRwAwRAIgB+ZU2g6gWrKuEZ+Hxbb/ad4lvvigtwjzRM4q3wgh +DDcCIC0mA6AFvWvR9lz4ZcyGbbOcNEhjhAnFjXca4syc4XR7 +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global ECC P384 Certification Authority" +# Serial: 2704997926503831671788816187 +# MD5 Fingerprint: ea:cf:60:c4:3b:b9:15:29:40:a1:97:ed:78:27:93:d6 +# SHA1 Fingerprint: e7:f3:a3:c8:cf:6f:c3:04:2e:6d:0e:67:32:c5:9e:68:95:0d:5e:d2 +# SHA256 Fingerprint: 55:90:38:59:c8:c0:c3:eb:b8:75:9e:ce:4e:25:57:22:5f:f5:75:8b:bd:38:eb:d4:82:76:60:1e:1b:d5:80:97 +-----BEGIN CERTIFICATE----- +MIICnTCCAiSgAwIBAgIMCL2Fl2yZJ6SAaEc7MAoGCCqGSM49BAMDMIGRMQswCQYD +VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf +BgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3 +YXZlIEdsb2JhbCBFQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x +NzA4MjMxOTM2NDNaFw00MjA4MjMxOTM2NDNaMIGRMQswCQYDVQQGEwJVUzERMA8G +A1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0 +d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF +Q0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTB2MBAGByqGSM49AgEGBSuB +BAAiA2IABGvaDXU1CDFHBa5FmVXxERMuSvgQMSOjfoPTfygIOiYaOs+Xgh+AtycJ +j9GOMMQKmw6sWASr9zZ9lCOkmwqKi6vr/TklZvFe/oyujUF5nQlgziip04pt89ZF +1PKYhDhloKNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0G +A1UdDgQWBBRVqYSJ0sEyvRjLbKYHTsjnnb6CkDAKBggqhkjOPQQDAwNnADBkAjA3 +AZKXRRJ+oPM+rRk6ct30UJMDEr5E0k9BpIycnR+j9sKS50gU/k6bpZFXrsY3crsC +MGclCrEMXu6pY5Jv5ZAL/mYiykf9ijH3g/56vxC+GCsej/YpHpRZ744hN8tRmKVu +Sw== +-----END CERTIFICATE----- + +# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. +# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. +# Label: "NAVER Global Root Certification Authority" +# Serial: 9013692873798656336226253319739695165984492813 +# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b +# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1 +# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65 +-----BEGIN CERTIFICATE----- +MIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM +BQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG +T1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx +CzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD +b3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA +iQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH +38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE +HoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz +kVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP +szuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq +vC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf +nZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG +YQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo +0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a +CJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K +AQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I +36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB +Af8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN +qo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj +cu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm ++LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL +hr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe +lHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7 +p/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8 +piKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR +LBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX +5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO +dh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul +9XXeifdy +-----END CERTIFICATE----- + +# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres +# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres +# Label: "AC RAIZ FNMT-RCM SERVIDORES SEGUROS" +# Serial: 131542671362353147877283741781055151509 +# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb +# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a +# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb +-----BEGIN CERTIFICATE----- +MIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw +CQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw +FgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S +Q00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5 +MzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL +DAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS +QUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH +sbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK +Um8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu +SuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC +MQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy +v+c= +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa +# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa +# Label: "GlobalSign Root R46" +# Serial: 1552617688466950547958867513931858518042577 +# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef +# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90 +# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9 +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA +MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD +VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy +MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt +c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ +OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG +vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud +316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo +0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE +y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF +zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE ++cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN +I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs +x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa +ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC +4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4 +7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg +JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti +2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk +pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF +FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt +rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk +ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5 +u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP +4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6 +N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3 +vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6 +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa +# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa +# Label: "GlobalSign Root E46" +# Serial: 1552617690338932563915843282459653771421763 +# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f +# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84 +# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58 +-----BEGIN CERTIFICATE----- +MIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx +CzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD +ExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw +MDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex +HDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq +R+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd +yXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud +DgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ +7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8 ++RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A= +-----END CERTIFICATE----- + +# Issuer: CN=GLOBALTRUST 2020 O=e-commerce monitoring GmbH +# Subject: CN=GLOBALTRUST 2020 O=e-commerce monitoring GmbH +# Label: "GLOBALTRUST 2020" +# Serial: 109160994242082918454945253 +# MD5 Fingerprint: 8a:c7:6f:cb:6d:e3:cc:a2:f1:7c:83:fa:0e:78:d7:e8 +# SHA1 Fingerprint: d0:67:c1:13:51:01:0c:aa:d0:c7:6a:65:37:31:16:26:4f:53:71:a2 +# SHA256 Fingerprint: 9a:29:6a:51:82:d1:d4:51:a2:e3:7f:43:9b:74:da:af:a2:67:52:33:29:f9:0f:9a:0d:20:07:c3:34:e2:3c:9a +-----BEGIN CERTIFICATE----- +MIIFgjCCA2qgAwIBAgILWku9WvtPilv6ZeUwDQYJKoZIhvcNAQELBQAwTTELMAkG +A1UEBhMCQVQxIzAhBgNVBAoTGmUtY29tbWVyY2UgbW9uaXRvcmluZyBHbWJIMRkw +FwYDVQQDExBHTE9CQUxUUlVTVCAyMDIwMB4XDTIwMDIxMDAwMDAwMFoXDTQwMDYx +MDAwMDAwMFowTTELMAkGA1UEBhMCQVQxIzAhBgNVBAoTGmUtY29tbWVyY2UgbW9u +aXRvcmluZyBHbWJIMRkwFwYDVQQDExBHTE9CQUxUUlVTVCAyMDIwMIICIjANBgkq +hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAri5WrRsc7/aVj6B3GyvTY4+ETUWiD59b +RatZe1E0+eyLinjF3WuvvcTfk0Uev5E4C64OFudBc/jbu9G4UeDLgztzOG53ig9Z +YybNpyrOVPu44sB8R85gfD+yc/LAGbaKkoc1DZAoouQVBGM+uq/ufF7MpotQsjj3 +QWPKzv9pj2gOlTblzLmMCcpL3TGQlsjMH/1WljTbjhzqLL6FLmPdqqmV0/0plRPw +yJiT2S0WR5ARg6I6IqIoV6Lr/sCMKKCmfecqQjuCgGOlYx8ZzHyyZqjC0203b+J+ +BlHZRYQfEs4kUmSFC0iAToexIiIwquuuvuAC4EDosEKAA1GqtH6qRNdDYfOiaxaJ +SaSjpCuKAsR49GiKweR6NrFvG5Ybd0mN1MkGco/PU+PcF4UgStyYJ9ORJitHHmkH +r96i5OTUawuzXnzUJIBHKWk7buis/UDr2O1xcSvy6Fgd60GXIsUf1DnQJ4+H4xj0 +4KlGDfV0OoIu0G4skaMxXDtG6nsEEFZegB31pWXogvziB4xiRfUg3kZwhqG8k9Me +dKZssCz3AwyIDMvUclOGvGBG85hqwvG/Q/lwIHfKN0F5VVJjjVsSn8VoxIidrPIw +q7ejMZdnrY8XD2zHc+0klGvIg5rQmjdJBKuxFshsSUktq6HQjJLyQUp5ISXbY9e2 +nKd+Qmn7OmMCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFNwuH9FhN3nkq9XVsxJxaD1qaJwiMB8GA1UdIwQYMBaAFNwu +H9FhN3nkq9XVsxJxaD1qaJwiMA0GCSqGSIb3DQEBCwUAA4ICAQCR8EICaEDuw2jA +VC/f7GLDw56KoDEoqoOOpFaWEhCGVrqXctJUMHytGdUdaG/7FELYjQ7ztdGl4wJC +XtzoRlgHNQIw4Lx0SsFDKv/bGtCwr2zD/cuz9X9tAy5ZVp0tLTWMstZDFyySCstd +6IwPS3BD0IL/qMy/pJTAvoe9iuOTe8aPmxadJ2W8esVCgmxcB9CpwYhgROmYhRZf ++I/KARDOJcP5YBugxZfD0yyIMaK9MOzQ0MAS8cE54+X1+NZK3TTN+2/BT+MAi1bi +kvcoskJ3ciNnxz8RFbLEAwW+uxF7Cr+obuf/WEPPm2eggAe2HcqtbepBEX4tdJP7 +wry+UUTF72glJ4DjyKDUEuzZpTcdN3y0kcra1LGWge9oXHYQSa9+pTeAsRxSvTOB +TI/53WXZFM2KJVj04sWDpQmQ1GwUY7VA3+vA/MRYfg0UFodUJ25W5HCEuGwyEn6C +MUO+1918oa2u1qsgEu8KwxCMSZY13At1XrFP1U80DhEgB3VDRemjEdqso5nCtnkn +4rnvyOL2NSl6dPrFf4IFYqYK6miyeUcGbvJXqBUzxvd4Sj1Ce2t+/vdG6tHrju+I +aFvowdlxfv1k7/9nR4hYJS8+hge9+6jlgqispdNpQ80xiEmEU5LAsTkbOYMBMMTy +qfrQA71yN2BWHzZ8vTmR9W0Nv3vXkg== +-----END CERTIFICATE----- + +# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz +# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz +# Label: "ANF Secure Server Root CA" +# Serial: 996390341000653745 +# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96 +# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74 +# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99 +-----BEGIN CERTIFICATE----- +MIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV +BAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk +YWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV +BAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN +MzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF +UzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD +VQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v +dCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj +cqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q +yGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH +2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX +H1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL +zc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR +p1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz +W7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/ +SiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn +LNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3 +n5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B +u8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj +o1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC +AgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L +9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej +rw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK +pFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0 +vPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq +OknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ +/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9 +2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI ++PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2 +MjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo +tt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw= +-----END CERTIFICATE----- + +# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Label: "Certum EC-384 CA" +# Serial: 160250656287871593594747141429395092468 +# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1 +# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed +# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6 +-----BEGIN CERTIFICATE----- +MIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw +CQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw +JQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT +EENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0 +WjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT +LkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX +BgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE +KI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm +Fy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8 +EF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J +UG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn +nvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k= +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Root CA" +# Serial: 40870380103424195783807378461123655149 +# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29 +# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5 +# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd +-----BEGIN CERTIFICATE----- +MIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6 +MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu +MScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV +BAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw +MzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg +U3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo +b3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ +n0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q +p1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq +NwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF +8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3 +HAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa +mqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi +7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF +ytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P +qafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ +v3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6 +Tsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1 +vALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD +ggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4 +WxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo +zMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR +5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ +GfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf +5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq +0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D +P78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM +qJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP +0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf +E2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb +-----END CERTIFICATE----- + +# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique +# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique +# Label: "TunTrust Root CA" +# Serial: 108534058042236574382096126452369648152337120275 +# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4 +# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb +# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41 +-----BEGIN CERTIFICATE----- +MIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL +BQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg +Q2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv +b3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG +EwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u +IEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ +n56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd +2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF +VwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ +GoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF +li/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU +r8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2 +eY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb +MlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg +jwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB +7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW +5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE +ITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0 +90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z +xiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu +QEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4 +FstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH +22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP +xOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn +dFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5 +Xc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b +nV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ +CvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH +u/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj +d9qDRIueVSjAi1jTkD5OGwDxFa2DK5o= +-----END CERTIFICATE----- + +# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Label: "HARICA TLS RSA Root CA 2021" +# Serial: 76817823531813593706434026085292783742 +# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91 +# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d +# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d +-----BEGIN CERTIFICATE----- +MIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs +MQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl +c2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg +Um9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL +MAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl +YXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv +b3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l +mwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE +4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv +a9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M +pbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw +Kh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b +LW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY +AuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB +AGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq +E613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr +W2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ +CoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE +AwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU +X15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3 +f5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja +H6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP +JzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P +zzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt +jBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0 +/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT +BGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79 +aPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW +xw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU +63ZTGI0RmLo= +-----END CERTIFICATE----- + +# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Label: "HARICA TLS ECC Root CA 2021" +# Serial: 137515985548005187474074462014555733966 +# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0 +# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48 +# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01 +-----BEGIN CERTIFICATE----- +MIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw +CQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh +cmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v +dCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG +A1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj +aCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg +Q0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7 +KKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y +STHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD +AgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw +SaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN +nxS2PFOiTAZpffpskcYqSUXm7LcT4Tps +-----END CERTIFICATE----- + +# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Label: "Autoridad de Certificacion Firmaprofesional CIF A62634068" +# Serial: 1977337328857672817 +# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3 +# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe +# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a +-----BEGIN CERTIFICATE----- +MIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE +BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h +cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1 +MDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg +Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9 +thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM +cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG +L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i +NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h +X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b +m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy +Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja +EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T +KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF +6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh +OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc +tHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd +IAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j +b20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC +AG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw +ADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m +iWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF +Sa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ +hfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P +Vf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE +EAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV +1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t +CsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR +5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw +f9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9 +ivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK +GbqEZycPvEJdvSRUDewdcAZfpLz6IHxV +-----END CERTIFICATE----- + +# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. +# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. +# Label: "vTrus ECC Root CA" +# Serial: 630369271402956006249506845124680065938238527194 +# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85 +# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1 +# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3 +-----BEGIN CERTIFICATE----- +MIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw +RzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY +BgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz +MTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u +LEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0 +v/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd +e4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD +VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw +V53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA +AjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG +GJTO +-----END CERTIFICATE----- + +# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd. +# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd. +# Label: "vTrus Root CA" +# Serial: 387574501246983434957692974888460947164905180485 +# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc +# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7 +# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87 +-----BEGIN CERTIFICATE----- +MIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL +BQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x +FjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx +MDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s +THRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc +IrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU +AyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+ +GrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9 +8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH +flqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt +J8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim +0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN +pGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ +UqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW +OXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB +AAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet +8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd +nxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j +bhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM +Kar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv +TDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS +S8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr +I8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9 +b91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB +UvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P +Ti07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven +sBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s= +-----END CERTIFICATE----- + +# Issuer: CN=ISRG Root X2 O=Internet Security Research Group +# Subject: CN=ISRG Root X2 O=Internet Security Research Group +# Label: "ISRG Root X2" +# Serial: 87493402998870891108772069816698636114 +# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5 +# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af +# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70 +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- + +# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. +# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. +# Label: "HiPKI Root CA - G1" +# Serial: 60966262342023497858655262305426234976 +# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3 +# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60 +# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc +-----BEGIN CERTIFICATE----- +MIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa +Fw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3 +YSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw +qNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv +Vcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6 +lZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz +Qs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ +KILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK +FgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj +HluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr +y+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ +/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM +a/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6 +fsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG +SIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi +7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc +SE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza +ZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc +XzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg +iLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho +L5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF +Ne85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr +kkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+ +vhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU +YDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 +# Label: "GlobalSign ECC Root CA - R4" +# Serial: 159662223612894884239637590694 +# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc +# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28 +# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2 +-----BEGIN CERTIFICATE----- +MIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD +VQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh +bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw +MTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g +UjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx +uYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV +HQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/ ++wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147 +bmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R1 O=Google Trust Services LLC +# Subject: CN=GTS Root R1 O=Google Trust Services LLC +# Label: "GTS Root R1" +# Serial: 159662320309726417404178440727 +# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40 +# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a +# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo +27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w +Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw +TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl +qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH +szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8 +Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk +MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92 +wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p +aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN +VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb +C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe +QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy +h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4 +7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J +ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef +MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/ +Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT +6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ +0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm +2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb +bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R2 O=Google Trust Services LLC +# Subject: CN=GTS Root R2 O=Google Trust Services LLC +# Label: "GTS Root R2" +# Serial: 159662449406622349769042896298 +# MD5 Fingerprint: 1e:39:c0:53:e6:1e:29:82:0b:ca:52:55:36:5d:57:dc +# SHA1 Fingerprint: 9a:44:49:76:32:db:de:fa:d0:bc:fb:5a:7b:17:bd:9e:56:09:24:94 +# SHA256 Fingerprint: 8d:25:cd:97:22:9d:bf:70:35:6b:da:4e:b3:cc:73:40:31:e2:4c:f0:0f:af:cf:d3:2d:c7:6e:b5:84:1c:7e:a8 +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlrsWNBCUaqxElqjANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTukk3LvCvpt +nfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+cnfgLFuv5AS/T3KgGjSY +6Dlo7JUle3ah5mm5hRm9iYz+re026nO8/4Piy33B0s5Ks40FnotJk9/BW9BuXvAu +MC6C/Pq8tBcKSOWIm8Wba96wyrQD8Nr0kLhlZPdcTK3ofmZemde4wj7I0BOdre7k +RXuJVfeKH2JShBKzwkCX44ofR5GmdFrS+LFjKBC4swm4VndAoiaYecb+3yXuPuWg +f9RhD1FLPD+M2uFwdNjCaKH5wQzpoeJ/u1U8dgbuak7MkogwTZq9TwtImoS1mKPV ++3PBV2HdKFZ1E66HjucMUQkQdYhMvI35ezzUIkgfKtzra7tEscszcTJGr61K8Yzo +dDqs5xoic4DSMPclQsciOzsSrZYuxsN2B6ogtzVJV+mSSeh2FnIxZyuWfoqjx5RW +Ir9qS34BIbIjMt/kmkRtWVtd9QCgHJvGeJeNkP+byKq0rxFROV7Z+2et1VsRnTKa +G73VululycslaVNVJ1zgyjbLiGH7HrfQy+4W+9OmTN6SpdTi3/UGVN4unUu0kzCq +gc7dGtxRcw1PcOnlthYhGXmy5okLdWTK1au8CcEYof/UVKGFPP0UJAOyh9OktwID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQUu//KjiOfT5nK2+JopqUVJxce2Q4wDQYJKoZIhvcNAQEMBQADggIBAB/Kzt3H +vqGf2SdMC9wXmBFqiN495nFWcrKeGk6c1SuYJF2ba3uwM4IJvd8lRuqYnrYb/oM8 +0mJhwQTtzuDFycgTE1XnqGOtjHsB/ncw4c5omwX4Eu55MaBBRTUoCnGkJE+M3DyC +B19m3H0Q/gxhswWV7uGugQ+o+MePTagjAiZrHYNSVc61LwDKgEDg4XSsYPWHgJ2u +NmSRXbBoGOqKYcl3qJfEycel/FVL8/B/uWU9J2jQzGv6U53hkRrJXRqWbTKH7QMg +yALOWr7Z6v2yTcQvG99fevX4i8buMTolUVVnjWQye+mew4K6Ki3pHrTgSAai/Gev +HyICc/sgCq+dVEuhzf9gR7A/Xe8bVr2XIZYtCtFenTgCR2y59PYjJbigapordwj6 +xLEokCZYCDzifqrXPW+6MYgKBesntaFJ7qBFVHvmJ2WZICGoo7z7GJa7Um8M7YNR +TOlZ4iBgxcJlkoKM8xAfDoqXvneCbT+PHV28SSe9zE8P4c52hgQjxcCMElv924Sg +JPFI/2R80L5cFtHvma3AH/vLrrw4IgYmZNralw4/KBVEqE8AyvCazM90arQ+POuV +7LXTWtiBmelDGDfrs7vRWGJB82bSj6p4lVQgw1oudCvV0b4YacCs1aTPObpRhANl +6WLAYv7YTVWW4tAR+kg0Eeye7QUd5MjWHYbL +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R3 O=Google Trust Services LLC +# Subject: CN=GTS Root R3 O=Google Trust Services LLC +# Label: "GTS Root R3" +# Serial: 159662495401136852707857743206 +# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73 +# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46 +# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48 +-----BEGIN CERTIFICATE----- +MIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD +VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG +A1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw +WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz +IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G +jOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2 +4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7 +VKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm +ZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R4 O=Google Trust Services LLC +# Subject: CN=GTS Root R4 O=Google Trust Services LLC +# Label: "GTS Root R4" +# Serial: 159662532700760215368942768210 +# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8 +# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47 +# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d +-----BEGIN CERTIFICATE----- +MIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD +VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG +A1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw +WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz +IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi +QHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR +HYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D +9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8 +p/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD +-----END CERTIFICATE----- + +# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj +# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj +# Label: "Telia Root CA v2" +# Serial: 7288924052977061235122729490515358 +# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48 +# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd +# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx +CzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE +AwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1 +NTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ +MBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq +AMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9 +vVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9 +lRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD +n3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT +7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o +6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC +TEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6 +WT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R +DolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI +pEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj +YzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy +rOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ +8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi +0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM +A8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS +SRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K +TTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF +6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er +3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt +Ty3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT +VmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW +ysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA +rBPuUBQemMc= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH +# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH +# Label: "D-TRUST BR Root CA 1 2020" +# Serial: 165870826978392376648679885835942448534 +# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed +# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67 +# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44 +-----BEGIN CERTIFICATE----- +MIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw +CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS +VVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5 +NDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG +A1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB +BAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS +zuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0 +QVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/ +VbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g +PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf +Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l +dC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 +c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO +PQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW +wKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV +dWNbFJWcHwHP2NVypw87 +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH +# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH +# Label: "D-TRUST EV Root CA 1 2020" +# Serial: 126288379621884218666039612629459926992 +# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e +# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07 +# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db +-----BEGIN CERTIFICATE----- +MIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw +CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS +VVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5 +NTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG +A1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB +BAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC +/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD +wpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3 +OqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g +PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf +Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l +dC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 +c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO +PQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA +y/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb +gfM0agPnIjhQW+0ZT0MW +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. +# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. +# Label: "DigiCert TLS ECC P384 Root G5" +# Serial: 13129116028163249804115411775095713523 +# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed +# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee +# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05 +-----BEGIN CERTIFICATE----- +MIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp +Z2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2 +MDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ +bmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS +7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp +0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS +B4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 +BAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ +LgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4 +DXZDjC5Ty3zfDBeWUA== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. +# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. +# Label: "DigiCert TLS RSA4096 Root G5" +# Serial: 11930366277458970227240571539258396554 +# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1 +# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35 +# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75 +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN +MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT +HERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN +NDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs +IEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+ +ajWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0 +2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp +wgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM +pG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD +nU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po +sMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx +Zre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd +Lvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX +KyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe +XoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL +tgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv +TiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN +AQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw +GXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H +PNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF +O4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ +REtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik +AdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv +/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+ +p6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw +MUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF +qUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK +ovfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+ +-----END CERTIFICATE----- + +# Issuer: CN=Certainly Root R1 O=Certainly +# Subject: CN=Certainly Root R1 O=Certainly +# Label: "Certainly Root R1" +# Serial: 188833316161142517227353805653483829216 +# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12 +# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af +# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0 +-----BEGIN CERTIFICATE----- +MIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw +PTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy +dGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9 +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0 +YWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2 +1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT +vqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed +aFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0 +1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5 +r3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5 +cBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ +wHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ +6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA +2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH +Wyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR +eiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB +/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u +d0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr +PbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d +8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi +1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd +rRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di +taY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7 +lcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj +yTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn +Kx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy +yCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n +wXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6 +OV+KmalBWQewLK8= +-----END CERTIFICATE----- + +# Issuer: CN=Certainly Root E1 O=Certainly +# Subject: CN=Certainly Root E1 O=Certainly +# Label: "Certainly Root E1" +# Serial: 8168531406727139161245376702891150584 +# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9 +# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b +# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2 +-----BEGIN CERTIFICATE----- +MIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw +CQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu +bHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ +BgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s +eSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK ++IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2 +QNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4 +hevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm +ut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG +BtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR +-----END CERTIFICATE----- + +# Issuer: CN=Security Communication RootCA3 O=SECOM Trust Systems CO.,LTD. +# Subject: CN=Security Communication RootCA3 O=SECOM Trust Systems CO.,LTD. +# Label: "Security Communication RootCA3" +# Serial: 16247922307909811815 +# MD5 Fingerprint: 1c:9a:16:ff:9e:5c:e0:4d:8a:14:01:f4:35:5d:29:26 +# SHA1 Fingerprint: c3:03:c8:22:74:92:e5:61:a2:9c:5f:79:91:2b:1e:44:13:91:30:3a +# SHA256 Fingerprint: 24:a5:5c:2a:b0:51:44:2d:06:17:76:65:41:23:9a:4a:d0:32:d7:c5:51:75:aa:34:ff:de:2f:bc:4f:5c:52:94 +-----BEGIN CERTIFICATE----- +MIIFfzCCA2egAwIBAgIJAOF8N0D9G/5nMA0GCSqGSIb3DQEBDAUAMF0xCzAJBgNV +BAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMScw +JQYDVQQDEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTMwHhcNMTYwNjE2 +MDYxNzE2WhcNMzgwMTE4MDYxNzE2WjBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc +U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UEAxMeU2VjdXJpdHkg +Q29tbXVuaWNhdGlvbiBSb290Q0EzMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEA48lySfcw3gl8qUCBWNO0Ot26YQ+TUG5pPDXC7ltzkBtnTCHsXzW7OT4r +CmDvu20rhvtxosis5FaU+cmvsXLUIKx00rgVrVH+hXShuRD+BYD5UpOzQD11EKzA +lrenfna84xtSGc4RHwsENPXY9Wk8d/Nk9A2qhd7gCVAEF5aEt8iKvE1y/By7z/MG +TfmfZPd+pmaGNXHIEYBMwXFAWB6+oHP2/D5Q4eAvJj1+XCO1eXDe+uDRpdYMQXF7 +9+qMHIjH7Iv10S9VlkZ8WjtYO/u62C21Jdp6Ts9EriGmnpjKIG58u4iFW/vAEGK7 +8vknR+/RiTlDxN/e4UG/VHMgly1s2vPUB6PmudhvrvyMGS7TZ2crldtYXLVqAvO4 +g160a75BflcJdURQVc1aEWEhCmHCqYj9E7wtiS/NYeCVvsq1e+F7NGcLH7YMx3we +GVPKp7FKFSBWFHA9K4IsD50VHUeAR/94mQ4xr28+j+2GaR57GIgUssL8gjMunEst ++3A7caoreyYn8xrC3PsXuKHqy6C0rtOUfnrQq8PsOC0RLoi/1D+tEjtCrI8Cbn3M +0V9hvqG8OmpI6iZVIhZdXw3/JzOfGAN0iltSIEdrRU0id4xVJ/CvHozJgyJUt5rQ +T9nO/NkuHJYosQLTA70lUhw0Zk8jq/R3gpYd0VcwCBEF/VfR2ccCAwEAAaNCMEAw +HQYDVR0OBBYEFGQUfPxYchamCik0FW8qy7z8r6irMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDAUAA4ICAQDcAiMI4u8hOscNtybS +YpOnpSNyByCCYN8Y11StaSWSntkUz5m5UoHPrmyKO1o5yGwBQ8IibQLwYs1OY0PA +FNr0Y/Dq9HHuTofjcan0yVflLl8cebsjqodEV+m9NU1Bu0soo5iyG9kLFwfl9+qd +9XbXv8S2gVj/yP9kaWJ5rW4OH3/uHWnlt3Jxs/6lATWUVCvAUm2PVcTJ0rjLyjQI +UYWg9by0F1jqClx6vWPGOi//lkkZhOpn2ASxYfQAW0q3nHE3GYV5v4GwxxMOdnE+ +OoAGrgYWp421wsTL/0ClXI2lyTrtcoHKXJg80jQDdwj98ClZXSEIx2C/pHF7uNke +gr4Jr2VvKKu/S7XuPghHJ6APbw+LP6yVGPO5DtxnVW5inkYO0QR4ynKudtml+LLf +iAlhi+8kTtFZP1rUPcmTPCtk9YENFpb3ksP+MW/oKjJ0DvRMmEoYDjBU1cXrvMUV +nuiZIesnKwkK2/HmcBhWuwzkvvnoEKQTkrgc4NtnHVMDpCKn3F2SEDzq//wbEBrD +2NCcnWXL0CsnMQMeNuE9dnUM/0Umud1RvCPHX9jYhxBAEg09ODfnRDwYwFMJZI// +1ZqmfHAuc1Uh6N//g7kdPjIe1qZ9LPFm6Vwdp6POXiUyK+OVrCoHzrQoeIY8Laad +TdJ0MN1kURXbg4NR16/9M51NZg== +-----END CERTIFICATE----- + +# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. +# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. +# Label: "Security Communication ECC RootCA1" +# Serial: 15446673492073852651 +# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86 +# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41 +# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11 +-----BEGIN CERTIFICATE----- +MIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT +AkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD +VQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx +NjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT +HFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5 +IENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl +dB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK +ULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu +9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O +be0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k= +-----END CERTIFICATE----- + +# Issuer: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY +# Subject: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY +# Label: "BJCA Global Root CA1" +# Serial: 113562791157148395269083148143378328608 +# MD5 Fingerprint: 42:32:99:76:43:33:36:24:35:07:82:9b:28:f9:d0:90 +# SHA1 Fingerprint: d5:ec:8d:7b:4c:ba:79:f4:e7:e8:cb:9d:6b:ae:77:83:10:03:21:6a +# SHA256 Fingerprint: f3:89:6f:88:fe:7c:0a:88:27:66:a7:fa:6a:d2:74:9f:b5:7a:7f:3e:98:fb:76:9c:1f:a7:b0:9c:2c:44:d5:ae +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIQVW9l47TZkGobCdFsPsBsIDANBgkqhkiG9w0BAQsFADBU +MQswCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRI +T1JJVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0ExMB4XDTE5MTIxOTAz +MTYxN1oXDTQ0MTIxMjAzMTYxN1owVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJF +SUpJTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2Jh +bCBSb290IENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPFmCL3Z +xRVhy4QEQaVpN3cdwbB7+sN3SJATcmTRuHyQNZ0YeYjjlwE8R4HyDqKYDZ4/N+AZ +spDyRhySsTphzvq3Rp4Dhtczbu33RYx2N95ulpH3134rhxfVizXuhJFyV9xgw8O5 +58dnJCNPYwpj9mZ9S1WnP3hkSWkSl+BMDdMJoDIwOvqfwPKcxRIqLhy1BDPapDgR +at7GGPZHOiJBhyL8xIkoVNiMpTAK+BcWyqw3/XmnkRd4OJmtWO2y3syJfQOcs4ll +5+M7sSKGjwZteAf9kRJ/sGsciQ35uMt0WwfCyPQ10WRjeulumijWML3mG90Vr4Tq +nMfK9Q7q8l0ph49pczm+LiRvRSGsxdRpJQaDrXpIhRMsDQa4bHlW/KNnMoH1V6XK +V0Jp6VwkYe/iMBhORJhVb3rCk9gZtt58R4oRTklH2yiUAguUSiz5EtBP6DF+bHq/ +pj+bOT0CFqMYs2esWz8sgytnOYFcuX6U1WTdno9uruh8W7TXakdI136z1C2OVnZO +z2nxbkRs1CTqjSShGL+9V/6pmTW12xB3uD1IutbB5/EjPtffhZ0nPNRAvQoMvfXn +jSXWgXSHRtQpdaJCbPdzied9v3pKH9MiyRVVz99vfFXQpIsHETdfg6YmV6YBW37+ +WGgHqel62bno/1Afq8K0wM7o6v0PvY1NuLxxAgMBAAGjQjBAMB0GA1UdDgQWBBTF +7+3M2I0hxkjk49cULqcWk+WYATAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE +AwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAUoKsITQfI/Ki2Pm4rzc2IInRNwPWaZ+4 +YRC6ojGYWUfo0Q0lHhVBDOAqVdVXUsv45Mdpox1NcQJeXyFFYEhcCY5JEMEE3Kli +awLwQ8hOnThJdMkycFRtwUf8jrQ2ntScvd0g1lPJGKm1Vrl2i5VnZu69mP6u775u ++2D2/VnGKhs/I0qUJDAnyIm860Qkmss9vk/Ves6OF8tiwdneHg56/0OGNFK8YT88 +X7vZdrRTvJez/opMEi4r89fO4aL/3Xtw+zuhTaRjAv04l5U/BXCga99igUOLtFkN +SoxUnMW7gZ/NfaXvCyUeOiDbHPwfmGcCCtRzRBPbUYQaVQNW4AB+dAb/OMRyHdOo +P2gxXdMJxy6MW2Pg6Nwe0uxhHvLe5e/2mXZgLR6UcnHGCyoyx5JO1UbXHfmpGQrI ++pXObSOYqgs4rZpWDW+N8TEAiMEXnM0ZNjX+VVOg4DwzX5Ze4jLp3zO7Bkqp2IRz +znfSxqxx4VyjHQy7Ct9f4qNx2No3WqB4K/TUfet27fJhcKVlmtOJNBir+3I+17Q9 +eVzYH6Eze9mCUAyTF6ps3MKCuwJXNq+YJyo5UOGwifUll35HaBC07HPKs5fRJNz2 +YqAo07WjuGS3iGJCz51TzZm+ZGiPTx4SSPfSKcOYKMryMguTjClPPGAyzQWWYezy +r/6zcCwupvI= +-----END CERTIFICATE----- + +# Issuer: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY +# Subject: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY +# Label: "BJCA Global Root CA2" +# Serial: 58605626836079930195615843123109055211 +# MD5 Fingerprint: 5e:0a:f6:47:5f:a6:14:e8:11:01:95:3f:4d:01:eb:3c +# SHA1 Fingerprint: f4:27:86:eb:6e:b8:6d:88:31:67:02:fb:ba:66:a4:53:00:aa:7a:a6 +# SHA256 Fingerprint: 57:4d:f6:93:1e:27:80:39:66:7b:72:0a:fd:c1:60:0f:c2:7e:b6:6d:d3:09:29:79:fb:73:85:64:87:21:28:82 +-----BEGIN CERTIFICATE----- +MIICJTCCAaugAwIBAgIQLBcIfWQqwP6FGFkGz7RK6zAKBggqhkjOPQQDAzBUMQsw +CQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRIT1JJ +VFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0EyMB4XDTE5MTIxOTAzMTgy +MVoXDTQ0MTIxMjAzMTgyMVowVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJFSUpJ +TkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2JhbCBS +b290IENBMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABJ3LgJGNU2e1uVCxA/jlSR9B +IgmwUVJY1is0j8USRhTFiy8shP8sbqjV8QnjAyEUxEM9fMEsxEtqSs3ph+B99iK+ ++kpRuDCK/eHeGBIK9ke35xe/J4rUQUyWPGCWwf0VHKNCMEAwHQYDVR0OBBYEFNJK +sVF/BvDRgh9Obl+rg/xI1LCRMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMAoGCCqGSM49BAMDA2gAMGUCMBq8W9f+qdJUDkpd0m2xQNz0Q9XSSpkZElaA +94M04TVOSG0ED1cxMDAtsaqdAzjbBgIxAMvMh1PLet8gUXOQwKhbYdDFUDn9hf7B +43j4ptZLvZuHjw/l1lOWqzzIQNph91Oj9w== +-----END CERTIFICATE----- + +# Issuer: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited +# Subject: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited +# Label: "Sectigo Public Server Authentication Root E46" +# Serial: 88989738453351742415770396670917916916 +# MD5 Fingerprint: 28:23:f8:b2:98:5c:37:16:3b:3e:46:13:4e:b0:b3:01 +# SHA1 Fingerprint: ec:8a:39:6c:40:f0:2e:bc:42:75:d4:9f:ab:1c:1a:5b:67:be:d2:9a +# SHA256 Fingerprint: c9:0f:26:f0:fb:1b:40:18:b2:22:27:51:9b:5c:a2:b5:3e:2c:a5:b3:be:5c:f1:8e:fe:1b:ef:47:38:0c:53:83 +-----BEGIN CERTIFICATE----- +MIICOjCCAcGgAwIBAgIQQvLM2htpN0RfFf51KBC49DAKBggqhkjOPQQDAzBfMQsw +CQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1T +ZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwHhcN +MjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEYMBYG +A1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1YmxpYyBT +ZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAR2+pmpbiDt+dd34wc7qNs9Xzjoq1WmVk/WSOrsfy2qw7LFeeyZYX8QeccC +WvkEN/U0NSt3zn8gj1KjAIns1aeibVvjS5KToID1AZTc8GgHHs3u/iVStSBDHBv+ +6xnOQ6OjQjBAMB0GA1UdDgQWBBTRItpMWfFLXyY4qp3W7usNw/upYTAOBgNVHQ8B +Af8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNnADBkAjAn7qRa +qCG76UeXlImldCBteU/IvZNeWBj7LRoAasm4PdCkT0RHlAFWovgzJQxC36oCMB3q +4S6ILuH5px0CMk7yn2xVdOOurvulGu7t0vzCAxHrRVxgED1cf5kDW21USAGKcw== +-----END CERTIFICATE----- + +# Issuer: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited +# Subject: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited +# Label: "Sectigo Public Server Authentication Root R46" +# Serial: 156256931880233212765902055439220583700 +# MD5 Fingerprint: 32:10:09:52:00:d5:7e:6c:43:df:15:c0:b1:16:93:e5 +# SHA1 Fingerprint: ad:98:f9:f3:e4:7d:75:3b:65:d4:82:b3:a4:52:17:bb:6e:f5:e4:38 +# SHA256 Fingerprint: 7b:b6:47:a6:2a:ee:ac:88:bf:25:7a:a5:22:d0:1f:fe:a3:95:e0:ab:45:c7:3f:93:f6:56:54:ec:38:f2:5a:06 +-----BEGIN CERTIFICATE----- +MIIFijCCA3KgAwIBAgIQdY39i658BwD6qSWn4cetFDANBgkqhkiG9w0BAQwFADBf +MQswCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQD +Ey1TZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYw +HhcNMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEY +MBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1Ymxp +YyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCTvtU2UnXYASOgHEdCSe5jtrch/cSV1UgrJnwUUxDa +ef0rty2k1Cz66jLdScK5vQ9IPXtamFSvnl0xdE8H/FAh3aTPaE8bEmNtJZlMKpnz +SDBh+oF8HqcIStw+KxwfGExxqjWMrfhu6DtK2eWUAtaJhBOqbchPM8xQljeSM9xf +iOefVNlI8JhD1mb9nxc4Q8UBUQvX4yMPFF1bFOdLvt30yNoDN9HWOaEhUTCDsG3X +ME6WW5HwcCSrv0WBZEMNvSE6Lzzpng3LILVCJ8zab5vuZDCQOc2TZYEhMbUjUDM3 +IuM47fgxMMxF/mL50V0yeUKH32rMVhlATc6qu/m1dkmU8Sf4kaWD5QazYw6A3OAS +VYCmO2a0OYctyPDQ0RTp5A1NDvZdV3LFOxxHVp3i1fuBYYzMTYCQNFu31xR13NgE +SJ/AwSiItOkcyqex8Va3e0lMWeUgFaiEAin6OJRpmkkGj80feRQXEgyDet4fsZfu ++Zd4KKTIRJLpfSYFplhym3kT2BFfrsU4YjRosoYwjviQYZ4ybPUHNs2iTG7sijbt +8uaZFURww3y8nDnAtOFr94MlI1fZEoDlSfB1D++N6xybVCi0ITz8fAr/73trdf+L +HaAZBav6+CuBQug4urv7qv094PPK306Xlynt8xhW6aWWrL3DkJiy4Pmi1KZHQ3xt +zwIDAQABo0IwQDAdBgNVHQ4EFgQUVnNYZJX5khqwEioEYnmhQBWIIUkwDgYDVR0P +AQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAC9c +mTz8Bl6MlC5w6tIyMY208FHVvArzZJ8HXtXBc2hkeqK5Duj5XYUtqDdFqij0lgVQ +YKlJfp/imTYpE0RHap1VIDzYm/EDMrraQKFz6oOht0SmDpkBm+S8f74TlH7Kph52 +gDY9hAaLMyZlbcp+nv4fjFg4exqDsQ+8FxG75gbMY/qB8oFM2gsQa6H61SilzwZA +Fv97fRheORKkU55+MkIQpiGRqRxOF3yEvJ+M0ejf5lG5Nkc/kLnHvALcWxxPDkjB +JYOcCj+esQMzEhonrPcibCTRAUH4WAP+JWgiH5paPHxsnnVI84HxZmduTILA7rpX +DhjvLpr3Etiga+kFpaHpaPi8TD8SHkXoUsCjvxInebnMMTzD9joiFgOgyY9mpFui +TdaBJQbpdqQACj7LzTWb4OE4y2BThihCQRxEV+ioratF4yUQvNs+ZUH7G6aXD+u5 +dHn5HrwdVw1Hr8Mvn4dGp+smWg9WY7ViYG4A++MnESLn/pmPNPW56MORcr3Ywx65 +LvKRRFHQV80MNNVIIb/bE/FmJUNS0nAiNs2fxBx1IK1jcmMGDw4nztJqDby1ORrp +0XZ60Vzk50lJLVU3aPAaOpg+VBeHVOmmJ1CJeyAvP/+/oYtKR5j/K3tJPsMpRmAY +QqszKbrAKbkTidOIijlBO8n9pu0f9GBj39ItVQGL +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation +# Subject: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation +# Label: "SSL.com TLS RSA Root CA 2022" +# Serial: 148535279242832292258835760425842727825 +# MD5 Fingerprint: d8:4e:c6:59:30:d8:fe:a0:d6:7a:5a:2c:2c:69:78:da +# SHA1 Fingerprint: ec:2c:83:40:72:af:26:95:10:ff:0e:f2:03:ee:31:70:f6:78:9d:ca +# SHA256 Fingerprint: 8f:af:7d:2e:2c:b4:70:9b:b8:e0:b3:36:66:bf:75:a5:dd:45:b5:de:48:0f:8e:a8:d4:bf:e6:be:bc:17:f2:ed +-----BEGIN CERTIFICATE----- +MIIFiTCCA3GgAwIBAgIQb77arXO9CEDii02+1PdbkTANBgkqhkiG9w0BAQsFADBO +MQswCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQD +DBxTU0wuY29tIFRMUyBSU0EgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzQyMloX +DTQ2MDgxOTE2MzQyMVowTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jw +b3JhdGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgUlNBIFJvb3QgQ0EgMjAyMjCC +AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANCkCXJPQIgSYT41I57u9nTP +L3tYPc48DRAokC+X94xI2KDYJbFMsBFMF3NQ0CJKY7uB0ylu1bUJPiYYf7ISf5OY +t6/wNr/y7hienDtSxUcZXXTzZGbVXcdotL8bHAajvI9AI7YexoS9UcQbOcGV0ins +S657Lb85/bRi3pZ7QcacoOAGcvvwB5cJOYF0r/c0WRFXCsJbwST0MXMwgsadugL3 +PnxEX4MN8/HdIGkWCVDi1FW24IBydm5MR7d1VVm0U3TZlMZBrViKMWYPHqIbKUBO +L9975hYsLfy/7PO0+r4Y9ptJ1O4Fbtk085zx7AGL0SDGD6C1vBdOSHtRwvzpXGk3 +R2azaPgVKPC506QVzFpPulJwoxJF3ca6TvvC0PeoUidtbnm1jPx7jMEWTO6Af77w +dr5BUxIzrlo4QqvXDz5BjXYHMtWrifZOZ9mxQnUjbvPNQrL8VfVThxc7wDNY8VLS ++YCk8OjwO4s4zKTGkH8PnP2L0aPP2oOnaclQNtVcBdIKQXTbYxE3waWglksejBYS +d66UNHsef8JmAOSqg+qKkK3ONkRN0VHpvB/zagX9wHQfJRlAUW7qglFA35u5CCoG +AtUjHBPW6dvbxrB6y3snm/vg1UYk7RBLY0ulBY+6uB0rpvqR4pJSvezrZ5dtmi2f +gTIFZzL7SAg/2SW4BCUvAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j +BBgwFoAU+y437uOEeicuzRk1sTN8/9REQrkwHQYDVR0OBBYEFPsuN+7jhHonLs0Z +NbEzfP/UREK5MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAjYlt +hEUY8U+zoO9opMAdrDC8Z2awms22qyIZZtM7QbUQnRC6cm4pJCAcAZli05bg4vsM +QtfhWsSWTVTNj8pDU/0quOr4ZcoBwq1gaAafORpR2eCNJvkLTqVTJXojpBzOCBvf +R4iyrT7gJ4eLSYwfqUdYe5byiB0YrrPRpgqU+tvT5TgKa3kSM/tKWTcWQA673vWJ +DPFs0/dRa1419dvAJuoSc06pkZCmF8NsLzjUo3KUQyxi4U5cMj29TH0ZR6LDSeeW +P4+a0zvkEdiLA9z2tmBVGKaBUfPhqBVq6+AL8BQx1rmMRTqoENjwuSfr98t67wVy +lrXEj5ZzxOhWc5y8aVFjvO9nHEMaX3cZHxj4HCUp+UmZKbaSPaKDN7EgkaibMOlq +bLQjk2UEqxHzDh1TJElTHaE/nUiSEeJ9DU/1172iWD54nR4fK/4huxoTtrEoZP2w +AgDHbICivRZQIA9ygV/MlP+7mea6kMvq+cYMwq7FGc4zoWtcu358NFcXrfA/rs3q +r5nsLFR+jM4uElZI7xc7P0peYNLcdDa8pUNjyw9bowJWCZ4kLOGGgYz+qxcs+sji +Mho6/4UIyYOf8kpIEFR3N+2ivEC+5BB09+Rbu7nzifmPQdjH5FCQNYA+HLhNkNPU +98OwoX6EyneSMSy4kLGCenROmxMmtNVQZlR4rmA= +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation +# Subject: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation +# Label: "SSL.com TLS ECC Root CA 2022" +# Serial: 26605119622390491762507526719404364228 +# MD5 Fingerprint: 99:d7:5c:f1:51:36:cc:e9:ce:d9:19:2e:77:71:56:c5 +# SHA1 Fingerprint: 9f:5f:d9:1a:54:6d:f5:0c:71:f0:ee:7a:bd:17:49:98:84:73:e2:39 +# SHA256 Fingerprint: c3:2f:fd:9f:46:f9:36:d1:6c:36:73:99:09:59:43:4b:9a:d6:0a:af:bb:9e:7c:f3:36:54:f1:44:cc:1b:a1:43 +-----BEGIN CERTIFICATE----- +MIICOjCCAcCgAwIBAgIQFAP1q/s3ixdAW+JDsqXRxDAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQDDBxT +U0wuY29tIFRMUyBFQ0MgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzM0OFoXDTQ2 +MDgxOTE2MzM0N1owTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jwb3Jh +dGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgRUNDIFJvb3QgQ0EgMjAyMjB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABEUpNXP6wrgjzhR9qLFNoFs27iosU8NgCTWyJGYm +acCzldZdkkAZDsalE3D07xJRKF3nzL35PIXBz5SQySvOkkJYWWf9lCcQZIxPBLFN +SeR7T5v15wj4A4j3p8OSSxlUgaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSME +GDAWgBSJjy+j6CugFFR781a4Jl9nOAuc0DAdBgNVHQ4EFgQUiY8vo+groBRUe/NW +uCZfZzgLnNAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2gAMGUCMFXjIlbp +15IkWE8elDIPDAI2wv2sdDJO4fscgIijzPvX6yv/N33w7deedWo1dlJF4AIxAMeN +b0Igj762TVntd00pxCAgRWSGOlDGxK0tk/UYfXLtqc/ErFc2KAhl3zx5Zn6g6g== +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos +# Subject: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos +# Label: "Atos TrustedRoot Root CA ECC TLS 2021" +# Serial: 81873346711060652204712539181482831616 +# MD5 Fingerprint: 16:9f:ad:f1:70:ad:79:d6:ed:29:b4:d1:c5:79:70:a8 +# SHA1 Fingerprint: 9e:bc:75:10:42:b3:02:f3:81:f4:f7:30:62:d4:8f:c3:a7:51:b2:dd +# SHA256 Fingerprint: b2:fa:e5:3e:14:cc:d7:ab:92:12:06:47:01:ae:27:9c:1d:89:88:fa:cb:77:5f:a8:a0:08:91:4e:66:39:88:a8 +-----BEGIN CERTIFICATE----- +MIICFTCCAZugAwIBAgIQPZg7pmY9kGP3fiZXOATvADAKBggqhkjOPQQDAzBMMS4w +LAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgRUNDIFRMUyAyMDIxMQ0w +CwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTI2MjNaFw00MTA0 +MTcwOTI2MjJaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBDQSBF +Q0MgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMHYwEAYHKoZI +zj0CAQYFK4EEACIDYgAEloZYKDcKZ9Cg3iQZGeHkBQcfl+3oZIK59sRxUM6KDP/X +tXa7oWyTbIOiaG6l2b4siJVBzV3dscqDY4PMwL502eCdpO5KTlbgmClBk1IQ1SQ4 +AjJn8ZQSb+/Xxd4u/RmAo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR2 +KCXWfeBmmnoJsmo7jjPXNtNPojAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMD +aAAwZQIwW5kp85wxtolrbNa9d+F851F+uDrNozZffPc8dz7kUK2o59JZDCaOMDtu +CCrCp1rIAjEAmeMM56PDr9NJLkaCI2ZdyQAUEv049OGYa3cpetskz2VAv9LcjBHo +9H1/IISpQuQo +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos +# Subject: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos +# Label: "Atos TrustedRoot Root CA RSA TLS 2021" +# Serial: 111436099570196163832749341232207667876 +# MD5 Fingerprint: d4:d3:46:b8:9a:c0:9c:76:5d:9e:3a:c3:b9:99:31:d2 +# SHA1 Fingerprint: 18:52:3b:0d:06:37:e4:d6:3a:df:23:e4:98:fb:5b:16:fb:86:74:48 +# SHA256 Fingerprint: 81:a9:08:8e:a5:9f:b3:64:c5:48:a6:f8:55:59:09:9b:6f:04:05:ef:bf:18:e5:32:4e:c9:f4:57:ba:00:11:2f +-----BEGIN CERTIFICATE----- +MIIFZDCCA0ygAwIBAgIQU9XP5hmTC/srBRLYwiqipDANBgkqhkiG9w0BAQwFADBM +MS4wLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgUlNBIFRMUyAyMDIx +MQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTIxMTBaFw00 +MTA0MTcwOTIxMDlaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBD +QSBSU0EgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMIICIjAN +BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtoAOxHm9BYx9sKOdTSJNy/BBl01Z +4NH+VoyX8te9j2y3I49f1cTYQcvyAh5x5en2XssIKl4w8i1mx4QbZFc4nXUtVsYv +Ye+W/CBGvevUez8/fEc4BKkbqlLfEzfTFRVOvV98r61jx3ncCHvVoOX3W3WsgFWZ +kmGbzSoXfduP9LVq6hdKZChmFSlsAvFr1bqjM9xaZ6cF4r9lthawEO3NUDPJcFDs +GY6wx/J0W2tExn2WuZgIWWbeKQGb9Cpt0xU6kGpn8bRrZtkh68rZYnxGEFzedUln +nkL5/nWpo63/dgpnQOPF943HhZpZnmKaau1Fh5hnstVKPNe0OwANwI8f4UDErmwh +3El+fsqyjW22v5MvoVw+j8rtgI5Y4dtXz4U2OLJxpAmMkokIiEjxQGMYsluMWuPD +0xeqqxmjLBvk1cbiZnrXghmmOxYsL3GHX0WelXOTwkKBIROW1527k2gV+p2kHYzy +geBYBr3JtuP2iV2J+axEoctr+hbxx1A9JNr3w+SH1VbxT5Aw+kUJWdo0zuATHAR8 +ANSbhqRAvNncTFd+rrcztl524WWLZt+NyteYr842mIycg5kDcPOvdO3GDjbnvezB +c6eUWsuSZIKmAMFwoW4sKeFYV+xafJlrJaSQOoD0IJ2azsct+bJLKZWD6TWNp0lI +pw9MGZHQ9b8Q4HECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU +dEmZ0f+0emhFdcN+tNzMzjkz2ggwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB +DAUAA4ICAQAjQ1MkYlxt/T7Cz1UAbMVWiLkO3TriJQ2VSpfKgInuKs1l+NsW4AmS +4BjHeJi78+xCUvuppILXTdiK/ORO/auQxDh1MoSf/7OwKwIzNsAQkG8dnK/haZPs +o0UvFJ/1TCplQ3IM98P4lYsU84UgYt1UU90s3BiVaU+DR3BAM1h3Egyi61IxHkzJ +qM7F78PRreBrAwA0JrRUITWXAdxfG/F851X6LWh3e9NpzNMOa7pNdkTWwhWaJuyw +xfW70Xp0wmzNxbVe9kzmWy2B27O3Opee7c9GslA9hGCZcbUztVdF5kJHdWoOsAgM +rr3e97sPWD2PAzHoPYJQyi9eDF20l74gNAf0xBLh7tew2VktafcxBPTy+av5EzH4 +AXcOPUIjJsyacmdRIXrMPIWo6iFqO9taPKU0nprALN+AnCng33eU0aKAQv9qTFsR +0PXNor6uzFFcw9VUewyu1rkGd4Di7wcaaMxZUa1+XGdrudviB0JbuAEFWDlN5LuY +o7Ey7Nmj1m+UI/87tyll5gfp77YZ6ufCOB0yiJA8EytuzO+rdwY0d4RPcuSBhPm5 +dDTedk+SKlOxJTnbPP/lPqYO5Wue/9vsL3SD3460s6neFE3/MaNFcyT6lSnMEpcE +oji2jbDwN/zIIX8/syQbPYtuzE2wFg2WHYMfRsCbvUOZ58SWLs5fyQ== +-----END CERTIFICATE----- + +# Issuer: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc. +# Subject: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc. +# Label: "TrustAsia Global Root CA G3" +# Serial: 576386314500428537169965010905813481816650257167 +# MD5 Fingerprint: 30:42:1b:b7:bb:81:75:35:e4:16:4f:53:d2:94:de:04 +# SHA1 Fingerprint: 63:cf:b6:c1:27:2b:56:e4:88:8e:1c:23:9a:b6:2e:81:47:24:c3:c7 +# SHA256 Fingerprint: e0:d3:22:6a:eb:11:63:c2:e4:8f:f9:be:3b:50:b4:c6:43:1b:e7:bb:1e:ac:c5:c3:6b:5d:5e:c5:09:03:9a:08 +-----BEGIN CERTIFICATE----- +MIIFpTCCA42gAwIBAgIUZPYOZXdhaqs7tOqFhLuxibhxkw8wDQYJKoZIhvcNAQEM +BQAwWjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dp +ZXMsIEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHMzAe +Fw0yMTA1MjAwMjEwMTlaFw00NjA1MTkwMjEwMTlaMFoxCzAJBgNVBAYTAkNOMSUw +IwYDVQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtU +cnVzdEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzMwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQDAMYJhkuSUGwoqZdC+BqmHO1ES6nBBruL7dOoKjbmzTNyPtxNS +T1QY4SxzlZHFZjtqz6xjbYdT8PfxObegQ2OwxANdV6nnRM7EoYNl9lA+sX4WuDqK +AtCWHwDNBSHvBm3dIZwZQ0WhxeiAysKtQGIXBsaqvPPW5vxQfmZCHzyLpnl5hkA1 +nyDvP+uLRx+PjsXUjrYsyUQE49RDdT/VP68czH5GX6zfZBCK70bwkPAPLfSIC7Ep +qq+FqklYqL9joDiR5rPmd2jE+SoZhLsO4fWvieylL1AgdB4SQXMeJNnKziyhWTXA +yB1GJ2Faj/lN03J5Zh6fFZAhLf3ti1ZwA0pJPn9pMRJpxx5cynoTi+jm9WAPzJMs +hH/x/Gr8m0ed262IPfN2dTPXS6TIi/n1Q1hPy8gDVI+lhXgEGvNz8teHHUGf59gX +zhqcD0r83ERoVGjiQTz+LISGNzzNPy+i2+f3VANfWdP3kXjHi3dqFuVJhZBFcnAv +kV34PmVACxmZySYgWmjBNb9Pp1Hx2BErW+Canig7CjoKH8GB5S7wprlppYiU5msT +f9FkPz2ccEblooV7WIQn3MSAPmeamseaMQ4w7OYXQJXZRe0Blqq/DPNL0WP3E1jA +uPP6Z92bfW1K/zJMtSU7/xxnD4UiWQWRkUF3gdCFTIcQcf+eQxuulXUtgQIDAQAB +o2MwYTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEDk5PIj7zjKsK5Xf/Ih +MBY027ySMB0GA1UdDgQWBBRA5OTyI+84yrCuV3/yITAWNNu8kjAOBgNVHQ8BAf8E +BAMCAQYwDQYJKoZIhvcNAQEMBQADggIBACY7UeFNOPMyGLS0XuFlXsSUT9SnYaP4 +wM8zAQLpw6o1D/GUE3d3NZ4tVlFEbuHGLige/9rsR82XRBf34EzC4Xx8MnpmyFq2 +XFNFV1pF1AWZLy4jVe5jaN/TG3inEpQGAHUNcoTpLrxaatXeL1nHo+zSh2bbt1S1 +JKv0Q3jbSwTEb93mPmY+KfJLaHEih6D4sTNjduMNhXJEIlU/HHzp/LgV6FL6qj6j +ITk1dImmasI5+njPtqzn59ZW/yOSLlALqbUHM/Q4X6RJpstlcHboCoWASzY9M/eV +VHUl2qzEc4Jl6VL1XP04lQJqaTDFHApXB64ipCz5xUG3uOyfT0gA+QEEVcys+TIx +xHWVBqB/0Y0n3bOppHKH/lmLmnp0Ft0WpWIp6zqW3IunaFnT63eROfjXy9mPX1on +AX1daBli2MjN9LdyR75bl87yraKZk62Uy5P2EgmVtqvXO9A/EcswFi55gORngS1d +7XB4tmBZrOFdRWOPyN9yaFvqHbgB8X7754qz41SgOAngPN5C8sLtLpvzHzW2Ntjj +gKGLzZlkD8Kqq7HK9W+eQ42EVJmzbsASZthwEPEGNTNDqJwuuhQxzhB/HIbjj9LV ++Hfsm6vxL2PZQl/gZ4FkkfGXL/xuJvYz+NO1+MRiqzFRJQJ6+N1rZdVtTTDIZbpo +FGWsJwt0ivKH +-----END CERTIFICATE----- + +# Issuer: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc. +# Subject: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc. +# Label: "TrustAsia Global Root CA G4" +# Serial: 451799571007117016466790293371524403291602933463 +# MD5 Fingerprint: 54:dd:b2:d7:5f:d8:3e:ed:7c:e0:0b:2e:cc:ed:eb:eb +# SHA1 Fingerprint: 57:73:a5:61:5d:80:b2:e6:ac:38:82:fc:68:07:31:ac:9f:b5:92:5a +# SHA256 Fingerprint: be:4b:56:cb:50:56:c0:13:6a:52:6d:f4:44:50:8d:aa:36:a0:b5:4f:42:e4:ac:38:f7:2a:f4:70:e4:79:65:4c +-----BEGIN CERTIFICATE----- +MIICVTCCAdygAwIBAgIUTyNkuI6XY57GU4HBdk7LKnQV1tcwCgYIKoZIzj0EAwMw +WjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs +IEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHNDAeFw0y +MTA1MjAwMjEwMjJaFw00NjA1MTkwMjEwMjJaMFoxCzAJBgNVBAYTAkNOMSUwIwYD +VQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtUcnVz +dEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATx +s8045CVD5d4ZCbuBeaIVXxVjAd7Cq92zphtnS4CDr5nLrBfbK5bKfFJV4hrhPVbw +LxYI+hW8m7tH5j/uqOFMjPXTNvk4XatwmkcN4oFBButJ+bAp3TPsUKV/eSm4IJij +YzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUpbtKl86zK3+kMd6Xg1mD +pm9xy94wHQYDVR0OBBYEFKW7SpfOsyt/pDHel4NZg6ZvccveMA4GA1UdDwEB/wQE +AwIBBjAKBggqhkjOPQQDAwNnADBkAjBe8usGzEkxn0AAbbd+NvBNEU/zy4k6LHiR +UKNbwMp1JvK/kF0LgoxgKJ/GcJpo5PECMFxYDlZ2z1jD1xCMuo6u47xkdUfFVZDj +/bpV6wfEU6s3qe4hsiFbYI89MvHVI5TWWA== +-----END CERTIFICATE----- + +# Issuer: CN=CommScope Public Trust ECC Root-01 O=CommScope +# Subject: CN=CommScope Public Trust ECC Root-01 O=CommScope +# Label: "CommScope Public Trust ECC Root-01" +# Serial: 385011430473757362783587124273108818652468453534 +# MD5 Fingerprint: 3a:40:a7:fc:03:8c:9c:38:79:2f:3a:a2:6c:b6:0a:16 +# SHA1 Fingerprint: 07:86:c0:d8:dd:8e:c0:80:98:06:98:d0:58:7a:ef:de:a6:cc:a2:5d +# SHA256 Fingerprint: 11:43:7c:da:7b:b4:5e:41:36:5f:45:b3:9a:38:98:6b:0d:e0:0d:ef:34:8e:0c:7b:b0:87:36:33:80:0b:c3:8b +-----BEGIN CERTIFICATE----- +MIICHTCCAaOgAwIBAgIUQ3CCd89NXTTxyq4yLzf39H91oJ4wCgYIKoZIzj0EAwMw +TjELMAkGA1UEBhMCVVMxEjAQBgNVBAoMCUNvbW1TY29wZTErMCkGA1UEAwwiQ29t +bVNjb3BlIFB1YmxpYyBUcnVzdCBFQ0MgUm9vdC0wMTAeFw0yMTA0MjgxNzM1NDNa +Fw00NjA0MjgxNzM1NDJaME4xCzAJBgNVBAYTAlVTMRIwEAYDVQQKDAlDb21tU2Nv +cGUxKzApBgNVBAMMIkNvbW1TY29wZSBQdWJsaWMgVHJ1c3QgRUNDIFJvb3QtMDEw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAARLNumuV16ocNfQj3Rid8NeeqrltqLxeP0C +flfdkXmcbLlSiFS8LwS+uM32ENEp7LXQoMPwiXAZu1FlxUOcw5tjnSCDPgYLpkJE +hRGnSjot6dZoL0hOUysHP029uax3OVejQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSOB2LAUN3GGQYARnQE9/OufXVNMDAKBggq +hkjOPQQDAwNoADBlAjEAnDPfQeMjqEI2Jpc1XHvr20v4qotzVRVcrHgpD7oh2MSg +2NED3W3ROT3Ek2DS43KyAjB8xX6I01D1HiXo+k515liWpDVfG2XqYZpwI7UNo5uS +Um9poIyNStDuiw7LR47QjRE= +-----END CERTIFICATE----- + +# Issuer: CN=CommScope Public Trust ECC Root-02 O=CommScope +# Subject: CN=CommScope Public Trust ECC Root-02 O=CommScope +# Label: "CommScope Public Trust ECC Root-02" +# Serial: 234015080301808452132356021271193974922492992893 +# MD5 Fingerprint: 59:b0:44:d5:65:4d:b8:5c:55:19:92:02:b6:d1:94:b2 +# SHA1 Fingerprint: 3c:3f:ef:57:0f:fe:65:93:86:9e:a0:fe:b0:f6:ed:8e:d1:13:c7:e5 +# SHA256 Fingerprint: 2f:fb:7f:81:3b:bb:b3:c8:9a:b4:e8:16:2d:0f:16:d7:15:09:a8:30:cc:9d:73:c2:62:e5:14:08:75:d1:ad:4a +-----BEGIN CERTIFICATE----- +MIICHDCCAaOgAwIBAgIUKP2ZYEFHpgE6yhR7H+/5aAiDXX0wCgYIKoZIzj0EAwMw +TjELMAkGA1UEBhMCVVMxEjAQBgNVBAoMCUNvbW1TY29wZTErMCkGA1UEAwwiQ29t +bVNjb3BlIFB1YmxpYyBUcnVzdCBFQ0MgUm9vdC0wMjAeFw0yMTA0MjgxNzQ0NTRa +Fw00NjA0MjgxNzQ0NTNaME4xCzAJBgNVBAYTAlVTMRIwEAYDVQQKDAlDb21tU2Nv +cGUxKzApBgNVBAMMIkNvbW1TY29wZSBQdWJsaWMgVHJ1c3QgRUNDIFJvb3QtMDIw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAR4MIHoYx7l63FRD/cHB8o5mXxO1Q/MMDAL +j2aTPs+9xYa9+bG3tD60B8jzljHz7aRP+KNOjSkVWLjVb3/ubCK1sK9IRQq9qEmU +v4RDsNuESgMjGWdqb8FuvAY5N9GIIvejQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTmGHX/72DehKT1RsfeSlXjMjZ59TAKBggq +hkjOPQQDAwNnADBkAjAmc0l6tqvmSfR9Uj/UQQSugEODZXW5hYA4O9Zv5JOGq4/n +ich/m35rChJVYaoR4HkCMHfoMXGsPHED1oQmHhS48zs73u1Z/GtMMH9ZzkXpc2AV +mkzw5l4lIhVtwodZ0LKOag== +-----END CERTIFICATE----- + +# Issuer: CN=CommScope Public Trust RSA Root-01 O=CommScope +# Subject: CN=CommScope Public Trust RSA Root-01 O=CommScope +# Label: "CommScope Public Trust RSA Root-01" +# Serial: 354030733275608256394402989253558293562031411421 +# MD5 Fingerprint: 0e:b4:15:bc:87:63:5d:5d:02:73:d4:26:38:68:73:d8 +# SHA1 Fingerprint: 6d:0a:5f:f7:b4:23:06:b4:85:b3:b7:97:64:fc:ac:75:f5:33:f2:93 +# SHA256 Fingerprint: 02:bd:f9:6e:2a:45:dd:9b:f1:8f:c7:e1:db:df:21:a0:37:9b:a3:c9:c2:61:03:44:cf:d8:d6:06:fe:c1:ed:81 +-----BEGIN CERTIFICATE----- +MIIFbDCCA1SgAwIBAgIUPgNJgXUWdDGOTKvVxZAplsU5EN0wDQYJKoZIhvcNAQEL +BQAwTjELMAkGA1UEBhMCVVMxEjAQBgNVBAoMCUNvbW1TY29wZTErMCkGA1UEAwwi +Q29tbVNjb3BlIFB1YmxpYyBUcnVzdCBSU0EgUm9vdC0wMTAeFw0yMTA0MjgxNjQ1 +NTRaFw00NjA0MjgxNjQ1NTNaME4xCzAJBgNVBAYTAlVTMRIwEAYDVQQKDAlDb21t +U2NvcGUxKzApBgNVBAMMIkNvbW1TY29wZSBQdWJsaWMgVHJ1c3QgUlNBIFJvb3Qt +MDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwSGWjDR1C45FtnYSk +YZYSwu3D2iM0GXb26v1VWvZVAVMP8syMl0+5UMuzAURWlv2bKOx7dAvnQmtVzslh +suitQDy6uUEKBU8bJoWPQ7VAtYXR1HHcg0Hz9kXHgKKEUJdGzqAMxGBWBB0HW0al +DrJLpA6lfO741GIDuZNqihS4cPgugkY4Iw50x2tBt9Apo52AsH53k2NC+zSDO3Oj +WiE260f6GBfZumbCk6SP/F2krfxQapWsvCQz0b2If4b19bJzKo98rwjyGpg/qYFl +P8GMicWWMJoKz/TUyDTtnS+8jTiGU+6Xn6myY5QXjQ/cZip8UlF1y5mO6D1cv547 +KI2DAg+pn3LiLCuz3GaXAEDQpFSOm117RTYm1nJD68/A6g3czhLmfTifBSeolz7p +UcZsBSjBAg/pGG3svZwG1KdJ9FQFa2ww8esD1eo9anbCyxooSU1/ZOD6K9pzg4H/ +kQO9lLvkuI6cMmPNn7togbGEW682v3fuHX/3SZtS7NJ3Wn2RnU3COS3kuoL4b/JO +Hg9O5j9ZpSPcPYeoKFgo0fEbNttPxP/hjFtyjMcmAyejOQoBqsCyMWCDIqFPEgkB +Ea801M/XrmLTBQe0MXXgDW1XT2mH+VepuhX2yFJtocucH+X8eKg1mp9BFM6ltM6U +CBwJrVbl2rZJmkrqYxhTnCwuwwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G +A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUN12mmnQywsL5x6YVEFm45P3luG0wDQYJ +KoZIhvcNAQELBQADggIBAK+nz97/4L1CjU3lIpbfaOp9TSp90K09FlxD533Ahuh6 +NWPxzIHIxgvoLlI1pKZJkGNRrDSsBTtXAOnTYtPZKdVUvhwQkZyybf5Z/Xn36lbQ +nmhUQo8mUuJM3y+Xpi/SB5io82BdS5pYV4jvguX6r2yBS5KPQJqTRlnLX3gWsWc+ +QgvfKNmwrZggvkN80V4aCRckjXtdlemrwWCrWxhkgPut4AZ9HcpZuPN4KWfGVh2v +trV0KnahP/t1MJ+UXjulYPPLXAziDslg+MkfFoom3ecnf+slpoq9uC02EJqxWE2a +aE9gVOX2RhOOiKy8IUISrcZKiX2bwdgt6ZYD9KJ0DLwAHb/WNyVntHKLr4W96ioD +j8z7PEQkguIBpQtZtjSNMgsSDesnwv1B10A8ckYpwIzqug/xBpMu95yo9GA+o/E4 +Xo4TwbM6l4c/ksp4qRyv0LAbJh6+cOx69TOY6lz/KwsETkPdY34Op054A5U+1C0w +lREQKC6/oAI+/15Z0wUOlV9TRe9rh9VIzRamloPh37MG88EU26fsHItdkJANclHn +YfkUyq+Dj7+vsQpZXdxc1+SWrVtgHdqul7I52Qb1dgAT+GhMIbA1xNxVssnBQVoc +icCMb3SgazNNtQEo/a2tiRc7ppqEvOuM6sRxJKi6KfkIsidWNTJf6jn7MZrVGczw +-----END CERTIFICATE----- + +# Issuer: CN=CommScope Public Trust RSA Root-02 O=CommScope +# Subject: CN=CommScope Public Trust RSA Root-02 O=CommScope +# Label: "CommScope Public Trust RSA Root-02" +# Serial: 480062499834624527752716769107743131258796508494 +# MD5 Fingerprint: e1:29:f9:62:7b:76:e2:96:6d:f3:d4:d7:0f:ae:1f:aa +# SHA1 Fingerprint: ea:b0:e2:52:1b:89:93:4c:11:68:f2:d8:9a:ac:22:4c:a3:8a:57:ae +# SHA256 Fingerprint: ff:e9:43:d7:93:42:4b:4f:7c:44:0c:1c:3d:64:8d:53:63:f3:4b:82:dc:87:aa:7a:9f:11:8f:c5:de:e1:01:f1 +-----BEGIN CERTIFICATE----- +MIIFbDCCA1SgAwIBAgIUVBa/O345lXGN0aoApYYNK496BU4wDQYJKoZIhvcNAQEL +BQAwTjELMAkGA1UEBhMCVVMxEjAQBgNVBAoMCUNvbW1TY29wZTErMCkGA1UEAwwi +Q29tbVNjb3BlIFB1YmxpYyBUcnVzdCBSU0EgUm9vdC0wMjAeFw0yMTA0MjgxNzE2 +NDNaFw00NjA0MjgxNzE2NDJaME4xCzAJBgNVBAYTAlVTMRIwEAYDVQQKDAlDb21t +U2NvcGUxKzApBgNVBAMMIkNvbW1TY29wZSBQdWJsaWMgVHJ1c3QgUlNBIFJvb3Qt +MDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDh+g77aAASyE3VrCLE +NQE7xVTlWXZjpX/rwcRqmL0yjReA61260WI9JSMZNRTpf4mnG2I81lDnNJUDMrG0 +kyI9p+Kx7eZ7Ti6Hmw0zdQreqjXnfuU2mKKuJZ6VszKWpCtYHu8//mI0SFHRtI1C +rWDaSWqVcN3SAOLMV2MCe5bdSZdbkk6V0/nLKR8YSvgBKtJjCW4k6YnS5cciTNxz +hkcAqg2Ijq6FfUrpuzNPDlJwnZXjfG2WWy09X6GDRl224yW4fKcZgBzqZUPckXk2 +LHR88mcGyYnJ27/aaL8j7dxrrSiDeS/sOKUNNwFnJ5rpM9kzXzehxfCrPfp4sOcs +n/Y+n2Dg70jpkEUeBVF4GiwSLFworA2iI540jwXmojPOEXcT1A6kHkIfhs1w/tku +FT0du7jyU1fbzMZ0KZwYszZ1OC4PVKH4kh+Jlk+71O6d6Ts2QrUKOyrUZHk2EOH5 +kQMreyBUzQ0ZGshBMjTRsJnhkB4BQDa1t/qp5Xd1pCKBXbCL5CcSD1SIxtuFdOa3 +wNemKfrb3vOTlycEVS8KbzfFPROvCgCpLIscgSjX74Yxqa7ybrjKaixUR9gqiC6v +wQcQeKwRoi9C8DfF8rhW3Q5iLc4tVn5V8qdE9isy9COoR+jUKgF4z2rDN6ieZdIs +5fq6M8EGRPbmz6UNp2YINIos8wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G +A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUR9DnsSL/nSz12Vdgs7GxcJXvYXowDQYJ +KoZIhvcNAQELBQADggIBAIZpsU0v6Z9PIpNojuQhmaPORVMbc0RTAIFhzTHjCLqB +KCh6krm2qMhDnscTJk3C2OVVnJJdUNjCK9v+5qiXz1I6JMNlZFxHMaNlNRPDk7n3 ++VGXu6TwYofF1gbTl4MgqX67tiHCpQ2EAOHyJxCDut0DgdXdaMNmEMjRdrSzbyme +APnCKfWxkxlSaRosTKCL4BWaMS/TiJVZbuXEs1DIFAhKm4sTg7GkcrI7djNB3Nyq +pgdvHSQSn8h2vS/ZjvQs7rfSOBAkNlEv41xdgSGn2rtO/+YHqP65DSdsu3BaVXoT +6fEqSWnHX4dXTEN5bTpl6TBcQe7rd6VzEojov32u5cSoHw2OHG1QAk8mGEPej1WF +sQs3BWDJVTkSBKEqz3EWnzZRSb9wO55nnPt7eck5HHisd5FUmrh1CoFSl+NmYWvt +PjgelmFV4ZFUjO2MJB+ByRCac5krFk5yAD9UG/iNuovnFNa2RU9g7Jauwy8CTl2d +lklyALKrdVwPaFsdZcJfMw8eD/A7hvWwTruc9+olBdytoptLFwG+Qt81IR2tq670 +v64fG9PiO/yzcnMcmyiQiRM9HcEARwmWmjgb3bHPDcK0RPOWlc4yOo80nOAXx17O +rg3bhzjlP1v9mxnhMUF6cKojawHhRUzNlM47ni3niAIi9G7oyOzWPPO5std3eqx7 +-----END CERTIFICATE----- + +# Issuer: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH +# Subject: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH +# Label: "Telekom Security TLS ECC Root 2020" +# Serial: 72082518505882327255703894282316633856 +# MD5 Fingerprint: c1:ab:fe:6a:10:2c:03:8d:bc:1c:22:32:c0:85:a7:fd +# SHA1 Fingerprint: c0:f8:96:c5:a9:3b:01:06:21:07:da:18:42:48:bc:e9:9d:88:d5:ec +# SHA256 Fingerprint: 57:8a:f4:de:d0:85:3f:4e:59:98:db:4a:ea:f9:cb:ea:8d:94:5f:60:b6:20:a3:8d:1a:3c:13:b2:bc:7b:a8:e1 +-----BEGIN CERTIFICATE----- +MIICQjCCAcmgAwIBAgIQNjqWjMlcsljN0AFdxeVXADAKBggqhkjOPQQDAzBjMQsw +CQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0eSBH +bWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBFQ0MgUm9vdCAyMDIw +MB4XDTIwMDgyNTA3NDgyMFoXDTQ1MDgyNTIzNTk1OVowYzELMAkGA1UEBhMCREUx +JzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkGA1UE +AwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgRUNDIFJvb3QgMjAyMDB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABM6//leov9Wq9xCazbzREaK9Z0LMkOsVGJDZos0MKiXrPk/O +tdKPD/M12kOLAoC+b1EkHQ9rK8qfwm9QMuU3ILYg/4gND21Ju9sGpIeQkpT0CdDP +f8iAC8GXs7s1J8nCG6NCMEAwHQYDVR0OBBYEFONyzG6VmUex5rNhTNHLq+O6zd6f +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA +MGQCMHVSi7ekEE+uShCLsoRbQuHmKjYC2qBuGT8lv9pZMo7k+5Dck2TOrbRBR2Di +z6fLHgIwN0GMZt9Ba9aDAEH9L1r3ULRn0SyocddDypwnJJGDSA3PzfdUga/sf+Rn +27iQ7t0l +-----END CERTIFICATE----- + +# Issuer: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH +# Subject: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH +# Label: "Telekom Security TLS RSA Root 2023" +# Serial: 44676229530606711399881795178081572759 +# MD5 Fingerprint: bf:5b:eb:54:40:cd:48:71:c4:20:8d:7d:de:0a:42:f2 +# SHA1 Fingerprint: 54:d3:ac:b3:bd:57:56:f6:85:9d:ce:e5:c3:21:e2:d4:ad:83:d0:93 +# SHA256 Fingerprint: ef:c6:5c:ad:bb:59:ad:b6:ef:e8:4d:a2:23:11:b3:56:24:b7:1b:3b:1e:a0:da:8b:66:55:17:4e:c8:97:86:46 +-----BEGIN CERTIFICATE----- +MIIFszCCA5ugAwIBAgIQIZxULej27HF3+k7ow3BXlzANBgkqhkiG9w0BAQwFADBj +MQswCQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0 +eSBHbWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBSU0EgUm9vdCAy +MDIzMB4XDTIzMDMyODEyMTY0NVoXDTQ4MDMyNzIzNTk1OVowYzELMAkGA1UEBhMC +REUxJzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkG +A1UEAwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgUlNBIFJvb3QgMjAyMzCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAO01oYGA88tKaVvC+1GDrib94W7zgRJ9 +cUD/h3VCKSHtgVIs3xLBGYSJwb3FKNXVS2xE1kzbB5ZKVXrKNoIENqil/Cf2SfHV +cp6R+SPWcHu79ZvB7JPPGeplfohwoHP89v+1VmLhc2o0mD6CuKyVU/QBoCcHcqMA +U6DksquDOFczJZSfvkgdmOGjup5czQRxUX11eKvzWarE4GC+j4NSuHUaQTXtvPM6 +Y+mpFEXX5lLRbtLevOP1Czvm4MS9Q2QTps70mDdsipWol8hHD/BeEIvnHRz+sTug +BTNoBUGCwQMrAcjnj02r6LX2zWtEtefdi+zqJbQAIldNsLGyMcEWzv/9FIS3R/qy +8XDe24tsNlikfLMR0cN3f1+2JeANxdKz+bi4d9s3cXFH42AYTyS2dTd4uaNir73J +co4vzLuu2+QVUhkHM/tqty1LkCiCc/4YizWN26cEar7qwU02OxY2kTLvtkCJkUPg +8qKrBC7m8kwOFjQgrIfBLX7JZkcXFBGk8/ehJImr2BrIoVyxo/eMbcgByU/J7MT8 +rFEz0ciD0cmfHdRHNCk+y7AO+oMLKFjlKdw/fKifybYKu6boRhYPluV75Gp6SG12 +mAWl3G0eQh5C2hrgUve1g8Aae3g1LDj1H/1Joy7SWWO/gLCMk3PLNaaZlSJhZQNg ++y+TS/qanIA7AgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtqeX +gj10hZv3PJ+TmpV5dVKMbUcwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS2 +p5eCPXSFm/c8n5OalXl1UoxtRzANBgkqhkiG9w0BAQwFAAOCAgEAqMxhpr51nhVQ +pGv7qHBFfLp+sVr8WyP6Cnf4mHGCDG3gXkaqk/QeoMPhk9tLrbKmXauw1GLLXrtm +9S3ul0A8Yute1hTWjOKWi0FpkzXmuZlrYrShF2Y0pmtjxrlO8iLpWA1WQdH6DErw +M807u20hOq6OcrXDSvvpfeWxm4bu4uB9tPcy/SKE8YXJN3nptT+/XOR0so8RYgDd +GGah2XsjX/GO1WfoVNpbOms2b/mBsTNHM3dA+VKq3dSDz4V4mZqTuXNnQkYRIer+ +CqkbGmVps4+uFrb2S1ayLfmlyOw7YqPta9BO1UAJpB+Y1zqlklkg5LB9zVtzaL1t +xKITDmcZuI1CfmwMmm6gJC3VRRvcxAIU/oVbZZfKTpBQCHpCNfnqwmbU+AGuHrS+ +w6jv/naaoqYfRvaE7fzbzsQCzndILIyy7MMAo+wsVRjBfhnu4S/yrYObnqsZ38aK +L4x35bcF7DvB7L6Gs4a8wPfc5+pbrrLMtTWGS9DiP7bY+A4A7l3j941Y/8+LN+lj +X273CXE2whJdV/LItM3z7gLfEdxquVeEHVlNjM7IDiPCtyaaEBRx/pOyiriA8A4Q +ntOoUAw3gi/q4Iqd4Sw5/7W0cwDk90imc6y/st53BIe0o82bNSQ3+pCTE4FCxpgm +dTdmQRCsu/WU48IxK63nI1bMNSWSs1A= +-----END CERTIFICATE----- diff --git a/shared/package-files/7a/7a36fd6c37f88c643184e9678cf99f9298f945af8b6f8b9933848b15e452dea5/blob b/shared/package-files/7a/7a36fd6c37f88c643184e9678cf99f9298f945af8b6f8b9933848b15e452dea5/blob new file mode 100644 index 0000000000000000000000000000000000000000..c378fbf8a0d2e3d300ec01989a6977bb0b45a0e2 --- /dev/null +++ b/shared/package-files/7a/7a36fd6c37f88c643184e9678cf99f9298f945af8b6f8b9933848b15e452dea5/blob @@ -0,0 +1,165 @@ +import numpy as np + + +class RegressionEffects: + """ + Base class for regression effects used in RegressionFDR + + Any implementation of the class must provide a method called + 'stats' that takes a RegressionFDR object and returns effect sizes + for the model coefficients. Greater values for these statistics + imply greater evidence that the effect is real. + + Knockoff effect sizes are based on fitting the regression model to + an extended design matrix [X X'], where X' is a design matrix with + the same shape as the actual design matrix X. The construction of + X' guarantees that there are no true associations between the + columns of X' and the dependent variable of the regression. If X + has p columns, then the effect size of covariate j is based on the + strength of the estimated association for coefficient j compared + to the strength of the estimated association for coefficient p+j. + """ + + def stats(self, parent): + raise NotImplementedError + + +class CorrelationEffects(RegressionEffects): + """ + Marginal correlation effect sizes for FDR control + + Parameters + ---------- + parent : RegressionFDR + The RegressionFDR instance to which this effect size is + applied. + + Notes + ----- + This class implements the marginal correlation approach to + constructing test statistics for a knockoff analysis, as + described under (1) in section 2.2 of the Barber and Candes + paper. + """ + + def stats(self, parent): + s1 = np.dot(parent.exog1.T, parent.endog) + s2 = np.dot(parent.exog2.T, parent.endog) + return np.abs(s1) - np.abs(s2) + + +class ForwardEffects(RegressionEffects): + """ + Forward selection effect sizes for FDR control + + Parameters + ---------- + parent : RegressionFDR + The RegressionFDR instance to which this effect size is + applied. + pursuit : bool + If True, 'basis pursuit' is used, which amounts to performing + a full regression at each selection step to adjust the working + residual vector. If False, the residual is adjusted by + regressing out each selected variable marginally. Setting + pursuit=True will be considerably slower, but may give better + results when exog is not orthogonal. + + Notes + ----- + This class implements the forward selection approach to + constructing test statistics for a knockoff analysis, as + described under (5) in section 2.2 of the Barber and Candes + paper. + """ + + def __init__(self, pursuit): + self.pursuit = pursuit + + def stats(self, parent): + nvar = parent.exog.shape[1] + rv = parent.endog.copy() + vl = [(i, parent.exog[:, i]) for i in range(nvar)] + z = np.empty(nvar) + past = [] + for i in range(nvar): + dp = np.r_[[np.abs(np.dot(rv, x[1])) for x in vl]] + j = np.argmax(dp) + z[vl[j][0]] = nvar - i - 1 + x = vl[j][1] + del vl[j] + if self.pursuit: + for v in past: + x -= np.dot(x, v)*v + past.append(x) + rv = rv - np.dot(rv, x) * x + z1 = z[0:nvar//2] + z2 = z[nvar//2:] + st = np.where(z1 > z2, z1, z2) * np.sign(z1 - z2) + return st + + +class OLSEffects(RegressionEffects): + """ + OLS regression for knockoff analysis + + Parameters + ---------- + parent : RegressionFDR + The RegressionFDR instance to which this effect size is + applied. + + Notes + ----- + This class implements the ordinary least squares regression + approach to constructing test statistics for a knockoff analysis, + as described under (2) in section 2.2 of the Barber and Candes + paper. + """ + + def stats(self, parent): + from statsmodels.regression.linear_model import OLS + + model = OLS(parent.endog, parent.exog) + result = model.fit() + q = len(result.params) // 2 + stats = np.abs(result.params[0:q]) - np.abs(result.params[q:]) + return stats + + +class RegModelEffects(RegressionEffects): + """ + Use any regression model for Regression FDR analysis + + Parameters + ---------- + parent : RegressionFDR + The RegressionFDR instance to which this effect size is + applied. + model_cls : class + Any model with appropriate fit or fit_regularized + functions. + regularized : bool, optional + If True, use fit_regularized to fit the model. + model_kws : dict, optional + Keywords passed to model initializer. + fit_kws : dict, optional + Dictionary of keyword arguments for fit or fit_regularized. + """ + + def __init__(self, model_cls, regularized=False, model_kws=None, + fit_kws=None): + self.model_cls = model_cls + self.regularized = regularized + self.model_kws = model_kws if model_kws is not None else {} + self.fit_kws = fit_kws if fit_kws is not None else {} + + def stats(self, parent): + model = self.model_cls(parent.endog, parent.exog, **self.model_kws) + if self.regularized: + params = model.fit_regularized(**self.fit_kws).params + else: + params = model.fit(**self.fit_kws).params + q = len(params) // 2 + stats = np.abs(params[0:q]) - np.abs(params[q:]) + return stats diff --git a/shared/package-files/7a/7a37e2d8fcc35cfd4850493c17277a1049017df27c39bf2045cf1e5edc9b1bb5/blob b/shared/package-files/7a/7a37e2d8fcc35cfd4850493c17277a1049017df27c39bf2045cf1e5edc9b1bb5/blob new file mode 100644 index 0000000000000000000000000000000000000000..c663422af56a6001b4d8191a190d5a9689c19bca --- /dev/null +++ b/shared/package-files/7a/7a37e2d8fcc35cfd4850493c17277a1049017df27c39bf2045cf1e5edc9b1bb5/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor logical_and(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_and_(at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_and_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/7a/7a3b72c5e797fd6d5adab36b1145221bdb713d6f3f52d4a0b7c21a0cec44da98/blob b/shared/package-files/7a/7a3b72c5e797fd6d5adab36b1145221bdb713d6f3f52d4a0b7c21a0cec44da98/blob new file mode 100644 index 0000000000000000000000000000000000000000..8716f7e3db67d1fd479f913d12286715029ed1a4 Binary files /dev/null and b/shared/package-files/7a/7a3b72c5e797fd6d5adab36b1145221bdb713d6f3f52d4a0b7c21a0cec44da98/blob differ diff --git a/shared/package-files/7a/7a40868360ddce2e294dfa5489a74d3396e0663a7cfa2f2dc446b5b6a1497529/blob b/shared/package-files/7a/7a40868360ddce2e294dfa5489a74d3396e0663a7cfa2f2dc446b5b6a1497529/blob new file mode 100644 index 0000000000000000000000000000000000000000..0c8bb5b0a77a017fbc1769eb541f924b2315c40b --- /dev/null +++ b/shared/package-files/7a/7a40868360ddce2e294dfa5489a74d3396e0663a7cfa2f2dc446b5b6a1497529/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_spdiags(Tensor diagonals, Tensor offsets, int[] shape, Layout? layout=None) -> Tensor +inline at::Tensor _spdiags(const at::Tensor & diagonals, const at::Tensor & offsets, at::IntArrayRef shape, c10::optional layout=c10::nullopt) { + return at::_ops::_spdiags::call(diagonals, offsets, shape, layout); +} + +// aten::_spdiags.out(Tensor diagonals, Tensor offsets, int[] shape, Layout? layout=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _spdiags_out(at::Tensor & out, const at::Tensor & diagonals, const at::Tensor & offsets, at::IntArrayRef shape, c10::optional layout=c10::nullopt) { + return at::_ops::_spdiags_out::call(diagonals, offsets, shape, layout, out); +} +// aten::_spdiags.out(Tensor diagonals, Tensor offsets, int[] shape, Layout? layout=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _spdiags_outf(const at::Tensor & diagonals, const at::Tensor & offsets, at::IntArrayRef shape, c10::optional layout, at::Tensor & out) { + return at::_ops::_spdiags_out::call(diagonals, offsets, shape, layout, out); +} + +} diff --git a/shared/package-files/7a/7a4337f63ce40c572e9376a120c9fe8f8254cf79197920f1c41ff659147150b3/blob b/shared/package-files/7a/7a4337f63ce40c572e9376a120c9fe8f8254cf79197920f1c41ff659147150b3/blob new file mode 100644 index 0000000000000000000000000000000000000000..794e365c0d8a5ce337765fc669d688e80240d540 --- /dev/null +++ b/shared/package-files/7a/7a4337f63ce40c572e9376a120c9fe8f8254cf79197920f1c41ff659147150b3/blob @@ -0,0 +1,45 @@ +""" +Check the SciPy config is valid. +""" +import scipy +import pytest +from unittest.mock import patch + +pytestmark = pytest.mark.skipif( + not hasattr(scipy.__config__, "_built_with_meson"), + reason="Requires Meson builds", +) + + +class TestSciPyConfigs: + REQUIRED_CONFIG_KEYS = [ + "Compilers", + "Machine Information", + "Python Information", + ] + + @pytest.mark.thread_unsafe + @patch("scipy.__config__._check_pyyaml") + def test_pyyaml_not_found(self, mock_yaml_importer): + mock_yaml_importer.side_effect = ModuleNotFoundError() + with pytest.warns(UserWarning): + scipy.show_config() + + def test_dict_mode(self): + config = scipy.show_config(mode="dicts") + + assert isinstance(config, dict) + assert all([key in config for key in self.REQUIRED_CONFIG_KEYS]), ( + "Required key missing," + " see index of `False` with `REQUIRED_CONFIG_KEYS`" + ) + + def test_invalid_mode(self): + with pytest.raises(AttributeError): + scipy.show_config(mode="foo") + + def test_warn_to_add_tests(self): + assert len(scipy.__config__.DisplayModes) == 2, ( + "New mode detected," + " please add UT if applicable and increment this count" + ) diff --git a/shared/package-files/7a/7a43821d29c5618a2651d8c51ac5a308d48fa7dfabe8045b5916daceb9089b99/blob b/shared/package-files/7a/7a43821d29c5618a2651d8c51ac5a308d48fa7dfabe8045b5916daceb9089b99/blob new file mode 100644 index 0000000000000000000000000000000000000000..c652ea8a4776691a1287fa6eed1afa532e752dd5 --- /dev/null +++ b/shared/package-files/7a/7a43821d29c5618a2651d8c51ac5a308d48fa7dfabe8045b5916daceb9089b99/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API max_pool2d_with_indices_out { + using schema = ::std::tuple (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::max_pool2d_with_indices") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "max_pool2d_with_indices.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))") + static ::std::tuple call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out, at::Tensor & indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out, at::Tensor & indices); +}; + +struct TORCH_API max_pool2d_with_indices { + using schema = ::std::tuple (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::max_pool2d_with_indices") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7a/7a43dd5f5c29e982d48436e5e1507c837fa057fd0a352f678f1f9b72f70dab66/blob b/shared/package-files/7a/7a43dd5f5c29e982d48436e5e1507c837fa057fd0a352f678f1f9b72f70dab66/blob new file mode 100644 index 0000000000000000000000000000000000000000..eaa436bfbcd5658131655b4de497cfc5c35734fa --- /dev/null +++ b/shared/package-files/7a/7a43dd5f5c29e982d48436e5e1507c837fa057fd0a352f678f1f9b72f70dab66/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_mish_out : public at::meta::structured_mish { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/7a/7a48594d3d57f7241ded334845dbbfbee8b9151d824e62343564c5253a85d4de/blob b/shared/package-files/7a/7a48594d3d57f7241ded334845dbbfbee8b9151d824e62343564c5253a85d4de/blob new file mode 100644 index 0000000000000000000000000000000000000000..f7c9c419622915b9834a5cb25a663f5d7ea23f43 --- /dev/null +++ b/shared/package-files/7a/7a48594d3d57f7241ded334845dbbfbee8b9151d824e62343564c5253a85d4de/blob @@ -0,0 +1,812 @@ +""" +Default legend handlers. + +.. important:: + + This is a low-level legend API, which most end users do not need. + + We recommend that you are familiar with the :ref:`legend guide + ` before reading this documentation. + +Legend handlers are expected to be a callable object with a following +signature:: + + legend_handler(legend, orig_handle, fontsize, handlebox) + +Where *legend* is the legend itself, *orig_handle* is the original +plot, *fontsize* is the fontsize in pixels, and *handlebox* is an +`.OffsetBox` instance. Within the call, you should create relevant +artists (using relevant properties from the *legend* and/or +*orig_handle*) and add them into the *handlebox*. The artists need to +be scaled according to the *fontsize* (note that the size is in pixels, +i.e., this is dpi-scaled value). + +This module includes definition of several legend handler classes +derived from the base class (HandlerBase) with the following method:: + + def legend_artist(self, legend, orig_handle, fontsize, handlebox) +""" + +from itertools import cycle + +import numpy as np + +from matplotlib import cbook +from matplotlib.lines import Line2D +from matplotlib.patches import Rectangle +import matplotlib.collections as mcoll + + +def update_from_first_child(tgt, src): + first_child = next(iter(src.get_children()), None) + if first_child is not None: + tgt.update_from(first_child) + + +class HandlerBase: + """ + A base class for default legend handlers. + + The derived classes are meant to override *create_artists* method, which + has the following signature:: + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + + The overridden method needs to create artists of the given + transform that fits in the given dimension (xdescent, ydescent, + width, height) that are scaled by fontsize if necessary. + + """ + def __init__(self, xpad=0., ypad=0., update_func=None): + """ + Parameters + ---------- + xpad : float, optional + Padding in x-direction. + ypad : float, optional + Padding in y-direction. + update_func : callable, optional + Function for updating the legend handler properties from another + legend handler, used by `~HandlerBase.update_prop`. + """ + self._xpad, self._ypad = xpad, ypad + self._update_prop_func = update_func + + def _update_prop(self, legend_handle, orig_handle): + if self._update_prop_func is None: + self._default_update_prop(legend_handle, orig_handle) + else: + self._update_prop_func(legend_handle, orig_handle) + + def _default_update_prop(self, legend_handle, orig_handle): + legend_handle.update_from(orig_handle) + + def update_prop(self, legend_handle, orig_handle, legend): + + self._update_prop(legend_handle, orig_handle) + + legend._set_artist_props(legend_handle) + legend_handle.set_clip_box(None) + legend_handle.set_clip_path(None) + + def adjust_drawing_area(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + ): + xdescent = xdescent - self._xpad * fontsize + ydescent = ydescent - self._ypad * fontsize + width = width - self._xpad * fontsize + height = height - self._ypad * fontsize + return xdescent, ydescent, width, height + + def legend_artist(self, legend, orig_handle, + fontsize, handlebox): + """ + Return the artist that this HandlerBase generates for the given + original artist/handle. + + Parameters + ---------- + legend : `~matplotlib.legend.Legend` + The legend for which these legend artists are being created. + orig_handle : :class:`matplotlib.artist.Artist` or similar + The object for which these legend artists are being created. + fontsize : int + The fontsize in pixels. The artists being created should + be scaled according to the given fontsize. + handlebox : `~matplotlib.offsetbox.OffsetBox` + The box which has been created to hold this legend entry's + artists. Artists created in the `legend_artist` method must + be added to this handlebox inside this method. + + """ + xdescent, ydescent, width, height = self.adjust_drawing_area( + legend, orig_handle, + handlebox.xdescent, handlebox.ydescent, + handlebox.width, handlebox.height, + fontsize) + artists = self.create_artists(legend, orig_handle, + xdescent, ydescent, width, height, + fontsize, handlebox.get_transform()) + + # create_artists will return a list of artists. + for a in artists: + handlebox.add_artist(a) + + # we only return the first artist + return artists[0] + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + """ + Return the legend artists generated. + + Parameters + ---------- + legend : `~matplotlib.legend.Legend` + The legend for which these legend artists are being created. + orig_handle : `~matplotlib.artist.Artist` or similar + The object for which these legend artists are being created. + xdescent, ydescent, width, height : int + The rectangle (*xdescent*, *ydescent*, *width*, *height*) that the + legend artists being created should fit within. + fontsize : int + The fontsize in pixels. The legend artists being created should + be scaled according to the given fontsize. + trans : `~matplotlib.transforms.Transform` + The transform that is applied to the legend artists being created. + Typically from unit coordinates in the handler box to screen + coordinates. + """ + raise NotImplementedError('Derived must override') + + +class HandlerNpoints(HandlerBase): + """ + A legend handler that shows *numpoints* points in the legend entry. + """ + + def __init__(self, marker_pad=0.3, numpoints=None, **kwargs): + """ + Parameters + ---------- + marker_pad : float + Padding between points in legend entry. + numpoints : int + Number of points to show in legend entry. + **kwargs + Keyword arguments forwarded to `.HandlerBase`. + """ + super().__init__(**kwargs) + + self._numpoints = numpoints + self._marker_pad = marker_pad + + def get_numpoints(self, legend): + if self._numpoints is None: + return legend.numpoints + else: + return self._numpoints + + def get_xdata(self, legend, xdescent, ydescent, width, height, fontsize): + numpoints = self.get_numpoints(legend) + if numpoints > 1: + # we put some pad here to compensate the size of the marker + pad = self._marker_pad * fontsize + xdata = np.linspace(-xdescent + pad, + -xdescent + width - pad, + numpoints) + xdata_marker = xdata + else: + xdata = [-xdescent, -xdescent + width] + xdata_marker = [-xdescent + 0.5 * width] + return xdata, xdata_marker + + +class HandlerNpointsYoffsets(HandlerNpoints): + """ + A legend handler that shows *numpoints* in the legend, and allows them to + be individually offset in the y-direction. + """ + + def __init__(self, numpoints=None, yoffsets=None, **kwargs): + """ + Parameters + ---------- + numpoints : int + Number of points to show in legend entry. + yoffsets : array of floats + Length *numpoints* list of y offsets for each point in + legend entry. + **kwargs + Keyword arguments forwarded to `.HandlerNpoints`. + """ + super().__init__(numpoints=numpoints, **kwargs) + self._yoffsets = yoffsets + + def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize): + if self._yoffsets is None: + ydata = height * legend._scatteryoffsets + else: + ydata = height * np.asarray(self._yoffsets) + + return ydata + + +class HandlerLine2DCompound(HandlerNpoints): + """ + Original handler for `.Line2D` instances, that relies on combining + a line-only with a marker-only artist. May be deprecated in the future. + """ + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + # docstring inherited + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + + ydata = np.full_like(xdata, ((height - ydescent) / 2)) + legline = Line2D(xdata, ydata) + + self.update_prop(legline, orig_handle, legend) + legline.set_drawstyle('default') + legline.set_marker("") + + legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) + self.update_prop(legline_marker, orig_handle, legend) + legline_marker.set_linestyle('None') + if legend.markerscale != 1: + newsz = legline_marker.get_markersize() * legend.markerscale + legline_marker.set_markersize(newsz) + # we don't want to add this to the return list because + # the texts and handles are assumed to be in one-to-one + # correspondence. + legline._legmarker = legline_marker + + legline.set_transform(trans) + legline_marker.set_transform(trans) + + return [legline, legline_marker] + + +class HandlerLine2D(HandlerNpoints): + """ + Handler for `.Line2D` instances. + + See Also + -------- + HandlerLine2DCompound : An earlier handler implementation, which used one + artist for the line and another for the marker(s). + """ + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + # docstring inherited + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + + markevery = None + if self.get_numpoints(legend) == 1: + # Special case: one wants a single marker in the center + # and a line that extends on both sides. One will use a + # 3 points line, but only mark the #1 (i.e. middle) point. + xdata = np.linspace(xdata[0], xdata[-1], 3) + markevery = [1] + + ydata = np.full_like(xdata, (height - ydescent) / 2) + legline = Line2D(xdata, ydata, markevery=markevery) + + self.update_prop(legline, orig_handle, legend) + + if legend.markerscale != 1: + newsz = legline.get_markersize() * legend.markerscale + legline.set_markersize(newsz) + + legline.set_transform(trans) + + return [legline] + + +class HandlerPatch(HandlerBase): + """ + Handler for `.Patch` instances. + """ + + def __init__(self, patch_func=None, **kwargs): + """ + Parameters + ---------- + patch_func : callable, optional + The function that creates the legend key artist. + *patch_func* should have the signature:: + + def patch_func(legend=legend, orig_handle=orig_handle, + xdescent=xdescent, ydescent=ydescent, + width=width, height=height, fontsize=fontsize) + + Subsequently, the created artist will have its ``update_prop`` + method called and the appropriate transform will be applied. + + **kwargs + Keyword arguments forwarded to `.HandlerBase`. + """ + super().__init__(**kwargs) + self._patch_func = patch_func + + def _create_patch(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize): + if self._patch_func is None: + p = Rectangle(xy=(-xdescent, -ydescent), + width=width, height=height) + else: + p = self._patch_func(legend=legend, orig_handle=orig_handle, + xdescent=xdescent, ydescent=ydescent, + width=width, height=height, fontsize=fontsize) + return p + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, trans): + # docstring inherited + p = self._create_patch(legend, orig_handle, + xdescent, ydescent, width, height, fontsize) + self.update_prop(p, orig_handle, legend) + p.set_transform(trans) + return [p] + + +class HandlerStepPatch(HandlerBase): + """ + Handler for `~.matplotlib.patches.StepPatch` instances. + """ + + @staticmethod + def _create_patch(orig_handle, xdescent, ydescent, width, height): + return Rectangle(xy=(-xdescent, -ydescent), width=width, + height=height, color=orig_handle.get_facecolor()) + + @staticmethod + def _create_line(orig_handle, width, height): + # Unfilled StepPatch should show as a line + legline = Line2D([0, width], [height/2, height/2], + color=orig_handle.get_edgecolor(), + linestyle=orig_handle.get_linestyle(), + linewidth=orig_handle.get_linewidth(), + ) + + # Overwrite manually because patch and line properties don't mix + legline.set_drawstyle('default') + legline.set_marker("") + return legline + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, trans): + # docstring inherited + if orig_handle.get_fill() or (orig_handle.get_hatch() is not None): + p = self._create_patch(orig_handle, xdescent, ydescent, width, + height) + self.update_prop(p, orig_handle, legend) + else: + p = self._create_line(orig_handle, width, height) + p.set_transform(trans) + return [p] + + +class HandlerLineCollection(HandlerLine2D): + """ + Handler for `.LineCollection` instances. + """ + def get_numpoints(self, legend): + if self._numpoints is None: + return legend.scatterpoints + else: + return self._numpoints + + def _default_update_prop(self, legend_handle, orig_handle): + lw = orig_handle.get_linewidths()[0] + dashes = orig_handle._us_linestyles[0] + color = orig_handle.get_colors()[0] + legend_handle.set_color(color) + legend_handle.set_linestyle(dashes) + legend_handle.set_linewidth(lw) + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, trans): + # docstring inherited + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + ydata = np.full_like(xdata, (height - ydescent) / 2) + legline = Line2D(xdata, ydata) + + self.update_prop(legline, orig_handle, legend) + legline.set_transform(trans) + + return [legline] + + +class HandlerRegularPolyCollection(HandlerNpointsYoffsets): + r"""Handler for `.RegularPolyCollection`\s.""" + + def __init__(self, yoffsets=None, sizes=None, **kwargs): + super().__init__(yoffsets=yoffsets, **kwargs) + + self._sizes = sizes + + def get_numpoints(self, legend): + if self._numpoints is None: + return legend.scatterpoints + else: + return self._numpoints + + def get_sizes(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize): + if self._sizes is None: + handle_sizes = orig_handle.get_sizes() + if not len(handle_sizes): + handle_sizes = [1] + size_max = max(handle_sizes) * legend.markerscale ** 2 + size_min = min(handle_sizes) * legend.markerscale ** 2 + + numpoints = self.get_numpoints(legend) + if numpoints < 4: + sizes = [.5 * (size_max + size_min), size_max, + size_min][:numpoints] + else: + rng = (size_max - size_min) + sizes = rng * np.linspace(0, 1, numpoints) + size_min + else: + sizes = self._sizes + + return sizes + + def update_prop(self, legend_handle, orig_handle, legend): + + self._update_prop(legend_handle, orig_handle) + + legend_handle.set_figure(legend.get_figure(root=False)) + # legend._set_artist_props(legend_handle) + legend_handle.set_clip_box(None) + legend_handle.set_clip_path(None) + + def create_collection(self, orig_handle, sizes, offsets, offset_transform): + return type(orig_handle)( + orig_handle.get_numsides(), + rotation=orig_handle.get_rotation(), sizes=sizes, + offsets=offsets, offset_transform=offset_transform, + ) + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + # docstring inherited + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + + ydata = self.get_ydata(legend, xdescent, ydescent, + width, height, fontsize) + + sizes = self.get_sizes(legend, orig_handle, xdescent, ydescent, + width, height, fontsize) + + p = self.create_collection( + orig_handle, sizes, + offsets=list(zip(xdata_marker, ydata)), offset_transform=trans) + + self.update_prop(p, orig_handle, legend) + p.set_offset_transform(trans) + return [p] + + +class HandlerPathCollection(HandlerRegularPolyCollection): + r"""Handler for `.PathCollection`\s, which are used by `~.Axes.scatter`.""" + + def create_collection(self, orig_handle, sizes, offsets, offset_transform): + return type(orig_handle)( + [orig_handle.get_paths()[0]], sizes=sizes, + offsets=offsets, offset_transform=offset_transform, + ) + + +class HandlerCircleCollection(HandlerRegularPolyCollection): + r"""Handler for `.CircleCollection`\s.""" + + def create_collection(self, orig_handle, sizes, offsets, offset_transform): + return type(orig_handle)( + sizes, offsets=offsets, offset_transform=offset_transform) + + +class HandlerErrorbar(HandlerLine2D): + """Handler for Errorbars.""" + + def __init__(self, xerr_size=0.5, yerr_size=None, + marker_pad=0.3, numpoints=None, **kwargs): + + self._xerr_size = xerr_size + self._yerr_size = yerr_size + + super().__init__(marker_pad=marker_pad, numpoints=numpoints, **kwargs) + + def get_err_size(self, legend, xdescent, ydescent, + width, height, fontsize): + xerr_size = self._xerr_size * fontsize + + if self._yerr_size is None: + yerr_size = xerr_size + else: + yerr_size = self._yerr_size * fontsize + + return xerr_size, yerr_size + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + # docstring inherited + plotlines, caplines, barlinecols = orig_handle + + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + + ydata = np.full_like(xdata, (height - ydescent) / 2) + legline = Line2D(xdata, ydata) + + xdata_marker = np.asarray(xdata_marker) + ydata_marker = np.asarray(ydata[:len(xdata_marker)]) + + xerr_size, yerr_size = self.get_err_size(legend, xdescent, ydescent, + width, height, fontsize) + + legline_marker = Line2D(xdata_marker, ydata_marker) + + # when plotlines are None (only errorbars are drawn), we just + # make legline invisible. + if plotlines is None: + legline.set_visible(False) + legline_marker.set_visible(False) + else: + self.update_prop(legline, plotlines, legend) + + legline.set_drawstyle('default') + legline.set_marker('none') + + self.update_prop(legline_marker, plotlines, legend) + legline_marker.set_linestyle('None') + + if legend.markerscale != 1: + newsz = legline_marker.get_markersize() * legend.markerscale + legline_marker.set_markersize(newsz) + + handle_barlinecols = [] + handle_caplines = [] + + if orig_handle.has_xerr: + verts = [((x - xerr_size, y), (x + xerr_size, y)) + for x, y in zip(xdata_marker, ydata_marker)] + coll = mcoll.LineCollection(verts) + self.update_prop(coll, barlinecols[0], legend) + handle_barlinecols.append(coll) + + if caplines: + capline_left = Line2D(xdata_marker - xerr_size, ydata_marker) + capline_right = Line2D(xdata_marker + xerr_size, ydata_marker) + self.update_prop(capline_left, caplines[0], legend) + self.update_prop(capline_right, caplines[0], legend) + capline_left.set_marker("|") + capline_right.set_marker("|") + + handle_caplines.append(capline_left) + handle_caplines.append(capline_right) + + if orig_handle.has_yerr: + verts = [((x, y - yerr_size), (x, y + yerr_size)) + for x, y in zip(xdata_marker, ydata_marker)] + coll = mcoll.LineCollection(verts) + self.update_prop(coll, barlinecols[0], legend) + handle_barlinecols.append(coll) + + if caplines: + capline_left = Line2D(xdata_marker, ydata_marker - yerr_size) + capline_right = Line2D(xdata_marker, ydata_marker + yerr_size) + self.update_prop(capline_left, caplines[0], legend) + self.update_prop(capline_right, caplines[0], legend) + capline_left.set_marker("_") + capline_right.set_marker("_") + + handle_caplines.append(capline_left) + handle_caplines.append(capline_right) + + artists = [ + *handle_barlinecols, *handle_caplines, legline, legline_marker, + ] + for artist in artists: + artist.set_transform(trans) + return artists + + +class HandlerStem(HandlerNpointsYoffsets): + """ + Handler for plots produced by `~.Axes.stem`. + """ + + def __init__(self, marker_pad=0.3, numpoints=None, + bottom=None, yoffsets=None, **kwargs): + """ + Parameters + ---------- + marker_pad : float, default: 0.3 + Padding between points in legend entry. + numpoints : int, optional + Number of points to show in legend entry. + bottom : float, optional + + yoffsets : array of floats, optional + Length *numpoints* list of y offsets for each point in + legend entry. + **kwargs + Keyword arguments forwarded to `.HandlerNpointsYoffsets`. + """ + super().__init__(marker_pad=marker_pad, numpoints=numpoints, + yoffsets=yoffsets, **kwargs) + self._bottom = bottom + + def get_ydata(self, legend, xdescent, ydescent, width, height, fontsize): + if self._yoffsets is None: + ydata = height * (0.5 * legend._scatteryoffsets + 0.5) + else: + ydata = height * np.asarray(self._yoffsets) + + return ydata + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + # docstring inherited + markerline, stemlines, baseline = orig_handle + # Check to see if the stemcontainer is storing lines as a list or a + # LineCollection. Eventually using a list will be removed, and this + # logic can also be removed. + using_linecoll = isinstance(stemlines, mcoll.LineCollection) + + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + + ydata = self.get_ydata(legend, xdescent, ydescent, + width, height, fontsize) + + if self._bottom is None: + bottom = 0. + else: + bottom = self._bottom + + leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)]) + self.update_prop(leg_markerline, markerline, legend) + + leg_stemlines = [Line2D([x, x], [bottom, y]) + for x, y in zip(xdata_marker, ydata)] + + if using_linecoll: + # change the function used by update_prop() from the default + # to one that handles LineCollection + with cbook._setattr_cm( + self, _update_prop_func=self._copy_collection_props): + for line in leg_stemlines: + self.update_prop(line, stemlines, legend) + + else: + for lm, m in zip(leg_stemlines, stemlines): + self.update_prop(lm, m, legend) + + leg_baseline = Line2D([np.min(xdata), np.max(xdata)], + [bottom, bottom]) + self.update_prop(leg_baseline, baseline, legend) + + artists = [*leg_stemlines, leg_baseline, leg_markerline] + for artist in artists: + artist.set_transform(trans) + return artists + + def _copy_collection_props(self, legend_handle, orig_handle): + """ + Copy properties from the `.LineCollection` *orig_handle* to the + `.Line2D` *legend_handle*. + """ + legend_handle.set_color(orig_handle.get_color()[0]) + legend_handle.set_linestyle(orig_handle.get_linestyle()[0]) + + +class HandlerTuple(HandlerBase): + """ + Handler for Tuple. + """ + + def __init__(self, ndivide=1, pad=None, **kwargs): + """ + Parameters + ---------- + ndivide : int or None, default: 1 + The number of sections to divide the legend area into. If None, + use the length of the input tuple. + pad : float, default: :rc:`legend.borderpad` + Padding in units of fraction of font size. + **kwargs + Keyword arguments forwarded to `.HandlerBase`. + """ + self._ndivide = ndivide + self._pad = pad + super().__init__(**kwargs) + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, + trans): + # docstring inherited + handler_map = legend.get_legend_handler_map() + + if self._ndivide is None: + ndivide = len(orig_handle) + else: + ndivide = self._ndivide + + if self._pad is None: + pad = legend.borderpad * fontsize + else: + pad = self._pad * fontsize + + if ndivide > 1: + width = (width - pad * (ndivide - 1)) / ndivide + + xds_cycle = cycle(xdescent - (width + pad) * np.arange(ndivide)) + + a_list = [] + for handle1 in orig_handle: + handler = legend.get_legend_handler(handler_map, handle1) + _a_list = handler.create_artists( + legend, handle1, + next(xds_cycle), ydescent, width, height, fontsize, trans) + a_list.extend(_a_list) + + return a_list + + +class HandlerPolyCollection(HandlerBase): + """ + Handler for `.PolyCollection` used in `~.Axes.fill_between` and + `~.Axes.stackplot`. + """ + def _update_prop(self, legend_handle, orig_handle): + def first_color(colors): + if colors.size == 0: + return (0, 0, 0, 0) + return tuple(colors[0]) + + def get_first(prop_array): + if len(prop_array): + return prop_array[0] + else: + return None + + # orig_handle is a PolyCollection and legend_handle is a Patch. + # Directly set Patch color attributes (must be RGBA tuples). + legend_handle._facecolor = first_color(orig_handle.get_facecolor()) + legend_handle._edgecolor = first_color(orig_handle.get_edgecolor()) + legend_handle._original_facecolor = orig_handle._original_facecolor + legend_handle._original_edgecolor = orig_handle._original_edgecolor + legend_handle._fill = orig_handle.get_fill() + legend_handle._hatch = orig_handle.get_hatch() + # Hatch color is anomalous in having no getters and setters. + legend_handle._hatch_color = orig_handle._hatch_color + # Setters are fine for the remaining attributes. + legend_handle.set_linewidth(get_first(orig_handle.get_linewidths())) + legend_handle.set_linestyle(get_first(orig_handle.get_linestyles())) + legend_handle.set_transform(get_first(orig_handle.get_transforms())) + # Alpha is already taken into account by the color attributes. + + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, trans): + # docstring inherited + p = Rectangle(xy=(-xdescent, -ydescent), + width=width, height=height) + self.update_prop(p, orig_handle, legend) + p.set_transform(trans) + return [p] diff --git a/shared/package-files/7a/7a4d44b5b21b2cbc1e85bf170d229e36f21d8d37c342843d092bb84db63c55ba/blob b/shared/package-files/7a/7a4d44b5b21b2cbc1e85bf170d229e36f21d8d37c342843d092bb84db63c55ba/blob new file mode 100644 index 0000000000000000000000000000000000000000..e81306304abffb313ab5abe09116a162642a9d67 --- /dev/null +++ b/shared/package-files/7a/7a4d44b5b21b2cbc1e85bf170d229e36f21d8d37c342843d092bb84db63c55ba/blob @@ -0,0 +1,24 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BarycentricInterpolator', + 'KroghInterpolator', + 'approximate_taylor_polynomial', + 'barycentric_interpolate', + 'krogh_interpolate', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="polyint", + private_modules=["_polyint"], all=__all__, + attribute=name) diff --git a/shared/package-files/7a/7a4d734bd9cbd6708e0f1246076b49e945f3d8a8c7a09cd77986b9e01ff0254e/blob b/shared/package-files/7a/7a4d734bd9cbd6708e0f1246076b49e945f3d8a8c7a09cd77986b9e01ff0254e/blob new file mode 100644 index 0000000000000000000000000000000000000000..ec5896f09bb0a7d8f8632a7ad94e60d9381e867a --- /dev/null +++ b/shared/package-files/7a/7a4d734bd9cbd6708e0f1246076b49e945f3d8a8c7a09cd77986b9e01ff0254e/blob @@ -0,0 +1,78 @@ +from argparse import ArgumentParser, HelpFormatter, Namespace +from io import StringIO, TextIOBase, TextIOWrapper +from typing import Any, Callable, List, Optional, Union, Tuple + +from django.apps.config import AppConfig +from django.core.management.color import Style + +class CommandError(Exception): ... +class SystemCheckError(CommandError): ... + +class CommandParser(ArgumentParser): + missing_args_message: None = ... + called_from_command_line: bool = ... + def __init__(self, **kwargs: Any) -> None: ... + def error(self, message: str) -> Any: ... + +def handle_default_options(options: Namespace) -> None: ... +def no_translations(handle_func: Callable) -> Callable: ... + +class DjangoHelpFormatter(HelpFormatter): ... + +class OutputWrapper(TextIOBase): + @property + def style_func(self): ... + @style_func.setter + def style_func(self, style_func: Callable[[str], str]): ... + ending: str = ... + def __init__( + self, out: Union[StringIO, TextIOWrapper], style_func: Optional[Callable[[str], str]] = ..., ending: str = ... + ) -> None: ... + def __getattr__(self, name: str) -> Callable: ... + def isatty(self) -> bool: ... + def write( # type: ignore[override] + self, msg: str, style_func: Optional[Callable[[str], str]] = ..., ending: Optional[str] = ... + ) -> None: ... + +class BaseCommand: + help: str = ... + output_transaction: bool = ... + requires_migrations_checks: bool = ... + requires_system_checks: bool = ... + base_stealth_options: Tuple[str, ...] = ... + stealth_options: Tuple[str, ...] = ... + stdout: OutputWrapper = ... + stderr: OutputWrapper = ... + style: Style = ... + def __init__( + self, + stdout: Optional[StringIO] = ..., + stderr: Optional[StringIO] = ..., + no_color: bool = ..., + force_color: bool = ..., + ) -> None: ... + def get_version(self) -> str: ... + def create_parser(self, prog_name: str, subcommand: str, **kwargs: Any) -> CommandParser: ... + def add_arguments(self, parser: CommandParser) -> None: ... + def print_help(self, prog_name: str, subcommand: str) -> None: ... + def run_from_argv(self, argv: List[str]) -> None: ... + def execute(self, *args: Any, **options: Any) -> Any: ... + def check( + self, + app_configs: Optional[List[AppConfig]] = ..., + tags: Optional[List[str]] = ..., + display_num_errors: bool = ..., + include_deployment_checks: bool = ..., + fail_level: int = ..., + ) -> None: ... + def check_migrations(self) -> None: ... + def handle(self, *args: Any, **options: Any) -> Optional[str]: ... + +class AppCommand(BaseCommand): + missing_args_message: str = ... + def handle_app_config(self, app_config: Any, **options: Any) -> None: ... + +class LabelCommand(BaseCommand): + label: str = ... + missing_args_message: Any = ... + def handle_label(self, label: Any, **options: Any) -> None: ... diff --git a/shared/package-files/7a/7a4e0e9ec98b05214a97d7ad312b2227b8788a861def77512156ce4be22f376f/blob b/shared/package-files/7a/7a4e0e9ec98b05214a97d7ad312b2227b8788a861def77512156ce4be22f376f/blob new file mode 100644 index 0000000000000000000000000000000000000000..19652884f003e6f6708234a5aecb9deadd69c580 Binary files /dev/null and b/shared/package-files/7a/7a4e0e9ec98b05214a97d7ad312b2227b8788a861def77512156ce4be22f376f/blob differ diff --git a/shared/package-files/7a/7a4f16b62848c8a46974e09535798dbed4712563bad48de4f247bef2b69ef50e/blob b/shared/package-files/7a/7a4f16b62848c8a46974e09535798dbed4712563bad48de4f247bef2b69ef50e/blob new file mode 100644 index 0000000000000000000000000000000000000000..22947f5b788a27fb32a1ceceebdea53490457cc5 --- /dev/null +++ b/shared/package-files/7a/7a4f16b62848c8a46974e09535798dbed4712563bad48de4f247bef2b69ef50e/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _foreach_ceil_out(at::TensorList out, at::TensorList self); +TORCH_API void _foreach_ceil_outf(at::TensorList self, at::TensorList out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/7a/7a5200bdb8cd3730109bfef8aaf9c27f3476fd714dfec68d0c1926c655a757e1/blob b/shared/package-files/7a/7a5200bdb8cd3730109bfef8aaf9c27f3476fd714dfec68d0c1926c655a757e1/blob new file mode 100644 index 0000000000000000000000000000000000000000..06d9f09be5fb0db7792b4004d5718c1ccc008502 Binary files /dev/null and b/shared/package-files/7a/7a5200bdb8cd3730109bfef8aaf9c27f3476fd714dfec68d0c1926c655a757e1/blob differ diff --git a/shared/package-files/7a/7a521b4d23396f9132c4b79b180c2b65526f8cb0f899d7debcd73f0e0801cf4f/blob b/shared/package-files/7a/7a521b4d23396f9132c4b79b180c2b65526f8cb0f899d7debcd73f0e0801cf4f/blob new file mode 100644 index 0000000000000000000000000000000000000000..8ffd2002e580db7cc6cae69161de1e88c788073c --- /dev/null +++ b/shared/package-files/7a/7a521b4d23396f9132c4b79b180c2b65526f8cb0f899d7debcd73f0e0801cf4f/blob @@ -0,0 +1,96 @@ +from __future__ import annotations + +import copy +from typing import List, Set + +import torch +import torch.nn.functional as F +from torch.ao.quantization.observer import PerChannelMinMaxObserver +from torch.ao.quantization.quantizer.quantizer import ( + QuantizationAnnotation, + QuantizationSpec, + Quantizer, +) +from torch.ao.quantization.quantizer.xnnpack_quantizer_utils import ( + OperatorConfig, + OperatorPatternType, + QuantizationConfig, +) + +__all__ = [ + "get_embedding_operators_config", + "EmbeddingQuantizer", +] + + +def get_embedding_operators_config() -> OperatorConfig: + weight_quantization_spec = QuantizationSpec( + dtype=torch.uint8, + qscheme=torch.per_channel_affine_float_qparams, + ch_axis=0, + observer_or_fake_quant_ctr=PerChannelMinMaxObserver.with_args(eps=2**-12), + ) + quantization_config = QuantizationConfig(None, None, weight_quantization_spec, None) + ops: List[OperatorPatternType] = [[torch.nn.Embedding]] + ops.append([F.embedding]) + supported_config_and_operators = OperatorConfig( + config=quantization_config, operators=ops + ) + return copy.deepcopy(supported_config_and_operators) + + +class EmbeddingQuantizer(Quantizer): + def __init__(self): + super().__init__() + + @classmethod + def get_supported_quantization_configs(cls) -> List[QuantizationConfig]: + op_configs: Set[QuantizationConfig] = set({}) + for spec, _ in cls.get_supported_operators(): + op_configs.add(spec) + return list(op_configs) + + @classmethod + def get_supported_operator_for_quantization_config( + cls, quantization_config: QuantizationConfig + ) -> List[OperatorPatternType]: + for config, ops in cls.get_supported_operators(): + # note: this assumes each entry in cls.supported_spec_and_operators + # corresponds to one spec, e.g. we don't have + # [(spec1, op_list1), (spec1, op_list2), (spec2, op_list3)] + # where the first and second entry have the same spec but did not + # merge the op list + if config == quantization_config: + return ops + return [] + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """just handling global spec for now""" + self._annotate_embedding_ops(model.graph) + return model + + def _annotate_embedding_ops(self, graph: torch.fx.Graph) -> None: + embedding_config: OperatorConfig = get_embedding_operators_config() + for node in graph.nodes: + # Keep node parsing based annotations instead of module partitioners + # just as an example of alternate ways of annotating + if ( + node.op == "call_function" + and node.target == torch.ops.aten.embedding.default + ): + if embedding_config.config.weight is None: + raise ValueError( + "Embedding config must have a valid weight quantization spec." + ) + node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map={ + node.args[0]: embedding_config.config.weight, + } + ) + + def validate(self, model: torch.fx.GraphModule) -> None: + pass + + @classmethod + def get_supported_operators(cls) -> List[OperatorConfig]: + return [get_embedding_operators_config()] diff --git a/shared/package-files/7a/7a53ccdd293ac86f06dbe258bfb496e2fae1a0314da1492e771a941cc51747b5/blob b/shared/package-files/7a/7a53ccdd293ac86f06dbe258bfb496e2fae1a0314da1492e771a941cc51747b5/blob new file mode 100644 index 0000000000000000000000000000000000000000..192177cc9bcfb0988171fb68554ab56a7120ed4c --- /dev/null +++ b/shared/package-files/7a/7a53ccdd293ac86f06dbe258bfb496e2fae1a0314da1492e771a941cc51747b5/blob @@ -0,0 +1,62 @@ +#pragma once + +namespace at { namespace native { inline namespace CPU_CAPABILITY { + +// n: number of function arguments (arity) +// traits: function_traits (see FunctionTraits.h) +// s: index of scalar argument or -1 +template +struct IsContiguous { + static bool eval(const int64_t* strides) { + using type = typename traits::template arg::type; + return strides[stride_index] == (s == n ? 0 : sizeof(type)) && + IsContiguous::eval(strides); + } +}; + +// will be called when there is an output exists +template +struct IsContiguous<0, 0, traits, s> { + static bool eval(const int64_t* strides) { + return strides[0] == sizeof(typename traits::result_type); + } +}; + +// will be called when there is no output +template +struct IsContiguous<0, -1, traits, s> { + static bool eval(const int64_t* /*strides*/) { + return true; + } +}; + +// output and all inputs are contiguous +template ::value>::type* = nullptr> +static inline bool is_contiguous(const int64_t* strides) { + return IsContiguous::eval(strides); +} + +template ::value>::type* = nullptr> +static inline bool is_contiguous(const int64_t* strides) { + return IsContiguous::eval(strides); +} + +// input at `s` is scalar (stride 0); output and other inputs are contiguous +// NB: output is typically at strides[0] so first input corresponds to s=1 +template ::value>::type* = nullptr> +static inline bool is_contiguous_scalar(const int64_t* strides) { + static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds"); + return IsContiguous::eval(strides); +} + +template ::value>::type* = nullptr> +static inline bool is_contiguous_scalar(const int64_t* strides) { + static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds"); + return IsContiguous::eval(strides); +} + +}}} diff --git a/shared/package-files/7a/7a55dbe717e32dd8e0492a10164e3fd90bb7969d8221a82517d310b5f2281fba/blob b/shared/package-files/7a/7a55dbe717e32dd8e0492a10164e3fd90bb7969d8221a82517d310b5f2281fba/blob new file mode 100644 index 0000000000000000000000000000000000000000..0aa85c253508b68bb075f556be3c3f76dc4467ad --- /dev/null +++ b/shared/package-files/7a/7a55dbe717e32dd8e0492a10164e3fd90bb7969d8221a82517d310b5f2281fba/blob @@ -0,0 +1,2 @@ +isympy +sympy diff --git a/shared/package-files/7a/7a564edfb888862d99591b0d31dd478cc7a449cce34bf74d9481a25a5fb5b2bf/blob b/shared/package-files/7a/7a564edfb888862d99591b0d31dd478cc7a449cce34bf74d9481a25a5fb5b2bf/blob new file mode 100644 index 0000000000000000000000000000000000000000..cb115d4c727f1842a0d43bdc4f6a8df2aba8f414 --- /dev/null +++ b/shared/package-files/7a/7a564edfb888862d99591b0d31dd478cc7a449cce34bf74d9481a25a5fb5b2bf/blob @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +""" +Conda's pure-python dependencies will be +`vendored `_ +until conda 5.0 when conda will be isolated in its own private environment. + +Introduction of dependencies for the 4.x series is discussed in +https://github.com/conda/conda/issues/2825. +""" diff --git a/shared/package-files/7a/7a56ca41232f57ca77a9610554503f9e77928dd5e5e37d906039616b5706546c/blob b/shared/package-files/7a/7a56ca41232f57ca77a9610554503f9e77928dd5e5e37d906039616b5706546c/blob new file mode 100644 index 0000000000000000000000000000000000000000..790ba92f70c40095af3f40396135be2842b33229 --- /dev/null +++ b/shared/package-files/7a/7a56ca41232f57ca77a9610554503f9e77928dd5e5e37d906039616b5706546c/blob @@ -0,0 +1,1177 @@ +from datetime import datetime +from io import StringIO +import itertools +import re +import textwrap + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + get_option, + option_context, +) +import pandas._testing as tm + +import pandas.io.formats.format as fmt + +lorem_ipsum = ( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " + "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex " + "ea commodo consequat. Duis aute irure dolor in reprehenderit in " + "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur " + "sint occaecat cupidatat non proident, sunt in culpa qui officia " + "deserunt mollit anim id est laborum." +) + + +def expected_html(datapath, name): + """ + Read HTML file from formats data directory. + + Parameters + ---------- + datapath : pytest fixture + The datapath fixture injected into a test by pytest. + name : str + The name of the HTML file without the suffix. + + Returns + ------- + str : contents of HTML file. + """ + filename = ".".join([name, "html"]) + filepath = datapath("io", "formats", "data", "html", filename) + with open(filepath, encoding="utf-8") as f: + html = f.read() + return html.rstrip() + + +@pytest.fixture(params=["mixed", "empty"]) +def biggie_df_fixture(request): + """Fixture for a big mixed Dataframe and an empty Dataframe""" + if request.param == "mixed": + df = DataFrame( + { + "A": np.random.default_rng(2).standard_normal(200), + "B": Index([f"{i}?!" for i in range(200)]), + }, + index=np.arange(200), + ) + df.loc[:20, "A"] = np.nan + df.loc[:20, "B"] = np.nan + return df + elif request.param == "empty": + df = DataFrame(index=np.arange(200)) + return df + + +@pytest.fixture(params=fmt.VALID_JUSTIFY_PARAMETERS) +def justify(request): + return request.param + + +@pytest.mark.parametrize("col_space", [30, 50]) +def test_to_html_with_col_space(col_space): + df = DataFrame(np.random.default_rng(2).random(size=(1, 3))) + # check that col_space affects HTML generation + # and be very brittle about it. + result = df.to_html(col_space=col_space) + hdrs = [x for x in result.split(r"\n") if re.search(r"\s]", x)] + assert len(hdrs) > 0 + for h in hdrs: + assert "min-width" in h + assert str(col_space) in h + + +def test_to_html_with_column_specific_col_space_raises(): + df = DataFrame( + np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"] + ) + + msg = ( + "Col_space length\\(\\d+\\) should match " + "DataFrame number of columns\\(\\d+\\)" + ) + with pytest.raises(ValueError, match=msg): + df.to_html(col_space=[30, 40]) + + with pytest.raises(ValueError, match=msg): + df.to_html(col_space=[30, 40, 50, 60]) + + msg = "unknown column" + with pytest.raises(ValueError, match=msg): + df.to_html(col_space={"a": "foo", "b": 23, "d": 34}) + + +def test_to_html_with_column_specific_col_space(): + df = DataFrame( + np.random.default_rng(2).random(size=(3, 3)), columns=["a", "b", "c"] + ) + + result = df.to_html(col_space={"a": "2em", "b": 23}) + hdrs = [x for x in result.split("\n") if re.search(r"\s]", x)] + assert 'min-width: 2em;">a' in hdrs[1] + assert 'min-width: 23px;">b' in hdrs[2] + assert "c" in hdrs[3] + + result = df.to_html(col_space=["1em", 2, 3]) + hdrs = [x for x in result.split("\n") if re.search(r"\s]", x)] + assert 'min-width: 1em;">a' in hdrs[1] + assert 'min-width: 2px;">b' in hdrs[2] + assert 'min-width: 3px;">c' in hdrs[3] + + +def test_to_html_with_empty_string_label(): + # GH 3547, to_html regards empty string labels as repeated labels + data = {"c1": ["a", "b"], "c2": ["a", ""], "data": [1, 2]} + df = DataFrame(data).set_index(["c1", "c2"]) + result = df.to_html() + assert "rowspan" not in result + + +@pytest.mark.parametrize( + "df,expected", + [ + (DataFrame({"\u03c3": np.arange(10.0)}), "unicode_1"), + (DataFrame({"A": ["\u03c3"]}), "unicode_2"), + ], +) +def test_to_html_unicode(df, expected, datapath): + expected = expected_html(datapath, expected) + result = df.to_html() + assert result == expected + + +def test_to_html_encoding(float_frame, tmp_path): + # GH 28663 + path = tmp_path / "test.html" + float_frame.to_html(path, encoding="gbk") + with open(str(path), encoding="gbk") as f: + assert float_frame.to_html() == f.read() + + +def test_to_html_decimal(datapath): + # GH 12031 + df = DataFrame({"A": [6.0, 3.1, 2.2]}) + result = df.to_html(decimal=",") + expected = expected_html(datapath, "gh12031_expected_output") + assert result == expected + + +@pytest.mark.parametrize( + "kwargs,string,expected", + [ + ({}, "", "escaped"), + ({"escape": False}, "bold", "escape_disabled"), + ], +) +def test_to_html_escaped(kwargs, string, expected, datapath): + a = "strl2": {a: string, b: string}} + result = DataFrame(test_dict).to_html(**kwargs) + expected = expected_html(datapath, expected) + assert result == expected + + +@pytest.mark.parametrize("index_is_named", [True, False]) +def test_to_html_multiindex_index_false(index_is_named, datapath): + # GH 8452 + df = DataFrame( + {"a": range(2), "b": range(3, 5), "c": range(5, 7), "d": range(3, 5)} + ) + df.columns = MultiIndex.from_product([["a", "b"], ["c", "d"]]) + if index_is_named: + df.index = Index(df.index.values, name="idx") + result = df.to_html(index=False) + expected = expected_html(datapath, "gh8452_expected_output") + assert result == expected + + +@pytest.mark.parametrize( + "multi_sparse,expected", + [ + (False, "multiindex_sparsify_false_multi_sparse_1"), + (False, "multiindex_sparsify_false_multi_sparse_2"), + (True, "multiindex_sparsify_1"), + (True, "multiindex_sparsify_2"), + ], +) +def test_to_html_multiindex_sparsify(multi_sparse, expected, datapath): + index = MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]], names=["foo", None]) + df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], index=index) + if expected.endswith("2"): + df.columns = index[::2] + with option_context("display.multi_sparse", multi_sparse): + result = df.to_html() + expected = expected_html(datapath, expected) + assert result == expected + + +@pytest.mark.parametrize( + "max_rows,expected", + [ + (60, "gh14882_expected_output_1"), + # Test that ... appears in a middle level + (56, "gh14882_expected_output_2"), + ], +) +def test_to_html_multiindex_odd_even_truncate(max_rows, expected, datapath): + # GH 14882 - Issue on truncation with odd length DataFrame + index = MultiIndex.from_product( + [[100, 200, 300], [10, 20, 30], [1, 2, 3, 4, 5, 6, 7]], names=["a", "b", "c"] + ) + df = DataFrame({"n": range(len(index))}, index=index) + result = df.to_html(max_rows=max_rows) + expected = expected_html(datapath, expected) + assert result == expected + + +@pytest.mark.parametrize( + "df,formatters,expected", + [ + ( + DataFrame( + [[0, 1], [2, 3], [4, 5], [6, 7]], + columns=Index(["foo", None], dtype=object), + index=np.arange(4), + ), + {"__index__": lambda x: "abcd"[x]}, + "index_formatter", + ), + ( + DataFrame({"months": [datetime(2016, 1, 1), datetime(2016, 2, 2)]}), + {"months": lambda x: x.strftime("%Y-%m")}, + "datetime64_monthformatter", + ), + ( + DataFrame( + { + "hod": pd.to_datetime( + ["10:10:10.100", "12:12:12.120"], format="%H:%M:%S.%f" + ) + } + ), + {"hod": lambda x: x.strftime("%H:%M")}, + "datetime64_hourformatter", + ), + ( + DataFrame( + { + "i": pd.Series([1, 2], dtype="int64"), + "f": pd.Series([1, 2], dtype="float64"), + "I": pd.Series([1, 2], dtype="Int64"), + "s": pd.Series([1, 2], dtype="string"), + "b": pd.Series([True, False], dtype="boolean"), + "c": pd.Series(["a", "b"], dtype=pd.CategoricalDtype(["a", "b"])), + "o": pd.Series([1, "2"], dtype=object), + } + ), + [lambda x: "formatted"] * 7, + "various_dtypes_formatted", + ), + ], +) +def test_to_html_formatters(df, formatters, expected, datapath): + expected = expected_html(datapath, expected) + result = df.to_html(formatters=formatters) + assert result == expected + + +def test_to_html_regression_GH6098(): + df = DataFrame( + { + "clé1": ["a", "a", "b", "b", "a"], + "clé2": ["1er", "2ème", "1er", "2ème", "1er"], + "données1": np.random.default_rng(2).standard_normal(5), + "données2": np.random.default_rng(2).standard_normal(5), + } + ) + + # it works + df.pivot_table(index=["clé1"], columns=["clé2"])._repr_html_() + + +def test_to_html_truncate(datapath): + index = pd.date_range(start="20010101", freq="D", periods=20) + df = DataFrame(index=index, columns=range(20)) + result = df.to_html(max_rows=8, max_cols=4) + expected = expected_html(datapath, "truncate") + assert result == expected + + +@pytest.mark.parametrize("size", [1, 5]) +def test_html_invalid_formatters_arg_raises(size): + # issue-28469 + df = DataFrame(columns=["a", "b", "c"]) + msg = "Formatters length({}) should match DataFrame number of columns(3)" + with pytest.raises(ValueError, match=re.escape(msg.format(size))): + df.to_html(formatters=["{}".format] * size) + + +def test_to_html_truncate_formatter(datapath): + # issue-25955 + data = [ + {"A": 1, "B": 2, "C": 3, "D": 4}, + {"A": 5, "B": 6, "C": 7, "D": 8}, + {"A": 9, "B": 10, "C": 11, "D": 12}, + {"A": 13, "B": 14, "C": 15, "D": 16}, + ] + + df = DataFrame(data) + fmt = lambda x: str(x) + "_mod" + formatters = [fmt, fmt, None, None] + result = df.to_html(formatters=formatters, max_cols=3) + expected = expected_html(datapath, "truncate_formatter") + assert result == expected + + +@pytest.mark.parametrize( + "sparsify,expected", + [(True, "truncate_multi_index"), (False, "truncate_multi_index_sparse_off")], +) +def test_to_html_truncate_multi_index(sparsify, expected, datapath): + arrays = [ + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + df = DataFrame(index=arrays, columns=arrays) + result = df.to_html(max_rows=7, max_cols=7, sparsify=sparsify) + expected = expected_html(datapath, expected) + assert result == expected + + +@pytest.mark.parametrize( + "option,result,expected", + [ + (None, lambda df: df.to_html(), "1"), + (None, lambda df: df.to_html(border=2), "2"), + (2, lambda df: df.to_html(), "2"), + (2, lambda df: df._repr_html_(), "2"), + ], +) +def test_to_html_border(option, result, expected): + df = DataFrame({"A": [1, 2]}) + if option is None: + result = result(df) + else: + with option_context("display.html.border", option): + result = result(df) + expected = f'border="{expected}"' + assert expected in result + + +@pytest.mark.parametrize("biggie_df_fixture", ["mixed"], indirect=True) +def test_to_html(biggie_df_fixture): + # TODO: split this test + df = biggie_df_fixture + s = df.to_html() + + buf = StringIO() + retval = df.to_html(buf=buf) + assert retval is None + assert buf.getvalue() == s + + assert isinstance(s, str) + + df.to_html(columns=["B", "A"], col_space=17) + df.to_html(columns=["B", "A"], formatters={"A": lambda x: f"{x:.1f}"}) + + df.to_html(columns=["B", "A"], float_format=str) + df.to_html(columns=["B", "A"], col_space=12, float_format=str) + + +@pytest.mark.parametrize("biggie_df_fixture", ["empty"], indirect=True) +def test_to_html_empty_dataframe(biggie_df_fixture): + df = biggie_df_fixture + df.to_html() + + +def test_to_html_filename(biggie_df_fixture, tmpdir): + df = biggie_df_fixture + expected = df.to_html() + path = tmpdir.join("test.html") + df.to_html(path) + result = path.read() + assert result == expected + + +def test_to_html_with_no_bold(): + df = DataFrame({"x": np.random.default_rng(2).standard_normal(5)}) + html = df.to_html(bold_rows=False) + result = html[html.find("")] + assert "B" not in result + + +@pytest.mark.parametrize( + "columns,justify,expected", + [ + ( + MultiIndex.from_arrays( + [np.arange(2).repeat(2), np.mod(range(4), 2)], + names=["CL0", "CL1"], + ), + "left", + "multiindex_1", + ), + ( + MultiIndex.from_arrays([np.arange(4), np.mod(range(4), 2)]), + "right", + "multiindex_2", + ), + ], +) +def test_to_html_multiindex(columns, justify, expected, datapath): + df = DataFrame([list("abcd"), list("efgh")], columns=columns) + result = df.to_html(justify=justify) + expected = expected_html(datapath, expected) + assert result == expected + + +def test_to_html_justify(justify, datapath): + df = DataFrame( + {"A": [6, 30000, 2], "B": [1, 2, 70000], "C": [223442, 0, 1]}, + columns=["A", "B", "C"], + ) + result = df.to_html(justify=justify) + expected = expected_html(datapath, "justify").format(justify=justify) + assert result == expected + + +@pytest.mark.parametrize( + "justify", ["super-right", "small-left", "noinherit", "tiny", "pandas"] +) +def test_to_html_invalid_justify(justify): + # GH 17527 + df = DataFrame() + msg = "Invalid value for justify parameter" + + with pytest.raises(ValueError, match=msg): + df.to_html(justify=justify) + + +class TestHTMLIndex: + @pytest.fixture + def df(self): + index = ["foo", "bar", "baz"] + df = DataFrame( + {"A": [1, 2, 3], "B": [1.2, 3.4, 5.6], "C": ["one", "two", np.nan]}, + columns=["A", "B", "C"], + index=index, + ) + return df + + @pytest.fixture + def expected_without_index(self, datapath): + return expected_html(datapath, "index_2") + + def test_to_html_flat_index_without_name( + self, datapath, df, expected_without_index + ): + expected_with_index = expected_html(datapath, "index_1") + assert df.to_html() == expected_with_index + + result = df.to_html(index=False) + for i in df.index: + assert i not in result + assert result == expected_without_index + + def test_to_html_flat_index_with_name(self, datapath, df, expected_without_index): + df.index = Index(["foo", "bar", "baz"], name="idx") + expected_with_index = expected_html(datapath, "index_3") + assert df.to_html() == expected_with_index + assert df.to_html(index=False) == expected_without_index + + def test_to_html_multiindex_without_names( + self, datapath, df, expected_without_index + ): + tuples = [("foo", "car"), ("foo", "bike"), ("bar", "car")] + df.index = MultiIndex.from_tuples(tuples) + + expected_with_index = expected_html(datapath, "index_4") + assert df.to_html() == expected_with_index + + result = df.to_html(index=False) + for i in ["foo", "bar", "car", "bike"]: + assert i not in result + # must be the same result as normal index + assert result == expected_without_index + + def test_to_html_multiindex_with_names(self, datapath, df, expected_without_index): + tuples = [("foo", "car"), ("foo", "bike"), ("bar", "car")] + df.index = MultiIndex.from_tuples(tuples, names=["idx1", "idx2"]) + expected_with_index = expected_html(datapath, "index_5") + assert df.to_html() == expected_with_index + assert df.to_html(index=False) == expected_without_index + + +@pytest.mark.parametrize("classes", ["sortable draggable", ["sortable", "draggable"]]) +def test_to_html_with_classes(classes, datapath): + df = DataFrame() + expected = expected_html(datapath, "with_classes") + result = df.to_html(classes=classes) + assert result == expected + + +def test_to_html_no_index_max_rows(datapath): + # GH 14998 + df = DataFrame({"A": [1, 2, 3, 4]}) + result = df.to_html(index=False, max_rows=1) + expected = expected_html(datapath, "gh14998_expected_output") + assert result == expected + + +def test_to_html_multiindex_max_cols(datapath): + # GH 6131 + index = MultiIndex( + levels=[["ba", "bb", "bc"], ["ca", "cb", "cc"]], + codes=[[0, 1, 2], [0, 1, 2]], + names=["b", "c"], + ) + columns = MultiIndex( + levels=[["d"], ["aa", "ab", "ac"]], + codes=[[0, 0, 0], [0, 1, 2]], + names=[None, "a"], + ) + data = np.array( + [[1.0, np.nan, np.nan], [np.nan, 2.0, np.nan], [np.nan, np.nan, 3.0]] + ) + df = DataFrame(data, index, columns) + result = df.to_html(max_cols=2) + expected = expected_html(datapath, "gh6131_expected_output") + assert result == expected + + +def test_to_html_multi_indexes_index_false(datapath): + # GH 22579 + df = DataFrame( + {"a": range(10), "b": range(10, 20), "c": range(10, 20), "d": range(10, 20)} + ) + df.columns = MultiIndex.from_product([["a", "b"], ["c", "d"]]) + df.index = MultiIndex.from_product([["a", "b"], ["c", "d", "e", "f", "g"]]) + result = df.to_html(index=False) + expected = expected_html(datapath, "gh22579_expected_output") + assert result == expected + + +@pytest.mark.parametrize("index_names", [True, False]) +@pytest.mark.parametrize("header", [True, False]) +@pytest.mark.parametrize("index", [True, False]) +@pytest.mark.parametrize( + "column_index, column_type", + [ + (Index([0, 1]), "unnamed_standard"), + (Index([0, 1], name="columns.name"), "named_standard"), + (MultiIndex.from_product([["a"], ["b", "c"]]), "unnamed_multi"), + ( + MultiIndex.from_product( + [["a"], ["b", "c"]], names=["columns.name.0", "columns.name.1"] + ), + "named_multi", + ), + ], +) +@pytest.mark.parametrize( + "row_index, row_type", + [ + (Index([0, 1]), "unnamed_standard"), + (Index([0, 1], name="index.name"), "named_standard"), + (MultiIndex.from_product([["a"], ["b", "c"]]), "unnamed_multi"), + ( + MultiIndex.from_product( + [["a"], ["b", "c"]], names=["index.name.0", "index.name.1"] + ), + "named_multi", + ), + ], +) +def test_to_html_basic_alignment( + datapath, row_index, row_type, column_index, column_type, index, header, index_names +): + # GH 22747, GH 22579 + df = DataFrame(np.zeros((2, 2), dtype=int), index=row_index, columns=column_index) + result = df.to_html(index=index, header=header, index_names=index_names) + + if not index: + row_type = "none" + elif not index_names and row_type.startswith("named"): + row_type = "un" + row_type + + if not header: + column_type = "none" + elif not index_names and column_type.startswith("named"): + column_type = "un" + column_type + + filename = "index_" + row_type + "_columns_" + column_type + expected = expected_html(datapath, filename) + assert result == expected + + +@pytest.mark.parametrize("index_names", [True, False]) +@pytest.mark.parametrize("header", [True, False]) +@pytest.mark.parametrize("index", [True, False]) +@pytest.mark.parametrize( + "column_index, column_type", + [ + (Index(np.arange(8)), "unnamed_standard"), + (Index(np.arange(8), name="columns.name"), "named_standard"), + ( + MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]), + "unnamed_multi", + ), + ( + MultiIndex.from_product( + [["a", "b"], ["c", "d"], ["e", "f"]], names=["foo", None, "baz"] + ), + "named_multi", + ), + ], +) +@pytest.mark.parametrize( + "row_index, row_type", + [ + (Index(np.arange(8)), "unnamed_standard"), + (Index(np.arange(8), name="index.name"), "named_standard"), + ( + MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]), + "unnamed_multi", + ), + ( + MultiIndex.from_product( + [["a", "b"], ["c", "d"], ["e", "f"]], names=["foo", None, "baz"] + ), + "named_multi", + ), + ], +) +def test_to_html_alignment_with_truncation( + datapath, row_index, row_type, column_index, column_type, index, header, index_names +): + # GH 22747, GH 22579 + df = DataFrame(np.arange(64).reshape(8, 8), index=row_index, columns=column_index) + result = df.to_html( + max_rows=4, max_cols=4, index=index, header=header, index_names=index_names + ) + + if not index: + row_type = "none" + elif not index_names and row_type.startswith("named"): + row_type = "un" + row_type + + if not header: + column_type = "none" + elif not index_names and column_type.startswith("named"): + column_type = "un" + column_type + + filename = "trunc_df_index_" + row_type + "_columns_" + column_type + expected = expected_html(datapath, filename) + assert result == expected + + +@pytest.mark.parametrize("index", [False, 0]) +def test_to_html_truncation_index_false_max_rows(datapath, index): + # GH 15019 + data = [ + [1.764052, 0.400157], + [0.978738, 2.240893], + [1.867558, -0.977278], + [0.950088, -0.151357], + [-0.103219, 0.410599], + ] + df = DataFrame(data) + result = df.to_html(max_rows=4, index=index) + expected = expected_html(datapath, "gh15019_expected_output") + assert result == expected + + +@pytest.mark.parametrize("index", [False, 0]) +@pytest.mark.parametrize( + "col_index_named, expected_output", + [(False, "gh22783_expected_output"), (True, "gh22783_named_columns_index")], +) +def test_to_html_truncation_index_false_max_cols( + datapath, index, col_index_named, expected_output +): + # GH 22783 + data = [ + [1.764052, 0.400157, 0.978738, 2.240893, 1.867558], + [-0.977278, 0.950088, -0.151357, -0.103219, 0.410599], + ] + df = DataFrame(data) + if col_index_named: + df.columns.rename("columns.name", inplace=True) + result = df.to_html(max_cols=4, index=index) + expected = expected_html(datapath, expected_output) + assert result == expected + + +@pytest.mark.parametrize("notebook", [True, False]) +def test_to_html_notebook_has_style(notebook): + df = DataFrame({"A": [1, 2, 3]}) + result = df.to_html(notebook=notebook) + + if notebook: + assert "tbody tr th:only-of-type" in result + assert "vertical-align: middle;" in result + assert "thead th" in result + else: + assert "tbody tr th:only-of-type" not in result + assert "vertical-align: middle;" not in result + assert "thead th" not in result + + +def test_to_html_with_index_names_false(): + # GH 16493 + df = DataFrame({"A": [1, 2]}, index=Index(["a", "b"], name="myindexname")) + result = df.to_html(index_names=False) + assert "myindexname" not in result + + +def test_to_html_with_id(): + # GH 8496 + df = DataFrame({"A": [1, 2]}, index=Index(["a", "b"], name="myindexname")) + result = df.to_html(index_names=False, table_id="TEST_ID") + assert ' id="TEST_ID"' in result + + +@pytest.mark.parametrize( + "value,float_format,expected", + [ + (0.19999, "%.3f", "gh21625_expected_output"), + (100.0, "%.0f", "gh22270_expected_output"), + ], +) +def test_to_html_float_format_no_fixed_width(value, float_format, expected, datapath): + # GH 21625, GH 22270 + df = DataFrame({"x": [value]}) + expected = expected_html(datapath, expected) + result = df.to_html(float_format=float_format) + assert result == expected + + +@pytest.mark.parametrize( + "render_links,expected", + [(True, "render_links_true"), (False, "render_links_false")], +) +def test_to_html_render_links(render_links, expected, datapath): + # GH 2679 + data = [ + [0, "https://pandas.pydata.org/?q1=a&q2=b", "pydata.org"], + [0, "www.pydata.org", "pydata.org"], + ] + df = DataFrame(data, columns=Index(["foo", "bar", None], dtype=object)) + + result = df.to_html(render_links=render_links) + expected = expected_html(datapath, expected) + assert result == expected + + +@pytest.mark.parametrize( + "method,expected", + [ + ("to_html", lambda x: lorem_ipsum), + ("_repr_html_", lambda x: lorem_ipsum[: x - 4] + "..."), # regression case + ], +) +@pytest.mark.parametrize("max_colwidth", [10, 20, 50, 100]) +def test_ignore_display_max_colwidth(method, expected, max_colwidth): + # see gh-17004 + df = DataFrame([lorem_ipsum]) + with option_context("display.max_colwidth", max_colwidth): + result = getattr(df, method)() + expected = expected(max_colwidth) + assert expected in result + + +@pytest.mark.parametrize("classes", [True, 0]) +def test_to_html_invalid_classes_type(classes): + # GH 25608 + df = DataFrame() + msg = "classes must be a string, list, or tuple" + + with pytest.raises(TypeError, match=msg): + df.to_html(classes=classes) + + +def test_to_html_round_column_headers(): + # GH 17280 + df = DataFrame([1], columns=[0.55555]) + with option_context("display.precision", 3): + html = df.to_html(notebook=False) + notebook = df.to_html(notebook=True) + assert "0.55555" in html + assert "0.556" in notebook + + +@pytest.mark.parametrize("unit", ["100px", "10%", "5em", 150]) +def test_to_html_with_col_space_units(unit): + # GH 25941 + df = DataFrame(np.random.default_rng(2).random(size=(1, 3))) + result = df.to_html(col_space=unit) + result = result.split("tbody")[0] + hdrs = [x for x in result.split("\n") if re.search(r"\s]", x)] + if isinstance(unit, int): + unit = str(unit) + "px" + for h in hdrs: + expected = f'' + assert expected in h + + +class TestReprHTML: + def test_html_repr_min_rows_default(self, datapath): + # gh-27991 + + # default setting no truncation even if above min_rows + df = DataFrame({"a": range(20)}) + result = df._repr_html_() + expected = expected_html(datapath, "html_repr_min_rows_default_no_truncation") + assert result == expected + + # default of max_rows 60 triggers truncation if above + df = DataFrame({"a": range(61)}) + result = df._repr_html_() + expected = expected_html(datapath, "html_repr_min_rows_default_truncated") + assert result == expected + + @pytest.mark.parametrize( + "max_rows,min_rows,expected", + [ + # truncated after first two rows + (10, 4, "html_repr_max_rows_10_min_rows_4"), + # when set to None, follow value of max_rows + (12, None, "html_repr_max_rows_12_min_rows_None"), + # when set value higher as max_rows, use the minimum + (10, 12, "html_repr_max_rows_10_min_rows_12"), + # max_rows of None -> never truncate + (None, 12, "html_repr_max_rows_None_min_rows_12"), + ], + ) + def test_html_repr_min_rows(self, datapath, max_rows, min_rows, expected): + # gh-27991 + + df = DataFrame({"a": range(61)}) + expected = expected_html(datapath, expected) + with option_context("display.max_rows", max_rows, "display.min_rows", min_rows): + result = df._repr_html_() + assert result == expected + + def test_repr_html_ipython_config(self, ip): + code = textwrap.dedent( + """\ + from pandas import DataFrame + df = DataFrame({"A": [1, 2]}) + df._repr_html_() + + cfg = get_ipython().config + cfg['IPKernelApp']['parent_appname'] + df._repr_html_() + """ + ) + result = ip.run_cell(code, silent=True) + assert not result.error_in_exec + + def test_info_repr_html(self): + max_rows = 60 + max_cols = 20 + # Long + h, w = max_rows + 1, max_cols - 1 + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) + assert r"<class" not in df._repr_html_() + with option_context("display.large_repr", "info"): + assert r"<class" in df._repr_html_() + + # Wide + h, w = max_rows - 1, max_cols + 1 + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) + assert "{40 + h}" in reg_repr + + h = max_rows + 1 + df = DataFrame( + { + "idx": np.linspace(-10, 10, h), + "A": np.arange(1, 1 + h), + "B": np.arange(41, 41 + h), + } + ).set_index("idx") + long_repr = df._repr_html_() + assert ".." in long_repr + assert "31" not in long_repr + assert f"{h} rows " in long_repr + assert "2 columns" in long_repr + + def test_repr_html_long_multiindex(self): + max_rows = 60 + max_L1 = max_rows // 2 + + tuples = list(itertools.product(np.arange(max_L1), ["foo", "bar"])) + idx = MultiIndex.from_tuples(tuples, names=["first", "second"]) + df = DataFrame( + np.random.default_rng(2).standard_normal((max_L1 * 2, 2)), + index=idx, + columns=["A", "B"], + ) + with option_context("display.max_rows", 60, "display.max_columns", 20): + reg_repr = df._repr_html_() + assert "..." not in reg_repr + + tuples = list(itertools.product(np.arange(max_L1 + 1), ["foo", "bar"])) + idx = MultiIndex.from_tuples(tuples, names=["first", "second"]) + df = DataFrame( + np.random.default_rng(2).standard_normal(((max_L1 + 1) * 2, 2)), + index=idx, + columns=["A", "B"], + ) + long_repr = df._repr_html_() + assert "..." in long_repr + + def test_repr_html_long_and_wide(self): + max_cols = 20 + max_rows = 60 + + h, w = max_rows - 1, max_cols - 1 + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) + with option_context("display.max_rows", 60, "display.max_columns", 20): + assert "..." not in df._repr_html_() + + h, w = max_rows + 1, max_cols + 1 + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) + with option_context("display.max_rows", 60, "display.max_columns", 20): + assert "..." in df._repr_html_() + + +def test_to_html_multilevel(multiindex_year_month_day_dataframe_random_data): + ymd = multiindex_year_month_day_dataframe_random_data + + ymd.columns.name = "foo" + ymd.to_html() + ymd.T.to_html() + + +@pytest.mark.parametrize("na_rep", ["NaN", "Ted"]) +def test_to_html_na_rep_and_float_format(na_rep, datapath): + # https://github.com/pandas-dev/pandas/issues/13828 + df = DataFrame( + [ + ["A", 1.2225], + ["A", None], + ], + columns=["Group", "Data"], + ) + result = df.to_html(na_rep=na_rep, float_format="{:.2f}".format) + expected = expected_html(datapath, "gh13828_expected_output") + expected = expected.format(na_rep=na_rep) + assert result == expected + + +def test_to_html_na_rep_non_scalar_data(datapath): + # GH47103 + df = DataFrame([{"a": 1, "b": [1, 2, 3]}]) + result = df.to_html(na_rep="-") + expected = expected_html(datapath, "gh47103_expected_output") + assert result == expected + + +def test_to_html_float_format_object_col(datapath): + # GH#40024 + df = DataFrame(data={"x": [1000.0, "test"]}) + result = df.to_html(float_format=lambda x: f"{x:,.0f}") + expected = expected_html(datapath, "gh40024_expected_output") + assert result == expected + + +def test_to_html_multiindex_col_with_colspace(): + # GH#53885 + df = DataFrame([[1, 2]]) + df.columns = MultiIndex.from_tuples([(1, 1), (2, 1)]) + result = df.to_html(col_space=100) + expected = ( + '\n' + " \n" + " \n" + ' \n' + ' \n' + ' \n' + " \n" + " \n" + ' \n' + ' \n' + ' \n' + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
12
11
012
" + ) + assert result == expected + + +def test_to_html_tuple_col_with_colspace(): + # GH#53885 + df = DataFrame({("a", "b"): [1], "b": [2]}) + result = df.to_html(col_space=100) + expected = ( + '\n' + " \n" + ' \n' + ' \n' + ' \n' + ' \n' + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
(a, b)b
012
" + ) + assert result == expected + + +def test_to_html_empty_complex_array(): + # GH#54167 + df = DataFrame({"x": np.array([], dtype="complex")}) + result = df.to_html(col_space=100) + expected = ( + '\n' + " \n" + ' \n' + ' \n' + ' \n' + " \n" + " \n" + " \n" + " \n" + "
x
" + ) + assert result == expected + + +def test_to_html_pos_args_deprecation(): + # GH-54229 + df = DataFrame({"a": [1, 2, 3]}) + msg = ( + r"Starting with pandas version 3.0 all arguments of to_html except for the " + r"argument 'buf' will be keyword-only." + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + df.to_html(None, None) diff --git a/shared/package-files/7a/7a5c767f196c8dfae5513abe3d5e7099aafba2a07e8d693db31d20a1f93e34b3/blob b/shared/package-files/7a/7a5c767f196c8dfae5513abe3d5e7099aafba2a07e8d693db31d20a1f93e34b3/blob new file mode 100644 index 0000000000000000000000000000000000000000..5b5b3479b95f2babc399afefe656e96520d9ac74 --- /dev/null +++ b/shared/package-files/7a/7a5c767f196c8dfae5513abe3d5e7099aafba2a07e8d693db31d20a1f93e34b3/blob @@ -0,0 +1,1311 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# * The names of the contributors may not be used to endorse or +# promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""So much practical programming involves string manipulation, which +Python readily accommodates. Still, there are dozens of basic and +common capabilities missing from the standard library, several of them +provided by ``strutils``. +""" + +from __future__ import print_function + +import re +import sys +import uuid +import zlib +import string +import unicodedata +import collections +from gzip import GzipFile + +try: + from cStringIO import cStringIO as StringIO +except ImportError: + from io import BytesIO as StringIO + +try: + from collections.abc import Mapping +except ImportError: + from collections import Mapping + +try: + unicode, str, bytes, basestring = unicode, str, str, basestring + from HTMLParser import HTMLParser + import htmlentitydefs +except NameError: # basestring not defined in Python 3 + unicode, str, bytes, basestring = str, bytes, bytes, (str, bytes) + unichr = chr + from html.parser import HTMLParser + from html import entities as htmlentitydefs + +try: + import __builtin__ as builtins +except ImportError: + import builtins + +__all__ = ['camel2under', 'under2camel', 'slugify', 'split_punct_ws', + 'unit_len', 'ordinalize', 'cardinalize', 'pluralize', 'singularize', + 'asciify', 'is_ascii', 'is_uuid', 'html2text', 'strip_ansi', + 'bytes2human', 'find_hashtags', 'a10n', 'gzip_bytes', 'gunzip_bytes', + 'iter_splitlines', 'indent', 'escape_shell_args', + 'args2cmd', 'args2sh', 'parse_int_list', 'format_int_list', + 'int_list_complement', 'int_list_to_int_tuples', 'MultiReplace', + 'multi_replace', 'unwrap_text'] + + +_punct_ws_str = string.punctuation + string.whitespace +_punct_re = re.compile('[' + _punct_ws_str + ']+') +_camel2under_re = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))') + + +def camel2under(camel_string): + """Converts a camelcased string to underscores. Useful for turning a + class name into a function name. + + >>> camel2under('BasicParseTest') + 'basic_parse_test' + """ + return _camel2under_re.sub(r'_\1', camel_string).lower() + + +def under2camel(under_string): + """Converts an underscored string to camelcased. Useful for turning a + function name into a class name. + + >>> under2camel('complex_tokenizer') + 'ComplexTokenizer' + """ + return ''.join(w.capitalize() or '_' for w in under_string.split('_')) + + +def slugify(text, delim='_', lower=True, ascii=False): + """ + A basic function that turns text full of scary characters + (i.e., punctuation and whitespace), into a relatively safe + lowercased string separated only by the delimiter specified + by *delim*, which defaults to ``_``. + + The *ascii* convenience flag will :func:`asciify` the slug if + you require ascii-only slugs. + + >>> slugify('First post! Hi!!!!~1 ') + 'first_post_hi_1' + + >>> slugify("Kurt Gödel's pretty cool.", ascii=True) == \ + b'kurt_goedel_s_pretty_cool' + True + + """ + ret = delim.join(split_punct_ws(text)) or delim if text else '' + if ascii: + ret = asciify(ret) + if lower: + ret = ret.lower() + return ret + + +def split_punct_ws(text): + """While :meth:`str.split` will split on whitespace, + :func:`split_punct_ws` will split on punctuation and + whitespace. This used internally by :func:`slugify`, above. + + >>> split_punct_ws('First post! Hi!!!!~1 ') + ['First', 'post', 'Hi', '1'] + """ + return [w for w in _punct_re.split(text) if w] + + +def unit_len(sized_iterable, unit_noun='item'): # TODO: len_units()/unitize()? + """Returns a plain-English description of an iterable's + :func:`len()`, conditionally pluralized with :func:`cardinalize`, + detailed below. + + >>> print(unit_len(range(10), 'number')) + 10 numbers + >>> print(unit_len('aeiou', 'vowel')) + 5 vowels + >>> print(unit_len([], 'worry')) + No worries + """ + count = len(sized_iterable) + units = cardinalize(unit_noun, count) + if count: + return u'%s %s' % (count, units) + return u'No %s' % (units,) + + +_ORDINAL_MAP = {'1': 'st', + '2': 'nd', + '3': 'rd'} # 'th' is the default + + +def ordinalize(number, ext_only=False): + """Turns *number* into its cardinal form, i.e., 1st, 2nd, + 3rd, 4th, etc. If the last character isn't a digit, it returns the + string value unchanged. + + Args: + number (int or str): Number to be cardinalized. + ext_only (bool): Whether to return only the suffix. Default ``False``. + + >>> print(ordinalize(1)) + 1st + >>> print(ordinalize(3694839230)) + 3694839230th + >>> print(ordinalize('hi')) + hi + >>> print(ordinalize(1515)) + 1515th + """ + numstr, ext = unicode(number), '' + if numstr and numstr[-1] in string.digits: + try: + # first check for teens + if numstr[-2] == '1': + ext = 'th' + else: + # all other cases + ext = _ORDINAL_MAP.get(numstr[-1], 'th') + except IndexError: + # single digit numbers (will reach here based on [-2] above) + ext = _ORDINAL_MAP.get(numstr[-1], 'th') + if ext_only: + return ext + else: + return numstr + ext + + +def cardinalize(unit_noun, count): + """Conditionally pluralizes a singular word *unit_noun* if + *count* is not one, preserving case when possible. + + >>> vowels = 'aeiou' + >>> print(len(vowels), cardinalize('vowel', len(vowels))) + 5 vowels + >>> print(3, cardinalize('Wish', 3)) + 3 Wishes + """ + if count == 1: + return unit_noun + return pluralize(unit_noun) + + +def singularize(word): + """Semi-intelligently converts an English plural *word* to its + singular form, preserving case pattern. + + >>> singularize('chances') + 'chance' + >>> singularize('Activities') + 'Activity' + >>> singularize('Glasses') + 'Glass' + >>> singularize('FEET') + 'FOOT' + + """ + orig_word, word = word, word.strip().lower() + if not word or word in _IRR_S2P: + return orig_word + + irr_singular = _IRR_P2S.get(word) + if irr_singular: + singular = irr_singular + elif not word.endswith('s'): + return orig_word + elif len(word) == 2: + singular = word[:-1] # or just return word? + elif word.endswith('ies') and word[-4:-3] not in 'aeiou': + singular = word[:-3] + 'y' + elif word.endswith('es') and word[-3] == 's': + singular = word[:-2] + else: + singular = word[:-1] + return _match_case(orig_word, singular) + + +def pluralize(word): + """Semi-intelligently converts an English *word* from singular form to + plural, preserving case pattern. + + >>> pluralize('friend') + 'friends' + >>> pluralize('enemy') + 'enemies' + >>> pluralize('Sheep') + 'Sheep' + """ + orig_word, word = word, word.strip().lower() + if not word or word in _IRR_P2S: + return orig_word + irr_plural = _IRR_S2P.get(word) + if irr_plural: + plural = irr_plural + elif word.endswith('y') and word[-2:-1] not in 'aeiou': + plural = word[:-1] + 'ies' + elif word[-1] == 's' or word.endswith('ch') or word.endswith('sh'): + plural = word if word.endswith('es') else word + 'es' + else: + plural = word + 's' + return _match_case(orig_word, plural) + + +def _match_case(master, disciple): + if not master.strip(): + return disciple + if master.lower() == master: + return disciple.lower() + elif master.upper() == master: + return disciple.upper() + elif master.title() == master: + return disciple.title() + return disciple + + +# Singular to plural map of irregular pluralizations +_IRR_S2P = {'addendum': 'addenda', 'alga': 'algae', 'alumna': 'alumnae', + 'alumnus': 'alumni', 'analysis': 'analyses', 'antenna': 'antennae', + 'appendix': 'appendices', 'axis': 'axes', 'bacillus': 'bacilli', + 'bacterium': 'bacteria', 'basis': 'bases', 'beau': 'beaux', + 'bison': 'bison', 'bureau': 'bureaus', 'cactus': 'cacti', + 'calf': 'calves', 'child': 'children', 'corps': 'corps', + 'corpus': 'corpora', 'crisis': 'crises', 'criterion': 'criteria', + 'curriculum': 'curricula', 'datum': 'data', 'deer': 'deer', + 'diagnosis': 'diagnoses', 'die': 'dice', 'dwarf': 'dwarves', + 'echo': 'echoes', 'elf': 'elves', 'ellipsis': 'ellipses', + 'embargo': 'embargoes', 'emphasis': 'emphases', 'erratum': 'errata', + 'fireman': 'firemen', 'fish': 'fish', 'focus': 'foci', + 'foot': 'feet', 'formula': 'formulae', 'formula': 'formulas', + 'fungus': 'fungi', 'genus': 'genera', 'goose': 'geese', + 'half': 'halves', 'hero': 'heroes', 'hippopotamus': 'hippopotami', + 'hoof': 'hooves', 'hypothesis': 'hypotheses', 'index': 'indices', + 'knife': 'knives', 'leaf': 'leaves', 'life': 'lives', + 'loaf': 'loaves', 'louse': 'lice', 'man': 'men', + 'matrix': 'matrices', 'means': 'means', 'medium': 'media', + 'memorandum': 'memoranda', 'millennium': 'milennia', 'moose': 'moose', + 'mosquito': 'mosquitoes', 'mouse': 'mice', 'nebula': 'nebulae', + 'neurosis': 'neuroses', 'nucleus': 'nuclei', 'oasis': 'oases', + 'octopus': 'octopi', 'offspring': 'offspring', 'ovum': 'ova', + 'ox': 'oxen', 'paralysis': 'paralyses', 'parenthesis': 'parentheses', + 'person': 'people', 'phenomenon': 'phenomena', 'potato': 'potatoes', + 'radius': 'radii', 'scarf': 'scarves', 'scissors': 'scissors', + 'self': 'selves', 'sense': 'senses', 'series': 'series', 'sheep': + 'sheep', 'shelf': 'shelves', 'species': 'species', 'stimulus': + 'stimuli', 'stratum': 'strata', 'syllabus': 'syllabi', 'symposium': + 'symposia', 'synopsis': 'synopses', 'synthesis': 'syntheses', + 'tableau': 'tableaux', 'that': 'those', 'thesis': 'theses', + 'thief': 'thieves', 'this': 'these', 'tomato': 'tomatoes', 'tooth': + 'teeth', 'torpedo': 'torpedoes', 'vertebra': 'vertebrae', 'veto': + 'vetoes', 'vita': 'vitae', 'watch': 'watches', 'wife': 'wives', + 'wolf': 'wolves', 'woman': 'women'} + + +# Reverse index of the above +_IRR_P2S = dict([(v, k) for k, v in _IRR_S2P.items()]) + +HASHTAG_RE = re.compile(r"(?:^|\s)[##]{1}(\w+)", re.UNICODE) + + +def find_hashtags(string): + """Finds and returns all hashtags in a string, with the hashmark + removed. Supports full-width hashmarks for Asian languages and + does not false-positive on URL anchors. + + >>> find_hashtags('#atag http://asite/#ananchor') + ['atag'] + + ``find_hashtags`` also works with unicode hashtags. + """ + + # the following works, doctest just struggles with it + # >>> find_hashtags(u"can't get enough of that dignity chicken #肯德基 woo") + # [u'\u80af\u5fb7\u57fa'] + return HASHTAG_RE.findall(string) + + +def a10n(string): + """That thing where "internationalization" becomes "i18n", what's it + called? Abbreviation? Oh wait, no: ``a10n``. (It's actually a form + of `numeronym`_.) + + >>> a10n('abbreviation') + 'a10n' + >>> a10n('internationalization') + 'i18n' + >>> a10n('') + '' + + .. _numeronym: http://en.wikipedia.org/wiki/Numeronym + """ + if len(string) < 3: + return string + return '%s%s%s' % (string[0], len(string[1:-1]), string[-1]) + + +# Based on https://en.wikipedia.org/wiki/ANSI_escape_code#Escape_sequences +ANSI_SEQUENCES = re.compile(r''' + \x1B # Sequence starts with ESC, i.e. hex 0x1B + (?: + [@-Z\\-_] # Second byte: + # all 0x40–0x5F range but CSI char, i.e ASCII @A–Z\]^_ + | # Or + \[ # CSI sequences, starting with [ + [0-?]* # Parameter bytes: + # range 0x30–0x3F, ASCII 0–9:;<=>? + [ -/]* # Intermediate bytes: + # range 0x20–0x2F, ASCII space and !"#$%&'()*+,-./ + [@-~] # Final byte + # range 0x40–0x7E, ASCII @A–Z[\]^_`a–z{|}~ + ) +''', re.VERBOSE) + + +def strip_ansi(text): + """Strips ANSI escape codes from *text*. Useful for the occasional + time when a log or redirected output accidentally captures console + color codes and the like. + + >>> strip_ansi('\x1b[0m\x1b[1;36mart\x1b[46;34m') + 'art' + + Supports unicode, str, bytes and bytearray content as input. Returns the + same type as the input. + + There's a lot of ANSI art available for testing on `sixteencolors.net`_. + This function does not interpret or render ANSI art, but you can do so with + `ansi2img`_ or `escapes.js`_. + + .. _sixteencolors.net: http://sixteencolors.net + .. _ansi2img: http://www.bedroomlan.org/projects/ansi2img + .. _escapes.js: https://github.com/atdt/escapes.js + """ + # TODO: move to cliutils.py + + # Transform any ASCII-like content to unicode to allow regex to match, and + # save input type for later. + target_type = None + # Unicode type aliased to str is code-smell for Boltons in Python 3 env. + is_py3 = (unicode == builtins.str) + if is_py3 and isinstance(text, (bytes, bytearray)): + target_type = type(text) + text = text.decode('utf-8') + + cleaned = ANSI_SEQUENCES.sub('', text) + + # Transform back the result to the same bytearray type provided by the user. + if target_type and target_type != type(cleaned): + cleaned = target_type(cleaned, 'utf-8') + + return cleaned + + +def asciify(text, ignore=False): + """Converts a unicode or bytestring, *text*, into a bytestring with + just ascii characters. Performs basic deaccenting for all you + Europhiles out there. + + Also, a gentle reminder that this is a **utility**, primarily meant + for slugification. Whenever possible, make your application work + **with** unicode, not against it. + + Args: + text (str or unicode): The string to be asciified. + ignore (bool): Configures final encoding to ignore remaining + unasciified unicode instead of replacing it. + + >>> asciify('Beyoncé') == b'Beyonce' + True + """ + try: + try: + return text.encode('ascii') + except UnicodeDecodeError: + # this usually means you passed in a non-unicode string + text = text.decode('utf-8') + return text.encode('ascii') + except UnicodeEncodeError: + mode = 'replace' + if ignore: + mode = 'ignore' + transd = unicodedata.normalize('NFKD', text.translate(DEACCENT_MAP)) + ret = transd.encode('ascii', mode) + return ret + + +def is_ascii(text): + """Check if a unicode or bytestring, *text*, is composed of ascii + characters only. Raises :exc:`ValueError` if argument is not text. + + Args: + text (str or unicode): The string to be checked. + + >>> is_ascii('Beyoncé') + False + >>> is_ascii('Beyonce') + True + """ + if isinstance(text, unicode): + try: + text.encode('ascii') + except UnicodeEncodeError: + return False + elif isinstance(text, bytes): + try: + text.decode('ascii') + except UnicodeDecodeError: + return False + else: + raise ValueError('expected text or bytes, not %r' % type(text)) + return True + + +class DeaccenterDict(dict): + "A small caching dictionary for deaccenting." + def __missing__(self, key): + ch = self.get(key) + if ch is not None: + return ch + try: + de = unicodedata.decomposition(unichr(key)) + p1, _, p2 = de.rpartition(' ') + if int(p2, 16) == 0x308: + ch = self.get(key) + else: + ch = int(p1, 16) + except (IndexError, ValueError): + ch = self.get(key, key) + self[key] = ch + return ch + + try: + from collections import defaultdict + except ImportError: + # no defaultdict means that __missing__ isn't supported in + # this version of python, so we define __getitem__ + def __getitem__(self, key): + try: + return super(DeaccenterDict, self).__getitem__(key) + except KeyError: + return self.__missing__(key) + else: + del defaultdict + + +# http://chmullig.com/2009/12/python-unicode-ascii-ifier/ +# For something more complete, investigate the unidecode +# or isounidecode packages, which are capable of performing +# crude transliteration. +_BASE_DEACCENT_MAP = { + 0xc6: u"AE", # Æ LATIN CAPITAL LETTER AE + 0xd0: u"D", # Ð LATIN CAPITAL LETTER ETH + 0xd8: u"OE", # Ø LATIN CAPITAL LETTER O WITH STROKE + 0xde: u"Th", # Þ LATIN CAPITAL LETTER THORN + 0xc4: u'Ae', # Ä LATIN CAPITAL LETTER A WITH DIAERESIS + 0xd6: u'Oe', # Ö LATIN CAPITAL LETTER O WITH DIAERESIS + 0xdc: u'Ue', # Ü LATIN CAPITAL LETTER U WITH DIAERESIS + 0xc0: u"A", # À LATIN CAPITAL LETTER A WITH GRAVE + 0xc1: u"A", # Á LATIN CAPITAL LETTER A WITH ACUTE + 0xc3: u"A", # Ã LATIN CAPITAL LETTER A WITH TILDE + 0xc7: u"C", # Ç LATIN CAPITAL LETTER C WITH CEDILLA + 0xc8: u"E", # È LATIN CAPITAL LETTER E WITH GRAVE + 0xc9: u"E", # É LATIN CAPITAL LETTER E WITH ACUTE + 0xca: u"E", # Ê LATIN CAPITAL LETTER E WITH CIRCUMFLEX + 0xcc: u"I", # Ì LATIN CAPITAL LETTER I WITH GRAVE + 0xcd: u"I", # Í LATIN CAPITAL LETTER I WITH ACUTE + 0xd2: u"O", # Ò LATIN CAPITAL LETTER O WITH GRAVE + 0xd3: u"O", # Ó LATIN CAPITAL LETTER O WITH ACUTE + 0xd5: u"O", # Õ LATIN CAPITAL LETTER O WITH TILDE + 0xd9: u"U", # Ù LATIN CAPITAL LETTER U WITH GRAVE + 0xda: u"U", # Ú LATIN CAPITAL LETTER U WITH ACUTE + 0xdf: u"ss", # ß LATIN SMALL LETTER SHARP S + 0xe6: u"ae", # æ LATIN SMALL LETTER AE + 0xf0: u"d", # ð LATIN SMALL LETTER ETH + 0xf8: u"oe", # ø LATIN SMALL LETTER O WITH STROKE + 0xfe: u"th", # þ LATIN SMALL LETTER THORN, + 0xe4: u'ae', # ä LATIN SMALL LETTER A WITH DIAERESIS + 0xf6: u'oe', # ö LATIN SMALL LETTER O WITH DIAERESIS + 0xfc: u'ue', # ü LATIN SMALL LETTER U WITH DIAERESIS + 0xe0: u"a", # à LATIN SMALL LETTER A WITH GRAVE + 0xe1: u"a", # á LATIN SMALL LETTER A WITH ACUTE + 0xe3: u"a", # ã LATIN SMALL LETTER A WITH TILDE + 0xe7: u"c", # ç LATIN SMALL LETTER C WITH CEDILLA + 0xe8: u"e", # è LATIN SMALL LETTER E WITH GRAVE + 0xe9: u"e", # é LATIN SMALL LETTER E WITH ACUTE + 0xea: u"e", # ê LATIN SMALL LETTER E WITH CIRCUMFLEX + 0xec: u"i", # ì LATIN SMALL LETTER I WITH GRAVE + 0xed: u"i", # í LATIN SMALL LETTER I WITH ACUTE + 0xf2: u"o", # ò LATIN SMALL LETTER O WITH GRAVE + 0xf3: u"o", # ó LATIN SMALL LETTER O WITH ACUTE + 0xf5: u"o", # õ LATIN SMALL LETTER O WITH TILDE + 0xf9: u"u", # ù LATIN SMALL LETTER U WITH GRAVE + 0xfa: u"u", # ú LATIN SMALL LETTER U WITH ACUTE + 0x2018: u"'", # ‘ LEFT SINGLE QUOTATION MARK + 0x2019: u"'", # ’ RIGHT SINGLE QUOTATION MARK + 0x201c: u'"', # “ LEFT DOUBLE QUOTATION MARK + 0x201d: u'"', # ” RIGHT DOUBLE QUOTATION MARK + } + + +DEACCENT_MAP = DeaccenterDict(_BASE_DEACCENT_MAP) + + +_SIZE_SYMBOLS = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') +_SIZE_BOUNDS = [(1024 ** i, sym) for i, sym in enumerate(_SIZE_SYMBOLS)] +_SIZE_RANGES = list(zip(_SIZE_BOUNDS, _SIZE_BOUNDS[1:])) + + +def bytes2human(nbytes, ndigits=0): + """Turns an integer value of *nbytes* into a human readable format. Set + *ndigits* to control how many digits after the decimal point + should be shown (default ``0``). + + >>> bytes2human(128991) + '126K' + >>> bytes2human(100001221) + '95M' + >>> bytes2human(0, 2) + '0.00B' + """ + abs_bytes = abs(nbytes) + for (size, symbol), (next_size, next_symbol) in _SIZE_RANGES: + if abs_bytes <= next_size: + break + hnbytes = float(nbytes) / size + return '{hnbytes:.{ndigits}f}{symbol}'.format(hnbytes=hnbytes, + ndigits=ndigits, + symbol=symbol) + + +class HTMLTextExtractor(HTMLParser): + def __init__(self): + self.reset() + self.strict = False + self.convert_charrefs = True + self.result = [] + + def handle_data(self, d): + self.result.append(d) + + def handle_charref(self, number): + if number[0] == u'x' or number[0] == u'X': + codepoint = int(number[1:], 16) + else: + codepoint = int(number) + self.result.append(unichr(codepoint)) + + def handle_entityref(self, name): + try: + codepoint = htmlentitydefs.name2codepoint[name] + except KeyError: + self.result.append(u'&' + name + u';') + else: + self.result.append(unichr(codepoint)) + + def get_text(self): + return u''.join(self.result) + + +def html2text(html): + """Strips tags from HTML text, returning markup-free text. Also, does + a best effort replacement of entities like " " + + >>> r = html2text(u'Test &(\u0394ημώ)') + >>> r == u'Test &(\u0394\u03b7\u03bc\u03ce)' + True + """ + # based on answers to http://stackoverflow.com/questions/753052/ + s = HTMLTextExtractor() + s.feed(html) + return s.get_text() + + +_EMPTY_GZIP_BYTES = b'\x1f\x8b\x08\x089\xf3\xb9U\x00\x03empty\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00' +_NON_EMPTY_GZIP_BYTES = b'\x1f\x8b\x08\x08\xbc\xf7\xb9U\x00\x03not_empty\x00K\xaa,I-N\xcc\xc8\xafT\xe4\x02\x00\xf3nb\xbf\x0b\x00\x00\x00' + + +def gunzip_bytes(bytestring): + """The :mod:`gzip` module is great if you have a file or file-like + object, but what if you just have bytes. StringIO is one + possibility, but it's often faster, easier, and simpler to just + use this one-liner. Use this tried-and-true utility function to + decompress gzip from bytes. + + >>> gunzip_bytes(_EMPTY_GZIP_BYTES) == b'' + True + >>> gunzip_bytes(_NON_EMPTY_GZIP_BYTES).rstrip() == b'bytesahoy!' + True + """ + return zlib.decompress(bytestring, 16 + zlib.MAX_WBITS) + + +def gzip_bytes(bytestring, level=6): + """Turn some bytes into some compressed bytes. + + >>> len(gzip_bytes(b'a' * 10000)) + 46 + + Args: + bytestring (bytes): Bytes to be compressed + level (int): An integer, 1-9, controlling the + speed/compression. 1 is fastest, least compressed, 9 is + slowest, but most compressed. + + Note that all levels of gzip are pretty fast these days, though + it's not really a competitor in compression, at any level. + """ + out = StringIO() + f = GzipFile(fileobj=out, mode='wb', compresslevel=level) + f.write(bytestring) + f.close() + return out.getvalue() + + + +_line_ending_re = re.compile(r'(\r\n|\n|\x0b|\f|\r|\x85|\x2028|\x2029)', + re.UNICODE) + + +def iter_splitlines(text): + r"""Like :meth:`str.splitlines`, but returns an iterator of lines + instead of a list. Also similar to :meth:`file.next`, as that also + lazily reads and yields lines from a file. + + This function works with a variety of line endings, but as always, + be careful when mixing line endings within a file. + + >>> list(iter_splitlines('\nhi\nbye\n')) + ['', 'hi', 'bye', ''] + >>> list(iter_splitlines('\r\nhi\rbye\r\n')) + ['', 'hi', 'bye', ''] + >>> list(iter_splitlines('')) + [] + """ + prev_end, len_text = 0, len(text) + # print('last: %r' % last_idx) + # start, end = None, None + for match in _line_ending_re.finditer(text): + start, end = match.start(1), match.end(1) + # print(start, end) + if prev_end <= start: + yield text[prev_end:start] + if end == len_text: + yield '' + prev_end = end + tail = text[prev_end:] + if tail: + yield tail + return + + +def indent(text, margin, newline='\n', key=bool): + """The missing counterpart to the built-in :func:`textwrap.dedent`. + + Args: + text (str): The text to indent. + margin (str): The string to prepend to each line. + newline (str): The newline used to rejoin the lines (default: ``\\n``) + key (callable): Called on each line to determine whether to + indent it. Default: :class:`bool`, to ensure that empty lines do + not get whitespace added. + """ + indented_lines = [(margin + line if key(line) else line) + for line in iter_splitlines(text)] + return newline.join(indented_lines) + + +def is_uuid(obj, version=4): + """Check the argument is either a valid UUID object or string. + + Args: + obj (object): The test target. Strings and UUID objects supported. + version (int): The target UUID version, set to 0 to skip version check. + + >>> is_uuid('e682ccca-5a4c-4ef2-9711-73f9ad1e15ea') + True + >>> is_uuid('0221f0d9-d4b9-11e5-a478-10ddb1c2feb9') + False + >>> is_uuid('0221f0d9-d4b9-11e5-a478-10ddb1c2feb9', version=1) + True + """ + if not isinstance(obj, uuid.UUID): + try: + obj = uuid.UUID(obj) + except (TypeError, ValueError, AttributeError): + return False + if version and obj.version != int(version): + return False + return True + + +def escape_shell_args(args, sep=' ', style=None): + """Returns an escaped version of each string in *args*, according to + *style*. + + Args: + args (list): A list of arguments to escape and join together + sep (str): The separator used to join the escaped arguments. + style (str): The style of escaping to use. Can be one of + ``cmd`` or ``sh``, geared toward Windows and Linux/BSD/etc., + respectively. If *style* is ``None``, then it is picked + according to the system platform. + + See :func:`args2cmd` and :func:`args2sh` for details and example + output for each style. + """ + if not style: + style = 'cmd' if sys.platform == 'win32' else 'sh' + + if style == 'sh': + return args2sh(args, sep=sep) + elif style == 'cmd': + return args2cmd(args, sep=sep) + + raise ValueError("style expected one of 'cmd' or 'sh', not %r" % style) + + +_find_sh_unsafe = re.compile(r'[^a-zA-Z0-9_@%+=:,./-]').search + + +def args2sh(args, sep=' '): + """Return a shell-escaped string version of *args*, separated by + *sep*, based on the rules of sh, bash, and other shells in the + Linux/BSD/MacOS ecosystem. + + >>> print(args2sh(['aa', '[bb]', "cc'cc", 'dd"dd'])) + aa '[bb]' 'cc'"'"'cc' 'dd"dd' + + As you can see, arguments with no special characters are not + escaped, arguments with special characters are quoted with single + quotes, and single quotes themselves are quoted with double + quotes. Double quotes are handled like any other special + character. + + Based on code from the :mod:`pipes`/:mod:`shlex` modules. Also + note that :mod:`shlex` and :mod:`argparse` have functions to split + and parse strings escaped in this manner. + """ + ret_list = [] + + for arg in args: + if not arg: + ret_list.append("''") + continue + if _find_sh_unsafe(arg) is None: + ret_list.append(arg) + continue + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + ret_list.append("'" + arg.replace("'", "'\"'\"'") + "'") + + return ' '.join(ret_list) + + +def args2cmd(args, sep=' '): + r"""Return a shell-escaped string version of *args*, separated by + *sep*, using the same rules as the Microsoft C runtime. + + >>> print(args2cmd(['aa', '[bb]', "cc'cc", 'dd"dd'])) + aa [bb] cc'cc dd\"dd + + As you can see, escaping is through backslashing and not quoting, + and double quotes are the only special character. See the comment + in the code for more details. Based on internal code from the + :mod:`subprocess` module. + + """ + # technique description from subprocess below + """ + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + + See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx + or search http://msdn.microsoft.com for + "Parsing C++ Command-Line Arguments" + """ + result = [] + needquote = False + for arg in args: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +def parse_int_list(range_string, delim=',', range_delim='-'): + """Returns a sorted list of positive integers based on + *range_string*. Reverse of :func:`format_int_list`. + + Args: + range_string (str): String of comma separated positive + integers or ranges (e.g. '1,2,4-6,8'). Typical of a custom + page range string used in printer dialogs. + delim (char): Defaults to ','. Separates integers and + contiguous ranges of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous + range of integers. + + >>> parse_int_list('1,3,5-8,10-11,15') + [1, 3, 5, 6, 7, 8, 10, 11, 15] + + """ + output = [] + + for x in range_string.strip().split(delim): + + # Range + if range_delim in x: + range_limits = list(map(int, x.split(range_delim))) + output += list(range(min(range_limits), max(range_limits)+1)) + + # Empty String + elif not x: + continue + + # Integer + else: + output.append(int(x)) + + return sorted(output) + + +def format_int_list(int_list, delim=',', range_delim='-', delim_space=False): + """Returns a sorted range string from a list of positive integers + (*int_list*). Contiguous ranges of integers are collapsed to min + and max values. Reverse of :func:`parse_int_list`. + + Args: + int_list (list): List of positive integers to be converted + into a range string (e.g. [1,2,4,5,6,8]). + delim (char): Defaults to ','. Separates integers and + contiguous ranges of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous + range of integers. + delim_space (bool): Defaults to ``False``. If ``True``, adds a + space after all *delim* characters. + + >>> format_int_list([1,3,5,6,7,8,10,11,15]) + '1,3,5-8,10-11,15' + + """ + output = [] + contig_range = collections.deque() + + for x in sorted(int_list): + + # Handle current (and first) value. + if len(contig_range) < 1: + contig_range.append(x) + + # Handle current value, given multiple previous values are contiguous. + elif len(contig_range) > 1: + delta = x - contig_range[-1] + + # Current value is contiguous. + if delta == 1: + contig_range.append(x) + + # Current value is non-contiguous. + elif delta > 1: + range_substr = '{0:d}{1}{2:d}'.format(min(contig_range), + range_delim, + max(contig_range)) + output.append(range_substr) + contig_range.clear() + contig_range.append(x) + + # Current value repeated. + else: + continue + + # Handle current value, given no previous contiguous integers + else: + delta = x - contig_range[0] + + # Current value is contiguous. + if delta == 1: + contig_range.append(x) + + # Current value is non-contiguous. + elif delta > 1: + output.append('{0:d}'.format(contig_range.popleft())) + contig_range.append(x) + + # Current value repeated. + else: + continue + + # Handle the last value. + else: + + # Last value is non-contiguous. + if len(contig_range) == 1: + output.append('{0:d}'.format(contig_range.popleft())) + contig_range.clear() + + # Last value is part of contiguous range. + elif len(contig_range) > 1: + range_substr = '{0:d}{1}{2:d}'.format(min(contig_range), + range_delim, + max(contig_range)) + output.append(range_substr) + contig_range.clear() + + if delim_space: + output_str = (delim+' ').join(output) + else: + output_str = delim.join(output) + + return output_str + + +def complement_int_list( + range_string, range_start=0, range_end=None, + delim=',', range_delim='-'): + """ Returns range string that is the complement of the one provided as + *range_string* parameter. + + These range strings are of the kind produce by :func:`format_int_list`, and + parseable by :func:`parse_int_list`. + + Args: + range_string (str): String of comma separated positive integers or + ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string + used in printer dialogs. + range_start (int): A positive integer from which to start the resulting + range. Value is inclusive. Defaults to ``0``. + range_end (int): A positive integer from which the produced range is + stopped. Value is exclusive. Defaults to the maximum value found in + the provided ``range_string``. + delim (char): Defaults to ','. Separates integers and contiguous ranges + of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous range of + integers. + + >>> complement_int_list('1,3,5-8,10-11,15') + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=0) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=1) + '2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=2) + '2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=3) + '4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=15) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=14) + '0,2,4,9,12-13' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=13) + '0,2,4,9,12' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=20) + '0,2,4,9,12-14,16-19' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=0) + '' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=-1) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=-1) + '' + + >>> complement_int_list('1,3,5-8', range_start=1, range_end=1) + '' + + >>> complement_int_list('1,3,5-8', range_start=2, range_end=2) + '' + + >>> complement_int_list('1,3,5-8', range_start=2, range_end=3) + '2' + + >>> complement_int_list('1,3,5-8', range_start=-10, range_end=-5) + '' + + >>> complement_int_list('1,3,5-8', range_start=20, range_end=10) + '' + + >>> complement_int_list('') + '' + """ + int_list = set(parse_int_list(range_string, delim, range_delim)) + if range_end is None: + if int_list: + range_end = max(int_list) + 1 + else: + range_end = range_start + complement_values = set( + range(range_end)) - int_list - set(range(range_start)) + return format_int_list(complement_values, delim, range_delim) + + +def int_ranges_from_int_list(range_string, delim=',', range_delim='-'): + """ Transform a string of ranges (*range_string*) into a tuple of tuples. + + Args: + range_string (str): String of comma separated positive integers or + ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string + used in printer dialogs. + delim (char): Defaults to ','. Separates integers and contiguous ranges + of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous range of + integers. + + >>> int_ranges_from_int_list('1,3,5-8,10-11,15') + ((1, 1), (3, 3), (5, 8), (10, 11), (15, 15)) + + >>> int_ranges_from_int_list('1') + ((1, 1),) + + >>> int_ranges_from_int_list('') + () + """ + int_tuples = [] + # Normalize the range string to our internal format for processing. + range_string = format_int_list( + parse_int_list(range_string, delim, range_delim)) + if range_string: + for bounds in range_string.split(','): + if '-' in bounds: + start, end = bounds.split('-') + else: + start, end = bounds, bounds + int_tuples.append((int(start), int(end))) + return tuple(int_tuples) + + +class MultiReplace(object): + """ + MultiReplace is a tool for doing multiple find/replace actions in one pass. + + Given a mapping of values to be replaced it allows for all of the matching + values to be replaced in a single pass which can save a lot of performance + on very large strings. In addition to simple replace, it also allows for + replacing based on regular expressions. + + Keyword Arguments: + + :type regex: bool + :param regex: Treat search keys as regular expressions [Default: False] + :type flags: int + :param flags: flags to pass to the regex engine during compile + + Dictionary Usage:: + + from boltons import stringutils + s = stringutils.MultiReplace({ + 'foo': 'zoo', + 'cat': 'hat', + 'bat': 'kraken' + }) + new = s.sub('The foo bar cat ate a bat') + new == 'The zoo bar hat ate a kraken' + + Iterable Usage:: + + from boltons import stringutils + s = stringutils.MultiReplace([ + ('foo', 'zoo'), + ('cat', 'hat'), + ('bat', 'kraken)' + ]) + new = s.sub('The foo bar cat ate a bat') + new == 'The zoo bar hat ate a kraken' + + + The constructor can be passed a dictionary or other mapping as well as + an iterable of tuples. If given an iterable, the substitution will be run + in the order the replacement values are specified in the iterable. This is + also true if it is given an OrderedDict. If given a dictionary then the + order will be non-deterministic:: + + >>> 'foo bar baz'.replace('foo', 'baz').replace('baz', 'bar') + 'bar bar bar' + >>> m = MultiReplace({'foo': 'baz', 'baz': 'bar'}) + >>> m.sub('foo bar baz') + 'baz bar bar' + + This is because the order of replacement can matter if you're inserting + something that might be replaced by a later substitution. Pay attention and + if you need to rely on order then consider using a list of tuples instead + of a dictionary. + """ + + def __init__(self, sub_map, **kwargs): + """Compile any regular expressions that have been passed.""" + options = { + 'regex': False, + 'flags': 0, + } + options.update(kwargs) + self.group_map = {} + regex_values = [] + + if isinstance(sub_map, Mapping): + sub_map = sub_map.items() + + for idx, vals in enumerate(sub_map): + group_name = 'group{0}'.format(idx) + if isinstance(vals[0], basestring): + # If we're not treating input strings like a regex, escape it + if not options['regex']: + exp = re.escape(vals[0]) + else: + exp = vals[0] + else: + exp = vals[0].pattern + + regex_values.append('(?P<{}>{})'.format(group_name, exp)) + self.group_map[group_name] = vals[1] + + self.combined_pattern = re.compile( + '|'.join(regex_values), + flags=options['flags'] + ) + + def _get_value(self, match): + """Given a match object find replacement value.""" + group_dict = match.groupdict() + key = [x for x in group_dict if group_dict[x]][0] + return self.group_map[key] + + def sub(self, text): + """ + Run substitutions on the input text. + + Given an input string, run all substitutions given in the + constructor. + """ + return self.combined_pattern.sub(self._get_value, text) + + +def multi_replace(text, sub_map, **kwargs): + """ + Shortcut function to invoke MultiReplace in a single call. + + Example Usage:: + + from boltons.stringutils import multi_replace + new = multi_replace( + 'The foo bar cat ate a bat', + {'foo': 'zoo', 'cat': 'hat', 'bat': 'kraken'} + ) + new == 'The zoo bar hat ate a kraken' + """ + m = MultiReplace(sub_map, **kwargs) + return m.sub(text) + + +def unwrap_text(text, ending='\n\n'): + r""" + Unwrap text, the natural complement to :func:`textwrap.wrap`. + + >>> text = "Short \n lines \nwrapped\nsmall.\n\nAnother\nparagraph." + >>> unwrap_text(text) + 'Short lines wrapped small.\n\nAnother paragraph.' + + Args: + text: A string to unwrap. + ending (str): The string to join all unwrapped paragraphs + by. Pass ``None`` to get the list. Defaults to '\n\n' for + compatibility with Markdown and RST. + + """ + all_grafs = [] + cur_graf = [] + for line in text.splitlines(): + line = line.strip() + if line: + cur_graf.append(line) + else: + all_grafs.append(' '.join(cur_graf)) + cur_graf = [] + if cur_graf: + all_grafs.append(' '.join(cur_graf)) + if ending is None: + return all_grafs + return ending.join(all_grafs) diff --git a/shared/package-files/7a/7a5e5c0048284c4a5140deb9b4ec4684496e7be09c70cbf4c6897e27633039cd/blob b/shared/package-files/7a/7a5e5c0048284c4a5140deb9b4ec4684496e7be09c70cbf4c6897e27633039cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..2479b6f7ba723b933978d10a6f80e28f60c3c1c6 --- /dev/null +++ b/shared/package-files/7a/7a5e5c0048284c4a5140deb9b4ec4684496e7be09c70cbf4c6897e27633039cd/blob @@ -0,0 +1,451 @@ +# ######################### LICENSE ############################ # + +# Copyright (c) 2005-2021, Michele Simionato +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: + +# Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# Redistributions in bytecode form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. + +""" +Decorator module, see +https://github.com/micheles/decorator/blob/master/docs/documentation.md +for the documentation. +""" +import re +import sys +import inspect +import operator +import itertools +from contextlib import _GeneratorContextManager +from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction + +__version__ = '5.1.1' + +DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(') +POS = inspect.Parameter.POSITIONAL_OR_KEYWORD +EMPTY = inspect.Parameter.empty + + +# this is not used anymore in the core, but kept for backward compatibility +class FunctionMaker(object): + """ + An object with the ability to create functions with a given signature. + It has attributes name, doc, module, signature, defaults, dict and + methods update and make. + """ + + # Atomic get-and-increment provided by the GIL + _compile_count = itertools.count() + + # make pylint happy + args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = () + + def __init__(self, func=None, name=None, signature=None, + defaults=None, doc=None, module=None, funcdict=None): + self.shortsignature = signature + if func: + # func can be a class or a callable, but not an instance method + self.name = func.__name__ + if self.name == '': # small hack for lambda functions + self.name = '_lambda_' + self.doc = func.__doc__ + self.module = func.__module__ + if inspect.isroutine(func): + argspec = getfullargspec(func) + self.annotations = getattr(func, '__annotations__', {}) + for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', + 'kwonlydefaults'): + setattr(self, a, getattr(argspec, a)) + for i, arg in enumerate(self.args): + setattr(self, 'arg%d' % i, arg) + allargs = list(self.args) + allshortargs = list(self.args) + if self.varargs: + allargs.append('*' + self.varargs) + allshortargs.append('*' + self.varargs) + elif self.kwonlyargs: + allargs.append('*') # single star syntax + for a in self.kwonlyargs: + allargs.append('%s=None' % a) + allshortargs.append('%s=%s' % (a, a)) + if self.varkw: + allargs.append('**' + self.varkw) + allshortargs.append('**' + self.varkw) + self.signature = ', '.join(allargs) + self.shortsignature = ', '.join(allshortargs) + self.dict = func.__dict__.copy() + # func=None happens when decorating a caller + if name: + self.name = name + if signature is not None: + self.signature = signature + if defaults: + self.defaults = defaults + if doc: + self.doc = doc + if module: + self.module = module + if funcdict: + self.dict = funcdict + # check existence required attributes + assert hasattr(self, 'name') + if not hasattr(self, 'signature'): + raise TypeError('You are decorating a non function: %s' % func) + + def update(self, func, **kw): + """ + Update the signature of func with the data in self + """ + func.__name__ = self.name + func.__doc__ = getattr(self, 'doc', None) + func.__dict__ = getattr(self, 'dict', {}) + func.__defaults__ = self.defaults + func.__kwdefaults__ = self.kwonlydefaults or None + func.__annotations__ = getattr(self, 'annotations', None) + try: + frame = sys._getframe(3) + except AttributeError: # for IronPython and similar implementations + callermodule = '?' + else: + callermodule = frame.f_globals.get('__name__', '?') + func.__module__ = getattr(self, 'module', callermodule) + func.__dict__.update(kw) + + def make(self, src_templ, evaldict=None, addsource=False, **attrs): + """ + Make a new function from a given template and update the signature + """ + src = src_templ % vars(self) # expand name and signature + evaldict = evaldict or {} + mo = DEF.search(src) + if mo is None: + raise SyntaxError('not a valid function template\n%s' % src) + name = mo.group(1) # extract the function name + names = set([name] + [arg.strip(' *') for arg in + self.shortsignature.split(',')]) + for n in names: + if n in ('_func_', '_call_'): + raise NameError('%s is overridden in\n%s' % (n, src)) + + if not src.endswith('\n'): # add a newline for old Pythons + src += '\n' + + # Ensure each generated function has a unique filename for profilers + # (such as cProfile) that depend on the tuple of (, + # , ) being unique. + filename = '' % next(self._compile_count) + try: + code = compile(src, filename, 'single') + exec(code, evaldict) + except Exception: + print('Error in generated code:', file=sys.stderr) + print(src, file=sys.stderr) + raise + func = evaldict[name] + if addsource: + attrs['__source__'] = src + self.update(func, **attrs) + return func + + @classmethod + def create(cls, obj, body, evaldict, defaults=None, + doc=None, module=None, addsource=True, **attrs): + """ + Create a function from the strings name, signature and body. + evaldict is the evaluation dictionary. If addsource is true an + attribute __source__ is added to the result. The attributes attrs + are added, if any. + """ + if isinstance(obj, str): # "name(signature)" + name, rest = obj.strip().split('(', 1) + signature = rest[:-1] # strip a right parens + func = None + else: # a function + name = None + signature = None + func = obj + self = cls(func, name, signature, defaults, doc, module) + ibody = '\n'.join(' ' + line for line in body.splitlines()) + caller = evaldict.get('_call_') # when called from `decorate` + if caller and iscoroutinefunction(caller): + body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( + 'return', 'return await') + else: + body = 'def %(name)s(%(signature)s):\n' + ibody + return self.make(body, evaldict, addsource, **attrs) + + +def fix(args, kwargs, sig): + """ + Fix args and kwargs to be consistent with the signature + """ + ba = sig.bind(*args, **kwargs) + ba.apply_defaults() # needed for test_dan_schult + return ba.args, ba.kwargs + + +def decorate(func, caller, extras=(), kwsyntax=False): + """ + Decorates a function/generator/coroutine using a caller. + If kwsyntax is True calling the decorated functions with keyword + syntax will pass the named arguments inside the ``kw`` dictionary, + even if such argument are positional, similarly to what functools.wraps + does. By default kwsyntax is False and the the arguments are untouched. + """ + sig = inspect.signature(func) + if iscoroutinefunction(caller): + async def fun(*args, **kw): + if not kwsyntax: + args, kw = fix(args, kw, sig) + return await caller(func, *(extras + args), **kw) + elif isgeneratorfunction(caller): + def fun(*args, **kw): + if not kwsyntax: + args, kw = fix(args, kw, sig) + for res in caller(func, *(extras + args), **kw): + yield res + else: + def fun(*args, **kw): + if not kwsyntax: + args, kw = fix(args, kw, sig) + return caller(func, *(extras + args), **kw) + fun.__name__ = func.__name__ + fun.__doc__ = func.__doc__ + fun.__wrapped__ = func + fun.__signature__ = sig + fun.__qualname__ = func.__qualname__ + # builtin functions like defaultdict.__setitem__ lack many attributes + try: + fun.__defaults__ = func.__defaults__ + except AttributeError: + pass + try: + fun.__kwdefaults__ = func.__kwdefaults__ + except AttributeError: + pass + try: + fun.__annotations__ = func.__annotations__ + except AttributeError: + pass + try: + fun.__module__ = func.__module__ + except AttributeError: + pass + try: + fun.__dict__.update(func.__dict__) + except AttributeError: + pass + return fun + + +def decoratorx(caller): + """ + A version of "decorator" implemented via "exec" and not via the + Signature object. Use this if you are want to preserve the `.__code__` + object properties (https://github.com/micheles/decorator/issues/129). + """ + def dec(func): + return FunctionMaker.create( + func, + "return _call_(_func_, %(shortsignature)s)", + dict(_call_=caller, _func_=func), + __wrapped__=func, __qualname__=func.__qualname__) + return dec + + +def decorator(caller, _func=None, kwsyntax=False): + """ + decorator(caller) converts a caller function into a decorator + """ + if _func is not None: # return a decorated function + # this is obsolete behavior; you should use decorate instead + return decorate(_func, caller, (), kwsyntax) + # else return a decorator function + sig = inspect.signature(caller) + dec_params = [p for p in sig.parameters.values() if p.kind is POS] + + def dec(func=None, *args, **kw): + na = len(args) + 1 + extras = args + tuple(kw.get(p.name, p.default) + for p in dec_params[na:] + if p.default is not EMPTY) + if func is None: + return lambda func: decorate(func, caller, extras, kwsyntax) + else: + return decorate(func, caller, extras, kwsyntax) + dec.__signature__ = sig.replace(parameters=dec_params) + dec.__name__ = caller.__name__ + dec.__doc__ = caller.__doc__ + dec.__wrapped__ = caller + dec.__qualname__ = caller.__qualname__ + dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None) + dec.__dict__.update(caller.__dict__) + return dec + + +# ####################### contextmanager ####################### # + + +class ContextManager(_GeneratorContextManager): + def __init__(self, g, *a, **k): + _GeneratorContextManager.__init__(self, g, a, k) + + def __call__(self, func): + def caller(f, *a, **k): + with self.__class__(self.func, *self.args, **self.kwds): + return f(*a, **k) + return decorate(func, caller) + + +_contextmanager = decorator(ContextManager) + + +def contextmanager(func): + # Enable Pylint config: contextmanager-decorators=decorator.contextmanager + return _contextmanager(func) + + +# ############################ dispatch_on ############################ # + +def append(a, vancestors): + """ + Append ``a`` to the list of the virtual ancestors, unless it is already + included. + """ + add = True + for j, va in enumerate(vancestors): + if issubclass(va, a): + add = False + break + if issubclass(a, va): + vancestors[j] = a + add = False + if add: + vancestors.append(a) + + +# inspired from simplegeneric by P.J. Eby and functools.singledispatch +def dispatch_on(*dispatch_args): + """ + Factory of decorators turning a function into a generic function + dispatching on the given arguments. + """ + assert dispatch_args, 'No dispatch args passed' + dispatch_str = '(%s,)' % ', '.join(dispatch_args) + + def check(arguments, wrong=operator.ne, msg=''): + """Make sure one passes the expected number of arguments""" + if wrong(len(arguments), len(dispatch_args)): + raise TypeError('Expected %d arguments, got %d%s' % + (len(dispatch_args), len(arguments), msg)) + + def gen_func_dec(func): + """Decorator turning a function into a generic function""" + + # first check the dispatch arguments + argset = set(getfullargspec(func).args) + if not set(dispatch_args) <= argset: + raise NameError('Unknown dispatch arguments %s' % dispatch_str) + + typemap = {} + + def vancestors(*types): + """ + Get a list of sets of virtual ancestors for the given types + """ + check(types) + ras = [[] for _ in range(len(dispatch_args))] + for types_ in typemap: + for t, type_, ra in zip(types, types_, ras): + if issubclass(t, type_) and type_ not in t.mro(): + append(type_, ra) + return [set(ra) for ra in ras] + + def ancestors(*types): + """ + Get a list of virtual MROs, one for each type + """ + check(types) + lists = [] + for t, vas in zip(types, vancestors(*types)): + n_vas = len(vas) + if n_vas > 1: + raise RuntimeError( + 'Ambiguous dispatch for %s: %s' % (t, vas)) + elif n_vas == 1: + va, = vas + mro = type('t', (t, va), {}).mro()[1:] + else: + mro = t.mro() + lists.append(mro[:-1]) # discard t and object + return lists + + def register(*types): + """ + Decorator to register an implementation for the given types + """ + check(types) + + def dec(f): + check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) + typemap[types] = f + return f + return dec + + def dispatch_info(*types): + """ + An utility to introspect the dispatch algorithm + """ + check(types) + lst = [] + for anc in itertools.product(*ancestors(*types)): + lst.append(tuple(a.__name__ for a in anc)) + return lst + + def _dispatch(dispatch_args, *args, **kw): + types = tuple(type(arg) for arg in dispatch_args) + try: # fast path + f = typemap[types] + except KeyError: + pass + else: + return f(*args, **kw) + combinations = itertools.product(*ancestors(*types)) + next(combinations) # the first one has been already tried + for types_ in combinations: + f = typemap.get(types_) + if f is not None: + return f(*args, **kw) + + # else call the default implementation + return func(*args, **kw) + + return FunctionMaker.create( + func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, + dict(_f_=_dispatch), register=register, default=func, + typemap=typemap, vancestors=vancestors, ancestors=ancestors, + dispatch_info=dispatch_info, __wrapped__=func) + + gen_func_dec.__name__ = 'dispatch_on' + dispatch_str + return gen_func_dec diff --git a/shared/package-files/7a/7a60e96886ed7d43652b4336ccc3fea13cb64b6ada43e2e94142cafc6ef83ad3/blob b/shared/package-files/7a/7a60e96886ed7d43652b4336ccc3fea13cb64b6ada43e2e94142cafc6ef83ad3/blob new file mode 100644 index 0000000000000000000000000000000000000000..abfb33bd5ba9e9d3699f0350a110672036949534 --- /dev/null +++ b/shared/package-files/7a/7a60e96886ed7d43652b4336ccc3fea13cb64b6ada43e2e94142cafc6ef83ad3/blob @@ -0,0 +1,47 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "parquet/types.h" + +namespace parquet::benchmarks { + +template +void GenerateBenchmarkData(uint32_t size, uint32_t seed, T* data, + std::vector* heap, uint32_t data_string_length); + +#define _GENERATE_BENCHMARK_DATA_DECL(KLASS) \ + template <> \ + void GenerateBenchmarkData(uint32_t size, uint32_t seed, KLASS* data, \ + std::vector* heap, uint32_t data_string_length); + +_GENERATE_BENCHMARK_DATA_DECL(int32_t) +_GENERATE_BENCHMARK_DATA_DECL(int64_t) +_GENERATE_BENCHMARK_DATA_DECL(float) +_GENERATE_BENCHMARK_DATA_DECL(double) +_GENERATE_BENCHMARK_DATA_DECL(ByteArray) +_GENERATE_BENCHMARK_DATA_DECL(FLBA) +_GENERATE_BENCHMARK_DATA_DECL(Int96) + +#undef _GENERATE_BENCHMARK_DATA_DECL + +} // namespace parquet::benchmarks diff --git a/shared/package-files/7a/7a6617f2ae1b3b0e121b139115b54a4b33ac459c219b61f4e0fa8569bd7ffa86/blob b/shared/package-files/7a/7a6617f2ae1b3b0e121b139115b54a4b33ac459c219b61f4e0fa8569bd7ffa86/blob new file mode 100644 index 0000000000000000000000000000000000000000..62a538d340318f3eeb745e77e1b13a1a5ea809af --- /dev/null +++ b/shared/package-files/7a/7a6617f2ae1b3b0e121b139115b54a4b33ac459c219b61f4e0fa8569bd7ffa86/blob @@ -0,0 +1,45 @@ +"""Ensemble-based methods for classification, regression and anomaly detection.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._bagging import BaggingClassifier, BaggingRegressor +from ._base import BaseEnsemble +from ._forest import ( + ExtraTreesClassifier, + ExtraTreesRegressor, + RandomForestClassifier, + RandomForestRegressor, + RandomTreesEmbedding, +) +from ._gb import GradientBoostingClassifier, GradientBoostingRegressor +from ._hist_gradient_boosting.gradient_boosting import ( + HistGradientBoostingClassifier, + HistGradientBoostingRegressor, +) +from ._iforest import IsolationForest +from ._stacking import StackingClassifier, StackingRegressor +from ._voting import VotingClassifier, VotingRegressor +from ._weight_boosting import AdaBoostClassifier, AdaBoostRegressor + +__all__ = [ + "AdaBoostClassifier", + "AdaBoostRegressor", + "BaggingClassifier", + "BaggingRegressor", + "BaseEnsemble", + "ExtraTreesClassifier", + "ExtraTreesRegressor", + "GradientBoostingClassifier", + "GradientBoostingRegressor", + "HistGradientBoostingClassifier", + "HistGradientBoostingRegressor", + "IsolationForest", + "RandomForestClassifier", + "RandomForestRegressor", + "RandomTreesEmbedding", + "StackingClassifier", + "StackingRegressor", + "VotingClassifier", + "VotingRegressor", +] diff --git a/shared/package-files/7a/7a670612a41e0affa4549c727d7eba4d9c5a849f296339c52c4d5fcb2cde6467/blob b/shared/package-files/7a/7a670612a41e0affa4549c727d7eba4d9c5a849f296339c52c4d5fcb2cde6467/blob new file mode 100644 index 0000000000000000000000000000000000000000..667b826f68850eda9392750c34e09673629180b2 --- /dev/null +++ b/shared/package-files/7a/7a670612a41e0affa4549c727d7eba4d9c5a849f296339c52c4d5fcb2cde6467/blob @@ -0,0 +1,52 @@ +from sympy.core.numbers import Integer +from sympy.core.symbol import Symbol +from sympy.physics.quantum.qexpr import QExpr, _qsympify_sequence +from sympy.physics.quantum.hilbert import HilbertSpace +from sympy.core.containers import Tuple + +x = Symbol('x') +y = Symbol('y') + + +def test_qexpr_new(): + q = QExpr(0) + assert q.label == (0,) + assert q.hilbert_space == HilbertSpace() + assert q.is_commutative is False + + q = QExpr(0, 1) + assert q.label == (Integer(0), Integer(1)) + + q = QExpr._new_rawargs(HilbertSpace(), Integer(0), Integer(1)) + assert q.label == (Integer(0), Integer(1)) + assert q.hilbert_space == HilbertSpace() + + +def test_qexpr_commutative(): + q1 = QExpr(x) + q2 = QExpr(y) + assert q1.is_commutative is False + assert q2.is_commutative is False + assert q1*q2 != q2*q1 + + q = QExpr._new_rawargs(Integer(0), Integer(1), HilbertSpace()) + assert q.is_commutative is False + +def test_qexpr_commutative_free_symbols(): + q1 = QExpr(x) + assert q1.free_symbols.pop().is_commutative is False + + q2 = QExpr('q2') + assert q2.free_symbols.pop().is_commutative is False + +def test_qexpr_subs(): + q1 = QExpr(x, y) + assert q1.subs(x, y) == QExpr(y, y) + assert q1.subs({x: 1, y: 2}) == QExpr(1, 2) + + +def test_qsympify(): + assert _qsympify_sequence([[1, 2], [1, 3]]) == (Tuple(1, 2), Tuple(1, 3)) + assert _qsympify_sequence(([1, 2, [3, 4, [2, ]], 1], 3)) == \ + (Tuple(1, 2, Tuple(3, 4, Tuple(2,)), 1), 3) + assert _qsympify_sequence((1,)) == (1,) diff --git a/shared/package-files/7a/7a68f5fa71e60889c94acfebbb1ad1e92d561a67fd38088920e1813571f23b7d/blob b/shared/package-files/7a/7a68f5fa71e60889c94acfebbb1ad1e92d561a67fd38088920e1813571f23b7d/blob new file mode 100644 index 0000000000000000000000000000000000000000..ec8b9646c44b509a7c1b2e91671d9c0192db212c --- /dev/null +++ b/shared/package-files/7a/7a68f5fa71e60889c94acfebbb1ad1e92d561a67fd38088920e1813571f23b7d/blob @@ -0,0 +1,391 @@ +from numpy import array + +from statsmodels.tools.testing import Holder + +mlpacf = Holder() +mlpacf.comment = "mlab.parcorr(x, [], 2, nout=3)" +mlpacf.name = "mlpacf" +mlpacf.lags1000 = array([ + [0.], + [1.], + [2.], + [3.], + [4.], + [5.], + [6.], + [7.], + [8.], + [9.], + [10.], + [11.], + [12.], + [13.], + [14.], + [15.], + [16.], + [17.], + [18.], + [19.], + [20.]]) +mlpacf.bounds1000 = array([ + [0.06334064], + [-0.06334064]]) +mlpacf.lags100 = array([ + [0.], + [1.], + [2.], + [3.], + [4.], + [5.], + [6.], + [7.], + [8.], + [9.], + [10.], + [11.], + [12.], + [13.], + [14.], + [15.], + [16.], + [17.], + [18.], + [19.], + [20.]]) +mlpacf.pacf100 = array([ + [1.], + [0.47253777], + [-0.49466966], + [-0.02689319], + [-0.00122204], + [0.08419183], + [0.03220774], + [0.10404012], + [0.05304617], + [-0.04129564], + [-0.04049451], + [0.11727754], + [0.11804158], + [-0.05864957], + [-0.15681802], + [0.11828684], + [0.05156002], + [0.00694629], + [0.01668964], + [0.02236851], + [-0.0909443]]) +mlpacf.pacf1000 = array([ + [1.00000000e+00], + [5.29288262e-01], + [-5.31849027e-01], + [1.17440051e-02], + [-5.37941905e-02], + [-4.11119348e-02], + [-2.40367432e-02], + [2.24289891e-02], + [3.33007235e-02], + [4.59658302e-02], + [6.65850553e-03], + [-3.76714278e-02], + [5.27229738e-02], + [2.50796558e-02], + [-4.42597301e-02], + [-1.95819186e-02], + [4.70451394e-02], + [-1.70963705e-03], + [3.04262524e-04], + [-6.22001614e-03], + [-1.16694989e-02]]) +mlpacf.bounds100 = array([ + [0.20306923], + [-0.20306923]]) + +mlacf = Holder() +mlacf.comment = "mlab.autocorr(x, [], 2, nout=3)" +mlacf.name = "mlacf" +mlacf.acf1000 = array([ + [1.], + [0.5291635], + [-0.10186759], + [-0.35798372], + [-0.25894203], + [-0.06398397], + [0.0513664], + [0.08222289], + [0.08115406], + [0.07674254], + [0.04540619], + [-0.03024699], + [-0.05886634], + [-0.01422948], + [0.01277825], + [-0.01013384], + [-0.00765693], + [0.02183677], + [0.03618889], + [0.01622553], + [-0.02073507]]) +mlacf.lags1000 = array([ + [0.], + [1.], + [2.], + [3.], + [4.], + [5.], + [6.], + [7.], + [8.], + [9.], + [10.], + [11.], + [12.], + [13.], + [14.], + [15.], + [16.], + [17.], + [18.], + [19.], + [20.]]) +mlacf.bounds1000 = array([ + [0.0795181], + [-0.0795181]]) +mlacf.lags100 = array([ + [0.], + [1.], + [2.], + [3.], + [4.], + [5.], + [6.], + [7.], + [8.], + [9.], + [10.], + [11.], + [12.], + [13.], + [14.], + [15.], + [16.], + [17.], + [18.], + [19.], + [20.]]) +mlacf.bounds100 = array([ + [0.24319646], + [-0.24319646]]) +mlacf.acf100 = array([ + [1.], + [0.47024791], + [-0.1348087], + [-0.32905777], + [-0.18632437], + [0.06223404], + [0.16645194], + [0.12589966], + [0.04805397], + [-0.03785273], + [-0.0956997], + [0.00644021], + [0.17157144], + [0.12370327], + [-0.07597526], + [-0.13865131], + [0.02730275], + [0.13624193], + [0.10417949], + [0.01114516], + [-0.09727938]]) + +mlccf = Holder() +mlccf.comment = "mlab.crosscorr(x[4:], x[:-4], [], 2, nout=3)" +mlccf.name = "mlccf" +mlccf.ccf100 = array([ + [0.20745123], + [0.12351939], + [-0.03436893], + [-0.14550879], + [-0.10570855], + [0.0108839], + [0.1108941], + [0.14562415], + [0.02872607], + [-0.14976649], + [-0.08274954], + [0.13158485], + [0.18350343], + [0.00633845], + [-0.10359988], + [-0.0416147], + [0.05056298], + [0.13438945], + [0.17832125], + [0.06665153], + [-0.19999538], + [-0.31700548], + [-0.09727956], + [0.46547234], + [0.92934645], + [0.44480271], + [-0.09228691], + [-0.21627289], + [-0.05447732], + [0.13786254], + [0.15409039], + [0.07466298], + [-0.01000896], + [-0.06744264], + [-0.0607185], + [0.04338471], + [0.12336618], + [0.07712367], + [-0.08739259], + [-0.09319212], + [0.04426167]]) +mlccf.lags1000 = array([ + [-20.], + [-19.], + [-18.], + [-17.], + [-16.], + [-15.], + [-14.], + [-13.], + [-12.], + [-11.], + [-10.], + [-9.], + [-8.], + [-7.], + [-6.], + [-5.], + [-4.], + [-3.], + [-2.], + [-1.], + [0.], + [1.], + [2.], + [3.], + [4.], + [5.], + [6.], + [7.], + [8.], + [9.], + [10.], + [11.], + [12.], + [13.], + [14.], + [15.], + [16.], + [17.], + [18.], + [19.], + [20.]]) +mlccf.bounds1000 = array([ + [0.06337243], + [-0.06337243]]) +mlccf.ccf1000 = array([ + [0.02733339], + [0.04372407], + [0.01082335], + [-0.02755073], + [-0.02076039], + [0.01624263], + [0.03622844], + [0.02186092], + [-0.00766506], + [-0.0101448], + [0.01279167], + [-0.01424596], + [-0.05893064], + [-0.03028013], + [0.04545462], + [0.076825], + [0.08124118], + [0.08231121], + [0.05142144], + [-0.06405412], + [-0.25922346], + [-0.35806674], + [-0.1017256], + [0.5293535], + [0.99891094], + [0.52941977], + [-0.10127572], + [-0.35691466], + [-0.25943369], + [-0.06458511], + [0.05026194], + [0.08196501], + [0.08242852], + [0.07775845], + [0.04590431], + [-0.03195209], + [-0.06162966], + [-0.01395345], + [0.01448736], + [-0.00952503], + [-0.00927344]]) +mlccf.lags100 = array([ + [-20.], + [-19.], + [-18.], + [-17.], + [-16.], + [-15.], + [-14.], + [-13.], + [-12.], + [-11.], + [-10.], + [-9.], + [-8.], + [-7.], + [-6.], + [-5.], + [-4.], + [-3.], + [-2.], + [-1.], + [0.], + [1.], + [2.], + [3.], + [4.], + [5.], + [6.], + [7.], + [8.], + [9.], + [10.], + [11.], + [12.], + [13.], + [14.], + [15.], + [16.], + [17.], + [18.], + [19.], + [20.]]) +mlccf.bounds100 = array([ + [0.20412415], + [-0.20412415]]) + +mlywar = Holder() +mlywar.comment = "mlab.ar(x100-x100.mean(), 10, 'yw').a.ravel()" +mlywar.arcoef100 = array([ + 1., -0.66685531, 0.43519425, -0.00399862, 0.05521524, + -0.09366752, 0.01093454, -0.00688404, -0.04739089, 0.00127931, + 0.03946846]) +mlywar.arcoef1000 = array([ + 1., -0.81230253, 0.55766432, -0.02370962, 0.02688963, + 0.01110911, 0.02239171, -0.01891209, -0.00240527, -0.01752532, + -0.06348611, 0.0609686, -0.00717163, -0.0467326, -0.00122755, + 0.06004768, -0.04893984, 0.00575949, 0.00249315, -0.00560358, + 0.01248498]) +mlywar.name = "mlywar" diff --git a/shared/package-files/7a/7a692c6854fc89ef2ef5165a5179162353e64756cb0908456ccd719cee3d338f/blob b/shared/package-files/7a/7a692c6854fc89ef2ef5165a5179162353e64756cb0908456ccd719cee3d338f/blob new file mode 100644 index 0000000000000000000000000000000000000000..923be85b5d4e77dc613f230790fd123a9e79c539 --- /dev/null +++ b/shared/package-files/7a/7a692c6854fc89ef2ef5165a5179162353e64756cb0908456ccd719cee3d338f/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor acos(const at::Tensor & self); +TORCH_API at::Tensor & acos_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & acos_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & acos_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/7a/7a6d64b2bde7ac8a184626821c4646e8a09ab2cd49ed2474e9f0f91327d9320b/blob b/shared/package-files/7a/7a6d64b2bde7ac8a184626821c4646e8a09ab2cd49ed2474e9f0f91327d9320b/blob new file mode 100644 index 0000000000000000000000000000000000000000..f59b6eab24d6a031738fe33dfaff30c1f3a36ad5 --- /dev/null +++ b/shared/package-files/7a/7a6d64b2bde7ac8a184626821c4646e8a09ab2cd49ed2474e9f0f91327d9320b/blob @@ -0,0 +1,430 @@ +from typing import Dict, List, NoReturn, Sequence, Union + +from torchgen.api.types import ( + ArrayRefCType, + BaseCType, + Binding, + boolT, + ConstRefCType, + deviceT, + Expr, + intArrayRefT, + iOptTensorListRefT, + layoutT, + ListCType, + longT, + memoryFormatT, + MutRefCType, + NamedCType, + opmath_t, + OptionalCType, + optionalIntArrayRefT, + optionalScalarRefT, + optionalSymIntArrayRefT, + optionalTensorRefT, + scalar_t, + scalarT, + scalarTypeT, + SpecialArgName, + symIntArrayRefT, + SymIntT, + tensorOptionsT, + tensorT, + VectorCType, +) + +# This file implements a small program synthesis engine that implements +# conversions between one API to another. +# +# The key data type in this file in NamedCType, short for Named C++ semantic type. A NamedCType +# represents a C++ type, plus semantic information about what it represents. +# For example, consider the argument "bool pin_memory"; its normal C++ type is +# "bool", but its C++ semantic type also keeps track that this represents a +# "pin_memory"; you can't just use a random other boolean in a context where you +# need a "pin_memory"! +# +# The translator takes a list of needed NamedCTypes, and then figures out how +# to construct expressions with these NamedCTypes from the given bindings. Many +# of these expressions are trivial (I need a Tensor other; there's a Tensor +# other scope); others are more nontrivial and may require packing/unpacking. +# Some examples of non-trivial action: +# +# - Need the "dtype" binding? Well, maybe "dtype" isn't available +# in the context, instead, "options" is, and you need to extract +# it from there. (Gather) +# +# - Need the "context" binding? Well, maybe "context" isn't available +# in the context, and you need to construct it from "dtype", "device", +# etc. (Scatter) +# +# - Need the "memory_format" binding? Well, actually, it's available +# from both "memory_format" and "options", so you had better make sure +# they are consistent. (Join) + +options_ctype = NamedCType("options", ConstRefCType(BaseCType(tensorOptionsT))) + +out_tensor_ctype = NamedCType("out", ConstRefCType(BaseCType(tensorT))) + +longVec_ctype = VectorCType(BaseCType(longT)) +longSymVec_ctype = VectorCType(BaseCType(SymIntT)) +optionalLongVec_ctype = OptionalCType(VectorCType(BaseCType(longT))) +optionalScalar_ctype = OptionalCType(BaseCType(scalarT)) +optionalTensor_ctype = OptionalCType(BaseCType(tensorT)) + + +class UnsatError(RuntimeError): + pass + + +# Given a set of in-scope bindings and a set of target bindings, synthesize +# a list of expressions that uses only the in-scope bindings (bindings) that +# have all of the types of goals. You may want to use this function if +# you're generating code for a function like: +# +# void f({args}) { +# g({exprs}); // g is a different API +# } +# +# and you need to generate "exprs". +# +# Typically, a list of Bindings is convenient to get (you usually call something +# like arguments() to get them); but technically you only need less information: +# for 'bindings' an (un-ordered) list of Exprs is sufficient; similarly, for +# 'goals', an (ordered) list of NamedCType goals is sufficient. If you are doing +# something more complicated, e.g., tracking the set of bindings in a context, +# you may find using these smaller types more convenient. +def translate( + bindings: Sequence[Union[Expr, Binding]], + goals: Sequence[Union[NamedCType, Binding]], + *, + method: bool = False, + allow_expensive_conversions: bool = False, +) -> List[Expr]: + binding_exprs: List[Expr] = [] + for b in bindings: + if isinstance(b, Binding): + binding_exprs.append( + Expr( + expr=b.name, + type=b.nctype, + ) + ) + else: + binding_exprs.append(b) + + goal_ctypes: List[NamedCType] = [] + for g in goals: + if isinstance(g, Binding): + goal_ctypes.append(g.nctype) + else: + goal_ctypes.append(g) + + # Add all the bindings to the context + ctx: Dict[NamedCType, str] = {} + for b in binding_exprs: + ctx[b.type] = b.expr + + # While we're at it, do some simple forward inference, looking through + # constructors. + # + # NB: When should you do forward inference versus backward inference? + # The general idea: + # + # - Backward inference WHEN the goal gets smaller + # - Forward inference WHEN the hypothesis gets smaller + # + # This helps ensure termination: backward inference starts with a goal + # and tries to make it simpler and simpler until it's trivial; if the + # goal can grow in size, we blow up to a really huge goal size. + # Similarly, with forward inference we take hypotheses and decompose + # them into simpler hypotheses; if hypotheses could expand in size, + # we also have potential nontermination. (In the code below, forward + # inference is only ever carried out at a single step, but you could + # imagine repeated application of forward inference being profitable.) + # + # A good starting point in the literature for exploring more about proof + # search are these lecture notes + # https://www.cs.cmu.edu/~fp/courses/oregon-m10/04-focusing.pdf + # + # TODO: My kingdom for a pattern matcher + # https://www.python.org/dev/peps/pep-0634/ + # + # TODO: This could get us in recomputation trouble if b.expr is nontrivial. + # Fix this by implementing some sort of sharing so that if multiple + # goals share the same expression, we only compute it once. This seems + # to matter in practice as compiler is often unwilling to CSE nontrivial + # expressions like scalar.to() + t = b.type + if ( + isinstance(t, ConstRefCType) + and isinstance(t.elem, OptionalCType) + and isinstance(t.elem.elem, BaseCType) + and str(t.elem.elem.type) == "at::Tensor" + ): + ctx[ + NamedCType(t.elem.elem.name, ConstRefCType(BaseCType(tensorT))) + ] = f"({b.expr}.has_value() ? *{b.expr} : at::Tensor())" + + if t.type == ConstRefCType(OptionalCType(BaseCType(tensorT))): + ctx[ + NamedCType(t.name, BaseCType(optionalTensorRefT)) + ] = f"(({b.expr}.has_value() && (*{b.expr}).defined()) ? at::OptionalTensorRef(*{b.expr}) : at::OptionalTensorRef())" + + if t.type == ConstRefCType(BaseCType(scalarT)): + ctx[NamedCType(t.name, BaseCType(opmath_t))] = f"({b.expr}).to()" + + if t.type == ConstRefCType(OptionalCType(BaseCType(scalarT))): + ctx[ + NamedCType(t.name, BaseCType(optionalScalarRefT)) + ] = f"({b.expr}.has_value() ? at::OptionalScalarRef(&({b.expr}.value())) : at::OptionalScalarRef())" + + if t.type == BaseCType(scalar_t): + ctx[ + NamedCType(t.name, BaseCType(opmath_t)) + ] = f"static_cast({b.expr})" + + # [Note: IOptTensorListRef] + if t.type == ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))): + ctx[ + NamedCType(t.name, BaseCType(iOptTensorListRefT)) + ] = f"at::IOptTensorListRef({b.expr})" + + # Add implicit bindings if the generated code is inside a Tensor method + if method: + ctx[ + NamedCType("self", MutRefCType(BaseCType(tensorT))) + ] = "const_cast(*this)" + ctx[ + NamedCType("self", ConstRefCType(BaseCType(tensorT))) + ] = "const_cast(*this)" + # This is better! Byte-for-byte compat + # ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = "*this" + + def unsat(goal: NamedCType) -> NoReturn: + ctx_desc = "\n".join( + f" {t.cpp_type()} {t.name}; // {e}" for t, e in ctx.items() + ) + raise UnsatError( + f""" +Failed to synthesize the expression "{goal.cpp_type()} {goal.name}". +When I failed, the following bindings were available in the context: + +{ctx_desc} + +This probably means there is a missing rule in the rules of torchgen.api.translate. +Check this module for more information. +""" + ) + + # A shitty backtracking search implementation. It's shitty because it + # does backtracking via stack (bad idea!) and for the most part tries to + # avoid backtracking. In particular, if + # direct=True, we won't try to do any fancy synthesis, just trivial + # conversions (e.g., "T a" is OK for "const T& a"). So all of the + # existing rules in this function simply try to solve immediately, + # and bail if things don't work out. + def solve(goal: NamedCType, *, direct: bool) -> str: + def direct_solve(goal: NamedCType) -> str: + return solve(goal, direct=True) + + if goal in ctx: + # Trivial + return ctx[goal] + + # const & is satisfied with mutable & + if isinstance(goal.type, ConstRefCType): + try: + # WARNING: not strictly decreasing; be careful not + # to add a direct conversion that goes satisfies + # mutable& with const& + return solve( + NamedCType(goal.name, MutRefCType(goal.type.elem)), direct=direct + ) + except UnsatError: + pass + + # mutable & is satisfied with value + if isinstance(goal.type, MutRefCType): + try: + return solve(NamedCType(goal.name, goal.type.elem), direct=direct) + except UnsatError: + pass + + # TODO: These are referentially equal, shouldn't have to do this; + # ensuring we don't use type synonym IntArrayRef in codegen would + # help + if goal.type == ArrayRefCType(BaseCType(longT)): + return solve(NamedCType(goal.name, BaseCType(intArrayRefT)), direct=direct) + + if direct: + unsat(goal) + + # For now, all of these rules are mutually exclusive. + if goal == NamedCType("memory_format", OptionalCType(BaseCType(memoryFormatT))): + memory_format = direct_solve( + NamedCType( + SpecialArgName.possibly_redundant_memory_format, + OptionalCType(BaseCType(memoryFormatT)), + ) + ) + # No need to join "memory_format" and "options" if the target API takes "options" directly. + # Otherwise it will cause the redundant memory_format error. + if options_ctype in goal_ctypes: + return memory_format + try: + options = direct_solve(options_ctype) + return f"c10::impl::check_tensor_options_and_extract_memory_format({options}, {memory_format})" + except UnsatError: + return memory_format + elif goal == NamedCType("options", BaseCType(tensorOptionsT)): + dtype = direct_solve( + NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))) + ) + pin_memory = direct_solve( + NamedCType("pin_memory", OptionalCType(BaseCType(boolT))) + ) + device = direct_solve( + NamedCType("device", OptionalCType(BaseCType(deviceT))) + ) + layout = direct_solve( + NamedCType("layout", OptionalCType(BaseCType(layoutT))) + ) + return f"TensorOptions().dtype({dtype}).layout({layout}).device({device}).pinned_memory({pin_memory})" + + elif goal == NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))): + try: + options = direct_solve(options_ctype) + return f"c10::optTypeMetaToScalarType({options}.dtype_opt())" + except UnsatError: + out_tensor = direct_solve(out_tensor_ctype) + return f"{out_tensor}.scalar_type()" + + elif goal == NamedCType("layout", OptionalCType(BaseCType(layoutT))): + try: + options = direct_solve(options_ctype) + return f"{options}.layout_opt()" + except UnsatError: + out_tensor = direct_solve(out_tensor_ctype) + return f"{out_tensor}.layout()" + + elif goal == NamedCType("device", OptionalCType(BaseCType(deviceT))): + try: + options = direct_solve(options_ctype) + return f"{options}.device_opt()" + except UnsatError: + out_tensor = direct_solve(out_tensor_ctype) + return f"{out_tensor}.device()" + + elif goal == NamedCType("pin_memory", OptionalCType(BaseCType(boolT))): + try: + options = direct_solve(options_ctype) + return f"{options}.pinned_memory_opt()" + except UnsatError: + # If we're calling a factory op from its out= variant, + # We don't actually care about the value of pin_memory. + out_tensor = direct_solve(out_tensor_ctype) + return "c10::nullopt" + + # We can always do translations from value types to reference types, like vector -> IntArrayRef + elif goal.type == BaseCType(intArrayRefT): + try: + return direct_solve(NamedCType(goal.name, longVec_ctype)) + except UnsatError: + # We can also go SymIntArrayRef -> IntArrayRef + symIntArrayRef_type = direct_solve( + NamedCType(goal.name, BaseCType(symIntArrayRefT)) + ) + return f"C10_AS_INTARRAYREF_SLOW({symIntArrayRef_type})" + elif goal.type == BaseCType(symIntArrayRefT): + try: + r = direct_solve(NamedCType(goal.name, BaseCType(intArrayRefT))) + return f"c10::fromIntArrayRefSlow({r})" + except UnsatError: + return direct_solve(NamedCType(goal.name, longSymVec_ctype)) + elif goal.type == BaseCType(SymIntT): + return direct_solve(NamedCType(goal.name, BaseCType(longT))) + elif goal.type == OptionalCType(BaseCType(SymIntT)): + argname = direct_solve( + NamedCType(goal.name, OptionalCType(BaseCType(longT))) + ) + return f"{argname}.has_value() ? c10::make_optional(c10::SymInt(*{argname})) : c10::nullopt" + elif goal.type == BaseCType(longT): + symInt_type = direct_solve(NamedCType(goal.name, BaseCType(SymIntT))) + return f"{symInt_type}.guard_int(__FILE__, __LINE__)" + elif goal.type == OptionalCType(BaseCType(longT)): + argname = direct_solve( + NamedCType(goal.name, OptionalCType(BaseCType(SymIntT))) + ) + return f"{argname}.has_value() ? c10::make_optional({argname}->guard_int(__FILE__, __LINE__)) : c10::nullopt" + elif goal.type == BaseCType(optionalIntArrayRefT): + try: + return direct_solve(NamedCType(goal.name, optionalLongVec_ctype)) + except UnsatError: + argname = direct_solve( + NamedCType(goal.name, BaseCType(optionalSymIntArrayRefT)) + ) + return f"{argname}.has_value() ? c10::make_optional(C10_AS_INTARRAYREF_SLOW(*{argname})) : c10::nullopt" + elif goal.type == BaseCType(optionalSymIntArrayRefT): + # TODO: You might also want to solve this from longSymVec_ctype or + # an optional version of it + argname = direct_solve( + NamedCType(goal.name, BaseCType(optionalIntArrayRefT)) + ) + return f"{argname}.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*{argname})) : c10::nullopt" + elif goal.type == BaseCType(optionalScalarRefT): + return direct_solve(NamedCType(goal.name, optionalScalar_ctype)) + elif goal.type == BaseCType(optionalTensorRefT): + return direct_solve(NamedCType(goal.name, optionalTensor_ctype)) + + # Note [translation from C++ reference to value types] + # The below cases are all for when we have an argument with a reference type, + # and a corresponding goal with a value type. + # These are needed when we populate the inputs to a lambda capture and we need + # to guarantee the lifetime of each captured argument. + # We guard it with an explicit kwarg because converting to a value type is expensive + # (O(n)) to convert from IntArrayRef to vector), + # so the caller of translate() should be explicit that they need it. + if allow_expensive_conversions: + if goal.type == VectorCType(BaseCType(longT)): + intArrayRef_ctype = NamedCType(goal.name, BaseCType(intArrayRefT)) + argname = direct_solve(intArrayRef_ctype) + return f"{argname}.vec()" + if goal.type == VectorCType(BaseCType(SymIntT)): + symIntArrayRef_ctype = NamedCType(goal.name, BaseCType(symIntArrayRefT)) + argname = direct_solve(symIntArrayRef_ctype) + return f"{argname}.vec()" + elif goal.type == OptionalCType(VectorCType(BaseCType(longT))): + optionalIntArrayRef_ctype = NamedCType( + goal.name, BaseCType(optionalIntArrayRefT) + ) + argname = direct_solve(optionalIntArrayRef_ctype) + return f"{argname}.has_value() ? c10::make_optional({argname}->vec()) : c10::nullopt" + elif goal.type == OptionalCType(BaseCType(scalarT)): + optionalScalarRef_ctype = NamedCType( + goal.name, BaseCType(optionalScalarRefT) + ) + argname = direct_solve(optionalScalarRef_ctype) + return f"{argname}.has_value() ? c10::make_optional({argname}) : c10::nullopt" + elif goal.type == OptionalCType(BaseCType(scalarT)): + optionalTensorRef_ctype = NamedCType( + goal.name, BaseCType(optionalTensorRefT) + ) + argname = direct_solve(optionalTensorRef_ctype) + return f"{argname}.has_value() ? c10::make_optional({argname}) : c10::nullopt" + # Technically, we also need to handle cases of C++ containers holding reference types. + # But there currently aren't any ops that require lambda capture codegen + # With arguments like std::vector. + # If that changes, we'll have to add the translation here. + + # We allow const casting on tensors, since const-correctness is a bit broken for at::Tensor. + # We could probably generalize this to non-tensor types too. + if goal.type == MutRefCType(BaseCType(tensorT)): + const_ref_tensor_ctype = NamedCType( + goal.name, ConstRefCType(BaseCType(tensorT)) + ) + argname = direct_solve(const_ref_tensor_ctype) + return f"const_cast({argname})" + + unsat(goal) + + return [Expr(solve(g, direct=False), g) for g in goal_ctypes] diff --git a/shared/package-files/7a/7a6d983070d61055dd647d012a2e5b2d1010f1b6037e8a764f443c4aa0e1d01f/blob b/shared/package-files/7a/7a6d983070d61055dd647d012a2e5b2d1010f1b6037e8a764f443c4aa0e1d01f/blob new file mode 100644 index 0000000000000000000000000000000000000000..76e1f6285b552c11ceae9bc6cdbd6a308419b0e8 Binary files /dev/null and b/shared/package-files/7a/7a6d983070d61055dd647d012a2e5b2d1010f1b6037e8a764f443c4aa0e1d01f/blob differ diff --git a/shared/package-files/7a/7a6e066702c3144d104b1c60d3cd70570861f839ad927f1fef04e12340e25d5b/blob b/shared/package-files/7a/7a6e066702c3144d104b1c60d3cd70570861f839ad927f1fef04e12340e25d5b/blob new file mode 100644 index 0000000000000000000000000000000000000000..6301e51769fee30db50bfaf1e2777bf894166de8 --- /dev/null +++ b/shared/package-files/7a/7a6e066702c3144d104b1c60d3cd70570861f839ad927f1fef04e12340e25d5b/blob @@ -0,0 +1,17 @@ +from collections.abc import Sequence +from numpy._typing import _NestedSequence + +a: Sequence[float] +b: list[complex] +c: tuple[str, ...] +d: int +e: str + +def func(a: _NestedSequence[int]) -> None: + ... + +reveal_type(func(a)) # E: incompatible type +reveal_type(func(b)) # E: incompatible type +reveal_type(func(c)) # E: incompatible type +reveal_type(func(d)) # E: incompatible type +reveal_type(func(e)) # E: incompatible type diff --git a/shared/package-files/7a/7a6e35746f6ccab41759e186e5ff2ffee6e261f80ff460d97efc302cd335b09b/blob b/shared/package-files/7a/7a6e35746f6ccab41759e186e5ff2ffee6e261f80ff460d97efc302cd335b09b/blob new file mode 100644 index 0000000000000000000000000000000000000000..af8f80db6a34741b761991a4256e395100080171 --- /dev/null +++ b/shared/package-files/7a/7a6e35746f6ccab41759e186e5ff2ffee6e261f80ff460d97efc302cd335b09b/blob @@ -0,0 +1,1400 @@ +""" +Base and utility classes for pandas objects. +""" + +from __future__ import annotations + +import textwrap +from typing import ( + TYPE_CHECKING, + Any, + Generic, + Literal, + cast, + final, + overload, +) +import warnings + +import numpy as np + +from pandas._config import using_copy_on_write + +from pandas._libs import lib +from pandas._typing import ( + AxisInt, + DtypeObj, + IndexLabel, + NDFrameT, + Self, + Shape, + npt, +) +from pandas.compat import PYPY +from pandas.compat.numpy import function as nv +from pandas.errors import AbstractMethodError +from pandas.util._decorators import ( + cache_readonly, + doc, +) +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.cast import can_hold_element +from pandas.core.dtypes.common import ( + is_object_dtype, + is_scalar, +) +from pandas.core.dtypes.dtypes import ExtensionDtype +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCIndex, + ABCMultiIndex, + ABCSeries, +) +from pandas.core.dtypes.missing import ( + isna, + remove_na_arraylike, +) + +from pandas.core import ( + algorithms, + nanops, + ops, +) +from pandas.core.accessor import DirNamesMixin +from pandas.core.arraylike import OpsMixin +from pandas.core.arrays import ExtensionArray +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, +) + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Iterator, + ) + + from pandas._typing import ( + DropKeep, + NumpySorter, + NumpyValueArrayLike, + ScalarLike_co, + ) + + from pandas import ( + DataFrame, + Index, + Series, + ) + + +_shared_docs: dict[str, str] = {} +_indexops_doc_kwargs = { + "klass": "IndexOpsMixin", + "inplace": "", + "unique": "IndexOpsMixin", + "duplicated": "IndexOpsMixin", +} + + +class PandasObject(DirNamesMixin): + """ + Baseclass for various pandas objects. + """ + + # results from calls to methods decorated with cache_readonly get added to _cache + _cache: dict[str, Any] + + @property + def _constructor(self): + """ + Class constructor (for this class it's just `__class__`). + """ + return type(self) + + def __repr__(self) -> str: + """ + Return a string representation for a particular object. + """ + # Should be overwritten by base classes + return object.__repr__(self) + + def _reset_cache(self, key: str | None = None) -> None: + """ + Reset cached properties. If ``key`` is passed, only clears that key. + """ + if not hasattr(self, "_cache"): + return + if key is None: + self._cache.clear() + else: + self._cache.pop(key, None) + + def __sizeof__(self) -> int: + """ + Generates the total memory usage for an object that returns + either a value or Series of values + """ + memory_usage = getattr(self, "memory_usage", None) + if memory_usage: + mem = memory_usage(deep=True) # pylint: disable=not-callable + return int(mem if is_scalar(mem) else mem.sum()) + + # no memory_usage attribute, so fall back to object's 'sizeof' + return super().__sizeof__() + + +class NoNewAttributesMixin: + """ + Mixin which prevents adding new attributes. + + Prevents additional attributes via xxx.attribute = "something" after a + call to `self.__freeze()`. Mainly used to prevent the user from using + wrong attributes on an accessor (`Series.cat/.str/.dt`). + + If you really want to add a new attribute at a later time, you need to use + `object.__setattr__(self, key, value)`. + """ + + def _freeze(self) -> None: + """ + Prevents setting additional attributes. + """ + object.__setattr__(self, "__frozen", True) + + # prevent adding any attribute via s.xxx.new_attribute = ... + def __setattr__(self, key: str, value) -> None: + # _cache is used by a decorator + # We need to check both 1.) cls.__dict__ and 2.) getattr(self, key) + # because + # 1.) getattr is false for attributes that raise errors + # 2.) cls.__dict__ doesn't traverse into base classes + if getattr(self, "__frozen", False) and not ( + key == "_cache" + or key in type(self).__dict__ + or getattr(self, key, None) is not None + ): + raise AttributeError(f"You cannot add any new attribute '{key}'") + object.__setattr__(self, key, value) + + +class SelectionMixin(Generic[NDFrameT]): + """ + mixin implementing the selection & aggregation interface on a group-like + object sub-classes need to define: obj, exclusions + """ + + obj: NDFrameT + _selection: IndexLabel | None = None + exclusions: frozenset[Hashable] + _internal_names = ["_cache", "__setstate__"] + _internal_names_set = set(_internal_names) + + @final + @property + def _selection_list(self): + if not isinstance( + self._selection, (list, tuple, ABCSeries, ABCIndex, np.ndarray) + ): + return [self._selection] + return self._selection + + @cache_readonly + def _selected_obj(self): + if self._selection is None or isinstance(self.obj, ABCSeries): + return self.obj + else: + return self.obj[self._selection] + + @final + @cache_readonly + def ndim(self) -> int: + return self._selected_obj.ndim + + @final + @cache_readonly + def _obj_with_exclusions(self): + if isinstance(self.obj, ABCSeries): + return self.obj + + if self._selection is not None: + return self.obj._getitem_nocopy(self._selection_list) + + if len(self.exclusions) > 0: + # equivalent to `self.obj.drop(self.exclusions, axis=1) + # but this avoids consolidating and making a copy + # TODO: following GH#45287 can we now use .drop directly without + # making a copy? + return self.obj._drop_axis(self.exclusions, axis=1, only_slice=True) + else: + return self.obj + + def __getitem__(self, key): + if self._selection is not None: + raise IndexError(f"Column(s) {self._selection} already selected") + + if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)): + if len(self.obj.columns.intersection(key)) != len(set(key)): + bad_keys = list(set(key).difference(self.obj.columns)) + raise KeyError(f"Columns not found: {str(bad_keys)[1:-1]}") + return self._gotitem(list(key), ndim=2) + + else: + if key not in self.obj: + raise KeyError(f"Column not found: {key}") + ndim = self.obj[key].ndim + return self._gotitem(key, ndim=ndim) + + def _gotitem(self, key, ndim: int, subset=None): + """ + sub-classes to define + return a sliced object + + Parameters + ---------- + key : str / list of selections + ndim : {1, 2} + requested ndim of result + subset : object, default None + subset to act on + """ + raise AbstractMethodError(self) + + @final + def _infer_selection(self, key, subset: Series | DataFrame): + """ + Infer the `selection` to pass to our constructor in _gotitem. + """ + # Shared by Rolling and Resample + selection = None + if subset.ndim == 2 and ( + (lib.is_scalar(key) and key in subset) or lib.is_list_like(key) + ): + selection = key + elif subset.ndim == 1 and lib.is_scalar(key) and key == subset.name: + selection = key + return selection + + def aggregate(self, func, *args, **kwargs): + raise AbstractMethodError(self) + + agg = aggregate + + +class IndexOpsMixin(OpsMixin): + """ + Common ops mixin to support a unified interface / docs for Series / Index + """ + + # ndarray compatibility + __array_priority__ = 1000 + _hidden_attrs: frozenset[str] = frozenset( + ["tolist"] # tolist is not deprecated, just suppressed in the __dir__ + ) + + @property + def dtype(self) -> DtypeObj: + # must be defined here as a property for mypy + raise AbstractMethodError(self) + + @property + def _values(self) -> ExtensionArray | np.ndarray: + # must be defined here as a property for mypy + raise AbstractMethodError(self) + + @final + def transpose(self, *args, **kwargs) -> Self: + """ + Return the transpose, which is by definition self. + + Returns + ------- + %(klass)s + """ + nv.validate_transpose(args, kwargs) + return self + + T = property( + transpose, + doc=""" + Return the transpose, which is by definition self. + + Examples + -------- + For Series: + + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.T + 0 Ant + 1 Bear + 2 Cow + dtype: object + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx.T + Index([1, 2, 3], dtype='int64') + """, + ) + + @property + def shape(self) -> Shape: + """ + Return a tuple of the shape of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.shape + (3,) + """ + return self._values.shape + + def __len__(self) -> int: + # We need this defined here for mypy + raise AbstractMethodError(self) + + # Temporarily avoid using `-> Literal[1]:` because of an IPython (jedi) bug + # https://github.com/ipython/ipython/issues/14412 + # https://github.com/davidhalter/jedi/issues/1990 + @property + def ndim(self) -> int: + """ + Number of dimensions of the underlying data, by definition 1. + + Examples + -------- + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.ndim + 1 + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.ndim + 1 + """ + return 1 + + @final + def item(self): + """ + Return the first element of the underlying data as a Python scalar. + + Returns + ------- + scalar + The first element of Series or Index. + + Raises + ------ + ValueError + If the data is not length = 1. + + Examples + -------- + >>> s = pd.Series([1]) + >>> s.item() + 1 + + For an index: + + >>> s = pd.Series([1], index=['a']) + >>> s.index.item() + 'a' + """ + if len(self) == 1: + return next(iter(self)) + raise ValueError("can only convert an array of size 1 to a Python scalar") + + @property + def nbytes(self) -> int: + """ + Return the number of bytes in the underlying data. + + Examples + -------- + For Series: + + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.nbytes + 24 + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.nbytes + 24 + """ + return self._values.nbytes + + @property + def size(self) -> int: + """ + Return the number of elements in the underlying data. + + Examples + -------- + For Series: + + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.size + 3 + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.size + 3 + """ + return len(self._values) + + @property + def array(self) -> ExtensionArray: + """ + The ExtensionArray of the data backing this Series or Index. + + Returns + ------- + ExtensionArray + An ExtensionArray of the values stored within. For extension + types, this is the actual array. For NumPy native types, this + is a thin (no copy) wrapper around :class:`numpy.ndarray`. + + ``.array`` differs from ``.values``, which may require converting + the data to a different form. + + See Also + -------- + Index.to_numpy : Similar method that always returns a NumPy array. + Series.to_numpy : Similar method that always returns a NumPy array. + + Notes + ----- + This table lays out the different array types for each extension + dtype within pandas. + + ================== ============================= + dtype array type + ================== ============================= + category Categorical + period PeriodArray + interval IntervalArray + IntegerNA IntegerArray + string StringArray + boolean BooleanArray + datetime64[ns, tz] DatetimeArray + ================== ============================= + + For any 3rd-party extension types, the array type will be an + ExtensionArray. + + For all remaining dtypes ``.array`` will be a + :class:`arrays.NumpyExtensionArray` wrapping the actual ndarray + stored within. If you absolutely need a NumPy array (possibly with + copying / coercing data), then use :meth:`Series.to_numpy` instead. + + Examples + -------- + For regular NumPy types like int, and float, a NumpyExtensionArray + is returned. + + >>> pd.Series([1, 2, 3]).array + + [1, 2, 3] + Length: 3, dtype: int64 + + For extension types, like Categorical, the actual ExtensionArray + is returned + + >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) + >>> ser.array + ['a', 'b', 'a'] + Categories (2, object): ['a', 'b'] + """ + raise AbstractMethodError(self) + + @final + def to_numpy( + self, + dtype: npt.DTypeLike | None = None, + copy: bool = False, + na_value: object = lib.no_default, + **kwargs, + ) -> np.ndarray: + """ + A NumPy ndarray representing the values in this Series or Index. + + Parameters + ---------- + dtype : str or numpy.dtype, optional + The dtype to pass to :meth:`numpy.asarray`. + copy : bool, default False + Whether to ensure that the returned value is not a view on + another array. Note that ``copy=False`` does not *ensure* that + ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that + a copy is made, even if not strictly necessary. + na_value : Any, optional + The value to use for missing values. The default value depends + on `dtype` and the type of the array. + **kwargs + Additional keywords passed through to the ``to_numpy`` method + of the underlying array (for extension arrays). + + Returns + ------- + numpy.ndarray + + See Also + -------- + Series.array : Get the actual data stored within. + Index.array : Get the actual data stored within. + DataFrame.to_numpy : Similar method for DataFrame. + + Notes + ----- + The returned array will be the same up to equality (values equal + in `self` will be equal in the returned array; likewise for values + that are not equal). When `self` contains an ExtensionArray, the + dtype may be different. For example, for a category-dtype Series, + ``to_numpy()`` will return a NumPy array and the categorical dtype + will be lost. + + For NumPy dtypes, this will be a reference to the actual data stored + in this Series or Index (assuming ``copy=False``). Modifying the result + in place will modify the data stored in the Series or Index (not that + we recommend doing that). + + For extension types, ``to_numpy()`` *may* require copying data and + coercing the result to a NumPy type (possibly object), which may be + expensive. When you need a no-copy reference to the underlying data, + :attr:`Series.array` should be used instead. + + This table lays out the different dtypes and default return types of + ``to_numpy()`` for various dtypes within pandas. + + ================== ================================ + dtype array type + ================== ================================ + category[T] ndarray[T] (same dtype as input) + period ndarray[object] (Periods) + interval ndarray[object] (Intervals) + IntegerNA ndarray[object] + datetime64[ns] datetime64[ns] + datetime64[ns, tz] ndarray[object] (Timestamps) + ================== ================================ + + Examples + -------- + >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) + >>> ser.to_numpy() + array(['a', 'b', 'a'], dtype=object) + + Specify the `dtype` to control how datetime-aware data is represented. + Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp` + objects, each with the correct ``tz``. + + >>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) + >>> ser.to_numpy(dtype=object) + array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'), + Timestamp('2000-01-02 00:00:00+0100', tz='CET')], + dtype=object) + + Or ``dtype='datetime64[ns]'`` to return an ndarray of native + datetime64 values. The values are converted to UTC and the timezone + info is dropped. + + >>> ser.to_numpy(dtype="datetime64[ns]") + ... # doctest: +ELLIPSIS + array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'], + dtype='datetime64[ns]') + """ + if isinstance(self.dtype, ExtensionDtype): + return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs) + elif kwargs: + bad_keys = next(iter(kwargs.keys())) + raise TypeError( + f"to_numpy() got an unexpected keyword argument '{bad_keys}'" + ) + + fillna = ( + na_value is not lib.no_default + # no need to fillna with np.nan if we already have a float dtype + and not (na_value is np.nan and np.issubdtype(self.dtype, np.floating)) + ) + + values = self._values + if fillna: + if not can_hold_element(values, na_value): + # if we can't hold the na_value asarray either makes a copy or we + # error before modifying values. The asarray later on thus won't make + # another copy + values = np.asarray(values, dtype=dtype) + else: + values = values.copy() + + values[np.asanyarray(isna(self))] = na_value + + result = np.asarray(values, dtype=dtype) + + if (copy and not fillna) or (not copy and using_copy_on_write()): + if np.shares_memory(self._values[:2], result[:2]): + # Take slices to improve performance of check + if using_copy_on_write() and not copy: + result = result.view() + result.flags.writeable = False + else: + result = result.copy() + + return result + + @final + @property + def empty(self) -> bool: + return not self.size + + @doc(op="max", oppose="min", value="largest") + def argmax( + self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs + ) -> int: + """ + Return int position of the {value} value in the Series. + + If the {op}imum is achieved in multiple locations, + the first row position is returned. + + Parameters + ---------- + axis : {{None}} + Unused. Parameter needed for compatibility with DataFrame. + skipna : bool, default True + Exclude NA/null values when showing the result. + *args, **kwargs + Additional arguments and keywords for compatibility with NumPy. + + Returns + ------- + int + Row position of the {op}imum value. + + See Also + -------- + Series.arg{op} : Return position of the {op}imum value. + Series.arg{oppose} : Return position of the {oppose}imum value. + numpy.ndarray.arg{op} : Equivalent method for numpy arrays. + Series.idxmax : Return index label of the maximum values. + Series.idxmin : Return index label of the minimum values. + + Examples + -------- + Consider dataset containing cereal calories + + >>> s = pd.Series({{'Corn Flakes': 100.0, 'Almond Delight': 110.0, + ... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}}) + >>> s + Corn Flakes 100.0 + Almond Delight 110.0 + Cinnamon Toast Crunch 120.0 + Cocoa Puff 110.0 + dtype: float64 + + >>> s.argmax() + 2 + >>> s.argmin() + 0 + + The maximum cereal calories is the third element and + the minimum cereal calories is the first element, + since series is zero-indexed. + """ + delegate = self._values + nv.validate_minmax_axis(axis) + skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs) + + if isinstance(delegate, ExtensionArray): + if not skipna and delegate.isna().any(): + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return -1 + else: + return delegate.argmax() + else: + result = nanops.nanargmax(delegate, skipna=skipna) + if result == -1: + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + # error: Incompatible return value type (got "Union[int, ndarray]", expected + # "int") + return result # type: ignore[return-value] + + @doc(argmax, op="min", oppose="max", value="smallest") + def argmin( + self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs + ) -> int: + delegate = self._values + nv.validate_minmax_axis(axis) + skipna = nv.validate_argmin_with_skipna(skipna, args, kwargs) + + if isinstance(delegate, ExtensionArray): + if not skipna and delegate.isna().any(): + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return -1 + else: + return delegate.argmin() + else: + result = nanops.nanargmin(delegate, skipna=skipna) + if result == -1: + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + # error: Incompatible return value type (got "Union[int, ndarray]", expected + # "int") + return result # type: ignore[return-value] + + def tolist(self): + """ + Return a list of the values. + + These are each a scalar type, which is a Python scalar + (for str, int, float) or a pandas scalar + (for Timestamp/Timedelta/Interval/Period) + + Returns + ------- + list + + See Also + -------- + numpy.ndarray.tolist : Return the array as an a.ndim-levels deep + nested list of Python scalars. + + Examples + -------- + For Series + + >>> s = pd.Series([1, 2, 3]) + >>> s.to_list() + [1, 2, 3] + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + + >>> idx.to_list() + [1, 2, 3] + """ + return self._values.tolist() + + to_list = tolist + + def __iter__(self) -> Iterator: + """ + Return an iterator of the values. + + These are each a scalar type, which is a Python scalar + (for str, int, float) or a pandas scalar + (for Timestamp/Timedelta/Interval/Period) + + Returns + ------- + iterator + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> for x in s: + ... print(x) + 1 + 2 + 3 + """ + # We are explicitly making element iterators. + if not isinstance(self._values, np.ndarray): + # Check type instead of dtype to catch DTA/TDA + return iter(self._values) + else: + return map(self._values.item, range(self._values.size)) + + @cache_readonly + def hasnans(self) -> bool: + """ + Return True if there are any NaNs. + + Enables various performance speedups. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 3, None]) + >>> s + 0 1.0 + 1 2.0 + 2 3.0 + 3 NaN + dtype: float64 + >>> s.hasnans + True + """ + # error: Item "bool" of "Union[bool, ndarray[Any, dtype[bool_]], NDFrame]" + # has no attribute "any" + return bool(isna(self).any()) # type: ignore[union-attr] + + @final + def _map_values(self, mapper, na_action=None, convert: bool = True): + """ + An internal function that maps values using the input + correspondence (which can be a dict, Series, or function). + + Parameters + ---------- + mapper : function, dict, or Series + The input correspondence object + na_action : {None, 'ignore'} + If 'ignore', propagate NA values, without passing them to the + mapping function + convert : bool, default True + Try to find better dtype for elementwise function results. If + False, leave as dtype=object. Note that the dtype is always + preserved for some extension array dtypes, such as Categorical. + + Returns + ------- + Union[Index, MultiIndex], inferred + The output of the mapping function applied to the index. + If the function returns a tuple with more than one element + a MultiIndex will be returned. + """ + arr = self._values + + if isinstance(arr, ExtensionArray): + return arr.map(mapper, na_action=na_action) + + return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert) + + @final + def value_counts( + self, + normalize: bool = False, + sort: bool = True, + ascending: bool = False, + bins=None, + dropna: bool = True, + ) -> Series: + """ + Return a Series containing counts of unique values. + + The resulting object will be in descending order so that the + first element is the most frequently-occurring element. + Excludes NA values by default. + + Parameters + ---------- + normalize : bool, default False + If True then the object returned will contain the relative + frequencies of the unique values. + sort : bool, default True + Sort by frequencies when True. Preserve the order of the data when False. + ascending : bool, default False + Sort in ascending order. + bins : int, optional + Rather than count values, group them into half-open bins, + a convenience for ``pd.cut``, only works with numeric data. + dropna : bool, default True + Don't include counts of NaN. + + Returns + ------- + Series + + See Also + -------- + Series.count: Number of non-NA elements in a Series. + DataFrame.count: Number of non-NA elements in a DataFrame. + DataFrame.value_counts: Equivalent method on DataFrames. + + Examples + -------- + >>> index = pd.Index([3, 1, 2, 3, 4, np.nan]) + >>> index.value_counts() + 3.0 2 + 1.0 1 + 2.0 1 + 4.0 1 + Name: count, dtype: int64 + + With `normalize` set to `True`, returns the relative frequency by + dividing all values by the sum of values. + + >>> s = pd.Series([3, 1, 2, 3, 4, np.nan]) + >>> s.value_counts(normalize=True) + 3.0 0.4 + 1.0 0.2 + 2.0 0.2 + 4.0 0.2 + Name: proportion, dtype: float64 + + **bins** + + Bins can be useful for going from a continuous variable to a + categorical variable; instead of counting unique + apparitions of values, divide the index in the specified + number of half-open bins. + + >>> s.value_counts(bins=3) + (0.996, 2.0] 2 + (2.0, 3.0] 2 + (3.0, 4.0] 1 + Name: count, dtype: int64 + + **dropna** + + With `dropna` set to `False` we can also see NaN index values. + + >>> s.value_counts(dropna=False) + 3.0 2 + 1.0 1 + 2.0 1 + 4.0 1 + NaN 1 + Name: count, dtype: int64 + """ + return algorithms.value_counts_internal( + self, + sort=sort, + ascending=ascending, + normalize=normalize, + bins=bins, + dropna=dropna, + ) + + def unique(self): + values = self._values + if not isinstance(values, np.ndarray): + # i.e. ExtensionArray + result = values.unique() + else: + result = algorithms.unique1d(values) + return result + + @final + def nunique(self, dropna: bool = True) -> int: + """ + Return number of unique elements in the object. + + Excludes NA values by default. + + Parameters + ---------- + dropna : bool, default True + Don't include NaN in the count. + + Returns + ------- + int + + See Also + -------- + DataFrame.nunique: Method nunique for DataFrame. + Series.count: Count non-NA/null observations in the Series. + + Examples + -------- + >>> s = pd.Series([1, 3, 5, 7, 7]) + >>> s + 0 1 + 1 3 + 2 5 + 3 7 + 4 7 + dtype: int64 + + >>> s.nunique() + 4 + """ + uniqs = self.unique() + if dropna: + uniqs = remove_na_arraylike(uniqs) + return len(uniqs) + + @property + def is_unique(self) -> bool: + """ + Return boolean if values in the object are unique. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.is_unique + True + + >>> s = pd.Series([1, 2, 3, 1]) + >>> s.is_unique + False + """ + return self.nunique(dropna=False) == len(self) + + @property + def is_monotonic_increasing(self) -> bool: + """ + Return boolean if values in the object are monotonically increasing. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 2]) + >>> s.is_monotonic_increasing + True + + >>> s = pd.Series([3, 2, 1]) + >>> s.is_monotonic_increasing + False + """ + from pandas import Index + + return Index(self).is_monotonic_increasing + + @property + def is_monotonic_decreasing(self) -> bool: + """ + Return boolean if values in the object are monotonically decreasing. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([3, 2, 2, 1]) + >>> s.is_monotonic_decreasing + True + + >>> s = pd.Series([1, 2, 3]) + >>> s.is_monotonic_decreasing + False + """ + from pandas import Index + + return Index(self).is_monotonic_decreasing + + @final + def _memory_usage(self, deep: bool = False) -> int: + """ + Memory usage of the values. + + Parameters + ---------- + deep : bool, default False + Introspect the data deeply, interrogate + `object` dtypes for system-level memory consumption. + + Returns + ------- + bytes used + + See Also + -------- + numpy.ndarray.nbytes : Total bytes consumed by the elements of the + array. + + Notes + ----- + Memory usage does not include memory consumed by elements that + are not components of the array if deep=False or if used on PyPy + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx.memory_usage() + 24 + """ + if hasattr(self.array, "memory_usage"): + return self.array.memory_usage( # pyright: ignore[reportGeneralTypeIssues] + deep=deep, + ) + + v = self.array.nbytes + if deep and is_object_dtype(self.dtype) and not PYPY: + values = cast(np.ndarray, self._values) + v += lib.memory_usage_of_objects(values) + return v + + @doc( + algorithms.factorize, + values="", + order="", + size_hint="", + sort=textwrap.dedent( + """\ + sort : bool, default False + Sort `uniques` and shuffle `codes` to maintain the + relationship. + """ + ), + ) + def factorize( + self, + sort: bool = False, + use_na_sentinel: bool = True, + ) -> tuple[npt.NDArray[np.intp], Index]: + codes, uniques = algorithms.factorize( + self._values, sort=sort, use_na_sentinel=use_na_sentinel + ) + if uniques.dtype == np.float16: + uniques = uniques.astype(np.float32) + + if isinstance(self, ABCMultiIndex): + # preserve MultiIndex + uniques = self._constructor(uniques) + else: + from pandas import Index + + try: + uniques = Index(uniques, dtype=self.dtype) + except NotImplementedError: + # not all dtypes are supported in Index that are allowed for Series + # e.g. float16 or bytes + uniques = Index(uniques) + return codes, uniques + + _shared_docs[ + "searchsorted" + ] = """ + Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted {klass} `self` such that, if the + corresponding elements in `value` were inserted before the indices, + the order of `self` would be preserved. + + .. note:: + + The {klass} *must* be monotonically sorted, otherwise + wrong locations will likely be returned. Pandas does *not* + check this for you. + + Parameters + ---------- + value : array-like or scalar + Values to insert into `self`. + side : {{'left', 'right'}}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `self`). + sorter : 1-D array-like, optional + Optional array of integer indices that sort `self` into ascending + order. They are typically the result of ``np.argsort``. + + Returns + ------- + int or array of int + A scalar or array of insertion points with the + same shape as `value`. + + See Also + -------- + sort_values : Sort by the values along either axis. + numpy.searchsorted : Similar method from NumPy. + + Notes + ----- + Binary search is used to find the required insertion points. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]) + >>> ser + 0 1 + 1 2 + 2 3 + dtype: int64 + + >>> ser.searchsorted(4) + 3 + + >>> ser.searchsorted([0, 4]) + array([0, 3]) + + >>> ser.searchsorted([1, 3], side='left') + array([0, 2]) + + >>> ser.searchsorted([1, 3], side='right') + array([1, 3]) + + >>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000'])) + >>> ser + 0 2000-03-11 + 1 2000-03-12 + 2 2000-03-13 + dtype: datetime64[ns] + + >>> ser.searchsorted('3/14/2000') + 3 + + >>> ser = pd.Categorical( + ... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True + ... ) + >>> ser + ['apple', 'bread', 'bread', 'cheese', 'milk'] + Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk'] + + >>> ser.searchsorted('bread') + 1 + + >>> ser.searchsorted(['bread'], side='right') + array([3]) + + If the values are not monotonically sorted, wrong locations + may be returned: + + >>> ser = pd.Series([2, 1, 3]) + >>> ser + 0 2 + 1 1 + 2 3 + dtype: int64 + + >>> ser.searchsorted(1) # doctest: +SKIP + 0 # wrong result, correct would be 1 + """ + + # This overload is needed so that the call to searchsorted in + # pandas.core.resample.TimeGrouper._get_period_bins picks the correct result + + # error: Overloaded function signatures 1 and 2 overlap with incompatible + # return types + @overload + def searchsorted( # type: ignore[overload-overlap] + self, + value: ScalarLike_co, + side: Literal["left", "right"] = ..., + sorter: NumpySorter = ..., + ) -> np.intp: + ... + + @overload + def searchsorted( + self, + value: npt.ArrayLike | ExtensionArray, + side: Literal["left", "right"] = ..., + sorter: NumpySorter = ..., + ) -> npt.NDArray[np.intp]: + ... + + @doc(_shared_docs["searchsorted"], klass="Index") + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter | None = None, + ) -> npt.NDArray[np.intp] | np.intp: + if isinstance(value, ABCDataFrame): + msg = ( + "Value must be 1-D array-like or scalar, " + f"{type(value).__name__} is not supported" + ) + raise ValueError(msg) + + values = self._values + if not isinstance(values, np.ndarray): + # Going through EA.searchsorted directly improves performance GH#38083 + return values.searchsorted(value, side=side, sorter=sorter) + + return algorithms.searchsorted( + values, + value, + side=side, + sorter=sorter, + ) + + def drop_duplicates(self, *, keep: DropKeep = "first"): + duplicated = self._duplicated(keep=keep) + # error: Value of type "IndexOpsMixin" is not indexable + return self[~duplicated] # type: ignore[index] + + @final + def _duplicated(self, keep: DropKeep = "first") -> npt.NDArray[np.bool_]: + arr = self._values + if isinstance(arr, ExtensionArray): + return arr.duplicated(keep=keep) + return algorithms.duplicated(arr, keep=keep) + + def _arith_method(self, other, op): + res_name = ops.get_op_result_name(self, other) + + lvalues = self._values + rvalues = extract_array(other, extract_numpy=True, extract_range=True) + rvalues = ops.maybe_prepare_scalar_for_op(rvalues, lvalues.shape) + rvalues = ensure_wrapped_if_datetimelike(rvalues) + if isinstance(rvalues, range): + rvalues = np.arange(rvalues.start, rvalues.stop, rvalues.step) + + with np.errstate(all="ignore"): + result = ops.arithmetic_op(lvalues, rvalues, op) + + return self._construct_result(result, name=res_name) + + def _construct_result(self, result, name): + """ + Construct an appropriately-wrapped result from the ArrayLike result + of an arithmetic-like operation. + """ + raise AbstractMethodError(self) diff --git a/shared/package-files/7a/7a70e07fcda238788ba06fd726489aaddb4771d23aed5d684265c050b6e43d6c/blob b/shared/package-files/7a/7a70e07fcda238788ba06fd726489aaddb4771d23aed5d684265c050b6e43d6c/blob new file mode 100644 index 0000000000000000000000000000000000000000..6aab0849469666395a951b36aaff19e2b674bdd3 --- /dev/null +++ b/shared/package-files/7a/7a70e07fcda238788ba06fd726489aaddb4771d23aed5d684265c050b6e43d6c/blob @@ -0,0 +1,500 @@ +"""PageRank analysis of graph structure. """ +from warnings import warn + +import networkx as nx + +__all__ = ["pagerank", "google_matrix"] + + +@nx._dispatch +def pagerank( + G, + alpha=0.85, + personalization=None, + max_iter=100, + tol=1.0e-6, + nstart=None, + weight="weight", + dangling=None, +): + """Returns the PageRank of the nodes in the graph. + + PageRank computes a ranking of the nodes in the graph G based on + the structure of the incoming links. It was originally designed as + an algorithm to rank web pages. + + Parameters + ---------- + G : graph + A NetworkX graph. Undirected graphs will be converted to a directed + graph with two directed edges for each undirected edge. + + alpha : float, optional + Damping parameter for PageRank, default=0.85. + + personalization: dict, optional + The "personalization vector" consisting of a dictionary with a + key some subset of graph nodes and personalization value each of those. + At least one personalization value must be non-zero. + If not specified, a nodes personalization value will be zero. + By default, a uniform distribution is used. + + max_iter : integer, optional + Maximum number of iterations in power method eigenvalue solver. + + tol : float, optional + Error tolerance used to check convergence in power method solver. + The iteration will stop after a tolerance of ``len(G) * tol`` is reached. + + nstart : dictionary, optional + Starting value of PageRank iteration for each node. + + weight : key, optional + Edge data key to use as weight. If None weights are set to 1. + + dangling: dict, optional + The outedges to be assigned to any "dangling" nodes, i.e., nodes without + any outedges. The dict key is the node the outedge points to and the dict + value is the weight of that outedge. By default, dangling nodes are given + outedges according to the personalization vector (uniform if not + specified). This must be selected to result in an irreducible transition + matrix (see notes under google_matrix). It may be common to have the + dangling dict to be the same as the personalization dict. + + + Returns + ------- + pagerank : dictionary + Dictionary of nodes with PageRank as value + + Examples + -------- + >>> G = nx.DiGraph(nx.path_graph(4)) + >>> pr = nx.pagerank(G, alpha=0.9) + + Notes + ----- + The eigenvector calculation is done by the power iteration method + and has no guarantee of convergence. The iteration will stop after + an error tolerance of ``len(G) * tol`` has been reached. If the + number of iterations exceed `max_iter`, a + :exc:`networkx.exception.PowerIterationFailedConvergence` exception + is raised. + + The PageRank algorithm was designed for directed graphs but this + algorithm does not check if the input graph is directed and will + execute on undirected graphs by converting each edge in the + directed graph to two edges. + + See Also + -------- + google_matrix + + Raises + ------ + PowerIterationFailedConvergence + If the algorithm fails to converge to the specified tolerance + within the specified number of iterations of the power iteration + method. + + References + ---------- + .. [1] A. Langville and C. Meyer, + "A survey of eigenvector methods of web information retrieval." + http://citeseer.ist.psu.edu/713792.html + .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, + The PageRank citation ranking: Bringing order to the Web. 1999 + http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf + + """ + return _pagerank_scipy( + G, alpha, personalization, max_iter, tol, nstart, weight, dangling + ) + + +def _pagerank_python( + G, + alpha=0.85, + personalization=None, + max_iter=100, + tol=1.0e-6, + nstart=None, + weight="weight", + dangling=None, +): + if len(G) == 0: + return {} + + D = G.to_directed() + + # Create a copy in (right) stochastic form + W = nx.stochastic_graph(D, weight=weight) + N = W.number_of_nodes() + + # Choose fixed starting vector if not given + if nstart is None: + x = dict.fromkeys(W, 1.0 / N) + else: + # Normalized nstart vector + s = sum(nstart.values()) + x = {k: v / s for k, v in nstart.items()} + + if personalization is None: + # Assign uniform personalization vector if not given + p = dict.fromkeys(W, 1.0 / N) + else: + s = sum(personalization.values()) + p = {k: v / s for k, v in personalization.items()} + + if dangling is None: + # Use personalization vector if dangling vector not specified + dangling_weights = p + else: + s = sum(dangling.values()) + dangling_weights = {k: v / s for k, v in dangling.items()} + dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0] + + # power iteration: make up to max_iter iterations + for _ in range(max_iter): + xlast = x + x = dict.fromkeys(xlast.keys(), 0) + danglesum = alpha * sum(xlast[n] for n in dangling_nodes) + for n in x: + # this matrix multiply looks odd because it is + # doing a left multiply x^T=xlast^T*W + for _, nbr, wt in W.edges(n, data=weight): + x[nbr] += alpha * xlast[n] * wt + x[n] += danglesum * dangling_weights.get(n, 0) + (1.0 - alpha) * p.get(n, 0) + # check convergence, l1 norm + err = sum(abs(x[n] - xlast[n]) for n in x) + if err < N * tol: + return x + raise nx.PowerIterationFailedConvergence(max_iter) + + +@nx._dispatch +def google_matrix( + G, alpha=0.85, personalization=None, nodelist=None, weight="weight", dangling=None +): + """Returns the Google matrix of the graph. + + Parameters + ---------- + G : graph + A NetworkX graph. Undirected graphs will be converted to a directed + graph with two directed edges for each undirected edge. + + alpha : float + The damping factor. + + personalization: dict, optional + The "personalization vector" consisting of a dictionary with a + key some subset of graph nodes and personalization value each of those. + At least one personalization value must be non-zero. + If not specified, a nodes personalization value will be zero. + By default, a uniform distribution is used. + + nodelist : list, optional + The rows and columns are ordered according to the nodes in nodelist. + If nodelist is None, then the ordering is produced by G.nodes(). + + weight : key, optional + Edge data key to use as weight. If None weights are set to 1. + + dangling: dict, optional + The outedges to be assigned to any "dangling" nodes, i.e., nodes without + any outedges. The dict key is the node the outedge points to and the dict + value is the weight of that outedge. By default, dangling nodes are given + outedges according to the personalization vector (uniform if not + specified) This must be selected to result in an irreducible transition + matrix (see notes below). It may be common to have the dangling dict to + be the same as the personalization dict. + + Returns + ------- + A : 2D NumPy ndarray + Google matrix of the graph + + Notes + ----- + The array returned represents the transition matrix that describes the + Markov chain used in PageRank. For PageRank to converge to a unique + solution (i.e., a unique stationary distribution in a Markov chain), the + transition matrix must be irreducible. In other words, it must be that + there exists a path between every pair of nodes in the graph, or else there + is the potential of "rank sinks." + + This implementation works with Multi(Di)Graphs. For multigraphs the + weight between two nodes is set to be the sum of all edge weights + between those nodes. + + See Also + -------- + pagerank + """ + import numpy as np + + if nodelist is None: + nodelist = list(G) + + A = nx.to_numpy_array(G, nodelist=nodelist, weight=weight) + N = len(G) + if N == 0: + return A + + # Personalization vector + if personalization is None: + p = np.repeat(1.0 / N, N) + else: + p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float) + if p.sum() == 0: + raise ZeroDivisionError + p /= p.sum() + + # Dangling nodes + if dangling is None: + dangling_weights = p + else: + # Convert the dangling dictionary into an array in nodelist order + dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float) + dangling_weights /= dangling_weights.sum() + dangling_nodes = np.where(A.sum(axis=1) == 0)[0] + + # Assign dangling_weights to any dangling nodes (nodes with no out links) + A[dangling_nodes] = dangling_weights + + A /= A.sum(axis=1)[:, np.newaxis] # Normalize rows to sum to 1 + + return alpha * A + (1 - alpha) * p + + +def _pagerank_numpy( + G, alpha=0.85, personalization=None, weight="weight", dangling=None +): + """Returns the PageRank of the nodes in the graph. + + PageRank computes a ranking of the nodes in the graph G based on + the structure of the incoming links. It was originally designed as + an algorithm to rank web pages. + + Parameters + ---------- + G : graph + A NetworkX graph. Undirected graphs will be converted to a directed + graph with two directed edges for each undirected edge. + + alpha : float, optional + Damping parameter for PageRank, default=0.85. + + personalization: dict, optional + The "personalization vector" consisting of a dictionary with a + key some subset of graph nodes and personalization value each of those. + At least one personalization value must be non-zero. + If not specified, a nodes personalization value will be zero. + By default, a uniform distribution is used. + + weight : key, optional + Edge data key to use as weight. If None weights are set to 1. + + dangling: dict, optional + The outedges to be assigned to any "dangling" nodes, i.e., nodes without + any outedges. The dict key is the node the outedge points to and the dict + value is the weight of that outedge. By default, dangling nodes are given + outedges according to the personalization vector (uniform if not + specified) This must be selected to result in an irreducible transition + matrix (see notes under google_matrix). It may be common to have the + dangling dict to be the same as the personalization dict. + + Returns + ------- + pagerank : dictionary + Dictionary of nodes with PageRank as value. + + Examples + -------- + >>> from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_numpy + >>> G = nx.DiGraph(nx.path_graph(4)) + >>> pr = _pagerank_numpy(G, alpha=0.9) + + Notes + ----- + The eigenvector calculation uses NumPy's interface to the LAPACK + eigenvalue solvers. This will be the fastest and most accurate + for small graphs. + + This implementation works with Multi(Di)Graphs. For multigraphs the + weight between two nodes is set to be the sum of all edge weights + between those nodes. + + See Also + -------- + pagerank, google_matrix + + References + ---------- + .. [1] A. Langville and C. Meyer, + "A survey of eigenvector methods of web information retrieval." + http://citeseer.ist.psu.edu/713792.html + .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, + The PageRank citation ranking: Bringing order to the Web. 1999 + http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf + """ + import numpy as np + + if len(G) == 0: + return {} + M = google_matrix( + G, alpha, personalization=personalization, weight=weight, dangling=dangling + ) + # use numpy LAPACK solver + eigenvalues, eigenvectors = np.linalg.eig(M.T) + ind = np.argmax(eigenvalues) + # eigenvector of largest eigenvalue is at ind, normalized + largest = np.array(eigenvectors[:, ind]).flatten().real + norm = largest.sum() + return dict(zip(G, map(float, largest / norm))) + + +def _pagerank_scipy( + G, + alpha=0.85, + personalization=None, + max_iter=100, + tol=1.0e-6, + nstart=None, + weight="weight", + dangling=None, +): + """Returns the PageRank of the nodes in the graph. + + PageRank computes a ranking of the nodes in the graph G based on + the structure of the incoming links. It was originally designed as + an algorithm to rank web pages. + + Parameters + ---------- + G : graph + A NetworkX graph. Undirected graphs will be converted to a directed + graph with two directed edges for each undirected edge. + + alpha : float, optional + Damping parameter for PageRank, default=0.85. + + personalization: dict, optional + The "personalization vector" consisting of a dictionary with a + key some subset of graph nodes and personalization value each of those. + At least one personalization value must be non-zero. + If not specified, a nodes personalization value will be zero. + By default, a uniform distribution is used. + + max_iter : integer, optional + Maximum number of iterations in power method eigenvalue solver. + + tol : float, optional + Error tolerance used to check convergence in power method solver. + The iteration will stop after a tolerance of ``len(G) * tol`` is reached. + + nstart : dictionary, optional + Starting value of PageRank iteration for each node. + + weight : key, optional + Edge data key to use as weight. If None weights are set to 1. + + dangling: dict, optional + The outedges to be assigned to any "dangling" nodes, i.e., nodes without + any outedges. The dict key is the node the outedge points to and the dict + value is the weight of that outedge. By default, dangling nodes are given + outedges according to the personalization vector (uniform if not + specified) This must be selected to result in an irreducible transition + matrix (see notes under google_matrix). It may be common to have the + dangling dict to be the same as the personalization dict. + + Returns + ------- + pagerank : dictionary + Dictionary of nodes with PageRank as value + + Examples + -------- + >>> from networkx.algorithms.link_analysis.pagerank_alg import _pagerank_scipy + >>> G = nx.DiGraph(nx.path_graph(4)) + >>> pr = _pagerank_scipy(G, alpha=0.9) + + Notes + ----- + The eigenvector calculation uses power iteration with a SciPy + sparse matrix representation. + + This implementation works with Multi(Di)Graphs. For multigraphs the + weight between two nodes is set to be the sum of all edge weights + between those nodes. + + See Also + -------- + pagerank + + Raises + ------ + PowerIterationFailedConvergence + If the algorithm fails to converge to the specified tolerance + within the specified number of iterations of the power iteration + method. + + References + ---------- + .. [1] A. Langville and C. Meyer, + "A survey of eigenvector methods of web information retrieval." + http://citeseer.ist.psu.edu/713792.html + .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, + The PageRank citation ranking: Bringing order to the Web. 1999 + http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf + """ + import numpy as np + import scipy as sp + import scipy.sparse # call as sp.sparse + + N = len(G) + if N == 0: + return {} + + nodelist = list(G) + A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float) + S = A.sum(axis=1) + S[S != 0] = 1.0 / S[S != 0] + # TODO: csr_array + Q = sp.sparse.csr_array(sp.sparse.spdiags(S.T, 0, *A.shape)) + A = Q @ A + + # initial vector + if nstart is None: + x = np.repeat(1.0 / N, N) + else: + x = np.array([nstart.get(n, 0) for n in nodelist], dtype=float) + x /= x.sum() + + # Personalization vector + if personalization is None: + p = np.repeat(1.0 / N, N) + else: + p = np.array([personalization.get(n, 0) for n in nodelist], dtype=float) + if p.sum() == 0: + raise ZeroDivisionError + p /= p.sum() + # Dangling nodes + if dangling is None: + dangling_weights = p + else: + # Convert the dangling dictionary into an array in nodelist order + dangling_weights = np.array([dangling.get(n, 0) for n in nodelist], dtype=float) + dangling_weights /= dangling_weights.sum() + is_dangling = np.where(S == 0)[0] + + # power iteration: make up to max_iter iterations + for _ in range(max_iter): + xlast = x + x = alpha * (x @ A + sum(x[is_dangling]) * dangling_weights) + (1 - alpha) * p + # check convergence, l1 norm + err = np.absolute(x - xlast).sum() + if err < N * tol: + return dict(zip(nodelist, map(float, x))) + raise nx.PowerIterationFailedConvergence(max_iter) diff --git a/shared/package-files/7a/7a71a891c68efec78ea5cab4590d19693974abec4d3d8b7c8017bb5d2713726f/blob b/shared/package-files/7a/7a71a891c68efec78ea5cab4590d19693974abec4d3d8b7c8017bb5d2713726f/blob new file mode 100644 index 0000000000000000000000000000000000000000..c0965932b583a3920645d91f5fc7164f1cfed4aa --- /dev/null +++ b/shared/package-files/7a/7a71a891c68efec78ea5cab4590d19693974abec4d3d8b7c8017bb5d2713726f/blob @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API resize_ { + using schema = const at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::resize_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "resize_(Tensor(a!) self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!)") + static const at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format); + static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format); +}; + +struct TORCH_API resize_out { + using schema = const at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::optional, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::resize") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "resize.out(Tensor self, SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)") + static const at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format, const at::Tensor & out); + static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format, const at::Tensor & out); +}; + +struct TORCH_API resize { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::resize") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "resize(Tensor self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::optional memory_format); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7a/7a7388de63a2187903b749720f8fa9b22b74a5f51d8b40cdd157684b004cdcae/blob b/shared/package-files/7a/7a7388de63a2187903b749720f8fa9b22b74a5f51d8b40cdd157684b004cdcae/blob new file mode 100644 index 0000000000000000000000000000000000000000..45cb33b480344b2da7cb0254de08553a93139ba7 --- /dev/null +++ b/shared/package-files/7a/7a7388de63a2187903b749720f8fa9b22b74a5f51d8b40cdd157684b004cdcae/blob @@ -0,0 +1,126 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once +#include +#include + +// This file contains template metaprogramming things that are used for our +// batching rules. +// +// See NOTE: [vmap plumbing] for more details on why this is necessary. +// The plumbing has a bunch of metaprogramming hacks for determining the signature +// of a batching rule from the signature of the operator, many of which use the +// helper functions in this file. + +namespace at::functorch { + +// Metaprogramming things +template using typelist = c10::guts::typelist::typelist; +template using head_t = c10::guts::typelist::head_t; +template using concat_t = c10::guts::typelist::concat_t; +template class debug_t; + +// tail operation +template +struct tail final { + static_assert(c10::guts::false_t::value, + "In typelist::tail, the T argument must be typelist<...>."); +}; +template +struct tail> final { + using type = typelist; +}; +template using tail_t = typename tail::type; + +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext { + using type = Next; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, optional, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext&, optional, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext&, optional, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, optional, Next, Tail> { + using type = Tail; +}; +template struct RemoveBatchDimAfterTensor { + using first = head_t; + using next = tail_t; + using second = head_t; + using tail = tail_t; + + using type = concat_t< + typelist, + typename RemoveBatchDimAfterTensor< + typename IfFirstIsTensorAndSecondisBatchDimThenTailElseNext::type + >::type + >; +}; +template struct RemoveBatchDimAfterTensor> { + using type = typelist; +}; +template <> struct RemoveBatchDimAfterTensor> { + using type = typelist<>; +}; +template using remove_batch_dim_after_tensor_t = typename RemoveBatchDimAfterTensor::type; + +template struct UnpackSingleItemTuple { + using type = T; +}; +template struct UnpackSingleItemTuple> { + using type = T; +}; +template using unpack_single_item_tuple_t = typename UnpackSingleItemTuple::type; + +template struct BuildFunctionHelper; +template struct BuildFunctionHelper> { + using type = Return(Args...); +}; +template +struct BuildFunction { + using type = typename BuildFunctionHelper>::type; +}; +template using build_function_t = typename BuildFunction::type; + + +template struct ToOperatorType { + using batch_rule_return_type = typename c10::guts::function_traits::return_type; + using batch_rule_parameter_types = typename c10::guts::function_traits::parameter_types; + + using operator_parameter_types = remove_batch_dim_after_tensor_t; + using operator_return_type = + unpack_single_item_tuple_t< + c10::guts::typelist::to_tuple_t< + remove_batch_dim_after_tensor_t< + c10::guts::typelist::from_tuple_t>>>; + + using type = build_function_t; +}; +template using to_operator_t = typename ToOperatorType::type; + +} // namespace at::functorch diff --git a/shared/package-files/7a/7a74ae923e3a63ef8a675e2877f8d93c4ce752b4a18e21c5cd6be9b04f2ce10b/blob b/shared/package-files/7a/7a74ae923e3a63ef8a675e2877f8d93c4ce752b4a18e21c5cd6be9b04f2ce10b/blob new file mode 100644 index 0000000000000000000000000000000000000000..3f606ca57d2e524e55cf373f34584a060ff6c7f2 --- /dev/null +++ b/shared/package-files/7a/7a74ae923e3a63ef8a675e2877f8d93c4ce752b4a18e21c5cd6be9b04f2ce10b/blob @@ -0,0 +1,10 @@ +_ruamel_yaml.cpython-310-x86_64-linux-gnu.so,sha256=8eX3v-pIQi3cJ2DuFzp7Sr7S6f7_7Wun3SGAMzlo0Pw,403256 +ruamel.yaml.clib-0.2.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ruamel.yaml.clib-0.2.6.dist-info/LICENSE,sha256=FhdNLPjC7kuQC_hXMQa8YcHOAJLaT6eBzA7oEEekZTk,1121 +ruamel.yaml.clib-0.2.6.dist-info/METADATA,sha256=ZsGCk_9RagO-_hszTlZD4QxFOu8Ym6johNuAX74DeKw,2076 +ruamel.yaml.clib-0.2.6.dist-info/RECORD,, +ruamel.yaml.clib-0.2.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ruamel.yaml.clib-0.2.6.dist-info/WHEEL,sha256=nTy_Z8ivGEB6qFwVLg7_h6rq0Jt0JU5Pz2cL2_FjSMQ,105 +ruamel.yaml.clib-0.2.6.dist-info/direct_url.json,sha256=07wKVmmdQlFkM16ZRiYTgQaausghmlivrmfKqXEiXhA,76 +ruamel.yaml.clib-0.2.6.dist-info/namespace_packages.txt,sha256=uMzCdGHNdow7_inOx6rZaxG6N45cVWHErU0hjitvehs,19 +ruamel.yaml.clib-0.2.6.dist-info/top_level.txt,sha256=1sJba3IGd2sab3u_6kWyNPS8yG_AHtP0JdmaDoB4XB0,20 diff --git a/shared/package-files/7a/7a751488c91f6481f89a54c936d51c7024be31e9ed0b29560ee5c25516b0fb4e/blob b/shared/package-files/7a/7a751488c91f6481f89a54c936d51c7024be31e9ed0b29560ee5c25516b0fb4e/blob new file mode 100644 index 0000000000000000000000000000000000000000..3b1ae80534ae6e2dec7434fd6ee4ede502136175 --- /dev/null +++ b/shared/package-files/7a/7a751488c91f6481f89a54c936d51c7024be31e9ed0b29560ee5c25516b0fb4e/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API bool retains_grad(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/7a/7a75372439650185d5b1a48c8b1aedce25eae1ba27ac205cc43cf4963db75b7a/blob b/shared/package-files/7a/7a75372439650185d5b1a48c8b1aedce25eae1ba27ac205cc43cf4963db75b7a/blob new file mode 100644 index 0000000000000000000000000000000000000000..5da8f7161a0a9e8883e9b492588613d193063513 --- /dev/null +++ b/shared/package-files/7a/7a75372439650185d5b1a48c8b1aedce25eae1ba27ac205cc43cf4963db75b7a/blob @@ -0,0 +1,711 @@ +"""Implementation of namespace-related magic functions. +""" +#----------------------------------------------------------------------------- +# Copyright (c) 2012 The IPython Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Stdlib +import gc +import re +import sys + +# Our own packages +from IPython.core import page +from IPython.core.error import StdinNotImplementedError, UsageError +from IPython.core.magic import Magics, magics_class, line_magic +from IPython.testing.skipdoctest import skip_doctest +from IPython.utils.encoding import DEFAULT_ENCODING +from IPython.utils.openpy import read_py_file +from IPython.utils.path import get_py_filename + +#----------------------------------------------------------------------------- +# Magic implementation classes +#----------------------------------------------------------------------------- + +@magics_class +class NamespaceMagics(Magics): + """Magics to manage various aspects of the user's namespace. + + These include listing variables, introspecting into them, etc. + """ + + @line_magic + def pinfo(self, parameter_s='', namespaces=None): + """Provide detailed information about an object. + + '%pinfo object' is just a synonym for object? or ?object.""" + + #print 'pinfo par: <%s>' % parameter_s # dbg + # detail_level: 0 -> obj? , 1 -> obj?? + detail_level = 0 + # We need to detect if we got called as 'pinfo pinfo foo', which can + # happen if the user types 'pinfo foo?' at the cmd line. + pinfo,qmark1,oname,qmark2 = \ + re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() + if pinfo or qmark1 or qmark2: + detail_level = 1 + if "*" in oname: + self.psearch(oname) + else: + self.shell._inspect('pinfo', oname, detail_level=detail_level, + namespaces=namespaces) + + @line_magic + def pinfo2(self, parameter_s='', namespaces=None): + """Provide extra detailed information about an object. + + '%pinfo2 object' is just a synonym for object?? or ??object.""" + self.shell._inspect('pinfo', parameter_s, detail_level=1, + namespaces=namespaces) + + @skip_doctest + @line_magic + def pdef(self, parameter_s='', namespaces=None): + """Print the call signature for any callable object. + + If the object is a class, print the constructor information. + + Examples + -------- + :: + + In [3]: %pdef urllib.urlopen + urllib.urlopen(url, data=None, proxies=None) + """ + self.shell._inspect('pdef',parameter_s, namespaces) + + @line_magic + def pdoc(self, parameter_s='', namespaces=None): + """Print the docstring for an object. + + If the given object is a class, it will print both the class and the + constructor docstrings.""" + self.shell._inspect('pdoc',parameter_s, namespaces) + + @line_magic + def psource(self, parameter_s='', namespaces=None): + """Print (or run through pager) the source code for an object.""" + if not parameter_s: + raise UsageError('Missing object name.') + self.shell._inspect('psource',parameter_s, namespaces) + + @line_magic + def pfile(self, parameter_s='', namespaces=None): + """Print (or run through pager) the file where an object is defined. + + The file opens at the line where the object definition begins. IPython + will honor the environment variable PAGER if set, and otherwise will + do its best to print the file in a convenient form. + + If the given argument is not an object currently defined, IPython will + try to interpret it as a filename (automatically adding a .py extension + if needed). You can thus use %pfile as a syntax highlighting code + viewer.""" + + # first interpret argument as an object name + out = self.shell._inspect('pfile',parameter_s, namespaces) + # if not, try the input as a filename + if out == 'not found': + try: + filename = get_py_filename(parameter_s) + except IOError as msg: + print(msg) + return + page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False))) + + @line_magic + def psearch(self, parameter_s=''): + """Search for object in namespaces by wildcard. + + %psearch [options] PATTERN [OBJECT TYPE] + + Note: ? can be used as a synonym for %psearch, at the beginning or at + the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the + rest of the command line must be unchanged (options come first), so + for example the following forms are equivalent + + %psearch -i a* function + -i a* function? + ?-i a* function + + Arguments: + + PATTERN + + where PATTERN is a string containing * as a wildcard similar to its + use in a shell. The pattern is matched in all namespaces on the + search path. By default objects starting with a single _ are not + matched, many IPython generated objects have a single + underscore. The default is case insensitive matching. Matching is + also done on the attributes of objects and not only on the objects + in a module. + + [OBJECT TYPE] + + Is the name of a python type from the types module. The name is + given in lowercase without the ending type, ex. StringType is + written string. By adding a type here only objects matching the + given type are matched. Using all here makes the pattern match all + types (this is the default). + + Options: + + -a: makes the pattern match even objects whose names start with a + single underscore. These names are normally omitted from the + search. + + -i/-c: make the pattern case insensitive/sensitive. If neither of + these options are given, the default is read from your configuration + file, with the option ``InteractiveShell.wildcards_case_sensitive``. + If this option is not specified in your configuration file, IPython's + internal default is to do a case sensitive search. + + -e/-s NAMESPACE: exclude/search a given namespace. The pattern you + specify can be searched in any of the following namespaces: + 'builtin', 'user', 'user_global','internal', 'alias', where + 'builtin' and 'user' are the search defaults. Note that you should + not use quotes when specifying namespaces. + + -l: List all available object types for object matching. This function + can be used without arguments. + + 'Builtin' contains the python module builtin, 'user' contains all + user data, 'alias' only contain the shell aliases and no python + objects, 'internal' contains objects used by IPython. The + 'user_global' namespace is only used by embedded IPython instances, + and it contains module-level globals. You can add namespaces to the + search with -s or exclude them with -e (these options can be given + more than once). + + Examples + -------- + :: + + %psearch a* -> objects beginning with an a + %psearch -e builtin a* -> objects NOT in the builtin space starting in a + %psearch a* function -> all functions beginning with an a + %psearch re.e* -> objects beginning with an e in module re + %psearch r*.e* -> objects that start with e in modules starting in r + %psearch r*.* string -> all strings in modules beginning with r + + Case sensitive search:: + + %psearch -c a* list all object beginning with lower case a + + Show objects beginning with a single _:: + + %psearch -a _* list objects beginning with a single underscore + + List available objects:: + + %psearch -l list all available object types + """ + # default namespaces to be searched + def_search = ['user_local', 'user_global', 'builtin'] + + # Process options/args + opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True) + opt = opts.get + shell = self.shell + psearch = shell.inspector.psearch + + # select list object types + list_types = False + if 'l' in opts: + list_types = True + + # select case options + if 'i' in opts: + ignore_case = True + elif 'c' in opts: + ignore_case = False + else: + ignore_case = not shell.wildcards_case_sensitive + + # Build list of namespaces to search from user options + def_search.extend(opt('s',[])) + ns_exclude = ns_exclude=opt('e',[]) + ns_search = [nm for nm in def_search if nm not in ns_exclude] + + # Call the actual search + try: + psearch(args,shell.ns_table,ns_search, + show_all=opt('a'),ignore_case=ignore_case, list_types=list_types) + except: + shell.showtraceback() + + @skip_doctest + @line_magic + def who_ls(self, parameter_s=''): + """Return a sorted list of all interactive variables. + + If arguments are given, only variables of types matching these + arguments are returned. + + Examples + -------- + Define two variables and list them with who_ls:: + + In [1]: alpha = 123 + + In [2]: beta = 'test' + + In [3]: %who_ls + Out[3]: ['alpha', 'beta'] + + In [4]: %who_ls int + Out[4]: ['alpha'] + + In [5]: %who_ls str + Out[5]: ['beta'] + """ + + user_ns = self.shell.user_ns + user_ns_hidden = self.shell.user_ns_hidden + nonmatching = object() # This can never be in user_ns + out = [ i for i in user_ns + if not i.startswith('_') \ + and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ] + + typelist = parameter_s.split() + if typelist: + typeset = set(typelist) + out = [i for i in out if type(user_ns[i]).__name__ in typeset] + + out.sort() + return out + + @skip_doctest + @line_magic + def who(self, parameter_s=''): + """Print all interactive variables, with some minimal formatting. + + If any arguments are given, only variables whose type matches one of + these are printed. For example:: + + %who function str + + will only list functions and strings, excluding all other types of + variables. To find the proper type names, simply use type(var) at a + command line to see how python prints type names. For example: + + :: + + In [1]: type('hello')\\ + Out[1]: + + indicates that the type name for strings is 'str'. + + ``%who`` always excludes executed names loaded through your configuration + file and things which are internal to IPython. + + This is deliberate, as typically you may load many modules and the + purpose of %who is to show you only what you've manually defined. + + Examples + -------- + + Define two variables and list them with who:: + + In [1]: alpha = 123 + + In [2]: beta = 'test' + + In [3]: %who + alpha beta + + In [4]: %who int + alpha + + In [5]: %who str + beta + """ + + varlist = self.who_ls(parameter_s) + if not varlist: + if parameter_s: + print('No variables match your requested type.') + else: + print('Interactive namespace is empty.') + return + + # if we have variables, move on... + count = 0 + for i in varlist: + print(i+'\t', end=' ') + count += 1 + if count > 8: + count = 0 + print() + print() + + @skip_doctest + @line_magic + def whos(self, parameter_s=''): + """Like %who, but gives some extra information about each variable. + + The same type filtering of %who can be applied here. + + For all variables, the type is printed. Additionally it prints: + + - For {},[],(): their length. + + - For numpy arrays, a summary with shape, number of + elements, typecode and size in memory. + + - Everything else: a string representation, snipping their middle if + too long. + + Examples + -------- + Define two variables and list them with whos:: + + In [1]: alpha = 123 + + In [2]: beta = 'test' + + In [3]: %whos + Variable Type Data/Info + -------------------------------- + alpha int 123 + beta str test + """ + + varnames = self.who_ls(parameter_s) + if not varnames: + if parameter_s: + print('No variables match your requested type.') + else: + print('Interactive namespace is empty.') + return + + # if we have variables, move on... + + # for these types, show len() instead of data: + seq_types = ['dict', 'list', 'tuple'] + + # for numpy arrays, display summary info + ndarray_type = None + if 'numpy' in sys.modules: + try: + from numpy import ndarray + except ImportError: + pass + else: + ndarray_type = ndarray.__name__ + + # Find all variable names and types so we can figure out column sizes + + # some types are well known and can be shorter + abbrevs = {'IPython.core.macro.Macro' : 'Macro'} + def type_name(v): + tn = type(v).__name__ + return abbrevs.get(tn,tn) + + varlist = [self.shell.user_ns[n] for n in varnames] + + typelist = [] + for vv in varlist: + tt = type_name(vv) + + if tt=='instance': + typelist.append( abbrevs.get(str(vv.__class__), + str(vv.__class__))) + else: + typelist.append(tt) + + # column labels and # of spaces as separator + varlabel = 'Variable' + typelabel = 'Type' + datalabel = 'Data/Info' + colsep = 3 + # variable format strings + vformat = "{0:<{varwidth}}{1:<{typewidth}}" + aformat = "%s: %s elems, type `%s`, %s bytes" + # find the size of the columns to format the output nicely + varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep + typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep + # table header + print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ + ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)) + # and the table itself + kb = 1024 + Mb = 1048576 # kb**2 + for vname,var,vtype in zip(varnames,varlist,typelist): + print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ') + if vtype in seq_types: + print("n="+str(len(var))) + elif vtype == ndarray_type: + vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] + if vtype==ndarray_type: + # numpy + vsize = var.size + vbytes = vsize*var.itemsize + vdtype = var.dtype + + if vbytes < 100000: + print(aformat % (vshape, vsize, vdtype, vbytes)) + else: + print(aformat % (vshape, vsize, vdtype, vbytes), end=' ') + if vbytes < Mb: + print('(%s kb)' % (vbytes/kb,)) + else: + print('(%s Mb)' % (vbytes/Mb,)) + else: + try: + vstr = str(var) + except UnicodeEncodeError: + vstr = var.encode(DEFAULT_ENCODING, + 'backslashreplace') + except: + vstr = "" % id(var) + vstr = vstr.replace('\n', '\\n') + if len(vstr) < 50: + print(vstr) + else: + print(vstr[:25] + "<...>" + vstr[-25:]) + + @line_magic + def reset(self, parameter_s=''): + """Resets the namespace by removing all names defined by the user, if + called without arguments, or by removing some types of objects, such + as everything currently in IPython's In[] and Out[] containers (see + the parameters for details). + + Parameters + ---------- + -f + force reset without asking for confirmation. + -s + 'Soft' reset: Only clears your namespace, leaving history intact. + References to objects may be kept. By default (without this option), + we do a 'hard' reset, giving you a new session and removing all + references to objects from the current session. + --aggressive + Try to aggressively remove modules from sys.modules ; this + may allow you to reimport Python modules that have been updated and + pick up changes, but can have unintended consequences. + + in + reset input history + out + reset output history + dhist + reset directory history + array + reset only variables that are NumPy arrays + + See Also + -------- + reset_selective : invoked as ``%reset_selective`` + + Examples + -------- + :: + + In [6]: a = 1 + + In [7]: a + Out[7]: 1 + + In [8]: 'a' in get_ipython().user_ns + Out[8]: True + + In [9]: %reset -f + + In [1]: 'a' in get_ipython().user_ns + Out[1]: False + + In [2]: %reset -f in + Flushing input history + + In [3]: %reset -f dhist in + Flushing directory history + Flushing input history + + Notes + ----- + Calling this magic from clients that do not implement standard input, + such as the ipython notebook interface, will reset the namespace + without confirmation. + """ + opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list") + if "f" in opts: + ans = True + else: + try: + ans = self.shell.ask_yes_no( + "Once deleted, variables cannot be recovered. Proceed (y/[n])?", + default='n') + except StdinNotImplementedError: + ans = True + if not ans: + print('Nothing done.') + return + + if 's' in opts: # Soft reset + user_ns = self.shell.user_ns + for i in self.who_ls(): + del(user_ns[i]) + elif len(args) == 0: # Hard reset + self.shell.reset(new_session=False, aggressive=("aggressive" in opts)) + + # reset in/out/dhist/array: previously extensinions/clearcmd.py + ip = self.shell + user_ns = self.shell.user_ns # local lookup, heavily used + + for target in args: + target = target.lower() # make matches case insensitive + if target == 'out': + print("Flushing output cache (%d entries)" % len(user_ns['_oh'])) + self.shell.displayhook.flush() + + elif target == 'in': + print("Flushing input history") + pc = self.shell.displayhook.prompt_count + 1 + for n in range(1, pc): + key = '_i'+repr(n) + user_ns.pop(key,None) + user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) + hm = ip.history_manager + # don't delete these, as %save and %macro depending on the + # length of these lists to be preserved + hm.input_hist_parsed[:] = [''] * pc + hm.input_hist_raw[:] = [''] * pc + # hm has internal machinery for _i,_ii,_iii, clear it out + hm._i = hm._ii = hm._iii = hm._i00 = u'' + + elif target == 'array': + # Support cleaning up numpy arrays + try: + from numpy import ndarray + # This must be done with items and not iteritems because + # we're going to modify the dict in-place. + for x,val in list(user_ns.items()): + if isinstance(val,ndarray): + del user_ns[x] + except ImportError: + print("reset array only works if Numpy is available.") + + elif target == 'dhist': + print("Flushing directory history") + del user_ns['_dh'][:] + + else: + print("Don't know how to reset ", end=' ') + print(target + ", please run `%reset?` for details") + + gc.collect() + + @line_magic + def reset_selective(self, parameter_s=''): + """Resets the namespace by removing names defined by the user. + + Input/Output history are left around in case you need them. + + %reset_selective [-f] regex + + No action is taken if regex is not included + + Options + -f : force reset without asking for confirmation. + + See Also + -------- + reset : invoked as ``%reset`` + + Examples + -------- + We first fully reset the namespace so your output looks identical to + this example for pedagogical reasons; in practice you do not need a + full reset:: + + In [1]: %reset -f + + Now, with a clean namespace we can make a few variables and use + ``%reset_selective`` to only delete names that match our regexp:: + + In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 + + In [3]: who_ls + Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] + + In [4]: %reset_selective -f b[2-3]m + + In [5]: who_ls + Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] + + In [6]: %reset_selective -f d + + In [7]: who_ls + Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] + + In [8]: %reset_selective -f c + + In [9]: who_ls + Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] + + In [10]: %reset_selective -f b + + In [11]: who_ls + Out[11]: ['a'] + + Notes + ----- + Calling this magic from clients that do not implement standard input, + such as the ipython notebook interface, will reset the namespace + without confirmation. + """ + + opts, regex = self.parse_options(parameter_s,'f') + + if 'f' in opts: + ans = True + else: + try: + ans = self.shell.ask_yes_no( + "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", + default='n') + except StdinNotImplementedError: + ans = True + if not ans: + print('Nothing done.') + return + user_ns = self.shell.user_ns + if not regex: + print('No regex pattern specified. Nothing done.') + return + else: + try: + m = re.compile(regex) + except TypeError as e: + raise TypeError('regex must be a string or compiled pattern') from e + for i in self.who_ls(): + if m.search(i): + del(user_ns[i]) + + @line_magic + def xdel(self, parameter_s=''): + """Delete a variable, trying to clear it from anywhere that + IPython's machinery has references to it. By default, this uses + the identity of the named object in the user namespace to remove + references held under other names. The object is also removed + from the output history. + + Options + -n : Delete the specified name from all namespaces, without + checking their identity. + """ + opts, varname = self.parse_options(parameter_s,'n') + try: + self.shell.del_var(varname, ('n' in opts)) + except (NameError, ValueError) as e: + print(type(e).__name__ +": "+ str(e)) diff --git a/shared/package-files/7a/7a7579b1bded95bcea7b1d26b2cf26de333c1a0f417fac6a0143eeb3a0c93aa2/blob b/shared/package-files/7a/7a7579b1bded95bcea7b1d26b2cf26de333c1a0f417fac6a0143eeb3a0c93aa2/blob new file mode 100644 index 0000000000000000000000000000000000000000..09cc6d3732d5a84c06c7b15a7be374665183cd88 Binary files /dev/null and b/shared/package-files/7a/7a7579b1bded95bcea7b1d26b2cf26de333c1a0f417fac6a0143eeb3a0c93aa2/blob differ diff --git a/shared/package-files/7a/7a75c6c904389bef6430f0da5af8a922dddbb986798cd8dac484cff06a12f3ab/blob b/shared/package-files/7a/7a75c6c904389bef6430f0da5af8a922dddbb986798cd8dac484cff06a12f3ab/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d28ccc93f4444f3f2e0b71da01c573d4f903dbc --- /dev/null +++ b/shared/package-files/7a/7a75c6c904389bef6430f0da5af8a922dddbb986798cd8dac484cff06a12f3ab/blob @@ -0,0 +1,74 @@ +import numpy as np +from numpy.testing import assert_equal, assert_allclose +from scipy.integrate import odeint +import scipy.integrate._test_odeint_banded as banded5x5 + + +def rhs(y, t): + dydt = np.zeros_like(y) + banded5x5.banded5x5(t, y, dydt) + return dydt + + +def jac(y, t): + n = len(y) + jac = np.zeros((n, n), order='F') + banded5x5.banded5x5_jac(t, y, 1, 1, jac) + return jac + + +def bjac(y, t): + n = len(y) + bjac = np.zeros((4, n), order='F') + banded5x5.banded5x5_bjac(t, y, 1, 1, bjac) + return bjac + + +JACTYPE_FULL = 1 +JACTYPE_BANDED = 4 + + +def check_odeint(jactype): + if jactype == JACTYPE_FULL: + ml = None + mu = None + jacobian = jac + elif jactype == JACTYPE_BANDED: + ml = 2 + mu = 1 + jacobian = bjac + else: + raise ValueError(f"invalid jactype: {jactype!r}") + + y0 = np.arange(1.0, 6.0) + # These tolerances must match the tolerances used in banded5x5.f. + rtol = 1e-11 + atol = 1e-13 + dt = 0.125 + nsteps = 64 + t = dt * np.arange(nsteps+1) + + sol, info = odeint(rhs, y0, t, + Dfun=jacobian, ml=ml, mu=mu, + atol=atol, rtol=rtol, full_output=True) + yfinal = sol[-1] + odeint_nst = info['nst'][-1] + odeint_nfe = info['nfe'][-1] + odeint_nje = info['nje'][-1] + + y1 = y0.copy() + # Pure Fortran solution. y1 is modified in-place. + nst, nfe, nje = banded5x5.banded5x5_solve(y1, nsteps, dt, jactype) + + # It is likely that yfinal and y1 are *exactly* the same, but + # we'll be cautious and use assert_allclose. + assert_allclose(yfinal, y1, rtol=1e-12) + assert_equal((odeint_nst, odeint_nfe, odeint_nje), (nst, nfe, nje)) + + +def test_odeint_full_jac(): + check_odeint(JACTYPE_FULL) + + +def test_odeint_banded_jac(): + check_odeint(JACTYPE_BANDED) diff --git a/shared/package-files/7a/7a7c6052968247f06e135e7a59ea2a89823b59fc41215a371f5269af5668f746/blob b/shared/package-files/7a/7a7c6052968247f06e135e7a59ea2a89823b59fc41215a371f5269af5668f746/blob new file mode 100644 index 0000000000000000000000000000000000000000..021d791533049a65e666ae27399491e234ceec20 --- /dev/null +++ b/shared/package-files/7a/7a7c6052968247f06e135e7a59ea2a89823b59fc41215a371f5269af5668f746/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a7c6052968247f06e135e7a59ea2a89823b59fc41215a371f5269af5668f746 +size 1078969 diff --git a/shared/package-files/7a/7a7dfa5eeaeda41ab6c286608c6115b02abb9027bc126fba03f7ac2017574162/blob b/shared/package-files/7a/7a7dfa5eeaeda41ab6c286608c6115b02abb9027bc126fba03f7ac2017574162/blob new file mode 100644 index 0000000000000000000000000000000000000000..85377e361c3391f3a0516123b68cf9d800d2ddae --- /dev/null +++ b/shared/package-files/7a/7a7dfa5eeaeda41ab6c286608c6115b02abb9027bc126fba03f7ac2017574162/blob @@ -0,0 +1,81 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple max(const at::Tensor & self, int64_t dim, bool keepdim=false) { + return at::_ops::max_dim::call(self, dim, keepdim); +} + +// aten::max.dim_max(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple max_out(at::Tensor & max, at::Tensor & max_values, const at::Tensor & self, int64_t dim, bool keepdim=false) { + return at::_ops::max_dim_max::call(self, dim, keepdim, max, max_values); +} +// aten::max.dim_max(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple max_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & max, at::Tensor & max_values) { + return at::_ops::max_dim_max::call(self, dim, keepdim, max, max_values); +} + +// aten::max.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple max(const at::Tensor & self, at::Dimname dim, bool keepdim=false) { + return at::_ops::max_names_dim::call(self, dim, keepdim); +} + +// aten::max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple max_out(at::Tensor & max, at::Tensor & max_values, const at::Tensor & self, at::Dimname dim, bool keepdim=false) { + return at::_ops::max_names_dim_max::call(self, dim, keepdim, max, max_values); +} +// aten::max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple max_outf(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & max, at::Tensor & max_values) { + return at::_ops::max_names_dim_max::call(self, dim, keepdim, max, max_values); +} + +// aten::max(Tensor self) -> Tensor +inline at::Tensor max(const at::Tensor & self) { + return at::_ops::max::call(self); +} + +// aten::max.other(Tensor self, Tensor other) -> Tensor +inline at::Tensor max(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::max_other::call(self, other); +} + +// aten::max.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & max_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::max_out::call(self, other, out); +} +// aten::max.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & max_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::max_out::call(self, other, out); +} + +// aten::max.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & max_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::max_unary_out::call(self, out); +} +// aten::max.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & max_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::max_unary_out::call(self, out); +} + +} diff --git a/shared/package-files/7a/7a8154ae9f3ad51597e120db7ba5497c377dfef87d6be7fac70a0eadf9fb26d0/blob b/shared/package-files/7a/7a8154ae9f3ad51597e120db7ba5497c377dfef87d6be7fac70a0eadf9fb26d0/blob new file mode 100644 index 0000000000000000000000000000000000000000..d824a84a80eda316b680ba4e43d0f418c774af99 --- /dev/null +++ b/shared/package-files/7a/7a8154ae9f3ad51597e120db7ba5497c377dfef87d6be7fac70a0eadf9fb26d0/blob @@ -0,0 +1,246 @@ +# Created by John Travers, Robert Hetland, 2007 +""" Test functions for rbf module """ + +import numpy as np + +from scipy._lib._array_api import assert_array_almost_equal, assert_almost_equal + +from numpy import linspace, sin, cos, exp, allclose +from scipy.interpolate._rbf import Rbf +from scipy._lib._testutils import _run_concurrent_barrier + +import pytest + + +FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', + 'cubic', 'quintic', 'thin-plate', 'linear') + + +def check_rbf1d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (1D) + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y, function=function) + yi = rbf(x) + assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0], check_0d=False) + + +def check_rbf2d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (2D). + rng = np.random.RandomState(1234) + x = rng.rand(50,1)*4-2 + y = rng.rand(50,1)*4-2 + z = x*exp(-x**2-1j*y**2) + rbf = Rbf(x, y, z, epsilon=2, function=function) + zi = rbf(x, y) + zi.shape = x.shape + assert_array_almost_equal(z, zi) + + +def check_rbf3d_interpolation(function): + # Check that the Rbf function interpolates through the nodes (3D). + rng = np.random.RandomState(1234) + x = rng.rand(50, 1)*4 - 2 + y = rng.rand(50, 1)*4 - 2 + z = rng.rand(50, 1)*4 - 2 + d = x*exp(-x**2 - y**2) + rbf = Rbf(x, y, z, d, epsilon=2, function=function) + di = rbf(x, y, z) + di.shape = x.shape + assert_array_almost_equal(di, d) + + +def test_rbf_interpolation(): + for function in FUNCTIONS: + check_rbf1d_interpolation(function) + check_rbf2d_interpolation(function) + check_rbf3d_interpolation(function) + + +def check_2drbf1d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (1D) + x = linspace(0, 10, 9) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, function=function, mode='N-D') + yi = rbf(x) + assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0]) + + +def check_2drbf2d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (2D). + rng = np.random.RandomState(1234) + x = rng.rand(50, ) * 4 - 2 + y = rng.rand(50, ) * 4 - 2 + z0 = x * exp(-x ** 2 - 1j * y ** 2) + z1 = y * exp(-y ** 2 - 1j * x ** 2) + z = np.vstack([z0, z1]).T + rbf = Rbf(x, y, z, epsilon=2, function=function, mode='N-D') + zi = rbf(x, y) + zi.shape = z.shape + assert_array_almost_equal(z, zi) + + +def check_2drbf3d_interpolation(function): + # Check that the 2-D Rbf function interpolates through the nodes (3D). + rng = np.random.RandomState(1234) + x = rng.rand(50, ) * 4 - 2 + y = rng.rand(50, ) * 4 - 2 + z = rng.rand(50, ) * 4 - 2 + d0 = x * exp(-x ** 2 - y ** 2) + d1 = y * exp(-y ** 2 - x ** 2) + d = np.vstack([d0, d1]).T + rbf = Rbf(x, y, z, d, epsilon=2, function=function, mode='N-D') + di = rbf(x, y, z) + di.shape = d.shape + assert_array_almost_equal(di, d) + + +def test_2drbf_interpolation(): + for function in FUNCTIONS: + check_2drbf1d_interpolation(function) + check_2drbf2d_interpolation(function) + check_2drbf3d_interpolation(function) + + +def check_rbf1d_regularity(function, atol): + # Check that the Rbf function approximates a smooth function well away + # from the nodes. + x = linspace(0, 10, 9) + y = sin(x) + rbf = Rbf(x, y, function=function) + xi = linspace(0, 10, 100) + yi = rbf(xi) + msg = f"abs-diff: {abs(yi - sin(xi)).max():f}" + assert allclose(yi, sin(xi), atol=atol), msg + + +def test_rbf_regularity(): + tolerances = { + 'multiquadric': 0.1, + 'inverse multiquadric': 0.15, + 'gaussian': 0.15, + 'cubic': 0.15, + 'quintic': 0.1, + 'thin-plate': 0.1, + 'linear': 0.2 + } + for function in FUNCTIONS: + check_rbf1d_regularity(function, tolerances.get(function, 1e-2)) + + +def check_2drbf1d_regularity(function, atol): + # Check that the 2-D Rbf function approximates a smooth function well away + # from the nodes. + x = linspace(0, 10, 9) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, function=function, mode='N-D') + xi = linspace(0, 10, 100) + yi = rbf(xi) + msg = f"abs-diff: {abs(yi - np.vstack([sin(xi), cos(xi)]).T).max():f}" + assert allclose(yi, np.vstack([sin(xi), cos(xi)]).T, atol=atol), msg + + +def test_2drbf_regularity(): + tolerances = { + 'multiquadric': 0.1, + 'inverse multiquadric': 0.15, + 'gaussian': 0.15, + 'cubic': 0.15, + 'quintic': 0.1, + 'thin-plate': 0.15, + 'linear': 0.2 + } + for function in FUNCTIONS: + check_2drbf1d_regularity(function, tolerances.get(function, 1e-2)) + + +def check_rbf1d_stability(function): + # Check that the Rbf function with default epsilon is not subject + # to overshoot. Regression for issue #4523. + # + # Generate some data (fixed random seed hence deterministic) + rng = np.random.RandomState(1234) + x = np.linspace(0, 10, 50) + z = x + 4.0 * rng.randn(len(x)) + + rbf = Rbf(x, z, function=function) + xi = np.linspace(0, 10, 1000) + yi = rbf(xi) + + # subtract the linear trend and make sure there no spikes + assert np.abs(yi-xi).max() / np.abs(z-x).max() < 1.1 + +def test_rbf_stability(): + for function in FUNCTIONS: + check_rbf1d_stability(function) + + +def test_default_construction(): + # Check that the Rbf class can be constructed with the default + # multiquadric basis function. Regression test for ticket #1228. + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_function_is_callable(): + # Check that the Rbf class can be constructed with function=callable. + x = linspace(0,10,9) + y = sin(x) + def linfunc(x): + return x + rbf = Rbf(x, y, function=linfunc) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_two_arg_function_is_callable(): + # Check that the Rbf class can be constructed with a two argument + # function=callable. + def _func(self, r): + return self.epsilon + r + + x = linspace(0,10,9) + y = sin(x) + rbf = Rbf(x, y, function=_func) + yi = rbf(x) + assert_array_almost_equal(y, yi) + + +def test_rbf_epsilon_none(): + x = linspace(0, 10, 9) + y = sin(x) + Rbf(x, y, epsilon=None) + + +def test_rbf_epsilon_none_collinear(): + # Check that collinear points in one dimension doesn't cause an error + # due to epsilon = 0 + x = [1, 2, 3] + y = [4, 4, 4] + z = [5, 6, 7] + rbf = Rbf(x, y, z, epsilon=None) + assert rbf.epsilon > 0 + + +@pytest.mark.thread_unsafe +def test_rbf_concurrency(): + x = linspace(0, 10, 100) + y0 = sin(x) + y1 = cos(x) + y = np.vstack([y0, y1]).T + rbf = Rbf(x, y, mode='N-D') + + def worker_fn(_, interp, xp): + interp(xp) + + _run_concurrent_barrier(10, worker_fn, rbf, x) + diff --git a/shared/package-files/7a/7a82ee5e298574ea95c9e030a06c9ddfade14c9e9f36c0d6ba7d424704d07c82/blob b/shared/package-files/7a/7a82ee5e298574ea95c9e030a06c9ddfade14c9e9f36c0d6ba7d424704d07c82/blob new file mode 100644 index 0000000000000000000000000000000000000000..392a6e27681064f30303d5a529834ca1fc7594f5 Binary files /dev/null and b/shared/package-files/7a/7a82ee5e298574ea95c9e030a06c9ddfade14c9e9f36c0d6ba7d424704d07c82/blob differ diff --git a/shared/package-files/7a/7a858680c0c8753aad533388164f04ba3e82855ee8a8b9cfa537f01d923e49c9/blob b/shared/package-files/7a/7a858680c0c8753aad533388164f04ba3e82855ee8a8b9cfa537f01d923e49c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..fdb47abf43fb7757202223b487b5d2377ca44eb6 --- /dev/null +++ b/shared/package-files/7a/7a858680c0c8753aad533388164f04ba3e82855ee8a8b9cfa537f01d923e49c9/blob @@ -0,0 +1,211 @@ +"Test editor, coverage 35%." + +from idlelib import editor +import unittest +from collections import namedtuple +from test.support import requires +from tkinter import Tk + +Editor = editor.EditorWindow + + +class EditorWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_init(self): + e = Editor(root=self.root) + self.assertEqual(e.root, self.root) + e._close() + + +class TestGetLineIndent(unittest.TestCase): + def test_empty_lines(self): + for tabwidth in [1, 2, 4, 6, 8]: + for line in ['', '\n']: + with self.subTest(line=line, tabwidth=tabwidth): + self.assertEqual( + editor.get_line_indent(line, tabwidth=tabwidth), + (0, 0), + ) + + def test_tabwidth_4(self): + # (line, (raw, effective)) + tests = (('no spaces', (0, 0)), + # Internal space isn't counted. + (' space test', (4, 4)), + ('\ttab test', (1, 4)), + ('\t\tdouble tabs test', (2, 8)), + # Different results when mixing tabs and spaces. + (' \tmixed test', (5, 8)), + (' \t mixed test', (5, 6)), + ('\t mixed test', (5, 8)), + # Spaces not divisible by tabwidth. + (' \tmixed test', (3, 4)), + (' \t mixed test', (3, 5)), + ('\t mixed test', (3, 6)), + # Only checks spaces and tabs. + ('\nnewline test', (0, 0))) + + for line, expected in tests: + with self.subTest(line=line): + self.assertEqual( + editor.get_line_indent(line, tabwidth=4), + expected, + ) + + def test_tabwidth_8(self): + # (line, (raw, effective)) + tests = (('no spaces', (0, 0)), + # Internal space isn't counted. + (' space test', (8, 8)), + ('\ttab test', (1, 8)), + ('\t\tdouble tabs test', (2, 16)), + # Different results when mixing tabs and spaces. + (' \tmixed test', (9, 16)), + (' \t mixed test', (9, 10)), + ('\t mixed test', (9, 16)), + # Spaces not divisible by tabwidth. + (' \tmixed test', (3, 8)), + (' \t mixed test', (3, 9)), + ('\t mixed test', (3, 10)), + # Only checks spaces and tabs. + ('\nnewline test', (0, 0))) + + for line, expected in tests: + with self.subTest(line=line): + self.assertEqual( + editor.get_line_indent(line, tabwidth=8), + expected, + ) + + +def insert(text, string): + text.delete('1.0', 'end') + text.insert('end', string) + text.update() # Force update for colorizer to finish. + + +class IndentAndNewlineTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.window = Editor(root=cls.root) + cls.window.indentwidth = 2 + cls.window.tabwidth = 2 + + @classmethod + def tearDownClass(cls): + cls.window._close() + del cls.window + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_indent_and_newline_event(self): + eq = self.assertEqual + w = self.window + text = w.text + get = text.get + nl = w.newline_and_indent_event + + TestInfo = namedtuple('Tests', ['label', 'text', 'expected', 'mark']) + + tests = (TestInfo('Empty line inserts with no indent.', + ' \n def __init__(self):', + '\n \n def __init__(self):\n', + '1.end'), + TestInfo('Inside bracket before space, deletes space.', + ' def f1(self, a, b):', + ' def f1(self,\n a, b):\n', + '1.14'), + TestInfo('Inside bracket after space, deletes space.', + ' def f1(self, a, b):', + ' def f1(self,\n a, b):\n', + '1.15'), + TestInfo('Inside string with one line - no indent.', + ' """Docstring."""', + ' """Docstring.\n"""\n', + '1.15'), + TestInfo('Inside string with more than one line.', + ' """Docstring.\n Docstring Line 2"""', + ' """Docstring.\n Docstring Line 2\n """\n', + '2.18'), + TestInfo('Backslash with one line.', + 'a =\\', + 'a =\\\n \n', + '1.end'), + TestInfo('Backslash with more than one line.', + 'a =\\\n multiline\\', + 'a =\\\n multiline\\\n \n', + '2.end'), + TestInfo('Block opener - indents +1 level.', + ' def f1(self):\n pass', + ' def f1(self):\n \n pass\n', + '1.end'), + TestInfo('Block closer - dedents -1 level.', + ' def f1(self):\n pass', + ' def f1(self):\n pass\n \n', + '2.end'), + ) + + for test in tests: + with self.subTest(label=test.label): + insert(text, test.text) + text.mark_set('insert', test.mark) + nl(event=None) + eq(get('1.0', 'end'), test.expected) + + # Selected text. + insert(text, ' def f1(self, a, b):\n return a + b') + text.tag_add('sel', '1.17', '1.end') + nl(None) + # Deletes selected text before adding new line. + eq(get('1.0', 'end'), ' def f1(self, a,\n \n return a + b\n') + + +class RMenuTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.window = Editor(root=cls.root) + + @classmethod + def tearDownClass(cls): + cls.window._close() + del cls.window + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + class DummyRMenu: + def tk_popup(x, y): pass + + def test_rclick(self): + pass + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/shared/package-files/7a/7a8643261c0f4415327147e6685e0872b404ccf87ab0a10551674b3fa215259d/blob b/shared/package-files/7a/7a8643261c0f4415327147e6685e0872b404ccf87ab0a10551674b3fa215259d/blob new file mode 100644 index 0000000000000000000000000000000000000000..14348e357fed9242c314530c88daf360cd9a69bd --- /dev/null +++ b/shared/package-files/7a/7a8643261c0f4415327147e6685e0872b404ccf87ab0a10551674b3fa215259d/blob @@ -0,0 +1,1830 @@ +"""The classes for specifying and compiling a declarative visualization.""" +from __future__ import annotations + +import io +import os +import re +import inspect +import itertools +import textwrap +from contextlib import contextmanager +from collections import abc +from collections.abc import Callable, Generator +from typing import Any, List, Literal, Optional, cast +from xml.etree import ElementTree + +from cycler import cycler +import pandas as pd +from pandas import DataFrame, Series, Index +import matplotlib as mpl +from matplotlib.axes import Axes +from matplotlib.artist import Artist +from matplotlib.figure import Figure +import numpy as np +from PIL import Image + +from seaborn._marks.base import Mark +from seaborn._stats.base import Stat +from seaborn._core.data import PlotData +from seaborn._core.moves import Move +from seaborn._core.scales import Scale +from seaborn._core.subplots import Subplots +from seaborn._core.groupby import GroupBy +from seaborn._core.properties import PROPERTIES, Property +from seaborn._core.typing import ( + DataSource, + VariableSpec, + VariableSpecList, + OrderSpec, + Default, +) +from seaborn._core.exceptions import PlotSpecError +from seaborn._core.rules import categorical_order +from seaborn._compat import get_layout_engine, set_layout_engine +from seaborn.utils import _version_predates +from seaborn.rcmod import axes_style, plotting_context +from seaborn.palettes import color_palette + +from typing import TYPE_CHECKING, TypedDict +if TYPE_CHECKING: + from matplotlib.figure import SubFigure + + +default = Default() + + +# ---- Definitions for internal specs ---------------------------------------------- # + + +class Layer(TypedDict, total=False): + + mark: Mark # TODO allow list? + stat: Stat | None # TODO allow list? + move: Move | list[Move] | None + data: PlotData + source: DataSource + vars: dict[str, VariableSpec] + orient: str + legend: bool + label: str | None + + +class FacetSpec(TypedDict, total=False): + + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + wrap: int | None + + +class PairSpec(TypedDict, total=False): + + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + cross: bool + wrap: int | None + + +# --- Local helpers ---------------------------------------------------------------- # + + +@contextmanager +def theme_context(params: dict[str, Any]) -> Generator: + """Temporarily modify specifc matplotlib rcParams.""" + orig_params = {k: mpl.rcParams[k] for k in params} + color_codes = "bgrmyck" + nice_colors = [*color_palette("deep6"), (.15, .15, .15)] + orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes] + # TODO how to allow this to reflect the color cycle when relevant? + try: + mpl.rcParams.update(params) + for (code, color) in zip(color_codes, nice_colors): + mpl.colors.colorConverter.colors[code] = color + yield + finally: + mpl.rcParams.update(orig_params) + for (code, color) in zip(color_codes, orig_colors): + mpl.colors.colorConverter.colors[code] = color + + +def build_plot_signature(cls): + """ + Decorator function for giving Plot a useful signature. + + Currently this mostly saves us some duplicated typing, but we would + like eventually to have a way of registering new semantic properties, + at which point dynamic signature generation would become more important. + + """ + sig = inspect.signature(cls) + params = [ + inspect.Parameter("args", inspect.Parameter.VAR_POSITIONAL), + inspect.Parameter("data", inspect.Parameter.KEYWORD_ONLY, default=None) + ] + params.extend([ + inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None) + for name in PROPERTIES + ]) + new_sig = sig.replace(parameters=params) + cls.__signature__ = new_sig + + known_properties = textwrap.fill( + ", ".join([f"|{p}|" for p in PROPERTIES]), + width=78, subsequent_indent=" " * 8, + ) + + if cls.__doc__ is not None: # support python -OO mode + cls.__doc__ = cls.__doc__.format(known_properties=known_properties) + + return cls + + +# ---- Plot configuration ---------------------------------------------------------- # + + +class ThemeConfig(mpl.RcParams): + """ + Configuration object for the Plot.theme, using matplotlib rc parameters. + """ + THEME_GROUPS = [ + "axes", "figure", "font", "grid", "hatch", "legend", "lines", + "mathtext", "markers", "patch", "savefig", "scatter", + "xaxis", "xtick", "yaxis", "ytick", + ] + + def __init__(self): + super().__init__() + self.reset() + + @property + def _default(self) -> dict[str, Any]: + + return { + **self._filter_params(mpl.rcParamsDefault), + **axes_style("darkgrid"), + **plotting_context("notebook"), + "axes.prop_cycle": cycler("color", color_palette("deep")), + } + + def reset(self) -> None: + """Update the theme dictionary with seaborn's default values.""" + self.update(self._default) + + def update(self, other: dict[str, Any] | None = None, /, **kwds): + """Update the theme with a dictionary or keyword arguments of rc parameters.""" + if other is not None: + theme = self._filter_params(other) + else: + theme = {} + theme.update(kwds) + super().update(theme) + + def _filter_params(self, params: dict[str, Any]) -> dict[str, Any]: + """Restruct to thematic rc params.""" + return { + k: v for k, v in params.items() + if any(k.startswith(p) for p in self.THEME_GROUPS) + } + + def _html_table(self, params: dict[str, Any]) -> list[str]: + + lines = [""] + for k, v in params.items(): + row = f"" + lines.append(row) + lines.append("
{k}:{v!r}
") + return lines + + def _repr_html_(self) -> str: + + repr = [ + "
", + "
", + *self._html_table(self), + "
", + "
", + ] + return "\n".join(repr) + + +class DisplayConfig(TypedDict): + """Configuration for IPython's rich display hooks.""" + format: Literal["png", "svg"] + scaling: float + hidpi: bool + + +class PlotConfig: + """Configuration for default behavior / appearance of class:`Plot` instances.""" + def __init__(self): + + self._theme = ThemeConfig() + self._display = {"format": "png", "scaling": .85, "hidpi": True} + + @property + def theme(self) -> dict[str, Any]: + """ + Dictionary of base theme parameters for :class:`Plot`. + + Keys and values correspond to matplotlib rc params, as documented here: + https://matplotlib.org/stable/tutorials/introductory/customizing.html + + """ + return self._theme + + @property + def display(self) -> DisplayConfig: + """ + Dictionary of parameters for rich display in Jupyter notebook. + + Valid parameters: + + - format ("png" or "svg"): Image format to produce + - scaling (float): Relative scaling of embedded image + - hidpi (bool): When True, double the DPI while preserving the size + + """ + return self._display + + +# ---- The main interface for declarative plotting --------------------------------- # + + +@build_plot_signature +class Plot: + """ + An interface for declaratively specifying statistical graphics. + + Plots are constructed by initializing this class and adding one or more + layers, comprising a `Mark` and optional `Stat` or `Move`. Additionally, + faceting variables or variable pairings may be defined to divide the space + into multiple subplots. The mappings from data values to visual properties + can be parametrized using scales, although the plot will try to infer good + defaults when scales are not explicitly defined. + + The constructor accepts a data source (a :class:`pandas.DataFrame` or + dictionary with columnar values) and variable assignments. Variables can be + passed as keys to the data source or directly as data vectors. If multiple + data-containing objects are provided, they will be index-aligned. + + The data source and variables defined in the constructor will be used for + all layers in the plot, unless overridden or disabled when adding a layer. + + The following variables can be defined in the constructor: + {known_properties} + + The `data`, `x`, and `y` variables can be passed as positional arguments or + using keywords. Whether the first positional argument is interpreted as a + data source or `x` variable depends on its type. + + The methods of this class return a copy of the instance; use chaining to + build up a plot through multiple calls. Methods can be called in any order. + + Most methods only add information to the plot spec; no actual processing + happens until the plot is shown or saved. It is also possible to compile + the plot without rendering it to access the lower-level representation. + + """ + config = PlotConfig() + + _data: PlotData + _layers: list[Layer] + + _scales: dict[str, Scale] + _shares: dict[str, bool | str] + _limits: dict[str, tuple[Any, Any]] + _labels: dict[str, str | Callable[[str], str]] + _theme: dict[str, Any] + + _facet_spec: FacetSpec + _pair_spec: PairSpec + + _figure_spec: dict[str, Any] + _subplot_spec: dict[str, Any] + _layout_spec: dict[str, Any] + + def __init__( + self, + *args: DataSource | VariableSpec, + data: DataSource = None, + **variables: VariableSpec, + ): + + if args: + data, variables = self._resolve_positionals(args, data, variables) + + unknown = [x for x in variables if x not in PROPERTIES] + if unknown: + err = f"Plot() got unexpected keyword argument(s): {', '.join(unknown)}" + raise TypeError(err) + + self._data = PlotData(data, variables) + + self._layers = [] + + self._scales = {} + self._shares = {} + self._limits = {} + self._labels = {} + self._theme = {} + + self._facet_spec = {} + self._pair_spec = {} + + self._figure_spec = {} + self._subplot_spec = {} + self._layout_spec = {} + + self._target = None + + def _resolve_positionals( + self, + args: tuple[DataSource | VariableSpec, ...], + data: DataSource, + variables: dict[str, VariableSpec], + ) -> tuple[DataSource, dict[str, VariableSpec]]: + """Handle positional arguments, which may contain data / x / y.""" + if len(args) > 3: + err = "Plot() accepts no more than 3 positional arguments (data, x, y)." + raise TypeError(err) + + if ( + isinstance(args[0], (abc.Mapping, pd.DataFrame)) + or hasattr(args[0], "__dataframe__") + ): + if data is not None: + raise TypeError("`data` given by both name and position.") + data, args = args[0], args[1:] + + if len(args) == 2: + x, y = args + elif len(args) == 1: + x, y = *args, None + else: + x = y = None + + for name, var in zip("yx", (y, x)): + if var is not None: + if name in variables: + raise TypeError(f"`{name}` given by both name and position.") + # Keep coordinates at the front of the variables dict + # Cast type because we know this isn't a DataSource at this point + variables = {name: cast(VariableSpec, var), **variables} + + return data, variables + + def __add__(self, other): + + if isinstance(other, Mark) or isinstance(other, Stat): + raise TypeError("Sorry, this isn't ggplot! Perhaps try Plot.add?") + + other_type = other.__class__.__name__ + raise TypeError(f"Unsupported operand type(s) for +: 'Plot' and '{other_type}") + + def _repr_png_(self) -> tuple[bytes, dict[str, float]] | None: + + if Plot.config.display["format"] != "png": + return None + return self.plot()._repr_png_() + + def _repr_svg_(self) -> str | None: + + if Plot.config.display["format"] != "svg": + return None + return self.plot()._repr_svg_() + + def _clone(self) -> Plot: + """Generate a new object with the same information as the current spec.""" + new = Plot() + + # TODO any way to enforce that data does not get mutated? + new._data = self._data + + new._layers.extend(self._layers) + + new._scales.update(self._scales) + new._shares.update(self._shares) + new._limits.update(self._limits) + new._labels.update(self._labels) + new._theme.update(self._theme) + + new._facet_spec.update(self._facet_spec) + new._pair_spec.update(self._pair_spec) + + new._figure_spec.update(self._figure_spec) + new._subplot_spec.update(self._subplot_spec) + new._layout_spec.update(self._layout_spec) + + new._target = self._target + + return new + + def _theme_with_defaults(self) -> dict[str, Any]: + + theme = self.config.theme.copy() + theme.update(self._theme) + return theme + + @property + def _variables(self) -> list[str]: + + variables = ( + list(self._data.frame) + + list(self._pair_spec.get("variables", [])) + + list(self._facet_spec.get("variables", [])) + ) + for layer in self._layers: + variables.extend(v for v in layer["vars"] if v not in variables) + + # Coerce to str in return to appease mypy; we know these will only + # ever be strings but I don't think we can type a DataFrame that way yet + return [str(v) for v in variables] + + def on(self, target: Axes | SubFigure | Figure) -> Plot: + """ + Provide existing Matplotlib figure or axes for drawing the plot. + + When using this method, you will also need to explicitly call a method that + triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you + want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot` + first to compile the plot without rendering it. + + Parameters + ---------- + target : Axes, SubFigure, or Figure + Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add + artists without otherwise modifying the figure. Otherwise, subplots will be + created within the space of the given :class:`matplotlib.figure.Figure` or + :class:`matplotlib.figure.SubFigure`. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.on.rst + + """ + accepted_types: tuple # Allow tuple of various length + accepted_types = ( + mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure + ) + accepted_types_str = ( + f"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}" + ) + + if not isinstance(target, accepted_types): + err = ( + f"The `Plot.on` target must be an instance of {accepted_types_str}. " + f"You passed an instance of {target.__class__} instead." + ) + raise TypeError(err) + + new = self._clone() + new._target = target + + return new + + def add( + self, + mark: Mark, + *transforms: Stat | Move, + orient: str | None = None, + legend: bool = True, + label: str | None = None, + data: DataSource = None, + **variables: VariableSpec, + ) -> Plot: + """ + Specify a layer of the visualization in terms of mark and data transform(s). + + This is the main method for specifying how the data should be visualized. + It can be called multiple times with different arguments to define + a plot with multiple layers. + + Parameters + ---------- + mark : :class:`Mark` + The visual representation of the data to use in this layer. + transforms : :class:`Stat` or :class:`Move` + Objects representing transforms to be applied before plotting the data. + Currently, at most one :class:`Stat` can be used, and it + must be passed first. This constraint will be relaxed in the future. + orient : "x", "y", "v", or "h" + The orientation of the mark, which also affects how transforms are computed. + Typically corresponds to the axis that defines groups for aggregation. + The "v" (vertical) and "h" (horizontal) options are synonyms for "x" / "y", + but may be more intuitive with some marks. When not provided, an + orientation will be inferred from characteristics of the data and scales. + legend : bool + Option to suppress the mark/mappings for this layer from the legend. + label : str + A label to use for the layer in the legend, independent of any mappings. + data : DataFrame or dict + Data source to override the global source provided in the constructor. + variables : data vectors or identifiers + Additional layer-specific variables, including variables that will be + passed directly to the transforms without scaling. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.add.rst + + """ + if not isinstance(mark, Mark): + msg = f"mark must be a Mark instance, not {type(mark)!r}." + raise TypeError(msg) + + # TODO This API for transforms was a late decision, and previously Plot.add + # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances. + # It will take some work to refactor the internals so that Stat and Move are + # treated identically, and until then well need to "unpack" the transforms + # here and enforce limitations on the order / types. + + stat: Optional[Stat] + move: Optional[List[Move]] + error = False + if not transforms: + stat, move = None, None + elif isinstance(transforms[0], Stat): + stat = transforms[0] + move = [m for m in transforms[1:] if isinstance(m, Move)] + error = len(move) != len(transforms) - 1 + else: + stat = None + move = [m for m in transforms if isinstance(m, Move)] + error = len(move) != len(transforms) + + if error: + msg = " ".join([ + "Transforms must have at most one Stat type (in the first position),", + "and all others must be a Move type. Given transform type(s):", + ", ".join(str(type(t).__name__) for t in transforms) + "." + ]) + raise TypeError(msg) + + new = self._clone() + new._layers.append({ + "mark": mark, + "stat": stat, + "move": move, + # TODO it doesn't work to supply scalars to variables, but it should + "vars": variables, + "source": data, + "legend": legend, + "label": label, + "orient": {"v": "x", "h": "y"}.get(orient, orient), # type: ignore + }) + + return new + + def pair( + self, + x: VariableSpecList = None, + y: VariableSpecList = None, + wrap: int | None = None, + cross: bool = True, + ) -> Plot: + """ + Produce subplots by pairing multiple `x` and/or `y` variables. + + Parameters + ---------- + x, y : sequence(s) of data vectors or identifiers + Variables that will define the grid of subplots. + wrap : int + When using only `x` or `y`, "wrap" subplots across a two-dimensional grid + with this many columns (when using `x`) or rows (when using `y`). + cross : bool + When False, zip the `x` and `y` lists such that the first subplot gets the + first pair, the second gets the second pair, etc. Otherwise, create a + two-dimensional grid from the cartesian product of the lists. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.pair.rst + + """ + # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows + # This may also be possible by setting `wrap=1`, but is that too unobvious? + # TODO PairGrid features not currently implemented: diagonals, corner + + pair_spec: PairSpec = {} + + axes = {"x": [] if x is None else x, "y": [] if y is None else y} + for axis, arg in axes.items(): + if isinstance(arg, (str, int)): + err = f"You must pass a sequence of variable keys to `{axis}`" + raise TypeError(err) + + pair_spec["variables"] = {} + pair_spec["structure"] = {} + + for axis in "xy": + keys = [] + for i, col in enumerate(axes[axis]): + key = f"{axis}{i}" + keys.append(key) + pair_spec["variables"][key] = col + + if keys: + pair_spec["structure"][axis] = keys + + if not cross and len(axes["x"]) != len(axes["y"]): + err = "Lengths of the `x` and `y` lists must match with cross=False" + raise ValueError(err) + + pair_spec["cross"] = cross + pair_spec["wrap"] = wrap + + new = self._clone() + new._pair_spec.update(pair_spec) + return new + + def facet( + self, + col: VariableSpec = None, + row: VariableSpec = None, + order: OrderSpec | dict[str, OrderSpec] = None, + wrap: int | None = None, + ) -> Plot: + """ + Produce subplots with conditional subsets of the data. + + Parameters + ---------- + col, row : data vectors or identifiers + Variables used to define subsets along the columns and/or rows of the grid. + Can be references to the global data source passed in the constructor. + order : list of strings, or dict with dimensional keys + Define the order of the faceting variables. + wrap : int + When using only `col` or `row`, wrap subplots across a two-dimensional + grid with this many subplots on the faceting dimension. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.facet.rst + + """ + variables: dict[str, VariableSpec] = {} + if col is not None: + variables["col"] = col + if row is not None: + variables["row"] = row + + structure = {} + if isinstance(order, dict): + for dim in ["col", "row"]: + dim_order = order.get(dim) + if dim_order is not None: + structure[dim] = list(dim_order) + elif order is not None: + if col is not None and row is not None: + err = " ".join([ + "When faceting on both col= and row=, passing `order` as a list" + "is ambiguous. Use a dict with 'col' and/or 'row' keys instead." + ]) + raise RuntimeError(err) + elif col is not None: + structure["col"] = list(order) + elif row is not None: + structure["row"] = list(order) + + spec: FacetSpec = { + "variables": variables, + "structure": structure, + "wrap": wrap, + } + + new = self._clone() + new._facet_spec.update(spec) + + return new + + # TODO def twin()? + + def scale(self, **scales: Scale) -> Plot: + """ + Specify mappings from data units to visual properties. + + Keywords correspond to variables defined in the plot, including coordinate + variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.). + + A number of "magic" arguments are accepted, including: + - The name of a transform (e.g., `"log"`, `"sqrt"`) + - The name of a palette (e.g., `"viridis"`, `"muted"`) + - A tuple of values, defining the output range (e.g. `(1, 5)`) + - A dict, implying a :class:`Nominal` scale (e.g. `{"a": .2, "b": .5}`) + - A list of values, implying a :class:`Nominal` scale (e.g. `["b", "r"]`) + + For more explicit control, pass a scale spec object such as :class:`Continuous` + or :class:`Nominal`. Or pass `None` to use an "identity" scale, which treats + data values as literally encoding visual properties. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.scale.rst + + """ + new = self._clone() + new._scales.update(scales) + return new + + def share(self, **shares: bool | str) -> Plot: + """ + Control sharing of axis limits and ticks across subplots. + + Keywords correspond to variables defined in the plot, and values can be + boolean (to share across all subplots), or one of "row" or "col" (to share + more selectively across one dimension of a grid). + + Behavior for non-coordinate variables is currently undefined. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.share.rst + + """ + new = self._clone() + new._shares.update(shares) + return new + + def limit(self, **limits: tuple[Any, Any]) -> Plot: + """ + Control the range of visible data. + + Keywords correspond to variables defined in the plot, and values are a + `(min, max)` tuple (where either can be `None` to leave unset). + + Limits apply only to the axis; data outside the visible range are + still used for any stat transforms and added to the plot. + + Behavior for non-coordinate variables is currently undefined. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.limit.rst + + """ + new = self._clone() + new._limits.update(limits) + return new + + def label( + self, *, + title: str | None = None, + legend: str | None = None, + **variables: str | Callable[[str], str] + ) -> Plot: + """ + Control the labels and titles for axes, legends, and subplots. + + Additional keywords correspond to variables defined in the plot. + Values can be one of the following types: + + - string (used literally; pass "" to clear the default label) + - function (called on the default label) + + For coordinate variables, the value sets the axis label. + For semantic variables, the value sets the legend title. + For faceting variables, `title=` modifies the subplot-specific label, + while `col=` and/or `row=` add a label for the faceting variable. + + When using a single subplot, `title=` sets its title. + + The `legend=` parameter sets the title for the "layer" legend + (i.e., when using `label` in :meth:`Plot.add`). + + Examples + -------- + .. include:: ../docstrings/objects.Plot.label.rst + + + """ + new = self._clone() + if title is not None: + new._labels["title"] = title + if legend is not None: + new._labels["legend"] = legend + new._labels.update(variables) + return new + + def layout( + self, + *, + size: tuple[float, float] | Default = default, + engine: str | None | Default = default, + extent: tuple[float, float, float, float] | Default = default, + ) -> Plot: + """ + Control the figure size and layout. + + .. note:: + + Default figure sizes and the API for specifying the figure size are subject + to change in future "experimental" releases of the objects API. The default + layout engine may also change. + + Parameters + ---------- + size : (width, height) + Size of the resulting figure, in inches. Size is inclusive of legend when + using pyplot, but not otherwise. + engine : {{"tight", "constrained", "none"}} + Name of method for automatically adjusting the layout to remove overlap. + The default depends on whether :meth:`Plot.on` is used. + extent : (left, bottom, right, top) + Boundaries of the plot layout, in fractions of the figure size. Takes + effect through the layout engine; exact results will vary across engines. + Note: the extent includes axis decorations when using a layout engine, + but it is exclusive of them when `engine="none"`. + + Examples + -------- + .. include:: ../docstrings/objects.Plot.layout.rst + + """ + # TODO add an "auto" mode for figsize that roughly scales with the rcParams + # figsize (so that works), but expands to prevent subplots from being squished + # Also should we have height=, aspect=, exclusive with figsize? Or working + # with figsize when only one is defined? + + new = self._clone() + + if size is not default: + new._figure_spec["figsize"] = size + if engine is not default: + new._layout_spec["engine"] = engine + if extent is not default: + new._layout_spec["extent"] = extent + + return new + + # TODO def legend (ugh) + + def theme(self, config: dict[str, Any], /) -> Plot: + """ + Control the appearance of elements in the plot. + + .. note:: + + The API for customizing plot appearance is not yet finalized. + Currently, the only valid argument is a dict of matplotlib rc parameters. + (This dict must be passed as a positional argument.) + + It is likely that this method will be enhanced in future releases. + + Matplotlib rc parameters are documented on the following page: + https://matplotlib.org/stable/tutorials/introductory/customizing.html + + Examples + -------- + .. include:: ../docstrings/objects.Plot.theme.rst + + """ + new = self._clone() + + rc = mpl.RcParams(config) + new._theme.update(rc) + + return new + + def save(self, loc, **kwargs) -> Plot: + """ + Compile the plot and write it to a buffer or file on disk. + + Parameters + ---------- + loc : str, path, or buffer + Location on disk to save the figure, or a buffer to write into. + kwargs + Other keyword arguments are passed through to + :meth:`matplotlib.figure.Figure.savefig`. + + """ + # TODO expose important keyword arguments in our signature? + with theme_context(self._theme_with_defaults()): + self._plot().save(loc, **kwargs) + return self + + def show(self, **kwargs) -> None: + """ + Compile the plot and display it by hooking into pyplot. + + Calling this method is not necessary to render a plot in notebook context, + but it may be in other environments (e.g., in a terminal). After compiling the + plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters). + + Unlike other :class:`Plot` methods, there is no return value. This should be + the last method you call when specifying a plot. + + """ + # TODO make pyplot configurable at the class level, and when not using, + # import IPython.display and call on self to populate cell output? + + # Keep an eye on whether matplotlib implements "attaching" an existing + # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024 + + self.plot(pyplot=True).show(**kwargs) + + def plot(self, pyplot: bool = False) -> Plotter: + """ + Compile the plot spec and return the Plotter object. + """ + with theme_context(self._theme_with_defaults()): + return self._plot(pyplot) + + def _plot(self, pyplot: bool = False) -> Plotter: + + # TODO if we have _target object, pyplot should be determined by whether it + # is hooked into the pyplot state machine (how do we check?) + + plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults()) + + # Process the variable assignments and initialize the figure + common, layers = plotter._extract_data(self) + plotter._setup_figure(self, common, layers) + + # Process the scale spec for coordinate variables and transform their data + coord_vars = [v for v in self._variables if re.match(r"^x|y", v)] + plotter._setup_scales(self, common, layers, coord_vars) + + # Apply statistical transform(s) + plotter._compute_stats(self, layers) + + # Process scale spec for semantic variables and coordinates computed by stat + plotter._setup_scales(self, common, layers) + + # TODO Remove these after updating other methods + # ---- Maybe have debug= param that attaches these when True? + plotter._data = common + plotter._layers = layers + + # Process the data for each layer and add matplotlib artists + for layer in layers: + plotter._plot_layer(self, layer) + + # Add various figure decorations + plotter._make_legend(self) + plotter._finalize_figure(self) + + return plotter + + +# ---- The plot compilation engine ---------------------------------------------- # + + +class Plotter: + """ + Engine for compiling a :class:`Plot` spec into a Matplotlib figure. + + This class is not intended to be instantiated directly by users. + + """ + # TODO decide if we ever want these (Plot.plot(debug=True))? + _data: PlotData + _layers: list[Layer] + _figure: Figure + + def __init__(self, pyplot: bool, theme: dict[str, Any]): + + self._pyplot = pyplot + self._theme = theme + self._legend_contents: list[tuple[ + tuple[str, str | int], list[Artist], list[str], + ]] = [] + self._scales: dict[str, Scale] = {} + + def save(self, loc, **kwargs) -> Plotter: # TODO type args + kwargs.setdefault("dpi", 96) + try: + loc = os.path.expanduser(loc) + except TypeError: + # loc may be a buffer in which case that would not work + pass + self._figure.savefig(loc, **kwargs) + return self + + def show(self, **kwargs) -> None: + """ + Display the plot by hooking into pyplot. + + This method calls :func:`matplotlib.pyplot.show` with any keyword parameters. + + """ + # TODO if we did not create the Plotter with pyplot, is it possible to do this? + # If not we should clearly raise. + import matplotlib.pyplot as plt + with theme_context(self._theme): + plt.show(**kwargs) + + # TODO API for accessing the underlying matplotlib objects + # TODO what else is useful in the public API for this class? + + def _repr_png_(self) -> tuple[bytes, dict[str, float]] | None: + + # TODO use matplotlib backend directly instead of going through savefig? + + # TODO perhaps have self.show() flip a switch to disable this, so that + # user does not end up with two versions of the figure in the output + + # TODO use bbox_inches="tight" like the inline backend? + # pro: better results, con: (sometimes) confusing results + # Better solution would be to default (with option to change) + # to using constrained/tight layout. + + if Plot.config.display["format"] != "png": + return None + + buffer = io.BytesIO() + + factor = 2 if Plot.config.display["hidpi"] else 1 + scaling = Plot.config.display["scaling"] / factor + dpi = 96 * factor # TODO put dpi in Plot.config? + + with theme_context(self._theme): # TODO _theme_with_defaults? + self._figure.savefig(buffer, dpi=dpi, format="png", bbox_inches="tight") + data = buffer.getvalue() + + w, h = Image.open(buffer).size + metadata = {"width": w * scaling, "height": h * scaling} + return data, metadata + + def _repr_svg_(self) -> str | None: + + if Plot.config.display["format"] != "svg": + return None + + # TODO DPI for rasterized artists? + + scaling = Plot.config.display["scaling"] + + buffer = io.StringIO() + with theme_context(self._theme): # TODO _theme_with_defaults? + self._figure.savefig(buffer, format="svg", bbox_inches="tight") + + root = ElementTree.fromstring(buffer.getvalue()) + w = scaling * float(root.attrib["width"][:-2]) + h = scaling * float(root.attrib["height"][:-2]) + root.attrib.update(width=f"{w}pt", height=f"{h}pt", viewbox=f"0 0 {w} {h}") + ElementTree.ElementTree(root).write(out := io.BytesIO()) + + return out.getvalue().decode() + + def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]: + + common_data = ( + p._data + .join(None, p._facet_spec.get("variables")) + .join(None, p._pair_spec.get("variables")) + ) + + layers: list[Layer] = [] + for layer in p._layers: + spec = layer.copy() + spec["data"] = common_data.join(layer.get("source"), layer.get("vars")) + layers.append(spec) + + return common_data, layers + + def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str: + + if re.match(r"[xy]\d+", var): + key = var if var in p._labels else var[0] + else: + key = var + + label: str + if key in p._labels: + manual_label = p._labels[key] + if callable(manual_label) and auto_label is not None: + label = manual_label(auto_label) + else: + label = cast(str, manual_label) + elif auto_label is None: + label = "" + else: + label = auto_label + return label + + def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None: + + # --- Parsing the faceting/pairing parameterization to specify figure grid + + subplot_spec = p._subplot_spec.copy() + facet_spec = p._facet_spec.copy() + pair_spec = p._pair_spec.copy() + + for axis in "xy": + if axis in p._shares: + subplot_spec[f"share{axis}"] = p._shares[axis] + + for dim in ["col", "row"]: + if dim in common.frame and dim not in facet_spec["structure"]: + order = categorical_order(common.frame[dim]) + facet_spec["structure"][dim] = order + + self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec) + + # --- Figure initialization + self._figure = subplots.init_figure( + pair_spec, self._pyplot, p._figure_spec, p._target, + ) + + # --- Figure annotation + for sub in subplots: + ax = sub["ax"] + for axis in "xy": + axis_key = sub[axis] + + # ~~ Axis labels + + # TODO Should we make it possible to use only one x/y label for + # all rows/columns in a faceted plot? Maybe using sub{axis}label, + # although the alignments of the labels from that method leaves + # something to be desired (in terms of how it defines 'centered'). + names = [ + common.names.get(axis_key), + *(layer["data"].names.get(axis_key) for layer in layers) + ] + auto_label = next((name for name in names if name is not None), None) + label = self._resolve_label(p, axis_key, auto_label) + ax.set(**{f"{axis}label": label}) + + # ~~ Decoration visibility + + # TODO there should be some override (in Plot.layout?) so that + # axis / tick labels can be shown on interior shared axes if desired + + axis_obj = getattr(ax, f"{axis}axis") + visible_side = {"x": "bottom", "y": "left"}.get(axis) + show_axis_label = ( + sub[visible_side] + or not p._pair_spec.get("cross", True) + or ( + axis in p._pair_spec.get("structure", {}) + and bool(p._pair_spec.get("wrap")) + ) + ) + axis_obj.get_label().set_visible(show_axis_label) + + show_tick_labels = ( + show_axis_label + or subplot_spec.get(f"share{axis}") not in ( + True, "all", {"x": "col", "y": "row"}[axis] + ) + ) + for group in ("major", "minor"): + side = {"x": "bottom", "y": "left"}[axis] + axis_obj.set_tick_params(**{f"label{side}": show_tick_labels}) + for t in getattr(axis_obj, f"get_{group}ticklabels")(): + t.set_visible(show_tick_labels) + + # TODO we want right-side titles for row facets in most cases? + # Let's have what we currently call "margin titles" but properly using the + # ax.set_title interface (see my gist) + title_parts = [] + for dim in ["col", "row"]: + if sub[dim] is not None: + val = self._resolve_label(p, "title", f"{sub[dim]}") + if dim in p._labels: + key = self._resolve_label(p, dim, common.names.get(dim)) + val = f"{key} {val}" + title_parts.append(val) + + has_col = sub["col"] is not None + has_row = sub["row"] is not None + show_title = ( + has_col and has_row + or (has_col or has_row) and p._facet_spec.get("wrap") + or (has_col and sub["top"]) + # TODO or has_row and sub["right"] and + or has_row # TODO and not + ) + if title_parts: + title = " | ".join(title_parts) + title_text = ax.set_title(title) + title_text.set_visible(show_title) + elif not (has_col or has_row): + title = self._resolve_label(p, "title", None) + title_text = ax.set_title(title) + + def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None: + + grouping_vars = [v for v in PROPERTIES if v not in "xy"] + grouping_vars += ["col", "row", "group"] + + pair_vars = spec._pair_spec.get("structure", {}) + + for layer in layers: + + data = layer["data"] + mark = layer["mark"] + stat = layer["stat"] + + if stat is None: + continue + + iter_axes = itertools.product(*[ + pair_vars.get(axis, [axis]) for axis in "xy" + ]) + + old = data.frame + + if pair_vars: + data.frames = {} + data.frame = data.frame.iloc[:0] # TODO to simplify typing + + for coord_vars in iter_axes: + + pairings = "xy", coord_vars + + df = old.copy() + scales = self._scales.copy() + + for axis, var in zip(*pairings): + if axis != var: + df = df.rename(columns={var: axis}) + drop_cols = [x for x in df if re.match(rf"{axis}\d+", str(x))] + df = df.drop(drop_cols, axis=1) + scales[axis] = scales[var] + + orient = layer["orient"] or mark._infer_orient(scales) + + if stat.group_by_orient: + grouper = [orient, *grouping_vars] + else: + grouper = grouping_vars + groupby = GroupBy(grouper) + res = stat(df, groupby, orient, scales) + + if pair_vars: + data.frames[coord_vars] = res + else: + data.frame = res + + def _get_scale( + self, p: Plot, var: str, prop: Property, values: Series + ) -> Scale: + + if re.match(r"[xy]\d+", var): + key = var if var in p._scales else var[0] + else: + key = var + + if key in p._scales: + arg = p._scales[key] + if arg is None or isinstance(arg, Scale): + scale = arg + else: + scale = prop.infer_scale(arg, values) + else: + scale = prop.default_scale(values) + + return scale + + def _get_subplot_data(self, df, var, view, share_state): + + if share_state in [True, "all"]: + # The all-shared case is easiest, every subplot sees all the data + seed_values = df[var] + else: + # Otherwise, we need to setup separate scales for different subplots + if share_state in [False, "none"]: + # Fully independent axes are also easy: use each subplot's data + idx = self._get_subplot_index(df, view) + elif share_state in df: + # Sharing within row/col is more complicated + use_rows = df[share_state] == view[share_state] + idx = df.index[use_rows] + else: + # This configuration doesn't make much sense, but it's fine + idx = df.index + + seed_values = df.loc[idx, var] + + return seed_values + + def _setup_scales( + self, + p: Plot, + common: PlotData, + layers: list[Layer], + variables: list[str] | None = None, + ) -> None: + + if variables is None: + # Add variables that have data but not a scale, which happens + # because this method can be called multiple time, to handle + # variables added during the Stat transform. + variables = [] + for layer in layers: + variables.extend(layer["data"].frame.columns) + for df in layer["data"].frames.values(): + variables.extend(str(v) for v in df if v not in variables) + variables = [v for v in variables if v not in self._scales] + + for var in variables: + + # Determine whether this is a coordinate variable + # (i.e., x/y, paired x/y, or derivative such as xmax) + m = re.match(r"^(?P(?Px|y)\d*).*", var) + if m is None: + coord = axis = None + else: + coord = m["coord"] + axis = m["axis"] + + # Get keys that handle things like x0, xmax, properly where relevant + prop_key = var if axis is None else axis + scale_key = var if coord is None else coord + + if prop_key not in PROPERTIES: + continue + + # Concatenate layers, using only the relevant coordinate and faceting vars, + # This is unnecessarily wasteful, as layer data will often be redundant. + # But figuring out the minimal amount we need is more complicated. + cols = [var, "col", "row"] + parts = [common.frame.filter(cols)] + for layer in layers: + parts.append(layer["data"].frame.filter(cols)) + for df in layer["data"].frames.values(): + parts.append(df.filter(cols)) + var_df = pd.concat(parts, ignore_index=True) + + prop = PROPERTIES[prop_key] + scale = self._get_scale(p, scale_key, prop, var_df[var]) + + if scale_key not in p._variables: + # TODO this implies that the variable was added by the stat + # It allows downstream orientation inference to work properly. + # But it feels rather hacky, so ideally revisit. + scale._priority = 0 # type: ignore + + if axis is None: + # We could think about having a broader concept of (un)shared properties + # In general, not something you want to do (different scales in facets) + # But could make sense e.g. with paired plots. Build later. + share_state = None + subplots = [] + else: + share_state = self._subplots.subplot_spec[f"share{axis}"] + subplots = [view for view in self._subplots if view[axis] == coord] + + if scale is None: + self._scales[var] = Scale._identity() + else: + try: + self._scales[var] = scale._setup(var_df[var], prop) + except Exception as err: + raise PlotSpecError._during("Scale setup", var) from err + + if axis is None or (var != coord and coord in p._variables): + # Everything below here applies only to coordinate variables + continue + + # Set up an empty series to receive the transformed values. + # We need this to handle piecemeal transforms of categories -> floats. + transformed_data = [] + for layer in layers: + index = layer["data"].frame.index + empty_series = pd.Series(dtype=float, index=index, name=var) + transformed_data.append(empty_series) + + for view in subplots: + + axis_obj = getattr(view["ax"], f"{axis}axis") + seed_values = self._get_subplot_data(var_df, var, view, share_state) + view_scale = scale._setup(seed_values, prop, axis=axis_obj) + view["ax"].set(**{f"{axis}scale": view_scale._matplotlib_scale}) + + for layer, new_series in zip(layers, transformed_data): + layer_df = layer["data"].frame + if var not in layer_df: + continue + + idx = self._get_subplot_index(layer_df, view) + try: + new_series.loc[idx] = view_scale(layer_df.loc[idx, var]) + except Exception as err: + spec_error = PlotSpecError._during("Scaling operation", var) + raise spec_error from err + + # Now the transformed data series are complete, update the layer data + for layer, new_series in zip(layers, transformed_data): + layer_df = layer["data"].frame + if var in layer_df: + layer_df[var] = pd.to_numeric(new_series) + + def _plot_layer(self, p: Plot, layer: Layer) -> None: + + data = layer["data"] + mark = layer["mark"] + move = layer["move"] + + default_grouping_vars = ["col", "row", "group"] # TODO where best to define? + grouping_properties = [v for v in PROPERTIES if v[0] not in "xy"] + + pair_variables = p._pair_spec.get("structure", {}) + + for subplots, df, scales in self._generate_pairings(data, pair_variables): + + orient = layer["orient"] or mark._infer_orient(scales) + + def get_order(var): + # Ignore order for x/y: they have been scaled to numeric indices, + # so any original order is no longer valid. Default ordering rules + # sorted unique numbers will correctly reconstruct intended order + # TODO This is tricky, make sure we add some tests for this + if var not in "xy" and var in scales: + return getattr(scales[var], "order", None) + + if orient in df: + width = pd.Series(index=df.index, dtype=float) + for view in subplots: + view_idx = self._get_subplot_data( + df, orient, view, p._shares.get(orient) + ).index + view_df = df.loc[view_idx] + if "width" in mark._mappable_props: + view_width = mark._resolve(view_df, "width", None) + elif "width" in df: + view_width = view_df["width"] + else: + view_width = 0.8 # TODO what default? + spacing = scales[orient]._spacing(view_df.loc[view_idx, orient]) + width.loc[view_idx] = view_width * spacing + df["width"] = width + + if "baseline" in mark._mappable_props: + # TODO what marks should have this? + # If we can set baseline with, e.g., Bar(), then the + # "other" (e.g. y for x oriented bars) parameterization + # is somewhat ambiguous. + baseline = mark._resolve(df, "baseline", None) + else: + # TODO unlike width, we might not want to add baseline to data + # if the mark doesn't use it. Practically, there is a concern about + # Mark abstraction like Area / Ribbon + baseline = 0 if "baseline" not in df else df["baseline"] + df["baseline"] = baseline + + if move is not None: + moves = move if isinstance(move, list) else [move] + for move_step in moves: + move_by = getattr(move_step, "by", None) + if move_by is None: + move_by = grouping_properties + move_groupers = [*move_by, *default_grouping_vars] + if move_step.group_by_orient: + move_groupers.insert(0, orient) + order = {var: get_order(var) for var in move_groupers} + groupby = GroupBy(order) + df = move_step(df, groupby, orient, scales) + + df = self._unscale_coords(subplots, df, orient) + + grouping_vars = mark._grouping_props + default_grouping_vars + split_generator = self._setup_split_generator(grouping_vars, df, subplots) + + mark._plot(split_generator, scales, orient) + + # TODO is this the right place for this? + for view in self._subplots: + view["ax"].autoscale_view() + + if layer["legend"]: + self._update_legend_contents(p, mark, data, scales, layer["label"]) + + def _unscale_coords( + self, subplots: list[dict], df: DataFrame, orient: str, + ) -> DataFrame: + # TODO do we still have numbers in the variable name at this point? + coord_cols = [c for c in df if re.match(r"^[xy]\D*$", str(c))] + out_df = ( + df + .drop(coord_cols, axis=1) + .reindex(df.columns, axis=1) # So unscaled columns retain their place + .copy(deep=False) + ) + + for view in subplots: + view_df = self._filter_subplot_data(df, view) + axes_df = view_df[coord_cols] + for var, values in axes_df.items(): + + axis = getattr(view["ax"], f"{str(var)[0]}axis") + # TODO see https://github.com/matplotlib/matplotlib/issues/22713 + transform = axis.get_transform().inverted().transform + inverted = transform(values) + out_df.loc[values.index, str(var)] = inverted + + return out_df + + def _generate_pairings( + self, data: PlotData, pair_variables: dict, + ) -> Generator[ + tuple[list[dict], DataFrame, dict[str, Scale]], None, None + ]: + # TODO retype return with subplot_spec or similar + + iter_axes = itertools.product(*[ + pair_variables.get(axis, [axis]) for axis in "xy" + ]) + + for x, y in iter_axes: + + subplots = [] + for view in self._subplots: + if (view["x"] == x) and (view["y"] == y): + subplots.append(view) + + if data.frame.empty and data.frames: + out_df = data.frames[(x, y)].copy() + elif not pair_variables: + out_df = data.frame.copy() + else: + if data.frame.empty and data.frames: + out_df = data.frames[(x, y)].copy() + else: + out_df = data.frame.copy() + + scales = self._scales.copy() + if x in out_df: + scales["x"] = self._scales[x] + if y in out_df: + scales["y"] = self._scales[y] + + for axis, var in zip("xy", (x, y)): + if axis != var: + out_df = out_df.rename(columns={var: axis}) + cols = [col for col in out_df if re.match(rf"{axis}\d+", str(col))] + out_df = out_df.drop(cols, axis=1) + + yield subplots, out_df, scales + + def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index: + + dims = df.columns.intersection(["col", "row"]) + if dims.empty: + return df.index + + keep_rows = pd.Series(True, df.index, dtype=bool) + for dim in dims: + keep_rows &= df[dim] == subplot[dim] + return df.index[keep_rows] + + def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame: + # TODO note redundancies with preceding function ... needs refactoring + dims = df.columns.intersection(["col", "row"]) + if dims.empty: + return df + + keep_rows = pd.Series(True, df.index, dtype=bool) + for dim in dims: + keep_rows &= df[dim] == subplot[dim] + return df[keep_rows] + + def _setup_split_generator( + self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]], + ) -> Callable[[], Generator]: + + grouping_keys = [] + grouping_vars = [ + v for v in grouping_vars if v in df and v not in ["col", "row"] + ] + for var in grouping_vars: + order = getattr(self._scales[var], "order", None) + if order is None: + order = categorical_order(df[var]) + grouping_keys.append(order) + + def split_generator(keep_na=False) -> Generator: + + for view in subplots: + + axes_df = self._filter_subplot_data(df, view) + + axes_df_inf_as_nan = axes_df.copy() + axes_df_inf_as_nan = axes_df_inf_as_nan.mask( + axes_df_inf_as_nan.isin([np.inf, -np.inf]), np.nan + ) + if keep_na: + # The simpler thing to do would be x.dropna().reindex(x.index). + # But that doesn't work with the way that the subset iteration + # is written below, which assumes data for grouping vars. + # Matplotlib (usually?) masks nan data, so this should "work". + # Downstream code can also drop these rows, at some speed cost. + present = axes_df_inf_as_nan.notna().all(axis=1) + nulled = {} + for axis in "xy": + if axis in axes_df: + nulled[axis] = axes_df[axis].where(present) + axes_df = axes_df_inf_as_nan.assign(**nulled) + else: + axes_df = axes_df_inf_as_nan.dropna() + + subplot_keys = {} + for dim in ["col", "row"]: + if view[dim] is not None: + subplot_keys[dim] = view[dim] + + if not grouping_vars or not any(grouping_keys): + if not axes_df.empty: + yield subplot_keys, axes_df.copy(), view["ax"] + continue + + grouped_df = axes_df.groupby( + grouping_vars, sort=False, as_index=False, observed=False, + ) + + for key in itertools.product(*grouping_keys): + + pd_key = ( + key[0] if len(key) == 1 and _version_predates(pd, "2.2.0") + else key + ) + try: + df_subset = grouped_df.get_group(pd_key) + except KeyError: + # TODO (from initial work on categorical plots refactor) + # We are adding this to allow backwards compatability + # with the empty artists that old categorical plots would + # add (before 0.12), which we may decide to break, in which + # case this option could be removed + df_subset = axes_df.loc[[]] + + if df_subset.empty: + continue + + sub_vars = dict(zip(grouping_vars, key)) + sub_vars.update(subplot_keys) + + # TODO need copy(deep=...) policy (here, above, anywhere else?) + yield sub_vars, df_subset.copy(), view["ax"] + + return split_generator + + def _update_legend_contents( + self, + p: Plot, + mark: Mark, + data: PlotData, + scales: dict[str, Scale], + layer_label: str | None, + ) -> None: + """Add legend artists / labels for one layer in the plot.""" + if data.frame.empty and data.frames: + legend_vars: list[str] = [] + for frame in data.frames.values(): + frame_vars = frame.columns.intersection(list(scales)) + legend_vars.extend(v for v in frame_vars if v not in legend_vars) + else: + legend_vars = list(data.frame.columns.intersection(list(scales))) + + # First handle layer legends, which occupy a single entry in legend_contents. + if layer_label is not None: + legend_title = str(p._labels.get("legend", "")) + layer_key = (legend_title, -1) + artist = mark._legend_artist([], None, {}) + if artist is not None: + for content in self._legend_contents: + if content[0] == layer_key: + content[1].append(artist) + content[2].append(layer_label) + break + else: + self._legend_contents.append((layer_key, [artist], [layer_label])) + + # Then handle the scale legends + # First pass: Identify the values that will be shown for each variable + schema: list[tuple[ + tuple[str, str | int], list[str], tuple[list[Any], list[str]] + ]] = [] + schema = [] + for var in legend_vars: + var_legend = scales[var]._legend + if var_legend is not None: + values, labels = var_legend + for (_, part_id), part_vars, _ in schema: + if data.ids[var] == part_id: + # Allow multiple plot semantics to represent same data variable + part_vars.append(var) + break + else: + title = self._resolve_label(p, var, data.names[var]) + entry = (title, data.ids[var]), [var], (values, labels) + schema.append(entry) + + # Second pass, generate an artist corresponding to each value + contents: list[tuple[tuple[str, str | int], Any, list[str]]] = [] + for key, variables, (values, labels) in schema: + artists = [] + for val in values: + artist = mark._legend_artist(variables, val, scales) + if artist is not None: + artists.append(artist) + if artists: + contents.append((key, artists, labels)) + + self._legend_contents.extend(contents) + + def _make_legend(self, p: Plot) -> None: + """Create the legend artist(s) and add onto the figure.""" + # Combine artists representing same information across layers + # Input list has an entry for each distinct variable in each layer + # Output dict has an entry for each distinct variable + merged_contents: dict[ + tuple[str, str | int], tuple[list[tuple[Artist, ...]], list[str]], + ] = {} + for key, new_artists, labels in self._legend_contents: + # Key is (name, id); we need the id to resolve variable uniqueness, + # but will need the name in the next step to title the legend + if key not in merged_contents: + # Matplotlib accepts a tuple of artists and will overlay them + new_artist_tuples = [tuple([a]) for a in new_artists] + merged_contents[key] = new_artist_tuples, labels + else: + existing_artists = merged_contents[key][0] + for i, new_artist in enumerate(new_artists): + existing_artists[i] += tuple([new_artist]) + + # When using pyplot, an "external" legend won't be shown, so this + # keeps it inside the axes (though still attached to the figure) + # This is necessary because matplotlib layout engines currently don't + # support figure legends — ideally this will change. + loc = "center right" if self._pyplot else "center left" + + base_legend = None + for (name, _), (handles, labels) in merged_contents.items(): + + legend = mpl.legend.Legend( + self._figure, + handles, # type: ignore # matplotlib/issues/26639 + labels, + title=name, + loc=loc, + bbox_to_anchor=(.98, .55), + ) + + if base_legend: + # Matplotlib has no public API for this so it is a bit of a hack. + # Ideally we'd define our own legend class with more flexibility, + # but that is a lot of work! + base_legend_box = base_legend.get_children()[0] + this_legend_box = legend.get_children()[0] + base_legend_box.get_children().extend(this_legend_box.get_children()) + else: + base_legend = legend + self._figure.legends.append(legend) + + def _finalize_figure(self, p: Plot) -> None: + + for sub in self._subplots: + ax = sub["ax"] + for axis in "xy": + axis_key = sub[axis] + axis_obj = getattr(ax, f"{axis}axis") + + # Axis limits + if axis_key in p._limits or axis in p._limits: + convert_units = getattr(ax, f"{axis}axis").convert_units + a, b = p._limits.get(axis_key) or p._limits[axis] + lo = a if a is None else convert_units(a) + hi = b if b is None else convert_units(b) + if isinstance(a, str): + lo = cast(float, lo) - 0.5 + if isinstance(b, str): + hi = cast(float, hi) + 0.5 + ax.set(**{f"{axis}lim": (lo, hi)}) + + if axis_key in self._scales: # TODO when would it not be? + self._scales[axis_key]._finalize(p, axis_obj) + + if (engine_name := p._layout_spec.get("engine", default)) is not default: + # None is a valid arg for Figure.set_layout_engine, hence `default` + set_layout_engine(self._figure, engine_name) + elif p._target is None: + # Don't modify the layout engine if the user supplied their own + # matplotlib figure and didn't specify an engine through Plot + # TODO switch default to "constrained"? + # TODO either way, make configurable + set_layout_engine(self._figure, "tight") + + if (extent := p._layout_spec.get("extent")) is not None: + engine = get_layout_engine(self._figure) + if engine is None: + self._figure.subplots_adjust(*extent) + else: + # Note the different parameterization for the layout engine rect... + left, bottom, right, top = extent + width, height = right - left, top - bottom + try: + # The base LayoutEngine.set method doesn't have rect= so we need + # to avoid typechecking this statement. We also catch a TypeError + # as a plugin LayoutEngine may not support it either. + # Alternatively we could guard this with a check on the engine type, + # but that would make later-developed engines would un-useable. + engine.set(rect=[left, bottom, width, height]) # type: ignore + except TypeError: + # Should we warn / raise? Note that we don't expect to get here + # under any normal circumstances. + pass diff --git a/shared/package-files/7a/7a876fa34f6b0957dc61ad5487a04a1cabd7c98f0ae59836b86417d69850e84c/blob b/shared/package-files/7a/7a876fa34f6b0957dc61ad5487a04a1cabd7c98f0ae59836b86417d69850e84c/blob new file mode 100644 index 0000000000000000000000000000000000000000..b77173c136d80eb57f5c993108b7408653acad13 --- /dev/null +++ b/shared/package-files/7a/7a876fa34f6b0957dc61ad5487a04a1cabd7c98f0ae59836b86417d69850e84c/blob @@ -0,0 +1,199 @@ +import numpy as np +from numpy import poly1d +from scipy.special import beta + + +# The following code was used to generate the Pade coefficients for the +# Tukey Lambda variance function. Version 0.17 of mpmath was used. +#--------------------------------------------------------------------------- +# import mpmath as mp +# +# mp.mp.dps = 60 +# +# one = mp.mpf(1) +# two = mp.mpf(2) +# +# def mpvar(lam): +# if lam == 0: +# v = mp.pi**2 / three +# else: +# v = (two / lam**2) * (one / (one + two*lam) - +# mp.beta(lam + one, lam + one)) +# return v +# +# t = mp.taylor(mpvar, 0, 8) +# p, q = mp.pade(t, 4, 4) +# print("p =", [mp.fp.mpf(c) for c in p]) +# print("q =", [mp.fp.mpf(c) for c in q]) +#--------------------------------------------------------------------------- + +# Pade coefficients for the Tukey Lambda variance function. +_tukeylambda_var_pc = [3.289868133696453, 0.7306125098871127, + -0.5370742306855439, 0.17292046290190008, + -0.02371146284628187] +_tukeylambda_var_qc = [1.0, 3.683605511659861, 4.184152498888124, + 1.7660926747377275, 0.2643989311168465] + +# numpy.poly1d instances for the numerator and denominator of the +# Pade approximation to the Tukey Lambda variance. +_tukeylambda_var_p = poly1d(_tukeylambda_var_pc[::-1]) +_tukeylambda_var_q = poly1d(_tukeylambda_var_qc[::-1]) + + +def tukeylambda_variance(lam): + """Variance of the Tukey Lambda distribution. + + Parameters + ---------- + lam : array_like + The lambda values at which to compute the variance. + + Returns + ------- + v : ndarray + The variance. For lam < -0.5, the variance is not defined, so + np.nan is returned. For lam = 0.5, np.inf is returned. + + Notes + ----- + In an interval around lambda=0, this function uses the [4,4] Pade + approximation to compute the variance. Otherwise it uses the standard + formula (https://en.wikipedia.org/wiki/Tukey_lambda_distribution). The + Pade approximation is used because the standard formula has a removable + discontinuity at lambda = 0, and does not produce accurate numerical + results near lambda = 0. + """ + lam = np.asarray(lam) + shp = lam.shape + lam = np.atleast_1d(lam).astype(np.float64) + + # For absolute values of lam less than threshold, use the Pade + # approximation. + threshold = 0.075 + + # Play games with masks to implement the conditional evaluation of + # the distribution. + # lambda < -0.5: var = nan + low_mask = lam < -0.5 + # lambda == -0.5: var = inf + neghalf_mask = lam == -0.5 + # abs(lambda) < threshold: use Pade approximation + small_mask = np.abs(lam) < threshold + # else the "regular" case: use the explicit formula. + reg_mask = ~(low_mask | neghalf_mask | small_mask) + + # Get the 'lam' values for the cases where they are needed. + small = lam[small_mask] + reg = lam[reg_mask] + + # Compute the function for each case. + v = np.empty_like(lam) + v[low_mask] = np.nan + v[neghalf_mask] = np.inf + if small.size > 0: + # Use the Pade approximation near lambda = 0. + v[small_mask] = _tukeylambda_var_p(small) / _tukeylambda_var_q(small) + if reg.size > 0: + v[reg_mask] = (2.0 / reg**2) * (1.0 / (1.0 + 2 * reg) - + beta(reg + 1, reg + 1)) + v.shape = shp + return v + + +# The following code was used to generate the Pade coefficients for the +# Tukey Lambda kurtosis function. Version 0.17 of mpmath was used. +#--------------------------------------------------------------------------- +# import mpmath as mp +# +# mp.mp.dps = 60 +# +# one = mp.mpf(1) +# two = mp.mpf(2) +# three = mp.mpf(3) +# four = mp.mpf(4) +# +# def mpkurt(lam): +# if lam == 0: +# k = mp.mpf(6)/5 +# else: +# numer = (one/(four*lam+one) - four*mp.beta(three*lam+one, lam+one) + +# three*mp.beta(two*lam+one, two*lam+one)) +# denom = two*(one/(two*lam+one) - mp.beta(lam+one,lam+one))**2 +# k = numer / denom - three +# return k +# +# # There is a bug in mpmath 0.17: when we use the 'method' keyword of the +# # taylor function and we request a degree 9 Taylor polynomial, we actually +# # get degree 8. +# t = mp.taylor(mpkurt, 0, 9, method='quad', radius=0.01) +# t = [mp.chop(c, tol=1e-15) for c in t] +# p, q = mp.pade(t, 4, 4) +# print("p =", [mp.fp.mpf(c) for c in p]) +# print("q =", [mp.fp.mpf(c) for c in q]) +#--------------------------------------------------------------------------- + +# Pade coefficients for the Tukey Lambda kurtosis function. +_tukeylambda_kurt_pc = [1.2, -5.853465139719495, -22.653447381131077, + 0.20601184383406815, 4.59796302262789] +_tukeylambda_kurt_qc = [1.0, 7.171149192233599, 12.96663094361842, + 0.43075235247853005, -2.789746758009912] + +# numpy.poly1d instances for the numerator and denominator of the +# Pade approximation to the Tukey Lambda kurtosis. +_tukeylambda_kurt_p = poly1d(_tukeylambda_kurt_pc[::-1]) +_tukeylambda_kurt_q = poly1d(_tukeylambda_kurt_qc[::-1]) + + +def tukeylambda_kurtosis(lam): + """Kurtosis of the Tukey Lambda distribution. + + Parameters + ---------- + lam : array_like + The lambda values at which to compute the variance. + + Returns + ------- + v : ndarray + The variance. For lam < -0.25, the variance is not defined, so + np.nan is returned. For lam = 0.25, np.inf is returned. + + """ + lam = np.asarray(lam) + shp = lam.shape + lam = np.atleast_1d(lam).astype(np.float64) + + # For absolute values of lam less than threshold, use the Pade + # approximation. + threshold = 0.055 + + # Use masks to implement the conditional evaluation of the kurtosis. + # lambda < -0.25: kurtosis = nan + low_mask = lam < -0.25 + # lambda == -0.25: kurtosis = inf + negqrtr_mask = lam == -0.25 + # lambda near 0: use Pade approximation + small_mask = np.abs(lam) < threshold + # else the "regular" case: use the explicit formula. + reg_mask = ~(low_mask | negqrtr_mask | small_mask) + + # Get the 'lam' values for the cases where they are needed. + small = lam[small_mask] + reg = lam[reg_mask] + + # Compute the function for each case. + k = np.empty_like(lam) + k[low_mask] = np.nan + k[negqrtr_mask] = np.inf + if small.size > 0: + k[small_mask] = _tukeylambda_kurt_p(small) / _tukeylambda_kurt_q(small) + if reg.size > 0: + numer = (1.0 / (4 * reg + 1) - 4 * beta(3 * reg + 1, reg + 1) + + 3 * beta(2 * reg + 1, 2 * reg + 1)) + denom = 2 * (1.0/(2 * reg + 1) - beta(reg + 1, reg + 1))**2 + k[reg_mask] = numer / denom - 3 + + # The return value will be a numpy array; resetting the shape ensures that + # if `lam` was a scalar, the return value is a 0-d array. + k.shape = shp + return k diff --git a/shared/package-files/7a/7a87e418b6d8d14d8c11d63708b38d607d28f7ddbf39606c7d8fba22be7892ca/blob b/shared/package-files/7a/7a87e418b6d8d14d8c11d63708b38d607d28f7ddbf39606c7d8fba22be7892ca/blob new file mode 100644 index 0000000000000000000000000000000000000000..55b19bf949e4e0b07d28d69f23a5c44aad764062 --- /dev/null +++ b/shared/package-files/7a/7a87e418b6d8d14d8c11d63708b38d607d28f7ddbf39606c7d8fba22be7892ca/blob @@ -0,0 +1,52 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset fr DAYS_OF_WEEK_ABBREV [list \ + "dim."\ + "lun."\ + "mar."\ + "mer."\ + "jeu."\ + "ven."\ + "sam."] + ::msgcat::mcset fr DAYS_OF_WEEK_FULL [list \ + "dimanche"\ + "lundi"\ + "mardi"\ + "mercredi"\ + "jeudi"\ + "vendredi"\ + "samedi"] + ::msgcat::mcset fr MONTHS_ABBREV [list \ + "janv."\ + "f\u00e9vr."\ + "mars"\ + "avr."\ + "mai"\ + "juin"\ + "juil."\ + "ao\u00fbt"\ + "sept."\ + "oct."\ + "nov."\ + "d\u00e9c."\ + ""] + ::msgcat::mcset fr MONTHS_FULL [list \ + "janvier"\ + "f\u00e9vrier"\ + "mars"\ + "avril"\ + "mai"\ + "juin"\ + "juillet"\ + "ao\u00fbt"\ + "septembre"\ + "octobre"\ + "novembre"\ + "d\u00e9cembre"\ + ""] + ::msgcat::mcset fr BCE "av. J.-C." + ::msgcat::mcset fr CE "ap. J.-C." + ::msgcat::mcset fr DATE_FORMAT "%e %B %Y" + ::msgcat::mcset fr TIME_FORMAT "%H:%M:%S" + ::msgcat::mcset fr DATE_TIME_FORMAT "%e %B %Y %H:%M:%S %z" +} diff --git a/shared/package-files/7a/7a8868536e6bc594dc106762da3148a76978484faa04aed6ae060885784eb32a/blob b/shared/package-files/7a/7a8868536e6bc594dc106762da3148a76978484faa04aed6ae060885784eb32a/blob new file mode 100644 index 0000000000000000000000000000000000000000..4baeadeb11b8e62cdb7a45f9826b94e804b44a05 --- /dev/null +++ b/shared/package-files/7a/7a8868536e6bc594dc106762da3148a76978484faa04aed6ae060885784eb32a/blob @@ -0,0 +1,391 @@ +import os +import time +import shutil +import logging +import unittest +import multiprocessing +import tempfile + +import urllib3 + +import etcd +from . import helpers + +from nose.tools import nottest + + +log = logging.getLogger() + + +class EtcdIntegrationTest(unittest.TestCase): + cl_size = 3 + + @classmethod + def setUpClass(cls): + program = cls._get_exe() + cls.directory = tempfile.mkdtemp(prefix='python-etcd') + cls.processHelper = helpers.EtcdProcessHelper( + cls.directory, + proc_name=program, + port_range_start=6001, + internal_port_range_start=8001) + cls.processHelper.run(number=cls.cl_size) + cls.client = etcd.Client(port=6001) + + @classmethod + def tearDownClass(cls): + cls.processHelper.stop() + shutil.rmtree(cls.directory) + + @classmethod + def _is_exe(cls, fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + @classmethod + def _get_exe(cls): + PROGRAM = 'etcd' + + program_path = None + + for path in os.environ["PATH"].split(os.pathsep): + path = path.strip('"') + exe_file = os.path.join(path, PROGRAM) + if cls._is_exe(exe_file): + program_path = exe_file + break + + if not program_path: + raise Exception('etcd not in path!!') + + return program_path + + +class TestSimple(EtcdIntegrationTest): + + def test_machines(self): + """ INTEGRATION: retrieve machines """ + self.assertEquals(self.client.machines[0], 'http://127.0.0.1:6001') + + def test_leader(self): + """ INTEGRATION: retrieve leader """ + self.assertIn(self.client.leader['clientURLs'][0], + ['http://127.0.0.1:6001','http://127.0.0.1:6002','http://127.0.0.1:6003']) + + def test_get_set_delete(self): + """ INTEGRATION: set a new value """ + try: + get_result = self.client.get('/test_set') + assert False + except etcd.EtcdKeyNotFound as e: + pass + + self.assertFalse('/test_set' in self.client) + + set_result = self.client.set('/test_set', 'test-key') + self.assertEquals('set', set_result.action.lower()) + self.assertEquals('/test_set', set_result.key) + self.assertEquals('test-key', set_result.value) + + self.assertTrue('/test_set' in self.client) + + get_result = self.client.get('/test_set') + self.assertEquals('get', get_result.action.lower()) + self.assertEquals('/test_set', get_result.key) + self.assertEquals('test-key', get_result.value) + + delete_result = self.client.delete('/test_set') + self.assertEquals('delete', delete_result.action.lower()) + self.assertEquals('/test_set', delete_result.key) + + self.assertFalse('/test_set' in self.client) + + try: + get_result = self.client.get('/test_set') + assert False + except etcd.EtcdKeyNotFound as e: + pass + + def test_update(self): + """INTEGRATION: update a value""" + self.client.set('/foo', 3) + c = self.client.get('/foo') + c.value = int(c.value) + 3 + self.client.update(c) + newres = self.client.get('/foo') + self.assertEquals(newres.value, u'6') + self.assertRaises(ValueError, self.client.update, c) + + def test_retrieve_subkeys(self): + """ INTEGRATION: retrieve multiple subkeys """ + set_result = self.client.write('/subtree/test_set', 'test-key1') + set_result = self.client.write('/subtree/test_set1', 'test-key2') + set_result = self.client.write('/subtree/test_set2', 'test-key3') + get_result = self.client.read('/subtree', recursive=True) + result = [subkey.value for subkey in get_result.leaves] + self.assertEquals(['test-key1', 'test-key2', 'test-key3'].sort(), result.sort()) + + def test_directory_ttl_update(self): + """ INTEGRATION: should be able to update a dir TTL """ + self.client.write('/dir', None, dir=True, ttl=30) + res = self.client.write('/dir', None, dir=True, ttl=31, prevExist=True) + self.assertEquals(res.ttl, 31) + res = self.client.get('/dir') + res.ttl = 120 + new_res = self.client.update(res) + self.assertEquals(new_res.ttl, 120) + + + +class TestErrors(EtcdIntegrationTest): + + def test_is_not_a_file(self): + """ INTEGRATION: try to write value to an existing directory """ + + self.client.set('/directory/test-key', 'test-value') + self.assertRaises(etcd.EtcdNotFile, self.client.set, '/directory', 'test-value') + + def test_test_and_set(self): + """ INTEGRATION: try test_and_set operation """ + + set_result = self.client.set('/test-key', 'old-test-value') + + set_result = self.client.test_and_set( + '/test-key', + 'test-value', + 'old-test-value') + + self.assertRaises(ValueError, self.client.test_and_set, '/test-key', 'new-value', 'old-test-value') + + def test_creating_already_existing_directory(self): + """ INTEGRATION: creating an already existing directory without + `prevExist=True` should fail """ + self.client.write('/mydir', None, dir=True) + + self.assertRaises(etcd.EtcdNotFile, self.client.write, '/mydir', None, dir=True) + self.assertRaises(etcd.EtcdAlreadyExist, self.client.write, '/mydir', None, dir=True, prevExist=False) + + +class TestClusterFunctions(EtcdIntegrationTest): + + @classmethod + def setUpClass(cls): + program = cls._get_exe() + cls.directory = tempfile.mkdtemp(prefix='python-etcd') + + cls.processHelper = helpers.EtcdProcessHelper( + cls.directory, + proc_name=program, + port_range_start=6001, + internal_port_range_start=8001, + cluster=True) + + def test_reconnect(self): + """ INTEGRATION: get key after the server we're connected fails. """ + self.processHelper.stop() + self.processHelper.run(number=3) + self.client = etcd.Client(port=6001, allow_reconnect=True) + set_result = self.client.set('/test_set', 'test-key1') + get_result = self.client.get('/test_set') + + self.assertEquals('test-key1', get_result.value) + + self.processHelper.kill_one(0) + + get_result = self.client.get('/test_set') + self.assertEquals('test-key1', get_result.value) + + def test_reconnect_with_several_hosts_passed(self): + """ INTEGRATION: receive several hosts at connection setup. """ + self.processHelper.stop() + self.processHelper.run(number=3) + self.client = etcd.Client( + host=( + ('127.0.0.1', 6004), + ('127.0.0.1', 6001)), + allow_reconnect=True) + set_result = self.client.set('/test_set', 'test-key1') + get_result = self.client.get('/test_set') + + self.assertEquals('test-key1', get_result.value) + + self.processHelper.kill_one(0) + + get_result = self.client.get('/test_set') + self.assertEquals('test-key1', get_result.value) + + def test_reconnect_not_allowed(self): + """ INTEGRATION: fail on server kill if not allow_reconnect """ + self.processHelper.stop() + self.processHelper.run(number=3) + self.client = etcd.Client(port=6001, allow_reconnect=False) + self.processHelper.kill_one(0) + self.assertRaises(etcd.EtcdConnectionFailed, self.client.get, + '/test_set') + + def test_reconnet_fails(self): + """ INTEGRATION: fails to reconnect if no available machines """ + self.processHelper.stop() + # Start with three instances (0, 1, 2) + self.processHelper.run(number=3) + # Connect to instance 0 + self.client = etcd.Client(port=6001, allow_reconnect=True) + set_result = self.client.set('/test_set', 'test-key1') + + get_result = self.client.get('/test_set') + self.assertEquals('test-key1', get_result.value) + self.processHelper.kill_one(2) + self.processHelper.kill_one(1) + self.processHelper.kill_one(0) + self.assertRaises(etcd.EtcdException, self.client.get, '/test_set') + + +class TestWatch(EtcdIntegrationTest): + + def test_watch(self): + """ INTEGRATION: Receive a watch event from other process """ + + set_result = self.client.set('/test-key', 'test-value') + + queue = multiprocessing.Queue() + + def change_value(key, newValue): + c = etcd.Client(port=6001) + c.set(key, newValue) + + def watch_value(key, queue): + c = etcd.Client(port=6001) + queue.put(c.watch(key).value) + + changer = multiprocessing.Process( + target=change_value, args=('/test-key', 'new-test-value',)) + + watcher = multiprocessing.Process( + target=watch_value, args=('/test-key', queue)) + + watcher.start() + time.sleep(1) + + changer.start() + + value = queue.get(timeout=2) + watcher.join(timeout=5) + changer.join(timeout=5) + + assert value == 'new-test-value' + + def test_watch_indexed(self): + """ INTEGRATION: Receive a watch event from other process, indexed """ + + set_result = self.client.set('/test-key', 'test-value') + set_result = self.client.set('/test-key', 'test-value0') + original_index = int(set_result.modifiedIndex) + set_result = self.client.set('/test-key', 'test-value1') + set_result = self.client.set('/test-key', 'test-value2') + + queue = multiprocessing.Queue() + + def change_value(key, newValue): + c = etcd.Client(port=6001) + c.set(key, newValue) + c.get(key) + + def watch_value(key, index, queue): + c = etcd.Client(port=6001) + for i in range(0, 3): + queue.put(c.watch(key, index=index + i).value) + + proc = multiprocessing.Process( + target=change_value, args=('/test-key', 'test-value3',)) + + watcher = multiprocessing.Process( + target=watch_value, args=('/test-key', original_index, queue)) + + watcher.start() + time.sleep(0.5) + + proc.start() + + for i in range(0, 3): + value = queue.get() + log.debug("index: %d: %s" % (i, value)) + self.assertEquals('test-value%d' % i, value) + + watcher.join(timeout=5) + proc.join(timeout=5) + + def test_watch_generator(self): + """ INTEGRATION: Receive a watch event from other process (gen) """ + + set_result = self.client.set('/test-key', 'test-value') + + queue = multiprocessing.Queue() + + def change_value(key): + time.sleep(0.5) + c = etcd.Client(port=6001) + for i in range(0, 3): + c.set(key, 'test-value%d' % i) + c.get(key) + + def watch_value(key, queue): + c = etcd.Client(port=6001) + for i in range(0, 3): + event = next(c.eternal_watch(key)).value + queue.put(event) + + changer = multiprocessing.Process( + target=change_value, args=('/test-key',)) + + watcher = multiprocessing.Process( + target=watch_value, args=('/test-key', queue)) + + watcher.start() + changer.start() + + values = ['test-value0', 'test-value1', 'test-value2'] + for i in range(0, 1): + value = queue.get() + log.debug("index: %d: %s" % (i, value)) + self.assertTrue(value in values) + + watcher.join(timeout=5) + changer.join(timeout=5) + + def test_watch_indexed_generator(self): + """ INTEGRATION: Receive a watch event from other process, ixd, (2) """ + + set_result = self.client.set('/test-key', 'test-value') + set_result = self.client.set('/test-key', 'test-value0') + original_index = int(set_result.modifiedIndex) + set_result = self.client.set('/test-key', 'test-value1') + set_result = self.client.set('/test-key', 'test-value2') + + queue = multiprocessing.Queue() + + def change_value(key, newValue): + c = etcd.Client(port=6001) + c.set(key, newValue) + + def watch_value(key, index, queue): + c = etcd.Client(port=6001) + iterevents = c.eternal_watch(key, index=index) + for i in range(0, 3): + queue.put(next(iterevents).value) + + proc = multiprocessing.Process( + target=change_value, args=('/test-key', 'test-value3',)) + + watcher = multiprocessing.Process( + target=watch_value, args=('/test-key', original_index, queue)) + + watcher.start() + time.sleep(0.5) + proc.start() + + for i in range(0, 3): + value = queue.get() + log.debug("index: %d: %s" % (i, value)) + self.assertEquals('test-value%d' % i, value) + + watcher.join(timeout=5) + proc.join(timeout=5) diff --git a/shared/package-files/7a/7a8a539c8b990aeffea06188b98dc437fd2a6e89ff66483ef334994e73fd0ec9/blob b/shared/package-files/7a/7a8a539c8b990aeffea06188b98dc437fd2a6e89ff66483ef334994e73fd0ec9/blob new file mode 100644 index 0000000000000000000000000000000000000000..296768043ace0d2e12e69cbfae2bf65d6602ab5c --- /dev/null +++ b/shared/package-files/7a/7a8a539c8b990aeffea06188b98dc437fd2a6e89ff66483ef334994e73fd0ec9/blob @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset kw_GB DATE_FORMAT "%d %B %Y" + ::msgcat::mcset kw_GB TIME_FORMAT_12 "%l:%M:%S %P" + ::msgcat::mcset kw_GB DATE_TIME_FORMAT "%d %B %Y %l:%M:%S %P %z" +} diff --git a/shared/package-files/7a/7a8b301fe75a304065b9ea15a715eb0e5a1a842a6bd112f31dbaf7cc11ceb239/blob b/shared/package-files/7a/7a8b301fe75a304065b9ea15a715eb0e5a1a842a6bd112f31dbaf7cc11ceb239/blob new file mode 100644 index 0000000000000000000000000000000000000000..659e0e96bd09d95c7241c10c3b3569ae7e84cf13 --- /dev/null +++ b/shared/package-files/7a/7a8b301fe75a304065b9ea15a715eb0e5a1a842a6bd112f31dbaf7cc11ceb239/blob @@ -0,0 +1,896 @@ +import textwrap, re, sys, subprocess, shlex +from pathlib import Path +from collections import namedtuple +import platform + +import pytest + +from . import util +from numpy.f2py.f2py2e import main as f2pycli + +######################### +# CLI utils and classes # +######################### + +PPaths = namedtuple("PPaths", "finp, f90inp, pyf, wrap77, wrap90, cmodf") + + +def get_io_paths(fname_inp, mname="untitled"): + """Takes in a temporary file for testing and returns the expected output and input paths + + Here expected output is essentially one of any of the possible generated + files. + + ..note:: + + Since this does not actually run f2py, none of these are guaranteed to + exist, and module names are typically incorrect + + Parameters + ---------- + fname_inp : str + The input filename + mname : str, optional + The name of the module, untitled by default + + Returns + ------- + genp : NamedTuple PPaths + The possible paths which are generated, not all of which exist + """ + bpath = Path(fname_inp) + return PPaths( + finp=bpath.with_suffix(".f"), + f90inp=bpath.with_suffix(".f90"), + pyf=bpath.with_suffix(".pyf"), + wrap77=bpath.with_name(f"{mname}-f2pywrappers.f"), + wrap90=bpath.with_name(f"{mname}-f2pywrappers2.f90"), + cmodf=bpath.with_name(f"{mname}module.c"), + ) + + +############## +# CLI Fixtures and Tests # +############# + + +@pytest.fixture(scope="session") +def hello_world_f90(tmpdir_factory): + """Generates a single f90 file for testing""" + fdat = util.getpath("tests", "src", "cli", "hiworld.f90").read_text() + fn = tmpdir_factory.getbasetemp() / "hello.f90" + fn.write_text(fdat, encoding="ascii") + return fn + + +@pytest.fixture(scope="session") +def gh23598_warn(tmpdir_factory): + """F90 file for testing warnings in gh23598""" + fdat = util.getpath("tests", "src", "crackfortran", "gh23598Warn.f90").read_text() + fn = tmpdir_factory.getbasetemp() / "gh23598Warn.f90" + fn.write_text(fdat, encoding="ascii") + return fn + + +@pytest.fixture(scope="session") +def gh22819_cli(tmpdir_factory): + """F90 file for testing disallowed CLI arguments in ghff819""" + fdat = util.getpath("tests", "src", "cli", "gh_22819.pyf").read_text() + fn = tmpdir_factory.getbasetemp() / "gh_22819.pyf" + fn.write_text(fdat, encoding="ascii") + return fn + + +@pytest.fixture(scope="session") +def hello_world_f77(tmpdir_factory): + """Generates a single f77 file for testing""" + fdat = util.getpath("tests", "src", "cli", "hi77.f").read_text() + fn = tmpdir_factory.getbasetemp() / "hello.f" + fn.write_text(fdat, encoding="ascii") + return fn + + +@pytest.fixture(scope="session") +def retreal_f77(tmpdir_factory): + """Generates a single f77 file for testing""" + fdat = util.getpath("tests", "src", "return_real", "foo77.f").read_text() + fn = tmpdir_factory.getbasetemp() / "foo.f" + fn.write_text(fdat, encoding="ascii") + return fn + +@pytest.fixture(scope="session") +def f2cmap_f90(tmpdir_factory): + """Generates a single f90 file for testing""" + fdat = util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90").read_text() + f2cmap = util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap").read_text() + fn = tmpdir_factory.getbasetemp() / "f2cmap.f90" + fmap = tmpdir_factory.getbasetemp() / "mapfile" + fn.write_text(fdat, encoding="ascii") + fmap.write_text(f2cmap, encoding="ascii") + return fn + + +def test_gh22819_cli(capfd, gh22819_cli, monkeypatch): + """Check that module names are handled correctly + gh-22819 + Essentially, the -m name cannot be used to import the module, so the module + named in the .pyf needs to be used instead + + CLI :: -m and a .pyf file + """ + ipath = Path(gh22819_cli) + monkeypatch.setattr(sys, "argv", f"f2py -m blah {ipath}".split()) + with util.switchdir(ipath.parent): + f2pycli() + gen_paths = [item.name for item in ipath.parent.rglob("*") if item.is_file()] + assert "blahmodule.c" not in gen_paths # shouldn't be generated + assert "blah-f2pywrappers.f" not in gen_paths + assert "test_22819-f2pywrappers.f" in gen_paths + assert "test_22819module.c" in gen_paths + assert "Ignoring blah" + + +def test_gh22819_many_pyf(capfd, gh22819_cli, monkeypatch): + """Only one .pyf file allowed + gh-22819 + CLI :: .pyf files + """ + ipath = Path(gh22819_cli) + monkeypatch.setattr(sys, "argv", f"f2py -m blah {ipath} hello.pyf".split()) + with util.switchdir(ipath.parent): + with pytest.raises(ValueError, match="Only one .pyf file per call"): + f2pycli() + + +def test_gh23598_warn(capfd, gh23598_warn, monkeypatch): + foutl = get_io_paths(gh23598_warn, mname="test") + ipath = foutl.f90inp + monkeypatch.setattr( + sys, "argv", + f'f2py {ipath} -m test'.split()) + + with util.switchdir(ipath.parent): + f2pycli() # Generate files + wrapper = foutl.wrap90.read_text() + assert "intproductf2pywrap, intpr" not in wrapper + + +def test_gen_pyf(capfd, hello_world_f90, monkeypatch): + """Ensures that a signature file is generated via the CLI + CLI :: -h + """ + ipath = Path(hello_world_f90) + opath = Path(hello_world_f90).stem + ".pyf" + monkeypatch.setattr(sys, "argv", f'f2py -h {opath} {ipath}'.split()) + + with util.switchdir(ipath.parent): + f2pycli() # Generate wrappers + out, _ = capfd.readouterr() + assert "Saving signatures to file" in out + assert Path(f'{opath}').exists() + + +def test_gen_pyf_stdout(capfd, hello_world_f90, monkeypatch): + """Ensures that a signature file can be dumped to stdout + CLI :: -h + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr(sys, "argv", f'f2py -h stdout {ipath}'.split()) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Saving signatures to file" in out + assert "function hi() ! in " in out + + +def test_gen_pyf_no_overwrite(capfd, hello_world_f90, monkeypatch): + """Ensures that the CLI refuses to overwrite signature files + CLI :: -h without --overwrite-signature + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr(sys, "argv", f'f2py -h faker.pyf {ipath}'.split()) + + with util.switchdir(ipath.parent): + Path("faker.pyf").write_text("Fake news", encoding="ascii") + with pytest.raises(SystemExit): + f2pycli() # Refuse to overwrite + _, err = capfd.readouterr() + assert "Use --overwrite-signature to overwrite" in err + + +@pytest.mark.skipif((platform.system() != 'Linux') or (sys.version_info <= (3, 12)), + reason='Compiler and 3.12 required') +def test_untitled_cli(capfd, hello_world_f90, monkeypatch): + """Check that modules are named correctly + + CLI :: defaults + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr(sys, "argv", f"f2py --backend meson -c {ipath}".split()) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "untitledmodule.c" in out + + +@pytest.mark.skipif((platform.system() != 'Linux') or (sys.version_info <= (3, 12)), reason='Compiler and 3.12 required') +def test_no_py312_distutils_fcompiler(capfd, hello_world_f90, monkeypatch): + """Check that no distutils imports are performed on 3.12 + CLI :: --fcompiler --help-link --backend distutils + """ + MNAME = "hi" + foutl = get_io_paths(hello_world_f90, mname=MNAME) + ipath = foutl.f90inp + monkeypatch.setattr( + sys, "argv", f"f2py {ipath} -c --fcompiler=gfortran -m {MNAME}".split() + ) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "--fcompiler cannot be used with meson" in out + monkeypatch.setattr( + sys, "argv", f"f2py --help-link".split() + ) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Use --dep for meson builds" in out + MNAME = "hi2" # Needs to be different for a new -c + monkeypatch.setattr( + sys, "argv", f"f2py {ipath} -c -m {MNAME} --backend distutils".split() + ) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Cannot use distutils backend with Python>=3.12" in out + + +@pytest.mark.xfail +def test_f2py_skip(capfd, retreal_f77, monkeypatch): + """Tests that functions can be skipped + CLI :: skip: + """ + foutl = get_io_paths(retreal_f77, mname="test") + ipath = foutl.finp + toskip = "t0 t4 t8 sd s8 s4" + remaining = "td s0" + monkeypatch.setattr( + sys, "argv", + f'f2py {ipath} -m test skip: {toskip}'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, err = capfd.readouterr() + for skey in toskip.split(): + assert ( + f'buildmodule: Could not found the body of interfaced routine "{skey}". Skipping.' + in err) + for rkey in remaining.split(): + assert f'Constructing wrapper function "{rkey}"' in out + + +def test_f2py_only(capfd, retreal_f77, monkeypatch): + """Test that functions can be kept by only: + CLI :: only: + """ + foutl = get_io_paths(retreal_f77, mname="test") + ipath = foutl.finp + toskip = "t0 t4 t8 sd s8 s4" + tokeep = "td s0" + monkeypatch.setattr( + sys, "argv", + f'f2py {ipath} -m test only: {tokeep}'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, err = capfd.readouterr() + for skey in toskip.split(): + assert ( + f'buildmodule: Could not find the body of interfaced routine "{skey}". Skipping.' + in err) + for rkey in tokeep.split(): + assert f'Constructing wrapper function "{rkey}"' in out + + +def test_file_processing_switch(capfd, hello_world_f90, retreal_f77, + monkeypatch): + """Tests that it is possible to return to file processing mode + CLI :: : + BUG: numpy-gh #20520 + """ + foutl = get_io_paths(retreal_f77, mname="test") + ipath = foutl.finp + toskip = "t0 t4 t8 sd s8 s4" + ipath2 = Path(hello_world_f90) + tokeep = "td s0 hi" # hi is in ipath2 + mname = "blah" + monkeypatch.setattr( + sys, + "argv", + f'f2py {ipath} -m {mname} only: {tokeep} : {ipath2}'.split( + ), + ) + + with util.switchdir(ipath.parent): + f2pycli() + out, err = capfd.readouterr() + for skey in toskip.split(): + assert ( + f'buildmodule: Could not find the body of interfaced routine "{skey}". Skipping.' + in err) + for rkey in tokeep.split(): + assert f'Constructing wrapper function "{rkey}"' in out + + +def test_mod_gen_f77(capfd, hello_world_f90, monkeypatch): + """Checks the generation of files based on a module name + CLI :: -m + """ + MNAME = "hi" + foutl = get_io_paths(hello_world_f90, mname=MNAME) + ipath = foutl.f90inp + monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME}'.split()) + with util.switchdir(ipath.parent): + f2pycli() + + # Always generate C module + assert Path.exists(foutl.cmodf) + # File contains a function, check for F77 wrappers + assert Path.exists(foutl.wrap77) + + +def test_mod_gen_gh25263(capfd, hello_world_f77, monkeypatch): + """Check that pyf files are correctly generated with module structure + CLI :: -m -h pyf_file + BUG: numpy-gh #20520 + """ + MNAME = "hi" + foutl = get_io_paths(hello_world_f77, mname=MNAME) + ipath = foutl.finp + monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME} -h hi.pyf'.split()) + with util.switchdir(ipath.parent): + f2pycli() + with Path('hi.pyf').open() as hipyf: + pyfdat = hipyf.read() + assert "python module hi" in pyfdat + + +def test_lower_cmod(capfd, hello_world_f77, monkeypatch): + """Lowers cases by flag or when -h is present + + CLI :: --[no-]lower + """ + foutl = get_io_paths(hello_world_f77, mname="test") + ipath = foutl.finp + capshi = re.compile(r"HI\(\)") + capslo = re.compile(r"hi\(\)") + # Case I: --lower is passed + monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m test --lower'.split()) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert capslo.search(out) is not None + assert capshi.search(out) is None + # Case II: --no-lower is passed + monkeypatch.setattr(sys, "argv", + f'f2py {ipath} -m test --no-lower'.split()) + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert capslo.search(out) is None + assert capshi.search(out) is not None + + +def test_lower_sig(capfd, hello_world_f77, monkeypatch): + """Lowers cases in signature files by flag or when -h is present + + CLI :: --[no-]lower -h + """ + foutl = get_io_paths(hello_world_f77, mname="test") + ipath = foutl.finp + # Signature files + capshi = re.compile(r"Block: HI") + capslo = re.compile(r"Block: hi") + # Case I: --lower is implied by -h + # TODO: Clean up to prevent passing --overwrite-signature + monkeypatch.setattr( + sys, + "argv", + f'f2py {ipath} -h {foutl.pyf} -m test --overwrite-signature'.split(), + ) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert capslo.search(out) is not None + assert capshi.search(out) is None + + # Case II: --no-lower overrides -h + monkeypatch.setattr( + sys, + "argv", + f'f2py {ipath} -h {foutl.pyf} -m test --overwrite-signature --no-lower' + .split(), + ) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert capslo.search(out) is None + assert capshi.search(out) is not None + + +def test_build_dir(capfd, hello_world_f90, monkeypatch): + """Ensures that the build directory can be specified + + CLI :: --build-dir + """ + ipath = Path(hello_world_f90) + mname = "blah" + odir = "tttmp" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --build-dir {odir}'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert f"Wrote C/API module \"{mname}\"" in out + + +def test_overwrite(capfd, hello_world_f90, monkeypatch): + """Ensures that the build directory can be specified + + CLI :: --overwrite-signature + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr( + sys, "argv", + f'f2py -h faker.pyf {ipath} --overwrite-signature'.split()) + + with util.switchdir(ipath.parent): + Path("faker.pyf").write_text("Fake news", encoding="ascii") + f2pycli() + out, _ = capfd.readouterr() + assert "Saving signatures to file" in out + + +def test_latexdoc(capfd, hello_world_f90, monkeypatch): + """Ensures that TeX documentation is written out + + CLI :: --latex-doc + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --latex-doc'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Documentation is saved to file" in out + with Path(f"{mname}module.tex").open() as otex: + assert "\\documentclass" in otex.read() + + +def test_nolatexdoc(capfd, hello_world_f90, monkeypatch): + """Ensures that TeX documentation is written out + + CLI :: --no-latex-doc + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --no-latex-doc'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Documentation is saved to file" not in out + + +def test_shortlatex(capfd, hello_world_f90, monkeypatch): + """Ensures that truncated documentation is written out + + TODO: Test to ensure this has no effect without --latex-doc + CLI :: --latex-doc --short-latex + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr( + sys, + "argv", + f'f2py -m {mname} {ipath} --latex-doc --short-latex'.split(), + ) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Documentation is saved to file" in out + with Path(f"./{mname}module.tex").open() as otex: + assert "\\documentclass" not in otex.read() + + +def test_restdoc(capfd, hello_world_f90, monkeypatch): + """Ensures that RsT documentation is written out + + CLI :: --rest-doc + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --rest-doc'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "ReST Documentation is saved to file" in out + with Path(f"./{mname}module.rest").open() as orst: + assert r".. -*- rest -*-" in orst.read() + + +def test_norestexdoc(capfd, hello_world_f90, monkeypatch): + """Ensures that TeX documentation is written out + + CLI :: --no-rest-doc + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --no-rest-doc'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "ReST Documentation is saved to file" not in out + + +def test_debugcapi(capfd, hello_world_f90, monkeypatch): + """Ensures that debugging wrappers are written + + CLI :: --debug-capi + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --debug-capi'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + with Path(f"./{mname}module.c").open() as ocmod: + assert r"#define DEBUGCFUNCS" in ocmod.read() + + +@pytest.mark.xfail(reason="Consistently fails on CI.") +def test_debugcapi_bld(hello_world_f90, monkeypatch): + """Ensures that debugging wrappers work + + CLI :: --debug-capi -c + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} -c --debug-capi'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + cmd_run = shlex.split("python3 -c \"import blah; blah.hi()\"") + rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8') + eout = ' Hello World\n' + eerr = textwrap.dedent("""\ +debug-capi:Python C/API function blah.hi() +debug-capi:float hi=:output,hidden,scalar +debug-capi:hi=0 +debug-capi:Fortran subroutine `f2pywraphi(&hi)' +debug-capi:hi=0 +debug-capi:Building return value. +debug-capi:Python C/API function blah.hi: successful. +debug-capi:Freeing memory. + """) + assert rout.stdout == eout + assert rout.stderr == eerr + + +def test_wrapfunc_def(capfd, hello_world_f90, monkeypatch): + """Ensures that fortran subroutine wrappers for F77 are included by default + + CLI :: --[no]-wrap-functions + """ + # Implied + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", f'f2py -m {mname} {ipath}'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert r"Fortran 77 wrappers are saved to" in out + + # Explicit + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --wrap-functions'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert r"Fortran 77 wrappers are saved to" in out + + +def test_nowrapfunc(capfd, hello_world_f90, monkeypatch): + """Ensures that fortran subroutine wrappers for F77 can be disabled + + CLI :: --no-wrap-functions + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr(sys, "argv", + f'f2py -m {mname} {ipath} --no-wrap-functions'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert r"Fortran 77 wrappers are saved to" not in out + + +def test_inclheader(capfd, hello_world_f90, monkeypatch): + """Add to the include directories + + CLI :: -include + TODO: Document this in the help string + """ + ipath = Path(hello_world_f90) + mname = "blah" + monkeypatch.setattr( + sys, + "argv", + f'f2py -m {mname} {ipath} -include -include '. + split(), + ) + + with util.switchdir(ipath.parent): + f2pycli() + with Path(f"./{mname}module.c").open() as ocmod: + ocmr = ocmod.read() + assert "#include " in ocmr + assert "#include " in ocmr + + +def test_inclpath(): + """Add to the include directories + + CLI :: --include-paths + """ + # TODO: populate + pass + + +def test_hlink(): + """Add to the include directories + + CLI :: --help-link + """ + # TODO: populate + pass + + +def test_f2cmap(capfd, f2cmap_f90, monkeypatch): + """Check that Fortran-to-Python KIND specs can be passed + + CLI :: --f2cmap + """ + ipath = Path(f2cmap_f90) + monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --f2cmap mapfile'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "Reading f2cmap from 'mapfile' ..." in out + assert "Mapping \"real(kind=real32)\" to \"float\"" in out + assert "Mapping \"real(kind=real64)\" to \"double\"" in out + assert "Mapping \"integer(kind=int64)\" to \"long_long\"" in out + assert "Successfully applied user defined f2cmap changes" in out + + +def test_quiet(capfd, hello_world_f90, monkeypatch): + """Reduce verbosity + + CLI :: --quiet + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --quiet'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert len(out) == 0 + + +def test_verbose(capfd, hello_world_f90, monkeypatch): + """Increase verbosity + + CLI :: --verbose + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --verbose'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + out, _ = capfd.readouterr() + assert "analyzeline" in out + + +def test_version(capfd, monkeypatch): + """Ensure version + + CLI :: -v + """ + monkeypatch.setattr(sys, "argv", 'f2py -v'.split()) + # TODO: f2py2e should not call sys.exit() after printing the version + with pytest.raises(SystemExit): + f2pycli() + out, _ = capfd.readouterr() + import numpy as np + assert np.__version__ == out.strip() + + +@pytest.mark.xfail(reason="Consistently fails on CI.") +def test_npdistop(hello_world_f90, monkeypatch): + """ + CLI :: -c + """ + ipath = Path(hello_world_f90) + monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} -c'.split()) + + with util.switchdir(ipath.parent): + f2pycli() + cmd_run = shlex.split("python -c \"import blah; blah.hi()\"") + rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8') + eout = ' Hello World\n' + assert rout.stdout == eout + + +# Numpy distutils flags +# TODO: These should be tested separately + + +def test_npd_fcompiler(): + """ + CLI :: -c --fcompiler + """ + # TODO: populate + pass + + +def test_npd_compiler(): + """ + CLI :: -c --compiler + """ + # TODO: populate + pass + + +def test_npd_help_fcompiler(): + """ + CLI :: -c --help-fcompiler + """ + # TODO: populate + pass + + +def test_npd_f77exec(): + """ + CLI :: -c --f77exec + """ + # TODO: populate + pass + + +def test_npd_f90exec(): + """ + CLI :: -c --f90exec + """ + # TODO: populate + pass + + +def test_npd_f77flags(): + """ + CLI :: -c --f77flags + """ + # TODO: populate + pass + + +def test_npd_f90flags(): + """ + CLI :: -c --f90flags + """ + # TODO: populate + pass + + +def test_npd_opt(): + """ + CLI :: -c --opt + """ + # TODO: populate + pass + + +def test_npd_arch(): + """ + CLI :: -c --arch + """ + # TODO: populate + pass + + +def test_npd_noopt(): + """ + CLI :: -c --noopt + """ + # TODO: populate + pass + + +def test_npd_noarch(): + """ + CLI :: -c --noarch + """ + # TODO: populate + pass + + +def test_npd_debug(): + """ + CLI :: -c --debug + """ + # TODO: populate + pass + + +def test_npd_link_auto(): + """ + CLI :: -c --link- + """ + # TODO: populate + pass + + +def test_npd_lib(): + """ + CLI :: -c -L/path/to/lib/ -l + """ + # TODO: populate + pass + + +def test_npd_define(): + """ + CLI :: -D + """ + # TODO: populate + pass + + +def test_npd_undefine(): + """ + CLI :: -U + """ + # TODO: populate + pass + + +def test_npd_incl(): + """ + CLI :: -I/path/to/include/ + """ + # TODO: populate + pass + + +def test_npd_linker(): + """ + CLI :: .o .so .a + """ + # TODO: populate + pass diff --git a/shared/package-files/7a/7a8e65c03ac6efc6bd5e531d4a351076eb9dd68276403b4f2f2626bbd81c6faf/blob b/shared/package-files/7a/7a8e65c03ac6efc6bd5e531d4a351076eb9dd68276403b4f2f2626bbd81c6faf/blob new file mode 100644 index 0000000000000000000000000000000000000000..b594cefe7f6fc3fbd79f3b5663df75e0125f20e0 --- /dev/null +++ b/shared/package-files/7a/7a8e65c03ac6efc6bd5e531d4a351076eb9dd68276403b4f2f2626bbd81c6faf/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & repeat_interleave_out(at::Tensor & out, const at::Tensor & repeats, c10::optional output_size=c10::nullopt); +TORCH_API at::Tensor & repeat_interleave_outf(const at::Tensor & repeats, c10::optional output_size, at::Tensor & out); +TORCH_API at::Tensor & repeat_interleave_symint_out(at::Tensor & out, const at::Tensor & repeats, c10::optional output_size=c10::nullopt); +TORCH_API at::Tensor & repeat_interleave_symint_outf(const at::Tensor & repeats, c10::optional output_size, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/7a/7a8f0d4e6b3217d343deba9707a889e5d6bb05154b881f0f235125f3082242bd/blob b/shared/package-files/7a/7a8f0d4e6b3217d343deba9707a889e5d6bb05154b881f0f235125f3082242bd/blob new file mode 100644 index 0000000000000000000000000000000000000000..7a102e6c9105382d52f0fee50e1b68ff53644596 --- /dev/null +++ b/shared/package-files/7a/7a8f0d4e6b3217d343deba9707a889e5d6bb05154b881f0f235125f3082242bd/blob @@ -0,0 +1,124 @@ +import os +import sys +import warnings +from typing import Any, Callable, NoReturn, Type, Union + +from cryptography.hazmat.bindings.openssl.binding import Binding + +StrOrBytesPath = Union[str, bytes, os.PathLike] + +binding = Binding() +ffi = binding.ffi +lib = binding.lib + + +# This is a special CFFI allocator that does not bother to zero its memory +# after allocation. This has vastly better performance on large allocations and +# so should be used whenever we don't need the memory zeroed out. +no_zero_allocator = ffi.new_allocator(should_clear_after_alloc=False) + + +def text(charp: Any) -> str: + """ + Get a native string type representing of the given CFFI ``char*`` object. + + :param charp: A C-style string represented using CFFI. + + :return: :class:`str` + """ + if not charp: + return "" + return ffi.string(charp).decode("utf-8") + + +def exception_from_error_queue(exception_type: Type[Exception]) -> NoReturn: + """ + Convert an OpenSSL library failure into a Python exception. + + When a call to the native OpenSSL library fails, this is usually signalled + by the return value, and an error code is stored in an error queue + associated with the current thread. The err library provides functions to + obtain these error codes and textual error messages. + """ + errors = [] + + while True: + error = lib.ERR_get_error() + if error == 0: + break + errors.append( + ( + text(lib.ERR_lib_error_string(error)), + text(lib.ERR_func_error_string(error)), + text(lib.ERR_reason_error_string(error)), + ) + ) + + raise exception_type(errors) + + +def make_assert(error: Type[Exception]) -> Callable[[bool], Any]: + """ + Create an assert function that uses :func:`exception_from_error_queue` to + raise an exception wrapped by *error*. + """ + + def openssl_assert(ok: bool) -> None: + """ + If *ok* is not True, retrieve the error from OpenSSL and raise it. + """ + if ok is not True: + exception_from_error_queue(error) + + return openssl_assert + + +def path_bytes(s: StrOrBytesPath) -> bytes: + """ + Convert a Python path to a :py:class:`bytes` for the path which can be + passed into an OpenSSL API accepting a filename. + + :param s: A path (valid for os.fspath). + + :return: An instance of :py:class:`bytes`. + """ + b = os.fspath(s) + + if isinstance(b, str): + return b.encode(sys.getfilesystemencoding()) + else: + return b + + +def byte_string(s: str) -> bytes: + return s.encode("charmap") + + +# A marker object to observe whether some optional arguments are passed any +# value or not. +UNSPECIFIED = object() + +_TEXT_WARNING = "str for {0} is no longer accepted, use bytes" + + +def text_to_bytes_and_warn(label: str, obj: Any) -> Any: + """ + If ``obj`` is text, emit a warning that it should be bytes instead and try + to convert it to bytes automatically. + + :param str label: The name of the parameter from which ``obj`` was taken + (so a developer can easily find the source of the problem and correct + it). + + :return: If ``obj`` is the text string type, a ``bytes`` object giving the + UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is + returned. + """ + if isinstance(obj, str): + warnings.warn( + _TEXT_WARNING.format(label), + category=DeprecationWarning, + stacklevel=3, + ) + return obj.encode("utf-8") + return obj diff --git a/shared/package-files/7a/7a920d0f27a144f58d2454a253e76b7909b87663a39387266b0d488f99c0b4e5/blob b/shared/package-files/7a/7a920d0f27a144f58d2454a253e76b7909b87663a39387266b0d488f99c0b4e5/blob new file mode 100644 index 0000000000000000000000000000000000000000..47184af418c27832914b048b13be6e3d456eab55 --- /dev/null +++ b/shared/package-files/7a/7a920d0f27a144f58d2454a253e76b7909b87663a39387266b0d488f99c0b4e5/blob @@ -0,0 +1,246 @@ +from typing import Any, cast, Optional, Union + +import typing_extensions + +import torch +import torch.nn as nn + +from torch.distributed._composable import contract +from torch.distributed._tensor import DeviceMesh, DTensor + +from ._fsdp_api import MixedPrecisionPolicy +from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo +from ._fsdp_init import ( + _get_device_from_mesh, + _get_managed_modules, + _get_managed_states, + _get_post_forward_mesh_info, + _init_default_fully_shard_mesh, + _move_states_to_device, +) +from ._fsdp_param_group import FSDPParamGroup +from ._fsdp_state import _get_module_fsdp_state, FSDPState + + +# The decorator adds a state object to `module` that can be accessed via +# `fully_shard.state(module)`. The state object and module are 1:1. +@contract(state_cls=FSDPState) +def fully_shard( + module: nn.Module, + *, + mesh: Optional[DeviceMesh] = None, + reshard_after_forward: Union[bool, int] = True, + mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(), +): + """ + Shard module parameters across data parallel workers. + + This function applies fully sharded data parallelism (FSDP) or a variant to + ``module``, a technique for memory savings at the cost of communication. + Parameters are sharded across ``mesh``, and in turn, so are their gradients + and optimizer states. + + The sharded parameters are all-gathered to construct the unsharded + parameters for forward or backward computation. The unsharded parameters + are freed after computation to save memory. The gradients are reduced + across the mesh and divided by the mesh size for data parallelism. The + optimizer step runs on the sharded parameters. + + Each call to ``fully_shard`` constructs one communication group that + includes the parameters in ``module.parameters()`` except those already + assigned to a group from a nested call. Each group's parameters and its + gradients are communicated together in one collective, respectively. + Constructing multiple groups across the model (e.g. "layer by layer") + allows for peak memory savings and communication/computation overlap. + + Implementation-wise, the sharded parameters are represented as + :class:`DTensor` s, sharded on dim-0, and the unsharded parameters are + represented as :class:`Tensor` s. A module forward pre-hook all-gathers the + parameters, and a module forward hook frees them. Similar backward hooks + gather parameters and later free parameters/reduce gradients. + + Args: + mesh (Optional[DeviceMesh]): This data parallel mesh defines the + sharding and device. If 1D, then parameters are fully sharded + across the 1D mesh (FSDP). If 2D, then parameters are sharded + across the 0th dim and replicated across the 1st dim (HSDP). The + mesh's device type gives the device type used for communication; + if a CUDA or CUDA-like device type, then we use the current device. + reshard_after_forward (Union[bool, int]): This controls the parameter + behavior after forward and can trade off memory and communication: + - If ``True``, then this reshards parameters after forward and + all-gathers in backward. + - If ``False``, then this keeps the unsharded parameters in memory + after forward and avoids the all-gather in backward. + - If an ``int``, then this represents the world size to reshard to + after forward. It should be a non-trivial divisor of the ``mesh`` + shard dim size (i.e. excluding 1 and the dim size itself). A choice + may be the intra-node size (e.g. ``torch.cuda.device_count()``). + This allows the all-gather in backward to be over a smaller world + size at the cost of higher memory usage than setting to ``True``. + - The root FSDP state has its value specially set to ``False`` as a + heuristic since its parameters would typically be immediately + all-gathered for backward. + - After forward, the parameters registered to the module depend on + to this: The registered parameters are the sharded parameters if + ``True``; unsharded parameters if ``False``; and the paramters + resharded to the smaller mesh otherwise. To modify the parameters + between forward and backward, the registered parameters must be the + sharded parameters. For ``False`` or an ``int``, this can be done + by manually resharding via :meth:`reshard`. + mp_policy (MixedPrecisionPolicy): This controls the mixed precision + policy, which offers parameter/reduction mixed precision for this + module. See :class:`MixedPrecisionPolicy` for details. + """ + if isinstance(module, (nn.ModuleList, nn.ModuleDict)): + raise ValueError( + f"fully_shard does not support containers that do not implement forward: {module}" + ) + mesh = mesh or _init_default_fully_shard_mesh() + if mesh.ndim not in (1, 2): + raise ValueError(f"fully_shard expects a 1D or 2D DeviceMesh but got {mesh}") + elif mesh.ndim == 1: + mesh_info = FSDPMeshInfo(mesh, shard_mesh_dim=0) + else: + mesh_info = HSDPMeshInfo(mesh, shard_mesh_dim=1, replicate_mesh_dim=0) + device = _get_device_from_mesh(mesh) + post_forward_mesh_info = _get_post_forward_mesh_info( + reshard_after_forward, mesh_info + ) + + state = fully_shard.state(module) + state.init(module, device, mp_policy) + + managed_modules = _get_managed_modules(module) + params, buffers = _get_managed_states(managed_modules) + _move_states_to_device(params, buffers, device, mesh_info) + if params: + state._fsdp_param_group = FSDPParamGroup( + params, module, mesh_info, post_forward_mesh_info, device, mp_policy + ) + + # for dynamo + for module in managed_modules: + module._is_fsdp_managed_module = True # type: ignore[assignment] + module._fsdp_use_orig_params = True # type: ignore[assignment] + + # Place FSDP leftmost for highest priority in the method resolution order + cls = module.__class__ + dct = {"__deepcopy__": unimplemented_deepcopy} + new_cls = type(f"FSDP{cls.__name__}", (FSDP, cls), dct) + module.__class__ = new_cls + return module + + +def unimplemented_deepcopy(*args: Any, **kwargs: Any) -> typing_extensions.Never: + raise AssertionError( + "FSDP does not support deepcopy. Please use state dict for serialization." + ) + + +class FSDP: + def __new__(cls, *args, **kwargs): + """ + Override ``__new__`` to remove the FSDP class and directly construct + the original class for cases like indexing into a container module. + """ + # Use index 2 since 0 is the dynamically constructed `FSDP<...>` class + # and index 1 is the `FSDP` class itself + orig_cls = cls.__mro__[2] + self = orig_cls.__new__(orig_cls, *args, **kwargs) + self.__init__(*args, **kwargs) + return self + + def reshard(self) -> None: + """ + Reshards the module's parameters, registering the sharded parameters + to the module and freeing the unsharded parameters if needed. This + method is *not* recursive. + """ + state = self._get_fsdp_state() + if fsdp_param_group := state._fsdp_param_group: + fsdp_param_group.reshard() + + def set_is_last_backward(self, is_last_backward: bool) -> None: + """ + Sets whether the next backward is the last one, meaning that FSDP + should wait for gradient reduction to finish and clear internal data + structures used for explicit prefetching. + """ + state = self._get_fsdp_state() + state._state_ctx.is_last_backward = is_last_backward + + def set_requires_gradient_sync( + self, requires_gradient_sync: bool, recurse: bool = True + ) -> None: + """ + Sets if the module should sync gradients. This can be used to implement + gradient accumulation without communication. For HSDP, this controls + both reduce-scatter and all-reduce together. + + Args: + requires_gradient_sync (bool): Whether to reduce gradients for the + module's parameters. + recurse (bool): Whether to set for all submodules or just the + passed-in module. + """ + for module in cast(nn.Module, self).modules(): + if isinstance(module, FSDP): + state = module._get_fsdp_state() + if fsdp_param_group := state._fsdp_param_group: + fsdp_param_group.reduce_scatter_grads = requires_gradient_sync + fsdp_param_group.all_reduce_grads = requires_gradient_sync + + def set_requires_all_reduce(self, requires_all_reduce: bool, recurse: bool = True): + """ + Sets if the module should all-reduce gradients. This can be used to + implement gradient accumulation with only reduce-scatter but not + all-reduce for HSDP. + """ + for module in cast(nn.Module, self).modules(): + if isinstance(module, FSDP): + state = module._get_fsdp_state() + if fsdp_param_group := state._fsdp_param_group: + fsdp_param_group.all_reduce_grads = requires_all_reduce + + def _get_fsdp_state(self) -> FSDPState: + if (state := _get_module_fsdp_state(cast(nn.Module, self))) is None: + raise AssertionError(f"No FSDP state found on {self}") + return state + + def _apply(self, *args: Any, **kwargs: Any) -> Any: + # Reshard to ensure that sharded parameters are registered + self.reshard() + ret = super()._apply(*args, **kwargs) # type: ignore[misc] + state = self._get_fsdp_state() + if not (fsdp_param_group := state._fsdp_param_group): + return ret + # TODO: Remove this padding logic once DTensor pads the local tensor: + # https://github.com/pytorch/pytorch/issues/113045 + with torch.no_grad(): + for fsdp_param in fsdp_param_group.fsdp_params: + module_info = fsdp_param._module_info + new_param = getattr(module_info.module, module_info.param_name) + if new_param is not fsdp_param.sharded_param: + if torch.__future__.get_swap_module_params_on_conversion(): + raise AssertionError( + "Expects swap_tensors to preserve object but got " + f"{new_param} instead of {fsdp_param.sharded_param}" + ) + else: + raise AssertionError( + "Please set torch.__future__.set_swap_module_params_on_conversion(True) " + "to use _apply methods with FSDP" + ) + local_tensor = new_param._local_tensor + padded_sharded_size = fsdp_param.padded_sharded_param_size + if local_tensor.size() != padded_sharded_size: + padded_local_tensor = local_tensor.new_zeros(padded_sharded_size) + padded_local_tensor[: local_tensor.size(0)].copy_(local_tensor) + local_tensor = padded_local_tensor + fsdp_param._sharded_param_data = local_tensor.view(-1) + assert isinstance(fsdp_param.sharded_param, DTensor) # mypy + fsdp_param.sharded_param._local_tensor = local_tensor[ + : fsdp_param.sharded_size[0] + ] + return ret diff --git a/shared/package-files/7a/7a93f5696ef3da1601d05b42ff1df0d401659e14a09f85159116a616555f5dde/blob b/shared/package-files/7a/7a93f5696ef3da1601d05b42ff1df0d401659e14a09f85159116a616555f5dde/blob new file mode 100644 index 0000000000000000000000000000000000000000..0040e318a6e0847a79f8ffad8b44ffe8cc684379 --- /dev/null +++ b/shared/package-files/7a/7a93f5696ef3da1601d05b42ff1df0d401659e14a09f85159116a616555f5dde/blob @@ -0,0 +1,8 @@ +from .core import Evaluator, CannotEval, group_expressions, is_expression_interesting +from .my_getattr_static import getattr_static + +try: + from .version import __version__ +except ImportError: + # version.py is auto-generated with the git tag when building + __version__ = "???" diff --git a/shared/package-files/7a/7a9653d86e9f89057a9741fefb17e6dbfb3c10ecfd1fdc6fd9c790a00c97d99e/blob b/shared/package-files/7a/7a9653d86e9f89057a9741fefb17e6dbfb3c10ecfd1fdc6fd9c790a00c97d99e/blob new file mode 100644 index 0000000000000000000000000000000000000000..3332f864aeb52e7b6de19a4d3a65362560d24f07 --- /dev/null +++ b/shared/package-files/7a/7a9653d86e9f89057a9741fefb17e6dbfb3c10ecfd1fdc6fd9c790a00c97d99e/blob @@ -0,0 +1,103 @@ +import os +from distutils import log +import itertools + + +flatten = itertools.chain.from_iterable + + +class Installer: + nspkg_ext = '-nspkg.pth' + + def install_namespaces(self): + nsp = self._get_all_ns_packages() + if not nsp: + return + filename = self._get_nspkg_file() + self.outputs.append(filename) + log.info("Installing %s", filename) + lines = map(self._gen_nspkg_line, nsp) + + if self.dry_run: + # always generate the lines, even in dry run + list(lines) + return + + with open(filename, 'wt') as f: + f.writelines(lines) + + def uninstall_namespaces(self): + filename = self._get_nspkg_file() + if not os.path.exists(filename): + return + log.info("Removing %s", filename) + os.remove(filename) + + def _get_nspkg_file(self): + filename, _ = os.path.splitext(self._get_target()) + return filename + self.nspkg_ext + + def _get_target(self): + return self.target + + _nspkg_tmpl = ( + "import sys, types, os", + "has_mfs = sys.version_info > (3, 5)", + "p = os.path.join(%(root)s, *%(pth)r)", + "importlib = has_mfs and __import__('importlib.util')", + "has_mfs and __import__('importlib.machinery')", + ( + "m = has_mfs and " + "sys.modules.setdefault(%(pkg)r, " + "importlib.util.module_from_spec(" + "importlib.machinery.PathFinder.find_spec(%(pkg)r, " + "[os.path.dirname(p)])))" + ), + ("m = m or " "sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"), + "mp = (m or []) and m.__dict__.setdefault('__path__',[])", + "(p not in mp) and mp.append(p)", + ) + "lines for the namespace installer" + + _nspkg_tmpl_multi = ('m and setattr(sys.modules[%(parent)r], %(child)r, m)',) + "additional line(s) when a parent package is indicated" + + def _get_root(self): + return "sys._getframe(1).f_locals['sitedir']" + + def _gen_nspkg_line(self, pkg): + pth = tuple(pkg.split('.')) + root = self._get_root() + tmpl_lines = self._nspkg_tmpl + parent, sep, child = pkg.rpartition('.') + if parent: + tmpl_lines += self._nspkg_tmpl_multi + return ';'.join(tmpl_lines) % locals() + '\n' + + def _get_all_ns_packages(self): + """Return sorted list of all package namespaces""" + pkgs = self.distribution.namespace_packages or [] + return sorted(set(flatten(map(self._pkg_names, pkgs)))) + + @staticmethod + def _pkg_names(pkg): + """ + Given a namespace package, yield the components of that + package. + + >>> names = Installer._pkg_names('a.b.c') + >>> set(names) == set(['a', 'a.b', 'a.b.c']) + True + """ + parts = pkg.split('.') + while parts: + yield '.'.join(parts) + parts.pop() + + +class DevelopInstaller(Installer): + def _get_root(self): + return repr(str(self.egg_path)) + + def _get_target(self): + return self.egg_link diff --git a/shared/package-files/7a/7a9b8ba5efa7d6c842a8fe41cc2f7b88c20021e39e0c776d34a1607316b1fbd0/blob b/shared/package-files/7a/7a9b8ba5efa7d6c842a8fe41cc2f7b88c20021e39e0c776d34a1607316b1fbd0/blob new file mode 100644 index 0000000000000000000000000000000000000000..8dbe1341377c37ac125e865f6783342e62e82179 --- /dev/null +++ b/shared/package-files/7a/7a9b8ba5efa7d6c842a8fe41cc2f7b88c20021e39e0c776d34a1607316b1fbd0/blob @@ -0,0 +1,24 @@ +CacheControl==0.13.1 # Make sure to update the license in pyproject.toml for this. +colorama==0.4.6 +distlib==0.3.6 +distro==1.8.0 +msgpack==1.0.5 +packaging==21.3 +platformdirs==3.8.1 +pyparsing==3.1.0 +pyproject-hooks==1.0.0 +requests==2.31.0 + certifi==2023.7.22 + chardet==5.1.0 + idna==3.4 + urllib3==1.26.17 +rich==13.4.2 + pygments==2.15.1 + typing_extensions==4.7.1 +resolvelib==1.0.1 +setuptools==68.0.0 +six==1.16.0 +tenacity==8.2.2 +tomli==2.0.1 +truststore==0.8.0 +webencodings==0.5.1 diff --git a/shared/package-files/7a/7a9e09c2d8ab3396c84df4396a6ebe9714bd00652df761f8526e23d38fceaaba/blob b/shared/package-files/7a/7a9e09c2d8ab3396c84df4396a6ebe9714bd00652df761f8526e23d38fceaaba/blob new file mode 100644 index 0000000000000000000000000000000000000000..dc3a370b00b1831ae66eb3acfb4bb483cf4e33a4 --- /dev/null +++ b/shared/package-files/7a/7a9e09c2d8ab3396c84df4396a6ebe9714bd00652df761f8526e23d38fceaaba/blob @@ -0,0 +1,144 @@ +from __future__ import annotations + +import numpy as np +from numpy.linalg import LinAlgError +import pandas as pd + +from statsmodels.tools.tools import Bunch +from statsmodels.tools.validation import ( + array_like, + dict_like, + int_like, + string_like, +) + +ArrayLike1D = np.ndarray | pd.Series | list[float] + + +def _safe_arma_fit(y, order, model_kw, trend, fit_kw, start_params=None): + from statsmodels.tsa.arima.model import ARIMA + + try: + return ARIMA(y, order=order, **model_kw, trend=trend).fit( + start_params=start_params, **fit_kw + ) + except LinAlgError: + # SVD convergence failure on badly misspecified models + return None + + except ValueError as error: + if start_params is not None: # do not recurse again + # user supplied start_params only get one chance + return None + # try a little harder, should be handled in fit really + elif "initial" not in error.args[0] or "initial" in str(error): + start_params = [0.1] * sum(order) + if trend == "c": + start_params = [0.1] + start_params + return _safe_arma_fit(y, order, model_kw, trend, fit_kw, start_params) + else: + return None + except Exception: # no idea what happened + return None + + +def arma_order_select_ic( + y, max_ar=4, max_ma=2, ic="bic", trend="c", model_kw=None, fit_kw=None +): + """ + Compute information criteria for many ARMA models + + Parameters + ---------- + y : array_like + Array of time-series data. + max_ar : int, optional + Maximum number of AR lags to use. Default 4. + max_ma : int, optional + Maximum number of MA lags to use. Default 2. + ic : str or sequence of str, optional + Information criteria to report. Either a single string or a list + of different criteria is possible. + trend : {'n', 'c'}, optional + The trend to use when fitting the ARMA models. + model_kw : dict, optional + Keyword arguments to be passed to the ``ARIMA`` model. + fit_kw : dict, optional + Keyword arguments to be passed to ``ARIMA.fit``. + + Returns + ------- + Bunch + Dict-like object with attribute access. Each ic is an attribute with a + DataFrame for the results. The AR order used is the row index. The ma + order used is the column index. The minimum orders are available as + ``ic_min_order``. + + Notes + ----- + This method can be used to tentatively identify the order of an ARMA + process, provided that the time series is stationary and invertible. This + function computes the full exact MLE estimate of each model and can + therefore be a little slow. An implementation using approximate estimates + will be provided in the future. In the meantime, consider passing + {method : "css"} to fit_kw. + + Examples + -------- + + >>> from statsmodels.tsa.arima_process import arma_generate_sample + >>> import statsmodels.api as sm + >>> import numpy as np + + >>> arparams = np.array([.75, -.25]) + >>> maparams = np.array([.65, .35]) + >>> arparams = np.r_[1, -arparams] + >>> maparams = np.r_[1, maparams] + >>> nobs = 250 + >>> np.random.seed(2014) + >>> y = arma_generate_sample(arparams, maparams, nobs) + >>> res = sm.tsa.arma_order_select_ic(y, ic=["aic", "bic"], trend="n") + >>> res.aic_min_order + >>> res.bic_min_order + """ + max_ar = int_like(max_ar, "max_ar") + max_ma = int_like(max_ma, "max_ma") + trend = string_like(trend, "trend", options=("n", "c")) + model_kw = dict_like(model_kw, "model_kw", optional=True) + fit_kw = dict_like(fit_kw, "fit_kw", optional=True) + + ar_range = list(range(max_ar + 1)) + ma_range = list(range(max_ma + 1)) + if isinstance(ic, str): + ic = [ic] + elif not isinstance(ic, (list, tuple)): + raise ValueError("Need a list or a tuple for ic if not a string.") + + results = np.zeros((len(ic), max_ar + 1, max_ma + 1)) + model_kw = {} if model_kw is None else model_kw + fit_kw = {} if fit_kw is None else fit_kw + y_arr = array_like(y, "y", contiguous=True) + for ar in ar_range: + for ma in ma_range: + mod = _safe_arma_fit(y_arr, (ar, 0, ma), model_kw, trend, fit_kw) + if mod is None: + results[:, ar, ma] = np.nan + continue + + for i, criteria in enumerate(ic): + results[i, ar, ma] = getattr(mod, criteria) + + dfs = [pd.DataFrame(res, columns=ma_range, index=ar_range) for res in results] + + res = dict(zip(ic, dfs, strict=True)) + + # add the minimums to the results dict + min_res = {} + for i, result in res.items(): + delta = np.ascontiguousarray(np.abs(result.min().min() - result)) + ncols = delta.shape[1] + loc = np.argmin(delta) + min_res.update({i + "_min_order": (loc // ncols, loc % ncols)}) + res.update(min_res) + + return Bunch(**res) diff --git a/shared/package-files/7a/7aa02f0f645fb887d20e1b6a939f0c102223cf95f5e0e1d9eda3b8cf5e249dd9/blob b/shared/package-files/7a/7aa02f0f645fb887d20e1b6a939f0c102223cf95f5e0e1d9eda3b8cf5e249dd9/blob new file mode 100644 index 0000000000000000000000000000000000000000..6e08a261274e48f93eb5e221ba294e54ca671b94 Binary files /dev/null and b/shared/package-files/7a/7aa02f0f645fb887d20e1b6a939f0c102223cf95f5e0e1d9eda3b8cf5e249dd9/blob differ diff --git a/shared/package-files/7a/7aa12d7f3a100960bc95cd703733ad45f39396a1e75147386f9325952dced56d/blob b/shared/package-files/7a/7aa12d7f3a100960bc95cd703733ad45f39396a1e75147386f9325952dced56d/blob new file mode 100644 index 0000000000000000000000000000000000000000..a84fa2e0d7095d6d20f1e376a76326e60e9d5431 --- /dev/null +++ b/shared/package-files/7a/7aa12d7f3a100960bc95cd703733ad45f39396a1e75147386f9325952dced56d/blob @@ -0,0 +1,265 @@ +"""Lazy ZIP over HTTP""" + +from __future__ import annotations + +import logging +import zipfile +from bisect import bisect_left, bisect_right +from contextlib import contextmanager +from tempfile import NamedTemporaryFile +from typing import Any, Iterator +from zipfile import BadZipfile, ZipFile + +from requests import Session +from requests.models import CONTENT_CHUNK_SIZE, Response + +# from pip 22.0.3 with fixes & remove imports from pip + + +log = logging.getLogger(__name__) + +# If-Match (etag) to detect file changed during fetch would also be nice +HEADERS = {"Accept-Encoding": "identity"} + + +class HTTPRangeRequestUnsupported(Exception): + pass + + +class LazyZipOverHTTP: + """File-like object mapped to a ZIP file over HTTP. + + This uses HTTP range requests to lazily fetch the file's content, + which is supposed to be fed to ZipFile. If such requests are not + supported by the server, raise HTTPRangeRequestUnsupported + during initialization. + """ + + def __init__( + self, url: str, session: Session, chunk_size: int = CONTENT_CHUNK_SIZE + ) -> None: + # if CONTENT_CHUNK_SIZE is bigger than the file: + # In [8]: response.headers["Content-Range"] + # Out[8]: 'bytes 0-3133374/3133375' + + self._request_count = 0 + + self._session, self._url, self._chunk_size = session, url, chunk_size + + # initial range request for the end of the file + tail = self._stream_response(start="", end=CONTENT_CHUNK_SIZE) + # e.g. {'accept-ranges': 'bytes', 'content-length': '10240', + # 'content-range': 'bytes 12824-23063/23064', 'last-modified': 'Sat, 16 + # Apr 2022 13:03:02 GMT', 'date': 'Thu, 21 Apr 2022 11:34:04 GMT'} + + if tail.status_code != 206: + raise HTTPRangeRequestUnsupported("range request is not supported") + + # lowercase content-range to support s3 + self._length = int(tail.headers["content-range"].partition("/")[-1]) + self._file = NamedTemporaryFile() + self.truncate(self._length) + + # length is also in Content-Length and Content-Range header + with self._stay(): + content_length = int(tail.headers["content-length"]) + if hasattr(tail, "content"): + assert content_length == len(tail.content) + self.seek(self._length - content_length) + for chunk in tail.iter_content(self._chunk_size): + self._file.write(chunk) + self._left: list[int] = [self._length - content_length] + self._right: list[int] = [self._length - 1] + + @property + def mode(self) -> str: + """Opening mode, which is always rb.""" + return "rb" + + @property + def name(self) -> str: + """Path to the underlying file.""" + return self._file.name + + def seekable(self) -> bool: + """Return whether random access is supported, which is True.""" + return True + + def close(self) -> None: + """Close the file.""" + self._file.close() + + @property + def closed(self) -> bool: + """Whether the file is closed.""" + return self._file.closed + + def read(self, size: int = -1) -> bytes: + """Read up to size bytes from the object and return them. + + As a convenience, if size is unspecified or -1, + all bytes until EOF are returned. Fewer than + size bytes may be returned if EOF is reached. + """ + # BUG does not download correctly if size is unspecified + download_size = size + start, length = self.tell(), self._length + stop = length if size < 0 else min(start + download_size, length) + start = max(0, stop - download_size) + self._download(start, stop - 1) + return self._file.read(size) + + def readable(self) -> bool: + """Return whether the file is readable, which is True.""" + return True + + def seek(self, offset: int, whence: int = 0) -> int: + """Change stream position and return the new absolute position. + + Seek to offset relative position indicated by whence: + * 0: Start of stream (the default). pos should be >= 0; + * 1: Current position - pos may be negative; + * 2: End of stream - pos usually negative. + """ + return self._file.seek(offset, whence) + + def tell(self) -> int: + """Return the current position.""" + return self._file.tell() + + def truncate(self, size: int | None = None) -> int: + """Resize the stream to the given size in bytes. + + If size is unspecified resize to the current position. + The current stream position isn't changed. + + Return the new file size. + """ + return self._file.truncate(size) + + def writable(self) -> bool: + """Return False.""" + return False + + def __enter__(self) -> LazyZipOverHTTP: + self._file.__enter__() + return self + + def __exit__(self, *exc: Any) -> bool | None: + return self._file.__exit__(*exc) + + @contextmanager + def _stay(self) -> Iterator[None]: + """Return a context manager keeping the position. + + At the end of the block, seek back to original position. + """ + pos = self.tell() + try: + yield + finally: + self.seek(pos) + + def _check_zip(self) -> None: + """Check and download until the file is a valid ZIP.""" + end = self._length - 1 + for start in reversed(range(0, end, self._chunk_size)): + self._download(start, end) + with self._stay(): + try: + # For read-only ZIP files, ZipFile only needs + # methods read, seek, seekable and tell. + ZipFile(self) # type: ignore + except BadZipfile: + pass + else: + break + + def _stream_response( + self, start: int | str, end: int, base_headers: dict[str, str] = HEADERS + ) -> Response: + """Return HTTP response to a range request from start to end. + + :param start: if "", request ``end` bytes from end of file.""" + headers = base_headers.copy() + headers["Range"] = f"bytes={start}-{end}" + log.debug("%s", headers["Range"]) + # TODO: Get range requests to be correctly cached + headers["Cache-Control"] = "no-cache" + self._request_count += 1 + response = self._session.get(self._url, headers=headers, stream=True) + response.raise_for_status() + return response + + def _merge( + self, start: int, end: int, left: int, right: int + ) -> Iterator[tuple[int, int]]: + """Return an iterator of intervals to be fetched. + + Args: + start (int): Start of needed interval + end (int): End of needed interval + left (int): Index of first overlapping downloaded data + right (int): Index after last overlapping downloaded data + """ + lslice, rslice = self._left[left:right], self._right[left:right] + i = start = min([start] + lslice[:1]) + end = max([end] + rslice[-1:]) + for j, k in zip(lslice, rslice): + if j > i: + yield i, j - 1 + i = k + 1 + if i <= end: + yield i, end + self._left[left:right], self._right[left:right] = [start], [end] + + def _download(self, start: int, end: int) -> None: + """Download bytes from start to end inclusively.""" + with self._stay(): + left = bisect_left(self._right, start) + right = bisect_right(self._left, end) + for start, end in self._merge(start, end, left, right): + response = self._stream_response(start, end) + self.seek(start) + for chunk in response.iter_content(self._chunk_size): + self._file.write(chunk) + + +class LazyConda(LazyZipOverHTTP): + def prefetch(self, conda_file_id): + """ + Conda fork specific. Prefetch the `.info` range from the remote archive. + Reduces number of Range requests to 2 or 3 (1 or 2 for the directory, 1 + for the file). + + conda_file_id: name of .conda without path or `.conda` extension + """ + target_file = f"info-{conda_file_id}.tar.zst" + with self._stay(): # not strictly necessary + # try to read entire conda info in one request + zf = zipfile.ZipFile(self) + infolist = zf.infolist() + for i, info in enumerate(infolist): + if info.filename == target_file: + # could be incorrect if zipfile was concatenated to another + # file (not likely for .conda) + start = info.header_offset + try: + end = infolist[i + 1].header_offset + # or info.header_offset + # + len(info.filename) + # + len(info.extra) + # + info.compress_size + # (unless Zip64) + except IndexError: + end = zf.start_dir + self.seek(start) + self.read(end - start) + log.debug( + "prefetch %s-%s", + info.header_offset, + end, + ) + break + else: + log.debug("no zip prefetch") diff --git a/shared/package-files/7a/7aa1d828e478f647a55710bc1571ef69db649956b2ba544b1ebd175f3b3e7d61/blob b/shared/package-files/7a/7aa1d828e478f647a55710bc1571ef69db649956b2ba544b1ebd175f3b3e7d61/blob new file mode 100644 index 0000000000000000000000000000000000000000..a55074812b612cd00204fdc20237ab047c449edb --- /dev/null +++ b/shared/package-files/7a/7aa1d828e478f647a55710bc1571ef69db649956b2ba544b1ebd175f3b3e7d61/blob @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace at { +namespace impl { + +TORCH_API bool tensor_has_dispatch(const at::Tensor& t); +TORCH_API bool tensorlist_has_dispatch(at::ITensorListRef li); +TORCH_API bool tensorlist_has_dispatch(const c10::List>& li); +using c10::impl::dispatch_mode_enabled; + +}} diff --git a/shared/package-files/7a/7aa41b9ac3ce66769dd1a1f7dba37f15f6595adcece0822f6ee8307e42e51ed4/blob b/shared/package-files/7a/7aa41b9ac3ce66769dd1a1f7dba37f15f6595adcece0822f6ee8307e42e51ed4/blob new file mode 100644 index 0000000000000000000000000000000000000000..2e032e74c963d7cd61721f7ac19acce986554eca --- /dev/null +++ b/shared/package-files/7a/7aa41b9ac3ce66769dd1a1f7dba37f15f6595adcece0822f6ee8307e42e51ed4/blob @@ -0,0 +1,611 @@ +from sympy.core.backend import Symbol +from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic +from sympy.physics.mechanics import RigidBody, Particle, inertia + +__all__ = ['Body'] + + +# XXX: We use type:ignore because the classes RigidBody and Particle have +# inconsistent parallel axis methods that take different numbers of arguments. +class Body(RigidBody, Particle): # type: ignore + """ + Body is a common representation of either a RigidBody or a Particle SymPy + object depending on what is passed in during initialization. If a mass is + passed in and central_inertia is left as None, the Particle object is + created. Otherwise a RigidBody object will be created. + + Explanation + =========== + + The attributes that Body possesses will be the same as a Particle instance + or a Rigid Body instance depending on which was created. Additional + attributes are listed below. + + Attributes + ========== + + name : string + The body's name + masscenter : Point + The point which represents the center of mass of the rigid body + frame : ReferenceFrame + The reference frame which the body is fixed in + mass : Sympifyable + The body's mass + inertia : (Dyadic, Point) + The body's inertia around its center of mass. This attribute is specific + to the rigid body form of Body and is left undefined for the Particle + form + loads : iterable + This list contains information on the different loads acting on the + Body. Forces are listed as a (point, vector) tuple and torques are + listed as (reference frame, vector) tuples. + + Parameters + ========== + + name : String + Defines the name of the body. It is used as the base for defining + body specific properties. + masscenter : Point, optional + A point that represents the center of mass of the body or particle. + If no point is given, a point is generated. + mass : Sympifyable, optional + A Sympifyable object which represents the mass of the body. If no + mass is passed, one is generated. + frame : ReferenceFrame, optional + The ReferenceFrame that represents the reference frame of the body. + If no frame is given, a frame is generated. + central_inertia : Dyadic, optional + Central inertia dyadic of the body. If none is passed while creating + RigidBody, a default inertia is generated. + + Examples + ======== + + Default behaviour. This results in the creation of a RigidBody object for + which the mass, mass center, frame and inertia attributes are given default + values. :: + + >>> from sympy.physics.mechanics import Body + >>> body = Body('name_of_body') + + This next example demonstrates the code required to specify all of the + values of the Body object. Note this will also create a RigidBody version of + the Body object. :: + + >>> from sympy import Symbol + >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia + >>> from sympy.physics.mechanics import Body + >>> mass = Symbol('mass') + >>> masscenter = Point('masscenter') + >>> frame = ReferenceFrame('frame') + >>> ixx = Symbol('ixx') + >>> body_inertia = inertia(frame, ixx, 0, 0) + >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia) + + The minimal code required to create a Particle version of the Body object + involves simply passing in a name and a mass. :: + + >>> from sympy import Symbol + >>> from sympy.physics.mechanics import Body + >>> mass = Symbol('mass') + >>> body = Body('name_of_body', mass=mass) + + The Particle version of the Body object can also receive a masscenter point + and a reference frame, just not an inertia. + """ + + def __init__(self, name, masscenter=None, mass=None, frame=None, + central_inertia=None): + + self.name = name + self._loads = [] + + if frame is None: + frame = ReferenceFrame(name + '_frame') + + if masscenter is None: + masscenter = Point(name + '_masscenter') + + if central_inertia is None and mass is None: + ixx = Symbol(name + '_ixx') + iyy = Symbol(name + '_iyy') + izz = Symbol(name + '_izz') + izx = Symbol(name + '_izx') + ixy = Symbol(name + '_ixy') + iyz = Symbol(name + '_iyz') + _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx), + masscenter) + else: + _inertia = (central_inertia, masscenter) + + if mass is None: + _mass = Symbol(name + '_mass') + else: + _mass = mass + + masscenter.set_vel(frame, 0) + + # If user passes masscenter and mass then a particle is created + # otherwise a rigidbody. As a result a body may or may not have inertia. + if central_inertia is None and mass is not None: + self.frame = frame + self.masscenter = masscenter + Particle.__init__(self, name, masscenter, _mass) + self._central_inertia = Dyadic(0) + else: + RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia) + + @property + def loads(self): + return self._loads + + @property + def x(self): + """The basis Vector for the Body, in the x direction.""" + return self.frame.x + + @property + def y(self): + """The basis Vector for the Body, in the y direction.""" + return self.frame.y + + @property + def z(self): + """The basis Vector for the Body, in the z direction.""" + return self.frame.z + + @property + def inertia(self): + """The body's inertia about a point; stored as (Dyadic, Point).""" + if self.is_rigidbody: + return RigidBody.inertia.fget(self) + return (self.central_inertia, self.masscenter) + + @inertia.setter + def inertia(self, I): + RigidBody.inertia.fset(self, I) + + @property + def is_rigidbody(self): + if hasattr(self, '_inertia'): + return True + return False + + def kinetic_energy(self, frame): + """Kinetic energy of the body. + + Parameters + ========== + + frame : ReferenceFrame or Body + The Body's angular velocity and the velocity of it's mass + center are typically defined with respect to an inertial frame but + any relevant frame in which the velocities are known can be supplied. + + Examples + ======== + + >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point + >>> from sympy import symbols + >>> m, v, r, omega = symbols('m v r omega') + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> P = Body('P', masscenter=O, mass=m) + >>> P.masscenter.set_vel(N, v * N.y) + >>> P.kinetic_energy(N) + m*v**2/2 + + >>> N = ReferenceFrame('N') + >>> b = ReferenceFrame('b') + >>> b.set_ang_vel(N, omega * b.x) + >>> P = Point('P') + >>> P.set_vel(N, v * N.x) + >>> B = Body('B', masscenter=P, frame=b) + >>> B.kinetic_energy(N) + B_ixx*omega**2/2 + B_mass*v**2/2 + + See Also + ======== + + sympy.physics.mechanics : Particle, RigidBody + + """ + if isinstance(frame, Body): + frame = Body.frame + if self.is_rigidbody: + return RigidBody(self.name, self.masscenter, self.frame, self.mass, + (self.central_inertia, self.masscenter)).kinetic_energy(frame) + return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame) + + def apply_force(self, force, point=None, reaction_body=None, reaction_point=None): + """Add force to the body(s). + + Explanation + =========== + + Applies the force on self or equal and oppposite forces on + self and other body if both are given on the desried point on the bodies. + The force applied on other body is taken opposite of self, i.e, -force. + + Parameters + ========== + + force: Vector + The force to be applied. + point: Point, optional + The point on self on which force is applied. + By default self's masscenter. + reaction_body: Body, optional + Second body on which equal and opposite force + is to be applied. + reaction_point : Point, optional + The point on other body on which equal and opposite + force is applied. By default masscenter of other body. + + Example + ======= + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols + >>> m, g = symbols('m g') + >>> B = Body('B') + >>> force1 = m*g*B.z + >>> B.apply_force(force1) #Applying force on B's masscenter + >>> B.loads + [(B_masscenter, g*m*B_frame.z)] + + We can also remove some part of force from any point on the body by + adding the opposite force to the body on that point. + + >>> f1, f2 = dynamicsymbols('f1 f2') + >>> P = Point('P') #Considering point P on body B + >>> B.apply_force(f1*B.x + f2*B.y, P) + >>> B.loads + [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)] + + Let's remove f1 from point P on body B. + + >>> B.apply_force(-f1*B.x, P) + >>> B.loads + [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)] + + To further demonstrate the use of ``apply_force`` attribute, + consider two bodies connected through a spring. + + >>> from sympy.physics.mechanics import Body, dynamicsymbols + >>> N = Body('N') #Newtonion Frame + >>> x = dynamicsymbols('x') + >>> B1 = Body('B1') + >>> B2 = Body('B2') + >>> spring_force = x*N.x + + Now let's apply equal and opposite spring force to the bodies. + + >>> P1 = Point('P1') + >>> P2 = Point('P2') + >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2) + + We can check the loads(forces) applied to bodies now. + + >>> B1.loads + [(P1, x(t)*N_frame.x)] + >>> B2.loads + [(P2, - x(t)*N_frame.x)] + + Notes + ===== + + If a new force is applied to a body on a point which already has some + force applied on it, then the new force is added to the already applied + force on that point. + + """ + + if not isinstance(point, Point): + if point is None: + point = self.masscenter # masscenter + else: + raise TypeError("Force must be applied to a point on the body.") + if not isinstance(force, Vector): + raise TypeError("Force must be a vector.") + + if reaction_body is not None: + reaction_body.apply_force(-force, point=reaction_point) + + for load in self._loads: + if point in load: + force += load[1] + self._loads.remove(load) + break + + self._loads.append((point, force)) + + def apply_torque(self, torque, reaction_body=None): + """Add torque to the body(s). + + Explanation + =========== + + Applies the torque on self or equal and oppposite torquess on + self and other body if both are given. + The torque applied on other body is taken opposite of self, + i.e, -torque. + + Parameters + ========== + + torque: Vector + The torque to be applied. + reaction_body: Body, optional + Second body on which equal and opposite torque + is to be applied. + + Example + ======= + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, dynamicsymbols + >>> t = symbols('t') + >>> B = Body('B') + >>> torque1 = t*B.z + >>> B.apply_torque(torque1) + >>> B.loads + [(B_frame, t*B_frame.z)] + + We can also remove some part of torque from the body by + adding the opposite torque to the body. + + >>> t1, t2 = dynamicsymbols('t1 t2') + >>> B.apply_torque(t1*B.x + t2*B.y) + >>> B.loads + [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)] + + Let's remove t1 from Body B. + + >>> B.apply_torque(-t1*B.x) + >>> B.loads + [(B_frame, t2(t)*B_frame.y + t*B_frame.z)] + + To further demonstrate the use, let us consider two bodies such that + a torque `T` is acting on one body, and `-T` on the other. + + >>> from sympy.physics.mechanics import Body, dynamicsymbols + >>> N = Body('N') #Newtonion frame + >>> B1 = Body('B1') + >>> B2 = Body('B2') + >>> v = dynamicsymbols('v') + >>> T = v*N.y #Torque + + Now let's apply equal and opposite torque to the bodies. + + >>> B1.apply_torque(T, B2) + + We can check the loads (torques) applied to bodies now. + + >>> B1.loads + [(B1_frame, v(t)*N_frame.y)] + >>> B2.loads + [(B2_frame, - v(t)*N_frame.y)] + + Notes + ===== + + If a new torque is applied on body which already has some torque applied on it, + then the new torque is added to the previous torque about the body's frame. + + """ + + if not isinstance(torque, Vector): + raise TypeError("A Vector must be supplied to add torque.") + + if reaction_body is not None: + reaction_body.apply_torque(-torque) + + for load in self._loads: + if self.frame in load: + torque += load[1] + self._loads.remove(load) + break + self._loads.append((self.frame, torque)) + + def clear_loads(self): + """ + Clears the Body's loads list. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> B = Body('B') + >>> force = B.x + B.y + >>> B.apply_force(force) + >>> B.loads + [(B_masscenter, B_frame.x + B_frame.y)] + >>> B.clear_loads() + >>> B.loads + [] + + """ + + self._loads = [] + + def remove_load(self, about=None): + """ + Remove load about a point or frame. + + Parameters + ========== + + about : Point or ReferenceFrame, optional + The point about which force is applied, + and is to be removed. + If about is None, then the torque about + self's frame is removed. + + Example + ======= + + >>> from sympy.physics.mechanics import Body, Point + >>> B = Body('B') + >>> P = Point('P') + >>> f1 = B.x + >>> f2 = B.y + >>> B.apply_force(f1) + >>> B.apply_force(f2, P) + >>> B.loads + [(B_masscenter, B_frame.x), (P, B_frame.y)] + + >>> B.remove_load(P) + >>> B.loads + [(B_masscenter, B_frame.x)] + + """ + + if about is not None: + if not isinstance(about, Point): + raise TypeError('Load is applied about Point or ReferenceFrame.') + else: + about = self.frame + + for load in self._loads: + if about in load: + self._loads.remove(load) + break + + def masscenter_vel(self, body): + """ + Returns the velocity of the mass center with respect to the provided + rigid body or reference frame. + + Parameters + ========== + + body: Body or ReferenceFrame + The rigid body or reference frame to calculate the velocity in. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> A = Body('A') + >>> B = Body('B') + >>> A.masscenter.set_vel(B.frame, 5*B.frame.x) + >>> A.masscenter_vel(B) + 5*B_frame.x + >>> A.masscenter_vel(B.frame) + 5*B_frame.x + + """ + + if isinstance(body, ReferenceFrame): + frame=body + elif isinstance(body, Body): + frame = body.frame + return self.masscenter.vel(frame) + + def ang_vel_in(self, body): + """ + Returns this body's angular velocity with respect to the provided + rigid body or reference frame. + + Parameters + ========== + + body: Body or ReferenceFrame + The rigid body or reference frame to calculate the angular velocity in. + + Example + ======= + + >>> from sympy.physics.mechanics import Body, ReferenceFrame + >>> A = Body('A') + >>> N = ReferenceFrame('N') + >>> B = Body('B', frame=N) + >>> A.frame.set_ang_vel(N, 5*N.x) + >>> A.ang_vel_in(B) + 5*N.x + >>> A.ang_vel_in(N) + 5*N.x + + """ + + if isinstance(body, ReferenceFrame): + frame=body + elif isinstance(body, Body): + frame = body.frame + return self.frame.ang_vel_in(frame) + + def dcm(self, body): + """ + Returns the direction cosine matrix of this body relative to the + provided rigid body or reference frame. + + Parameters + ========== + + body: Body or ReferenceFrame + The rigid body or reference frame to calculate the dcm. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> A = Body('A') + >>> B = Body('B') + >>> A.frame.orient_axis(B.frame, B.frame.x, 5) + >>> A.dcm(B) + Matrix([ + [1, 0, 0], + [0, cos(5), sin(5)], + [0, -sin(5), cos(5)]]) + >>> A.dcm(B.frame) + Matrix([ + [1, 0, 0], + [0, cos(5), sin(5)], + [0, -sin(5), cos(5)]]) + + """ + + if isinstance(body, ReferenceFrame): + frame=body + elif isinstance(body, Body): + frame = body.frame + return self.frame.dcm(frame) + + def parallel_axis(self, point, frame=None): + """Returns the inertia dyadic of the body with respect to another + point. + + Parameters + ========== + + point : sympy.physics.vector.Point + The point to express the inertia dyadic about. + frame : sympy.physics.vector.ReferenceFrame + The reference frame used to construct the dyadic. + + Returns + ======= + + inertia : sympy.physics.vector.Dyadic + The inertia dyadic of the rigid body expressed about the provided + point. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> A = Body('A') + >>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y) + >>> A.parallel_axis(P).to_matrix(A.frame) + Matrix([ + [A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx], + [A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz], + [ A_izx, A_iyz, A_izz + 34*A_mass]]) + + """ + if self.is_rigidbody: + return RigidBody.parallel_axis(self, point, frame) + return Particle.parallel_axis(self, point, frame) diff --git a/shared/package-files/7a/7aa6b6c9afceb672a664fd32f571a12ddc305f7e3c487ec5337bade7d11fff14/blob b/shared/package-files/7a/7aa6b6c9afceb672a664fd32f571a12ddc305f7e3c487ec5337bade7d11fff14/blob new file mode 100644 index 0000000000000000000000000000000000000000..7701603072c2d717a6df02a0e43fadc3fbcee96f --- /dev/null +++ b/shared/package-files/7a/7aa6b6c9afceb672a664fd32f571a12ddc305f7e3c487ec5337bade7d11fff14/blob @@ -0,0 +1,81 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple min(const at::Tensor & self, int64_t dim, bool keepdim=false) { + return at::_ops::min_dim::call(self, dim, keepdim); +} + +// aten::min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple min_out(at::Tensor & min, at::Tensor & min_indices, const at::Tensor & self, int64_t dim, bool keepdim=false) { + return at::_ops::min_dim_min::call(self, dim, keepdim, min, min_indices); +} +// aten::min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple min_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices) { + return at::_ops::min_dim_min::call(self, dim, keepdim, min, min_indices); +} + +// aten::min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) +inline ::std::tuple min(const at::Tensor & self, at::Dimname dim, bool keepdim=false) { + return at::_ops::min_names_dim::call(self, dim, keepdim); +} + +// aten::min.names_dim_min(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple min_out(at::Tensor & min, at::Tensor & min_indices, const at::Tensor & self, at::Dimname dim, bool keepdim=false) { + return at::_ops::min_names_dim_min::call(self, dim, keepdim, min, min_indices); +} +// aten::min.names_dim_min(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple min_outf(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & min, at::Tensor & min_indices) { + return at::_ops::min_names_dim_min::call(self, dim, keepdim, min, min_indices); +} + +// aten::min(Tensor self) -> Tensor +inline at::Tensor min(const at::Tensor & self) { + return at::_ops::min::call(self); +} + +// aten::min.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & min_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::min_unary_out::call(self, out); +} +// aten::min.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & min_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::min_unary_out::call(self, out); +} + +// aten::min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & min_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::min_out::call(self, other, out); +} +// aten::min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & min_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::min_out::call(self, other, out); +} + +// aten::min.other(Tensor self, Tensor other) -> Tensor +inline at::Tensor min(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::min_other::call(self, other); +} + +} diff --git a/shared/package-files/7a/7aa7e1bc9898f4d76fb581476c3d9dc1714672dfd40f31da9669db1d77b1b0fc/blob b/shared/package-files/7a/7aa7e1bc9898f4d76fb581476c3d9dc1714672dfd40f31da9669db1d77b1b0fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..e8afb70cc51ac1b8473f9452543200a6c5726082 --- /dev/null +++ b/shared/package-files/7a/7aa7e1bc9898f4d76fb581476c3d9dc1714672dfd40f31da9669db1d77b1b0fc/blob @@ -0,0 +1,1582 @@ +error(0.005874221237820127957) D0 +error(0.005237349157286241841) D0 D1 +error(0.02427572132224391568) D0 D4 +error(0.001907572715309251024) D0 D4 ^ D5 +error(0.005410745439301045852) D0 D7 +error(0.0004549748272775545909) D0 D7 ^ D5 +error(0.001154784058800543056) D0 D8 +error(0.001438136383980862312) D0 D8 ^ D5 +error(0.007710234219536729779) D1 D2 +error(0.004653647962191782318) D1 D2 ^ D10 +error(0.02741123806428793011) D1 D7 +error(0.001521301119681984235) D1 D7 ^ D9 +error(0.004096930853910097509) D1 D7 ^ D9 D10 +error(5.628280615812403503e-05) D1 D7 ^ D10 +error(0.001538127947744045163) D1 D8 +error(0.000162573872617425289) D1 D8 ^ D9 +error(0.001490548591580561407) D1 D8 ^ D10 +error(0.0009856789433433537674) D1 D11 +error(0.003253477109862460553) D1 D11 ^ D10 +error(0.01521352500047653579) D1 L0 +error(0.004687689022829302776) D1 L0 ^ D9 +error(0.01564401567892503148) D2 +error(0.01277788181059941186) D2 D3 +error(0.01485579550327015101) D2 D8 +error(0.002232866341697163637) D2 D8 ^ D10 +error(0.01192912324394215275) D2 D11 +error(0.009030700968205426435) D2 D11 ^ D10 +error(0.02570772224573802944) D3 D11 +error(0.009229667664364019086) D3 L0 +error(0.005000000000000000104) D4 +error(0.01455625531367630426) D4 D7 +error(0.01274676990334093138) D4 D7 ^ D5 +error(0.02113542811391193668) D4 D12 +error(0.003601039126778393662) D4 D12 ^ D13 +error(0.00359794063471834645) D4 D15 +error(0.003550675664690026209) D4 D15 ^ D5 +error(0.002523312720004263019) D4 D15 ^ D13 +error(0.00120410006428202875) D4 D15 ^ D13 ^ D5 +error(0.002358990922302896861) D4 D16 +error(0.000900329109565413334) D4 D16 ^ D5 +error(0.001422466139403531522) D4 D16 ^ D5 D13 +error(0.000227529332159509529) D4 D16 ^ D13 +error(0.006981607648030838109) D4 ^ D5 +error(0.002837628295752675847) D4 ^ D13 +error(0.003307776772393457038) D5 D13 ^ D4 +error(0.02282983922518961803) D5 +error(0.01023570743151261744) D5 D6 +error(0.001144319323025969884) D5 D6 ^ D4 +error(0.01259555888214780074) D5 D6 ^ D8 +error(0.002468551585310864264) D5 D6 ^ D8 D16 +error(0.002247465333081031646) D5 D6 ^ D16 +error(7.99905811885554506e-05) D5 D6 ^ D16 ^ D4 +error(0.01682833066875222966) D5 D10 +error(0.01250760269848300021) D5 D10 ^ D7 D8 +error(0.03097165563823810197) D5 D13 +error(0.002341580630745021974) D5 D13 ^ D15 D16 +error(0.001004674392747008198) D5 D13 ^ D16 +error(0.001715583818580762978) D5 D17 +error(0.001950587289979390914) D5 D17 ^ D7 D15 +error(0.0002873849163372229633) D5 D17 ^ D7 D16 +error(0.000250635755306040397) D5 D17 ^ D15 D16 +error(0.003948014621302732043) D5 D18 +error(0.001775671469750636109) D5 D18 ^ D7 D8 +error(0.001801781851294598745) D5 D18 ^ D7 D15 +error(0.001714031950420857008) D5 D18 ^ D7 D16 +error(0.0005120024926036837636) D5 D18 ^ D8 D16 +error(0.00216425719161783851) D5 D18 ^ D15 D16 +error(0.004511966489743314546) D5 ^ D0 +error(0.0005118591541988273515) D5 ^ D7 L0 +error(0.0003322483982904619122) D5 ^ D8 +error(0.0004354228931719861663) D5 ^ D15 L0 +error(0.003765899750618454181) D7 D15 ^ D5 +error(0.05014062583988330296) D6 +error(0.001854426416129751048) D6 D13 +error(0.0002354062236734246057) D6 D13 ^ D4 +error(0.002188603398587882221) D6 D13 ^ D16 +error(9.046428883286232426e-05) D6 D13 ^ D16 ^ D4 +error(0.03357286637296971049) D6 D14 +error(0.003027692963263897263) D6 D14 ^ D16 +error(0.001416082311859589949) D6 D18 +error(3.42651728233790256e-05) D6 D18 ^ D7 D8 +error(0.0001287815486031648618) D6 D18 ^ D7 D16 +error(0.001487500032960160099) D6 D18 ^ D8 D16 +error(0.01853943245126968634) D6 ^ D8 +error(0.001452163632415732868) D6 ^ D16 ^ D8 +error(0.01410192552700904531) D7 D8 +error(0.001302402352213913447) D7 D8 ^ D5 +error(0.001021923265936209788) D7 D8 ^ D10 +error(0.002627104611062700337) D7 D8 ^ D10 D18 +error(0.002171612446080710412) D7 D8 ^ D10 ^ D9 +error(0.001775990005087981979) D7 D8 ^ D18 +error(0.04390708729114359971) D7 D15 +error(0.003367806044768197494) D7 D15 ^ D17 D18 +error(0.002385866215008573821) D7 D16 +error(0.0003400294089845564468) D7 D16 ^ D17 D18 +error(0.001711368909680681914) D7 D19 +error(0.0006907184389567510435) D7 D19 ^ D10 +error(0.001678528085572790918) D7 D19 ^ D10 D18 +error(0.0006093950648277737803) D7 D19 ^ D18 +error(0.01000000000000000021) D7 L0 +error(0.01176510697969633361) D7 L0 ^ D9 +error(0.003252238252497897768) D9 D17 ^ D7 L0 +error(0.02614550097157030892) D8 +error(0.01754503701780024683) D8 D11 +error(0.02008898775495391448) D8 D11 ^ D10 +error(0.01583066593640236955) D8 D16 +error(0.003023260842645458021) D8 D16 ^ D18 +error(0.008295038404182598218) D8 D19 +error(0.005521572502132320731) D8 D19 ^ D10 +error(0.007766717057027912145) D8 D19 ^ D18 +error(0.0008028985601615047695) D8 D19 ^ D18 ^ D10 +error(0.03964446904422613827) D9 +error(0.01585324681163168339) D9 D10 +error(0.002850280711798483177) D9 D10 ^ D1 L0 +error(0.01788944737927963477) D9 D10 ^ D7 L0 +error(0.0199456988747792191) D9 D17 +error(0.04395883820436224249) D10 +error(0.003518916957238571799) D10 D17 +error(0.003138668157944232186) D10 D17 ^ D7 L0 +error(0.0002848009832623634948) D10 D17 ^ D19 L0 +error(0.0002809672024858596447) D10 D17 ^ D19 L0 ^ D7 L0 +error(0.02037863138761538545) D10 D18 +error(0.0008394508946699175177) D10 D18 ^ D7 L0 +error(0.00393251772886478012) D10 D18 ^ D19 L0 +error(0.001373943680781148768) D10 ^ D2 +error(0.01715770221520333816) D10 ^ D11 L0 +error(1.152447667230613086e-05) D10 ^ D11 L0 ^ D9 +error(0.00214963269345377515) D10 ^ D19 L0 +error(0.00497062980159790422) D11 D19 ^ D10 +error(0.02465692158241580487) D11 D19 +error(0.0109501579040953978) D11 L0 +error(0.0009271936675182802182) D11 L0 ^ D1 L0 ^ D9 +error(0.005000000000000000104) D12 +error(0.01511339752813176118) D12 D15 +error(0.01318529921048066343) D12 D15 ^ D13 +error(0.02113542811391193668) D12 D20 +error(0.003601039126778393662) D12 D20 ^ D21 +error(0.00359794063471834645) D12 D23 +error(0.003550675664690026209) D12 D23 ^ D13 +error(0.002523312720004263019) D12 D23 ^ D21 +error(0.00120410006428202875) D12 D23 ^ D21 ^ D13 +error(0.002358990922302896861) D12 D24 +error(0.000900329109565413334) D12 D24 ^ D13 +error(0.001422466139403531522) D12 D24 ^ D13 D21 +error(0.000227529332159509529) D12 D24 ^ D21 +error(0.005671061927629780092) D12 ^ D13 +error(0.002837628295752675847) D12 ^ D21 +error(0.003307776772393457038) D13 D21 ^ D12 +error(0.01000000000000000021) D13 +error(0.009659594482854964859) D13 D14 +error(0.0005681221308502792944) D13 D14 ^ D12 +error(1.221615784209272829e-05) D13 D14 ^ D15 D16 +error(0.01197970675250215056) D13 D14 ^ D16 +error(0.002468551585310864264) D13 D14 ^ D16 D24 +error(0.002247465333081031646) D13 D14 ^ D24 +error(7.99905811885554506e-05) D13 D14 ^ D24 ^ D12 +error(0.0149046830253691618) D13 D18 +error(0.01158960761781799818) D13 D18 ^ D15 D16 +error(0.03097165563823810197) D13 D21 +error(0.002341580630745021974) D13 D21 ^ D23 D24 +error(0.001004674392747008198) D13 D21 ^ D24 +error(0.001715583818580762978) D13 D25 +error(0.001950587289979390914) D13 D25 ^ D15 D23 +error(0.0002873849163372229633) D13 D25 ^ D15 D24 +error(0.000250635755306040397) D13 D25 ^ D23 D24 +error(0.003948014621302732043) D13 D26 +error(0.001775671469750636109) D13 D26 ^ D15 D16 +error(0.001801781851294598745) D13 D26 ^ D15 D23 +error(0.001714031950420857008) D13 D26 ^ D15 D24 +error(0.0005120024926036837636) D13 D26 ^ D16 D24 +error(0.00216425719161783851) D13 D26 ^ D23 D24 +error(0.0004354228931719861663) D13 ^ D23 L0 +error(0.003765899750618454181) D15 D23 ^ D13 +error(0.01549347680688980405) D14 +error(0.001854426416129751048) D14 D21 +error(0.0002354062236734246057) D14 D21 ^ D12 +error(0.002188603398587882221) D14 D21 ^ D24 +error(9.046428883286232426e-05) D14 D21 ^ D24 ^ D12 +error(0.03357286637296971049) D14 D22 +error(0.003027692963263897263) D14 D22 ^ D24 +error(0.001416082311859589949) D14 D26 +error(3.42651728233790256e-05) D14 D26 ^ D15 D16 +error(0.0001287815486031648618) D14 D26 ^ D15 D24 +error(0.001487500032960160099) D14 D26 ^ D16 D24 +error(0.01554489029060489302) D14 ^ D16 +error(0.001452163632415732868) D14 ^ D24 ^ D16 +error(0.01232976508330123518) D15 D16 +error(0.0009024575091639398068) D15 D16 ^ D17 D18 +error(0.00132845243984354433) D15 D16 ^ D18 +error(0.002627104611062700337) D15 D16 ^ D18 D26 +error(0.001775990005087981979) D15 D16 ^ D26 +error(0.04390708729114359971) D15 D23 +error(0.003367806044768197494) D15 D23 ^ D25 D26 +error(0.002385866215008573821) D15 D24 +error(0.0003400294089845564468) D15 D24 ^ D25 D26 +error(0.001711368909680681914) D15 D27 +error(0.0006907184389567510435) D15 D27 ^ D18 +error(0.001678528085572790918) D15 D27 ^ D18 D26 +error(0.0006093950648277737803) D15 D27 ^ D26 +error(0.01000000000000000021) D15 L0 +error(0.01224181716280624624) D15 L0 ^ D17 +error(0.003252238252497897768) D17 D25 ^ D15 L0 +error(0.01790797738103024755) D16 +error(0.02001725581242098928) D16 D19 +error(0.02111497934355966929) D16 D19 ^ D18 +error(0.01583066593640236955) D16 D24 +error(0.003023260842645458021) D16 D24 ^ D26 +error(0.008295038404182598218) D16 D27 +error(0.005521572502132320731) D16 D27 ^ D18 +error(0.007766717057027912145) D16 D27 ^ D26 +error(0.0008028985601615047695) D16 D27 ^ D26 ^ D18 +error(0.008757252326096141501) D17 +error(0.01400557781329538239) D17 D18 +error(0.003940429509688737897) D17 D18 ^ D7 L0 +error(0.01774801221981088181) D17 D18 ^ D15 L0 +error(0.0002241990306885290963) D17 D18 ^ D19 L0 +error(0.0002398915537285264889) D17 D18 ^ D19 L0 ^ D7 L0 +error(0.0199456988747792191) D17 D25 +error(3.564955517285772993e-07) D17 ^ D5 ^ D7 L0 +error(0.0007061037462806830011) D17 ^ D5 ^ D15 L0 +error(0.0003886023791641102015) D17 ^ D15 L0 ^ D7 L0 +error(0.02267274013643192504) D18 +error(0.003518916957238571799) D18 D25 +error(0.003138668157944232186) D18 D25 ^ D15 L0 +error(0.0002848009832623634948) D18 D25 ^ D27 L0 +error(0.0002809672024858596447) D18 D25 ^ D27 L0 ^ D15 L0 +error(0.02037863138761538545) D18 D26 +error(0.0008394508946699175177) D18 D26 ^ D15 L0 +error(0.00393251772886478012) D18 D26 ^ D27 L0 +error(0.0003455869076207062881) D18 ^ D6 ^ D8 +error(0.0005475199888806141137) D18 ^ D6 ^ D16 +error(0.001624233559704021295) D18 ^ D8 +error(0.01066461502177179499) D18 ^ D19 L0 +error(0.00214963269345377515) D18 ^ D27 L0 +error(0.00497062980159790422) D19 D27 ^ D18 +error(0.02465692158241580487) D19 D27 +error(0.005000000000000000104) D19 L0 +error(0.005000000000000000104) D20 +error(0.01511339752813176118) D20 D23 +error(0.01318529921048066343) D20 D23 ^ D21 +error(0.02113542811391193668) D20 D28 +error(0.003601039126778393662) D20 D28 ^ D29 +error(0.00359794063471834645) D20 D31 +error(0.003550675664690026209) D20 D31 ^ D21 +error(0.002523312720004263019) D20 D31 ^ D29 +error(0.00120410006428202875) D20 D31 ^ D29 ^ D21 +error(0.002358990922302896861) D20 D32 +error(0.000900329109565413334) D20 D32 ^ D21 +error(0.001422466139403531522) D20 D32 ^ D21 D29 +error(0.000227529332159509529) D20 D32 ^ D29 +error(0.005671061927629780092) D20 ^ D21 +error(0.002837628295752675847) D20 ^ D29 +error(0.003307776772393457038) D21 D29 ^ D20 +error(0.01000000000000000021) D21 +error(0.009659594482854964859) D21 D22 +error(0.0005681221308502792944) D21 D22 ^ D20 +error(1.221615784209272829e-05) D21 D22 ^ D23 D24 +error(0.01197970675250215056) D21 D22 ^ D24 +error(0.002468551585310864264) D21 D22 ^ D24 D32 +error(0.002247465333081031646) D21 D22 ^ D32 +error(7.99905811885554506e-05) D21 D22 ^ D32 ^ D20 +error(0.0149046830253691618) D21 D26 +error(0.01158960761781799818) D21 D26 ^ D23 D24 +error(0.03097165563823810197) D21 D29 +error(0.002341580630745021974) D21 D29 ^ D31 D32 +error(0.001004674392747008198) D21 D29 ^ D32 +error(0.001715583818580762978) D21 D33 +error(0.001950587289979390914) D21 D33 ^ D23 D31 +error(0.0002873849163372229633) D21 D33 ^ D23 D32 +error(0.000250635755306040397) D21 D33 ^ D31 D32 +error(0.003948014621302732043) D21 D34 +error(0.001775671469750636109) D21 D34 ^ D23 D24 +error(0.001801781851294598745) D21 D34 ^ D23 D31 +error(0.001714031950420857008) D21 D34 ^ D23 D32 +error(0.0005120024926036837636) D21 D34 ^ D24 D32 +error(0.00216425719161783851) D21 D34 ^ D31 D32 +error(0.0004354228931719861663) D21 ^ D31 L0 +error(0.003765899750618454181) D23 D31 ^ D21 +error(0.01549347680688980405) D22 +error(0.001854426416129751048) D22 D29 +error(0.0002354062236734246057) D22 D29 ^ D20 +error(0.002188603398587882221) D22 D29 ^ D32 +error(9.046428883286232426e-05) D22 D29 ^ D32 ^ D20 +error(0.03357286637296971049) D22 D30 +error(0.003027692963263897263) D22 D30 ^ D32 +error(0.001416082311859589949) D22 D34 +error(3.42651728233790256e-05) D22 D34 ^ D23 D24 +error(0.0001287815486031648618) D22 D34 ^ D23 D32 +error(0.001487500032960160099) D22 D34 ^ D24 D32 +error(0.01554489029060489302) D22 ^ D24 +error(0.001452163632415732868) D22 ^ D32 ^ D24 +error(0.01232976508330123518) D23 D24 +error(0.0009024575091639398068) D23 D24 ^ D25 D26 +error(0.00132845243984354433) D23 D24 ^ D26 +error(0.002627104611062700337) D23 D24 ^ D26 D34 +error(0.001775990005087981979) D23 D24 ^ D34 +error(0.04390708729114359971) D23 D31 +error(0.003367806044768197494) D23 D31 ^ D33 D34 +error(0.002385866215008573821) D23 D32 +error(0.0003400294089845564468) D23 D32 ^ D33 D34 +error(0.001711368909680681914) D23 D35 +error(0.0006907184389567510435) D23 D35 ^ D26 +error(0.001678528085572790918) D23 D35 ^ D26 D34 +error(0.0006093950648277737803) D23 D35 ^ D34 +error(0.01000000000000000021) D23 L0 +error(0.01224181716280624624) D23 L0 ^ D25 +error(0.003252238252497897768) D25 D33 ^ D23 L0 +error(0.01790797738103024755) D24 +error(0.02001725581242098928) D24 D27 +error(0.02111497934355966929) D24 D27 ^ D26 +error(0.01583066593640236955) D24 D32 +error(0.003023260842645458021) D24 D32 ^ D34 +error(0.008295038404182598218) D24 D35 +error(0.005521572502132320731) D24 D35 ^ D26 +error(0.007766717057027912145) D24 D35 ^ D34 +error(0.0008028985601615047695) D24 D35 ^ D34 ^ D26 +error(0.008757252326096141501) D25 +error(0.01400557781329538239) D25 D26 +error(0.003940429509688737897) D25 D26 ^ D15 L0 +error(0.01774801221981088181) D25 D26 ^ D23 L0 +error(0.0002241990306885290963) D25 D26 ^ D27 L0 +error(0.0002398915537285264889) D25 D26 ^ D27 L0 ^ D15 L0 +error(0.0199456988747792191) D25 D33 +error(3.564955517285772993e-07) D25 ^ D13 ^ D15 L0 +error(0.0007061037462806830011) D25 ^ D13 ^ D23 L0 +error(0.0003886023791641102015) D25 ^ D23 L0 ^ D15 L0 +error(0.02267274013643192504) D26 +error(0.003518916957238571799) D26 D33 +error(0.003138668157944232186) D26 D33 ^ D23 L0 +error(0.0002848009832623634948) D26 D33 ^ D35 L0 +error(0.0002809672024858596447) D26 D33 ^ D35 L0 ^ D23 L0 +error(0.02037863138761538545) D26 D34 +error(0.0008394508946699175177) D26 D34 ^ D23 L0 +error(0.00393251772886478012) D26 D34 ^ D35 L0 +error(0.0003455869076207062881) D26 ^ D14 ^ D16 +error(0.0005475199888806141137) D26 ^ D14 ^ D24 +error(0.001624233559704021295) D26 ^ D16 +error(0.01066461502177179499) D26 ^ D27 L0 +error(0.00214963269345377515) D26 ^ D35 L0 +error(0.00497062980159790422) D27 D35 ^ D26 +error(0.02465692158241580487) D27 D35 +error(0.005000000000000000104) D27 L0 +error(0.005000000000000000104) D28 +error(0.01511339752813176118) D28 D31 +error(0.01318529921048066343) D28 D31 ^ D29 +error(0.02113542811391193668) D28 D36 +error(0.003601039126778393662) D28 D36 ^ D37 +error(0.00359794063471834645) D28 D39 +error(0.003550675664690026209) D28 D39 ^ D29 +error(0.002523312720004263019) D28 D39 ^ D37 +error(0.00120410006428202875) D28 D39 ^ D37 ^ D29 +error(0.002358990922302896861) D28 D40 +error(0.000900329109565413334) D28 D40 ^ D29 +error(0.001422466139403531522) D28 D40 ^ D29 D37 +error(0.000227529332159509529) D28 D40 ^ D37 +error(0.005671061927629780092) D28 ^ D29 +error(0.002837628295752675847) D28 ^ D37 +error(0.003307776772393457038) D29 D37 ^ D28 +error(0.01000000000000000021) D29 +error(0.009659594482854964859) D29 D30 +error(0.0005681221308502792944) D29 D30 ^ D28 +error(1.221615784209272829e-05) D29 D30 ^ D31 D32 +error(0.01197970675250215056) D29 D30 ^ D32 +error(0.002468551585310864264) D29 D30 ^ D32 D40 +error(0.002247465333081031646) D29 D30 ^ D40 +error(7.99905811885554506e-05) D29 D30 ^ D40 ^ D28 +error(0.0149046830253691618) D29 D34 +error(0.01158960761781799818) D29 D34 ^ D31 D32 +error(0.03097165563823810197) D29 D37 +error(0.002341580630745021974) D29 D37 ^ D39 D40 +error(0.001004674392747008198) D29 D37 ^ D40 +error(0.001715583818580762978) D29 D41 +error(0.001950587289979390914) D29 D41 ^ D31 D39 +error(0.0002873849163372229633) D29 D41 ^ D31 D40 +error(0.000250635755306040397) D29 D41 ^ D39 D40 +error(0.003948014621302732043) D29 D42 +error(0.001775671469750636109) D29 D42 ^ D31 D32 +error(0.001801781851294598745) D29 D42 ^ D31 D39 +error(0.001714031950420857008) D29 D42 ^ D31 D40 +error(0.0005120024926036837636) D29 D42 ^ D32 D40 +error(0.00216425719161783851) D29 D42 ^ D39 D40 +error(0.0004354228931719861663) D29 ^ D39 L0 +error(0.003765899750618454181) D31 D39 ^ D29 +error(0.01549347680688980405) D30 +error(0.001854426416129751048) D30 D37 +error(0.0002354062236734246057) D30 D37 ^ D28 +error(0.002188603398587882221) D30 D37 ^ D40 +error(9.046428883286232426e-05) D30 D37 ^ D40 ^ D28 +error(0.03357286637296971049) D30 D38 +error(0.003027692963263897263) D30 D38 ^ D40 +error(0.001416082311859589949) D30 D42 +error(3.42651728233790256e-05) D30 D42 ^ D31 D32 +error(0.0001287815486031648618) D30 D42 ^ D31 D40 +error(0.001487500032960160099) D30 D42 ^ D32 D40 +error(0.01554489029060489302) D30 ^ D32 +error(0.001452163632415732868) D30 ^ D40 ^ D32 +error(0.01232976508330123518) D31 D32 +error(0.0009024575091639398068) D31 D32 ^ D33 D34 +error(0.00132845243984354433) D31 D32 ^ D34 +error(0.002627104611062700337) D31 D32 ^ D34 D42 +error(0.001775990005087981979) D31 D32 ^ D42 +error(0.04390708729114359971) D31 D39 +error(0.003367806044768197494) D31 D39 ^ D41 D42 +error(0.002385866215008573821) D31 D40 +error(0.0003400294089845564468) D31 D40 ^ D41 D42 +error(0.001711368909680681914) D31 D43 +error(0.0006907184389567510435) D31 D43 ^ D34 +error(0.001678528085572790918) D31 D43 ^ D34 D42 +error(0.0006093950648277737803) D31 D43 ^ D42 +error(0.01000000000000000021) D31 L0 +error(0.01224181716280624624) D31 L0 ^ D33 +error(0.003252238252497897768) D33 D41 ^ D31 L0 +error(0.01790797738103024755) D32 +error(0.02001725581242098928) D32 D35 +error(0.02111497934355966929) D32 D35 ^ D34 +error(0.01583066593640236955) D32 D40 +error(0.003023260842645458021) D32 D40 ^ D42 +error(0.008295038404182598218) D32 D43 +error(0.005521572502132320731) D32 D43 ^ D34 +error(0.007766717057027912145) D32 D43 ^ D42 +error(0.0008028985601615047695) D32 D43 ^ D42 ^ D34 +error(0.008757252326096141501) D33 +error(0.01400557781329538239) D33 D34 +error(0.003940429509688737897) D33 D34 ^ D23 L0 +error(0.01774801221981088181) D33 D34 ^ D31 L0 +error(0.0002241990306885290963) D33 D34 ^ D35 L0 +error(0.0002398915537285264889) D33 D34 ^ D35 L0 ^ D23 L0 +error(0.0199456988747792191) D33 D41 +error(3.564955517285772993e-07) D33 ^ D21 ^ D23 L0 +error(0.0007061037462806830011) D33 ^ D21 ^ D31 L0 +error(0.0003886023791641102015) D33 ^ D31 L0 ^ D23 L0 +error(0.02267274013643192504) D34 +error(0.003518916957238571799) D34 D41 +error(0.003138668157944232186) D34 D41 ^ D31 L0 +error(0.0002848009832623634948) D34 D41 ^ D43 L0 +error(0.0002809672024858596447) D34 D41 ^ D43 L0 ^ D31 L0 +error(0.02037863138761538545) D34 D42 +error(0.0008394508946699175177) D34 D42 ^ D31 L0 +error(0.00393251772886478012) D34 D42 ^ D43 L0 +error(0.0003455869076207062881) D34 ^ D22 ^ D24 +error(0.0005475199888806141137) D34 ^ D22 ^ D32 +error(0.001624233559704021295) D34 ^ D24 +error(0.01066461502177179499) D34 ^ D35 L0 +error(0.00214963269345377515) D34 ^ D43 L0 +error(0.00497062980159790422) D35 D43 ^ D34 +error(0.02465692158241580487) D35 D43 +error(0.005000000000000000104) D35 L0 +error(0.005000000000000000104) D36 +error(0.01511339752813176118) D36 D39 +error(0.01318529921048066343) D36 D39 ^ D37 +error(0.02113542811391193668) D36 D44 +error(0.003601039126778393662) D36 D44 ^ D45 +error(0.00359794063471834645) D36 D47 +error(0.003550675664690026209) D36 D47 ^ D37 +error(0.002523312720004263019) D36 D47 ^ D45 +error(0.00120410006428202875) D36 D47 ^ D45 ^ D37 +error(0.002358990922302896861) D36 D48 +error(0.000900329109565413334) D36 D48 ^ D37 +error(0.001422466139403531522) D36 D48 ^ D37 D45 +error(0.000227529332159509529) D36 D48 ^ D45 +error(0.005671061927629780092) D36 ^ D37 +error(0.002837628295752675847) D36 ^ D45 +error(0.003307776772393457038) D37 D45 ^ D36 +error(0.01000000000000000021) D37 +error(0.009659594482854964859) D37 D38 +error(0.0005681221308502792944) D37 D38 ^ D36 +error(1.221615784209272829e-05) D37 D38 ^ D39 D40 +error(0.01197970675250215056) D37 D38 ^ D40 +error(0.002468551585310864264) D37 D38 ^ D40 D48 +error(0.002247465333081031646) D37 D38 ^ D48 +error(7.99905811885554506e-05) D37 D38 ^ D48 ^ D36 +error(0.0149046830253691618) D37 D42 +error(0.01158960761781799818) D37 D42 ^ D39 D40 +error(0.03097165563823810197) D37 D45 +error(0.002341580630745021974) D37 D45 ^ D47 D48 +error(0.001004674392747008198) D37 D45 ^ D48 +error(0.001715583818580762978) D37 D49 +error(0.001950587289979390914) D37 D49 ^ D39 D47 +error(0.0002873849163372229633) D37 D49 ^ D39 D48 +error(0.000250635755306040397) D37 D49 ^ D47 D48 +error(0.003948014621302732043) D37 D50 +error(0.001775671469750636109) D37 D50 ^ D39 D40 +error(0.001801781851294598745) D37 D50 ^ D39 D47 +error(0.001714031950420857008) D37 D50 ^ D39 D48 +error(0.0005120024926036837636) D37 D50 ^ D40 D48 +error(0.00216425719161783851) D37 D50 ^ D47 D48 +error(0.0004354228931719861663) D37 ^ D47 L0 +error(0.003765899750618454181) D39 D47 ^ D37 +error(0.01549347680688980405) D38 +error(0.001854426416129751048) D38 D45 +error(0.0002354062236734246057) D38 D45 ^ D36 +error(0.002188603398587882221) D38 D45 ^ D48 +error(9.046428883286232426e-05) D38 D45 ^ D48 ^ D36 +error(0.03357286637296971049) D38 D46 +error(0.003027692963263897263) D38 D46 ^ D48 +error(0.001416082311859589949) D38 D50 +error(3.42651728233790256e-05) D38 D50 ^ D39 D40 +error(0.0001287815486031648618) D38 D50 ^ D39 D48 +error(0.001487500032960160099) D38 D50 ^ D40 D48 +error(0.01554489029060489302) D38 ^ D40 +error(0.001452163632415732868) D38 ^ D48 ^ D40 +error(0.01232976508330123518) D39 D40 +error(0.0009024575091639398068) D39 D40 ^ D41 D42 +error(0.00132845243984354433) D39 D40 ^ D42 +error(0.002627104611062700337) D39 D40 ^ D42 D50 +error(0.001775990005087981979) D39 D40 ^ D50 +error(0.04390708729114359971) D39 D47 +error(0.003367806044768197494) D39 D47 ^ D49 D50 +error(0.002385866215008573821) D39 D48 +error(0.0003400294089845564468) D39 D48 ^ D49 D50 +error(0.001711368909680681914) D39 D51 +error(0.0006907184389567510435) D39 D51 ^ D42 +error(0.001678528085572790918) D39 D51 ^ D42 D50 +error(0.0006093950648277737803) D39 D51 ^ D50 +error(0.01000000000000000021) D39 L0 +error(0.01224181716280624624) D39 L0 ^ D41 +error(0.003252238252497897768) D41 D49 ^ D39 L0 +error(0.01790797738103024755) D40 +error(0.02001725581242098928) D40 D43 +error(0.02111497934355966929) D40 D43 ^ D42 +error(0.01583066593640236955) D40 D48 +error(0.003023260842645458021) D40 D48 ^ D50 +error(0.008295038404182598218) D40 D51 +error(0.005521572502132320731) D40 D51 ^ D42 +error(0.007766717057027912145) D40 D51 ^ D50 +error(0.0008028985601615047695) D40 D51 ^ D50 ^ D42 +error(0.008757252326096141501) D41 +error(0.01400557781329538239) D41 D42 +error(0.003940429509688737897) D41 D42 ^ D31 L0 +error(0.01774801221981088181) D41 D42 ^ D39 L0 +error(0.0002241990306885290963) D41 D42 ^ D43 L0 +error(0.0002398915537285264889) D41 D42 ^ D43 L0 ^ D31 L0 +error(0.0199456988747792191) D41 D49 +error(3.564955517285772993e-07) D41 ^ D29 ^ D31 L0 +error(0.0007061037462806830011) D41 ^ D29 ^ D39 L0 +error(0.0003886023791641102015) D41 ^ D39 L0 ^ D31 L0 +error(0.02267274013643192504) D42 +error(0.003518916957238571799) D42 D49 +error(0.003138668157944232186) D42 D49 ^ D39 L0 +error(0.0002848009832623634948) D42 D49 ^ D51 L0 +error(0.0002809672024858596447) D42 D49 ^ D51 L0 ^ D39 L0 +error(0.02037863138761538545) D42 D50 +error(0.0008394508946699175177) D42 D50 ^ D39 L0 +error(0.00393251772886478012) D42 D50 ^ D51 L0 +error(0.0003455869076207062881) D42 ^ D30 ^ D32 +error(0.0005475199888806141137) D42 ^ D30 ^ D40 +error(0.001624233559704021295) D42 ^ D32 +error(0.01066461502177179499) D42 ^ D43 L0 +error(0.00214963269345377515) D42 ^ D51 L0 +error(0.00497062980159790422) D43 D51 ^ D42 +error(0.02465692158241580487) D43 D51 +error(0.005000000000000000104) D43 L0 +error(0.005000000000000000104) D44 +error(0.01511339752813176118) D44 D47 +error(0.01318529921048066343) D44 D47 ^ D45 +error(0.02113542811391193668) D44 D52 +error(0.003601039126778393662) D44 D52 ^ D53 +error(0.00359794063471834645) D44 D55 +error(0.003550675664690026209) D44 D55 ^ D45 +error(0.002523312720004263019) D44 D55 ^ D53 +error(0.00120410006428202875) D44 D55 ^ D53 ^ D45 +error(0.002358990922302896861) D44 D56 +error(0.000900329109565413334) D44 D56 ^ D45 +error(0.001422466139403531522) D44 D56 ^ D45 D53 +error(0.000227529332159509529) D44 D56 ^ D53 +error(0.005671061927629780092) D44 ^ D45 +error(0.002837628295752675847) D44 ^ D53 +error(0.003307776772393457038) D45 D53 ^ D44 +error(0.01000000000000000021) D45 +error(0.009659594482854964859) D45 D46 +error(0.0005681221308502792944) D45 D46 ^ D44 +error(1.221615784209272829e-05) D45 D46 ^ D47 D48 +error(0.01197970675250215056) D45 D46 ^ D48 +error(0.002468551585310864264) D45 D46 ^ D48 D56 +error(0.002247465333081031646) D45 D46 ^ D56 +error(7.99905811885554506e-05) D45 D46 ^ D56 ^ D44 +error(0.0149046830253691618) D45 D50 +error(0.01158960761781799818) D45 D50 ^ D47 D48 +error(0.03097165563823810197) D45 D53 +error(0.002341580630745021974) D45 D53 ^ D55 D56 +error(0.001004674392747008198) D45 D53 ^ D56 +error(0.001715583818580762978) D45 D57 +error(0.001950587289979390914) D45 D57 ^ D47 D55 +error(0.0002873849163372229633) D45 D57 ^ D47 D56 +error(0.000250635755306040397) D45 D57 ^ D55 D56 +error(0.003948014621302732043) D45 D58 +error(0.001775671469750636109) D45 D58 ^ D47 D48 +error(0.001801781851294598745) D45 D58 ^ D47 D55 +error(0.001714031950420857008) D45 D58 ^ D47 D56 +error(0.0005120024926036837636) D45 D58 ^ D48 D56 +error(0.00216425719161783851) D45 D58 ^ D55 D56 +error(0.0004354228931719861663) D45 ^ D55 L0 +error(0.003765899750618454181) D47 D55 ^ D45 +error(0.01549347680688980405) D46 +error(0.001854426416129751048) D46 D53 +error(0.0002354062236734246057) D46 D53 ^ D44 +error(0.002188603398587882221) D46 D53 ^ D56 +error(9.046428883286232426e-05) D46 D53 ^ D56 ^ D44 +error(0.03357286637296971049) D46 D54 +error(0.003027692963263897263) D46 D54 ^ D56 +error(0.001416082311859589949) D46 D58 +error(3.42651728233790256e-05) D46 D58 ^ D47 D48 +error(0.0001287815486031648618) D46 D58 ^ D47 D56 +error(0.001487500032960160099) D46 D58 ^ D48 D56 +error(0.01554489029060489302) D46 ^ D48 +error(0.001452163632415732868) D46 ^ D56 ^ D48 +error(0.01232976508330123518) D47 D48 +error(0.0009024575091639398068) D47 D48 ^ D49 D50 +error(0.00132845243984354433) D47 D48 ^ D50 +error(0.002627104611062700337) D47 D48 ^ D50 D58 +error(0.001775990005087981979) D47 D48 ^ D58 +error(0.04390708729114359971) D47 D55 +error(0.003367806044768197494) D47 D55 ^ D57 D58 +error(0.002385866215008573821) D47 D56 +error(0.0003400294089845564468) D47 D56 ^ D57 D58 +error(0.001711368909680681914) D47 D59 +error(0.0006907184389567510435) D47 D59 ^ D50 +error(0.001678528085572790918) D47 D59 ^ D50 D58 +error(0.0006093950648277737803) D47 D59 ^ D58 +error(0.01000000000000000021) D47 L0 +error(0.01224181716280624624) D47 L0 ^ D49 +error(0.003252238252497897768) D49 D57 ^ D47 L0 +error(0.01790797738103024755) D48 +error(0.02001725581242098928) D48 D51 +error(0.02111497934355966929) D48 D51 ^ D50 +error(0.01583066593640236955) D48 D56 +error(0.003023260842645458021) D48 D56 ^ D58 +error(0.008295038404182598218) D48 D59 +error(0.005521572502132320731) D48 D59 ^ D50 +error(0.007766717057027912145) D48 D59 ^ D58 +error(0.0008028985601615047695) D48 D59 ^ D58 ^ D50 +error(0.008757252326096141501) D49 +error(0.01400557781329538239) D49 D50 +error(0.003940429509688737897) D49 D50 ^ D39 L0 +error(0.01774801221981088181) D49 D50 ^ D47 L0 +error(0.0002241990306885290963) D49 D50 ^ D51 L0 +error(0.0002398915537285264889) D49 D50 ^ D51 L0 ^ D39 L0 +error(0.0199456988747792191) D49 D57 +error(3.564955517285772993e-07) D49 ^ D37 ^ D39 L0 +error(0.0007061037462806830011) D49 ^ D37 ^ D47 L0 +error(0.0003886023791641102015) D49 ^ D47 L0 ^ D39 L0 +error(0.02267274013643192504) D50 +error(0.003518916957238571799) D50 D57 +error(0.003138668157944232186) D50 D57 ^ D47 L0 +error(0.0002848009832623634948) D50 D57 ^ D59 L0 +error(0.0002809672024858596447) D50 D57 ^ D59 L0 ^ D47 L0 +error(0.02037863138761538545) D50 D58 +error(0.0008394508946699175177) D50 D58 ^ D47 L0 +error(0.00393251772886478012) D50 D58 ^ D59 L0 +error(0.0003455869076207062881) D50 ^ D38 ^ D40 +error(0.0005475199888806141137) D50 ^ D38 ^ D48 +error(0.001624233559704021295) D50 ^ D40 +error(0.01066461502177179499) D50 ^ D51 L0 +error(0.00214963269345377515) D50 ^ D59 L0 +error(0.00497062980159790422) D51 D59 ^ D50 +error(0.02465692158241580487) D51 D59 +error(0.005000000000000000104) D51 L0 +error(0.005000000000000000104) D52 +error(0.01511339752813176118) D52 D55 +error(0.01318529921048066343) D52 D55 ^ D53 +error(0.02113542811391193668) D52 D60 +error(0.003601039126778393662) D52 D60 ^ D61 +error(0.00359794063471834645) D52 D63 +error(0.003550675664690026209) D52 D63 ^ D53 +error(0.002523312720004263019) D52 D63 ^ D61 +error(0.00120410006428202875) D52 D63 ^ D61 ^ D53 +error(0.002358990922302896861) D52 D64 +error(0.000900329109565413334) D52 D64 ^ D53 +error(0.001422466139403531522) D52 D64 ^ D53 D61 +error(0.000227529332159509529) D52 D64 ^ D61 +error(0.005671061927629780092) D52 ^ D53 +error(0.002837628295752675847) D52 ^ D61 +error(0.003307776772393457038) D53 D61 ^ D52 +error(0.01000000000000000021) D53 +error(0.009659594482854964859) D53 D54 +error(0.0005681221308502792944) D53 D54 ^ D52 +error(1.221615784209272829e-05) D53 D54 ^ D55 D56 +error(0.01197970675250215056) D53 D54 ^ D56 +error(0.002468551585310864264) D53 D54 ^ D56 D64 +error(0.002247465333081031646) D53 D54 ^ D64 +error(7.99905811885554506e-05) D53 D54 ^ D64 ^ D52 +error(0.0149046830253691618) D53 D58 +error(0.01158960761781799818) D53 D58 ^ D55 D56 +error(0.03097165563823810197) D53 D61 +error(0.002341580630745021974) D53 D61 ^ D63 D64 +error(0.001004674392747008198) D53 D61 ^ D64 +error(0.001715583818580762978) D53 D65 +error(0.001950587289979390914) D53 D65 ^ D55 D63 +error(0.0002873849163372229633) D53 D65 ^ D55 D64 +error(0.000250635755306040397) D53 D65 ^ D63 D64 +error(0.003948014621302732043) D53 D66 +error(0.001775671469750636109) D53 D66 ^ D55 D56 +error(0.001801781851294598745) D53 D66 ^ D55 D63 +error(0.001714031950420857008) D53 D66 ^ D55 D64 +error(0.0005120024926036837636) D53 D66 ^ D56 D64 +error(0.00216425719161783851) D53 D66 ^ D63 D64 +error(0.0004354228931719861663) D53 ^ D63 L0 +error(0.003765899750618454181) D55 D63 ^ D53 +error(0.01549347680688980405) D54 +error(0.001854426416129751048) D54 D61 +error(0.0002354062236734246057) D54 D61 ^ D52 +error(0.002188603398587882221) D54 D61 ^ D64 +error(9.046428883286232426e-05) D54 D61 ^ D64 ^ D52 +error(0.03357286637296971049) D54 D62 +error(0.003027692963263897263) D54 D62 ^ D64 +error(0.001416082311859589949) D54 D66 +error(3.42651728233790256e-05) D54 D66 ^ D55 D56 +error(0.0001287815486031648618) D54 D66 ^ D55 D64 +error(0.001487500032960160099) D54 D66 ^ D56 D64 +error(0.01554489029060489302) D54 ^ D56 +error(0.001452163632415732868) D54 ^ D64 ^ D56 +error(0.01232976508330123518) D55 D56 +error(0.0009024575091639398068) D55 D56 ^ D57 D58 +error(0.00132845243984354433) D55 D56 ^ D58 +error(0.002627104611062700337) D55 D56 ^ D58 D66 +error(0.001775990005087981979) D55 D56 ^ D66 +error(0.04390708729114359971) D55 D63 +error(0.003367806044768197494) D55 D63 ^ D65 D66 +error(0.002385866215008573821) D55 D64 +error(0.0003400294089845564468) D55 D64 ^ D65 D66 +error(0.001711368909680681914) D55 D67 +error(0.0006907184389567510435) D55 D67 ^ D58 +error(0.001678528085572790918) D55 D67 ^ D58 D66 +error(0.0006093950648277737803) D55 D67 ^ D66 +error(0.01000000000000000021) D55 L0 +error(0.01224181716280624624) D55 L0 ^ D57 +error(0.003252238252497897768) D57 D65 ^ D55 L0 +error(0.01790797738103024755) D56 +error(0.02001725581242098928) D56 D59 +error(0.02111497934355966929) D56 D59 ^ D58 +error(0.01583066593640236955) D56 D64 +error(0.003023260842645458021) D56 D64 ^ D66 +error(0.008295038404182598218) D56 D67 +error(0.005521572502132320731) D56 D67 ^ D58 +error(0.007766717057027912145) D56 D67 ^ D66 +error(0.0008028985601615047695) D56 D67 ^ D66 ^ D58 +error(0.008757252326096141501) D57 +error(0.01400557781329538239) D57 D58 +error(0.003940429509688737897) D57 D58 ^ D47 L0 +error(0.01774801221981088181) D57 D58 ^ D55 L0 +error(0.0002241990306885290963) D57 D58 ^ D59 L0 +error(0.0002398915537285264889) D57 D58 ^ D59 L0 ^ D47 L0 +error(0.0199456988747792191) D57 D65 +error(3.564955517285772993e-07) D57 ^ D45 ^ D47 L0 +error(0.0007061037462806830011) D57 ^ D45 ^ D55 L0 +error(0.0003886023791641102015) D57 ^ D55 L0 ^ D47 L0 +error(0.02267274013643192504) D58 +error(0.003518916957238571799) D58 D65 +error(0.003138668157944232186) D58 D65 ^ D55 L0 +error(0.0002848009832623634948) D58 D65 ^ D67 L0 +error(0.0002809672024858596447) D58 D65 ^ D67 L0 ^ D55 L0 +error(0.02037863138761538545) D58 D66 +error(0.0008394508946699175177) D58 D66 ^ D55 L0 +error(0.00393251772886478012) D58 D66 ^ D67 L0 +error(0.0003455869076207062881) D58 ^ D46 ^ D48 +error(0.0005475199888806141137) D58 ^ D46 ^ D56 +error(0.001624233559704021295) D58 ^ D48 +error(0.01066461502177179499) D58 ^ D59 L0 +error(0.00214963269345377515) D58 ^ D67 L0 +error(0.00497062980159790422) D59 D67 ^ D58 +error(0.02465692158241580487) D59 D67 +error(0.005000000000000000104) D59 L0 +error(0.005000000000000000104) D60 +error(0.01511339752813176118) D60 D63 +error(0.01318529921048066343) D60 D63 ^ D61 +error(0.02113542811391193668) D60 D68 +error(0.003601039126778393662) D60 D68 ^ D69 +error(0.00359794063471834645) D60 D71 +error(0.003550675664690026209) D60 D71 ^ D61 +error(0.002523312720004263019) D60 D71 ^ D69 +error(0.00120410006428202875) D60 D71 ^ D69 ^ D61 +error(0.002358990922302896861) D60 D72 +error(0.000900329109565413334) D60 D72 ^ D61 +error(0.001422466139403531522) D60 D72 ^ D61 D69 +error(0.000227529332159509529) D60 D72 ^ D69 +error(0.005671061927629780092) D60 ^ D61 +error(0.002837628295752675847) D60 ^ D69 +error(0.003307776772393457038) D61 D69 ^ D60 +error(0.01000000000000000021) D61 +error(0.009659594482854964859) D61 D62 +error(0.0005681221308502792944) D61 D62 ^ D60 +error(1.221615784209272829e-05) D61 D62 ^ D63 D64 +error(0.01197970675250215056) D61 D62 ^ D64 +error(0.002468551585310864264) D61 D62 ^ D64 D72 +error(0.002247465333081031646) D61 D62 ^ D72 +error(7.99905811885554506e-05) D61 D62 ^ D72 ^ D60 +error(0.0149046830253691618) D61 D66 +error(0.01158960761781799818) D61 D66 ^ D63 D64 +error(0.03097165563823810197) D61 D69 +error(0.002341580630745021974) D61 D69 ^ D71 D72 +error(0.001004674392747008198) D61 D69 ^ D72 +error(0.001715583818580762978) D61 D73 +error(0.001950587289979390914) D61 D73 ^ D63 D71 +error(0.0002873849163372229633) D61 D73 ^ D63 D72 +error(0.000250635755306040397) D61 D73 ^ D71 D72 +error(0.003948014621302732043) D61 D74 +error(0.001775671469750636109) D61 D74 ^ D63 D64 +error(0.001801781851294598745) D61 D74 ^ D63 D71 +error(0.001714031950420857008) D61 D74 ^ D63 D72 +error(0.0005120024926036837636) D61 D74 ^ D64 D72 +error(0.00216425719161783851) D61 D74 ^ D71 D72 +error(0.0004354228931719861663) D61 ^ D71 L0 +error(0.003765899750618454181) D63 D71 ^ D61 +error(0.01549347680688980405) D62 +error(0.001854426416129751048) D62 D69 +error(0.0002354062236734246057) D62 D69 ^ D60 +error(0.002188603398587882221) D62 D69 ^ D72 +error(9.046428883286232426e-05) D62 D69 ^ D72 ^ D60 +error(0.03357286637296971049) D62 D70 +error(0.003027692963263897263) D62 D70 ^ D72 +error(0.001416082311859589949) D62 D74 +error(3.42651728233790256e-05) D62 D74 ^ D63 D64 +error(0.0001287815486031648618) D62 D74 ^ D63 D72 +error(0.001487500032960160099) D62 D74 ^ D64 D72 +error(0.01554489029060489302) D62 ^ D64 +error(0.001452163632415732868) D62 ^ D72 ^ D64 +error(0.01232976508330123518) D63 D64 +error(0.0009024575091639398068) D63 D64 ^ D65 D66 +error(0.00132845243984354433) D63 D64 ^ D66 +error(0.002627104611062700337) D63 D64 ^ D66 D74 +error(0.001775990005087981979) D63 D64 ^ D74 +error(0.04390708729114359971) D63 D71 +error(0.003367806044768197494) D63 D71 ^ D73 D74 +error(0.002385866215008573821) D63 D72 +error(0.0003400294089845564468) D63 D72 ^ D73 D74 +error(0.001711368909680681914) D63 D75 +error(0.0006907184389567510435) D63 D75 ^ D66 +error(0.001678528085572790918) D63 D75 ^ D66 D74 +error(0.0006093950648277737803) D63 D75 ^ D74 +error(0.01000000000000000021) D63 L0 +error(0.01224181716280624624) D63 L0 ^ D65 +error(0.003252238252497897768) D65 D73 ^ D63 L0 +error(0.01790797738103024755) D64 +error(0.02001725581242098928) D64 D67 +error(0.02111497934355966929) D64 D67 ^ D66 +error(0.01583066593640236955) D64 D72 +error(0.003023260842645458021) D64 D72 ^ D74 +error(0.008295038404182598218) D64 D75 +error(0.005521572502132320731) D64 D75 ^ D66 +error(0.007766717057027912145) D64 D75 ^ D74 +error(0.0008028985601615047695) D64 D75 ^ D74 ^ D66 +error(0.008757252326096141501) D65 +error(0.01400557781329538239) D65 D66 +error(0.003940429509688737897) D65 D66 ^ D55 L0 +error(0.01774801221981088181) D65 D66 ^ D63 L0 +error(0.0002241990306885290963) D65 D66 ^ D67 L0 +error(0.0002398915537285264889) D65 D66 ^ D67 L0 ^ D55 L0 +error(0.0199456988747792191) D65 D73 +error(3.564955517285772993e-07) D65 ^ D53 ^ D55 L0 +error(0.0007061037462806830011) D65 ^ D53 ^ D63 L0 +error(0.0003886023791641102015) D65 ^ D63 L0 ^ D55 L0 +error(0.02267274013643192504) D66 +error(0.003518916957238571799) D66 D73 +error(0.003138668157944232186) D66 D73 ^ D63 L0 +error(0.0002848009832623634948) D66 D73 ^ D75 L0 +error(0.0002809672024858596447) D66 D73 ^ D75 L0 ^ D63 L0 +error(0.02037863138761538545) D66 D74 +error(0.0008394508946699175177) D66 D74 ^ D63 L0 +error(0.00393251772886478012) D66 D74 ^ D75 L0 +error(0.0003455869076207062881) D66 ^ D54 ^ D56 +error(0.0005475199888806141137) D66 ^ D54 ^ D64 +error(0.001624233559704021295) D66 ^ D56 +error(0.01066461502177179499) D66 ^ D67 L0 +error(0.00214963269345377515) D66 ^ D75 L0 +error(0.00497062980159790422) D67 D75 ^ D66 +error(0.02465692158241580487) D67 D75 +error(0.005000000000000000104) D67 L0 +error(0.005000000000000000104) D68 +error(0.01511339752813176118) D68 D71 +error(0.01318529921048066343) D68 D71 ^ D69 +error(0.02113542811391193668) D68 D76 +error(0.003601039126778393662) D68 D76 ^ D77 +error(0.00359794063471834645) D68 D79 +error(0.003550675664690026209) D68 D79 ^ D69 +error(0.002523312720004263019) D68 D79 ^ D77 +error(0.00120410006428202875) D68 D79 ^ D77 ^ D69 +error(0.002358990922302896861) D68 D80 +error(0.000900329109565413334) D68 D80 ^ D69 +error(0.001422466139403531522) D68 D80 ^ D69 D77 +error(0.000227529332159509529) D68 D80 ^ D77 +error(0.005671061927629780092) D68 ^ D69 +error(0.002837628295752675847) D68 ^ D77 +error(0.003307776772393457038) D69 D77 ^ D68 +error(0.01000000000000000021) D69 +error(0.009659594482854964859) D69 D70 +error(0.0005681221308502792944) D69 D70 ^ D68 +error(1.221615784209272829e-05) D69 D70 ^ D71 D72 +error(0.01197970675250215056) D69 D70 ^ D72 +error(0.002468551585310864264) D69 D70 ^ D72 D80 +error(0.002247465333081031646) D69 D70 ^ D80 +error(7.99905811885554506e-05) D69 D70 ^ D80 ^ D68 +error(0.0149046830253691618) D69 D74 +error(0.01158960761781799818) D69 D74 ^ D71 D72 +error(0.03097165563823810197) D69 D77 +error(0.002341580630745021974) D69 D77 ^ D79 D80 +error(0.001004674392747008198) D69 D77 ^ D80 +error(0.001715583818580762978) D69 D81 +error(0.001950587289979390914) D69 D81 ^ D71 D79 +error(0.0002873849163372229633) D69 D81 ^ D71 D80 +error(0.000250635755306040397) D69 D81 ^ D79 D80 +error(0.003948014621302732043) D69 D82 +error(0.001775671469750636109) D69 D82 ^ D71 D72 +error(0.001801781851294598745) D69 D82 ^ D71 D79 +error(0.001714031950420857008) D69 D82 ^ D71 D80 +error(0.0005120024926036837636) D69 D82 ^ D72 D80 +error(0.00216425719161783851) D69 D82 ^ D79 D80 +error(0.0004354228931719861663) D69 ^ D79 L0 +error(0.003765899750618454181) D71 D79 ^ D69 +error(0.01549347680688980405) D70 +error(0.001854426416129751048) D70 D77 +error(0.0002354062236734246057) D70 D77 ^ D68 +error(0.002188603398587882221) D70 D77 ^ D80 +error(9.046428883286232426e-05) D70 D77 ^ D80 ^ D68 +error(0.03357286637296971049) D70 D78 +error(0.003027692963263897263) D70 D78 ^ D80 +error(0.001416082311859589949) D70 D82 +error(3.42651728233790256e-05) D70 D82 ^ D71 D72 +error(0.0001287815486031648618) D70 D82 ^ D71 D80 +error(0.001487500032960160099) D70 D82 ^ D72 D80 +error(0.01554489029060489302) D70 ^ D72 +error(0.001452163632415732868) D70 ^ D80 ^ D72 +error(0.01232976508330123518) D71 D72 +error(0.0009024575091639398068) D71 D72 ^ D73 D74 +error(0.00132845243984354433) D71 D72 ^ D74 +error(0.002627104611062700337) D71 D72 ^ D74 D82 +error(0.001775990005087981979) D71 D72 ^ D82 +error(0.04390708729114359971) D71 D79 +error(0.003367806044768197494) D71 D79 ^ D81 D82 +error(0.002385866215008573821) D71 D80 +error(0.0003400294089845564468) D71 D80 ^ D81 D82 +error(0.001711368909680681914) D71 D83 +error(0.0006907184389567510435) D71 D83 ^ D74 +error(0.001678528085572790918) D71 D83 ^ D74 D82 +error(0.0006093950648277737803) D71 D83 ^ D82 +error(0.01000000000000000021) D71 L0 +error(0.01224181716280624624) D71 L0 ^ D73 +error(0.003252238252497897768) D73 D81 ^ D71 L0 +error(0.01790797738103024755) D72 +error(0.02001725581242098928) D72 D75 +error(0.02111497934355966929) D72 D75 ^ D74 +error(0.01583066593640236955) D72 D80 +error(0.003023260842645458021) D72 D80 ^ D82 +error(0.008295038404182598218) D72 D83 +error(0.005521572502132320731) D72 D83 ^ D74 +error(0.007766717057027912145) D72 D83 ^ D82 +error(0.0008028985601615047695) D72 D83 ^ D82 ^ D74 +error(0.008757252326096141501) D73 +error(0.01400557781329538239) D73 D74 +error(0.003940429509688737897) D73 D74 ^ D63 L0 +error(0.01774801221981088181) D73 D74 ^ D71 L0 +error(0.0002241990306885290963) D73 D74 ^ D75 L0 +error(0.0002398915537285264889) D73 D74 ^ D75 L0 ^ D63 L0 +error(0.0199456988747792191) D73 D81 +error(3.564955517285772993e-07) D73 ^ D61 ^ D63 L0 +error(0.0007061037462806830011) D73 ^ D61 ^ D71 L0 +error(0.0003886023791641102015) D73 ^ D71 L0 ^ D63 L0 +error(0.02267274013643192504) D74 +error(0.003518916957238571799) D74 D81 +error(0.003138668157944232186) D74 D81 ^ D71 L0 +error(0.0002848009832623634948) D74 D81 ^ D83 L0 +error(0.0002809672024858596447) D74 D81 ^ D83 L0 ^ D71 L0 +error(0.02037863138761538545) D74 D82 +error(0.0008394508946699175177) D74 D82 ^ D71 L0 +error(0.00393251772886478012) D74 D82 ^ D83 L0 +error(0.0003455869076207062881) D74 ^ D62 ^ D64 +error(0.0005475199888806141137) D74 ^ D62 ^ D72 +error(0.001624233559704021295) D74 ^ D64 +error(0.01066461502177179499) D74 ^ D75 L0 +error(0.00214963269345377515) D74 ^ D83 L0 +error(0.00497062980159790422) D75 D83 ^ D74 +error(0.02465692158241580487) D75 D83 +error(0.005000000000000000104) D75 L0 +error(0.005000000000000000104) D76 +error(0.01511339752813176118) D76 D79 +error(0.01318529921048066343) D76 D79 ^ D77 +error(0.02113542811391193668) D76 D84 +error(0.003601039126778393662) D76 D84 ^ D85 +error(0.00359794063471834645) D76 D87 +error(0.003550675664690026209) D76 D87 ^ D77 +error(0.002523312720004263019) D76 D87 ^ D85 +error(0.00120410006428202875) D76 D87 ^ D85 ^ D77 +error(0.002358990922302896861) D76 D88 +error(0.000900329109565413334) D76 D88 ^ D77 +error(0.001422466139403531522) D76 D88 ^ D77 D85 +error(0.000227529332159509529) D76 D88 ^ D85 +error(0.005671061927629780092) D76 ^ D77 +error(0.002837628295752675847) D76 ^ D85 +error(0.003307776772393457038) D77 D85 ^ D76 +error(0.01000000000000000021) D77 +error(0.009659594482854964859) D77 D78 +error(0.0005681221308502792944) D77 D78 ^ D76 +error(1.221615784209272829e-05) D77 D78 ^ D79 D80 +error(0.01197970675250215056) D77 D78 ^ D80 +error(0.002468551585310864264) D77 D78 ^ D80 D88 +error(0.002247465333081031646) D77 D78 ^ D88 +error(7.99905811885554506e-05) D77 D78 ^ D88 ^ D76 +error(0.0149046830253691618) D77 D82 +error(0.01158960761781799818) D77 D82 ^ D79 D80 +error(0.03097165563823810197) D77 D85 +error(0.002341580630745021974) D77 D85 ^ D87 D88 +error(0.001004674392747008198) D77 D85 ^ D88 +error(0.001715583818580762978) D77 D89 +error(0.001950587289979390914) D77 D89 ^ D79 D87 +error(0.0002873849163372229633) D77 D89 ^ D79 D88 +error(0.000250635755306040397) D77 D89 ^ D87 D88 +error(0.003948014621302732043) D77 D90 +error(0.001775671469750636109) D77 D90 ^ D79 D80 +error(0.001801781851294598745) D77 D90 ^ D79 D87 +error(0.001714031950420857008) D77 D90 ^ D79 D88 +error(0.0005120024926036837636) D77 D90 ^ D80 D88 +error(0.00216425719161783851) D77 D90 ^ D87 D88 +error(0.0004354228931719861663) D77 ^ D87 L0 +error(0.003765899750618454181) D79 D87 ^ D77 +error(0.01549347680688980405) D78 +error(0.001854426416129751048) D78 D85 +error(0.0002354062236734246057) D78 D85 ^ D76 +error(0.002188603398587882221) D78 D85 ^ D88 +error(9.046428883286232426e-05) D78 D85 ^ D88 ^ D76 +error(0.03357286637296971049) D78 D86 +error(0.003027692963263897263) D78 D86 ^ D88 +error(0.001416082311859589949) D78 D90 +error(3.42651728233790256e-05) D78 D90 ^ D79 D80 +error(0.0001287815486031648618) D78 D90 ^ D79 D88 +error(0.001487500032960160099) D78 D90 ^ D80 D88 +error(0.01554489029060489302) D78 ^ D80 +error(0.001452163632415732868) D78 ^ D88 ^ D80 +error(0.01232976508330123518) D79 D80 +error(0.0009024575091639398068) D79 D80 ^ D81 D82 +error(0.00132845243984354433) D79 D80 ^ D82 +error(0.002627104611062700337) D79 D80 ^ D82 D90 +error(0.001775990005087981979) D79 D80 ^ D90 +error(0.04390708729114359971) D79 D87 +error(0.003367806044768197494) D79 D87 ^ D89 D90 +error(0.002385866215008573821) D79 D88 +error(0.0003400294089845564468) D79 D88 ^ D89 D90 +error(0.001711368909680681914) D79 D91 +error(0.0006907184389567510435) D79 D91 ^ D82 +error(0.001678528085572790918) D79 D91 ^ D82 D90 +error(0.0006093950648277737803) D79 D91 ^ D90 +error(0.01000000000000000021) D79 L0 +error(0.01224181716280624624) D79 L0 ^ D81 +error(0.003252238252497897768) D81 D89 ^ D79 L0 +error(0.01790797738103024755) D80 +error(0.02001725581242098928) D80 D83 +error(0.02111497934355966929) D80 D83 ^ D82 +error(0.01583066593640236955) D80 D88 +error(0.003023260842645458021) D80 D88 ^ D90 +error(0.008295038404182598218) D80 D91 +error(0.005521572502132320731) D80 D91 ^ D82 +error(0.007766717057027912145) D80 D91 ^ D90 +error(0.0008028985601615047695) D80 D91 ^ D90 ^ D82 +error(0.008757252326096141501) D81 +error(0.01400557781329538239) D81 D82 +error(0.003940429509688737897) D81 D82 ^ D71 L0 +error(0.01774801221981088181) D81 D82 ^ D79 L0 +error(0.0002241990306885290963) D81 D82 ^ D83 L0 +error(0.0002398915537285264889) D81 D82 ^ D83 L0 ^ D71 L0 +error(0.0199456988747792191) D81 D89 +error(3.564955517285772993e-07) D81 ^ D69 ^ D71 L0 +error(0.0007061037462806830011) D81 ^ D69 ^ D79 L0 +error(0.0003886023791641102015) D81 ^ D79 L0 ^ D71 L0 +error(0.02267274013643192504) D82 +error(0.003518916957238571799) D82 D89 +error(0.003138668157944232186) D82 D89 ^ D79 L0 +error(0.0002848009832623634948) D82 D89 ^ D91 L0 +error(0.0002809672024858596447) D82 D89 ^ D91 L0 ^ D79 L0 +error(0.02037863138761538545) D82 D90 +error(0.0008394508946699175177) D82 D90 ^ D79 L0 +error(0.00393251772886478012) D82 D90 ^ D91 L0 +error(0.0003455869076207062881) D82 ^ D70 ^ D72 +error(0.0005475199888806141137) D82 ^ D70 ^ D80 +error(0.001624233559704021295) D82 ^ D72 +error(0.01066461502177179499) D82 ^ D83 L0 +error(0.00214963269345377515) D82 ^ D91 L0 +error(0.00497062980159790422) D83 D91 ^ D82 +error(0.02465692158241580487) D83 D91 +error(0.005000000000000000104) D83 L0 +error(0.005000000000000000104) D84 +error(0.01511339752813176118) D84 D87 +error(0.01318529921048066343) D84 D87 ^ D85 +error(0.02113542811391193668) D84 D92 +error(0.003601039126778393662) D84 D92 ^ D93 +error(0.00359794063471834645) D84 D95 +error(0.003550675664690026209) D84 D95 ^ D85 +error(0.002523312720004263019) D84 D95 ^ D93 +error(0.00120410006428202875) D84 D95 ^ D93 ^ D85 +error(0.002358990922302896861) D84 D96 +error(0.000900329109565413334) D84 D96 ^ D85 +error(0.001422466139403531522) D84 D96 ^ D85 D93 +error(0.000227529332159509529) D84 D96 ^ D93 +error(0.005671061927629780092) D84 ^ D85 +error(0.002837628295752675847) D84 ^ D93 +error(0.003307776772393457038) D85 D93 ^ D84 +error(0.01000000000000000021) D85 +error(0.009659594482854964859) D85 D86 +error(0.0005681221308502792944) D85 D86 ^ D84 +error(1.221615784209272829e-05) D85 D86 ^ D87 D88 +error(0.01197970675250215056) D85 D86 ^ D88 +error(0.002468551585310864264) D85 D86 ^ D88 D96 +error(0.002247465333081031646) D85 D86 ^ D96 +error(7.99905811885554506e-05) D85 D86 ^ D96 ^ D84 +error(0.0149046830253691618) D85 D90 +error(0.01158960761781799818) D85 D90 ^ D87 D88 +error(0.03097165563823810197) D85 D93 +error(0.002341580630745021974) D85 D93 ^ D95 D96 +error(0.001004674392747008198) D85 D93 ^ D96 +error(0.001715583818580762978) D85 D97 +error(0.001950587289979390914) D85 D97 ^ D87 D95 +error(0.0002873849163372229633) D85 D97 ^ D87 D96 +error(0.000250635755306040397) D85 D97 ^ D95 D96 +error(0.003948014621302732043) D85 D98 +error(0.001775671469750636109) D85 D98 ^ D87 D88 +error(0.001801781851294598745) D85 D98 ^ D87 D95 +error(0.001714031950420857008) D85 D98 ^ D87 D96 +error(0.0005120024926036837636) D85 D98 ^ D88 D96 +error(0.00216425719161783851) D85 D98 ^ D95 D96 +error(0.0004354228931719861663) D85 ^ D95 L0 +error(0.003765899750618454181) D87 D95 ^ D85 +error(0.01549347680688980405) D86 +error(0.001854426416129751048) D86 D93 +error(0.0002354062236734246057) D86 D93 ^ D84 +error(0.002188603398587882221) D86 D93 ^ D96 +error(9.046428883286232426e-05) D86 D93 ^ D96 ^ D84 +error(0.03357286637296971049) D86 D94 +error(0.003027692963263897263) D86 D94 ^ D96 +error(0.001416082311859589949) D86 D98 +error(3.42651728233790256e-05) D86 D98 ^ D87 D88 +error(0.0001287815486031648618) D86 D98 ^ D87 D96 +error(0.001487500032960160099) D86 D98 ^ D88 D96 +error(0.01554489029060489302) D86 ^ D88 +error(0.001452163632415732868) D86 ^ D96 ^ D88 +error(0.01232976508330123518) D87 D88 +error(0.0009024575091639398068) D87 D88 ^ D89 D90 +error(0.00132845243984354433) D87 D88 ^ D90 +error(0.002627104611062700337) D87 D88 ^ D90 D98 +error(0.001775990005087981979) D87 D88 ^ D98 +error(0.04390708729114359971) D87 D95 +error(0.003367806044768197494) D87 D95 ^ D97 D98 +error(0.002385866215008573821) D87 D96 +error(0.0003400294089845564468) D87 D96 ^ D97 D98 +error(0.001711368909680681914) D87 D99 +error(0.0006907184389567510435) D87 D99 ^ D90 +error(0.001678528085572790918) D87 D99 ^ D90 D98 +error(0.0006093950648277737803) D87 D99 ^ D98 +error(0.01000000000000000021) D87 L0 +error(0.01224181716280624624) D87 L0 ^ D89 +error(0.003252238252497897768) D89 D97 ^ D87 L0 +error(0.01790797738103024755) D88 +error(0.02001725581242098928) D88 D91 +error(0.02111497934355966929) D88 D91 ^ D90 +error(0.01583066593640236955) D88 D96 +error(0.003023260842645458021) D88 D96 ^ D98 +error(0.008295038404182598218) D88 D99 +error(0.005521572502132320731) D88 D99 ^ D90 +error(0.007766717057027912145) D88 D99 ^ D98 +error(0.0008028985601615047695) D88 D99 ^ D98 ^ D90 +error(0.008757252326096141501) D89 +error(0.01400557781329538239) D89 D90 +error(0.003940429509688737897) D89 D90 ^ D79 L0 +error(0.01774801221981088181) D89 D90 ^ D87 L0 +error(0.0002241990306885290963) D89 D90 ^ D91 L0 +error(0.0002398915537285264889) D89 D90 ^ D91 L0 ^ D79 L0 +error(0.0199456988747792191) D89 D97 +error(3.564955517285772993e-07) D89 ^ D77 ^ D79 L0 +error(0.0007061037462806830011) D89 ^ D77 ^ D87 L0 +error(0.0003886023791641102015) D89 ^ D87 L0 ^ D79 L0 +error(0.02267274013643192504) D90 +error(0.003518916957238571799) D90 D97 +error(0.003138668157944232186) D90 D97 ^ D87 L0 +error(0.0002848009832623634948) D90 D97 ^ D99 L0 +error(0.0002809672024858596447) D90 D97 ^ D99 L0 ^ D87 L0 +error(0.02037863138761538545) D90 D98 +error(0.0008394508946699175177) D90 D98 ^ D87 L0 +error(0.00393251772886478012) D90 D98 ^ D99 L0 +error(0.0003455869076207062881) D90 ^ D78 ^ D80 +error(0.0005475199888806141137) D90 ^ D78 ^ D88 +error(0.001624233559704021295) D90 ^ D80 +error(0.01066461502177179499) D90 ^ D91 L0 +error(0.00214963269345377515) D90 ^ D99 L0 +error(0.00497062980159790422) D91 D99 ^ D90 +error(0.02465692158241580487) D91 D99 +error(0.005000000000000000104) D91 L0 +error(0.005000000000000000104) D92 +error(0.01511339752813176118) D92 D95 +error(0.01318529921048066343) D92 D95 ^ D93 +error(0.02113542811391193668) D92 D100 +error(0.003601039126778393662) D92 D100 ^ D101 +error(0.00359794063471834645) D92 D103 +error(0.003550675664690026209) D92 D103 ^ D93 +error(0.002523312720004263019) D92 D103 ^ D101 +error(0.00120410006428202875) D92 D103 ^ D101 ^ D93 +error(0.002358990922302896861) D92 D104 +error(0.000900329109565413334) D92 D104 ^ D93 +error(0.001422466139403531522) D92 D104 ^ D93 D101 +error(0.000227529332159509529) D92 D104 ^ D101 +error(0.005671061927629780092) D92 ^ D93 +error(0.002837628295752675847) D92 ^ D101 +error(0.003307776772393457038) D93 D101 ^ D92 +error(0.01000000000000000021) D93 +error(0.009659594482854964859) D93 D94 +error(0.0005681221308502792944) D93 D94 ^ D92 +error(1.221615784209272829e-05) D93 D94 ^ D95 D96 +error(0.01197970675250215056) D93 D94 ^ D96 +error(0.002468551585310864264) D93 D94 ^ D96 D104 +error(0.002247465333081031646) D93 D94 ^ D104 +error(7.99905811885554506e-05) D93 D94 ^ D104 ^ D92 +error(0.0149046830253691618) D93 D98 +error(0.01158960761781799818) D93 D98 ^ D95 D96 +error(0.03097165563823810197) D93 D101 +error(0.002341580630745021974) D93 D101 ^ D103 D104 +error(0.001004674392747008198) D93 D101 ^ D104 +error(0.001715583818580762978) D93 D105 +error(0.001950587289979390914) D93 D105 ^ D95 D103 +error(0.0002873849163372229633) D93 D105 ^ D95 D104 +error(0.000250635755306040397) D93 D105 ^ D103 D104 +error(0.003948014621302732043) D93 D106 +error(0.001775671469750636109) D93 D106 ^ D95 D96 +error(0.001801781851294598745) D93 D106 ^ D95 D103 +error(0.001714031950420857008) D93 D106 ^ D95 D104 +error(0.0005120024926036837636) D93 D106 ^ D96 D104 +error(0.00216425719161783851) D93 D106 ^ D103 D104 +error(0.0004354228931719861663) D93 ^ D103 L0 +error(0.003765899750618454181) D95 D103 ^ D93 +error(0.01549347680688980405) D94 +error(0.001854426416129751048) D94 D101 +error(0.0002354062236734246057) D94 D101 ^ D92 +error(0.002188603398587882221) D94 D101 ^ D104 +error(9.046428883286232426e-05) D94 D101 ^ D104 ^ D92 +error(0.03357286637296971049) D94 D102 +error(0.003027692963263897263) D94 D102 ^ D104 +error(0.001416082311859589949) D94 D106 +error(3.42651728233790256e-05) D94 D106 ^ D95 D96 +error(0.0001287815486031648618) D94 D106 ^ D95 D104 +error(0.001487500032960160099) D94 D106 ^ D96 D104 +error(0.01554489029060489302) D94 ^ D96 +error(0.001452163632415732868) D94 ^ D104 ^ D96 +error(0.01232976508330123518) D95 D96 +error(0.0009024575091639398068) D95 D96 ^ D97 D98 +error(0.00132845243984354433) D95 D96 ^ D98 +error(0.002627104611062700337) D95 D96 ^ D98 D106 +error(0.001775990005087981979) D95 D96 ^ D106 +error(0.04390708729114359971) D95 D103 +error(0.003367806044768197494) D95 D103 ^ D105 D106 +error(0.002385866215008573821) D95 D104 +error(0.0003400294089845564468) D95 D104 ^ D105 D106 +error(0.001711368909680681914) D95 D107 +error(0.0006907184389567510435) D95 D107 ^ D98 +error(0.001678528085572790918) D95 D107 ^ D98 D106 +error(0.0006093950648277737803) D95 D107 ^ D106 +error(0.01000000000000000021) D95 L0 +error(0.01224181716280624624) D95 L0 ^ D97 +error(0.003252238252497897768) D97 D105 ^ D95 L0 +error(0.01790797738103024755) D96 +error(0.02001725581242098928) D96 D99 +error(0.02111497934355966929) D96 D99 ^ D98 +error(0.01583066593640236955) D96 D104 +error(0.003023260842645458021) D96 D104 ^ D106 +error(0.008295038404182598218) D96 D107 +error(0.005521572502132320731) D96 D107 ^ D98 +error(0.007766717057027912145) D96 D107 ^ D106 +error(0.0008028985601615047695) D96 D107 ^ D106 ^ D98 +error(0.008757252326096141501) D97 +error(0.01400557781329538239) D97 D98 +error(0.003940429509688737897) D97 D98 ^ D87 L0 +error(0.01774801221981088181) D97 D98 ^ D95 L0 +error(0.0002241990306885290963) D97 D98 ^ D99 L0 +error(0.0002398915537285264889) D97 D98 ^ D99 L0 ^ D87 L0 +error(0.0199456988747792191) D97 D105 +error(3.564955517285772993e-07) D97 ^ D85 ^ D87 L0 +error(0.0007061037462806830011) D97 ^ D85 ^ D95 L0 +error(0.0003886023791641102015) D97 ^ D95 L0 ^ D87 L0 +error(0.02267274013643192504) D98 +error(0.003518916957238571799) D98 D105 +error(0.003138668157944232186) D98 D105 ^ D95 L0 +error(0.0002848009832623634948) D98 D105 ^ D107 L0 +error(0.0002809672024858596447) D98 D105 ^ D107 L0 ^ D95 L0 +error(0.02037863138761538545) D98 D106 +error(0.0008394508946699175177) D98 D106 ^ D95 L0 +error(0.00393251772886478012) D98 D106 ^ D107 L0 +error(0.0003455869076207062881) D98 ^ D86 ^ D88 +error(0.0005475199888806141137) D98 ^ D86 ^ D96 +error(0.001624233559704021295) D98 ^ D88 +error(0.01066461502177179499) D98 ^ D99 L0 +error(0.00214963269345377515) D98 ^ D107 L0 +error(0.00497062980159790422) D99 D107 ^ D98 +error(0.02465692158241580487) D99 D107 +error(0.005000000000000000104) D99 L0 +error(0.005000000000000000104) D100 +error(0.01511339752813176118) D100 D103 +error(0.01318529921048066343) D100 D103 ^ D101 +error(0.02113542811391193668) D100 D108 +error(0.003601039126778393662) D100 D108 ^ D109 +error(0.00359794063471834645) D100 D111 +error(0.003550675664690026209) D100 D111 ^ D101 +error(0.002523312720004263019) D100 D111 ^ D109 +error(0.00120410006428202875) D100 D111 ^ D109 ^ D101 +error(0.002358990922302896861) D100 D112 +error(0.000900329109565413334) D100 D112 ^ D101 +error(0.001422466139403531522) D100 D112 ^ D101 D109 +error(0.000227529332159509529) D100 D112 ^ D109 +error(0.005671061927629780092) D100 ^ D101 +error(0.002837628295752675847) D100 ^ D109 +error(0.003307776772393457038) D101 D109 ^ D100 +error(0.01000000000000000021) D101 +error(0.009659594482854964859) D101 D102 +error(0.0005681221308502792944) D101 D102 ^ D100 +error(1.221615784209272829e-05) D101 D102 ^ D103 D104 +error(0.01197970675250215056) D101 D102 ^ D104 +error(0.002468551585310864264) D101 D102 ^ D104 D112 +error(0.002247465333081031646) D101 D102 ^ D112 +error(7.99905811885554506e-05) D101 D102 ^ D112 ^ D100 +error(0.0149046830253691618) D101 D106 +error(0.01158960761781799818) D101 D106 ^ D103 D104 +error(0.03097165563823810197) D101 D109 +error(0.002341580630745021974) D101 D109 ^ D111 D112 +error(0.001004674392747008198) D101 D109 ^ D112 +error(0.001715583818580762978) D101 D113 +error(0.001950587289979390914) D101 D113 ^ D103 D111 +error(0.0002873849163372229633) D101 D113 ^ D103 D112 +error(0.000250635755306040397) D101 D113 ^ D111 D112 +error(0.003948014621302732043) D101 D114 +error(0.001775671469750636109) D101 D114 ^ D103 D104 +error(0.001801781851294598745) D101 D114 ^ D103 D111 +error(0.001714031950420857008) D101 D114 ^ D103 D112 +error(0.0005120024926036837636) D101 D114 ^ D104 D112 +error(0.00216425719161783851) D101 D114 ^ D111 D112 +error(0.0004354228931719861663) D101 ^ D111 L0 +error(0.003765899750618454181) D103 D111 ^ D101 +error(0.01549347680688980405) D102 +error(0.001854426416129751048) D102 D109 +error(0.0002354062236734246057) D102 D109 ^ D100 +error(0.002188603398587882221) D102 D109 ^ D112 +error(9.046428883286232426e-05) D102 D109 ^ D112 ^ D100 +error(0.03357286637296971049) D102 D110 +error(0.003027692963263897263) D102 D110 ^ D112 +error(0.001416082311859589949) D102 D114 +error(3.42651728233790256e-05) D102 D114 ^ D103 D104 +error(0.0001287815486031648618) D102 D114 ^ D103 D112 +error(0.001487500032960160099) D102 D114 ^ D104 D112 +error(0.01554489029060489302) D102 ^ D104 +error(0.001452163632415732868) D102 ^ D112 ^ D104 +error(0.01232976508330123518) D103 D104 +error(0.0009024575091639398068) D103 D104 ^ D105 D106 +error(0.00132845243984354433) D103 D104 ^ D106 +error(0.002627104611062700337) D103 D104 ^ D106 D114 +error(0.001775990005087981979) D103 D104 ^ D114 +error(0.04390708729114359971) D103 D111 +error(0.003367806044768197494) D103 D111 ^ D113 D114 +error(0.002385866215008573821) D103 D112 +error(0.0003400294089845564468) D103 D112 ^ D113 D114 +error(0.001711368909680681914) D103 D115 +error(0.0006907184389567510435) D103 D115 ^ D106 +error(0.001678528085572790918) D103 D115 ^ D106 D114 +error(0.0006093950648277737803) D103 D115 ^ D114 +error(0.01000000000000000021) D103 L0 +error(0.01224181716280624624) D103 L0 ^ D105 +error(0.003252238252497897768) D105 D113 ^ D103 L0 +error(0.01790797738103024755) D104 +error(0.02001725581242098928) D104 D107 +error(0.02111497934355966929) D104 D107 ^ D106 +error(0.01583066593640236955) D104 D112 +error(0.003023260842645458021) D104 D112 ^ D114 +error(0.008295038404182598218) D104 D115 +error(0.005521572502132320731) D104 D115 ^ D106 +error(0.007766717057027912145) D104 D115 ^ D114 +error(0.0008028985601615047695) D104 D115 ^ D114 ^ D106 +error(0.008757252326096141501) D105 +error(0.01400557781329538239) D105 D106 +error(0.003940429509688737897) D105 D106 ^ D95 L0 +error(0.01774801221981088181) D105 D106 ^ D103 L0 +error(0.0002241990306885290963) D105 D106 ^ D107 L0 +error(0.0002398915537285264889) D105 D106 ^ D107 L0 ^ D95 L0 +error(0.0199456988747792191) D105 D113 +error(3.564955517285772993e-07) D105 ^ D93 ^ D95 L0 +error(0.0007061037462806830011) D105 ^ D93 ^ D103 L0 +error(0.0003886023791641102015) D105 ^ D103 L0 ^ D95 L0 +error(0.02267274013643192504) D106 +error(0.003518916957238571799) D106 D113 +error(0.003138668157944232186) D106 D113 ^ D103 L0 +error(0.0002848009832623634948) D106 D113 ^ D115 L0 +error(0.0002809672024858596447) D106 D113 ^ D115 L0 ^ D103 L0 +error(0.02037863138761538545) D106 D114 +error(0.0008394508946699175177) D106 D114 ^ D103 L0 +error(0.00393251772886478012) D106 D114 ^ D115 L0 +error(0.0003455869076207062881) D106 ^ D94 ^ D96 +error(0.0005475199888806141137) D106 ^ D94 ^ D104 +error(0.001624233559704021295) D106 ^ D96 +error(0.01066461502177179499) D106 ^ D107 L0 +error(0.00214963269345377515) D106 ^ D115 L0 +error(0.00497062980159790422) D107 D115 ^ D106 +error(0.02465692158241580487) D107 D115 +error(0.005000000000000000104) D107 L0 +error(0.01064826117247528493) D108 +error(0.01535342853307404033) D108 D111 +error(0.01531649121687973965) D108 D111 ^ D109 +error(0.02293861178759282193) D108 D116 +error(0.006991277280231780224) D108 D117 +error(0.008120210516096498105) D108 D117 ^ D109 +error(0.001216436566432994035) D108 D118 +error(0.002600084290867491019) D108 D118 ^ D109 +error(0.007310118816029364738) D108 ^ D109 +error(0.03929924001406559508) D109 +error(0.008159658064767030469) D109 D110 +error(0.01219076708807322398) D109 D110 ^ D112 +error(0.003018032674040771034) D109 D110 ^ D112 D118 +error(0.001923756849450659326) D109 D110 ^ D118 +error(0.01509695768880400107) D109 D114 +error(0.01139076130845960953) D109 D114 ^ D111 D112 +error(0.0002250687862692107714) D109 ^ D108 ^ D110 +error(0.01148111994429172784) D111 D117 ^ D109 +error(0.0002827020949743823267) D109 ^ D118 ^ D108 ^ D110 +error(0.05633782082531501451) D110 +error(0.01419663893917521603) D110 ^ D112 +error(0.004838269102819408446) D110 ^ D118 +error(0.00154454522270051171) D112 D118 ^ D110 +error(0.01622968909418632741) D111 D112 +error(0.001106202564465585524) D111 D112 ^ D109 +error(0.0001412990991437007397) D111 D112 ^ D110 +error(0.001559716742253365812) D111 D112 ^ D110 ^ D109 +error(0.0007333178221243871623) D111 D112 ^ D113 D114 +error(0.04526577923285379085) D111 D117 +error(0.001015868383061570594) D111 D118 +error(0.000841420760882988835) D111 D118 ^ D109 +error(0.0009176484209109087411) D111 D118 ^ D110 ^ D109 +error(0.003090750048484729) D111 D119 +error(0.003667333877125703717) D111 D119 ^ D114 +error(0.02211573865829306526) D111 L0 +error(0.01620860279923914959) D111 L0 ^ D113 +error(0.00450576926113959407) D111 L0 ^ D114 +error(0.0276202946096632436) D112 +error(0.01940669201801058924) D112 D115 +error(0.01964804903338024031) D112 D115 ^ D114 +error(0.0198353922389704479) D112 D118 +error(0.0008123585169809105586) D112 D118 ^ D109 +error(0.0147020499542864988) D112 D119 +error(0.008111446276258220747) D112 D119 ^ D114 +error(0.03297184033200565439) D113 +error(0.01465743904992945421) D113 D114 +error(0.003940429509688737897) D113 D114 ^ D103 L0 +error(0.01888147075908841802) D113 D114 ^ D111 L0 +error(0.0002398915537285264889) D113 D114 ^ D115 L0 ^ D103 L0 +error(3.564955517285772993e-07) D113 ^ D101 ^ D103 L0 +error(0.0007061037462806830011) D113 ^ D101 ^ D111 L0 +error(0.0003886023791641102015) D113 ^ D111 L0 ^ D103 L0 +error(0.04451385209786002523) D114 +error(0.0003455869076207062881) D114 ^ D102 ^ D104 +error(0.0005475199888806141137) D114 ^ D102 ^ D112 +error(0.001624233559704021295) D114 ^ D104 +error(0.01051163455881684756) D114 ^ D115 L0 +error(0.00664235678993867467) D114 ^ D119 L0 +error(0.006181239082717415213) D115 D119 ^ D114 +error(0.02555574496623561759) D115 D119 +error(0.005000000000000000104) D115 L0 +error(0.01613085979114306512) D116 +error(0.01415572965116701498) D116 D117 +error(0.01478631434994625259) D117 D118 +error(0.005754537495719985567) D117 D118 ^ D109 +error(0.03732076531226294347) D117 L0 +error(0.03120068832460676927) D118 +error(0.01474268458781374802) D118 D119 +error(0.0005945985939834754711) D118 ^ D108 ^ D110 +error(0.01264502110982365472) D119 L0 +detector(3, 2, 0) D0 +detector(5, 2, 0) D1 +detector(5, 4, 0) D2 +detector(7, 4, 0) D3 +detector(3, 2, 1) D4 +detector(4, 3, 1) D5 +detector(4, 5, 1) D6 +detector(5, 2, 1) D7 +detector(5, 4, 1) D8 +detector(6, 1, 1) D9 +detector(6, 3, 1) D10 +detector(7, 4, 1) D11 +detector(3, 2, 2) D12 +detector(4, 3, 2) D13 +detector(4, 5, 2) D14 +detector(5, 2, 2) D15 +detector(5, 4, 2) D16 +detector(6, 1, 2) D17 +detector(6, 3, 2) D18 +detector(7, 4, 2) D19 +detector(3, 2, 3) D20 +detector(4, 3, 3) D21 +detector(4, 5, 3) D22 +detector(5, 2, 3) D23 +detector(5, 4, 3) D24 +detector(6, 1, 3) D25 +detector(6, 3, 3) D26 +detector(7, 4, 3) D27 +detector(3, 2, 4) D28 +detector(4, 3, 4) D29 +detector(4, 5, 4) D30 +detector(5, 2, 4) D31 +detector(5, 4, 4) D32 +detector(6, 1, 4) D33 +detector(6, 3, 4) D34 +detector(7, 4, 4) D35 +detector(3, 2, 5) D36 +detector(4, 3, 5) D37 +detector(4, 5, 5) D38 +detector(5, 2, 5) D39 +detector(5, 4, 5) D40 +detector(6, 1, 5) D41 +detector(6, 3, 5) D42 +detector(7, 4, 5) D43 +detector(3, 2, 6) D44 +detector(4, 3, 6) D45 +detector(4, 5, 6) D46 +detector(5, 2, 6) D47 +detector(5, 4, 6) D48 +detector(6, 1, 6) D49 +detector(6, 3, 6) D50 +detector(7, 4, 6) D51 +detector(3, 2, 7) D52 +detector(4, 3, 7) D53 +detector(4, 5, 7) D54 +detector(5, 2, 7) D55 +detector(5, 4, 7) D56 +detector(6, 1, 7) D57 +detector(6, 3, 7) D58 +detector(7, 4, 7) D59 +detector(3, 2, 8) D60 +detector(4, 3, 8) D61 +detector(4, 5, 8) D62 +detector(5, 2, 8) D63 +detector(5, 4, 8) D64 +detector(6, 1, 8) D65 +detector(6, 3, 8) D66 +detector(7, 4, 8) D67 +detector(3, 2, 9) D68 +detector(4, 3, 9) D69 +detector(4, 5, 9) D70 +detector(5, 2, 9) D71 +detector(5, 4, 9) D72 +detector(6, 1, 9) D73 +detector(6, 3, 9) D74 +detector(7, 4, 9) D75 +detector(3, 2, 10) D76 +detector(4, 3, 10) D77 +detector(4, 5, 10) D78 +detector(5, 2, 10) D79 +detector(5, 4, 10) D80 +detector(6, 1, 10) D81 +detector(6, 3, 10) D82 +detector(7, 4, 10) D83 +detector(3, 2, 11) D84 +detector(4, 3, 11) D85 +detector(4, 5, 11) D86 +detector(5, 2, 11) D87 +detector(5, 4, 11) D88 +detector(6, 1, 11) D89 +detector(6, 3, 11) D90 +detector(7, 4, 11) D91 +detector(3, 2, 12) D92 +detector(4, 3, 12) D93 +detector(4, 5, 12) D94 +detector(5, 2, 12) D95 +detector(5, 4, 12) D96 +detector(6, 1, 12) D97 +detector(6, 3, 12) D98 +detector(7, 4, 12) D99 +detector(3, 2, 13) D100 +detector(4, 3, 13) D101 +detector(4, 5, 13) D102 +detector(5, 2, 13) D103 +detector(5, 4, 13) D104 +detector(6, 1, 13) D105 +detector(6, 3, 13) D106 +detector(7, 4, 13) D107 +detector(3, 2, 14) D108 +detector(4, 3, 14) D109 +detector(4, 5, 14) D110 +detector(5, 2, 14) D111 +detector(5, 4, 14) D112 +detector(6, 1, 14) D113 +detector(6, 3, 14) D114 +detector(7, 4, 14) D115 +detector(3, 2, 15) D116 +detector(5, 2, 15) D117 +detector(5, 4, 15) D118 +detector(7, 4, 15) D119 diff --git a/shared/package-files/7a/7aaa9927ba034150a5ecfdfe3cb9be82d87349cfa45a71760f562fe36197a069/blob b/shared/package-files/7a/7aaa9927ba034150a5ecfdfe3cb9be82d87349cfa45a71760f562fe36197a069/blob new file mode 100644 index 0000000000000000000000000000000000000000..9b362a0e1346c29f7207dc0afce392118daaeb2b --- /dev/null +++ b/shared/package-files/7a/7aaa9927ba034150a5ecfdfe3cb9be82d87349cfa45a71760f562fe36197a069/blob @@ -0,0 +1,155 @@ +"""Routines to calculate the broadcast time of certain graphs. + +Broadcasting is an information dissemination problem in which a node in a graph, +called the originator, must distribute a message to all other nodes by placing +a series of calls along the edges of the graph. Once informed, other nodes aid +the originator in distributing the message. + +The broadcasting must be completed as quickly as possible subject to the +following constraints: +- Each call requires one unit of time. +- A node can only participate in one call per unit of time. +- Each call only involves two adjacent nodes: a sender and a receiver. +""" + +import networkx as nx +from networkx import NetworkXError +from networkx.utils import not_implemented_for + +__all__ = [ + "tree_broadcast_center", + "tree_broadcast_time", +] + + +def _get_max_broadcast_value(G, U, v, values): + adj = sorted(set(G.neighbors(v)) & U, key=values.get, reverse=True) + return max(values[u] + i for i, u in enumerate(adj, start=1)) + + +def _get_broadcast_centers(G, v, values, target): + adj = sorted(G.neighbors(v), key=values.get, reverse=True) + j = next(i for i, u in enumerate(adj, start=1) if values[u] + i == target) + return set([v] + adj[:j]) + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +@nx._dispatchable +def tree_broadcast_center(G): + """Return the Broadcast Center of the tree `G`. + + The broadcast center of a graph G denotes the set of nodes having + minimum broadcast time [1]_. This is a linear algorithm for determining + the broadcast center of a tree with ``N`` nodes, as a by-product it also + determines the broadcast time from the broadcast center. + + Parameters + ---------- + G : undirected graph + The graph should be an undirected tree + + Returns + ------- + BC : (int, set) tuple + minimum broadcast number of the tree, set of broadcast centers + + Raises + ------ + NetworkXNotImplemented + If the graph is directed or is a multigraph. + + References + ---------- + .. [1] Slater, P.J., Cockayne, E.J., Hedetniemi, S.T, + Information dissemination in trees. SIAM J.Comput. 10(4), 692–701 (1981) + """ + # Assert that the graph G is a tree + if not nx.is_tree(G): + NetworkXError("Input graph is not a tree") + # step 0 + if G.number_of_nodes() == 2: + return 1, set(G.nodes()) + if G.number_of_nodes() == 1: + return 0, set(G.nodes()) + + # step 1 + U = {node for node, deg in G.degree if deg == 1} + values = {n: 0 for n in U} + T = G.copy() + T.remove_nodes_from(U) + + # step 2 + W = {node for node, deg in T.degree if deg == 1} + values.update((w, G.degree[w] - 1) for w in W) + + # step 3 + while T.number_of_nodes() >= 2: + # step 4 + w = min(W, key=lambda n: values[n]) + v = next(T.neighbors(w)) + + # step 5 + U.add(w) + W.remove(w) + T.remove_node(w) + + # step 6 + if T.degree(v) == 1: + # update t(v) + values.update({v: _get_max_broadcast_value(G, U, v, values)}) + W.add(v) + + # step 7 + v = nx.utils.arbitrary_element(T) + b_T = _get_max_broadcast_value(G, U, v, values) + return b_T, _get_broadcast_centers(G, v, values, b_T) + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +@nx._dispatchable +def tree_broadcast_time(G, node=None): + """Return the Broadcast Time of the tree `G`. + + The minimum broadcast time of a node is defined as the minimum amount + of time required to complete broadcasting starting from the + originator. The broadcast time of a graph is the maximum over + all nodes of the minimum broadcast time from that node [1]_. + This function returns the minimum broadcast time of `node`. + If `node` is None the broadcast time for the graph is returned. + + Parameters + ---------- + G : undirected graph + The graph should be an undirected tree + node: int, optional + index of starting node. If `None`, the algorithm returns the broadcast + time of the tree. + + Returns + ------- + BT : int + Broadcast Time of a node in a tree + + Raises + ------ + NetworkXNotImplemented + If the graph is directed or is a multigraph. + + References + ---------- + .. [1] Harutyunyan, H. A. and Li, Z. + "A Simple Construction of Broadcast Graphs." + In Computing and Combinatorics. COCOON 2019 + (Ed. D. Z. Du and C. Tian.) Springer, pp. 240-253, 2019. + """ + b_T, b_C = tree_broadcast_center(G) + if node is not None: + return b_T + min(nx.shortest_path_length(G, node, u) for u in b_C) + dist_from_center = dict.fromkeys(G, len(G)) + for u in b_C: + for v, dist in nx.shortest_path_length(G, u).items(): + if dist < dist_from_center[v]: + dist_from_center[v] = dist + return b_T + max(dist_from_center.values()) diff --git a/shared/package-files/7a/7aad2bc9a6deb3e467e2d7e8e7da15bc242942cfe2a1a8941bd9fbf392ae3897/blob b/shared/package-files/7a/7aad2bc9a6deb3e467e2d7e8e7da15bc242942cfe2a1a8941bd9fbf392ae3897/blob new file mode 100644 index 0000000000000000000000000000000000000000..b44e5a001049994a6f98bd28e2be080c5ba737dd Binary files /dev/null and b/shared/package-files/7a/7aad2bc9a6deb3e467e2d7e8e7da15bc242942cfe2a1a8941bd9fbf392ae3897/blob differ diff --git a/shared/package-files/7a/7aafcf38045e0edbee296ce32eec1bc91f6cb049e5e96f5b20e4200159f46ba5/README.md b/shared/package-files/7a/7aafcf38045e0edbee296ce32eec1bc91f6cb049e5e96f5b20e4200159f46ba5/README.md new file mode 100644 index 0000000000000000000000000000000000000000..37e465b1e9ff49af31ed2bf963adb06d06e0a366 --- /dev/null +++ b/shared/package-files/7a/7aafcf38045e0edbee296ce32eec1bc91f6cb049e5e96f5b20e4200159f46ba5/README.md @@ -0,0 +1,3 @@ +# Molecular retrieval research package + +E014: equal-weight ensemble of ten-peak and64-peak transformers with fragment/neutral-loss bin embeddings and fine mass-defect Fourier features, trained from random initialization on MassSpecGym v1.5 train fold plus supplied held-out-clean ICEBERG simulations (2,333,477 nonempty spectra). Morgan fingerprint predictions rank supplied molecular candidates by training-frequency-weighted cosine plus a train-calibrated Cauchy precursor-mass likelihood; candidate exact masses derive from supplied SMILES and no true query formula is used. All adducts and instrument conditions use the same trained model. Selected by full-validation retrieval Hit@1; validation results do not establish improvement over the external test reference. Run infer.sh INPUT_ROOT OUTPUT_ROOT. Runtime: supplied /opt/glacier/bin/python, one GPU, 4 CPU workers. No external data or cache is needed. diff --git a/shared/package-files/7a/7ab138a387e0bc91d8a479c9890324e07b5337d0911dd10cff7ce79708674f56/blob b/shared/package-files/7a/7ab138a387e0bc91d8a479c9890324e07b5337d0911dd10cff7ce79708674f56/blob new file mode 100644 index 0000000000000000000000000000000000000000..06febe4a73334d368c3c851bb466bd894e91aadf Binary files /dev/null and b/shared/package-files/7a/7ab138a387e0bc91d8a479c9890324e07b5337d0911dd10cff7ce79708674f56/blob differ diff --git a/shared/package-files/7a/7ab1489ca0e7b696374f0f41a2ae422b22c3e43a5f783e445e6fdebfbc4e93e4/blob b/shared/package-files/7a/7ab1489ca0e7b696374f0f41a2ae422b22c3e43a5f783e445e6fdebfbc4e93e4/blob new file mode 100644 index 0000000000000000000000000000000000000000..0d71edfcf48fff6eb711b3000032cd1a62ef7e60 --- /dev/null +++ b/shared/package-files/7a/7ab1489ca0e7b696374f0f41a2ae422b22c3e43a5f783e445e6fdebfbc4e93e4/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & nll_loss_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & nll_loss_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & nll_loss_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & nll_loss_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor +inline at::Tensor nll_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); +} +namespace symint { + template ::value>> + at::Tensor nll_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); + } +} + +// aten::nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor +inline at::Tensor nll_loss_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); +} +namespace symint { + template ::value>> + at::Tensor nll_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); + } +} + +} diff --git a/shared/package-files/7a/7ab57b963cd64f210d5a074b15e8dae9b4d1699da980dd523362d3f88e966847/blob b/shared/package-files/7a/7ab57b963cd64f210d5a074b15e8dae9b4d1699da980dd523362d3f88e966847/blob new file mode 100644 index 0000000000000000000000000000000000000000..caf159002d8bb6778b53315a96dabc2e177ac23c --- /dev/null +++ b/shared/package-files/7a/7ab57b963cd64f210d5a074b15e8dae9b4d1699da980dd523362d3f88e966847/blob @@ -0,0 +1,230 @@ +"""Running tests""" + +import sys +import time +import warnings + +from . import result +from .signals import registerResult + +__unittest = True + + +class _WritelnDecorator(object): + """Used to decorate file-like objects with a handy 'writeln' method""" + def __init__(self,stream): + self.stream = stream + + def __getattr__(self, attr): + if attr in ('stream', '__getstate__'): + raise AttributeError(attr) + return getattr(self.stream,attr) + + def writeln(self, arg=None): + if arg: + self.write(arg) + self.write('\n') # text-mode streams translate to \r\n if needed + + +class TextTestResult(result.TestResult): + """A test result class that can print formatted text results to a stream. + + Used by TextTestRunner. + """ + separator1 = '=' * 70 + separator2 = '-' * 70 + + def __init__(self, stream, descriptions, verbosity): + super(TextTestResult, self).__init__(stream, descriptions, verbosity) + self.stream = stream + self.showAll = verbosity > 1 + self.dots = verbosity == 1 + self.descriptions = descriptions + + def getDescription(self, test): + doc_first_line = test.shortDescription() + if self.descriptions and doc_first_line: + return '\n'.join((str(test), doc_first_line)) + else: + return str(test) + + def startTest(self, test): + super(TextTestResult, self).startTest(test) + if self.showAll: + self.stream.write(self.getDescription(test)) + self.stream.write(" ... ") + self.stream.flush() + + def addSuccess(self, test): + super(TextTestResult, self).addSuccess(test) + if self.showAll: + self.stream.writeln("ok") + self.stream.flush() + elif self.dots: + self.stream.write('.') + self.stream.flush() + + def addError(self, test, err): + super(TextTestResult, self).addError(test, err) + if self.showAll: + self.stream.writeln("ERROR") + self.stream.flush() + elif self.dots: + self.stream.write('E') + self.stream.flush() + + def addFailure(self, test, err): + super(TextTestResult, self).addFailure(test, err) + if self.showAll: + self.stream.writeln("FAIL") + self.stream.flush() + elif self.dots: + self.stream.write('F') + self.stream.flush() + + def addSkip(self, test, reason): + super(TextTestResult, self).addSkip(test, reason) + if self.showAll: + self.stream.writeln("skipped {0!r}".format(reason)) + self.stream.flush() + elif self.dots: + self.stream.write("s") + self.stream.flush() + + def addExpectedFailure(self, test, err): + super(TextTestResult, self).addExpectedFailure(test, err) + if self.showAll: + self.stream.writeln("expected failure") + self.stream.flush() + elif self.dots: + self.stream.write("x") + self.stream.flush() + + def addUnexpectedSuccess(self, test): + super(TextTestResult, self).addUnexpectedSuccess(test) + if self.showAll: + self.stream.writeln("unexpected success") + self.stream.flush() + elif self.dots: + self.stream.write("u") + self.stream.flush() + + def printErrors(self): + if self.dots or self.showAll: + self.stream.writeln() + self.stream.flush() + self.printErrorList('ERROR', self.errors) + self.printErrorList('FAIL', self.failures) + + def printErrorList(self, flavour, errors): + for test, err in errors: + self.stream.writeln(self.separator1) + self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) + self.stream.writeln(self.separator2) + self.stream.writeln("%s" % err) + self.stream.flush() + + +class TextTestRunner(object): + """A test runner class that displays results in textual form. + + It prints out the names of tests as they are run, errors as they + occur, and a summary of the results at the end of the test run. + """ + resultclass = TextTestResult + + def __init__(self, stream=None, descriptions=True, verbosity=1, + failfast=False, buffer=False, resultclass=None, warnings=None, + *, tb_locals=False): + """Construct a TextTestRunner. + + Subclasses should accept **kwargs to ensure compatibility as the + interface changes. + """ + if stream is None: + stream = sys.stderr + self.stream = _WritelnDecorator(stream) + self.descriptions = descriptions + self.verbosity = verbosity + self.failfast = failfast + self.buffer = buffer + self.tb_locals = tb_locals + self.warnings = warnings + if resultclass is not None: + self.resultclass = resultclass + + def _makeResult(self): + return self.resultclass(self.stream, self.descriptions, self.verbosity) + + def run(self, test): + "Run the given test case or test suite." + result = self._makeResult() + registerResult(result) + result.failfast = self.failfast + result.buffer = self.buffer + result.tb_locals = self.tb_locals + with warnings.catch_warnings(): + if self.warnings: + # if self.warnings is set, use it to filter all the warnings + warnings.simplefilter(self.warnings) + # if the filter is 'default' or 'always', special-case the + # warnings from the deprecated unittest methods to show them + # no more than once per module, because they can be fairly + # noisy. The -Wd and -Wa flags can be used to bypass this + # only when self.warnings is None. + if self.warnings in ['default', 'always']: + warnings.filterwarnings('module', + category=DeprecationWarning, + message=r'Please use assert\w+ instead.') + startTime = time.perf_counter() + startTestRun = getattr(result, 'startTestRun', None) + if startTestRun is not None: + startTestRun() + try: + test(result) + finally: + stopTestRun = getattr(result, 'stopTestRun', None) + if stopTestRun is not None: + stopTestRun() + stopTime = time.perf_counter() + timeTaken = stopTime - startTime + result.printErrors() + if hasattr(result, 'separator2'): + self.stream.writeln(result.separator2) + run = result.testsRun + self.stream.writeln("Ran %d test%s in %.3fs" % + (run, run != 1 and "s" or "", timeTaken)) + self.stream.writeln() + + expectedFails = unexpectedSuccesses = skipped = 0 + try: + results = map(len, (result.expectedFailures, + result.unexpectedSuccesses, + result.skipped)) + except AttributeError: + pass + else: + expectedFails, unexpectedSuccesses, skipped = results + + infos = [] + if not result.wasSuccessful(): + self.stream.write("FAILED") + failed, errored = len(result.failures), len(result.errors) + if failed: + infos.append("failures=%d" % failed) + if errored: + infos.append("errors=%d" % errored) + else: + self.stream.write("OK") + if skipped: + infos.append("skipped=%d" % skipped) + if expectedFails: + infos.append("expected failures=%d" % expectedFails) + if unexpectedSuccesses: + infos.append("unexpected successes=%d" % unexpectedSuccesses) + if infos: + self.stream.writeln(" (%s)" % (", ".join(infos),)) + else: + self.stream.write("\n") + self.stream.flush() + return result diff --git a/shared/package-files/7a/7ab70ecd76d85ff538c7e42927d1f9acdc19f2447abe4bbf318425cd12275b6f/blob b/shared/package-files/7a/7ab70ecd76d85ff538c7e42927d1f9acdc19f2447abe4bbf318425cd12275b6f/blob new file mode 100644 index 0000000000000000000000000000000000000000..0b3719cca3bf1ff7154625c510c8292dd47444a7 --- /dev/null +++ b/shared/package-files/7a/7ab70ecd76d85ff538c7e42927d1f9acdc19f2447abe4bbf318425cd12275b6f/blob @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/shared/package-files/7a/7ab7ce0ebdc3ad2a73eb990074eed3b367466d9c6f75d10fea0c78057df2d89d/blob b/shared/package-files/7a/7ab7ce0ebdc3ad2a73eb990074eed3b367466d9c6f75d10fea0c78057df2d89d/blob new file mode 100644 index 0000000000000000000000000000000000000000..5a0b7f1ca032be1adf8ba91f863e727c5ec6a026 Binary files /dev/null and b/shared/package-files/7a/7ab7ce0ebdc3ad2a73eb990074eed3b367466d9c6f75d10fea0c78057df2d89d/blob differ diff --git a/shared/package-files/7a/7aba31084b50405fb5e9f22fc6c13c6c355d34f28999cf4526ad6d1f2a16ebbf/train.py b/shared/package-files/7a/7aba31084b50405fb5e9f22fc6c13c6c355d34f28999cf4526ad6d1f2a16ebbf/train.py new file mode 100644 index 0000000000000000000000000000000000000000..6ece1fc56210899ca3b75487ebb08dcda2f250fd --- /dev/null +++ b/shared/package-files/7a/7aba31084b50405fb5e9f22fc6c13c6c355d34f28999cf4526ad6d1f2a16ebbf/train.py @@ -0,0 +1,229 @@ +"""train.py + +Train ffn to predict binned specs + +""" +import logging +import yaml +import argparse +from pathlib import Path +import pandas as pd +from datetime import datetime + +from torch.utils.data import DataLoader + +import pytorch_lightning as pl +from pytorch_lightning import loggers as pl_loggers +from pytorch_lightning.callbacks.early_stopping import EarlyStopping +from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint + +import ms_pred.common as common +from ms_pred.ffn_pred import ffn_data, ffn_model + + +def add_ffn_train_args(parser): + parser.add_argument("--debug", default=False, action="store_true") + parser.add_argument("--debug-overfit", default=False, action="store_true") + parser.add_argument("--gpu", default=False, action="store_true") + parser.add_argument("--seed", default=42, action="store", type=int) + parser.add_argument("--num-workers", default=0, action="store", type=int) + parser.add_argument("--batch-size", default=128, action="store", type=int) + parser.add_argument("--max-epochs", default=100, action="store", type=int) + parser.add_argument("--min-epochs", default=0, action="store", type=int) + + date = datetime.now().strftime("%Y_%m_%d") + parser.add_argument("--save-dir", default=f"results/{date}_ffn/") + + parser.add_argument("--dataset-name", default="gnps2015_debug") + parser.add_argument("--dataset-labels", default="labels.tsv") + parser.add_argument("--split-name", default="split_1.tsv") + + parser.add_argument("--learning-rate", default=4e-7, action="store", type=float) + parser.add_argument("--weight-decay", default=0, action="store", type=float) + + parser.add_argument("--num-bins", default=15000, action="store", type=int) + parser.add_argument( + "--loss-fn", default="cosine", action="store", choices=["mse", "cosine"] + ) + parser.add_argument("--layers", default=3, action="store", type=int) + parser.add_argument("--lr-decay-rate", default=1.0, action="store", type=float) + parser.add_argument("--dropout", default=0.1, action="store", type=float) + parser.add_argument("--hidden-size", default=256, action="store", type=int) + parser.add_argument("--use-reverse", default=False, action="store_true") + parser.add_argument("--embed-adduct", default=False, action="store_true") + parser.add_argument("--form-dir-name", default="subform_20", action="store") + return parser + + +def get_args(): + parser = argparse.ArgumentParser() + parser = add_ffn_train_args(parser) + return parser.parse_args() + + +def train_model(): + args = get_args() + kwargs = args.__dict__ + + save_dir = kwargs["save_dir"] + common.setup_logger(save_dir, log_name="ffn_train.log", debug=kwargs["debug"]) + pl.seed_everything(kwargs.get("seed")) + + # Dump args + yaml_args = yaml.dump(kwargs) + logging.info(f"\n{yaml_args}") + with open(Path(save_dir) / "args.yaml", "w") as fp: + fp.write(yaml_args) + + # Get dataset + # Load smiles dataset and split into 3 subsets + dataset_name = kwargs["dataset_name"] + data_dir = Path("data/spec_datasets") / dataset_name + labels = data_dir / kwargs["dataset_labels"] + split_file = data_dir / "splits" / kwargs["split_name"] + + # Get train, val, test inds + df = pd.read_csv(labels, sep="\t") + if kwargs["debug"]: + df = df[:300] + spec_names = df["spec"].values + + train_inds, val_inds, test_inds = common.get_splits(spec_names, split_file) + train_df = df.iloc[train_inds] + val_df = df.iloc[val_inds] + test_df = df.iloc[test_inds] + + num_bins = kwargs.get("num_bins") + num_workers = kwargs.get("num_workers", 0) + upper_limit = kwargs.get("upper_limit", 1500) + train_dataset = ffn_data.BinnedDataset( + train_df, + data_dir=data_dir, + num_bins=num_bins, + # num_workers=num_workers, + form_dir_name=kwargs["form_dir_name"], + upper_limit=upper_limit, + ) + val_dataset = ffn_data.BinnedDataset( + val_df, + data_dir=data_dir, + num_bins=num_bins, + # num_workers=num_workers, + form_dir_name=kwargs["form_dir_name"], + upper_limit=upper_limit, + ) + test_dataset = ffn_data.BinnedDataset( + test_df, + data_dir=data_dir, + num_bins=num_bins, + # num_workers=num_workers, + form_dir_name=kwargs["form_dir_name"], + upper_limit=upper_limit, + ) + logging.info( + f"Train, val, test of sizes: {len(train_dataset)}, {len(val_dataset)}, {len(test_dataset)}" + ) + + # Define dataloaders + collate_fn = train_dataset.get_collate_fn() + train_loader = DataLoader( + train_dataset, + num_workers=kwargs["num_workers"], + collate_fn=collate_fn, + shuffle=True, + batch_size=kwargs["batch_size"], + ) + val_loader = DataLoader( + val_dataset, + num_workers=kwargs["num_workers"], + collate_fn=collate_fn, + shuffle=False, + batch_size=kwargs["batch_size"], + ) + test_loader = DataLoader( + test_dataset, + num_workers=kwargs["num_workers"], + collate_fn=collate_fn, + shuffle=False, + batch_size=kwargs["batch_size"], + ) + + # outputs = model(test_batch['fps']) + monitor = "val_loss" + if kwargs["debug"]: + kwargs["max_epochs"] = 2 + + if kwargs["debug_overfit"]: + kwargs["min_epochs"] = 2000 + kwargs["max_epochs"] = None + kwargs["no_monitor"] = True + kwargs["warmup"] = 0 + monitor = "train_loss" + + # Define model + # test_batch = next(iter(train_loader)) + model = ffn_model.ForwardFFN( + hidden_size=kwargs["hidden_size"], + layers=kwargs["layers"], + dropout=kwargs["dropout"], + output_dim=num_bins, + use_reverse=kwargs["use_reverse"], + learning_rate=kwargs["learning_rate"], + weight_decay=kwargs["weight_decay"], + upper_limit=upper_limit, + loss_fn=kwargs["loss_fn"], + lr_decay_rate=kwargs["lr_decay_rate"], + embed_adduct=kwargs["embed_adduct"], + warmup=kwargs.get("warmup", 1000), + ) + + # Create trainer + tb_logger = pl_loggers.TensorBoardLogger(save_dir, name="") + console_logger = common.ConsoleLogger() + + tb_path = tb_logger.log_dir + checkpoint_callback = ModelCheckpoint( + monitor=monitor, + dirpath=tb_path, + filename="best", # "{epoch}-{val_loss:.2f}", + save_weights_only=False, + ) + earlystop_callback = EarlyStopping(monitor=monitor, patience=10) + callbacks = [earlystop_callback, checkpoint_callback] + + trainer = pl.Trainer( + logger=[tb_logger, console_logger], + accelerator="gpu" if kwargs["gpu"] else "cpu", + devices=1 if kwargs["gpu"] else 0, + callbacks=callbacks, + gradient_clip_val=5, + min_epochs=kwargs["min_epochs"], + max_epochs=kwargs["max_epochs"], + gradient_clip_algorithm="value", + ) + + if kwargs["debug_overfit"]: + trainer.fit(model, train_loader) + else: + trainer.fit(model, train_loader, val_loader) + + checkpoint_callback = trainer.checkpoint_callback + best_checkpoint = checkpoint_callback.best_model_path + best_checkpoint_score = checkpoint_callback.best_model_score.item() + + # Load from checkpoint + model = ffn_model.ForwardFFN.load_from_checkpoint(best_checkpoint) + logging.info( + f"Loaded model with from {best_checkpoint} with val loss of {best_checkpoint_score}" + ) + model.eval() + trainer.test(dataloaders=test_loader) + + +if __name__ == "__main__": + import time + + start_time = time.time() + train_model() + end_time = time.time() + logging.info(f"Program finished in: {end_time - start_time} seconds") diff --git a/shared/package-files/7a/7abc3a8f140dab07f620a691862f5cebfc7cb2c73128a10516e9ce376acc5307/blob b/shared/package-files/7a/7abc3a8f140dab07f620a691862f5cebfc7cb2c73128a10516e9ce376acc5307/blob new file mode 100644 index 0000000000000000000000000000000000000000..5151a33f7ee351184e53daa68155dcc6c7390358 --- /dev/null +++ b/shared/package-files/7a/7abc3a8f140dab07f620a691862f5cebfc7cb2c73128a10516e9ce376acc5307/blob @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace torch { +namespace distributed { +namespace c10d { + +PyMethodDef* python_functions(); + +} // namespace c10d +} // namespace distributed +} // namespace torch diff --git a/shared/package-files/7a/7abd8034148719bcbf43172c66f38a828f739e32997dc3f1280013d43a0b1a12/blob b/shared/package-files/7a/7abd8034148719bcbf43172c66f38a828f739e32997dc3f1280013d43a0b1a12/blob new file mode 100644 index 0000000000000000000000000000000000000000..173319cb223c11bd0cb1866926d50b63dee9a36e --- /dev/null +++ b/shared/package-files/7a/7abd8034148719bcbf43172c66f38a828f739e32997dc3f1280013d43a0b1a12/blob @@ -0,0 +1,129 @@ +import re +import numpy as np +from numba import cuda +from numba.cuda.testing import unittest, skip_on_cudasim, CUDATestCase +from llvmlite import ir + + +@skip_on_cudasim("This is testing CUDA backend code generation") +class TestConstStringCodegen(unittest.TestCase): + def test_const_string(self): + # These imports are incompatible with CUDASIM + from numba.cuda.descriptor import cuda_target + from numba.cuda.cudadrv.nvvm import compile_ir + + targetctx = cuda_target.target_context + mod = targetctx.create_module("") + textstring = 'A Little Brown Fox' + gv0 = targetctx.insert_const_string(mod, textstring) + # Insert the same const string a second time - the first should be + # reused. + targetctx.insert_const_string(mod, textstring) + + res = re.findall(r"@\"__conststring__.*internal.*constant.*\[" + r"19\s+x\s+i8\]", str(mod)) + # Ensure that the const string was only inserted once + self.assertEqual(len(res), 1) + + fnty = ir.FunctionType(ir.IntType(8).as_pointer(), []) + + # Using insert_const_string + fn = ir.Function(mod, fnty, "test_insert_const_string") + builder = ir.IRBuilder(fn.append_basic_block()) + res = builder.addrspacecast(gv0, ir.PointerType(ir.IntType(8)), + 'generic') + builder.ret(res) + + matches = re.findall(r"@\"__conststring__.*internal.*constant.*\[" + r"19\s+x\s+i8\]", str(mod)) + self.assertEqual(len(matches), 1) + + # Using insert_string_const_addrspace + fn = ir.Function(mod, fnty, "test_insert_string_const_addrspace") + builder = ir.IRBuilder(fn.append_basic_block()) + res = targetctx.insert_string_const_addrspace(builder, textstring) + builder.ret(res) + + matches = re.findall(r"@\"__conststring__.*internal.*constant.*\[" + r"19\s+x\s+i8\]", str(mod)) + self.assertEqual(len(matches), 1) + + ptx = compile_ir(str(mod)).decode('ascii') + matches = list(re.findall(r"\.const.*__conststring__", ptx)) + + self.assertEqual(len(matches), 1) + + +# Inspired by the reproducer from Issue #7041. +class TestConstString(CUDATestCase): + def test_assign_const_unicode_string(self): + @cuda.jit + def str_assign(arr): + i = cuda.grid(1) + if i < len(arr): + arr[i] = "XYZ" + + n_strings = 8 + arr = np.zeros(n_strings + 1, dtype=" +#include + +#include +#include +#include +#include +#include +#include + +/** + * Note [Generator] + * ~~~~~~~~~~~~~~~~ + * A Pseudo Random Number Generator (PRNG) is an engine that uses an algorithm + * to generate a seemingly random sequence of numbers, that may be later be used + * in creating a random distribution. Such an engine almost always maintains a + * state and requires a seed to start off the creation of random numbers. Often + * times, users have found it beneficial to be able to explicitly create, + * retain, and destroy PRNG states and also be able to have control over the + * seed value. + * + * A Generator in ATen gives users the ability to read, write and modify a PRNG + * engine. For instance, it does so by letting users seed a PRNG engine, fork + * the state of the engine, etc. + * + * By default, there is one generator per device, and a device's generator is + * lazily created. A user can use the torch.Generator() api to create their own + * generator. Currently torch.Generator() can only create a CPUGeneratorImpl. + */ + +/** + * Note [Acquire lock when using random generators] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Generator and its derived classes are NOT thread-safe. Please note that most + * of the places where we have inserted locking for generators are historically + * based, and we haven't actually checked that everything is truly thread safe + * (and it probably isn't). Please use the public mutex_ when using any methods + * from these classes, except for the read-only methods. You can learn about the + * usage by looking into the unittests (aten/src/ATen/cpu_generator_test.cpp) + * and other places where we have used lock_guard. + * + * TODO: Look into changing the threading semantics of Generators in ATen (e.g., + * making them non-thread safe and instead making the generator state + * splittable, to accommodate forks into other threads). + */ + +namespace c10 { + +// The default seed is selected to be a large number +// with good distribution of 0s and 1s in bit representation +constexpr uint64_t default_rng_seed_val = 67280421310721; + +struct C10_API GeneratorImpl : public c10::intrusive_ptr_target { + // Constructors + GeneratorImpl(Device device_in, DispatchKeySet key_set); + + // Delete all copy and move assignment in favor of clone() + // method + GeneratorImpl(const GeneratorImpl& other) = delete; + GeneratorImpl(GeneratorImpl&& other) = delete; + GeneratorImpl& operator=(const GeneratorImpl& other) = delete; + + ~GeneratorImpl() override = default; + c10::intrusive_ptr clone() const; + + // Common methods for all generators + virtual void set_current_seed(uint64_t seed) = 0; + virtual void set_offset(uint64_t offset) = 0; + virtual uint64_t get_offset() const = 0; + virtual uint64_t current_seed() const = 0; + virtual uint64_t seed() = 0; + virtual void set_state(const c10::TensorImpl& new_state) = 0; + virtual c10::intrusive_ptr get_state() const = 0; + Device device() const; + + // See Note [Acquire lock when using random generators] + std::mutex mutex_; + + DispatchKeySet key_set() const { + return key_set_; + } + + inline void set_pyobj(PyObject* pyobj) noexcept { + pyobj_ = pyobj; + } + + inline PyObject* pyobj() const noexcept { + return pyobj_; + } + + protected: + Device device_; + DispatchKeySet key_set_; + PyObject* pyobj_ = nullptr; + + virtual GeneratorImpl* clone_impl() const = 0; +}; + +namespace detail { + +C10_API uint64_t getNonDeterministicRandom(bool is_cuda = false); + +} // namespace detail + +} // namespace c10 diff --git a/shared/package-files/7a/7ac5fc35bc422a5445603e0430236e62cca3558787811de22305f72d439eb4bb/blob b/shared/package-files/7a/7ac5fc35bc422a5445603e0430236e62cca3558787811de22305f72d439eb4bb/blob new file mode 100644 index 0000000000000000000000000000000000000000..7a652fa41532077db2525999d8ec16d3b858896a --- /dev/null +++ b/shared/package-files/7a/7ac5fc35bc422a5445603e0430236e62cca3558787811de22305f72d439eb4bb/blob @@ -0,0 +1,6 @@ +# created by tools/loadICU.tcl -- do not edit +namespace eval ::tcl::clock { + ::msgcat::mcset es_CR DATE_FORMAT "%d/%m/%Y" + ::msgcat::mcset es_CR TIME_FORMAT_12 "%I:%M:%S %P" + ::msgcat::mcset es_CR DATE_TIME_FORMAT "%d/%m/%Y %I:%M:%S %P %z" +} diff --git a/shared/package-files/7a/7ac64431d296479464490138b0268350c84162f30b384f83a002a35c53c56a14/blob b/shared/package-files/7a/7ac64431d296479464490138b0268350c84162f30b384f83a002a35c53c56a14/blob new file mode 100644 index 0000000000000000000000000000000000000000..db0b7c2ddb11756d2a0d9a2454fe45505b035737 --- /dev/null +++ b/shared/package-files/7a/7ac64431d296479464490138b0268350c84162f30b384f83a002a35c53c56a14/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API ::std::tuple _choose_qparams_per_tensor(const at::Tensor & self, bool reduce_range=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/7a/7aca8dc657d9b00d4abc9d4ed974016d3f78ec44c123dcf141b15f9b26340fb4/blob b/shared/package-files/7a/7aca8dc657d9b00d4abc9d4ed974016d3f78ec44c123dcf141b15f9b26340fb4/blob new file mode 100644 index 0000000000000000000000000000000000000000..1f4c90e3063b8855836d18776a514be2cd99f738 --- /dev/null +++ b/shared/package-files/7a/7aca8dc657d9b00d4abc9d4ed974016d3f78ec44c123dcf141b15f9b26340fb4/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_amin_out : public at::meta::structured_amin { +void impl(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/7a/7acccf1abdd70bd26cee6414074805c65acd8d0c1fb9c405cff53017234b8deb/blob b/shared/package-files/7a/7acccf1abdd70bd26cee6414074805c65acd8d0c1fb9c405cff53017234b8deb/blob new file mode 100644 index 0000000000000000000000000000000000000000..2c426462bd34e00f9a0b04e01fb124784c2afb7b --- /dev/null +++ b/shared/package-files/7a/7acccf1abdd70bd26cee6414074805c65acd8d0c1fb9c405cff53017234b8deb/blob @@ -0,0 +1,30 @@ +#if defined(DETECT_FEATURES) && defined(__INTEL_COMPILER) + /* + * Unlike GCC and CLANG, Intel Compiler exposes all supported intrinsics, + * whether or not the build options for those features are specified. + * Therefore, we must test #definitions of CPU features when option native/host + * is enabled via `--cpu-baseline` or through env var `CFLAGS` otherwise + * the test will be broken and leads to enable all possible features. + */ + #if !defined(__AVX5124FMAPS__) || !defined(__AVX5124VNNIW__) || !defined(__AVX512VPOPCNTDQ__) + #error "HOST/ARCH doesn't support Knights Mill AVX512 features" + #endif +#endif + +#include + +int main(int argc, char **argv) +{ + __m512i a = _mm512_loadu_si512((const __m512i*)argv[argc-1]); + __m512 b = _mm512_loadu_ps((const __m512*)argv[argc-2]); + + /* 4FMAPS */ + b = _mm512_4fmadd_ps(b, b, b, b, b, NULL); + /* 4VNNIW */ + a = _mm512_4dpwssd_epi32(a, a, a, a, a, NULL); + /* VPOPCNTDQ */ + a = _mm512_popcnt_epi64(a); + + a = _mm512_add_epi32(a, _mm512_castps_si512(b)); + return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); +} diff --git a/shared/package-files/7a/7acd1c09eccab29ceb890fb757cf21df2273c73d36f1eb95dac53033ad6413ea/blob b/shared/package-files/7a/7acd1c09eccab29ceb890fb757cf21df2273c73d36f1eb95dac53033ad6413ea/blob new file mode 100644 index 0000000000000000000000000000000000000000..33c613b749a49d6035c0e549389e92c3d68a83ad --- /dev/null +++ b/shared/package-files/7a/7acd1c09eccab29ceb890fb757cf21df2273c73d36f1eb95dac53033ad6413ea/blob @@ -0,0 +1,141 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import re +from typing import FrozenSet, NewType, Tuple, Union, cast + +from .tags import Tag, parse_tag +from .version import InvalidVersion, Version + +BuildTag = Union[Tuple[()], Tuple[int, str]] +NormalizedName = NewType("NormalizedName", str) + + +class InvalidWheelFilename(ValueError): + """ + An invalid wheel filename was found, users should refer to PEP 427. + """ + + +class InvalidSdistFilename(ValueError): + """ + An invalid sdist filename was found, users should refer to the packaging user guide. + """ + + +_canonicalize_regex = re.compile(r"[-_.]+") +# PEP 427: The build number must start with a digit. +_build_tag_regex = re.compile(r"(\d+)(.*)") + + +def canonicalize_name(name: str) -> NormalizedName: + # This is taken from PEP 503. + value = _canonicalize_regex.sub("-", name).lower() + return cast(NormalizedName, value) + + +def canonicalize_version( + version: Union[Version, str], *, strip_trailing_zero: bool = True +) -> str: + """ + This is very similar to Version.__str__, but has one subtle difference + with the way it handles the release segment. + """ + if isinstance(version, str): + try: + parsed = Version(version) + except InvalidVersion: + # Legacy versions cannot be normalized + return version + else: + parsed = version + + parts = [] + + # Epoch + if parsed.epoch != 0: + parts.append(f"{parsed.epoch}!") + + # Release segment + release_segment = ".".join(str(x) for x in parsed.release) + if strip_trailing_zero: + # NB: This strips trailing '.0's to normalize + release_segment = re.sub(r"(\.0)+$", "", release_segment) + parts.append(release_segment) + + # Pre-release + if parsed.pre is not None: + parts.append("".join(str(x) for x in parsed.pre)) + + # Post-release + if parsed.post is not None: + parts.append(f".post{parsed.post}") + + # Development release + if parsed.dev is not None: + parts.append(f".dev{parsed.dev}") + + # Local version segment + if parsed.local is not None: + parts.append(f"+{parsed.local}") + + return "".join(parts) + + +def parse_wheel_filename( + filename: str, +) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]: + if not filename.endswith(".whl"): + raise InvalidWheelFilename( + f"Invalid wheel filename (extension must be '.whl'): {filename}" + ) + + filename = filename[:-4] + dashes = filename.count("-") + if dashes not in (4, 5): + raise InvalidWheelFilename( + f"Invalid wheel filename (wrong number of parts): {filename}" + ) + + parts = filename.split("-", dashes - 2) + name_part = parts[0] + # See PEP 427 for the rules on escaping the project name + if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: + raise InvalidWheelFilename(f"Invalid project name: {filename}") + name = canonicalize_name(name_part) + version = Version(parts[1]) + if dashes == 5: + build_part = parts[2] + build_match = _build_tag_regex.match(build_part) + if build_match is None: + raise InvalidWheelFilename( + f"Invalid build number: {build_part} in '{filename}'" + ) + build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2))) + else: + build = () + tags = parse_tag(parts[-1]) + return (name, version, build, tags) + + +def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]: + if filename.endswith(".tar.gz"): + file_stem = filename[: -len(".tar.gz")] + elif filename.endswith(".zip"): + file_stem = filename[: -len(".zip")] + else: + raise InvalidSdistFilename( + f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" + f" {filename}" + ) + + # We are requiring a PEP 440 version, which cannot contain dashes, + # so we split on the last dash. + name_part, sep, version_part = file_stem.rpartition("-") + if not sep: + raise InvalidSdistFilename(f"Invalid sdist filename: {filename}") + + name = canonicalize_name(name_part) + version = Version(version_part) + return (name, version) diff --git a/shared/package-files/7a/7acf0428cbd78f9c93a087d0fa97f70efe539c879e33ab0c1342d6fa7e1e707a/blob b/shared/package-files/7a/7acf0428cbd78f9c93a087d0fa97f70efe539c879e33ab0c1342d6fa7e1e707a/blob new file mode 100644 index 0000000000000000000000000000000000000000..2f7f8cbad05d3955be8fbe68ac8ba6c13ef974e6 --- /dev/null +++ b/shared/package-files/7a/7acf0428cbd78f9c93a087d0fa97f70efe539c879e33ab0c1342d6fa7e1e707a/blob @@ -0,0 +1,17 @@ +""" + pygments.__main__ + ~~~~~~~~~~~~~~~~~ + + Main entry point for ``python -m pygments``. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import sys +from pip._vendor.pygments.cmdline import main + +try: + sys.exit(main(sys.argv)) +except KeyboardInterrupt: + sys.exit(1) diff --git a/shared/package-files/7a/7ad4013d142826b29a3bcd799b5cfe03253fb11cca41521aede2cb562940601d/blob b/shared/package-files/7a/7ad4013d142826b29a3bcd799b5cfe03253fb11cca41521aede2cb562940601d/blob new file mode 100644 index 0000000000000000000000000000000000000000..33e4ea6706cfcc98ce151b45196d43f4aef070ff --- /dev/null +++ b/shared/package-files/7a/7ad4013d142826b29a3bcd799b5cfe03253fb11cca41521aede2cb562940601d/blob @@ -0,0 +1,125 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +import math +from collections import Counter + +from hypothesis._settings import Phase +from hypothesis.utils.dynamicvariables import DynamicVariable + +collector = DynamicVariable(None) + + +def note_statistics(stats_dict): + callback = collector.value + if callback is not None: + callback(stats_dict) + + +def describe_targets(best_targets): + """Return a list of lines describing the results of `target`, if any.""" + # These lines are included in the general statistics description below, + # but also printed immediately below failing examples to alleviate the + # "threshold problem" where shrinking can make severe bug look trivial. + # See https://github.com/HypothesisWorks/hypothesis/issues/2180 + if not best_targets: + return [] + elif len(best_targets) == 1: + label, score = next(iter(best_targets.items())) + return [f"Highest target score: {score:g} ({label=})"] + else: + lines = ["Highest target scores:"] + for label, score in sorted(best_targets.items(), key=lambda x: x[::-1]): + lines.append(f"{score:>16g} ({label=})") + return lines + + +def format_ms(times): + """Format `times` into a string representing approximate milliseconds. + + `times` is a collection of durations in seconds. + """ + ordered = sorted(times) + n = len(ordered) - 1 + assert n >= 0 + lower = int(ordered[int(math.floor(n * 0.05))] * 1000) + upper = int(ordered[int(math.ceil(n * 0.95))] * 1000) + if upper == 0: + return "< 1ms" + elif lower == upper: + return f"~ {lower}ms" + else: + return f"~ {lower}-{upper} ms" + + +def describe_statistics(stats_dict): + """Return a multi-line string describing the passed run statistics. + + `stats_dict` must be a dictionary of data in the format collected by + `hypothesis.internal.conjecture.engine.ConjectureRunner.statistics`. + + We DO NOT promise that this format will be stable or supported over + time, but do aim to make it reasonably useful for downstream users. + It's also meant to support benchmarking for research purposes. + + This function is responsible for the report which is printed in the + terminal for our pytest --hypothesis-show-statistics option. + """ + lines = [stats_dict["nodeid"] + ":\n"] if "nodeid" in stats_dict else [] + prev_failures = 0 + for phase in (p.name for p in list(Phase)[1:]): + d = stats_dict.get(phase + "-phase", {}) + # Basic information we report for every phase + cases = d.get("test-cases", []) + if not cases: + continue + statuses = Counter(t["status"] for t in cases) + runtime_ms = format_ms(t["runtime"] for t in cases) + drawtime_ms = format_ms(t["drawtime"] for t in cases) + lines.append( + f" - during {phase} phase ({d['duration-seconds']:.2f} seconds):\n" + f" - Typical runtimes: {runtime_ms}, of which {drawtime_ms} in data generation\n" + f" - {statuses['valid']} passing examples, {statuses['interesting']} " + f"failing examples, {statuses['invalid'] + statuses['overrun']} invalid examples" + ) + # If we've found new distinct failures in this phase, report them + distinct_failures = d["distinct-failures"] - prev_failures + if distinct_failures: + plural = distinct_failures > 1 + lines.append( + " - Found {}{} distinct error{} in this phase".format( + distinct_failures, " more" * bool(prev_failures), "s" * plural + ) + ) + prev_failures = d["distinct-failures"] + # Report events during the generate phase, if there were any + if phase == "generate": + events = Counter(sum((t["events"] for t in cases), [])) + if events: + lines.append(" - Events:") + lines += [ + f" * {100 * v / len(cases):.2f}%, {k}" + for k, v in sorted(events.items(), key=lambda x: (-x[1], x[0])) + ] + # Some additional details on the shrinking phase + if phase == "shrink": + lines.append( + " - Tried {} shrinks of which {} were successful".format( + len(cases), d["shrinks-successful"] + ) + ) + lines.append("") + + target_lines = describe_targets(stats_dict.get("targets", {})) + if target_lines: + lines.append(" - " + target_lines[0]) + lines.extend(" " + l for l in target_lines[1:]) + lines.append(" - Stopped because " + stats_dict["stopped-because"]) + return "\n".join(lines) diff --git a/shared/package-files/7a/7ad6709bd4713ec24e958368560e08f7ea6bb312967834a9d6f52641d7b4979b/blob b/shared/package-files/7a/7ad6709bd4713ec24e958368560e08f7ea6bb312967834a9d6f52641d7b4979b/blob new file mode 100644 index 0000000000000000000000000000000000000000..1740ead3b914e507198032ca2e8d875abcdf5108 --- /dev/null +++ b/shared/package-files/7a/7ad6709bd4713ec24e958368560e08f7ea6bb312967834a9d6f52641d7b4979b/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ad6709bd4713ec24e958368560e08f7ea6bb312967834a9d6f52641d7b4979b +size 148932 diff --git a/shared/package-files/7a/7ada1069fe7adf3f70a78ec6eb517ac2cbfd5ae20d0f33344a380c76e7d71099/blob b/shared/package-files/7a/7ada1069fe7adf3f70a78ec6eb517ac2cbfd5ae20d0f33344a380c76e7d71099/blob new file mode 100644 index 0000000000000000000000000000000000000000..dc4a8ae5ca09e16d304c70dd601d3136bc473aac Binary files /dev/null and b/shared/package-files/7a/7ada1069fe7adf3f70a78ec6eb517ac2cbfd5ae20d0f33344a380c76e7d71099/blob differ diff --git a/shared/package-files/7a/7ada21f1e41e46dca74d0265beb2f49f55807ffbeddf6ba01230f28466f32a58/blob b/shared/package-files/7a/7ada21f1e41e46dca74d0265beb2f49f55807ffbeddf6ba01230f28466f32a58/blob new file mode 100644 index 0000000000000000000000000000000000000000..3f6622bb048dbd6441b8d181e1012835ecd1f478 --- /dev/null +++ b/shared/package-files/7a/7ada21f1e41e46dca74d0265beb2f49f55807ffbeddf6ba01230f28466f32a58/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor log_normal(const at::Tensor & self, double mean=1, double std=2, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & log_normal_out(at::Tensor & out, const at::Tensor & self, double mean=1, double std=2, c10::optional generator=c10::nullopt); +TORCH_API at::Tensor & log_normal_outf(const at::Tensor & self, double mean, double std, c10::optional generator, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/7a/7adc704059e0c522d1823449f00ccf736f020909b9eb1c7d091969e0c3f0865e/blob b/shared/package-files/7a/7adc704059e0c522d1823449f00ccf736f020909b9eb1c7d091969e0c3f0865e/blob new file mode 100644 index 0000000000000000000000000000000000000000..043b120f163c4009c62d72070c9ecb26c58b04bb --- /dev/null +++ b/shared/package-files/7a/7adc704059e0c522d1823449f00ccf736f020909b9eb1c7d091969e0c3f0865e/blob @@ -0,0 +1,1226 @@ +"""Algorithms for computing symbolic roots of polynomials. """ + + +import math +from functools import reduce + +from sympy.core import S, I, pi +from sympy.core.exprtools import factor_terms +from sympy.core.function import _mexpand +from sympy.core.logic import fuzzy_not +from sympy.core.mul import expand_2arg, Mul +from sympy.core.numbers import Rational, igcd, comp +from sympy.core.power import Pow +from sympy.core.relational import Eq +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, Symbol, symbols +from sympy.core.sympify import sympify +from sympy.functions import exp, im, cos, acos, Piecewise +from sympy.functions.elementary.miscellaneous import root, sqrt +from sympy.ntheory import divisors, isprime, nextprime +from sympy.polys.domains import EX +from sympy.polys.polyerrors import (PolynomialError, GeneratorsNeeded, + DomainError, UnsolvableFactorError) +from sympy.polys.polyquinticconst import PolyQuintic +from sympy.polys.polytools import Poly, cancel, factor, gcd_list, discriminant +from sympy.polys.rationaltools import together +from sympy.polys.specialpolys import cyclotomic_poly +from sympy.utilities import public +from sympy.utilities.misc import filldedent + + + +z = Symbol('z') # importing from abc cause O to be lost as clashing symbol + + +def roots_linear(f): + """Returns a list of roots of a linear polynomial.""" + r = -f.nth(0)/f.nth(1) + dom = f.get_domain() + + if not dom.is_Numerical: + if dom.is_Composite: + r = factor(r) + else: + from sympy.simplify.simplify import simplify + r = simplify(r) + + return [r] + + +def roots_quadratic(f): + """Returns a list of roots of a quadratic polynomial. If the domain is ZZ + then the roots will be sorted with negatives coming before positives. + The ordering will be the same for any numerical coefficients as long as + the assumptions tested are correct, otherwise the ordering will not be + sorted (but will be canonical). + """ + + a, b, c = f.all_coeffs() + dom = f.get_domain() + + def _sqrt(d): + # remove squares from square root since both will be represented + # in the results; a similar thing is happening in roots() but + # must be duplicated here because not all quadratics are binomials + co = [] + other = [] + for di in Mul.make_args(d): + if di.is_Pow and di.exp.is_Integer and di.exp % 2 == 0: + co.append(Pow(di.base, di.exp//2)) + else: + other.append(di) + if co: + d = Mul(*other) + co = Mul(*co) + return co*sqrt(d) + return sqrt(d) + + def _simplify(expr): + if dom.is_Composite: + return factor(expr) + else: + from sympy.simplify.simplify import simplify + return simplify(expr) + + if c is S.Zero: + r0, r1 = S.Zero, -b/a + + if not dom.is_Numerical: + r1 = _simplify(r1) + elif r1.is_negative: + r0, r1 = r1, r0 + elif b is S.Zero: + r = -c/a + if not dom.is_Numerical: + r = _simplify(r) + + R = _sqrt(r) + r0 = -R + r1 = R + else: + d = b**2 - 4*a*c + A = 2*a + B = -b/A + + if not dom.is_Numerical: + d = _simplify(d) + B = _simplify(B) + + D = factor_terms(_sqrt(d)/A) + r0 = B - D + r1 = B + D + if a.is_negative: + r0, r1 = r1, r0 + elif not dom.is_Numerical: + r0, r1 = [expand_2arg(i) for i in (r0, r1)] + + return [r0, r1] + + +def roots_cubic(f, trig=False): + """Returns a list of roots of a cubic polynomial. + + References + ========== + [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots, + (accessed November 17, 2014). + """ + if trig: + a, b, c, d = f.all_coeffs() + p = (3*a*c - b**2)/(3*a**2) + q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) + D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 + if (D > 0) == True: + rv = [] + for k in range(3): + rv.append(2*sqrt(-p/3)*cos(acos(q/p*sqrt(-3/p)*Rational(3, 2))/3 - k*pi*Rational(2, 3))) + return [i - b/3/a for i in rv] + + # a*x**3 + b*x**2 + c*x + d -> x**3 + a*x**2 + b*x + c + _, a, b, c = f.monic().all_coeffs() + + if c is S.Zero: + x1, x2 = roots([1, a, b], multiple=True) + return [x1, S.Zero, x2] + + # x**3 + a*x**2 + b*x + c -> u**3 + p*u + q + p = b - a**2/3 + q = c - a*b/3 + 2*a**3/27 + + pon3 = p/3 + aon3 = a/3 + + u1 = None + if p is S.Zero: + if q is S.Zero: + return [-aon3]*3 + u1 = -root(q, 3) if q.is_positive else root(-q, 3) + elif q is S.Zero: + y1, y2 = roots([1, 0, p], multiple=True) + return [tmp - aon3 for tmp in [y1, S.Zero, y2]] + elif q.is_real and q.is_negative: + u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) + + coeff = I*sqrt(3)/2 + if u1 is None: + u1 = S.One + u2 = Rational(-1, 2) + coeff + u3 = Rational(-1, 2) - coeff + b, c, d = a, b, c # a, b, c, d = S.One, a, b, c + D0 = b**2 - 3*c # b**2 - 3*a*c + D1 = 2*b**3 - 9*b*c + 27*d # 2*b**3 - 9*a*b*c + 27*a**2*d + C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3) + return [-(b + uk*C + D0/C/uk)/3 for uk in [u1, u2, u3]] # -(b + uk*C + D0/C/uk)/3/a + + u2 = u1*(Rational(-1, 2) + coeff) + u3 = u1*(Rational(-1, 2) - coeff) + + if p is S.Zero: + return [u1 - aon3, u2 - aon3, u3 - aon3] + + soln = [ + -u1 + pon3/u1 - aon3, + -u2 + pon3/u2 - aon3, + -u3 + pon3/u3 - aon3 + ] + + return soln + +def _roots_quartic_euler(p, q, r, a): + """ + Descartes-Euler solution of the quartic equation + + Parameters + ========== + + p, q, r: coefficients of ``x**4 + p*x**2 + q*x + r`` + a: shift of the roots + + Notes + ===== + + This is a helper function for ``roots_quartic``. + + Look for solutions of the form :: + + ``x1 = sqrt(R) - sqrt(A + B*sqrt(R))`` + ``x2 = -sqrt(R) - sqrt(A - B*sqrt(R))`` + ``x3 = -sqrt(R) + sqrt(A - B*sqrt(R))`` + ``x4 = sqrt(R) + sqrt(A + B*sqrt(R))`` + + To satisfy the quartic equation one must have + ``p = -2*(R + A); q = -4*B*R; r = (R - A)**2 - B**2*R`` + so that ``R`` must satisfy the Descartes-Euler resolvent equation + ``64*R**3 + 32*p*R**2 + (4*p**2 - 16*r)*R - q**2 = 0`` + + If the resolvent does not have a rational solution, return None; + in that case it is likely that the Ferrari method gives a simpler + solution. + + Examples + ======== + + >>> from sympy import S + >>> from sympy.polys.polyroots import _roots_quartic_euler + >>> p, q, r = -S(64)/5, -S(512)/125, -S(1024)/3125 + >>> _roots_quartic_euler(p, q, r, S(0))[0] + -sqrt(32*sqrt(5)/125 + 16/5) + 4*sqrt(5)/5 + """ + # solve the resolvent equation + x = Dummy('x') + eq = 64*x**3 + 32*p*x**2 + (4*p**2 - 16*r)*x - q**2 + xsols = list(roots(Poly(eq, x), cubics=False).keys()) + xsols = [sol for sol in xsols if sol.is_rational and sol.is_nonzero] + if not xsols: + return None + R = max(xsols) + c1 = sqrt(R) + B = -q*c1/(4*R) + A = -R - p/2 + c2 = sqrt(A + B) + c3 = sqrt(A - B) + return [c1 - c2 - a, -c1 - c3 - a, -c1 + c3 - a, c1 + c2 - a] + + +def roots_quartic(f): + r""" + Returns a list of roots of a quartic polynomial. + + There are many references for solving quartic expressions available [1-5]. + This reviewer has found that many of them require one to select from among + 2 or more possible sets of solutions and that some solutions work when one + is searching for real roots but do not work when searching for complex roots + (though this is not always stated clearly). The following routine has been + tested and found to be correct for 0, 2 or 4 complex roots. + + The quasisymmetric case solution [6] looks for quartics that have the form + `x**4 + A*x**3 + B*x**2 + C*x + D = 0` where `(C/A)**2 = D`. + + Although no general solution that is always applicable for all + coefficients is known to this reviewer, certain conditions are tested + to determine the simplest 4 expressions that can be returned: + + 1) `f = c + a*(a**2/8 - b/2) == 0` + 2) `g = d - a*(a*(3*a**2/256 - b/16) + c/4) = 0` + 3) if `f != 0` and `g != 0` and `p = -d + a*c/4 - b**2/12` then + a) `p == 0` + b) `p != 0` + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.polys.polyroots import roots_quartic + + >>> r = roots_quartic(Poly('x**4-6*x**3+17*x**2-26*x+20')) + + >>> # 4 complex roots: 1+-I*sqrt(3), 2+-I + >>> sorted(str(tmp.evalf(n=2)) for tmp in r) + ['1.0 + 1.7*I', '1.0 - 1.7*I', '2.0 + 1.0*I', '2.0 - 1.0*I'] + + References + ========== + + 1. http://mathforum.org/dr.math/faq/faq.cubic.equations.html + 2. https://en.wikipedia.org/wiki/Quartic_function#Summary_of_Ferrari.27s_method + 3. https://planetmath.org/encyclopedia/GaloisTheoreticDerivationOfTheQuarticFormula.html + 4. https://people.bath.ac.uk/masjhd/JHD-CA.pdf + 5. http://www.albmath.org/files/Math_5713.pdf + 6. https://web.archive.org/web/20171002081448/http://www.statemaster.com/encyclopedia/Quartic-equation + 7. https://eqworld.ipmnet.ru/en/solutions/ae/ae0108.pdf + """ + _, a, b, c, d = f.monic().all_coeffs() + + if not d: + return [S.Zero] + roots([1, a, b, c], multiple=True) + elif (c/a)**2 == d: + x, m = f.gen, c/a + + g = Poly(x**2 + a*x + b - 2*m, x) + + z1, z2 = roots_quadratic(g) + + h1 = Poly(x**2 - z1*x + m, x) + h2 = Poly(x**2 - z2*x + m, x) + + r1 = roots_quadratic(h1) + r2 = roots_quadratic(h2) + + return r1 + r2 + else: + a2 = a**2 + e = b - 3*a2/8 + f = _mexpand(c + a*(a2/8 - b/2)) + aon4 = a/4 + g = _mexpand(d - aon4*(a*(3*a2/64 - b/4) + c)) + + if f.is_zero: + y1, y2 = [sqrt(tmp) for tmp in + roots([1, e, g], multiple=True)] + return [tmp - aon4 for tmp in [-y1, -y2, y1, y2]] + if g.is_zero: + y = [S.Zero] + roots([1, 0, e, f], multiple=True) + return [tmp - aon4 for tmp in y] + else: + # Descartes-Euler method, see [7] + sols = _roots_quartic_euler(e, f, g, aon4) + if sols: + return sols + # Ferrari method, see [1, 2] + p = -e**2/12 - g + q = -e**3/108 + e*g/3 - f**2/8 + TH = Rational(1, 3) + + def _ans(y): + w = sqrt(e + 2*y) + arg1 = 3*e + 2*y + arg2 = 2*f/w + ans = [] + for s in [-1, 1]: + root = sqrt(-(arg1 + s*arg2)) + for t in [-1, 1]: + ans.append((s*w - t*root)/2 - aon4) + return ans + + # whether a Piecewise is returned or not + # depends on knowing p, so try to put + # in a simple form + p = _mexpand(p) + + + # p == 0 case + y1 = e*Rational(-5, 6) - q**TH + if p.is_zero: + return _ans(y1) + + # if p != 0 then u below is not 0 + root = sqrt(q**2/4 + p**3/27) + r = -q/2 + root # or -q/2 - root + u = r**TH # primary root of solve(x**3 - r, x) + y2 = e*Rational(-5, 6) + u - p/u/3 + if fuzzy_not(p.is_zero): + return _ans(y2) + + # sort it out once they know the values of the coefficients + return [Piecewise((a1, Eq(p, 0)), (a2, True)) + for a1, a2 in zip(_ans(y1), _ans(y2))] + + +def roots_binomial(f): + """Returns a list of roots of a binomial polynomial. If the domain is ZZ + then the roots will be sorted with negatives coming before positives. + The ordering will be the same for any numerical coefficients as long as + the assumptions tested are correct, otherwise the ordering will not be + sorted (but will be canonical). + """ + n = f.degree() + + a, b = f.nth(n), f.nth(0) + base = -cancel(b/a) + alpha = root(base, n) + + if alpha.is_number: + alpha = alpha.expand(complex=True) + + # define some parameters that will allow us to order the roots. + # If the domain is ZZ this is guaranteed to return roots sorted + # with reals before non-real roots and non-real sorted according + # to real part and imaginary part, e.g. -1, 1, -1 + I, 2 - I + neg = base.is_negative + even = n % 2 == 0 + if neg: + if even == True and (base + 1).is_positive: + big = True + else: + big = False + + # get the indices in the right order so the computed + # roots will be sorted when the domain is ZZ + ks = [] + imax = n//2 + if even: + ks.append(imax) + imax -= 1 + if not neg: + ks.append(0) + for i in range(imax, 0, -1): + if neg: + ks.extend([i, -i]) + else: + ks.extend([-i, i]) + if neg: + ks.append(0) + if big: + for i in range(0, len(ks), 2): + pair = ks[i: i + 2] + pair = list(reversed(pair)) + + # compute the roots + roots, d = [], 2*I*pi/n + for k in ks: + zeta = exp(k*d).expand(complex=True) + roots.append((alpha*zeta).expand(power_base=False)) + + return roots + + +def _inv_totient_estimate(m): + """ + Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``. + + Examples + ======== + + >>> from sympy.polys.polyroots import _inv_totient_estimate + + >>> _inv_totient_estimate(192) + (192, 840) + >>> _inv_totient_estimate(400) + (400, 1750) + + """ + primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ] + + a, b = 1, 1 + + for p in primes: + a *= p + b *= p - 1 + + L = m + U = int(math.ceil(m*(float(a)/b))) + + P = p = 2 + primes = [] + + while P <= U: + p = nextprime(p) + primes.append(p) + P *= p + + P //= p + b = 1 + + for p in primes[:-1]: + b *= p - 1 + + U = int(math.ceil(m*(float(P)/b))) + + return L, U + + +def roots_cyclotomic(f, factor=False): + """Compute roots of cyclotomic polynomials. """ + L, U = _inv_totient_estimate(f.degree()) + + for n in range(L, U + 1): + g = cyclotomic_poly(n, f.gen, polys=True) + + if f.expr == g.expr: + break + else: # pragma: no cover + raise RuntimeError("failed to find index of a cyclotomic polynomial") + + roots = [] + + if not factor: + # get the indices in the right order so the computed + # roots will be sorted + h = n//2 + ks = [i for i in range(1, n + 1) if igcd(i, n) == 1] + ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1)) + d = 2*I*pi/n + for k in reversed(ks): + roots.append(exp(k*d).expand(complex=True)) + else: + g = Poly(f, extension=root(-1, n)) + + for h, _ in ordered(g.factor_list()[1]): + roots.append(-h.TC()) + + return roots + + +def roots_quintic(f): + """ + Calculate exact roots of a solvable irreducible quintic with rational coefficients. + Return an empty list if the quintic is reducible or not solvable. + """ + result = [] + + coeff_5, coeff_4, p_, q_, r_, s_ = f.all_coeffs() + + if not all(coeff.is_Rational for coeff in (coeff_5, coeff_4, p_, q_, r_, s_)): + return result + + if coeff_5 != 1: + f = Poly(f / coeff_5) + _, coeff_4, p_, q_, r_, s_ = f.all_coeffs() + + # Cancel coeff_4 to form x^5 + px^3 + qx^2 + rx + s + if coeff_4: + p = p_ - 2*coeff_4*coeff_4/5 + q = q_ - 3*coeff_4*p_/5 + 4*coeff_4**3/25 + r = r_ - 2*coeff_4*q_/5 + 3*coeff_4**2*p_/25 - 3*coeff_4**4/125 + s = s_ - coeff_4*r_/5 + coeff_4**2*q_/25 - coeff_4**3*p_/125 + 4*coeff_4**5/3125 + x = f.gen + f = Poly(x**5 + p*x**3 + q*x**2 + r*x + s) + else: + p, q, r, s = p_, q_, r_, s_ + + quintic = PolyQuintic(f) + + # Eqn standardized. Algo for solving starts here + if not f.is_irreducible: + return result + f20 = quintic.f20 + # Check if f20 has linear factors over domain Z + if f20.is_irreducible: + return result + # Now, we know that f is solvable + for _factor in f20.factor_list()[1]: + if _factor[0].is_linear: + theta = _factor[0].root(0) + break + d = discriminant(f) + delta = sqrt(d) + # zeta = a fifth root of unity + zeta1, zeta2, zeta3, zeta4 = quintic.zeta + T = quintic.T(theta, d) + tol = S(1e-10) + alpha = T[1] + T[2]*delta + alpha_bar = T[1] - T[2]*delta + beta = T[3] + T[4]*delta + beta_bar = T[3] - T[4]*delta + + disc = alpha**2 - 4*beta + disc_bar = alpha_bar**2 - 4*beta_bar + + l0 = quintic.l0(theta) + Stwo = S(2) + l1 = _quintic_simplify((-alpha + sqrt(disc)) / Stwo) + l4 = _quintic_simplify((-alpha - sqrt(disc)) / Stwo) + + l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / Stwo) + l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / Stwo) + + order = quintic.order(theta, d) + test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) ) + # Comparing floats + if not comp(test, 0, tol): + l2, l3 = l3, l2 + + # Now we have correct order of l's + R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4 + R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4 + R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4 + R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4 + + Res = [None, [None]*5, [None]*5, [None]*5, [None]*5] + Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5] + + # Simplifying improves performance a lot for exact expressions + R1 = _quintic_simplify(R1) + R2 = _quintic_simplify(R2) + R3 = _quintic_simplify(R3) + R4 = _quintic_simplify(R4) + + # hard-coded results for [factor(i) for i in _vsolve(x**5 - a - I*b, x)] + x0 = z**(S(1)/5) + x1 = sqrt(2) + x2 = sqrt(5) + x3 = sqrt(5 - x2) + x4 = I*x2 + x5 = x4 + I + x6 = I*x0/4 + x7 = x1*sqrt(x2 + 5) + sol = [x0, -x6*(x1*x3 - x5), x6*(x1*x3 + x5), -x6*(x4 + x7 - I), x6*(-x4 + x7 + I)] + + R1 = R1.as_real_imag() + R2 = R2.as_real_imag() + R3 = R3.as_real_imag() + R4 = R4.as_real_imag() + + for i, s in enumerate(sol): + Res[1][i] = _quintic_simplify(s.xreplace({z: R1[0] + I*R1[1]})) + Res[2][i] = _quintic_simplify(s.xreplace({z: R2[0] + I*R2[1]})) + Res[3][i] = _quintic_simplify(s.xreplace({z: R3[0] + I*R3[1]})) + Res[4][i] = _quintic_simplify(s.xreplace({z: R4[0] + I*R4[1]})) + + for i in range(1, 5): + for j in range(5): + Res_n[i][j] = Res[i][j].n() + Res[i][j] = _quintic_simplify(Res[i][j]) + r1 = Res[1][0] + r1_n = Res_n[1][0] + + for i in range(5): + if comp(im(r1_n*Res_n[4][i]), 0, tol): + r4 = Res[4][i] + break + + # Now we have various Res values. Each will be a list of five + # values. We have to pick one r value from those five for each Res + u, v = quintic.uv(theta, d) + testplus = (u + v*delta*sqrt(5)).n() + testminus = (u - v*delta*sqrt(5)).n() + + # Evaluated numbers suffixed with _n + # We will use evaluated numbers for calculation. Much faster. + r4_n = r4.n() + r2 = r3 = None + + for i in range(5): + r2temp_n = Res_n[2][i] + for j in range(5): + # Again storing away the exact number and using + # evaluated numbers in computations + r3temp_n = Res_n[3][j] + if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and + comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)): + r2 = Res[2][i] + r3 = Res[3][j] + break + if r2 is not None: + break + else: + return [] # fall back to normal solve + + # Now, we have r's so we can get roots + x1 = (r1 + r2 + r3 + r4)/5 + x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5 + x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5 + x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5 + x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5 + result = [x1, x2, x3, x4, x5] + + # Now check if solutions are distinct + + saw = set() + for r in result: + r = r.n(2) + if r in saw: + # Roots were identical. Abort, return [] + # and fall back to usual solve + return [] + saw.add(r) + + # Restore to original equation where coeff_4 is nonzero + if coeff_4: + result = [x - coeff_4 / 5 for x in result] + return result + + +def _quintic_simplify(expr): + from sympy.simplify.simplify import powsimp + expr = powsimp(expr) + expr = cancel(expr) + return together(expr) + + +def _integer_basis(poly): + """Compute coefficient basis for a polynomial over integers. + + Returns the integer ``div`` such that substituting ``x = div*y`` + ``p(x) = m*q(y)`` where the coefficients of ``q`` are smaller + than those of ``p``. + + For example ``x**5 + 512*x + 1024 = 0`` + with ``div = 4`` becomes ``y**5 + 2*y + 1 = 0`` + + Returns the integer ``div`` or ``None`` if there is no possible scaling. + + Examples + ======== + + >>> from sympy.polys import Poly + >>> from sympy.abc import x + >>> from sympy.polys.polyroots import _integer_basis + >>> p = Poly(x**5 + 512*x + 1024, x, domain='ZZ') + >>> _integer_basis(p) + 4 + """ + monoms, coeffs = list(zip(*poly.terms())) + + monoms, = list(zip(*monoms)) + coeffs = list(map(abs, coeffs)) + + if coeffs[0] < coeffs[-1]: + coeffs = list(reversed(coeffs)) + n = monoms[0] + monoms = [n - i for i in reversed(monoms)] + else: + return None + + monoms = monoms[:-1] + coeffs = coeffs[:-1] + + # Special case for two-term polynominals + if len(monoms) == 1: + r = Pow(coeffs[0], S.One/monoms[0]) + if r.is_Integer: + return int(r) + else: + return None + + divs = reversed(divisors(gcd_list(coeffs))[1:]) + + try: + div = next(divs) + except StopIteration: + return None + + while True: + for monom, coeff in zip(monoms, coeffs): + if coeff % div**monom != 0: + try: + div = next(divs) + except StopIteration: + return None + else: + break + else: + return div + + +def preprocess_roots(poly): + """Try to get rid of symbolic coefficients from ``poly``. """ + coeff = S.One + + poly_func = poly.func + try: + _, poly = poly.clear_denoms(convert=True) + except DomainError: + return coeff, poly + + poly = poly.primitive()[1] + poly = poly.retract() + + # TODO: This is fragile. Figure out how to make this independent of construct_domain(). + if poly.get_domain().is_Poly and all(c.is_term for c in poly.rep.coeffs()): + poly = poly.inject() + + strips = list(zip(*poly.monoms())) + gens = list(poly.gens[1:]) + + base, strips = strips[0], strips[1:] + + for gen, strip in zip(list(gens), strips): + reverse = False + + if strip[0] < strip[-1]: + strip = reversed(strip) + reverse = True + + ratio = None + + for a, b in zip(base, strip): + if not a and not b: + continue + elif not a or not b: + break + elif b % a != 0: + break + else: + _ratio = b // a + + if ratio is None: + ratio = _ratio + elif ratio != _ratio: + break + else: + if reverse: + ratio = -ratio + + poly = poly.eval(gen, 1) + coeff *= gen**(-ratio) + gens.remove(gen) + + if gens: + poly = poly.eject(*gens) + + if poly.is_univariate and poly.get_domain().is_ZZ: + basis = _integer_basis(poly) + + if basis is not None: + n = poly.degree() + + def func(k, coeff): + return coeff//basis**(n - k[0]) + + poly = poly.termwise(func) + coeff *= basis + + if not isinstance(poly, poly_func): + poly = poly_func(poly) + return coeff, poly + + +@public +def roots(f, *gens, + auto=True, + cubics=True, + trig=False, + quartics=True, + quintics=False, + multiple=False, + filter=None, + predicate=None, + strict=False, + **flags): + """ + Computes symbolic roots of a univariate polynomial. + + Given a univariate polynomial f with symbolic coefficients (or + a list of the polynomial's coefficients), returns a dictionary + with its roots and their multiplicities. + + Only roots expressible via radicals will be returned. To get + a complete set of roots use RootOf class or numerical methods + instead. By default cubic and quartic formulas are used in + the algorithm. To disable them because of unreadable output + set ``cubics=False`` or ``quartics=False`` respectively. If cubic + roots are real but are expressed in terms of complex numbers + (casus irreducibilis [1]) the ``trig`` flag can be set to True to + have the solutions returned in terms of cosine and inverse cosine + functions. + + To get roots from a specific domain set the ``filter`` flag with + one of the following specifiers: Z, Q, R, I, C. By default all + roots are returned (this is equivalent to setting ``filter='C'``). + + By default a dictionary is returned giving a compact result in + case of multiple roots. However to get a list containing all + those roots set the ``multiple`` flag to True; the list will + have identical roots appearing next to each other in the result. + (For a given Poly, the all_roots method will give the roots in + sorted numerical order.) + + If the ``strict`` flag is True, ``UnsolvableFactorError`` will be + raised if the roots found are known to be incomplete (because + some roots are not expressible in radicals). + + Examples + ======== + + >>> from sympy import Poly, roots, degree + >>> from sympy.abc import x, y + + >>> roots(x**2 - 1, x) + {-1: 1, 1: 1} + + >>> p = Poly(x**2-1, x) + >>> roots(p) + {-1: 1, 1: 1} + + >>> p = Poly(x**2-y, x, y) + + >>> roots(Poly(p, x)) + {-sqrt(y): 1, sqrt(y): 1} + + >>> roots(x**2 - y, x) + {-sqrt(y): 1, sqrt(y): 1} + + >>> roots([1, 0, -1]) + {-1: 1, 1: 1} + + ``roots`` will only return roots expressible in radicals. If + the given polynomial has some or all of its roots inexpressible in + radicals, the result of ``roots`` will be incomplete or empty + respectively. + + Example where result is incomplete: + + >>> roots((x-1)*(x**5-x+1), x) + {1: 1} + + In this case, the polynomial has an unsolvable quintic factor + whose roots cannot be expressed by radicals. The polynomial has a + rational root (due to the factor `(x-1)`), which is returned since + ``roots`` always finds all rational roots. + + Example where result is empty: + + >>> roots(x**7-3*x**2+1, x) + {} + + Here, the polynomial has no roots expressible in radicals, so + ``roots`` returns an empty dictionary. + + The result produced by ``roots`` is complete if and only if the + sum of the multiplicity of each root is equal to the degree of + the polynomial. If strict=True, UnsolvableFactorError will be + raised if the result is incomplete. + + The result can be be checked for completeness as follows: + + >>> f = x**3-2*x**2+1 + >>> sum(roots(f, x).values()) == degree(f, x) + True + >>> f = (x-1)*(x**5-x+1) + >>> sum(roots(f, x).values()) == degree(f, x) + False + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Cubic_equation#Trigonometric_and_hyperbolic_solutions + + """ + from sympy.polys.polytools import to_rational_coeffs + flags = dict(flags) + + if isinstance(f, list): + if gens: + raise ValueError('redundant generators given') + + x = Dummy('x') + + poly, i = {}, len(f) - 1 + + for coeff in f: + poly[i], i = sympify(coeff), i - 1 + + f = Poly(poly, x, field=True) + else: + try: + F = Poly(f, *gens, **flags) + if not isinstance(f, Poly) and not F.gen.is_Symbol: + raise PolynomialError("generator must be a Symbol") + f = F + except GeneratorsNeeded: + if multiple: + return [] + else: + return {} + else: + n = f.degree() + if f.length() == 2 and n > 2: + # check for foo**n in constant if dep is c*gen**m + con, dep = f.as_expr().as_independent(*f.gens) + fcon = -(-con).factor() + if fcon != con: + con = fcon + bases = [] + for i in Mul.make_args(con): + if i.is_Pow: + b, e = i.as_base_exp() + if e.is_Integer and b.is_Add: + bases.append((b, Dummy(positive=True))) + if bases: + rv = roots(Poly((dep + con).xreplace(dict(bases)), + *f.gens), *F.gens, + auto=auto, + cubics=cubics, + trig=trig, + quartics=quartics, + quintics=quintics, + multiple=multiple, + filter=filter, + predicate=predicate, + **flags) + return {factor_terms(k.xreplace( + {v: k for k, v in bases}) + ): v for k, v in rv.items()} + + if f.is_multivariate: + raise PolynomialError('multivariate polynomials are not supported') + + def _update_dict(result, zeros, currentroot, k): + if currentroot == S.Zero: + if S.Zero in zeros: + zeros[S.Zero] += k + else: + zeros[S.Zero] = k + if currentroot in result: + result[currentroot] += k + else: + result[currentroot] = k + + def _try_decompose(f): + """Find roots using functional decomposition. """ + factors, roots = f.decompose(), [] + + for currentroot in _try_heuristics(factors[0]): + roots.append(currentroot) + + for currentfactor in factors[1:]: + previous, roots = list(roots), [] + + for currentroot in previous: + g = currentfactor - Poly(currentroot, f.gen) + + for currentroot in _try_heuristics(g): + roots.append(currentroot) + + return roots + + def _try_heuristics(f): + """Find roots using formulas and some tricks. """ + if f.is_ground: + return [] + if f.is_monomial: + return [S.Zero]*f.degree() + + if f.length() == 2: + if f.degree() == 1: + return list(map(cancel, roots_linear(f))) + else: + return roots_binomial(f) + + result = [] + + for i in [-1, 1]: + if not f.eval(i): + f = f.quo(Poly(f.gen - i, f.gen)) + result.append(i) + break + + n = f.degree() + + if n == 1: + result += list(map(cancel, roots_linear(f))) + elif n == 2: + result += list(map(cancel, roots_quadratic(f))) + elif f.is_cyclotomic: + result += roots_cyclotomic(f) + elif n == 3 and cubics: + result += roots_cubic(f, trig=trig) + elif n == 4 and quartics: + result += roots_quartic(f) + elif n == 5 and quintics: + result += roots_quintic(f) + + return result + + # Convert the generators to symbols + dumgens = symbols('x:%d' % len(f.gens), cls=Dummy) + f = f.per(f.rep, dumgens) + + (k,), f = f.terms_gcd() + + if not k: + zeros = {} + else: + zeros = {S.Zero: k} + + coeff, f = preprocess_roots(f) + + if auto and f.get_domain().is_Ring: + f = f.to_field() + + # Use EX instead of ZZ_I or QQ_I + if f.get_domain().is_QQ_I: + f = f.per(f.rep.convert(EX)) + + rescale_x = None + translate_x = None + + result = {} + + if not f.is_ground: + dom = f.get_domain() + if not dom.is_Exact and dom.is_Numerical: + for r in f.nroots(): + _update_dict(result, zeros, r, 1) + elif f.degree() == 1: + _update_dict(result, zeros, roots_linear(f)[0], 1) + elif f.length() == 2: + roots_fun = roots_quadratic if f.degree() == 2 else roots_binomial + for r in roots_fun(f): + _update_dict(result, zeros, r, 1) + else: + _, factors = Poly(f.as_expr()).factor_list() + if len(factors) == 1 and f.degree() == 2: + for r in roots_quadratic(f): + _update_dict(result, zeros, r, 1) + else: + if len(factors) == 1 and factors[0][1] == 1: + if f.get_domain().is_EX: + res = to_rational_coeffs(f) + if res: + if res[0] is None: + translate_x, f = res[2:] + else: + rescale_x, f = res[1], res[-1] + result = roots(f) + if not result: + for currentroot in _try_decompose(f): + _update_dict(result, zeros, currentroot, 1) + else: + for r in _try_heuristics(f): + _update_dict(result, zeros, r, 1) + else: + for currentroot in _try_decompose(f): + _update_dict(result, zeros, currentroot, 1) + else: + for currentfactor, k in factors: + for r in _try_heuristics(Poly(currentfactor, f.gen, field=True)): + _update_dict(result, zeros, r, k) + + if coeff is not S.One: + _result, result, = result, {} + + for currentroot, k in _result.items(): + result[coeff*currentroot] = k + + if filter not in [None, 'C']: + handlers = { + 'Z': lambda r: r.is_Integer, + 'Q': lambda r: r.is_Rational, + 'R': lambda r: all(a.is_real for a in r.as_numer_denom()), + 'I': lambda r: r.is_imaginary, + } + + try: + query = handlers[filter] + except KeyError: + raise ValueError("Invalid filter: %s" % filter) + + for zero in dict(result).keys(): + if not query(zero): + del result[zero] + + if predicate is not None: + for zero in dict(result).keys(): + if not predicate(zero): + del result[zero] + if rescale_x: + result1 = {} + for k, v in result.items(): + result1[k*rescale_x] = v + result = result1 + if translate_x: + result1 = {} + for k, v in result.items(): + result1[k + translate_x] = v + result = result1 + + # adding zero roots after non-trivial roots have been translated + result.update(zeros) + + if strict and sum(result.values()) < f.degree(): + raise UnsolvableFactorError(filldedent(''' + Strict mode: some factors cannot be solved in radicals, so + a complete list of solutions cannot be returned. Call + roots with strict=False to get solutions expressible in + radicals (if there are any). + ''')) + + if not multiple: + return result + else: + zeros = [] + + for zero in ordered(result): + zeros.extend([zero]*result[zero]) + + return zeros + + +def root_factors(f, *gens, filter=None, **args): + """ + Returns all factors of a univariate polynomial. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy.polys.polyroots import root_factors + + >>> root_factors(x**2 - y, x) + [x - sqrt(y), x + sqrt(y)] + + """ + args = dict(args) + + F = Poly(f, *gens, **args) + + if not F.is_Poly: + return [f] + + if F.is_multivariate: + raise ValueError('multivariate polynomials are not supported') + + x = F.gens[0] + + zeros = roots(F, filter=filter) + + if not zeros: + factors = [F] + else: + factors, N = [], 0 + + for r, n in ordered(zeros.items()): + factors, N = factors + [Poly(x - r, x)]*n, N + n + + if N < F.degree(): + G = reduce(lambda p, q: p*q, factors) + factors.append(F.quo(G)) + + if not isinstance(f, Poly): + factors = [ f.as_expr() for f in factors ] + + return factors diff --git a/shared/package-files/7a/7ae004112d1a2f5741a0f0296c1f932369557edf3c6931c708b453e9cde5022b/README.md b/shared/package-files/7a/7ae004112d1a2f5741a0f0296c1f932369557edf3c6931c708b453e9cde5022b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..067d4910a71a13d8a1db3f4fdf8fa0d5c124461f --- /dev/null +++ b/shared/package-files/7a/7ae004112d1a2f5741a0f0296c1f932369557edf3c6931c708b453e9cde5022b/README.md @@ -0,0 +1,3 @@ +# Molecular retrieval research package + +E006: formula-free fragment and neutral-loss residual encoder, trained from random initialization on MassSpecGym v1.5 train fold plus supplied held-out-clean ICEBERG simulations (2,333,477 nonempty spectra). Morgan fingerprint predictions rank supplied molecular candidates by training-frequency-weighted cosine similarity. All adducts and instrument conditions use the same trained model. Selected by full-validation retrieval Hit@1; validation results do not establish improvement over the external test reference. Run infer.sh INPUT_ROOT OUTPUT_ROOT. Runtime: supplied /opt/glacier/bin/python, one GPU, 8 CPU workers. No external data or cache is needed. diff --git a/shared/package-files/7a/7ae009e03fd1a7bd7363075ca621bdb38cad3aba72839655636aa5bba7f3c4ec/blob b/shared/package-files/7a/7ae009e03fd1a7bd7363075ca621bdb38cad3aba72839655636aa5bba7f3c4ec/blob new file mode 100644 index 0000000000000000000000000000000000000000..6370f4fb0ca2235bd5aebbbbf9803d466b2b048c --- /dev/null +++ b/shared/package-files/7a/7ae009e03fd1a7bd7363075ca621bdb38cad3aba72839655636aa5bba7f3c4ec/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple linalg_qr(const at::Tensor & A, c10::string_view mode="reduced"); +TORCH_API ::std::tuple linalg_qr_out(at::Tensor & Q, at::Tensor & R, const at::Tensor & A, c10::string_view mode="reduced"); +TORCH_API ::std::tuple linalg_qr_outf(const at::Tensor & A, c10::string_view mode, at::Tensor & Q, at::Tensor & R); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/7a/7ae0f6b23d8521b40ccc83c0e2b0ab208ff2f1157368cc8404ab1274141a51be/blob b/shared/package-files/7a/7ae0f6b23d8521b40ccc83c0e2b0ab208ff2f1157368cc8404ab1274141a51be/blob new file mode 100644 index 0000000000000000000000000000000000000000..75a09b7b5d8c7f9097e965d76fbae7bab2b41a01 --- /dev/null +++ b/shared/package-files/7a/7ae0f6b23d8521b40ccc83c0e2b0ab208ff2f1157368cc8404ab1274141a51be/blob @@ -0,0 +1,177 @@ +""" +Enums representing sets of strings that Matplotlib uses as input parameters. + +Matplotlib often uses simple data types like strings or tuples to define a +concept; e.g. the line capstyle can be specified as one of 'butt', 'round', +or 'projecting'. The classes in this module are used internally and serve to +document these concepts formally. + +As an end-user you will not use these classes directly, but only the values +they define. +""" + +from enum import Enum +from matplotlib import _docstring + + +class JoinStyle(str, Enum): + """ + Define how the connection between two line segments is drawn. + + For a visual impression of each *JoinStyle*, `view these docs online + `, or run `JoinStyle.demo`. + + Lines in Matplotlib are typically defined by a 1D `~.path.Path` and a + finite ``linewidth``, where the underlying 1D `~.path.Path` represents the + center of the stroked line. + + By default, `~.backend_bases.GraphicsContextBase` defines the boundaries of + a stroked line to simply be every point within some radius, + ``linewidth/2``, away from any point of the center line. However, this + results in corners appearing "rounded", which may not be the desired + behavior if you are drawing, for example, a polygon or pointed star. + + **Supported values:** + + .. rst-class:: value-list + + 'miter' + the "arrow-tip" style. Each boundary of the filled-in area will + extend in a straight line parallel to the tangent vector of the + centerline at the point it meets the corner, until they meet in a + sharp point. + 'round' + stokes every point within a radius of ``linewidth/2`` of the center + lines. + 'bevel' + the "squared-off" style. It can be thought of as a rounded corner + where the "circular" part of the corner has been cut off. + + .. note:: + + Very long miter tips are cut off (to form a *bevel*) after a + backend-dependent limit called the "miter limit", which specifies the + maximum allowed ratio of miter length to line width. For example, the + PDF backend uses the default value of 10 specified by the PDF standard, + while the SVG backend does not even specify the miter limit, resulting + in a default value of 4 per the SVG specification. Matplotlib does not + currently allow the user to adjust this parameter. + + A more detailed description of the effect of a miter limit can be found + in the `Mozilla Developer Docs + `_ + + .. plot:: + :alt: Demo of possible JoinStyle's + + from matplotlib._enums import JoinStyle + JoinStyle.demo() + + """ + + miter = "miter" + round = "round" + bevel = "bevel" + + @staticmethod + def demo(): + """Demonstrate how each JoinStyle looks for various join angles.""" + import numpy as np + import matplotlib.pyplot as plt + + def plot_angle(ax, x, y, angle, style): + phi = np.radians(angle) + xx = [x + .5, x, x + .5*np.cos(phi)] + yy = [y, y, y + .5*np.sin(phi)] + ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style) + ax.plot(xx, yy, lw=1, color='black') + ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3) + + fig, ax = plt.subplots(figsize=(5, 4), constrained_layout=True) + ax.set_title('Join style') + for x, style in enumerate(['miter', 'round', 'bevel']): + ax.text(x, 5, style) + for y, angle in enumerate([20, 45, 60, 90, 120]): + plot_angle(ax, x, y, angle, style) + if x == 0: + ax.text(-1.3, y, f'{angle} degrees') + ax.set_xlim(-1.5, 2.75) + ax.set_ylim(-.5, 5.5) + ax.set_axis_off() + fig.show() + + +JoinStyle.input_description = "{" \ + + ", ".join([f"'{js.name}'" for js in JoinStyle]) \ + + "}" + + +class CapStyle(str, Enum): + r""" + Define how the two endpoints (caps) of an unclosed line are drawn. + + How to draw the start and end points of lines that represent a closed curve + (i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's + `JoinStyle`. For all other lines, how the start and end points are drawn is + controlled by the *CapStyle*. + + For a visual impression of each *CapStyle*, `view these docs online + ` or run `CapStyle.demo`. + + By default, `~.backend_bases.GraphicsContextBase` draws a stroked line as + squared off at its endpoints. + + **Supported values:** + + .. rst-class:: value-list + + 'butt' + the line is squared off at its endpoint. + 'projecting' + the line is squared off as in *butt*, but the filled in area + extends beyond the endpoint a distance of ``linewidth/2``. + 'round' + like *butt*, but a semicircular cap is added to the end of the + line, of radius ``linewidth/2``. + + .. plot:: + :alt: Demo of possible CapStyle's + + from matplotlib._enums import CapStyle + CapStyle.demo() + + """ + butt = "butt" + projecting = "projecting" + round = "round" + + @staticmethod + def demo(): + """Demonstrate how each CapStyle looks for a thick line segment.""" + import matplotlib.pyplot as plt + + fig = plt.figure(figsize=(4, 1.2)) + ax = fig.add_axes([0, 0, 1, 0.8]) + ax.set_title('Cap style') + + for x, style in enumerate(['butt', 'round', 'projecting']): + ax.text(x+0.25, 0.85, style, ha='center') + xx = [x, x+0.5] + yy = [0, 0] + ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style) + ax.plot(xx, yy, lw=1, color='black') + ax.plot(xx, yy, 'o', color='tab:red', markersize=3) + + ax.set_ylim(-.5, 1.5) + ax.set_axis_off() + fig.show() + + +CapStyle.input_description = "{" \ + + ", ".join([f"'{cs.name}'" for cs in CapStyle]) \ + + "}" + +_docstring.interpd.register( + JoinStyle=JoinStyle.input_description, + CapStyle=CapStyle.input_description, +) diff --git a/shared/package-files/7a/7ae39b88f2102d76fe85aaae8f03f802893b8938e07d78f433a83edf2691f18d/blob b/shared/package-files/7a/7ae39b88f2102d76fe85aaae8f03f802893b8938e07d78f433a83edf2691f18d/blob new file mode 100644 index 0000000000000000000000000000000000000000..dd35e468215e6bfadbcb2398e866c0ed0f1f85e5 --- /dev/null +++ b/shared/package-files/7a/7ae39b88f2102d76fe85aaae8f03f802893b8938e07d78f433a83edf2691f18d/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _unpack_dual { + using schema = ::std::tuple (const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_unpack_dual") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_unpack_dual(Tensor(a) dual, int level) -> (Tensor(a) primal, Tensor tangent)") + static ::std::tuple call(const at::Tensor & dual, int64_t level); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & dual, int64_t level); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7a/7aeaea470b8a5c2ba0b1728107fe3976163031f1ac10e23724cdfa314d3fdfc7/blob b/shared/package-files/7a/7aeaea470b8a5c2ba0b1728107fe3976163031f1ac10e23724cdfa314d3fdfc7/blob new file mode 100644 index 0000000000000000000000000000000000000000..1260d42de9586bd24e5c9671e1906247a73a2185 --- /dev/null +++ b/shared/package-files/7a/7aeaea470b8a5c2ba0b1728107fe3976163031f1ac10e23724cdfa314d3fdfc7/blob @@ -0,0 +1,21 @@ +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple + +TIMEOUT_MAX: int +error = RuntimeError + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def exit() -> NoReturn: ... +def get_ident() -> int: ... +def allocate_lock() -> LockType: ... +def stack_size(size: Optional[int] = ...) -> int: ... + +class LockType(object): + locked_status: bool + def __init__(self) -> None: ... + def acquire(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ... + def __enter__(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ... + def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def release(self) -> bool: ... + def locked(self) -> bool: ... + +def interrupt_main() -> None: ... diff --git a/shared/package-files/7a/7aec2a507183a4d1cc61304834906c3a957a9947ee2685e442eae8571b9f6539/blob b/shared/package-files/7a/7aec2a507183a4d1cc61304834906c3a957a9947ee2685e442eae8571b9f6539/blob new file mode 100644 index 0000000000000000000000000000000000000000..86d3a4c2a3ad5cc9d3b27091e85924e8a6c8da9c --- /dev/null +++ b/shared/package-files/7a/7aec2a507183a4d1cc61304834906c3a957a9947ee2685e442eae8571b9f6539/blob @@ -0,0 +1,339 @@ +from itertools import chain, count + +import networkx as nx + +__all__ = ["node_link_data", "node_link_graph"] + + +_attrs = { + "source": "source", + "target": "target", + "name": "id", + "key": "key", + "link": "links", +} + + +def _to_tuple(x): + """Converts lists to tuples, including nested lists. + + All other non-list inputs are passed through unmodified. This function is + intended to be used to convert potentially nested lists from json files + into valid nodes. + + Examples + -------- + >>> _to_tuple([1, 2, [3, 4]]) + (1, 2, (3, 4)) + """ + if not isinstance(x, (tuple, list)): + return x + return tuple(map(_to_tuple, x)) + + +def node_link_data( + G, + attrs=None, + *, + source="source", + target="target", + name="id", + key="key", + link="links", +): + """Returns data in node-link format that is suitable for JSON serialization + and use in Javascript documents. + + Parameters + ---------- + G : NetworkX graph + + attrs : dict + A dictionary that contains five keys 'source', 'target', 'name', + 'key' and 'link'. The corresponding values provide the attribute + names for storing NetworkX-internal graph data. The values should + be unique. Default value:: + + dict(source='source', target='target', name='id', + key='key', link='links') + + If some user-defined graph data use these attribute names as data keys, + they may be silently dropped. + + .. deprecated:: 2.8.6 + + The `attrs` keyword argument will be replaced with `source`, `target`, `name`, + `key` and `link`. in networkx 3.2 + + If the `attrs` keyword and the new keywords are both used in a single function call (not recommended) + the `attrs` keyword argument will take precedence. + + The values of the keywords must be unique. + + source : string + A string that provides the 'source' attribute name for storing NetworkX-internal graph data. + target : string + A string that provides the 'target' attribute name for storing NetworkX-internal graph data. + name : string + A string that provides the 'name' attribute name for storing NetworkX-internal graph data. + key : string + A string that provides the 'key' attribute name for storing NetworkX-internal graph data. + link : string + A string that provides the 'link' attribute name for storing NetworkX-internal graph data. + + Returns + ------- + data : dict + A dictionary with node-link formatted data. + + Raises + ------ + NetworkXError + If the values of 'source', 'target' and 'key' are not unique. + + Examples + -------- + >>> G = nx.Graph([("A", "B")]) + >>> data1 = nx.node_link_data(G) + >>> data1 + {'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]} + + To serialize with JSON + + >>> import json + >>> s1 = json.dumps(data1) + >>> s1 + '{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}' + + A graph can also be serialized by passing `node_link_data` as an encoder function. The two methods are equivalent. + + >>> s1 = json.dumps(G, default=nx.node_link_data) + >>> s1 + '{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}' + + The attribute names for storing NetworkX-internal graph data can + be specified as keyword options. + + >>> H = nx.gn_graph(2) + >>> data2 = nx.node_link_data(H, link="edges", source="from", target="to") + >>> data2 + {'directed': True, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 0}, {'id': 1}], 'edges': [{'from': 1, 'to': 0}]} + + Notes + ----- + Graph, node, and link attributes are stored in this format. Note that + attribute keys will be converted to strings in order to comply with JSON. + + Attribute 'key' is only used for multigraphs. + + To use `node_link_data` in conjunction with `node_link_graph`, + the keyword names for the attributes must match. + + + See Also + -------- + node_link_graph, adjacency_data, tree_data + """ + # ------ TODO: Remove between the lines after signature change is complete ----- # + if attrs is not None: + import warnings + + msg = ( + "\n\nThe `attrs` keyword argument of node_link_data is deprecated\n" + "and will be removed in networkx 3.2. It is replaced with explicit\n" + "keyword arguments: `source`, `target`, `name`, `key` and `link`.\n" + "To make this warning go away, and ensure usage is forward\n" + "compatible, replace `attrs` with the keywords. " + "For example:\n\n" + " >>> node_link_data(G, attrs={'target': 'foo', 'name': 'bar'})\n\n" + "should instead be written as\n\n" + " >>> node_link_data(G, target='foo', name='bar')\n\n" + "in networkx 3.2.\n" + "The default values of the keywords will not change.\n" + ) + warnings.warn(msg, DeprecationWarning, stacklevel=2) + + source = attrs.get("source", "source") + target = attrs.get("target", "target") + name = attrs.get("name", "name") + key = attrs.get("key", "key") + link = attrs.get("link", "links") + # -------------------------------------------------- # + multigraph = G.is_multigraph() + + # Allow 'key' to be omitted from attrs if the graph is not a multigraph. + key = None if not multigraph else key + if len({source, target, key}) < 3: + raise nx.NetworkXError("Attribute names are not unique.") + data = { + "directed": G.is_directed(), + "multigraph": multigraph, + "graph": G.graph, + "nodes": [dict(chain(G.nodes[n].items(), [(name, n)])) for n in G], + } + if multigraph: + data[link] = [ + dict(chain(d.items(), [(source, u), (target, v), (key, k)])) + for u, v, k, d in G.edges(keys=True, data=True) + ] + else: + data[link] = [ + dict(chain(d.items(), [(source, u), (target, v)])) + for u, v, d in G.edges(data=True) + ] + return data + + +def node_link_graph( + data, + directed=False, + multigraph=True, + attrs=None, + *, + source="source", + target="target", + name="id", + key="key", + link="links", +): + """Returns graph from node-link data format. + Useful for de-serialization from JSON. + + Parameters + ---------- + data : dict + node-link formatted graph data + + directed : bool + If True, and direction not specified in data, return a directed graph. + + multigraph : bool + If True, and multigraph not specified in data, return a multigraph. + + attrs : dict + A dictionary that contains five keys 'source', 'target', 'name', + 'key' and 'link'. The corresponding values provide the attribute + names for storing NetworkX-internal graph data. Default value: + + dict(source='source', target='target', name='id', + key='key', link='links') + + .. deprecated:: 2.8.6 + + The `attrs` keyword argument will be replaced with the individual keywords: `source`, `target`, `name`, + `key` and `link`. in networkx 3.2. + + If the `attrs` keyword and the new keywords are both used in a single function call (not recommended) + the `attrs` keyword argument will take precedence. + + The values of the keywords must be unique. + + source : string + A string that provides the 'source' attribute name for storing NetworkX-internal graph data. + target : string + A string that provides the 'target' attribute name for storing NetworkX-internal graph data. + name : string + A string that provides the 'name' attribute name for storing NetworkX-internal graph data. + key : string + A string that provides the 'key' attribute name for storing NetworkX-internal graph data. + link : string + A string that provides the 'link' attribute name for storing NetworkX-internal graph data. + + Returns + ------- + G : NetworkX graph + A NetworkX graph object + + Examples + -------- + + Create data in node-link format by converting a graph. + + >>> G = nx.Graph([('A', 'B')]) + >>> data = nx.node_link_data(G) + >>> data + {'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]} + + Revert data in node-link format to a graph. + + >>> H = nx.node_link_graph(data) + >>> print(H.edges) + [('A', 'B')] + + To serialize and deserialize a graph with JSON, + + >>> import json + >>> d = json.dumps(node_link_data(G)) + >>> H = node_link_graph(json.loads(d)) + >>> print(G.edges, H.edges) + [('A', 'B')] [('A', 'B')] + + + Notes + ----- + Attribute 'key' is only used for multigraphs. + + To use `node_link_data` in conjunction with `node_link_graph`, + the keyword names for the attributes must match. + + See Also + -------- + node_link_data, adjacency_data, tree_data + """ + # ------ TODO: Remove between the lines after signature change is complete ----- # + if attrs is not None: + import warnings + + msg = ( + "\n\nThe `attrs` keyword argument of node_link_graph is deprecated\n" + "and will be removed in networkx 3.2. It is replaced with explicit\n" + "keyword arguments: `source`, `target`, `name`, `key` and `link`.\n" + "To make this warning go away, and ensure usage is forward\n" + "compatible, replace `attrs` with the keywords. " + "For example:\n\n" + " >>> node_link_graph(data, attrs={'target': 'foo', 'name': 'bar'})\n\n" + "should instead be written as\n\n" + " >>> node_link_graph(data, target='foo', name='bar')\n\n" + "in networkx 3.2.\n" + "The default values of the keywords will not change.\n" + ) + warnings.warn(msg, DeprecationWarning, stacklevel=2) + + source = attrs.get("source", "source") + target = attrs.get("target", "target") + name = attrs.get("name", "name") + key = attrs.get("key", "key") + link = attrs.get("link", "links") + # -------------------------------------------------- # + multigraph = data.get("multigraph", multigraph) + directed = data.get("directed", directed) + if multigraph: + graph = nx.MultiGraph() + else: + graph = nx.Graph() + if directed: + graph = graph.to_directed() + + # Allow 'key' to be omitted from attrs if the graph is not a multigraph. + key = None if not multigraph else key + graph.graph = data.get("graph", {}) + c = count() + for d in data["nodes"]: + node = _to_tuple(d.get(name, next(c))) + nodedata = {str(k): v for k, v in d.items() if k != name} + graph.add_node(node, **nodedata) + for d in data[link]: + src = tuple(d[source]) if isinstance(d[source], list) else d[source] + tgt = tuple(d[target]) if isinstance(d[target], list) else d[target] + if not multigraph: + edgedata = {str(k): v for k, v in d.items() if k != source and k != target} + graph.add_edge(src, tgt, **edgedata) + else: + ky = d.get(key, None) + edgedata = { + str(k): v + for k, v in d.items() + if k != source and k != target and k != key + } + graph.add_edge(src, tgt, ky, **edgedata) + return graph diff --git a/shared/package-files/7a/7aed9a0c69700608faa87f4b97e8b52bfa884fb7ade1f6cf60fe3708efeaaa0f/blob b/shared/package-files/7a/7aed9a0c69700608faa87f4b97e8b52bfa884fb7ade1f6cf60fe3708efeaaa0f/blob new file mode 100644 index 0000000000000000000000000000000000000000..f618d531ab83c36e7c5a070c574bfe36670d2f26 --- /dev/null +++ b/shared/package-files/7a/7aed9a0c69700608faa87f4b97e8b52bfa884fb7ade1f6cf60fe3708efeaaa0f/blob @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_bicubic2d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); +} +namespace symint { + template ::value>> + at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input) { + return at::_ops::upsample_bicubic2d_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); + } +} + +// aten::upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w); + } +} + +// aten::upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor +inline at::Tensor upsample_bicubic2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w); +} +namespace symint { + template ::value>> + at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt) { + return at::_ops::upsample_bicubic2d_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w); + } +} + +} diff --git a/shared/package-files/7a/7af00a53129b55a145f31b52a5809f5c8033bfd6183779183768807b7265e5c7/blob b/shared/package-files/7a/7af00a53129b55a145f31b52a5809f5c8033bfd6183779183768807b7265e5c7/blob new file mode 100644 index 0000000000000000000000000000000000000000..34a8035754af910fb86b5230f83965066a1b027c --- /dev/null +++ b/shared/package-files/7a/7af00a53129b55a145f31b52a5809f5c8033bfd6183779183768807b7265e5c7/blob @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor quantile(const at::Tensor & self, const at::Tensor & q, c10::optional dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear"); +TORCH_API at::Tensor & quantile_out(const at::Tensor & self, const at::Tensor & q, c10::optional dim, bool keepdim, c10::string_view interpolation, at::Tensor & out); +TORCH_API at::Tensor quantile(const at::Tensor & self, double q, c10::optional dim=c10::nullopt, bool keepdim=false, c10::string_view interpolation="linear"); +TORCH_API at::Tensor & quantile_out(const at::Tensor & self, double q, c10::optional dim, bool keepdim, c10::string_view interpolation, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/7a/7af063d74c7ff3d8e57ee55a7290034ceca7a765c5f67f1ddaf41fe65660fa91/blob b/shared/package-files/7a/7af063d74c7ff3d8e57ee55a7290034ceca7a765c5f67f1ddaf41fe65660fa91/blob new file mode 100644 index 0000000000000000000000000000000000000000..88d80e69c92d454ae42fe9f201f90b08b0452bd7 --- /dev/null +++ b/shared/package-files/7a/7af063d74c7ff3d8e57ee55a7290034ceca7a765c5f67f1ddaf41fe65660fa91/blob @@ -0,0 +1,117 @@ +from typing import Any, Optional, Tuple + +whitespace_re: Any +string_re: Any +integer_re: Any +name_re: Any +float_re: Any +newline_re: Any +TOKEN_ADD: Any +TOKEN_ASSIGN: Any +TOKEN_COLON: Any +TOKEN_COMMA: Any +TOKEN_DIV: Any +TOKEN_DOT: Any +TOKEN_EQ: Any +TOKEN_FLOORDIV: Any +TOKEN_GT: Any +TOKEN_GTEQ: Any +TOKEN_LBRACE: Any +TOKEN_LBRACKET: Any +TOKEN_LPAREN: Any +TOKEN_LT: Any +TOKEN_LTEQ: Any +TOKEN_MOD: Any +TOKEN_MUL: Any +TOKEN_NE: Any +TOKEN_PIPE: Any +TOKEN_POW: Any +TOKEN_RBRACE: Any +TOKEN_RBRACKET: Any +TOKEN_RPAREN: Any +TOKEN_SEMICOLON: Any +TOKEN_SUB: Any +TOKEN_TILDE: Any +TOKEN_WHITESPACE: Any +TOKEN_FLOAT: Any +TOKEN_INTEGER: Any +TOKEN_NAME: Any +TOKEN_STRING: Any +TOKEN_OPERATOR: Any +TOKEN_BLOCK_BEGIN: Any +TOKEN_BLOCK_END: Any +TOKEN_VARIABLE_BEGIN: Any +TOKEN_VARIABLE_END: Any +TOKEN_RAW_BEGIN: Any +TOKEN_RAW_END: Any +TOKEN_COMMENT_BEGIN: Any +TOKEN_COMMENT_END: Any +TOKEN_COMMENT: Any +TOKEN_LINESTATEMENT_BEGIN: Any +TOKEN_LINESTATEMENT_END: Any +TOKEN_LINECOMMENT_BEGIN: Any +TOKEN_LINECOMMENT_END: Any +TOKEN_LINECOMMENT: Any +TOKEN_DATA: Any +TOKEN_INITIAL: Any +TOKEN_EOF: Any +operators: Any +reverse_operators: Any +operator_re: Any +ignored_tokens: Any +ignore_if_empty: Any + +def describe_token(token): ... +def describe_token_expr(expr): ... +def count_newlines(value): ... +def compile_rules(environment): ... + +class Failure: + message: Any + error_class: Any + def __init__(self, message, cls: Any = ...) -> None: ... + def __call__(self, lineno, filename): ... + +class Token(Tuple[int, Any, Any]): + lineno: Any + type: Any + value: Any + def __new__(cls, lineno, type, value): ... + def test(self, expr): ... + def test_any(self, *iterable): ... + +class TokenStreamIterator: + stream: Any + def __init__(self, stream) -> None: ... + def __iter__(self): ... + def __next__(self): ... + +class TokenStream: + name: Any + filename: Any + closed: bool + current: Any + def __init__(self, generator, name, filename) -> None: ... + def __iter__(self): ... + def __bool__(self): ... + __nonzero__: Any + eos: Any + def push(self, token): ... + def look(self): ... + def skip(self, n: int = ...): ... + def next_if(self, expr): ... + def skip_if(self, expr): ... + def __next__(self): ... + def close(self): ... + def expect(self, expr): ... + +def get_lexer(environment): ... + +class Lexer: + newline_sequence: Any + keep_trailing_newline: Any + rules: Any + def __init__(self, environment) -> None: ... + def tokenize(self, source, name: Optional[Any] = ..., filename: Optional[Any] = ..., state: Optional[Any] = ...): ... + def wrap(self, stream, name: Optional[Any] = ..., filename: Optional[Any] = ...): ... + def tokeniter(self, source, name, filename: Optional[Any] = ..., state: Optional[Any] = ...): ... diff --git a/shared/package-files/7a/7af0edf10378945e428b0ad421794e2429ed8ad0423ac23764b3c42005512c95/blob b/shared/package-files/7a/7af0edf10378945e428b0ad421794e2429ed8ad0423ac23764b3c42005512c95/blob new file mode 100644 index 0000000000000000000000000000000000000000..4f6d8b2d79406012c5f8bae9c289ed5bf4d179cc --- /dev/null +++ b/shared/package-files/7a/7af0edf10378945e428b0ad421794e2429ed8ad0423ac23764b3c42005512c95/blob @@ -0,0 +1,17 @@ +from typing import Optional + + +def pick_bool(*values: Optional[bool]) -> bool: + """Pick the first non-none bool or return the last value. + + Args: + *values (bool): Any number of boolean or None values. + + Returns: + bool: First non-none boolean. + """ + assert values, "1 or more values required" + for value in values: + if value is not None: + return value + return bool(value) diff --git a/shared/package-files/7a/7af3e6d7690b818a939bea5bce6eb46cebae9ae993f08a41356169d2e332af31/blob b/shared/package-files/7a/7af3e6d7690b818a939bea5bce6eb46cebae9ae993f08a41356169d2e332af31/blob new file mode 100644 index 0000000000000000000000000000000000000000..34e3a9950cc557879af8d797f9382b18a870fb56 --- /dev/null +++ b/shared/package-files/7a/7af3e6d7690b818a939bea5bce6eb46cebae9ae993f08a41356169d2e332af31/blob @@ -0,0 +1,36 @@ +"""Read resources contained within a package.""" + +from ._common import ( + as_file, + files, + Package, +) + +from ._legacy import ( + contents, + open_binary, + read_binary, + open_text, + read_text, + is_resource, + path, + Resource, +) + +from .abc import ResourceReader + + +__all__ = [ + 'Package', + 'Resource', + 'ResourceReader', + 'as_file', + 'contents', + 'files', + 'is_resource', + 'open_binary', + 'open_text', + 'path', + 'read_binary', + 'read_text', +] diff --git a/shared/package-files/7a/7af73035632b6887174383f051dc8fb87c89189ed526100f31ccf71cae3df17a/blob b/shared/package-files/7a/7af73035632b6887174383f051dc8fb87c89189ed526100f31ccf71cae3df17a/blob new file mode 100644 index 0000000000000000000000000000000000000000..75c48dab7213bf86ff7d9443d7af369e4932de68 --- /dev/null +++ b/shared/package-files/7a/7af73035632b6887174383f051dc8fb87c89189ed526100f31ccf71cae3df17a/blob @@ -0,0 +1,175 @@ +import contextlib +from typing import Generator +import warnings + +from torch._C import default_generator +import torch + + +def set_rng_state(new_state: torch.Tensor) -> None: + r"""Sets the random number generator state. + + .. note: This function only works for CPU. For CUDA, please use + torch.manual_seed(seed), which works for both CPU and CUDA. + + Args: + new_state (torch.ByteTensor): The desired state + """ + default_generator.set_state(new_state) + + +def get_rng_state() -> torch.Tensor: + r"""Returns the random number generator state as a `torch.ByteTensor`.""" + return default_generator.get_state() + + +def manual_seed(seed) -> torch._C.Generator: + r"""Sets the seed for generating random numbers. Returns a + `torch.Generator` object. + + Args: + seed (int): The desired seed. Value must be within the inclusive range + `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError + is raised. Negative inputs are remapped to positive values with the formula + `0xffff_ffff_ffff_ffff + seed`. + """ + seed = int(seed) + import torch.cuda + + if not torch.cuda._is_in_bad_fork(): + torch.cuda.manual_seed_all(seed) + + import torch.mps + if not torch.mps._is_in_bad_fork(): + torch.mps.manual_seed(seed) + + import torch.xpu + if not torch.xpu._is_in_bad_fork(): + torch.xpu.manual_seed_all(seed) + + _seed_custom_device(seed) + + return default_generator.manual_seed(seed) + + +def seed() -> int: + r"""Sets the seed for generating random numbers to a non-deterministic + random number. Returns a 64 bit number used to seed the RNG. + """ + seed = default_generator.seed() + import torch.cuda + + if not torch.cuda._is_in_bad_fork(): + torch.cuda.manual_seed_all(seed) + + import torch.mps + if not torch.mps._is_in_bad_fork(): + torch.mps.manual_seed(seed) + + import torch.xpu + if not torch.xpu._is_in_bad_fork(): + torch.xpu.manual_seed_all(seed) + + _seed_custom_device(seed) + + return seed + + +def _seed_custom_device(seed) -> None: + r"""Sets the seed to generate random numbers for custom device. + + Args: + seed (int): The desired seed. + + See [Note: support the custom device with privateuse1] + """ + seed = int(seed) + custom_backend_name = torch._C._get_privateuse1_backend_name() + if hasattr(torch, custom_backend_name): + custom_device_mod = getattr(torch, custom_backend_name) + _bad_fork_name = "_is_in_bad_fork" + _seed_all_name = "manual_seed_all" + if hasattr(custom_device_mod, _bad_fork_name) and hasattr(custom_device_mod, _seed_all_name): + if not getattr(custom_device_mod, _bad_fork_name)(): + getattr(custom_device_mod, _seed_all_name)(seed) + else: + message = f"Set seed for `{custom_backend_name}` device does not take effect, please add API's " + message += f"`{_bad_fork_name}` and `{_seed_all_name}` to `{custom_backend_name}` device module." + warnings.warn(message, UserWarning, stacklevel=3) + + +def initial_seed() -> int: + r"""Returns the initial seed for generating random numbers as a + Python `long`. + """ + return default_generator.initial_seed() + + +_fork_rng_warned_already = False + + +@contextlib.contextmanager +def fork_rng(devices=None, enabled=True, _caller="fork_rng", _devices_kw="devices", device_type="cuda") -> Generator: + """ + Forks the RNG, so that when you return, the RNG is reset + to the state that it was previously in. + + Args: + devices (iterable of Device IDs): devices for which to fork + the RNG. CPU RNG state is always forked. By default, :meth:`fork_rng` operates + on all devices, but will emit a warning if your machine has a lot + of devices, since this function will run very slowly in that case. + If you explicitly specify devices, this warning will be suppressed + enabled (bool): if ``False``, the RNG is not forked. This is a convenience + argument for easily disabling the context manager without having + to delete it and unindent your Python code under it. + deivce_type (str): device type str, default is `cuda`. As for custom device, + see details in [Note: support the custom device with privateuse1] + """ + + device_type = torch.device(device_type).type + device_mod = getattr(torch, device_type, None) + if device_mod is None: + raise RuntimeError(f"torch has no module of `{device_type}`, you should register " + + "a module by `torch._register_device_module`.") + global _fork_rng_warned_already + + # Internal arguments: + # _caller: the function which called fork_rng, which the user used + # _devices_kw: the devices keyword of _caller + + if not enabled: + yield + return + + if devices is None: + num_devices = device_mod.device_count() + if num_devices > 1 and not _fork_rng_warned_already: + message = (f"{device_type.upper()} reports that you have {num_devices} available devices, and " + f"you have used {_caller} without explicitly specifying which devices are being used. " + f"For safety, we initialize *every* {device_type.upper()} device by default, which can " + f"be quite slow if you have a lot of {device_type.upper()}s. If you know that you are only" + f" making use of a few {device_type.upper()} devices, set the environment variable " + f"{device_type.upper()}_VISIBLE_DEVICES or the '{_devices_kw}' keyword argument of {_caller} " + "with the set of devices you are actually using. For example, if you are using CPU only, " + "set device.upper()_VISIBLE_DEVICES= or devices=[]; if you are using device 0 only, " + f"set {device_type.upper()}_VISIBLE_DEVICES=0 or devices=[0]. To initialize all devices " + f"and suppress this warning, set the '{_devices_kw}' keyword argument to " + f"`range(torch.{device_type}.device_count())`.") + warnings.warn(message) + _fork_rng_warned_already = True + devices = list(range(num_devices)) + else: + # Protect against user passing us a generator; we need to traverse this + # multiple times but a generator will be exhausted upon first traversal + devices = list(devices) + + cpu_rng_state = torch.get_rng_state() + device_rng_states = [device_mod.get_rng_state(device) for device in devices] + + try: + yield + finally: + torch.set_rng_state(cpu_rng_state) + for device, device_rng_state in zip(devices, device_rng_states): + device_mod.set_rng_state(device_rng_state, device) diff --git a/shared/package-files/7a/7af7d9cd380e514befbe52b40d174365046ac489462df258ccabbc4033314a4b/blob b/shared/package-files/7a/7af7d9cd380e514befbe52b40d174365046ac489462df258ccabbc4033314a4b/blob new file mode 100644 index 0000000000000000000000000000000000000000..1a8e47928b76034dd1d7ba8b8f87bd527bb1cdeb --- /dev/null +++ b/shared/package-files/7a/7af7d9cd380e514befbe52b40d174365046ac489462df258ccabbc4033314a4b/blob @@ -0,0 +1,12 @@ +from sympy.core import Symbol, Integer + +x = Symbol('x') +i3 = Integer(3) + + +def timeit_x_is_integer(): + x.is_integer + + +def timeit_Integer_is_irrational(): + i3.is_irrational diff --git a/shared/package-files/7a/7af8854ffcf801755ca9a6fdb5e81bbbe6b0de5e45422a246541b7667e8ccd45/blob b/shared/package-files/7a/7af8854ffcf801755ca9a6fdb5e81bbbe6b0de5e45422a246541b7667e8ccd45/blob new file mode 100644 index 0000000000000000000000000000000000000000..ad9ff8f05257b38c56897e73a1b722de5c5388c4 --- /dev/null +++ b/shared/package-files/7a/7af8854ffcf801755ca9a6fdb5e81bbbe6b0de5e45422a246541b7667e8ccd45/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_shape_as_tensor(Tensor self) -> Tensor +inline at::Tensor _shape_as_tensor(const at::Tensor & self) { + return at::_ops::_shape_as_tensor::call(self); +} + +} diff --git a/shared/package-files/7a/7afaef5098c028df1b09e068a17a807869d645cd2a06a1bf5b64cc44f5aaed0e/blob b/shared/package-files/7a/7afaef5098c028df1b09e068a17a807869d645cd2a06a1bf5b64cc44f5aaed0e/blob new file mode 100644 index 0000000000000000000000000000000000000000..5d3c96fb8f796416907fc73e4685ab98bbdb2ad0 --- /dev/null +++ b/shared/package-files/7a/7afaef5098c028df1b09e068a17a807869d645cd2a06a1bf5b64cc44f5aaed0e/blob @@ -0,0 +1,411 @@ +""" + pygments.lexers._julia_builtins + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Julia builtins. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +# operators +# see https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm +# Julia v1.6.0-rc1 +OPERATORS_LIST = [ + # other + '->', + # prec-assignment + ':=', '$=', + # prec-conditional, prec-lazy-or, prec-lazy-and + '?', '||', '&&', + # prec-colon + ':', + # prec-plus + '$', + # prec-decl + '::', +] +DOTTED_OPERATORS_LIST = [ + # prec-assignment + r'=', r'+=', r'-=', r'*=', r'/=', r'//=', r'\=', r'^=', r'÷=', r'%=', r'<<=', + r'>>=', r'>>>=', r'|=', r'&=', r'⊻=', r'≔', r'⩴', r"≕'", r'~', + # prec-pair + '=>', + # prec-arrow + r'→', r'↔', r'↚', r'↛', r'↞', r'↠', r'↢', r'↣', r'↦', r'↤', r'↮', r'⇎', r'⇍', r'⇏', + r'⇐', r'⇒', r'⇔', r'⇴', r'⇶', r'⇷', r'⇸', r'⇹', r'⇺', r'⇻', r'⇼', r'⇽', r'⇾', r'⇿', + r'⟵', r'⟶', r'⟷', r'⟹', r'⟺', r'⟻', r'⟼', r'⟽', r'⟾', r'⟿', r'⤀', r'⤁', r'⤂', r'⤃', + r'⤄', r'⤅', r'⤆', r'⤇', r'⤌', r'⤍', r'⤎', r'⤏', r'⤐', r'⤑', r'⤔', r'⤕', r'⤖', r'⤗', + r'⤘', r'⤝', r'⤞', r'⤟', r'⤠', r'⥄', r'⥅', r'⥆', r'⥇', r'⥈', r'⥊', r'⥋', r'⥎', r'⥐', + r'⥒', r'⥓', r'⥖', r'⥗', r'⥚', r'⥛', r'⥞', r'⥟', r'⥢', r'⥤', r'⥦', r'⥧', r'⥨', r'⥩', + r'⥪', r'⥫', r'⥬', r'⥭', r'⥰', r'⧴', r'⬱', r'⬰', r'⬲', r'⬳', r'⬴', r'⬵', r'⬶', r'⬷', + r'⬸', r'⬹', r'⬺', r'⬻', r'⬼', r'⬽', r'⬾', r'⬿', r'⭀', r'⭁', r'⭂', r'⭃', r'⭄', r'⭇', + r'⭈', r'⭉', r'⭊', r'⭋', r'⭌', r'←', r'→', r'⇜', r'⇝', r'↜', r'↝', r'↩', r'↪', r'↫', + r'↬', r'↼', r'↽', r'⇀', r'⇁', r'⇄', r'⇆', r'⇇', r'⇉', r'⇋', r'⇌', r'⇚', r'⇛', r'⇠', + r'⇢', r'↷', r'↶', r'↺', r'↻', r'-->', r'<--', r'<-->', + # prec-comparison + r'>', r'<', r'>=', r'≥', r'<=', r'≤', r'==', r'===', r'≡', r'!=', r'≠', r'!==', + r'≢', r'∈', r'∉', r'∋', r'∌', r'⊆', r'⊈', r'⊂', r'⊄', r'⊊', r'∝', r'∊', r'∍', r'∥', + r'∦', r'∷', r'∺', r'∻', r'∽', r'∾', r'≁', r'≃', r'≂', r'≄', r'≅', r'≆', r'≇', r'≈', + r'≉', r'≊', r'≋', r'≌', r'≍', r'≎', r'≐', r'≑', r'≒', r'≓', r'≖', r'≗', r'≘', r'≙', + r'≚', r'≛', r'≜', r'≝', r'≞', r'≟', r'≣', r'≦', r'≧', r'≨', r'≩', r'≪', r'≫', r'≬', + r'≭', r'≮', r'≯', r'≰', r'≱', r'≲', r'≳', r'≴', r'≵', r'≶', r'≷', r'≸', r'≹', r'≺', + r'≻', r'≼', r'≽', r'≾', r'≿', r'⊀', r'⊁', r'⊃', r'⊅', r'⊇', r'⊉', r'⊋', r'⊏', r'⊐', + r'⊑', r'⊒', r'⊜', r'⊩', r'⊬', r'⊮', r'⊰', r'⊱', r'⊲', r'⊳', r'⊴', r'⊵', r'⊶', r'⊷', + r'⋍', r'⋐', r'⋑', r'⋕', r'⋖', r'⋗', r'⋘', r'⋙', r'⋚', r'⋛', r'⋜', r'⋝', r'⋞', r'⋟', + r'⋠', r'⋡', r'⋢', r'⋣', r'⋤', r'⋥', r'⋦', r'⋧', r'⋨', r'⋩', r'⋪', r'⋫', r'⋬', r'⋭', + r'⋲', r'⋳', r'⋴', r'⋵', r'⋶', r'⋷', r'⋸', r'⋹', r'⋺', r'⋻', r'⋼', r'⋽', r'⋾', r'⋿', + r'⟈', r'⟉', r'⟒', r'⦷', r'⧀', r'⧁', r'⧡', r'⧣', r'⧤', r'⧥', r'⩦', r'⩧', r'⩪', r'⩫', + r'⩬', r'⩭', r'⩮', r'⩯', r'⩰', r'⩱', r'⩲', r'⩳', r'⩵', r'⩶', r'⩷', r'⩸', r'⩹', r'⩺', + r'⩻', r'⩼', r'⩽', r'⩾', r'⩿', r'⪀', r'⪁', r'⪂', r'⪃', r'⪄', r'⪅', r'⪆', r'⪇', r'⪈', + r'⪉', r'⪊', r'⪋', r'⪌', r'⪍', r'⪎', r'⪏', r'⪐', r'⪑', r'⪒', r'⪓', r'⪔', r'⪕', r'⪖', + r'⪗', r'⪘', r'⪙', r'⪚', r'⪛', r'⪜', r'⪝', r'⪞', r'⪟', r'⪠', r'⪡', r'⪢', r'⪣', r'⪤', + r'⪥', r'⪦', r'⪧', r'⪨', r'⪩', r'⪪', r'⪫', r'⪬', r'⪭', r'⪮', r'⪯', r'⪰', r'⪱', r'⪲', + r'⪳', r'⪴', r'⪵', r'⪶', r'⪷', r'⪸', r'⪹', r'⪺', r'⪻', r'⪼', r'⪽', r'⪾', r'⪿', r'⫀', + r'⫁', r'⫂', r'⫃', r'⫄', r'⫅', r'⫆', r'⫇', r'⫈', r'⫉', r'⫊', r'⫋', r'⫌', r'⫍', r'⫎', + r'⫏', r'⫐', r'⫑', r'⫒', r'⫓', r'⫔', r'⫕', r'⫖', r'⫗', r'⫘', r'⫙', r'⫷', r'⫸', r'⫹', + r'⫺', r'⊢', r'⊣', r'⟂', r'<:', r'>:', + # prec-pipe + '<|', '|>', + # prec-colon + r'…', r'⁝', r'⋮', r'⋱', r'⋰', r'⋯', + # prec-plus + r'+', r'-', r'¦', r'|', r'⊕', r'⊖', r'⊞', r'⊟', r'++', r'∪', r'∨', r'⊔', r'±', r'∓', + r'∔', r'∸', r'≏', r'⊎', r'⊻', r'⊽', r'⋎', r'⋓', r'⧺', r'⧻', r'⨈', r'⨢', r'⨣', r'⨤', + r'⨥', r'⨦', r'⨧', r'⨨', r'⨩', r'⨪', r'⨫', r'⨬', r'⨭', r'⨮', r'⨹', r'⨺', r'⩁', r'⩂', + r'⩅', r'⩊', r'⩌', r'⩏', r'⩐', r'⩒', r'⩔', r'⩖', r'⩗', r'⩛', r'⩝', r'⩡', r'⩢', r'⩣', + # prec-times + r'*', r'/', r'⌿', r'÷', r'%', r'&', r'⋅', r'∘', r'×', '\\', r'∩', r'∧', r'⊗', r'⊘', + r'⊙', r'⊚', r'⊛', r'⊠', r'⊡', r'⊓', r'∗', r'∙', r'∤', r'⅋', r'≀', r'⊼', r'⋄', r'⋆', + r'⋇', r'⋉', r'⋊', r'⋋', r'⋌', r'⋏', r'⋒', r'⟑', r'⦸', r'⦼', r'⦾', r'⦿', r'⧶', r'⧷', + r'⨇', r'⨰', r'⨱', r'⨲', r'⨳', r'⨴', r'⨵', r'⨶', r'⨷', r'⨸', r'⨻', r'⨼', r'⨽', r'⩀', + r'⩃', r'⩄', r'⩋', r'⩍', r'⩎', r'⩑', r'⩓', r'⩕', r'⩘', r'⩚', r'⩜', r'⩞', r'⩟', r'⩠', + r'⫛', r'⊍', r'▷', r'⨝', r'⟕', r'⟖', r'⟗', r'⨟', + # prec-rational, prec-bitshift + '//', '>>', '<<', '>>>', + # prec-power + r'^', r'↑', r'↓', r'⇵', r'⟰', r'⟱', r'⤈', r'⤉', r'⤊', r'⤋', r'⤒', r'⤓', r'⥉', r'⥌', + r'⥍', r'⥏', r'⥑', r'⥔', r'⥕', r'⥘', r'⥙', r'⥜', r'⥝', r'⥠', r'⥡', r'⥣', r'⥥', r'⥮', + r'⥯', r'↑', r'↓', + # unary-ops, excluding unary-and-binary-ops + '!', r'¬', r'√', r'∛', r'∜' +] + +# Generated with the following in Julia v1.6.0-rc1 +''' +#!/usr/bin/env julia + +import REPL.REPLCompletions +res = String["in", "isa", "where"] +for kw in collect(x.keyword for x in REPLCompletions.complete_keyword("")) + if !(contains(kw, " ") || kw == "struct") + push!(res, kw) + end +end +sort!(unique!(setdiff!(res, ["true", "false"]))) +foreach(x -> println("\'", x, "\',"), res) +''' +KEYWORD_LIST = ( + 'baremodule', + 'begin', + 'break', + 'catch', + 'ccall', + 'const', + 'continue', + 'do', + 'else', + 'elseif', + 'end', + 'export', + 'finally', + 'for', + 'function', + 'global', + 'if', + 'import', + 'in', + 'isa', + 'let', + 'local', + 'macro', + 'module', + 'quote', + 'return', + 'try', + 'using', + 'where', + 'while', +) + +# Generated with the following in Julia v1.6.0-rc1 +''' +#!/usr/bin/env julia + +import REPL.REPLCompletions +res = String[] +for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core), + REPLCompletions.completions("", 0)[1]) + try + v = eval(Symbol(compl.mod)) + if (v isa Type || v isa TypeVar) && (compl.mod != "=>") + push!(res, compl.mod) + end + catch e + end +end +sort!(unique!(res)) +foreach(x -> println("\'", x, "\',"), res) +''' +BUILTIN_LIST = ( + 'AbstractArray', + 'AbstractChannel', + 'AbstractChar', + 'AbstractDict', + 'AbstractDisplay', + 'AbstractFloat', + 'AbstractIrrational', + 'AbstractMatch', + 'AbstractMatrix', + 'AbstractPattern', + 'AbstractRange', + 'AbstractSet', + 'AbstractString', + 'AbstractUnitRange', + 'AbstractVecOrMat', + 'AbstractVector', + 'Any', + 'ArgumentError', + 'Array', + 'AssertionError', + 'BigFloat', + 'BigInt', + 'BitArray', + 'BitMatrix', + 'BitSet', + 'BitVector', + 'Bool', + 'BoundsError', + 'CapturedException', + 'CartesianIndex', + 'CartesianIndices', + 'Cchar', + 'Cdouble', + 'Cfloat', + 'Channel', + 'Char', + 'Cint', + 'Cintmax_t', + 'Clong', + 'Clonglong', + 'Cmd', + 'Colon', + 'Complex', + 'ComplexF16', + 'ComplexF32', + 'ComplexF64', + 'ComposedFunction', + 'CompositeException', + 'Condition', + 'Cptrdiff_t', + 'Cshort', + 'Csize_t', + 'Cssize_t', + 'Cstring', + 'Cuchar', + 'Cuint', + 'Cuintmax_t', + 'Culong', + 'Culonglong', + 'Cushort', + 'Cvoid', + 'Cwchar_t', + 'Cwstring', + 'DataType', + 'DenseArray', + 'DenseMatrix', + 'DenseVecOrMat', + 'DenseVector', + 'Dict', + 'DimensionMismatch', + 'Dims', + 'DivideError', + 'DomainError', + 'EOFError', + 'Enum', + 'ErrorException', + 'Exception', + 'ExponentialBackOff', + 'Expr', + 'Float16', + 'Float32', + 'Float64', + 'Function', + 'GlobalRef', + 'HTML', + 'IO', + 'IOBuffer', + 'IOContext', + 'IOStream', + 'IdDict', + 'IndexCartesian', + 'IndexLinear', + 'IndexStyle', + 'InexactError', + 'InitError', + 'Int', + 'Int128', + 'Int16', + 'Int32', + 'Int64', + 'Int8', + 'Integer', + 'InterruptException', + 'InvalidStateException', + 'Irrational', + 'KeyError', + 'LinRange', + 'LineNumberNode', + 'LinearIndices', + 'LoadError', + 'MIME', + 'Matrix', + 'Method', + 'MethodError', + 'Missing', + 'MissingException', + 'Module', + 'NTuple', + 'NamedTuple', + 'Nothing', + 'Number', + 'OrdinalRange', + 'OutOfMemoryError', + 'OverflowError', + 'Pair', + 'PartialQuickSort', + 'PermutedDimsArray', + 'Pipe', + 'ProcessFailedException', + 'Ptr', + 'QuoteNode', + 'Rational', + 'RawFD', + 'ReadOnlyMemoryError', + 'Real', + 'ReentrantLock', + 'Ref', + 'Regex', + 'RegexMatch', + 'RoundingMode', + 'SegmentationFault', + 'Set', + 'Signed', + 'Some', + 'StackOverflowError', + 'StepRange', + 'StepRangeLen', + 'StridedArray', + 'StridedMatrix', + 'StridedVecOrMat', + 'StridedVector', + 'String', + 'StringIndexError', + 'SubArray', + 'SubString', + 'SubstitutionString', + 'Symbol', + 'SystemError', + 'Task', + 'TaskFailedException', + 'Text', + 'TextDisplay', + 'Timer', + 'Tuple', + 'Type', + 'TypeError', + 'TypeVar', + 'UInt', + 'UInt128', + 'UInt16', + 'UInt32', + 'UInt64', + 'UInt8', + 'UndefInitializer', + 'UndefKeywordError', + 'UndefRefError', + 'UndefVarError', + 'Union', + 'UnionAll', + 'UnitRange', + 'Unsigned', + 'Val', + 'Vararg', + 'VecElement', + 'VecOrMat', + 'Vector', + 'VersionNumber', + 'WeakKeyDict', + 'WeakRef', +) + +# Generated with the following in Julia v1.6.0-rc1 +''' +#!/usr/bin/env julia + +import REPL.REPLCompletions +res = String["true", "false"] +for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core), + REPLCompletions.completions("", 0)[1]) + try + v = eval(Symbol(compl.mod)) + if !(v isa Function || v isa Type || v isa TypeVar || v isa Module || v isa Colon) + push!(res, compl.mod) + end + catch e + end +end +sort!(unique!(res)) +foreach(x -> println("\'", x, "\',"), res) +''' +LITERAL_LIST = ( + 'ARGS', + 'C_NULL', + 'DEPOT_PATH', + 'ENDIAN_BOM', + 'ENV', + 'Inf', + 'Inf16', + 'Inf32', + 'Inf64', + 'InsertionSort', + 'LOAD_PATH', + 'MergeSort', + 'NaN', + 'NaN16', + 'NaN32', + 'NaN64', + 'PROGRAM_FILE', + 'QuickSort', + 'RoundDown', + 'RoundFromZero', + 'RoundNearest', + 'RoundNearestTiesAway', + 'RoundNearestTiesUp', + 'RoundToZero', + 'RoundUp', + 'VERSION', + 'devnull', + 'false', + 'im', + 'missing', + 'nothing', + 'pi', + 'stderr', + 'stdin', + 'stdout', + 'true', + 'undef', + 'π', + 'ℯ', +) diff --git a/shared/package-files/7a/7afff58acaa2df9c39c795247fac78629316274f9816c9528947a79dea2bd4bc/blob b/shared/package-files/7a/7afff58acaa2df9c39c795247fac78629316274f9816c9528947a79dea2bd4bc/blob new file mode 100644 index 0000000000000000000000000000000000000000..f1e571fcf2c497f02a4942aea90d55dfcf34bf74 --- /dev/null +++ b/shared/package-files/7a/7afff58acaa2df9c39c795247fac78629316274f9816c9528947a79dea2bd4bc/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor view_as_complex(const at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7b/7b01b053add02db61779195372d3503aa6a2ef3ed0ddf4e1d047e22b90e48ec0/blob b/shared/package-files/7b/7b01b053add02db61779195372d3503aa6a2ef3ed0ddf4e1d047e22b90e48ec0/blob new file mode 100644 index 0000000000000000000000000000000000000000..58d757c1acefc3c2ef6ecb8bec01c152ea08729d --- /dev/null +++ b/shared/package-files/7b/7b01b053add02db61779195372d3503aa6a2ef3ed0ddf4e1d047e22b90e48ec0/blob @@ -0,0 +1,76 @@ +from __future__ import annotations +from collections import defaultdict +from dataclasses import dataclass + +import numpy as np +import matplotlib as mpl +from matplotlib.transforms import ScaledTranslation + +from seaborn._marks.base import ( + Mark, + Mappable, + MappableFloat, + MappableString, + MappableColor, + resolve_properties, + resolve_color, + document_properties, +) + + +@document_properties +@dataclass +class Text(Mark): + """ + A textual mark to annotate or represent data values. + + Examples + -------- + .. include:: ../docstrings/objects.Text.rst + + """ + text: MappableString = Mappable("") + color: MappableColor = Mappable("k") + alpha: MappableFloat = Mappable(1) + fontsize: MappableFloat = Mappable(rc="font.size") + halign: MappableString = Mappable("center") + valign: MappableString = Mappable("center_baseline") + offset: MappableFloat = Mappable(4) + + def _plot(self, split_gen, scales, orient): + + ax_data = defaultdict(list) + + for keys, data, ax in split_gen(): + + vals = resolve_properties(self, keys, scales) + color = resolve_color(self, keys, "", scales) + + halign = vals["halign"] + valign = vals["valign"] + fontsize = vals["fontsize"] + offset = vals["offset"] / 72 + + offset_trans = ScaledTranslation( + {"right": -offset, "left": +offset}.get(halign, 0), + {"top": -offset, "bottom": +offset, "baseline": +offset}.get(valign, 0), + ax.figure.dpi_scale_trans, + ) + + for row in data.to_dict("records"): + artist = mpl.text.Text( + x=row["x"], + y=row["y"], + text=str(row.get("text", vals["text"])), + color=color, + fontsize=fontsize, + horizontalalignment=halign, + verticalalignment=valign, + transform=ax.transData + offset_trans, + **self.artist_kws, + ) + ax.add_artist(artist) + ax_data[ax].append([row["x"], row["y"]]) + + for ax, ax_vals in ax_data.items(): + ax.update_datalim(np.array(ax_vals)) diff --git a/shared/package-files/7b/7b02d02d4a43c205483ee08ffe2bc9055d686b770708f703f2a8a8ea10694a28/blob b/shared/package-files/7b/7b02d02d4a43c205483ee08ffe2bc9055d686b770708f703f2a8a8ea10694a28/blob new file mode 100644 index 0000000000000000000000000000000000000000..4f9ac6dcd7dd31bcfb90f7543c2a5d9d633aad0b Binary files /dev/null and b/shared/package-files/7b/7b02d02d4a43c205483ee08ffe2bc9055d686b770708f703f2a8a8ea10694a28/blob differ diff --git a/shared/package-files/7b/7b0798c1f60b7da60a64ac26fbe8ba4d9420843e420b12c878cd2c79e401828e/blob b/shared/package-files/7b/7b0798c1f60b7da60a64ac26fbe8ba4d9420843e420b12c878cd2c79e401828e/blob new file mode 100644 index 0000000000000000000000000000000000000000..39cd69d5497f8b793da61a80c8926b99feb33c35 --- /dev/null +++ b/shared/package-files/7b/7b0798c1f60b7da60a64ac26fbe8ba4d9420843e420b12c878cd2c79e401828e/blob @@ -0,0 +1,626 @@ +"""Visualize cumulative SHAP values.""" + +from __future__ import annotations + +import matplotlib.cm as cm +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd + +from ..utils import hclust_ordering +from ..utils._legacy import LogitLink, convert_to_link +from . import colors +from ._labels import labels + + +def __change_shap_base_value(base_value, new_base_value, shap_values) -> np.ndarray: + """Shift SHAP base value to a new value. This function assumes that `base_value` and `new_base_value` are scalars + and that `shap_values` is a two or three dimensional array. + """ + # matrix of shap_values + if shap_values.ndim == 2: + return shap_values + (base_value - new_base_value) / shap_values.shape[1] + + # cube of shap_interaction_values + main_effects = shap_values.shape[1] + all_effects = main_effects * (main_effects + 1) // 2 + temp = (base_value - new_base_value) / all_effects / 2 # divided by 2 because interaction effects are halved + shap_values = shap_values + temp + # Add the other half to the main effects on the diagonal + idx = np.diag_indices_from(shap_values[0]) + shap_values[:, idx[0], idx[1]] += temp + return shap_values + + +def __decision_plot_matplotlib( + base_value, + cumsum, + ascending, + feature_display_count, + features, + feature_names, + highlight, + plot_color, + axis_color, + y_demarc_color, + xlim, + alpha, + color_bar, + auto_size_plot, + title, + show, + legend_labels, + legend_location, +): + """Matplotlib rendering for decision_plot()""" + # image size + row_height = 0.4 + if auto_size_plot: + plt.gcf().set_size_inches(8, feature_display_count * row_height + 1.5) + + # draw vertical line indicating center + plt.axvline(x=base_value, color="#999999", zorder=-1) + + # draw horizontal dashed lines for each feature contribution + for i in range(1, feature_display_count): + plt.axhline(y=i, color=y_demarc_color, lw=0.5, dashes=(1, 5), zorder=-1) + + # initialize highlighting + linestyle = np.array("-", dtype=object) + linestyle = np.repeat(linestyle, cumsum.shape[0]) + linewidth = np.repeat(1, cumsum.shape[0]) + if highlight is not None: + linestyle[highlight] = "-." + linewidth[highlight] = 2 + + # plot each observation's cumulative SHAP values. + ax = plt.gca() + ax.set_xlim(xlim) + m = cm.ScalarMappable(cmap=plot_color) + m.set_clim(xlim) + y_pos = np.arange(0, feature_display_count + 1) + lines = [] + for i in range(cumsum.shape[0]): + o = plt.plot( + cumsum[i, :], y_pos, color=m.to_rgba(cumsum[i, -1], alpha), linewidth=linewidth[i], linestyle=linestyle[i] + ) + lines.append(o[0]) + + # determine font size. if ' *\n' character sequence is found (as in interaction labels), use a smaller + # font. we don't shrink the font for all interaction plots because if an interaction term is not + # in the display window there is no need to shrink the font. + s = next((s for s in feature_names if " *\n" in s), None) + fontsize = 13 if s is None else 9 + + # if there is a single observation and feature values are supplied, print them. + if (cumsum.shape[0] == 1) and (features is not None): + renderer = plt.gcf().canvas.get_renderer() # type: ignore + inverter = plt.gca().transData.inverted() + y_pos = y_pos + 0.5 + for i in range(feature_display_count): + v = features[0, i] + if isinstance(v, str): + v = f"({str(v).strip()})" + else: + v = "({})".format(f"{v:,.3f}".rstrip("0").rstrip(".")) + t = ax.text( + np.max(cumsum[0, i : (i + 2)]), + y_pos[i], + " " + v, + fontsize=fontsize, + horizontalalignment="left", + verticalalignment="center_baseline", + color="#666666", + ) + bb = inverter.transform_bbox(t.get_window_extent(renderer=renderer)) + if bb.xmax > xlim[1]: + t.set_text(v + " ") + t.set_x(np.min(cumsum[0, i : (i + 2)])) + t.set_horizontalalignment("right") + bb = inverter.transform_bbox(t.get_window_extent(renderer=renderer)) + if bb.xmin < xlim[0]: + t.set_text(v) + t.set_x(xlim[0]) + t.set_horizontalalignment("left") + + # style axes + ax.xaxis.set_ticks_position("both") + ax.yaxis.set_ticks_position("none") + ax.spines["right"].set_visible(False) + ax.spines["left"].set_visible(False) + ax.tick_params(color=axis_color, labelcolor=axis_color, labeltop=True) + plt.yticks(np.arange(feature_display_count) + 0.5, feature_names, fontsize=fontsize) + ax.tick_params("x", labelsize=11) + plt.ylim(0, feature_display_count) + plt.xlabel(labels["MODEL_OUTPUT"], fontsize=13) + + # draw the color bar - must come after axes styling + if color_bar: + m = cm.ScalarMappable(cmap=plot_color) + m.set_array(np.array([0, 1])) + + # place the colorbar + plt.ylim(0, feature_display_count + 0.25) + ax_cb = ax.inset_axes((xlim[0], feature_display_count, xlim[1] - xlim[0], 0.25), transform=ax.transData) + cb = plt.colorbar(m, ticks=[0, 1], orientation="horizontal", cax=ax_cb) + cb.set_ticklabels([]) + cb.ax.tick_params(labelsize=11, length=0) + cb.set_alpha(alpha) + cb.outline.set_visible(False) # type: ignore + + # re-activate the main axis for drawing. + plt.sca(ax) + + if title: + # TODO decide on style/size + plt.title(title) + + if ascending: + plt.gca().invert_yaxis() + + if legend_labels is not None: + ax.legend(handles=lines, labels=legend_labels, loc=legend_location) + + if show: + plt.show() + + +class DecisionPlotResult: + """The optional return value of decision_plot. + + The class attributes can be used to apply the same scale and feature ordering to other decision plots. + """ + + def __init__(self, base_value, shap_values, feature_names, feature_idx, xlim): + """Example + ------- + Plot two decision plots using the same feature order and x-axis. + >>> range1, range2 = range(20), range(20, 40) + >>> r = decision_plot(base, shap_values[range1], features[range1], return_objects=True) + >>> decision_plot(base, shap_values[range2], features[range2], feature_order=r.feature_idx, xlim=r.xlim) + + Parameters + ---------- + base_value : float + The base value used in the plot. For multioutput models, + this will be the mean of the base values. This will inherit `new_base_value` if specified. + + shap_values : numpy.ndarray + The `shap_values` passed to decision_plot re-ordered based on `feature_order`. If SHAP interaction values + are passed to decision_plot, `shap_values` is a 2D (matrix) representation of the interactions. See + `feature_names` to locate the feature positions. If `new_base_value` is specified, the SHAP values are + relative to the new base value. + + feature_names : list of str + The feature names used in the plot in the order specified in the decision_plot parameter `feature_order`. + + feature_idx : numpy.ndarray + The index used to order `shap_values` based on `feature_order`. This attribute can be used to specify + identical feature ordering in multiple decision plots. + + xlim : tuple[float, float] + The x-axis limits. This attributed can be used to specify the same x-axis in multiple decision plots. + + """ + self.base_value = base_value + self.shap_values = shap_values + self.feature_names = feature_names + self.feature_idx = feature_idx + self.xlim = xlim + + +def decision( + base_value: float | np.ndarray, + shap_values: np.ndarray, + features: np.ndarray | pd.Series | pd.DataFrame | list | None = None, + feature_names=None, + feature_order="importance", + feature_display_range=None, + highlight=None, + link="identity", + plot_color=None, + axis_color="#333333", + y_demarc_color="#333333", + alpha=None, + color_bar=True, + auto_size_plot=True, + title=None, + xlim=None, + show=True, + return_objects=False, + ignore_warnings=False, + new_base_value=None, + legend_labels=None, + legend_location="best", +) -> DecisionPlotResult | None: + """Visualize model decisions using cumulative SHAP values. + + Each plotted line explains a single model prediction. If a single prediction is plotted, feature values will be + printed in the plot (if supplied). If multiple predictions are plotted together, feature values will not be printed. + Plotting too many predictions together will make the plot unintelligible. + + Parameters + ---------- + base_value : float or numpy.ndarray + This is the reference value that the feature contributions start from. Usually, this is + ``explainer.expected_value``. + + shap_values : numpy.ndarray + Matrix of SHAP values (# features) or (# samples x # features) from + ``explainer.shap_values()``. Or cube of SHAP interaction values (# samples x + # features x # features) from ``explainer.shap_interaction_values()``. + + features : numpy.array or pandas.Series or pandas.DataFrame or numpy.ndarray or list + Matrix of feature values (# features) or (# samples x # features). This provides the values of all the + features and, optionally, the feature names. + + feature_names : list or numpy.ndarray + List of feature names (# features). If ``None``, names may be derived from the + ``features`` argument if a Pandas object is provided. Otherwise, numeric feature + names will be generated. + + feature_order : str or None or list or numpy.ndarray + Any of "importance" (the default), "hclust" (hierarchical clustering), ``None``, + or a list/array of indices. + + feature_display_range: slice or range + The slice or range of features to plot after ordering features by ``feature_order``. A step of 1 or ``None`` + will display the features in ascending order. A step of -1 will display the features in descending order. If + ``feature_display_range=None``, ``slice(-1, -21, -1)`` is used (i.e. show the last 20 features in descending order). + If ``shap_values`` contains interaction values, the number of features is automatically expanded to include all + possible interactions: N(N + 1)/2 where N = ``shap_values.shape[1]``. + + highlight : Any + Specify which observations to draw in a different line style. All numpy indexing methods are supported. For + example, list of integer indices, or a bool array. + + link : str + Use "identity" or "logit" to specify the transformation used for the x-axis. The "logit" link transforms + log-odds into probabilities. + + plot_color : str or matplotlib.colors.ColorMap + Color spectrum used to draw the plot lines. If ``str``, a registered matplotlib color name is assumed. + + axis_color : str or int + Color used to draw plot axes. + + y_demarc_color : str or int + Color used to draw feature demarcation lines on the y-axis. + + alpha : float + Alpha blending value in [0, 1] used to draw plot lines. + + color_bar : bool + Whether to draw the color bar (legend). + + auto_size_plot : bool + Whether to automatically size the matplotlib plot to fit the number of features + displayed. If ``False``, specify the plot size using matplotlib before calling + this function. + + title : str + Title of the plot. + + xlim: tuple[float, float] + The extents of the x-axis (e.g. ``(-1.0, 1.0)``). If not specified, the limits + are determined by the maximum/minimum predictions centered around base_value + when ``link="identity"``. When ``link="logit"``, the x-axis extents are ``(0, + 1)`` centered at 0.5. ``xlim`` values are not transformed by the ``link`` + function. This argument is provided to simplify producing multiple plots on the + same scale for comparison. + + show : bool + Whether :external+mpl:func:`matplotlib.pyplot.show()` is called before returning. + Setting this to ``False`` allows the plot + to be customized further after it has been created. + + return_objects : bool + Whether to return a :obj:`DecisionPlotResult` object containing various plotting + features. This can be used to generate multiple decision plots using the same + feature ordering and scale. + + ignore_warnings : bool + Plotting many data points or too many features at a time may be slow, or may create very large plots. Set + this argument to ``True`` to override hard-coded limits that prevent plotting large amounts of data. + + new_base_value : float + SHAP values are relative to a base value. By default, this base value is the + expected value of the model's raw predictions. Use ``new_base_value`` to shift + the base value to an arbitrary value (e.g. the cutoff point for a binary + classification task). + + legend_labels : list of str + List of legend labels. If ``None``, legend will not be shown. + + legend_location : str + Legend location. Any of "best", "upper right", "upper left", "lower left", "lower right", "right", + "center left", "center right", "lower center", "upper center", "center". + + Returns + ------- + DecisionPlotResult or None + Returns a :obj:`DecisionPlotResult` object if ``return_objects=True``. Returns ``None`` otherwise (the default). + + Examples + -------- + Plot two decision plots using the same feature order and x-axis. + + >>> range1, range2 = range(20), range(20, 40) + >>> r = decision_plot(base, shap_values[range1], features[range1], return_objects=True) + >>> decision_plot(base, shap_values[range2], features[range2], feature_order=r.feature_idx, xlim=r.xlim) + + See more `decision plot examples here `_. + + """ + # code taken from force_plot. auto unwrap the base_value + if isinstance(base_value, np.ndarray) and len(base_value) == 1: + base_value = base_value[0] + + if isinstance(base_value, list) or isinstance(shap_values, list): + raise TypeError( + "Looks like multi output. Try base_value[i] and shap_values[i], or use shap.multioutput_decision_plot()." + ) + + # validate shap_values + if not isinstance(shap_values, np.ndarray): + raise TypeError("The shap_values arg is the wrong type. Try explainer.shap_values().") + + # calculate the various dimensions involved (observations, features, interactions, display, etc. + if shap_values.ndim == 1: + shap_values = shap_values.reshape(1, -1) + observation_count = shap_values.shape[0] + feature_count = shap_values.shape[1] + + # code taken from force_plot. convert features from other types. + if isinstance(features, pd.DataFrame): + if feature_names is None: + feature_names = features.columns.to_list() + features = features.values + elif isinstance(features, pd.Series): + if feature_names is None: + feature_names = features.index.to_list() + features = features.values + elif isinstance(features, list): + if feature_names is None: + feature_names = features + features = None + elif features is not None and features.ndim == 1 and feature_names is None: + feature_names = features.tolist() + features = None + + # the above code converts features to either None or np.ndarray. if features is something else at this point, + # there's a problem. + if not isinstance(features, (np.ndarray, type(None))): + raise TypeError("The features arg uses an unsupported type.") + if (features is not None) and (features.ndim == 1): + features = features.reshape(1, -1) + + # validate/generate feature_names. at this point, feature_names does not include interactions. + if feature_names is None: + feature_names = [labels["FEATURE"] % str(i) for i in range(feature_count)] + elif len(feature_names) != feature_count: + raise ValueError("The feature_names arg must include all features represented in shap_values.") + elif not isinstance(feature_names, (list, np.ndarray)): + raise TypeError("The feature_names arg requires a list or numpy array.") + + # transform interactions cube to a matrix and generate interaction names. + if shap_values.ndim == 3: + # flatten + triu_count = feature_count * (feature_count - 1) // 2 + idx_diag = np.diag_indices_from(shap_values[0]) + idx_triu = np.triu_indices_from(shap_values[0], 1) + a: np.ndarray = np.ndarray((observation_count, feature_count + triu_count), shap_values.dtype) + a[:, :feature_count] = shap_values[:, idx_diag[0], idx_diag[1]] + a[:, feature_count:] = shap_values[:, idx_triu[0], idx_triu[1]] * 2 + shap_values = a + # names + b: list[str | None] = [None] * shap_values.shape[1] + b[:feature_count] = feature_names + for i, row, col in zip(range(feature_count, shap_values.shape[1]), idx_triu[0], idx_triu[1]): + b[i] = f"{feature_names[row]} *\n{feature_names[col]}" + feature_names = b + feature_count = shap_values.shape[1] + features = None # Can't use feature values for interactions... + + # determine feature order + if isinstance(feature_order, list): + feature_idx = np.array(feature_order) + elif isinstance(feature_order, np.ndarray): + feature_idx = feature_order + elif (feature_order is None) or (feature_order.lower() == "none"): + feature_idx = np.arange(feature_count) + elif feature_order == "importance": + feature_idx = np.argsort(np.sum(np.abs(shap_values), axis=0)) + elif feature_order == "hclust": + feature_idx = np.array(hclust_ordering(shap_values.transpose())) + else: + raise ValueError( + "The feature_order arg requires 'importance', 'hclust', 'none', or an integer list/array " + "of feature indices." + ) + + if (feature_idx.shape != (feature_count,)) or (not np.issubdtype(feature_idx.dtype, np.integer)): + raise ValueError( + "A list or array has been specified for the feature_order arg. The length must match the " + "feature count and the data type must be integer." + ) + + # validate and convert feature_display_range to a slice. prevents out of range errors later. + if feature_display_range is None: + feature_display_range = slice(-1, -21, -1) # show last 20 features in descending order. + elif not isinstance(feature_display_range, (slice, range)): + raise TypeError("The feature_display_range arg requires a slice or a range.") + elif feature_display_range.step not in (-1, 1, None): + raise ValueError("The feature_display_range arg supports a step of 1, -1, or None.") + elif isinstance(feature_display_range, range): + # Negative values in a range are not the same as negs in a slice. Consider range(2, -1, -1) == [2, 1, 0], + # but slice(2, -1, -1) == [] when len(features) > 2. However, range(2, -1, -1) == slice(2, -inf, -1) after + # clipping. + c = np.iinfo(np.integer).min + feature_display_range = slice( + feature_display_range.start if feature_display_range.start >= 0 else c, # should never happen, but... + feature_display_range.stop if feature_display_range.stop >= 0 else c, + feature_display_range.step, + ) + + # apply new_base_value + if new_base_value is not None: + shap_values = __change_shap_base_value(base_value, new_base_value, shap_values) + base_value = new_base_value + + # use feature_display_range to determine which features will be plotted. convert feature_display_range to + # ascending indices and expand by one in the negative direction. why? we are plotting the change in prediction + # for every feature. this requires that we include the value previous to the first displayed feature + # (i.e. i_0 - 1 to i_n). + d = feature_display_range.indices(feature_count) + ascending = True + if d[2] == -1: # The step + ascending = False + d = (d[1] + 1, d[0] + 1, 1) + feature_display_count = d[1] - d[0] + shap_values = shap_values[:, feature_idx] + if d[0] == 0: + cumsum: np.ndarray = np.ndarray((observation_count, feature_display_count + 1), shap_values.dtype) + cumsum[:, 0] = base_value + cumsum[:, 1:] = base_value + np.nancumsum(shap_values[:, 0 : d[1]], axis=1) + else: + cumsum = base_value + np.nancumsum(shap_values, axis=1)[:, (d[0] - 1) : d[1]] + + # Select and sort feature names and features according to the range selected above + feature_names = np.array(feature_names) + feature_names_display = feature_names[feature_idx[d[0] : d[1]]].tolist() + feature_names = feature_names[feature_idx].tolist() + features_display = None if features is None else features[:, feature_idx[d[0] : d[1]]] + + # throw large data errors + if not ignore_warnings: + if observation_count > 2000: + raise RuntimeError( + f"Plotting {observation_count} observations may be slow. Consider subsampling or set " + "ignore_warnings=True to ignore this message." + ) + if feature_display_count > 200: + raise RuntimeError( + f"Plotting {feature_display_count} features may create a very large plot. Set " + "ignore_warnings=True to ignore this " + "message." + ) + if feature_count * observation_count > 100000000: + raise RuntimeError( + f"Processing SHAP values for {feature_count} features over {observation_count} observations may be slow. Set " + "ignore_warnings=True to ignore this " + "message." + ) + + # convert values based on link and update x-axis extents + create_xlim = xlim is None + link = convert_to_link(link) + base_value_saved = base_value + if isinstance(link, LogitLink): + base_value = link.finv(base_value) + cumsum = link.finv(cumsum) + if create_xlim: + # Expand [0, 1] limits a little for a visual margin + xlim = (-0.02, 1.02) + elif create_xlim: + xmin: float = min((cumsum.min(), base_value)) + xmax: float = max((cumsum.max(), base_value)) + # create a symmetric axis around base_value + n, m = (base_value - xmin), (xmax - base_value) + if n > m: + xlim = (base_value - n, base_value + m) + else: + xlim = (base_value - m, base_value + m) + # Adjust xlim to include a little visual margin. + e = (xlim[1] - xlim[0]) * 0.02 + xlim = (xlim[0] - e, xlim[1] + e) + + # Initialize style arguments + if alpha is None: + alpha = 1.0 + + if plot_color is None: + plot_color = colors.red_blue + + __decision_plot_matplotlib( + base_value, + cumsum, + ascending, + feature_display_count, + features_display, + feature_names_display, + highlight, + plot_color, + axis_color, + y_demarc_color, + xlim, + alpha, + color_bar, + auto_size_plot, + title, + show, + legend_labels, + legend_location, + ) + + if not return_objects: + return None + + return DecisionPlotResult(base_value_saved, shap_values, feature_names, feature_idx, xlim) + + +def multioutput_decision(base_values, shap_values, row_index, **kwargs) -> DecisionPlotResult | None: + """Decision plot for multioutput models. + + Plots all outputs for a single observation. By default, the plotted base value will be the mean of base_values + unless new_base_value is specified. Supports both SHAP values and SHAP interaction values. + + Parameters + ---------- + base_values : list of float + This is the reference value that the feature contributions start from. Use explainer.expected_value. + + shap_values : list of numpy.ndarray + A multioutput list of SHAP matrices or SHAP cubes from explainer.shap_values() or + explainer.shap_interaction_values(), respectively. + + row_index : int + The integer index of the row to plot. + + **kwargs : Any + Arguments to be passed on to decision_plot(). + + Returns + ------- + DecisionPlotResult or None + Returns a DecisionPlotResult object if `return_objects=True`. Returns `None` otherwise (the default). + + """ + # todo: adjust to breaking changes made in #3318 + if not (isinstance(base_values, list) and isinstance(shap_values, list)): + raise ValueError("The base_values and shap_values args expect lists.") + + # convert arguments to arrays for simpler handling + base_values = np.array(base_values) + if not ((base_values.ndim == 1) or (np.issubdtype(base_values.dtype, np.number))): + raise ValueError("The base_values arg should be a list of scalars.") + shap_values = np.array(shap_values) + if shap_values.ndim not in [3, 4]: + raise ValueError("The shap_values arg should be a list of two or three dimensional SHAP arrays.") + if shap_values.shape[0] != base_values.shape[0]: + raise ValueError("The base_values output length is different than shap_values.") + + # shift shap base values to mean of base values + base_values_mean = base_values.mean() + for i in range(shap_values.shape[0]): + shap_values[i] = __change_shap_base_value(base_values[i], base_values_mean, shap_values[i]) + + # select the feature row corresponding to row_index + if (kwargs is not None) and ("features" in kwargs): + features = kwargs["features"] + if isinstance(features, np.ndarray) and (features.ndim == 2): + kwargs["features"] = features[[row_index]] + elif isinstance(features, pd.DataFrame): + kwargs["features"] = features.iloc[row_index] + + return decision(base_values_mean, shap_values[:, row_index, :], **kwargs) diff --git a/shared/package-files/7b/7b085d5d8a0dd0facea1cec941d4fe50e10da87cac358da9e6556a88e0694adb/blob b/shared/package-files/7b/7b085d5d8a0dd0facea1cec941d4fe50e10da87cac358da9e6556a88e0694adb/blob new file mode 100644 index 0000000000000000000000000000000000000000..b404e6115e93d3d4a8f09e61006f6a1400e48a4f --- /dev/null +++ b/shared/package-files/7b/7b085d5d8a0dd0facea1cec941d4fe50e10da87cac358da9e6556a88e0694adb/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API int64_t _debug_has_internal_overlap(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/7b/7b097082e7d0b480ae972a3140e2ec3ddbd4b5e8ae81dbfd11005c69e7939c38/blob b/shared/package-files/7b/7b097082e7d0b480ae972a3140e2ec3ddbd4b5e8ae81dbfd11005c69e7939c38/blob new file mode 100644 index 0000000000000000000000000000000000000000..82e8e3ad17786852a63b430775474fc077c689c1 --- /dev/null +++ b/shared/package-files/7b/7b097082e7d0b480ae972a3140e2ec3ddbd4b5e8ae81dbfd11005c69e7939c38/blob @@ -0,0 +1,30 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::vector _foreach_add(at::TensorList self, const at::Scalar & scalar); +TORCH_API void _foreach_add_(at::TensorList self, const at::Scalar & scalar); +TORCH_API ::std::vector _foreach_add(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1); +TORCH_API void _foreach_add_(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1); +TORCH_API ::std::vector _foreach_add(at::TensorList self, at::ArrayRef scalars); +TORCH_API void _foreach_add_(at::TensorList self, at::ArrayRef scalars); +TORCH_API ::std::vector _foreach_add(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1); +TORCH_API void _foreach_add_(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7b/7b0b89898b83f55236c2e1598838c66153fb82794fe07f6e5459e38de956e795/blob b/shared/package-files/7b/7b0b89898b83f55236c2e1598838c66153fb82794fe07f6e5459e38de956e795/blob new file mode 100644 index 0000000000000000000000000000000000000000..bc3b939734534520f0cf7051dbc72989d0caf990 --- /dev/null +++ b/shared/package-files/7b/7b0b89898b83f55236c2e1598838c66153fb82794fe07f6e5459e38de956e795/blob @@ -0,0 +1,156 @@ +import numpy as np + +from pandas import ( + DataFrame, + Index, + MultiIndex, + RangeIndex, + Series, +) +import pandas._testing as tm +from pandas.tests.copy_view.util import get_array + +# ----------------------------------------------------------------------------- +# Copy/view behaviour for the values that are set in a DataFrame + + +def test_set_column_with_array(): + # Case: setting an array as a new column (df[col] = arr) copies that data + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + arr = np.array([1, 2, 3], dtype="int64") + + df["c"] = arr + + # the array data is copied + assert not np.shares_memory(get_array(df, "c"), arr) + # and thus modifying the array does not modify the DataFrame + arr[0] = 0 + tm.assert_series_equal(df["c"], Series([1, 2, 3], name="c")) + + +def test_set_column_with_series(using_copy_on_write): + # Case: setting a series as a new column (df[col] = s) copies that data + # (with delayed copy with CoW) + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + ser = Series([1, 2, 3]) + + df["c"] = ser + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "c"), get_array(ser)) + else: + # the series data is copied + assert not np.shares_memory(get_array(df, "c"), get_array(ser)) + + # and modifying the series does not modify the DataFrame + ser.iloc[0] = 0 + assert ser.iloc[0] == 0 + tm.assert_series_equal(df["c"], Series([1, 2, 3], name="c")) + + +def test_set_column_with_index(using_copy_on_write): + # Case: setting an index as a new column (df[col] = idx) copies that data + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + idx = Index([1, 2, 3]) + + df["c"] = idx + + # the index data is copied + assert not np.shares_memory(get_array(df, "c"), idx.values) + + idx = RangeIndex(1, 4) + arr = idx.values + + df["d"] = idx + + assert not np.shares_memory(get_array(df, "d"), arr) + + +def test_set_columns_with_dataframe(using_copy_on_write): + # Case: setting a DataFrame as new columns copies that data + # (with delayed copy with CoW) + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df2 = DataFrame({"c": [7, 8, 9], "d": [10, 11, 12]}) + + df[["c", "d"]] = df2 + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + else: + # the data is copied + assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + + # and modifying the set DataFrame does not modify the original DataFrame + df2.iloc[0, 0] = 0 + tm.assert_series_equal(df["c"], Series([7, 8, 9], name="c")) + + +def test_setitem_series_no_copy(using_copy_on_write): + # Case: setting a Series as column into a DataFrame can delay copying that data + df = DataFrame({"a": [1, 2, 3]}) + rhs = Series([4, 5, 6]) + rhs_orig = rhs.copy() + + # adding a new column + df["b"] = rhs + if using_copy_on_write: + assert np.shares_memory(get_array(rhs), get_array(df, "b")) + + df.iloc[0, 1] = 100 + tm.assert_series_equal(rhs, rhs_orig) + + +def test_setitem_series_no_copy_single_block(using_copy_on_write): + # Overwriting an existing column that is a single block + df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]}) + rhs = Series([4, 5, 6]) + rhs_orig = rhs.copy() + + df["a"] = rhs + if using_copy_on_write: + assert np.shares_memory(get_array(rhs), get_array(df, "a")) + + df.iloc[0, 0] = 100 + tm.assert_series_equal(rhs, rhs_orig) + + +def test_setitem_series_no_copy_split_block(using_copy_on_write): + # Overwriting an existing column that is part of a larger block + df = DataFrame({"a": [1, 2, 3], "b": 1}) + rhs = Series([4, 5, 6]) + rhs_orig = rhs.copy() + + df["b"] = rhs + if using_copy_on_write: + assert np.shares_memory(get_array(rhs), get_array(df, "b")) + + df.iloc[0, 1] = 100 + tm.assert_series_equal(rhs, rhs_orig) + + +def test_setitem_series_column_midx_broadcasting(using_copy_on_write): + # Setting a Series to multiple columns will repeat the data + # (currently copying the data eagerly) + df = DataFrame( + [[1, 2, 3], [3, 4, 5]], + columns=MultiIndex.from_arrays([["a", "a", "b"], [1, 2, 3]]), + ) + rhs = Series([10, 11]) + df["a"] = rhs + assert not np.shares_memory(get_array(rhs), df._get_column_array(0)) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + + +def test_set_column_with_inplace_operator(using_copy_on_write, warn_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + + # this should not raise any warning + with tm.assert_produces_warning(None): + df["a"] += 1 + + # when it is not in a chain, then it should produce a warning + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + ser = df["a"] + with tm.assert_cow_warning(warn_copy_on_write): + ser += 1 diff --git a/shared/package-files/7b/7b0c04b9e8a8d42d977874ef4f5ee7f1d6542603afc82582b7459534b0a53fda/blob b/shared/package-files/7b/7b0c04b9e8a8d42d977874ef4f5ee7f1d6542603afc82582b7459534b0a53fda/blob new file mode 100644 index 0000000000000000000000000000000000000000..5bad85fdc1cd08553756d0fb2c7be8b5ad6af7fb --- /dev/null +++ b/shared/package-files/7b/7b0c04b9e8a8d42d977874ef4f5ee7f1d6542603afc82582b7459534b0a53fda/blob @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/shared/package-files/7b/7b0c589d4942caf685e5c78ca738a2cf87ba1408249f33f9702d5956f43f60b1/blob b/shared/package-files/7b/7b0c589d4942caf685e5c78ca738a2cf87ba1408249f33f9702d5956f43f60b1/blob new file mode 100644 index 0000000000000000000000000000000000000000..13517e0f6dd3cba0362ea5daa148e3d03f23dfd5 --- /dev/null +++ b/shared/package-files/7b/7b0c589d4942caf685e5c78ca738a2cf87ba1408249f33f9702d5956f43f60b1/blob @@ -0,0 +1,350 @@ +from sympy.concrete.summations import (Sum, summation) +from sympy.core.basic import Basic +from sympy.core.cache import cacheit +from sympy.core.function import Lambda +from sympy.core.numbers import I +from sympy.core.relational import (Eq, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, symbols) +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.integers import floor +from sympy.functions.elementary.piecewise import Piecewise +from sympy.logic.boolalg import And +from sympy.polys.polytools import poly +from sympy.series.series import series + +from sympy.polys.polyerrors import PolynomialError +from sympy.stats.crv import reduce_rational_inequalities_wrap +from sympy.stats.rv import (NamedArgsMixin, SinglePSpace, SingleDomain, + random_symbols, PSpace, ConditionalDomain, RandomDomain, + ProductDomain, Distribution) +from sympy.stats.symbolic_probability import Probability +from sympy.sets.fancysets import Range, FiniteSet +from sympy.sets.sets import Union +from sympy.sets.contains import Contains +from sympy.utilities import filldedent +from sympy.core.sympify import _sympify + + +class DiscreteDistribution(Distribution): + def __call__(self, *args): + return self.pdf(*args) + + +class SingleDiscreteDistribution(DiscreteDistribution, NamedArgsMixin): + """ Discrete distribution of a single variable. + + Serves as superclass for PoissonDistribution etc.... + + Provides methods for pdf, cdf, and sampling + + See Also: + sympy.stats.crv_types.* + """ + + set = S.Integers + + def __new__(cls, *args): + args = list(map(sympify, args)) + return Basic.__new__(cls, *args) + + @staticmethod + def check(*args): + pass + + @cacheit + def compute_cdf(self, **kwargs): + """ Compute the CDF from the PDF. + + Returns a Lambda. + """ + x = symbols('x', integer=True, cls=Dummy) + z = symbols('z', real=True, cls=Dummy) + left_bound = self.set.inf + + # CDF is integral of PDF from left bound to z + pdf = self.pdf(x) + cdf = summation(pdf, (x, left_bound, floor(z)), **kwargs) + # CDF Ensure that CDF left of left_bound is zero + cdf = Piecewise((cdf, z >= left_bound), (0, True)) + return Lambda(z, cdf) + + def _cdf(self, x): + return None + + def cdf(self, x, **kwargs): + """ Cumulative density function """ + if not kwargs: + cdf = self._cdf(x) + if cdf is not None: + return cdf + return self.compute_cdf(**kwargs)(x) + + @cacheit + def compute_characteristic_function(self, **kwargs): + """ Compute the characteristic function from the PDF. + + Returns a Lambda. + """ + x, t = symbols('x, t', real=True, cls=Dummy) + pdf = self.pdf(x) + cf = summation(exp(I*t*x)*pdf, (x, self.set.inf, self.set.sup)) + return Lambda(t, cf) + + def _characteristic_function(self, t): + return None + + def characteristic_function(self, t, **kwargs): + """ Characteristic function """ + if not kwargs: + cf = self._characteristic_function(t) + if cf is not None: + return cf + return self.compute_characteristic_function(**kwargs)(t) + + @cacheit + def compute_moment_generating_function(self, **kwargs): + t = Dummy('t', real=True) + x = Dummy('x', integer=True) + pdf = self.pdf(x) + mgf = summation(exp(t*x)*pdf, (x, self.set.inf, self.set.sup)) + return Lambda(t, mgf) + + def _moment_generating_function(self, t): + return None + + def moment_generating_function(self, t, **kwargs): + if not kwargs: + mgf = self._moment_generating_function(t) + if mgf is not None: + return mgf + return self.compute_moment_generating_function(**kwargs)(t) + + @cacheit + def compute_quantile(self, **kwargs): + """ Compute the Quantile from the PDF. + + Returns a Lambda. + """ + x = Dummy('x', integer=True) + p = Dummy('p', real=True) + left_bound = self.set.inf + pdf = self.pdf(x) + cdf = summation(pdf, (x, left_bound, x), **kwargs) + set = ((x, p <= cdf), ) + return Lambda(p, Piecewise(*set)) + + def _quantile(self, x): + return None + + def quantile(self, x, **kwargs): + """ Cumulative density function """ + if not kwargs: + quantile = self._quantile(x) + if quantile is not None: + return quantile + return self.compute_quantile(**kwargs)(x) + + def expectation(self, expr, var, evaluate=True, **kwargs): + """ Expectation of expression over distribution """ + # TODO: support discrete sets with non integer stepsizes + + if evaluate: + try: + p = poly(expr, var) + + t = Dummy('t', real=True) + + mgf = self.moment_generating_function(t) + deg = p.degree() + taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t) + result = 0 + for k in range(deg+1): + result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k) + + return result + + except PolynomialError: + return summation(expr * self.pdf(var), + (var, self.set.inf, self.set.sup), **kwargs) + + else: + return Sum(expr * self.pdf(var), + (var, self.set.inf, self.set.sup), **kwargs) + + def __call__(self, *args): + return self.pdf(*args) + + +class DiscreteDomain(RandomDomain): + """ + A domain with discrete support with step size one. + Represented using symbols and Range. + """ + is_Discrete = True + +class SingleDiscreteDomain(DiscreteDomain, SingleDomain): + def as_boolean(self): + return Contains(self.symbol, self.set) + + +class ConditionalDiscreteDomain(DiscreteDomain, ConditionalDomain): + """ + Domain with discrete support of step size one, that is restricted by + some condition. + """ + @property + def set(self): + rv = self.symbols + if len(self.symbols) > 1: + raise NotImplementedError(filldedent(''' + Multivariate conditional domains are not yet implemented.''')) + rv = list(rv)[0] + return reduce_rational_inequalities_wrap(self.condition, + rv).intersect(self.fulldomain.set) + + +class DiscretePSpace(PSpace): + is_real = True + is_Discrete = True + + @property + def pdf(self): + return self.density(*self.symbols) + + def where(self, condition): + rvs = random_symbols(condition) + assert all(r.symbol in self.symbols for r in rvs) + if len(rvs) > 1: + raise NotImplementedError(filldedent('''Multivariate discrete + random variables are not yet supported.''')) + conditional_domain = reduce_rational_inequalities_wrap(condition, + rvs[0]) + conditional_domain = conditional_domain.intersect(self.domain.set) + return SingleDiscreteDomain(rvs[0].symbol, conditional_domain) + + def probability(self, condition): + complement = isinstance(condition, Ne) + if complement: + condition = Eq(condition.args[0], condition.args[1]) + try: + _domain = self.where(condition).set + if condition == False or _domain is S.EmptySet: + return S.Zero + if condition == True or _domain == self.domain.set: + return S.One + prob = self.eval_prob(_domain) + except NotImplementedError: + from sympy.stats.rv import density + expr = condition.lhs - condition.rhs + dens = density(expr) + if not isinstance(dens, DiscreteDistribution): + from sympy.stats.drv_types import DiscreteDistributionHandmade + dens = DiscreteDistributionHandmade(dens) + z = Dummy('z', real=True) + space = SingleDiscretePSpace(z, dens) + prob = space.probability(condition.__class__(space.value, 0)) + if prob is None: + prob = Probability(condition) + return prob if not complement else S.One - prob + + def eval_prob(self, _domain): + sym = list(self.symbols)[0] + if isinstance(_domain, Range): + n = symbols('n', integer=True) + inf, sup, step = (r for r in _domain.args) + summand = ((self.pdf).replace( + sym, n*step)) + rv = summation(summand, + (n, inf/step, (sup)/step - 1)).doit() + return rv + elif isinstance(_domain, FiniteSet): + pdf = Lambda(sym, self.pdf) + rv = sum(pdf(x) for x in _domain) + return rv + elif isinstance(_domain, Union): + rv = sum(self.eval_prob(x) for x in _domain.args) + return rv + + def conditional_space(self, condition): + # XXX: Converting from set to tuple. The order matters to Lambda + # though so we should be starting with a set... + density = Lambda(tuple(self.symbols), self.pdf/self.probability(condition)) + condition = condition.xreplace({rv: rv.symbol for rv in self.values}) + domain = ConditionalDiscreteDomain(self.domain, condition) + return DiscretePSpace(domain, density) + +class ProductDiscreteDomain(ProductDomain, DiscreteDomain): + def as_boolean(self): + return And(*[domain.as_boolean for domain in self.domains]) + +class SingleDiscretePSpace(DiscretePSpace, SinglePSpace): + """ Discrete probability space over a single univariate variable """ + is_real = True + + @property + def set(self): + return self.distribution.set + + @property + def domain(self): + return SingleDiscreteDomain(self.symbol, self.set) + + def sample(self, size=(), library='scipy', seed=None): + """ + Internal sample method. + + Returns dictionary mapping RandomSymbol to realization value. + """ + return {self.value: self.distribution.sample(size, library=library, seed=seed)} + + def compute_expectation(self, expr, rvs=None, evaluate=True, **kwargs): + rvs = rvs or (self.value,) + if self.value not in rvs: + return expr + + expr = _sympify(expr) + expr = expr.xreplace({rv: rv.symbol for rv in rvs}) + + x = self.value.symbol + try: + return self.distribution.expectation(expr, x, evaluate=evaluate, + **kwargs) + except NotImplementedError: + return Sum(expr * self.pdf, (x, self.set.inf, self.set.sup), + **kwargs) + + def compute_cdf(self, expr, **kwargs): + if expr == self.value: + x = Dummy("x", real=True) + return Lambda(x, self.distribution.cdf(x, **kwargs)) + else: + raise NotImplementedError() + + def compute_density(self, expr, **kwargs): + if expr == self.value: + return self.distribution + raise NotImplementedError() + + def compute_characteristic_function(self, expr, **kwargs): + if expr == self.value: + t = Dummy("t", real=True) + return Lambda(t, self.distribution.characteristic_function(t, **kwargs)) + else: + raise NotImplementedError() + + def compute_moment_generating_function(self, expr, **kwargs): + if expr == self.value: + t = Dummy("t", real=True) + return Lambda(t, self.distribution.moment_generating_function(t, **kwargs)) + else: + raise NotImplementedError() + + def compute_quantile(self, expr, **kwargs): + if expr == self.value: + p = Dummy("p", real=True) + return Lambda(p, self.distribution.quantile(p, **kwargs)) + else: + raise NotImplementedError() diff --git a/shared/package-files/7b/7b0d5f26983cd46a586dd92ba7823b9ed59d6e19037a0e5f367d52ae9176e789/blob b/shared/package-files/7b/7b0d5f26983cd46a586dd92ba7823b9ed59d6e19037a0e5f367d52ae9176e789/blob new file mode 100644 index 0000000000000000000000000000000000000000..1bb27dbfd53902914177ee7fb24a21402b9ae3d3 --- /dev/null +++ b/shared/package-files/7b/7b0d5f26983cd46a586dd92ba7823b9ed59d6e19037a0e5f367d52ae9176e789/blob @@ -0,0 +1,72 @@ +import logging + +log = logging.getLogger("fontTools.varLib.avar") + + +def main(args=None): + from fontTools.ttLib import TTFont + from fontTools.misc.cliTools import makeOutputFileName + from fontTools import configLogger + import argparse + import sys + + print( + "WARNING: This script is deprecated. Use `fonttools varLib.avar.build` " + "or `fonttools varLib.avar.unbuild` instead.\n", + file=sys.stderr, + ) + + if args is None: + args = sys.argv[1:] + + parser = argparse.ArgumentParser( + "fonttools varLib.avar", + description="Add `avar` table from designspace file to variable font.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "designspace", + metavar="family.designspace", + help="Designspace file.", + nargs="?", + default=None, + ) + parser.add_argument( + "-o", + "--output-file", + type=str, + help="Output font file name.", + ) + parser.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + + options = parser.parse_args(args) + + configLogger(level=("INFO" if options.verbose else "WARNING")) + + font = TTFont(options.font) + + if options.designspace is None: + from .unbuild import unbuild + + unbuild(font) + return 0 + + from .build import build + + build(font, options.designspace) + + if options.output_file is None: + outfile = makeOutputFileName(options.font, overWrite=True, suffix=".avar") + else: + outfile = options.output_file + if outfile: + log.info("Saving %s", outfile) + font.save(outfile) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/shared/package-files/7b/7b0f4c3613d07752ec0998968859a3f4867bc8e9c0dc728e5df7c3791f57d63c/blob b/shared/package-files/7b/7b0f4c3613d07752ec0998968859a3f4867bc8e9c0dc728e5df7c3791f57d63c/blob new file mode 100644 index 0000000000000000000000000000000000000000..f4eb8039b50c21c0977a38ee5f47c8f89307d482 --- /dev/null +++ b/shared/package-files/7b/7b0f4c3613d07752ec0998968859a3f4867bc8e9c0dc728e5df7c3791f57d63c/blob @@ -0,0 +1,2079 @@ +// libdivide.h - Optimized integer division +// https://libdivide.com +// +// Copyright (C) 2010 - 2019 ridiculous_fish, +// Copyright (C) 2016 - 2019 Kim Walisch, +// +// libdivide is dual-licensed under the Boost or zlib licenses. +// You may use libdivide under the terms of either of these. +// See LICENSE.txt for more details. + +#ifndef NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_ +#define NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_ + +#define LIBDIVIDE_VERSION "3.0" +#define LIBDIVIDE_VERSION_MAJOR 3 +#define LIBDIVIDE_VERSION_MINOR 0 + +#include + +#if defined(__cplusplus) + #include + #include + #include +#else + #include + #include +#endif + +#if defined(LIBDIVIDE_AVX512) + #include +#elif defined(LIBDIVIDE_AVX2) + #include +#elif defined(LIBDIVIDE_SSE2) + #include +#endif + +#if defined(_MSC_VER) + #include + // disable warning C4146: unary minus operator applied + // to unsigned type, result still unsigned + #pragma warning(disable: 4146) + #define LIBDIVIDE_VC +#endif + +#if !defined(__has_builtin) + #define __has_builtin(x) 0 +#endif + +#if defined(__SIZEOF_INT128__) + #define HAS_INT128_T + // clang-cl on Windows does not yet support 128-bit division + #if !(defined(__clang__) && defined(LIBDIVIDE_VC)) + #define HAS_INT128_DIV + #endif +#endif + +#if defined(__x86_64__) || defined(_M_X64) + #define LIBDIVIDE_X86_64 +#endif + +#if defined(__i386__) + #define LIBDIVIDE_i386 +#endif + +#if defined(__GNUC__) || defined(__clang__) + #define LIBDIVIDE_GCC_STYLE_ASM +#endif + +#if defined(__cplusplus) || defined(LIBDIVIDE_VC) + #define LIBDIVIDE_FUNCTION __FUNCTION__ +#else + #define LIBDIVIDE_FUNCTION __func__ +#endif + +#define LIBDIVIDE_ERROR(msg) \ + do { \ + fprintf(stderr, "libdivide.h:%d: %s(): Error: %s\n", \ + __LINE__, LIBDIVIDE_FUNCTION, msg); \ + abort(); \ + } while (0) + +#if defined(LIBDIVIDE_ASSERTIONS_ON) + #define LIBDIVIDE_ASSERT(x) \ + do { \ + if (!(x)) { \ + fprintf(stderr, "libdivide.h:%d: %s(): Assertion failed: %s\n", \ + __LINE__, LIBDIVIDE_FUNCTION, #x); \ + abort(); \ + } \ + } while (0) +#else + #define LIBDIVIDE_ASSERT(x) +#endif + +#ifdef __cplusplus +namespace libdivide { +#endif + +// pack divider structs to prevent compilers from padding. +// This reduces memory usage by up to 43% when using a large +// array of libdivide dividers and improves performance +// by up to 10% because of reduced memory bandwidth. +#pragma pack(push, 1) + +struct libdivide_u32_t { + uint32_t magic; + uint8_t more; +}; + +struct libdivide_s32_t { + int32_t magic; + uint8_t more; +}; + +struct libdivide_u64_t { + uint64_t magic; + uint8_t more; +}; + +struct libdivide_s64_t { + int64_t magic; + uint8_t more; +}; + +struct libdivide_u32_branchfree_t { + uint32_t magic; + uint8_t more; +}; + +struct libdivide_s32_branchfree_t { + int32_t magic; + uint8_t more; +}; + +struct libdivide_u64_branchfree_t { + uint64_t magic; + uint8_t more; +}; + +struct libdivide_s64_branchfree_t { + int64_t magic; + uint8_t more; +}; + +#pragma pack(pop) + +// Explanation of the "more" field: +// +// * Bits 0-5 is the shift value (for shift path or mult path). +// * Bit 6 is the add indicator for mult path. +// * Bit 7 is set if the divisor is negative. We use bit 7 as the negative +// divisor indicator so that we can efficiently use sign extension to +// create a bitmask with all bits set to 1 (if the divisor is negative) +// or 0 (if the divisor is positive). +// +// u32: [0-4] shift value +// [5] ignored +// [6] add indicator +// magic number of 0 indicates shift path +// +// s32: [0-4] shift value +// [5] ignored +// [6] add indicator +// [7] indicates negative divisor +// magic number of 0 indicates shift path +// +// u64: [0-5] shift value +// [6] add indicator +// magic number of 0 indicates shift path +// +// s64: [0-5] shift value +// [6] add indicator +// [7] indicates negative divisor +// magic number of 0 indicates shift path +// +// In s32 and s64 branchfree modes, the magic number is negated according to +// whether the divisor is negated. In branchfree strategy, it is not negated. + +enum { + LIBDIVIDE_32_SHIFT_MASK = 0x1F, + LIBDIVIDE_64_SHIFT_MASK = 0x3F, + LIBDIVIDE_ADD_MARKER = 0x40, + LIBDIVIDE_NEGATIVE_DIVISOR = 0x80 +}; + +static inline struct libdivide_s32_t libdivide_s32_gen(int32_t d); +static inline struct libdivide_u32_t libdivide_u32_gen(uint32_t d); +static inline struct libdivide_s64_t libdivide_s64_gen(int64_t d); +static inline struct libdivide_u64_t libdivide_u64_gen(uint64_t d); + +static inline struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d); +static inline struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d); +static inline struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d); +static inline struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d); + +static inline int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom); +static inline uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom); +static inline int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom); +static inline uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom); + +static inline int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom); +static inline uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom); +static inline int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom); +static inline uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom); + +static inline int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom); +static inline uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom); +static inline int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom); +static inline uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom); + +static inline int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom); +static inline uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom); +static inline int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom); +static inline uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom); + +//////// Internal Utility Functions + +static inline uint32_t libdivide_mullhi_u32(uint32_t x, uint32_t y) { + uint64_t xl = x, yl = y; + uint64_t rl = xl * yl; + return (uint32_t)(rl >> 32); +} + +static inline int32_t libdivide_mullhi_s32(int32_t x, int32_t y) { + int64_t xl = x, yl = y; + int64_t rl = xl * yl; + // needs to be arithmetic shift + return (int32_t)(rl >> 32); +} + +static inline uint64_t libdivide_mullhi_u64(uint64_t x, uint64_t y) { +#if defined(LIBDIVIDE_VC) && \ + defined(LIBDIVIDE_X86_64) + return __umulh(x, y); +#elif defined(HAS_INT128_T) + __uint128_t xl = x, yl = y; + __uint128_t rl = xl * yl; + return (uint64_t)(rl >> 64); +#else + // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) + uint32_t mask = 0xFFFFFFFF; + uint32_t x0 = (uint32_t)(x & mask); + uint32_t x1 = (uint32_t)(x >> 32); + uint32_t y0 = (uint32_t)(y & mask); + uint32_t y1 = (uint32_t)(y >> 32); + uint32_t x0y0_hi = libdivide_mullhi_u32(x0, y0); + uint64_t x0y1 = x0 * (uint64_t)y1; + uint64_t x1y0 = x1 * (uint64_t)y0; + uint64_t x1y1 = x1 * (uint64_t)y1; + uint64_t temp = x1y0 + x0y0_hi; + uint64_t temp_lo = temp & mask; + uint64_t temp_hi = temp >> 32; + + return x1y1 + temp_hi + ((temp_lo + x0y1) >> 32); +#endif +} + +static inline int64_t libdivide_mullhi_s64(int64_t x, int64_t y) { +#if defined(LIBDIVIDE_VC) && \ + defined(LIBDIVIDE_X86_64) + return __mulh(x, y); +#elif defined(HAS_INT128_T) + __int128_t xl = x, yl = y; + __int128_t rl = xl * yl; + return (int64_t)(rl >> 64); +#else + // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) + uint32_t mask = 0xFFFFFFFF; + uint32_t x0 = (uint32_t)(x & mask); + uint32_t y0 = (uint32_t)(y & mask); + int32_t x1 = (int32_t)(x >> 32); + int32_t y1 = (int32_t)(y >> 32); + uint32_t x0y0_hi = libdivide_mullhi_u32(x0, y0); + int64_t t = x1 * (int64_t)y0 + x0y0_hi; + int64_t w1 = x0 * (int64_t)y1 + (t & mask); + + return x1 * (int64_t)y1 + (t >> 32) + (w1 >> 32); +#endif +} + +static inline int32_t libdivide_count_leading_zeros32(uint32_t val) { +#if defined(__GNUC__) || \ + __has_builtin(__builtin_clz) + // Fast way to count leading zeros + return __builtin_clz(val); +#elif defined(LIBDIVIDE_VC) + unsigned long result; + if (_BitScanReverse(&result, val)) { + return 31 - result; + } + return 0; +#else + if (val == 0) + return 32; + int32_t result = 8; + uint32_t hi = 0xFFU << 24; + while ((val & hi) == 0) { + hi >>= 8; + result += 8; + } + while (val & hi) { + result -= 1; + hi <<= 1; + } + return result; +#endif +} + +static inline int32_t libdivide_count_leading_zeros64(uint64_t val) { +#if defined(__GNUC__) || \ + __has_builtin(__builtin_clzll) + // Fast way to count leading zeros + return __builtin_clzll(val); +#elif defined(LIBDIVIDE_VC) && defined(_WIN64) + unsigned long result; + if (_BitScanReverse64(&result, val)) { + return 63 - result; + } + return 0; +#else + uint32_t hi = val >> 32; + uint32_t lo = val & 0xFFFFFFFF; + if (hi != 0) return libdivide_count_leading_zeros32(hi); + return 32 + libdivide_count_leading_zeros32(lo); +#endif +} + +// libdivide_64_div_32_to_32: divides a 64-bit uint {u1, u0} by a 32-bit +// uint {v}. The result must fit in 32 bits. +// Returns the quotient directly and the remainder in *r +static inline uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { +#if (defined(LIBDIVIDE_i386) || defined(LIBDIVIDE_X86_64)) && \ + defined(LIBDIVIDE_GCC_STYLE_ASM) + uint32_t result; + __asm__("divl %[v]" + : "=a"(result), "=d"(*r) + : [v] "r"(v), "a"(u0), "d"(u1) + ); + return result; +#else + uint64_t n = ((uint64_t)u1 << 32) | u0; + uint32_t result = (uint32_t)(n / v); + *r = (uint32_t)(n - result * (uint64_t)v); + return result; +#endif +} + +// libdivide_128_div_64_to_64: divides a 128-bit uint {u1, u0} by a 64-bit +// uint {v}. The result must fit in 64 bits. +// Returns the quotient directly and the remainder in *r +static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) { +#if defined(LIBDIVIDE_X86_64) && \ + defined(LIBDIVIDE_GCC_STYLE_ASM) + uint64_t result; + __asm__("divq %[v]" + : "=a"(result), "=d"(*r) + : [v] "r"(v), "a"(u0), "d"(u1) + ); + return result; +#elif defined(HAS_INT128_T) && \ + defined(HAS_INT128_DIV) + __uint128_t n = ((__uint128_t)u1 << 64) | u0; + uint64_t result = (uint64_t)(n / v); + *r = (uint64_t)(n - result * (__uint128_t)v); + return result; +#else + // Code taken from Hacker's Delight: + // http://www.hackersdelight.org/HDcode/divlu.c. + // License permits inclusion here per: + // http://www.hackersdelight.org/permissions.htm + + const uint64_t b = (1ULL << 32); // Number base (32 bits) + uint64_t un1, un0; // Norm. dividend LSD's + uint64_t vn1, vn0; // Norm. divisor digits + uint64_t q1, q0; // Quotient digits + uint64_t un64, un21, un10; // Dividend digit pairs + uint64_t rhat; // A remainder + int32_t s; // Shift amount for norm + + // If overflow, set rem. to an impossible value, + // and return the largest possible quotient + if (u1 >= v) { + *r = (uint64_t) -1; + return (uint64_t) -1; + } + + // count leading zeros + s = libdivide_count_leading_zeros64(v); + if (s > 0) { + // Normalize divisor + v = v << s; + un64 = (u1 << s) | (u0 >> (64 - s)); + un10 = u0 << s; // Shift dividend left + } else { + // Avoid undefined behavior of (u0 >> 64). + // The behavior is undefined if the right operand is + // negative, or greater than or equal to the length + // in bits of the promoted left operand. + un64 = u1; + un10 = u0; + } + + // Break divisor up into two 32-bit digits + vn1 = v >> 32; + vn0 = v & 0xFFFFFFFF; + + // Break right half of dividend into two digits + un1 = un10 >> 32; + un0 = un10 & 0xFFFFFFFF; + + // Compute the first quotient digit, q1 + q1 = un64 / vn1; + rhat = un64 - q1 * vn1; + + while (q1 >= b || q1 * vn0 > b * rhat + un1) { + q1 = q1 - 1; + rhat = rhat + vn1; + if (rhat >= b) + break; + } + + // Multiply and subtract + un21 = un64 * b + un1 - q1 * v; + + // Compute the second quotient digit + q0 = un21 / vn1; + rhat = un21 - q0 * vn1; + + while (q0 >= b || q0 * vn0 > b * rhat + un0) { + q0 = q0 - 1; + rhat = rhat + vn1; + if (rhat >= b) + break; + } + + *r = (un21 * b + un0 - q0 * v) >> s; + return q1 * b + q0; +#endif +} + +// Bitshift a u128 in place, left (signed_shift > 0) or right (signed_shift < 0) +static inline void libdivide_u128_shift(uint64_t *u1, uint64_t *u0, int32_t signed_shift) { + if (signed_shift > 0) { + uint32_t shift = signed_shift; + *u1 <<= shift; + *u1 |= *u0 >> (64 - shift); + *u0 <<= shift; + } + else if (signed_shift < 0) { + uint32_t shift = -signed_shift; + *u0 >>= shift; + *u0 |= *u1 << (64 - shift); + *u1 >>= shift; + } +} + +// Computes a 128 / 128 -> 64 bit division, with a 128 bit remainder. +static uint64_t libdivide_128_div_128_to_64(uint64_t u_hi, uint64_t u_lo, uint64_t v_hi, uint64_t v_lo, uint64_t *r_hi, uint64_t *r_lo) { +#if defined(HAS_INT128_T) && \ + defined(HAS_INT128_DIV) + __uint128_t ufull = u_hi; + __uint128_t vfull = v_hi; + ufull = (ufull << 64) | u_lo; + vfull = (vfull << 64) | v_lo; + uint64_t res = (uint64_t)(ufull / vfull); + __uint128_t remainder = ufull - (vfull * res); + *r_lo = (uint64_t)remainder; + *r_hi = (uint64_t)(remainder >> 64); + return res; +#else + // Adapted from "Unsigned Doubleword Division" in Hacker's Delight + // We want to compute u / v + typedef struct { uint64_t hi; uint64_t lo; } u128_t; + u128_t u = {u_hi, u_lo}; + u128_t v = {v_hi, v_lo}; + + if (v.hi == 0) { + // divisor v is a 64 bit value, so we just need one 128/64 division + // Note that we are simpler than Hacker's Delight here, because we know + // the quotient fits in 64 bits whereas Hacker's Delight demands a full + // 128 bit quotient + *r_hi = 0; + return libdivide_128_div_64_to_64(u.hi, u.lo, v.lo, r_lo); + } + // Here v >= 2**64 + // We know that v.hi != 0, so count leading zeros is OK + // We have 0 <= n <= 63 + uint32_t n = libdivide_count_leading_zeros64(v.hi); + + // Normalize the divisor so its MSB is 1 + u128_t v1t = v; + libdivide_u128_shift(&v1t.hi, &v1t.lo, n); + uint64_t v1 = v1t.hi; // i.e. v1 = v1t >> 64 + + // To ensure no overflow + u128_t u1 = u; + libdivide_u128_shift(&u1.hi, &u1.lo, -1); + + // Get quotient from divide unsigned insn. + uint64_t rem_ignored; + uint64_t q1 = libdivide_128_div_64_to_64(u1.hi, u1.lo, v1, &rem_ignored); + + // Undo normalization and division of u by 2. + u128_t q0 = {0, q1}; + libdivide_u128_shift(&q0.hi, &q0.lo, n); + libdivide_u128_shift(&q0.hi, &q0.lo, -63); + + // Make q0 correct or too small by 1 + // Equivalent to `if (q0 != 0) q0 = q0 - 1;` + if (q0.hi != 0 || q0.lo != 0) { + q0.hi -= (q0.lo == 0); // borrow + q0.lo -= 1; + } + + // Now q0 is correct. + // Compute q0 * v as q0v + // = (q0.hi << 64 + q0.lo) * (v.hi << 64 + v.lo) + // = (q0.hi * v.hi << 128) + (q0.hi * v.lo << 64) + + // (q0.lo * v.hi << 64) + q0.lo * v.lo) + // Each term is 128 bit + // High half of full product (upper 128 bits!) are dropped + u128_t q0v = {0, 0}; + q0v.hi = q0.hi*v.lo + q0.lo*v.hi + libdivide_mullhi_u64(q0.lo, v.lo); + q0v.lo = q0.lo*v.lo; + + // Compute u - q0v as u_q0v + // This is the remainder + u128_t u_q0v = u; + u_q0v.hi -= q0v.hi + (u.lo < q0v.lo); // second term is borrow + u_q0v.lo -= q0v.lo; + + // Check if u_q0v >= v + // This checks if our remainder is larger than the divisor + if ((u_q0v.hi > v.hi) || + (u_q0v.hi == v.hi && u_q0v.lo >= v.lo)) { + // Increment q0 + q0.lo += 1; + q0.hi += (q0.lo == 0); // carry + + // Subtract v from remainder + u_q0v.hi -= v.hi + (u_q0v.lo < v.lo); + u_q0v.lo -= v.lo; + } + + *r_hi = u_q0v.hi; + *r_lo = u_q0v.lo; + + LIBDIVIDE_ASSERT(q0.hi == 0); + return q0.lo; +#endif +} + +////////// UINT32 + +static inline struct libdivide_u32_t libdivide_internal_u32_gen(uint32_t d, int branchfree) { + if (d == 0) { + LIBDIVIDE_ERROR("divider must be != 0"); + } + + struct libdivide_u32_t result; + uint32_t floor_log_2_d = 31 - libdivide_count_leading_zeros32(d); + + // Power of 2 + if ((d & (d - 1)) == 0) { + // We need to subtract 1 from the shift value in case of an unsigned + // branchfree divider because there is a hardcoded right shift by 1 + // in its division algorithm. Because of this we also need to add back + // 1 in its recovery algorithm. + result.magic = 0; + result.more = (uint8_t)(floor_log_2_d - (branchfree != 0)); + } else { + uint8_t more; + uint32_t rem, proposed_m; + proposed_m = libdivide_64_div_32_to_32(1U << floor_log_2_d, 0, d, &rem); + + LIBDIVIDE_ASSERT(rem > 0 && rem < d); + const uint32_t e = d - rem; + + // This power works if e < 2**floor_log_2_d. + if (!branchfree && (e < (1U << floor_log_2_d))) { + // This power works + more = floor_log_2_d; + } else { + // We have to use the general 33-bit algorithm. We need to compute + // (2**power) / d. However, we already have (2**(power-1))/d and + // its remainder. By doubling both, and then correcting the + // remainder, we can compute the larger division. + // don't care about overflow here - in fact, we expect it + proposed_m += proposed_m; + const uint32_t twice_rem = rem + rem; + if (twice_rem >= d || twice_rem < rem) proposed_m += 1; + more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; + } + result.magic = 1 + proposed_m; + result.more = more; + // result.more's shift should in general be ceil_log_2_d. But if we + // used the smaller power, we subtract one from the shift because we're + // using the smaller power. If we're using the larger power, we + // subtract one from the shift because it's taken care of by the add + // indicator. So floor_log_2_d happens to be correct in both cases. + } + return result; +} + +struct libdivide_u32_t libdivide_u32_gen(uint32_t d) { + return libdivide_internal_u32_gen(d, 0); +} + +struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d) { + if (d == 1) { + LIBDIVIDE_ERROR("branchfree divider must be != 1"); + } + struct libdivide_u32_t tmp = libdivide_internal_u32_gen(d, 1); + struct libdivide_u32_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_32_SHIFT_MASK)}; + return ret; +} + +uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return numer >> more; + } + else { + uint32_t q = libdivide_mullhi_u32(denom->magic, numer); + if (more & LIBDIVIDE_ADD_MARKER) { + uint32_t t = ((numer - q) >> 1) + q; + return t >> (more & LIBDIVIDE_32_SHIFT_MASK); + } + else { + // All upper bits are 0, + // don't need to mask them off. + return q >> more; + } + } +} + +uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom) { + uint32_t q = libdivide_mullhi_u32(denom->magic, numer); + uint32_t t = ((numer - q) >> 1) + q; + return t >> denom->more; +} + +uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + + if (!denom->magic) { + return 1U << shift; + } else if (!(more & LIBDIVIDE_ADD_MARKER)) { + // We compute q = n/d = n*m / 2^(32 + shift) + // Therefore we have d = 2^(32 + shift) / m + // We need to ceil it. + // We know d is not a power of 2, so m is not a power of 2, + // so we can just add 1 to the floor + uint32_t hi_dividend = 1U << shift; + uint32_t rem_ignored; + return 1 + libdivide_64_div_32_to_32(hi_dividend, 0, denom->magic, &rem_ignored); + } else { + // Here we wish to compute d = 2^(32+shift+1)/(m+2^32). + // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now + // Also note that shift may be as high as 31, so shift + 1 will + // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and + // then double the quotient and remainder. + uint64_t half_n = 1ULL << (32 + shift); + uint64_t d = (1ULL << 32) | denom->magic; + // Note that the quotient is guaranteed <= 32 bits, but the remainder + // may need 33! + uint32_t half_q = (uint32_t)(half_n / d); + uint64_t rem = half_n % d; + // We computed 2^(32+shift)/(m+2^32) + // Need to double it, and then add 1 to the quotient if doubling th + // remainder would increase the quotient. + // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits + uint32_t full_q = half_q + half_q + ((rem<<1) >= d); + + // We rounded down in gen (hence +1) + return full_q + 1; + } +} + +uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + + if (!denom->magic) { + return 1U << (shift + 1); + } else { + // Here we wish to compute d = 2^(32+shift+1)/(m+2^32). + // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now + // Also note that shift may be as high as 31, so shift + 1 will + // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and + // then double the quotient and remainder. + uint64_t half_n = 1ULL << (32 + shift); + uint64_t d = (1ULL << 32) | denom->magic; + // Note that the quotient is guaranteed <= 32 bits, but the remainder + // may need 33! + uint32_t half_q = (uint32_t)(half_n / d); + uint64_t rem = half_n % d; + // We computed 2^(32+shift)/(m+2^32) + // Need to double it, and then add 1 to the quotient if doubling th + // remainder would increase the quotient. + // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits + uint32_t full_q = half_q + half_q + ((rem<<1) >= d); + + // We rounded down in gen (hence +1) + return full_q + 1; + } +} + +/////////// UINT64 + +static inline struct libdivide_u64_t libdivide_internal_u64_gen(uint64_t d, int branchfree) { + if (d == 0) { + LIBDIVIDE_ERROR("divider must be != 0"); + } + + struct libdivide_u64_t result; + uint32_t floor_log_2_d = 63 - libdivide_count_leading_zeros64(d); + + // Power of 2 + if ((d & (d - 1)) == 0) { + // We need to subtract 1 from the shift value in case of an unsigned + // branchfree divider because there is a hardcoded right shift by 1 + // in its division algorithm. Because of this we also need to add back + // 1 in its recovery algorithm. + result.magic = 0; + result.more = (uint8_t)(floor_log_2_d - (branchfree != 0)); + } else { + uint64_t proposed_m, rem; + uint8_t more; + // (1 << (64 + floor_log_2_d)) / d + proposed_m = libdivide_128_div_64_to_64(1ULL << floor_log_2_d, 0, d, &rem); + + LIBDIVIDE_ASSERT(rem > 0 && rem < d); + const uint64_t e = d - rem; + + // This power works if e < 2**floor_log_2_d. + if (!branchfree && e < (1ULL << floor_log_2_d)) { + // This power works + more = floor_log_2_d; + } else { + // We have to use the general 65-bit algorithm. We need to compute + // (2**power) / d. However, we already have (2**(power-1))/d and + // its remainder. By doubling both, and then correcting the + // remainder, we can compute the larger division. + // don't care about overflow here - in fact, we expect it + proposed_m += proposed_m; + const uint64_t twice_rem = rem + rem; + if (twice_rem >= d || twice_rem < rem) proposed_m += 1; + more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; + } + result.magic = 1 + proposed_m; + result.more = more; + // result.more's shift should in general be ceil_log_2_d. But if we + // used the smaller power, we subtract one from the shift because we're + // using the smaller power. If we're using the larger power, we + // subtract one from the shift because it's taken care of by the add + // indicator. So floor_log_2_d happens to be correct in both cases, + // which is why we do it outside of the if statement. + } + return result; +} + +struct libdivide_u64_t libdivide_u64_gen(uint64_t d) { + return libdivide_internal_u64_gen(d, 0); +} + +struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d) { + if (d == 1) { + LIBDIVIDE_ERROR("branchfree divider must be != 1"); + } + struct libdivide_u64_t tmp = libdivide_internal_u64_gen(d, 1); + struct libdivide_u64_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_64_SHIFT_MASK)}; + return ret; +} + +uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return numer >> more; + } + else { + uint64_t q = libdivide_mullhi_u64(denom->magic, numer); + if (more & LIBDIVIDE_ADD_MARKER) { + uint64_t t = ((numer - q) >> 1) + q; + return t >> (more & LIBDIVIDE_64_SHIFT_MASK); + } + else { + // All upper bits are 0, + // don't need to mask them off. + return q >> more; + } + } +} + +uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom) { + uint64_t q = libdivide_mullhi_u64(denom->magic, numer); + uint64_t t = ((numer - q) >> 1) + q; + return t >> denom->more; +} + +uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + + if (!denom->magic) { + return 1ULL << shift; + } else if (!(more & LIBDIVIDE_ADD_MARKER)) { + // We compute q = n/d = n*m / 2^(64 + shift) + // Therefore we have d = 2^(64 + shift) / m + // We need to ceil it. + // We know d is not a power of 2, so m is not a power of 2, + // so we can just add 1 to the floor + uint64_t hi_dividend = 1ULL << shift; + uint64_t rem_ignored; + return 1 + libdivide_128_div_64_to_64(hi_dividend, 0, denom->magic, &rem_ignored); + } else { + // Here we wish to compute d = 2^(64+shift+1)/(m+2^64). + // Notice (m + 2^64) is a 65 bit number. This gets hairy. See + // libdivide_u32_recover for more on what we do here. + // TODO: do something better than 128 bit math + + // Full n is a (potentially) 129 bit value + // half_n is a 128 bit value + // Compute the hi half of half_n. Low half is 0. + uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0; + // d is a 65 bit value. The high bit is always set to 1. + const uint64_t d_hi = 1, d_lo = denom->magic; + // Note that the quotient is guaranteed <= 64 bits, + // but the remainder may need 65! + uint64_t r_hi, r_lo; + uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo); + // We computed 2^(64+shift)/(m+2^64) + // Double the remainder ('dr') and check if that is larger than d + // Note that d is a 65 bit value, so r1 is small and so r1 + r1 + // cannot overflow + uint64_t dr_lo = r_lo + r_lo; + uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry + int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo); + uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0); + return full_q + 1; + } +} + +uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + + if (!denom->magic) { + return 1ULL << (shift + 1); + } else { + // Here we wish to compute d = 2^(64+shift+1)/(m+2^64). + // Notice (m + 2^64) is a 65 bit number. This gets hairy. See + // libdivide_u32_recover for more on what we do here. + // TODO: do something better than 128 bit math + + // Full n is a (potentially) 129 bit value + // half_n is a 128 bit value + // Compute the hi half of half_n. Low half is 0. + uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0; + // d is a 65 bit value. The high bit is always set to 1. + const uint64_t d_hi = 1, d_lo = denom->magic; + // Note that the quotient is guaranteed <= 64 bits, + // but the remainder may need 65! + uint64_t r_hi, r_lo; + uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo); + // We computed 2^(64+shift)/(m+2^64) + // Double the remainder ('dr') and check if that is larger than d + // Note that d is a 65 bit value, so r1 is small and so r1 + r1 + // cannot overflow + uint64_t dr_lo = r_lo + r_lo; + uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry + int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo); + uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0); + return full_q + 1; + } +} + +/////////// SINT32 + +static inline struct libdivide_s32_t libdivide_internal_s32_gen(int32_t d, int branchfree) { + if (d == 0) { + LIBDIVIDE_ERROR("divider must be != 0"); + } + + struct libdivide_s32_t result; + + // If d is a power of 2, or negative a power of 2, we have to use a shift. + // This is especially important because the magic algorithm fails for -1. + // To check if d is a power of 2 or its inverse, it suffices to check + // whether its absolute value has exactly one bit set. This works even for + // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set + // and is a power of 2. + uint32_t ud = (uint32_t)d; + uint32_t absD = (d < 0) ? -ud : ud; + uint32_t floor_log_2_d = 31 - libdivide_count_leading_zeros32(absD); + // check if exactly one bit is set, + // don't care if absD is 0 since that's divide by zero + if ((absD & (absD - 1)) == 0) { + // Branchfree and normal paths are exactly the same + result.magic = 0; + result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); + } else { + LIBDIVIDE_ASSERT(floor_log_2_d >= 1); + + uint8_t more; + // the dividend here is 2**(floor_log_2_d + 31), so the low 32 bit word + // is 0 and the high word is floor_log_2_d - 1 + uint32_t rem, proposed_m; + proposed_m = libdivide_64_div_32_to_32(1U << (floor_log_2_d - 1), 0, absD, &rem); + const uint32_t e = absD - rem; + + // We are going to start with a power of floor_log_2_d - 1. + // This works if works if e < 2**floor_log_2_d. + if (!branchfree && e < (1U << floor_log_2_d)) { + // This power works + more = floor_log_2_d - 1; + } else { + // We need to go one higher. This should not make proposed_m + // overflow, but it will make it negative when interpreted as an + // int32_t. + proposed_m += proposed_m; + const uint32_t twice_rem = rem + rem; + if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; + more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; + } + + proposed_m += 1; + int32_t magic = (int32_t)proposed_m; + + // Mark if we are negative. Note we only negate the magic number in the + // branchfull case. + if (d < 0) { + more |= LIBDIVIDE_NEGATIVE_DIVISOR; + if (!branchfree) { + magic = -magic; + } + } + + result.more = more; + result.magic = magic; + } + return result; +} + +struct libdivide_s32_t libdivide_s32_gen(int32_t d) { + return libdivide_internal_s32_gen(d, 0); +} + +struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d) { + struct libdivide_s32_t tmp = libdivide_internal_s32_gen(d, 1); + struct libdivide_s32_branchfree_t result = {tmp.magic, tmp.more}; + return result; +} + +int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + + if (!denom->magic) { + uint32_t sign = (int8_t)more >> 7; + uint32_t mask = (1U << shift) - 1; + uint32_t uq = numer + ((numer >> 31) & mask); + int32_t q = (int32_t)uq; + q >>= shift; + q = (q ^ sign) - sign; + return q; + } else { + uint32_t uq = (uint32_t)libdivide_mullhi_s32(denom->magic, numer); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift and then sign extend + int32_t sign = (int8_t)more >> 7; + // q += (more < 0 ? -numer : numer) + // cast required to avoid UB + uq += ((uint32_t)numer ^ sign) - sign; + } + int32_t q = (int32_t)uq; + q >>= shift; + q += (q < 0); + return q; + } +} + +int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + // must be arithmetic shift and then sign extend + int32_t sign = (int8_t)more >> 7; + int32_t magic = denom->magic; + int32_t q = libdivide_mullhi_s32(magic, numer); + q += numer; + + // If q is non-negative, we have nothing to do + // If q is negative, we want to add either (2**shift)-1 if d is a power of + // 2, or (2**shift) if it is not a power of 2 + uint32_t is_power_of_2 = (magic == 0); + uint32_t q_sign = (uint32_t)(q >> 31); + q += q_sign & ((1U << shift) - is_power_of_2); + + // Now arithmetic right shift + q >>= shift; + // Negate if needed + q = (q ^ sign) - sign; + + return q; +} + +int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + if (!denom->magic) { + uint32_t absD = 1U << shift; + if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { + absD = -absD; + } + return (int32_t)absD; + } else { + // Unsigned math is much easier + // We negate the magic number only in the branchfull case, and we don't + // know which case we're in. However we have enough information to + // determine the correct sign of the magic number. The divisor was + // negative if LIBDIVIDE_NEGATIVE_DIVISOR is set. If ADD_MARKER is set, + // the magic number's sign is opposite that of the divisor. + // We want to compute the positive magic number. + int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); + int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) + ? denom->magic > 0 : denom->magic < 0; + + // Handle the power of 2 case (including branchfree) + if (denom->magic == 0) { + int32_t result = 1U << shift; + return negative_divisor ? -result : result; + } + + uint32_t d = (uint32_t)(magic_was_negated ? -denom->magic : denom->magic); + uint64_t n = 1ULL << (32 + shift); // this shift cannot exceed 30 + uint32_t q = (uint32_t)(n / d); + int32_t result = (int32_t)q; + result += 1; + return negative_divisor ? -result : result; + } +} + +int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom) { + return libdivide_s32_recover((const struct libdivide_s32_t *)denom); +} + +///////////// SINT64 + +static inline struct libdivide_s64_t libdivide_internal_s64_gen(int64_t d, int branchfree) { + if (d == 0) { + LIBDIVIDE_ERROR("divider must be != 0"); + } + + struct libdivide_s64_t result; + + // If d is a power of 2, or negative a power of 2, we have to use a shift. + // This is especially important because the magic algorithm fails for -1. + // To check if d is a power of 2 or its inverse, it suffices to check + // whether its absolute value has exactly one bit set. This works even for + // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set + // and is a power of 2. + uint64_t ud = (uint64_t)d; + uint64_t absD = (d < 0) ? -ud : ud; + uint32_t floor_log_2_d = 63 - libdivide_count_leading_zeros64(absD); + // check if exactly one bit is set, + // don't care if absD is 0 since that's divide by zero + if ((absD & (absD - 1)) == 0) { + // Branchfree and non-branchfree cases are the same + result.magic = 0; + result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); + } else { + // the dividend here is 2**(floor_log_2_d + 63), so the low 64 bit word + // is 0 and the high word is floor_log_2_d - 1 + uint8_t more; + uint64_t rem, proposed_m; + proposed_m = libdivide_128_div_64_to_64(1ULL << (floor_log_2_d - 1), 0, absD, &rem); + const uint64_t e = absD - rem; + + // We are going to start with a power of floor_log_2_d - 1. + // This works if works if e < 2**floor_log_2_d. + if (!branchfree && e < (1ULL << floor_log_2_d)) { + // This power works + more = floor_log_2_d - 1; + } else { + // We need to go one higher. This should not make proposed_m + // overflow, but it will make it negative when interpreted as an + // int32_t. + proposed_m += proposed_m; + const uint64_t twice_rem = rem + rem; + if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; + // note that we only set the LIBDIVIDE_NEGATIVE_DIVISOR bit if we + // also set ADD_MARKER this is an annoying optimization that + // enables algorithm #4 to avoid the mask. However we always set it + // in the branchfree case + more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; + } + proposed_m += 1; + int64_t magic = (int64_t)proposed_m; + + // Mark if we are negative + if (d < 0) { + more |= LIBDIVIDE_NEGATIVE_DIVISOR; + if (!branchfree) { + magic = -magic; + } + } + + result.more = more; + result.magic = magic; + } + return result; +} + +struct libdivide_s64_t libdivide_s64_gen(int64_t d) { + return libdivide_internal_s64_gen(d, 0); +} + +struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d) { + struct libdivide_s64_t tmp = libdivide_internal_s64_gen(d, 1); + struct libdivide_s64_branchfree_t ret = {tmp.magic, tmp.more}; + return ret; +} + +int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + + if (!denom->magic) { // shift path + uint64_t mask = (1ULL << shift) - 1; + uint64_t uq = numer + ((numer >> 63) & mask); + int64_t q = (int64_t)uq; + q >>= shift; + // must be arithmetic shift and then sign-extend + int64_t sign = (int8_t)more >> 7; + q = (q ^ sign) - sign; + return q; + } else { + uint64_t uq = (uint64_t)libdivide_mullhi_s64(denom->magic, numer); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift and then sign extend + int64_t sign = (int8_t)more >> 7; + // q += (more < 0 ? -numer : numer) + // cast required to avoid UB + uq += ((uint64_t)numer ^ sign) - sign; + } + int64_t q = (int64_t)uq; + q >>= shift; + q += (q < 0); + return q; + } +} + +int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + // must be arithmetic shift and then sign extend + int64_t sign = (int8_t)more >> 7; + int64_t magic = denom->magic; + int64_t q = libdivide_mullhi_s64(magic, numer); + q += numer; + + // If q is non-negative, we have nothing to do. + // If q is negative, we want to add either (2**shift)-1 if d is a power of + // 2, or (2**shift) if it is not a power of 2. + uint64_t is_power_of_2 = (magic == 0); + uint64_t q_sign = (uint64_t)(q >> 63); + q += q_sign & ((1ULL << shift) - is_power_of_2); + + // Arithmetic right shift + q >>= shift; + // Negate if needed + q = (q ^ sign) - sign; + + return q; +} + +int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom) { + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + if (denom->magic == 0) { // shift path + uint64_t absD = 1ULL << shift; + if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { + absD = -absD; + } + return (int64_t)absD; + } else { + // Unsigned math is much easier + int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); + int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) + ? denom->magic > 0 : denom->magic < 0; + + uint64_t d = (uint64_t)(magic_was_negated ? -denom->magic : denom->magic); + uint64_t n_hi = 1ULL << shift, n_lo = 0; + uint64_t rem_ignored; + uint64_t q = libdivide_128_div_64_to_64(n_hi, n_lo, d, &rem_ignored); + int64_t result = (int64_t)(q + 1); + if (negative_divisor) { + result = -result; + } + return result; + } +} + +int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom) { + return libdivide_s64_recover((const struct libdivide_s64_t *)denom); +} + +#if defined(LIBDIVIDE_AVX512) + +static inline __m512i libdivide_u32_do_vector(__m512i numers, const struct libdivide_u32_t *denom); +static inline __m512i libdivide_s32_do_vector(__m512i numers, const struct libdivide_s32_t *denom); +static inline __m512i libdivide_u64_do_vector(__m512i numers, const struct libdivide_u64_t *denom); +static inline __m512i libdivide_s64_do_vector(__m512i numers, const struct libdivide_s64_t *denom); + +static inline __m512i libdivide_u32_branchfree_do_vector(__m512i numers, const struct libdivide_u32_branchfree_t *denom); +static inline __m512i libdivide_s32_branchfree_do_vector(__m512i numers, const struct libdivide_s32_branchfree_t *denom); +static inline __m512i libdivide_u64_branchfree_do_vector(__m512i numers, const struct libdivide_u64_branchfree_t *denom); +static inline __m512i libdivide_s64_branchfree_do_vector(__m512i numers, const struct libdivide_s64_branchfree_t *denom); + +//////// Internal Utility Functions + +static inline __m512i libdivide_s64_signbits(__m512i v) {; + return _mm512_srai_epi64(v, 63); +} + +static inline __m512i libdivide_s64_shift_right_vector(__m512i v, int amt) { + return _mm512_srai_epi64(v, amt); +} + +// Here, b is assumed to contain one 32-bit value repeated. +static inline __m512i libdivide_mullhi_u32_vector(__m512i a, __m512i b) { + __m512i hi_product_0Z2Z = _mm512_srli_epi64(_mm512_mul_epu32(a, b), 32); + __m512i a1X3X = _mm512_srli_epi64(a, 32); + __m512i mask = _mm512_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0); + __m512i hi_product_Z1Z3 = _mm512_and_si512(_mm512_mul_epu32(a1X3X, b), mask); + return _mm512_or_si512(hi_product_0Z2Z, hi_product_Z1Z3); +} + +// b is one 32-bit value repeated. +static inline __m512i libdivide_mullhi_s32_vector(__m512i a, __m512i b) { + __m512i hi_product_0Z2Z = _mm512_srli_epi64(_mm512_mul_epi32(a, b), 32); + __m512i a1X3X = _mm512_srli_epi64(a, 32); + __m512i mask = _mm512_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0); + __m512i hi_product_Z1Z3 = _mm512_and_si512(_mm512_mul_epi32(a1X3X, b), mask); + return _mm512_or_si512(hi_product_0Z2Z, hi_product_Z1Z3); +} + +// Here, y is assumed to contain one 64-bit value repeated. +// https://stackoverflow.com/a/28827013 +static inline __m512i libdivide_mullhi_u64_vector(__m512i x, __m512i y) { + __m512i lomask = _mm512_set1_epi64(0xffffffff); + __m512i xh = _mm512_shuffle_epi32(x, (_MM_PERM_ENUM) 0xB1); + __m512i yh = _mm512_shuffle_epi32(y, (_MM_PERM_ENUM) 0xB1); + __m512i w0 = _mm512_mul_epu32(x, y); + __m512i w1 = _mm512_mul_epu32(x, yh); + __m512i w2 = _mm512_mul_epu32(xh, y); + __m512i w3 = _mm512_mul_epu32(xh, yh); + __m512i w0h = _mm512_srli_epi64(w0, 32); + __m512i s1 = _mm512_add_epi64(w1, w0h); + __m512i s1l = _mm512_and_si512(s1, lomask); + __m512i s1h = _mm512_srli_epi64(s1, 32); + __m512i s2 = _mm512_add_epi64(w2, s1l); + __m512i s2h = _mm512_srli_epi64(s2, 32); + __m512i hi = _mm512_add_epi64(w3, s1h); + hi = _mm512_add_epi64(hi, s2h); + + return hi; +} + +// y is one 64-bit value repeated. +static inline __m512i libdivide_mullhi_s64_vector(__m512i x, __m512i y) { + __m512i p = libdivide_mullhi_u64_vector(x, y); + __m512i t1 = _mm512_and_si512(libdivide_s64_signbits(x), y); + __m512i t2 = _mm512_and_si512(libdivide_s64_signbits(y), x); + p = _mm512_sub_epi64(p, t1); + p = _mm512_sub_epi64(p, t2); + return p; +} + +////////// UINT32 + +__m512i libdivide_u32_do_vector(__m512i numers, const struct libdivide_u32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return _mm512_srli_epi32(numers, more); + } + else { + __m512i q = libdivide_mullhi_u32_vector(numers, _mm512_set1_epi32(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // uint32_t t = ((numer - q) >> 1) + q; + // return t >> denom->shift; + uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + __m512i t = _mm512_add_epi32(_mm512_srli_epi32(_mm512_sub_epi32(numers, q), 1), q); + return _mm512_srli_epi32(t, shift); + } + else { + return _mm512_srli_epi32(q, more); + } + } +} + +__m512i libdivide_u32_branchfree_do_vector(__m512i numers, const struct libdivide_u32_branchfree_t *denom) { + __m512i q = libdivide_mullhi_u32_vector(numers, _mm512_set1_epi32(denom->magic)); + __m512i t = _mm512_add_epi32(_mm512_srli_epi32(_mm512_sub_epi32(numers, q), 1), q); + return _mm512_srli_epi32(t, denom->more); +} + +////////// UINT64 + +__m512i libdivide_u64_do_vector(__m512i numers, const struct libdivide_u64_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return _mm512_srli_epi64(numers, more); + } + else { + __m512i q = libdivide_mullhi_u64_vector(numers, _mm512_set1_epi64(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // uint32_t t = ((numer - q) >> 1) + q; + // return t >> denom->shift; + uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + __m512i t = _mm512_add_epi64(_mm512_srli_epi64(_mm512_sub_epi64(numers, q), 1), q); + return _mm512_srli_epi64(t, shift); + } + else { + return _mm512_srli_epi64(q, more); + } + } +} + +__m512i libdivide_u64_branchfree_do_vector(__m512i numers, const struct libdivide_u64_branchfree_t *denom) { + __m512i q = libdivide_mullhi_u64_vector(numers, _mm512_set1_epi64(denom->magic)); + __m512i t = _mm512_add_epi64(_mm512_srli_epi64(_mm512_sub_epi64(numers, q), 1), q); + return _mm512_srli_epi64(t, denom->more); +} + +////////// SINT32 + +__m512i libdivide_s32_do_vector(__m512i numers, const struct libdivide_s32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + uint32_t mask = (1U << shift) - 1; + __m512i roundToZeroTweak = _mm512_set1_epi32(mask); + // q = numer + ((numer >> 31) & roundToZeroTweak); + __m512i q = _mm512_add_epi32(numers, _mm512_and_si512(_mm512_srai_epi32(numers, 31), roundToZeroTweak)); + q = _mm512_srai_epi32(q, shift); + __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); + // q = (q ^ sign) - sign; + q = _mm512_sub_epi32(_mm512_xor_si512(q, sign), sign); + return q; + } + else { + __m512i q = libdivide_mullhi_s32_vector(numers, _mm512_set1_epi32(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift + __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); + // q += ((numer ^ sign) - sign); + q = _mm512_add_epi32(q, _mm512_sub_epi32(_mm512_xor_si512(numers, sign), sign)); + } + // q >>= shift + q = _mm512_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK); + q = _mm512_add_epi32(q, _mm512_srli_epi32(q, 31)); // q += (q < 0) + return q; + } +} + +__m512i libdivide_s32_branchfree_do_vector(__m512i numers, const struct libdivide_s32_branchfree_t *denom) { + int32_t magic = denom->magic; + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + // must be arithmetic shift + __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); + __m512i q = libdivide_mullhi_s32_vector(numers, _mm512_set1_epi32(magic)); + q = _mm512_add_epi32(q, numers); // q += numers + + // If q is non-negative, we have nothing to do + // If q is negative, we want to add either (2**shift)-1 if d is + // a power of 2, or (2**shift) if it is not a power of 2 + uint32_t is_power_of_2 = (magic == 0); + __m512i q_sign = _mm512_srai_epi32(q, 31); // q_sign = q >> 31 + __m512i mask = _mm512_set1_epi32((1U << shift) - is_power_of_2); + q = _mm512_add_epi32(q, _mm512_and_si512(q_sign, mask)); // q = q + (q_sign & mask) + q = _mm512_srai_epi32(q, shift); // q >>= shift + q = _mm512_sub_epi32(_mm512_xor_si512(q, sign), sign); // q = (q ^ sign) - sign + return q; +} + +////////// SINT64 + +__m512i libdivide_s64_do_vector(__m512i numers, const struct libdivide_s64_t *denom) { + uint8_t more = denom->more; + int64_t magic = denom->magic; + if (magic == 0) { // shift path + uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + uint64_t mask = (1ULL << shift) - 1; + __m512i roundToZeroTweak = _mm512_set1_epi64(mask); + // q = numer + ((numer >> 63) & roundToZeroTweak); + __m512i q = _mm512_add_epi64(numers, _mm512_and_si512(libdivide_s64_signbits(numers), roundToZeroTweak)); + q = libdivide_s64_shift_right_vector(q, shift); + __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); + // q = (q ^ sign) - sign; + q = _mm512_sub_epi64(_mm512_xor_si512(q, sign), sign); + return q; + } + else { + __m512i q = libdivide_mullhi_s64_vector(numers, _mm512_set1_epi64(magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift + __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); + // q += ((numer ^ sign) - sign); + q = _mm512_add_epi64(q, _mm512_sub_epi64(_mm512_xor_si512(numers, sign), sign)); + } + // q >>= denom->mult_path.shift + q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); + q = _mm512_add_epi64(q, _mm512_srli_epi64(q, 63)); // q += (q < 0) + return q; + } +} + +__m512i libdivide_s64_branchfree_do_vector(__m512i numers, const struct libdivide_s64_branchfree_t *denom) { + int64_t magic = denom->magic; + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + // must be arithmetic shift + __m512i sign = _mm512_set1_epi32((int8_t)more >> 7); + + // libdivide_mullhi_s64(numers, magic); + __m512i q = libdivide_mullhi_s64_vector(numers, _mm512_set1_epi64(magic)); + q = _mm512_add_epi64(q, numers); // q += numers + + // If q is non-negative, we have nothing to do. + // If q is negative, we want to add either (2**shift)-1 if d is + // a power of 2, or (2**shift) if it is not a power of 2. + uint32_t is_power_of_2 = (magic == 0); + __m512i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 + __m512i mask = _mm512_set1_epi64((1ULL << shift) - is_power_of_2); + q = _mm512_add_epi64(q, _mm512_and_si512(q_sign, mask)); // q = q + (q_sign & mask) + q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift + q = _mm512_sub_epi64(_mm512_xor_si512(q, sign), sign); // q = (q ^ sign) - sign + return q; +} + +#elif defined(LIBDIVIDE_AVX2) + +static inline __m256i libdivide_u32_do_vector(__m256i numers, const struct libdivide_u32_t *denom); +static inline __m256i libdivide_s32_do_vector(__m256i numers, const struct libdivide_s32_t *denom); +static inline __m256i libdivide_u64_do_vector(__m256i numers, const struct libdivide_u64_t *denom); +static inline __m256i libdivide_s64_do_vector(__m256i numers, const struct libdivide_s64_t *denom); + +static inline __m256i libdivide_u32_branchfree_do_vector(__m256i numers, const struct libdivide_u32_branchfree_t *denom); +static inline __m256i libdivide_s32_branchfree_do_vector(__m256i numers, const struct libdivide_s32_branchfree_t *denom); +static inline __m256i libdivide_u64_branchfree_do_vector(__m256i numers, const struct libdivide_u64_branchfree_t *denom); +static inline __m256i libdivide_s64_branchfree_do_vector(__m256i numers, const struct libdivide_s64_branchfree_t *denom); + +//////// Internal Utility Functions + +// Implementation of _mm256_srai_epi64(v, 63) (from AVX512). +static inline __m256i libdivide_s64_signbits(__m256i v) { + __m256i hiBitsDuped = _mm256_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1)); + __m256i signBits = _mm256_srai_epi32(hiBitsDuped, 31); + return signBits; +} + +// Implementation of _mm256_srai_epi64 (from AVX512). +static inline __m256i libdivide_s64_shift_right_vector(__m256i v, int amt) { + const int b = 64 - amt; + __m256i m = _mm256_set1_epi64x(1ULL << (b - 1)); + __m256i x = _mm256_srli_epi64(v, amt); + __m256i result = _mm256_sub_epi64(_mm256_xor_si256(x, m), m); + return result; +} + +// Here, b is assumed to contain one 32-bit value repeated. +static inline __m256i libdivide_mullhi_u32_vector(__m256i a, __m256i b) { + __m256i hi_product_0Z2Z = _mm256_srli_epi64(_mm256_mul_epu32(a, b), 32); + __m256i a1X3X = _mm256_srli_epi64(a, 32); + __m256i mask = _mm256_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0); + __m256i hi_product_Z1Z3 = _mm256_and_si256(_mm256_mul_epu32(a1X3X, b), mask); + return _mm256_or_si256(hi_product_0Z2Z, hi_product_Z1Z3); +} + +// b is one 32-bit value repeated. +static inline __m256i libdivide_mullhi_s32_vector(__m256i a, __m256i b) { + __m256i hi_product_0Z2Z = _mm256_srli_epi64(_mm256_mul_epi32(a, b), 32); + __m256i a1X3X = _mm256_srli_epi64(a, 32); + __m256i mask = _mm256_set_epi32(-1, 0, -1, 0, -1, 0, -1, 0); + __m256i hi_product_Z1Z3 = _mm256_and_si256(_mm256_mul_epi32(a1X3X, b), mask); + return _mm256_or_si256(hi_product_0Z2Z, hi_product_Z1Z3); +} + +// Here, y is assumed to contain one 64-bit value repeated. +// https://stackoverflow.com/a/28827013 +static inline __m256i libdivide_mullhi_u64_vector(__m256i x, __m256i y) { + __m256i lomask = _mm256_set1_epi64x(0xffffffff); + __m256i xh = _mm256_shuffle_epi32(x, 0xB1); // x0l, x0h, x1l, x1h + __m256i yh = _mm256_shuffle_epi32(y, 0xB1); // y0l, y0h, y1l, y1h + __m256i w0 = _mm256_mul_epu32(x, y); // x0l*y0l, x1l*y1l + __m256i w1 = _mm256_mul_epu32(x, yh); // x0l*y0h, x1l*y1h + __m256i w2 = _mm256_mul_epu32(xh, y); // x0h*y0l, x1h*y0l + __m256i w3 = _mm256_mul_epu32(xh, yh); // x0h*y0h, x1h*y1h + __m256i w0h = _mm256_srli_epi64(w0, 32); + __m256i s1 = _mm256_add_epi64(w1, w0h); + __m256i s1l = _mm256_and_si256(s1, lomask); + __m256i s1h = _mm256_srli_epi64(s1, 32); + __m256i s2 = _mm256_add_epi64(w2, s1l); + __m256i s2h = _mm256_srli_epi64(s2, 32); + __m256i hi = _mm256_add_epi64(w3, s1h); + hi = _mm256_add_epi64(hi, s2h); + + return hi; +} + +// y is one 64-bit value repeated. +static inline __m256i libdivide_mullhi_s64_vector(__m256i x, __m256i y) { + __m256i p = libdivide_mullhi_u64_vector(x, y); + __m256i t1 = _mm256_and_si256(libdivide_s64_signbits(x), y); + __m256i t2 = _mm256_and_si256(libdivide_s64_signbits(y), x); + p = _mm256_sub_epi64(p, t1); + p = _mm256_sub_epi64(p, t2); + return p; +} + +////////// UINT32 + +__m256i libdivide_u32_do_vector(__m256i numers, const struct libdivide_u32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return _mm256_srli_epi32(numers, more); + } + else { + __m256i q = libdivide_mullhi_u32_vector(numers, _mm256_set1_epi32(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // uint32_t t = ((numer - q) >> 1) + q; + // return t >> denom->shift; + uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + __m256i t = _mm256_add_epi32(_mm256_srli_epi32(_mm256_sub_epi32(numers, q), 1), q); + return _mm256_srli_epi32(t, shift); + } + else { + return _mm256_srli_epi32(q, more); + } + } +} + +__m256i libdivide_u32_branchfree_do_vector(__m256i numers, const struct libdivide_u32_branchfree_t *denom) { + __m256i q = libdivide_mullhi_u32_vector(numers, _mm256_set1_epi32(denom->magic)); + __m256i t = _mm256_add_epi32(_mm256_srli_epi32(_mm256_sub_epi32(numers, q), 1), q); + return _mm256_srli_epi32(t, denom->more); +} + +////////// UINT64 + +__m256i libdivide_u64_do_vector(__m256i numers, const struct libdivide_u64_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return _mm256_srli_epi64(numers, more); + } + else { + __m256i q = libdivide_mullhi_u64_vector(numers, _mm256_set1_epi64x(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // uint32_t t = ((numer - q) >> 1) + q; + // return t >> denom->shift; + uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + __m256i t = _mm256_add_epi64(_mm256_srli_epi64(_mm256_sub_epi64(numers, q), 1), q); + return _mm256_srli_epi64(t, shift); + } + else { + return _mm256_srli_epi64(q, more); + } + } +} + +__m256i libdivide_u64_branchfree_do_vector(__m256i numers, const struct libdivide_u64_branchfree_t *denom) { + __m256i q = libdivide_mullhi_u64_vector(numers, _mm256_set1_epi64x(denom->magic)); + __m256i t = _mm256_add_epi64(_mm256_srli_epi64(_mm256_sub_epi64(numers, q), 1), q); + return _mm256_srli_epi64(t, denom->more); +} + +////////// SINT32 + +__m256i libdivide_s32_do_vector(__m256i numers, const struct libdivide_s32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + uint32_t mask = (1U << shift) - 1; + __m256i roundToZeroTweak = _mm256_set1_epi32(mask); + // q = numer + ((numer >> 31) & roundToZeroTweak); + __m256i q = _mm256_add_epi32(numers, _mm256_and_si256(_mm256_srai_epi32(numers, 31), roundToZeroTweak)); + q = _mm256_srai_epi32(q, shift); + __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); + // q = (q ^ sign) - sign; + q = _mm256_sub_epi32(_mm256_xor_si256(q, sign), sign); + return q; + } + else { + __m256i q = libdivide_mullhi_s32_vector(numers, _mm256_set1_epi32(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift + __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); + // q += ((numer ^ sign) - sign); + q = _mm256_add_epi32(q, _mm256_sub_epi32(_mm256_xor_si256(numers, sign), sign)); + } + // q >>= shift + q = _mm256_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK); + q = _mm256_add_epi32(q, _mm256_srli_epi32(q, 31)); // q += (q < 0) + return q; + } +} + +__m256i libdivide_s32_branchfree_do_vector(__m256i numers, const struct libdivide_s32_branchfree_t *denom) { + int32_t magic = denom->magic; + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + // must be arithmetic shift + __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); + __m256i q = libdivide_mullhi_s32_vector(numers, _mm256_set1_epi32(magic)); + q = _mm256_add_epi32(q, numers); // q += numers + + // If q is non-negative, we have nothing to do + // If q is negative, we want to add either (2**shift)-1 if d is + // a power of 2, or (2**shift) if it is not a power of 2 + uint32_t is_power_of_2 = (magic == 0); + __m256i q_sign = _mm256_srai_epi32(q, 31); // q_sign = q >> 31 + __m256i mask = _mm256_set1_epi32((1U << shift) - is_power_of_2); + q = _mm256_add_epi32(q, _mm256_and_si256(q_sign, mask)); // q = q + (q_sign & mask) + q = _mm256_srai_epi32(q, shift); // q >>= shift + q = _mm256_sub_epi32(_mm256_xor_si256(q, sign), sign); // q = (q ^ sign) - sign + return q; +} + +////////// SINT64 + +__m256i libdivide_s64_do_vector(__m256i numers, const struct libdivide_s64_t *denom) { + uint8_t more = denom->more; + int64_t magic = denom->magic; + if (magic == 0) { // shift path + uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + uint64_t mask = (1ULL << shift) - 1; + __m256i roundToZeroTweak = _mm256_set1_epi64x(mask); + // q = numer + ((numer >> 63) & roundToZeroTweak); + __m256i q = _mm256_add_epi64(numers, _mm256_and_si256(libdivide_s64_signbits(numers), roundToZeroTweak)); + q = libdivide_s64_shift_right_vector(q, shift); + __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); + // q = (q ^ sign) - sign; + q = _mm256_sub_epi64(_mm256_xor_si256(q, sign), sign); + return q; + } + else { + __m256i q = libdivide_mullhi_s64_vector(numers, _mm256_set1_epi64x(magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift + __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); + // q += ((numer ^ sign) - sign); + q = _mm256_add_epi64(q, _mm256_sub_epi64(_mm256_xor_si256(numers, sign), sign)); + } + // q >>= denom->mult_path.shift + q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); + q = _mm256_add_epi64(q, _mm256_srli_epi64(q, 63)); // q += (q < 0) + return q; + } +} + +__m256i libdivide_s64_branchfree_do_vector(__m256i numers, const struct libdivide_s64_branchfree_t *denom) { + int64_t magic = denom->magic; + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + // must be arithmetic shift + __m256i sign = _mm256_set1_epi32((int8_t)more >> 7); + + // libdivide_mullhi_s64(numers, magic); + __m256i q = libdivide_mullhi_s64_vector(numers, _mm256_set1_epi64x(magic)); + q = _mm256_add_epi64(q, numers); // q += numers + + // If q is non-negative, we have nothing to do. + // If q is negative, we want to add either (2**shift)-1 if d is + // a power of 2, or (2**shift) if it is not a power of 2. + uint32_t is_power_of_2 = (magic == 0); + __m256i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 + __m256i mask = _mm256_set1_epi64x((1ULL << shift) - is_power_of_2); + q = _mm256_add_epi64(q, _mm256_and_si256(q_sign, mask)); // q = q + (q_sign & mask) + q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift + q = _mm256_sub_epi64(_mm256_xor_si256(q, sign), sign); // q = (q ^ sign) - sign + return q; +} + +#elif defined(LIBDIVIDE_SSE2) + +static inline __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom); +static inline __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom); +static inline __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom); +static inline __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom); + +static inline __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom); +static inline __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom); +static inline __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom); +static inline __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom); + +//////// Internal Utility Functions + +// Implementation of _mm_srai_epi64(v, 63) (from AVX512). +static inline __m128i libdivide_s64_signbits(__m128i v) { + __m128i hiBitsDuped = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1)); + __m128i signBits = _mm_srai_epi32(hiBitsDuped, 31); + return signBits; +} + +// Implementation of _mm_srai_epi64 (from AVX512). +static inline __m128i libdivide_s64_shift_right_vector(__m128i v, int amt) { + const int b = 64 - amt; + __m128i m = _mm_set1_epi64x(1ULL << (b - 1)); + __m128i x = _mm_srli_epi64(v, amt); + __m128i result = _mm_sub_epi64(_mm_xor_si128(x, m), m); + return result; +} + +// Here, b is assumed to contain one 32-bit value repeated. +static inline __m128i libdivide_mullhi_u32_vector(__m128i a, __m128i b) { + __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epu32(a, b), 32); + __m128i a1X3X = _mm_srli_epi64(a, 32); + __m128i mask = _mm_set_epi32(-1, 0, -1, 0); + __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epu32(a1X3X, b), mask); + return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3); +} + +// SSE2 does not have a signed multiplication instruction, but we can convert +// unsigned to signed pretty efficiently. Again, b is just a 32 bit value +// repeated four times. +static inline __m128i libdivide_mullhi_s32_vector(__m128i a, __m128i b) { + __m128i p = libdivide_mullhi_u32_vector(a, b); + // t1 = (a >> 31) & y, arithmetic shift + __m128i t1 = _mm_and_si128(_mm_srai_epi32(a, 31), b); + __m128i t2 = _mm_and_si128(_mm_srai_epi32(b, 31), a); + p = _mm_sub_epi32(p, t1); + p = _mm_sub_epi32(p, t2); + return p; +} + +// Here, y is assumed to contain one 64-bit value repeated. +// https://stackoverflow.com/a/28827013 +static inline __m128i libdivide_mullhi_u64_vector(__m128i x, __m128i y) { + __m128i lomask = _mm_set1_epi64x(0xffffffff); + __m128i xh = _mm_shuffle_epi32(x, 0xB1); // x0l, x0h, x1l, x1h + __m128i yh = _mm_shuffle_epi32(y, 0xB1); // y0l, y0h, y1l, y1h + __m128i w0 = _mm_mul_epu32(x, y); // x0l*y0l, x1l*y1l + __m128i w1 = _mm_mul_epu32(x, yh); // x0l*y0h, x1l*y1h + __m128i w2 = _mm_mul_epu32(xh, y); // x0h*y0l, x1h*y0l + __m128i w3 = _mm_mul_epu32(xh, yh); // x0h*y0h, x1h*y1h + __m128i w0h = _mm_srli_epi64(w0, 32); + __m128i s1 = _mm_add_epi64(w1, w0h); + __m128i s1l = _mm_and_si128(s1, lomask); + __m128i s1h = _mm_srli_epi64(s1, 32); + __m128i s2 = _mm_add_epi64(w2, s1l); + __m128i s2h = _mm_srli_epi64(s2, 32); + __m128i hi = _mm_add_epi64(w3, s1h); + hi = _mm_add_epi64(hi, s2h); + + return hi; +} + +// y is one 64-bit value repeated. +static inline __m128i libdivide_mullhi_s64_vector(__m128i x, __m128i y) { + __m128i p = libdivide_mullhi_u64_vector(x, y); + __m128i t1 = _mm_and_si128(libdivide_s64_signbits(x), y); + __m128i t2 = _mm_and_si128(libdivide_s64_signbits(y), x); + p = _mm_sub_epi64(p, t1); + p = _mm_sub_epi64(p, t2); + return p; +} + +////////// UINT32 + +__m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return _mm_srli_epi32(numers, more); + } + else { + __m128i q = libdivide_mullhi_u32_vector(numers, _mm_set1_epi32(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // uint32_t t = ((numer - q) >> 1) + q; + // return t >> denom->shift; + uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); + return _mm_srli_epi32(t, shift); + } + else { + return _mm_srli_epi32(q, more); + } + } +} + +__m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom) { + __m128i q = libdivide_mullhi_u32_vector(numers, _mm_set1_epi32(denom->magic)); + __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); + return _mm_srli_epi32(t, denom->more); +} + +////////// UINT64 + +__m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + return _mm_srli_epi64(numers, more); + } + else { + __m128i q = libdivide_mullhi_u64_vector(numers, _mm_set1_epi64x(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // uint32_t t = ((numer - q) >> 1) + q; + // return t >> denom->shift; + uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); + return _mm_srli_epi64(t, shift); + } + else { + return _mm_srli_epi64(q, more); + } + } +} + +__m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom) { + __m128i q = libdivide_mullhi_u64_vector(numers, _mm_set1_epi64x(denom->magic)); + __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); + return _mm_srli_epi64(t, denom->more); +} + +////////// SINT32 + +__m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom) { + uint8_t more = denom->more; + if (!denom->magic) { + uint32_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + uint32_t mask = (1U << shift) - 1; + __m128i roundToZeroTweak = _mm_set1_epi32(mask); + // q = numer + ((numer >> 31) & roundToZeroTweak); + __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); + q = _mm_srai_epi32(q, shift); + __m128i sign = _mm_set1_epi32((int8_t)more >> 7); + // q = (q ^ sign) - sign; + q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); + return q; + } + else { + __m128i q = libdivide_mullhi_s32_vector(numers, _mm_set1_epi32(denom->magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift + __m128i sign = _mm_set1_epi32((int8_t)more >> 7); + // q += ((numer ^ sign) - sign); + q = _mm_add_epi32(q, _mm_sub_epi32(_mm_xor_si128(numers, sign), sign)); + } + // q >>= shift + q = _mm_srai_epi32(q, more & LIBDIVIDE_32_SHIFT_MASK); + q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0) + return q; + } +} + +__m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom) { + int32_t magic = denom->magic; + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; + // must be arithmetic shift + __m128i sign = _mm_set1_epi32((int8_t)more >> 7); + __m128i q = libdivide_mullhi_s32_vector(numers, _mm_set1_epi32(magic)); + q = _mm_add_epi32(q, numers); // q += numers + + // If q is non-negative, we have nothing to do + // If q is negative, we want to add either (2**shift)-1 if d is + // a power of 2, or (2**shift) if it is not a power of 2 + uint32_t is_power_of_2 = (magic == 0); + __m128i q_sign = _mm_srai_epi32(q, 31); // q_sign = q >> 31 + __m128i mask = _mm_set1_epi32((1U << shift) - is_power_of_2); + q = _mm_add_epi32(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) + q = _mm_srai_epi32(q, shift); // q >>= shift + q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign + return q; +} + +////////// SINT64 + +__m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom) { + uint8_t more = denom->more; + int64_t magic = denom->magic; + if (magic == 0) { // shift path + uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + uint64_t mask = (1ULL << shift) - 1; + __m128i roundToZeroTweak = _mm_set1_epi64x(mask); + // q = numer + ((numer >> 63) & roundToZeroTweak); + __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); + q = libdivide_s64_shift_right_vector(q, shift); + __m128i sign = _mm_set1_epi32((int8_t)more >> 7); + // q = (q ^ sign) - sign; + q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); + return q; + } + else { + __m128i q = libdivide_mullhi_s64_vector(numers, _mm_set1_epi64x(magic)); + if (more & LIBDIVIDE_ADD_MARKER) { + // must be arithmetic shift + __m128i sign = _mm_set1_epi32((int8_t)more >> 7); + // q += ((numer ^ sign) - sign); + q = _mm_add_epi64(q, _mm_sub_epi64(_mm_xor_si128(numers, sign), sign)); + } + // q >>= denom->mult_path.shift + q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); + q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) + return q; + } +} + +__m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom) { + int64_t magic = denom->magic; + uint8_t more = denom->more; + uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; + // must be arithmetic shift + __m128i sign = _mm_set1_epi32((int8_t)more >> 7); + + // libdivide_mullhi_s64(numers, magic); + __m128i q = libdivide_mullhi_s64_vector(numers, _mm_set1_epi64x(magic)); + q = _mm_add_epi64(q, numers); // q += numers + + // If q is non-negative, we have nothing to do. + // If q is negative, we want to add either (2**shift)-1 if d is + // a power of 2, or (2**shift) if it is not a power of 2. + uint32_t is_power_of_2 = (magic == 0); + __m128i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 + __m128i mask = _mm_set1_epi64x((1ULL << shift) - is_power_of_2); + q = _mm_add_epi64(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) + q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift + q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign + return q; +} + +#endif + +/////////// C++ stuff + +#ifdef __cplusplus + +// The C++ divider class is templated on both an integer type +// (like uint64_t) and an algorithm type. +// * BRANCHFULL is the default algorithm type. +// * BRANCHFREE is the branchfree algorithm type. +enum { + BRANCHFULL, + BRANCHFREE +}; + +#if defined(LIBDIVIDE_AVX512) + #define LIBDIVIDE_VECTOR_TYPE __m512i +#elif defined(LIBDIVIDE_AVX2) + #define LIBDIVIDE_VECTOR_TYPE __m256i +#elif defined(LIBDIVIDE_SSE2) + #define LIBDIVIDE_VECTOR_TYPE __m128i +#endif + +#if !defined(LIBDIVIDE_VECTOR_TYPE) + #define LIBDIVIDE_DIVIDE_VECTOR(ALGO) +#else + #define LIBDIVIDE_DIVIDE_VECTOR(ALGO) \ + LIBDIVIDE_VECTOR_TYPE divide(LIBDIVIDE_VECTOR_TYPE n) const { \ + return libdivide_##ALGO##_do_vector(n, &denom); \ + } +#endif + +// The DISPATCHER_GEN() macro generates C++ methods (for the given integer +// and algorithm types) that redirect to libdivide's C API. +#define DISPATCHER_GEN(T, ALGO) \ + libdivide_##ALGO##_t denom; \ + dispatcher() { } \ + dispatcher(T d) \ + : denom(libdivide_##ALGO##_gen(d)) \ + { } \ + T divide(T n) const { \ + return libdivide_##ALGO##_do(n, &denom); \ + } \ + LIBDIVIDE_DIVIDE_VECTOR(ALGO) \ + T recover() const { \ + return libdivide_##ALGO##_recover(&denom); \ + } + +// The dispatcher selects a specific division algorithm for a given +// type and ALGO using partial template specialization. +template struct dispatcher { }; + +template<> struct dispatcher { DISPATCHER_GEN(int32_t, s32) }; +template<> struct dispatcher { DISPATCHER_GEN(int32_t, s32_branchfree) }; +template<> struct dispatcher { DISPATCHER_GEN(uint32_t, u32) }; +template<> struct dispatcher { DISPATCHER_GEN(uint32_t, u32_branchfree) }; +template<> struct dispatcher { DISPATCHER_GEN(int64_t, s64) }; +template<> struct dispatcher { DISPATCHER_GEN(int64_t, s64_branchfree) }; +template<> struct dispatcher { DISPATCHER_GEN(uint64_t, u64) }; +template<> struct dispatcher { DISPATCHER_GEN(uint64_t, u64_branchfree) }; + +// This is the main divider class for use by the user (C++ API). +// The actual division algorithm is selected using the dispatcher struct +// based on the integer and algorithm template parameters. +template +class divider { +public: + // We leave the default constructor empty so that creating + // an array of dividers and then initializing them + // later doesn't slow us down. + divider() { } + + // Constructor that takes the divisor as a parameter + divider(T d) : div(d) { } + + // Divides n by the divisor + T divide(T n) const { + return div.divide(n); + } + + // Recovers the divisor, returns the value that was + // used to initialize this divider object. + T recover() const { + return div.recover(); + } + + bool operator==(const divider& other) const { + return div.denom.magic == other.denom.magic && + div.denom.more == other.denom.more; + } + + bool operator!=(const divider& other) const { + return !(*this == other); + } + +#if defined(LIBDIVIDE_VECTOR_TYPE) + // Treats the vector as packed integer values with the same type as + // the divider (e.g. s32, u32, s64, u64) and divides each of + // them by the divider, returning the packed quotients. + LIBDIVIDE_VECTOR_TYPE divide(LIBDIVIDE_VECTOR_TYPE n) const { + return div.divide(n); + } +#endif + +private: + // Storage for the actual divisor + dispatcher::value, + std::is_signed::value, sizeof(T), ALGO> div; +}; + +// Overload of operator / for scalar division +template +T operator/(T n, const divider& div) { + return div.divide(n); +} + +// Overload of operator /= for scalar division +template +T& operator/=(T& n, const divider& div) { + n = div.divide(n); + return n; +} + +#if defined(LIBDIVIDE_VECTOR_TYPE) + // Overload of operator / for vector division + template + LIBDIVIDE_VECTOR_TYPE operator/(LIBDIVIDE_VECTOR_TYPE n, const divider& div) { + return div.divide(n); + } + // Overload of operator /= for vector division + template + LIBDIVIDE_VECTOR_TYPE& operator/=(LIBDIVIDE_VECTOR_TYPE& n, const divider& div) { + n = div.divide(n); + return n; + } +#endif + +// libdivdie::branchfree_divider +template +using branchfree_divider = divider; + +} // namespace libdivide + +#endif // __cplusplus + +#endif // NUMPY_CORE_INCLUDE_NUMPY_LIBDIVIDE_LIBDIVIDE_H_ diff --git a/shared/package-files/7b/7b109186233615d0ad098a92238e64a0a65a92f5103a85f402b05ba4e983f67b/blob b/shared/package-files/7b/7b109186233615d0ad098a92238e64a0a65a92f5103a85f402b05ba4e983f67b/blob new file mode 100644 index 0000000000000000000000000000000000000000..707b714f4d94354d314b01a3bf3b4f7f0992ae1a --- /dev/null +++ b/shared/package-files/7b/7b109186233615d0ad098a92238e64a0a65a92f5103a85f402b05ba4e983f67b/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::masked_select.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & masked_select_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mask) { + return at::_ops::masked_select_out::call(self, mask, out); +} +// aten::masked_select.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & masked_select_outf(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out) { + return at::_ops::masked_select_out::call(self, mask, out); +} + +// aten::masked_select(Tensor self, Tensor mask) -> Tensor +inline at::Tensor masked_select(const at::Tensor & self, const at::Tensor & mask) { + return at::_ops::masked_select::call(self, mask); +} + +} diff --git a/shared/package-files/7b/7b11e6144b7264c2615584d6152065319856761424e8cd9c8e0364bc8983ee8e/blob b/shared/package-files/7b/7b11e6144b7264c2615584d6152065319856761424e8cd9c8e0364bc8983ee8e/blob new file mode 100644 index 0000000000000000000000000000000000000000..03e933e9c10f348c88fc8a93c1170216d74de128 --- /dev/null +++ b/shared/package-files/7b/7b11e6144b7264c2615584d6152065319856761424e8cd9c8e0364bc8983ee8e/blob @@ -0,0 +1,741 @@ +from sympy.core.function import expand_func, Subs +from sympy.core import EulerGamma +from sympy.core.numbers import (I, Rational, nan, oo, pi, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol) +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.combinatorial.numbers import harmonic +from sympy.functions.elementary.complexes import (Abs, conjugate, im, re) +from sympy.functions.elementary.exponential import (exp, exp_polar, log) +from sympy.functions.elementary.hyperbolic import tanh +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin, atan) +from sympy.functions.special.error_functions import (Ei, erf, erfc) +from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, lowergamma, multigamma, polygamma, trigamma, uppergamma) +from sympy.functions.special.zeta_functions import zeta +from sympy.series.order import O + +from sympy.core.expr import unchanged +from sympy.core.function import ArgumentIndexError +from sympy.testing.pytest import raises +from sympy.core.random import (test_derivative_numerically as td, + random_complex_number as randcplx, + verify_numerically as tn) + +x = Symbol('x') +y = Symbol('y') +n = Symbol('n', integer=True) +w = Symbol('w', real=True) + +def test_gamma(): + assert gamma(nan) is nan + assert gamma(oo) is oo + + assert gamma(-100) is zoo + assert gamma(0) is zoo + assert gamma(-100.0) is zoo + + assert gamma(1) == 1 + assert gamma(2) == 1 + assert gamma(3) == 2 + + assert gamma(102) == factorial(101) + + assert gamma(S.Half) == sqrt(pi) + + assert gamma(Rational(3, 2)) == sqrt(pi)*S.Half + assert gamma(Rational(5, 2)) == sqrt(pi)*Rational(3, 4) + assert gamma(Rational(7, 2)) == sqrt(pi)*Rational(15, 8) + + assert gamma(Rational(-1, 2)) == -2*sqrt(pi) + assert gamma(Rational(-3, 2)) == sqrt(pi)*Rational(4, 3) + assert gamma(Rational(-5, 2)) == sqrt(pi)*Rational(-8, 15) + + assert gamma(Rational(-15, 2)) == sqrt(pi)*Rational(256, 2027025) + + assert gamma(Rational( + -11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8)) + assert gamma(Rational( + -10, 3)).expand(func=True) == Rational(81, 280)*gamma(Rational(2, 3)) + assert gamma(Rational( + 14, 3)).expand(func=True) == Rational(880, 81)*gamma(Rational(2, 3)) + assert gamma(Rational( + 17, 7)).expand(func=True) == Rational(30, 49)*gamma(Rational(3, 7)) + assert gamma(Rational( + 19, 8)).expand(func=True) == Rational(33, 64)*gamma(Rational(3, 8)) + + assert gamma(x).diff(x) == gamma(x)*polygamma(0, x) + + assert gamma(x - 1).expand(func=True) == gamma(x)/(x - 1) + assert gamma(x + 2).expand(func=True, mul=False) == x*(x + 1)*gamma(x) + + assert conjugate(gamma(x)) == gamma(conjugate(x)) + + assert expand_func(gamma(x + Rational(3, 2))) == \ + (x + S.Half)*gamma(x + S.Half) + + assert expand_func(gamma(x - S.Half)) == \ + gamma(S.Half + x)/(x - S.Half) + + # Test a bug: + assert expand_func(gamma(x + Rational(3, 4))) == gamma(x + Rational(3, 4)) + + # XXX: Not sure about these tests. I can fix them by defining e.g. + # exp_polar.is_integer but I'm not sure if that makes sense. + assert gamma(3*exp_polar(I*pi)/4).is_nonnegative is False + assert gamma(3*exp_polar(I*pi)/4).is_extended_nonpositive is True + + y = Symbol('y', nonpositive=True, integer=True) + assert gamma(y).is_real == False + y = Symbol('y', positive=True, noninteger=True) + assert gamma(y).is_real == True + + assert gamma(-1.0, evaluate=False).is_real == False + assert gamma(0, evaluate=False).is_real == False + assert gamma(-2, evaluate=False).is_real == False + + +def test_gamma_rewrite(): + assert gamma(n).rewrite(factorial) == factorial(n - 1) + + +def test_gamma_series(): + assert gamma(x + 1).series(x, 0, 3) == \ + 1 - EulerGamma*x + x**2*(EulerGamma**2/2 + pi**2/12) + O(x**3) + assert gamma(x).series(x, -1, 3) == \ + -1/(x + 1) + EulerGamma - 1 + (x + 1)*(-1 - pi**2/12 - EulerGamma**2/2 + \ + EulerGamma) + (x + 1)**2*(-1 - pi**2/12 - EulerGamma**2/2 + EulerGamma**3/6 - \ + polygamma(2, 1)/6 + EulerGamma*pi**2/12 + EulerGamma) + O((x + 1)**3, (x, -1)) + + +def tn_branch(s, func): + from sympy.core.random import uniform + c = uniform(1, 5) + expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) + eps = 1e-15 + expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) + return abs(expr.n() - expr2.n()).n() < 1e-10 + + +def test_lowergamma(): + from sympy.functions.special.error_functions import expint + from sympy.functions.special.hyper import meijerg + assert lowergamma(x, 0) == 0 + assert lowergamma(x, y).diff(y) == y**(x - 1)*exp(-y) + assert td(lowergamma(randcplx(), y), y) + assert td(lowergamma(x, randcplx()), x) + assert lowergamma(x, y).diff(x) == \ + gamma(x)*digamma(x) - uppergamma(x, y)*log(y) \ + - meijerg([], [1, 1], [0, 0, x], [], y) + + assert lowergamma(S.Half, x) == sqrt(pi)*erf(sqrt(x)) + assert not lowergamma(S.Half - 3, x).has(lowergamma) + assert not lowergamma(S.Half + 3, x).has(lowergamma) + assert lowergamma(S.Half, x, evaluate=False).has(lowergamma) + assert tn(lowergamma(S.Half + 3, x, evaluate=False), + lowergamma(S.Half + 3, x), x) + assert tn(lowergamma(S.Half - 3, x, evaluate=False), + lowergamma(S.Half - 3, x), x) + + assert tn_branch(-3, lowergamma) + assert tn_branch(-4, lowergamma) + assert tn_branch(Rational(1, 3), lowergamma) + assert tn_branch(pi, lowergamma) + assert lowergamma(3, exp_polar(4*pi*I)*x) == lowergamma(3, x) + assert lowergamma(y, exp_polar(5*pi*I)*x) == \ + exp(4*I*pi*y)*lowergamma(y, x*exp_polar(pi*I)) + assert lowergamma(-2, exp_polar(5*pi*I)*x) == \ + lowergamma(-2, x*exp_polar(I*pi)) + 2*pi*I + + assert conjugate(lowergamma(x, y)) == lowergamma(conjugate(x), conjugate(y)) + assert conjugate(lowergamma(x, 0)) == 0 + assert unchanged(conjugate, lowergamma(x, -oo)) + + assert lowergamma(0, x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(S(1)/3, x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(1, x, evaluate=False)._eval_is_meromorphic(x, 0) == True + assert lowergamma(x, x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(x + 1, x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(1/x, x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(0, x + 1)._eval_is_meromorphic(x, 0) == False + assert lowergamma(S(1)/3, x + 1)._eval_is_meromorphic(x, 0) == True + assert lowergamma(1, x + 1, evaluate=False)._eval_is_meromorphic(x, 0) == True + assert lowergamma(x, x + 1)._eval_is_meromorphic(x, 0) == True + assert lowergamma(x + 1, x + 1)._eval_is_meromorphic(x, 0) == True + assert lowergamma(1/x, x + 1)._eval_is_meromorphic(x, 0) == False + assert lowergamma(0, 1/x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(S(1)/3, 1/x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(1, 1/x, evaluate=False)._eval_is_meromorphic(x, 0) == False + assert lowergamma(x, 1/x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(x + 1, 1/x)._eval_is_meromorphic(x, 0) == False + assert lowergamma(1/x, 1/x)._eval_is_meromorphic(x, 0) == False + + assert lowergamma(x, 2).series(x, oo, 3) == \ + 2**x*(1 + 2/(x + 1))*exp(-2)/x + O(exp(x*log(2))/x**3, (x, oo)) + + assert lowergamma( + x, y).rewrite(expint) == -y**x*expint(-x + 1, y) + gamma(x) + k = Symbol('k', integer=True) + assert lowergamma( + k, y).rewrite(expint) == -y**k*expint(-k + 1, y) + gamma(k) + k = Symbol('k', integer=True, positive=False) + assert lowergamma(k, y).rewrite(expint) == lowergamma(k, y) + assert lowergamma(x, y).rewrite(uppergamma) == gamma(x) - uppergamma(x, y) + + assert lowergamma(70, 6) == factorial(69) - 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320 * exp(-6) + assert (lowergamma(S(77) / 2, 6) - lowergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 + assert (lowergamma(-S(77) / 2, 6) - lowergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 + + +def test_uppergamma(): + from sympy.functions.special.error_functions import expint + from sympy.functions.special.hyper import meijerg + assert uppergamma(4, 0) == 6 + assert uppergamma(x, y).diff(y) == -y**(x - 1)*exp(-y) + assert td(uppergamma(randcplx(), y), y) + assert uppergamma(x, y).diff(x) == \ + uppergamma(x, y)*log(y) + meijerg([], [1, 1], [0, 0, x], [], y) + assert td(uppergamma(x, randcplx()), x) + + p = Symbol('p', positive=True) + assert uppergamma(0, p) == -Ei(-p) + assert uppergamma(p, 0) == gamma(p) + assert uppergamma(S.Half, x) == sqrt(pi)*erfc(sqrt(x)) + assert not uppergamma(S.Half - 3, x).has(uppergamma) + assert not uppergamma(S.Half + 3, x).has(uppergamma) + assert uppergamma(S.Half, x, evaluate=False).has(uppergamma) + assert tn(uppergamma(S.Half + 3, x, evaluate=False), + uppergamma(S.Half + 3, x), x) + assert tn(uppergamma(S.Half - 3, x, evaluate=False), + uppergamma(S.Half - 3, x), x) + + assert unchanged(uppergamma, x, -oo) + assert unchanged(uppergamma, x, 0) + + assert tn_branch(-3, uppergamma) + assert tn_branch(-4, uppergamma) + assert tn_branch(Rational(1, 3), uppergamma) + assert tn_branch(pi, uppergamma) + assert uppergamma(3, exp_polar(4*pi*I)*x) == uppergamma(3, x) + assert uppergamma(y, exp_polar(5*pi*I)*x) == \ + exp(4*I*pi*y)*uppergamma(y, x*exp_polar(pi*I)) + \ + gamma(y)*(1 - exp(4*pi*I*y)) + assert uppergamma(-2, exp_polar(5*pi*I)*x) == \ + uppergamma(-2, x*exp_polar(I*pi)) - 2*pi*I + + assert uppergamma(-2, x) == expint(3, x)/x**2 + + assert conjugate(uppergamma(x, y)) == uppergamma(conjugate(x), conjugate(y)) + assert unchanged(conjugate, uppergamma(x, -oo)) + + assert uppergamma(x, y).rewrite(expint) == y**x*expint(-x + 1, y) + assert uppergamma(x, y).rewrite(lowergamma) == gamma(x) - lowergamma(x, y) + + assert uppergamma(70, 6) == 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320*exp(-6) + assert (uppergamma(S(77) / 2, 6) - uppergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 + assert (uppergamma(-S(77) / 2, 6) - uppergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 + + +def test_polygamma(): + assert polygamma(n, nan) is nan + + assert polygamma(0, oo) is oo + assert polygamma(0, -oo) is oo + assert polygamma(0, I*oo) is oo + assert polygamma(0, -I*oo) is oo + assert polygamma(1, oo) == 0 + assert polygamma(5, oo) == 0 + + assert polygamma(0, -9) is zoo + + assert polygamma(0, -9) is zoo + assert polygamma(0, -1) is zoo + assert polygamma(Rational(3, 2), -1) is zoo + + assert polygamma(0, 0) is zoo + + assert polygamma(0, 1) == -EulerGamma + assert polygamma(0, 7) == Rational(49, 20) - EulerGamma + + assert polygamma(1, 1) == pi**2/6 + assert polygamma(1, 2) == pi**2/6 - 1 + assert polygamma(1, 3) == pi**2/6 - Rational(5, 4) + assert polygamma(3, 1) == pi**4 / 15 + assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90) + assert polygamma(5, 1) == 8 * pi**6 / 63 + + assert polygamma(1, S.Half) == pi**2 / 2 + assert polygamma(2, S.Half) == -14*zeta(3) + assert polygamma(11, S.Half) == 176896*pi**12 + + def t(m, n): + x = S(m)/n + r = polygamma(0, x) + if r.has(polygamma): + return False + return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10 + assert t(1, 2) + assert t(3, 2) + assert t(-1, 2) + assert t(1, 4) + assert t(-3, 4) + assert t(1, 3) + assert t(4, 3) + assert t(3, 4) + assert t(2, 3) + assert t(123, 5) + + assert polygamma(0, x).rewrite(zeta) == polygamma(0, x) + assert polygamma(1, x).rewrite(zeta) == zeta(2, x) + assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x) + assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2) + n1 = Symbol('n1') + n2 = Symbol('n2', real=True) + n3 = Symbol('n3', integer=True) + n4 = Symbol('n4', positive=True) + n5 = Symbol('n5', positive=True, integer=True) + assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x) + assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x) + assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x) + assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x) + assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x) + + assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x) + + assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma + assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3) + ni = Symbol("n", integer=True) + assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1) + + zeta(ni + 1))*factorial(ni) + + # Polygamma of non-negative integer order is unbranched: + k = Symbol('n', integer=True, nonnegative=True) + assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x) + + # but negative integers are branched! + k = Symbol('n', integer=True) + assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x) + + # Polygamma of order -1 is loggamma: + assert polygamma(-1, x) == loggamma(x) - log(2*pi) / 2 + + # But smaller orders are iterated integrals and don't have a special name + assert polygamma(-2, x).func is polygamma + + # Test a bug + assert polygamma(0, -x).expand(func=True) == polygamma(0, -x) + + assert polygamma(2, 2.5).is_positive == False + assert polygamma(2, -2.5).is_positive == False + assert polygamma(3, 2.5).is_positive == True + assert polygamma(3, -2.5).is_positive is True + assert polygamma(-2, -2.5).is_positive is None + assert polygamma(-3, -2.5).is_positive is None + + assert polygamma(2, 2.5).is_negative == True + assert polygamma(3, 2.5).is_negative == False + assert polygamma(3, -2.5).is_negative == False + assert polygamma(2, -2.5).is_negative is True + assert polygamma(-2, -2.5).is_negative is None + assert polygamma(-3, -2.5).is_negative is None + + assert polygamma(I, 2).is_positive is None + assert polygamma(I, 3).is_negative is None + + # issue 17350 + assert (I*polygamma(I, pi)).as_real_imag() == \ + (-im(polygamma(I, pi)), re(polygamma(I, pi))) + assert (tanh(polygamma(I, 1))).rewrite(exp) == \ + (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1))) + assert (I / polygamma(I, 4)).rewrite(exp) == \ + I*exp(-I*atan(im(polygamma(I, 4))/re(polygamma(I, 4))))/Abs(polygamma(I, 4)) + + # issue 12569 + assert unchanged(im, polygamma(0, I)) + assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True + assert polygamma(0, I).is_real is None + + assert str(polygamma(pi, 3).evalf(n=10)) == "0.1169314564" + assert str(polygamma(2.3, 1.0).evalf(n=10)) == "-3.003302909" + assert str(polygamma(-1, 1).evalf(n=10)) == "-0.9189385332" # not zero + assert str(polygamma(I, 1).evalf(n=10)) == "-3.109856569 + 1.89089016*I" + assert str(polygamma(1, I).evalf(n=10)) == "-0.5369999034 - 0.7942335428*I" + assert str(polygamma(I, I).evalf(n=10)) == "6.332362889 + 45.92828268*I" + + +def test_polygamma_expand_func(): + assert polygamma(0, x).expand(func=True) == polygamma(0, x) + assert polygamma(0, 2*x).expand(func=True) == \ + polygamma(0, x)/2 + polygamma(0, S.Half + x)/2 + log(2) + assert polygamma(1, 2*x).expand(func=True) == \ + polygamma(1, x)/4 + polygamma(1, S.Half + x)/4 + assert polygamma(2, x).expand(func=True) == \ + polygamma(2, x) + assert polygamma(0, -1 + x).expand(func=True) == \ + polygamma(0, x) - 1/(x - 1) + assert polygamma(0, 1 + x).expand(func=True) == \ + 1/x + polygamma(0, x ) + assert polygamma(0, 2 + x).expand(func=True) == \ + 1/x + 1/(1 + x) + polygamma(0, x) + assert polygamma(0, 3 + x).expand(func=True) == \ + polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + assert polygamma(0, 4 + x).expand(func=True) == \ + polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) + assert polygamma(1, 1 + x).expand(func=True) == \ + polygamma(1, x) - 1/x**2 + assert polygamma(1, 2 + x).expand(func=True, multinomial=False) == \ + polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 + assert polygamma(1, 3 + x).expand(func=True, multinomial=False) == \ + polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 + assert polygamma(1, 4 + x).expand(func=True, multinomial=False) == \ + polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ + 1/(2 + x)**2 - 1/(3 + x)**2 + assert polygamma(0, x + y).expand(func=True) == \ + polygamma(0, x + y) + assert polygamma(1, x + y).expand(func=True) == \ + polygamma(1, x + y) + assert polygamma(1, 3 + 4*x + y).expand(func=True, multinomial=False) == \ + polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ + 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 + assert polygamma(3, 3 + 4*x + y).expand(func=True, multinomial=False) == \ + polygamma(3, y + 4*x) - 6/(y + 4*x)**4 - \ + 6/(1 + y + 4*x)**4 - 6/(2 + y + 4*x)**4 + assert polygamma(3, 4*x + y + 1).expand(func=True, multinomial=False) == \ + polygamma(3, y + 4*x) - 6/(y + 4*x)**4 + e = polygamma(3, 4*x + y + Rational(3, 2)) + assert e.expand(func=True) == e + e = polygamma(3, x + y + Rational(3, 4)) + assert e.expand(func=True, basic=False) == e + + assert polygamma(-1, x, evaluate=False).expand(func=True) == \ + loggamma(x) - log(pi)/2 - log(2)/2 + p2 = polygamma(-2, x).expand(func=True) + x**2/2 - x/2 + S(1)/12 + assert isinstance(p2, Subs) + assert p2.point == (-1,) + + +def test_digamma(): + assert digamma(nan) == nan + + assert digamma(oo) == oo + assert digamma(-oo) == oo + assert digamma(I*oo) == oo + assert digamma(-I*oo) == oo + + assert digamma(-9) == zoo + + assert digamma(-9) == zoo + assert digamma(-1) == zoo + + assert digamma(0) == zoo + + assert digamma(1) == -EulerGamma + assert digamma(7) == Rational(49, 20) - EulerGamma + + def t(m, n): + x = S(m)/n + r = digamma(x) + if r.has(digamma): + return False + return abs(digamma(x.n()).n() - r.n()).n() < 1e-10 + assert t(1, 2) + assert t(3, 2) + assert t(-1, 2) + assert t(1, 4) + assert t(-3, 4) + assert t(1, 3) + assert t(4, 3) + assert t(3, 4) + assert t(2, 3) + assert t(123, 5) + + assert digamma(x).rewrite(zeta) == polygamma(0, x) + + assert digamma(x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma + + assert digamma(I).is_real is None + + assert digamma(x,evaluate=False).fdiff() == polygamma(1, x) + + assert digamma(x,evaluate=False).is_real is None + + assert digamma(x,evaluate=False).is_positive is None + + assert digamma(x,evaluate=False).is_negative is None + + assert digamma(x,evaluate=False).rewrite(polygamma) == polygamma(0, x) + + +def test_digamma_expand_func(): + assert digamma(x).expand(func=True) == polygamma(0, x) + assert digamma(2*x).expand(func=True) == \ + polygamma(0, x)/2 + polygamma(0, Rational(1, 2) + x)/2 + log(2) + assert digamma(-1 + x).expand(func=True) == \ + polygamma(0, x) - 1/(x - 1) + assert digamma(1 + x).expand(func=True) == \ + 1/x + polygamma(0, x ) + assert digamma(2 + x).expand(func=True) == \ + 1/x + 1/(1 + x) + polygamma(0, x) + assert digamma(3 + x).expand(func=True) == \ + polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + assert digamma(4 + x).expand(func=True) == \ + polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) + assert digamma(x + y).expand(func=True) == \ + polygamma(0, x + y) + +def test_trigamma(): + assert trigamma(nan) == nan + + assert trigamma(oo) == 0 + + assert trigamma(1) == pi**2/6 + assert trigamma(2) == pi**2/6 - 1 + assert trigamma(3) == pi**2/6 - Rational(5, 4) + + assert trigamma(x, evaluate=False).rewrite(zeta) == zeta(2, x) + assert trigamma(x, evaluate=False).rewrite(harmonic) == \ + trigamma(x).rewrite(polygamma).rewrite(harmonic) + + assert trigamma(x,evaluate=False).fdiff() == polygamma(2, x) + + assert trigamma(x,evaluate=False).is_real is None + + assert trigamma(x,evaluate=False).is_positive is None + + assert trigamma(x,evaluate=False).is_negative is None + + assert trigamma(x,evaluate=False).rewrite(polygamma) == polygamma(1, x) + +def test_trigamma_expand_func(): + assert trigamma(2*x).expand(func=True) == \ + polygamma(1, x)/4 + polygamma(1, Rational(1, 2) + x)/4 + assert trigamma(1 + x).expand(func=True) == \ + polygamma(1, x) - 1/x**2 + assert trigamma(2 + x).expand(func=True, multinomial=False) == \ + polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 + assert trigamma(3 + x).expand(func=True, multinomial=False) == \ + polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 + assert trigamma(4 + x).expand(func=True, multinomial=False) == \ + polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ + 1/(2 + x)**2 - 1/(3 + x)**2 + assert trigamma(x + y).expand(func=True) == \ + polygamma(1, x + y) + assert trigamma(3 + 4*x + y).expand(func=True, multinomial=False) == \ + polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ + 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 + +def test_loggamma(): + raises(TypeError, lambda: loggamma(2, 3)) + raises(ArgumentIndexError, lambda: loggamma(x).fdiff(2)) + + assert loggamma(-1) is oo + assert loggamma(-2) is oo + assert loggamma(0) is oo + assert loggamma(1) == 0 + assert loggamma(2) == 0 + assert loggamma(3) == log(2) + assert loggamma(4) == log(6) + + n = Symbol("n", integer=True, positive=True) + assert loggamma(n) == log(gamma(n)) + assert loggamma(-n) is oo + assert loggamma(n/2) == log(2**(-n + 1)*sqrt(pi)*gamma(n)/gamma(n/2 + S.Half)) + + assert loggamma(oo) is oo + assert loggamma(-oo) is zoo + assert loggamma(I*oo) is zoo + assert loggamma(-I*oo) is zoo + assert loggamma(zoo) is zoo + assert loggamma(nan) is nan + + L = loggamma(Rational(16, 3)) + E = -5*log(3) + loggamma(Rational(1, 3)) + log(4) + log(7) + log(10) + log(13) + assert expand_func(L).doit() == E + assert L.n() == E.n() + + L = loggamma(Rational(19, 4)) + E = -4*log(4) + loggamma(Rational(3, 4)) + log(3) + log(7) + log(11) + log(15) + assert expand_func(L).doit() == E + assert L.n() == E.n() + + L = loggamma(Rational(23, 7)) + E = -3*log(7) + log(2) + loggamma(Rational(2, 7)) + log(9) + log(16) + assert expand_func(L).doit() == E + assert L.n() == E.n() + + L = loggamma(Rational(19, 4) - 7) + E = -log(9) - log(5) + loggamma(Rational(3, 4)) + 3*log(4) - 3*I*pi + assert expand_func(L).doit() == E + assert L.n() == E.n() + + L = loggamma(Rational(23, 7) - 6) + E = -log(19) - log(12) - log(5) + loggamma(Rational(2, 7)) + 3*log(7) - 3*I*pi + assert expand_func(L).doit() == E + assert L.n() == E.n() + + assert loggamma(x).diff(x) == polygamma(0, x) + s1 = loggamma(1/(x + sin(x)) + cos(x)).nseries(x, n=4) + s2 = (-log(2*x) - 1)/(2*x) - log(x/pi)/2 + (4 - log(2*x))*x/24 + O(x**2) + \ + log(x)*x**2/2 + assert (s1 - s2).expand(force=True).removeO() == 0 + s1 = loggamma(1/x).series(x) + s2 = (1/x - S.Half)*log(1/x) - 1/x + log(2*pi)/2 + \ + x/12 - x**3/360 + x**5/1260 + O(x**7) + assert ((s1 - s2).expand(force=True)).removeO() == 0 + + assert loggamma(x).rewrite('intractable') == log(gamma(x)) + + s1 = loggamma(x).series(x).cancel() + assert s1 == -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + \ + pi**4*x**4/360 + x**5*polygamma(4, 1)/120 + O(x**6) + assert s1 == loggamma(x).rewrite('intractable').series(x).cancel() + + assert conjugate(loggamma(x)) == loggamma(conjugate(x)) + assert conjugate(loggamma(0)) is oo + assert conjugate(loggamma(1)) == loggamma(conjugate(1)) + assert conjugate(loggamma(-oo)) == conjugate(zoo) + + assert loggamma(Symbol('v', positive=True)).is_real is True + assert loggamma(Symbol('v', zero=True)).is_real is False + assert loggamma(Symbol('v', negative=True)).is_real is False + assert loggamma(Symbol('v', nonpositive=True)).is_real is False + assert loggamma(Symbol('v', nonnegative=True)).is_real is None + assert loggamma(Symbol('v', imaginary=True)).is_real is None + assert loggamma(Symbol('v', real=True)).is_real is None + assert loggamma(Symbol('v')).is_real is None + + assert loggamma(S.Half).is_real is True + assert loggamma(0).is_real is False + assert loggamma(Rational(-1, 2)).is_real is False + assert loggamma(I).is_real is None + assert loggamma(2 + 3*I).is_real is None + + def tN(N, M): + assert loggamma(1/x)._eval_nseries(x, n=N).getn() == M + tN(0, 0) + tN(1, 1) + tN(2, 2) + tN(3, 3) + tN(4, 4) + tN(5, 5) + + +def test_polygamma_expansion(): + # A. & S., pa. 259 and 260 + assert polygamma(0, 1/x).nseries(x, n=3) == \ + -log(x) - x/2 - x**2/12 + O(x**3) + assert polygamma(1, 1/x).series(x, n=5) == \ + x + x**2/2 + x**3/6 + O(x**5) + assert polygamma(3, 1/x).nseries(x, n=11) == \ + 2*x**3 + 3*x**4 + 2*x**5 - x**7 + 4*x**9/3 + O(x**11) + + +def test_polygamma_leading_term(): + expr = -log(1/x) + polygamma(0, 1 + 1/x) + S.EulerGamma + assert expr.as_leading_term(x, logx=-y) == S.EulerGamma + + +def test_issue_8657(): + n = Symbol('n', negative=True, integer=True) + m = Symbol('m', integer=True) + o = Symbol('o', positive=True) + p = Symbol('p', negative=True, integer=False) + assert gamma(n).is_real is False + assert gamma(m).is_real is None + assert gamma(o).is_real is True + assert gamma(p).is_real is True + assert gamma(w).is_real is None + + +def test_issue_8524(): + x = Symbol('x', positive=True) + y = Symbol('y', negative=True) + z = Symbol('z', positive=False) + p = Symbol('p', negative=False) + q = Symbol('q', integer=True) + r = Symbol('r', integer=False) + e = Symbol('e', even=True, negative=True) + assert gamma(x).is_positive is True + assert gamma(y).is_positive is None + assert gamma(z).is_positive is None + assert gamma(p).is_positive is None + assert gamma(q).is_positive is None + assert gamma(r).is_positive is None + assert gamma(e + S.Half).is_positive is True + assert gamma(e - S.Half).is_positive is False + +def test_issue_14450(): + assert uppergamma(Rational(3, 8), x).evalf() == uppergamma(Rational(3, 8), x) + assert lowergamma(x, Rational(3, 8)).evalf() == lowergamma(x, Rational(3, 8)) + # some values from Wolfram Alpha for comparison + assert abs(uppergamma(Rational(3, 8), 2).evalf() - 0.07105675881) < 1e-9 + assert abs(lowergamma(Rational(3, 8), 2).evalf() - 2.2993794256) < 1e-9 + +def test_issue_14528(): + k = Symbol('k', integer=True, nonpositive=True) + assert isinstance(gamma(k), gamma) + +def test_multigamma(): + from sympy.concrete.products import Product + p = Symbol('p') + _k = Dummy('_k') + + assert multigamma(x, p).dummy_eq(pi**(p*(p - 1)/4)*\ + Product(gamma(x + (1 - _k)/2), (_k, 1, p))) + + assert conjugate(multigamma(x, p)).dummy_eq(pi**((conjugate(p) - 1)*\ + conjugate(p)/4)*Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) + assert conjugate(multigamma(x, 1)) == gamma(conjugate(x)) + + p = Symbol('p', positive=True) + assert conjugate(multigamma(x, p)).dummy_eq(pi**((p - 1)*p/4)*\ + Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) + + assert multigamma(nan, 1) is nan + assert multigamma(oo, 1).doit() is oo + + assert multigamma(1, 1) == 1 + assert multigamma(2, 1) == 1 + assert multigamma(3, 1) == 2 + + assert multigamma(102, 1) == factorial(101) + assert multigamma(S.Half, 1) == sqrt(pi) + + assert multigamma(1, 2) == pi + assert multigamma(2, 2) == pi/2 + + assert multigamma(1, 3) is zoo + assert multigamma(2, 3) == pi**2/2 + assert multigamma(3, 3) == 3*pi**2/2 + + assert multigamma(x, 1).diff(x) == gamma(x)*polygamma(0, x) + assert multigamma(x, 2).diff(x) == sqrt(pi)*gamma(x)*gamma(x - S.Half)*\ + polygamma(0, x) + sqrt(pi)*gamma(x)*gamma(x - S.Half)*polygamma(0, x - S.Half) + + assert multigamma(x - 1, 1).expand(func=True) == gamma(x)/(x - 1) + assert multigamma(x + 2, 1).expand(func=True, mul=False) == x*(x + 1)*\ + gamma(x) + assert multigamma(x - 1, 2).expand(func=True) == sqrt(pi)*gamma(x)*\ + gamma(x + S.Half)/(x**3 - 3*x**2 + x*Rational(11, 4) - Rational(3, 4)) + assert multigamma(x - 1, 3).expand(func=True) == pi**Rational(3, 2)*gamma(x)**2*\ + gamma(x + S.Half)/(x**5 - 6*x**4 + 55*x**3/4 - 15*x**2 + x*Rational(31, 4) - Rational(3, 2)) + + assert multigamma(n, 1).rewrite(factorial) == factorial(n - 1) + assert multigamma(n, 2).rewrite(factorial) == sqrt(pi)*\ + factorial(n - Rational(3, 2))*factorial(n - 1) + assert multigamma(n, 3).rewrite(factorial) == pi**Rational(3, 2)*\ + factorial(n - 2)*factorial(n - Rational(3, 2))*factorial(n - 1) + + assert multigamma(Rational(-1, 2), 3, evaluate=False).is_real == False + assert multigamma(S.Half, 3, evaluate=False).is_real == False + assert multigamma(0, 1, evaluate=False).is_real == False + assert multigamma(1, 3, evaluate=False).is_real == False + assert multigamma(-1.0, 3, evaluate=False).is_real == False + assert multigamma(0.7, 3, evaluate=False).is_real == True + assert multigamma(3, 3, evaluate=False).is_real == True + +def test_gamma_as_leading_term(): + assert gamma(x).as_leading_term(x) == 1/x + assert gamma(2 + x).as_leading_term(x) == S(1) + assert gamma(cos(x)).as_leading_term(x) == S(1) + assert gamma(sin(x)).as_leading_term(x) == 1/x diff --git a/shared/package-files/7b/7b12f028f764293a9496d9fd2ddbf92ba9c23653d7889a602a9ec23f8cde3d6b/blob b/shared/package-files/7b/7b12f028f764293a9496d9fd2ddbf92ba9c23653d7889a602a9ec23f8cde3d6b/blob new file mode 100644 index 0000000000000000000000000000000000000000..b0b8696d08099780eb79a72e7a522dcc7b934958 Binary files /dev/null and b/shared/package-files/7b/7b12f028f764293a9496d9fd2ddbf92ba9c23653d7889a602a9ec23f8cde3d6b/blob differ diff --git a/shared/package-files/7b/7b137b14ed43577fc114110754f1e675c0388da18d00c672223ee7ba829745f7/blob b/shared/package-files/7b/7b137b14ed43577fc114110754f1e675c0388da18d00c672223ee7ba829745f7/blob new file mode 100644 index 0000000000000000000000000000000000000000..1f64a0469d430cfacd71e0d9a2e72eb73fb28c66 Binary files /dev/null and b/shared/package-files/7b/7b137b14ed43577fc114110754f1e675c0388da18d00c672223ee7ba829745f7/blob differ diff --git a/shared/package-files/7b/7b14aa02788e3ec8f3f68aa73120bdfdb9771aba3c4f0db6af2482707322fcb5/blob b/shared/package-files/7b/7b14aa02788e3ec8f3f68aa73120bdfdb9771aba3c4f0db6af2482707322fcb5/blob new file mode 100644 index 0000000000000000000000000000000000000000..752e9db5ba5d909aad96d679a468b228942bd9b3 --- /dev/null +++ b/shared/package-files/7b/7b14aa02788e3ec8f3f68aa73120bdfdb9771aba3c4f0db6af2482707322fcb5/blob @@ -0,0 +1,493 @@ +"""Tests for distutils.command.sdist.""" +import os +import tarfile +import unittest +import warnings +import zipfile +from os.path import join +from textwrap import dedent +from test.support import captured_stdout, run_unittest +from test.support.warnings_helper import check_warnings + +try: + import zlib + ZLIB_SUPPORT = True +except ImportError: + ZLIB_SUPPORT = False + +try: + import grp + import pwd + UID_GID_SUPPORT = True +except ImportError: + UID_GID_SUPPORT = False + +from distutils.command.sdist import sdist, show_formats +from distutils.core import Distribution +from distutils.tests.test_config import BasePyPIRCCommandTestCase +from distutils.errors import DistutilsOptionError +from distutils.spawn import find_executable +from distutils.log import WARN +from distutils.filelist import FileList +from distutils.archive_util import ARCHIVE_FORMATS + +SETUP_PY = """ +from distutils.core import setup +import somecode + +setup(name='fake') +""" + +MANIFEST = """\ +# file GENERATED by distutils, do NOT edit +README +buildout.cfg +inroot.txt +setup.py +data%(sep)sdata.dt +scripts%(sep)sscript.py +some%(sep)sfile.txt +some%(sep)sother_file.txt +somecode%(sep)s__init__.py +somecode%(sep)sdoc.dat +somecode%(sep)sdoc.txt +""" + +class SDistTestCase(BasePyPIRCCommandTestCase): + + def setUp(self): + # PyPIRCCommandTestCase creates a temp dir already + # and put it in self.tmp_dir + super(SDistTestCase, self).setUp() + # setting up an environment + self.old_path = os.getcwd() + os.mkdir(join(self.tmp_dir, 'somecode')) + os.mkdir(join(self.tmp_dir, 'dist')) + # a package, and a README + self.write_file((self.tmp_dir, 'README'), 'xxx') + self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#') + self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY) + os.chdir(self.tmp_dir) + + def tearDown(self): + # back to normal + os.chdir(self.old_path) + super(SDistTestCase, self).tearDown() + + def get_cmd(self, metadata=None): + """Returns a cmd""" + if metadata is None: + metadata = {'name': 'fake', 'version': '1.0', + 'url': 'xxx', 'author': 'xxx', + 'author_email': 'xxx'} + dist = Distribution(metadata) + dist.script_name = 'setup.py' + dist.packages = ['somecode'] + dist.include_package_data = True + cmd = sdist(dist) + cmd.dist_dir = 'dist' + return dist, cmd + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_prune_file_list(self): + # this test creates a project with some VCS dirs and an NFS rename + # file, then launches sdist to check they get pruned on all systems + + # creating VCS directories with some files in them + os.mkdir(join(self.tmp_dir, 'somecode', '.svn')) + self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx') + + os.mkdir(join(self.tmp_dir, 'somecode', '.hg')) + self.write_file((self.tmp_dir, 'somecode', '.hg', + 'ok'), 'xxx') + + os.mkdir(join(self.tmp_dir, 'somecode', '.git')) + self.write_file((self.tmp_dir, 'somecode', '.git', + 'ok'), 'xxx') + + self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx') + + # now building a sdist + dist, cmd = self.get_cmd() + + # zip is available universally + # (tar might not be installed under win32) + cmd.formats = ['zip'] + + cmd.ensure_finalized() + cmd.run() + + # now let's check what we have + dist_folder = join(self.tmp_dir, 'dist') + files = os.listdir(dist_folder) + self.assertEqual(files, ['fake-1.0.zip']) + + zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) + try: + content = zip_file.namelist() + finally: + zip_file.close() + + # making sure everything has been pruned correctly + expected = ['', 'PKG-INFO', 'README', 'setup.py', + 'somecode/', 'somecode/__init__.py'] + self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected]) + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + @unittest.skipIf(find_executable('tar') is None, + "The tar command is not found") + @unittest.skipIf(find_executable('gzip') is None, + "The gzip command is not found") + def test_make_distribution(self): + # now building a sdist + dist, cmd = self.get_cmd() + + # creating a gztar then a tar + cmd.formats = ['gztar', 'tar'] + cmd.ensure_finalized() + cmd.run() + + # making sure we have two files + dist_folder = join(self.tmp_dir, 'dist') + result = os.listdir(dist_folder) + result.sort() + self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) + + os.remove(join(dist_folder, 'fake-1.0.tar')) + os.remove(join(dist_folder, 'fake-1.0.tar.gz')) + + # now trying a tar then a gztar + cmd.formats = ['tar', 'gztar'] + + cmd.ensure_finalized() + cmd.run() + + result = os.listdir(dist_folder) + result.sort() + self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_add_defaults(self): + + # http://bugs.python.org/issue2279 + + # add_default should also include + # data_files and package_data + dist, cmd = self.get_cmd() + + # filling data_files by pointing files + # in package_data + dist.package_data = {'': ['*.cfg', '*.dat'], + 'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#') + + # adding some data in data_files + data_dir = join(self.tmp_dir, 'data') + os.mkdir(data_dir) + self.write_file((data_dir, 'data.dt'), '#') + some_dir = join(self.tmp_dir, 'some') + os.mkdir(some_dir) + # make sure VCS directories are pruned (#14004) + hg_dir = join(self.tmp_dir, '.hg') + os.mkdir(hg_dir) + self.write_file((hg_dir, 'last-message.txt'), '#') + # a buggy regex used to prevent this from working on windows (#6884) + self.write_file((self.tmp_dir, 'buildout.cfg'), '#') + self.write_file((self.tmp_dir, 'inroot.txt'), '#') + self.write_file((some_dir, 'file.txt'), '#') + self.write_file((some_dir, 'other_file.txt'), '#') + + dist.data_files = [('data', ['data/data.dt', + 'buildout.cfg', + 'inroot.txt', + 'notexisting']), + 'some/file.txt', + 'some/other_file.txt'] + + # adding a script + script_dir = join(self.tmp_dir, 'scripts') + os.mkdir(script_dir) + self.write_file((script_dir, 'script.py'), '#') + dist.scripts = [join('scripts', 'script.py')] + + cmd.formats = ['zip'] + cmd.use_defaults = True + + cmd.ensure_finalized() + cmd.run() + + # now let's check what we have + dist_folder = join(self.tmp_dir, 'dist') + files = os.listdir(dist_folder) + self.assertEqual(files, ['fake-1.0.zip']) + + zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) + try: + content = zip_file.namelist() + finally: + zip_file.close() + + # making sure everything was added + expected = ['', 'PKG-INFO', 'README', 'buildout.cfg', + 'data/', 'data/data.dt', 'inroot.txt', + 'scripts/', 'scripts/script.py', 'setup.py', + 'some/', 'some/file.txt', 'some/other_file.txt', + 'somecode/', 'somecode/__init__.py', 'somecode/doc.dat', + 'somecode/doc.txt'] + self.assertEqual(sorted(content), ['fake-1.0/' + x for x in expected]) + + # checking the MANIFEST + f = open(join(self.tmp_dir, 'MANIFEST')) + try: + manifest = f.read() + finally: + f.close() + self.assertEqual(manifest, MANIFEST % {'sep': os.sep}) + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_metadata_check_option(self): + # testing the `medata-check` option + dist, cmd = self.get_cmd(metadata={}) + + # this should raise some warnings ! + # with the `check` subcommand + cmd.ensure_finalized() + cmd.run() + warnings = [msg for msg in self.get_logs(WARN) if + msg.startswith('warning: check:')] + self.assertEqual(len(warnings), 2) + + # trying with a complete set of metadata + self.clear_logs() + dist, cmd = self.get_cmd() + cmd.ensure_finalized() + cmd.metadata_check = 0 + cmd.run() + warnings = [msg for msg in self.get_logs(WARN) if + msg.startswith('warning: check:')] + self.assertEqual(len(warnings), 0) + + def test_check_metadata_deprecated(self): + # makes sure make_metadata is deprecated + dist, cmd = self.get_cmd() + with check_warnings() as w: + warnings.simplefilter("always") + cmd.check_metadata() + self.assertEqual(len(w.warnings), 1) + + def test_show_formats(self): + with captured_stdout() as stdout: + show_formats() + + # the output should be a header line + one line per format + num_formats = len(ARCHIVE_FORMATS.keys()) + output = [line for line in stdout.getvalue().split('\n') + if line.strip().startswith('--formats=')] + self.assertEqual(len(output), num_formats) + + def test_finalize_options(self): + dist, cmd = self.get_cmd() + cmd.finalize_options() + + # default options set by finalize + self.assertEqual(cmd.manifest, 'MANIFEST') + self.assertEqual(cmd.template, 'MANIFEST.in') + self.assertEqual(cmd.dist_dir, 'dist') + + # formats has to be a string splitable on (' ', ',') or + # a stringlist + cmd.formats = 1 + self.assertRaises(DistutilsOptionError, cmd.finalize_options) + cmd.formats = ['zip'] + cmd.finalize_options() + + # formats has to be known + cmd.formats = 'supazipa' + self.assertRaises(DistutilsOptionError, cmd.finalize_options) + + # the following tests make sure there is a nice error message instead + # of a traceback when parsing an invalid manifest template + + def _check_template(self, content): + dist, cmd = self.get_cmd() + os.chdir(self.tmp_dir) + self.write_file('MANIFEST.in', content) + cmd.ensure_finalized() + cmd.filelist = FileList() + cmd.read_template() + warnings = self.get_logs(WARN) + self.assertEqual(len(warnings), 1) + + def test_invalid_template_unknown_command(self): + self._check_template('taunt knights *') + + def test_invalid_template_wrong_arguments(self): + # this manifest command takes one argument + self._check_template('prune') + + @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only') + def test_invalid_template_wrong_path(self): + # on Windows, trailing slashes are not allowed + # this used to crash instead of raising a warning: #8286 + self._check_template('include examples/') + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.formats = ['gztar'] + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEqual(len(manifest), 5) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEqual(len(manifest2), 6) + self.assertIn('doc2.txt', manifest2[-1]) + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_manifest_marker(self): + # check that autogenerated MANIFESTs have a marker + dist, cmd = self.get_cmd() + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEqual(manifest[0], + '# file GENERATED by distutils, do NOT edit') + + @unittest.skipUnless(ZLIB_SUPPORT, "Need zlib support to run") + def test_manifest_comments(self): + # make sure comments don't cause exceptions or wrong includes + contents = dedent("""\ + # bad.py + #bad.py + good.py + """) + dist, cmd = self.get_cmd() + cmd.ensure_finalized() + self.write_file((self.tmp_dir, cmd.manifest), contents) + self.write_file((self.tmp_dir, 'good.py'), '# pick me!') + self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") + self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") + cmd.run() + self.assertEqual(cmd.filelist.files, ['good.py']) + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_manual_manifest(self): + # check that a MANIFEST without a marker is left alone + dist, cmd = self.get_cmd() + cmd.formats = ['gztar'] + cmd.ensure_finalized() + self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') + self.write_file((self.tmp_dir, 'README.manual'), + 'This project maintains its MANIFEST file itself.') + cmd.run() + self.assertEqual(cmd.filelist.files, ['README.manual']) + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEqual(manifest, ['README.manual']) + + archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') + archive = tarfile.open(archive_name) + try: + filenames = [tarinfo.name for tarinfo in archive] + finally: + archive.close() + self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO', + 'fake-1.0/README.manual']) + + @unittest.skipUnless(ZLIB_SUPPORT, "requires zlib") + @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") + @unittest.skipIf(find_executable('tar') is None, + "The tar command is not found") + @unittest.skipIf(find_executable('gzip') is None, + "The gzip command is not found") + def test_make_distribution_owner_group(self): + # now building a sdist + dist, cmd = self.get_cmd() + + # creating a gztar and specifying the owner+group + cmd.formats = ['gztar'] + cmd.owner = pwd.getpwuid(0)[0] + cmd.group = grp.getgrgid(0)[0] + cmd.ensure_finalized() + cmd.run() + + # making sure we have the good rights + archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') + archive = tarfile.open(archive_name) + try: + for member in archive.getmembers(): + self.assertEqual(member.uid, 0) + self.assertEqual(member.gid, 0) + finally: + archive.close() + + # building a sdist again + dist, cmd = self.get_cmd() + + # creating a gztar + cmd.formats = ['gztar'] + cmd.ensure_finalized() + cmd.run() + + # making sure we have the good rights + archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') + archive = tarfile.open(archive_name) + + # note that we are not testing the group ownership here + # because, depending on the platforms and the container + # rights (see #7408) + try: + for member in archive.getmembers(): + self.assertEqual(member.uid, os.getuid()) + finally: + archive.close() + +def test_suite(): + return unittest.makeSuite(SDistTestCase) + +if __name__ == "__main__": + run_unittest(test_suite()) diff --git a/shared/package-files/7b/7b14aa6f76f913e7cc4ac819025130f5770ba448286cf391099a5c68482500ce/blob b/shared/package-files/7b/7b14aa6f76f913e7cc4ac819025130f5770ba448286cf391099a5c68482500ce/blob new file mode 100644 index 0000000000000000000000000000000000000000..51a1312f9759f21063caea779a62882d7f7c86ae --- /dev/null +++ b/shared/package-files/7b/7b14aa6f76f913e7cc4ac819025130f5770ba448286cf391099a5c68482500ce/blob @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: MIT + + +from functools import total_ordering + +from ._funcs import astuple +from ._make import attrib, attrs + + +@total_ordering +@attrs(eq=False, order=False, slots=True, frozen=True) +class VersionInfo: + """ + A version object that can be compared to tuple of length 1--4: + + >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2) + True + >>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1) + True + >>> vi = attr.VersionInfo(19, 2, 0, "final") + >>> vi < (19, 1, 1) + False + >>> vi < (19,) + False + >>> vi == (19, 2,) + True + >>> vi == (19, 2, 1) + False + + .. versionadded:: 19.2 + """ + + year = attrib(type=int) + minor = attrib(type=int) + micro = attrib(type=int) + releaselevel = attrib(type=str) + + @classmethod + def _from_version_string(cls, s): + """ + Parse *s* and return a _VersionInfo. + """ + v = s.split(".") + if len(v) == 3: + v.append("final") + + return cls( + year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3] + ) + + def _ensure_tuple(self, other): + """ + Ensure *other* is a tuple of a valid length. + + Returns a possibly transformed *other* and ourselves as a tuple of + the same length as *other*. + """ + + if self.__class__ is other.__class__: + other = astuple(other) + + if not isinstance(other, tuple): + raise NotImplementedError + + if not (1 <= len(other) <= 4): + raise NotImplementedError + + return astuple(self)[: len(other)], other + + def __eq__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + return us == them + + def __lt__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + # Since alphabetically "dev0" < "final" < "post1" < "post2", we don't + # have to do anything special with releaselevel for now. + return us < them diff --git a/shared/package-files/7b/7b15ebdb1c3fd29075924f777186ccdcca216f3a149233a6b3564c522d2e4191/blob b/shared/package-files/7b/7b15ebdb1c3fd29075924f777186ccdcca216f3a149233a6b3564c522d2e4191/blob new file mode 100644 index 0000000000000000000000000000000000000000..09f46b1e817f806873c4a4bdd7b8466046b5f64d --- /dev/null +++ b/shared/package-files/7b/7b15ebdb1c3fd29075924f777186ccdcca216f3a149233a6b3564c522d2e4191/blob @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +class _Reasons: + BACKEND_MISSING_INTERFACE: _Reasons + UNSUPPORTED_HASH: _Reasons + UNSUPPORTED_CIPHER: _Reasons + UNSUPPORTED_PADDING: _Reasons + UNSUPPORTED_MGF: _Reasons + UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons + UNSUPPORTED_ELLIPTIC_CURVE: _Reasons + UNSUPPORTED_SERIALIZATION: _Reasons + UNSUPPORTED_X509: _Reasons + UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons + UNSUPPORTED_DIFFIE_HELLMAN: _Reasons + UNSUPPORTED_MAC: _Reasons diff --git a/shared/package-files/7b/7b17a9459a1226964077255666ab1ec1a296ddaeeec7956a44c32994bb566646/blob b/shared/package-files/7b/7b17a9459a1226964077255666ab1ec1a296ddaeeec7956a44c32994bb566646/blob new file mode 100644 index 0000000000000000000000000000000000000000..6e91eb40a977e623e2aec7894596e0be2e7c4210 Binary files /dev/null and b/shared/package-files/7b/7b17a9459a1226964077255666ab1ec1a296ddaeeec7956a44c32994bb566646/blob differ diff --git a/shared/package-files/7b/7b18eefdc7f56642b1d20d9cb418e242f5f60e12a96556a468e6e3b62cd1663a/blob b/shared/package-files/7b/7b18eefdc7f56642b1d20d9cb418e242f5f60e12a96556a468e6e3b62cd1663a/blob new file mode 100644 index 0000000000000000000000000000000000000000..8aa24a643d81a3462df60ae158aeae12dd3a1d44 --- /dev/null +++ b/shared/package-files/7b/7b18eefdc7f56642b1d20d9cb418e242f5f60e12a96556a468e6e3b62cd1663a/blob @@ -0,0 +1,105 @@ +fsspec-2024.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +fsspec-2024.3.1.dist-info/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513 +fsspec-2024.3.1.dist-info/METADATA,sha256=Wv4QVGqB4lYfHfgP-Cfby1Nce57WYXXAhH0f6Ju5FUM,6786 +fsspec-2024.3.1.dist-info/RECORD,, +fsspec-2024.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fsspec-2024.3.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +fsspec-2024.3.1.dist-info/top_level.txt,sha256=blt2pDrQDwN3Gklcw13CSPLQRd6aaOgJ8AxqrW395MI,7 +fsspec/__init__.py,sha256=C8G5rqeNAes0NHYFhdxcw-ZMg4yDipqzSNc4NIR7uoc,2010 +fsspec/__pycache__/__init__.cpython-310.pyc,, +fsspec/__pycache__/_version.cpython-310.pyc,, +fsspec/__pycache__/archive.cpython-310.pyc,, +fsspec/__pycache__/asyn.cpython-310.pyc,, +fsspec/__pycache__/caching.cpython-310.pyc,, +fsspec/__pycache__/callbacks.cpython-310.pyc,, +fsspec/__pycache__/compression.cpython-310.pyc,, +fsspec/__pycache__/config.cpython-310.pyc,, +fsspec/__pycache__/conftest.cpython-310.pyc,, +fsspec/__pycache__/core.cpython-310.pyc,, +fsspec/__pycache__/dircache.cpython-310.pyc,, +fsspec/__pycache__/exceptions.cpython-310.pyc,, +fsspec/__pycache__/fuse.cpython-310.pyc,, +fsspec/__pycache__/generic.cpython-310.pyc,, +fsspec/__pycache__/gui.cpython-310.pyc,, +fsspec/__pycache__/mapping.cpython-310.pyc,, +fsspec/__pycache__/parquet.cpython-310.pyc,, +fsspec/__pycache__/registry.cpython-310.pyc,, +fsspec/__pycache__/spec.cpython-310.pyc,, +fsspec/__pycache__/transaction.cpython-310.pyc,, +fsspec/__pycache__/utils.cpython-310.pyc,, +fsspec/_version.py,sha256=wHq_BWmvVWba6IeFL8lWxmbw1fXQhCR4NJHH8b77Nxs,500 +fsspec/archive.py,sha256=S__DzfZj-urAN3tp2W6jJ6YDiXG1fAl7FjvWUN73qIE,2386 +fsspec/asyn.py,sha256=AOd2SXH2YPCaQL5jA6IegYevdMFkAnGD7Seh9DC2gSE,36404 +fsspec/caching.py,sha256=TrZqKo3drK9Afujg7grZRiLNcmgUr84rnvMcojzURnI,28819 +fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210 +fsspec/compression.py,sha256=Yyd8FXw2rwWRtVoRVah_yguv-J7BUcBo4yDu6Qt52a0,4859 +fsspec/config.py,sha256=LF4Zmu1vhJW7Je9Q-cwkRc3xP7Rhyy7Xnwj26Z6sv2g,4279 +fsspec/conftest.py,sha256=fVfx-NLrH_OZS1TIpYNoPzM7efEcMoL62reHOdYeFCA,1245 +fsspec/core.py,sha256=kkwJ7IR3-i1C9SAZ_oGrPpbM5hqpBZ2OLkuHU5a1sYE,22471 +fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717 +fsspec/exceptions.py,sha256=xcS7LiRrQ748kvOB9mrUR14kpjNztrHgEkZWi9M-VaI,330 +fsspec/fuse.py,sha256=66amOa6wdIbS0DMhhfAPUoOB37HPorfXD1izV0prmTY,10145 +fsspec/generic.py,sha256=jIA7wBwtUzJhTth78PTzWbOBjGom2e4IjmQ_KBSlHPg,13575 +fsspec/gui.py,sha256=XKoXZpUhRE7jOhRCJH4-jRbKhVu56aS8h9tecvPD3nc,13932 +fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fsspec/implementations/__pycache__/__init__.cpython-310.pyc,, +fsspec/implementations/__pycache__/arrow.cpython-310.pyc,, +fsspec/implementations/__pycache__/cache_mapper.cpython-310.pyc,, +fsspec/implementations/__pycache__/cache_metadata.cpython-310.pyc,, +fsspec/implementations/__pycache__/cached.cpython-310.pyc,, +fsspec/implementations/__pycache__/dask.cpython-310.pyc,, +fsspec/implementations/__pycache__/data.cpython-310.pyc,, +fsspec/implementations/__pycache__/dbfs.cpython-310.pyc,, +fsspec/implementations/__pycache__/dirfs.cpython-310.pyc,, +fsspec/implementations/__pycache__/ftp.cpython-310.pyc,, +fsspec/implementations/__pycache__/git.cpython-310.pyc,, +fsspec/implementations/__pycache__/github.cpython-310.pyc,, +fsspec/implementations/__pycache__/http.cpython-310.pyc,, +fsspec/implementations/__pycache__/jupyter.cpython-310.pyc,, +fsspec/implementations/__pycache__/libarchive.cpython-310.pyc,, +fsspec/implementations/__pycache__/local.cpython-310.pyc,, +fsspec/implementations/__pycache__/memory.cpython-310.pyc,, +fsspec/implementations/__pycache__/reference.cpython-310.pyc,, +fsspec/implementations/__pycache__/sftp.cpython-310.pyc,, +fsspec/implementations/__pycache__/smb.cpython-310.pyc,, +fsspec/implementations/__pycache__/tar.cpython-310.pyc,, +fsspec/implementations/__pycache__/webhdfs.cpython-310.pyc,, +fsspec/implementations/__pycache__/zip.cpython-310.pyc,, +fsspec/implementations/arrow.py,sha256=_7TLuV6ZzNlpmUU_v6ud56u2wadzsKmY5qugPBxgMEs,8649 +fsspec/implementations/cache_mapper.py,sha256=iHgBA6gjzDJ7_mBboHFzpLTf55HP3UEwUOZ43xyUK4M,2429 +fsspec/implementations/cache_metadata.py,sha256=ZvyA7Y3KK-5Ct4E5pELzD6mH_5T03XqaKVT96qYDADU,8576 +fsspec/implementations/cached.py,sha256=CuxQXQ6f-MRnLvsRzvauEhpmXEgicZZCfViKjIu1kn4,33029 +fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466 +fsspec/implementations/data.py,sha256=LDLczxRh8h7x39Zjrd-GgzdQHr78yYxDlrv2C9Uxb5E,1658 +fsspec/implementations/dbfs.py,sha256=cix9OYUveuSOx5UO5uRUwNUkYqjzyY0fkKnca1kTgZ0,15014 +fsspec/implementations/dirfs.py,sha256=inDIRSDPhI1_ud1MMBFrpZQ11VIAMJ_dZQtbE4V08Ng,11384 +fsspec/implementations/ftp.py,sha256=rp6cTog8xqjDPlKdSLKcsyP7K593_ByMabxGbNSEpTo,11655 +fsspec/implementations/git.py,sha256=vKGI-Vd5q4H2RrvhebkPc9NwlfkZ980OUGhebeCw-M0,4034 +fsspec/implementations/github.py,sha256=0kIiKkeAaROuHgdWBHVQFrzJ2ZfoDgymCehL_kJXHYA,7565 +fsspec/implementations/http.py,sha256=yr6t0OhLwZx_pvNQ05detAehcQjRw0Pg6XdwWv81jxk,29601 +fsspec/implementations/jupyter.py,sha256=B2uj7OEm7yIk-vRSsO37_ND0t0EBvn4B-Su43ibN4Pg,3811 +fsspec/implementations/libarchive.py,sha256=5_I2DiLXwQ1JC8x-K7jXu-tBwhO9dj7tFLnb0bTnVMQ,7102 +fsspec/implementations/local.py,sha256=XLsBoG4lf92w5ZddmbHXcStThSYxHgeoJEd2Mp5Uo0Y,14327 +fsspec/implementations/memory.py,sha256=tlaGCekgZ2Z_9n8B6hsSpo6_V89PwjugkOmD445QrqE,9778 +fsspec/implementations/reference.py,sha256=3dPi55riD_cROCafpeoUm2Xbb1vpXpyQijl09f5jTsE,43871 +fsspec/implementations/sftp.py,sha256=fMY9XZcmpjszQ2tCqO_TPaJesaeD_Dv7ptYzgUPGoO0,5631 +fsspec/implementations/smb.py,sha256=_hR5MKwDUCi3u5zEzvnenIWRIGPMhuUryWRYvNSp0WE,10804 +fsspec/implementations/tar.py,sha256=dam78Tp_CozybNqCY2JYgGBS3Uc9FuJUAT9oB0lolOs,4111 +fsspec/implementations/webhdfs.py,sha256=wqVfno7z0TY1HepaIvKTUUcl_bi5NkV6qWsST8t_s7Y,16745 +fsspec/implementations/zip.py,sha256=vc1fNz-yO8uWQ9bQUqBFYpTcgsfZQq9vDwwg4Aufs9Y,4417 +fsspec/mapping.py,sha256=hSsiRo-dgAOj6oHf67bF3i11U4xREglXToHGUX4GhRY,8261 +fsspec/parquet.py,sha256=qVxDhwc960SGOt5etcYAJxCr-7HQKP01687KpDR02Gw,19463 +fsspec/registry.py,sha256=VjnfGUg39lvlCDxOoGSeYm8UL12wZC5yQ5n8-W92eD0,11173 +fsspec/spec.py,sha256=3t96RgizRN_slIuHXnuR0bXjVUfBS1TfuDrEua4oQvE,66277 +fsspec/tests/abstract/__init__.py,sha256=i1wcFixV6QhOwdoB24c8oXjzobISNqiKVz9kl2DvAY8,10028 +fsspec/tests/abstract/__pycache__/__init__.cpython-310.pyc,, +fsspec/tests/abstract/__pycache__/common.cpython-310.pyc,, +fsspec/tests/abstract/__pycache__/copy.cpython-310.pyc,, +fsspec/tests/abstract/__pycache__/get.cpython-310.pyc,, +fsspec/tests/abstract/__pycache__/put.cpython-310.pyc,, +fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973 +fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967 +fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755 +fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201 +fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398 +fsspec/utils.py,sha256=kYBiiw_0AEFJPCYwYlbZ7QxiGwuXdaaxrK6KM3mcFak,23052 diff --git a/shared/package-files/7b/7b1bf1c1c3c84023ab49484b56a9ebf4d152b6aa385500272823840b6a8c6f12/blob b/shared/package-files/7b/7b1bf1c1c3c84023ab49484b56a9ebf4d152b6aa385500272823840b6a8c6f12/blob new file mode 100644 index 0000000000000000000000000000000000000000..0aae0dcf5bb7423408d1037825c22706a86d3232 --- /dev/null +++ b/shared/package-files/7b/7b1bf1c1c3c84023ab49484b56a9ebf4d152b6aa385500272823840b6a8c6f12/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_weight_norm_differentiable_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor) +inline ::std::tuple _weight_norm_differentiable_backward(const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim) { + return at::_ops::_weight_norm_differentiable_backward::call(grad_w, saved_v, saved_g, saved_norms, dim); +} + +} diff --git a/shared/package-files/7b/7b1db754684e2a6f659e247ea23d9d0317ac60804c0b71910d95584467bc4b76/blob b/shared/package-files/7b/7b1db754684e2a6f659e247ea23d9d0317ac60804c0b71910d95584467bc4b76/blob new file mode 100644 index 0000000000000000000000000000000000000000..42c8407ef085fa349bb0e72e22973054c31cd7dc --- /dev/null +++ b/shared/package-files/7b/7b1db754684e2a6f659e247ea23d9d0317ac60804c0b71910d95584467bc4b76/blob @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor +inline at::Tensor scatter_add(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src) { + return at::_ops::scatter_add::call(self, dim, index, src); +} + +// aten::scatter_add.out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & scatter_add_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src) { + return at::_ops::scatter_add_out::call(self, dim, index, src, out); +} +// aten::scatter_add.out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & scatter_add_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, at::Tensor & out) { + return at::_ops::scatter_add_out::call(self, dim, index, src, out); +} + +// aten::scatter_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor +inline at::Tensor scatter_add(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, const at::Tensor & src) { + return at::_ops::scatter_add_dimname::call(self, dim, index, src); +} + +} diff --git a/shared/package-files/7b/7b1dc883213eecc042ff2e53da02698657d47b1ee7a911b955f5fada64db7b91/blob b/shared/package-files/7b/7b1dc883213eecc042ff2e53da02698657d47b1ee7a911b955f5fada64db7b91/blob new file mode 100644 index 0000000000000000000000000000000000000000..aafda0ff62bbdf94331fb7cb8fe5d51b6eb1d63a --- /dev/null +++ b/shared/package-files/7b/7b1dc883213eecc042ff2e53da02698657d47b1ee7a911b955f5fada64db7b91/blob @@ -0,0 +1,38 @@ +from pathlib import Path + +import pytest + + +@pytest.fixture +def xml_data_path(): + return Path(__file__).parent.parent / "data" / "xml" + + +@pytest.fixture +def xml_books(xml_data_path, datapath): + return datapath(xml_data_path / "books.xml") + + +@pytest.fixture +def xml_doc_ch_utf(xml_data_path, datapath): + return datapath(xml_data_path / "doc_ch_utf.xml") + + +@pytest.fixture +def xml_baby_names(xml_data_path, datapath): + return datapath(xml_data_path / "baby_names.xml") + + +@pytest.fixture +def kml_cta_rail_lines(xml_data_path, datapath): + return datapath(xml_data_path / "cta_rail_lines.kml") + + +@pytest.fixture +def xsl_flatten_doc(xml_data_path, datapath): + return datapath(xml_data_path / "flatten_doc.xsl") + + +@pytest.fixture +def xsl_row_field_output(xml_data_path, datapath): + return datapath(xml_data_path / "row_field_output.xsl") diff --git a/shared/package-files/7b/7b1dd16ce9c819c7a873674e0d95502e85bfd94d598589883f3fd597a759724b/blob b/shared/package-files/7b/7b1dd16ce9c819c7a873674e0d95502e85bfd94d598589883f3fd597a759724b/blob new file mode 100644 index 0000000000000000000000000000000000000000..0413b9ff28482441ab13f624f87adf6bd9c01c21 --- /dev/null +++ b/shared/package-files/7b/7b1dd16ce9c819c7a873674e0d95502e85bfd94d598589883f3fd597a759724b/blob @@ -0,0 +1,218 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +class SymNodeImpl; +using SymNode = c10::intrusive_ptr; + +// When you add a method, you also need to edit +// torch/csrc/jit/python/init.cpp +// torch/csrc/utils/python_symnode.h +// c10/core/ConstantSymNodeImpl.h +class C10_API SymNodeImpl : public c10::intrusive_ptr_target { + public: + ~SymNodeImpl() override = default; + + template + c10::intrusive_ptr dyn_cast() const { + return c10::intrusive_ptr::reclaim_copy(dynamic_cast(this)); + } + + // these could be pure virtual when we implement LTC versions + virtual bool is_int() { + TORCH_CHECK(false, "NYI"); + }; + virtual bool is_bool() { + TORCH_CHECK(false, "NYI"); + }; + virtual bool is_float() { + TORCH_CHECK(false, "NYI"); + }; + virtual bool is_nested_int() const { + return false; + }; + virtual SymNode add(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sub(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode mul(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode truediv(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode pow(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode floordiv(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode mod(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode eq(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode ne(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode gt(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode lt(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode le(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode ge(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode ceil() { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode floor() { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode neg() { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_min(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_max(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_or(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_and(const SymNode& other) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_not() { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_ite(const SymNode& then_val, const SymNode& else_val) { + TORCH_CHECK(false, "NYI"); + }; + // NB: self is ignored here, only the arguments are used + virtual SymNode is_contiguous( + ArrayRef sizes, + ArrayRef strides) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode is_channels_last_contiguous_2d( + ArrayRef sizes, + ArrayRef strides) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode is_channels_last_contiguous_3d( + ArrayRef sizes, + ArrayRef strides) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode is_channels_last_strides_2d( + ArrayRef sizes, + ArrayRef strides) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode is_channels_last_strides_3d( + ArrayRef sizes, + ArrayRef strides) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode is_non_overlapping_and_dense( + ArrayRef sizes, + ArrayRef strides) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode clone() { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode sym_float() { + TORCH_CHECK(false, "NYI"); + } + virtual SymNode wrap_int(int64_t num) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode wrap_float(double num) { + TORCH_CHECK(false, "NYI"); + }; + virtual SymNode wrap_bool(bool num) { + TORCH_CHECK(false, "NYI"); + }; + virtual int64_t guard_int(const char* file, int64_t line) { + TORCH_CHECK(false, "NYI"); + }; + virtual bool guard_bool(const char* file, int64_t line) { + TORCH_CHECK(false, "NYI"); + }; + virtual double guard_float(const char* file, int64_t line) { + TORCH_CHECK(false, "NYI"); + }; + virtual bool guard_size_oblivious(const char* file, int64_t line) { + // No improvement for unbacked SymBools by default, replace this + // with a better implementation! + return guard_bool(file, line); + } + virtual bool expect_true(const char* file, int64_t line) { + // No improvement for unbacked SymBools by default, replace this + // with a better implementation! + return guard_bool(file, line); + }; + virtual bool expect_size(const char* file, int64_t line) { + // No improvement for unbacked SymInts by default, replace this + // with a better implementation! + return ge(wrap_int(0))->guard_bool(file, line); + }; + virtual int64_t int_() { + TORCH_CHECK(false, "NYI"); + }; + virtual bool bool_() { + TORCH_CHECK(false, "NYI"); + }; + virtual bool has_hint() { + TORCH_CHECK(false, "NYI"); + }; + virtual std::string str() { + TORCH_CHECK(false, "NYI"); + }; + virtual c10::optional nested_int() { + return c10::nullopt; + } + virtual c10::optional nested_int_coeff() { + return c10::nullopt; + } + virtual c10::optional constant_int() { + return c10::nullopt; + } + virtual c10::optional constant_bool() { + return c10::nullopt; + } + virtual c10::optional maybe_as_int() { + return c10::nullopt; + } + virtual bool is_constant() { + return false; + } + virtual bool is_symbolic() { + return true; + } + std::ostream& operator<<(std::ostream& os) { + os << str(); + return os; + } +}; + +} // namespace c10 diff --git a/shared/package-files/7b/7b1f83ffafd8bf21ee56537a09811e0ccae470d703c7b1c0b958671502843c6a/blob b/shared/package-files/7b/7b1f83ffafd8bf21ee56537a09811e0ccae470d703c7b1c0b958671502843c6a/blob new file mode 100644 index 0000000000000000000000000000000000000000..1c63274547bded618ac1ba7f304573ebda21bb03 --- /dev/null +++ b/shared/package-files/7b/7b1f83ffafd8bf21ee56537a09811e0ccae470d703c7b1c0b958671502843c6a/blob @@ -0,0 +1,214 @@ +Series Id: LNS14000000Q + +Seasonally Adjusted +Series title: (Seas) Unemployment Rate +Labor force status: Unemployment rate +Type of data: Percent or rate +Age: 16 years and over + + +Series id,Year,Period,Value, +LNS14000000Q,1959,Q01,5.8 +LNS14000000Q,1959,Q02,5.1 +LNS14000000Q,1959,Q03,5.3 +LNS14000000Q,1959,Q04,5.6 +LNS14000000Q,1960,Q01,5.2 +LNS14000000Q,1960,Q02,5.2 +LNS14000000Q,1960,Q03,5.6 +LNS14000000Q,1960,Q04,6.3 +LNS14000000Q,1961,Q01,6.8 +LNS14000000Q,1961,Q02,7.0 +LNS14000000Q,1961,Q03,6.8 +LNS14000000Q,1961,Q04,6.2 +LNS14000000Q,1962,Q01,5.6 +LNS14000000Q,1962,Q02,5.5 +LNS14000000Q,1962,Q03,5.6 +LNS14000000Q,1962,Q04,5.5 +LNS14000000Q,1963,Q01,5.8 +LNS14000000Q,1963,Q02,5.7 +LNS14000000Q,1963,Q03,5.5 +LNS14000000Q,1963,Q04,5.6 +LNS14000000Q,1964,Q01,5.5 +LNS14000000Q,1964,Q02,5.2 +LNS14000000Q,1964,Q03,5.0 +LNS14000000Q,1964,Q04,5.0 +LNS14000000Q,1965,Q01,4.9 +LNS14000000Q,1965,Q02,4.7 +LNS14000000Q,1965,Q03,4.4 +LNS14000000Q,1965,Q04,4.1 +LNS14000000Q,1966,Q01,3.9 +LNS14000000Q,1966,Q02,3.8 +LNS14000000Q,1966,Q03,3.8 +LNS14000000Q,1966,Q04,3.7 +LNS14000000Q,1967,Q01,3.8 +LNS14000000Q,1967,Q02,3.8 +LNS14000000Q,1967,Q03,3.8 +LNS14000000Q,1967,Q04,3.9 +LNS14000000Q,1968,Q01,3.7 +LNS14000000Q,1968,Q02,3.5 +LNS14000000Q,1968,Q03,3.5 +LNS14000000Q,1968,Q04,3.4 +LNS14000000Q,1969,Q01,3.4 +LNS14000000Q,1969,Q02,3.4 +LNS14000000Q,1969,Q03,3.6 +LNS14000000Q,1969,Q04,3.6 +LNS14000000Q,1970,Q01,4.2 +LNS14000000Q,1970,Q02,4.8 +LNS14000000Q,1970,Q03,5.2 +LNS14000000Q,1970,Q04,5.8 +LNS14000000Q,1971,Q01,5.9 +LNS14000000Q,1971,Q02,5.9 +LNS14000000Q,1971,Q03,6.0 +LNS14000000Q,1971,Q04,6.0 +LNS14000000Q,1972,Q01,5.8 +LNS14000000Q,1972,Q02,5.7 +LNS14000000Q,1972,Q03,5.6 +LNS14000000Q,1972,Q04,5.3 +LNS14000000Q,1973,Q01,5.0 +LNS14000000Q,1973,Q02,4.9 +LNS14000000Q,1973,Q03,4.8 +LNS14000000Q,1973,Q04,4.8 +LNS14000000Q,1974,Q01,5.1 +LNS14000000Q,1974,Q02,5.2 +LNS14000000Q,1974,Q03,5.6 +LNS14000000Q,1974,Q04,6.6 +LNS14000000Q,1975,Q01,8.2 +LNS14000000Q,1975,Q02,8.9 +LNS14000000Q,1975,Q03,8.5 +LNS14000000Q,1975,Q04,8.3 +LNS14000000Q,1976,Q01,7.7 +LNS14000000Q,1976,Q02,7.6 +LNS14000000Q,1976,Q03,7.7 +LNS14000000Q,1976,Q04,7.8 +LNS14000000Q,1977,Q01,7.5 +LNS14000000Q,1977,Q02,7.1 +LNS14000000Q,1977,Q03,6.9 +LNS14000000Q,1977,Q04,6.6 +LNS14000000Q,1978,Q01,6.3 +LNS14000000Q,1978,Q02,6.0 +LNS14000000Q,1978,Q03,6.0 +LNS14000000Q,1978,Q04,5.9 +LNS14000000Q,1979,Q01,5.9 +LNS14000000Q,1979,Q02,5.7 +LNS14000000Q,1979,Q03,5.9 +LNS14000000Q,1979,Q04,5.9 +LNS14000000Q,1980,Q01,6.3 +LNS14000000Q,1980,Q02,7.3 +LNS14000000Q,1980,Q03,7.7 +LNS14000000Q,1980,Q04,7.4 +LNS14000000Q,1981,Q01,7.4 +LNS14000000Q,1981,Q02,7.4 +LNS14000000Q,1981,Q03,7.4 +LNS14000000Q,1981,Q04,8.2 +LNS14000000Q,1982,Q01,8.8 +LNS14000000Q,1982,Q02,9.4 +LNS14000000Q,1982,Q03,9.9 +LNS14000000Q,1982,Q04,10.7 +LNS14000000Q,1983,Q01,10.4 +LNS14000000Q,1983,Q02,10.1 +LNS14000000Q,1983,Q03,9.4 +LNS14000000Q,1983,Q04,8.5 +LNS14000000Q,1984,Q01,7.9 +LNS14000000Q,1984,Q02,7.5 +LNS14000000Q,1984,Q03,7.4 +LNS14000000Q,1984,Q04,7.3 +LNS14000000Q,1985,Q01,7.3 +LNS14000000Q,1985,Q02,7.3 +LNS14000000Q,1985,Q03,7.2 +LNS14000000Q,1985,Q04,7.0 +LNS14000000Q,1986,Q01,7.0 +LNS14000000Q,1986,Q02,7.2 +LNS14000000Q,1986,Q03,7.0 +LNS14000000Q,1986,Q04,6.8 +LNS14000000Q,1987,Q01,6.6 +LNS14000000Q,1987,Q02,6.3 +LNS14000000Q,1987,Q03,6.0 +LNS14000000Q,1987,Q04,5.9 +LNS14000000Q,1988,Q01,5.7 +LNS14000000Q,1988,Q02,5.5 +LNS14000000Q,1988,Q03,5.5 +LNS14000000Q,1988,Q04,5.3 +LNS14000000Q,1989,Q01,5.2 +LNS14000000Q,1989,Q02,5.2 +LNS14000000Q,1989,Q03,5.3 +LNS14000000Q,1989,Q04,5.4 +LNS14000000Q,1990,Q01,5.3 +LNS14000000Q,1990,Q02,5.3 +LNS14000000Q,1990,Q03,5.7 +LNS14000000Q,1990,Q04,6.1 +LNS14000000Q,1991,Q01,6.6 +LNS14000000Q,1991,Q02,6.8 +LNS14000000Q,1991,Q03,6.9 +LNS14000000Q,1991,Q04,7.1 +LNS14000000Q,1992,Q01,7.4 +LNS14000000Q,1992,Q02,7.6 +LNS14000000Q,1992,Q03,7.6 +LNS14000000Q,1992,Q04,7.4 +LNS14000000Q,1993,Q01,7.2 +LNS14000000Q,1993,Q02,7.1 +LNS14000000Q,1993,Q03,6.8 +LNS14000000Q,1993,Q04,6.6 +LNS14000000Q,1994,Q01,6.6 +LNS14000000Q,1994,Q02,6.2 +LNS14000000Q,1994,Q03,6.0 +LNS14000000Q,1994,Q04,5.6 +LNS14000000Q,1995,Q01,5.5 +LNS14000000Q,1995,Q02,5.7 +LNS14000000Q,1995,Q03,5.7 +LNS14000000Q,1995,Q04,5.6 +LNS14000000Q,1996,Q01,5.5 +LNS14000000Q,1996,Q02,5.5 +LNS14000000Q,1996,Q03,5.3 +LNS14000000Q,1996,Q04,5.3 +LNS14000000Q,1997,Q01,5.2 +LNS14000000Q,1997,Q02,5.0 +LNS14000000Q,1997,Q03,4.9 +LNS14000000Q,1997,Q04,4.7 +LNS14000000Q,1998,Q01,4.6 +LNS14000000Q,1998,Q02,4.4 +LNS14000000Q,1998,Q03,4.5 +LNS14000000Q,1998,Q04,4.4 +LNS14000000Q,1999,Q01,4.3 +LNS14000000Q,1999,Q02,4.3 +LNS14000000Q,1999,Q03,4.2 +LNS14000000Q,1999,Q04,4.1 +LNS14000000Q,2000,Q01,4.0 +LNS14000000Q,2000,Q02,3.9 +LNS14000000Q,2000,Q03,4.0 +LNS14000000Q,2000,Q04,3.9 +LNS14000000Q,2001,Q01,4.2 +LNS14000000Q,2001,Q02,4.4 +LNS14000000Q,2001,Q03,4.8 +LNS14000000Q,2001,Q04,5.5 +LNS14000000Q,2002,Q01,5.7 +LNS14000000Q,2002,Q02,5.8 +LNS14000000Q,2002,Q03,5.7 +LNS14000000Q,2002,Q04,5.8 +LNS14000000Q,2003,Q01,5.9 +LNS14000000Q,2003,Q02,6.2 +LNS14000000Q,2003,Q03,6.1 +LNS14000000Q,2003,Q04,5.8 +LNS14000000Q,2004,Q01,5.7 +LNS14000000Q,2004,Q02,5.6 +LNS14000000Q,2004,Q03,5.4 +LNS14000000Q,2004,Q04,5.4 +LNS14000000Q,2005,Q01,5.3 +LNS14000000Q,2005,Q02,5.1 +LNS14000000Q,2005,Q03,5.0 +LNS14000000Q,2005,Q04,4.9 +LNS14000000Q,2006,Q01,4.7 +LNS14000000Q,2006,Q02,4.7 +LNS14000000Q,2006,Q03,4.7 +LNS14000000Q,2006,Q04,4.4 +LNS14000000Q,2007,Q01,4.5 +LNS14000000Q,2007,Q02,4.5 +LNS14000000Q,2007,Q03,4.7 +LNS14000000Q,2007,Q04,4.8 +LNS14000000Q,2008,Q01,4.9 +LNS14000000Q,2008,Q02,5.4 +LNS14000000Q,2008,Q03,6.0 +LNS14000000Q,2008,Q04,6.9 +LNS14000000Q,2009,Q01,8.1 +LNS14000000Q,2009,Q02,9.2 +LNS14000000Q,2009,Q03,9.6 + diff --git a/shared/package-files/7b/7b20569c1d31d42c6c78538c3d791fa6ebb8f2786432e2b6e2164f0656b6c15b/blob b/shared/package-files/7b/7b20569c1d31d42c6c78538c3d791fa6ebb8f2786432e2b6e2164f0656b6c15b/blob new file mode 100644 index 0000000000000000000000000000000000000000..67ec12870ccf1dfe52624da05787b197542a0253 --- /dev/null +++ b/shared/package-files/7b/7b20569c1d31d42c6c78538c3d791fa6ebb8f2786432e2b6e2164f0656b6c15b/blob @@ -0,0 +1,1687 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np +from . import _ni_support +from . import _ni_label +from . import _nd_image +from . import _morphology + +__all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean', + 'variance', 'standard_deviation', 'minimum', 'maximum', 'median', + 'minimum_position', 'maximum_position', 'extrema', 'center_of_mass', + 'histogram', 'watershed_ift', 'sum_labels', 'value_indices'] + + +def label(input, structure=None, output=None): + """ + Label features in an array. + + Parameters + ---------- + input : array_like + An array-like object to be labeled. Any non-zero values in `input` are + counted as features and zero values are considered the background. + structure : array_like, optional + A structuring element that defines feature connections. + `structure` must be centrosymmetric + (see Notes). + If no structuring element is provided, + one is automatically generated with a squared connectivity equal to + one. That is, for a 2-D `input` array, the default structuring element + is:: + + [[0,1,0], + [1,1,1], + [0,1,0]] + + output : (None, data-type, array_like), optional + If `output` is a data type, it specifies the type of the resulting + labeled feature array. + If `output` is an array-like object, then `output` will be updated + with the labeled features from this function. This function can + operate in-place, by passing output=input. + Note that the output must be able to store the largest label, or this + function will raise an Exception. + + Returns + ------- + label : ndarray or int + An integer ndarray where each unique feature in `input` has a unique + label in the returned array. + num_features : int + How many objects were found. + + If `output` is None, this function returns a tuple of + (`labeled_array`, `num_features`). + + If `output` is a ndarray, then it will be updated with values in + `labeled_array` and only `num_features` will be returned by this + function. + + See Also + -------- + find_objects : generate a list of slices for the labeled features (or + objects); useful for finding features' position or + dimensions + + Notes + ----- + A centrosymmetric matrix is a matrix that is symmetric about the center. + See [1]_ for more information. + + The `structure` matrix must be centrosymmetric to ensure + two-way connections. + For instance, if the `structure` matrix is not centrosymmetric + and is defined as:: + + [[0,1,0], + [1,1,0], + [0,0,0]] + + and the `input` is:: + + [[1,2], + [0,3]] + + then the structure matrix would indicate the + entry 2 in the input is connected to 1, + but 1 is not connected to 2. + + References + ---------- + .. [1] James R. Weaver, "Centrosymmetric (cross-symmetric) + matrices, their basic properties, eigenvalues, and + eigenvectors." The American Mathematical Monthly 92.10 + (1985): 711-717. + + Examples + -------- + Create an image with some features, then label it using the default + (cross-shaped) structuring element: + + >>> from scipy.ndimage import label, generate_binary_structure + >>> import numpy as np + >>> a = np.array([[0,0,1,1,0,0], + ... [0,0,0,1,0,0], + ... [1,1,0,0,1,0], + ... [0,0,0,1,0,0]]) + >>> labeled_array, num_features = label(a) + + Each of the 4 features are labeled with a different integer: + + >>> num_features + 4 + >>> labeled_array + array([[0, 0, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0], + [2, 2, 0, 0, 3, 0], + [0, 0, 0, 4, 0, 0]], dtype=int32) + + Generate a structuring element that will consider features connected even + if they touch diagonally: + + >>> s = generate_binary_structure(2,2) + + or, + + >>> s = [[1,1,1], + ... [1,1,1], + ... [1,1,1]] + + Label the image using the new structuring element: + + >>> labeled_array, num_features = label(a, structure=s) + + Show the 2 labeled features (note that features 1, 3, and 4 from above are + now considered a single feature): + + >>> num_features + 2 + >>> labeled_array + array([[0, 0, 1, 1, 0, 0], + [0, 0, 0, 1, 0, 0], + [2, 2, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 0]], dtype=int32) + + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + if structure is None: + structure = _morphology.generate_binary_structure(input.ndim, 1) + structure = np.asarray(structure, dtype=bool) + if structure.ndim != input.ndim: + raise RuntimeError('structure and input must have equal rank') + for ii in structure.shape: + if ii != 3: + raise ValueError('structure dimensions must be equal to 3') + + # Use 32 bits if it's large enough for this image. + # _ni_label.label() needs two entries for background and + # foreground tracking + need_64bits = input.size >= (2**31 - 2) + + if isinstance(output, np.ndarray): + if output.shape != input.shape: + raise ValueError("output shape not correct") + caller_provided_output = True + else: + caller_provided_output = False + if output is None: + output = np.empty(input.shape, np.intp if need_64bits else np.int32) + else: + output = np.empty(input.shape, output) + + # handle scalars, 0-D arrays + if input.ndim == 0 or input.size == 0: + if input.ndim == 0: + # scalar + maxlabel = 1 if (input != 0) else 0 + output[...] = maxlabel + else: + # 0-D + maxlabel = 0 + if caller_provided_output: + return maxlabel + else: + return output, maxlabel + + try: + max_label = _ni_label._label(input, structure, output) + except _ni_label.NeedMoreBits as e: + # Make another attempt with enough bits, then try to cast to the + # new type. + tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32) + max_label = _ni_label._label(input, structure, tmp_output) + output[...] = tmp_output[...] + if not np.all(output == tmp_output): + # refuse to return bad results + raise RuntimeError( + "insufficient bit-depth in requested output type" + ) from e + + if caller_provided_output: + # result was written in-place + return max_label + else: + return output, max_label + + +def find_objects(input, max_label=0): + """ + Find objects in a labeled array. + + Parameters + ---------- + input : ndarray of ints + Array containing objects defined by different labels. Labels with + value 0 are ignored. + max_label : int, optional + Maximum label to be searched for in `input`. If max_label is not + given, the positions of all objects are returned. + + Returns + ------- + object_slices : list of tuples + A list of tuples, with each tuple containing N slices (with N the + dimension of the input array). Slices correspond to the minimal + parallelepiped that contains the object. If a number is missing, + None is returned instead of a slice. The label ``l`` corresponds to + the index ``l-1`` in the returned list. + + See Also + -------- + label, center_of_mass + + Notes + ----- + This function is very useful for isolating a volume of interest inside + a 3-D array, that cannot be "seen through". + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.zeros((6,6), dtype=int) + >>> a[2:4, 2:4] = 1 + >>> a[4, 4] = 1 + >>> a[:2, :3] = 2 + >>> a[0, 5] = 3 + >>> a + array([[2, 2, 2, 0, 0, 3], + [2, 2, 2, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0]]) + >>> ndimage.find_objects(a) + [(slice(2, 5, None), slice(2, 5, None)), + (slice(0, 2, None), slice(0, 3, None)), + (slice(0, 1, None), slice(5, 6, None))] + >>> ndimage.find_objects(a, max_label=2) + [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))] + >>> ndimage.find_objects(a == 1, max_label=2) + [(slice(2, 5, None), slice(2, 5, None)), None] + + >>> loc = ndimage.find_objects(a)[0] + >>> a[loc] + array([[1, 1, 0], + [1, 1, 0], + [0, 0, 1]]) + + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + + if max_label < 1: + max_label = input.max() + + return _nd_image.find_objects(input, max_label) + + +def value_indices(arr, *, ignore_value=None): + """ + Find indices of each distinct value in given array. + + Parameters + ---------- + arr : ndarray of ints + Array containing integer values. + ignore_value : int, optional + This value will be ignored in searching the `arr` array. If not + given, all values found will be included in output. Default + is None. + + Returns + ------- + indices : dictionary + A Python dictionary of array indices for each distinct value. The + dictionary is keyed by the distinct values, the entries are array + index tuples covering all occurrences of the value within the + array. + + This dictionary can occupy significant memory, usually several times + the size of the input array. + + See Also + -------- + label, maximum, median, minimum_position, extrema, sum, mean, variance, + standard_deviation, numpy.where, numpy.unique + + Notes + ----- + For a small array with few distinct values, one might use + `numpy.unique()` to find all possible values, and ``(arr == val)`` to + locate each value within that array. However, for large arrays, + with many distinct values, this can become extremely inefficient, + as locating each value would require a new search through the entire + array. Using this function, there is essentially one search, with + the indices saved for all distinct values. + + This is useful when matching a categorical image (e.g. a segmentation + or classification) to an associated image of other data, allowing + any per-class statistic(s) to then be calculated. Provides a + more flexible alternative to functions like ``scipy.ndimage.mean()`` + and ``scipy.ndimage.variance()``. + + Some other closely related functionality, with different strengths and + weaknesses, can also be found in ``scipy.stats.binned_statistic()`` and + the `scikit-image `_ function + ``skimage.measure.regionprops()``. + + Note for IDL users: this provides functionality equivalent to IDL's + REVERSE_INDICES option (as per the IDL documentation for the + `HISTOGRAM `_ + function). + + .. versionadded:: 1.10.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy import ndimage + >>> a = np.zeros((6, 6), dtype=int) + >>> a[2:4, 2:4] = 1 + >>> a[4, 4] = 1 + >>> a[:2, :3] = 2 + >>> a[0, 5] = 3 + >>> a + array([[2, 2, 2, 0, 0, 3], + [2, 2, 2, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 0]]) + >>> val_indices = ndimage.value_indices(a) + + The dictionary `val_indices` will have an entry for each distinct + value in the input array. + + >>> val_indices.keys() + dict_keys([np.int64(0), np.int64(1), np.int64(2), np.int64(3)]) + + The entry for each value is an index tuple, locating the elements + with that value. + + >>> ndx1 = val_indices[1] + >>> ndx1 + (array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4])) + + This can be used to index into the original array, or any other + array with the same shape. + + >>> a[ndx1] + array([1, 1, 1, 1, 1]) + + If the zeros were to be ignored, then the resulting dictionary + would no longer have an entry for zero. + + >>> val_indices = ndimage.value_indices(a, ignore_value=0) + >>> val_indices.keys() + dict_keys([np.int64(1), np.int64(2), np.int64(3)]) + + """ + # Cope with ignore_value being None, without too much extra complexity + # in the C code. If not None, the value is passed in as a numpy array + # with the same dtype as arr. + arr = np.asarray(arr) + ignore_value_arr = np.zeros((1,), dtype=arr.dtype) + ignoreIsNone = (ignore_value is None) + if not ignoreIsNone: + ignore_value_arr[0] = ignore_value_arr.dtype.type(ignore_value) + + val_indices = _nd_image.value_indices(arr, ignoreIsNone, ignore_value_arr) + return val_indices + + +def labeled_comprehension(input, labels, index, func, out_dtype, default, + pass_positions=False): + """ + Roughly equivalent to [func(input[labels == i]) for i in index]. + + Sequentially applies an arbitrary function (that works on array_like input) + to subsets of an N-D image array specified by `labels` and `index`. + The option exists to provide the function with positional parameters as the + second argument. + + Parameters + ---------- + input : array_like + Data from which to select `labels` to process. + labels : array_like or None + Labels to objects in `input`. + If not None, array must be same shape as `input`. + If None, `func` is applied to raveled `input`. + index : int, sequence of ints or None + Subset of `labels` to which to apply `func`. + If a scalar, a single value is returned. + If None, `func` is applied to all non-zero values of `labels`. + func : callable + Python function to apply to `labels` from `input`. + out_dtype : dtype + Dtype to use for `result`. + default : int, float or None + Default return value when a element of `index` does not exist + in `labels`. + pass_positions : bool, optional + If True, pass linear indices to `func` as a second argument. + Default is False. + + Returns + ------- + result : ndarray + Result of applying `func` to each of `labels` to `input` in `index`. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> lbl, nlbl = ndimage.label(a) + >>> lbls = np.arange(1, nlbl+1) + >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0) + array([ 2.75, 5.5 , 6. ]) + + Falling back to `default`: + + >>> lbls = np.arange(1, nlbl+2) + >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1) + array([ 2.75, 5.5 , 6. , -1. ]) + + Passing positions: + + >>> def fn(val, pos): + ... print("fn says: %s : %s" % (val, pos)) + ... return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum()) + ... + >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True) + fn says: [1 2 5 3] : [0 1 4 5] + fn says: [4 7] : [ 7 11] + fn says: [9 3] : [12 13] + array([ 11., 11., -12., 0.]) + + """ + + as_scalar = np.isscalar(index) + input = np.asarray(input) + + if pass_positions: + positions = np.arange(input.size).reshape(input.shape) + + if labels is None: + if index is not None: + raise ValueError("index without defined labels") + if not pass_positions: + return func(input.ravel()) + else: + return func(input.ravel(), positions.ravel()) + + labels = np.asarray(labels) + + try: + input, labels = np.broadcast_arrays(input, labels) + except ValueError as e: + raise ValueError("input and labels must have the same shape " + "(excepting dimensions with width 1)") from e + + if index is None: + if not pass_positions: + return func(input[labels > 0]) + else: + return func(input[labels > 0], positions[labels > 0]) + + index = np.atleast_1d(index) + if np.any(index.astype(labels.dtype).astype(index.dtype) != index): + raise ValueError(f"Cannot convert index values from <{index.dtype}> to " + f"<{labels.dtype}> (labels' type) without loss of precision") + + index = index.astype(labels.dtype) + + # optimization: find min/max in index, + # and select those parts of labels, input, and positions + lo = index.min() + hi = index.max() + mask = (labels >= lo) & (labels <= hi) + + # this also ravels the arrays + labels = labels[mask] + input = input[mask] + if pass_positions: + positions = positions[mask] + + # sort everything by labels + label_order = labels.argsort() + labels = labels[label_order] + input = input[label_order] + if pass_positions: + positions = positions[label_order] + + index_order = index.argsort() + sorted_index = index[index_order] + + def do_map(inputs, output): + """labels must be sorted""" + nidx = sorted_index.size + + # Find boundaries for each stretch of constant labels + # This could be faster, but we already paid N log N to sort labels. + lo = np.searchsorted(labels, sorted_index, side='left') + hi = np.searchsorted(labels, sorted_index, side='right') + + for i, l, h in zip(range(nidx), lo, hi): + if l == h: + continue + output[i] = func(*[inp[l:h] for inp in inputs]) + + temp = np.empty(index.shape, out_dtype) + temp[:] = default + if not pass_positions: + do_map([input], temp) + else: + do_map([input, positions], temp) + + output = np.zeros(index.shape, out_dtype) + output[index_order] = temp + if as_scalar: + output = output[0] + + return output + + +def _safely_castable_to_int(dt): + """Test whether the NumPy data type `dt` can be safely cast to an int.""" + int_size = np.dtype(int).itemsize + safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or + (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size)) + return safe + + +def _stats(input, labels=None, index=None, centered=False): + """Count, sum, and optionally compute (sum - centre)^2 of input by label + + Parameters + ---------- + input : array_like, N-D + The input data to be analyzed. + labels : array_like (N-D), optional + The labels of the data in `input`. This array must be broadcast + compatible with `input`; typically, it is the same shape as `input`. + If `labels` is None, all nonzero values in `input` are treated as + the single labeled group. + index : label or sequence of labels, optional + These are the labels of the groups for which the stats are computed. + If `index` is None, the stats are computed for the single group where + `labels` is greater than 0. + centered : bool, optional + If True, the centered sum of squares for each labeled group is + also returned. Default is False. + + Returns + ------- + counts : int or ndarray of ints + The number of elements in each labeled group. + sums : scalar or ndarray of scalars + The sums of the values in each labeled group. + sums_c : scalar or ndarray of scalars, optional + The sums of mean-centered squares of the values in each labeled group. + This is only returned if `centered` is True. + + """ + def single_group(vals): + if centered: + vals_c = vals - vals.mean() + return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum() + else: + return vals.size, vals.sum() + + input = np.asarray(input) + if labels is None: + return single_group(input) + + # ensure input and labels match sizes + input, labels = np.broadcast_arrays(input, labels) + + if index is None: + return single_group(input[labels > 0]) + + if np.isscalar(index): + return single_group(input[labels == index]) + + def _sum_centered(labels): + # `labels` is expected to be an ndarray with the same shape as `input`. + # It must contain the label indices (which are not necessarily the labels + # themselves). + means = sums / counts + centered_input = input - means[labels] + # bincount expects 1-D inputs, so we ravel the arguments. + bc = np.bincount(labels.ravel(), + weights=(centered_input * + centered_input.conjugate()).ravel()) + return bc + + # Remap labels to unique integers if necessary, or if the largest + # label is larger than the number of values. + + if (not _safely_castable_to_int(labels.dtype) or + labels.min() < 0 or labels.max() > labels.size): + # Use np.unique to generate the label indices. `new_labels` will + # be 1-D, but it should be interpreted as the flattened N-D array of + # label indices. + unique_labels, new_labels = np.unique(labels, return_inverse=True) + new_labels = np.reshape(new_labels, (-1,)) # flatten, since it may be >1-D + counts = np.bincount(new_labels) + sums = np.bincount(new_labels, weights=input.ravel()) + if centered: + # Compute the sum of the mean-centered squares. + # We must reshape new_labels to the N-D shape of `input` before + # passing it _sum_centered. + sums_c = _sum_centered(new_labels.reshape(labels.shape)) + idxs = np.searchsorted(unique_labels, index) + # make all of idxs valid + idxs[idxs >= unique_labels.size] = 0 + found = (unique_labels[idxs] == index) + else: + # labels are an integer type allowed by bincount, and there aren't too + # many, so call bincount directly. + counts = np.bincount(labels.ravel()) + sums = np.bincount(labels.ravel(), weights=input.ravel()) + if centered: + sums_c = _sum_centered(labels) + # make sure all index values are valid + idxs = np.asanyarray(index, np.int_).copy() + found = (idxs >= 0) & (idxs < counts.size) + idxs[~found] = 0 + + counts = counts[idxs] + counts[~found] = 0 + sums = sums[idxs] + sums[~found] = 0 + + if not centered: + return (counts, sums) + else: + sums_c = sums_c[idxs] + sums_c[~found] = 0 + return (counts, sums, sums_c) + + +def sum(input, labels=None, index=None): + """ + Calculate the sum of the values of the array. + + Notes + ----- + This is an alias for `ndimage.sum_labels` kept for backwards compatibility + reasons, for new code please prefer `sum_labels`. See the `sum_labels` + docstring for more details. + + """ + return sum_labels(input, labels, index) + + +def sum_labels(input, labels=None, index=None): + """ + Calculate the sum of the values of the array. + + Parameters + ---------- + input : array_like + Values of `input` inside the regions defined by `labels` + are summed together. + labels : array_like of ints, optional + Assign labels to the values of the array. Has to have the same shape as + `input`. + index : array_like, optional + A single label number or a sequence of label numbers of + the objects to be measured. + + Returns + ------- + sum : ndarray or scalar + An array of the sums of values of `input` inside the regions defined + by `labels` with the same shape as `index`. If 'index' is None or scalar, + a scalar is returned. + + See Also + -------- + mean, median + + Examples + -------- + >>> from scipy import ndimage + >>> input = [0,1,2,3] + >>> labels = [1,1,2,2] + >>> ndimage.sum_labels(input, labels, index=[1,2]) + [1.0, 5.0] + >>> ndimage.sum_labels(input, labels, index=1) + 1 + >>> ndimage.sum_labels(input, labels) + 6 + + + """ + count, sum = _stats(input, labels, index) + return sum + + +def mean(input, labels=None, index=None): + """ + Calculate the mean of the values of an array at labels. + + Parameters + ---------- + input : array_like + Array on which to compute the mean of elements over distinct + regions. + labels : array_like, optional + Array of labels of same shape, or broadcastable to the same shape as + `input`. All elements sharing the same label form one region over + which the mean of the elements is computed. + index : int or sequence of ints, optional + Labels of the objects over which the mean is to be computed. + Default is None, in which case the mean for all values where label is + greater than 0 is calculated. + + Returns + ------- + out : list + Sequence of same length as `index`, with the mean of the different + regions labeled by the labels in `index`. + + See Also + -------- + variance, standard_deviation, minimum, maximum, sum, label + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(25).reshape((5,5)) + >>> labels = np.zeros_like(a) + >>> labels[3:5,3:5] = 1 + >>> index = np.unique(labels) + >>> labels + array([[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1]]) + >>> index + array([0, 1]) + >>> ndimage.mean(a, labels=labels, index=index) + [10.285714285714286, 21.0] + + """ + + count, sum = _stats(input, labels, index) + return sum / np.asanyarray(count).astype(np.float64) + + +def variance(input, labels=None, index=None): + """ + Calculate the variance of the values of an N-D image array, optionally at + specified sub-regions. + + Parameters + ---------- + input : array_like + Nd-image data to process. + labels : array_like, optional + Labels defining sub-regions in `input`. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + `labels` to include in output. If None (default), all values where + `labels` is non-zero are used. + + Returns + ------- + variance : float or ndarray + Values of variance, for each sub-region if `labels` and `index` are + specified. + + See Also + -------- + label, standard_deviation, maximum, minimum, extrema + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> ndimage.variance(a) + 7.609375 + + Features to process can be specified using `labels` and `index`: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1)) + array([ 2.1875, 2.25 , 9. ]) + + If no index is given, all non-zero `labels` are processed: + + >>> ndimage.variance(a, lbl) + 6.1875 + + """ + count, sum, sum_c_sq = _stats(input, labels, index, centered=True) + return sum_c_sq / np.asanyarray(count).astype(float) + + +def standard_deviation(input, labels=None, index=None): + """ + Calculate the standard deviation of the values of an N-D image array, + optionally at specified sub-regions. + + Parameters + ---------- + input : array_like + N-D image data to process. + labels : array_like, optional + Labels to identify sub-regions in `input`. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + `labels` to include in output. If None (default), all values where + `labels` is non-zero are used. + + Returns + ------- + standard_deviation : float or ndarray + Values of standard deviation, for each sub-region if `labels` and + `index` are specified. + + See Also + -------- + label, variance, maximum, minimum, extrema + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> ndimage.standard_deviation(a) + 2.7585095613392387 + + Features to process can be specified using `labels` and `index`: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1)) + array([ 1.479, 1.5 , 3. ]) + + If no index is given, non-zero `labels` are processed: + + >>> ndimage.standard_deviation(a, lbl) + 2.4874685927665499 + + """ + return np.sqrt(variance(input, labels, index)) + + +def _select(input, labels=None, index=None, find_min=False, find_max=False, + find_min_positions=False, find_max_positions=False, + find_median=False): + """Returns min, max, or both, plus their positions (if requested), and + median.""" + + input = np.asanyarray(input) + + find_positions = find_min_positions or find_max_positions + positions = None + if find_positions: + positions = np.arange(input.size).reshape(input.shape) + + def single_group(vals, positions): + result = [] + if find_min: + result += [vals.min()] + if find_min_positions: + result += [positions[vals == vals.min()][0]] + if find_max: + result += [vals.max()] + if find_max_positions: + result += [positions[vals == vals.max()][0]] + if find_median: + result += [np.median(vals)] + return result + + if labels is None: + return single_group(input, positions) + + # ensure input and labels match sizes + input, labels = np.broadcast_arrays(input, labels) + + if index is None: + mask = (labels > 0) + masked_positions = None + if find_positions: + masked_positions = positions[mask] + return single_group(input[mask], masked_positions) + + if np.isscalar(index): + mask = (labels == index) + masked_positions = None + if find_positions: + masked_positions = positions[mask] + return single_group(input[mask], masked_positions) + + index = np.asarray(index) + + # remap labels to unique integers if necessary, or if the largest + # label is larger than the number of values. + if (not _safely_castable_to_int(labels.dtype) or + labels.min() < 0 or labels.max() > labels.size): + # remap labels, and indexes + unique_labels, labels = np.unique(labels, return_inverse=True) + idxs = np.searchsorted(unique_labels, index) + + # make all of idxs valid + idxs[idxs >= unique_labels.size] = 0 + found = (unique_labels[idxs] == index) + else: + # labels are an integer type, and there aren't too many + idxs = np.asanyarray(index, np.int_).copy() + found = (idxs >= 0) & (idxs <= labels.max()) + + idxs[~ found] = labels.max() + 1 + + if find_median: + order = np.lexsort((input.ravel(), labels.ravel())) + else: + order = input.ravel().argsort() + input = input.ravel()[order] + labels = labels.ravel()[order] + if find_positions: + positions = positions.ravel()[order] + + result = [] + if find_min: + mins = np.zeros(labels.max() + 2, input.dtype) + mins[labels[::-1]] = input[::-1] + result += [mins[idxs]] + if find_min_positions: + minpos = np.zeros(labels.max() + 2, int) + minpos[labels[::-1]] = positions[::-1] + result += [minpos[idxs]] + if find_max: + maxs = np.zeros(labels.max() + 2, input.dtype) + maxs[labels] = input + result += [maxs[idxs]] + if find_max_positions: + maxpos = np.zeros(labels.max() + 2, int) + maxpos[labels] = positions + result += [maxpos[idxs]] + if find_median: + locs = np.arange(len(labels)) + lo = np.zeros(labels.max() + 2, np.int_) + lo[labels[::-1]] = locs[::-1] + hi = np.zeros(labels.max() + 2, np.int_) + hi[labels] = locs + lo = lo[idxs] + hi = hi[idxs] + # lo is an index to the lowest value in input for each label, + # hi is an index to the largest value. + # move them to be either the same ((hi - lo) % 2 == 0) or next + # to each other ((hi - lo) % 2 == 1), then average. + step = (hi - lo) // 2 + lo += step + hi -= step + if (np.issubdtype(input.dtype, np.integer) + or np.issubdtype(input.dtype, np.bool_)): + # avoid integer overflow or boolean addition (gh-12836) + result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0] + else: + result += [(input[lo] + input[hi]) / 2.0] + + return result + + +def minimum(input, labels=None, index=None): + """ + Calculate the minimum of the values of an array over labeled regions. + + Parameters + ---------- + input : array_like + Array_like of values. For each region specified by `labels`, the + minimal values of `input` over the region is computed. + labels : array_like, optional + An array_like of integers marking different regions over which the + minimum value of `input` is to be computed. `labels` must have the + same shape as `input`. If `labels` is not specified, the minimum + over the whole array is returned. + index : array_like, optional + A list of region labels that are taken into account for computing the + minima. If index is None, the minimum over all elements where `labels` + is non-zero is returned. + + Returns + ------- + minimum : float or list of floats + List of minima of `input` over the regions determined by `labels` and + whose index is in `index`. If `index` or `labels` are not specified, a + float is returned: the minimal value of `input` if `labels` is None, + and the minimal value of elements where `labels` is greater than zero + if `index` is None. + + See Also + -------- + label, maximum, median, minimum_position, extrema, sum, mean, variance, + standard_deviation + + Notes + ----- + The function returns a Python list and not a NumPy array, use + `np.array` to convert the list to an array. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> labels, labels_nb = ndimage.label(a) + >>> labels + array([[1, 1, 0, 0], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]], dtype=int32) + >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1)) + [1, 4, 3] + >>> ndimage.minimum(a) + 0 + >>> ndimage.minimum(a, labels=labels) + 1 + + """ + return _select(input, labels, index, find_min=True)[0] + + +def maximum(input, labels=None, index=None): + """ + Calculate the maximum of the values of an array over labeled regions. + + Parameters + ---------- + input : array_like + Array_like of values. For each region specified by `labels`, the + maximal values of `input` over the region is computed. + labels : array_like, optional + An array of integers marking different regions over which the + maximum value of `input` is to be computed. `labels` must have the + same shape as `input`. If `labels` is not specified, the maximum + over the whole array is returned. + index : array_like, optional + A list of region labels that are taken into account for computing the + maxima. If index is None, the maximum over all elements where `labels` + is non-zero is returned. + + Returns + ------- + output : float or list of floats + List of maxima of `input` over the regions determined by `labels` and + whose index is in `index`. If `index` or `labels` are not specified, a + float is returned: the maximal value of `input` if `labels` is None, + and the maximal value of elements where `labels` is greater than zero + if `index` is None. + + See Also + -------- + label, minimum, median, maximum_position, extrema, sum, mean, variance, + standard_deviation + + Notes + ----- + The function returns a Python list and not a NumPy array, use + `np.array` to convert the list to an array. + + Examples + -------- + >>> import numpy as np + >>> a = np.arange(16).reshape((4,4)) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + >>> labels = np.zeros_like(a) + >>> labels[:2,:2] = 1 + >>> labels[2:, 1:3] = 2 + >>> labels + array([[1, 1, 0, 0], + [1, 1, 0, 0], + [0, 2, 2, 0], + [0, 2, 2, 0]]) + >>> from scipy import ndimage + >>> ndimage.maximum(a) + 15 + >>> ndimage.maximum(a, labels=labels, index=[1,2]) + [5, 14] + >>> ndimage.maximum(a, labels=labels) + 14 + + >>> b = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> labels, labels_nb = ndimage.label(b) + >>> labels + array([[1, 1, 0, 0], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]], dtype=int32) + >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1)) + [5, 7, 9] + + """ + return _select(input, labels, index, find_max=True)[0] + + +def median(input, labels=None, index=None): + """ + Calculate the median of the values of an array over labeled regions. + + Parameters + ---------- + input : array_like + Array_like of values. For each region specified by `labels`, the + median value of `input` over the region is computed. + labels : array_like, optional + An array_like of integers marking different regions over which the + median value of `input` is to be computed. `labels` must have the + same shape as `input`. If `labels` is not specified, the median + over the whole array is returned. + index : array_like, optional + A list of region labels that are taken into account for computing the + medians. If index is None, the median over all elements where `labels` + is non-zero is returned. + + Returns + ------- + median : float or list of floats + List of medians of `input` over the regions determined by `labels` and + whose index is in `index`. If `index` or `labels` are not specified, a + float is returned: the median value of `input` if `labels` is None, + and the median value of elements where `labels` is greater than zero + if `index` is None. + + See Also + -------- + label, minimum, maximum, extrema, sum, mean, variance, standard_deviation + + Notes + ----- + The function returns a Python list and not a NumPy array, use + `np.array` to convert the list to an array. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 1], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> labels, labels_nb = ndimage.label(a) + >>> labels + array([[1, 1, 0, 2], + [1, 1, 0, 2], + [0, 0, 0, 2], + [3, 3, 0, 0]], dtype=int32) + >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1)) + [2.5, 4.0, 6.0] + >>> ndimage.median(a) + 1.0 + >>> ndimage.median(a, labels=labels) + 3.0 + + """ + return _select(input, labels, index, find_median=True)[0] + + +def minimum_position(input, labels=None, index=None): + """ + Find the positions of the minimums of the values of an array at labels. + + Parameters + ---------- + input : array_like + Array_like of values. + labels : array_like, optional + An array of integers marking different regions over which the + position of the minimum value of `input` is to be computed. + `labels` must have the same shape as `input`. If `labels` is not + specified, the location of the first minimum over the whole + array is returned. + + The `labels` argument only works when `index` is specified. + index : array_like, optional + A list of region labels that are taken into account for finding the + location of the minima. If `index` is None, the ``first`` minimum + over all elements where `labels` is non-zero is returned. + + The `index` argument only works when `labels` is specified. + + Returns + ------- + output : list of tuples of ints + Tuple of ints or list of tuples of ints that specify the location + of minima of `input` over the regions determined by `labels` and + whose index is in `index`. + + If `index` or `labels` are not specified, a tuple of ints is + returned specifying the location of the first minimal value of `input`. + + See Also + -------- + label, minimum, median, maximum_position, extrema, sum, mean, variance, + standard_deviation + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[10, 20, 30], + ... [40, 80, 100], + ... [1, 100, 200]]) + >>> b = np.array([[1, 2, 0, 1], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + + >>> from scipy import ndimage + + >>> ndimage.minimum_position(a) + (2, 0) + >>> ndimage.minimum_position(b) + (0, 2) + + Features to process can be specified using `labels` and `index`: + + >>> label, pos = ndimage.label(a) + >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1)) + [(2, 0)] + + >>> label, pos = ndimage.label(b) + >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1)) + [(0, 0), (0, 3), (3, 1)] + + """ + dims = np.array(np.asarray(input).shape) + # see np.unravel_index to understand this line. + dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1] + + result = _select(input, labels, index, find_min_positions=True)[0] + + if np.isscalar(result): + return tuple((result // dim_prod) % dims) + + return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims] + + +def maximum_position(input, labels=None, index=None): + """ + Find the positions of the maximums of the values of an array at labels. + + For each region specified by `labels`, the position of the maximum + value of `input` within the region is returned. + + Parameters + ---------- + input : array_like + Array_like of values. + labels : array_like, optional + An array of integers marking different regions over which the + position of the maximum value of `input` is to be computed. + `labels` must have the same shape as `input`. If `labels` is not + specified, the location of the first maximum over the whole + array is returned. + + The `labels` argument only works when `index` is specified. + index : array_like, optional + A list of region labels that are taken into account for finding the + location of the maxima. If `index` is None, the first maximum + over all elements where `labels` is non-zero is returned. + + The `index` argument only works when `labels` is specified. + + Returns + ------- + output : list of tuples of ints + List of tuples of ints that specify the location of maxima of + `input` over the regions determined by `labels` and whose index + is in `index`. + + If `index` or `labels` are not specified, a tuple of ints is + returned specifying the location of the ``first`` maximal value + of `input`. + + See Also + -------- + label, minimum, median, maximum_position, extrema, sum, mean, variance, + standard_deviation + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> ndimage.maximum_position(a) + (3, 0) + + Features to process can be specified using `labels` and `index`: + + >>> lbl = np.array([[0, 1, 2, 3], + ... [0, 1, 2, 3], + ... [0, 1, 2, 3], + ... [0, 1, 2, 3]]) + >>> ndimage.maximum_position(a, lbl, 1) + (1, 1) + + If no index is given, non-zero `labels` are processed: + + >>> ndimage.maximum_position(a, lbl) + (2, 3) + + If there are no maxima, the position of the first element is returned: + + >>> ndimage.maximum_position(a, lbl, 2) + (0, 2) + + """ + dims = np.array(np.asarray(input).shape) + # see np.unravel_index to understand this line. + dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1] + + result = _select(input, labels, index, find_max_positions=True)[0] + + if np.isscalar(result): + return tuple((result // dim_prod) % dims) + + return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims] + + +def extrema(input, labels=None, index=None): + """ + Calculate the minimums and maximums of the values of an array + at labels, along with their positions. + + Parameters + ---------- + input : ndarray + N-D image data to process. + labels : ndarray, optional + Labels of features in input. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + Labels to include in output. If None (default), all values where + non-zero `labels` are used. + + Returns + ------- + minimums, maximums : int or ndarray + Values of minimums and maximums in each feature. + min_positions, max_positions : tuple or list of tuples + Each tuple gives the N-D coordinates of the corresponding minimum + or maximum. + + See Also + -------- + maximum, minimum, maximum_position, minimum_position, center_of_mass + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> from scipy import ndimage + >>> ndimage.extrema(a) + (0, 9, (0, 2), (3, 0)) + + Features to process can be specified using `labels` and `index`: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1)) + (array([1, 4, 3]), + array([5, 7, 9]), + [(0, 0), (1, 3), (3, 1)], + [(1, 0), (2, 3), (3, 0)]) + + If no index is given, non-zero `labels` are processed: + + >>> ndimage.extrema(a, lbl) + (1, 9, (0, 0), (3, 0)) + + """ + dims = np.array(np.asarray(input).shape) + # see np.unravel_index to understand this line. + dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1] + + minimums, min_positions, maximums, max_positions = _select(input, labels, + index, + find_min=True, + find_max=True, + find_min_positions=True, + find_max_positions=True) + + if np.isscalar(minimums): + return (minimums, maximums, tuple((min_positions // dim_prod) % dims), + tuple((max_positions // dim_prod) % dims)) + + min_positions = [ + tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims + ] + max_positions = [ + tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims + ] + + return minimums, maximums, min_positions, max_positions + + +def center_of_mass(input, labels=None, index=None): + """ + Calculate the center of mass of the values of an array at labels. + + Parameters + ---------- + input : ndarray + Data from which to calculate center-of-mass. The masses can either + be positive or negative. + labels : ndarray, optional + Labels for objects in `input`, as generated by `ndimage.label`. + Only used with `index`. Dimensions must be the same as `input`. + index : int or sequence of ints, optional + Labels for which to calculate centers-of-mass. If not specified, + the combined center of mass of all labels greater than zero + will be calculated. Only used with `labels`. + + Returns + ------- + center_of_mass : tuple, or list of tuples + Coordinates of centers-of-mass. + + Examples + -------- + >>> import numpy as np + >>> a = np.array(([0,0,0,0], + ... [0,1,1,0], + ... [0,1,1,0], + ... [0,1,1,0])) + >>> from scipy import ndimage + >>> ndimage.center_of_mass(a) + (2.0, 1.5) + + Calculation of multiple objects in an image + + >>> b = np.array(([0,1,1,0], + ... [0,1,0,0], + ... [0,0,0,0], + ... [0,0,1,1], + ... [0,0,1,1])) + >>> lbl = ndimage.label(b)[0] + >>> ndimage.center_of_mass(b, lbl, [1,2]) + [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)] + + Negative masses are also accepted, which can occur for example when + bias is removed from measured data due to random noise. + + >>> c = np.array(([-1,0,0,0], + ... [0,-1,-1,0], + ... [0,1,-1,0], + ... [0,1,1,0])) + >>> ndimage.center_of_mass(c) + (-4.0, 1.0) + + If there are division by zero issues, the function does not raise an + error but rather issues a RuntimeWarning before returning inf and/or NaN. + + >>> d = np.array([-1, 1]) + >>> ndimage.center_of_mass(d) + (inf,) + """ + input = np.asarray(input) + normalizer = sum_labels(input, labels, index) + grids = np.ogrid[[slice(0, i) for i in input.shape]] + + results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer + for dir in range(input.ndim)] + + if np.isscalar(results[0]): + return tuple(results) + + return [tuple(v) for v in np.array(results).T] + + +def histogram(input, min, max, bins, labels=None, index=None): + """ + Calculate the histogram of the values of an array, optionally at labels. + + Histogram calculates the frequency of values in an array within bins + determined by `min`, `max`, and `bins`. The `labels` and `index` + keywords can limit the scope of the histogram to specified sub-regions + within the array. + + Parameters + ---------- + input : array_like + Data for which to calculate histogram. + min, max : int + Minimum and maximum values of range of histogram bins. + bins : int + Number of bins. + labels : array_like, optional + Labels for objects in `input`. + If not None, must be same shape as `input`. + index : int or sequence of ints, optional + Label or labels for which to calculate histogram. If None, all values + where label is greater than zero are used + + Returns + ------- + hist : ndarray + Histogram counts. + + Examples + -------- + >>> import numpy as np + >>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ], + ... [ 0. , 0.7778, 0. , 0. ], + ... [ 0. , 0. , 0. , 0. ], + ... [ 0. , 0. , 0.7181, 0.2787], + ... [ 0. , 0. , 0.6573, 0.3094]]) + >>> from scipy import ndimage + >>> ndimage.histogram(a, 0, 1, 10) + array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0]) + + With labels and no indices, non-zero elements are counted: + + >>> lbl, nlbl = ndimage.label(a) + >>> ndimage.histogram(a, 0, 1, 10, lbl) + array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0]) + + Indices can be used to count only certain objects: + + >>> ndimage.histogram(a, 0, 1, 10, lbl, 2) + array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0]) + + """ + _bins = np.linspace(min, max, bins + 1) + + def _hist(vals): + return np.histogram(vals, _bins)[0] + + return labeled_comprehension(input, labels, index, _hist, object, None, + pass_positions=False) + + +def watershed_ift(input, markers, structure=None, output=None): + """ + Apply watershed from markers using image foresting transform algorithm. + + Parameters + ---------- + input : array_like + Input. + markers : array_like + Markers are points within each watershed that form the beginning + of the process. Negative markers are considered background markers + which are processed after the other markers. + structure : structure element, optional + A structuring element defining the connectivity of the object can be + provided. If None, an element is generated with a squared + connectivity equal to one. + output : ndarray, optional + An output array can optionally be provided. The same shape as input. + + Returns + ------- + watershed_ift : ndarray + Output. Same shape as `input`. + + References + ---------- + .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image + foresting transform: theory, algorithms, and applications", + Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004. + + """ + input = np.asarray(input) + if input.dtype.type not in [np.uint8, np.uint16]: + raise TypeError('only 8 and 16 unsigned inputs are supported') + + if structure is None: + structure = _morphology.generate_binary_structure(input.ndim, 1) + structure = np.asarray(structure, dtype=bool) + if structure.ndim != input.ndim: + raise RuntimeError('structure and input must have equal rank') + for ii in structure.shape: + if ii != 3: + raise RuntimeError('structure dimensions must be equal to 3') + + if not structure.flags.contiguous: + structure = structure.copy() + markers = np.asarray(markers) + if input.shape != markers.shape: + raise RuntimeError('input and markers must have equal shape') + + integral_types = [np.int8, + np.int16, + np.int32, + np.int64, + np.intc, + np.intp] + + if markers.dtype.type not in integral_types: + raise RuntimeError('marker should be of integer type') + + if isinstance(output, np.ndarray): + if output.dtype.type not in integral_types: + raise RuntimeError('output should be of integer type') + else: + output = markers.dtype + + output = _ni_support._get_output(output, input) + _nd_image.watershed_ift(input, markers, structure, output) + return output diff --git a/shared/package-files/7b/7b22b4ac09b31e129b064d36d212f9f5bb69eb0029a735e466929342072b2b01/blob b/shared/package-files/7b/7b22b4ac09b31e129b064d36d212f9f5bb69eb0029a735e466929342072b2b01/blob new file mode 100644 index 0000000000000000000000000000000000000000..b707f93a43a82622e0204acccded9aaca39d5e62 --- /dev/null +++ b/shared/package-files/7b/7b22b4ac09b31e129b064d36d212f9f5bb69eb0029a735e466929342072b2b01/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _weight_norm_interface(const at::Tensor & v, const at::Tensor & g, int64_t dim=0); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7b/7b22d96b88a64f541d77b3c26c35fd97412d0eedfd4fcd1e0ab4ab7b6c264ee1/blob b/shared/package-files/7b/7b22d96b88a64f541d77b3c26c35fd97412d0eedfd4fcd1e0ab4ab7b6c264ee1/blob new file mode 100644 index 0000000000000000000000000000000000000000..1ed626cd5108081eff7156275f439ececdf28241 --- /dev/null +++ b/shared/package-files/7b/7b22d96b88a64f541d77b3c26c35fd97412d0eedfd4fcd1e0ab4ab7b6c264ee1/blob @@ -0,0 +1,26 @@ +""" +Tests for behavior if an author does *not* implement EA methods. +""" +import numpy as np +import pytest + +from pandas.core.arrays import ExtensionArray + + +class MyEA(ExtensionArray): + def __init__(self, values) -> None: + self._values = values + + +@pytest.fixture +def data(): + arr = np.arange(10) + return MyEA(arr) + + +class TestExtensionArray: + def test_errors(self, data, all_arithmetic_operators): + # invalid ops + op_name = all_arithmetic_operators + with pytest.raises(AttributeError): + getattr(data, op_name) diff --git a/shared/package-files/7b/7b231d7f1fa072025a548458d8d060403b769d6e4a49d519dccf5544f61426d5/blob b/shared/package-files/7b/7b231d7f1fa072025a548458d8d060403b769d6e4a49d519dccf5544f61426d5/blob new file mode 100644 index 0000000000000000000000000000000000000000..7e553ca448218435eafe1fd7ca97dce6f739e2a3 --- /dev/null +++ b/shared/package-files/7b/7b231d7f1fa072025a548458d8d060403b769d6e4a49d519dccf5544f61426d5/blob @@ -0,0 +1,355 @@ +""" +Module for scope operations +""" +from __future__ import annotations + +from collections import ChainMap +import datetime +import inspect +from io import StringIO +import itertools +import pprint +import struct +import sys +from typing import TypeVar + +import numpy as np + +from pandas._libs.tslibs import Timestamp +from pandas.errors import UndefinedVariableError + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +# https://docs.python.org/3/library/collections.html#chainmap-examples-and-recipes +class DeepChainMap(ChainMap[_KT, _VT]): + """ + Variant of ChainMap that allows direct updates to inner scopes. + + Only works when all passed mapping are mutable. + """ + + def __setitem__(self, key: _KT, value: _VT) -> None: + for mapping in self.maps: + if key in mapping: + mapping[key] = value + return + self.maps[0][key] = value + + def __delitem__(self, key: _KT) -> None: + """ + Raises + ------ + KeyError + If `key` doesn't exist. + """ + for mapping in self.maps: + if key in mapping: + del mapping[key] + return + raise KeyError(key) + + +def ensure_scope( + level: int, global_dict=None, local_dict=None, resolvers=(), target=None +) -> Scope: + """Ensure that we are grabbing the correct scope.""" + return Scope( + level + 1, + global_dict=global_dict, + local_dict=local_dict, + resolvers=resolvers, + target=target, + ) + + +def _replacer(x) -> str: + """ + Replace a number with its hexadecimal representation. Used to tag + temporary variables with their calling scope's id. + """ + # get the hex repr of the binary char and remove 0x and pad by pad_size + # zeros + try: + hexin = ord(x) + except TypeError: + # bytes literals masquerade as ints when iterating in py3 + hexin = x + + return hex(hexin) + + +def _raw_hex_id(obj) -> str: + """Return the padded hexadecimal id of ``obj``.""" + # interpret as a pointer since that's what really what id returns + packed = struct.pack("@P", id(obj)) + return "".join([_replacer(x) for x in packed]) + + +DEFAULT_GLOBALS = { + "Timestamp": Timestamp, + "datetime": datetime.datetime, + "True": True, + "False": False, + "list": list, + "tuple": tuple, + "inf": np.inf, + "Inf": np.inf, +} + + +def _get_pretty_string(obj) -> str: + """ + Return a prettier version of obj. + + Parameters + ---------- + obj : object + Object to pretty print + + Returns + ------- + str + Pretty print object repr + """ + sio = StringIO() + pprint.pprint(obj, stream=sio) + return sio.getvalue() + + +class Scope: + """ + Object to hold scope, with a few bells to deal with some custom syntax + and contexts added by pandas. + + Parameters + ---------- + level : int + global_dict : dict or None, optional, default None + local_dict : dict or Scope or None, optional, default None + resolvers : list-like or None, optional, default None + target : object + + Attributes + ---------- + level : int + scope : DeepChainMap + target : object + temps : dict + """ + + __slots__ = ["level", "scope", "target", "resolvers", "temps"] + level: int + scope: DeepChainMap + resolvers: DeepChainMap + temps: dict + + def __init__( + self, level: int, global_dict=None, local_dict=None, resolvers=(), target=None + ) -> None: + self.level = level + 1 + + # shallow copy because we don't want to keep filling this up with what + # was there before if there are multiple calls to Scope/_ensure_scope + self.scope = DeepChainMap(DEFAULT_GLOBALS.copy()) + self.target = target + + if isinstance(local_dict, Scope): + self.scope.update(local_dict.scope) + if local_dict.target is not None: + self.target = local_dict.target + self._update(local_dict.level) + + frame = sys._getframe(self.level) + + try: + # shallow copy here because we don't want to replace what's in + # scope when we align terms (alignment accesses the underlying + # numpy array of pandas objects) + scope_global = self.scope.new_child( + (global_dict if global_dict is not None else frame.f_globals).copy() + ) + self.scope = DeepChainMap(scope_global) + if not isinstance(local_dict, Scope): + scope_local = self.scope.new_child( + (local_dict if local_dict is not None else frame.f_locals).copy() + ) + self.scope = DeepChainMap(scope_local) + finally: + del frame + + # assumes that resolvers are going from outermost scope to inner + if isinstance(local_dict, Scope): + resolvers += tuple(local_dict.resolvers.maps) + self.resolvers = DeepChainMap(*resolvers) + self.temps = {} + + def __repr__(self) -> str: + scope_keys = _get_pretty_string(list(self.scope.keys())) + res_keys = _get_pretty_string(list(self.resolvers.keys())) + return f"{type(self).__name__}(scope={scope_keys}, resolvers={res_keys})" + + @property + def has_resolvers(self) -> bool: + """ + Return whether we have any extra scope. + + For example, DataFrames pass Their columns as resolvers during calls to + ``DataFrame.eval()`` and ``DataFrame.query()``. + + Returns + ------- + hr : bool + """ + return bool(len(self.resolvers)) + + def resolve(self, key: str, is_local: bool): + """ + Resolve a variable name in a possibly local context. + + Parameters + ---------- + key : str + A variable name + is_local : bool + Flag indicating whether the variable is local or not (prefixed with + the '@' symbol) + + Returns + ------- + value : object + The value of a particular variable + """ + try: + # only look for locals in outer scope + if is_local: + return self.scope[key] + + # not a local variable so check in resolvers if we have them + if self.has_resolvers: + return self.resolvers[key] + + # if we're here that means that we have no locals and we also have + # no resolvers + assert not is_local and not self.has_resolvers + return self.scope[key] + except KeyError: + try: + # last ditch effort we look in temporaries + # these are created when parsing indexing expressions + # e.g., df[df > 0] + return self.temps[key] + except KeyError as err: + raise UndefinedVariableError(key, is_local) from err + + def swapkey(self, old_key: str, new_key: str, new_value=None) -> None: + """ + Replace a variable name, with a potentially new value. + + Parameters + ---------- + old_key : str + Current variable name to replace + new_key : str + New variable name to replace `old_key` with + new_value : object + Value to be replaced along with the possible renaming + """ + if self.has_resolvers: + maps = self.resolvers.maps + self.scope.maps + else: + maps = self.scope.maps + + maps.append(self.temps) + + for mapping in maps: + if old_key in mapping: + mapping[new_key] = new_value + return + + def _get_vars(self, stack, scopes: list[str]) -> None: + """ + Get specifically scoped variables from a list of stack frames. + + Parameters + ---------- + stack : list + A list of stack frames as returned by ``inspect.stack()`` + scopes : sequence of strings + A sequence containing valid stack frame attribute names that + evaluate to a dictionary. For example, ('locals', 'globals') + """ + variables = itertools.product(scopes, stack) + for scope, (frame, _, _, _, _, _) in variables: + try: + d = getattr(frame, f"f_{scope}") + self.scope = DeepChainMap(self.scope.new_child(d)) + finally: + # won't remove it, but DECREF it + # in Py3 this probably isn't necessary since frame won't be + # scope after the loop + del frame + + def _update(self, level: int) -> None: + """ + Update the current scope by going back `level` levels. + + Parameters + ---------- + level : int + """ + sl = level + 1 + + # add sl frames to the scope starting with the + # most distant and overwriting with more current + # makes sure that we can capture variable scope + stack = inspect.stack() + + try: + self._get_vars(stack[:sl], scopes=["locals"]) + finally: + del stack[:], stack + + def add_tmp(self, value) -> str: + """ + Add a temporary variable to the scope. + + Parameters + ---------- + value : object + An arbitrary object to be assigned to a temporary variable. + + Returns + ------- + str + The name of the temporary variable created. + """ + name = f"{type(value).__name__}_{self.ntemps}_{_raw_hex_id(self)}" + + # add to inner most scope + assert name not in self.temps + self.temps[name] = value + assert name in self.temps + + # only increment if the variable gets put in the scope + return name + + @property + def ntemps(self) -> int: + """The number of temporary variables in this scope""" + return len(self.temps) + + @property + def full_scope(self) -> DeepChainMap: + """ + Return the full scope for use with passing to engines transparently + as a mapping. + + Returns + ------- + vars : DeepChainMap + All variables in this scope. + """ + maps = [self.temps] + self.resolvers.maps + self.scope.maps + return DeepChainMap(*maps) diff --git a/shared/package-files/7b/7b2356a9ab71ae89c314e3a87f6f7b45b9e1cf73d3ab0fdde9864021c76481e2/blob b/shared/package-files/7b/7b2356a9ab71ae89c314e3a87f6f7b45b9e1cf73d3ab0fdde9864021c76481e2/blob new file mode 100644 index 0000000000000000000000000000000000000000..a6a9ce211b1ac204977768d6efd8606643a02f99 --- /dev/null +++ b/shared/package-files/7b/7b2356a9ab71ae89c314e3a87f6f7b45b9e1cf73d3ab0fdde9864021c76481e2/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor upsample_bicubic2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor upsample_bicubic2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_bicubic2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_bicubic2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & upsample_bicubic2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_bicubic2d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional scales_h, c10::optional scales_w, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/7b/7b244de14dc54db34677d5978e2faa117f19882e36243f806ec38b56e175235a/blob b/shared/package-files/7b/7b244de14dc54db34677d5978e2faa117f19882e36243f806ec38b56e175235a/blob new file mode 100644 index 0000000000000000000000000000000000000000..d24c83f41e4852dad221af8e53e96b9598368a13 --- /dev/null +++ b/shared/package-files/7b/7b244de14dc54db34677d5978e2faa117f19882e36243f806ec38b56e175235a/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::matrix_exp_backward(Tensor self, Tensor grad) -> Tensor +inline at::Tensor matrix_exp_backward(const at::Tensor & self, const at::Tensor & grad) { + return at::_ops::matrix_exp_backward::call(self, grad); +} + +} diff --git a/shared/package-files/7b/7b250ef5ddf4e0ace50590d3ac555304ec89826cd15d3dede227e02699525095/blob b/shared/package-files/7b/7b250ef5ddf4e0ace50590d3ac555304ec89826cd15d3dede227e02699525095/blob new file mode 100644 index 0000000000000000000000000000000000000000..c4f1fe5170b780186740c32e779a29f3f4a58407 --- /dev/null +++ b/shared/package-files/7b/7b250ef5ddf4e0ace50590d3ac555304ec89826cd15d3dede227e02699525095/blob @@ -0,0 +1,24 @@ +from __future__ import annotations + +from enum import Enum +from typing import Literal + +from typing_extensions import TypeAlias + + +class Sentinel(Enum): + MISSING = "MISSING" + UNSET = "UNSET" + + def __bool__(self) -> bool: + return False + + def __repr__(self) -> str: + return self.name + + +UnsetType: TypeAlias = Literal[Sentinel.UNSET] +UNSET: UnsetType = Sentinel.UNSET + +MissingType: TypeAlias = Literal[Sentinel.MISSING] +MISSING: MissingType = Sentinel.MISSING diff --git a/shared/package-files/7b/7b25c61c9e8c47b218d3fbb801541a2861926ac712843d2113fff90e2074f5ba/blob b/shared/package-files/7b/7b25c61c9e8c47b218d3fbb801541a2861926ac712843d2113fff90e2074f5ba/blob new file mode 100644 index 0000000000000000000000000000000000000000..4fe9210697ce29487035e8691a5502c82c0b1eb5 --- /dev/null +++ b/shared/package-files/7b/7b25c61c9e8c47b218d3fbb801541a2861926ac712843d2113fff90e2074f5ba/blob @@ -0,0 +1,698 @@ +""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP855.TXT' with gencodec.py. + +"""#" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_map) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_map)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='cp855', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + +### Decoding Map + +decoding_map = codecs.make_identity_dict(range(256)) +decoding_map.update({ + 0x0080: 0x0452, # CYRILLIC SMALL LETTER DJE + 0x0081: 0x0402, # CYRILLIC CAPITAL LETTER DJE + 0x0082: 0x0453, # CYRILLIC SMALL LETTER GJE + 0x0083: 0x0403, # CYRILLIC CAPITAL LETTER GJE + 0x0084: 0x0451, # CYRILLIC SMALL LETTER IO + 0x0085: 0x0401, # CYRILLIC CAPITAL LETTER IO + 0x0086: 0x0454, # CYRILLIC SMALL LETTER UKRAINIAN IE + 0x0087: 0x0404, # CYRILLIC CAPITAL LETTER UKRAINIAN IE + 0x0088: 0x0455, # CYRILLIC SMALL LETTER DZE + 0x0089: 0x0405, # CYRILLIC CAPITAL LETTER DZE + 0x008a: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + 0x008b: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I + 0x008c: 0x0457, # CYRILLIC SMALL LETTER YI + 0x008d: 0x0407, # CYRILLIC CAPITAL LETTER YI + 0x008e: 0x0458, # CYRILLIC SMALL LETTER JE + 0x008f: 0x0408, # CYRILLIC CAPITAL LETTER JE + 0x0090: 0x0459, # CYRILLIC SMALL LETTER LJE + 0x0091: 0x0409, # CYRILLIC CAPITAL LETTER LJE + 0x0092: 0x045a, # CYRILLIC SMALL LETTER NJE + 0x0093: 0x040a, # CYRILLIC CAPITAL LETTER NJE + 0x0094: 0x045b, # CYRILLIC SMALL LETTER TSHE + 0x0095: 0x040b, # CYRILLIC CAPITAL LETTER TSHE + 0x0096: 0x045c, # CYRILLIC SMALL LETTER KJE + 0x0097: 0x040c, # CYRILLIC CAPITAL LETTER KJE + 0x0098: 0x045e, # CYRILLIC SMALL LETTER SHORT U + 0x0099: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U + 0x009a: 0x045f, # CYRILLIC SMALL LETTER DZHE + 0x009b: 0x040f, # CYRILLIC CAPITAL LETTER DZHE + 0x009c: 0x044e, # CYRILLIC SMALL LETTER YU + 0x009d: 0x042e, # CYRILLIC CAPITAL LETTER YU + 0x009e: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN + 0x009f: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN + 0x00a0: 0x0430, # CYRILLIC SMALL LETTER A + 0x00a1: 0x0410, # CYRILLIC CAPITAL LETTER A + 0x00a2: 0x0431, # CYRILLIC SMALL LETTER BE + 0x00a3: 0x0411, # CYRILLIC CAPITAL LETTER BE + 0x00a4: 0x0446, # CYRILLIC SMALL LETTER TSE + 0x00a5: 0x0426, # CYRILLIC CAPITAL LETTER TSE + 0x00a6: 0x0434, # CYRILLIC SMALL LETTER DE + 0x00a7: 0x0414, # CYRILLIC CAPITAL LETTER DE + 0x00a8: 0x0435, # CYRILLIC SMALL LETTER IE + 0x00a9: 0x0415, # CYRILLIC CAPITAL LETTER IE + 0x00aa: 0x0444, # CYRILLIC SMALL LETTER EF + 0x00ab: 0x0424, # CYRILLIC CAPITAL LETTER EF + 0x00ac: 0x0433, # CYRILLIC SMALL LETTER GHE + 0x00ad: 0x0413, # CYRILLIC CAPITAL LETTER GHE + 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00b0: 0x2591, # LIGHT SHADE + 0x00b1: 0x2592, # MEDIUM SHADE + 0x00b2: 0x2593, # DARK SHADE + 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL + 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x00b5: 0x0445, # CYRILLIC SMALL LETTER HA + 0x00b6: 0x0425, # CYRILLIC CAPITAL LETTER HA + 0x00b7: 0x0438, # CYRILLIC SMALL LETTER I + 0x00b8: 0x0418, # CYRILLIC CAPITAL LETTER I + 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT + 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL + 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT + 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT + 0x00bd: 0x0439, # CYRILLIC SMALL LETTER SHORT I + 0x00be: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I + 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT + 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT + 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL + 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x00c6: 0x043a, # CYRILLIC SMALL LETTER KA + 0x00c7: 0x041a, # CYRILLIC CAPITAL LETTER KA + 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT + 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT + 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL + 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL + 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + 0x00cf: 0x00a4, # CURRENCY SIGN + 0x00d0: 0x043b, # CYRILLIC SMALL LETTER EL + 0x00d1: 0x041b, # CYRILLIC CAPITAL LETTER EL + 0x00d2: 0x043c, # CYRILLIC SMALL LETTER EM + 0x00d3: 0x041c, # CYRILLIC CAPITAL LETTER EM + 0x00d4: 0x043d, # CYRILLIC SMALL LETTER EN + 0x00d5: 0x041d, # CYRILLIC CAPITAL LETTER EN + 0x00d6: 0x043e, # CYRILLIC SMALL LETTER O + 0x00d7: 0x041e, # CYRILLIC CAPITAL LETTER O + 0x00d8: 0x043f, # CYRILLIC SMALL LETTER PE + 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT + 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x00db: 0x2588, # FULL BLOCK + 0x00dc: 0x2584, # LOWER HALF BLOCK + 0x00dd: 0x041f, # CYRILLIC CAPITAL LETTER PE + 0x00de: 0x044f, # CYRILLIC SMALL LETTER YA + 0x00df: 0x2580, # UPPER HALF BLOCK + 0x00e0: 0x042f, # CYRILLIC CAPITAL LETTER YA + 0x00e1: 0x0440, # CYRILLIC SMALL LETTER ER + 0x00e2: 0x0420, # CYRILLIC CAPITAL LETTER ER + 0x00e3: 0x0441, # CYRILLIC SMALL LETTER ES + 0x00e4: 0x0421, # CYRILLIC CAPITAL LETTER ES + 0x00e5: 0x0442, # CYRILLIC SMALL LETTER TE + 0x00e6: 0x0422, # CYRILLIC CAPITAL LETTER TE + 0x00e7: 0x0443, # CYRILLIC SMALL LETTER U + 0x00e8: 0x0423, # CYRILLIC CAPITAL LETTER U + 0x00e9: 0x0436, # CYRILLIC SMALL LETTER ZHE + 0x00ea: 0x0416, # CYRILLIC CAPITAL LETTER ZHE + 0x00eb: 0x0432, # CYRILLIC SMALL LETTER VE + 0x00ec: 0x0412, # CYRILLIC CAPITAL LETTER VE + 0x00ed: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN + 0x00ee: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN + 0x00ef: 0x2116, # NUMERO SIGN + 0x00f0: 0x00ad, # SOFT HYPHEN + 0x00f1: 0x044b, # CYRILLIC SMALL LETTER YERU + 0x00f2: 0x042b, # CYRILLIC CAPITAL LETTER YERU + 0x00f3: 0x0437, # CYRILLIC SMALL LETTER ZE + 0x00f4: 0x0417, # CYRILLIC CAPITAL LETTER ZE + 0x00f5: 0x0448, # CYRILLIC SMALL LETTER SHA + 0x00f6: 0x0428, # CYRILLIC CAPITAL LETTER SHA + 0x00f7: 0x044d, # CYRILLIC SMALL LETTER E + 0x00f8: 0x042d, # CYRILLIC CAPITAL LETTER E + 0x00f9: 0x0449, # CYRILLIC SMALL LETTER SHCHA + 0x00fa: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA + 0x00fb: 0x0447, # CYRILLIC SMALL LETTER CHE + 0x00fc: 0x0427, # CYRILLIC CAPITAL LETTER CHE + 0x00fd: 0x00a7, # SECTION SIGN + 0x00fe: 0x25a0, # BLACK SQUARE + 0x00ff: 0x00a0, # NO-BREAK SPACE +}) + +### Decoding Table + +decoding_table = ( + '\x00' # 0x0000 -> NULL + '\x01' # 0x0001 -> START OF HEADING + '\x02' # 0x0002 -> START OF TEXT + '\x03' # 0x0003 -> END OF TEXT + '\x04' # 0x0004 -> END OF TRANSMISSION + '\x05' # 0x0005 -> ENQUIRY + '\x06' # 0x0006 -> ACKNOWLEDGE + '\x07' # 0x0007 -> BELL + '\x08' # 0x0008 -> BACKSPACE + '\t' # 0x0009 -> HORIZONTAL TABULATION + '\n' # 0x000a -> LINE FEED + '\x0b' # 0x000b -> VERTICAL TABULATION + '\x0c' # 0x000c -> FORM FEED + '\r' # 0x000d -> CARRIAGE RETURN + '\x0e' # 0x000e -> SHIFT OUT + '\x0f' # 0x000f -> SHIFT IN + '\x10' # 0x0010 -> DATA LINK ESCAPE + '\x11' # 0x0011 -> DEVICE CONTROL ONE + '\x12' # 0x0012 -> DEVICE CONTROL TWO + '\x13' # 0x0013 -> DEVICE CONTROL THREE + '\x14' # 0x0014 -> DEVICE CONTROL FOUR + '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE + '\x16' # 0x0016 -> SYNCHRONOUS IDLE + '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK + '\x18' # 0x0018 -> CANCEL + '\x19' # 0x0019 -> END OF MEDIUM + '\x1a' # 0x001a -> SUBSTITUTE + '\x1b' # 0x001b -> ESCAPE + '\x1c' # 0x001c -> FILE SEPARATOR + '\x1d' # 0x001d -> GROUP SEPARATOR + '\x1e' # 0x001e -> RECORD SEPARATOR + '\x1f' # 0x001f -> UNIT SEPARATOR + ' ' # 0x0020 -> SPACE + '!' # 0x0021 -> EXCLAMATION MARK + '"' # 0x0022 -> QUOTATION MARK + '#' # 0x0023 -> NUMBER SIGN + '$' # 0x0024 -> DOLLAR SIGN + '%' # 0x0025 -> PERCENT SIGN + '&' # 0x0026 -> AMPERSAND + "'" # 0x0027 -> APOSTROPHE + '(' # 0x0028 -> LEFT PARENTHESIS + ')' # 0x0029 -> RIGHT PARENTHESIS + '*' # 0x002a -> ASTERISK + '+' # 0x002b -> PLUS SIGN + ',' # 0x002c -> COMMA + '-' # 0x002d -> HYPHEN-MINUS + '.' # 0x002e -> FULL STOP + '/' # 0x002f -> SOLIDUS + '0' # 0x0030 -> DIGIT ZERO + '1' # 0x0031 -> DIGIT ONE + '2' # 0x0032 -> DIGIT TWO + '3' # 0x0033 -> DIGIT THREE + '4' # 0x0034 -> DIGIT FOUR + '5' # 0x0035 -> DIGIT FIVE + '6' # 0x0036 -> DIGIT SIX + '7' # 0x0037 -> DIGIT SEVEN + '8' # 0x0038 -> DIGIT EIGHT + '9' # 0x0039 -> DIGIT NINE + ':' # 0x003a -> COLON + ';' # 0x003b -> SEMICOLON + '<' # 0x003c -> LESS-THAN SIGN + '=' # 0x003d -> EQUALS SIGN + '>' # 0x003e -> GREATER-THAN SIGN + '?' # 0x003f -> QUESTION MARK + '@' # 0x0040 -> COMMERCIAL AT + 'A' # 0x0041 -> LATIN CAPITAL LETTER A + 'B' # 0x0042 -> LATIN CAPITAL LETTER B + 'C' # 0x0043 -> LATIN CAPITAL LETTER C + 'D' # 0x0044 -> LATIN CAPITAL LETTER D + 'E' # 0x0045 -> LATIN CAPITAL LETTER E + 'F' # 0x0046 -> LATIN CAPITAL LETTER F + 'G' # 0x0047 -> LATIN CAPITAL LETTER G + 'H' # 0x0048 -> LATIN CAPITAL LETTER H + 'I' # 0x0049 -> LATIN CAPITAL LETTER I + 'J' # 0x004a -> LATIN CAPITAL LETTER J + 'K' # 0x004b -> LATIN CAPITAL LETTER K + 'L' # 0x004c -> LATIN CAPITAL LETTER L + 'M' # 0x004d -> LATIN CAPITAL LETTER M + 'N' # 0x004e -> LATIN CAPITAL LETTER N + 'O' # 0x004f -> LATIN CAPITAL LETTER O + 'P' # 0x0050 -> LATIN CAPITAL LETTER P + 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q + 'R' # 0x0052 -> LATIN CAPITAL LETTER R + 'S' # 0x0053 -> LATIN CAPITAL LETTER S + 'T' # 0x0054 -> LATIN CAPITAL LETTER T + 'U' # 0x0055 -> LATIN CAPITAL LETTER U + 'V' # 0x0056 -> LATIN CAPITAL LETTER V + 'W' # 0x0057 -> LATIN CAPITAL LETTER W + 'X' # 0x0058 -> LATIN CAPITAL LETTER X + 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y + 'Z' # 0x005a -> LATIN CAPITAL LETTER Z + '[' # 0x005b -> LEFT SQUARE BRACKET + '\\' # 0x005c -> REVERSE SOLIDUS + ']' # 0x005d -> RIGHT SQUARE BRACKET + '^' # 0x005e -> CIRCUMFLEX ACCENT + '_' # 0x005f -> LOW LINE + '`' # 0x0060 -> GRAVE ACCENT + 'a' # 0x0061 -> LATIN SMALL LETTER A + 'b' # 0x0062 -> LATIN SMALL LETTER B + 'c' # 0x0063 -> LATIN SMALL LETTER C + 'd' # 0x0064 -> LATIN SMALL LETTER D + 'e' # 0x0065 -> LATIN SMALL LETTER E + 'f' # 0x0066 -> LATIN SMALL LETTER F + 'g' # 0x0067 -> LATIN SMALL LETTER G + 'h' # 0x0068 -> LATIN SMALL LETTER H + 'i' # 0x0069 -> LATIN SMALL LETTER I + 'j' # 0x006a -> LATIN SMALL LETTER J + 'k' # 0x006b -> LATIN SMALL LETTER K + 'l' # 0x006c -> LATIN SMALL LETTER L + 'm' # 0x006d -> LATIN SMALL LETTER M + 'n' # 0x006e -> LATIN SMALL LETTER N + 'o' # 0x006f -> LATIN SMALL LETTER O + 'p' # 0x0070 -> LATIN SMALL LETTER P + 'q' # 0x0071 -> LATIN SMALL LETTER Q + 'r' # 0x0072 -> LATIN SMALL LETTER R + 's' # 0x0073 -> LATIN SMALL LETTER S + 't' # 0x0074 -> LATIN SMALL LETTER T + 'u' # 0x0075 -> LATIN SMALL LETTER U + 'v' # 0x0076 -> LATIN SMALL LETTER V + 'w' # 0x0077 -> LATIN SMALL LETTER W + 'x' # 0x0078 -> LATIN SMALL LETTER X + 'y' # 0x0079 -> LATIN SMALL LETTER Y + 'z' # 0x007a -> LATIN SMALL LETTER Z + '{' # 0x007b -> LEFT CURLY BRACKET + '|' # 0x007c -> VERTICAL LINE + '}' # 0x007d -> RIGHT CURLY BRACKET + '~' # 0x007e -> TILDE + '\x7f' # 0x007f -> DELETE + '\u0452' # 0x0080 -> CYRILLIC SMALL LETTER DJE + '\u0402' # 0x0081 -> CYRILLIC CAPITAL LETTER DJE + '\u0453' # 0x0082 -> CYRILLIC SMALL LETTER GJE + '\u0403' # 0x0083 -> CYRILLIC CAPITAL LETTER GJE + '\u0451' # 0x0084 -> CYRILLIC SMALL LETTER IO + '\u0401' # 0x0085 -> CYRILLIC CAPITAL LETTER IO + '\u0454' # 0x0086 -> CYRILLIC SMALL LETTER UKRAINIAN IE + '\u0404' # 0x0087 -> CYRILLIC CAPITAL LETTER UKRAINIAN IE + '\u0455' # 0x0088 -> CYRILLIC SMALL LETTER DZE + '\u0405' # 0x0089 -> CYRILLIC CAPITAL LETTER DZE + '\u0456' # 0x008a -> CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + '\u0406' # 0x008b -> CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I + '\u0457' # 0x008c -> CYRILLIC SMALL LETTER YI + '\u0407' # 0x008d -> CYRILLIC CAPITAL LETTER YI + '\u0458' # 0x008e -> CYRILLIC SMALL LETTER JE + '\u0408' # 0x008f -> CYRILLIC CAPITAL LETTER JE + '\u0459' # 0x0090 -> CYRILLIC SMALL LETTER LJE + '\u0409' # 0x0091 -> CYRILLIC CAPITAL LETTER LJE + '\u045a' # 0x0092 -> CYRILLIC SMALL LETTER NJE + '\u040a' # 0x0093 -> CYRILLIC CAPITAL LETTER NJE + '\u045b' # 0x0094 -> CYRILLIC SMALL LETTER TSHE + '\u040b' # 0x0095 -> CYRILLIC CAPITAL LETTER TSHE + '\u045c' # 0x0096 -> CYRILLIC SMALL LETTER KJE + '\u040c' # 0x0097 -> CYRILLIC CAPITAL LETTER KJE + '\u045e' # 0x0098 -> CYRILLIC SMALL LETTER SHORT U + '\u040e' # 0x0099 -> CYRILLIC CAPITAL LETTER SHORT U + '\u045f' # 0x009a -> CYRILLIC SMALL LETTER DZHE + '\u040f' # 0x009b -> CYRILLIC CAPITAL LETTER DZHE + '\u044e' # 0x009c -> CYRILLIC SMALL LETTER YU + '\u042e' # 0x009d -> CYRILLIC CAPITAL LETTER YU + '\u044a' # 0x009e -> CYRILLIC SMALL LETTER HARD SIGN + '\u042a' # 0x009f -> CYRILLIC CAPITAL LETTER HARD SIGN + '\u0430' # 0x00a0 -> CYRILLIC SMALL LETTER A + '\u0410' # 0x00a1 -> CYRILLIC CAPITAL LETTER A + '\u0431' # 0x00a2 -> CYRILLIC SMALL LETTER BE + '\u0411' # 0x00a3 -> CYRILLIC CAPITAL LETTER BE + '\u0446' # 0x00a4 -> CYRILLIC SMALL LETTER TSE + '\u0426' # 0x00a5 -> CYRILLIC CAPITAL LETTER TSE + '\u0434' # 0x00a6 -> CYRILLIC SMALL LETTER DE + '\u0414' # 0x00a7 -> CYRILLIC CAPITAL LETTER DE + '\u0435' # 0x00a8 -> CYRILLIC SMALL LETTER IE + '\u0415' # 0x00a9 -> CYRILLIC CAPITAL LETTER IE + '\u0444' # 0x00aa -> CYRILLIC SMALL LETTER EF + '\u0424' # 0x00ab -> CYRILLIC CAPITAL LETTER EF + '\u0433' # 0x00ac -> CYRILLIC SMALL LETTER GHE + '\u0413' # 0x00ad -> CYRILLIC CAPITAL LETTER GHE + '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + '\u2591' # 0x00b0 -> LIGHT SHADE + '\u2592' # 0x00b1 -> MEDIUM SHADE + '\u2593' # 0x00b2 -> DARK SHADE + '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL + '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT + '\u0445' # 0x00b5 -> CYRILLIC SMALL LETTER HA + '\u0425' # 0x00b6 -> CYRILLIC CAPITAL LETTER HA + '\u0438' # 0x00b7 -> CYRILLIC SMALL LETTER I + '\u0418' # 0x00b8 -> CYRILLIC CAPITAL LETTER I + '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT + '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL + '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT + '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT + '\u0439' # 0x00bd -> CYRILLIC SMALL LETTER SHORT I + '\u0419' # 0x00be -> CYRILLIC CAPITAL LETTER SHORT I + '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT + '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT + '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL + '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT + '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL + '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + '\u043a' # 0x00c6 -> CYRILLIC SMALL LETTER KA + '\u041a' # 0x00c7 -> CYRILLIC CAPITAL LETTER KA + '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT + '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT + '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL + '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL + '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + '\xa4' # 0x00cf -> CURRENCY SIGN + '\u043b' # 0x00d0 -> CYRILLIC SMALL LETTER EL + '\u041b' # 0x00d1 -> CYRILLIC CAPITAL LETTER EL + '\u043c' # 0x00d2 -> CYRILLIC SMALL LETTER EM + '\u041c' # 0x00d3 -> CYRILLIC CAPITAL LETTER EM + '\u043d' # 0x00d4 -> CYRILLIC SMALL LETTER EN + '\u041d' # 0x00d5 -> CYRILLIC CAPITAL LETTER EN + '\u043e' # 0x00d6 -> CYRILLIC SMALL LETTER O + '\u041e' # 0x00d7 -> CYRILLIC CAPITAL LETTER O + '\u043f' # 0x00d8 -> CYRILLIC SMALL LETTER PE + '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT + '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT + '\u2588' # 0x00db -> FULL BLOCK + '\u2584' # 0x00dc -> LOWER HALF BLOCK + '\u041f' # 0x00dd -> CYRILLIC CAPITAL LETTER PE + '\u044f' # 0x00de -> CYRILLIC SMALL LETTER YA + '\u2580' # 0x00df -> UPPER HALF BLOCK + '\u042f' # 0x00e0 -> CYRILLIC CAPITAL LETTER YA + '\u0440' # 0x00e1 -> CYRILLIC SMALL LETTER ER + '\u0420' # 0x00e2 -> CYRILLIC CAPITAL LETTER ER + '\u0441' # 0x00e3 -> CYRILLIC SMALL LETTER ES + '\u0421' # 0x00e4 -> CYRILLIC CAPITAL LETTER ES + '\u0442' # 0x00e5 -> CYRILLIC SMALL LETTER TE + '\u0422' # 0x00e6 -> CYRILLIC CAPITAL LETTER TE + '\u0443' # 0x00e7 -> CYRILLIC SMALL LETTER U + '\u0423' # 0x00e8 -> CYRILLIC CAPITAL LETTER U + '\u0436' # 0x00e9 -> CYRILLIC SMALL LETTER ZHE + '\u0416' # 0x00ea -> CYRILLIC CAPITAL LETTER ZHE + '\u0432' # 0x00eb -> CYRILLIC SMALL LETTER VE + '\u0412' # 0x00ec -> CYRILLIC CAPITAL LETTER VE + '\u044c' # 0x00ed -> CYRILLIC SMALL LETTER SOFT SIGN + '\u042c' # 0x00ee -> CYRILLIC CAPITAL LETTER SOFT SIGN + '\u2116' # 0x00ef -> NUMERO SIGN + '\xad' # 0x00f0 -> SOFT HYPHEN + '\u044b' # 0x00f1 -> CYRILLIC SMALL LETTER YERU + '\u042b' # 0x00f2 -> CYRILLIC CAPITAL LETTER YERU + '\u0437' # 0x00f3 -> CYRILLIC SMALL LETTER ZE + '\u0417' # 0x00f4 -> CYRILLIC CAPITAL LETTER ZE + '\u0448' # 0x00f5 -> CYRILLIC SMALL LETTER SHA + '\u0428' # 0x00f6 -> CYRILLIC CAPITAL LETTER SHA + '\u044d' # 0x00f7 -> CYRILLIC SMALL LETTER E + '\u042d' # 0x00f8 -> CYRILLIC CAPITAL LETTER E + '\u0449' # 0x00f9 -> CYRILLIC SMALL LETTER SHCHA + '\u0429' # 0x00fa -> CYRILLIC CAPITAL LETTER SHCHA + '\u0447' # 0x00fb -> CYRILLIC SMALL LETTER CHE + '\u0427' # 0x00fc -> CYRILLIC CAPITAL LETTER CHE + '\xa7' # 0x00fd -> SECTION SIGN + '\u25a0' # 0x00fe -> BLACK SQUARE + '\xa0' # 0x00ff -> NO-BREAK SPACE +) + +### Encoding Map + +encoding_map = { + 0x0000: 0x0000, # NULL + 0x0001: 0x0001, # START OF HEADING + 0x0002: 0x0002, # START OF TEXT + 0x0003: 0x0003, # END OF TEXT + 0x0004: 0x0004, # END OF TRANSMISSION + 0x0005: 0x0005, # ENQUIRY + 0x0006: 0x0006, # ACKNOWLEDGE + 0x0007: 0x0007, # BELL + 0x0008: 0x0008, # BACKSPACE + 0x0009: 0x0009, # HORIZONTAL TABULATION + 0x000a: 0x000a, # LINE FEED + 0x000b: 0x000b, # VERTICAL TABULATION + 0x000c: 0x000c, # FORM FEED + 0x000d: 0x000d, # CARRIAGE RETURN + 0x000e: 0x000e, # SHIFT OUT + 0x000f: 0x000f, # SHIFT IN + 0x0010: 0x0010, # DATA LINK ESCAPE + 0x0011: 0x0011, # DEVICE CONTROL ONE + 0x0012: 0x0012, # DEVICE CONTROL TWO + 0x0013: 0x0013, # DEVICE CONTROL THREE + 0x0014: 0x0014, # DEVICE CONTROL FOUR + 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE + 0x0016: 0x0016, # SYNCHRONOUS IDLE + 0x0017: 0x0017, # END OF TRANSMISSION BLOCK + 0x0018: 0x0018, # CANCEL + 0x0019: 0x0019, # END OF MEDIUM + 0x001a: 0x001a, # SUBSTITUTE + 0x001b: 0x001b, # ESCAPE + 0x001c: 0x001c, # FILE SEPARATOR + 0x001d: 0x001d, # GROUP SEPARATOR + 0x001e: 0x001e, # RECORD SEPARATOR + 0x001f: 0x001f, # UNIT SEPARATOR + 0x0020: 0x0020, # SPACE + 0x0021: 0x0021, # EXCLAMATION MARK + 0x0022: 0x0022, # QUOTATION MARK + 0x0023: 0x0023, # NUMBER SIGN + 0x0024: 0x0024, # DOLLAR SIGN + 0x0025: 0x0025, # PERCENT SIGN + 0x0026: 0x0026, # AMPERSAND + 0x0027: 0x0027, # APOSTROPHE + 0x0028: 0x0028, # LEFT PARENTHESIS + 0x0029: 0x0029, # RIGHT PARENTHESIS + 0x002a: 0x002a, # ASTERISK + 0x002b: 0x002b, # PLUS SIGN + 0x002c: 0x002c, # COMMA + 0x002d: 0x002d, # HYPHEN-MINUS + 0x002e: 0x002e, # FULL STOP + 0x002f: 0x002f, # SOLIDUS + 0x0030: 0x0030, # DIGIT ZERO + 0x0031: 0x0031, # DIGIT ONE + 0x0032: 0x0032, # DIGIT TWO + 0x0033: 0x0033, # DIGIT THREE + 0x0034: 0x0034, # DIGIT FOUR + 0x0035: 0x0035, # DIGIT FIVE + 0x0036: 0x0036, # DIGIT SIX + 0x0037: 0x0037, # DIGIT SEVEN + 0x0038: 0x0038, # DIGIT EIGHT + 0x0039: 0x0039, # DIGIT NINE + 0x003a: 0x003a, # COLON + 0x003b: 0x003b, # SEMICOLON + 0x003c: 0x003c, # LESS-THAN SIGN + 0x003d: 0x003d, # EQUALS SIGN + 0x003e: 0x003e, # GREATER-THAN SIGN + 0x003f: 0x003f, # QUESTION MARK + 0x0040: 0x0040, # COMMERCIAL AT + 0x0041: 0x0041, # LATIN CAPITAL LETTER A + 0x0042: 0x0042, # LATIN CAPITAL LETTER B + 0x0043: 0x0043, # LATIN CAPITAL LETTER C + 0x0044: 0x0044, # LATIN CAPITAL LETTER D + 0x0045: 0x0045, # LATIN CAPITAL LETTER E + 0x0046: 0x0046, # LATIN CAPITAL LETTER F + 0x0047: 0x0047, # LATIN CAPITAL LETTER G + 0x0048: 0x0048, # LATIN CAPITAL LETTER H + 0x0049: 0x0049, # LATIN CAPITAL LETTER I + 0x004a: 0x004a, # LATIN CAPITAL LETTER J + 0x004b: 0x004b, # LATIN CAPITAL LETTER K + 0x004c: 0x004c, # LATIN CAPITAL LETTER L + 0x004d: 0x004d, # LATIN CAPITAL LETTER M + 0x004e: 0x004e, # LATIN CAPITAL LETTER N + 0x004f: 0x004f, # LATIN CAPITAL LETTER O + 0x0050: 0x0050, # LATIN CAPITAL LETTER P + 0x0051: 0x0051, # LATIN CAPITAL LETTER Q + 0x0052: 0x0052, # LATIN CAPITAL LETTER R + 0x0053: 0x0053, # LATIN CAPITAL LETTER S + 0x0054: 0x0054, # LATIN CAPITAL LETTER T + 0x0055: 0x0055, # LATIN CAPITAL LETTER U + 0x0056: 0x0056, # LATIN CAPITAL LETTER V + 0x0057: 0x0057, # LATIN CAPITAL LETTER W + 0x0058: 0x0058, # LATIN CAPITAL LETTER X + 0x0059: 0x0059, # LATIN CAPITAL LETTER Y + 0x005a: 0x005a, # LATIN CAPITAL LETTER Z + 0x005b: 0x005b, # LEFT SQUARE BRACKET + 0x005c: 0x005c, # REVERSE SOLIDUS + 0x005d: 0x005d, # RIGHT SQUARE BRACKET + 0x005e: 0x005e, # CIRCUMFLEX ACCENT + 0x005f: 0x005f, # LOW LINE + 0x0060: 0x0060, # GRAVE ACCENT + 0x0061: 0x0061, # LATIN SMALL LETTER A + 0x0062: 0x0062, # LATIN SMALL LETTER B + 0x0063: 0x0063, # LATIN SMALL LETTER C + 0x0064: 0x0064, # LATIN SMALL LETTER D + 0x0065: 0x0065, # LATIN SMALL LETTER E + 0x0066: 0x0066, # LATIN SMALL LETTER F + 0x0067: 0x0067, # LATIN SMALL LETTER G + 0x0068: 0x0068, # LATIN SMALL LETTER H + 0x0069: 0x0069, # LATIN SMALL LETTER I + 0x006a: 0x006a, # LATIN SMALL LETTER J + 0x006b: 0x006b, # LATIN SMALL LETTER K + 0x006c: 0x006c, # LATIN SMALL LETTER L + 0x006d: 0x006d, # LATIN SMALL LETTER M + 0x006e: 0x006e, # LATIN SMALL LETTER N + 0x006f: 0x006f, # LATIN SMALL LETTER O + 0x0070: 0x0070, # LATIN SMALL LETTER P + 0x0071: 0x0071, # LATIN SMALL LETTER Q + 0x0072: 0x0072, # LATIN SMALL LETTER R + 0x0073: 0x0073, # LATIN SMALL LETTER S + 0x0074: 0x0074, # LATIN SMALL LETTER T + 0x0075: 0x0075, # LATIN SMALL LETTER U + 0x0076: 0x0076, # LATIN SMALL LETTER V + 0x0077: 0x0077, # LATIN SMALL LETTER W + 0x0078: 0x0078, # LATIN SMALL LETTER X + 0x0079: 0x0079, # LATIN SMALL LETTER Y + 0x007a: 0x007a, # LATIN SMALL LETTER Z + 0x007b: 0x007b, # LEFT CURLY BRACKET + 0x007c: 0x007c, # VERTICAL LINE + 0x007d: 0x007d, # RIGHT CURLY BRACKET + 0x007e: 0x007e, # TILDE + 0x007f: 0x007f, # DELETE + 0x00a0: 0x00ff, # NO-BREAK SPACE + 0x00a4: 0x00cf, # CURRENCY SIGN + 0x00a7: 0x00fd, # SECTION SIGN + 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00ad: 0x00f0, # SOFT HYPHEN + 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x0401: 0x0085, # CYRILLIC CAPITAL LETTER IO + 0x0402: 0x0081, # CYRILLIC CAPITAL LETTER DJE + 0x0403: 0x0083, # CYRILLIC CAPITAL LETTER GJE + 0x0404: 0x0087, # CYRILLIC CAPITAL LETTER UKRAINIAN IE + 0x0405: 0x0089, # CYRILLIC CAPITAL LETTER DZE + 0x0406: 0x008b, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I + 0x0407: 0x008d, # CYRILLIC CAPITAL LETTER YI + 0x0408: 0x008f, # CYRILLIC CAPITAL LETTER JE + 0x0409: 0x0091, # CYRILLIC CAPITAL LETTER LJE + 0x040a: 0x0093, # CYRILLIC CAPITAL LETTER NJE + 0x040b: 0x0095, # CYRILLIC CAPITAL LETTER TSHE + 0x040c: 0x0097, # CYRILLIC CAPITAL LETTER KJE + 0x040e: 0x0099, # CYRILLIC CAPITAL LETTER SHORT U + 0x040f: 0x009b, # CYRILLIC CAPITAL LETTER DZHE + 0x0410: 0x00a1, # CYRILLIC CAPITAL LETTER A + 0x0411: 0x00a3, # CYRILLIC CAPITAL LETTER BE + 0x0412: 0x00ec, # CYRILLIC CAPITAL LETTER VE + 0x0413: 0x00ad, # CYRILLIC CAPITAL LETTER GHE + 0x0414: 0x00a7, # CYRILLIC CAPITAL LETTER DE + 0x0415: 0x00a9, # CYRILLIC CAPITAL LETTER IE + 0x0416: 0x00ea, # CYRILLIC CAPITAL LETTER ZHE + 0x0417: 0x00f4, # CYRILLIC CAPITAL LETTER ZE + 0x0418: 0x00b8, # CYRILLIC CAPITAL LETTER I + 0x0419: 0x00be, # CYRILLIC CAPITAL LETTER SHORT I + 0x041a: 0x00c7, # CYRILLIC CAPITAL LETTER KA + 0x041b: 0x00d1, # CYRILLIC CAPITAL LETTER EL + 0x041c: 0x00d3, # CYRILLIC CAPITAL LETTER EM + 0x041d: 0x00d5, # CYRILLIC CAPITAL LETTER EN + 0x041e: 0x00d7, # CYRILLIC CAPITAL LETTER O + 0x041f: 0x00dd, # CYRILLIC CAPITAL LETTER PE + 0x0420: 0x00e2, # CYRILLIC CAPITAL LETTER ER + 0x0421: 0x00e4, # CYRILLIC CAPITAL LETTER ES + 0x0422: 0x00e6, # CYRILLIC CAPITAL LETTER TE + 0x0423: 0x00e8, # CYRILLIC CAPITAL LETTER U + 0x0424: 0x00ab, # CYRILLIC CAPITAL LETTER EF + 0x0425: 0x00b6, # CYRILLIC CAPITAL LETTER HA + 0x0426: 0x00a5, # CYRILLIC CAPITAL LETTER TSE + 0x0427: 0x00fc, # CYRILLIC CAPITAL LETTER CHE + 0x0428: 0x00f6, # CYRILLIC CAPITAL LETTER SHA + 0x0429: 0x00fa, # CYRILLIC CAPITAL LETTER SHCHA + 0x042a: 0x009f, # CYRILLIC CAPITAL LETTER HARD SIGN + 0x042b: 0x00f2, # CYRILLIC CAPITAL LETTER YERU + 0x042c: 0x00ee, # CYRILLIC CAPITAL LETTER SOFT SIGN + 0x042d: 0x00f8, # CYRILLIC CAPITAL LETTER E + 0x042e: 0x009d, # CYRILLIC CAPITAL LETTER YU + 0x042f: 0x00e0, # CYRILLIC CAPITAL LETTER YA + 0x0430: 0x00a0, # CYRILLIC SMALL LETTER A + 0x0431: 0x00a2, # CYRILLIC SMALL LETTER BE + 0x0432: 0x00eb, # CYRILLIC SMALL LETTER VE + 0x0433: 0x00ac, # CYRILLIC SMALL LETTER GHE + 0x0434: 0x00a6, # CYRILLIC SMALL LETTER DE + 0x0435: 0x00a8, # CYRILLIC SMALL LETTER IE + 0x0436: 0x00e9, # CYRILLIC SMALL LETTER ZHE + 0x0437: 0x00f3, # CYRILLIC SMALL LETTER ZE + 0x0438: 0x00b7, # CYRILLIC SMALL LETTER I + 0x0439: 0x00bd, # CYRILLIC SMALL LETTER SHORT I + 0x043a: 0x00c6, # CYRILLIC SMALL LETTER KA + 0x043b: 0x00d0, # CYRILLIC SMALL LETTER EL + 0x043c: 0x00d2, # CYRILLIC SMALL LETTER EM + 0x043d: 0x00d4, # CYRILLIC SMALL LETTER EN + 0x043e: 0x00d6, # CYRILLIC SMALL LETTER O + 0x043f: 0x00d8, # CYRILLIC SMALL LETTER PE + 0x0440: 0x00e1, # CYRILLIC SMALL LETTER ER + 0x0441: 0x00e3, # CYRILLIC SMALL LETTER ES + 0x0442: 0x00e5, # CYRILLIC SMALL LETTER TE + 0x0443: 0x00e7, # CYRILLIC SMALL LETTER U + 0x0444: 0x00aa, # CYRILLIC SMALL LETTER EF + 0x0445: 0x00b5, # CYRILLIC SMALL LETTER HA + 0x0446: 0x00a4, # CYRILLIC SMALL LETTER TSE + 0x0447: 0x00fb, # CYRILLIC SMALL LETTER CHE + 0x0448: 0x00f5, # CYRILLIC SMALL LETTER SHA + 0x0449: 0x00f9, # CYRILLIC SMALL LETTER SHCHA + 0x044a: 0x009e, # CYRILLIC SMALL LETTER HARD SIGN + 0x044b: 0x00f1, # CYRILLIC SMALL LETTER YERU + 0x044c: 0x00ed, # CYRILLIC SMALL LETTER SOFT SIGN + 0x044d: 0x00f7, # CYRILLIC SMALL LETTER E + 0x044e: 0x009c, # CYRILLIC SMALL LETTER YU + 0x044f: 0x00de, # CYRILLIC SMALL LETTER YA + 0x0451: 0x0084, # CYRILLIC SMALL LETTER IO + 0x0452: 0x0080, # CYRILLIC SMALL LETTER DJE + 0x0453: 0x0082, # CYRILLIC SMALL LETTER GJE + 0x0454: 0x0086, # CYRILLIC SMALL LETTER UKRAINIAN IE + 0x0455: 0x0088, # CYRILLIC SMALL LETTER DZE + 0x0456: 0x008a, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I + 0x0457: 0x008c, # CYRILLIC SMALL LETTER YI + 0x0458: 0x008e, # CYRILLIC SMALL LETTER JE + 0x0459: 0x0090, # CYRILLIC SMALL LETTER LJE + 0x045a: 0x0092, # CYRILLIC SMALL LETTER NJE + 0x045b: 0x0094, # CYRILLIC SMALL LETTER TSHE + 0x045c: 0x0096, # CYRILLIC SMALL LETTER KJE + 0x045e: 0x0098, # CYRILLIC SMALL LETTER SHORT U + 0x045f: 0x009a, # CYRILLIC SMALL LETTER DZHE + 0x2116: 0x00ef, # NUMERO SIGN + 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL + 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL + 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT + 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT + 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT + 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL + 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL + 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT + 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT + 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT + 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT + 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT + 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL + 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + 0x2580: 0x00df, # UPPER HALF BLOCK + 0x2584: 0x00dc, # LOWER HALF BLOCK + 0x2588: 0x00db, # FULL BLOCK + 0x2591: 0x00b0, # LIGHT SHADE + 0x2592: 0x00b1, # MEDIUM SHADE + 0x2593: 0x00b2, # DARK SHADE + 0x25a0: 0x00fe, # BLACK SQUARE +} diff --git a/shared/package-files/7b/7b2968e5c90f955940cfd8ff50601f2464e99cdb276f381c5c3e9d643fe59092/blob b/shared/package-files/7b/7b2968e5c90f955940cfd8ff50601f2464e99cdb276f381c5c3e9d643fe59092/blob new file mode 100644 index 0000000000000000000000000000000000000000..0ab2828dc2ffbb38a1f85e19ade6cfd431b3b6bb --- /dev/null +++ b/shared/package-files/7b/7b2968e5c90f955940cfd8ff50601f2464e99cdb276f381c5c3e9d643fe59092/blob @@ -0,0 +1,183 @@ +# coding: utf-8 + +from _ruamel_yaml import CParser, CEmitter # type: ignore + +from ruamel.yaml.constructor import Constructor, BaseConstructor, SafeConstructor +from ruamel.yaml.representer import Representer, SafeRepresenter, BaseRepresenter +from ruamel.yaml.resolver import Resolver, BaseResolver + +if False: # MYPY + from typing import Any, Union, Optional # NOQA + from ruamel.yaml.compat import StreamTextType, StreamType, VersionType # NOQA + +__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader', 'CBaseDumper', 'CSafeDumper', 'CDumper'] + + +# this includes some hacks to solve the usage of resolver by lower level +# parts of the parser + + +class CBaseLoader(CParser, BaseConstructor, BaseResolver): # type: ignore + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + CParser.__init__(self, stream) + self._parser = self._composer = self + BaseConstructor.__init__(self, loader=self) + BaseResolver.__init__(self, loadumper=self) + # self.descend_resolver = self._resolver.descend_resolver + # self.ascend_resolver = self._resolver.ascend_resolver + # self.resolve = self._resolver.resolve + + +class CSafeLoader(CParser, SafeConstructor, Resolver): # type: ignore + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + CParser.__init__(self, stream) + self._parser = self._composer = self + SafeConstructor.__init__(self, loader=self) + Resolver.__init__(self, loadumper=self) + # self.descend_resolver = self._resolver.descend_resolver + # self.ascend_resolver = self._resolver.ascend_resolver + # self.resolve = self._resolver.resolve + + +class CLoader(CParser, Constructor, Resolver): # type: ignore + def __init__(self, stream, version=None, preserve_quotes=None): + # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None + CParser.__init__(self, stream) + self._parser = self._composer = self + Constructor.__init__(self, loader=self) + Resolver.__init__(self, loadumper=self) + # self.descend_resolver = self._resolver.descend_resolver + # self.ascend_resolver = self._resolver.ascend_resolver + # self.resolve = self._resolver.resolve + + +class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): # type: ignore + def __init__( + self, + stream, + default_style=None, + default_flow_style=None, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=None, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, + ): + # type: (StreamType, Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None # NOQA + CEmitter.__init__( + self, + stream, + canonical=canonical, + indent=indent, + width=width, + encoding=encoding, + allow_unicode=allow_unicode, + line_break=line_break, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + tags=tags, + ) + self._emitter = self._serializer = self._representer = self + BaseRepresenter.__init__( + self, + default_style=default_style, + default_flow_style=default_flow_style, + dumper=self, + ) + BaseResolver.__init__(self, loadumper=self) + + +class CSafeDumper(CEmitter, SafeRepresenter, Resolver): # type: ignore + def __init__( + self, + stream, + default_style=None, + default_flow_style=None, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=None, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, + ): + # type: (StreamType, Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None # NOQA + self._emitter = self._serializer = self._representer = self + CEmitter.__init__( + self, + stream, + canonical=canonical, + indent=indent, + width=width, + encoding=encoding, + allow_unicode=allow_unicode, + line_break=line_break, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + tags=tags, + ) + self._emitter = self._serializer = self._representer = self + SafeRepresenter.__init__( + self, default_style=default_style, default_flow_style=default_flow_style + ) + Resolver.__init__(self) + + +class CDumper(CEmitter, Representer, Resolver): # type: ignore + def __init__( + self, + stream, + default_style=None, + default_flow_style=None, + canonical=None, + indent=None, + width=None, + allow_unicode=None, + line_break=None, + encoding=None, + explicit_start=None, + explicit_end=None, + version=None, + tags=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, + ): + # type: (StreamType, Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None # NOQA + CEmitter.__init__( + self, + stream, + canonical=canonical, + indent=indent, + width=width, + encoding=encoding, + allow_unicode=allow_unicode, + line_break=line_break, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + tags=tags, + ) + self._emitter = self._serializer = self._representer = self + Representer.__init__( + self, default_style=default_style, default_flow_style=default_flow_style + ) + Resolver.__init__(self) diff --git a/shared/package-files/7b/7b2d3852e9d9a74b13cfd852b138456368a3533ad9711a82e99d2a4454af30a2/blob b/shared/package-files/7b/7b2d3852e9d9a74b13cfd852b138456368a3533ad9711a82e99d2a4454af30a2/blob new file mode 100644 index 0000000000000000000000000000000000000000..7096b36f26de50d456794f16eff7e6171bb3853b --- /dev/null +++ b/shared/package-files/7b/7b2d3852e9d9a74b13cfd852b138456368a3533ad9711a82e99d2a4454af30a2/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b2d3852e9d9a74b13cfd852b138456368a3533ad9711a82e99d2a4454af30a2 +size 456536 diff --git a/shared/package-files/7b/7b30576a6ec266ee385da00ebe01492db644744a106bc1e1929ffa8623b5b6fe/blob b/shared/package-files/7b/7b30576a6ec266ee385da00ebe01492db644744a106bc1e1929ffa8623b5b6fe/blob new file mode 100644 index 0000000000000000000000000000000000000000..3707cf7fdc8adede0719fa9b8ac490a1c8fe10bb --- /dev/null +++ b/shared/package-files/7b/7b30576a6ec266ee385da00ebe01492db644744a106bc1e1929ffa8623b5b6fe/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _cholesky_solve_helper { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cholesky_solve_helper") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cholesky_solve_helper(Tensor self, Tensor A, bool upper) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & A, bool upper); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & A, bool upper); +}; + +struct TORCH_API _cholesky_solve_helper_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cholesky_solve_helper") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cholesky_solve_helper.out(Tensor self, Tensor A, bool upper, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & A, bool upper, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & A, bool upper, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7b/7b30b10441b317fd16c34e4025b7ebdb58b18ecf836b7ebd07841926daf1ed59/blob b/shared/package-files/7b/7b30b10441b317fd16c34e4025b7ebdb58b18ecf836b7ebd07841926daf1ed59/blob new file mode 100644 index 0000000000000000000000000000000000000000..a29c3b34f11c316dfee4fa65856177575511aee1 --- /dev/null +++ b/shared/package-files/7b/7b30b10441b317fd16c34e4025b7ebdb58b18ecf836b7ebd07841926daf1ed59/blob @@ -0,0 +1,422 @@ +""" + +TestGMMMultTwostepDefault() has lower precision + +""" +from statsmodels.compat.python import lmap + +from pathlib import Path + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pandas as pd +import pytest +from scipy import stats + +from statsmodels.regression.linear_model import OLS +from statsmodels.sandbox.regression import gmm + + +def get_data(): + import os + + curdir = os.path.split(__file__)[0] + dt = pd.read_csv(Path(curdir).joinpath("racd10data_with_transformed.csv")) + + # Transformations compared to original data + # dt3['income'] /= 10. + # dt3['aget'] = (dt3['age'] - dt3['age'].min()) / 5. + # dt3['aget2'] = dt3['aget']**2 + + # How do we do this with pandas + mask = ~((np.asarray(dt["private"]) == 1) & (dt["medicaid"] == 1)) + mask = mask & (dt["docvis"] <= 70) + dt3 = dt[mask] + dt3["const"] = 1 # add constant + return dt3 + + +DATA = get_data() + +# ------------- moment conditions for example + + +def moment_exponential_add(params, exog, exp=True): + + if not np.isfinite(params).all(): + print("invalid params", params) + + # moment condition without instrument + if exp: + predicted = np.exp(np.dot(exog, params)) + # if not np.isfinite(predicted).all(): + # print "invalid predicted", predicted + # raise RuntimeError('invalid predicted') + predicted = np.clip(predicted, 0, 1e100) # try to avoid inf + else: + predicted = np.dot(exog, params) + + return predicted + + +def moment_exponential_mult(params, data, exp=True): + # multiplicative error model + + endog = data[:, 0] + exog = data[:, 1:] + + if not np.isfinite(params).all(): + print("invalid params", params) + + # moment condition without instrument + if exp: + predicted = np.exp(np.dot(exog, params)) + predicted = np.clip(predicted, 0, 1e100) # avoid inf + resid = endog / predicted - 1 + if not np.isfinite(resid).all(): + print("invalid resid", resid) + + else: + resid = endog - np.dot(exog, params) + + return resid + + +# ------------------- test classes + + +# copied from test_gmm.py, with changes +class CheckGMM: + + # default tolerance, overwritten by subclasses + params_tol = [5e-6, 5e-6] + bse_tol = [5e-7, 5e-7] + q_tol = [5e-6, 1e-9] + j_tol = [5e-5, 1e-9] + + def test_basic(self): + res1, res2 = self.res1, self.res2 + # test both absolute and relative difference + rtol, atol = self.params_tol + assert_allclose(res1.params, res2.params, rtol=rtol, atol=0) + assert_allclose(res1.params, res2.params, rtol=0, atol=atol) + + rtol, atol = self.bse_tol + assert_allclose(res1.bse, res2.bse, rtol=rtol, atol=0) + assert_allclose(res1.bse, res2.bse, rtol=0, atol=atol) + + def test_other(self): + res1, res2 = self.res1, self.res2 + rtol, atol = self.q_tol + assert_allclose(res1.q, res2.Q, rtol=atol, atol=rtol) + rtol, atol = self.j_tol + assert_allclose(res1.jval, res2.J, rtol=atol, atol=rtol) + + j, jpval, jdf = res1.jtest() + # j and jval should be the same + assert_allclose(res1.jval, res2.J, rtol=13, atol=13) + # pvalue is not saved in Stata results + pval = stats.chi2.sf(res2.J, res2.J_df) + # assert_allclose(jpval, pval, rtol=1e-4, atol=1e-6) + assert_allclose(jpval, pval, rtol=rtol, atol=atol) + assert_equal(jdf, res2.J_df) + + @pytest.mark.smoke + def test_summary(self): + res1 = self.res1 + summ = res1.summary() + assert_equal(len(summ.tables[1]), len(res1.params) + 1) + + +class TestGMMAddOnestep(CheckGMM): + + @classmethod + def setup_class(cls): + XLISTEXOG2 = "aget aget2 educyr actlim totchr".split() + + endog_name = "docvis" + exog_names = "private medicaid".split() + XLISTEXOG2 + ["const"] + instrument_names = "income ssiratio".split() + XLISTEXOG2 + ["const"] + + endog = DATA[endog_name] + exog = DATA[exog_names] + instrument = DATA[instrument_names] + + def asarray(x): + return np.asarray(x, float) + + endog, exog, instrument = lmap(asarray, [endog, exog, instrument]) + + cls.bse_tol = [5e-6, 5e-7] + # compare to Stata default options, iterative GMM + # with const at end + start = OLS(np.log(endog + 1), exog).fit().params + nobs, k_instr = instrument.shape + w0inv = np.dot(instrument.T, instrument) / nobs + + mod = gmm.NonlinearIVGMM(endog, exog, instrument, moment_exponential_add) + res0 = mod.fit( + start, + maxiter=0, + inv_weights=w0inv, + optim_method="bfgs", + optim_args={"gtol": 1e-8, "disp": 0}, + wargs={"centered": False}, + ) + cls.res1 = res0 + + from .results_gmm_poisson import results_addonestep as results + + cls.res2 = results + + +class TestGMMAddTwostep(CheckGMM): + + @classmethod + def setup_class(cls): + XLISTEXOG2 = "aget aget2 educyr actlim totchr".split() + + endog_name = "docvis" + exog_names = "private medicaid".split() + XLISTEXOG2 + ["const"] + instrument_names = "income ssiratio".split() + XLISTEXOG2 + ["const"] + + endog = DATA[endog_name] + exog = DATA[exog_names] + instrument = DATA[instrument_names] + + def asarray(x): + return np.asarray(x, float) + + endog, exog, instrument = lmap(asarray, [endog, exog, instrument]) + + cls.bse_tol = [5e-6, 5e-7] + # compare to Stata default options, iterative GMM + # with const at end + start = OLS(np.log(endog + 1), exog).fit().params + nobs, k_instr = instrument.shape + w0inv = np.dot(instrument.T, instrument) / nobs + + mod = gmm.NonlinearIVGMM(endog, exog, instrument, moment_exponential_add) + res0 = mod.fit( + start, + maxiter=2, + inv_weights=w0inv, + optim_method="bfgs", + optim_args={"gtol": 1e-8, "disp": 0}, + wargs={"centered": False}, + has_optimal_weights=False, + ) + cls.res1 = res0 + + from .results_gmm_poisson import results_addtwostep as results + + cls.res2 = results + + +class TestGMMMultOnestep(CheckGMM): + # compares has_optimal_weights=True with Stata's has_optimal_weights=False + + @classmethod + def setup_class(cls): + # compare to Stata default options, twostep GMM + XLISTEXOG2 = "aget aget2 educyr actlim totchr".split() + + endog_name = "docvis" + exog_names = "private medicaid".split() + XLISTEXOG2 + ["const"] + instrument_names = "income medicaid ssiratio".split() + XLISTEXOG2 + ["const"] + + endog = DATA[endog_name] + exog = DATA[exog_names] + instrument = DATA[instrument_names] + + def asarray(x): + return np.asarray(x, float) + + endog, exog, instrument = lmap(asarray, [endog, exog, instrument]) + + # Need to add all data into exog + endog_ = np.zeros(len(endog)) + exog_ = np.column_stack((endog, exog)) + + cls.bse_tol = [5e-6, 5e-7] + cls.q_tol = [0.04, 0] + cls.j_tol = [0.04, 0] + # compare to Stata default options, iterative GMM + # with const at end + start = OLS(endog, exog).fit().params + nobs, k_instr = instrument.shape + w0inv = np.dot(instrument.T, instrument) / nobs + + mod = gmm.NonlinearIVGMM(endog_, exog_, instrument, moment_exponential_mult) + res0 = mod.fit( + start, + maxiter=0, + inv_weights=w0inv, + optim_method="bfgs", + optim_args={"gtol": 1e-8, "disp": 0}, + wargs={"centered": False}, + has_optimal_weights=False, + ) + cls.res1 = res0 + + from .results_gmm_poisson import results_multonestep as results + + cls.res2 = results + + +class TestGMMMultTwostep(CheckGMM): + # compares has_optimal_weights=True with Stata's has_optimal_weights=False + + @classmethod + def setup_class(cls): + # compare to Stata default options, twostep GMM + XLISTEXOG2 = "aget aget2 educyr actlim totchr".split() + + endog_name = "docvis" + exog_names = "private medicaid".split() + XLISTEXOG2 + ["const"] + instrument_names = "income medicaid ssiratio".split() + XLISTEXOG2 + ["const"] + + endog = DATA[endog_name] + exog = DATA[exog_names] + instrument = DATA[instrument_names] + + def asarray(x): + return np.asarray(x, float) + + endog, exog, instrument = lmap(asarray, [endog, exog, instrument]) + + # Need to add all data into exog + endog_ = np.zeros(len(endog)) + exog_ = np.column_stack((endog, exog)) + + cls.bse_tol = [5e-6, 5e-7] + # compare to Stata default options, iterative GMM + # with const at end + start = OLS(endog, exog).fit().params + nobs, k_instr = instrument.shape + w0inv = np.dot(instrument.T, instrument) / nobs + + mod = gmm.NonlinearIVGMM(endog_, exog_, instrument, moment_exponential_mult) + res0 = mod.fit( + start, + maxiter=2, + inv_weights=w0inv, + optim_method="bfgs", + optim_args={"gtol": 1e-8, "disp": 0}, + wargs={"centered": False}, + has_optimal_weights=False, + ) + cls.res1 = res0 + + from .results_gmm_poisson import results_multtwostep as results + + cls.res2 = results + + +class TestGMMMultTwostepDefault(CheckGMM): + # compares my defaults with the same options in Stata + # agreement is not very high, maybe vce(unadjusted) is different after all + + @classmethod + def setup_class(cls): + # compare to Stata default options, twostep GMM + XLISTEXOG2 = "aget aget2 educyr actlim totchr".split() + + endog_name = "docvis" + exog_names = "private medicaid".split() + XLISTEXOG2 + ["const"] + instrument_names = "income medicaid ssiratio".split() + XLISTEXOG2 + ["const"] + + endog = DATA[endog_name] + exog = DATA[exog_names] + instrument = DATA[instrument_names] + + def asarray(x): + return np.asarray(x, float) + + endog, exog, instrument = lmap(asarray, [endog, exog, instrument]) + + # Need to add all data into exog + endog_ = np.zeros(len(endog)) + exog_ = np.column_stack((endog, exog)) + + cls.bse_tol = [0.004, 5e-4] + cls.params_tol = [5e-5, 5e-5] + # compare to Stata default options, iterative GMM + # with const at end + start = OLS(endog, exog).fit().params + nobs, k_instr = instrument.shape + w0inv = np.dot(instrument.T, instrument) / nobs + + mod = gmm.NonlinearIVGMM(endog_, exog_, instrument, moment_exponential_mult) + res0 = mod.fit( + start, + maxiter=2, + inv_weights=w0inv, + optim_method="bfgs", + optim_args={"gtol": 1e-8, "disp": 0}, + # wargs={'centered':True}, has_optimal_weights=True + ) + cls.res1 = res0 + + from .results_gmm_poisson import results_multtwostepdefault as results + + cls.res2 = results + + +class TestGMMMultTwostepCenter(CheckGMM): + # compares my defaults with the same options in Stata + + @classmethod + def setup_class(cls): + # compare to Stata default options, twostep GMM + XLISTEXOG2 = "aget aget2 educyr actlim totchr".split() + + endog_name = "docvis" + exog_names = "private medicaid".split() + XLISTEXOG2 + ["const"] + instrument_names = "income medicaid ssiratio".split() + XLISTEXOG2 + ["const"] + + endog = DATA[endog_name] + exog = DATA[exog_names] + instrument = DATA[instrument_names] + + def asarray(x): + return np.asarray(x, float) + + endog, exog, instrument = lmap(asarray, [endog, exog, instrument]) + + # Need to add all data into exog + endog_ = np.zeros(len(endog)) + exog_ = np.column_stack((endog, exog)) + + cls.bse_tol = [5e-4, 5e-5] + cls.params_tol = [5e-5, 5e-5] + # compare to Stata default options, iterative GMM + # with const at end + start = OLS(endog, exog).fit().params + nobs, k_instr = instrument.shape + w0inv = np.dot(instrument.T, instrument) / nobs + + mod = gmm.NonlinearIVGMM(endog_, exog_, instrument, moment_exponential_mult) + res0 = mod.fit( + start, + maxiter=2, + inv_weights=w0inv, + optim_method="bfgs", + optim_args={"gtol": 1e-8, "disp": 0}, + wargs={"centered": True}, + has_optimal_weights=False, + ) + cls.res1 = res0 + + from .results_gmm_poisson import results_multtwostepcenter as results + + cls.res2 = results + + def test_more(self): + + # from Stata `overid` + J_p = 0.332254330027383 + + _, jpval, _ = self.res1.jtest() + + assert_allclose(jpval, J_p, rtol=5e-5, atol=0) diff --git a/shared/package-files/7b/7b30fc3d10f39a3cb822ccec23910e121d0a84fb51646defd2fb8162d9679d37/blob b/shared/package-files/7b/7b30fc3d10f39a3cb822ccec23910e121d0a84fb51646defd2fb8162d9679d37/blob new file mode 100644 index 0000000000000000000000000000000000000000..2d9f47af5147270a2de192ea8b0b34a23204b4e7 --- /dev/null +++ b/shared/package-files/7b/7b30fc3d10f39a3cb822ccec23910e121d0a84fb51646defd2fb8162d9679d37/blob @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::range.step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step=1, at::TensorOptions options={}) { + return at::_ops::range_step::call(start, end, step, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::range.step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::range_step::call(start, end, step, dtype, layout, device, pin_memory); +} + +// aten::range(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, at::TensorOptions options={}) { + return at::_ops::range::call(start, end, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::range(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor range(const at::Scalar & start, const at::Scalar & end, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::range::call(start, end, dtype, layout, device, pin_memory); +} + +// aten::range.out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & range_out(at::Tensor & out, const at::Scalar & start, const at::Scalar & end) { + return at::_ops::range_out_::call(start, end, out); +} +// aten::range.out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & range_outf(const at::Scalar & start, const at::Scalar & end, at::Tensor & out) { + return at::_ops::range_out_::call(start, end, out); +} + +// aten::range.out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & range_out(at::Tensor & out, const at::Scalar & start, const at::Scalar & end, const at::Scalar & step) { + return at::_ops::range_out::call(start, end, step, out); +} +// aten::range.out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & range_outf(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out) { + return at::_ops::range_out::call(start, end, step, out); +} + +} diff --git a/shared/package-files/7b/7b31c1e33b6cec63e0ab2288955654f43da089cecf3a6a7248fa50424b0862fb/blob b/shared/package-files/7b/7b31c1e33b6cec63e0ab2288955654f43da089cecf3a6a7248fa50424b0862fb/blob new file mode 100644 index 0000000000000000000000000000000000000000..ee45ffb288368dc35ffb76e385bcee20ced22235 --- /dev/null +++ b/shared/package-files/7b/7b31c1e33b6cec63e0ab2288955654f43da089cecf3a6a7248fa50424b0862fb/blob @@ -0,0 +1,20 @@ +import torch + +from torch._export.db.case import export_case + + +@export_case( + example_inputs=(torch.ones(3, 2),), + tags={"torch.dynamic-shape"}, +) +class DynamicShapeSlicing(torch.nn.Module): + """ + Slices with dynamic shape arguments should be captured into the graph + rather than being baked in. + """ + + def __init__(self): + super().__init__() + + def forward(self, x): + return x[: x.shape[0] - 2, x.shape[1] - 1 :: 2] diff --git a/shared/package-files/7b/7b31f6e4c2f011b03e7c38701f7932f57fff21d2bc70deb6586b202351a7d964/blob b/shared/package-files/7b/7b31f6e4c2f011b03e7c38701f7932f57fff21d2bc70deb6586b202351a7d964/blob new file mode 100644 index 0000000000000000000000000000000000000000..e51ddec77c3e39197927543ee47cdcf9caf8d63a --- /dev/null +++ b/shared/package-files/7b/7b31f6e4c2f011b03e7c38701f7932f57fff21d2bc70deb6586b202351a7d964/blob @@ -0,0 +1,329 @@ +""" +Variance functions for use with the link functions in statsmodels.family.links +""" +import numpy as np + +FLOAT_EPS = np.finfo(float).eps + + +class VarianceFunction: + """ + Relates the variance of a random variable to its mean. Defaults to 1. + + Methods + ------- + call + Returns an array of ones that is the same shape as `mu` + + Notes + ----- + After a variance function is initialized, its call method can be used. + + Alias for VarianceFunction: + constant = VarianceFunction() + + See Also + -------- + statsmodels.genmod.families.family + """ + + def __call__(self, mu): + """ + Default variance function + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + v : ndarray + ones(mu.shape) + """ + mu = np.asarray(mu) + return np.ones(mu.shape, np.float64) + + def deriv(self, mu): + """ + Derivative of the variance function v'(mu) + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + v' : ndarray + zeros(mu.shape) + """ + return np.zeros_like(mu) + + +constant = VarianceFunction() +constant.__doc__ = """ +The call method of constant returns a constant variance, i.e., a vector of +ones. + +constant is an alias of VarianceFunction() +""" + + +class Power: + """ + Power variance function + + Parameters + ---------- + power : float, optional + exponent used in power variance function + + Methods + ------- + call + Returns the power variance + + Notes + ----- + Formulas + V(mu) = numpy.fabs(mu)**power + + Aliases for Power: + mu = Power() + mu_squared = Power(power=2) + mu_cubed = Power(power=3) + """ + + def __init__(self, power=1.): + self.power = power + + def __call__(self, mu): + """ + Power variance function + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + variance : ndarray + numpy.fabs(mu)**self.power + """ + return np.power(np.fabs(mu), self.power) + + def deriv(self, mu): + """ + Derivative of the variance function v'(mu) + + May be undefined at zero. + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + v' : ndarray + The value of the derivative of the power variance function + """ + + der = self.power * np.fabs(mu) ** (self.power - 1) + ii = np.flatnonzero(mu < 0) + der[ii] *= -1 + return der + + +mu = Power() +mu.__doc__ = """ +Returns np.fabs(mu) + +Notes +----- +This is an alias of Power() +""" +mu_squared = Power(power=2) +mu_squared.__doc__ = """ +Returns np.fabs(mu)**2 + +Notes +----- +This is an alias of statsmodels.family.links.Power(power=2) +""" +mu_cubed = Power(power=3) +mu_cubed.__doc__ = """ +Returns np.fabs(mu)**3 + +Notes +----- +This is an alias of statsmodels.family.links.Power(power=3) +""" + + +class Binomial: + """ + Binomial variance function + + Parameters + ---------- + n : int, optional + The number of trials for a binomial variable. The default is 1 for + p in (0,1) + + Methods + ------- + call + Returns the binomial variance + + Notes + ----- + Formulas : + + V(mu) = p * (1 - p) * n + + where p = mu / n + + Alias for Binomial: + binary = Binomial() + + A private method _clean trims the data by machine epsilon so that p is + in (0,1) + """ + + def __init__(self, n=1): + self.n = n + + def _clean(self, p): + return np.clip(p, FLOAT_EPS, 1 - FLOAT_EPS) + + def __call__(self, mu): + """ + Binomial variance function + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + variance : ndarray + variance = mu/n * (1 - mu/n) * self.n + """ + p = self._clean(mu / self.n) + return p * (1 - p) * self.n + + # TODO: inherit from super + def deriv(self, mu): + """ + Derivative of the variance function V'(mu). + + For the Binomial variance V(mu) = p*(1 - p)*n where p = mu/n, the + derivative with respect to mu is dV/dmu = 1 - 2*p. + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + V' : ndarray + The value of the derivative of the binomial variance function + """ + p = self._clean(mu / self.n) + return 1 - 2 * p + + +binary = Binomial() +binary.__doc__ = """ +The binomial variance function for n = 1 + +Notes +----- +This is an alias of Binomial(n=1) +""" + + +class NegativeBinomial: + """ + Negative binomial variance function + + Parameters + ---------- + alpha : float, optional + The ancillary parameter for the negative binomial variance function. + `alpha` is assumed to be nonstochastic. The default is 1. + + Methods + ------- + call + Returns the negative binomial variance + + Notes + ----- + Formulas : + + V(mu) = mu + alpha*mu**2 + + Alias for NegativeBinomial: + nbinom = NegativeBinomial() + + A private method _clean trims the data by machine epsilon so that p is + in (0,inf) + """ + + def __init__(self, alpha=1.): + self.alpha = alpha + + def _clean(self, p): + return np.clip(p, FLOAT_EPS, np.inf) + + def __call__(self, mu): + """ + Negative binomial variance function + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + variance : ndarray + variance = mu + alpha*mu**2 + """ + p = self._clean(mu) + return p + self.alpha*p**2 + + def deriv(self, mu): + """ + Derivative of the negative binomial variance function. + + Parameters + ---------- + mu : array_like + mean parameters + + Returns + ------- + V' : ndarray + The value of the derivative of the negative binomial variance + function + """ + + p = self._clean(mu) + return 1 + 2 * self.alpha * p + + +nbinom = NegativeBinomial() +nbinom.__doc__ = """ +Negative Binomial variance function. + +Notes +----- +This is an alias of NegativeBinomial(alpha=1.) +""" diff --git a/shared/package-files/7b/7b341e6adb4e4341b211a221a7224849ea415fc1e39c014b05ae7d9a566819f4/blob b/shared/package-files/7b/7b341e6adb4e4341b211a221a7224849ea415fc1e39c014b05ae7d9a566819f4/blob new file mode 100644 index 0000000000000000000000000000000000000000..0f8587317c2bbc4c37c79b9112ffc281c67bcebd --- /dev/null +++ b/shared/package-files/7b/7b341e6adb4e4341b211a221a7224849ea415fc1e39c014b05ae7d9a566819f4/blob @@ -0,0 +1,483 @@ +"""A POP3 client class. + +Based on the J. Myers POP3 draft, Jan. 96 +""" + +# Author: David Ascher +# [heavily stealing from nntplib.py] +# Updated: Piers Lauder [Jul '97] +# String method conversion and test jig improvements by ESR, February 2001. +# Added the POP3_SSL class. Methods loosely based on IMAP_SSL. Hector Urtubia Aug 2003 + +# Example (see the test function at the end of this file) + +# Imports + +import errno +import re +import socket +import sys + +try: + import ssl + HAVE_SSL = True +except ImportError: + HAVE_SSL = False + +__all__ = ["POP3","error_proto"] + +# Exception raised when an error or invalid response is received: + +class error_proto(Exception): pass + +# Standard Port +POP3_PORT = 110 + +# POP SSL PORT +POP3_SSL_PORT = 995 + +# Line terminators (we always output CRLF, but accept any of CRLF, LFCR, LF) +CR = b'\r' +LF = b'\n' +CRLF = CR+LF + +# maximal line length when calling readline(). This is to prevent +# reading arbitrary length lines. RFC 1939 limits POP3 line length to +# 512 characters, including CRLF. We have selected 2048 just to be on +# the safe side. +_MAXLINE = 2048 + + +class POP3: + + """This class supports both the minimal and optional command sets. + Arguments can be strings or integers (where appropriate) + (e.g.: retr(1) and retr('1') both work equally well. + + Minimal Command Set: + USER name user(name) + PASS string pass_(string) + STAT stat() + LIST [msg] list(msg = None) + RETR msg retr(msg) + DELE msg dele(msg) + NOOP noop() + RSET rset() + QUIT quit() + + Optional Commands (some servers support these): + RPOP name rpop(name) + APOP name digest apop(name, digest) + TOP msg n top(msg, n) + UIDL [msg] uidl(msg = None) + CAPA capa() + STLS stls() + UTF8 utf8() + + Raises one exception: 'error_proto'. + + Instantiate with: + POP3(hostname, port=110) + + NB: the POP protocol locks the mailbox from user + authorization until QUIT, so be sure to get in, suck + the messages, and quit, each time you access the + mailbox. + + POP is a line-based protocol, which means large mail + messages consume lots of python cycles reading them + line-by-line. + + If it's available on your mail server, use IMAP4 + instead, it doesn't suffer from the two problems + above. + """ + + encoding = 'UTF-8' + + def __init__(self, host, port=POP3_PORT, + timeout=socket._GLOBAL_DEFAULT_TIMEOUT): + self.host = host + self.port = port + self._tls_established = False + sys.audit("poplib.connect", self, host, port) + self.sock = self._create_socket(timeout) + self.file = self.sock.makefile('rb') + self._debugging = 0 + self.welcome = self._getresp() + + def _create_socket(self, timeout): + if timeout is not None and not timeout: + raise ValueError('Non-blocking socket (timeout=0) is not supported') + return socket.create_connection((self.host, self.port), timeout) + + def _putline(self, line): + if self._debugging > 1: print('*put*', repr(line)) + sys.audit("poplib.putline", self, line) + self.sock.sendall(line + CRLF) + + + # Internal: send one command to the server (through _putline()) + + def _putcmd(self, line): + if self._debugging: print('*cmd*', repr(line)) + line = bytes(line, self.encoding) + self._putline(line) + + + # Internal: return one line from the server, stripping CRLF. + # This is where all the CPU time of this module is consumed. + # Raise error_proto('-ERR EOF') if the connection is closed. + + def _getline(self): + line = self.file.readline(_MAXLINE + 1) + if len(line) > _MAXLINE: + raise error_proto('line too long') + + if self._debugging > 1: print('*get*', repr(line)) + if not line: raise error_proto('-ERR EOF') + octets = len(line) + # server can send any combination of CR & LF + # however, 'readline()' returns lines ending in LF + # so only possibilities are ...LF, ...CRLF, CR...LF + if line[-2:] == CRLF: + return line[:-2], octets + if line[:1] == CR: + return line[1:-1], octets + return line[:-1], octets + + + # Internal: get a response from the server. + # Raise 'error_proto' if the response doesn't start with '+'. + + def _getresp(self): + resp, o = self._getline() + if self._debugging > 1: print('*resp*', repr(resp)) + if not resp.startswith(b'+'): + raise error_proto(resp) + return resp + + + # Internal: get a response plus following text from the server. + + def _getlongresp(self): + resp = self._getresp() + list = []; octets = 0 + line, o = self._getline() + while line != b'.': + if line.startswith(b'..'): + o = o-1 + line = line[1:] + octets = octets + o + list.append(line) + line, o = self._getline() + return resp, list, octets + + + # Internal: send a command and get the response + + def _shortcmd(self, line): + self._putcmd(line) + return self._getresp() + + + # Internal: send a command and get the response plus following text + + def _longcmd(self, line): + self._putcmd(line) + return self._getlongresp() + + + # These can be useful: + + def getwelcome(self): + return self.welcome + + + def set_debuglevel(self, level): + self._debugging = level + + + # Here are all the POP commands: + + def user(self, user): + """Send user name, return response + + (should indicate password required). + """ + return self._shortcmd('USER %s' % user) + + + def pass_(self, pswd): + """Send password, return response + + (response includes message count, mailbox size). + + NB: mailbox is locked by server from here to 'quit()' + """ + return self._shortcmd('PASS %s' % pswd) + + + def stat(self): + """Get mailbox status. + + Result is tuple of 2 ints (message count, mailbox size) + """ + retval = self._shortcmd('STAT') + rets = retval.split() + if self._debugging: print('*stat*', repr(rets)) + numMessages = int(rets[1]) + sizeMessages = int(rets[2]) + return (numMessages, sizeMessages) + + + def list(self, which=None): + """Request listing, return result. + + Result without a message number argument is in form + ['response', ['mesg_num octets', ...], octets]. + + Result when a message number argument is given is a + single response: the "scan listing" for that message. + """ + if which is not None: + return self._shortcmd('LIST %s' % which) + return self._longcmd('LIST') + + + def retr(self, which): + """Retrieve whole message number 'which'. + + Result is in form ['response', ['line', ...], octets]. + """ + return self._longcmd('RETR %s' % which) + + + def dele(self, which): + """Delete message number 'which'. + + Result is 'response'. + """ + return self._shortcmd('DELE %s' % which) + + + def noop(self): + """Does nothing. + + One supposes the response indicates the server is alive. + """ + return self._shortcmd('NOOP') + + + def rset(self): + """Unmark all messages marked for deletion.""" + return self._shortcmd('RSET') + + + def quit(self): + """Signoff: commit changes on server, unlock mailbox, close connection.""" + resp = self._shortcmd('QUIT') + self.close() + return resp + + def close(self): + """Close the connection without assuming anything about it.""" + try: + file = self.file + self.file = None + if file is not None: + file.close() + finally: + sock = self.sock + self.sock = None + if sock is not None: + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError as exc: + # The server might already have closed the connection. + # On Windows, this may result in WSAEINVAL (error 10022): + # An invalid operation was attempted. + if (exc.errno != errno.ENOTCONN + and getattr(exc, 'winerror', 0) != 10022): + raise + finally: + sock.close() + + #__del__ = quit + + + # optional commands: + + def rpop(self, user): + """Not sure what this does.""" + return self._shortcmd('RPOP %s' % user) + + + timestamp = re.compile(br'\+OK.[^<]*(<.*>)') + + def apop(self, user, password): + """Authorisation + + - only possible if server has supplied a timestamp in initial greeting. + + Args: + user - mailbox user; + password - mailbox password. + + NB: mailbox is locked by server from here to 'quit()' + """ + secret = bytes(password, self.encoding) + m = self.timestamp.match(self.welcome) + if not m: + raise error_proto('-ERR APOP not supported by server') + import hashlib + digest = m.group(1)+secret + digest = hashlib.md5(digest).hexdigest() + return self._shortcmd('APOP %s %s' % (user, digest)) + + + def top(self, which, howmuch): + """Retrieve message header of message number 'which' + and first 'howmuch' lines of message body. + + Result is in form ['response', ['line', ...], octets]. + """ + return self._longcmd('TOP %s %s' % (which, howmuch)) + + + def uidl(self, which=None): + """Return message digest (unique id) list. + + If 'which', result contains unique id for that message + in the form 'response mesgnum uid', otherwise result is + the list ['response', ['mesgnum uid', ...], octets] + """ + if which is not None: + return self._shortcmd('UIDL %s' % which) + return self._longcmd('UIDL') + + + def utf8(self): + """Try to enter UTF-8 mode (see RFC 6856). Returns server response. + """ + return self._shortcmd('UTF8') + + + def capa(self): + """Return server capabilities (RFC 2449) as a dictionary + >>> c=poplib.POP3('localhost') + >>> c.capa() + {'IMPLEMENTATION': ['Cyrus', 'POP3', 'server', 'v2.2.12'], + 'TOP': [], 'LOGIN-DELAY': ['0'], 'AUTH-RESP-CODE': [], + 'EXPIRE': ['NEVER'], 'USER': [], 'STLS': [], 'PIPELINING': [], + 'UIDL': [], 'RESP-CODES': []} + >>> + + Really, according to RFC 2449, the cyrus folks should avoid + having the implementation split into multiple arguments... + """ + def _parsecap(line): + lst = line.decode('ascii').split() + return lst[0], lst[1:] + + caps = {} + try: + resp = self._longcmd('CAPA') + rawcaps = resp[1] + for capline in rawcaps: + capnm, capargs = _parsecap(capline) + caps[capnm] = capargs + except error_proto: + raise error_proto('-ERR CAPA not supported by server') + return caps + + + def stls(self, context=None): + """Start a TLS session on the active connection as specified in RFC 2595. + + context - a ssl.SSLContext + """ + if not HAVE_SSL: + raise error_proto('-ERR TLS support missing') + if self._tls_established: + raise error_proto('-ERR TLS session already established') + caps = self.capa() + if not 'STLS' in caps: + raise error_proto('-ERR STLS not supported by server') + if context is None: + context = ssl._create_stdlib_context() + resp = self._shortcmd('STLS') + self.sock = context.wrap_socket(self.sock, + server_hostname=self.host) + self.file = self.sock.makefile('rb') + self._tls_established = True + return resp + + +if HAVE_SSL: + + class POP3_SSL(POP3): + """POP3 client class over SSL connection + + Instantiate with: POP3_SSL(hostname, port=995, keyfile=None, certfile=None, + context=None) + + hostname - the hostname of the pop3 over ssl server + port - port number + keyfile - PEM formatted file that contains your private key + certfile - PEM formatted certificate chain file + context - a ssl.SSLContext + + See the methods of the parent class POP3 for more documentation. + """ + + def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None, + timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=None): + if context is not None and keyfile is not None: + raise ValueError("context and keyfile arguments are mutually " + "exclusive") + if context is not None and certfile is not None: + raise ValueError("context and certfile arguments are mutually " + "exclusive") + if keyfile is not None or certfile is not None: + import warnings + warnings.warn("keyfile and certfile are deprecated, use a " + "custom context instead", DeprecationWarning, 2) + self.keyfile = keyfile + self.certfile = certfile + if context is None: + context = ssl._create_stdlib_context(certfile=certfile, + keyfile=keyfile) + self.context = context + POP3.__init__(self, host, port, timeout) + + def _create_socket(self, timeout): + sock = POP3._create_socket(self, timeout) + sock = self.context.wrap_socket(sock, + server_hostname=self.host) + return sock + + def stls(self, keyfile=None, certfile=None, context=None): + """The method unconditionally raises an exception since the + STLS command doesn't make any sense on an already established + SSL/TLS session. + """ + raise error_proto('-ERR TLS session already established') + + __all__.append("POP3_SSL") + +if __name__ == "__main__": + import sys + a = POP3(sys.argv[1]) + print(a.getwelcome()) + a.user(sys.argv[2]) + a.pass_(sys.argv[3]) + a.list() + (numMsgs, totalSize) = a.stat() + for i in range(1, numMsgs + 1): + (header, msg, octets) = a.retr(i) + print("Message %d:" % i) + for line in msg: + print(' ' + line) + print('-----------------------') + a.quit() diff --git a/shared/package-files/7b/7b349d4ce203b0d84528a3c0cb42d775edc414819bfba6001b2d8cbd11b7117c/blob b/shared/package-files/7b/7b349d4ce203b0d84528a3c0cb42d775edc414819bfba6001b2d8cbd11b7117c/blob new file mode 100644 index 0000000000000000000000000000000000000000..f0b55d220d60dbbf6b117a1691241deb44874fe2 --- /dev/null +++ b/shared/package-files/7b/7b349d4ce203b0d84528a3c0cb42d775edc414819bfba6001b2d8cbd11b7117c/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_dim_arange(Tensor like, int dim) -> Tensor +inline at::Tensor _dim_arange(const at::Tensor & like, int64_t dim) { + return at::_ops::_dim_arange::call(like, dim); +} + +} diff --git a/shared/package-files/7b/7b35329fb0185816e5ad96d2b6522d258bbb5c83422e28a1ac205907e065f90c/blob b/shared/package-files/7b/7b35329fb0185816e5ad96d2b6522d258bbb5c83422e28a1ac205907e065f90c/blob new file mode 100644 index 0000000000000000000000000000000000000000..824f814160ee4a95cc6a6d5553b3c1aacc907895 Binary files /dev/null and b/shared/package-files/7b/7b35329fb0185816e5ad96d2b6522d258bbb5c83422e28a1ac205907e065f90c/blob differ diff --git a/shared/package-files/7b/7b37332f0d3b818aef91eeab4738006ac20e325e49dd881cfa9ca24fda79037b/blob b/shared/package-files/7b/7b37332f0d3b818aef91eeab4738006ac20e325e49dd881cfa9ca24fda79037b/blob new file mode 100644 index 0000000000000000000000000000000000000000..b78d8a1e9434fe8ad99af043f2fb537615da46d1 Binary files /dev/null and b/shared/package-files/7b/7b37332f0d3b818aef91eeab4738006ac20e325e49dd881cfa9ca24fda79037b/blob differ diff --git a/shared/package-files/7b/7b3778c80b115c8d51f8cc44d6221bc871c89441b22ae99c910cd51c0c78eab3/blob b/shared/package-files/7b/7b3778c80b115c8d51f8cc44d6221bc871c89441b22ae99c910cd51c0c78eab3/blob new file mode 100644 index 0000000000000000000000000000000000000000..5390a24b90d207cb159523e9bf571136536f580e --- /dev/null +++ b/shared/package-files/7b/7b3778c80b115c8d51f8cc44d6221bc871c89441b22ae99c910cd51c0c78eab3/blob @@ -0,0 +1,179 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import io + +try: + import numpy as np +except ImportError: + np = None + +import pyarrow as pa +from pyarrow.tests import util + + +def _write_table(table, path, **kwargs): + # So we see the ImportError somewhere + import pyarrow.parquet as pq + from pyarrow.pandas_compat import _pandas_api + + if _pandas_api.is_data_frame(table): + table = pa.Table.from_pandas(table) + + pq.write_table(table, path, **kwargs) + return table + + +def _read_table(*args, **kwargs): + import pyarrow.parquet as pq + + table = pq.read_table(*args, **kwargs) + table.validate(full=True) + return table + + +def _roundtrip_table(table, read_table_kwargs=None, + write_table_kwargs=None): + read_table_kwargs = read_table_kwargs or {} + write_table_kwargs = write_table_kwargs or {} + + writer = pa.BufferOutputStream() + _write_table(table, writer, **write_table_kwargs) + reader = pa.BufferReader(writer.getvalue()) + return _read_table(reader, **read_table_kwargs) + + +def _check_roundtrip(table, expected=None, read_table_kwargs=None, + **write_table_kwargs): + if expected is None: + expected = table + + read_table_kwargs = read_table_kwargs or {} + + # intentionally check twice + result = _roundtrip_table(table, read_table_kwargs=read_table_kwargs, + write_table_kwargs=write_table_kwargs) + assert result.schema == expected.schema + assert result.equals(expected) + result = _roundtrip_table(result, read_table_kwargs=read_table_kwargs, + write_table_kwargs=write_table_kwargs) + assert result.schema == expected.schema + assert result.equals(expected) + + +def _roundtrip_pandas_dataframe(df, write_kwargs): + table = pa.Table.from_pandas(df) + result = _roundtrip_table( + table, write_table_kwargs=write_kwargs) + return result.to_pandas() + + +def _random_integers(size, dtype): + # We do not generate integers outside the int64 range + platform_int_info = np.iinfo('int_') + iinfo = np.iinfo(dtype) + return np.random.randint(max(iinfo.min, platform_int_info.min), + min(iinfo.max, platform_int_info.max), + size=size, dtype=dtype) + + +def _range_integers(size, dtype): + return pa.array(np.arange(size, dtype=dtype)) + + +def _test_dict(size=10000, seed=0): + np.random.seed(seed) + return { + 'uint8': _random_integers(size, np.uint8), + 'uint16': _random_integers(size, np.uint16), + 'uint32': _random_integers(size, np.uint32), + 'uint64': _random_integers(size, np.uint64), + 'int8': _random_integers(size, np.int8), + 'int16': _random_integers(size, np.int16), + 'int32': _random_integers(size, np.int32), + 'int64': _random_integers(size, np.int64), + 'float32': np.random.randn(size).astype(np.float32), + 'float64': np.arange(size, dtype=np.float64), + 'bool': np.random.randn(size) > 0, + 'strings': [util.rands(10) for i in range(size)], + 'all_none': [None] * size, + 'all_none_category': [None] * size + } + + +def _test_dataframe(size=10000, seed=0): + import pandas as pd + + df = pd.DataFrame(_test_dict(size, seed)) + + # TODO(PARQUET-1015) + # df['all_none_category'] = df['all_none_category'].astype('category') + return df + + +def _test_table(size=10000, seed=0): + return pa.Table.from_pydict(_test_dict(size, seed)) + + +def make_sample_file(table_or_df): + import pyarrow.parquet as pq + + if isinstance(table_or_df, pa.Table): + a_table = table_or_df + else: + a_table = pa.Table.from_pandas(table_or_df) + + buf = io.BytesIO() + _write_table(a_table, buf, compression='SNAPPY', version='2.6') + + buf.seek(0) + return pq.ParquetFile(buf) + + +def alltypes_sample(size=10000, seed=0, categorical=False): + import pandas as pd + + np.random.seed(seed) + arrays = { + 'uint8': np.arange(size, dtype=np.uint8), + 'uint16': np.arange(size, dtype=np.uint16), + 'uint32': np.arange(size, dtype=np.uint32), + 'uint64': np.arange(size, dtype=np.uint64), + 'int8': np.arange(size, dtype=np.int16), + 'int16': np.arange(size, dtype=np.int16), + 'int32': np.arange(size, dtype=np.int32), + 'int64': np.arange(size, dtype=np.int64), + 'float16': np.arange(size, dtype=np.float16), + 'float32': np.arange(size, dtype=np.float32), + 'float64': np.arange(size, dtype=np.float64), + 'bool': np.random.randn(size) > 0, + 'datetime_ms': np.arange("2016-01-01T00:00:00.001", size, + dtype='datetime64[ms]'), + 'datetime_us': np.arange("2016-01-01T00:00:00.000001", size, + dtype='datetime64[us]'), + 'datetime_ns': np.arange("2016-01-01T00:00:00.000000001", size, + dtype='datetime64[ns]'), + 'timedelta': np.arange(0, size, dtype="timedelta64[s]"), + 'str': pd.Series([str(x) for x in range(size)]), + 'empty_str': [''] * size, + 'str_with_nulls': [None] + [str(x) for x in range(size - 2)] + [None], + 'null': [None] * size, + 'null_list': [None] * 2 + [[None] * (x % 4) for x in range(size - 2)], + } + if categorical: + arrays['str_category'] = arrays['str'].astype('category') + return pd.DataFrame(arrays) diff --git a/shared/package-files/7b/7b38d711e2e91bd04132b374adb33767bee6727d17112c52940699132d9eafe9/blob b/shared/package-files/7b/7b38d711e2e91bd04132b374adb33767bee6727d17112c52940699132d9eafe9/blob new file mode 100644 index 0000000000000000000000000000000000000000..e79620668d7283770a9604647ba5d2ee78d98a01 --- /dev/null +++ b/shared/package-files/7b/7b38d711e2e91bd04132b374adb33767bee6727d17112c52940699132d9eafe9/blob @@ -0,0 +1,158 @@ +# Grammar for Python + +# NOTE WELL: You should also follow all the steps listed at +# https://docs.python.org/devguide/grammar.html + +# Start symbols for the grammar: +# single_input is a single interactive statement; +# file_input is a module or sequence of commands read from an input file; +# eval_input is the input for the eval() functions. +# NB: compound_stmt in single_input is followed by extra NEWLINE! +single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE +file_input: stmt* ENDMARKER +eval_input: testlist NEWLINE* ENDMARKER +decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE +decorators: decorator+ +decorated: decorators (classdef | funcdef | async_funcdef) + +# NOTE: Francisco Souza/Reinoud Elhorst, using ASYNC/'await' keywords instead of +# skipping python3.5+ compatibility, in favour of 3.7 solution +async_funcdef: 'async' funcdef +funcdef: 'def' NAME parameters ['->' test] ':' suite + +parameters: '(' [typedargslist] ')' +typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [ + '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']]] + | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + | '**' tfpdef [',']) +tfpdef: NAME [':' test] +varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ + '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [',']]] + | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] + | '**' vfpdef [','] +) +vfpdef: NAME + +stmt: simple_stmt | compound_stmt | NEWLINE +simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE +small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | + import_stmt | global_stmt | nonlocal_stmt | assert_stmt) +expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | + ('=' (yield_expr|testlist_star_expr))*) +annassign: ':' test ['=' test] +testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] +augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | + '<<=' | '>>=' | '**=' | '//=') +# For normal and annotated assignments, additional restrictions enforced by the interpreter +del_stmt: 'del' exprlist +pass_stmt: 'pass' +flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt +break_stmt: 'break' +continue_stmt: 'continue' +return_stmt: 'return' [testlist] +yield_stmt: yield_expr +raise_stmt: 'raise' [test ['from' test]] +import_stmt: import_name | import_from +import_name: 'import' dotted_as_names +# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS +import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) + 'import' ('*' | '(' import_as_names ')' | import_as_names)) +import_as_name: NAME ['as' NAME] +dotted_as_name: dotted_name ['as' NAME] +import_as_names: import_as_name (',' import_as_name)* [','] +dotted_as_names: dotted_as_name (',' dotted_as_name)* +dotted_name: NAME ('.' NAME)* +global_stmt: 'global' NAME (',' NAME)* +nonlocal_stmt: 'nonlocal' NAME (',' NAME)* +assert_stmt: 'assert' test [',' test] + +compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt +async_stmt: 'async' (funcdef | with_stmt | for_stmt) +if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] +while_stmt: 'while' test ':' suite ['else' ':' suite] +for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] +try_stmt: ('try' ':' suite + ((except_clause ':' suite)+ + ['else' ':' suite] + ['finally' ':' suite] | + 'finally' ':' suite)) +with_stmt: 'with' with_item (',' with_item)* ':' suite +with_item: test ['as' expr] +# NB compile.c makes sure that the default except clause is last +except_clause: 'except' [test ['as' NAME]] +suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT + +test: or_test ['if' or_test 'else' test] | lambdef +test_nocond: or_test | lambdef_nocond +lambdef: 'lambda' [varargslist] ':' test +lambdef_nocond: 'lambda' [varargslist] ':' test_nocond +or_test: and_test ('or' and_test)* +and_test: not_test ('and' not_test)* +not_test: 'not' not_test | comparison +comparison: expr (comp_op expr)* +# <> isn't actually a valid comparison operator in Python. It's here for the +# sake of a __future__ import described in PEP 401 (which really works :-) +comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' +star_expr: '*' expr +expr: xor_expr ('|' xor_expr)* +xor_expr: and_expr ('^' and_expr)* +and_expr: shift_expr ('&' shift_expr)* +shift_expr: arith_expr (('<<'|'>>') arith_expr)* +arith_expr: term (('+'|'-') term)* +term: factor (('*'|'@'|'/'|'%'|'//') factor)* +factor: ('+'|'-'|'~') factor | power +power: atom_expr ['**' factor] +atom_expr: ['await'] atom trailer* +atom: ('(' [yield_expr|testlist_comp] ')' | + '[' [testlist_comp] ']' | + '{' [dictorsetmaker] '}' | + NAME | NUMBER | strings | '...' | 'None' | 'True' | 'False') +testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] ) +trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME +subscriptlist: subscript (',' subscript)* [','] +subscript: test | [test] ':' [test] [sliceop] +sliceop: ':' [test] +exprlist: (expr|star_expr) (',' (expr|star_expr))* [','] +testlist: test (',' test)* [','] +dictorsetmaker: ( ((test ':' test | '**' expr) + (comp_for | (',' (test ':' test | '**' expr))* [','])) | + ((test | star_expr) + (comp_for | (',' (test | star_expr))* [','])) ) + +classdef: 'class' NAME ['(' [arglist] ')'] ':' suite + +arglist: argument (',' argument)* [','] + +# The reason that keywords are test nodes instead of NAME is that using NAME +# results in an ambiguity. ast.c makes sure it's a NAME. +# "test '=' test" is really "keyword '=' test", but we have no such token. +# These need to be in a single rule to avoid grammar that is ambiguous +# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr, +# we explicitly match '*' here, too, to give it proper precedence. +# Illegal combinations and orderings are blocked in ast.c: +# multiple (test comp_for) arguments are blocked; keyword unpackings +# that precede iterable unpackings are blocked; etc. +argument: ( test [comp_for] | + test '=' test | + '**' test | + '*' test ) + +comp_iter: comp_for | comp_if +sync_comp_for: 'for' exprlist 'in' or_test [comp_iter] +comp_for: ['async'] sync_comp_for +comp_if: 'if' test_nocond [comp_iter] + +# not used in grammar, but may appear in "node" passed from Parser to Compiler +encoding_decl: NAME + +yield_expr: 'yield' [yield_arg] +yield_arg: 'from' test | testlist + +strings: (STRING | fstring)+ +fstring: FSTRING_START fstring_content* FSTRING_END +fstring_content: FSTRING_STRING | fstring_expr +fstring_conversion: '!' NAME +fstring_expr: '{' (testlist_comp | yield_expr) [ fstring_conversion ] [ fstring_format_spec ] '}' +fstring_format_spec: ':' fstring_content* diff --git a/shared/package-files/7b/7b38eacbb17b930103420ad3ccaf89e5e04ba654735ee30eb2d392290d770771/blob b/shared/package-files/7b/7b38eacbb17b930103420ad3ccaf89e5e04ba654735ee30eb2d392290d770771/blob new file mode 100644 index 0000000000000000000000000000000000000000..75b8dd21a63b7dbc571534cdc9e5e17a4637aeb3 --- /dev/null +++ b/shared/package-files/7b/7b38eacbb17b930103420ad3ccaf89e5e04ba654735ee30eb2d392290d770771/blob @@ -0,0 +1,235 @@ +""" +The default styling. +""" +from __future__ import annotations + +from prompt_toolkit.cache import memoized + +from .base import ANSI_COLOR_NAMES, BaseStyle +from .named_colors import NAMED_COLORS +from .style import Style, merge_styles + +__all__ = [ + "default_ui_style", + "default_pygments_style", +] + +#: Default styling. Mapping from classnames to their style definition. +PROMPT_TOOLKIT_STYLE = [ + # Highlighting of search matches in document. + ("search", "bg:ansibrightyellow ansiblack"), + ("search.current", ""), + # Incremental search. + ("incsearch", ""), + ("incsearch.current", "reverse"), + # Highlighting of select text in document. + ("selected", "reverse"), + ("cursor-column", "bg:#dddddd"), + ("cursor-line", "underline"), + ("color-column", "bg:#ccaacc"), + # Highlighting of matching brackets. + ("matching-bracket", ""), + ("matching-bracket.other", "#000000 bg:#aacccc"), + ("matching-bracket.cursor", "#ff8888 bg:#880000"), + # Styling of other cursors, in case of block editing. + ("multiple-cursors", "#000000 bg:#ccccaa"), + # Line numbers. + ("line-number", "#888888"), + ("line-number.current", "bold"), + ("tilde", "#8888ff"), + # Default prompt. + ("prompt", ""), + ("prompt.arg", "noinherit"), + ("prompt.arg.text", ""), + ("prompt.search", "noinherit"), + ("prompt.search.text", ""), + # Search toolbar. + ("search-toolbar", "bold"), + ("search-toolbar.text", "nobold"), + # System toolbar + ("system-toolbar", "bold"), + ("system-toolbar.text", "nobold"), + # "arg" toolbar. + ("arg-toolbar", "bold"), + ("arg-toolbar.text", "nobold"), + # Validation toolbar. + ("validation-toolbar", "bg:#550000 #ffffff"), + ("window-too-small", "bg:#550000 #ffffff"), + # Completions toolbar. + ("completion-toolbar", "bg:#bbbbbb #000000"), + ("completion-toolbar.arrow", "bg:#bbbbbb #000000 bold"), + ("completion-toolbar.completion", "bg:#bbbbbb #000000"), + ("completion-toolbar.completion.current", "bg:#444444 #ffffff"), + # Completions menu. + ("completion-menu", "bg:#bbbbbb #000000"), + ("completion-menu.completion", ""), + # (Note: for the current completion, we use 'reverse' on top of fg/bg + # colors. This is to have proper rendering with NO_COLOR=1). + ("completion-menu.completion.current", "fg:#888888 bg:#ffffff reverse"), + ("completion-menu.meta.completion", "bg:#999999 #000000"), + ("completion-menu.meta.completion.current", "bg:#aaaaaa #000000"), + ("completion-menu.multi-column-meta", "bg:#aaaaaa #000000"), + # Fuzzy matches in completion menu (for FuzzyCompleter). + ("completion-menu.completion fuzzymatch.outside", "fg:#444444"), + ("completion-menu.completion fuzzymatch.inside", "bold"), + ("completion-menu.completion fuzzymatch.inside.character", "underline"), + ("completion-menu.completion.current fuzzymatch.outside", "fg:default"), + ("completion-menu.completion.current fuzzymatch.inside", "nobold"), + # Styling of readline-like completions. + ("readline-like-completions", ""), + ("readline-like-completions.completion", ""), + ("readline-like-completions.completion fuzzymatch.outside", "#888888"), + ("readline-like-completions.completion fuzzymatch.inside", ""), + ("readline-like-completions.completion fuzzymatch.inside.character", "underline"), + # Scrollbars. + ("scrollbar.background", "bg:#aaaaaa"), + ("scrollbar.button", "bg:#444444"), + ("scrollbar.arrow", "noinherit bold"), + # Start/end of scrollbars. Adding 'underline' here provides a nice little + # detail to the progress bar, but it doesn't look good on all terminals. + # ('scrollbar.start', 'underline #ffffff'), + # ('scrollbar.end', 'underline #000000'), + # Auto suggestion text. + ("auto-suggestion", "#666666"), + # Trailing whitespace and tabs. + ("trailing-whitespace", "#999999"), + ("tab", "#999999"), + # When Control-C/D has been pressed. Grayed. + ("aborting", "#888888 bg:default noreverse noitalic nounderline noblink"), + ("exiting", "#888888 bg:default noreverse noitalic nounderline noblink"), + # Entering a Vi digraph. + ("digraph", "#4444ff"), + # Control characters, like ^C, ^X. + ("control-character", "ansiblue"), + # Non-breaking space. + ("nbsp", "underline ansiyellow"), + # Default styling of HTML elements. + ("i", "italic"), + ("u", "underline"), + ("s", "strike"), + ("b", "bold"), + ("em", "italic"), + ("strong", "bold"), + ("del", "strike"), + ("hidden", "hidden"), + # It should be possible to use the style names in HTML. + # ... or .... + ("italic", "italic"), + ("underline", "underline"), + ("strike", "strike"), + ("bold", "bold"), + ("reverse", "reverse"), + ("noitalic", "noitalic"), + ("nounderline", "nounderline"), + ("nostrike", "nostrike"), + ("nobold", "nobold"), + ("noreverse", "noreverse"), + # Prompt bottom toolbar + ("bottom-toolbar", "reverse"), +] + + +# Style that will turn for instance the class 'red' into 'red'. +COLORS_STYLE = [(name, "fg:" + name) for name in ANSI_COLOR_NAMES] + [ + (name.lower(), "fg:" + name) for name in NAMED_COLORS +] + + +WIDGETS_STYLE = [ + # Dialog windows. + ("dialog", "bg:#4444ff"), + ("dialog.body", "bg:#ffffff #000000"), + ("dialog.body text-area", "bg:#cccccc"), + ("dialog.body text-area last-line", "underline"), + ("dialog frame.label", "#ff0000 bold"), + # Scrollbars in dialogs. + ("dialog.body scrollbar.background", ""), + ("dialog.body scrollbar.button", "bg:#000000"), + ("dialog.body scrollbar.arrow", ""), + ("dialog.body scrollbar.start", "nounderline"), + ("dialog.body scrollbar.end", "nounderline"), + # Buttons. + ("button", ""), + ("button.arrow", "bold"), + ("button.focused", "bg:#aa0000 #ffffff"), + # Menu bars. + ("menu-bar", "bg:#aaaaaa #000000"), + ("menu-bar.selected-item", "bg:#ffffff #000000"), + ("menu", "bg:#888888 #ffffff"), + ("menu.border", "#aaaaaa"), + ("menu.border shadow", "#444444"), + # Shadows. + ("dialog shadow", "bg:#000088"), + ("dialog.body shadow", "bg:#aaaaaa"), + ("progress-bar", "bg:#000088"), + ("progress-bar.used", "bg:#ff0000"), +] + + +# The default Pygments style, include this by default in case a Pygments lexer +# is used. +PYGMENTS_DEFAULT_STYLE = { + "pygments.whitespace": "#bbbbbb", + "pygments.comment": "italic #408080", + "pygments.comment.preproc": "noitalic #bc7a00", + "pygments.keyword": "bold #008000", + "pygments.keyword.pseudo": "nobold", + "pygments.keyword.type": "nobold #b00040", + "pygments.operator": "#666666", + "pygments.operator.word": "bold #aa22ff", + "pygments.name.builtin": "#008000", + "pygments.name.function": "#0000ff", + "pygments.name.class": "bold #0000ff", + "pygments.name.namespace": "bold #0000ff", + "pygments.name.exception": "bold #d2413a", + "pygments.name.variable": "#19177c", + "pygments.name.constant": "#880000", + "pygments.name.label": "#a0a000", + "pygments.name.entity": "bold #999999", + "pygments.name.attribute": "#7d9029", + "pygments.name.tag": "bold #008000", + "pygments.name.decorator": "#aa22ff", + # Note: In Pygments, Token.String is an alias for Token.Literal.String, + # and Token.Number as an alias for Token.Literal.Number. + "pygments.literal.string": "#ba2121", + "pygments.literal.string.doc": "italic", + "pygments.literal.string.interpol": "bold #bb6688", + "pygments.literal.string.escape": "bold #bb6622", + "pygments.literal.string.regex": "#bb6688", + "pygments.literal.string.symbol": "#19177c", + "pygments.literal.string.other": "#008000", + "pygments.literal.number": "#666666", + "pygments.generic.heading": "bold #000080", + "pygments.generic.subheading": "bold #800080", + "pygments.generic.deleted": "#a00000", + "pygments.generic.inserted": "#00a000", + "pygments.generic.error": "#ff0000", + "pygments.generic.emph": "italic", + "pygments.generic.strong": "bold", + "pygments.generic.prompt": "bold #000080", + "pygments.generic.output": "#888", + "pygments.generic.traceback": "#04d", + "pygments.error": "border:#ff0000", +} + + +@memoized() +def default_ui_style() -> BaseStyle: + """ + Create a default `Style` object. + """ + return merge_styles( + [ + Style(PROMPT_TOOLKIT_STYLE), + Style(COLORS_STYLE), + Style(WIDGETS_STYLE), + ] + ) + + +@memoized() +def default_pygments_style() -> Style: + """ + Create a `Style` object that contains the default Pygments style. + """ + return Style.from_dict(PYGMENTS_DEFAULT_STYLE) diff --git a/shared/package-files/7b/7b39b57496ee8a638b118464ffc2eb012d5117e8464f52a485afe16fcef6d2d6/blob b/shared/package-files/7b/7b39b57496ee8a638b118464ffc2eb012d5117e8464f52a485afe16fcef6d2d6/blob new file mode 100644 index 0000000000000000000000000000000000000000..2e6f83e2646afdd352e3bb1eaa769ed33b9cb30f --- /dev/null +++ b/shared/package-files/7b/7b39b57496ee8a638b118464ffc2eb012d5117e8464f52a485afe16fcef6d2d6/blob @@ -0,0 +1,350 @@ +#!/usr/bin/env python3 + +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +Unit test runner, providing new features on top of unittest module: +- colourized output +- parallel run (UNIX only) +- print failures/tracebacks on CTRL+C +- re-run failed tests only (make test-failed) + +Invocation examples: +- make test +- make test-failed + +Parallel: +- make test-parallel +- make test-process ARGS=--parallel +""" + +from __future__ import print_function + +import atexit +import optparse +import os +import sys +import textwrap +import time +import unittest + + +try: + import ctypes +except ImportError: + ctypes = None + +try: + import concurrencytest # pip install concurrencytest +except ImportError: + concurrencytest = None + +import psutil +from psutil._common import hilite +from psutil._common import print_color +from psutil._common import term_supports_colors +from psutil._compat import super +from psutil.tests import CI_TESTING +from psutil.tests import import_module_by_path +from psutil.tests import print_sysinfo +from psutil.tests import reap_children +from psutil.tests import safe_rmpath + + +VERBOSITY = 2 +FAILED_TESTS_FNAME = '.failed-tests.txt' +NWORKERS = psutil.cpu_count() or 1 +USE_COLORS = not CI_TESTING and term_supports_colors() + +HERE = os.path.abspath(os.path.dirname(__file__)) +loadTestsFromTestCase = unittest.defaultTestLoader.loadTestsFromTestCase + + +def cprint(msg, color, bold=False, file=None): + if file is None: + file = sys.stderr if color == 'red' else sys.stdout + if USE_COLORS: + print_color(msg, color, bold=bold, file=file) + else: + print(msg, file=file) + + +class TestLoader: + + testdir = HERE + skip_files = ['test_memleaks.py'] + if "WHEELHOUSE_UPLOADER_USERNAME" in os.environ: + skip_files.extend(['test_osx.py', 'test_linux.py', 'test_posix.py']) + + def _get_testmods(self): + return [os.path.join(self.testdir, x) + for x in os.listdir(self.testdir) + if x.startswith('test_') and x.endswith('.py') and + x not in self.skip_files] + + def _iter_testmod_classes(self): + """Iterate over all test files in this directory and return + all TestCase classes in them. + """ + for path in self._get_testmods(): + mod = import_module_by_path(path) + for name in dir(mod): + obj = getattr(mod, name) + if isinstance(obj, type) and \ + issubclass(obj, unittest.TestCase): + yield obj + + def all(self): + suite = unittest.TestSuite() + for obj in self._iter_testmod_classes(): + test = loadTestsFromTestCase(obj) + suite.addTest(test) + return suite + + def last_failed(self): + # ...from previously failed test run + suite = unittest.TestSuite() + if not os.path.isfile(FAILED_TESTS_FNAME): + return suite + with open(FAILED_TESTS_FNAME, 'rt') as f: + names = f.read().split() + for n in names: + test = unittest.defaultTestLoader.loadTestsFromName(n) + suite.addTest(test) + return suite + + def from_name(self, name): + if name.endswith('.py'): + name = os.path.splitext(os.path.basename(name))[0] + return unittest.defaultTestLoader.loadTestsFromName(name) + + +class ColouredResult(unittest.TextTestResult): + + def addSuccess(self, test): + unittest.TestResult.addSuccess(self, test) + cprint("OK", "green") + + def addError(self, test, err): + unittest.TestResult.addError(self, test, err) + cprint("ERROR", "red", bold=True) + + def addFailure(self, test, err): + unittest.TestResult.addFailure(self, test, err) + cprint("FAIL", "red") + + def addSkip(self, test, reason): + unittest.TestResult.addSkip(self, test, reason) + cprint("skipped: %s" % reason.strip(), "brown") + + def printErrorList(self, flavour, errors): + flavour = hilite(flavour, "red", bold=flavour == 'ERROR') + super().printErrorList(flavour, errors) + + +class ColouredTextRunner(unittest.TextTestRunner): + """ + A coloured text runner which also prints failed tests on KeyboardInterrupt + and save failed tests in a file so that they can be re-run. + """ + resultclass = ColouredResult if USE_COLORS else unittest.TextTestResult + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.failed_tnames = set() + + def _makeResult(self): + # Store result instance so that it can be accessed on + # KeyboardInterrupt. + self.result = super()._makeResult() + return self.result + + def _write_last_failed(self): + if self.failed_tnames: + with open(FAILED_TESTS_FNAME, 'wt') as f: + for tname in self.failed_tnames: + f.write(tname + '\n') + + def _save_result(self, result): + if not result.wasSuccessful(): + for t in result.errors + result.failures: + tname = t[0].id() + self.failed_tnames.add(tname) + + def _run(self, suite): + try: + result = super().run(suite) + except (KeyboardInterrupt, SystemExit): + result = self.runner.result + result.printErrors() + raise sys.exit(1) + else: + self._save_result(result) + return result + + def _exit(self, success): + if success: + cprint("SUCCESS", "green", bold=True) + safe_rmpath(FAILED_TESTS_FNAME) + sys.exit(0) + else: + cprint("FAILED", "red", bold=True) + self._write_last_failed() + sys.exit(1) + + def run(self, suite): + result = self._run(suite) + self._exit(result.wasSuccessful()) + + +class ParallelRunner(ColouredTextRunner): + + @staticmethod + def _parallelize(suite): + def fdopen(fd, mode, *kwds): + stream = orig_fdopen(fd, mode) + atexit.register(stream.close) + return stream + + # Monkey patch concurrencytest lib bug (fdopen() stream not closed). + # https://github.com/cgoldberg/concurrencytest/issues/11 + orig_fdopen = os.fdopen + concurrencytest.os.fdopen = fdopen + forker = concurrencytest.fork_for_tests(NWORKERS) + return concurrencytest.ConcurrentTestSuite(suite, forker) + + @staticmethod + def _split_suite(suite): + serial = unittest.TestSuite() + parallel = unittest.TestSuite() + for test in suite: + if test.countTestCases() == 0: + continue + elif isinstance(test, unittest.TestSuite): + test_class = test._tests[0].__class__ + elif isinstance(test, unittest.TestCase): + test_class = test + else: + raise TypeError("can't recognize type %r" % test) + + if getattr(test_class, '_serialrun', False): + serial.addTest(test) + else: + parallel.addTest(test) + return (serial, parallel) + + def run(self, suite): + ser_suite, par_suite = self._split_suite(suite) + par_suite = self._parallelize(par_suite) + + # run parallel + cprint("starting parallel tests using %s workers" % NWORKERS, + "green", bold=True) + t = time.time() + par = self._run(par_suite) + par_elapsed = time.time() - t + + # At this point we should have N zombies (the workers), which + # will disappear with wait(). + orphans = psutil.Process().children() + gone, alive = psutil.wait_procs(orphans, timeout=1) + if alive: + cprint("alive processes %s" % alive, "red") + reap_children() + + # run serial + t = time.time() + ser = self._run(ser_suite) + ser_elapsed = time.time() - t + + # print + if not par.wasSuccessful() and ser_suite.countTestCases() > 0: + par.printErrors() # print them again at the bottom + par_fails, par_errs, par_skips = map(len, (par.failures, + par.errors, + par.skipped)) + ser_fails, ser_errs, ser_skips = map(len, (ser.failures, + ser.errors, + ser.skipped)) + print(textwrap.dedent(""" + +----------+----------+----------+----------+----------+----------+ + | | total | failures | errors | skipped | time | + +----------+----------+----------+----------+----------+----------+ + | parallel | %3s | %3s | %3s | %3s | %.2fs | + +----------+----------+----------+----------+----------+----------+ + | serial | %3s | %3s | %3s | %3s | %.2fs | + +----------+----------+----------+----------+----------+----------+ + """ % (par.testsRun, par_fails, par_errs, par_skips, par_elapsed, + ser.testsRun, ser_fails, ser_errs, ser_skips, ser_elapsed))) + print("Ran %s tests in %.3fs using %s workers" % ( + par.testsRun + ser.testsRun, par_elapsed + ser_elapsed, NWORKERS)) + ok = par.wasSuccessful() and ser.wasSuccessful() + self._exit(ok) + + +def get_runner(parallel=False): + def warn(msg): + cprint(msg + " Running serial tests instead.", "red") + if parallel: + if psutil.WINDOWS: + warn("Can't run parallel tests on Windows.") + elif concurrencytest is None: + warn("concurrencytest module is not installed.") + elif NWORKERS == 1: + warn("Only 1 CPU available.") + else: + return ParallelRunner(verbosity=VERBOSITY) + return ColouredTextRunner(verbosity=VERBOSITY) + + +# Used by test_*,py modules. +def run_from_name(name): + if CI_TESTING: + print_sysinfo() + suite = TestLoader().from_name(name) + runner = get_runner() + runner.run(suite) + + +def setup(): + psutil._set_debug(True) + + +def main(): + setup() + usage = "python3 -m psutil.tests [opts] [test-name]" + parser = optparse.OptionParser(usage=usage, description="run unit tests") + parser.add_option("--last-failed", + action="store_true", default=False, + help="only run last failed tests") + parser.add_option("--parallel", + action="store_true", default=False, + help="run tests in parallel") + opts, args = parser.parse_args() + + if not opts.last_failed: + safe_rmpath(FAILED_TESTS_FNAME) + + # loader + loader = TestLoader() + if args: + if len(args) > 1: + parser.print_usage() + return sys.exit(1) + else: + suite = loader.from_name(args[0]) + elif opts.last_failed: + suite = loader.last_failed() + else: + suite = loader.all() + + if CI_TESTING: + print_sysinfo() + runner = get_runner(opts.parallel) + runner.run(suite) + + +if __name__ == '__main__': + main() diff --git a/shared/package-files/7b/7b3e0546f37929a4a8b09789d96cd4c8a743760df91c3cbf4922cf5ca09db793/blob b/shared/package-files/7b/7b3e0546f37929a4a8b09789d96cd4c8a743760df91c3cbf4922cf5ca09db793/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d36e64c467ca8d9cadc88ab03da71faf1aa8abb --- /dev/null +++ b/shared/package-files/7b/7b3e0546f37929a4a8b09789d96cd4c8a743760df91c3cbf4922cf5ca09db793/blob @@ -0,0 +1,16 @@ +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + # TypedDict was introduced in Python 3.8. + # + # TODO: Remove the else block and TYPE_CHECKING check when dropping support + # for Python 3.7. + from typing import TypedDict + + class ResultDict(TypedDict): + encoding: Optional[str] + confidence: float + language: Optional[str] + +else: + ResultDict = dict diff --git a/shared/package-files/7b/7b408145e96088048219d07534544c4abd3805b6a0823c8701962f994521d6c3/blob b/shared/package-files/7b/7b408145e96088048219d07534544c4abd3805b6a0823c8701962f994521d6c3/blob new file mode 100644 index 0000000000000000000000000000000000000000..3eb058015cd3da081e3c34954c0bd3229337de31 --- /dev/null +++ b/shared/package-files/7b/7b408145e96088048219d07534544c4abd3805b6a0823c8701962f994521d6c3/blob @@ -0,0 +1,72 @@ +import numpy as np + +from pandas import ( + DataFrame, + MultiIndex, + Series, +) +import pandas._testing as tm + + +class TestDataFramePop: + def test_pop(self, float_frame, warn_copy_on_write): + float_frame.columns.name = "baz" + + float_frame.pop("A") + assert "A" not in float_frame + + float_frame["foo"] = "bar" + float_frame.pop("foo") + assert "foo" not in float_frame + assert float_frame.columns.name == "baz" + + # gh-10912: inplace ops cause caching issue + a = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"], index=["X", "Y"]) + b = a.pop("B") + with tm.assert_cow_warning(warn_copy_on_write): + b += 1 + + # original frame + expected = DataFrame([[1, 3], [4, 6]], columns=["A", "C"], index=["X", "Y"]) + tm.assert_frame_equal(a, expected) + + # result + expected = Series([2, 5], index=["X", "Y"], name="B") + 1 + tm.assert_series_equal(b, expected) + + def test_pop_non_unique_cols(self): + df = DataFrame({0: [0, 1], 1: [0, 1], 2: [4, 5]}) + df.columns = ["a", "b", "a"] + + res = df.pop("a") + assert type(res) == DataFrame + assert len(res) == 2 + assert len(df.columns) == 1 + assert "b" in df.columns + assert "a" not in df.columns + assert len(df.index) == 2 + + def test_mixed_depth_pop(self): + arrays = [ + ["a", "top", "top", "routine1", "routine1", "routine2"], + ["", "OD", "OD", "result1", "result2", "result1"], + ["", "wx", "wy", "", "", ""], + ] + + tuples = sorted(zip(*arrays)) + index = MultiIndex.from_tuples(tuples) + df = DataFrame(np.random.default_rng(2).standard_normal((4, 6)), columns=index) + + df1 = df.copy() + df2 = df.copy() + result = df1.pop("a") + expected = df2.pop(("a", "", "")) + tm.assert_series_equal(expected, result, check_names=False) + tm.assert_frame_equal(df1, df2) + assert result.name == "a" + + expected = df1["top"] + df1 = df1.drop(["top"], axis=1) + result = df2.pop("top") + tm.assert_frame_equal(expected, result) + tm.assert_frame_equal(df1, df2) diff --git a/shared/package-files/7b/7b40aaa273fc81a46fa40df0e3ea468f8874acaab55a0bdf78211edb4d1a032f/blob b/shared/package-files/7b/7b40aaa273fc81a46fa40df0e3ea468f8874acaab55a0bdf78211edb4d1a032f/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d9afd34ee4ad9bf8254ef02850d035faf7a961b --- /dev/null +++ b/shared/package-files/7b/7b40aaa273fc81a46fa40df0e3ea468f8874acaab55a0bdf78211edb4d1a032f/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API signbit { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::signbit") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "signbit(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API signbit_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::signbit") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7b/7b45f97630b1870dd80c58a7d88cd4dd129dffb84cdc6e71569b359751250274/blob b/shared/package-files/7b/7b45f97630b1870dd80c58a7d88cd4dd129dffb84cdc6e71569b359751250274/blob new file mode 100644 index 0000000000000000000000000000000000000000..1fc1aeb49e8f8bffc9ea91fa8f642ab200fa4ee0 --- /dev/null +++ b/shared/package-files/7b/7b45f97630b1870dd80c58a7d88cd4dd129dffb84cdc6e71569b359751250274/blob @@ -0,0 +1,405 @@ +""" +Helper functions for managing the Matplotlib API. + +This documentation is only relevant for Matplotlib developers, not for users. + +.. warning:: + + This module and its submodules are for internal use only. Do not use them + in your own code. We may change the API at any time with no warning. + +""" + +import functools +import itertools +import pathlib +import re +import sys +import warnings + +from .deprecation import ( # noqa: F401 + deprecated, warn_deprecated, + rename_parameter, delete_parameter, make_keyword_only, + deprecate_method_override, deprecate_privatize_attribute, + suppress_matplotlib_deprecation_warning, + MatplotlibDeprecationWarning) + + +class classproperty: + """ + Like `property`, but also triggers on access via the class, and it is the + *class* that's passed as argument. + + Examples + -------- + :: + + class C: + @classproperty + def foo(cls): + return cls.__name__ + + assert C.foo == "C" + """ + + def __init__(self, fget, fset=None, fdel=None, doc=None): + self._fget = fget + if fset is not None or fdel is not None: + raise ValueError('classproperty only implements fget.') + self.fset = fset + self.fdel = fdel + # docs are ignored for now + self._doc = doc + + def __get__(self, instance, owner): + return self._fget(owner) + + @property + def fget(self): + return self._fget + + +# In the following check_foo() functions, the first parameter is positional-only to make +# e.g. `_api.check_isinstance([...], types=foo)` work. + +def check_isinstance(types, /, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* is an instance + of one of *types*; if not, raise an appropriate TypeError. + + As a special case, a ``None`` entry in *types* is treated as NoneType. + + Examples + -------- + >>> _api.check_isinstance((SomeClass, None), arg=arg) + """ + none_type = type(None) + types = ((types,) if isinstance(types, type) else + (none_type,) if types is None else + tuple(none_type if tp is None else tp for tp in types)) + + def type_name(tp): + return ("None" if tp is none_type + else tp.__qualname__ if tp.__module__ == "builtins" + else f"{tp.__module__}.{tp.__qualname__}") + + for k, v in kwargs.items(): + if not isinstance(v, types): + names = [*map(type_name, types)] + if "None" in names: # Move it to the end for better wording. + names.remove("None") + names.append("None") + raise TypeError( + "{!r} must be an instance of {}, not a {}".format( + k, + ", ".join(names[:-1]) + " or " + names[-1] + if len(names) > 1 else names[0], + type_name(type(v)))) + + +def check_in_list(values, /, *, _print_supported_values=True, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* is in *values*; + if not, raise an appropriate ValueError. + + Parameters + ---------- + values : iterable + Sequence of values to check on. + + Note: All values must support == comparisons. + This means in particular the entries must not be numpy arrays. + _print_supported_values : bool, default: True + Whether to print *values* when raising ValueError. + **kwargs : dict + *key, value* pairs as keyword arguments to find in *values*. + + Raises + ------ + ValueError + If any *value* in *kwargs* is not found in *values*. + + Examples + -------- + >>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg) + """ + if not kwargs: + raise TypeError("No argument to check!") + for key, val in kwargs.items(): + try: + exists = val in values + except ValueError: + # `in` internally uses `val == values[i]`. There are some objects + # that do not support == to arbitrary other objects, in particular + # numpy arrays. + # Since such objects are not allowed in values, we can gracefully + # handle the case that val (typically provided by users) is of such + # type and directly state it's not in the list instead of letting + # the individual `val == values[i]` ValueError surface. + exists = False + if not exists: + msg = f"{val!r} is not a valid value for {key}" + if _print_supported_values: + msg += f"; supported values are {', '.join(map(repr, values))}" + raise ValueError(msg) + + +def check_shape(shape, /, **kwargs): + """ + For each *key, value* pair in *kwargs*, check that *value* has the shape *shape*; + if not, raise an appropriate ValueError. + + *None* in the shape is treated as a "free" size that can have any length. + e.g. (None, 2) -> (N, 2) + + The values checked must be numpy arrays. + + Examples + -------- + To check for (N, 2) shaped arrays + + >>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg) + """ + for k, v in kwargs.items(): + data_shape = v.shape + + if (len(data_shape) != len(shape) + or any(s != t and t is not None for s, t in zip(data_shape, shape))): + dim_labels = iter(itertools.chain( + 'NMLKJIH', + (f"D{i}" for i in itertools.count()))) + text_shape = ", ".join([str(n) if n is not None else next(dim_labels) + for n in shape[::-1]][::-1]) + if len(shape) == 1: + text_shape += "," + + raise ValueError( + f"{k!r} must be {len(shape)}D with shape ({text_shape}), " + f"but your input has shape {v.shape}" + ) + + +def check_getitem(mapping, /, **kwargs): + """ + *kwargs* must consist of a single *key, value* pair. If *key* is in + *mapping*, return ``mapping[value]``; else, raise an appropriate + ValueError. + + Examples + -------- + >>> _api.check_getitem({"foo": "bar"}, arg=arg) + """ + if len(kwargs) != 1: + raise ValueError("check_getitem takes a single keyword argument") + (k, v), = kwargs.items() + try: + return mapping[v] + except KeyError: + raise ValueError( + f"{v!r} is not a valid value for {k}; supported values are " + f"{', '.join(map(repr, mapping))}") from None + + +def caching_module_getattr(cls): + """ + Helper decorator for implementing module-level ``__getattr__`` as a class. + + This decorator must be used at the module toplevel as follows:: + + @caching_module_getattr + class __getattr__: # The class *must* be named ``__getattr__``. + @property # Only properties are taken into account. + def name(self): ... + + The ``__getattr__`` class will be replaced by a ``__getattr__`` + function such that trying to access ``name`` on the module will + resolve the corresponding property (which may be decorated e.g. with + ``_api.deprecated`` for deprecating module globals). The properties are + all implicitly cached. Moreover, a suitable AttributeError is generated + and raised if no property with the given name exists. + """ + + assert cls.__name__ == "__getattr__" + # Don't accidentally export cls dunders. + props = {name: prop for name, prop in vars(cls).items() + if isinstance(prop, property)} + instance = cls() + + @functools.cache + def __getattr__(name): + if name in props: + return props[name].__get__(instance) + raise AttributeError( + f"module {cls.__module__!r} has no attribute {name!r}") + + return __getattr__ + + +def define_aliases(alias_d, cls=None): + """ + Class decorator for defining property aliases. + + Use as :: + + @_api.define_aliases({"property": ["alias", ...], ...}) + class C: ... + + For each property, if the corresponding ``get_property`` is defined in the + class so far, an alias named ``get_alias`` will be defined; the same will + be done for setters. If neither the getter nor the setter exists, an + exception will be raised. + + The alias map is stored as the ``_alias_map`` attribute on the class and + can be used by `.normalize_kwargs` (which assumes that higher priority + aliases come last). + """ + if cls is None: # Return the actual class decorator. + return functools.partial(define_aliases, alias_d) + + def make_alias(name): # Enforce a closure over *name*. + @functools.wraps(getattr(cls, name)) + def method(self, *args, **kwargs): + return getattr(self, name)(*args, **kwargs) + return method + + for prop, aliases in alias_d.items(): + exists = False + for prefix in ["get_", "set_"]: + if prefix + prop in vars(cls): + exists = True + for alias in aliases: + method = make_alias(prefix + prop) + method.__name__ = prefix + alias + method.__doc__ = f"Alias for `{prefix + prop}`." + setattr(cls, prefix + alias, method) + if not exists: + raise ValueError( + f"Neither getter nor setter exists for {prop!r}") + + def get_aliased_and_aliases(d): + return {*d, *(alias for aliases in d.values() for alias in aliases)} + + preexisting_aliases = getattr(cls, "_alias_map", {}) + conflicting = (get_aliased_and_aliases(preexisting_aliases) + & get_aliased_and_aliases(alias_d)) + if conflicting: + # Need to decide on conflict resolution policy. + raise NotImplementedError( + f"Parent class already defines conflicting aliases: {conflicting}") + cls._alias_map = {**preexisting_aliases, **alias_d} + return cls + + +def select_matching_signature(funcs, *args, **kwargs): + """ + Select and call the function that accepts ``*args, **kwargs``. + + *funcs* is a list of functions which should not raise any exception (other + than `TypeError` if the arguments passed do not match their signature). + + `select_matching_signature` tries to call each of the functions in *funcs* + with ``*args, **kwargs`` (in the order in which they are given). Calls + that fail with a `TypeError` are silently skipped. As soon as a call + succeeds, `select_matching_signature` returns its return value. If no + function accepts ``*args, **kwargs``, then the `TypeError` raised by the + last failing call is re-raised. + + Callers should normally make sure that any ``*args, **kwargs`` can only + bind a single *func* (to avoid any ambiguity), although this is not checked + by `select_matching_signature`. + + Notes + ----- + `select_matching_signature` is intended to help implementing + signature-overloaded functions. In general, such functions should be + avoided, except for back-compatibility concerns. A typical use pattern is + :: + + def my_func(*args, **kwargs): + params = select_matching_signature( + [lambda old1, old2: locals(), lambda new: locals()], + *args, **kwargs) + if "old1" in params: + warn_deprecated(...) + old1, old2 = params.values() # note that locals() is ordered. + else: + new, = params.values() + # do things with params + + which allows *my_func* to be called either with two parameters (*old1* and + *old2*) or a single one (*new*). Note that the new signature is given + last, so that callers get a `TypeError` corresponding to the new signature + if the arguments they passed in do not match any signature. + """ + # Rather than relying on locals() ordering, one could have just used func's + # signature (``bound = inspect.signature(func).bind(*args, **kwargs); + # bound.apply_defaults(); return bound``) but that is significantly slower. + for i, func in enumerate(funcs): + try: + return func(*args, **kwargs) + except TypeError: + if i == len(funcs) - 1: + raise + + +def nargs_error(name, takes, given): + """Generate a TypeError to be raised by function calls with wrong arity.""" + return TypeError(f"{name}() takes {takes} positional arguments but " + f"{given} were given") + + +def kwarg_error(name, kw): + """ + Generate a TypeError to be raised by function calls with wrong kwarg. + + Parameters + ---------- + name : str + The name of the calling function. + kw : str or Iterable[str] + Either the invalid keyword argument name, or an iterable yielding + invalid keyword arguments (e.g., a ``kwargs`` dict). + """ + if not isinstance(kw, str): + kw = next(iter(kw)) + return TypeError(f"{name}() got an unexpected keyword argument '{kw}'") + + +def recursive_subclasses(cls): + """Yield *cls* and direct and indirect subclasses of *cls*.""" + yield cls + for subcls in cls.__subclasses__(): + yield from recursive_subclasses(subcls) + + +def warn_external(message, category=None): + """ + `warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib". + + The original emitter of the warning can be obtained by patching this + function back to `warnings.warn`, i.e. ``_api.warn_external = + warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``, + etc.). + """ + kwargs = {} + if sys.version_info[:2] >= (3, 12): + # Go to Python's `site-packages` or `lib` from an editable install. + basedir = pathlib.Path(__file__).parents[2] + kwargs['skip_file_prefixes'] = (str(basedir / 'matplotlib'), + str(basedir / 'mpl_toolkits')) + else: + frame = sys._getframe() + for stacklevel in itertools.count(1): + if frame is None: + # when called in embedded context may hit frame is None + kwargs['stacklevel'] = stacklevel + break + if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))", + # Work around sphinx-gallery not setting __name__. + frame.f_globals.get("__name__", "")): + kwargs['stacklevel'] = stacklevel + break + frame = frame.f_back + # preemptively break reference cycle between locals and the frame + del frame + warnings.warn(message, category, **kwargs) diff --git a/shared/package-files/7b/7b468cedaec2a50de7dd5325346f1837f5880f4a127dd2b61a8899464c6e8960/blob b/shared/package-files/7b/7b468cedaec2a50de7dd5325346f1837f5880f4a127dd2b61a8899464c6e8960/blob new file mode 100644 index 0000000000000000000000000000000000000000..d0fa9f979a98372dfca3cfe9c33f3aa549b9e6d8 --- /dev/null +++ b/shared/package-files/7b/7b468cedaec2a50de7dd5325346f1837f5880f4a127dd2b61a8899464c6e8960/blob @@ -0,0 +1,1136 @@ +""" +SARIMAX specification class + +Author: Chad Fulton +License: BSD-3 +""" +import numpy as np +import pandas as pd + +from statsmodels.tools.data import _is_using_pandas +from statsmodels.tools.validation import string_like +from statsmodels.tsa.arima.tools import standardize_lag_order, validate_basic +from statsmodels.tsa.base.tsa_model import TimeSeriesModel +from statsmodels.tsa.statespace.tools import ( + constrain_stationary_univariate as constrain, + is_invertible, + prepare_exog, + prepare_trend_data, + prepare_trend_spec, + unconstrain_stationary_univariate as unconstrain, +) + + +class SARIMAXSpecification: + """ + SARIMAX specification + + Parameters + ---------- + endog : array_like, optional + The observed time-series process :math:`y`. + exog : array_like, optional + Array of exogenous regressors. + order : tuple, optional + The (p,d,q) order of the model for the autoregressive, differences, and + moving average components. d is always an integer, while p and q may + either be integers or lists of integers. May not be used in combination + with the arguments `ar_order`, `diff`, or `ma_order`. + seasonal_order : tuple, optional + The (P,D,Q,s) order of the seasonal component of the model for the + AR parameters, differences, MA parameters, and periodicity. Default + is (0, 0, 0, 0). D and s are always integers, while P and Q + may either be integers or lists of positive integers. May not be used + in combination with the arguments `seasonal_ar_order`, `seasonal_diff`, + or `seasonal_ma_order`. + ar_order : int or list of int, optional + The autoregressive order of the model. May be an integer, in which case + all autoregressive lags up to and including it will be included. + Alternatively, may be a list of integers specifying which lag orders + are included. May not be used in combination with `order`. + diff : int, optional + The order of integration of the model. May not be used in combination + with `order`. + ma_order : int or list of int, optional + The moving average order of the model. May be an integer or + list of integers. See the documentation for `ar_order` for details. + May not be used in combination with `order`. + seasonal_ar_order : int or list of int, optional + The seasonal autoregressive order of the model. May be an integer or + list of integers. See the documentation for `ar_order` for examples. + Note that if `seasonal_periods = 4` and `seasonal_ar_order = 2`, then + this implies that the overall model will include lags 4 and 8. + May not be used in combination with `seasonal_order`. + seasonal_diff : int, optional + The order of seasonal integration of the model. May not be used in + combination with `seasonal_order`. + seasonal_ma_order : int or list of int, optional + The moving average order of the model. May be an integer or + list of integers. See the documentation for `ar_order` and + `seasonal_ar_order` for additional details. May not be used in + combination with `seasonal_order`. + seasonal_periods : int, optional + Number of periods in a season. May not be used in combination with + `seasonal_order`. + trend : {'n', 'c', 't', 'ct', 'ctt'} or array_like, optional + Parameter controlling the deterministic trend polynomial :math:`A(t)`. + Can be specified as a string where 'n' indicates no trend, 'c' + indicates a constant (i.e., a degree zero component of the trend + polynomial), 't' indicates a linear trend with time, 'ct' includes + both, and 'ctt' includes a constant, linear trend, and squared time + trend. Can also be specified as an array_like defining the polynomial + as in `numpy.poly1d`, where `[1,1,0,1]` would denote + :math:`a + bt + ct^3`. Default is to not include a trend component. + enforce_stationarity : bool, optional + Whether or not to require the autoregressive parameters to correspond + to a stationarity process. This is only possible in estimation by + numerical maximum likelihood. + enforce_invertibility : bool, optional + Whether or not to require the moving average parameters to correspond + to an invertible process. This is only possible in estimation by + numerical maximum likelihood. + concentrate_scale : bool, optional + Whether or not to concentrate the scale (variance of the error term) + out of the likelihood. This reduces the number of parameters by one. + This is only applicable when considering estimation by numerical + maximum likelihood. + trend_offset : int, optional + The offset at which to start time trend values. Default is 1, so that + if `trend='t'` the trend is equal to 1, 2, ..., nobs. Typically is + only set when the model created by extending a previous dataset. + dates : array_like of datetime, optional + If no index is given by `endog` or `exog`, an array-like object of + datetime objects can be provided. + freq : str, optional + If no index is given by `endog` or `exog`, the frequency of the + time-series may be specified here as a Pandas offset or offset string. + missing : str, optional + Available options are 'none', 'drop', and 'raise'. If 'none', no nan + checking is done. If 'drop', any observations with nans are dropped. + If 'raise', an error is raised. Default is 'none'. + validate_specification : bool, optional + Whether or not to validate the model specification, e.g., that there + is no overlap between the given AR and seasonal AR terms, that the + differencing orders and seasonal periodicity are not invalid, and + that the trend does not duplicate a constant column already present + in `exog`. Default is True. + validate_exog : bool, optional + Whether or not to check that `exog` does not contain a constant column + that duplicates a constant trend. Has no effect unless + `validate_specification` is True. This is separated out so that it can + be disabled when extending an already-validated model with data that is + constant only over the extension window. Default is True. + + Attributes + ---------- + order : tuple + The (p,d,q) order of the model for the autoregressive, differences, and + moving average components. d is always an integer, while p and q may + either be integers or lists of integers. + seasonal_order : tuple + The (P,D,Q,s) order of the seasonal component of the model for the + AR parameters, differences, MA parameters, and periodicity. Default + is (0, 0, 0, 0). D and s are always integers, while P and Q + may either be integers or lists of positive integers. + ar_order : int or list of int + The autoregressive order of the model. May be an integer, in which case + all autoregressive lags up to and including it will be included. For + example, if `ar_order = 3`, then the model will include lags 1, 2, + and 3. Alternatively, may be a list of integers specifying exactly + which lag orders are included. For example, if `ar_order = [1, 3]`, + then the model will include lags 1 and 3 but will exclude lag 2. + diff : int + The order of integration of the model. + ma_order : int or list of int + The moving average order of the model. May be an integer or + list of integers. See the documentation for `ar_order` for examples. + seasonal_ar_order : int or list of int + The seasonal autoregressive order of the model. May be an integer or + list of integers. See the documentation for `ar_order` for examples. + Note that if `seasonal_periods = 4` and `seasonal_ar_order = 2`, then + this implies that the overall model will include lags 4 and 8. + seasonal_diff : int + The order of seasonal integration of the model. + seasonal_ma_order : int or list of int + The moving average order of the model. May be an integer or + list of integers. See the documentation for `ar_order` and + `seasonal_ar_order` for additional details. + seasonal_periods : int + Number of periods in a season. + trend : {'n', 'c', 't', 'ct', 'ctt'} or array_like + Parameter controlling the deterministic trend polynomial :math:`A(t)`. + Can be specified as a string where 'n' indicates no trend, 'c' + indicates a constant (i.e., a degree zero component of the trend + polynomial), 't' indicates a linear trend with time, 'ct' includes + both, and 'ctt' includes a constant, linear trend, and squared time + trend. Can also be specified as an array_like defining the polynomial + as in `numpy.poly1d`, where `[1,1,0,1]` would denote + :math:`a + bt + ct^3`. Default is to not include a trend component. + ar_lags : list of int + List of included autoregressive lags. If `ar_order` is a list, then + `ar_lags == ar_order`. If `ar_lags = [1, 2]`, then the overall model + will include the 1st and 2nd autoregressive lags. + ma_lags : list of int + List of included moving average lags. If `ma_order` is a list, then + `ma_lags == ma_order`. If `ma_lags = [1, 2]`, then the overall model + will include the 1st and 2nd moving average lags. + seasonal_ar_lags : list of int + List of included seasonal autoregressive lags. If `seasonal_ar_order` + is a list, then `seasonal_ar_lags == seasonal_ar_order`. If + `seasonal_periods = 4` and `seasonal_ar_lags = [1, 2]`, then the + overall model will include the 4th and 8th autoregressive lags. + seasonal_ma_lags : list of int + List of included seasonal moving average lags. If `seasonal_ma_order` + is a list, then `seasonal_ma_lags == seasonal_ma_order`. See the + documentation to `seasonal_ar_lags` for examples. + max_ar_order : int + Largest included autoregressive lag. + max_ma_order : int + Largest included moving average lag. + max_seasonal_ar_order : int + Largest included seasonal autoregressive lag. + max_seasonal_ma_order : int + Largest included seasonal moving average lag. + max_reduced_ar_order : int + Largest lag in the reduced autoregressive polynomial. Equal to + `max_ar_order + max_seasonal_ar_order * seasonal_periods`. + max_reduced_ma_order : int + Largest lag in the reduced moving average polynomial. Equal to + `max_ma_order + max_seasonal_ma_order * seasonal_periods`. + enforce_stationarity : bool + Whether or not to transform the AR parameters to enforce stationarity + in the autoregressive component of the model. This is only possible + in estimation by numerical maximum likelihood. + enforce_invertibility : bool + Whether or not to transform the MA parameters to enforce invertibility + in the moving average component of the model. This is only possible + in estimation by numerical maximum likelihood. + concentrate_scale : bool + Whether or not to concentrate the variance (scale term) out of the + log-likelihood function. This is only applicable when considering + estimation by numerical maximum likelihood. + is_ar_consecutive + is_ma_consecutive + is_integrated + is_seasonal + k_exog_params + k_ar_params + k_ma_params + k_seasonal_ar_params + k_seasonal_ma_params + k_params + exog_names + ar_names + ma_names + seasonal_ar_names + seasonal_ma_names + param_names + + Examples + -------- + >>> SARIMAXSpecification(order=(1, 0, 2)) + SARIMAXSpecification(order=(1, 0, 2)) + + >>> SARIMAXSpecification(ar_order=1, ma_order=2) + SARIMAXSpecification(order=(1, 0, 2)) + + >>> SARIMAXSpecification(ar_order=1, seasonal_order=(1, 0, 0, 4)) + SARIMAXSpecification(order=(1, 0, 0), seasonal_order=(1, 0, 0, 4)) + """ + + def __init__(self, endog=None, exog=None, order=None, + seasonal_order=None, ar_order=None, diff=None, ma_order=None, + seasonal_ar_order=None, seasonal_diff=None, + seasonal_ma_order=None, seasonal_periods=None, trend=None, + enforce_stationarity=None, enforce_invertibility=None, + concentrate_scale=None, trend_offset=1, dates=None, freq=None, + missing="none", validate_specification=True, *, + validate_exog=True): + + # Basic parameters + self.enforce_stationarity = enforce_stationarity + self.enforce_invertibility = enforce_invertibility + self.concentrate_scale = concentrate_scale + self.trend_offset = trend_offset + + # Validate that we were not given conflicting specifications + has_order = order is not None + has_specific_order = (ar_order is not None or diff is not None or + ma_order is not None) + has_seasonal_order = seasonal_order is not None + has_specific_seasonal_order = (seasonal_ar_order is not None or + seasonal_diff is not None or + seasonal_ma_order is not None or + seasonal_periods is not None) + if has_order and has_specific_order: + raise ValueError("Cannot specify both `order` and either of" + " `ar_order` or `ma_order`.") + if has_seasonal_order and has_specific_seasonal_order: + raise ValueError("Cannot specify both `seasonal_order` and any of" + " `seasonal_ar_order`, `seasonal_ma_order`," + " or `seasonal_periods`.") + + # Compute `order` + if has_specific_order: + ar_order = 0 if ar_order is None else ar_order + diff = 0 if diff is None else diff + ma_order = 0 if ma_order is None else ma_order + order = (ar_order, diff, ma_order) + elif not has_order: + order = (0, 0, 0) + + # Compute `seasonal_order` + if has_specific_seasonal_order: + seasonal_ar_order = ( + 0 if seasonal_ar_order is None else seasonal_ar_order) + seasonal_diff = 0 if seasonal_diff is None else seasonal_diff + seasonal_ma_order = ( + 0 if seasonal_ma_order is None else seasonal_ma_order) + seasonal_periods = ( + 0 if seasonal_periods is None else seasonal_periods) + seasonal_order = (seasonal_ar_order, seasonal_diff, + seasonal_ma_order, seasonal_periods) + elif not has_seasonal_order: + seasonal_order = (0, 0, 0, 0) + + # Validate shapes of `order`, `seasonal_order` + if len(order) != 3: + raise ValueError("`order` argument must be an iterable with three" + " elements.") + if len(seasonal_order) != 4: + raise ValueError("`seasonal_order` argument must be an iterable" + " with four elements.") + + # Validate differencing parameters + if validate_specification: + if order[1] < 0: + raise ValueError("Cannot specify negative differencing.") + if order[1] != int(order[1]): + raise ValueError("Cannot specify fractional differencing.") + if seasonal_order[1] < 0: + raise ValueError("Cannot specify negative seasonal" + " differencing.") + if seasonal_order[1] != int(seasonal_order[1]): + raise ValueError("Cannot specify fractional seasonal" + " differencing.") + if seasonal_order[3] < 0: + raise ValueError("Cannot specify negative seasonal" + " periodicity.") + + # Standardize to integers or lists of integers + order = ( + standardize_lag_order(order[0], "AR"), + int(order[1]), + standardize_lag_order(order[2], "MA")) + seasonal_order = ( + standardize_lag_order(seasonal_order[0], "seasonal AR"), + int(seasonal_order[1]), + standardize_lag_order(seasonal_order[2], "seasonal MA"), + int(seasonal_order[3])) + + # Validate seasonals + if validate_specification: + if seasonal_order[3] == 1: + raise ValueError("Seasonal periodicity must be greater" + " than 1.") + if ((seasonal_order[0] != 0 or seasonal_order[1] != 0 or + seasonal_order[2] != 0) and seasonal_order[3] == 0): + raise ValueError("Must include nonzero seasonal periodicity if" + " including seasonal AR, MA, or" + " differencing.") + + # Basic order + self.order = order + self.ar_order, self.diff, self.ma_order = order + + self.seasonal_order = seasonal_order + (self.seasonal_ar_order, self.seasonal_diff, self.seasonal_ma_order, + self.seasonal_periods) = seasonal_order + + # Lists of included lags + if isinstance(self.ar_order, list): + self.ar_lags = self.ar_order + else: + self.ar_lags = np.arange(1, self.ar_order + 1).tolist() + if isinstance(self.ma_order, list): + self.ma_lags = self.ma_order + else: + self.ma_lags = np.arange(1, self.ma_order + 1).tolist() + + if isinstance(self.seasonal_ar_order, list): + self.seasonal_ar_lags = self.seasonal_ar_order + else: + self.seasonal_ar_lags = ( + np.arange(1, self.seasonal_ar_order + 1).tolist()) + if isinstance(self.seasonal_ma_order, list): + self.seasonal_ma_lags = self.seasonal_ma_order + else: + self.seasonal_ma_lags = ( + np.arange(1, self.seasonal_ma_order + 1).tolist()) + + # Maximum lag orders + self.max_ar_order = self.ar_lags[-1] if self.ar_lags else 0 + self.max_ma_order = self.ma_lags[-1] if self.ma_lags else 0 + + self.max_seasonal_ar_order = ( + self.seasonal_ar_lags[-1] if self.seasonal_ar_lags else 0) + self.max_seasonal_ma_order = ( + self.seasonal_ma_lags[-1] if self.seasonal_ma_lags else 0) + + self.max_reduced_ar_order = ( + self.max_ar_order + + self.max_seasonal_ar_order * self.seasonal_periods) + self.max_reduced_ma_order = ( + self.max_ma_order + + self.max_seasonal_ma_order * self.seasonal_periods) + + # Check that we don't have duplicate AR or MA lags from the seasonal + # component + ar_lags = set(self.ar_lags) + seasonal_ar_lags = set(np.array(self.seasonal_ar_lags) + * self.seasonal_periods) + duplicate_ar_lags = ar_lags.intersection(seasonal_ar_lags) + if validate_specification and len(duplicate_ar_lags) > 0: + raise ValueError(f"Invalid model: autoregressive lag(s) {duplicate_ar_lags} are" + " in both the seasonal and non-seasonal" + " autoregressive components.") + + ma_lags = set(self.ma_lags) + seasonal_ma_lags = set(np.array(self.seasonal_ma_lags) + * self.seasonal_periods) + duplicate_ma_lags = ma_lags.intersection(seasonal_ma_lags) + if validate_specification and len(duplicate_ma_lags) > 0: + raise ValueError(f"Invalid model: moving average lag(s) {duplicate_ma_lags} are" + " in both the seasonal and non-seasonal" + " moving average components.") + + # Handle trend + self.trend = trend + self.trend_poly, _ = prepare_trend_spec(trend) + + # Check for a constant column in the provided exog + exog_is_pandas = _is_using_pandas(exog, None) + if (validate_specification and validate_exog and exog is not None and + len(self.trend_poly) > 0 and self.trend_poly[0] == 1): + # Figure out if we have any constant columns + x = np.asanyarray(exog) + ptp0 = np.ptp(x, axis=0) + col_is_const = ptp0 == 0 + nz_const = col_is_const & (x[0] != 0) + col_const = nz_const + + # If we already have a constant column, raise an error + if np.any(col_const): + raise ValueError("A constant trend was included in the model" + " specification, but the `exog` data already" + " contains a column of constants.") + + # This contains the included exponents of the trend polynomial, + # where e.g., the constant term has exponent 0, a linear trend has + # exponent 1, etc. + self.trend_terms = np.where(self.trend_poly == 1)[0] + # Trend order is either the degree of the trend polynomial, if all + # exponents are included, or a list of included exponents. Here we need + # to make a distinction between a degree zero polynomial (i.e., a + # constant) and the zero polynomial (i.e., not even a constant). The + # former has `trend_order = 0`, while the latter has + # `trend_order = None`. + self.k_trend = len(self.trend_terms) + if len(self.trend_terms) == 0: + self.trend_order = None + self.trend_degree = None + elif np.all(self.trend_terms == np.arange(len(self.trend_terms))): + self.trend_order = self.trend_terms[-1] + self.trend_degree = self.trend_terms[-1] + else: + self.trend_order = self.trend_terms + self.trend_degree = self.trend_terms[-1] + + # Handle endog / exog + # Standardize exog + self.k_exog, exog = prepare_exog(exog) + + # Standardize endog (including creating a faux endog if necessary) + faux_endog = endog is None + if endog is None: + endog = [] if exog is None else np.zeros(len(exog)) * np.nan + + # Add trend data into exog + nobs = len(endog) if exog is None else len(exog) + if self.trend_order is not None: + # Add in the data + trend_data = self.construct_trend_data(nobs, trend_offset) + if exog is None: + exog = trend_data + elif exog_is_pandas: + trend_data = pd.DataFrame(trend_data, index=exog.index, + columns=self.construct_trend_names()) + exog = pd.concat([trend_data, exog], axis=1) + else: + exog = np.c_[trend_data, exog] + + # Create an underlying time series model, to handle endog / exog, + # especially validating shapes, retrieving names, and potentially + # providing us with a time series index + self._model = TimeSeriesModel(endog, exog=exog, dates=dates, freq=freq, + missing=missing) + self.endog = None if faux_endog else self._model.endog + self.exog = self._model.exog + + # Validate endog shape + if (validate_specification and not faux_endog and + self.endog.ndim > 1 and self.endog.shape[1] > 1): + raise ValueError("SARIMAX models require univariate `endog`. Got" + f" shape {self.endog.shape!s}.") + + self._has_missing = ( + None if faux_endog else np.any(np.isnan(self.endog))) + + @property + def is_ar_consecutive(self): + """ + (bool) Is autoregressive lag polynomial consecutive + + i.e., does it include all lags up to and including the maximum lag. + """ + return (self.max_seasonal_ar_order == 0 and + not isinstance(self.ar_order, list)) + + @property + def is_ma_consecutive(self): + """ + (bool) Is moving average lag polynomial consecutive + + i.e., does it include all lags up to and including the maximum lag. + """ + return (self.max_seasonal_ma_order == 0 and + not isinstance(self.ma_order, list)) + + @property + def is_integrated(self): + """ + (bool) Is the model integrated + + i.e., does it have a nonzero `diff` or `seasonal_diff`. + """ + return self.diff > 0 or self.seasonal_diff > 0 + + @property + def is_seasonal(self): + """(bool) Does the model include a seasonal component""" + return self.seasonal_periods != 0 + + @property + def k_exog_params(self): + """(int) Number of parameters associated with exogenous variables""" + return len(self.exog_names) + + @property + def k_ar_params(self): + """(int) Number of autoregressive (non-seasonal) parameters""" + return len(self.ar_lags) + + @property + def k_ma_params(self): + """(int) Number of moving average (non-seasonal) parameters""" + return len(self.ma_lags) + + @property + def k_seasonal_ar_params(self): + """(int) Number of seasonal autoregressive parameters""" + return len(self.seasonal_ar_lags) + + @property + def k_seasonal_ma_params(self): + """(int) Number of seasonal moving average parameters""" + return len(self.seasonal_ma_lags) + + @property + def k_params(self): + """(int) Total number of model parameters""" + k_params = (self.k_exog_params + self.k_ar_params + self.k_ma_params + + self.k_seasonal_ar_params + self.k_seasonal_ma_params) + if not self.concentrate_scale: + k_params += 1 + return k_params + + @property + def exog_names(self): + """(list of str) Names associated with exogenous parameters""" + exog_names = self._model.exog_names + return [] if exog_names is None else exog_names + + @property + def ar_names(self): + """(list of str) Names of (non-seasonal) autoregressive parameters""" + return [f"ar.L{i:d}" for i in self.ar_lags] + + @property + def ma_names(self): + """(list of str) Names of (non-seasonal) moving average parameters""" + return [f"ma.L{i:d}" for i in self.ma_lags] + + @property + def seasonal_ar_names(self): + """(list of str) Names of seasonal autoregressive parameters""" + s = self.seasonal_periods + return [f"ar.S.L{i * s:d}" for i in self.seasonal_ar_lags] + + @property + def seasonal_ma_names(self): + """(list of str) Names of seasonal moving average parameters""" + s = self.seasonal_periods + return [f"ma.S.L{i * s:d}" for i in self.seasonal_ma_lags] + + @property + def param_names(self): + """(list of str) Names of all model parameters""" + names = (self.exog_names + self.ar_names + self.ma_names + + self.seasonal_ar_names + self.seasonal_ma_names) + if not self.concentrate_scale: + names.append("sigma2") + return names + + @property + def valid_estimators(self): + """ + (list of str) Estimators that could be used with specification + + Note: does not consider the presence of `exog` in determining valid + estimators. If there are exogenous variables, then feasible Generalized + Least Squares should be used through the `gls` estimator, and the + `valid_estimators` are the estimators that could be passed as the + `arma_estimator` argument to `gls`. + """ + estimators = {"yule_walker", "burg", "innovations", + "hannan_rissanen", "innovations_mle", "statespace"} + + # Properties + has_ar = self.max_ar_order != 0 + has_ma = self.max_ma_order != 0 + has_seasonal = self.seasonal_periods != 0 + + # Only state space can handle missing data or concentrated scale + if self._has_missing: + estimators.intersection_update(["statespace"]) + + # Only numerical MLE estimators can enforce restrictions + if ((self.enforce_stationarity and self.max_ar_order > 0) or + (self.enforce_invertibility and self.max_ma_order > 0)): + estimators.intersection_update(["innovations_mle", "statespace"]) + + # Innovations: no AR, non-consecutive MA, seasonal + if has_ar or not self.is_ma_consecutive or has_seasonal: + estimators.discard("innovations") + # Yule-Walker/Burg: no MA, non-consecutive AR, seasonal + if has_ma or not self.is_ar_consecutive or has_seasonal: + estimators.discard("yule_walker") + estimators.discard("burg") + # Hannan-Rissanen: no seasonal + if has_seasonal: + estimators.discard("hannan_rissanen") + # Innovations MLE: cannot have enforce_stationary=False or + # concentratre_scale=True + if self.enforce_stationarity is False or self.concentrate_scale: + estimators.discard("innovations_mle") + + return estimators + + def validate_estimator(self, estimator): + """ + Validate a SARIMA estimator + + Parameters + ---------- + estimator : str + Name of the estimator to validate against the current state of + the specification. Possible values are: 'yule_walker', 'burg', + 'innovations', 'hannan_rissanen', 'innovations_mle', 'statespace'. + + Notes + ----- + This method will raise a `ValueError` if an invalid method is passed, + and otherwise will return None. + + This method does not consider the presence of `exog` in determining + valid estimators. If there are exogenous variables, then feasible + Generalized Least Squares should be used through the `gls` estimator, + and a "valid" estimator is one that could be passed as the + `arma_estimator` argument to `gls`. + + This method only uses the attributes `enforce_stationarity` and + `concentrate_scale` to determine the validity of numerical maximum + likelihood estimators. These only include 'innovations_mle' (which + does not support `enforce_stationarity=False` or + `concentrate_scale=True`) and 'statespace' (which supports all + combinations of each). + + Examples + -------- + >>> spec = SARIMAXSpecification(order=(1, 0, 2)) + + >>> spec.validate_estimator('yule_walker') + ValueError: Yule-Walker estimator does not support moving average + components. + + >>> spec.validate_estimator('burg') + ValueError: Burg estimator does not support moving average components. + + >>> spec.validate_estimator('innovations') + ValueError: Innovations estimator does not support autoregressive + components. + + >>> spec.validate_estimator('hannan_rissanen') # returns None + >>> spec.validate_estimator('innovations_mle') # returns None + >>> spec.validate_estimator('statespace') # returns None + + >>> spec.validate_estimator('not_an_estimator') + ValueError: estimator must be one of: 'yule_walker', 'burg', \ +'innovations', 'hannan_rissanen', 'innovations_mle', 'statespace' + """ + estimator = string_like( + estimator, + "estimator", + options=( + "yule_walker", + "burg", + "innovations", + "hannan_rissanen", + "innovations_mle", + "statespace", + ), + lower=False, + ) + has_ar = self.max_ar_order != 0 + has_ma = self.max_ma_order != 0 + has_missing = self._has_missing + + titles = { + "yule_walker": "Yule-Walker", + "burg": "Burg", + "innovations": "Innovations", + "hannan_rissanen": "Hannan-Rissanen", + "innovations_mle": "Innovations MLE", + "statespace": "State space" + } + + # Only state space form can support missing data + if estimator != "statespace": + if has_missing: + raise ValueError(f"{titles[estimator]} estimator does not support missing" + " values in `endog`.") + + # Only state space and innovations MLE can enforce parameter + # restrictions + if estimator not in ["innovations_mle", "statespace"]: + if self.max_ar_order > 0 and self.enforce_stationarity: + raise ValueError(f"{titles[estimator]} estimator cannot enforce a stationary" + " autoregressive lag polynomial.") + if self.max_ma_order > 0 and self.enforce_invertibility: + raise ValueError(f"{titles[estimator]} estimator cannot enforce an invertible" + " moving average lag polynomial.") + + # Now go through specific disqualifications for each estimator + has_seasonal_ar_or_ma = (self.max_seasonal_ar_order > 0 + or self.max_seasonal_ma_order > 0) + + if estimator in ["yule_walker", "burg"]: + if has_seasonal_ar_or_ma: + raise ValueError(f"{titles[estimator]} estimator does not support seasonal" + " AR or MA components.") + if not self.is_ar_consecutive: + raise ValueError(f"{titles[estimator]} estimator does not support" + " non-consecutive autoregressive lags.") + if has_ma: + raise ValueError(f"{titles[estimator]} estimator does not support moving average" + " components.") + elif estimator == "innovations": + if has_seasonal_ar_or_ma: + raise ValueError("Innovations estimator does not support" + " seasonal AR or MA components.") + if not self.is_ma_consecutive: + raise ValueError("Innovations estimator does not support" + " non-consecutive moving average lags.") + if has_ar: + raise ValueError("Innovations estimator does not support" + " autoregressive components.") + elif estimator == "hannan_rissanen": + if has_seasonal_ar_or_ma: + raise ValueError("Hannan-Rissanen estimator does not support" + " seasonal AR or MA components.") + elif estimator == "innovations_mle": + if self.enforce_stationarity is False: + raise ValueError("Innovations MLE estimator does not support" + " non-stationary autoregressive components," + " but `enforce_stationarity` is set to False") + if self.concentrate_scale: + raise ValueError("Innovations MLE estimator does not support" + " concentrating the scale out of the" + " log-likelihood function") + else: # estimator == "statespace" + # State space form supports all variations of SARIMAX. + pass + + def split_params(self, params, allow_infnan=False): + """ + Split parameter array by type into dictionary + + Parameters + ---------- + params : array_like + Array of model parameters. + allow_infnan : bool, optional + Whether or not to allow `params` to contain -np.inf, np.inf, and + np.nan. Default is False. + + Returns + ------- + split_params : dict + Dictionary with keys 'exog_params', 'ar_params', 'ma_params', + 'seasonal_ar_params', 'seasonal_ma_params', and (unless + `concentrate_scale=True`) 'sigma2'. Values are the parameters + associated with the key, based on the `params` argument. + + Examples + -------- + >>> spec = SARIMAXSpecification(ar_order=1) + >>> spec.split_params([0.5, 4]) + {'exog_params': array([], dtype=float64), + 'ar_params': array([0.5]), + 'ma_params': array([], dtype=float64), + 'seasonal_ar_params': array([], dtype=float64), + 'seasonal_ma_params': array([], dtype=float64), + 'sigma2': 4.0} + """ + params = validate_basic(params, self.k_params, + allow_infnan=allow_infnan, + title="joint parameters") + + ix = [self.k_exog_params, self.k_ar_params, self.k_ma_params, + self.k_seasonal_ar_params, self.k_seasonal_ma_params] + names = ["exog_params", "ar_params", "ma_params", + "seasonal_ar_params", "seasonal_ma_params"] + if not self.concentrate_scale: + ix.append(1) + names.append("sigma2") + ix = np.cumsum(ix) + # Bug: was creating an extra split, discard the final + split_params = np.split(params, ix) + out = dict(zip(names, split_params[:-1], strict=True)) + if "sigma2" in out: + out["sigma2"] = out["sigma2"].item() + + return out + + def join_params(self, exog_params=None, ar_params=None, ma_params=None, + seasonal_ar_params=None, seasonal_ma_params=None, + sigma2=None): + """ + Join parameters into a single vector + + Parameters + ---------- + exog_params : array_like, optional + Parameters associated with exogenous regressors. Required if + `exog` is part of specification. + ar_params : array_like, optional + Parameters associated with (non-seasonal) autoregressive component. + Required if this component is part of the specification. + ma_params : array_like, optional + Parameters associated with (non-seasonal) moving average component. + Required if this component is part of the specification. + seasonal_ar_params : array_like, optional + Parameters associated with seasonal autoregressive component. + Required if this component is part of the specification. + seasonal_ma_params : array_like, optional + Parameters associated with seasonal moving average component. + Required if this component is part of the specification. + sigma2 : array_like, optional + Innovation variance parameter. Required unless + `concentrated_scale=True`. + + Returns + ------- + params : ndarray + Array of parameters. + + Examples + -------- + >>> spec = SARIMAXSpecification(ar_order=1) + >>> spec.join_params(ar_params=0.5, sigma2=4) + array([0.5, 4. ]) + """ + definitions = [ + ("exogenous variables", self.k_exog_params, exog_params), + ("AR terms", self.k_ar_params, ar_params), + ("MA terms", self.k_ma_params, ma_params), + ("seasonal AR terms", self.k_seasonal_ar_params, + seasonal_ar_params), + ("seasonal MA terms", self.k_seasonal_ma_params, + seasonal_ma_params), + ("variance", int(not self.concentrate_scale), sigma2)] + + params_list = [] + for title, k, params in definitions: + if k > 0: + # Validate + if params is None: + raise ValueError(f"Specification includes {title}, but no" + " parameters were provided.") + params_arr = np.atleast_1d(np.squeeze(params)) + if not params_arr.shape == (k,): + raise ValueError(f"Specification included {k:d} {title}, but" + f" parameters with shape {params_arr.shape} were provided.") + + # Otherwise add to the list + params_list.append(params_arr) + + return np.concatenate(params_list) + + def validate_params(self, params): + """ + Validate parameter vector by raising ValueError on invalid values + + Parameters + ---------- + params : array_like + Array of model parameters. + + Notes + ----- + Primarily checks that the parameters have the right shape and are not + NaN or infinite. Also checks if parameters are consistent with a + stationary process if `enforce_stationarity=True` and that they are + consistent with an invertible process if `enforce_invertibility=True`. + Finally, checks that the variance term is positive, unless + `concentrate_scale=True`. + + Examples + -------- + >>> spec = SARIMAXSpecification(ar_order=1, enforce_stationarity=True) + >>> spec.validate_params([-0.5, 4.]) # returns None + >>> spec.validate_params([-0.5, -2]) + ValueError: Non-positive variance term. + >>> spec.validate_params([-1.5, 4.]) + ValueError: Non-stationary autoregressive polynomial. + """ + # Note: split_params includes basic validation + params = self.split_params(params) + + # Specific checks + if self.enforce_stationarity: + if self.k_ar_params: + ar_poly = np.r_[1, -params["ar_params"]] + if not is_invertible(ar_poly): + raise ValueError("Non-stationary autoregressive" + " polynomial.") + if self.k_seasonal_ar_params: + seasonal_ar_poly = np.r_[1, -params["seasonal_ar_params"]] + if not is_invertible(seasonal_ar_poly): + raise ValueError("Non-stationary seasonal autoregressive" + " polynomial.") + + if self.enforce_invertibility: + if self.k_ma_params: + ma_poly = np.r_[1, params["ma_params"]] + if not is_invertible(ma_poly): + raise ValueError("Non-invertible moving average" + " polynomial.") + if self.k_seasonal_ma_params: + seasonal_ma_poly = np.r_[1, params["seasonal_ma_params"]] + if not is_invertible(seasonal_ma_poly): + raise ValueError("Non-invertible seasonal moving average" + " polynomial.") + + if not self.concentrate_scale: + if params["sigma2"] <= 0: + raise ValueError("Non-positive variance term.") + + def constrain_params(self, unconstrained): + """ + Constrain parameter values to be valid through transformations + + Parameters + ---------- + unconstrained : array_like + Array of model unconstrained parameters. + + Returns + ------- + constrained : ndarray + Array of model parameters transformed to produce a valid model. + + Notes + ----- + This is usually only used when performing numerical minimization + of the log-likelihood function. This function is necessary because + the minimizers consider values over the entire real space, while + SARIMAX models require parameters in subspaces (for example positive + variances). + + Examples + -------- + >>> spec = SARIMAXSpecification(ar_order=1, enforce_stationarity=True) + >>> spec.constrain_params([10, -2]) + array([-0.99504, 4. ]) + """ + unconstrained = self.split_params(unconstrained) + params = {} + + if self.k_exog_params: + params["exog_params"] = unconstrained["exog_params"] + if self.k_ar_params: + if self.enforce_stationarity: + params["ar_params"] = constrain(unconstrained["ar_params"]) + else: + params["ar_params"] = unconstrained["ar_params"] + if self.k_ma_params: + if self.enforce_invertibility: + params["ma_params"] = -constrain(unconstrained["ma_params"]) + else: + params["ma_params"] = unconstrained["ma_params"] + if self.k_seasonal_ar_params: + if self.enforce_stationarity: + params["seasonal_ar_params"] = ( + constrain(unconstrained["seasonal_ar_params"])) + else: + params["seasonal_ar_params"] = ( + unconstrained["seasonal_ar_params"]) + if self.k_seasonal_ma_params: + if self.enforce_invertibility: + params["seasonal_ma_params"] = ( + -constrain(unconstrained["seasonal_ma_params"])) + else: + params["seasonal_ma_params"] = ( + unconstrained["seasonal_ma_params"]) + if not self.concentrate_scale: + params["sigma2"] = unconstrained["sigma2"]**2 + + return self.join_params(**params) + + def unconstrain_params(self, constrained): + """ + Reverse transformations used to constrain parameter values to be valid + + Parameters + ---------- + constrained : array_like + Array of model parameters. + + Returns + ------- + unconstrained : ndarray + Array of parameters with constraining transformations reversed. + + Notes + ----- + This is usually only used when performing numerical minimization + of the log-likelihood function. This function is the (approximate) + inverse of `constrain_params`. + + Examples + -------- + >>> spec = SARIMAXSpecification(ar_order=1, enforce_stationarity=True) + >>> spec.unconstrain_params([-0.5, 4.]) + array([0.57735, 2. ]) + """ + constrained = self.split_params(constrained) + params = {} + + if self.k_exog_params: + params["exog_params"] = constrained["exog_params"] + if self.k_ar_params: + if self.enforce_stationarity: + params["ar_params"] = unconstrain(constrained["ar_params"]) + else: + params["ar_params"] = constrained["ar_params"] + if self.k_ma_params: + if self.enforce_invertibility: + params["ma_params"] = unconstrain(-constrained["ma_params"]) + else: + params["ma_params"] = constrained["ma_params"] + if self.k_seasonal_ar_params: + if self.enforce_stationarity: + params["seasonal_ar_params"] = ( + unconstrain(constrained["seasonal_ar_params"])) + else: + params["seasonal_ar_params"] = ( + constrained["seasonal_ar_params"]) + if self.k_seasonal_ma_params: + if self.enforce_invertibility: + params["seasonal_ma_params"] = ( + unconstrain(-constrained["seasonal_ma_params"])) + else: + params["seasonal_ma_params"] = ( + constrained["seasonal_ma_params"]) + if not self.concentrate_scale: + params["sigma2"] = constrained["sigma2"]**0.5 + + return self.join_params(**params) + + def construct_trend_data(self, nobs, offset=1): + """ + Construct the trend data array implied by the trend specification + + Parameters + ---------- + nobs : int + Number of observations for which to construct trend data. + offset : int, optional + The offset at which to start time trend values. Default is 1, + so that if the specification includes a linear trend, the + trend values are 1, 2, ..., nobs. + + Returns + ------- + trend_data : ndarray or None + Array shaped ``(nobs, k_trend)`` containing the trend + regressors implied by `trend_poly`, or None if the + specification does not include a trend component. + """ + if self.trend_order is None: + trend_data = None + else: + trend_data = prepare_trend_data( + self.trend_poly, int(np.sum(self.trend_poly)), nobs, offset) + + return trend_data + + def construct_trend_names(self): + """ + Construct names for the trend terms included in the specification + + Returns + ------- + names : list of str + Names of the included trend terms, using 'const' for a + constant term, 'drift' for a linear trend, and 'trend.' + for a higher order term of degree `i`. + """ + names = [] + for i in self.trend_terms: + if i == 0: + names.append("const") + elif i == 1: + names.append("drift") + else: + names.append(f"trend.{i:d}") + return names + + def __repr__(self): + """Represent SARIMAXSpecification object as a string""" + components = [] + if self.endog is not None: + components.append(f"endog={self._model.endog_names}") + if self.k_exog_params: + components.append(f"exog={self.exog_names}") + components.append(f"order={self.order!s}") + if self.seasonal_periods > 0: + components.append(f"seasonal_order={self.seasonal_order!s}") + if self.enforce_stationarity is not None: + components.append(f"enforce_stationarity={self.enforce_stationarity}") + if self.enforce_invertibility is not None: + components.append(f"enforce_invertibility={self.enforce_invertibility}") + if self.concentrate_scale is not None: + components.append(f"concentrate_scale={self.concentrate_scale}") + return "SARIMAXSpecification({})".format(", ".join(components)) diff --git a/shared/package-files/7b/7b47b4a48f9746d3e6bd4096d954ca2f50de62ed69bcf99451e4528046d69a29/blob b/shared/package-files/7b/7b47b4a48f9746d3e6bd4096d954ca2f50de62ed69bcf99451e4528046d69a29/blob new file mode 100644 index 0000000000000000000000000000000000000000..f9c6439b9b84bfdf40a2570d6971951b94977841 Binary files /dev/null and b/shared/package-files/7b/7b47b4a48f9746d3e6bd4096d954ca2f50de62ed69bcf99451e4528046d69a29/blob differ diff --git a/shared/package-files/7b/7b48e99ec6db33d42169a312c9aa7efd9814c5cc70a722c393a44772b76e3cb8/blob b/shared/package-files/7b/7b48e99ec6db33d42169a312c9aa7efd9814c5cc70a722c393a44772b76e3cb8/blob new file mode 100644 index 0000000000000000000000000000000000000000..d98d98cb52bef152098bd4277dabcd99b0f528bc --- /dev/null +++ b/shared/package-files/7b/7b48e99ec6db33d42169a312c9aa7efd9814c5cc70a722c393a44772b76e3cb8/blob @@ -0,0 +1,26 @@ +from __future__ import annotations + +import base64 +import logging + +log = logging.getLogger("wheel") + +# ensure Python logging is configured +try: + __import__("setuptools.logging") +except ImportError: + # setuptools < ?? + from . import _setuptools_logging + + _setuptools_logging.configure() + + +def urlsafe_b64encode(data: bytes) -> bytes: + """urlsafe_b64encode without padding""" + return base64.urlsafe_b64encode(data).rstrip(b"=") + + +def urlsafe_b64decode(data: bytes) -> bytes: + """urlsafe_b64decode without padding""" + pad = b"=" * (4 - (len(data) & 3)) + return base64.urlsafe_b64decode(data + pad) diff --git a/shared/package-files/7b/7b4a424c167d867f550154e710db9b6c48a2ff08ad17bdf151e05934841def72/blob b/shared/package-files/7b/7b4a424c167d867f550154e710db9b6c48a2ff08ad17bdf151e05934841def72/blob new file mode 100644 index 0000000000000000000000000000000000000000..588806507039c90dc655a1a6df961151ace25502 --- /dev/null +++ b/shared/package-files/7b/7b4a424c167d867f550154e710db9b6c48a2ff08ad17bdf151e05934841def72/blob @@ -0,0 +1,126 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/util/launder.h" +#include "arrow/util/macros.h" + +namespace arrow { +namespace internal { + +template +class AlignedStorage { + public: + static constexpr bool can_memcpy = std::is_trivial::value; + + constexpr T* get() noexcept { + return arrow::internal::launder(reinterpret_cast(&data_)); + } + + constexpr const T* get() const noexcept { + // Use fully qualified name to avoid ambiguities with MSVC (ARROW-14800) + return arrow::internal::launder(reinterpret_cast(&data_)); + } + + void destroy() noexcept { + if (!std::is_trivially_destructible::value) { + get()->~T(); + } + } + + template + void construct(A&&... args) noexcept { + new (&data_) T(std::forward(args)...); + } + + template + void assign(V&& v) noexcept { + *get() = std::forward(v); + } + + void move_construct(AlignedStorage* other) noexcept { + new (&data_) T(std::move(*other->get())); + } + + void move_assign(AlignedStorage* other) noexcept { *get() = std::move(*other->get()); } + + template + static typename std::enable_if::type move_construct_several( + AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + memcpy(dest->get(), src->get(), memcpy_length * sizeof(T)); + } + + template + static typename std::enable_if::type + move_construct_several_and_destroy_source(AlignedStorage* ARROW_RESTRICT src, + AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + memcpy(dest->get(), src->get(), memcpy_length * sizeof(T)); + } + + template + static typename std::enable_if::type move_construct_several( + AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + for (size_t i = 0; i < n; ++i) { + new (dest[i].get()) T(std::move(*src[i].get())); + } + } + + template + static typename std::enable_if::type + move_construct_several_and_destroy_source(AlignedStorage* ARROW_RESTRICT src, + AlignedStorage* ARROW_RESTRICT dest, size_t n, + size_t memcpy_length) noexcept { + for (size_t i = 0; i < n; ++i) { + new (dest[i].get()) T(std::move(*src[i].get())); + src[i].destroy(); + } + } + + static void move_construct_several(AlignedStorage* ARROW_RESTRICT src, + AlignedStorage* ARROW_RESTRICT dest, + size_t n) noexcept { + move_construct_several(src, dest, n, n); + } + + static void move_construct_several_and_destroy_source( + AlignedStorage* ARROW_RESTRICT src, AlignedStorage* ARROW_RESTRICT dest, + size_t n) noexcept { + move_construct_several_and_destroy_source(src, dest, n, n); + } + + static void destroy_several(AlignedStorage* p, size_t n) noexcept { + if (!std::is_trivially_destructible::value) { + for (size_t i = 0; i < n; ++i) { + p[i].destroy(); + } + } + } + + private: + alignas(T) std::byte data_[sizeof(T)]; +}; + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/7b/7b4b3a732a0a25e60c02b75c787a67283bed095730ed7b81e383810c7a686ba5/blob b/shared/package-files/7b/7b4b3a732a0a25e60c02b75c787a67283bed095730ed7b81e383810c7a686ba5/blob new file mode 100644 index 0000000000000000000000000000000000000000..969b7143dfff3bb817dbf70c54af8303c3b5822e Binary files /dev/null and b/shared/package-files/7b/7b4b3a732a0a25e60c02b75c787a67283bed095730ed7b81e383810c7a686ba5/blob differ diff --git a/shared/package-files/7b/7b4c82f57e8174c11f6e1ca64fab8092bd432bbe78ea88740a779a164f4e6570/blob b/shared/package-files/7b/7b4c82f57e8174c11f6e1ca64fab8092bd432bbe78ea88740a779a164f4e6570/blob new file mode 100644 index 0000000000000000000000000000000000000000..6b94c72fa74415b6cb52740b7128ed50df6989d5 --- /dev/null +++ b/shared/package-files/7b/7b4c82f57e8174c11f6e1ca64fab8092bd432bbe78ea88740a779a164f4e6570/blob @@ -0,0 +1,16 @@ +tomli-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tomli-2.0.1.dist-info/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +tomli-2.0.1.dist-info/METADATA,sha256=zPDceKmPwJGLWtZykrHixL7WVXWmJGzZ1jyRT5lCoPI,8875 +tomli-2.0.1.dist-info/RECORD,, +tomli-2.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +tomli-2.0.1.dist-info/WHEEL,sha256=VUbF57hf4yRZWWrOOjp25Fr4BQX9EtnVSbnP2vNxHDM,81 +tomli-2.0.1.dist-info/direct_url.json,sha256=2jdhiY3TvX-Yj76qlUTF9IJyrK3MCPAwtY7d45QCmUs,79 +tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396 +tomli/__pycache__/__init__.cpython-310.pyc,, +tomli/__pycache__/_parser.cpython-310.pyc,, +tomli/__pycache__/_re.cpython-310.pyc,, +tomli/__pycache__/_types.cpython-310.pyc,, +tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633 +tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943 +tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 diff --git a/shared/package-files/7b/7b5134e3a1d561bc1956e87db67b59ff67d140709a45099ebc544dddbc9450f9/blob b/shared/package-files/7b/7b5134e3a1d561bc1956e87db67b59ff67d140709a45099ebc544dddbc9450f9/blob new file mode 100644 index 0000000000000000000000000000000000000000..f87f5aa34c628d3e3313a8e18d7288ee1c77febc --- /dev/null +++ b/shared/package-files/7b/7b5134e3a1d561bc1956e87db67b59ff67d140709a45099ebc544dddbc9450f9/blob @@ -0,0 +1,18 @@ +## `conda.base` + +Code in `conda.base` is the lowest level of the application stack. It is loaded and executed +virtually every time the application is executed. Any code within, and any of its imports, must +be highly performant. + +Conda modules importable from `conda.base` are: + +- `conda._vendor` +- `conda.base` +- `conda.common` + +Modules prohibited from importing `conda.base` are: + +- `conda._vendor` +- `conda.common` + +All other `conda` modules may import from `conda.base`. diff --git a/shared/package-files/7b/7b5390b15c50a60c9fa8c370da9b944c04e5fb0decc2f7649e572d0225b17ff1/blob b/shared/package-files/7b/7b5390b15c50a60c9fa8c370da9b944c04e5fb0decc2f7649e572d0225b17ff1/blob new file mode 100644 index 0000000000000000000000000000000000000000..84d3b03b7d37afb0ddb2965300f9ce49ba9e4a53 --- /dev/null +++ b/shared/package-files/7b/7b5390b15c50a60c9fa8c370da9b944c04e5fb0decc2f7649e572d0225b17ff1/blob @@ -0,0 +1,31 @@ +import sys +from typing import Any + +import numpy as np +import numpy.typing as npt + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +a: np.flatiter[npt.NDArray[np.str_]] + +assert_type(a.base, npt.NDArray[np.str_]) +assert_type(a.copy(), npt.NDArray[np.str_]) +assert_type(a.coords, tuple[int, ...]) +assert_type(a.index, int) +assert_type(iter(a), np.flatiter[npt.NDArray[np.str_]]) +assert_type(next(a), np.str_) +assert_type(a[0], np.str_) +assert_type(a[[0, 1, 2]], npt.NDArray[np.str_]) +assert_type(a[...], npt.NDArray[np.str_]) +assert_type(a[:], npt.NDArray[np.str_]) +assert_type(a[(...,)], npt.NDArray[np.str_]) +assert_type(a[(0,)], np.str_) +assert_type(a.__array__(), npt.NDArray[np.str_]) +assert_type(a.__array__(np.dtype(np.float64)), npt.NDArray[np.float64]) +a[0] = "a" +a[:5] = "a" +a[...] = "a" +a[(...,)] = "a" diff --git a/shared/package-files/7b/7b53da9450d4d346be82d09953f7ad9128d71e7971929043892263502096716d/blob b/shared/package-files/7b/7b53da9450d4d346be82d09953f7ad9128d71e7971929043892263502096716d/blob new file mode 100644 index 0000000000000000000000000000000000000000..34009313a8fc489d088209577df126cde1244b98 --- /dev/null +++ b/shared/package-files/7b/7b53da9450d4d346be82d09953f7ad9128d71e7971929043892263502096716d/blob @@ -0,0 +1,24 @@ +All of the people who have made at least one contribution to conda-package-handling. +Authors are sorted alphabetically. + +* Alan Du +* Cheng H. Lee +* Chris Burr +* Christopher Barber +* Conda Bot +* Daniel Bast +* Daniel Holth +* Eli Uriegas +* Jannis Leidel +* John Lee +* Jonathan J. Helmus +* Ken Odegard +* Marius van Niekerk +* Matthew R. Becker +* Michael Sarahan +* Nehal J Wani +* Pure Software +* Ray Donnelly +* Tobias "Tobi" Koch +* Vadim Zayakin +* pre-commit-ci[bot] diff --git a/shared/package-files/7b/7b5f689b5a7c9790431da8d784722d9d0808f524d04a88b04e1a04bd6f163d4f/blob b/shared/package-files/7b/7b5f689b5a7c9790431da8d784722d9d0808f524d04a88b04e1a04bd6f163d4f/blob new file mode 100644 index 0000000000000000000000000000000000000000..a4c02aa58dadefec13a810615658389c1197eb99 Binary files /dev/null and b/shared/package-files/7b/7b5f689b5a7c9790431da8d784722d9d0808f524d04a88b04e1a04bd6f163d4f/blob differ diff --git a/shared/package-files/7b/7b62799e98fc3de61f9d0ab6a56d512c280ca1f9922138c35561f4676966bf46/blob b/shared/package-files/7b/7b62799e98fc3de61f9d0ab6a56d512c280ca1f9922138c35561f4676966bf46/blob new file mode 100644 index 0000000000000000000000000000000000000000..a8c716d41a5c1bb83e4f11d6385d627278fff5ab --- /dev/null +++ b/shared/package-files/7b/7b62799e98fc3de61f9d0ab6a56d512c280ca1f9922138c35561f4676966bf46/blob @@ -0,0 +1,8 @@ +from typing import Dict, List, Tuple + +class ModulusPack: + pack: Dict[int, List[Tuple[int, int]]] + discarded: List[Tuple[int, str]] + def __init__(self) -> None: ... + def read_file(self, filename: str) -> None: ... + def get_modulus(self, min: int, prefer: int, max: int) -> Tuple[int, int]: ... diff --git a/shared/package-files/7b/7b666e534317d8f18bfdb2a0fc3397b15ce5d2472a8ddaea87903600a2483b55/blob b/shared/package-files/7b/7b666e534317d8f18bfdb2a0fc3397b15ce5d2472a8ddaea87903600a2483b55/blob new file mode 100644 index 0000000000000000000000000000000000000000..66d583d8870efda8e49984bcda2e79905b1a5696 --- /dev/null +++ b/shared/package-files/7b/7b666e534317d8f18bfdb2a0fc3397b15ce5d2472a8ddaea87903600a2483b55/blob @@ -0,0 +1,216 @@ +from collections import namedtuple + +from numba.core import types, ir +from numba.core.typing import signature + + +_CallableNode = namedtuple("BoundFunc", ["func", "sig"]) + + +class ParforLoweringBuilder: + """Helper class for building Numba-IR and lowering for Parfor. + """ + def __init__(self, lowerer, scope, loc): + self._lowerer = lowerer + self._scope = scope + self._loc = loc + + @property + def _context(self): + return self._lowerer.context + + @property + def _typingctx(self): + return self._context.typing_context + + @property + def _typemap(self): + return self._lowerer.fndesc.typemap + + @property + def _calltypes(self): + return self._lowerer.fndesc.calltypes + + def bind_global_function(self, fobj, ftype, args, kws=None): + """Binds a global function to a variable. + + Parameters + ---------- + fobj : object + The function to be bound. + ftype : types.Type + args : Sequence[types.Type] + kws : Mapping[str, types.Type] + + Returns + ------- + callable: _CallableNode + """ + if kws is None: + kws = {} + loc = self._loc + varname = f"{fobj.__name__}_func" + gvname = f"{fobj.__name__}" + + func_sig = self._typingctx.resolve_function_type(ftype, args, kws) + func_var = self.assign( + rhs=ir.Global(gvname, fobj, loc=loc), typ=ftype, name=varname + ) + return _CallableNode(func=func_var, sig=func_sig) + + def make_const_variable(self, cval, typ, name="pf_const") -> ir.Var: + """Makes a constant variable + + Parameters + ---------- + cval : object + The constant value + typ : types.Type + type of the value + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + return self.assign( + rhs=ir.Const(cval, loc=self._loc), typ=typ, name=name + ) + + def make_tuple_variable(self, varlist, name="pf_tuple") -> ir.Var: + """Makes a tuple variable + + Parameters + ---------- + varlist : Sequence[ir.Var] + Variables containing the values to be stored. + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + loc = self._loc + vartys = [self._typemap[x.name] for x in varlist] + tupty = types.Tuple.from_types(vartys) + return self.assign( + rhs=ir.Expr.build_tuple(varlist, loc), typ=tupty, name=name + ) + + def assign(self, rhs, typ, name="pf_assign") -> ir.Var: + """Assign a value to a new variable + + Parameters + ---------- + rhs : object + The value + typ : types.Type + type of the value + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + loc = self._loc + var = self._scope.redefine(name, loc) + self._typemap[var.name] = typ + assign = ir.Assign(rhs, var, loc) + self._lowerer.lower_inst(assign) + return var + + def assign_inplace(self, rhs, typ, name) -> ir.Var: + """Assign a value to a new variable or inplace if it already exist + + Parameters + ---------- + rhs : object + The value + typ : types.Type + type of the value + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + loc = self._loc + var = ir.Var(self._scope, name, loc) + assign = ir.Assign(rhs, var, loc) + self._typemap.setdefault(var.name, typ) + self._lowerer.lower_inst(assign) + return var + + def call(self, callable_node, args, kws=None) -> ir.Expr: + """Call a bound callable + + Parameters + ---------- + callable_node : _CallableNode + The callee + args : Sequence[ir.Var] + kws : Mapping[str, ir.Var] + + Returns + ------- + res : ir.Expr + The expression node for the return value of the call + """ + if kws is None: + kws = {} + call = ir.Expr.call(callable_node.func, args, kws, loc=self._loc) + self._calltypes[call] = callable_node.sig + return call + + def setitem(self, obj, index, val) -> ir.SetItem: + """Makes a setitem call + + Parameters + ---------- + obj : ir.Var + the object being indexed + index : ir.Var + the index + val : ir.Var + the value to be stored + + Returns + ------- + res : ir.SetItem + """ + loc = self._loc + tm = self._typemap + setitem = ir.SetItem(obj, index, val, loc=loc) + self._lowerer.fndesc.calltypes[setitem] = signature( + types.none, tm[obj.name], tm[index.name], tm[val.name] + ) + self._lowerer.lower_inst(setitem) + return setitem + + def getitem(self, obj, index, typ) -> ir.Expr: + """Makes a getitem call + + Parameters + ---------- + obj : ir.Var + the object being indexed + index : ir.Var + the index + val : ir.Var + the ty + + Returns + ------- + res : ir.Expr + the retrieved value + """ + tm = self._typemap + getitem = ir.Expr.getitem(obj, index, loc=self._loc) + self._lowerer.fndesc.calltypes[getitem] = signature( + typ, tm[obj.name], tm[index.name], + ) + return getitem diff --git a/shared/package-files/7b/7b6bad55400cf301b86fc543891bfcd9270db2a93283e0b2dd7ca919346f3602/blob b/shared/package-files/7b/7b6bad55400cf301b86fc543891bfcd9270db2a93283e0b2dd7ca919346f3602/blob new file mode 100644 index 0000000000000000000000000000000000000000..a2bcee47190d39b3bf61666cf4f0b2a9451c6336 --- /dev/null +++ b/shared/package-files/7b/7b6bad55400cf301b86fc543891bfcd9270db2a93283e0b2dd7ca919346f3602/blob @@ -0,0 +1,35 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::lstm.input(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor) +inline ::std::tuple lstm(const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first) { + return at::_ops::lstm_input::call(input, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first); +} + +// aten::lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor, Tensor) +inline ::std::tuple lstm(const at::Tensor & data, const at::Tensor & batch_sizes, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional) { + return at::_ops::lstm_data::call(data, batch_sizes, hx, params, has_biases, num_layers, dropout, train, bidirectional); +} + +} diff --git a/shared/package-files/7b/7b725550d38f2347c22c55dec0db68bcdccc4cc5d76409c0cbdbd281bf71ec7e/blob b/shared/package-files/7b/7b725550d38f2347c22c55dec0db68bcdccc4cc5d76409c0cbdbd281bf71ec7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..3dc23cc107dd814036d7601967a9e2083df72f8e Binary files /dev/null and b/shared/package-files/7b/7b725550d38f2347c22c55dec0db68bcdccc4cc5d76409c0cbdbd281bf71ec7e/blob differ diff --git a/shared/package-files/7b/7b72e42cf238a1ad88cf2911ec180ef4821f08a470d2fad7e2e1f13d307eb893/blob b/shared/package-files/7b/7b72e42cf238a1ad88cf2911ec180ef4821f08a470d2fad7e2e1f13d307eb893/blob new file mode 100644 index 0000000000000000000000000000000000000000..c6634af6f31b5be2025794a789dc1466f97a3f19 --- /dev/null +++ b/shared/package-files/7b/7b72e42cf238a1ad88cf2911ec180ef4821f08a470d2fad7e2e1f13d307eb893/blob @@ -0,0 +1,14 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, TypeVar + +if TYPE_CHECKING: + from narwhals._sql.dataframe import SQLLazyFrame + from narwhals._sql.expr import SQLExpr + + SQLExprAny = SQLExpr[Any, Any] + SQLLazyFrameAny = SQLLazyFrame[Any, Any, Any] + +SQLExprT = TypeVar("SQLExprT", bound="SQLExprAny") +SQLExprT_contra = TypeVar("SQLExprT_contra", bound="SQLExprAny", contravariant=True) +SQLLazyFrameT = TypeVar("SQLLazyFrameT", bound="SQLLazyFrameAny") diff --git a/shared/package-files/7b/7b74483b6c413e117e3f13d9b4f33c56456192361d50db5c87dbdca11a47b841/blob b/shared/package-files/7b/7b74483b6c413e117e3f13d9b4f33c56456192361d50db5c87dbdca11a47b841/blob new file mode 100644 index 0000000000000000000000000000000000000000..2d1d213322bac02e65f710ac77943876425102a5 --- /dev/null +++ b/shared/package-files/7b/7b74483b6c413e117e3f13d9b4f33c56456192361d50db5c87dbdca11a47b841/blob @@ -0,0 +1,119 @@ +""" +This file contains a minimal set of tests for compliance with the extension +array interface test suite, and should contain no other tests. +The test suite for the full functionality of the array is located in +`pandas/tests/arrays/`. + +The tests in this file are inherited from the BaseExtensionTests, and only +minimal tweaks should be applied to get the tests passing (by overwriting a +parent method). + +Additional tests should either be added to one of the BaseExtensionTests +classes (if they are relevant for the extension interface for all dtypes), or +be added to the array-specific tests in `pandas/tests/arrays/`. + +""" +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +from pandas._libs import ( + Period, + iNaT, +) +from pandas.compat import is_platform_windows +from pandas.compat.numpy import np_version_gte1p24 + +from pandas.core.dtypes.dtypes import PeriodDtype + +import pandas._testing as tm +from pandas.core.arrays import PeriodArray +from pandas.tests.extension import base + +if TYPE_CHECKING: + import pandas as pd + + +@pytest.fixture(params=["D", "2D"]) +def dtype(request): + return PeriodDtype(freq=request.param) + + +@pytest.fixture +def data(dtype): + return PeriodArray(np.arange(1970, 2070), dtype=dtype) + + +@pytest.fixture +def data_for_sorting(dtype): + return PeriodArray([2018, 2019, 2017], dtype=dtype) + + +@pytest.fixture +def data_missing(dtype): + return PeriodArray([iNaT, 2017], dtype=dtype) + + +@pytest.fixture +def data_missing_for_sorting(dtype): + return PeriodArray([2018, iNaT, 2017], dtype=dtype) + + +@pytest.fixture +def data_for_grouping(dtype): + B = 2018 + NA = iNaT + A = 2017 + C = 2019 + return PeriodArray([B, B, NA, NA, A, A, B, C], dtype=dtype) + + +class TestPeriodArray(base.ExtensionTests): + def _get_expected_exception(self, op_name, obj, other): + if op_name in ("__sub__", "__rsub__"): + return None + return super()._get_expected_exception(op_name, obj, other) + + def _supports_accumulation(self, ser, op_name: str) -> bool: + return op_name in ["cummin", "cummax"] + + def _supports_reduction(self, obj, op_name: str) -> bool: + return op_name in ["min", "max", "median"] + + def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool): + if op_name == "median": + res_op = getattr(ser, op_name) + + alt = ser.astype("int64") + + exp_op = getattr(alt, op_name) + result = res_op(skipna=skipna) + expected = exp_op(skipna=skipna) + # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no + # attribute "freq" + freq = ser.dtype.freq # type: ignore[union-attr] + expected = Period._from_ordinal(int(expected), freq=freq) + tm.assert_almost_equal(result, expected) + + else: + return super().check_reduce(ser, op_name, skipna) + + @pytest.mark.parametrize("periods", [1, -2]) + def test_diff(self, data, periods): + if is_platform_windows() and np_version_gte1p24: + with tm.assert_produces_warning(RuntimeWarning, check_stacklevel=False): + super().test_diff(data, periods) + else: + super().test_diff(data, periods) + + @pytest.mark.parametrize("na_action", [None, "ignore"]) + def test_map(self, data, na_action): + result = data.map(lambda x: x, na_action=na_action) + tm.assert_extension_array_equal(result, data) + + +class Test2DCompat(base.NDArrayBacked2DTests): + pass diff --git a/shared/package-files/7b/7b74941b9d151aaa3af1e4bff1e6d309540f6b801ac4bc6ea35262597e132168/blob b/shared/package-files/7b/7b74941b9d151aaa3af1e4bff1e6d309540f6b801ac4bc6ea35262597e132168/blob new file mode 100644 index 0000000000000000000000000000000000000000..72eb2dc70b906680b65e312a750386f6ed44ec6e --- /dev/null +++ b/shared/package-files/7b/7b74941b9d151aaa3af1e4bff1e6d309540f6b801ac4bc6ea35262597e132168/blob @@ -0,0 +1,46 @@ +import ctypes + +from .backend_cairo import cairo, FigureCanvasCairo +from .backend_qt import _BackendQT, FigureCanvasQT +from .qt_compat import QT_API, QtCore, QtGui + + +class FigureCanvasQTCairo(FigureCanvasCairo, FigureCanvasQT): + def draw(self): + if hasattr(self._renderer.gc, "ctx"): + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + super().draw() + + def paintEvent(self, event): + width = int(self.device_pixel_ratio * self.width()) + height = int(self.device_pixel_ratio * self.height()) + if (width, height) != self._renderer.get_canvas_width_height(): + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) + self._renderer.set_context(cairo.Context(surface)) + self._renderer.dpi = self.figure.dpi + self.figure.draw(self._renderer) + buf = self._renderer.gc.ctx.get_target().get_data() + if QT_API == "PyQt6": + from PyQt6 import sip + ptr = int(sip.voidptr(buf)) + else: + ptr = buf + qimage = QtGui.QImage( + ptr, width, height, + QtGui.QImage.Format.Format_ARGB32_Premultiplied) + # Adjust the buf reference count to work around a memory leak bug in + # QImage under PySide. + if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12): + ctypes.c_long.from_address(id(buf)).value = 1 + qimage.setDevicePixelRatio(self.device_pixel_ratio) + painter = QtGui.QPainter(self) + painter.eraseRect(event.rect()) + painter.drawImage(0, 0, qimage) + self._draw_rect_callback(painter) + painter.end() + + +@_BackendQT.export +class _BackendQTCairo(_BackendQT): + FigureCanvas = FigureCanvasQTCairo diff --git a/shared/package-files/7b/7b761b3e121f0a0ca1ea2a0b8e2cc856bcf801604b8268d71bacaa202bc0c13b/blob b/shared/package-files/7b/7b761b3e121f0a0ca1ea2a0b8e2cc856bcf801604b8268d71bacaa202bc0c13b/blob new file mode 100644 index 0000000000000000000000000000000000000000..2248a0c80bbfc51b67863f848f60466f135cdb2b --- /dev/null +++ b/shared/package-files/7b/7b761b3e121f0a0ca1ea2a0b8e2cc856bcf801604b8268d71bacaa202bc0c13b/blob @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$recursiveRef": "#" }, + { "$ref": "meta/validation#/$defs/stringArray" } + ] + } + } + } +} diff --git a/shared/package-files/7b/7b774aa6d040005eac47f8b5a9bc90d5bac92ea43267229935ef326e61615d87/blob b/shared/package-files/7b/7b774aa6d040005eac47f8b5a9bc90d5bac92ea43267229935ef326e61615d87/blob new file mode 100644 index 0000000000000000000000000000000000000000..5ad1dd68d083293c2e3f880989079281251efd36 --- /dev/null +++ b/shared/package-files/7b/7b774aa6d040005eac47f8b5a9bc90d5bac92ea43267229935ef326e61615d87/blob @@ -0,0 +1,813 @@ +""" +Renders the command line on the console. +(Redraws parts of the input line that were changed.) +""" +from __future__ import annotations + +from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait +from collections import deque +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable, Dict, Hashable + +from prompt_toolkit.application.current import get_app +from prompt_toolkit.cursor_shapes import CursorShape +from prompt_toolkit.data_structures import Point, Size +from prompt_toolkit.filters import FilterOrBool, to_filter +from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text +from prompt_toolkit.layout.mouse_handlers import MouseHandlers +from prompt_toolkit.layout.screen import Char, Screen, WritePosition +from prompt_toolkit.output import ColorDepth, Output +from prompt_toolkit.styles import ( + Attrs, + BaseStyle, + DummyStyleTransformation, + StyleTransformation, +) + +if TYPE_CHECKING: + from prompt_toolkit.application import Application + from prompt_toolkit.layout.layout import Layout + + +__all__ = [ + "Renderer", + "print_formatted_text", +] + + +def _output_screen_diff( + app: Application[Any], + output: Output, + screen: Screen, + current_pos: Point, + color_depth: ColorDepth, + previous_screen: Screen | None, + last_style: str | None, + is_done: bool, # XXX: drop is_done + full_screen: bool, + attrs_for_style_string: _StyleStringToAttrsCache, + style_string_has_style: _StyleStringHasStyleCache, + size: Size, + previous_width: int, +) -> tuple[Point, str | None]: + """ + Render the diff between this screen and the previous screen. + + This takes two `Screen` instances. The one that represents the output like + it was during the last rendering and one that represents the current + output raster. Looking at these two `Screen` instances, this function will + render the difference by calling the appropriate methods of the `Output` + object that only paint the changes to the terminal. + + This is some performance-critical code which is heavily optimized. + Don't change things without profiling first. + + :param current_pos: Current cursor position. + :param last_style: The style string, used for drawing the last drawn + character. (Color/attributes.) + :param attrs_for_style_string: :class:`._StyleStringToAttrsCache` instance. + :param width: The width of the terminal. + :param previous_width: The width of the terminal during the last rendering. + """ + width, height = size.columns, size.rows + + #: Variable for capturing the output. + write = output.write + write_raw = output.write_raw + + # Create locals for the most used output methods. + # (Save expensive attribute lookups.) + _output_set_attributes = output.set_attributes + _output_reset_attributes = output.reset_attributes + _output_cursor_forward = output.cursor_forward + _output_cursor_up = output.cursor_up + _output_cursor_backward = output.cursor_backward + + # Hide cursor before rendering. (Avoid flickering.) + output.hide_cursor() + + def reset_attributes() -> None: + "Wrapper around Output.reset_attributes." + nonlocal last_style + _output_reset_attributes() + last_style = None # Forget last char after resetting attributes. + + def move_cursor(new: Point) -> Point: + "Move cursor to this `new` point. Returns the given Point." + current_x, current_y = current_pos.x, current_pos.y + + if new.y > current_y: + # Use newlines instead of CURSOR_DOWN, because this might add new lines. + # CURSOR_DOWN will never create new lines at the bottom. + # Also reset attributes, otherwise the newline could draw a + # background color. + reset_attributes() + write("\r\n" * (new.y - current_y)) + current_x = 0 + _output_cursor_forward(new.x) + return new + elif new.y < current_y: + _output_cursor_up(current_y - new.y) + + if current_x >= width - 1: + write("\r") + _output_cursor_forward(new.x) + elif new.x < current_x or current_x >= width - 1: + _output_cursor_backward(current_x - new.x) + elif new.x > current_x: + _output_cursor_forward(new.x - current_x) + + return new + + def output_char(char: Char) -> None: + """ + Write the output of this character. + """ + nonlocal last_style + + # If the last printed character has the same style, don't output the + # style again. + if last_style == char.style: + write(char.char) + else: + # Look up `Attr` for this style string. Only set attributes if different. + # (Two style strings can still have the same formatting.) + # Note that an empty style string can have formatting that needs to + # be applied, because of style transformations. + new_attrs = attrs_for_style_string[char.style] + if not last_style or new_attrs != attrs_for_style_string[last_style]: + _output_set_attributes(new_attrs, color_depth) + + write(char.char) + last_style = char.style + + def get_max_column_index(row: dict[int, Char]) -> int: + """ + Return max used column index, ignoring whitespace (without style) at + the end of the line. This is important for people that copy/paste + terminal output. + + There are two reasons we are sometimes seeing whitespace at the end: + - `BufferControl` adds a trailing space to each line, because it's a + possible cursor position, so that the line wrapping won't change if + the cursor position moves around. + - The `Window` adds a style class to the current line for highlighting + (cursor-line). + """ + numbers = ( + index + for index, cell in row.items() + if cell.char != " " or style_string_has_style[cell.style] + ) + return max(numbers, default=0) + + # Render for the first time: reset styling. + if not previous_screen: + reset_attributes() + + # Disable autowrap. (When entering a the alternate screen, or anytime when + # we have a prompt. - In the case of a REPL, like IPython, people can have + # background threads, and it's hard for debugging if their output is not + # wrapped.) + if not previous_screen or not full_screen: + output.disable_autowrap() + + # When the previous screen has a different size, redraw everything anyway. + # Also when we are done. (We might take up less rows, so clearing is important.) + if ( + is_done or not previous_screen or previous_width != width + ): # XXX: also consider height?? + current_pos = move_cursor(Point(x=0, y=0)) + reset_attributes() + output.erase_down() + + previous_screen = Screen() + + # Get height of the screen. + # (height changes as we loop over data_buffer, so remember the current value.) + # (Also make sure to clip the height to the size of the output.) + current_height = min(screen.height, height) + + # Loop over the rows. + row_count = min(max(screen.height, previous_screen.height), height) + + for y in range(row_count): + new_row = screen.data_buffer[y] + previous_row = previous_screen.data_buffer[y] + zero_width_escapes_row = screen.zero_width_escapes[y] + + new_max_line_len = min(width - 1, get_max_column_index(new_row)) + previous_max_line_len = min(width - 1, get_max_column_index(previous_row)) + + # Loop over the columns. + c = 0 # Column counter. + while c <= new_max_line_len: + new_char = new_row[c] + old_char = previous_row[c] + char_width = new_char.width or 1 + + # When the old and new character at this position are different, + # draw the output. (Because of the performance, we don't call + # `Char.__ne__`, but inline the same expression.) + if new_char.char != old_char.char or new_char.style != old_char.style: + current_pos = move_cursor(Point(x=c, y=y)) + + # Send injected escape sequences to output. + if c in zero_width_escapes_row: + write_raw(zero_width_escapes_row[c]) + + output_char(new_char) + current_pos = Point(x=current_pos.x + char_width, y=current_pos.y) + + c += char_width + + # If the new line is shorter, trim it. + if previous_screen and new_max_line_len < previous_max_line_len: + current_pos = move_cursor(Point(x=new_max_line_len + 1, y=y)) + reset_attributes() + output.erase_end_of_line() + + # Correctly reserve vertical space as required by the layout. + # When this is a new screen (drawn for the first time), or for some reason + # higher than the previous one. Move the cursor once to the bottom of the + # output. That way, we're sure that the terminal scrolls up, even when the + # lower lines of the canvas just contain whitespace. + + # The most obvious reason that we actually want this behavior is the avoid + # the artifact of the input scrolling when the completion menu is shown. + # (If the scrolling is actually wanted, the layout can still be build in a + # way to behave that way by setting a dynamic height.) + if current_height > previous_screen.height: + current_pos = move_cursor(Point(x=0, y=current_height - 1)) + + # Move cursor: + if is_done: + current_pos = move_cursor(Point(x=0, y=current_height)) + output.erase_down() + else: + current_pos = move_cursor(screen.get_cursor_position(app.layout.current_window)) + + if is_done or not full_screen: + output.enable_autowrap() + + # Always reset the color attributes. This is important because a background + # thread could print data to stdout and we want that to be displayed in the + # default colors. (Also, if a background color has been set, many terminals + # give weird artifacts on resize events.) + reset_attributes() + + if screen.show_cursor or is_done: + output.show_cursor() + + return current_pos, last_style + + +class HeightIsUnknownError(Exception): + "Information unavailable. Did not yet receive the CPR response." + + +class _StyleStringToAttrsCache(Dict[str, Attrs]): + """ + A cache structure that maps style strings to :class:`.Attr`. + (This is an important speed up.) + """ + + def __init__( + self, + get_attrs_for_style_str: Callable[[str], Attrs], + style_transformation: StyleTransformation, + ) -> None: + self.get_attrs_for_style_str = get_attrs_for_style_str + self.style_transformation = style_transformation + + def __missing__(self, style_str: str) -> Attrs: + attrs = self.get_attrs_for_style_str(style_str) + attrs = self.style_transformation.transform_attrs(attrs) + + self[style_str] = attrs + return attrs + + +class _StyleStringHasStyleCache(Dict[str, bool]): + """ + Cache for remember which style strings don't render the default output + style (default fg/bg, no underline and no reverse and no blink). That way + we know that we should render these cells, even when they're empty (when + they contain a space). + + Note: we don't consider bold/italic/hidden because they don't change the + output if there's no text in the cell. + """ + + def __init__(self, style_string_to_attrs: dict[str, Attrs]) -> None: + self.style_string_to_attrs = style_string_to_attrs + + def __missing__(self, style_str: str) -> bool: + attrs = self.style_string_to_attrs[style_str] + is_default = bool( + attrs.color + or attrs.bgcolor + or attrs.underline + or attrs.strike + or attrs.blink + or attrs.reverse + ) + + self[style_str] = is_default + return is_default + + +class CPR_Support(Enum): + "Enum: whether or not CPR is supported." + + SUPPORTED = "SUPPORTED" + NOT_SUPPORTED = "NOT_SUPPORTED" + UNKNOWN = "UNKNOWN" + + +class Renderer: + """ + Typical usage: + + :: + + output = Vt100_Output.from_pty(sys.stdout) + r = Renderer(style, output) + r.render(app, layout=...) + """ + + CPR_TIMEOUT = 2 # Time to wait until we consider CPR to be not supported. + + def __init__( + self, + style: BaseStyle, + output: Output, + full_screen: bool = False, + mouse_support: FilterOrBool = False, + cpr_not_supported_callback: Callable[[], None] | None = None, + ) -> None: + self.style = style + self.output = output + self.full_screen = full_screen + self.mouse_support = to_filter(mouse_support) + self.cpr_not_supported_callback = cpr_not_supported_callback + + self._in_alternate_screen = False + self._mouse_support_enabled = False + self._bracketed_paste_enabled = False + self._cursor_key_mode_reset = False + + # Future set when we are waiting for a CPR flag. + self._waiting_for_cpr_futures: deque[Future[None]] = deque() + self.cpr_support = CPR_Support.UNKNOWN + + if not output.responds_to_cpr: + self.cpr_support = CPR_Support.NOT_SUPPORTED + + # Cache for the style. + self._attrs_for_style: _StyleStringToAttrsCache | None = None + self._style_string_has_style: _StyleStringHasStyleCache | None = None + self._last_style_hash: Hashable | None = None + self._last_transformation_hash: Hashable | None = None + self._last_color_depth: ColorDepth | None = None + + self.reset(_scroll=True) + + def reset(self, _scroll: bool = False, leave_alternate_screen: bool = True) -> None: + # Reset position + self._cursor_pos = Point(x=0, y=0) + + # Remember the last screen instance between renderers. This way, + # we can create a `diff` between two screens and only output the + # difference. It's also to remember the last height. (To show for + # instance a toolbar at the bottom position.) + self._last_screen: Screen | None = None + self._last_size: Size | None = None + self._last_style: str | None = None + self._last_cursor_shape: CursorShape | None = None + + # Default MouseHandlers. (Just empty.) + self.mouse_handlers = MouseHandlers() + + #: Space from the top of the layout, until the bottom of the terminal. + #: We don't know this until a `report_absolute_cursor_row` call. + self._min_available_height = 0 + + # In case of Windows, also make sure to scroll to the current cursor + # position. (Only when rendering the first time.) + # It does nothing for vt100 terminals. + if _scroll: + self.output.scroll_buffer_to_prompt() + + # Quit alternate screen. + if self._in_alternate_screen and leave_alternate_screen: + self.output.quit_alternate_screen() + self._in_alternate_screen = False + + # Disable mouse support. + if self._mouse_support_enabled: + self.output.disable_mouse_support() + self._mouse_support_enabled = False + + # Disable bracketed paste. + if self._bracketed_paste_enabled: + self.output.disable_bracketed_paste() + self._bracketed_paste_enabled = False + + self.output.reset_cursor_shape() + + # NOTE: No need to set/reset cursor key mode here. + + # Flush output. `disable_mouse_support` needs to write to stdout. + self.output.flush() + + @property + def last_rendered_screen(self) -> Screen | None: + """ + The `Screen` class that was generated during the last rendering. + This can be `None`. + """ + return self._last_screen + + @property + def height_is_known(self) -> bool: + """ + True when the height from the cursor until the bottom of the terminal + is known. (It's often nicer to draw bottom toolbars only if the height + is known, in order to avoid flickering when the CPR response arrives.) + """ + if self.full_screen or self._min_available_height > 0: + return True + try: + self._min_available_height = self.output.get_rows_below_cursor_position() + return True + except NotImplementedError: + return False + + @property + def rows_above_layout(self) -> int: + """ + Return the number of rows visible in the terminal above the layout. + """ + if self._in_alternate_screen: + return 0 + elif self._min_available_height > 0: + total_rows = self.output.get_size().rows + last_screen_height = self._last_screen.height if self._last_screen else 0 + return total_rows - max(self._min_available_height, last_screen_height) + else: + raise HeightIsUnknownError("Rows above layout is unknown.") + + def request_absolute_cursor_position(self) -> None: + """ + Get current cursor position. + + We do this to calculate the minimum available height that we can + consume for rendering the prompt. This is the available space below te + cursor. + + For vt100: Do CPR request. (answer will arrive later.) + For win32: Do API call. (Answer comes immediately.) + """ + # Only do this request when the cursor is at the top row. (after a + # clear or reset). We will rely on that in `report_absolute_cursor_row`. + assert self._cursor_pos.y == 0 + + # In full-screen mode, always use the total height as min-available-height. + if self.full_screen: + self._min_available_height = self.output.get_size().rows + return + + # For Win32, we have an API call to get the number of rows below the + # cursor. + try: + self._min_available_height = self.output.get_rows_below_cursor_position() + return + except NotImplementedError: + pass + + # Use CPR. + if self.cpr_support == CPR_Support.NOT_SUPPORTED: + return + + def do_cpr() -> None: + # Asks for a cursor position report (CPR). + self._waiting_for_cpr_futures.append(Future()) + self.output.ask_for_cpr() + + if self.cpr_support == CPR_Support.SUPPORTED: + do_cpr() + return + + # If we don't know whether CPR is supported, only do a request if + # none is pending, and test it, using a timer. + if self.waiting_for_cpr: + return + + do_cpr() + + async def timer() -> None: + await sleep(self.CPR_TIMEOUT) + + # Not set in the meantime -> not supported. + if self.cpr_support == CPR_Support.UNKNOWN: + self.cpr_support = CPR_Support.NOT_SUPPORTED + + if self.cpr_not_supported_callback: + # Make sure to call this callback in the main thread. + self.cpr_not_supported_callback() + + get_app().create_background_task(timer()) + + def report_absolute_cursor_row(self, row: int) -> None: + """ + To be called when we know the absolute cursor position. + (As an answer of a "Cursor Position Request" response.) + """ + self.cpr_support = CPR_Support.SUPPORTED + + # Calculate the amount of rows from the cursor position until the + # bottom of the terminal. + total_rows = self.output.get_size().rows + rows_below_cursor = total_rows - row + 1 + + # Set the minimum available height. + self._min_available_height = rows_below_cursor + + # Pop and set waiting for CPR future. + try: + f = self._waiting_for_cpr_futures.popleft() + except IndexError: + pass # Received CPR response without having a CPR. + else: + f.set_result(None) + + @property + def waiting_for_cpr(self) -> bool: + """ + Waiting for CPR flag. True when we send the request, but didn't got a + response. + """ + return bool(self._waiting_for_cpr_futures) + + async def wait_for_cpr_responses(self, timeout: int = 1) -> None: + """ + Wait for a CPR response. + """ + cpr_futures = list(self._waiting_for_cpr_futures) # Make copy. + + # When there are no CPRs in the queue. Don't do anything. + if not cpr_futures or self.cpr_support == CPR_Support.NOT_SUPPORTED: + return None + + async def wait_for_responses() -> None: + for response_f in cpr_futures: + await response_f + + async def wait_for_timeout() -> None: + await sleep(timeout) + + # Got timeout, erase queue. + for response_f in cpr_futures: + response_f.cancel() + self._waiting_for_cpr_futures = deque() + + tasks = { + ensure_future(wait_for_responses()), + ensure_future(wait_for_timeout()), + } + _, pending = await wait(tasks, return_when=FIRST_COMPLETED) + for task in pending: + task.cancel() + + def render( + self, app: Application[Any], layout: Layout, is_done: bool = False + ) -> None: + """ + Render the current interface to the output. + + :param is_done: When True, put the cursor at the end of the interface. We + won't print any changes to this part. + """ + output = self.output + + # Enter alternate screen. + if self.full_screen and not self._in_alternate_screen: + self._in_alternate_screen = True + output.enter_alternate_screen() + + # Enable bracketed paste. + if not self._bracketed_paste_enabled: + self.output.enable_bracketed_paste() + self._bracketed_paste_enabled = True + + # Reset cursor key mode. + if not self._cursor_key_mode_reset: + self.output.reset_cursor_key_mode() + self._cursor_key_mode_reset = True + + # Enable/disable mouse support. + needs_mouse_support = self.mouse_support() + + if needs_mouse_support and not self._mouse_support_enabled: + output.enable_mouse_support() + self._mouse_support_enabled = True + + elif not needs_mouse_support and self._mouse_support_enabled: + output.disable_mouse_support() + self._mouse_support_enabled = False + + # Create screen and write layout to it. + size = output.get_size() + screen = Screen() + screen.show_cursor = False # Hide cursor by default, unless one of the + # containers decides to display it. + mouse_handlers = MouseHandlers() + + # Calculate height. + if self.full_screen: + height = size.rows + elif is_done: + # When we are done, we don't necessary want to fill up until the bottom. + height = layout.container.preferred_height( + size.columns, size.rows + ).preferred + else: + last_height = self._last_screen.height if self._last_screen else 0 + height = max( + self._min_available_height, + last_height, + layout.container.preferred_height(size.columns, size.rows).preferred, + ) + + height = min(height, size.rows) + + # When the size changes, don't consider the previous screen. + if self._last_size != size: + self._last_screen = None + + # When we render using another style or another color depth, do a full + # repaint. (Forget about the previous rendered screen.) + # (But note that we still use _last_screen to calculate the height.) + if ( + self.style.invalidation_hash() != self._last_style_hash + or app.style_transformation.invalidation_hash() + != self._last_transformation_hash + or app.color_depth != self._last_color_depth + ): + self._last_screen = None + self._attrs_for_style = None + self._style_string_has_style = None + + if self._attrs_for_style is None: + self._attrs_for_style = _StyleStringToAttrsCache( + self.style.get_attrs_for_style_str, app.style_transformation + ) + if self._style_string_has_style is None: + self._style_string_has_style = _StyleStringHasStyleCache( + self._attrs_for_style + ) + + self._last_style_hash = self.style.invalidation_hash() + self._last_transformation_hash = app.style_transformation.invalidation_hash() + self._last_color_depth = app.color_depth + + layout.container.write_to_screen( + screen, + mouse_handlers, + WritePosition(xpos=0, ypos=0, width=size.columns, height=height), + parent_style="", + erase_bg=False, + z_index=None, + ) + screen.draw_all_floats() + + # When grayed. Replace all styles in the new screen. + if app.exit_style: + screen.append_style_to_content(app.exit_style) + + # Process diff and write to output. + self._cursor_pos, self._last_style = _output_screen_diff( + app, + output, + screen, + self._cursor_pos, + app.color_depth, + self._last_screen, + self._last_style, + is_done, + full_screen=self.full_screen, + attrs_for_style_string=self._attrs_for_style, + style_string_has_style=self._style_string_has_style, + size=size, + previous_width=(self._last_size.columns if self._last_size else 0), + ) + self._last_screen = screen + self._last_size = size + self.mouse_handlers = mouse_handlers + + # Handle cursor shapes. + new_cursor_shape = app.cursor.get_cursor_shape(app) + if ( + self._last_cursor_shape is None + or self._last_cursor_shape != new_cursor_shape + ): + output.set_cursor_shape(new_cursor_shape) + self._last_cursor_shape = new_cursor_shape + + # Flush buffered output. + output.flush() + + # Set visible windows in layout. + app.layout.visible_windows = screen.visible_windows + + if is_done: + self.reset() + + def erase(self, leave_alternate_screen: bool = True) -> None: + """ + Hide all output and put the cursor back at the first line. This is for + instance used for running a system command (while hiding the CLI) and + later resuming the same CLI.) + + :param leave_alternate_screen: When True, and when inside an alternate + screen buffer, quit the alternate screen. + """ + output = self.output + + output.cursor_backward(self._cursor_pos.x) + output.cursor_up(self._cursor_pos.y) + output.erase_down() + output.reset_attributes() + output.enable_autowrap() + + output.flush() + + self.reset(leave_alternate_screen=leave_alternate_screen) + + def clear(self) -> None: + """ + Clear screen and go to 0,0 + """ + # Erase current output first. + self.erase() + + # Send "Erase Screen" command and go to (0, 0). + output = self.output + + output.erase_screen() + output.cursor_goto(0, 0) + output.flush() + + self.request_absolute_cursor_position() + + +def print_formatted_text( + output: Output, + formatted_text: AnyFormattedText, + style: BaseStyle, + style_transformation: StyleTransformation | None = None, + color_depth: ColorDepth | None = None, +) -> None: + """ + Print a list of (style_str, text) tuples in the given style to the output. + """ + fragments = to_formatted_text(formatted_text) + style_transformation = style_transformation or DummyStyleTransformation() + color_depth = color_depth or output.get_default_color_depth() + + # Reset first. + output.reset_attributes() + output.enable_autowrap() + last_attrs: Attrs | None = None + + # Print all (style_str, text) tuples. + attrs_for_style_string = _StyleStringToAttrsCache( + style.get_attrs_for_style_str, style_transformation + ) + + for style_str, text, *_ in fragments: + attrs = attrs_for_style_string[style_str] + + # Set style attributes if something changed. + if attrs != last_attrs: + if attrs: + output.set_attributes(attrs, color_depth) + else: + output.reset_attributes() + last_attrs = attrs + + # Print escape sequences as raw output + if "[ZeroWidthEscape]" in style_str: + output.write_raw(text) + else: + # Eliminate carriage returns + text = text.replace("\r", "") + # Insert a carriage return before every newline (important when the + # front-end is a telnet client). + text = text.replace("\n", "\r\n") + output.write(text) + + # Reset again. + output.reset_attributes() + output.flush() diff --git a/shared/package-files/7b/7b7810136fab605d8c8fd105a9260e28e8cc0e6cacf28fb269eed212388e784b/blob b/shared/package-files/7b/7b7810136fab605d8c8fd105a9260e28e8cc0e6cacf28fb269eed212388e784b/blob new file mode 100644 index 0000000000000000000000000000000000000000..4d532d0f4d589efa103890a10fa41d047a223ead --- /dev/null +++ b/shared/package-files/7b/7b7810136fab605d8c8fd105a9260e28e8cc0e6cacf28fb269eed212388e784b/blob @@ -0,0 +1,155 @@ +# coding: utf-8 +""" +Support for creating GUI apps and starting event loops. + +IPython's GUI integration allows interactive plotting and GUI usage in IPython +session. IPython has two different types of GUI integration: + +1. The terminal based IPython supports GUI event loops through Python's + PyOS_InputHook. PyOS_InputHook is a hook that Python calls periodically + whenever raw_input is waiting for a user to type code. We implement GUI + support in the terminal by setting PyOS_InputHook to a function that + iterates the event loop for a short while. It is important to note that + in this situation, the real GUI event loop is NOT run in the normal + manner, so you can't use the normal means to detect that it is running. +2. In the two process IPython kernel/frontend, the GUI event loop is run in + the kernel. In this case, the event loop is run in the normal manner by + calling the function or method of the GUI toolkit that starts the event + loop. + +In addition to starting the GUI event loops in one of these two ways, IPython +will *always* create an appropriate GUI application object when GUi +integration is enabled. + +If you want your GUI apps to run in IPython you need to do two things: + +1. Test to see if there is already an existing main application object. If + there is, you should use it. If there is not an existing application object + you should create one. +2. Test to see if the GUI event loop is running. If it is, you should not + start it. If the event loop is not running you may start it. + +This module contains functions for each toolkit that perform these things +in a consistent manner. Because of how PyOS_InputHook runs the event loop +you cannot detect if the event loop is running using the traditional calls +(such as ``wx.GetApp.IsMainLoopRunning()`` in wxPython). If PyOS_InputHook is +set These methods will return a false negative. That is, they will say the +event loop is not running, when is actually is. To work around this limitation +we proposed the following informal protocol: + +* Whenever someone starts the event loop, they *must* set the ``_in_event_loop`` + attribute of the main application object to ``True``. This should be done + regardless of how the event loop is actually run. +* Whenever someone stops the event loop, they *must* set the ``_in_event_loop`` + attribute of the main application object to ``False``. +* If you want to see if the event loop is running, you *must* use ``hasattr`` + to see if ``_in_event_loop`` attribute has been set. If it is set, you + *must* use its value. If it has not been set, you can query the toolkit + in the normal manner. +* If you want GUI support and no one else has created an application or + started the event loop you *must* do this. We don't want projects to + attempt to defer these things to someone else if they themselves need it. + +The functions below implement this logic for each GUI toolkit. If you need +to create custom application subclasses, you will likely have to modify this +code for your own purposes. This code can be copied into your own project +so you don't have to depend on IPython. + +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +from IPython.core.getipython import get_ipython + +#----------------------------------------------------------------------------- +# wx +#----------------------------------------------------------------------------- + +def get_app_wx(*args, **kwargs): + """Create a new wx app or return an exiting one.""" + import wx + app = wx.GetApp() + if app is None: + if 'redirect' not in kwargs: + kwargs['redirect'] = False + app = wx.PySimpleApp(*args, **kwargs) + return app + +def is_event_loop_running_wx(app=None): + """Is the wx event loop running.""" + # New way: check attribute on shell instance + ip = get_ipython() + if ip is not None: + if ip.active_eventloop and ip.active_eventloop == 'wx': + return True + # Fall through to checking the application, because Wx has a native way + # to check if the event loop is running, unlike Qt. + + # Old way: check Wx application + if app is None: + app = get_app_wx() + if hasattr(app, '_in_event_loop'): + return app._in_event_loop + else: + return app.IsMainLoopRunning() + +def start_event_loop_wx(app=None): + """Start the wx event loop in a consistent manner.""" + if app is None: + app = get_app_wx() + if not is_event_loop_running_wx(app): + app._in_event_loop = True + app.MainLoop() + app._in_event_loop = False + else: + app._in_event_loop = True + +#----------------------------------------------------------------------------- +# Qt +#----------------------------------------------------------------------------- + +def get_app_qt4(*args, **kwargs): + """Create a new Qt app or return an existing one.""" + from IPython.external.qt_for_kernel import QtGui + app = QtGui.QApplication.instance() + if app is None: + if not args: + args = ([""],) + app = QtGui.QApplication(*args, **kwargs) + return app + +def is_event_loop_running_qt4(app=None): + """Is the qt event loop running.""" + # New way: check attribute on shell instance + ip = get_ipython() + if ip is not None: + return ip.active_eventloop and ip.active_eventloop.startswith('qt') + + # Old way: check attribute on QApplication singleton + if app is None: + app = get_app_qt4([""]) + if hasattr(app, '_in_event_loop'): + return app._in_event_loop + else: + # Does qt provide a other way to detect this? + return False + +def start_event_loop_qt4(app=None): + """Start the qt event loop in a consistent manner.""" + if app is None: + app = get_app_qt4([""]) + if not is_event_loop_running_qt4(app): + app._in_event_loop = True + app.exec_() + app._in_event_loop = False + else: + app._in_event_loop = True + +#----------------------------------------------------------------------------- +# Tk +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# gtk +#----------------------------------------------------------------------------- diff --git a/shared/package-files/7b/7b7843467339e537b2f209bab8866453d5da28be8ad61402a9b830a362447c3f/blob b/shared/package-files/7b/7b7843467339e537b2f209bab8866453d5da28be8ad61402a9b830a362447c3f/blob new file mode 100644 index 0000000000000000000000000000000000000000..3070976c294d2c103780aec9a5218a573e46a3c3 --- /dev/null +++ b/shared/package-files/7b/7b7843467339e537b2f209bab8866453d5da28be8ad61402a9b830a362447c3f/blob @@ -0,0 +1,7 @@ +from typing import Any, List, Optional + +from django.urls.resolvers import URLPattern + +urlpatterns: List[Any] = ... + +def staticfiles_urlpatterns(prefix: Optional[str] = ...) -> List[URLPattern]: ... diff --git a/shared/package-files/7b/7b7a32d82ba0f1488b524082f9ba6ff7a9accc095c2ff01de2830c01e70fae7e/blob b/shared/package-files/7b/7b7a32d82ba0f1488b524082f9ba6ff7a9accc095c2ff01de2830c01e70fae7e/blob new file mode 100644 index 0000000000000000000000000000000000000000..f885a233fbed2c46b8d73c615b32dc327be5cae5 --- /dev/null +++ b/shared/package-files/7b/7b7a32d82ba0f1488b524082f9ba6ff7a9accc095c2ff01de2830c01e70fae7e/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor log2(const at::Tensor & self); +TORCH_API at::Tensor & log2_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & log2_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & log2_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/7b/7b7b06c26204d5c4c9dadf57944297ce1ed7fee9f0330738e11f5b5d49f994d3/blob b/shared/package-files/7b/7b7b06c26204d5c4c9dadf57944297ce1ed7fee9f0330738e11f5b5d49f994d3/blob new file mode 100644 index 0000000000000000000000000000000000000000..6332bfdc50e0112e2184f7f02da88f1b15b2f284 --- /dev/null +++ b/shared/package-files/7b/7b7b06c26204d5c4c9dadf57944297ce1ed7fee9f0330738e11f5b5d49f994d3/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor atan(const at::Tensor & self); +TORCH_API at::Tensor & atan_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & atan_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & atan_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/shared/package-files/7b/7b815b9980973b8a265c570c5b69faaa4fc275cc31d5e287c940f91fe07bd5f7/blob b/shared/package-files/7b/7b815b9980973b8a265c570c5b69faaa4fc275cc31d5e287c940f91fe07bd5f7/blob new file mode 100644 index 0000000000000000000000000000000000000000..96fef89ac35a271f3a5501beaefd06da13ede685 --- /dev/null +++ b/shared/package-files/7b/7b815b9980973b8a265c570c5b69faaa4fc275cc31d5e287c940f91fe07bd5f7/blob @@ -0,0 +1,575 @@ +""" +Implementation of Harwell-Boeing read/write. + +At the moment not the full Harwell-Boeing format is supported. Supported +features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + +""" +# TODO: +# - Add more support (symmetric/complex matrices, non-assembled matrices ?) + +# XXX: reading is reasonably efficient (>= 85 % is in numpy.fromstring), but +# takes a lot of memory. Being faster would require compiled code. +# write is not efficient. Although not a terribly exciting task, +# having reusable facilities to efficiently read/write fortran-formatted files +# would be useful outside this module. + +import warnings + +import numpy as np +from scipy.sparse import csc_array, csc_matrix +from ._fortran_format_parser import FortranFormatParser, IntFormat, ExpFormat + +__all__ = ["hb_read", "hb_write"] + + +class MalformedHeader(Exception): + pass + + +class LineOverflow(Warning): + pass + + +def _nbytes_full(fmt, nlines): + """Return the number of bytes to read to get every full lines for the + given parsed fortran format.""" + return (fmt.repeat * fmt.width + 1) * (nlines - 1) + + +class HBInfo: + @classmethod + def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None): + """Create a HBInfo instance from an existing sparse matrix. + + Parameters + ---------- + m : sparse array or matrix + the HBInfo instance will derive its parameters from m + title : str + Title to put in the HB header + key : str + Key + mxtype : HBMatrixType + type of the input matrix + fmt : dict + not implemented + + Returns + ------- + hb_info : HBInfo instance + """ + m = m.tocsc(copy=False) + + pointer = m.indptr + indices = m.indices + values = m.data + + nrows, ncols = m.shape + nnon_zeros = m.nnz + + if fmt is None: + # +1 because HB use one-based indexing (Fortran), and we will write + # the indices /pointer as such + pointer_fmt = IntFormat.from_number(np.max(pointer+1)) + indices_fmt = IntFormat.from_number(np.max(indices+1)) + + if values.dtype.kind in np.typecodes["AllFloat"]: + values_fmt = ExpFormat.from_number(-np.max(np.abs(values))) + elif values.dtype.kind in np.typecodes["AllInteger"]: + values_fmt = IntFormat.from_number(-np.max(np.abs(values))) + else: + message = f"type {values.dtype.kind} not implemented yet" + raise NotImplementedError(message) + else: + raise NotImplementedError("fmt argument not supported yet.") + + if mxtype is None: + if not np.isrealobj(values): + raise ValueError("Complex values not supported yet") + if values.dtype.kind in np.typecodes["AllInteger"]: + tp = "integer" + elif values.dtype.kind in np.typecodes["AllFloat"]: + tp = "real" + else: + raise NotImplementedError( + f"type {values.dtype} for values not implemented") + mxtype = HBMatrixType(tp, "unsymmetric", "assembled") + else: + raise ValueError("mxtype argument not handled yet.") + + def _nlines(fmt, size): + nlines = size // fmt.repeat + if nlines * fmt.repeat != size: + nlines += 1 + return nlines + + pointer_nlines = _nlines(pointer_fmt, pointer.size) + indices_nlines = _nlines(indices_fmt, indices.size) + values_nlines = _nlines(values_fmt, values.size) + + total_nlines = pointer_nlines + indices_nlines + values_nlines + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_fmt.fortran_format, indices_fmt.fortran_format, + values_fmt.fortran_format) + + @classmethod + def from_file(cls, fid): + """Create a HBInfo instance from a file object containing a matrix in the + HB format. + + Parameters + ---------- + fid : file-like matrix + File or file-like object containing a matrix in the HB format. + + Returns + ------- + hb_info : HBInfo instance + """ + # First line + line = fid.readline().strip("\n") + if not len(line) > 72: + raise ValueError("Expected at least 72 characters for first line, " + f"got: \n{line}") + title = line[:72] + key = line[72:] + + # Second line + line = fid.readline().strip("\n") + if not len(line.rstrip()) >= 56: + raise ValueError("Expected at least 56 characters for second line, " + f"got: \n{line}") + total_nlines = _expect_int(line[:14]) + pointer_nlines = _expect_int(line[14:28]) + indices_nlines = _expect_int(line[28:42]) + values_nlines = _expect_int(line[42:56]) + + rhs_nlines = line[56:72].strip() + if rhs_nlines == '': + rhs_nlines = 0 + else: + rhs_nlines = _expect_int(rhs_nlines) + if not rhs_nlines == 0: + raise ValueError("Only files without right hand side supported for " + "now.") + + # Third line + line = fid.readline().strip("\n") + if not len(line) >= 70: + raise ValueError(f"Expected at least 72 character for third line, " + f"got:\n{line}") + + mxtype_s = line[:3].upper() + if not len(mxtype_s) == 3: + raise ValueError("mxtype expected to be 3 characters long") + + mxtype = HBMatrixType.from_fortran(mxtype_s) + if mxtype.value_type not in ["real", "integer"]: + raise ValueError("Only real or integer matrices supported for " + f"now (detected {mxtype})") + if not mxtype.structure == "unsymmetric": + raise ValueError("Only unsymmetric matrices supported for " + f"now (detected {mxtype})") + if not mxtype.storage == "assembled": + raise ValueError("Only assembled matrices supported for now") + + if not line[3:14] == " " * 11: + raise ValueError(f"Malformed data for third line: {line}") + + nrows = _expect_int(line[14:28]) + ncols = _expect_int(line[28:42]) + nnon_zeros = _expect_int(line[42:56]) + nelementals = _expect_int(line[56:70]) + if not nelementals == 0: + raise ValueError("Unexpected value %d for nltvl (last entry of line 3)" + % nelementals) + + # Fourth line + line = fid.readline().strip("\n") + + ct = line.split() + if not len(ct) == 3: + raise ValueError(f"Expected 3 formats, got {ct}") + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + ct[0], ct[1], ct[2], + rhs_nlines, nelementals) + + def __init__(self, title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_format_str, indices_format_str, values_format_str, + right_hand_sides_nlines=0, nelementals=0): + """Do not use this directly, but the class ctrs (from_* functions).""" + if title is None: + title = "No Title" + if len(title) > 72: + raise ValueError("title cannot be > 72 characters") + + if key is None: + key = "|No Key" + if len(key) > 8: + warnings.warn(f"key is > 8 characters (key is {key})", + LineOverflow, stacklevel=3) + self.title = title + self.key = key + + self.total_nlines = total_nlines + self.pointer_nlines = pointer_nlines + self.indices_nlines = indices_nlines + self.values_nlines = values_nlines + + parser = FortranFormatParser() + pointer_format = parser.parse(pointer_format_str) + if not isinstance(pointer_format, IntFormat): + raise ValueError("Expected int format for pointer format, got " + f"{pointer_format}") + + indices_format = parser.parse(indices_format_str) + if not isinstance(indices_format, IntFormat): + raise ValueError("Expected int format for indices format, got " + f"{indices_format}") + + values_format = parser.parse(values_format_str) + if isinstance(values_format, ExpFormat): + if mxtype.value_type not in ["real", "complex"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + values_dtype = np.float64 + elif isinstance(values_format, IntFormat): + if mxtype.value_type not in ["integer"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + # XXX: fortran int -> dtype association ? + values_dtype = int + else: + raise ValueError(f"Unsupported format for values {values_format!r}") + + self.pointer_format = pointer_format + self.indices_format = indices_format + self.values_format = values_format + + self.pointer_dtype = np.int32 + self.indices_dtype = np.int32 + self.values_dtype = values_dtype + + self.pointer_nlines = pointer_nlines + self.pointer_nbytes_full = _nbytes_full(pointer_format, pointer_nlines) + + self.indices_nlines = indices_nlines + self.indices_nbytes_full = _nbytes_full(indices_format, indices_nlines) + + self.values_nlines = values_nlines + self.values_nbytes_full = _nbytes_full(values_format, values_nlines) + + self.nrows = nrows + self.ncols = ncols + self.nnon_zeros = nnon_zeros + self.nelementals = nelementals + self.mxtype = mxtype + + def dump(self): + """Gives the header corresponding to this instance as a string.""" + header = [self.title.ljust(72) + self.key.ljust(8)] + + header.append("%14d%14d%14d%14d" % + (self.total_nlines, self.pointer_nlines, + self.indices_nlines, self.values_nlines)) + header.append("%14s%14d%14d%14d%14d" % + (self.mxtype.fortran_format.ljust(14), self.nrows, + self.ncols, self.nnon_zeros, 0)) + + pffmt = self.pointer_format.fortran_format + iffmt = self.indices_format.fortran_format + vffmt = self.values_format.fortran_format + header.append("%16s%16s%20s" % + (pffmt.ljust(16), iffmt.ljust(16), vffmt.ljust(20))) + return "\n".join(header) + + +def _expect_int(value, msg=None): + try: + return int(value) + except ValueError as e: + if msg is None: + msg = "Expected an int, got %s" + raise ValueError(msg % value) from e + + +def _read_hb_data(content, header): + # XXX: look at a way to reduce memory here (big string creation) + ptr_string = "".join([content.read(header.pointer_nbytes_full), + content.readline()]) + ptr = np.fromstring(ptr_string, + dtype=int, sep=' ') + + ind_string = "".join([content.read(header.indices_nbytes_full), + content.readline()]) + ind = np.fromstring(ind_string, + dtype=int, sep=' ') + + val_string = "".join([content.read(header.values_nbytes_full), + content.readline()]) + val = np.fromstring(val_string, + dtype=header.values_dtype, sep=' ') + + return csc_array((val, ind-1, ptr-1), shape=(header.nrows, header.ncols)) + + +def _write_data(m, fid, header): + m = m.tocsc(copy=False) + + def write_array(f, ar, nlines, fmt): + # ar_nlines is the number of full lines, n is the number of items per + # line, ffmt the fortran format + pyfmt = fmt.python_format + pyfmt_full = pyfmt * fmt.repeat + + # for each array to write, we first write the full lines, and special + # case for partial line + full = ar[:(nlines - 1) * fmt.repeat] + for row in full.reshape((nlines-1, fmt.repeat)): + f.write(pyfmt_full % tuple(row) + "\n") + nremain = ar.size - full.size + if nremain > 0: + f.write((pyfmt * nremain) % tuple(ar[ar.size - nremain:]) + "\n") + + fid.write(header.dump()) + fid.write("\n") + # +1 is for Fortran one-based indexing + write_array(fid, m.indptr+1, header.pointer_nlines, + header.pointer_format) + write_array(fid, m.indices+1, header.indices_nlines, + header.indices_format) + write_array(fid, m.data, header.values_nlines, + header.values_format) + + +class HBMatrixType: + """Class to hold the matrix type.""" + # q2f* translates qualified names to Fortran character + _q2f_type = { + "real": "R", + "complex": "C", + "pattern": "P", + "integer": "I", + } + _q2f_structure = { + "symmetric": "S", + "unsymmetric": "U", + "hermitian": "H", + "skewsymmetric": "Z", + "rectangular": "R" + } + _q2f_storage = { + "assembled": "A", + "elemental": "E", + } + + _f2q_type = {j: i for i, j in _q2f_type.items()} + _f2q_structure = {j: i for i, j in _q2f_structure.items()} + _f2q_storage = {j: i for i, j in _q2f_storage.items()} + + @classmethod + def from_fortran(cls, fmt): + if not len(fmt) == 3: + raise ValueError("Fortran format for matrix type should be 3 " + "characters long") + try: + value_type = cls._f2q_type[fmt[0]] + structure = cls._f2q_structure[fmt[1]] + storage = cls._f2q_storage[fmt[2]] + return cls(value_type, structure, storage) + except KeyError as e: + raise ValueError(f"Unrecognized format {fmt}") from e + + def __init__(self, value_type, structure, storage="assembled"): + self.value_type = value_type + self.structure = structure + self.storage = storage + + if value_type not in self._q2f_type: + raise ValueError(f"Unrecognized type {value_type}") + if structure not in self._q2f_structure: + raise ValueError(f"Unrecognized structure {structure}") + if storage not in self._q2f_storage: + raise ValueError(f"Unrecognized storage {storage}") + + @property + def fortran_format(self): + return self._q2f_type[self.value_type] + \ + self._q2f_structure[self.structure] + \ + self._q2f_storage[self.storage] + + def __repr__(self): + return f"HBMatrixType({self.value_type}, {self.structure}, {self.storage})" + + +class HBFile: + def __init__(self, file, hb_info=None): + """Create a HBFile instance. + + Parameters + ---------- + file : file-object + StringIO work as well + hb_info : HBInfo, optional + Should be given as an argument for writing, in which case the file + should be writable. + """ + self._fid = file + if hb_info is None: + self._hb_info = HBInfo.from_file(file) + else: + #raise OSError("file %s is not writable, and hb_info " + # "was given." % file) + self._hb_info = hb_info + + @property + def title(self): + return self._hb_info.title + + @property + def key(self): + return self._hb_info.key + + @property + def type(self): + return self._hb_info.mxtype.value_type + + @property + def structure(self): + return self._hb_info.mxtype.structure + + @property + def storage(self): + return self._hb_info.mxtype.storage + + def read_matrix(self): + return _read_hb_data(self._fid, self._hb_info) + + def write_matrix(self, m): + return _write_data(m, self._fid, self._hb_info) + + +def hb_read(path_or_open_file, *, spmatrix=True): + """Read HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before reading. + spmatrix : bool, optional (default: True) + If ``True``, return sparse ``coo_matrix``. Otherwise return ``coo_array``. + + Returns + ------- + data : csc_array or csc_matrix + The data read from the HB file as a sparse array. + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_array, eye + >>> data = csr_array(eye(3)) # create a sparse array + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb", spmatrix=False)) # read a hb file + + Coords Values + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + """ + def _get_matrix(fid): + hb = HBFile(fid) + return hb.read_matrix() + + if hasattr(path_or_open_file, 'read'): + data = _get_matrix(path_or_open_file) + else: + with open(path_or_open_file) as f: + data = _get_matrix(f) + if spmatrix: + return csc_matrix(data) + return data + + +def hb_write(path_or_open_file, m, hb_info=None): + """Write HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before writing. + m : sparse array or matrix + the sparse array to write + hb_info : HBInfo + contains the meta-data for write + + Returns + ------- + None + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_array, eye + >>> data = csr_array(eye(3)) # create a sparse array + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb", spmatrix=False)) # read a hb file + + Coords Values + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + """ + m = m.tocsc(copy=False) + + if hb_info is None: + hb_info = HBInfo.from_data(m) + + def _set_matrix(fid): + hb = HBFile(fid, hb_info) + return hb.write_matrix(m) + + if hasattr(path_or_open_file, 'write'): + return _set_matrix(path_or_open_file) + else: + with open(path_or_open_file, 'w') as f: + return _set_matrix(f) diff --git a/shared/package-files/7b/7b83320c5e6c25207d7cdc36ebdbe12d79418020d9c7f0b5bdba19e65fe5fcc1/blob b/shared/package-files/7b/7b83320c5e6c25207d7cdc36ebdbe12d79418020d9c7f0b5bdba19e65fe5fcc1/blob new file mode 100644 index 0000000000000000000000000000000000000000..3e2600f7ae9b33268c241b8d81715839e30d955f --- /dev/null +++ b/shared/package-files/7b/7b83320c5e6c25207d7cdc36ebdbe12d79418020d9c7f0b5bdba19e65fe5fcc1/blob @@ -0,0 +1,69 @@ +from . import DefaultTable +import sys +import array +import logging + +log = logging.getLogger(__name__) + + +class table__l_o_c_a(DefaultTable.DefaultTable): + """Index to Location table + + The ``loca`` table stores the offsets in the ``glyf`` table that correspond + to the descriptions of each glyph. The glyphs are references by Glyph ID. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/loca + """ + + dependencies = ["glyf"] + + def decompile(self, data, ttFont): + longFormat = ttFont["head"].indexToLocFormat + if longFormat: + format = "I" + else: + format = "H" + locations = array.array(format) + locations.frombytes(data) + if sys.byteorder != "big": + locations.byteswap() + if not longFormat: + locations = array.array("I", (2 * l for l in locations)) + if len(locations) < (ttFont["maxp"].numGlyphs + 1): + log.warning( + "corrupt 'loca' table, or wrong numGlyphs in 'maxp': %d %d", + len(locations) - 1, + ttFont["maxp"].numGlyphs, + ) + self.locations = locations + + def compile(self, ttFont): + try: + max_location = max(self.locations) + except AttributeError: + self.set([]) + max_location = 0 + if max_location < 0x20000 and all(l % 2 == 0 for l in self.locations): + locations = array.array("H") + for location in self.locations: + locations.append(location // 2) + ttFont["head"].indexToLocFormat = 0 + else: + locations = array.array("I", self.locations) + ttFont["head"].indexToLocFormat = 1 + if sys.byteorder != "big": + locations.byteswap() + return locations.tobytes() + + def set(self, locations): + self.locations = array.array("I", locations) + + def toXML(self, writer, ttFont): + writer.comment("The 'loca' table will be calculated by the compiler") + writer.newline() + + def __getitem__(self, index): + return self.locations[index] + + def __len__(self): + return len(self.locations) diff --git a/shared/package-files/7b/7b83eb6db89a2ad90add59d480723f91092c61d5f0bad4f5515cf0fba809e0e9/blob b/shared/package-files/7b/7b83eb6db89a2ad90add59d480723f91092c61d5f0bad4f5515cf0fba809e0e9/blob new file mode 100644 index 0000000000000000000000000000000000000000..8e1067c433f1c54958de097374b0a399cd2f20cb --- /dev/null +++ b/shared/package-files/7b/7b83eb6db89a2ad90add59d480723f91092c61d5f0bad4f5515cf0fba809e0e9/blob @@ -0,0 +1,2844 @@ +from statsmodels.compat.pandas import MONTH_END, YEAR_END, assert_index_equal +from statsmodels.compat.platform import PLATFORM_WIN +from statsmodels.compat.python import PYTHON_IMPL_WASM, lrange + +from pathlib import Path +import warnings + +import numpy as np +from numpy.testing import ( + assert_allclose, + assert_almost_equal, + assert_equal, +) +import pandas as pd +from pandas import DataFrame, Series, date_range +import pytest +from scipy import stats +from scipy.interpolate import interp1d + +from statsmodels.datasets import macrodata, modechoice, nile, randhie, sunspots +from statsmodels.regression.linear_model import OLS +from statsmodels.tools.sm_exceptions import ( + CollinearityWarning, + InfeasibleTestError, + InterpolationWarning, + MissingDataError, + SingularMatrixWarning, +) + +# Remove imports when range unit root test gets an R implementation +from statsmodels.tools.validation import array_like, bool_like +from statsmodels.tsa.arima_process import arma_acovf +from statsmodels.tsa.statespace.sarimax import SARIMAX +from statsmodels.tsa.stattools import ( + AcfResult, + ADFullerResult, + BreakvarHeteroskedasticityResult, + CcfResult, + CointResult, + JackknifeResult, + KPSSResult, + LevinsonDurbinPacfResult, + LevinsonDurbinResult, + PacfBurgResult, + PacfResult, + PccfResult, + QStatResult, + RURResult, + acf, + acovf, + adfuller, + arma_order_select_ic, + block_jackknife, + breakvar_heteroskedasticity_test, + ccf, + ccovf, + coint, + diebold_mariano_test, + grangercausalitytests, + innovations_algo, + innovations_filter, + kpss, + levinson_durbin, + levinson_durbin_pacf, + leybourne, + pacf, + pacf_burg, + pacf_ols, + pacf_yw, + pccf, + q_stat, + range_unit_root_test, + zivot_andrews, +) + +DECIMAL_8 = 8 +DECIMAL_6 = 6 +DECIMAL_5 = 5 +DECIMAL_4 = 4 +DECIMAL_3 = 3 +DECIMAL_2 = 2 +DECIMAL_1 = 1 + +CURR_DIR = Path(__file__).resolve().parent + + +@pytest.fixture(scope="module") +def acovf_data(): + rs = np.random.RandomState(12345) + return rs.randn(250) + + +@pytest.fixture(scope="module") +def gc_data(): + mdata = macrodata.load_pandas().data + mdata = mdata[["realgdp", "realcons"]].values + data = mdata.astype(float) + return np.diff(np.log(data), axis=0) + + +class CheckADF: + """ + Test Augmented Dickey-Fuller + + Test values taken from Stata. + """ + + levels = ["1%", "5%", "10%"] + data = macrodata.load_pandas() + x = data.data["realgdp"].values + y = data.data["infl"].values + + def test_teststat(self): + assert_almost_equal(self.res1[0], self.teststat, DECIMAL_5) + + def test_pvalue(self): + assert_almost_equal(self.res1[1], self.pvalue, DECIMAL_5) + + def test_critvalues(self): + critvalues = [self.res1[4][lev] for lev in self.levels] + assert_almost_equal(critvalues, self.critvalues, DECIMAL_2) + + +class TestADFConstant(CheckADF): + """ + Dickey-Fuller test for unit root + """ + + @classmethod + def setup_class(cls): + cls.res1 = adfuller( + cls.x, regression="c", autolag=None, maxlag=4, result_object=False + ) + cls.teststat = 0.97505319 + cls.pvalue = 0.99399563 + cls.critvalues = [-3.476, -2.883, -2.573] + + +class TestADFConstantTrend(CheckADF): + """""" + + @classmethod + def setup_class(cls): + cls.res1 = adfuller( + cls.x, regression="ct", autolag=None, maxlag=4, result_object=False + ) + cls.teststat = -1.8566374 + cls.pvalue = 0.67682968 + cls.critvalues = [-4.007, -3.437, -3.137] + + +# FIXME: do not leave commented-out +# class TestADFConstantTrendSquared(CheckADF): +# """ +# """ +# pass +# TODO: get test values from R? + + +class TestADFNoConstant(CheckADF): + """""" + + @classmethod + def setup_class(cls): + cls.res1 = adfuller( + cls.x, regression="n", autolag=None, maxlag=4, result_object=False + ) + cls.teststat = 3.5227498 + + cls.pvalue = 0.99999 + # Stata does not return a p-value for noconstant. + # Tau^max in MacKinnon (1994) is missing, so it is + # assumed that its right-tail is well-behaved + + cls.critvalues = [-2.587, -1.950, -1.617] + + +# No Unit Root + + +class TestADFConstant2(CheckADF): + @classmethod + def setup_class(cls): + cls.res1 = adfuller( + cls.y, regression="c", autolag=None, maxlag=1, result_object=False + ) + cls.teststat = -4.3346988 + cls.pvalue = 0.00038661 + cls.critvalues = [-3.476, -2.883, -2.573] + + +class TestADFConstantTrend2(CheckADF): + @classmethod + def setup_class(cls): + cls.res1 = adfuller( + cls.y, regression="ct", autolag=None, maxlag=1, result_object=False + ) + cls.teststat = -4.425093 + cls.pvalue = 0.00199633 + cls.critvalues = [-4.006, -3.437, -3.137] + + +class TestADFNoConstant2(CheckADF): + @classmethod + def setup_class(cls): + cls.res1 = adfuller( + cls.y, regression="n", autolag=None, maxlag=1, result_object=False + ) + cls.teststat = -2.4511596 + cls.pvalue = 0.013747 + # Stata does not return a p-value for noconstant + # this value is just taken from our results + cls.critvalues = [-2.587, -1.950, -1.617] + _, _1, _2, cls.store = adfuller( + cls.y, + regression="n", + autolag=None, + maxlag=1, + store=True, + result_object=False, + ) + + def test_store_str(self): + assert_equal(self.store.__str__(), "Augmented Dickey-Fuller Test Results") + + +@pytest.mark.parametrize("x", [np.full(8, 5.0)]) +def test_adfuller_resid_variance_zero(x): + with pytest.raises(ValueError): + adfuller(x) + + +class CheckCorrGram: + """ + Set up for ACF, PACF tests. + """ + + data = macrodata.load_pandas() + x = data.data["realgdp"] + filename = Path(CURR_DIR).joinpath("results", "results_corrgram.csv") + results = pd.read_csv(filename, delimiter=",") + + +class TestACF(CheckCorrGram): + """ + Test Autocorrelation Function + """ + + @classmethod + def setup_class(cls): + cls.acf = cls.results["acvar"] + # cls.acf = np.concatenate(([1.], cls.acf)) + cls.qstat = cls.results["Q1"] + cls.res1 = acf( + cls.x, nlags=40, qstat=True, alpha=0.05, fft=False, result_object=False + ) + cls.confint_res = cls.results[["acvar_lb", "acvar_ub"]].values + + def test_acf(self): + assert_almost_equal(self.res1.acf[1:41], self.acf, DECIMAL_8) + + def test_confint(self): + centered = self.res1.confint - self.res1.confint.mean(1)[:, None] + assert_almost_equal(centered[1:41], self.confint_res, DECIMAL_8) + + def test_qstat(self): + assert_almost_equal(self.res1.qstat[:40], self.qstat, DECIMAL_3) + # 3 decimal places because of stata rounding + + # FIXME: enable/xfail/skip or delete + # def pvalue(self): + # pass + # NOTE: should not need testing if Q stat is correct + + def test_result_object_true(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = acf( + self.x, + nlags=40, + qstat=True, + alpha=0.05, + fft=False, + result_object=True, + ) + assert isinstance(res, AcfResult) + assert res[0] is res.acf + assert res[1] is res.confint + assert res[2] is res.qstat + assert res[3] is res.pvalues + assert_almost_equal(res.acf[1:41], self.acf, DECIMAL_8) + assert_almost_equal(res.qstat[:40], self.qstat, DECIMAL_3) + + @pytest.mark.parametrize("qstat", [True, False]) + @pytest.mark.parametrize("alpha", [None, 0.05]) + def test_result_object_true_always_four_fields(self, qstat, alpha): + # AcfResult always has 4 fields regardless of which of qstat/alpha + # were requested; unrequested fields are None rather than omitted. + if not (qstat or alpha): + pytest.skip("not a variable-arity case; acf always returns bare array") + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = acf( + self.x, + nlags=10, + qstat=qstat, + alpha=alpha, + fft=False, + result_object=True, + ) + assert isinstance(res, AcfResult) + assert isinstance(res.acf, np.ndarray) + assert (res.confint is None) == (alpha is None) + assert (res.qstat is None) == (not qstat) + assert (res.pvalues is None) == (not qstat) + + def test_default_warns(self): + with pytest.warns(FutureWarning, match="result_object"): + res = acf(self.x, nlags=40, qstat=True, fft=False) + assert isinstance(res, tuple) + assert not isinstance(res, AcfResult) + + def test_no_qstat_no_alpha_never_warns(self): + # The single-output path is unchanged and must stay silent, but an + # explicit result_object=True still returns the result object with + # the unrequested fields left as None. + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = acf(self.x, nlags=40, fft=False) + res_nt = acf(self.x, nlags=40, fft=False, result_object=True) + assert isinstance(res, np.ndarray) + assert isinstance(res_nt, AcfResult) + assert_allclose(res_nt.acf, res) + assert res_nt.confint is None + assert res_nt.qstat is None + assert res_nt.pvalues is None + + @pytest.mark.parametrize( + "kwargs, expected", + [ + ({"alpha": 0.05}, 2), + ({"qstat": True}, 3), + ({"qstat": True, "alpha": 0.05}, 4), + ], + ) + def test_legacy_unpacking_preserved(self, kwargs, expected): + # AcfResult always carries four fields, so it may only be adopted by + # default where that matches the legacy arity. Returning it for + # alpha-only or qstat-only would raise "too many values to unpack" + # in existing user code. + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + res = acf(self.x, nlags=40, fft=False, **kwargs) + opted_out = acf(self.x, nlags=40, fft=False, result_object=False, **kwargs) + assert len(res) == expected + assert len(opted_out) == expected + + # unpacking with exactly `expected` names is a stable, non-deprecated + # part of the API, whether res is a bare tuple or an AcfResult. + _ = [*res] + assert len([*res]) == expected + + def test_only_full_request_adopts_result_object_silently(self): + # Both qstat and alpha -> the four-field result object matches the + # legacy 4-tuple exactly, so it is adopted with no warning. + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = acf(self.x, nlags=40, fft=False, qstat=True, alpha=0.05) + assert isinstance(res, AcfResult) + # Requesting only one of them still warns and keeps the short tuple. + for kwargs in ({"alpha": 0.05}, {"qstat": True}): + with pytest.warns(FutureWarning, match="result_object"): + short = acf(self.x, nlags=40, fft=False, **kwargs) + assert not isinstance(short, AcfResult) + + +class TestACF_FFT(CheckCorrGram): + # Test Autocorrelation Function using FFT + @classmethod + def setup_class(cls): + cls.acf = cls.results["acvarfft"] + cls.qstat = cls.results["Q1"] + cls.res1 = acf(cls.x, nlags=40, qstat=True, fft=True, result_object=False) + + def test_acf(self): + assert_almost_equal(self.res1[0][1:], self.acf, DECIMAL_8) + + def test_qstat(self): + # todo why is res1/qstat 1 short + assert_almost_equal(self.res1[1], self.qstat, DECIMAL_3) + + +class TestACFMissing(CheckCorrGram): + # Test Autocorrelation Function using Missing + @classmethod + def setup_class(cls): + cls.x = np.concatenate((np.array([np.nan]), cls.x)) + cls.acf = cls.results["acvar"] # drop and conservative + cls.qstat = cls.results["Q1"] + cls.confint_res = cls.results[["acvar_lb", "acvar_ub"]].values + cls.res_drop = acf( + cls.x, + nlags=40, + qstat=True, + alpha=0.05, + missing="drop", + fft=False, + result_object=False, + ) + cls.res_conservative = acf( + cls.x, + nlags=40, + qstat=True, + alpha=0.05, + fft=False, + missing="conservative", + result_object=False, + ) + cls.acf_none = np.empty(40) * np.nan # lags 1 to 40 inclusive + cls.qstat_none = np.empty(40) * np.nan + cls.res_none = acf( + cls.x, + nlags=40, + qstat=True, + alpha=0.05, + missing="none", + fft=False, + result_object=False, + ) + + def test_raise(self): + with pytest.raises(MissingDataError): + acf( + self.x, + nlags=40, + qstat=True, + fft=False, + alpha=0.05, + missing="raise", + ) + + def test_acf_none(self): + assert_almost_equal(self.res_none.acf[1:41], self.acf_none, DECIMAL_8) + + def test_acf_drop(self): + assert_almost_equal(self.res_drop.acf[1:41], self.acf, DECIMAL_8) + + def test_acf_conservative(self): + assert_almost_equal(self.res_conservative.acf[1:41], self.acf, DECIMAL_8) + + def test_qstat_none(self): + # todo why is res1/qstat 1 short + assert_almost_equal(self.res_none.qstat, self.qstat_none, DECIMAL_3) + + def test_qstat_drop(self): + assert_almost_equal(self.res_drop.qstat[:40], self.qstat, DECIMAL_3) + + def test_qstat_conservative(self): + assert_almost_equal(self.res_conservative.qstat[:40], self.qstat, DECIMAL_3) + + def test_confint_drop(self): + centered = self.res_drop.confint - self.res_drop.confint.mean(1)[:, None] + assert_almost_equal(centered[1:41], self.confint_res, DECIMAL_8) + + def test_confint_conservative(self): + centered = ( + self.res_conservative.confint + - self.res_conservative.confint.mean(1)[:, None] + ) + assert_almost_equal(centered[1:41], self.confint_res, DECIMAL_8) + + @pytest.mark.parametrize("missing", ["drop", "conservative"]) + def test_drop_all(self, missing): + all_missing = np.full_like(self.x, np.nan) + with pytest.raises(ValueError, match="All observations are missing"): + acf(all_missing, nlags=40, missing=missing) + + +class TestPACF(CheckCorrGram): + @classmethod + def setup_class(cls): + cls.pacfols = cls.results["PACOLS"] + cls.pacfyw = cls.results["PACYW"] + + def test_ols(self): + _result = pacf( + self.x, nlags=40, alpha=0.05, method="ols", result_object=False + ) + pacfols, confint = _result.pacf, _result.confint + assert_almost_equal(pacfols[1:], self.pacfols, DECIMAL_6) + centered = confint - confint.mean(1)[:, None] + # from edited Stata ado file + res = [[-0.1375625, 0.1375625]] * 40 + assert_almost_equal(centered[1:41], res, DECIMAL_6) + # check lag 0 + assert_equal(centered[0], [0.0, 0.0]) + assert_equal(confint[0], [1, 1]) + assert_equal(pacfols[0], 1) + + def test_alpha_default_returns_result_object(self): + # PacfResult has the same length and contents as the legacy + # (pacf, confint) tuple, so it is adopted without a warning. + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = pacf(self.x, nlags=40, alpha=0.05, method="ols") + assert isinstance(res, PacfResult) + assert len(res) == 2 + # The result object is used whenever it matches the legacy tuple's + # contents, so result_object=False cannot opt out of it here. + with warnings.catch_warnings(): + warnings.simplefilter("error") + opted_out = pacf( + self.x, nlags=40, alpha=0.05, method="ols", result_object=False + ) + assert isinstance(opted_out, PacfResult) + # ...and unpacking is a stable, non-deprecated part of the API. + vals, confint = res + assert_allclose(vals, res.pacf) + assert_allclose(confint, res.confint) + + def test_alpha_result_object_true(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = pacf(self.x, nlags=40, alpha=0.05, method="ols", result_object=True) + assert isinstance(res, PacfResult) + assert res[0] is res.pacf + assert res[1] is res.confint + + def test_no_alpha_never_warns(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = pacf(self.x, nlags=40, method="ols") + res_nt = pacf(self.x, nlags=40, method="ols", result_object=True) + assert isinstance(res, np.ndarray) + assert isinstance(res_nt, PacfResult) + assert_allclose(res_nt.pacf, res) + assert res_nt.confint is None + + def test_ols_inefficient(self): + lag_len = 5 + pacfols = pacf_ols(self.x, nlags=lag_len, efficient=False) + x = self.x.copy() + x -= x.mean() + n = x.shape[0] + lags = np.zeros((n - 5, 5)) + lead = x[5:] + direct = np.empty(lag_len + 1) + direct[0] = 1.0 + for i in range(lag_len): + lags[:, i] = x[5 - (i + 1) : -(i + 1)] + direct[i + 1] = np.linalg.lstsq(lags[:, : (i + 1)], lead, rcond=None)[0][-1] + assert_allclose(pacfols, direct, atol=1e-8) + + def test_yw(self): + pacfyw = pacf_yw(self.x, nlags=40, method="mle") + assert_almost_equal(pacfyw[1:], self.pacfyw, DECIMAL_8) + + @pytest.mark.skipif(PYTHON_IMPL_WASM, reason="No fp exception support in WASM") + def test_yw_singular(self): + with pytest.warns(SingularMatrixWarning): + pacf(np.ones(30), nlags=6) + + def test_ld(self): + pacfyw = pacf_yw(self.x, nlags=40, method="mle") + pacfld = pacf(self.x, nlags=40, method="ldb") + assert_almost_equal(pacfyw, pacfld, DECIMAL_8) + + pacfyw = pacf(self.x, nlags=40, method="yw") + pacfld = pacf(self.x, nlags=40, method="lda") + assert_almost_equal(pacfyw, pacfld, DECIMAL_8) + + def test_burg(self): + pacfburg_ = pacf_burg(self.x, nlags=40).pacf + pacfburg = pacf(self.x, nlags=40, method="burg") + assert_almost_equal(pacfburg_, pacfburg, DECIMAL_8) + + +class TestCCF: + """ + Test cross-correlation function + """ + + data = macrodata.load_pandas() + x = data.data["unemp"].diff().dropna() + y = data.data["infl"].diff().dropna() + filename = Path(CURR_DIR).joinpath("results", "results_ccf.csv") + results = pd.read_csv(filename, delimiter=",") + nlags = 20 + + @classmethod + def setup_class(cls): + cls.ccf = cls.results["ccf"] + cls.res1 = ccf(cls.x, cls.y, nlags=cls.nlags, adjusted=False, fft=False) + + def test_ccf(self): + assert_almost_equal(self.res1, self.ccf, DECIMAL_8) + + def test_confint(self): + alpha = 0.05 + _result = ccf( + self.x, + self.y, + nlags=self.nlags, + adjusted=False, + fft=False, + alpha=alpha, + result_object=False, + ) + res2, confint = _result.ccf, _result.confint + assert_equal(res2, self.res1) + assert_almost_equal(res2 - confint[:, 0], confint[:, 1] - res2, DECIMAL_8) + alpha1 = stats.norm.cdf(confint[:, 1] - res2, scale=1.0 / np.sqrt(len(self.x))) + assert_almost_equal(alpha1, np.repeat(1 - alpha / 2.0, self.nlags), DECIMAL_8) + + def test_alpha_default_returns_result_object(self): + # CcfResult has the same length and contents as the legacy + # (ccf, confint) tuple, so it is adopted without a warning. + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = ccf(self.x, self.y, nlags=self.nlags, alpha=0.05) + assert isinstance(res, CcfResult) + assert len(res) == 2 + # The result object is used whenever it matches the legacy tuple's + # contents, so result_object=False cannot opt out of it here. + with warnings.catch_warnings(): + warnings.simplefilter("error") + opted_out = ccf( + self.x, self.y, nlags=self.nlags, alpha=0.05, result_object=False + ) + assert isinstance(opted_out, CcfResult) + # ...and unpacking is a stable, non-deprecated part of the API. + vals, confint = res + assert_allclose(vals, res.ccf) + assert_allclose(confint, res.confint) + + def test_alpha_result_object_true(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = ccf(self.x, self.y, nlags=self.nlags, alpha=0.05, result_object=True) + assert isinstance(res, CcfResult) + assert res[0] is res.ccf + assert res[1] is res.confint + + def test_no_alpha_never_warns(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = ccf(self.x, self.y, nlags=self.nlags) + res_nt = ccf(self.x, self.y, nlags=self.nlags, result_object=True) + assert isinstance(res, np.ndarray) + assert isinstance(res_nt, CcfResult) + assert_allclose(res_nt.ccf, res) + assert res_nt.confint is None + + +class TestPCCF: + data = macrodata.load_pandas() + x = data.data["realgdp"] + y = data.data["realcons"] + filename = Path(CURR_DIR).joinpath("results", "results_pccf.csv") + results = pd.read_csv(filename, delimiter=",") + nlags = 20 + + @classmethod + def setup_class(cls): + cls.pccf = cls.results["pccf"] + cls.res1 = pccf(cls.x, cls.y, nlags=cls.nlags, method="ols") + + def test_pccf(self): + assert_almost_equal(self.res1, self.pccf, DECIMAL_8) + + def test_pccf_hand_computed(self): + x = np.array( + [2.1, 4.5, 1.3, 6.8, 3.2, 5.7, 0.9, 7.4, 2.8, 4.1, 6.3, 1.7, 5.5, 3.9, 7.1] + ) + y = np.array( + [3.4, 2.7, 5.1, 1.8, 4.6, 3.3, 6.2, 2.5, 4.8, 3.1, 5.5, 2.2, 4.3, 3.7, 5.9] + ) + result = pccf(x, y, nlags=3, method="ols") + expected = np.array( + [ + 0.46195683919821806, + 0.11931602624087348, + 0.5204421499138578, + ] + ) + assert_almost_equal(result, expected, DECIMAL_8) + + def test_confint(self): + alpha = 0.05 + _result = pccf( + self.x, + self.y, + nlags=self.nlags, + method="ols", + alpha=alpha, + result_object=False, + ) + res2, confint = _result.pccf, _result.confint + assert_equal(res2, self.res1) + assert_almost_equal(res2 - confint[:, 0], confint[:, 1] - res2, DECIMAL_8) + alpha1 = stats.norm.cdf( + confint[:, 1] - res2, + scale=1.0 / np.sqrt(len(self.x)), + ) + assert_almost_equal(alpha1, np.repeat(1 - alpha / 2.0, self.nlags), DECIMAL_8) + + def test_alpha_default_returns_result_object(self): + # PccfResult has the same length and contents as the legacy + # (pccf, confint) tuple, so it is adopted without a warning. + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = pccf(self.x, self.y, nlags=self.nlags, method="ols", alpha=0.05) + assert isinstance(res, PccfResult) + assert len(res) == 2 + # The result object is used whenever it matches the legacy tuple's + # contents, so result_object=False cannot opt out of it here. + with warnings.catch_warnings(): + warnings.simplefilter("error") + opted_out = pccf( + self.x, + self.y, + nlags=self.nlags, + method="ols", + alpha=0.05, + result_object=False, + ) + assert isinstance(opted_out, PccfResult) + # ...and unpacking is a stable, non-deprecated part of the API. + vals, confint = res + assert_allclose(vals, res.pccf) + assert_allclose(confint, res.confint) + + def test_alpha_result_object_true(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = pccf( + self.x, + self.y, + nlags=self.nlags, + method="ols", + alpha=0.05, + result_object=True, + ) + assert isinstance(res, PccfResult) + assert res[0] is res.pccf + assert res[1] is res.confint + + def test_no_alpha_never_warns(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = pccf(self.x, self.y, nlags=self.nlags, method="ols") + res_nt = pccf( + self.x, self.y, nlags=self.nlags, method="ols", result_object=True + ) + assert isinstance(res, np.ndarray) + assert isinstance(res_nt, PccfResult) + assert_allclose(res_nt.pccf, res) + assert res_nt.confint is None + + def test_confint_widths(self): + alphas = [0.01, 0.05, 0.10] + widths = {} + for a in alphas: + confint = pccf( + self.x, self.y, nlags=5, method="ols", alpha=a, result_object=False + ).confint + widths[a] = confint[:, 1] - confint[:, 0] + assert np.all(widths[0.01] > widths[0.05]) + assert np.all(widths[0.05] > widths[0.10]) + + def test_pccf_edge_cases(self): + x_small = np.array([1.0, 2.0, 3.0]) + y_small = np.array([4.0, 5.0, 6.0]) + result_small = pccf(x_small, y_small, nlags=1, method="ols") + assert len(result_small) == 1 + assert not np.isnan(result_small[0]) + + with pytest.raises(ValueError): + pccf(self.x[:10], self.y[:15], nlags=5) + + def test_pccf_statistical_properties(self): + result = pccf(self.x, self.y, nlags=10) + valid_values = result[~np.isnan(result)] + assert np.all(valid_values >= -1.0) + assert np.all(valid_values <= 1.0) + + result_lag1 = pccf(self.x, self.y, nlags=1, method="ols") + ccf_lag1 = np.corrcoef(self.x[:-1], self.y[1:])[0, 1] + assert_almost_equal(result_lag1[0], ccf_lag1, DECIMAL_8) + + def test_pccf_parameter_validation(self): + with pytest.raises(ValueError): + pccf(self.x, self.y, nlags=0) + with pytest.raises(ValueError): + pccf(self.x, self.y, nlags=-1) + with pytest.raises(ValueError): + pccf(self.x[:10], self.y[:10], nlags=6) + + @pytest.mark.parametrize("method", ["ols", "yw", "ywm"]) + def test_constant_series(self, method): + x_const = np.ones(50) + y_const = np.ones(50) * 2.0 + result = pccf(x_const, y_const, nlags=5, method=method) + assert len(result) == 5 + assert np.all(np.isnan(result)) + + def test_yw_singular_intermediate_recursion_returns_nan(self): + x = np.array([0.0, 0.0, -1.0, 2.0, -1.0]) + y = np.array([-1.0, 0.0, -2.0, -2.0, 0.0]) + result = pccf(x, y, nlags=2, method="yw") + assert len(result) == 2 + assert np.all(np.isfinite(result) | np.isnan(result)) + + def test_return_consistency(self): + result_no_alpha = pccf(self.x, self.y, nlags=5) + _result = pccf( + self.x, self.y, nlags=5, alpha=0.05, result_object=False + ) + result_with_alpha, confint = _result.pccf, _result.confint + assert_almost_equal(result_no_alpha, result_with_alpha, DECIMAL_8) + assert confint.shape == (5, 2) + assert np.all(confint[:, 0] <= result_with_alpha) + assert np.all(result_with_alpha <= confint[:, 1]) + + def test_default_nlags(self): + result = pccf(self.x, self.y) + nobs = len(self.x) + expected_nlags = min(int(10 * np.log10(nobs)), nobs // 2 - 1) + assert len(result) == expected_nlags + + def test_nan_fallback_large_lag(self): + x_short = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + y_short = np.array([2.0, 3.0, 1.0, 4.0, 2.0]) + result = pccf(x_short, y_short, nlags=2, method="ols") + assert len(result) == 2 + assert np.isnan(result[1]) + + def test_var1_pccf_cutoff(self): + rng = np.random.default_rng(98765) + n = 500 + x = np.zeros(n) + y = np.zeros(n) + x[0] = rng.standard_normal() + y[0] = rng.standard_normal() + for t in range(1, n): + e = rng.standard_normal(2) + x[t] = 0.6 * x[t - 1] + 0.3 * y[t - 1] + e[0] + y[t] = 0.2 * x[t - 1] + 0.5 * y[t - 1] + e[1] + result = pccf(x, y, nlags=8) + threshold = 2.0 / np.sqrt(n) + assert np.abs(result[0]) > threshold + assert np.all(np.abs(result[3:]) < 3 * threshold) + + def test_independent_series(self): + rng = np.random.default_rng(54321) + x = rng.standard_normal(200) + y = rng.standard_normal(200) + result = pccf(x, y, nlags=10) + threshold = 2.0 / np.sqrt(200) + assert np.all(np.abs(result) < 3 * threshold) + + def test_yw_ols_agreement_stationary(self): + rng = np.random.default_rng(11111) + n = 2000 + x = np.zeros(n) + y = np.zeros(n) + x[0] = rng.standard_normal() + y[0] = rng.standard_normal() + for t in range(1, n): + e = rng.standard_normal(2) + x[t] = 0.5 * x[t - 1] + 0.2 * y[t - 1] + e[0] + y[t] = 0.3 * x[t - 1] + 0.4 * y[t - 1] + e[1] + yw = pccf(x, y, nlags=5, method="ywm") + ols = pccf(x, y, nlags=5, method="ols") + assert_almost_equal(yw, ols, decimal=2) + + def test_method_parameter_validation(self): + with pytest.raises(ValueError): + pccf(self.x, self.y, nlags=5, method="invalid") + + def test_yw_method_aliases(self): + ywm = pccf(self.x, self.y, nlags=5, method="ywm") + ywmle = pccf(self.x, self.y, nlags=5, method="ywmle") + yw_mle = pccf(self.x, self.y, nlags=5, method="yw_mle") + assert_almost_equal(ywm, ywmle, DECIMAL_8) + assert_almost_equal(ywm, yw_mle, DECIMAL_8) + + yw = pccf(self.x, self.y, nlags=5, method="yw") + ywa = pccf(self.x, self.y, nlags=5, method="ywa") + ywadjusted = pccf(self.x, self.y, nlags=5, method="ywadjusted") + yw_adjusted = pccf(self.x, self.y, nlags=5, method="yw_adjusted") + assert_almost_equal(yw, ywa, DECIMAL_8) + assert_almost_equal(yw, ywadjusted, DECIMAL_8) + assert_almost_equal(yw, yw_adjusted, DECIMAL_8) + + def test_yw_analytical_var1(self): + from scipy.linalg import solve_discrete_lyapunov + + A = np.array([[0.6, 0.3], [0.2, 0.5]]) + Q = np.eye(2) + G0 = solve_discrete_lyapunov(A, Q) + + nlags = 3 + gamma = [G0] + for h in range(1, nlags + 1): + gamma.append(G0 @ np.linalg.matrix_power(A.T, h)) + + sig_f = G0.copy() + sig_b = G0.copy() + phi_prev = [None] * (nlags + 1) + psi_prev = [None] * (nlags + 1) + expected = np.empty(nlags) + + for s in range(1, nlags + 1): + delta_f = gamma[s].copy() + delta_b = gamma[s].T.copy() + for j in range(1, s): + delta_f -= phi_prev[j] @ gamma[s - j] + delta_b -= psi_prev[j] @ gamma[s - j].T + d_f = np.sqrt(np.diag(sig_f)) + d_b = np.sqrt(np.diag(sig_b)) + expected[s - 1] = delta_f[0, 1] / (d_f[0] * d_b[1]) + phi_ss = delta_f @ np.linalg.inv(sig_b) + psi_ss = delta_b @ np.linalg.inv(sig_f) + phi_new = [None] * (nlags + 1) + psi_new = [None] * (nlags + 1) + phi_new[s] = phi_ss + psi_new[s] = psi_ss + for j in range(1, s): + phi_new[j] = phi_prev[j] - phi_ss @ psi_prev[s - j] + psi_new[j] = psi_prev[j] - psi_ss @ phi_prev[s - j] + sig_f = sig_f - phi_ss @ delta_b + sig_b = sig_b - psi_ss @ delta_f + phi_prev = phi_new + psi_prev = psi_new + + assert_almost_equal(expected[1:], np.zeros(nlags - 1), DECIMAL_8) + + rng = np.random.default_rng(77777) + n = 5000 + z = np.zeros((n, 2)) + z[0] = rng.standard_normal(2) + for t in range(1, n): + z[t] = A @ z[t - 1] + rng.standard_normal(2) + result = pccf(z[:, 0], z[:, 1], nlags=nlags, method="ywm") + assert_almost_equal(result[0], expected[0], decimal=1) + assert_almost_equal(result[1:], expected[1:], decimal=1) + + def test_asymmetry(self): + rng = np.random.default_rng(42) + n = 500 + x = np.zeros(n) + y = np.zeros(n) + for t in range(1, n): + e = rng.standard_normal(2) + x[t] = 0.6 * x[t - 1] + 0.3 * y[t - 1] + e[0] + y[t] = 0.2 * x[t - 1] + 0.5 * y[t - 1] + e[1] + fwd = pccf(x, y, nlags=3) + rev = pccf(y, x, nlags=3) + assert not np.allclose(fwd, rev) + + def test_nan_input_raises(self): + x = np.array([1.0, 2.0, np.nan, 4.0, 5.0, 6.0, 7.0, 8.0]) + y = np.arange(8, dtype=float) + with pytest.raises(MissingDataError): + pccf(x, y, nlags=3) + with pytest.raises(MissingDataError): + pccf(y, x, nlags=3, method="ols") + + def test_inf_input_raises(self): + x = np.array([1.0, 2.0, np.inf, 4.0, 5.0, 6.0, 7.0, 8.0]) + y = np.arange(8, dtype=float) + with pytest.raises(MissingDataError): + pccf(x, y, nlags=3) + + def test_ols_underdetermined_returns_nan(self): + rng = np.random.default_rng(42) + x = rng.standard_normal(30) + y = rng.standard_normal(30) + result = pccf(x, y, nlags=15, method="ols") + for h in range(1, 16): + n_obs = 30 - h + n_cols = 2 * (h - 1) + 1 + if n_obs <= n_cols and h > 1: + assert np.isnan( + result[h - 1] + ), f"lag {h}: {n_obs} obs, {n_cols} cols should be NaN" + + +class TestBlockJackknife: + """ + Test block (delete-k) jackknife estimator + """ + + def test_mean_closed_form(self): + # Leave-one-out jackknife applied to the sample mean should exactly + # reproduce the standard unbiased variance formula: Var(xbar) = s^2/n + rng = np.random.default_rng(42) + x = rng.normal(loc=10, scale=2, size=100) + + result = block_jackknife(x, np.mean, n_blocks=-1) + theta_jack, se = result.theta_jack, result.se + + expected_se = np.sqrt(np.var(x, ddof=1) / len(x)) + + assert_allclose(se, expected_se, rtol=1e-10) + assert_almost_equal(theta_jack, np.mean(x), DECIMAL_6) + + def test_hand_computed(self): + # Matches the manually-verified 3-block case: + # x = [0..9], n_blocks=3 + x = np.arange(10) + + result = block_jackknife(x, np.mean, n_blocks=3) + theta_jack, se = result.theta_jack, result.se + + assert_almost_equal(theta_jack, 4.309523809523809, DECIMAL_8) + assert_almost_equal(se, 2.044294088920541, DECIMAL_8) + + def test_acf_runs(self): + # Reproduces the motivating AR(1)/ACF use case from the original + # feature request; checks shape and finiteness, not exact values, + # since there is no independent closed-form to check ACF jackknife + # SEs against. + rng = np.random.default_rng(0) + n = 5000 + phi = 0.8 + noise = rng.normal(scale=1.0, size=n) + x = np.zeros(n) + for t in range(1, n): + x[t] = phi * x[t - 1] + noise[t] + + max_lag = 50 + n_blocks = n // 20 + + def est(arr): + return acf(arr, nlags=max_lag) + + result = block_jackknife(x, est, n_blocks=n_blocks) + rho, rho_se = result.theta_jack, result.se + + assert rho.shape == (max_lag + 1,) + assert rho_se.shape == (max_lag + 1,) + assert np.all(np.isfinite(rho)) + assert np.all(np.isfinite(rho_se)) + assert np.all(rho_se >= 0) + + def test_invalid_n_blocks(self): + x = np.arange(10) + with pytest.raises(ValueError, match="n_blocks must be greater than 1"): + block_jackknife(x, np.mean, n_blocks=1) + with pytest.raises(ValueError, match="n_blocks cannot exceed"): + block_jackknife(x, np.mean, n_blocks=20) + + def test_non_callable_statistic(self): + x = np.arange(10) + with pytest.raises(ValueError, match="must be callable"): + block_jackknife(x, "not_a_function", n_blocks=2) + + +class TestBreakvarHeteroskedasticityTest: + from scipy.stats import chi2, f + + def test_1d_input(self): + + input_residuals = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + expected_statistic = (4.0**2 + 5.0**2) / (0.0**2 + 1.0**2) + # ~ F(2, 2), two-sided test + expected_pvalue = 2 * min( + self.f.cdf(expected_statistic, 2, 2), + self.f.sf(expected_statistic, 2, 2), + ) + _result = breakvar_heteroskedasticity_test(input_residuals) + actual_statistic, actual_pvalue = _result.statistic, _result.pvalue + + assert actual_statistic == expected_statistic + assert actual_pvalue == expected_pvalue + + def test_2d_input_with_missing_values(self): + + input_residuals = np.array( + [ + [0.0, 0.0, np.nan], + [1.0, np.nan, 1.0], + [2.0, 2.0, np.nan], + [3.0, 3.0, 3.0], + [4.0, 4.0, 4.0], + [5.0, 5.0, 5.0], + [6.0, 6.0, 6.0], + [7.0, 7.0, 7.0], + [8.0, 8.0, 8.0], + ] + ) + expected_statistic = np.array( + [ + (8.0**2 + 7.0**2 + 6.0**2) / (0.0**2 + 1.0**2 + 2.0**2), + (8.0**2 + 7.0**2 + 6.0**2) / (0.0**2 + 2.0**2), + np.nan, + ] + ) + # H(h) is a ratio of sums of squares, so it is F(dfn, dfd) only after + # rescaling by dfd / dfn. Column 1 has an unbalanced (3, 2) split. + expected_pvalue = np.array( + [ + 2 + * min( + self.f.cdf(expected_statistic[0] * 3 / 3, 3, 3), + self.f.sf(expected_statistic[0] * 3 / 3, 3, 3), + ), + 2 + * min( + self.f.cdf(expected_statistic[1] * 2 / 3, 3, 2), + self.f.sf(expected_statistic[1] * 2 / 3, 3, 2), + ), + np.nan, + ] + ) + _result = breakvar_heteroskedasticity_test(input_residuals) + actual_statistic, actual_pvalue = _result.statistic, _result.pvalue + + assert_equal(actual_statistic, expected_statistic) + assert_equal(actual_pvalue, expected_pvalue) + + @pytest.mark.parametrize("use_f", [True, False]) + @pytest.mark.parametrize( + "alternative", ["increasing", "decreasing", "two-sided"] + ) + def test_unbalanced_degrees_of_freedom(self, alternative, use_f): + # When missing values leave the two subsets with different numbers of + # usable residuals, H(h) -- a ratio of *sums* of squares -- must be + # rescaled by denom_dof / numer_dof before it is F(dfn, dfd), and + # inverting it for "decreasing" must swap the two degrees of freedom. + resid = np.array([np.nan, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]) + # h = 3; numerator {7, 8, 9} -> dfn = 3, denominator {2, 3} -> dfd = 2 + stat = (7.0**2 + 8.0**2 + 9.0**2) / (2.0**2 + 3.0**2) + dfn, dfd = 3, 2 + if alternative == "decreasing": + stat = 1.0 / stat + dfn, dfd = dfd, dfn + if use_f: + scaled, dist, args = stat * dfd / dfn, self.f, (dfn, dfd) + else: + scaled, dist, args = stat * dfd, self.chi2, (dfn,) + if alternative == "two-sided": + expected = 2 * min(dist.cdf(scaled, *args), dist.sf(scaled, *args)) + else: + expected = dist.sf(scaled, *args) + + result = breakvar_heteroskedasticity_test( + resid, alternative=alternative, use_f=use_f + ) + assert_allclose(result.statistic, stat) + assert_allclose(result.pvalue, expected) + + @pytest.mark.parametrize( + "resid", + [ + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], + [np.nan, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], + ], + ids=["balanced", "unbalanced"], + ) + def test_one_sided_alternatives_are_complementary(self, resid): + # The exact (F) versions of the two one-sided tests are opposite tails + # of the same statistic, so their p-values sum to one -- including + # when missing values make the degrees of freedom unbalanced, because + # 1 / F(dfn, dfd) is F(dfd, dfn). The unscaled ratio of sums does not + # have this property. It does not hold for use_f=False: the two chi2 + # approximations are different limits (dfd -> oo and dfn -> oo). + resid = np.asarray(resid) + up = breakvar_heteroskedasticity_test( + resid, alternative="increasing" + ).pvalue + down = breakvar_heteroskedasticity_test( + resid, alternative="decreasing" + ).pvalue + assert_allclose(up + down, 1.0) + + @pytest.mark.parametrize( + "subset_length,expected_statistic,expected_pvalue", + [ + (2, 41, 2 * min(f.cdf(41, 2, 2), f.sf(41, 2, 2))), + (0.5, 10, 2 * min(f.cdf(10, 3, 3), f.sf(10, 3, 3))), + ], + ) + def test_subset_length(self, subset_length, expected_statistic, expected_pvalue): + + input_residuals = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + _result = breakvar_heteroskedasticity_test( + input_residuals, + subset_length=subset_length, + ) + actual_statistic, actual_pvalue = _result.statistic, _result.pvalue + + assert actual_statistic == expected_statistic + assert actual_pvalue == expected_pvalue + + @pytest.mark.parametrize( + "alternative,expected_statistic,expected_pvalue", + [ + ("two-sided", 41, 2 * min(f.cdf(41, 2, 2), f.sf(41, 2, 2))), + ("decreasing", 1 / 41, f.sf(1 / 41, 2, 2)), + ("increasing", 41, f.sf(41, 2, 2)), + ], + ) + def test_alternative(self, alternative, expected_statistic, expected_pvalue): + + input_residuals = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + _result = breakvar_heteroskedasticity_test( + input_residuals, + alternative=alternative, + ) + actual_statistic, actual_pvalue = _result.statistic, _result.pvalue + assert actual_statistic == expected_statistic + assert actual_pvalue == expected_pvalue + + @pytest.mark.parametrize( + "alias,canonical", + [("2", "two-sided"), ("d", "decreasing"), ("i", "increasing")], + ) + def test_alternative_deprecated_alias(self, alias, canonical): + # undocumented short forms still work but warn, and are equivalent + # to spelling out the documented alternative (case-insensitively) + input_residuals = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + with pytest.warns(FutureWarning, match="is a deprecated alias"): + alias_result = breakvar_heteroskedasticity_test( + input_residuals, alternative=alias.upper() + ) + canonical_result = breakvar_heteroskedasticity_test( + input_residuals, alternative=canonical + ) + assert_allclose(alias_result, canonical_result) + + with pytest.raises(ValueError, match="alternative must be one of"): + breakvar_heteroskedasticity_test(input_residuals, alternative="bogus") + + def test_use_chi2(self): + + input_residuals = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + expected_statistic = (4.0**2 + 5.0**2) / (0.0**2 + 1.0**2) + expected_pvalue = 2 * min( + self.chi2.cdf(2 * expected_statistic, 2), + self.chi2.sf(2 * expected_statistic, 2), + ) + _result = breakvar_heteroskedasticity_test( + input_residuals, + use_f=False, + ) + actual_statistic, actual_pvalue = _result.statistic, _result.pvalue + assert actual_statistic == expected_statistic + assert actual_pvalue == expected_pvalue + + +class CheckCoint: + """ + Test Cointegration Test Results for 2-variable system + + Test values taken from Stata + """ + + levels = ["1%", "5%", "10%"] + data = macrodata.load_pandas() + y1 = data.data["realcons"].values + y2 = data.data["realgdp"].values + + def test_tstat(self): + assert_almost_equal(self.coint_t, self.teststat, DECIMAL_4) + + +# this does not produce the old results anymore +class TestCoint_t(CheckCoint): + """ + Get AR(1) parameter on residuals + """ + + @classmethod + def setup_class(cls): + # cls.coint_t = coint(cls.y1, cls.y2, trend="c")[0] + cls.coint_t = coint(cls.y1, cls.y2, trend="c", maxlag=0, autolag=None).coint_t + cls.teststat = -1.8208817 + cls.teststat = -1.830170986148 + + +def test_coint(): + nobs = 200 + scale_e = 1 + const = [1, 0, 0.5, 0] + rs = np.random.RandomState(123) + unit = rs.randn(nobs).cumsum() + y = scale_e * rs.randn(nobs, 4) + y[:, :2] += unit[:, None] + y += const + y = np.round(y, 4) + + # FIXME: enable/xfail/skip or delete + for trend in []: # ['c', 'ct', 'ctt', 'n']: + print("\n", trend) + print(coint(y[:, 0], y[:, 1], trend=trend, maxlag=4, autolag=None)) + print(coint(y[:, 0], y[:, 1:3], trend=trend, maxlag=4, autolag=None)) + print(coint(y[:, 0], y[:, 2:], trend=trend, maxlag=4, autolag=None)) + print(coint(y[:, 0], y[:, 1:], trend=trend, maxlag=4, autolag=None)) + + # results from Stata egranger + res_egranger = {} + # trend = 'ct' + res = res_egranger["ct"] = {} + res[0] = [ + -5.615251442239, + -4.406102369132, + -3.82866685109, + -3.532082997903, + ] + res[1] = [ + -5.63591313706, + -4.758609717199, + -4.179130554708, + -3.880909696863, + ] + res[2] = [ + -2.892029275027, + -4.758609717199, + -4.179130554708, + -3.880909696863, + ] + res[3] = [-5.626932544079, -5.08363327039, -4.502469783057, -4.2031051091] + + # trend = 'c' + res = res_egranger["c"] = {} + # first critical value res[0][1] has a discrepancy starting at 4th decimal + res[0] = [ + -5.760696844656, + -3.952043522638, + -3.367006313729, + -3.065831247948, + ] + # manually adjusted to have higher precision as in other cases + res[0][1] = -3.952321293401682 + res[1] = [ + -5.781087068772, + -4.367111915942, + -3.783961136005, + -3.483501524709, + ] + res[2] = [ + -2.477444137366, + -4.367111915942, + -3.783961136005, + -3.483501524709, + ] + res[3] = [ + -5.778205811661, + -4.735249216434, + -4.152738973763, + -3.852480848968, + ] + + # trend = 'ctt' + res = res_egranger["ctt"] = {} + res[0] = [ + -5.644431269946, + -4.796038299708, + -4.221469431008, + -3.926472577178, + ] + res[1] = [-5.665691609506, -5.111158174219, -4.53317278104, -4.23601008516] + res[2] = [-3.161462374828, -5.111158174219, -4.53317278104, -4.23601008516] + res[3] = [ + -5.657904558563, + -5.406880189412, + -4.826111619543, + -4.527090164875, + ] + + # The following for 'n' are only regression test numbers + # trend = 'n' not allowed in egranger + # trend = 'n' + res = res_egranger["n"] = {} + nan = np.nan # shortcut for table + res[0] = [-3.7146175989071137, nan, nan, nan] + res[1] = [-3.8199323012888384, nan, nan, nan] + res[2] = [-1.6865000791270679, nan, nan, nan] + res[3] = [-3.7991270451873675, nan, nan, nan] + + for trend in ["c", "ct", "ctt", "n"]: + res1 = {} + res1[0] = coint(y[:, 0], y[:, 1], trend=trend, maxlag=4, autolag=None) + res1[1] = coint(y[:, 0], y[:, 1:3], trend=trend, maxlag=4, autolag=None) + res1[2] = coint(y[:, 0], y[:, 2:], trend=trend, maxlag=4, autolag=None) + res1[3] = coint(y[:, 0], y[:, 1:], trend=trend, maxlag=4, autolag=None) + + for i in range(4): + res = res_egranger[trend] + + assert_allclose(res1[i].coint_t, res[i][0], rtol=1e-11) + r2 = res[i][1:] + r1 = res1[i].critical_values + assert_allclose(r1, r2, rtol=0, atol=6e-7) + + # use default autolag #4490 + res1_0 = coint(y[:, 0], y[:, 1], trend="ct", maxlag=4) + assert_allclose(res1_0.critical_values, res_egranger["ct"][0][1:], rtol=0, atol=6e-7) + # the following is just a regression test + assert_allclose( + [res1_0.coint_t, res1_0.pvalue], + [-13.992946638547112, 2.270898990540678e-27], + rtol=1e-10, + atol=1e-27, + ) + + +def test_coint_identical_series(): + nobs = 200 + scale_e = 1 + rs = np.random.RandomState(123) + y = scale_e * rs.randn(nobs) + warnings.simplefilter("always", CollinearityWarning) + with pytest.warns(CollinearityWarning): + c = coint(y, y, trend="c", maxlag=0, autolag=None) + assert_equal(c.pvalue, 0.0) + assert np.isneginf(c.coint_t) + + +def test_coint_perfect_collinearity(): + # test uses nearly perfect collinearity + nobs = 200 + scale_e = 1 + rs = np.random.RandomState(123) + x = scale_e * rs.randn(nobs, 2) + y = 1 + x.sum(axis=1) + 1e-7 * rs.randn(nobs) + warnings.simplefilter("always", CollinearityWarning) + with warnings.catch_warnings(record=True): + c = coint(y, x, trend="c", maxlag=0, autolag=None) + assert_equal(c.pvalue, 0.0) + assert np.isneginf(c.coint_t) + + +class TestGrangerCausality: + def test_grangercausality(self): + # some example data + mdata = macrodata.load_pandas().data + mdata = mdata[["realgdp", "realcons"]].values + data = mdata.astype(float) + data = np.diff(np.log(data), axis=0) + + # R: lmtest:grangertest + r_result = [0.243097, 0.7844328, 195, 2] # f_test + gr = grangercausalitytests(data[:, 1::-1], 2) + assert_almost_equal(r_result, gr[2][0]["ssr_ftest"], decimal=7) + assert_almost_equal(gr[2][0]["params_ftest"], gr[2][0]["ssr_ftest"], decimal=7) + + def test_grangercausality_single(self): + mdata = macrodata.load_pandas().data + mdata = mdata[["realgdp", "realcons"]].values + data = mdata.astype(float) + data = np.diff(np.log(data), axis=0) + gr = grangercausalitytests(data[:, 1::-1], 2) + gr2 = grangercausalitytests(data[:, 1::-1], [2]) + assert 1 in gr + assert 1 not in gr2 + assert_almost_equal(gr[2][0]["ssr_ftest"], gr2[2][0]["ssr_ftest"], decimal=7) + assert_almost_equal(gr[2][0]["params_ftest"], gr2[2][0]["ssr_ftest"], decimal=7) + + def test_granger_fails_on_nobs_check(self): + # Test that if maxlag is too large, Granger Test raises a clear error. + rs = np.random.RandomState(3239291) + x = rs.rand(10, 2) + grangercausalitytests(x, 2) # This should pass. + + def test_granger_fails_on_finite_check(self): + rs = np.random.RandomState(1234) + x = rs.rand(1000, 2) + x[500, 0] = np.nan + x[750, 1] = np.inf + with pytest.raises(ValueError, match="x contains NaN"): + grangercausalitytests(x, 2) + + def test_granger_fails_on_zero_lag(self): + rs = np.random.RandomState(388776) + x = rs.rand(1000, 2) + with pytest.raises( + ValueError, + match="maxlag must be a non-empty list containing only positive integers", + ): + grangercausalitytests(x, [0, 1, 2]) + + +class TestKPSS: + """ + R-code + ------ + library(tseries) + kpss.stat(x, "Level") + kpss.stat(x, "Trend") + + In this context, x is the vector containing the + macrodata['realgdp'] series. + """ + + def setup_method(self): + self.data = macrodata.load_pandas() + self.x = self.data.data["realgdp"].values + + def test_fail_nonvector_input(self): + # should be fine + with pytest.warns(InterpolationWarning): + kpss(self.x, nlags="legacy", result_object=False) + + x = rs.rand(20, 2) + with pytest.raises(ValueError): + kpss(x) + + def test_fail_invalid_nlags_string(self): + with pytest.raises(ValueError, match="nlags"): + kpss(self.x, nlags="invalid", result_object=False) + + def test_fail_unclear_hypothesis(self): + # these should be fine, + with pytest.warns(InterpolationWarning): + kpss(self.x, "c", nlags="legacy", result_object=False) + with pytest.warns(InterpolationWarning): + kpss(self.x, "C", nlags="legacy", result_object=False) + with pytest.warns(InterpolationWarning): + kpss(self.x, "ct", nlags="legacy", result_object=False) + with pytest.warns(InterpolationWarning): + kpss(self.x, "CT", nlags="legacy", result_object=False) + + with pytest.raises(ValueError): + kpss(self.x, "unclear hypothesis", nlags="legacy") + + def test_teststat(self): + with pytest.warns(InterpolationWarning): + kpss_stat, _, _, _ = kpss(self.x, "c", 3, result_object=False) + assert_almost_equal(kpss_stat, 5.0169, DECIMAL_3) + + with pytest.warns(InterpolationWarning): + kpss_stat, _, _, _ = kpss(self.x, "ct", 3, result_object=False) + assert_almost_equal(kpss_stat, 1.1828, DECIMAL_3) + + def test_pval(self): + with pytest.warns(InterpolationWarning): + _, pval, _, _ = kpss(self.x, "c", 3, result_object=False) + assert_equal(pval, 0.01) + + with pytest.warns(InterpolationWarning): + _, pval, _, _ = kpss(self.x, "ct", 3, result_object=False) + assert_equal(pval, 0.01) + + def test_store(self): + with pytest.warns(InterpolationWarning): + _, _, _, store = kpss(self.x, "c", 3, True, result_object=False) + + # assert attributes, and make sure they're correct + assert_equal(store.nobs, len(self.x)) + assert_equal(store.lags, 3) + + # test autolag function _kpss_autolag against SAS 9.3 + def test_lags(self): + # real GDP from macrodata data set + with pytest.warns(InterpolationWarning): + res = kpss(self.x, "c", nlags="auto", result_object=False) + assert_equal(res[2], 9) + # real interest rates from macrodata data set + res = kpss( + sunspots.load().data["SUNACTIVITY"], + "c", + nlags="auto", + result_object=False, + ) + assert_equal(res[2], 7) + # volumes from nile data set + with pytest.warns(InterpolationWarning): + res = kpss( + nile.load().data["volume"], "c", nlags="auto", result_object=False + ) + assert_equal(res[2], 5) + # log-coinsurance from randhie data set + with pytest.warns(InterpolationWarning): + res = kpss( + randhie.load().data["lncoins"], + "ct", + nlags="auto", + result_object=False, + ) + assert_equal(res[2], 75) + # in-vehicle time from modechoice data set + with pytest.warns(InterpolationWarning): + res = kpss( + modechoice.load().data["invt"], + "ct", + nlags="auto", + result_object=False, + ) + assert_equal(res[2], 18) + + def test_kpss_fails_on_nobs_check(self): + # Test that if lags exceeds number of observations KPSS raises a + # clear error + # GH5925 + nobs = len(self.x) + msg = rf"lags \({nobs}\) must be < number of observations \({nobs}\)" + with pytest.raises(ValueError, match=msg): + kpss(self.x, "c", nlags=nobs) + + def test_kpss_autolags_does_not_assign_lags_equal_to_nobs(self): + # Test that if *autolags* exceeds number of observations, we set + # suitable lags + # GH5925 + base = np.array([0, 0, 0, 0, 0, 1, 1.0]) + data_which_breaks_autolag = np.r_[np.tile(base, 297 // 7), [0, 0, 0]] + kpss(data_which_breaks_autolag, nlags="auto", result_object=False) + + def test_legacy_lags(self): + # Test legacy lags are the same + with pytest.warns(InterpolationWarning): + res = kpss(self.x, "c", nlags="legacy", result_object=False) + assert_equal(res[2], 15) + + def test_unknown_lags(self): + # Test legacy lags are the same + with pytest.raises(ValueError): + kpss(self.x, "c", nlags="unknown") + + def test_none(self): + with pytest.raises(ValueError, match="None is not a valid value"): + kpss(self.x, nlags=None) + + def test_result_object_default_warns(self): + with pytest.warns(InterpolationWarning, match="The test statistic is"): + with pytest.warns(FutureWarning, match="result_object"): + res = kpss(self.x, "c", nlags=3) + assert not isinstance(res, KPSSResult) + + def test_result_object_false_silences_warning(self): + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=FutureWarning) + with pytest.warns(InterpolationWarning, match="The test statistic is"): + res = kpss(self.x, "c", nlags=3, result_object=False) + assert not isinstance(res, KPSSResult) + + def test_result_object_true_returns_result_object(self): + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=FutureWarning) + with pytest.warns(InterpolationWarning, match="The test statistic is"): + res = kpss(self.x, "c", nlags=3, result_object=True) + assert isinstance(res, KPSSResult) + assert res.resstore is None + assert res[0] == res.statistic + assert res[1] == res.pvalue + assert res.lags == 3 + assert isinstance(res.critical_values, dict) + + def test_result_object_true_with_store(self): + with pytest.warns(InterpolationWarning, match="The test statistic is"): + res = kpss(self.x, "c", nlags=3, store=True, result_object=True) + assert isinstance(res, KPSSResult) + assert res.lags == 3 + assert res.resstore is not None + assert res.resstore.nobs == len(self.x) + assert res.resstore.lags == 3 + + +class TestRUR: + """ + Simple implementation + ------ + Since an R implementation of the test cannot be found, the method is tested against + a simple implementation using a for loop. + In this context, x is the vector containing the + macrodata['realgdp'] series. + """ + + def setup_method(self): + self.data = macrodata.load_pandas() + self.x = self.data.data["realgdp"].values + + # To be removed when range unit test gets an R implementation + def simple_rur(self, x, store=False): + x = array_like(x, "x") + store = bool_like(store, "store") + + nobs = x.shape[0] + + # if m is not one, n != m * n + if nobs != x.size: + raise ValueError(f"x of shape {x.shape} not understood") + + # Table from [1] has been replicated using 200,000 samples + # Critical values for new n_obs values have been identified + pvals = [0.01, 0.025, 0.05, 0.10, 0.90, 0.95] + n = np.array([25, 50, 100, 150, 200, 250, 500, 1000, 2000, 3000, 4000, 5000]) + crit = np.array( + [ + [0.6626, 0.8126, 0.9192, 1.0712, 2.4863, 2.7312], + [0.7977, 0.9274, 1.0478, 1.1964, 2.6821, 2.9613], + [0.907, 1.0243, 1.1412, 1.2888, 2.8317, 3.1393], + [0.9543, 1.0768, 1.1869, 1.3294, 2.8915, 3.2049], + [0.9833, 1.0984, 1.2101, 1.3494, 2.9308, 3.2482], + [0.9982, 1.1137, 1.2242, 1.3632, 2.9571, 3.2482], + [1.0494, 1.1643, 1.2712, 1.4076, 3.0207, 3.3584], + [1.0846, 1.1959, 1.2988, 1.4344, 3.0653, 3.4073], + [1.1121, 1.2200, 1.3230, 1.4556, 3.0948, 3.4439], + [1.1204, 1.2295, 1.3318, 1.4656, 3.1054, 3.4632], + [1.1309, 1.2347, 1.3318, 1.4693, 3.1165, 3.4717], + [1.1377, 1.2402, 1.3408, 1.4729, 3.1252, 3.4807], + ] + ) + + # Interpolation for nobs + inter_crit = np.zeros((1, crit.shape[1])) + for i in range(crit.shape[1]): + f = interp1d(n, crit[:, i]) + inter_crit[0, i] = f(nobs) + + # Calculate RUR stat + count = 0 + + max_p = x[0] + min_p = x[0] + + for v in x[1:]: + if v > max_p: + max_p = v + count = count + 1 + if v < min_p: + min_p = v + count = count + 1 + + rur_stat = count / np.sqrt(len(x)) + + k = len(pvals) - 1 + for i in range(len(pvals) - 1, -1, -1): + if rur_stat < inter_crit[0, i]: + k = i + else: + break + + p_value = pvals[k] + + warn_msg = """\ + The test statistic is outside of the range of p-values available in the + look-up table. The actual p-value is {direction} than the p-value returned. + """ + direction = "" + if p_value == pvals[-1]: + direction = "smaller" + elif p_value == pvals[0]: + direction = "larger" + + if direction: + warnings.warn( + warn_msg.format(direction=direction), InterpolationWarning, stacklevel=2 + ) + + crit_dict = { + "10%": inter_crit[0, 3], + "5%": inter_crit[0, 2], + "2.5%": inter_crit[0, 1], + "1%": inter_crit[0, 0], + } + + if store: + from statsmodels.stats.diagnostic import ResultsStore + + rstore = ResultsStore() + rstore.nobs = nobs + + rstore.H0 = "The series is not stationary" + rstore.HA = "The series is stationary" + + return rur_stat, p_value, crit_dict, rstore + else: + return rur_stat, p_value, crit_dict + + def test_fail_nonvector_input(self): + with pytest.warns(InterpolationWarning): + range_unit_root_test(self.x, result_object=False) + + rs = np.random.RandomState(8474768) + x = rs.rand(20, 2) + with pytest.raises(ValueError): + range_unit_root_test(x, result_object=False) + + def test_teststat(self): + with pytest.warns(InterpolationWarning): + rur_stat, _, _ = range_unit_root_test(self.x, result_object=False) + simple_rur_stat, _, _ = self.simple_rur(self.x) + assert_almost_equal(rur_stat, simple_rur_stat, DECIMAL_3) + + def test_pval(self): + with pytest.warns(InterpolationWarning): + _, pval, _ = range_unit_root_test(self.x, result_object=False) + _, simple_pval, _ = self.simple_rur(self.x) + assert_equal(pval, simple_pval) + + def test_store(self): + with pytest.warns(InterpolationWarning): + result = range_unit_root_test(self.x, True, result_object=False) + _, _, _, store = result + + # assert attributes, and make sure they're correct + assert_equal(store.nobs, len(self.x)) + + def test_result_object_true_returns_result_object(self): + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=FutureWarning) + warnings.filterwarnings("ignore", category=InterpolationWarning) + res = range_unit_root_test(self.x, result_object=True) + assert isinstance(res, RURResult) + assert res.resstore is None + assert res[0] == res.statistic + assert res[1] == res.pvalue + assert isinstance(res.critical_values, dict) + + def test_result_object_true_with_store(self): + with pytest.warns(InterpolationWarning, match="The test statistic is"): + res = range_unit_root_test(self.x, store=True, result_object=True) + assert isinstance(res, RURResult) + assert res.resstore is not None + assert res.resstore.nobs == len(self.x) + + +def test_pandasacovf(): + s = Series(lrange(1, 11)) + assert_almost_equal(acovf(s, fft=False), acovf(s.values, fft=False)) + + +def test_acovf2d(): + dta = sunspots.load_pandas().data + dta.index = date_range(start="1700", end="2009", freq=YEAR_END)[:309] + del dta["YEAR"] + res = acovf(dta, fft=False) + assert_equal(res, acovf(dta.values, fft=False)) + rs = np.random.RandomState(992333) + x = rs.random((10, 2)) + with pytest.raises(ValueError): + acovf(x, fft=False) + + +@pytest.mark.parametrize("demean", [True, False]) +@pytest.mark.parametrize("adjusted", [True, False]) +def test_acovf_fft_vs_convolution(demean, adjusted): + rs = np.random.RandomState(83747) + q = rs.normal(size=100) + + F1 = acovf(q, demean=demean, adjusted=adjusted, fft=True) + F2 = acovf(q, demean=demean, adjusted=adjusted, fft=False) + assert_almost_equal(F1, F2, decimal=7) + + +@pytest.mark.parametrize("demean", [True, False]) +@pytest.mark.parametrize("adjusted", [True, False]) +def test_ccovf_fft_vs_convolution(demean, adjusted): + rs = np.random.RandomState(3843983) + x = rs.normal(size=128) + y = rs.normal(size=128) + + F1 = ccovf(x, y, demean=demean, adjusted=adjusted, fft=False) + F2 = ccovf(x, y, demean=demean, adjusted=adjusted, fft=True) + assert_almost_equal(F1, F2, decimal=7) + + +@pytest.mark.parametrize("demean", [True, False]) +@pytest.mark.parametrize("adjusted", [True, False]) +@pytest.mark.parametrize("fft", [True, False]) +def test_compare_acovf_vs_ccovf(demean, adjusted, fft): + rs = np.random.RandomState(14523) + x = rs.normal(size=128) + + F1 = acovf(x, demean=demean, adjusted=adjusted, fft=fft) + F2 = ccovf(x, x, demean=demean, adjusted=adjusted, fft=fft) + assert_almost_equal(F1, F2, decimal=7) + + +@pytest.mark.parametrize("adjusted", [True, False]) +@pytest.mark.parametrize("fft", [True, False]) +def test_ccovf_different_lengths(adjusted, fft): + # Regression test for GH#9565 + # ccovf crashed when len(x) != len(y) and adjusted=True + rs = np.random.RandomState(98765) + x = rs.normal(size=200) + y = rs.normal(size=150) + + result = ccovf(x, y, adjusted=adjusted, fft=fft) + # Output should always have length len(x) + assert result.shape == (200,) + assert np.all(np.isfinite(result)) + + # Also test when len(x) < len(y) + result2 = ccovf(y, x, adjusted=adjusted, fft=fft) + assert result2.shape == (150,) + assert np.all(np.isfinite(result2)) + + +def test_ccovf_different_lengths_known_lag(): + # Verify that ccovf correctly identifies a known lag + # when the arrays have different lengths (GH#9565) + rs = np.random.RandomState(54321) + x = rs.normal(size=200) + # y is x shifted by 5 positions, but shorter + y = x[5:180] + rs.normal(size=175) * 0.05 + + result = ccovf(x, y, adjusted=False) + # Peak should be at lag 5 + assert result.shape == (200,) + assert np.argmax(result[:50]) == 5 + + +@pytest.mark.parametrize("fft", [True, False]) +def test_ccovf_adjusted_shorter_y(fft): + # GH#9565 follow-up: with len(y) < len(x), adjusted=True must divide by + # the number of overlapping observations, min(len(y), len(x) - k), not + # by len(x) - k. + x = np.ones(6) + y = np.ones(2) + + # Every product is exactly 1.0, so every adjusted average must be 1.0. + result = ccovf(x, y, adjusted=True, demean=False, fft=fft) + assert_allclose(result, np.ones(6)) + + # The unadjusted path divides by len(x) throughout, by definition, so the + # overlap counts min(2, 6 - k) show through unscaled. + unadjusted = ccovf(x, y, adjusted=False, demean=False, fft=fft) + assert_allclose(unadjusted, np.array([2, 2, 2, 2, 2, 1]) / 6) + + +def test_ccf_different_lengths(): + # Regression test for GH#9565 (ccf calls ccovf) + rs = np.random.RandomState(11111) + x = rs.normal(size=100) + y = rs.normal(size=80) + + result = ccf(x, y, adjusted=True, nlags=30) + assert result.shape == (30,) + assert np.all(np.isfinite(result)) + + +@pytest.mark.smoke +@pytest.mark.slow +def test_arma_order_select_ic(): + # smoke test, assumes info-criteria are right + from statsmodels.tsa.arima_process import arma_generate_sample + + arparams = np.array([0.75, -0.25]) + maparams = np.array([0.65, 0.35]) + arparams = np.r_[1, -arparams] + nobs = 250 + rs = np.random.RandomState(2014) + y = arma_generate_sample(arparams, maparams, nobs, distrvs=rs.standard_normal) + res = arma_order_select_ic(y, ic=["aic", "bic"], trend="n") + # regression tests in case we change algorithm to minic in sas + aic_x = np.array( + [ + [764.36517643, 552.7342255, 484.29687843], + [562.10924262, 485.5197969, 480.32858497], + [507.04581344, 482.91065829, 481.91926034], + [484.03995962, 482.14868032, 483.86378955], + [481.8849479, 483.8377379, 485.83756612], + ] + ) + bic_x = np.array( + [ + [767.88663735, 559.77714733, 494.86126118], + [569.15216446, 496.08417966, 494.41442864], + [517.61019619, 496.99650196, 499.52656493], + [498.12580329, 499.75598491, 504.99255506], + [499.49225249, 504.96650341, 510.48779255], + ] + ) + aic = DataFrame(aic_x, index=lrange(5), columns=lrange(3)) + bic = DataFrame(bic_x, index=lrange(5), columns=lrange(3)) + assert_almost_equal(res.aic.values, aic.values, 5) + assert_almost_equal(res.bic.values, bic.values, 5) + assert_equal(res.aic_min_order, (1, 2)) + assert_equal(res.bic_min_order, (1, 2)) + assert res.aic.index.equals(aic.index) + assert res.aic.columns.equals(aic.columns) + assert res.bic.index.equals(bic.index) + assert res.bic.columns.equals(bic.columns) + + index = pd.date_range("2000-1-1", freq=MONTH_END, periods=len(y)) + y_series = pd.Series(y, index=index) + res_pd = arma_order_select_ic( + y_series, max_ar=2, max_ma=1, ic=["aic", "bic"], trend="n" + ) + assert_almost_equal(res_pd.aic.values, aic.values[:3, :2], 5) + assert_almost_equal(res_pd.bic.values, bic.values[:3, :2], 5) + assert_equal(res_pd.aic_min_order, (2, 1)) + assert_equal(res_pd.bic_min_order, (1, 1)) + + res = arma_order_select_ic(y, ic="aic", trend="n") + assert_almost_equal(res.aic.values, aic.values, 5) + assert res.aic.index.equals(aic.index) + assert res.aic.columns.equals(aic.columns) + assert_equal(res.aic_min_order, (1, 2)) + + +def test_diebold_mariano_test(): + y = np.array( + [ + 0.7905291971644244, + 1.3165423213858396, + 2.629194824493898, + 2.274163381390831, + 2.3350897900078773, + 4.309556160533848, + 3.2008616600117854, + 3.0279620894948263, + 2.567645423157318, + 0.8342527751292501, + 2.0985671460216464, + 3.408247061676925, + 2.9699882967078457, + 3.6732582708103863, + 3.4609292040029644, + ] + ) + f1 = np.array( + [ + 0.9824387126880363, + 3.347555830856235, + 1.8132440948000608, + 4.501884323116638, + 0.993073450965922, + 0.988116816888287, + 3.7834883570834847, + 2.498189378576747, + 4.8566413245270965, + 1.7412497391486617, + 3.4637323882747384, + 3.101483832900048, + 3.0411384793663037, + 3.2500575506493394, + 3.199491151189982, + ] + ) + f2 = np.array( + [ + 0.8002551776387801, + 2.35554283908294, + 2.5017107565163754, + 2.9709840260800897, + 2.031947528256514, + 2.044069317891979, + 1.8690271476061573, + 2.541558191277514, + 3.0762879697739653, + 3.420942734113572, + 3.9529070460967226, + 3.036772850400313, + 3.898343203105889, + 4.397338510819033, + 4.699775884928464, + ] + ) + + res1 = diebold_mariano_test(y, f1, f2, criterion="mse") + res2 = diebold_mariano_test(y, f1, f2, lags=2, criterion="mse") + res3 = diebold_mariano_test(y, f1, f2, criterion="mad") + + d = (y - f1) ** 2 - (y - f2) ** 2 + maxlags = int(np.ceil(len(d) ** (1 / 3))) + res = OLS(d, np.ones_like(d)).fit(cov_type="HAC", cov_kwds={"maxlags": maxlags}) + + assert_almost_equal(res1.statistic, res.tvalues[0], DECIMAL_3) + assert_almost_equal(res1.pvalue, res.pvalues[0], DECIMAL_3) + + res = OLS(d, np.ones_like(d)).fit(cov_type="HAC", cov_kwds={"maxlags": 2}) + + assert_almost_equal(res2.statistic, res.tvalues[0], DECIMAL_3) + assert_almost_equal(res2.pvalue, res.pvalues[0], DECIMAL_3) + + d = np.abs(y - f1) - np.abs(y - f2) + res = OLS(d, np.ones_like(d)).fit(cov_type="HAC", cov_kwds={"maxlags": maxlags}) + + assert_almost_equal(res3.statistic, res.tvalues[0], DECIMAL_3) + assert_almost_equal(res3.pvalue, res.pvalues[0], DECIMAL_3) + + y += 10 + f1 += 10 + f2 += 10 + res4 = diebold_mariano_test(y, f1, f2, criterion="mape") + d = np.abs((y - f1) / y) - np.abs((y - f2) / y) + res = OLS(d, np.ones_like(d)).fit(cov_type="HAC", cov_kwds={"maxlags": maxlags}) + + assert_almost_equal(res4.statistic, res.tvalues[0], DECIMAL_3) + assert_almost_equal(res4.pvalue, res.pvalues[0], DECIMAL_3) + + +def test_diebold_mariano_harvey_adj(): + rs = np.random.default_rng() + y, f1, f2 = rs.standard_normal((3, 100)) + res_no = diebold_mariano_test(y, f1, f2, harvey_adj=False) + res_yes = diebold_mariano_test(y, f1, f2, harvey_adj=True, horizon=3) + assert res_no.harvey_adj_factor is None + assert isinstance(res_yes.harvey_adj_factor, float) + assert 0 <= res_yes.harvey_adj_factor < 1 + direct_factor = np.sqrt((100 + 1 - (2 * 3) + ((3 * 2) / 100)) / 100) + assert_almost_equal(res_yes.harvey_adj_factor, direct_factor) + assert res_yes.pvalue > res_no.pvalue + assert np.abs(res_no.statistic) > np.abs(res_yes.statistic) + assert len(res_no) == 2 + + +def test_diebold_mariano_equiv(): + rs = np.random.default_rng() + y, f1, f2 = rs.standard_normal((3, 100)) + res = diebold_mariano_test(y, f1, f2) + res_poly = diebold_mariano_test(y, f1, f2, criterion="poly", power=2) + assert_almost_equal(res.statistic, res_poly.statistic) + + res = diebold_mariano_test(y, f1, f2, criterion="mad") + res_mae = diebold_mariano_test(y, f1, f2, criterion="mae") + res_poly = diebold_mariano_test(y, f1, f2, criterion="poly", power=1) + assert_almost_equal(res.statistic, res_poly.statistic) + assert_almost_equal(res_mae.statistic, res_poly.statistic) + + +@pytest.mark.smoke +def test_diebold_mariano_callable_smoke(): + + rng = np.random.default_rng(0) + y = rng.standard_normal(200) ** 2 + scale = rng.chisquare(5, size=y.shape) / 5 + forecast_a = 0.9 * scale * y + forecast_b = scale * y + + def qlike(y, forecast): + ratio = y / forecast + return ratio - np.log(ratio) - 1 + + res = diebold_mariano_test(y, forecast_a, forecast_b, criterion=qlike) + assert np.isfinite(res.statistic) + assert 0 <= res.pvalue <= 1 + + +def test_diebold_mariano_exceptions(): + rs = np.random.default_rng() + y, f1, f2 = rs.standard_normal((3, 100)) + with pytest.raises(ValueError, match="lags must be a non-negative integer"): + diebold_mariano_test(y, f1, f2, lags=-1) + with pytest.raises(ValueError, match="y, forecast_a and forecast_b must all"): + diebold_mariano_test(y, f1, f2[::2]) + with pytest.raises(ValueError, match="horizon must be a positive integer"): + diebold_mariano_test(y, f1, f2, horizon=0) + + +def test_arma_order_select_ic_failure(): + # this should trigger an SVD convergence failure, smoke test that it + # returns, likely platform dependent failure... + # looks like AR roots may be cancelling out for 4, 1? + y = np.array( + [ + 0.86074377817203640006, + 0.85316549067906921611, + 0.87104653774363305363, + 0.60692382068987393851, + 0.69225941967301307667, + 0.73336177248909339976, + 0.03661329261479619179, + 0.15693067239962379955, + 0.12777403512447857437, + -0.27531446294481976, + -0.24198139631653581283, + -0.23903317951236391359, + -0.26000241325906497947, + -0.21282920015519238288, + -0.15943768324388354896, + 0.25169301564268781179, + 0.1762305709151877342, + 0.12678133368791388857, + 0.89755829086753169399, + 0.82667068795350151511, + ] + ) + import warnings + + with warnings.catch_warnings(): + # catch a hessian inversion and convergence failure warning + warnings.simplefilter("ignore") + arma_order_select_ic(y) + + +def test_acf_fft_dataframe(): + # regression test #322 + + result = acf(sunspots.load_pandas().data[["SUNACTIVITY"]], fft=True, nlags=20) + assert_equal(result.ndim, 1) + + +def test_levinson_durbin_acov(): + rho = 0.9 + m = 20 + acov = rho ** np.arange(200) + _ld_result = levinson_durbin(acov, m, isacov=True) + sigma2_eps, ar, pacf = _ld_result.sigma_v, _ld_result.arcoefs, _ld_result.pacf + assert_allclose(sigma2_eps, 1 - rho**2) + assert_allclose(ar, np.array([rho] + [0] * (m - 1)), atol=1e-8) + assert_allclose(pacf, np.array([1, rho] + [0] * (m - 1)), atol=1e-8) + + +@pytest.mark.parametrize("missing", ["conservative", "drop", "raise", "none"]) +@pytest.mark.parametrize("fft", [False, True]) +@pytest.mark.parametrize("demean", [True, False]) +@pytest.mark.parametrize("adjusted", [True, False]) +def test_acovf_nlags(acovf_data, adjusted, demean, fft, missing): + full = acovf(acovf_data, adjusted=adjusted, demean=demean, fft=fft, missing=missing) + limited = acovf( + acovf_data, + adjusted=adjusted, + demean=demean, + fft=fft, + missing=missing, + nlag=10, + ) + assert_allclose(full[:11], limited) + + +@pytest.mark.parametrize("missing", ["conservative", "drop"]) +@pytest.mark.parametrize("fft", [False, True]) +@pytest.mark.parametrize("demean", [True, False]) +@pytest.mark.parametrize("adjusted", [True, False]) +def test_acovf_nlags_missing(acovf_data, adjusted, demean, fft, missing): + acovf_data = acovf_data.copy() + acovf_data[1:3] = np.nan + full = acovf(acovf_data, adjusted=adjusted, demean=demean, fft=fft, missing=missing) + limited = acovf( + acovf_data, + adjusted=adjusted, + demean=demean, + fft=fft, + missing=missing, + nlag=10, + ) + assert_allclose(full[:11], limited) + + +def test_acovf_error(acovf_data): + with pytest.raises(ValueError): + acovf(acovf_data, nlag=250, fft=False) + + +def test_pacf2acf_ar(): + pacf = np.zeros(10) + pacf[0] = 1 + pacf[1] = 0.9 + _ldp_result = levinson_durbin_pacf(pacf) + ar, acf = _ldp_result.arcoefs, _ldp_result.acf + assert_allclose(acf, 0.9 ** np.arange(10.0)) + assert_allclose(ar, pacf[1:], atol=1e-8) + + _ldp_result = levinson_durbin_pacf(pacf, nlags=5) + ar, acf = _ldp_result.arcoefs, _ldp_result.acf + assert_allclose(acf, 0.9 ** np.arange(6.0)) + assert_allclose(ar, pacf[1:6], atol=1e-8) + + +def test_pacf2acf_levinson_durbin(): + pacf = -(0.9 ** np.arange(11.0)) + pacf[0] = 1 + _ldp_result = levinson_durbin_pacf(pacf) + ar, acf = _ldp_result.arcoefs, _ldp_result.acf + _ld_result = levinson_durbin(acf, 10, isacov=True) + ar_ld, pacf_ld = _ld_result.arcoefs, _ld_result.pacf + assert_allclose(ar, ar_ld, atol=1e-8) + assert_allclose(pacf, pacf_ld, atol=1e-8) + + # From R, FitAR, PacfToAR + ar_from_r = [ + -4.1609, + -9.2549, + -14.4826, + -17.6505, + -17.5012, + -14.2969, + -9.5020, + -4.9184, + -1.7911, + -0.3486, + ] + assert_allclose(ar, ar_from_r, atol=1e-4) + + +def test_pacf2acf_errors(): + pacf = -(0.9 ** np.arange(11.0)) + pacf[0] = 1 + with pytest.raises(ValueError): + levinson_durbin_pacf(pacf, nlags=20) + with pytest.raises(ValueError): + levinson_durbin_pacf(pacf[1:]) + with pytest.raises(ValueError): + levinson_durbin_pacf(np.zeros(10)) + with pytest.raises(ValueError): + levinson_durbin_pacf(np.zeros((10, 2))) + + +def test_pacf_burg(): + rnd = np.random.RandomState(12345) + e = rnd.randn(10001) + y = e[1:] + 0.5 * e[:-1] + _pb_result = pacf_burg(y, 10) + pacf, sigma2 = _pb_result.pacf, _pb_result.sigma2 + yw_pacf = pacf_yw(y, 10) + assert_allclose(pacf, yw_pacf, atol=5e-4) + # Internal consistency check between pacf and sigma2 + ye = y - y.mean() + s2y = ye.dot(ye) / 10000 + pacf[0] = 0 + sigma2_direct = s2y * np.cumprod(1 - pacf**2) + assert_allclose(sigma2, sigma2_direct, atol=1e-3) + + +def test_pacf_burg_error(): + with pytest.raises(ValueError): + pacf_burg(np.empty((20, 2)), 10) + with pytest.raises(ValueError): + pacf_burg(np.empty(100), 101) + + +def test_innovations_algo_brockwell_davis(): + ma = -0.9 + acovf = np.array([1 + ma**2, ma]) + theta, sigma2 = innovations_algo(acovf, nobs=4) + exp_theta = np.array([[0], [-0.4972], [-0.6606], [-0.7404]]) + assert_allclose(theta, exp_theta, rtol=1e-4) + assert_allclose(sigma2, [1.81, 1.3625, 1.2155, 1.1436], rtol=1e-4) + + theta, sigma2 = innovations_algo(acovf, nobs=500) + assert_allclose(theta[-1, 0], ma) + assert_allclose(sigma2[-1], 1.0) + + +def test_innovations_algo_rtol(): + ma = np.array([-0.9, 0.5]) + acovf = np.array([1 + (ma**2).sum(), ma[0] + ma[1] * ma[0], ma[1]]) + theta, sigma2 = innovations_algo(acovf, nobs=500) + theta_2, sigma2_2 = innovations_algo(acovf, nobs=500, rtol=1e-8) + assert_allclose(theta, theta_2) + assert_allclose(sigma2, sigma2_2) + + +def test_innovations_errors(): + ma = -0.9 + acovf = np.array([1 + ma**2, ma]) + with pytest.raises(TypeError): + innovations_algo(acovf, nobs=2.2) + with pytest.raises(ValueError): + innovations_algo(acovf, nobs=-1) + with pytest.raises(ValueError): + innovations_algo(np.empty((2, 2))) + with pytest.raises(TypeError): + innovations_algo(acovf, rtol="none") + + +def test_innovations_filter_brockwell_davis(): + ma = -0.9 + acovf = np.array([1 + ma**2, ma]) + theta, _ = innovations_algo(acovf, nobs=4) + rs = np.random.RandomState(12345) + e = rs.randn(5) + endog = e[1:] + ma * e[:-1] + resid = innovations_filter(endog, theta) + expected = [endog[0]] + for i in range(1, 4): + expected.append(endog[i] - theta[i, 0] * expected[-1]) + expected = np.array(expected) + assert_allclose(resid, expected) + + +def test_innovations_filter_pandas(): + ma = np.array([-0.9, 0.5]) + acovf = np.array([1 + (ma**2).sum(), ma[0] + ma[1] * ma[0], ma[1]]) + theta, _ = innovations_algo(acovf, nobs=10) + rs = np.random.RandomState(12345) + endog = rs.randn(10) + endog_pd = pd.Series(endog, index=pd.date_range("2000-01-01", periods=10)) + resid = innovations_filter(endog, theta) + resid_pd = innovations_filter(endog_pd, theta) + assert_allclose(resid, resid_pd.values) + assert_index_equal(endog_pd.index, resid_pd.index) + + +def test_innovations_filter_errors(): + ma = -0.9 + acovf = np.array([1 + ma**2, ma]) + theta, _ = innovations_algo(acovf, nobs=4) + with pytest.raises(ValueError): + innovations_filter(np.empty((2, 2)), theta) + with pytest.raises(ValueError): + innovations_filter(np.empty(4), theta[:-1]) + with pytest.raises(ValueError): + innovations_filter(pd.DataFrame(np.empty((1, 4))), theta) + + +def test_innovations_algo_filter_kalman_filter(): + # Test the innovations algorithm and filter against the Kalman filter + # for exact likelihood evaluation of an ARMA process + ar_params = np.array([0.5]) + ma_params = np.array([0.2]) + # TODO could generalize to sigma2 != 1, if desired, after #5324 is merged + # and there is a sigma2 argument to arma_acovf + # (but maybe this is not really necessary for the point of this test) + sigma2 = 1 + rs = np.random.RandomState(123456) + endog = rs.normal(size=10) + + # Innovations algorithm approach + acovf = arma_acovf(np.r_[1, -ar_params], np.r_[1, ma_params], nobs=len(endog)) + + theta, v = innovations_algo(acovf) + u = innovations_filter(endog, theta) + llf_obs = -0.5 * u**2 / (sigma2 * v) - 0.5 * np.log(2 * np.pi * v) + + # Kalman filter apparoach + mod = SARIMAX(endog, order=(len(ar_params), 0, len(ma_params))) + res = mod.filter(np.r_[ar_params, ma_params, sigma2]) + + # Test that the two approaches are identical + atol = 1e-6 if PLATFORM_WIN else 0.0 + assert_allclose(u, res.forecasts_error[0], rtol=1e-6, atol=atol) + assert_allclose(theta[1:, 0], res.filter_results.kalman_gain[0, 0, :-1], atol=atol) + assert_allclose(llf_obs, res.llf_obs, atol=atol) + + +def test_adfuller_short_series(): + rs = np.random.RandomState(9374) + y = rs.standard_normal(7) + res = adfuller(y, store=True, result_object=False) + assert res[-1].maxlag == 1 + y = rs.standard_normal(2) + with pytest.raises(ValueError, match="sample size is too short"): + adfuller(y) + y = rs.standard_normal(3) + with pytest.raises(ValueError, match="sample size is too short"): + adfuller(y, regression="ct") + + +def test_adfuller_maxlag_too_large(): + rs = np.random.RandomState(3723) + y = rs.standard_normal(100) + with pytest.raises(ValueError, match="maxlag must be less than"): + adfuller(y, maxlag=51) + + +@pytest.fixture +def adfuller_data(): + rs = np.random.RandomState(0) + return np.cumsum(rs.standard_normal(200)) + + +def test_adfuller_result_object_default_warns(adfuller_data): + with pytest.warns(FutureWarning, match="result_object"): + res = adfuller(adfuller_data) + assert isinstance(res, tuple) + assert not isinstance(res, ADFullerResult) + assert len(res) == 6 + + +def test_adfuller_result_object_false_silences_warning(adfuller_data): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = adfuller(adfuller_data, result_object=False) + assert isinstance(res, tuple) + assert not isinstance(res, ADFullerResult) + assert len(res) == 6 + + +def test_adfuller_result_object_true_returns_result_object(adfuller_data): + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = adfuller(adfuller_data, result_object=True) + assert isinstance(res, ADFullerResult) + # still positionally indexable like the legacy tuple + assert res[0] == res.statistic + assert res[1] == res.pvalue + assert res.resstore is None + + +def test_adfuller_result_object_true_with_store(adfuller_data): + res = adfuller(adfuller_data, store=True, result_object=True) + assert isinstance(res, ADFullerResult) + assert res.resstore is not None + assert res.resstore.__str__() == "Augmented Dickey-Fuller Test Results" + + +def test_adfuller_result_object_true_without_autolag(adfuller_data): + res = adfuller(adfuller_data, autolag=None, maxlag=4, result_object=True) + assert isinstance(res, ADFullerResult) + assert res.icbest is None + + +def test_adfuller_result_object_matches_legacy_values(adfuller_data): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + legacy = adfuller(adfuller_data) + nt = adfuller(adfuller_data, result_object=True) + assert_almost_equal(nt.statistic, legacy[0]) + assert_almost_equal(nt.pvalue, legacy[1]) + assert nt.lags == legacy[2] + assert nt.nobs == legacy[3] + assert nt.critical_values == legacy[4] + assert_almost_equal(nt.icbest, legacy[5]) + + +class SetupZivotAndrews: + # test directory + cur_dir = CURR_DIR + run_dir = Path(cur_dir).joinpath("results") + # use same file for testing failure modes + fail_file = Path(run_dir).joinpath("rgnp.csv") + fail_mdl = np.asarray(pd.read_csv(fail_file)) + + +class TestZivotAndrews(SetupZivotAndrews): + # failure mode tests + def test_fail_regression_type(self): + with pytest.raises(ValueError): + zivot_andrews(self.fail_mdl, regression="x") + + def test_fail_trim_value(self): + with pytest.raises(ValueError): + zivot_andrews(self.fail_mdl, trim=0.5) + + def test_fail_array_shape(self): + with pytest.raises(ValueError): + rs = np.random.RandomState(37283) + zivot_andrews(rs.rand(50, 2)) + + def test_fail_autolag_type(self): + with pytest.raises(ValueError): + zivot_andrews(self.fail_mdl, autolag="None") + + @pytest.mark.parametrize("autolag", ["AIC", "aic", "Aic"]) + def test_autolag_case_sensitivity(self, autolag): + res = zivot_andrews(self.fail_mdl, autolag=autolag) + assert res[3] == 1 + + # following tests compare results to R package urca.ur.za (1.13-0) + def test_rgnp_case(self): + res = zivot_andrews(self.fail_mdl, maxlag=8, regression="c", autolag=None) + assert_allclose([res[0], res[1], res[4]], [-5.57615, 0.00312, 20], rtol=1e-3) + + def test_gnpdef_case(self): + mdlfile = Path(self.run_dir).joinpath("gnpdef.csv") + mdl = np.asarray(pd.read_csv(mdlfile)) + res = zivot_andrews(mdl, maxlag=8, regression="c", autolag="t-stat") + assert_allclose( + [res[0], res[1], res[3], res[4]], + [-4.12155, 0.28024, 5, 40], + rtol=1e-3, + ) + + def test_stkprc_case(self): + mdlfile = Path(self.run_dir).joinpath("stkprc.csv") + mdl = np.asarray(pd.read_csv(mdlfile)) + res = zivot_andrews(mdl, maxlag=8, regression="ct", autolag="t-stat") + assert_allclose( + [res[0], res[1], res[3], res[4]], + [-5.60689, 0.00894, 1, 65], + rtol=1e-3, + ) + + def test_rgnpq_case(self): + mdlfile = Path(self.run_dir).joinpath("rgnpq.csv") + mdl = np.asarray(pd.read_csv(mdlfile)) + res = zivot_andrews(mdl, maxlag=12, regression="t", autolag="t-stat") + assert_allclose( + [res[0], res[1], res[3], res[4]], + [-3.02761, 0.63993, 12, 102], + rtol=1e-3, + ) + + def test_rand10000_case(self): + mdlfile = Path(self.run_dir).joinpath("rand10000.csv") + mdl = np.asarray(pd.read_csv(mdlfile)) + res = zivot_andrews(mdl, regression="c", autolag="t-stat") + assert_allclose( + [res[0], res[1], res[3], res[4]], + [-3.48223, 0.69111, 25, 7071], + rtol=1e-3, + ) + + +def test_acf_conservate_nanops(): + # GH 6729 + rs = np.random.RandomState(32738493) + e = rs.standard_normal(100) + for i in range(1, e.shape[0]): + e[i] += 0.9 * e[i - 1] + e[::7] = np.nan + result = acf(e, missing="conservative", nlags=10, fft=False) + resid = e - np.nanmean(e) + expected = np.ones(11) + nobs = e.shape[0] + gamma0 = np.nansum(resid * resid) + for i in range(1, 10 + 1): + expected[i] = np.nansum(resid[i:] * resid[: nobs - i]) / gamma0 + assert_allclose(result, expected, rtol=1e-4, atol=1e-4) + + +def test_pacf_nlags_error(): + rs = np.random.RandomState(12487) + e = rs.standard_normal(99) + with pytest.raises(ValueError, match="Can only compute partial"): + pacf(e, 50) + + +def test_coint_auto_tstat(): + rs = np.random.RandomState(3733696641) + x = np.cumsum(rs.standard_normal(100)) + y = np.cumsum(rs.standard_normal(100)) + res = coint( + x, + y, + trend="c", + method="aeg", + maxlag=0, + autolag="t-stat", + return_results=False, + ) + assert np.abs(res.coint_t) < 1.65 + + +rs = np.random.RandomState(1) +a = rs.random_sample(120) +b = np.zeros_like(a) +df1 = pd.DataFrame({"b": b, "a": a}) +df2 = pd.DataFrame({"a": a, "b": b}) + +b = np.ones_like(a) +df3 = pd.DataFrame({"b": b, "a": a}) +df4 = pd.DataFrame({"a": a, "b": b}) + +gc_data_sets = [df1, df2, df3, df4] + + +@pytest.mark.parametrize("dataset", gc_data_sets) +def test_granger_causality_exceptions(dataset): + with pytest.raises(InfeasibleTestError): + grangercausalitytests(dataset, 4) + + +def test_granger_causality_exception_maxlag(gc_data): + with pytest.raises(ValueError, match="maxlag must be"): + grangercausalitytests(gc_data, maxlag=-1) + with pytest.raises(NotImplementedError): + grangercausalitytests(gc_data, 3, addconst=False) + + +@pytest.mark.parametrize("size", [3, 5, 7, 9]) +def test_pacf_small_sample(size): + rs = np.random.RandomState(490203) + y = rs.standard_normal(size) + a = pacf(y) + assert isinstance(a, np.ndarray) + _pb_result = pacf_burg(y) + a, b = _pb_result.pacf, _pb_result.sigma2 + assert isinstance(a, np.ndarray) + assert isinstance(b, np.ndarray) + a = pacf_ols(y) + assert isinstance(a, np.ndarray) + a = pacf_yw(y) + assert isinstance(a, np.ndarray) + + +def test_pacf_1_obs(): + rs = np.random.RandomState(34857549) + y = rs.standard_normal(1) + with pytest.raises(ValueError): + pacf(y) + with pytest.raises(ValueError): + pacf_burg(y) + with pytest.raises(ValueError): + pacf_ols(y) + pacf_yw(y) + + +def test_zivot_andrews_change_data(): + # GH9307 + years = pd.date_range(start="1990-01-01", end="2023-12-31", freq="YS") + df = pd.DataFrame(index=years) + df["variable1"] = np.where(df.index.year <= 2002, 10, 20) + df["variable2"] = np.where(df.index.year <= 2002, 10, 20) + df.iloc[-1] = 30 + + # Zivot-Andrews test with data with type float64 + df = df.astype(float) + df_original = df.copy() + zivot_andrews(df["variable1"]) + zivot_andrews(df["variable1"], regression="c") + pd.testing.assert_frame_equal(df, df_original) + + +class TestLeybourneMcCabe: + cur_dir = CURR_DIR + run_dir = Path(cur_dir).joinpath("results") + + # failure mode tests + def test_fail_inputs(self): + # use results/BAA.csv file for testing failure modes + fail_file = Path(self.run_dir).joinpath("BAA.csv") + fail_mdl = np.asarray(pd.read_csv(fail_file)) + with pytest.raises(ValueError): + leybourne(fail_mdl, regression="nc") + with pytest.raises(ValueError): + leybourne(fail_mdl, method="gls") + with pytest.raises(ValueError): + leybourne(fail_mdl, varest="var98") + with pytest.raises(ValueError): + leybourne([[1, 1], [2, 2]], regression="c") + with pytest.raises(ValueError): + leybourne(fail_mdl, arlags=250) + with pytest.raises(ValueError): + leybourne(fail_mdl, arlags="error") + + # the following tests use data sets from Schwert (1987) + # and were verified against Matlab 9.13 + def test_baa_results(self): + mdl_file = Path(self.run_dir).joinpath("BAA.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, regression="ct", method="mle") + assert_allclose(res[0:3], [5.4438, 0.0000, 3], rtol=1e-4, atol=1e-4) + res = leybourne(mdl, regression="ct") + assert_allclose(res[0:3], [5.4757, 0.0000, 3], rtol=1e-4, atol=1e-4) + + def test_dbaa_results(self): + mdl_file = Path(self.run_dir).joinpath("DBAA.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, method="mle") + assert_allclose(res[0:3], [0.096534, 0.602535, 2], rtol=1e-4, atol=1e-4) + res = leybourne(mdl, regression="ct", method="mle") + assert_allclose(res[0:3], [0.047924, 0.601817, 2], rtol=1e-4, atol=1e-4) + + def test_dsp500_results(self): + mdl_file = Path(self.run_dir).joinpath("DSP500.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, method="mle") + assert_allclose(res[0:3], [0.3118, 0.1256, 0], rtol=1e-4, atol=1e-4) + res = leybourne(mdl, varest="var99", method="mle") + assert_allclose(res[0:3], [0.306886, 0.129934, 0], rtol=1e-4, atol=1e-4) + + def test_dun_results(self): + mdl_file = Path(self.run_dir).joinpath("DUN.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, regression="ct", method="ols") + assert_allclose(res[0:3], [0.0938, 0.1890, 3], rtol=1e-4, atol=1e-4) + + @pytest.mark.xfail(reason="Fails due to numerical issues", strict=False) + def test_dun_results_arima(self): + mdl_file = Path(self.run_dir).joinpath("DUN.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, regression="ct") + assert_allclose(res[0], 0.024083, rtol=1e-4, atol=1e-4) + assert_allclose(res[1], 0.943151, rtol=1e-4, atol=1e-4) + assert res[2] == 3 + + def test_sp500_results(self): + mdl_file = Path(self.run_dir).joinpath("SP500.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, arlags=4, regression="ct", method="mle") + assert_allclose(res[0:2], [1.8761, 0.0000], rtol=1e-4, atol=1e-4) + res = leybourne(mdl, arlags=4, regression="ct") + assert_allclose(res[0:2], [1.9053, 0.0000], rtol=1e-4, atol=1e-4) + + def test_un_results(self): + mdl_file = Path(self.run_dir).joinpath("UN.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, method="ols", varest="var99") + assert_allclose(res[0:3], [556.0444, 0.0000, 4], rtol=1e-4, atol=1e-4) + + @pytest.mark.xfail(reason="Fails due to numerical issues", strict=False) + def test_un_results_arima(self): + mdl_file = Path(self.run_dir).joinpath("UN.csv") + mdl = np.asarray(pd.read_csv(mdl_file)) + res = leybourne(mdl, varest="var99") + assert_allclose(res[0], 285.5181, rtol=1e-4, atol=1e-4) + assert_allclose(res[1], 0.0000, rtol=1e-4, atol=1e-4) + assert res[2] == 4 + + def test_lm_whitenoise(self): + rg = np.random.RandomState(0) + y = rg.standard_normal(250) + res = leybourne(y, method="ols", varest="var99") + assert res[2] == 0 + + +def test_acovf_all_missing(): + x = np.full(100, np.nan) + with pytest.raises( + ValueError, match=r"All observations are missing after dropping." + ): + acovf(x, missing="drop") + + assert np.all(np.isnan(acovf(x, missing="conservative"))) + + +def test_stattools_fixed_arity_result_objects(): + # These functions always return the same number of values, so unlike + # the result_object=True/False/None functions, they unconditionally + # return a result object with no deprecation cycle for *whether* one + # is returned. Indexing/unpacking the result object itself is a + # stable, non-deprecated part of the API. + rs = np.random.RandomState(0) + x = rs.standard_normal(200).cumsum() + + res = block_jackknife(rs.standard_normal(100), np.mean, n_blocks=10) + assert isinstance(res, JackknifeResult) + assert res[0] is res.theta_jack + assert res[1] is res.se + + a = acf(x, nlags=10, fft=False) + res = q_stat(a[1:], nobs=len(x)) + assert isinstance(res, QStatResult) + assert res[0] is res.statistic + assert res[1] is res.pvalue + + res = pacf_burg(x, nlags=5) + assert isinstance(res, PacfBurgResult) + assert res[0] is res.pacf + assert res[1] is res.sigma2 + + res = levinson_durbin(x, nlags=5, isacov=False) + assert isinstance(res, LevinsonDurbinResult) + assert res[0] == res.sigma_v + assert res[1] is res.arcoefs + assert res[2] is res.pacf + assert res[3] is res.sigma + assert res[4] is res.phi + + res2 = levinson_durbin_pacf(res.pacf, nlags=3) + assert isinstance(res2, LevinsonDurbinPacfResult) + assert res2[0] is res2.arcoefs + assert res2[1] is res2.acf + + res = breakvar_heteroskedasticity_test(x) + assert isinstance(res, BreakvarHeteroskedasticityResult) + assert res[0] == res.statistic + assert res[1] == res.pvalue + + y1 = (x + rs.standard_normal(200))[:, None] + res = coint(x, y1, trend="c", maxlag=0, autolag=None) + assert isinstance(res, CointResult) + assert res[0] == res.coint_t + assert res[1] == res.pvalue + assert res[2] is res.critical_values diff --git a/shared/package-files/7b/7b840b66d2b1097b9ca7bc3016e66e011c95e11b10f63101b0b94e789560848d/blob b/shared/package-files/7b/7b840b66d2b1097b9ca7bc3016e66e011c95e11b10f63101b0b94e789560848d/blob new file mode 100644 index 0000000000000000000000000000000000000000..3ed9d34824132093313b1e0bc9371e90c26a9936 Binary files /dev/null and b/shared/package-files/7b/7b840b66d2b1097b9ca7bc3016e66e011c95e11b10f63101b0b94e789560848d/blob differ diff --git a/shared/package-files/7b/7b8567de7134daaf947911f66962ce48cbf440de27374e2278f2acb7937e55ba/blob b/shared/package-files/7b/7b8567de7134daaf947911f66962ce48cbf440de27374e2278f2acb7937e55ba/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d2fa1ad5d21175dcfafe9a57dd8169fc4413360 --- /dev/null +++ b/shared/package-files/7b/7b8567de7134daaf947911f66962ce48cbf440de27374e2278f2acb7937e55ba/blob @@ -0,0 +1,144 @@ +import numpy as np +import pytest + +from pandas import Series +import pandas._testing as tm + + +def no_nans(x): + return x.notna().all().all() + + +def all_na(x): + return x.isnull().all().all() + + +@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum]) +def test_expanding_apply_consistency_sum_nans(request, all_data, min_periods, f): + if f is np.sum: + if not no_nans(all_data) and not ( + all_na(all_data) and not all_data.empty and min_periods > 0 + ): + request.applymarker( + pytest.mark.xfail(reason="np.sum has different behavior with NaNs") + ) + expanding_f_result = all_data.expanding(min_periods=min_periods).sum() + expanding_apply_f_result = all_data.expanding(min_periods=min_periods).apply( + func=f, raw=True + ) + tm.assert_equal(expanding_f_result, expanding_apply_f_result) + + +@pytest.mark.parametrize("ddof", [0, 1]) +def test_moments_consistency_var(all_data, min_periods, ddof): + var_x = all_data.expanding(min_periods=min_periods).var(ddof=ddof) + assert not (var_x < 0).any().any() + + if ddof == 0: + # check that biased var(x) == mean(x^2) - mean(x)^2 + mean_x2 = (all_data * all_data).expanding(min_periods=min_periods).mean() + mean_x = all_data.expanding(min_periods=min_periods).mean() + tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x)) + + +@pytest.mark.parametrize("ddof", [0, 1]) +def test_moments_consistency_var_constant(consistent_data, min_periods, ddof): + count_x = consistent_data.expanding(min_periods=min_periods).count() + var_x = consistent_data.expanding(min_periods=min_periods).var(ddof=ddof) + + # check that variance of constant series is identically 0 + assert not (var_x > 0).any().any() + expected = consistent_data * np.nan + expected[count_x >= max(min_periods, 1)] = 0.0 + if ddof == 1: + expected[count_x < 2] = np.nan + tm.assert_equal(var_x, expected) + + +@pytest.mark.parametrize("ddof", [0, 1]) +def test_expanding_consistency_var_std_cov(all_data, min_periods, ddof): + var_x = all_data.expanding(min_periods=min_periods).var(ddof=ddof) + assert not (var_x < 0).any().any() + + std_x = all_data.expanding(min_periods=min_periods).std(ddof=ddof) + assert not (std_x < 0).any().any() + + # check that var(x) == std(x)^2 + tm.assert_equal(var_x, std_x * std_x) + + cov_x_x = all_data.expanding(min_periods=min_periods).cov(all_data, ddof=ddof) + assert not (cov_x_x < 0).any().any() + + # check that var(x) == cov(x, x) + tm.assert_equal(var_x, cov_x_x) + + +@pytest.mark.parametrize("ddof", [0, 1]) +def test_expanding_consistency_series_cov_corr(series_data, min_periods, ddof): + var_x_plus_y = ( + (series_data + series_data).expanding(min_periods=min_periods).var(ddof=ddof) + ) + var_x = series_data.expanding(min_periods=min_periods).var(ddof=ddof) + var_y = series_data.expanding(min_periods=min_periods).var(ddof=ddof) + cov_x_y = series_data.expanding(min_periods=min_periods).cov(series_data, ddof=ddof) + # check that cov(x, y) == (var(x+y) - var(x) - + # var(y)) / 2 + tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y)) + + # check that corr(x, y) == cov(x, y) / (std(x) * + # std(y)) + corr_x_y = series_data.expanding(min_periods=min_periods).corr(series_data) + std_x = series_data.expanding(min_periods=min_periods).std(ddof=ddof) + std_y = series_data.expanding(min_periods=min_periods).std(ddof=ddof) + tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y)) + + if ddof == 0: + # check that biased cov(x, y) == mean(x*y) - + # mean(x)*mean(y) + mean_x = series_data.expanding(min_periods=min_periods).mean() + mean_y = series_data.expanding(min_periods=min_periods).mean() + mean_x_times_y = ( + (series_data * series_data).expanding(min_periods=min_periods).mean() + ) + tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y)) + + +def test_expanding_consistency_mean(all_data, min_periods): + result = all_data.expanding(min_periods=min_periods).mean() + expected = ( + all_data.expanding(min_periods=min_periods).sum() + / all_data.expanding(min_periods=min_periods).count() + ) + tm.assert_equal(result, expected.astype("float64")) + + +def test_expanding_consistency_constant(consistent_data, min_periods): + count_x = consistent_data.expanding().count() + mean_x = consistent_data.expanding(min_periods=min_periods).mean() + # check that correlation of a series with itself is either 1 or NaN + corr_x_x = consistent_data.expanding(min_periods=min_periods).corr(consistent_data) + + exp = ( + consistent_data.max() + if isinstance(consistent_data, Series) + else consistent_data.max().max() + ) + + # check mean of constant series + expected = consistent_data * np.nan + expected[count_x >= max(min_periods, 1)] = exp + tm.assert_equal(mean_x, expected) + + # check correlation of constant series with itself is NaN + expected[:] = np.nan + tm.assert_equal(corr_x_x, expected) + + +def test_expanding_consistency_var_debiasing_factors(all_data, min_periods): + # check variance debiasing factors + var_unbiased_x = all_data.expanding(min_periods=min_periods).var() + var_biased_x = all_data.expanding(min_periods=min_periods).var(ddof=0) + var_debiasing_factors_x = all_data.expanding().count() / ( + all_data.expanding().count() - 1.0 + ).replace(0.0, np.nan) + tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x) diff --git a/shared/package-files/7b/7b8870d3cf331a8dba5a625a30846f0a788b94b9a83a3aa8946c9f1e3b029024/blob b/shared/package-files/7b/7b8870d3cf331a8dba5a625a30846f0a788b94b9a83a3aa8946c9f1e3b029024/blob new file mode 100644 index 0000000000000000000000000000000000000000..54247a78a654187206cd17a403913c6257ffcc7d --- /dev/null +++ b/shared/package-files/7b/7b8870d3cf331a8dba5a625a30846f0a788b94b9a83a3aa8946c9f1e3b029024/blob @@ -0,0 +1,147 @@ +import logging +import os +from optparse import Values +from typing import List + +from pip._internal.cli import cmdoptions +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.req_command import RequirementCommand, with_cleanup +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.req.req_install import check_legacy_setup_py_options +from pip._internal.utils.misc import ensure_dir, normalize_path, write_output +from pip._internal.utils.temp_dir import TempDirectory + +logger = logging.getLogger(__name__) + + +class DownloadCommand(RequirementCommand): + """ + Download packages from: + + - PyPI (and other indexes) using requirement specifiers. + - VCS project urls. + - Local project directories. + - Local or remote source archives. + + pip also supports downloading from "requirements files", which provide + an easy way to specify a whole environment to be downloaded. + """ + + usage = """ + %prog [options] [package-index-options] ... + %prog [options] -r [package-index-options] ... + %prog [options] ... + %prog [options] ... + %prog [options] ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.global_options()) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.src()) + self.cmd_opts.add_option(cmdoptions.pre()) + self.cmd_opts.add_option(cmdoptions.require_hashes()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + + self.cmd_opts.add_option( + "-d", + "--dest", + "--destination-dir", + "--destination-directory", + dest="download_dir", + metavar="dir", + default=os.curdir, + help="Download packages into .", + ) + + cmdoptions.add_target_python_options(self.cmd_opts) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + options.ignore_installed = True + # editable doesn't really make sense for `pip download`, but the bowels + # of the RequirementSet code require that property. + options.editables = [] + + cmdoptions.check_dist_restriction(options) + + options.download_dir = normalize_path(options.download_dir) + ensure_dir(options.download_dir) + + session = self.get_default_session(options) + + target_python = make_target_python(options) + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="download", + globally_managed=True, + ) + + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options(options, reqs) + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + download_dir=options.download_dir, + use_user_site=False, + verbosity=self.verbosity, + ) + + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + ignore_requires_python=options.ignore_requires_python, + use_pep517=options.use_pep517, + py_version_info=options.python_version, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve(reqs, check_supported_wheels=True) + + downloaded: List[str] = [] + for req in requirement_set.requirements.values(): + if req.satisfied_by is None: + assert req.name is not None + preparer.save_linked_requirement(req) + downloaded.append(req.name) + + preparer.prepare_linked_requirements_more(requirement_set.requirements.values()) + requirement_set.warn_legacy_versions_and_specifiers() + + if downloaded: + write_output("Successfully downloaded %s", " ".join(downloaded)) + + return SUCCESS diff --git a/shared/package-files/7b/7b8cc50cbc204745d38fa3d57b3bd6bb4c3f6ea0d346bef61b3cc423eb15b9d1/blob b/shared/package-files/7b/7b8cc50cbc204745d38fa3d57b3bd6bb4c3f6ea0d346bef61b3cc423eb15b9d1/blob new file mode 100644 index 0000000000000000000000000000000000000000..f036ef37a5aba76d4daac08c849932154fe5d976 --- /dev/null +++ b/shared/package-files/7b/7b8cc50cbc204745d38fa3d57b3bd6bb4c3f6ea0d346bef61b3cc423eb15b9d1/blob @@ -0,0 +1,6 @@ +/* + CSS file for pydoc. + + Contents of this file are subject to change without notice. + +*/ diff --git a/shared/package-files/7b/7b8da55f3cc71bd9388ab3b39ee75f15bdb455b2db715409e485715474b47a60/blob b/shared/package-files/7b/7b8da55f3cc71bd9388ab3b39ee75f15bdb455b2db715409e485715474b47a60/blob new file mode 100644 index 0000000000000000000000000000000000000000..6a776696d66ed604dfd8e95de878aef1bf19e8f7 --- /dev/null +++ b/shared/package-files/7b/7b8da55f3cc71bd9388ab3b39ee75f15bdb455b2db715409e485715474b47a60/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor ger(const at::Tensor & self, const at::Tensor & vec2); +TORCH_API at::Tensor & ger_out(const at::Tensor & self, const at::Tensor & vec2, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/7b/7b91fa6afde2a0e9fc8e48f20c1ad3dcd1260a4c876cde991073a5c81f4e60b9/blob b/shared/package-files/7b/7b91fa6afde2a0e9fc8e48f20c1ad3dcd1260a4c876cde991073a5c81f4e60b9/blob new file mode 100644 index 0000000000000000000000000000000000000000..b4444716a76a52e3638dd7a36238a9f459179083 --- /dev/null +++ b/shared/package-files/7b/7b91fa6afde2a0e9fc8e48f20c1ad3dcd1260a4c876cde991073a5c81f4e60b9/blob @@ -0,0 +1,150 @@ +from sympy.core.mod import Mod +from sympy.core.numbers import I +from sympy.core.symbol import symbols +from sympy.functions.elementary.integers import floor +from sympy.matrices.dense import (Matrix, eye) +from sympy.matrices import MatrixSymbol, Identity +from sympy.matrices.expressions import det, trace + +from sympy.matrices.expressions.kronecker import (KroneckerProduct, + kronecker_product, + combine_kronecker) + + +mat1 = Matrix([[1, 2 * I], [1 + I, 3]]) +mat2 = Matrix([[2 * I, 3], [4 * I, 2]]) + +i, j, k, n, m, o, p, x = symbols('i,j,k,n,m,o,p,x') +Z = MatrixSymbol('Z', n, n) +W = MatrixSymbol('W', m, m) +A = MatrixSymbol('A', n, m) +B = MatrixSymbol('B', n, m) +C = MatrixSymbol('C', m, k) + + +def test_KroneckerProduct(): + assert isinstance(KroneckerProduct(A, B), KroneckerProduct) + assert KroneckerProduct(A, B).subs(A, C) == KroneckerProduct(C, B) + assert KroneckerProduct(A, C).shape == (n*m, m*k) + assert (KroneckerProduct(A, C) + KroneckerProduct(-A, C)).is_ZeroMatrix + assert (KroneckerProduct(W, Z) * KroneckerProduct(W.I, Z.I)).is_Identity + + +def test_KroneckerProduct_identity(): + assert KroneckerProduct(Identity(m), Identity(n)) == Identity(m*n) + assert KroneckerProduct(eye(2), eye(3)) == eye(6) + + +def test_KroneckerProduct_explicit(): + X = MatrixSymbol('X', 2, 2) + Y = MatrixSymbol('Y', 2, 2) + kp = KroneckerProduct(X, Y) + assert kp.shape == (4, 4) + assert kp.as_explicit() == Matrix( + [ + [X[0, 0]*Y[0, 0], X[0, 0]*Y[0, 1], X[0, 1]*Y[0, 0], X[0, 1]*Y[0, 1]], + [X[0, 0]*Y[1, 0], X[0, 0]*Y[1, 1], X[0, 1]*Y[1, 0], X[0, 1]*Y[1, 1]], + [X[1, 0]*Y[0, 0], X[1, 0]*Y[0, 1], X[1, 1]*Y[0, 0], X[1, 1]*Y[0, 1]], + [X[1, 0]*Y[1, 0], X[1, 0]*Y[1, 1], X[1, 1]*Y[1, 0], X[1, 1]*Y[1, 1]] + ] + ) + + +def test_tensor_product_adjoint(): + assert KroneckerProduct(I*A, B).adjoint() == \ + -I*KroneckerProduct(A.adjoint(), B.adjoint()) + assert KroneckerProduct(mat1, mat2).adjoint() == \ + kronecker_product(mat1.adjoint(), mat2.adjoint()) + + +def test_tensor_product_conjugate(): + assert KroneckerProduct(I*A, B).conjugate() == \ + -I*KroneckerProduct(A.conjugate(), B.conjugate()) + assert KroneckerProduct(mat1, mat2).conjugate() == \ + kronecker_product(mat1.conjugate(), mat2.conjugate()) + + +def test_tensor_product_transpose(): + assert KroneckerProduct(I*A, B).transpose() == \ + I*KroneckerProduct(A.transpose(), B.transpose()) + assert KroneckerProduct(mat1, mat2).transpose() == \ + kronecker_product(mat1.transpose(), mat2.transpose()) + + +def test_KroneckerProduct_is_associative(): + assert kronecker_product(A, kronecker_product( + B, C)) == kronecker_product(kronecker_product(A, B), C) + assert kronecker_product(A, kronecker_product( + B, C)) == KroneckerProduct(A, B, C) + + +def test_KroneckerProduct_is_bilinear(): + assert kronecker_product(x*A, B) == x*kronecker_product(A, B) + assert kronecker_product(A, x*B) == x*kronecker_product(A, B) + + +def test_KroneckerProduct_determinant(): + kp = kronecker_product(W, Z) + assert det(kp) == det(W)**n * det(Z)**m + + +def test_KroneckerProduct_trace(): + kp = kronecker_product(W, Z) + assert trace(kp) == trace(W)*trace(Z) + + +def test_KroneckerProduct_isnt_commutative(): + assert KroneckerProduct(A, B) != KroneckerProduct(B, A) + assert KroneckerProduct(A, B).is_commutative is False + + +def test_KroneckerProduct_extracts_commutative_part(): + assert kronecker_product(x * A, 2 * B) == x * \ + 2 * KroneckerProduct(A, B) + + +def test_KroneckerProduct_inverse(): + kp = kronecker_product(W, Z) + assert kp.inverse() == kronecker_product(W.inverse(), Z.inverse()) + + +def test_KroneckerProduct_combine_add(): + kp1 = kronecker_product(A, B) + kp2 = kronecker_product(C, W) + assert combine_kronecker(kp1*kp2) == kronecker_product(A*C, B*W) + + +def test_KroneckerProduct_combine_mul(): + X = MatrixSymbol('X', m, n) + Y = MatrixSymbol('Y', m, n) + kp1 = kronecker_product(A, X) + kp2 = kronecker_product(B, Y) + assert combine_kronecker(kp1+kp2) == kronecker_product(A+B, X+Y) + + +def test_KroneckerProduct_combine_pow(): + X = MatrixSymbol('X', n, n) + Y = MatrixSymbol('Y', n, n) + assert combine_kronecker(KroneckerProduct( + X, Y)**x) == KroneckerProduct(X**x, Y**x) + assert combine_kronecker(x * KroneckerProduct(X, Y) + ** 2) == x * KroneckerProduct(X**2, Y**2) + assert combine_kronecker( + x * (KroneckerProduct(X, Y)**2) * KroneckerProduct(A, B)) == x * KroneckerProduct(X**2 * A, Y**2 * B) + # cannot simplify because of non-square arguments to kronecker product: + assert combine_kronecker(KroneckerProduct(A, B.T) ** m) == KroneckerProduct(A, B.T) ** m + + +def test_KroneckerProduct_expand(): + X = MatrixSymbol('X', n, n) + Y = MatrixSymbol('Y', n, n) + + assert KroneckerProduct(X + Y, Y + Z).expand(kroneckerproduct=True) == \ + KroneckerProduct(X, Y) + KroneckerProduct(X, Z) + \ + KroneckerProduct(Y, Y) + KroneckerProduct(Y, Z) + +def test_KroneckerProduct_entry(): + A = MatrixSymbol('A', n, m) + B = MatrixSymbol('B', o, p) + + assert KroneckerProduct(A, B)._entry(i, j) == A[Mod(floor(i/o), n), Mod(floor(j/p), m)]*B[Mod(i, o), Mod(j, p)] diff --git a/shared/package-files/7b/7b9346d03d8f354fd0be30714b422e3da317d535dc8c0ca9784265d8563880b0/blob b/shared/package-files/7b/7b9346d03d8f354fd0be30714b422e3da317d535dc8c0ca9784265d8563880b0/blob new file mode 100644 index 0000000000000000000000000000000000000000..70b07894ad414113214c6ddca7358c0d69064c69 --- /dev/null +++ b/shared/package-files/7b/7b9346d03d8f354fd0be30714b422e3da317d535dc8c0ca9784265d8563880b0/blob @@ -0,0 +1,1360 @@ +error(0.005431634047440528357) D0 +error(0.005964954222803964257) D0 D1 +error(0.02487512677384539489) D0 D4 +error(0.0003639179218844885663) D0 D4 ^ D5 +error(0.004143029050632550565) D0 D7 +error(0.001385125853343636493) D0 D7 ^ D5 +error(0.004296856531535620145) D0 D8 +error(0.004303676515646938545) D0 D8 ^ D5 +error(0.005780359428960434552) D1 D2 +error(0.003690478996958558317) D1 D2 ^ D10 +error(0.0159193185030979123) D1 D7 +error(0.004055362519912400314) D1 D7 ^ D9 +error(0.002348248941733193425) D1 D7 ^ D9 D10 +error(0.0008273390697088928072) D1 D7 ^ D10 +error(0.001238312409605233939) D1 D8 +error(0.00117488591196874821) D1 D8 ^ D9 +error(0.001014379236049836944) D1 D8 ^ D10 +error(0.0002469269986714141339) D1 D8 ^ D10 ^ D9 +error(0.002271926213893261243) D1 D11 +error(0.001144173147062035791) D1 D11 ^ D10 +error(0.014656794067464873) D1 L0 +error(0.006118185918356833231) D1 L0 ^ D9 +error(0.0123030037363634475) D2 +error(0.008546297200226815605) D2 D3 +error(0.02867764933504240998) D2 D8 +error(0.002788959084610136314) D2 D8 ^ D10 +error(0.006004144602894966043) D2 D11 +error(0.006040896792809387177) D2 D11 ^ D10 +error(0.0221684266234157823) D3 D11 +error(0.01224725271226403955) D3 L0 +error(0.005000000000000000104) D4 +error(0.01230128208703430703) D4 D7 +error(0.01392426562420221933) D4 D7 ^ D5 +error(0.02563183000941281556) D4 D12 +error(0.007311517658274590235) D4 D12 ^ D13 +error(0.005648422745192678562) D4 D15 +error(0.004936162390005865291) D4 D15 ^ D5 +error(0.004470595127259575224) D4 D15 ^ D13 +error(0.003376400387429945651) D4 D15 ^ D13 ^ D5 +error(0.002859464556123720354) D4 D16 +error(0.0006704424957878181782) D4 D16 ^ D5 +error(0.003338387470335747731) D4 D16 ^ D5 D13 +error(0.0007316530848325324609) D4 D16 ^ D13 +error(0.006057403044567649317) D4 ^ D5 +error(0.005574457326479488953) D5 D13 ^ D4 +error(0.03950481225222186171) D5 +error(0.005000000000000000104) D5 D6 +error(0.0009266697049759946552) D5 D6 ^ D7 D8 +error(0.0008582430700132457051) D5 D6 ^ D7 D16 +error(0.009561058208314966722) D5 D6 ^ D8 +error(0.003725859569174878438) D5 D6 ^ D8 D16 +error(0.002066805836596927268) D5 D6 ^ D16 +error(0.0006904309616043598479) D5 D6 ^ D16 ^ D4 +error(0.0214876350460488745) D5 D10 +error(0.01170171200672361425) D5 D10 ^ D7 D8 +error(0.04640023301592229726) D5 D13 +error(0.002674301988377119754) D5 D13 ^ D15 D16 +error(0.003646625935930334229) D5 D13 ^ D16 +error(0.002530344283181031918) D5 D17 +error(0.002584336660252296424) D5 D17 ^ D7 D15 +error(0.0002635990637095448502) D5 D17 ^ D7 D16 +error(0.0006575318638258634231) D5 D17 ^ D15 D16 +error(0.004899237620589364482) D5 D18 +error(0.001632140203929661375) D5 D18 ^ D7 D8 +error(0.0007633653605808868791) D5 D18 ^ D7 D15 +error(0.001551636612335751666) D5 D18 ^ D7 D16 +error(0.0002089500978056947329) D5 D18 ^ D8 D16 +error(0.001540326152393501529) D5 D18 ^ D15 D16 +error(0.006074380365619835506) D5 ^ D0 +error(0.004895794405914832316) D5 ^ D8 +error(0.007004877619730071579) D7 D15 ^ D5 +error(0.02117481473955185392) D6 +error(0.00609080404863404385) D6 D13 +error(0.0006412086781627615063) D6 D13 ^ D4 +error(0.005316099403978277391) D6 D13 ^ D16 +error(0.0007231499252243798288) D6 D13 ^ D16 ^ D4 +error(0.02533370078930012592) D6 D14 +error(0.009581264674680716603) D6 D14 ^ D16 +error(0.001717039387100297628) D6 D18 +error(3.550316796919824485e-05) D6 D18 ^ D7 D8 +error(9.818036825801125544e-05) D6 D18 ^ D7 D16 +error(0.001668407009476837073) D6 D18 ^ D8 D16 +error(0.02286884440169168961) D6 ^ D8 +error(0.002565883255846221084) D6 ^ D16 ^ D8 +error(0.006179145807535635186) D7 D8 +error(0.005095611251686533484) D7 D8 ^ D5 +error(0.0001147710304432338199) D7 D8 ^ D9 +error(0.001068053872257022918) D7 D8 ^ D10 +error(0.001506582328336537879) D7 D8 ^ D10 D18 +error(0.000130588664525313849) D7 D8 ^ D10 ^ D9 +error(0.0003262905498523500881) D7 D8 ^ D18 +error(0.02436416753328735779) D7 D15 +error(0.003343901663810583142) D7 D15 ^ D17 D18 +error(0.002338381856532108314) D7 D16 +error(0.0003284014923968432719) D7 D16 ^ D17 D18 +error(0.001971685112299993888) D7 D19 +error(0.0002356806454351069381) D7 D19 ^ D10 +error(0.00140513153775703812) D7 D19 ^ D10 D18 +error(0.01000000000000000021) D7 L0 +error(0.008040850332653616886) D7 L0 ^ D9 +error(0.003754870086818663799) D9 D17 ^ D7 L0 +error(0.01519707141935213411) D8 +error(0.02198010663815965632) D8 D11 +error(0.01827053271703663051) D8 D11 ^ D10 +error(0.0330796271598641986) D8 D16 +error(0.002060971124883901814) D8 D16 ^ D18 +error(0.01030641088581470306) D8 D19 +error(0.002027746224853679054) D8 D19 ^ D10 +error(0.004327870205481603241) D8 D19 ^ D18 +error(0.0007044985519714150974) D8 D19 ^ D18 ^ D10 +error(0.03478538838649904152) D9 +error(0.0109155725276884781) D9 D10 +error(0.001973534187711347213) D9 D10 ^ D1 L0 +error(0.01382896806184134506) D9 D10 ^ D7 L0 +error(0.0259144440966448085) D9 D17 +error(0.0402041702114115454) D10 +error(0.002522540241894852004) D10 D17 +error(0.002185884653266327669) D10 D17 ^ D7 L0 +error(0.0001203041160746442053) D10 D17 ^ D19 L0 +error(1.442812011990793695e-05) D10 D17 ^ D19 L0 ^ D7 L0 +error(0.03317048719226503573) D10 D18 +error(0.00136191988277857925) D10 D18 ^ D7 L0 +error(0.00221531971963198019) D10 D18 ^ D19 L0 +error(0.0003681756804402285671) D10 ^ D2 +error(0.003563315838144102791) D10 ^ D8 +error(0.01608478224154660449) D10 ^ D11 L0 +error(0.000195462401747826392) D10 ^ D11 L0 ^ D1 L0 ^ D9 +error(0.002590779815204308223) D10 ^ D19 L0 +error(0.002555392989364372192) D11 D19 ^ D10 +error(0.02371428898985290801) D11 D19 +error(0.006797745799825858325) D11 L0 +error(0.0005088086653185742384) D11 L0 ^ D1 L0 ^ D9 +error(0.005000000000000000104) D12 +error(0.01599867247798393219) D12 D15 +error(0.01738551052587990892) D12 D15 ^ D13 +error(0.02563183000941281556) D12 D20 +error(0.007311517658274590235) D12 D20 ^ D21 +error(0.005648422745192678562) D12 D23 +error(0.004936162390005865291) D12 D23 ^ D13 +error(0.004470595127259575224) D12 D23 ^ D21 +error(0.003376400387429945651) D12 D23 ^ D21 ^ D13 +error(0.002859464556123720354) D12 D24 +error(0.0006704424957878181782) D12 D24 ^ D13 +error(0.003338387470335747731) D12 D24 ^ D13 D21 +error(0.0007316530848325324609) D12 D24 ^ D21 +error(0.005000000000000000104) D12 ^ D13 +error(0.005574457326479488953) D13 D21 ^ D12 +error(0.01000000000000000021) D13 +error(0.006223930169853710004) D13 D14 +error(0.000514866994970966294) D13 D14 ^ D12 +error(0.0005827841883569776209) D13 D14 ^ D15 D16 +error(0.0008582430700132457051) D13 D14 ^ D15 D24 +error(0.01465800186464856318) D13 D14 ^ D16 +error(0.003725859569174878438) D13 D14 ^ D16 D24 +error(0.002066805836596927268) D13 D14 ^ D24 +error(0.0006904309616043598479) D13 D14 ^ D24 ^ D12 +error(0.01953042700852838931) D13 D18 +error(0.01191093091747521225) D13 D18 ^ D15 D16 +error(0.04640023301592229726) D13 D21 +error(0.002674301988377119754) D13 D21 ^ D23 D24 +error(0.003646625935930334229) D13 D21 ^ D24 +error(0.002530344283181031918) D13 D25 +error(0.002584336660252296424) D13 D25 ^ D15 D23 +error(0.0002635990637095448502) D13 D25 ^ D15 D24 +error(0.0006575318638258634231) D13 D25 ^ D23 D24 +error(0.004899237620589364482) D13 D26 +error(0.001632140203929661375) D13 D26 ^ D15 D16 +error(0.0007633653605808868791) D13 D26 ^ D15 D23 +error(0.001551636612335751666) D13 D26 ^ D15 D24 +error(0.0002089500978056947329) D13 D26 ^ D16 D24 +error(0.001540326152393501529) D13 D26 ^ D23 D24 +error(0.007004877619730071579) D15 D23 ^ D13 +error(0.005000000000000000104) D14 +error(0.00609080404863404385) D14 D21 +error(0.0006412086781627615063) D14 D21 ^ D12 +error(0.005316099403978277391) D14 D21 ^ D24 +error(0.0007231499252243798288) D14 D21 ^ D24 ^ D12 +error(0.02533370078930012592) D14 D22 +error(0.009581264674680716603) D14 D22 ^ D24 +error(0.001717039387100297628) D14 D26 +error(3.550316796919824485e-05) D14 D26 ^ D15 D16 +error(9.818036825801125544e-05) D14 D26 ^ D15 D24 +error(0.001668407009476837073) D14 D26 ^ D16 D24 +error(0.011427700059054028) D14 ^ D16 +error(0.002565883255846221084) D14 ^ D24 ^ D16 +error(0.008257398629531276929) D15 D16 +error(0.001068074573925781269) D15 D16 ^ D5 +error(0.0004160547161542342337) D15 D16 ^ D13 +error(0.0001809928460819403126) D15 D16 ^ D17 D18 +error(0.0007976095382669129343) D15 D16 ^ D18 +error(0.001506582328336537879) D15 D16 ^ D18 D26 +error(0.0003262905498523500881) D15 D16 ^ D26 +error(0.02436416753328735779) D15 D23 +error(0.003343901663810583142) D15 D23 ^ D25 D26 +error(0.002338381856532108314) D15 D24 +error(0.0003284014923968432719) D15 D24 ^ D25 D26 +error(0.001971685112299993888) D15 D27 +error(0.0002356806454351069381) D15 D27 ^ D18 +error(0.00140513153775703812) D15 D27 ^ D18 D26 +error(0.01000000000000000021) D15 L0 +error(0.008025747665072297324) D15 L0 ^ D17 +error(0.003754870086818663799) D17 D25 ^ D15 L0 +error(0.01000000000000000021) D16 +error(0.02111566487520867563) D16 D19 +error(0.020531600646543368) D16 D19 ^ D18 +error(0.0330796271598641986) D16 D24 +error(0.002060971124883901814) D16 D24 ^ D26 +error(0.01030641088581470306) D16 D27 +error(0.002027746224853679054) D16 D27 ^ D18 +error(0.004327870205481603241) D16 D27 ^ D26 +error(0.0007044985519714150974) D16 D27 ^ D26 ^ D18 +error(0.005000000000000000104) D17 +error(0.008135044191840199237) D17 D18 +error(0.003334200928408607208) D17 D18 ^ D7 L0 +error(0.01256896312079426245) D17 D18 ^ D15 L0 +error(3.523362331973171245e-05) D17 D18 ^ D19 L0 +error(0.0259144440966448085) D17 D25 +error(2.319766608052355999e-05) D17 ^ D5 ^ D7 L0 +error(0.0003729435504305767522) D17 ^ D5 ^ D15 L0 +error(0.0009907078669806480397) D17 ^ D15 L0 ^ D7 L0 +error(0.01000000000000000021) D18 +error(0.002522540241894852004) D18 D25 +error(0.002185884653266327669) D18 D25 ^ D15 L0 +error(0.0001203041160746442053) D18 D25 ^ D27 L0 +error(1.442812011990793695e-05) D18 D25 ^ D27 L0 ^ D15 L0 +error(0.03317048719226503573) D18 D26 +error(0.00136191988277857925) D18 D26 ^ D15 L0 +error(0.00221531971963198019) D18 D26 ^ D27 L0 +error(0.0006239191787623928152) D18 ^ D6 ^ D8 +error(0.001328042672585219922) D18 ^ D6 ^ D16 +error(0.001476553639008023819) D18 ^ D8 +error(0.001260766357202842145) D18 ^ D16 +error(0.01450099492487482572) D18 ^ D19 L0 +error(0.002590779815204308223) D18 ^ D27 L0 +error(0.002555392989364372192) D19 D27 ^ D18 +error(0.02371428898985290801) D19 D27 +error(0.005560840932060947574) D19 L0 +error(0.005000000000000000104) D20 +error(0.01599867247798393219) D20 D23 +error(0.01738551052587990892) D20 D23 ^ D21 +error(0.02563183000941281556) D20 D28 +error(0.007311517658274590235) D20 D28 ^ D29 +error(0.005648422745192678562) D20 D31 +error(0.004936162390005865291) D20 D31 ^ D21 +error(0.004470595127259575224) D20 D31 ^ D29 +error(0.003376400387429945651) D20 D31 ^ D29 ^ D21 +error(0.002859464556123720354) D20 D32 +error(0.0006704424957878181782) D20 D32 ^ D21 +error(0.003338387470335747731) D20 D32 ^ D21 D29 +error(0.0007316530848325324609) D20 D32 ^ D29 +error(0.005000000000000000104) D20 ^ D21 +error(0.005574457326479488953) D21 D29 ^ D20 +error(0.01000000000000000021) D21 +error(0.006223930169853710004) D21 D22 +error(0.000514866994970966294) D21 D22 ^ D20 +error(0.0005827841883569776209) D21 D22 ^ D23 D24 +error(0.0008582430700132457051) D21 D22 ^ D23 D32 +error(0.01465800186464856318) D21 D22 ^ D24 +error(0.003725859569174878438) D21 D22 ^ D24 D32 +error(0.002066805836596927268) D21 D22 ^ D32 +error(0.0006904309616043598479) D21 D22 ^ D32 ^ D20 +error(0.01953042700852838931) D21 D26 +error(0.01191093091747521225) D21 D26 ^ D23 D24 +error(0.04640023301592229726) D21 D29 +error(0.002674301988377119754) D21 D29 ^ D31 D32 +error(0.003646625935930334229) D21 D29 ^ D32 +error(0.002530344283181031918) D21 D33 +error(0.002584336660252296424) D21 D33 ^ D23 D31 +error(0.0002635990637095448502) D21 D33 ^ D23 D32 +error(0.0006575318638258634231) D21 D33 ^ D31 D32 +error(0.004899237620589364482) D21 D34 +error(0.001632140203929661375) D21 D34 ^ D23 D24 +error(0.0007633653605808868791) D21 D34 ^ D23 D31 +error(0.001551636612335751666) D21 D34 ^ D23 D32 +error(0.0002089500978056947329) D21 D34 ^ D24 D32 +error(0.001540326152393501529) D21 D34 ^ D31 D32 +error(0.007004877619730071579) D23 D31 ^ D21 +error(0.005000000000000000104) D22 +error(0.00609080404863404385) D22 D29 +error(0.0006412086781627615063) D22 D29 ^ D20 +error(0.005316099403978277391) D22 D29 ^ D32 +error(0.0007231499252243798288) D22 D29 ^ D32 ^ D20 +error(0.02533370078930012592) D22 D30 +error(0.009581264674680716603) D22 D30 ^ D32 +error(0.001717039387100297628) D22 D34 +error(3.550316796919824485e-05) D22 D34 ^ D23 D24 +error(9.818036825801125544e-05) D22 D34 ^ D23 D32 +error(0.001668407009476837073) D22 D34 ^ D24 D32 +error(0.011427700059054028) D22 ^ D24 +error(0.002565883255846221084) D22 ^ D32 ^ D24 +error(0.008257398629531276929) D23 D24 +error(0.001068074573925781269) D23 D24 ^ D13 +error(0.0004160547161542342337) D23 D24 ^ D21 +error(0.0001809928460819403126) D23 D24 ^ D25 D26 +error(0.0007976095382669129343) D23 D24 ^ D26 +error(0.001506582328336537879) D23 D24 ^ D26 D34 +error(0.0003262905498523500881) D23 D24 ^ D34 +error(0.02436416753328735779) D23 D31 +error(0.003343901663810583142) D23 D31 ^ D33 D34 +error(0.002338381856532108314) D23 D32 +error(0.0003284014923968432719) D23 D32 ^ D33 D34 +error(0.001971685112299993888) D23 D35 +error(0.0002356806454351069381) D23 D35 ^ D26 +error(0.00140513153775703812) D23 D35 ^ D26 D34 +error(0.01000000000000000021) D23 L0 +error(0.008025747665072297324) D23 L0 ^ D25 +error(0.003754870086818663799) D25 D33 ^ D23 L0 +error(0.01000000000000000021) D24 +error(0.02111566487520867563) D24 D27 +error(0.020531600646543368) D24 D27 ^ D26 +error(0.0330796271598641986) D24 D32 +error(0.002060971124883901814) D24 D32 ^ D34 +error(0.01030641088581470306) D24 D35 +error(0.002027746224853679054) D24 D35 ^ D26 +error(0.004327870205481603241) D24 D35 ^ D34 +error(0.0007044985519714150974) D24 D35 ^ D34 ^ D26 +error(0.005000000000000000104) D25 +error(0.008135044191840199237) D25 D26 +error(0.003334200928408607208) D25 D26 ^ D15 L0 +error(0.01256896312079426245) D25 D26 ^ D23 L0 +error(3.523362331973171245e-05) D25 D26 ^ D27 L0 +error(0.0259144440966448085) D25 D33 +error(2.319766608052355999e-05) D25 ^ D13 ^ D15 L0 +error(0.0003729435504305767522) D25 ^ D13 ^ D23 L0 +error(0.0009907078669806480397) D25 ^ D23 L0 ^ D15 L0 +error(0.01000000000000000021) D26 +error(0.002522540241894852004) D26 D33 +error(0.002185884653266327669) D26 D33 ^ D23 L0 +error(0.0001203041160746442053) D26 D33 ^ D35 L0 +error(1.442812011990793695e-05) D26 D33 ^ D35 L0 ^ D23 L0 +error(0.03317048719226503573) D26 D34 +error(0.00136191988277857925) D26 D34 ^ D23 L0 +error(0.00221531971963198019) D26 D34 ^ D35 L0 +error(0.0006239191787623928152) D26 ^ D14 ^ D16 +error(0.001328042672585219922) D26 ^ D14 ^ D24 +error(0.001476553639008023819) D26 ^ D16 +error(0.001260766357202842145) D26 ^ D24 +error(0.01450099492487482572) D26 ^ D27 L0 +error(0.002590779815204308223) D26 ^ D35 L0 +error(0.002555392989364372192) D27 D35 ^ D26 +error(0.02371428898985290801) D27 D35 +error(0.005560840932060947574) D27 L0 +error(0.005000000000000000104) D28 +error(0.01599867247798393219) D28 D31 +error(0.01738551052587990892) D28 D31 ^ D29 +error(0.02563183000941281556) D28 D36 +error(0.007311517658274590235) D28 D36 ^ D37 +error(0.005648422745192678562) D28 D39 +error(0.004936162390005865291) D28 D39 ^ D29 +error(0.004470595127259575224) D28 D39 ^ D37 +error(0.003376400387429945651) D28 D39 ^ D37 ^ D29 +error(0.002859464556123720354) D28 D40 +error(0.0006704424957878181782) D28 D40 ^ D29 +error(0.003338387470335747731) D28 D40 ^ D29 D37 +error(0.0007316530848325324609) D28 D40 ^ D37 +error(0.005000000000000000104) D28 ^ D29 +error(0.005574457326479488953) D29 D37 ^ D28 +error(0.01000000000000000021) D29 +error(0.006223930169853710004) D29 D30 +error(0.000514866994970966294) D29 D30 ^ D28 +error(0.0005827841883569776209) D29 D30 ^ D31 D32 +error(0.0008582430700132457051) D29 D30 ^ D31 D40 +error(0.01465800186464856318) D29 D30 ^ D32 +error(0.003725859569174878438) D29 D30 ^ D32 D40 +error(0.002066805836596927268) D29 D30 ^ D40 +error(0.0006904309616043598479) D29 D30 ^ D40 ^ D28 +error(0.01953042700852838931) D29 D34 +error(0.01191093091747521225) D29 D34 ^ D31 D32 +error(0.04640023301592229726) D29 D37 +error(0.002674301988377119754) D29 D37 ^ D39 D40 +error(0.003646625935930334229) D29 D37 ^ D40 +error(0.002530344283181031918) D29 D41 +error(0.002584336660252296424) D29 D41 ^ D31 D39 +error(0.0002635990637095448502) D29 D41 ^ D31 D40 +error(0.0006575318638258634231) D29 D41 ^ D39 D40 +error(0.004899237620589364482) D29 D42 +error(0.001632140203929661375) D29 D42 ^ D31 D32 +error(0.0007633653605808868791) D29 D42 ^ D31 D39 +error(0.001551636612335751666) D29 D42 ^ D31 D40 +error(0.0002089500978056947329) D29 D42 ^ D32 D40 +error(0.001540326152393501529) D29 D42 ^ D39 D40 +error(0.007004877619730071579) D31 D39 ^ D29 +error(0.005000000000000000104) D30 +error(0.00609080404863404385) D30 D37 +error(0.0006412086781627615063) D30 D37 ^ D28 +error(0.005316099403978277391) D30 D37 ^ D40 +error(0.0007231499252243798288) D30 D37 ^ D40 ^ D28 +error(0.02533370078930012592) D30 D38 +error(0.009581264674680716603) D30 D38 ^ D40 +error(0.001717039387100297628) D30 D42 +error(3.550316796919824485e-05) D30 D42 ^ D31 D32 +error(9.818036825801125544e-05) D30 D42 ^ D31 D40 +error(0.001668407009476837073) D30 D42 ^ D32 D40 +error(0.011427700059054028) D30 ^ D32 +error(0.002565883255846221084) D30 ^ D40 ^ D32 +error(0.008257398629531276929) D31 D32 +error(0.001068074573925781269) D31 D32 ^ D21 +error(0.0004160547161542342337) D31 D32 ^ D29 +error(0.0001809928460819403126) D31 D32 ^ D33 D34 +error(0.0007976095382669129343) D31 D32 ^ D34 +error(0.001506582328336537879) D31 D32 ^ D34 D42 +error(0.0003262905498523500881) D31 D32 ^ D42 +error(0.02436416753328735779) D31 D39 +error(0.003343901663810583142) D31 D39 ^ D41 D42 +error(0.002338381856532108314) D31 D40 +error(0.0003284014923968432719) D31 D40 ^ D41 D42 +error(0.001971685112299993888) D31 D43 +error(0.0002356806454351069381) D31 D43 ^ D34 +error(0.00140513153775703812) D31 D43 ^ D34 D42 +error(0.01000000000000000021) D31 L0 +error(0.008025747665072297324) D31 L0 ^ D33 +error(0.003754870086818663799) D33 D41 ^ D31 L0 +error(0.01000000000000000021) D32 +error(0.02111566487520867563) D32 D35 +error(0.020531600646543368) D32 D35 ^ D34 +error(0.0330796271598641986) D32 D40 +error(0.002060971124883901814) D32 D40 ^ D42 +error(0.01030641088581470306) D32 D43 +error(0.002027746224853679054) D32 D43 ^ D34 +error(0.004327870205481603241) D32 D43 ^ D42 +error(0.0007044985519714150974) D32 D43 ^ D42 ^ D34 +error(0.005000000000000000104) D33 +error(0.008135044191840199237) D33 D34 +error(0.003334200928408607208) D33 D34 ^ D23 L0 +error(0.01256896312079426245) D33 D34 ^ D31 L0 +error(3.523362331973171245e-05) D33 D34 ^ D35 L0 +error(0.0259144440966448085) D33 D41 +error(2.319766608052355999e-05) D33 ^ D21 ^ D23 L0 +error(0.0003729435504305767522) D33 ^ D21 ^ D31 L0 +error(0.0009907078669806480397) D33 ^ D31 L0 ^ D23 L0 +error(0.01000000000000000021) D34 +error(0.002522540241894852004) D34 D41 +error(0.002185884653266327669) D34 D41 ^ D31 L0 +error(0.0001203041160746442053) D34 D41 ^ D43 L0 +error(1.442812011990793695e-05) D34 D41 ^ D43 L0 ^ D31 L0 +error(0.03317048719226503573) D34 D42 +error(0.00136191988277857925) D34 D42 ^ D31 L0 +error(0.00221531971963198019) D34 D42 ^ D43 L0 +error(0.0006239191787623928152) D34 ^ D22 ^ D24 +error(0.001328042672585219922) D34 ^ D22 ^ D32 +error(0.001476553639008023819) D34 ^ D24 +error(0.001260766357202842145) D34 ^ D32 +error(0.01450099492487482572) D34 ^ D35 L0 +error(0.002590779815204308223) D34 ^ D43 L0 +error(0.002555392989364372192) D35 D43 ^ D34 +error(0.02371428898985290801) D35 D43 +error(0.005560840932060947574) D35 L0 +error(0.005000000000000000104) D36 +error(0.01599867247798393219) D36 D39 +error(0.01738551052587990892) D36 D39 ^ D37 +error(0.02563183000941281556) D36 D44 +error(0.007311517658274590235) D36 D44 ^ D45 +error(0.005648422745192678562) D36 D47 +error(0.004936162390005865291) D36 D47 ^ D37 +error(0.004470595127259575224) D36 D47 ^ D45 +error(0.003376400387429945651) D36 D47 ^ D45 ^ D37 +error(0.002859464556123720354) D36 D48 +error(0.0006704424957878181782) D36 D48 ^ D37 +error(0.003338387470335747731) D36 D48 ^ D37 D45 +error(0.0007316530848325324609) D36 D48 ^ D45 +error(0.005000000000000000104) D36 ^ D37 +error(0.005574457326479488953) D37 D45 ^ D36 +error(0.01000000000000000021) D37 +error(0.006223930169853710004) D37 D38 +error(0.000514866994970966294) D37 D38 ^ D36 +error(0.0005827841883569776209) D37 D38 ^ D39 D40 +error(0.0008582430700132457051) D37 D38 ^ D39 D48 +error(0.01465800186464856318) D37 D38 ^ D40 +error(0.003725859569174878438) D37 D38 ^ D40 D48 +error(0.002066805836596927268) D37 D38 ^ D48 +error(0.0006904309616043598479) D37 D38 ^ D48 ^ D36 +error(0.01953042700852838931) D37 D42 +error(0.01191093091747521225) D37 D42 ^ D39 D40 +error(0.04640023301592229726) D37 D45 +error(0.002674301988377119754) D37 D45 ^ D47 D48 +error(0.003646625935930334229) D37 D45 ^ D48 +error(0.002530344283181031918) D37 D49 +error(0.002584336660252296424) D37 D49 ^ D39 D47 +error(0.0002635990637095448502) D37 D49 ^ D39 D48 +error(0.0006575318638258634231) D37 D49 ^ D47 D48 +error(0.004899237620589364482) D37 D50 +error(0.001632140203929661375) D37 D50 ^ D39 D40 +error(0.0007633653605808868791) D37 D50 ^ D39 D47 +error(0.001551636612335751666) D37 D50 ^ D39 D48 +error(0.0002089500978056947329) D37 D50 ^ D40 D48 +error(0.001540326152393501529) D37 D50 ^ D47 D48 +error(0.007004877619730071579) D39 D47 ^ D37 +error(0.005000000000000000104) D38 +error(0.00609080404863404385) D38 D45 +error(0.0006412086781627615063) D38 D45 ^ D36 +error(0.005316099403978277391) D38 D45 ^ D48 +error(0.0007231499252243798288) D38 D45 ^ D48 ^ D36 +error(0.02533370078930012592) D38 D46 +error(0.009581264674680716603) D38 D46 ^ D48 +error(0.001717039387100297628) D38 D50 +error(3.550316796919824485e-05) D38 D50 ^ D39 D40 +error(9.818036825801125544e-05) D38 D50 ^ D39 D48 +error(0.001668407009476837073) D38 D50 ^ D40 D48 +error(0.011427700059054028) D38 ^ D40 +error(0.002565883255846221084) D38 ^ D48 ^ D40 +error(0.008257398629531276929) D39 D40 +error(0.001068074573925781269) D39 D40 ^ D29 +error(0.0004160547161542342337) D39 D40 ^ D37 +error(0.0001809928460819403126) D39 D40 ^ D41 D42 +error(0.0007976095382669129343) D39 D40 ^ D42 +error(0.001506582328336537879) D39 D40 ^ D42 D50 +error(0.0003262905498523500881) D39 D40 ^ D50 +error(0.02436416753328735779) D39 D47 +error(0.003343901663810583142) D39 D47 ^ D49 D50 +error(0.002338381856532108314) D39 D48 +error(0.0003284014923968432719) D39 D48 ^ D49 D50 +error(0.001971685112299993888) D39 D51 +error(0.0002356806454351069381) D39 D51 ^ D42 +error(0.00140513153775703812) D39 D51 ^ D42 D50 +error(0.01000000000000000021) D39 L0 +error(0.008025747665072297324) D39 L0 ^ D41 +error(0.003754870086818663799) D41 D49 ^ D39 L0 +error(0.01000000000000000021) D40 +error(0.02111566487520867563) D40 D43 +error(0.020531600646543368) D40 D43 ^ D42 +error(0.0330796271598641986) D40 D48 +error(0.002060971124883901814) D40 D48 ^ D50 +error(0.01030641088581470306) D40 D51 +error(0.002027746224853679054) D40 D51 ^ D42 +error(0.004327870205481603241) D40 D51 ^ D50 +error(0.0007044985519714150974) D40 D51 ^ D50 ^ D42 +error(0.005000000000000000104) D41 +error(0.008135044191840199237) D41 D42 +error(0.003334200928408607208) D41 D42 ^ D31 L0 +error(0.01256896312079426245) D41 D42 ^ D39 L0 +error(3.523362331973171245e-05) D41 D42 ^ D43 L0 +error(0.0259144440966448085) D41 D49 +error(2.319766608052355999e-05) D41 ^ D29 ^ D31 L0 +error(0.0003729435504305767522) D41 ^ D29 ^ D39 L0 +error(0.0009907078669806480397) D41 ^ D39 L0 ^ D31 L0 +error(0.01000000000000000021) D42 +error(0.002522540241894852004) D42 D49 +error(0.002185884653266327669) D42 D49 ^ D39 L0 +error(0.0001203041160746442053) D42 D49 ^ D51 L0 +error(1.442812011990793695e-05) D42 D49 ^ D51 L0 ^ D39 L0 +error(0.03317048719226503573) D42 D50 +error(0.00136191988277857925) D42 D50 ^ D39 L0 +error(0.00221531971963198019) D42 D50 ^ D51 L0 +error(0.0006239191787623928152) D42 ^ D30 ^ D32 +error(0.001328042672585219922) D42 ^ D30 ^ D40 +error(0.001476553639008023819) D42 ^ D32 +error(0.001260766357202842145) D42 ^ D40 +error(0.01450099492487482572) D42 ^ D43 L0 +error(0.002590779815204308223) D42 ^ D51 L0 +error(0.002555392989364372192) D43 D51 ^ D42 +error(0.02371428898985290801) D43 D51 +error(0.005560840932060947574) D43 L0 +error(0.005000000000000000104) D44 +error(0.01599867247798393219) D44 D47 +error(0.01738551052587990892) D44 D47 ^ D45 +error(0.02563183000941281556) D44 D52 +error(0.007311517658274590235) D44 D52 ^ D53 +error(0.005648422745192678562) D44 D55 +error(0.004936162390005865291) D44 D55 ^ D45 +error(0.004470595127259575224) D44 D55 ^ D53 +error(0.003376400387429945651) D44 D55 ^ D53 ^ D45 +error(0.002859464556123720354) D44 D56 +error(0.0006704424957878181782) D44 D56 ^ D45 +error(0.003338387470335747731) D44 D56 ^ D45 D53 +error(0.0007316530848325324609) D44 D56 ^ D53 +error(0.005000000000000000104) D44 ^ D45 +error(0.005574457326479488953) D45 D53 ^ D44 +error(0.01000000000000000021) D45 +error(0.006223930169853710004) D45 D46 +error(0.000514866994970966294) D45 D46 ^ D44 +error(0.0005827841883569776209) D45 D46 ^ D47 D48 +error(0.0008582430700132457051) D45 D46 ^ D47 D56 +error(0.01465800186464856318) D45 D46 ^ D48 +error(0.003725859569174878438) D45 D46 ^ D48 D56 +error(0.002066805836596927268) D45 D46 ^ D56 +error(0.0006904309616043598479) D45 D46 ^ D56 ^ D44 +error(0.01953042700852838931) D45 D50 +error(0.01191093091747521225) D45 D50 ^ D47 D48 +error(0.04640023301592229726) D45 D53 +error(0.002674301988377119754) D45 D53 ^ D55 D56 +error(0.003646625935930334229) D45 D53 ^ D56 +error(0.002530344283181031918) D45 D57 +error(0.002584336660252296424) D45 D57 ^ D47 D55 +error(0.0002635990637095448502) D45 D57 ^ D47 D56 +error(0.0006575318638258634231) D45 D57 ^ D55 D56 +error(0.004899237620589364482) D45 D58 +error(0.001632140203929661375) D45 D58 ^ D47 D48 +error(0.0007633653605808868791) D45 D58 ^ D47 D55 +error(0.001551636612335751666) D45 D58 ^ D47 D56 +error(0.0002089500978056947329) D45 D58 ^ D48 D56 +error(0.001540326152393501529) D45 D58 ^ D55 D56 +error(0.007004877619730071579) D47 D55 ^ D45 +error(0.005000000000000000104) D46 +error(0.00609080404863404385) D46 D53 +error(0.0006412086781627615063) D46 D53 ^ D44 +error(0.005316099403978277391) D46 D53 ^ D56 +error(0.0007231499252243798288) D46 D53 ^ D56 ^ D44 +error(0.02533370078930012592) D46 D54 +error(0.009581264674680716603) D46 D54 ^ D56 +error(0.001717039387100297628) D46 D58 +error(3.550316796919824485e-05) D46 D58 ^ D47 D48 +error(9.818036825801125544e-05) D46 D58 ^ D47 D56 +error(0.001668407009476837073) D46 D58 ^ D48 D56 +error(0.011427700059054028) D46 ^ D48 +error(0.002565883255846221084) D46 ^ D56 ^ D48 +error(0.008257398629531276929) D47 D48 +error(0.001068074573925781269) D47 D48 ^ D37 +error(0.0004160547161542342337) D47 D48 ^ D45 +error(0.0001809928460819403126) D47 D48 ^ D49 D50 +error(0.0007976095382669129343) D47 D48 ^ D50 +error(0.001506582328336537879) D47 D48 ^ D50 D58 +error(0.0003262905498523500881) D47 D48 ^ D58 +error(0.02436416753328735779) D47 D55 +error(0.003343901663810583142) D47 D55 ^ D57 D58 +error(0.002338381856532108314) D47 D56 +error(0.0003284014923968432719) D47 D56 ^ D57 D58 +error(0.001971685112299993888) D47 D59 +error(0.0002356806454351069381) D47 D59 ^ D50 +error(0.00140513153775703812) D47 D59 ^ D50 D58 +error(0.01000000000000000021) D47 L0 +error(0.008025747665072297324) D47 L0 ^ D49 +error(0.003754870086818663799) D49 D57 ^ D47 L0 +error(0.01000000000000000021) D48 +error(0.02111566487520867563) D48 D51 +error(0.020531600646543368) D48 D51 ^ D50 +error(0.0330796271598641986) D48 D56 +error(0.002060971124883901814) D48 D56 ^ D58 +error(0.01030641088581470306) D48 D59 +error(0.002027746224853679054) D48 D59 ^ D50 +error(0.004327870205481603241) D48 D59 ^ D58 +error(0.0007044985519714150974) D48 D59 ^ D58 ^ D50 +error(0.005000000000000000104) D49 +error(0.008135044191840199237) D49 D50 +error(0.003334200928408607208) D49 D50 ^ D39 L0 +error(0.01256896312079426245) D49 D50 ^ D47 L0 +error(3.523362331973171245e-05) D49 D50 ^ D51 L0 +error(0.0259144440966448085) D49 D57 +error(2.319766608052355999e-05) D49 ^ D37 ^ D39 L0 +error(0.0003729435504305767522) D49 ^ D37 ^ D47 L0 +error(0.0009907078669806480397) D49 ^ D47 L0 ^ D39 L0 +error(0.01000000000000000021) D50 +error(0.002522540241894852004) D50 D57 +error(0.002185884653266327669) D50 D57 ^ D47 L0 +error(0.0001203041160746442053) D50 D57 ^ D59 L0 +error(1.442812011990793695e-05) D50 D57 ^ D59 L0 ^ D47 L0 +error(0.03317048719226503573) D50 D58 +error(0.00136191988277857925) D50 D58 ^ D47 L0 +error(0.00221531971963198019) D50 D58 ^ D59 L0 +error(0.0006239191787623928152) D50 ^ D38 ^ D40 +error(0.001328042672585219922) D50 ^ D38 ^ D48 +error(0.001476553639008023819) D50 ^ D40 +error(0.001260766357202842145) D50 ^ D48 +error(0.01450099492487482572) D50 ^ D51 L0 +error(0.002590779815204308223) D50 ^ D59 L0 +error(0.002555392989364372192) D51 D59 ^ D50 +error(0.02371428898985290801) D51 D59 +error(0.005560840932060947574) D51 L0 +error(0.005000000000000000104) D52 +error(0.01599867247798393219) D52 D55 +error(0.01738551052587990892) D52 D55 ^ D53 +error(0.02563183000941281556) D52 D60 +error(0.007311517658274590235) D52 D60 ^ D61 +error(0.005648422745192678562) D52 D63 +error(0.004936162390005865291) D52 D63 ^ D53 +error(0.004470595127259575224) D52 D63 ^ D61 +error(0.003376400387429945651) D52 D63 ^ D61 ^ D53 +error(0.002859464556123720354) D52 D64 +error(0.0006704424957878181782) D52 D64 ^ D53 +error(0.003338387470335747731) D52 D64 ^ D53 D61 +error(0.0007316530848325324609) D52 D64 ^ D61 +error(0.005000000000000000104) D52 ^ D53 +error(0.005574457326479488953) D53 D61 ^ D52 +error(0.01000000000000000021) D53 +error(0.006223930169853710004) D53 D54 +error(0.000514866994970966294) D53 D54 ^ D52 +error(0.0005827841883569776209) D53 D54 ^ D55 D56 +error(0.0008582430700132457051) D53 D54 ^ D55 D64 +error(0.01465800186464856318) D53 D54 ^ D56 +error(0.003725859569174878438) D53 D54 ^ D56 D64 +error(0.002066805836596927268) D53 D54 ^ D64 +error(0.0006904309616043598479) D53 D54 ^ D64 ^ D52 +error(0.01953042700852838931) D53 D58 +error(0.01191093091747521225) D53 D58 ^ D55 D56 +error(0.04640023301592229726) D53 D61 +error(0.002674301988377119754) D53 D61 ^ D63 D64 +error(0.003646625935930334229) D53 D61 ^ D64 +error(0.002530344283181031918) D53 D65 +error(0.002584336660252296424) D53 D65 ^ D55 D63 +error(0.0002635990637095448502) D53 D65 ^ D55 D64 +error(0.0006575318638258634231) D53 D65 ^ D63 D64 +error(0.004899237620589364482) D53 D66 +error(0.001632140203929661375) D53 D66 ^ D55 D56 +error(0.0007633653605808868791) D53 D66 ^ D55 D63 +error(0.001551636612335751666) D53 D66 ^ D55 D64 +error(0.0002089500978056947329) D53 D66 ^ D56 D64 +error(0.001540326152393501529) D53 D66 ^ D63 D64 +error(0.007004877619730071579) D55 D63 ^ D53 +error(0.005000000000000000104) D54 +error(0.00609080404863404385) D54 D61 +error(0.0006412086781627615063) D54 D61 ^ D52 +error(0.005316099403978277391) D54 D61 ^ D64 +error(0.0007231499252243798288) D54 D61 ^ D64 ^ D52 +error(0.02533370078930012592) D54 D62 +error(0.009581264674680716603) D54 D62 ^ D64 +error(0.001717039387100297628) D54 D66 +error(3.550316796919824485e-05) D54 D66 ^ D55 D56 +error(9.818036825801125544e-05) D54 D66 ^ D55 D64 +error(0.001668407009476837073) D54 D66 ^ D56 D64 +error(0.011427700059054028) D54 ^ D56 +error(0.002565883255846221084) D54 ^ D64 ^ D56 +error(0.008257398629531276929) D55 D56 +error(0.001068074573925781269) D55 D56 ^ D45 +error(0.0004160547161542342337) D55 D56 ^ D53 +error(0.0001809928460819403126) D55 D56 ^ D57 D58 +error(0.0007976095382669129343) D55 D56 ^ D58 +error(0.001506582328336537879) D55 D56 ^ D58 D66 +error(0.0003262905498523500881) D55 D56 ^ D66 +error(0.02436416753328735779) D55 D63 +error(0.003343901663810583142) D55 D63 ^ D65 D66 +error(0.002338381856532108314) D55 D64 +error(0.0003284014923968432719) D55 D64 ^ D65 D66 +error(0.001971685112299993888) D55 D67 +error(0.0002356806454351069381) D55 D67 ^ D58 +error(0.00140513153775703812) D55 D67 ^ D58 D66 +error(0.01000000000000000021) D55 L0 +error(0.008025747665072297324) D55 L0 ^ D57 +error(0.003754870086818663799) D57 D65 ^ D55 L0 +error(0.01000000000000000021) D56 +error(0.02111566487520867563) D56 D59 +error(0.020531600646543368) D56 D59 ^ D58 +error(0.0330796271598641986) D56 D64 +error(0.002060971124883901814) D56 D64 ^ D66 +error(0.01030641088581470306) D56 D67 +error(0.002027746224853679054) D56 D67 ^ D58 +error(0.004327870205481603241) D56 D67 ^ D66 +error(0.0007044985519714150974) D56 D67 ^ D66 ^ D58 +error(0.005000000000000000104) D57 +error(0.008135044191840199237) D57 D58 +error(0.003334200928408607208) D57 D58 ^ D47 L0 +error(0.01256896312079426245) D57 D58 ^ D55 L0 +error(3.523362331973171245e-05) D57 D58 ^ D59 L0 +error(0.0259144440966448085) D57 D65 +error(2.319766608052355999e-05) D57 ^ D45 ^ D47 L0 +error(0.0003729435504305767522) D57 ^ D45 ^ D55 L0 +error(0.0009907078669806480397) D57 ^ D55 L0 ^ D47 L0 +error(0.01000000000000000021) D58 +error(0.002522540241894852004) D58 D65 +error(0.002185884653266327669) D58 D65 ^ D55 L0 +error(0.0001203041160746442053) D58 D65 ^ D67 L0 +error(1.442812011990793695e-05) D58 D65 ^ D67 L0 ^ D55 L0 +error(0.03317048719226503573) D58 D66 +error(0.00136191988277857925) D58 D66 ^ D55 L0 +error(0.00221531971963198019) D58 D66 ^ D67 L0 +error(0.0006239191787623928152) D58 ^ D46 ^ D48 +error(0.001328042672585219922) D58 ^ D46 ^ D56 +error(0.001476553639008023819) D58 ^ D48 +error(0.001260766357202842145) D58 ^ D56 +error(0.01450099492487482572) D58 ^ D59 L0 +error(0.002590779815204308223) D58 ^ D67 L0 +error(0.002555392989364372192) D59 D67 ^ D58 +error(0.02371428898985290801) D59 D67 +error(0.005560840932060947574) D59 L0 +error(0.005000000000000000104) D60 +error(0.01599867247798393219) D60 D63 +error(0.01738551052587990892) D60 D63 ^ D61 +error(0.02563183000941281556) D60 D68 +error(0.007311517658274590235) D60 D68 ^ D69 +error(0.005648422745192678562) D60 D71 +error(0.004936162390005865291) D60 D71 ^ D61 +error(0.004470595127259575224) D60 D71 ^ D69 +error(0.003376400387429945651) D60 D71 ^ D69 ^ D61 +error(0.002859464556123720354) D60 D72 +error(0.0006704424957878181782) D60 D72 ^ D61 +error(0.003338387470335747731) D60 D72 ^ D61 D69 +error(0.0007316530848325324609) D60 D72 ^ D69 +error(0.005000000000000000104) D60 ^ D61 +error(0.005574457326479488953) D61 D69 ^ D60 +error(0.01000000000000000021) D61 +error(0.006223930169853710004) D61 D62 +error(0.000514866994970966294) D61 D62 ^ D60 +error(0.0005827841883569776209) D61 D62 ^ D63 D64 +error(0.0008582430700132457051) D61 D62 ^ D63 D72 +error(0.01465800186464856318) D61 D62 ^ D64 +error(0.003725859569174878438) D61 D62 ^ D64 D72 +error(0.002066805836596927268) D61 D62 ^ D72 +error(0.0006904309616043598479) D61 D62 ^ D72 ^ D60 +error(0.01953042700852838931) D61 D66 +error(0.01191093091747521225) D61 D66 ^ D63 D64 +error(0.04640023301592229726) D61 D69 +error(0.002674301988377119754) D61 D69 ^ D71 D72 +error(0.003646625935930334229) D61 D69 ^ D72 +error(0.002530344283181031918) D61 D73 +error(0.002584336660252296424) D61 D73 ^ D63 D71 +error(0.0002635990637095448502) D61 D73 ^ D63 D72 +error(0.0006575318638258634231) D61 D73 ^ D71 D72 +error(0.004899237620589364482) D61 D74 +error(0.001632140203929661375) D61 D74 ^ D63 D64 +error(0.0007633653605808868791) D61 D74 ^ D63 D71 +error(0.001551636612335751666) D61 D74 ^ D63 D72 +error(0.0002089500978056947329) D61 D74 ^ D64 D72 +error(0.001540326152393501529) D61 D74 ^ D71 D72 +error(0.007004877619730071579) D63 D71 ^ D61 +error(0.005000000000000000104) D62 +error(0.00609080404863404385) D62 D69 +error(0.0006412086781627615063) D62 D69 ^ D60 +error(0.005316099403978277391) D62 D69 ^ D72 +error(0.0007231499252243798288) D62 D69 ^ D72 ^ D60 +error(0.02533370078930012592) D62 D70 +error(0.009581264674680716603) D62 D70 ^ D72 +error(0.001717039387100297628) D62 D74 +error(3.550316796919824485e-05) D62 D74 ^ D63 D64 +error(9.818036825801125544e-05) D62 D74 ^ D63 D72 +error(0.001668407009476837073) D62 D74 ^ D64 D72 +error(0.011427700059054028) D62 ^ D64 +error(0.002565883255846221084) D62 ^ D72 ^ D64 +error(0.008257398629531276929) D63 D64 +error(0.001068074573925781269) D63 D64 ^ D53 +error(0.0004160547161542342337) D63 D64 ^ D61 +error(0.0001809928460819403126) D63 D64 ^ D65 D66 +error(0.0007976095382669129343) D63 D64 ^ D66 +error(0.001506582328336537879) D63 D64 ^ D66 D74 +error(0.0003262905498523500881) D63 D64 ^ D74 +error(0.02436416753328735779) D63 D71 +error(0.003343901663810583142) D63 D71 ^ D73 D74 +error(0.002338381856532108314) D63 D72 +error(0.0003284014923968432719) D63 D72 ^ D73 D74 +error(0.001971685112299993888) D63 D75 +error(0.0002356806454351069381) D63 D75 ^ D66 +error(0.00140513153775703812) D63 D75 ^ D66 D74 +error(0.01000000000000000021) D63 L0 +error(0.008025747665072297324) D63 L0 ^ D65 +error(0.003754870086818663799) D65 D73 ^ D63 L0 +error(0.01000000000000000021) D64 +error(0.02111566487520867563) D64 D67 +error(0.020531600646543368) D64 D67 ^ D66 +error(0.0330796271598641986) D64 D72 +error(0.002060971124883901814) D64 D72 ^ D74 +error(0.01030641088581470306) D64 D75 +error(0.002027746224853679054) D64 D75 ^ D66 +error(0.004327870205481603241) D64 D75 ^ D74 +error(0.0007044985519714150974) D64 D75 ^ D74 ^ D66 +error(0.005000000000000000104) D65 +error(0.008135044191840199237) D65 D66 +error(0.003334200928408607208) D65 D66 ^ D55 L0 +error(0.01256896312079426245) D65 D66 ^ D63 L0 +error(3.523362331973171245e-05) D65 D66 ^ D67 L0 +error(0.0259144440966448085) D65 D73 +error(2.319766608052355999e-05) D65 ^ D53 ^ D55 L0 +error(0.0003729435504305767522) D65 ^ D53 ^ D63 L0 +error(0.0009907078669806480397) D65 ^ D63 L0 ^ D55 L0 +error(0.01000000000000000021) D66 +error(0.002522540241894852004) D66 D73 +error(0.002185884653266327669) D66 D73 ^ D63 L0 +error(0.0001203041160746442053) D66 D73 ^ D75 L0 +error(1.442812011990793695e-05) D66 D73 ^ D75 L0 ^ D63 L0 +error(0.03317048719226503573) D66 D74 +error(0.00136191988277857925) D66 D74 ^ D63 L0 +error(0.00221531971963198019) D66 D74 ^ D75 L0 +error(0.0006239191787623928152) D66 ^ D54 ^ D56 +error(0.001328042672585219922) D66 ^ D54 ^ D64 +error(0.001476553639008023819) D66 ^ D56 +error(0.001260766357202842145) D66 ^ D64 +error(0.01450099492487482572) D66 ^ D67 L0 +error(0.002590779815204308223) D66 ^ D75 L0 +error(0.002555392989364372192) D67 D75 ^ D66 +error(0.02371428898985290801) D67 D75 +error(0.005560840932060947574) D67 L0 +error(0.005000000000000000104) D68 +error(0.01599867247798393219) D68 D71 +error(0.01738551052587990892) D68 D71 ^ D69 +error(0.02563183000941281556) D68 D76 +error(0.007311517658274590235) D68 D76 ^ D77 +error(0.005648422745192678562) D68 D79 +error(0.004936162390005865291) D68 D79 ^ D69 +error(0.004470595127259575224) D68 D79 ^ D77 +error(0.003376400387429945651) D68 D79 ^ D77 ^ D69 +error(0.002859464556123720354) D68 D80 +error(0.0006704424957878181782) D68 D80 ^ D69 +error(0.003338387470335747731) D68 D80 ^ D69 D77 +error(0.0007316530848325324609) D68 D80 ^ D77 +error(0.005000000000000000104) D68 ^ D69 +error(0.005574457326479488953) D69 D77 ^ D68 +error(0.01000000000000000021) D69 +error(0.006223930169853710004) D69 D70 +error(0.000514866994970966294) D69 D70 ^ D68 +error(0.0005827841883569776209) D69 D70 ^ D71 D72 +error(0.0008582430700132457051) D69 D70 ^ D71 D80 +error(0.01465800186464856318) D69 D70 ^ D72 +error(0.003725859569174878438) D69 D70 ^ D72 D80 +error(0.002066805836596927268) D69 D70 ^ D80 +error(0.0006904309616043598479) D69 D70 ^ D80 ^ D68 +error(0.01953042700852838931) D69 D74 +error(0.01191093091747521225) D69 D74 ^ D71 D72 +error(0.04640023301592229726) D69 D77 +error(0.002674301988377119754) D69 D77 ^ D79 D80 +error(0.003646625935930334229) D69 D77 ^ D80 +error(0.002530344283181031918) D69 D81 +error(0.002584336660252296424) D69 D81 ^ D71 D79 +error(0.0002635990637095448502) D69 D81 ^ D71 D80 +error(0.0006575318638258634231) D69 D81 ^ D79 D80 +error(0.004899237620589364482) D69 D82 +error(0.001632140203929661375) D69 D82 ^ D71 D72 +error(0.0007633653605808868791) D69 D82 ^ D71 D79 +error(0.001551636612335751666) D69 D82 ^ D71 D80 +error(0.0002089500978056947329) D69 D82 ^ D72 D80 +error(0.001540326152393501529) D69 D82 ^ D79 D80 +error(0.007004877619730071579) D71 D79 ^ D69 +error(0.005000000000000000104) D70 +error(0.00609080404863404385) D70 D77 +error(0.0006412086781627615063) D70 D77 ^ D68 +error(0.005316099403978277391) D70 D77 ^ D80 +error(0.0007231499252243798288) D70 D77 ^ D80 ^ D68 +error(0.02533370078930012592) D70 D78 +error(0.009581264674680716603) D70 D78 ^ D80 +error(0.001717039387100297628) D70 D82 +error(3.550316796919824485e-05) D70 D82 ^ D71 D72 +error(9.818036825801125544e-05) D70 D82 ^ D71 D80 +error(0.001668407009476837073) D70 D82 ^ D72 D80 +error(0.011427700059054028) D70 ^ D72 +error(0.002565883255846221084) D70 ^ D80 ^ D72 +error(0.008257398629531276929) D71 D72 +error(0.001068074573925781269) D71 D72 ^ D61 +error(0.0004160547161542342337) D71 D72 ^ D69 +error(0.0001809928460819403126) D71 D72 ^ D73 D74 +error(0.0007976095382669129343) D71 D72 ^ D74 +error(0.001506582328336537879) D71 D72 ^ D74 D82 +error(0.0003262905498523500881) D71 D72 ^ D82 +error(0.02436416753328735779) D71 D79 +error(0.003343901663810583142) D71 D79 ^ D81 D82 +error(0.002338381856532108314) D71 D80 +error(0.0003284014923968432719) D71 D80 ^ D81 D82 +error(0.001971685112299993888) D71 D83 +error(0.0002356806454351069381) D71 D83 ^ D74 +error(0.00140513153775703812) D71 D83 ^ D74 D82 +error(0.01000000000000000021) D71 L0 +error(0.008025747665072297324) D71 L0 ^ D73 +error(0.003754870086818663799) D73 D81 ^ D71 L0 +error(0.01000000000000000021) D72 +error(0.02111566487520867563) D72 D75 +error(0.020531600646543368) D72 D75 ^ D74 +error(0.0330796271598641986) D72 D80 +error(0.002060971124883901814) D72 D80 ^ D82 +error(0.01030641088581470306) D72 D83 +error(0.002027746224853679054) D72 D83 ^ D74 +error(0.004327870205481603241) D72 D83 ^ D82 +error(0.0007044985519714150974) D72 D83 ^ D82 ^ D74 +error(0.005000000000000000104) D73 +error(0.008135044191840199237) D73 D74 +error(0.003334200928408607208) D73 D74 ^ D63 L0 +error(0.01256896312079426245) D73 D74 ^ D71 L0 +error(3.523362331973171245e-05) D73 D74 ^ D75 L0 +error(0.0259144440966448085) D73 D81 +error(2.319766608052355999e-05) D73 ^ D61 ^ D63 L0 +error(0.0003729435504305767522) D73 ^ D61 ^ D71 L0 +error(0.0009907078669806480397) D73 ^ D71 L0 ^ D63 L0 +error(0.01000000000000000021) D74 +error(0.002522540241894852004) D74 D81 +error(0.002185884653266327669) D74 D81 ^ D71 L0 +error(0.0001203041160746442053) D74 D81 ^ D83 L0 +error(1.442812011990793695e-05) D74 D81 ^ D83 L0 ^ D71 L0 +error(0.03317048719226503573) D74 D82 +error(0.00136191988277857925) D74 D82 ^ D71 L0 +error(0.00221531971963198019) D74 D82 ^ D83 L0 +error(0.0006239191787623928152) D74 ^ D62 ^ D64 +error(0.001328042672585219922) D74 ^ D62 ^ D72 +error(0.001476553639008023819) D74 ^ D64 +error(0.001260766357202842145) D74 ^ D72 +error(0.01450099492487482572) D74 ^ D75 L0 +error(0.002590779815204308223) D74 ^ D83 L0 +error(0.002555392989364372192) D75 D83 ^ D74 +error(0.02371428898985290801) D75 D83 +error(0.005560840932060947574) D75 L0 +error(0.005000000000000000104) D76 +error(0.01599867247798393219) D76 D79 +error(0.01738551052587990892) D76 D79 ^ D77 +error(0.02563183000941281556) D76 D84 +error(0.007311517658274590235) D76 D84 ^ D85 +error(0.005648422745192678562) D76 D87 +error(0.004936162390005865291) D76 D87 ^ D77 +error(0.004470595127259575224) D76 D87 ^ D85 +error(0.003376400387429945651) D76 D87 ^ D85 ^ D77 +error(0.002859464556123720354) D76 D88 +error(0.0006704424957878181782) D76 D88 ^ D77 +error(0.003338387470335747731) D76 D88 ^ D77 D85 +error(0.0007316530848325324609) D76 D88 ^ D85 +error(0.005000000000000000104) D76 ^ D77 +error(0.005574457326479488953) D77 D85 ^ D76 +error(0.01000000000000000021) D77 +error(0.006223930169853710004) D77 D78 +error(0.000514866994970966294) D77 D78 ^ D76 +error(0.0005827841883569776209) D77 D78 ^ D79 D80 +error(0.0008582430700132457051) D77 D78 ^ D79 D88 +error(0.01465800186464856318) D77 D78 ^ D80 +error(0.003725859569174878438) D77 D78 ^ D80 D88 +error(0.002066805836596927268) D77 D78 ^ D88 +error(0.0006904309616043598479) D77 D78 ^ D88 ^ D76 +error(0.01953042700852838931) D77 D82 +error(0.01191093091747521225) D77 D82 ^ D79 D80 +error(0.04640023301592229726) D77 D85 +error(0.002674301988377119754) D77 D85 ^ D87 D88 +error(0.003646625935930334229) D77 D85 ^ D88 +error(0.002530344283181031918) D77 D89 +error(0.002584336660252296424) D77 D89 ^ D79 D87 +error(0.0002635990637095448502) D77 D89 ^ D79 D88 +error(0.0006575318638258634231) D77 D89 ^ D87 D88 +error(0.004899237620589364482) D77 D90 +error(0.001632140203929661375) D77 D90 ^ D79 D80 +error(0.0007633653605808868791) D77 D90 ^ D79 D87 +error(0.001551636612335751666) D77 D90 ^ D79 D88 +error(0.0002089500978056947329) D77 D90 ^ D80 D88 +error(0.001540326152393501529) D77 D90 ^ D87 D88 +error(0.007004877619730071579) D79 D87 ^ D77 +error(0.005000000000000000104) D78 +error(0.00609080404863404385) D78 D85 +error(0.0006412086781627615063) D78 D85 ^ D76 +error(0.005316099403978277391) D78 D85 ^ D88 +error(0.0007231499252243798288) D78 D85 ^ D88 ^ D76 +error(0.02533370078930012592) D78 D86 +error(0.009581264674680716603) D78 D86 ^ D88 +error(0.001717039387100297628) D78 D90 +error(3.550316796919824485e-05) D78 D90 ^ D79 D80 +error(9.818036825801125544e-05) D78 D90 ^ D79 D88 +error(0.001668407009476837073) D78 D90 ^ D80 D88 +error(0.011427700059054028) D78 ^ D80 +error(0.002565883255846221084) D78 ^ D88 ^ D80 +error(0.008257398629531276929) D79 D80 +error(0.001068074573925781269) D79 D80 ^ D69 +error(0.0004160547161542342337) D79 D80 ^ D77 +error(0.0001809928460819403126) D79 D80 ^ D81 D82 +error(0.0007976095382669129343) D79 D80 ^ D82 +error(0.001506582328336537879) D79 D80 ^ D82 D90 +error(0.0003262905498523500881) D79 D80 ^ D90 +error(0.02436416753328735779) D79 D87 +error(0.003343901663810583142) D79 D87 ^ D89 D90 +error(0.002338381856532108314) D79 D88 +error(0.0003284014923968432719) D79 D88 ^ D89 D90 +error(0.001971685112299993888) D79 D91 +error(0.0002356806454351069381) D79 D91 ^ D82 +error(0.00140513153775703812) D79 D91 ^ D82 D90 +error(0.01000000000000000021) D79 L0 +error(0.008025747665072297324) D79 L0 ^ D81 +error(0.003754870086818663799) D81 D89 ^ D79 L0 +error(0.01000000000000000021) D80 +error(0.02111566487520867563) D80 D83 +error(0.020531600646543368) D80 D83 ^ D82 +error(0.0330796271598641986) D80 D88 +error(0.002060971124883901814) D80 D88 ^ D90 +error(0.01030641088581470306) D80 D91 +error(0.002027746224853679054) D80 D91 ^ D82 +error(0.004327870205481603241) D80 D91 ^ D90 +error(0.0007044985519714150974) D80 D91 ^ D90 ^ D82 +error(0.005000000000000000104) D81 +error(0.008135044191840199237) D81 D82 +error(0.003334200928408607208) D81 D82 ^ D71 L0 +error(0.01256896312079426245) D81 D82 ^ D79 L0 +error(3.523362331973171245e-05) D81 D82 ^ D83 L0 +error(0.0259144440966448085) D81 D89 +error(2.319766608052355999e-05) D81 ^ D69 ^ D71 L0 +error(0.0003729435504305767522) D81 ^ D69 ^ D79 L0 +error(0.0009907078669806480397) D81 ^ D79 L0 ^ D71 L0 +error(0.01000000000000000021) D82 +error(0.002522540241894852004) D82 D89 +error(0.002185884653266327669) D82 D89 ^ D79 L0 +error(0.0001203041160746442053) D82 D89 ^ D91 L0 +error(1.442812011990793695e-05) D82 D89 ^ D91 L0 ^ D79 L0 +error(0.03317048719226503573) D82 D90 +error(0.00136191988277857925) D82 D90 ^ D79 L0 +error(0.00221531971963198019) D82 D90 ^ D91 L0 +error(0.0006239191787623928152) D82 ^ D70 ^ D72 +error(0.001328042672585219922) D82 ^ D70 ^ D80 +error(0.001476553639008023819) D82 ^ D72 +error(0.001260766357202842145) D82 ^ D80 +error(0.01450099492487482572) D82 ^ D83 L0 +error(0.002590779815204308223) D82 ^ D91 L0 +error(0.002555392989364372192) D83 D91 ^ D82 +error(0.02371428898985290801) D83 D91 +error(0.005560840932060947574) D83 L0 +error(0.005000000000000000104) D84 +error(0.01599867247798393219) D84 D87 +error(0.01738551052587990892) D84 D87 ^ D85 +error(0.02563183000941281556) D84 D92 +error(0.007311517658274590235) D84 D92 ^ D93 +error(0.005648422745192678562) D84 D95 +error(0.004936162390005865291) D84 D95 ^ D85 +error(0.004470595127259575224) D84 D95 ^ D93 +error(0.003376400387429945651) D84 D95 ^ D93 ^ D85 +error(0.002859464556123720354) D84 D96 +error(0.0006704424957878181782) D84 D96 ^ D85 +error(0.003338387470335747731) D84 D96 ^ D85 D93 +error(0.0007316530848325324609) D84 D96 ^ D93 +error(0.005000000000000000104) D84 ^ D85 +error(0.005574457326479488953) D85 D93 ^ D84 +error(0.01000000000000000021) D85 +error(0.006223930169853710004) D85 D86 +error(0.000514866994970966294) D85 D86 ^ D84 +error(0.0005827841883569776209) D85 D86 ^ D87 D88 +error(0.0008582430700132457051) D85 D86 ^ D87 D96 +error(0.01465800186464856318) D85 D86 ^ D88 +error(0.003725859569174878438) D85 D86 ^ D88 D96 +error(0.002066805836596927268) D85 D86 ^ D96 +error(0.0006904309616043598479) D85 D86 ^ D96 ^ D84 +error(0.01953042700852838931) D85 D90 +error(0.01191093091747521225) D85 D90 ^ D87 D88 +error(0.04640023301592229726) D85 D93 +error(0.002674301988377119754) D85 D93 ^ D95 D96 +error(0.003646625935930334229) D85 D93 ^ D96 +error(0.002530344283181031918) D85 D97 +error(0.002584336660252296424) D85 D97 ^ D87 D95 +error(0.0002635990637095448502) D85 D97 ^ D87 D96 +error(0.0006575318638258634231) D85 D97 ^ D95 D96 +error(0.004899237620589364482) D85 D98 +error(0.001632140203929661375) D85 D98 ^ D87 D88 +error(0.0007633653605808868791) D85 D98 ^ D87 D95 +error(0.001551636612335751666) D85 D98 ^ D87 D96 +error(0.0002089500978056947329) D85 D98 ^ D88 D96 +error(0.001540326152393501529) D85 D98 ^ D95 D96 +error(0.007004877619730071579) D87 D95 ^ D85 +error(0.005000000000000000104) D86 +error(0.00609080404863404385) D86 D93 +error(0.0006412086781627615063) D86 D93 ^ D84 +error(0.005316099403978277391) D86 D93 ^ D96 +error(0.0007231499252243798288) D86 D93 ^ D96 ^ D84 +error(0.02533370078930012592) D86 D94 +error(0.009581264674680716603) D86 D94 ^ D96 +error(0.001717039387100297628) D86 D98 +error(3.550316796919824485e-05) D86 D98 ^ D87 D88 +error(9.818036825801125544e-05) D86 D98 ^ D87 D96 +error(0.001668407009476837073) D86 D98 ^ D88 D96 +error(0.011427700059054028) D86 ^ D88 +error(0.002565883255846221084) D86 ^ D96 ^ D88 +error(0.008257398629531276929) D87 D88 +error(0.001068074573925781269) D87 D88 ^ D77 +error(0.0004160547161542342337) D87 D88 ^ D85 +error(0.0001809928460819403126) D87 D88 ^ D89 D90 +error(0.0007976095382669129343) D87 D88 ^ D90 +error(0.001506582328336537879) D87 D88 ^ D90 D98 +error(0.0003262905498523500881) D87 D88 ^ D98 +error(0.02436416753328735779) D87 D95 +error(0.003343901663810583142) D87 D95 ^ D97 D98 +error(0.002338381856532108314) D87 D96 +error(0.0003284014923968432719) D87 D96 ^ D97 D98 +error(0.001971685112299993888) D87 D99 +error(0.0002356806454351069381) D87 D99 ^ D90 +error(0.00140513153775703812) D87 D99 ^ D90 D98 +error(0.01000000000000000021) D87 L0 +error(0.008025747665072297324) D87 L0 ^ D89 +error(0.003754870086818663799) D89 D97 ^ D87 L0 +error(0.01000000000000000021) D88 +error(0.02111566487520867563) D88 D91 +error(0.020531600646543368) D88 D91 ^ D90 +error(0.0330796271598641986) D88 D96 +error(0.002060971124883901814) D88 D96 ^ D98 +error(0.01030641088581470306) D88 D99 +error(0.002027746224853679054) D88 D99 ^ D90 +error(0.004327870205481603241) D88 D99 ^ D98 +error(0.0007044985519714150974) D88 D99 ^ D98 ^ D90 +error(0.005000000000000000104) D89 +error(0.008135044191840199237) D89 D90 +error(0.003334200928408607208) D89 D90 ^ D79 L0 +error(0.01256896312079426245) D89 D90 ^ D87 L0 +error(3.523362331973171245e-05) D89 D90 ^ D91 L0 +error(0.0259144440966448085) D89 D97 +error(2.319766608052355999e-05) D89 ^ D77 ^ D79 L0 +error(0.0003729435504305767522) D89 ^ D77 ^ D87 L0 +error(0.0009907078669806480397) D89 ^ D87 L0 ^ D79 L0 +error(0.01000000000000000021) D90 +error(0.002522540241894852004) D90 D97 +error(0.002185884653266327669) D90 D97 ^ D87 L0 +error(0.0001203041160746442053) D90 D97 ^ D99 L0 +error(1.442812011990793695e-05) D90 D97 ^ D99 L0 ^ D87 L0 +error(0.03317048719226503573) D90 D98 +error(0.00136191988277857925) D90 D98 ^ D87 L0 +error(0.00221531971963198019) D90 D98 ^ D99 L0 +error(0.0006239191787623928152) D90 ^ D78 ^ D80 +error(0.001328042672585219922) D90 ^ D78 ^ D88 +error(0.001476553639008023819) D90 ^ D80 +error(0.001260766357202842145) D90 ^ D88 +error(0.01450099492487482572) D90 ^ D91 L0 +error(0.002590779815204308223) D90 ^ D99 L0 +error(0.002555392989364372192) D91 D99 ^ D90 +error(0.02371428898985290801) D91 D99 +error(0.005560840932060947574) D91 L0 +error(0.005000000000000000104) D92 +error(0.02267805869898589094) D92 D95 +error(0.01873364660511162363) D92 D95 ^ D93 +error(0.04100545857448617548) D92 D100 +error(0.01141739295701620083) D92 D101 +error(0.009557076143876483063) D92 D101 ^ D93 +error(0.002077419822676541527) D92 D102 +error(0.005354528838095110564) D92 D102 ^ D93 +error(0.0113209120008606369) D92 ^ D93 +error(0.0006792624355961453383) D92 ^ D94 +error(0.04234581131636085821) D93 +error(0.00678606573782423745) D93 D94 +error(0.0145226519619787893) D93 D94 ^ D96 +error(0.005137275095700253452) D93 D94 ^ D96 D102 +error(0.002975969365861628503) D93 D94 ^ D102 +error(0.02338861187096557756) D93 D98 +error(0.01247004701382990223) D93 D98 ^ D95 D96 +error(0.001498689292283549458) D93 ^ D92 ^ D94 +error(0.002000425380570747345) D93 ^ D101 L0 +error(0.01181237328125289351) D95 D101 ^ D93 +error(0.0003050700272574752531) D93 ^ D102 +error(0.0006319504913480969129) D93 ^ D102 ^ D92 ^ D94 +error(0.03845252020992127179) D94 +error(0.01340303062296463454) D94 ^ D96 +error(0.01567631124036529891) D94 ^ D102 +error(0.008233302669587784159) D96 D102 ^ D94 +error(0.005002458988042899658) D95 D96 +error(0.001068074573925781269) D95 D96 ^ D85 +error(0.002241384301584336842) D95 D96 ^ D93 +error(0.001047450376039640516) D95 D96 ^ D94 +error(0.005839977714280467774) D95 D96 ^ D98 +error(0.03347220262306321859) D95 D101 +error(0.001338098317433359351) D95 D102 +error(0.003118523564046928303) D95 D102 ^ D93 +error(6.995191040884665332e-05) D95 D102 ^ D94 +error(0.000705781335417173146) D95 D102 ^ D94 ^ D93 +error(0.0005754833532841477101) D95 D103 +error(0.002335765027682870382) D95 D103 ^ D98 +error(0.01000000000000000021) D95 L0 +error(0.0101976883807940108) D95 L0 ^ D97 +error(0.001430731709873393548) D95 L0 ^ D98 +error(0.02094149898258004794) D96 +error(0.01980660729454878852) D96 D99 +error(0.02156572384803468953) D96 D99 ^ D98 +error(0.03408863979946338829) D96 D102 +error(0.003761119774534770355) D96 D102 ^ D93 +error(0.01356746672354330711) D96 D103 +error(0.003694484725144231603) D96 D103 ^ D98 +error(0.03490157767228494606) D97 +error(0.01278836414926115723) D97 D98 +error(0.003334200928408607208) D97 D98 ^ D87 L0 +error(0.01493169429312366479) D97 D98 ^ D95 L0 +error(1.03686754372217694e-05) D97 D98 ^ D99 L0 +error(2.319766608052355999e-05) D97 ^ D85 ^ D87 L0 +error(0.0003729435504305767522) D97 ^ D85 ^ D95 L0 +error(0.0009907078669806480397) D97 ^ D95 L0 ^ D87 L0 +error(0.04387285734034779977) D98 +error(0.0006239191787623928152) D98 ^ D86 ^ D88 +error(0.001328042672585219922) D98 ^ D86 ^ D96 +error(0.001476553639008023819) D98 ^ D88 +error(0.01108230520926279869) D98 ^ D99 L0 +error(0.003750785469958562487) D98 ^ D103 L0 +error(0.003606775919368128067) D99 D103 ^ D98 +error(0.02200449541619549712) D99 D103 +error(0.009093594333468374424) D99 L0 +error(0.03495995643871752795) D100 +error(0.02949353923398922994) D100 D101 +error(0.01561423083624485265) D101 D102 +error(0.006854868332884836955) D101 D102 ^ D93 +error(0.01000000000000000021) D101 L0 +error(0.02138918065130495857) D102 +error(0.01538724512914729781) D102 D103 +error(0.0007777296251364652782) D102 ^ D92 ^ D94 +error(0.0229321079385099956) D103 L0 +detector(1, 4, 0) D0 +detector(3, 4, 0) D1 +detector(3, 6, 0) D2 +detector(5, 6, 0) D3 +detector(1, 4, 1) D4 +detector(2, 5, 1) D5 +detector(2, 7, 1) D6 +detector(3, 4, 1) D7 +detector(3, 6, 1) D8 +detector(4, 3, 1) D9 +detector(4, 5, 1) D10 +detector(5, 6, 1) D11 +detector(1, 4, 2) D12 +detector(2, 5, 2) D13 +detector(2, 7, 2) D14 +detector(3, 4, 2) D15 +detector(3, 6, 2) D16 +detector(4, 3, 2) D17 +detector(4, 5, 2) D18 +detector(5, 6, 2) D19 +detector(1, 4, 3) D20 +detector(2, 5, 3) D21 +detector(2, 7, 3) D22 +detector(3, 4, 3) D23 +detector(3, 6, 3) D24 +detector(4, 3, 3) D25 +detector(4, 5, 3) D26 +detector(5, 6, 3) D27 +detector(1, 4, 4) D28 +detector(2, 5, 4) D29 +detector(2, 7, 4) D30 +detector(3, 4, 4) D31 +detector(3, 6, 4) D32 +detector(4, 3, 4) D33 +detector(4, 5, 4) D34 +detector(5, 6, 4) D35 +detector(1, 4, 5) D36 +detector(2, 5, 5) D37 +detector(2, 7, 5) D38 +detector(3, 4, 5) D39 +detector(3, 6, 5) D40 +detector(4, 3, 5) D41 +detector(4, 5, 5) D42 +detector(5, 6, 5) D43 +detector(1, 4, 6) D44 +detector(2, 5, 6) D45 +detector(2, 7, 6) D46 +detector(3, 4, 6) D47 +detector(3, 6, 6) D48 +detector(4, 3, 6) D49 +detector(4, 5, 6) D50 +detector(5, 6, 6) D51 +detector(1, 4, 7) D52 +detector(2, 5, 7) D53 +detector(2, 7, 7) D54 +detector(3, 4, 7) D55 +detector(3, 6, 7) D56 +detector(4, 3, 7) D57 +detector(4, 5, 7) D58 +detector(5, 6, 7) D59 +detector(1, 4, 8) D60 +detector(2, 5, 8) D61 +detector(2, 7, 8) D62 +detector(3, 4, 8) D63 +detector(3, 6, 8) D64 +detector(4, 3, 8) D65 +detector(4, 5, 8) D66 +detector(5, 6, 8) D67 +detector(1, 4, 9) D68 +detector(2, 5, 9) D69 +detector(2, 7, 9) D70 +detector(3, 4, 9) D71 +detector(3, 6, 9) D72 +detector(4, 3, 9) D73 +detector(4, 5, 9) D74 +detector(5, 6, 9) D75 +detector(1, 4, 10) D76 +detector(2, 5, 10) D77 +detector(2, 7, 10) D78 +detector(3, 4, 10) D79 +detector(3, 6, 10) D80 +detector(4, 3, 10) D81 +detector(4, 5, 10) D82 +detector(5, 6, 10) D83 +detector(1, 4, 11) D84 +detector(2, 5, 11) D85 +detector(2, 7, 11) D86 +detector(3, 4, 11) D87 +detector(3, 6, 11) D88 +detector(4, 3, 11) D89 +detector(4, 5, 11) D90 +detector(5, 6, 11) D91 +detector(1, 4, 12) D92 +detector(2, 5, 12) D93 +detector(2, 7, 12) D94 +detector(3, 4, 12) D95 +detector(3, 6, 12) D96 +detector(4, 3, 12) D97 +detector(4, 5, 12) D98 +detector(5, 6, 12) D99 +detector(1, 4, 13) D100 +detector(3, 4, 13) D101 +detector(3, 6, 13) D102 +detector(5, 6, 13) D103 diff --git a/shared/package-files/7b/7b942b072545566eab1196dd4a27d8041098f9ccd3cd6659e72ecec9facf92cc/blob b/shared/package-files/7b/7b942b072545566eab1196dd4a27d8041098f9ccd3cd6659e72ecec9facf92cc/blob new file mode 100644 index 0000000000000000000000000000000000000000..066393d91eeadcdc08873f4ffeedda0f689337fe --- /dev/null +++ b/shared/package-files/7b/7b942b072545566eab1196dd4a27d8041098f9ccd3cd6659e72ecec9facf92cc/blob @@ -0,0 +1,76 @@ +import io + +import numpy as np +import pytest + +from pandas.compat import is_platform_windows + +import pandas as pd +import pandas._testing as tm + +from pandas.io.excel import ExcelFile +from pandas.io.excel._base import inspect_excel_format + +xlrd = pytest.importorskip("xlrd") + +if is_platform_windows(): + pytestmark = pytest.mark.single_cpu + + +@pytest.fixture(params=[".xls"]) +def read_ext_xlrd(request): + """ + Valid extensions for reading Excel files with xlrd. + + Similar to read_ext, but excludes .ods, .xlsb, and for xlrd>2 .xlsx, .xlsm + """ + return request.param + + +def test_read_xlrd_book(read_ext_xlrd, datapath): + engine = "xlrd" + sheet_name = "Sheet1" + pth = datapath("io", "data", "excel", "test1.xls") + with xlrd.open_workbook(pth) as book: + with ExcelFile(book, engine=engine) as xl: + result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0) + + expected = pd.read_excel( + book, sheet_name=sheet_name, engine=engine, index_col=0 + ) + tm.assert_frame_equal(result, expected) + + +def test_read_xlsx_fails(datapath): + # GH 29375 + from xlrd.biffh import XLRDError + + path = datapath("io", "data", "excel", "test1.xlsx") + with pytest.raises(XLRDError, match="Excel xlsx file; not supported"): + pd.read_excel(path, engine="xlrd") + + +def test_nan_in_xls(datapath): + # GH 54564 + path = datapath("io", "data", "excel", "test6.xls") + + expected = pd.DataFrame({0: np.r_[0, 2].astype("int64"), 1: np.r_[1, np.nan]}) + + result = pd.read_excel(path, header=None) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "file_header", + [ + b"\x09\x00\x04\x00\x07\x00\x10\x00", + b"\x09\x02\x06\x00\x00\x00\x10\x00", + b"\x09\x04\x06\x00\x00\x00\x10\x00", + b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", + ], +) +def test_read_old_xls_files(file_header): + # GH 41226 + f = io.BytesIO(file_header) + assert inspect_excel_format(f) == "xls" diff --git a/shared/package-files/7b/7b9be638af7a9630e8683d591103c443ccf1acbc89fbc25321e320292489238c/blob b/shared/package-files/7b/7b9be638af7a9630e8683d591103c443ccf1acbc89fbc25321e320292489238c/blob new file mode 100644 index 0000000000000000000000000000000000000000..0a88b448c4c8ddbc0676aa839e532d2016f13c1d --- /dev/null +++ b/shared/package-files/7b/7b9be638af7a9630e8683d591103c443ccf1acbc89fbc25321e320292489238c/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API bool is_neg(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/7b/7b9e3ef33dc9c2920ab37ebe348f5559f43d2c49dcc033025c9ac9234c229edf/blob b/shared/package-files/7b/7b9e3ef33dc9c2920ab37ebe348f5559f43d2c49dcc033025c9ac9234c229edf/blob new file mode 100644 index 0000000000000000000000000000000000000000..ba939cffa8fec435f91ff12beb8ab0d751075a51 --- /dev/null +++ b/shared/package-files/7b/7b9e3ef33dc9c2920ab37ebe348f5559f43d2c49dcc033025c9ac9234c229edf/blob @@ -0,0 +1,36 @@ +from typing import Any, Generic, Iterator, TypeVar, overload + +from google.protobuf.descriptor import FieldDescriptor +from google.protobuf.message import Message + +_ContainerMessageT = TypeVar("_ContainerMessageT", bound=Message) +_ExtenderMessageT = TypeVar("_ExtenderMessageT", bound=Message) + +class _ExtensionFieldDescriptor(FieldDescriptor, Generic[_ContainerMessageT, _ExtenderMessageT]): ... + +class _ExtensionDict(Generic[_ContainerMessageT]): + def __init__(self, extended_message: _ContainerMessageT) -> None: ... + # Dummy fallback overloads with FieldDescriptor are for backward compatibility with + # mypy-protobuf <= 1.23. We can drop them a few months after 1.24 releases. + @overload + def __getitem__( + self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT] + ) -> _ExtenderMessageT: ... + @overload + def __getitem__(self, extension_handle: FieldDescriptor) -> Any: ... + @overload + def __setitem__( + self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT], value: _ExtenderMessageT + ) -> None: ... + @overload + def __setitem__(self, extension_handle: FieldDescriptor, value: Any) -> None: ... + @overload + def __delitem__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> None: ... + @overload + def __delitem__(self, extension_handle: FieldDescriptor) -> None: ... + @overload + def __contains__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> bool: ... + @overload + def __contains__(self, extension_handle: FieldDescriptor) -> bool: ... + def __iter__(self) -> Iterator[_ExtensionFieldDescriptor[_ContainerMessageT, Any]]: ... + def __len__(self) -> int: ... diff --git a/shared/package-files/7b/7ba0012e380ff1ffb55d56650d50e7ddc0d4d6739e94e4c8c787d2b9b948e9a7/blob b/shared/package-files/7b/7ba0012e380ff1ffb55d56650d50e7ddc0d4d6739e94e4c8c787d2b9b948e9a7/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c6944f806a2ae77b4a826684a9474769cd18e30 --- /dev/null +++ b/shared/package-files/7b/7ba0012e380ff1ffb55d56650d50e7ddc0d4d6739e94e4c8c787d2b9b948e9a7/blob @@ -0,0 +1,395 @@ +from copy import deepcopy +import inspect +import pydoc + +import numpy as np +import pytest + +from pandas._config import using_string_dtype +from pandas._config.config import option_context + +from pandas.compat import HAS_PYARROW + +import pandas as pd +from pandas import ( + DataFrame, + Series, + date_range, + timedelta_range, +) +import pandas._testing as tm + + +class TestDataFrameMisc: + def test_getitem_pop_assign_name(self, float_frame): + s = float_frame["A"] + assert s.name == "A" + + s = float_frame.pop("A") + assert s.name == "A" + + s = float_frame.loc[:, "B"] + assert s.name == "B" + + s2 = s.loc[:] + assert s2.name == "B" + + def test_get_axis(self, float_frame): + f = float_frame + assert f._get_axis_number(0) == 0 + assert f._get_axis_number(1) == 1 + assert f._get_axis_number("index") == 0 + assert f._get_axis_number("rows") == 0 + assert f._get_axis_number("columns") == 1 + + assert f._get_axis_name(0) == "index" + assert f._get_axis_name(1) == "columns" + assert f._get_axis_name("index") == "index" + assert f._get_axis_name("rows") == "index" + assert f._get_axis_name("columns") == "columns" + + assert f._get_axis(0) is f.index + assert f._get_axis(1) is f.columns + + with pytest.raises(ValueError, match="No axis named"): + f._get_axis_number(2) + + with pytest.raises(ValueError, match="No axis.*foo"): + f._get_axis_name("foo") + + with pytest.raises(ValueError, match="No axis.*None"): + f._get_axis_name(None) + + with pytest.raises(ValueError, match="No axis named"): + f._get_axis_number(None) + + def test_column_contains_raises(self, float_frame): + with pytest.raises(TypeError, match="unhashable type: 'Index'"): + float_frame.columns in float_frame + + def test_tab_completion(self): + # DataFrame whose columns are identifiers shall have them in __dir__. + df = DataFrame([list("abcd"), list("efgh")], columns=list("ABCD")) + for key in list("ABCD"): + assert key in dir(df) + assert isinstance(df.__getitem__("A"), Series) + + # DataFrame whose first-level columns are identifiers shall have + # them in __dir__. + df = DataFrame( + [list("abcd"), list("efgh")], + columns=pd.MultiIndex.from_tuples(list(zip("ABCD", "EFGH"))), + ) + for key in list("ABCD"): + assert key in dir(df) + for key in list("EFGH"): + assert key not in dir(df) + assert isinstance(df.__getitem__("A"), DataFrame) + + def test_display_max_dir_items(self): + # display.max_dir_items increaes the number of columns that are in __dir__. + columns = ["a" + str(i) for i in range(420)] + values = [range(420), range(420)] + df = DataFrame(values, columns=columns) + + # The default value for display.max_dir_items is 100 + assert "a99" in dir(df) + assert "a100" not in dir(df) + + with option_context("display.max_dir_items", 300): + df = DataFrame(values, columns=columns) + assert "a299" in dir(df) + assert "a300" not in dir(df) + + with option_context("display.max_dir_items", None): + df = DataFrame(values, columns=columns) + assert "a419" in dir(df) + + def test_not_hashable(self): + empty_frame = DataFrame() + + df = DataFrame([1]) + msg = "unhashable type: 'DataFrame'" + with pytest.raises(TypeError, match=msg): + hash(df) + with pytest.raises(TypeError, match=msg): + hash(empty_frame) + + @pytest.mark.xfail( + using_string_dtype() and HAS_PYARROW, reason="surrogates not allowed" + ) + def test_column_name_contains_unicode_surrogate(self): + # GH 25509 + colname = "\ud83d" + df = DataFrame({colname: []}) + # this should not crash + assert colname not in dir(df) + assert df.columns[0] == colname + + def test_new_empty_index(self): + df1 = DataFrame(np.random.default_rng(2).standard_normal((0, 3))) + df2 = DataFrame(np.random.default_rng(2).standard_normal((0, 3))) + df1.index.name = "foo" + assert df2.index.name is None + + def test_get_agg_axis(self, float_frame): + cols = float_frame._get_agg_axis(0) + assert cols is float_frame.columns + + idx = float_frame._get_agg_axis(1) + assert idx is float_frame.index + + msg = r"Axis must be 0 or 1 \(got 2\)" + with pytest.raises(ValueError, match=msg): + float_frame._get_agg_axis(2) + + def test_empty(self, float_frame, float_string_frame): + empty_frame = DataFrame() + assert empty_frame.empty + + assert not float_frame.empty + assert not float_string_frame.empty + + # corner case + df = DataFrame({"A": [1.0, 2.0, 3.0], "B": ["a", "b", "c"]}, index=np.arange(3)) + del df["A"] + assert not df.empty + + def test_len(self, float_frame): + assert len(float_frame) == len(float_frame.index) + + # single block corner case + arr = float_frame[["A", "B"]].values + expected = float_frame.reindex(columns=["A", "B"]).values + tm.assert_almost_equal(arr, expected) + + def test_axis_aliases(self, float_frame): + f = float_frame + + # reg name + expected = f.sum(axis=0) + result = f.sum(axis="index") + tm.assert_series_equal(result, expected) + + expected = f.sum(axis=1) + result = f.sum(axis="columns") + tm.assert_series_equal(result, expected) + + def test_class_axis(self): + # GH 18147 + # no exception and no empty docstring + assert pydoc.getdoc(DataFrame.index) + assert pydoc.getdoc(DataFrame.columns) + + def test_series_put_names(self, float_string_frame): + series = float_string_frame._series + for k, v in series.items(): + assert v.name == k + + def test_empty_nonzero(self): + df = DataFrame([1, 2, 3]) + assert not df.empty + df = DataFrame(index=[1], columns=[1]) + assert not df.empty + df = DataFrame(index=["a", "b"], columns=["c", "d"]).dropna() + assert df.empty + assert df.T.empty + + @pytest.mark.parametrize( + "df", + [ + DataFrame(), + DataFrame(index=[1]), + DataFrame(columns=[1]), + DataFrame({1: []}), + ], + ) + def test_empty_like(self, df): + assert df.empty + assert df.T.empty + + def test_with_datetimelikes(self): + df = DataFrame( + { + "A": date_range("20130101", periods=10), + "B": timedelta_range("1 day", periods=10), + } + ) + t = df.T + + result = t.dtypes.value_counts() + expected = Series({np.dtype("object"): 10}, name="count") + tm.assert_series_equal(result, expected) + + def test_deepcopy(self, float_frame): + cp = deepcopy(float_frame) + cp.loc[0, "A"] = 10 + assert not float_frame.equals(cp) + + def test_inplace_return_self(self): + # GH 1893 + + data = DataFrame( + {"a": ["foo", "bar", "baz", "qux"], "b": [0, 0, 1, 1], "c": [1, 2, 3, 4]} + ) + + def _check_f(base, f): + result = f(base) + assert result is None + + # -----DataFrame----- + + # set_index + f = lambda x: x.set_index("a", inplace=True) + _check_f(data.copy(), f) + + # reset_index + f = lambda x: x.reset_index(inplace=True) + _check_f(data.set_index("a"), f) + + # drop_duplicates + f = lambda x: x.drop_duplicates(inplace=True) + _check_f(data.copy(), f) + + # sort + f = lambda x: x.sort_values("b", inplace=True) + _check_f(data.copy(), f) + + # sort_index + f = lambda x: x.sort_index(inplace=True) + _check_f(data.copy(), f) + + # fillna + f = lambda x: x.fillna(0, inplace=True) + _check_f(data.copy(), f) + + # replace + f = lambda x: x.replace(1, 0, inplace=True) + _check_f(data.copy(), f) + + # rename + f = lambda x: x.rename({1: "foo"}, inplace=True) + _check_f(data.copy(), f) + + # -----Series----- + d = data.copy()["c"] + + # reset_index + f = lambda x: x.reset_index(inplace=True, drop=True) + _check_f(data.set_index("a")["c"], f) + + # fillna + f = lambda x: x.fillna(0, inplace=True) + _check_f(d.copy(), f) + + # replace + f = lambda x: x.replace(1, 0, inplace=True) + _check_f(d.copy(), f) + + # rename + f = lambda x: x.rename({1: "foo"}, inplace=True) + _check_f(d.copy(), f) + + def test_tab_complete_warning(self, ip, frame_or_series): + # GH 16409 + pytest.importorskip("IPython", minversion="6.0.0") + from IPython.core.completer import provisionalcompleter + + if frame_or_series is DataFrame: + code = "from pandas import DataFrame; obj = DataFrame()" + else: + code = "from pandas import Series; obj = Series(dtype=object)" + + ip.run_cell(code) + # GH 31324 newer jedi version raises Deprecation warning; + # appears resolved 2021-02-02 + with tm.assert_produces_warning(None, raise_on_extra_warnings=False): + with provisionalcompleter("ignore"): + list(ip.Completer.completions("obj.", 1)) + + def test_attrs(self): + df = DataFrame({"A": [2, 3]}) + assert df.attrs == {} + df.attrs["version"] = 1 + + result = df.rename(columns=str) + assert result.attrs == {"version": 1} + + def test_attrs_deepcopy(self): + df = DataFrame({"A": [2, 3]}) + assert df.attrs == {} + df.attrs["tags"] = {"spam", "ham"} + + result = df.rename(columns=str) + assert result.attrs == df.attrs + assert result.attrs["tags"] is not df.attrs["tags"] + + @pytest.mark.parametrize("allows_duplicate_labels", [True, False, None]) + def test_set_flags( + self, + allows_duplicate_labels, + frame_or_series, + using_copy_on_write, + warn_copy_on_write, + ): + obj = DataFrame({"A": [1, 2]}) + key = (0, 0) + if frame_or_series is Series: + obj = obj["A"] + key = 0 + + result = obj.set_flags(allows_duplicate_labels=allows_duplicate_labels) + + if allows_duplicate_labels is None: + # We don't update when it's not provided + assert result.flags.allows_duplicate_labels is True + else: + assert result.flags.allows_duplicate_labels is allows_duplicate_labels + + # We made a copy + assert obj is not result + + # We didn't mutate obj + assert obj.flags.allows_duplicate_labels is True + + # But we didn't copy data + if frame_or_series is Series: + assert np.may_share_memory(obj.values, result.values) + else: + assert np.may_share_memory(obj["A"].values, result["A"].values) + + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[key] = 0 + if using_copy_on_write: + assert obj.iloc[key] == 1 + else: + assert obj.iloc[key] == 0 + # set back to 1 for test below + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[key] = 1 + + # Now we do copy. + result = obj.set_flags( + copy=True, allows_duplicate_labels=allows_duplicate_labels + ) + result.iloc[key] = 10 + assert obj.iloc[key] == 1 + + def test_constructor_expanddim(self): + # GH#33628 accessing _constructor_expanddim should not raise NotImplementedError + # GH38782 pandas has no container higher than DataFrame (two-dim), so + # DataFrame._constructor_expand_dim, doesn't make sense, so is removed. + df = DataFrame() + + msg = "'DataFrame' object has no attribute '_constructor_expanddim'" + with pytest.raises(AttributeError, match=msg): + df._constructor_expanddim(np.arange(27).reshape(3, 3, 3)) + + def test_inspect_getmembers(self): + # GH38740 + df = DataFrame() + msg = "DataFrame._data is deprecated" + with tm.assert_produces_warning( + DeprecationWarning, match=msg, check_stacklevel=False + ): + inspect.getmembers(df) diff --git a/shared/package-files/7b/7ba46fb29b0241762cc54bae509baa92bd7656201c3b6324cfe3a9710626c627/blob b/shared/package-files/7b/7ba46fb29b0241762cc54bae509baa92bd7656201c3b6324cfe3a9710626c627/blob new file mode 100644 index 0000000000000000000000000000000000000000..66ef337248e80b63e464990133f554a36b00a4da --- /dev/null +++ b/shared/package-files/7b/7ba46fb29b0241762cc54bae509baa92bd7656201c3b6324cfe3a9710626c627/blob @@ -0,0 +1,68 @@ +# coding: utf-8 +"""Compatibility tricks for Python 3. Mainly to do with unicode. + +This file is deprecated and will be removed in a future version. +""" +import platform +import builtins as builtin_mod + +from .encoding import DEFAULT_ENCODING + + +def decode(s, encoding=None): + encoding = encoding or DEFAULT_ENCODING + return s.decode(encoding, "replace") + + +def encode(u, encoding=None): + encoding = encoding or DEFAULT_ENCODING + return u.encode(encoding, "replace") + + +def cast_unicode(s, encoding=None): + if isinstance(s, bytes): + return decode(s, encoding) + return s + + +def safe_unicode(e): + """unicode(e) with various fallbacks. Used for exceptions, which may not be + safe to call unicode() on. + """ + try: + return str(e) + except UnicodeError: + pass + + try: + return repr(e) + except UnicodeError: + pass + + return "Unrecoverably corrupt evalue" + + +# keep reference to builtin_mod because the kernel overrides that value +# to forward requests to a frontend. +def input(prompt=""): + return builtin_mod.input(prompt) + + +def execfile(fname, glob, loc=None, compiler=None): + loc = loc if (loc is not None) else glob + with open(fname, "rb") as f: + compiler = compiler or compile + exec(compiler(f.read(), fname, "exec"), glob, loc) + + +PYPY = platform.python_implementation() == "PyPy" + + +# Cython still rely on that as a Dec 28 2019 +# See https://github.com/cython/cython/pull/3291 and +# https://github.com/ipython/ipython/issues/12068 +def no_code(x, encoding=None): + return x + + +unicode_to_str = cast_bytes_py2 = no_code diff --git a/shared/package-files/7b/7ba762b69615c9282c2e26ac8de97b7e1ed3f61db446f9344093e5210336232d/blob b/shared/package-files/7b/7ba762b69615c9282c2e26ac8de97b7e1ed3f61db446f9344093e5210336232d/blob new file mode 100644 index 0000000000000000000000000000000000000000..132bd5e78096e4554637fac3d224db9cc8543ce2 --- /dev/null +++ b/shared/package-files/7b/7ba762b69615c9282c2e26ac8de97b7e1ed3f61db446f9344093e5210336232d/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _cast_Half { + using schema = at::Tensor (const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cast_Half") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cast_Half(Tensor self, bool non_blocking=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, bool non_blocking); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7b/7ba78cfabed7aef8e9da51add670b448e8f9eaefe6daeeb2b1dd270655cc3f4b/blob b/shared/package-files/7b/7ba78cfabed7aef8e9da51add670b448e8f9eaefe6daeeb2b1dd270655cc3f4b/blob new file mode 100644 index 0000000000000000000000000000000000000000..94b3c9c679969b5bf3b6e9581fb06125d236c1fb --- /dev/null +++ b/shared/package-files/7b/7ba78cfabed7aef8e9da51add670b448e8f9eaefe6daeeb2b1dd270655cc3f4b/blob @@ -0,0 +1,15 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace py = pybind11; + +namespace pybind11 { +namespace detail {} +} // namespace pybind11 diff --git a/shared/package-files/7b/7ba83186dfa735464ad89fc4d009221296ba51d2a55c9039730c22bb95db5d57/blob b/shared/package-files/7b/7ba83186dfa735464ad89fc4d009221296ba51d2a55c9039730c22bb95db5d57/blob new file mode 100644 index 0000000000000000000000000000000000000000..2a7970ba4c283e851430ed0025e1ed5c772eb7b1 --- /dev/null +++ b/shared/package-files/7b/7ba83186dfa735464ad89fc4d009221296ba51d2a55c9039730c22bb95db5d57/blob @@ -0,0 +1 @@ +from .common import lift_subgraph_as_module, HolderModule, compare_graphs diff --git a/shared/package-files/7b/7ba9a48b87bc3276f8950458a1e6d80857550ac50a538bc78473abf7e83326c9/blob b/shared/package-files/7b/7ba9a48b87bc3276f8950458a1e6d80857550ac50a538bc78473abf7e83326c9/blob new file mode 100644 index 0000000000000000000000000000000000000000..017a2fb7dadfb2146ca629373b9a9d3506ad3b71 --- /dev/null +++ b/shared/package-files/7b/7ba9a48b87bc3276f8950458a1e6d80857550ac50a538bc78473abf7e83326c9/blob @@ -0,0 +1,339 @@ +"""Module for handling symbolic function registration.""" + +import warnings +from typing import ( + Callable, + Collection, + Dict, + Generic, + Optional, + Sequence, + Set, + TypeVar, + Union, +) + +from torch.onnx import _constants, errors +from torch.onnx._internal import _beartype + +OpsetVersion = int + + +def _dispatch_opset_version( + target: OpsetVersion, registered_opsets: Collection[OpsetVersion] +) -> Optional[OpsetVersion]: + """Finds the registered opset given a target opset version and the available opsets. + + Args: + target: The target opset version. + registered_opsets: The available opsets. + + Returns: + The registered opset version. + """ + if not registered_opsets: + return None + + descending_registered_versions = sorted(registered_opsets, reverse=True) + # Linear search for the opset version, which is fine since the number of opset + # versions is small. + + if target >= _constants.ONNX_BASE_OPSET: + # Always look down toward opset 1 when the target is >= ONNX_BASE_OPSET (opset 9). + # When a custom op is register at opset 1, we want to be able to discover it as a + # fallback for all opsets >= ONNX_BASE_OPSET. + for version in descending_registered_versions: + if version <= target: + return version + return None + + # target < opset 9. This is the legacy behavior to support opset 7 and opset 8. + # for caffe2 support. We search up toward opset 9. + for version in reversed(descending_registered_versions): + # Count back up until _constants.ONNX_BASE_OPSET + if target <= version <= _constants.ONNX_BASE_OPSET: + return version + + return None + + +_K = TypeVar("_K") +_V = TypeVar("_V") + + +class OverrideDict(Generic[_K, _V], Collection[_K]): + """A dictionary that merges built-in and custom symbolic functions. + + It supports overriding and un-overriding built-in symbolic functions with custom + ones. + """ + + def __init__(self): + self._base: Dict[_K, _V] = {} + self._overrides: Dict[_K, _V] = {} + self._merged: Dict[_K, _V] = {} + + def set_base(self, key: _K, value: _V) -> None: + self._base[key] = value + if key not in self._overrides: + self._merged[key] = value + + def in_base(self, key: _K) -> bool: + """Checks if a key is in the base dictionary.""" + return key in self._base + + def override(self, key: _K, value: _V) -> None: + """Overrides a base key-value with a new pair.""" + self._overrides[key] = value + self._merged[key] = value + + def remove_override(self, key: _K) -> None: + """Un-overrides a key-value pair.""" + self._overrides.pop(key, None) # type: ignore[arg-type] + self._merged.pop(key, None) # type: ignore[arg-type] + if key in self._base: + self._merged[key] = self._base[key] + + def overridden(self, key: _K) -> bool: + """Checks if a key-value pair is overridden.""" + return key in self._overrides + + def __getitem__(self, key: _K) -> _V: + return self._merged[key] + + def get(self, key: _K, default: Optional[_V] = None): + return self._merged.get(key, default) + + def __contains__(self, key: object) -> bool: + return key in self._merged + + def __iter__(self): + return iter(self._merged) + + def __len__(self) -> int: + return len(self._merged) + + def __repr__(self) -> str: + return f"OverrideDict(base={self._base}, overrides={self._overrides})" + + def __bool__(self) -> bool: + return bool(self._merged) + + +class _SymbolicFunctionGroup: + """Different versions of symbolic functions registered to the same name. + + O(number of registered versions of an op) search is performed to find the most + recent version of the op. + + The registration is delayed until op is used to improve startup time. + + Function overloads with different arguments are not allowed. + Custom op overrides are supported. + """ + + def __init__(self, name: str) -> None: + self._name = name + # A dictionary of functions, keyed by the opset version. + self._functions: OverrideDict[OpsetVersion, Callable] = OverrideDict() + + def __repr__(self) -> str: + return f"_SymbolicFunctionGroup({self._name}, registered={self._functions})" + + def __getitem__(self, key: OpsetVersion) -> Callable: + result = self.get(key) + if result is None: + raise KeyError(key) + return result + + # TODO(justinchuby): Add @functools.lru_cache(maxsize=None) if lookup time becomes + # a problem. + def get(self, opset: OpsetVersion) -> Optional[Callable]: + """Find the most recent version of the function.""" + version = _dispatch_opset_version(opset, self._functions) + if version is None: + return None + + return self._functions[version] + + def add(self, func: Callable, opset: OpsetVersion) -> None: + """Adds a symbolic function. + + Args: + func: The function to add. + opset: The opset version of the function to add. + """ + if self._functions.in_base(opset): + warnings.warn( + f"Symbolic function '{self._name}' already registered for opset {opset}. " + f"Replacing the existing function with new function. This is unexpected. " + f"Please report it on {_constants.PYTORCH_GITHUB_ISSUES_URL}.", + errors.OnnxExporterWarning, + ) + self._functions.set_base(opset, func) + + def add_custom(self, func: Callable, opset: OpsetVersion) -> None: + """Adds a custom symbolic function. + + Args: + func: The symbolic function to register. + opset: The corresponding opset version. + """ + self._functions.override(opset, func) + + def remove_custom(self, opset: OpsetVersion) -> None: + """Removes a custom symbolic function. + + Args: + opset: The opset version of the custom function to remove. + """ + if not self._functions.overridden(opset): + warnings.warn( + f"No custom function registered for '{self._name}' opset {opset}" + ) + return + self._functions.remove_override(opset) + + def get_min_supported(self) -> OpsetVersion: + """Returns the lowest built-in opset version supported by the function.""" + return min(self._functions) + + +class SymbolicRegistry: + """Registry for symbolic functions. + + The registry maintains a mapping from qualified names to symbolic functions. + It is used to register new symbolic functions and to dispatch calls to + the appropriate function. + """ + + def __init__(self) -> None: + self._registry: Dict[str, _SymbolicFunctionGroup] = {} + + def register( + self, name: str, opset: OpsetVersion, func: Callable, custom: bool = False + ) -> None: + """Registers a symbolic function. + + Args: + name: The qualified name of the function to register. In the form of 'domain::op'. + E.g. 'aten::add'. + opset: The opset version of the function to register. + func: The symbolic function to register. + custom: Whether the function is a custom function that overrides existing ones. + + Raises: + ValueError: If the separator '::' is not in the name. + """ + if "::" not in name: + raise ValueError( + f"The name must be in the form of 'domain::op', not '{name}'" + ) + symbolic_functions = self._registry.setdefault( + name, _SymbolicFunctionGroup(name) + ) + if custom: + symbolic_functions.add_custom(func, opset) + else: + symbolic_functions.add(func, opset) + + def unregister(self, name: str, opset: OpsetVersion) -> None: + """Unregisters a symbolic function. + + Args: + name: The qualified name of the function to unregister. + opset: The opset version of the function to unregister. + """ + if name not in self._registry: + return + self._registry[name].remove_custom(opset) + + def get_function_group(self, name: str) -> Optional[_SymbolicFunctionGroup]: + """Returns the function group for the given name.""" + return self._registry.get(name) + + def is_registered_op(self, name: str, version: int) -> bool: + """Returns whether the given op is registered for the given opset version.""" + functions = self.get_function_group(name) + if functions is None: + return False + return functions.get(version) is not None + + def all_functions(self) -> Set[str]: + """Returns the set of all registered function names.""" + return set(self._registry) + + +@_beartype.beartype +def onnx_symbolic( + name: str, + opset: Union[OpsetVersion, Sequence[OpsetVersion]], + decorate: Optional[Sequence[Callable]] = None, + custom: bool = False, +) -> Callable: + """Registers a symbolic function. + + Usage:: + + ``` + @onnx_symbolic("aten::symbolic_b", opset=10, decorate=[quantized_aten_handler(scale=1/128, zero_point=0)]) + @symbolic_helper.parse_args("v", "v", "b") + def symbolic_b(g: _C.Graph, x: _C.Value, y: _C.Value, arg1: bool) -> _C.Value: + ... + ``` + + Args: + name: The qualified name of the function in the form of 'domain::op'. + E.g. 'aten::add'. + opset: The opset versions of the function to register at. + decorate: A sequence of decorators to apply to the function. + custom: Whether the function is a custom symbolic function. + + Raises: + ValueError: If the separator '::' is not in the name. + """ + + def wrapper(func: Callable) -> Callable: + decorated = func + if decorate is not None: + for decorate_func in decorate: + decorated = decorate_func(decorated) + + global registry + nonlocal opset + if isinstance(opset, OpsetVersion): + opset = (opset,) + for opset_version in opset: + registry.register(name, opset_version, decorated, custom=custom) + + # Return the original function because the decorators in "decorate" are only + # specific to the instance being registered. + return func + + return wrapper + + +@_beartype.beartype +def custom_onnx_symbolic( + name: str, + opset: Union[OpsetVersion, Sequence[OpsetVersion]], + decorate: Optional[Sequence[Callable]] = None, +) -> Callable: + """Registers a custom symbolic function. + + Args: + name: the qualified name of the function. + opset: the opset version of the function. + decorate: a sequence of decorators to apply to the function. + + Returns: + The decorator. + + Raises: + ValueError: If the separator '::' is not in the name. + """ + return onnx_symbolic(name, opset, decorate, custom=True) + + +# The registry for all symbolic functions. +registry = SymbolicRegistry() diff --git a/shared/package-files/7b/7bacf240915ee1026073a9942b766a3aa4532865eafd0c492d72ecdefc954075/blob b/shared/package-files/7b/7bacf240915ee1026073a9942b766a3aa4532865eafd0c492d72ecdefc954075/blob new file mode 100644 index 0000000000000000000000000000000000000000..73e84fba3763e3d96c57df155241153a9827e253 --- /dev/null +++ b/shared/package-files/7b/7bacf240915ee1026073a9942b766a3aa4532865eafd0c492d72ecdefc954075/blob @@ -0,0 +1,15 @@ +from _curses import * # noqa: F403 +from _curses import _CursesWindow as _CursesWindow +from typing import Any, Callable, TypeVar + +_T = TypeVar("_T") + +# available after calling `curses.initscr()` +LINES: int +COLS: int + +# available after calling `curses.start_color()` +COLORS: int +COLOR_PAIRS: int + +def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... diff --git a/shared/package-files/7b/7badd0ca2b759270eee3e6fefba817d6d858ec2810769abe6f5a15299b5e58a9/blob b/shared/package-files/7b/7badd0ca2b759270eee3e6fefba817d6d858ec2810769abe6f5a15299b5e58a9/blob new file mode 100644 index 0000000000000000000000000000000000000000..c67583b0ce9466aabf7a0dc49af41acaf5535a81 --- /dev/null +++ b/shared/package-files/7b/7badd0ca2b759270eee3e6fefba817d6d858ec2810769abe6f5a15299b5e58a9/blob @@ -0,0 +1,131 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::ones.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor ones(at::IntArrayRef size, c10::optional names, at::TensorOptions options={}) { + return at::_ops::ones_names::call(size, names, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::ones.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor ones(at::IntArrayRef size, c10::optional names, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::ones_names::call(size, names, dtype, layout, device, pin_memory); +} + +// aten::ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor ones(at::IntArrayRef size, at::TensorOptions options={}) { + return at::_ops::ones::call(c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +namespace symint { + template ::value>> + at::Tensor ones(at::IntArrayRef size, at::TensorOptions options={}) { + return at::_ops::ones::call(c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); + } +} + +// aten::ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor ones(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::ones::call(c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); +} +namespace symint { + template ::value>> + at::Tensor ones(at::IntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::ones::call(c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); + } +} + +// aten::ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor ones_symint(c10::SymIntArrayRef size, at::TensorOptions options={}) { + return at::_ops::ones::call(size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +namespace symint { + template ::value>> + at::Tensor ones(c10::SymIntArrayRef size, at::TensorOptions options={}) { + return at::_ops::ones::call(size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); + } +} + +// aten::ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor ones_symint(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::ones::call(size, dtype, layout, device, pin_memory); +} +namespace symint { + template ::value>> + at::Tensor ones(c10::SymIntArrayRef size, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::ones::call(size, dtype, layout, device, pin_memory); + } +} + +// aten::ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ones_out(at::Tensor & out, at::IntArrayRef size) { + return at::_ops::ones_out::call(c10::fromIntArrayRefSlow(size), out); +} +namespace symint { + template ::value>> + at::Tensor & ones_out(at::Tensor & out, at::IntArrayRef size) { + return at::_ops::ones_out::call(c10::fromIntArrayRefSlow(size), out); + } +} + +// aten::ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ones_outf(at::IntArrayRef size, at::Tensor & out) { + return at::_ops::ones_out::call(c10::fromIntArrayRefSlow(size), out); +} +namespace symint { + template ::value>> + at::Tensor & ones_outf(at::IntArrayRef size, at::Tensor & out) { + return at::_ops::ones_out::call(c10::fromIntArrayRefSlow(size), out); + } +} + +// aten::ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ones_symint_out(at::Tensor & out, c10::SymIntArrayRef size) { + return at::_ops::ones_out::call(size, out); +} +namespace symint { + template ::value>> + at::Tensor & ones_out(at::Tensor & out, c10::SymIntArrayRef size) { + return at::_ops::ones_out::call(size, out); + } +} + +// aten::ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ones_symint_outf(c10::SymIntArrayRef size, at::Tensor & out) { + return at::_ops::ones_out::call(size, out); +} +namespace symint { + template ::value>> + at::Tensor & ones_outf(c10::SymIntArrayRef size, at::Tensor & out) { + return at::_ops::ones_out::call(size, out); + } +} + +// aten::ones.names_out(int[] size, *, Dimname[]? names, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ones_out(at::Tensor & out, at::IntArrayRef size, c10::optional names) { + return at::_ops::ones_names_out::call(size, names, out); +} +// aten::ones.names_out(int[] size, *, Dimname[]? names, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ones_outf(at::IntArrayRef size, c10::optional names, at::Tensor & out) { + return at::_ops::ones_names_out::call(size, names, out); +} + +} diff --git a/shared/package-files/7b/7bae6e723db12d186c8c332a898b7eb16aca6b0b4b0546d4a23d0e4bcb4300b7/blob b/shared/package-files/7b/7bae6e723db12d186c8c332a898b7eb16aca6b0b4b0546d4a23d0e4bcb4300b7/blob new file mode 100644 index 0000000000000000000000000000000000000000..1174366e885e5a4b44110887a0da35c7c56f37b3 --- /dev/null +++ b/shared/package-files/7b/7bae6e723db12d186c8c332a898b7eb16aca6b0b4b0546d4a23d0e4bcb4300b7/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::signbit(Tensor self) -> Tensor +inline at::Tensor signbit(const at::Tensor & self) { + return at::_ops::signbit::call(self); +} + +// aten::signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & signbit_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::signbit_out::call(self, out); +} +// aten::signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & signbit_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::signbit_out::call(self, out); +} + +} diff --git a/shared/package-files/7b/7bb5f648228dbc986238570dd8b30c833b3020a3673b97a62dd33c66d70ee507/blob b/shared/package-files/7b/7bb5f648228dbc986238570dd8b30c833b3020a3673b97a62dd33c66d70ee507/blob new file mode 100644 index 0000000000000000000000000000000000000000..e7edf9837f1cba0810a1b98904fedd694a198495 --- /dev/null +++ b/shared/package-files/7b/7bb5f648228dbc986238570dd8b30c833b3020a3673b97a62dd33c66d70ee507/blob @@ -0,0 +1,299 @@ +"""Nose Plugin that supports IPython doctests. + +Limitations: + +- When generating examples for use as doctests, make sure that you have + pretty-printing OFF. This can be done either by setting the + ``PlainTextFormatter.pprint`` option in your configuration file to False, or + by interactively disabling it with %Pprint. This is required so that IPython + output matches that of normal Python, which is used by doctest for internal + execution. + +- Do not rely on specific prompt numbers for results (such as using + '_34==True', for example). For IPython tests run via an external process the + prompt numbers may be different, and IPython tests run as normal python code + won't even have these special _NN variables set at all. +""" + +#----------------------------------------------------------------------------- +# Module imports + +# From the standard library +import doctest +import logging +import re + +from testpath import modified_env + +#----------------------------------------------------------------------------- +# Module globals and other constants +#----------------------------------------------------------------------------- + +log = logging.getLogger(__name__) + + +#----------------------------------------------------------------------------- +# Classes and functions +#----------------------------------------------------------------------------- + + +class DocTestFinder(doctest.DocTestFinder): + def _get_test(self, obj, name, module, globs, source_lines): + test = super()._get_test(obj, name, module, globs, source_lines) + + if bool(getattr(obj, "__skip_doctest__", False)) and test is not None: + for example in test.examples: + example.options[doctest.SKIP] = True + + return test + + +class IPDoctestOutputChecker(doctest.OutputChecker): + """Second-chance checker with support for random tests. + + If the default comparison doesn't pass, this checker looks in the expected + output string for flags that tell us to ignore the output. + """ + + random_re = re.compile(r'#\s*random\s+') + + def check_output(self, want, got, optionflags): + """Check output, accepting special markers embedded in the output. + + If the output didn't pass the default validation but the special string + '#random' is included, we accept it.""" + + # Let the original tester verify first, in case people have valid tests + # that happen to have a comment saying '#random' embedded in. + ret = doctest.OutputChecker.check_output(self, want, got, + optionflags) + if not ret and self.random_re.search(want): + #print >> sys.stderr, 'RANDOM OK:',want # dbg + return True + + return ret + + +# A simple subclassing of the original with a different class name, so we can +# distinguish and treat differently IPython examples from pure python ones. +class IPExample(doctest.Example): pass + + +class IPDocTestParser(doctest.DocTestParser): + """ + A class used to parse strings containing doctest examples. + + Note: This is a version modified to properly recognize IPython input and + convert any IPython examples into valid Python ones. + """ + # This regular expression is used to find doctest examples in a + # string. It defines three groups: `source` is the source code + # (including leading indentation and prompts); `indent` is the + # indentation of the first (PS1) line of the source code; and + # `want` is the expected output (including leading indentation). + + # Classic Python prompts or default IPython ones + _PS1_PY = r'>>>' + _PS2_PY = r'\.\.\.' + + _PS1_IP = r'In\ \[\d+\]:' + _PS2_IP = r'\ \ \ \.\.\.+:' + + _RE_TPL = r''' + # Source consists of a PS1 line followed by zero or more PS2 lines. + (?P + (?:^(?P [ ]*) (?P %s) .*) # PS1 line + (?:\n [ ]* (?P %s) .*)*) # PS2 lines + \n? # a newline + # Want consists of any non-blank lines that do not start with PS1. + (?P (?:(?![ ]*$) # Not a blank line + (?![ ]*%s) # Not a line starting with PS1 + (?![ ]*%s) # Not a line starting with PS2 + .*$\n? # But any other line + )*) + ''' + + _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY), + re.MULTILINE | re.VERBOSE) + + _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP), + re.MULTILINE | re.VERBOSE) + + # Mark a test as being fully random. In this case, we simply append the + # random marker ('#random') to each individual example's output. This way + # we don't need to modify any other code. + _RANDOM_TEST = re.compile(r'#\s*all-random\s+') + + def ip2py(self,source): + """Convert input IPython source into valid Python.""" + block = _ip.input_transformer_manager.transform_cell(source) + if len(block.splitlines()) == 1: + return _ip.prefilter(block) + else: + return block + + def parse(self, string, name=''): + """ + Divide the given string into examples and intervening text, + and return them as a list of alternating Examples and strings. + Line numbers for the Examples are 0-based. The optional + argument `name` is a name identifying this string, and is only + used for error messages. + """ + + #print 'Parse string:\n',string # dbg + + string = string.expandtabs() + # If all lines begin with the same indentation, then strip it. + min_indent = self._min_indent(string) + if min_indent > 0: + string = '\n'.join([l[min_indent:] for l in string.split('\n')]) + + output = [] + charno, lineno = 0, 0 + + # We make 'all random' tests by adding the '# random' mark to every + # block of output in the test. + if self._RANDOM_TEST.search(string): + random_marker = '\n# random' + else: + random_marker = '' + + # Whether to convert the input from ipython to python syntax + ip2py = False + # Find all doctest examples in the string. First, try them as Python + # examples, then as IPython ones + terms = list(self._EXAMPLE_RE_PY.finditer(string)) + if terms: + # Normal Python example + Example = doctest.Example + else: + # It's an ipython example. + terms = list(self._EXAMPLE_RE_IP.finditer(string)) + Example = IPExample + ip2py = True + + for m in terms: + # Add the pre-example text to `output`. + output.append(string[charno:m.start()]) + # Update lineno (lines before this example) + lineno += string.count('\n', charno, m.start()) + # Extract info from the regexp match. + (source, options, want, exc_msg) = \ + self._parse_example(m, name, lineno,ip2py) + + # Append the random-output marker (it defaults to empty in most + # cases, it's only non-empty for 'all-random' tests): + want += random_marker + + # Create an Example, and add it to the list. + if not self._IS_BLANK_OR_COMMENT(source): + output.append(Example(source, want, exc_msg, + lineno=lineno, + indent=min_indent+len(m.group('indent')), + options=options)) + # Update lineno (lines inside this example) + lineno += string.count('\n', m.start(), m.end()) + # Update charno. + charno = m.end() + # Add any remaining post-example text to `output`. + output.append(string[charno:]) + return output + + def _parse_example(self, m, name, lineno,ip2py=False): + """ + Given a regular expression match from `_EXAMPLE_RE` (`m`), + return a pair `(source, want)`, where `source` is the matched + example's source code (with prompts and indentation stripped); + and `want` is the example's expected output (with indentation + stripped). + + `name` is the string's name, and `lineno` is the line number + where the example starts; both are used for error messages. + + Optional: + `ip2py`: if true, filter the input via IPython to convert the syntax + into valid python. + """ + + # Get the example's indentation level. + indent = len(m.group('indent')) + + # Divide source into lines; check that they're properly + # indented; and then strip their indentation & prompts. + source_lines = m.group('source').split('\n') + + # We're using variable-length input prompts + ps1 = m.group('ps1') + ps2 = m.group('ps2') + ps1_len = len(ps1) + + self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len) + if ps2: + self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno) + + source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines]) + + if ip2py: + # Convert source input from IPython into valid Python syntax + source = self.ip2py(source) + + # Divide want into lines; check that it's properly indented; and + # then strip the indentation. Spaces before the last newline should + # be preserved, so plain rstrip() isn't good enough. + want = m.group('want') + want_lines = want.split('\n') + if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): + del want_lines[-1] # forget final newline & spaces after it + self._check_prefix(want_lines, ' '*indent, name, + lineno + len(source_lines)) + + # Remove ipython output prompt that might be present in the first line + want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0]) + + want = '\n'.join([wl[indent:] for wl in want_lines]) + + # If `want` contains a traceback message, then extract it. + m = self._EXCEPTION_RE.match(want) + if m: + exc_msg = m.group('msg') + else: + exc_msg = None + + # Extract options from the source. + options = self._find_options(source, name, lineno) + + return source, options, want, exc_msg + + def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len): + """ + Given the lines of a source string (including prompts and + leading indentation), check to make sure that every prompt is + followed by a space character. If any line is not followed by + a space character, then raise ValueError. + + Note: IPython-modified version which takes the input prompt length as a + parameter, so that prompts of variable length can be dealt with. + """ + space_idx = indent+ps1_len + min_len = space_idx+1 + for i, line in enumerate(lines): + if len(line) >= min_len and line[space_idx] != ' ': + raise ValueError('line %r of the docstring for %s ' + 'lacks blank after %s: %r' % + (lineno+i+1, name, + line[indent:space_idx], line)) + + +SKIP = doctest.register_optionflag('SKIP') + + +class IPDocTestRunner(doctest.DocTestRunner,object): + """Test runner that synchronizes the IPython namespace with test globals. + """ + + def run(self, test, compileflags=None, out=None, clear_globs=True): + # Override terminal size to standardise traceback format + with modified_env({'COLUMNS': '80', 'LINES': '24'}): + return super(IPDocTestRunner,self).run(test, + compileflags,out,clear_globs) diff --git a/shared/package-files/7b/7bb63838ebab29adde3323a759a37e7ba61038cd7ba274c44944630e9594612e/blob b/shared/package-files/7b/7bb63838ebab29adde3323a759a37e7ba61038cd7ba274c44944630e9594612e/blob new file mode 100644 index 0000000000000000000000000000000000000000..9d7415e1ec9a7e03b94dd8893935d46294b4b215 --- /dev/null +++ b/shared/package-files/7b/7bb63838ebab29adde3323a759a37e7ba61038cd7ba274c44944630e9594612e/blob @@ -0,0 +1,948 @@ +import numpy as np +from scipy.sparse.linalg import LinearOperator +from scipy.sparse import kron, eye, dia_array + +__all__ = ['LaplacianNd'] +# Sakurai and Mikota classes are intended for tests and benchmarks +# and explicitly not included in the public API of this module. + + +class LaplacianNd(LinearOperator): + """ + The grid Laplacian in ``N`` dimensions and its eigenvalues/eigenvectors. + + Construct Laplacian on a uniform rectangular grid in `N` dimensions + and output its eigenvalues and eigenvectors. + The Laplacian ``L`` is square, negative definite, real symmetric array + with signed integer entries and zeros otherwise. + + Parameters + ---------- + grid_shape : tuple + A tuple of integers of length ``N`` (corresponding to the dimension of + the Lapacian), where each entry gives the size of that dimension. The + Laplacian matrix is square of the size ``np.prod(grid_shape)``. + boundary_conditions : {'neumann', 'dirichlet', 'periodic'}, optional + The type of the boundary conditions on the boundaries of the grid. + Valid values are ``'dirichlet'`` or ``'neumann'``(default) or + ``'periodic'``. + dtype : dtype + Numerical type of the array. Default is ``np.int8``. + + Methods + ------- + toarray() + Construct a dense array from Laplacian data + tosparse() + Construct a sparse array from Laplacian data + eigenvalues(m=None) + Construct a 1D array of `m` largest (smallest in absolute value) + eigenvalues of the Laplacian matrix in ascending order. + eigenvectors(m=None): + Construct the array with columns made of `m` eigenvectors (``float``) + of the ``Nd`` Laplacian corresponding to the `m` ordered eigenvalues. + + .. versionadded:: 1.12.0 + + Notes + ----- + Compared to the MATLAB/Octave implementation [1] of 1-, 2-, and 3-D + Laplacian, this code allows the arbitrary N-D case and the matrix-free + callable option, but is currently limited to pure Dirichlet, Neumann or + Periodic boundary conditions only. + + The Laplacian matrix of a graph (`scipy.sparse.csgraph.laplacian`) of a + rectangular grid corresponds to the negative Laplacian with the Neumann + conditions, i.e., ``boundary_conditions = 'neumann'``. + + All eigenvalues and eigenvectors of the discrete Laplacian operator for + an ``N``-dimensional regular grid of shape `grid_shape` with the grid + step size ``h=1`` are analytically known [2]. + + References + ---------- + .. [1] https://github.com/lobpcg/blopex/blob/master/blopex_\ +tools/matlab/laplacian/laplacian.m + .. [2] "Eigenvalues and eigenvectors of the second derivative", Wikipedia + https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors_\ +of_the_second_derivative + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse.linalg import LaplacianNd + >>> from scipy.sparse import diags, csgraph + >>> from scipy.linalg import eigvalsh + + The one-dimensional Laplacian demonstrated below for pure Neumann boundary + conditions on a regular grid with ``n=6`` grid points is exactly the + negative graph Laplacian for the undirected linear graph with ``n`` + vertices using the sparse adjacency matrix ``G`` represented by the + famous tri-diagonal matrix: + + >>> n = 6 + >>> G = diags(np.ones(n - 1), 1, format='csr') + >>> Lf = csgraph.laplacian(G, symmetrized=True, form='function') + >>> grid_shape = (n, ) + >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann') + >>> np.array_equal(lap.matmat(np.eye(n)), -Lf(np.eye(n))) + True + + Since all matrix entries of the Laplacian are integers, ``'int8'`` is + the default dtype for storing matrix representations. + + >>> lap.tosparse() + + >>> lap.toarray() + array([[-1, 1, 0, 0, 0, 0], + [ 1, -2, 1, 0, 0, 0], + [ 0, 1, -2, 1, 0, 0], + [ 0, 0, 1, -2, 1, 0], + [ 0, 0, 0, 1, -2, 1], + [ 0, 0, 0, 0, 1, -1]], dtype=int8) + >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray()) + True + >>> np.array_equal(lap.tosparse().toarray(), lap.toarray()) + True + + Any number of extreme eigenvalues and/or eigenvectors can be computed. + + >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic') + >>> lap.eigenvalues() + array([-4., -3., -3., -1., -1., 0.]) + >>> lap.eigenvalues()[-2:] + array([-1., 0.]) + >>> lap.eigenvalues(2) + array([-1., 0.]) + >>> lap.eigenvectors(1) + array([[0.40824829], + [0.40824829], + [0.40824829], + [0.40824829], + [0.40824829], + [0.40824829]]) + >>> lap.eigenvectors(2) + array([[ 0.5 , 0.40824829], + [ 0. , 0.40824829], + [-0.5 , 0.40824829], + [-0.5 , 0.40824829], + [ 0. , 0.40824829], + [ 0.5 , 0.40824829]]) + >>> lap.eigenvectors() + array([[ 0.40824829, 0.28867513, 0.28867513, 0.5 , 0.5 , + 0.40824829], + [-0.40824829, -0.57735027, -0.57735027, 0. , 0. , + 0.40824829], + [ 0.40824829, 0.28867513, 0.28867513, -0.5 , -0.5 , + 0.40824829], + [-0.40824829, 0.28867513, 0.28867513, -0.5 , -0.5 , + 0.40824829], + [ 0.40824829, -0.57735027, -0.57735027, 0. , 0. , + 0.40824829], + [-0.40824829, 0.28867513, 0.28867513, 0.5 , 0.5 , + 0.40824829]]) + + The two-dimensional Laplacian is illustrated on a regular grid with + ``grid_shape = (2, 3)`` points in each dimension. + + >>> grid_shape = (2, 3) + >>> n = np.prod(grid_shape) + + Numeration of grid points is as follows: + + >>> np.arange(n).reshape(grid_shape + (-1,)) + array([[[0], + [1], + [2]], + + [[3], + [4], + [5]]]) + + Each of the boundary conditions ``'dirichlet'``, ``'periodic'``, and + ``'neumann'`` is illustrated separately; with ``'dirichlet'`` + + >>> lap = LaplacianNd(grid_shape, boundary_conditions='dirichlet') + >>> lap.tosparse() + + >>> lap.toarray() + array([[-4, 1, 0, 1, 0, 0], + [ 1, -4, 1, 0, 1, 0], + [ 0, 1, -4, 0, 0, 1], + [ 1, 0, 0, -4, 1, 0], + [ 0, 1, 0, 1, -4, 1], + [ 0, 0, 1, 0, 1, -4]], dtype=int8) + >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray()) + True + >>> np.array_equal(lap.tosparse().toarray(), lap.toarray()) + True + >>> lap.eigenvalues() + array([-6.41421356, -5. , -4.41421356, -3.58578644, -3. , + -1.58578644]) + >>> eigvals = eigvalsh(lap.toarray().astype(np.float64)) + >>> np.allclose(lap.eigenvalues(), eigvals) + True + >>> np.allclose(lap.toarray() @ lap.eigenvectors(), + ... lap.eigenvectors() @ np.diag(lap.eigenvalues())) + True + + with ``'periodic'`` + + >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic') + >>> lap.tosparse() + + >>> lap.toarray() + array([[-4, 1, 1, 2, 0, 0], + [ 1, -4, 1, 0, 2, 0], + [ 1, 1, -4, 0, 0, 2], + [ 2, 0, 0, -4, 1, 1], + [ 0, 2, 0, 1, -4, 1], + [ 0, 0, 2, 1, 1, -4]], dtype=int8) + >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray()) + True + >>> np.array_equal(lap.tosparse().toarray(), lap.toarray()) + True + >>> lap.eigenvalues() + array([-7., -7., -4., -3., -3., 0.]) + >>> eigvals = eigvalsh(lap.toarray().astype(np.float64)) + >>> np.allclose(lap.eigenvalues(), eigvals) + True + >>> np.allclose(lap.toarray() @ lap.eigenvectors(), + ... lap.eigenvectors() @ np.diag(lap.eigenvalues())) + True + + and with ``'neumann'`` + + >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann') + >>> lap.tosparse() + + >>> lap.toarray() + array([[-2, 1, 0, 1, 0, 0], + [ 1, -3, 1, 0, 1, 0], + [ 0, 1, -2, 0, 0, 1], + [ 1, 0, 0, -2, 1, 0], + [ 0, 1, 0, 1, -3, 1], + [ 0, 0, 1, 0, 1, -2]], dtype=int8) + >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray()) + True + >>> np.array_equal(lap.tosparse().toarray(), lap.toarray()) + True + >>> lap.eigenvalues() + array([-5., -3., -3., -2., -1., 0.]) + >>> eigvals = eigvalsh(lap.toarray().astype(np.float64)) + >>> np.allclose(lap.eigenvalues(), eigvals) + True + >>> np.allclose(lap.toarray() @ lap.eigenvectors(), + ... lap.eigenvectors() @ np.diag(lap.eigenvalues())) + True + + """ + + def __init__(self, grid_shape, *, + boundary_conditions='neumann', + dtype=np.int8): + + if boundary_conditions not in ('dirichlet', 'neumann', 'periodic'): + raise ValueError( + f"Unknown value {boundary_conditions!r} is given for " + "'boundary_conditions' parameter. The valid options are " + "'dirichlet', 'periodic', and 'neumann' (default)." + ) + + self.grid_shape = grid_shape + self.boundary_conditions = boundary_conditions + # LaplacianNd folds all dimensions in `grid_shape` into a single one + N = np.prod(grid_shape) + super().__init__(dtype=dtype, shape=(N, N)) + + def _eigenvalue_ordering(self, m): + """Compute `m` largest eigenvalues in each of the ``N`` directions, + i.e., up to ``m * N`` total, order them and return `m` largest. + """ + grid_shape = self.grid_shape + if m is None: + indices = np.indices(grid_shape) + Leig = np.zeros(grid_shape) + else: + grid_shape_min = min(grid_shape, + tuple(np.ones_like(grid_shape) * m)) + indices = np.indices(grid_shape_min) + Leig = np.zeros(grid_shape_min) + + for j, n in zip(indices, grid_shape): + if self.boundary_conditions == 'dirichlet': + Leig += -4 * np.sin(np.pi * (j + 1) / (2 * (n + 1))) ** 2 + elif self.boundary_conditions == 'neumann': + Leig += -4 * np.sin(np.pi * j / (2 * n)) ** 2 + else: # boundary_conditions == 'periodic' + Leig += -4 * np.sin(np.pi * np.floor((j + 1) / 2) / n) ** 2 + + Leig_ravel = Leig.ravel() + ind = np.argsort(Leig_ravel) + eigenvalues = Leig_ravel[ind] + if m is not None: + eigenvalues = eigenvalues[-m:] + ind = ind[-m:] + + return eigenvalues, ind + + def eigenvalues(self, m=None): + """Return the requested number of eigenvalues. + + Parameters + ---------- + m : int, optional + The positive number of smallest eigenvalues to return. + If not provided, then all eigenvalues will be returned. + + Returns + ------- + eigenvalues : float array + The requested `m` smallest or all eigenvalues, in ascending order. + """ + eigenvalues, _ = self._eigenvalue_ordering(m) + return eigenvalues + + def _ev1d(self, j, n): + """Return 1 eigenvector in 1d with index `j` + and number of grid points `n` where ``j < n``. + """ + if self.boundary_conditions == 'dirichlet': + i = np.pi * (np.arange(n) + 1) / (n + 1) + ev = np.sqrt(2. / (n + 1.)) * np.sin(i * (j + 1)) + elif self.boundary_conditions == 'neumann': + i = np.pi * (np.arange(n) + 0.5) / n + ev = np.sqrt((1. if j == 0 else 2.) / n) * np.cos(i * j) + else: # boundary_conditions == 'periodic' + if j == 0: + ev = np.sqrt(1. / n) * np.ones(n) + elif j + 1 == n and n % 2 == 0: + ev = np.sqrt(1. / n) * np.tile([1, -1], n//2) + else: + i = 2. * np.pi * (np.arange(n) + 0.5) / n + ev = np.sqrt(2. / n) * np.cos(i * np.floor((j + 1) / 2)) + # make small values exact zeros correcting round-off errors + # due to symmetry of eigenvectors the exact 0. is correct + ev[np.abs(ev) < np.finfo(np.float64).eps] = 0. + return ev + + def _one_eve(self, k): + """Return 1 eigenvector in Nd with multi-index `j` + as a tensor product of the corresponding 1d eigenvectors. + """ + phi = [self._ev1d(j, n) for j, n in zip(k, self.grid_shape)] + result = phi[0] + for phi in phi[1:]: + result = np.tensordot(result, phi, axes=0) + return np.asarray(result).ravel() + + def eigenvectors(self, m=None): + """Return the requested number of eigenvectors for ordered eigenvalues. + + Parameters + ---------- + m : int, optional + The positive number of eigenvectors to return. If not provided, + then all eigenvectors will be returned. + + Returns + ------- + eigenvectors : float array + An array with columns made of the requested `m` or all eigenvectors. + The columns are ordered according to the `m` ordered eigenvalues. + """ + _, ind = self._eigenvalue_ordering(m) + if m is None: + grid_shape_min = self.grid_shape + else: + grid_shape_min = min(self.grid_shape, + tuple(np.ones_like(self.grid_shape) * m)) + + N_indices = np.unravel_index(ind, grid_shape_min) + N_indices = [tuple(x) for x in zip(*N_indices)] + eigenvectors_list = [self._one_eve(k) for k in N_indices] + return np.column_stack(eigenvectors_list) + + def toarray(self): + """ + Converts the Laplacian data to a dense array. + + Returns + ------- + L : ndarray + The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``. + + """ + grid_shape = self.grid_shape + n = np.prod(grid_shape) + L = np.zeros([n, n], dtype=np.int8) + # Scratch arrays + L_i = np.empty_like(L) + Ltemp = np.empty_like(L) + + for ind, dim in enumerate(grid_shape): + # Start zeroing out L_i + L_i[:] = 0 + # Allocate the top left corner with the kernel of L_i + # Einsum returns writable view of arrays + np.einsum("ii->i", L_i[:dim, :dim])[:] = -2 + np.einsum("ii->i", L_i[: dim - 1, 1:dim])[:] = 1 + np.einsum("ii->i", L_i[1:dim, : dim - 1])[:] = 1 + + if self.boundary_conditions == 'neumann': + L_i[0, 0] = -1 + L_i[dim - 1, dim - 1] = -1 + elif self.boundary_conditions == 'periodic': + if dim > 1: + L_i[0, dim - 1] += 1 + L_i[dim - 1, 0] += 1 + else: + L_i[0, 0] += 1 + + # kron is too slow for large matrices hence the next two tricks + # 1- kron(eye, mat) is block_diag(mat, mat, ...) + # 2- kron(mat, eye) can be performed by 4d stride trick + + # 1- + new_dim = dim + # for block_diag we tile the top left portion on the diagonal + if ind > 0: + tiles = np.prod(grid_shape[:ind]) + for j in range(1, tiles): + L_i[j*dim:(j+1)*dim, j*dim:(j+1)*dim] = L_i[:dim, :dim] + new_dim += dim + # 2- + # we need the keep L_i, but reset the array + Ltemp[:new_dim, :new_dim] = L_i[:new_dim, :new_dim] + tiles = int(np.prod(grid_shape[ind+1:])) + # Zero out the top left, the rest is already 0 + L_i[:new_dim, :new_dim] = 0 + idx = [x for x in range(tiles)] + L_i.reshape( + (new_dim, tiles, + new_dim, tiles) + )[:, idx, :, idx] = Ltemp[:new_dim, :new_dim] + + L += L_i + + return L.astype(self.dtype) + + def tosparse(self): + """ + Constructs a sparse array from the Laplacian data. The returned sparse + array format is dependent on the selected boundary conditions. + + Returns + ------- + L : scipy.sparse.sparray + The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``. + + """ + N = len(self.grid_shape) + p = np.prod(self.grid_shape) + L = dia_array((p, p), dtype=np.int8) + + for i in range(N): + dim = self.grid_shape[i] + data = np.ones([3, dim], dtype=np.int8) + data[1, :] *= -2 + + if self.boundary_conditions == 'neumann': + data[1, 0] = -1 + data[1, -1] = -1 + + L_i = dia_array((data, [-1, 0, 1]), shape=(dim, dim), + dtype=np.int8 + ) + + if self.boundary_conditions == 'periodic': + t = dia_array((dim, dim), dtype=np.int8) + t.setdiag([1], k=-dim+1) + t.setdiag([1], k=dim-1) + L_i += t + + for j in range(i): + L_i = kron(eye(self.grid_shape[j], dtype=np.int8), L_i) + for j in range(i + 1, N): + L_i = kron(L_i, eye(self.grid_shape[j], dtype=np.int8)) + L += L_i + return L.astype(self.dtype) + + def _matvec(self, x): + grid_shape = self.grid_shape + N = len(grid_shape) + X = x.reshape(grid_shape + (-1,)) + Y = -2 * N * X + for i in range(N): + Y += np.roll(X, 1, axis=i) + Y += np.roll(X, -1, axis=i) + if self.boundary_conditions in ('neumann', 'dirichlet'): + Y[(slice(None),)*i + (0,) + (slice(None),)*(N-i-1) + ] -= np.roll(X, 1, axis=i)[ + (slice(None),) * i + (0,) + (slice(None),) * (N-i-1) + ] + Y[ + (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1) + ] -= np.roll(X, -1, axis=i)[ + (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1) + ] + + if self.boundary_conditions == 'neumann': + Y[ + (slice(None),) * i + (0,) + (slice(None),) * (N-i-1) + ] += np.roll(X, 0, axis=i)[ + (slice(None),) * i + (0,) + (slice(None),) * (N-i-1) + ] + Y[ + (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1) + ] += np.roll(X, 0, axis=i)[ + (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1) + ] + + return Y.reshape(-1, X.shape[-1]) + + def _matmat(self, x): + return self._matvec(x) + + def _adjoint(self): + return self + + def _transpose(self): + return self + + +class Sakurai(LinearOperator): + """ + Construct a Sakurai matrix in various formats and its eigenvalues. + + Constructs the "Sakurai" matrix motivated by reference [1]_: + square real symmetric positive definite and 5-diagonal + with the main diagonal ``[5, 6, 6, ..., 6, 6, 5], the ``+1`` and ``-1`` + diagonals filled with ``-4``, and the ``+2`` and ``-2`` diagonals + made of ``1``. Its eigenvalues are analytically known to be + ``16. * np.power(np.cos(0.5 * k * np.pi / (n + 1)), 4)``. + The matrix gets ill-conditioned with its size growing. + It is useful for testing and benchmarking sparse eigenvalue solvers + especially those taking advantage of its banded 5-diagonal structure. + See the notes below for details. + + Parameters + ---------- + n : int + The size of the matrix. + dtype : dtype + Numerical type of the array. Default is ``np.int8``. + + Methods + ------- + toarray() + Construct a dense array from Laplacian data + tosparse() + Construct a sparse array from Laplacian data + tobanded() + The Sakurai matrix in the format for banded symmetric matrices, + i.e., (3, n) ndarray with 3 upper diagonals + placing the main diagonal at the bottom. + eigenvalues + All eigenvalues of the Sakurai matrix ordered ascending. + + Notes + ----- + Reference [1]_ introduces a generalized eigenproblem for the matrix pair + `A` and `B` where `A` is the identity so we turn it into an eigenproblem + just for the matrix `B` that this function outputs in various formats + together with its eigenvalues. + + .. versionadded:: 1.12.0 + + References + ---------- + .. [1] T. Sakurai, H. Tadano, Y. Inadomi, and U. Nagashima, + "A moment-based method for large-scale generalized + eigenvalue problems", + Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004). + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse.linalg._special_sparse_arrays import Sakurai + >>> from scipy.linalg import eig_banded + >>> n = 6 + >>> sak = Sakurai(n) + + Since all matrix entries are small integers, ``'int8'`` is + the default dtype for storing matrix representations. + + >>> sak.toarray() + array([[ 5, -4, 1, 0, 0, 0], + [-4, 6, -4, 1, 0, 0], + [ 1, -4, 6, -4, 1, 0], + [ 0, 1, -4, 6, -4, 1], + [ 0, 0, 1, -4, 6, -4], + [ 0, 0, 0, 1, -4, 5]], dtype=int8) + >>> sak.tobanded() + array([[ 1, 1, 1, 1, 1, 1], + [-4, -4, -4, -4, -4, -4], + [ 5, 6, 6, 6, 6, 5]], dtype=int8) + >>> sak.tosparse() + + >>> np.array_equal(sak.dot(np.eye(n)), sak.tosparse().toarray()) + True + >>> sak.eigenvalues() + array([0.03922866, 0.56703972, 2.41789479, 5.97822974, + 10.54287655, 14.45473055]) + >>> sak.eigenvalues(2) + array([0.03922866, 0.56703972]) + + The banded form can be used in scipy functions for banded matrices, e.g., + + >>> e = eig_banded(sak.tobanded(), eigvals_only=True) + >>> np.allclose(sak.eigenvalues, e, atol= n * n * n * np.finfo(float).eps) + True + + """ + def __init__(self, n, dtype=np.int8): + self.n = n + self.dtype = dtype + shape = (n, n) + super().__init__(dtype, shape) + + def eigenvalues(self, m=None): + """Return the requested number of eigenvalues. + + Parameters + ---------- + m : int, optional + The positive number of smallest eigenvalues to return. + If not provided, then all eigenvalues will be returned. + + Returns + ------- + eigenvalues : `np.float64` array + The requested `m` smallest or all eigenvalues, in ascending order. + """ + if m is None: + m = self.n + k = np.arange(self.n + 1 -m, self.n + 1) + return np.flip(16. * np.power(np.cos(0.5 * k * np.pi / (self.n + 1)), 4)) + + def tobanded(self): + """ + Construct the Sakurai matrix as a banded array. + """ + d0 = np.r_[5, 6 * np.ones(self.n - 2, dtype=self.dtype), 5] + d1 = -4 * np.ones(self.n, dtype=self.dtype) + d2 = np.ones(self.n, dtype=self.dtype) + return np.array([d2, d1, d0]).astype(self.dtype) + + def tosparse(self): + """ + Construct the Sakurai matrix is a sparse format. + """ + from scipy.sparse import spdiags + d = self.tobanded() + # the banded format has the main diagonal at the bottom + # `spdiags` has no `dtype` parameter so inherits dtype from banded + return spdiags([d[0], d[1], d[2], d[1], d[0]], [-2, -1, 0, 1, 2], + self.n, self.n) + + def toarray(self): + return self.tosparse().toarray() + + def _matvec(self, x): + """ + Construct matrix-free callable banded-matrix-vector multiplication by + the Sakurai matrix without constructing or storing the matrix itself + using the knowledge of its entries and the 5-diagonal format. + """ + x = x.reshape(self.n, -1) + result_dtype = np.promote_types(x.dtype, self.dtype) + sx = np.zeros_like(x, dtype=result_dtype) + sx[0, :] = 5 * x[0, :] - 4 * x[1, :] + x[2, :] + sx[-1, :] = 5 * x[-1, :] - 4 * x[-2, :] + x[-3, :] + sx[1: -1, :] = (6 * x[1: -1, :] - 4 * (x[:-2, :] + x[2:, :]) + + np.pad(x[:-3, :], ((1, 0), (0, 0))) + + np.pad(x[3:, :], ((0, 1), (0, 0)))) + return sx + + def _matmat(self, x): + """ + Construct matrix-free callable matrix-matrix multiplication by + the Sakurai matrix without constructing or storing the matrix itself + by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``. + """ + return self._matvec(x) + + def _adjoint(self): + return self + + def _transpose(self): + return self + + +class MikotaM(LinearOperator): + """ + Construct a mass matrix in various formats of Mikota pair. + + The mass matrix `M` is square real diagonal + positive definite with entries that are reciprocal to integers. + + Parameters + ---------- + shape : tuple of int + The shape of the matrix. + dtype : dtype + Numerical type of the array. Default is ``np.float64``. + + Methods + ------- + toarray() + Construct a dense array from Mikota data + tosparse() + Construct a sparse array from Mikota data + tobanded() + The format for banded symmetric matrices, + i.e., (1, n) ndarray with the main diagonal. + """ + def __init__(self, shape, dtype=np.float64): + self.shape = shape + self.dtype = dtype + super().__init__(dtype, shape) + + def _diag(self): + # The matrix is constructed from its diagonal 1 / [1, ..., N+1]; + # compute in a function to avoid duplicated code & storage footprint + return (1. / np.arange(1, self.shape[0] + 1)).astype(self.dtype) + + def tobanded(self): + return self._diag() + + def tosparse(self): + from scipy.sparse import diags + return diags([self._diag()], [0], shape=self.shape, dtype=self.dtype) + + def toarray(self): + return np.diag(self._diag()).astype(self.dtype) + + def _matvec(self, x): + """ + Construct matrix-free callable banded-matrix-vector multiplication by + the Mikota mass matrix without constructing or storing the matrix itself + using the knowledge of its entries and the diagonal format. + """ + x = x.reshape(self.shape[0], -1) + return self._diag()[:, np.newaxis] * x + + def _matmat(self, x): + """ + Construct matrix-free callable matrix-matrix multiplication by + the Mikota mass matrix without constructing or storing the matrix itself + by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``. + """ + return self._matvec(x) + + def _adjoint(self): + return self + + def _transpose(self): + return self + + +class MikotaK(LinearOperator): + """ + Construct a stiffness matrix in various formats of Mikota pair. + + The stiffness matrix `K` is square real tri-diagonal symmetric + positive definite with integer entries. + + Parameters + ---------- + shape : tuple of int + The shape of the matrix. + dtype : dtype + Numerical type of the array. Default is ``np.int32``. + + Methods + ------- + toarray() + Construct a dense array from Mikota data + tosparse() + Construct a sparse array from Mikota data + tobanded() + The format for banded symmetric matrices, + i.e., (2, n) ndarray with 2 upper diagonals + placing the main diagonal at the bottom. + """ + def __init__(self, shape, dtype=np.int32): + self.shape = shape + self.dtype = dtype + super().__init__(dtype, shape) + # The matrix is constructed from its diagonals; + # we precompute these to avoid duplicating the computation + n = shape[0] + self._diag0 = np.arange(2 * n - 1, 0, -2, dtype=self.dtype) + self._diag1 = - np.arange(n - 1, 0, -1, dtype=self.dtype) + + def tobanded(self): + return np.array([np.pad(self._diag1, (1, 0), 'constant'), self._diag0]) + + def tosparse(self): + from scipy.sparse import diags + return diags([self._diag1, self._diag0, self._diag1], [-1, 0, 1], + shape=self.shape, dtype=self.dtype) + + def toarray(self): + return self.tosparse().toarray() + + def _matvec(self, x): + """ + Construct matrix-free callable banded-matrix-vector multiplication by + the Mikota stiffness matrix without constructing or storing the matrix + itself using the knowledge of its entries and the 3-diagonal format. + """ + x = x.reshape(self.shape[0], -1) + result_dtype = np.promote_types(x.dtype, self.dtype) + kx = np.zeros_like(x, dtype=result_dtype) + d1 = self._diag1 + d0 = self._diag0 + kx[0, :] = d0[0] * x[0, :] + d1[0] * x[1, :] + kx[-1, :] = d1[-1] * x[-2, :] + d0[-1] * x[-1, :] + kx[1: -1, :] = (d1[:-1, None] * x[: -2, :] + + d0[1: -1, None] * x[1: -1, :] + + d1[1:, None] * x[2:, :]) + return kx + + def _matmat(self, x): + """ + Construct matrix-free callable matrix-matrix multiplication by + the Stiffness mass matrix without constructing or storing the matrix itself + by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``. + """ + return self._matvec(x) + + def _adjoint(self): + return self + + def _transpose(self): + return self + + +class MikotaPair: + """ + Construct the Mikota pair of matrices in various formats and + eigenvalues of the generalized eigenproblem with them. + + The Mikota pair of matrices [1, 2]_ models a vibration problem + of a linear mass-spring system with the ends attached where + the stiffness of the springs and the masses increase along + the system length such that vibration frequencies are subsequent + integers 1, 2, ..., `n` where `n` is the number of the masses. Thus, + eigenvalues of the generalized eigenvalue problem for + the matrix pair `K` and `M` where `K` is the system stiffness matrix + and `M` is the system mass matrix are the squares of the integers, + i.e., 1, 4, 9, ..., ``n * n``. + + The stiffness matrix `K` is square real tri-diagonal symmetric + positive definite. The mass matrix `M` is diagonal with diagonal + entries 1, 1/2, 1/3, ...., ``1/n``. Both matrices get + ill-conditioned with `n` growing. + + Parameters + ---------- + n : int + The size of the matrices of the Mikota pair. + dtype : dtype + Numerical type of the array. Default is ``np.float64``. + + Attributes + ---------- + eigenvalues : 1D ndarray, ``np.uint64`` + All eigenvalues of the Mikota pair ordered ascending. + + Methods + ------- + MikotaK() + A `LinearOperator` custom object for the stiffness matrix. + MikotaM() + A `LinearOperator` custom object for the mass matrix. + + .. versionadded:: 1.12.0 + + References + ---------- + .. [1] J. Mikota, "Frequency tuning of chain structure multibody oscillators + to place the natural frequencies at omega1 and N-1 integer multiples + omega2,..., omegaN", Z. Angew. Math. Mech. 81 (2001), S2, S201-S202. + Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004). + .. [2] Peter C. Muller and Metin Gurgoze, + "Natural frequencies of a multi-degree-of-freedom vibration system", + Proc. Appl. Math. Mech. 6, 319-320 (2006). + http://dx.doi.org/10.1002/pamm.200610141. + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse.linalg._special_sparse_arrays import MikotaPair + >>> n = 6 + >>> mik = MikotaPair(n) + >>> mik_k = mik.k + >>> mik_m = mik.m + >>> mik_k.toarray() + array([[11., -5., 0., 0., 0., 0.], + [-5., 9., -4., 0., 0., 0.], + [ 0., -4., 7., -3., 0., 0.], + [ 0., 0., -3., 5., -2., 0.], + [ 0., 0., 0., -2., 3., -1.], + [ 0., 0., 0., 0., -1., 1.]]) + >>> mik_k.tobanded() + array([[ 0., -5., -4., -3., -2., -1.], + [11., 9., 7., 5., 3., 1.]]) + >>> mik_m.tobanded() + array([1. , 0.5 , 0.33333333, 0.25 , 0.2 , + 0.16666667]) + >>> mik_k.tosparse() + + >>> mik_m.tosparse() + + >>> np.array_equal(mik_k(np.eye(n)), mik_k.toarray()) + True + >>> np.array_equal(mik_m(np.eye(n)), mik_m.toarray()) + True + >>> mik.eigenvalues() + array([ 1, 4, 9, 16, 25, 36]) + >>> mik.eigenvalues(2) + array([ 1, 4]) + + """ + def __init__(self, n, dtype=np.float64): + self.n = n + self.dtype = dtype + self.shape = (n, n) + self.m = MikotaM(self.shape, self.dtype) + self.k = MikotaK(self.shape, self.dtype) + + def eigenvalues(self, m=None): + """Return the requested number of eigenvalues. + + Parameters + ---------- + m : int, optional + The positive number of smallest eigenvalues to return. + If not provided, then all eigenvalues will be returned. + + Returns + ------- + eigenvalues : `np.uint64` array + The requested `m` smallest or all eigenvalues, in ascending order. + """ + if m is None: + m = self.n + arange_plus1 = np.arange(1, m + 1, dtype=np.uint64) + return arange_plus1 * arange_plus1 diff --git a/shared/package-files/7b/7bb6f918a4d60ad286a01f33d9af1e76c5b45e3975acc85e00bb2fcc4263942c/blob b/shared/package-files/7b/7bb6f918a4d60ad286a01f33d9af1e76c5b45e3975acc85e00bb2fcc4263942c/blob new file mode 100644 index 0000000000000000000000000000000000000000..803870e2feadd18815ebc57665aa63d42423c752 --- /dev/null +++ b/shared/package-files/7b/7bb6f918a4d60ad286a01f33d9af1e76c5b45e3975acc85e00bb2fcc4263942c/blob @@ -0,0 +1,28 @@ +import numpy as np +import numpy.typing as npt + +AR_U: npt.NDArray[np.str_] + +def func() -> bool: ... + +np.testing.assert_(True, msg=1) # E: incompatible type +np.testing.build_err_msg(1, "test") # E: incompatible type +np.testing.assert_almost_equal(AR_U, AR_U) # E: incompatible type +np.testing.assert_approx_equal([1, 2, 3], [1, 2, 3]) # E: incompatible type +np.testing.assert_array_almost_equal(AR_U, AR_U) # E: incompatible type +np.testing.assert_array_less(AR_U, AR_U) # E: incompatible type +np.testing.assert_string_equal(b"a", b"a") # E: incompatible type + +np.testing.assert_raises(expected_exception=TypeError, callable=func) # E: No overload variant +np.testing.assert_raises_regex(expected_exception=TypeError, expected_regex="T", callable=func) # E: No overload variant + +np.testing.assert_allclose(AR_U, AR_U) # E: incompatible type +np.testing.assert_array_almost_equal_nulp(AR_U, AR_U) # E: incompatible type +np.testing.assert_array_max_ulp(AR_U, AR_U) # E: incompatible type + +np.testing.assert_warns(warning_class=RuntimeWarning, func=func) # E: No overload variant +np.testing.assert_no_warnings(func=func) # E: No overload variant +np.testing.assert_no_warnings(func, None) # E: Too many arguments +np.testing.assert_no_warnings(func, test=None) # E: Unexpected keyword argument + +np.testing.assert_no_gc_cycles(func=func) # E: No overload variant diff --git a/shared/package-files/7b/7bbe0bb4e3fd7bc924461beb209fd15f3f546bf2f8dcf77d222c703707ab9a73/blob b/shared/package-files/7b/7bbe0bb4e3fd7bc924461beb209fd15f3f546bf2f8dcf77d222c703707ab9a73/blob new file mode 100644 index 0000000000000000000000000000000000000000..9f8e0d4edbfba4b29fb9ac8743009f3073c63e40 --- /dev/null +++ b/shared/package-files/7b/7bbe0bb4e3fd7bc924461beb209fd15f3f546bf2f8dcf77d222c703707ab9a73/blob @@ -0,0 +1,445 @@ +"""A module with private type-check-only `numpy.ufunc` subclasses. + +The signatures of the ufuncs are too varied to reasonably type +with a single class. So instead, `ufunc` has been expanded into +four private subclasses, one for each combination of +`~ufunc.nin` and `~ufunc.nout`. + +""" + +from typing import ( + Any, + Generic, + overload, + TypeVar, + Literal, + SupportsIndex, + Protocol, +) + +from numpy import ufunc, _CastingKind, _OrderKACF +from numpy.typing import NDArray + +from ._shape import _ShapeLike +from ._scalars import _ScalarLike_co +from ._array_like import ArrayLike, _ArrayLikeBool_co, _ArrayLikeInt_co +from ._dtype_like import DTypeLike + +_T = TypeVar("_T") +_2Tuple = tuple[_T, _T] +_3Tuple = tuple[_T, _T, _T] +_4Tuple = tuple[_T, _T, _T, _T] + +_NTypes = TypeVar("_NTypes", bound=int) +_IDType = TypeVar("_IDType", bound=Any) +_NameType = TypeVar("_NameType", bound=str) + + +class _SupportsArrayUFunc(Protocol): + def __array_ufunc__( + self, + ufunc: ufunc, + method: Literal["__call__", "reduce", "reduceat", "accumulate", "outer", "inner"], + *inputs: Any, + **kwargs: Any, + ) -> Any: ... + + +# NOTE: In reality `extobj` should be a length of list 3 containing an +# int, an int, and a callable, but there's no way to properly express +# non-homogenous lists. +# Use `Any` over `Union` to avoid issues related to lists invariance. + +# NOTE: `reduce`, `accumulate`, `reduceat` and `outer` raise a ValueError for +# ufuncs that don't accept two input arguments and return one output argument. +# In such cases the respective methods are simply typed as `None`. + +# NOTE: Similarly, `at` won't be defined for ufuncs that return +# multiple outputs; in such cases `at` is typed as `None` + +# NOTE: If 2 output types are returned then `out` must be a +# 2-tuple of arrays. Otherwise `None` or a plain array are also acceptable + +class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc] + @property + def __name__(self) -> _NameType: ... + @property + def ntypes(self) -> _NTypes: ... + @property + def identity(self) -> _IDType: ... + @property + def nin(self) -> Literal[1]: ... + @property + def nout(self) -> Literal[1]: ... + @property + def nargs(self) -> Literal[2]: ... + @property + def signature(self) -> None: ... + @property + def reduce(self) -> None: ... + @property + def accumulate(self) -> None: ... + @property + def reduceat(self) -> None: ... + @property + def outer(self) -> None: ... + + @overload + def __call__( + self, + __x1: _ScalarLike_co, + out: None = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _2Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> Any: ... + @overload + def __call__( + self, + __x1: ArrayLike, + out: None | NDArray[Any] | tuple[NDArray[Any]] = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _2Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> NDArray[Any]: ... + @overload + def __call__( + self, + __x1: _SupportsArrayUFunc, + out: None | NDArray[Any] | tuple[NDArray[Any]] = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _2Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> Any: ... + + def at( + self, + a: _SupportsArrayUFunc, + indices: _ArrayLikeInt_co, + /, + ) -> None: ... + +class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc] + @property + def __name__(self) -> _NameType: ... + @property + def ntypes(self) -> _NTypes: ... + @property + def identity(self) -> _IDType: ... + @property + def nin(self) -> Literal[2]: ... + @property + def nout(self) -> Literal[1]: ... + @property + def nargs(self) -> Literal[3]: ... + @property + def signature(self) -> None: ... + + @overload + def __call__( + self, + __x1: _ScalarLike_co, + __x2: _ScalarLike_co, + out: None = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> Any: ... + @overload + def __call__( + self, + __x1: ArrayLike, + __x2: ArrayLike, + out: None | NDArray[Any] | tuple[NDArray[Any]] = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> NDArray[Any]: ... + + def at( + self, + a: NDArray[Any], + indices: _ArrayLikeInt_co, + b: ArrayLike, + /, + ) -> None: ... + + def reduce( + self, + array: ArrayLike, + axis: None | _ShapeLike = ..., + dtype: DTypeLike = ..., + out: None | NDArray[Any] = ..., + keepdims: bool = ..., + initial: Any = ..., + where: _ArrayLikeBool_co = ..., + ) -> Any: ... + + def accumulate( + self, + array: ArrayLike, + axis: SupportsIndex = ..., + dtype: DTypeLike = ..., + out: None | NDArray[Any] = ..., + ) -> NDArray[Any]: ... + + def reduceat( + self, + array: ArrayLike, + indices: _ArrayLikeInt_co, + axis: SupportsIndex = ..., + dtype: DTypeLike = ..., + out: None | NDArray[Any] = ..., + ) -> NDArray[Any]: ... + + # Expand `**kwargs` into explicit keyword-only arguments + @overload + def outer( + self, + A: _ScalarLike_co, + B: _ScalarLike_co, + /, *, + out: None = ..., + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> Any: ... + @overload + def outer( # type: ignore[misc] + self, + A: ArrayLike, + B: ArrayLike, + /, *, + out: None | NDArray[Any] | tuple[NDArray[Any]] = ..., + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> NDArray[Any]: ... + +class _UFunc_Nin1_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc] + @property + def __name__(self) -> _NameType: ... + @property + def ntypes(self) -> _NTypes: ... + @property + def identity(self) -> _IDType: ... + @property + def nin(self) -> Literal[1]: ... + @property + def nout(self) -> Literal[2]: ... + @property + def nargs(self) -> Literal[3]: ... + @property + def signature(self) -> None: ... + @property + def at(self) -> None: ... + @property + def reduce(self) -> None: ... + @property + def accumulate(self) -> None: ... + @property + def reduceat(self) -> None: ... + @property + def outer(self) -> None: ... + + @overload + def __call__( + self, + __x1: _ScalarLike_co, + __out1: None = ..., + __out2: None = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> _2Tuple[Any]: ... + @overload + def __call__( + self, + __x1: ArrayLike, + __out1: None | NDArray[Any] = ..., + __out2: None | NDArray[Any] = ..., + *, + out: _2Tuple[NDArray[Any]] = ..., + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> _2Tuple[NDArray[Any]]: ... + @overload + def __call__( + self, + __x1: _SupportsArrayUFunc, + __out1: None | NDArray[Any] = ..., + __out2: None | NDArray[Any] = ..., + *, + out: _2Tuple[NDArray[Any]] = ..., + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> _2Tuple[Any]: ... + +class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc] + @property + def __name__(self) -> _NameType: ... + @property + def ntypes(self) -> _NTypes: ... + @property + def identity(self) -> _IDType: ... + @property + def nin(self) -> Literal[2]: ... + @property + def nout(self) -> Literal[2]: ... + @property + def nargs(self) -> Literal[4]: ... + @property + def signature(self) -> None: ... + @property + def at(self) -> None: ... + @property + def reduce(self) -> None: ... + @property + def accumulate(self) -> None: ... + @property + def reduceat(self) -> None: ... + @property + def outer(self) -> None: ... + + @overload + def __call__( + self, + __x1: _ScalarLike_co, + __x2: _ScalarLike_co, + __out1: None = ..., + __out2: None = ..., + *, + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _4Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> _2Tuple[Any]: ... + @overload + def __call__( + self, + __x1: ArrayLike, + __x2: ArrayLike, + __out1: None | NDArray[Any] = ..., + __out2: None | NDArray[Any] = ..., + *, + out: _2Tuple[NDArray[Any]] = ..., + where: None | _ArrayLikeBool_co = ..., + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _4Tuple[None | str] = ..., + extobj: list[Any] = ..., + ) -> _2Tuple[NDArray[Any]]: ... + +class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc] + @property + def __name__(self) -> _NameType: ... + @property + def ntypes(self) -> _NTypes: ... + @property + def identity(self) -> _IDType: ... + @property + def nin(self) -> Literal[2]: ... + @property + def nout(self) -> Literal[1]: ... + @property + def nargs(self) -> Literal[3]: ... + + # NOTE: In practice the only gufunc in the main namespace is `matmul`, + # so we can use its signature here + @property + def signature(self) -> Literal["(n?,k),(k,m?)->(n?,m?)"]: ... + @property + def reduce(self) -> None: ... + @property + def accumulate(self) -> None: ... + @property + def reduceat(self) -> None: ... + @property + def outer(self) -> None: ... + @property + def at(self) -> None: ... + + # Scalar for 1D array-likes; ndarray otherwise + @overload + def __call__( + self, + __x1: ArrayLike, + __x2: ArrayLike, + out: None = ..., + *, + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + axes: list[_2Tuple[SupportsIndex]] = ..., + ) -> Any: ... + @overload + def __call__( + self, + __x1: ArrayLike, + __x2: ArrayLike, + out: NDArray[Any] | tuple[NDArray[Any]], + *, + casting: _CastingKind = ..., + order: _OrderKACF = ..., + dtype: DTypeLike = ..., + subok: bool = ..., + signature: str | _3Tuple[None | str] = ..., + extobj: list[Any] = ..., + axes: list[_2Tuple[SupportsIndex]] = ..., + ) -> NDArray[Any]: ... diff --git a/shared/package-files/7b/7bc220699d68795eb939c32c965f77a0fccc56ea4dfd2bc00e85b2f818d4605c/blob b/shared/package-files/7b/7bc220699d68795eb939c32c965f77a0fccc56ea4dfd2bc00e85b2f818d4605c/blob new file mode 100644 index 0000000000000000000000000000000000000000..b373bb81b38dca4f1ef98ba21a82e676547a947e --- /dev/null +++ b/shared/package-files/7b/7bc220699d68795eb939c32c965f77a0fccc56ea4dfd2bc00e85b2f818d4605c/blob @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mul_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mul.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API mul__Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mul_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mul_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API mul_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API mul_Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mul.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API mul__Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mul_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API mul_Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mul") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mul.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7b/7bc28c345c4960b5dc16fd95e0e221ed8988d5cc28f8d74269a99598a5a700dc/blob b/shared/package-files/7b/7bc28c345c4960b5dc16fd95e0e221ed8988d5cc28f8d74269a99598a5a700dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..6b7b2d2abcc6a55558a2c7142809fa7571a9fde6 --- /dev/null +++ b/shared/package-files/7b/7bc28c345c4960b5dc16fd95e0e221ed8988d5cc28f8d74269a99598a5a700dc/blob @@ -0,0 +1,29 @@ +import numpy as np + +from numba import cuda +from numba.cuda.testing import unittest, CUDATestCase + + +class TestFreeVar(CUDATestCase): + def test_freevar(self): + """Make sure we can compile the following kernel with freevar reference + in arguments to shared.array + """ + from numba import float32 + + size = 1024 + nbtype = float32 + + @cuda.jit("(float32[::1], intp)") + def foo(A, i): + "Dummy function" + sdata = cuda.shared.array(size, # size is freevar + dtype=nbtype) # nbtype is freevar + A[i] = sdata[i] + + A = np.arange(2, dtype="float32") + foo[1, 1](A, 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/shared/package-files/7b/7bc3d2e8e5f08a75b1e52eb9103c1a721d267c1315a2201415bfc16c0af7f9b9/blob b/shared/package-files/7b/7bc3d2e8e5f08a75b1e52eb9103c1a721d267c1315a2201415bfc16c0af7f9b9/blob new file mode 100644 index 0000000000000000000000000000000000000000..5f5c20b6c98efc5a62b6c75422decb0fd877a608 --- /dev/null +++ b/shared/package-files/7b/7bc3d2e8e5f08a75b1e52eb9103c1a721d267c1315a2201415bfc16c0af7f9b9/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & pixel_shuffle_out(const at::Tensor & self, int64_t upscale_factor, at::Tensor & out); +TORCH_API at::Tensor pixel_shuffle_cpu(const at::Tensor & self, int64_t upscale_factor); +TORCH_API at::Tensor math_pixel_shuffle(const at::Tensor & self, int64_t upscale_factor); +} // namespace native +} // namespace at diff --git a/shared/package-files/7b/7bc735a783f02431a8691ee6cb282e81b1243fd3e81e5d69d7bc39475b39c462/blob b/shared/package-files/7b/7bc735a783f02431a8691ee6cb282e81b1243fd3e81e5d69d7bc39475b39c462/blob new file mode 100644 index 0000000000000000000000000000000000000000..818e24d6d8cf76a0b86eb4bc05386ef84fe9a747 --- /dev/null +++ b/shared/package-files/7b/7bc735a783f02431a8691ee6cb282e81b1243fd3e81e5d69d7bc39475b39c462/blob @@ -0,0 +1,71 @@ +""" + pygments.styles.friendly + ~~~~~~~~~~~~~~~~~~~~~~~~ + + A modern style based on the VIM pyte theme. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.style import Style +from pygments.token import Keyword, Name, Comment, String, Error, \ + Number, Operator, Generic, Whitespace + + +class FriendlyStyle(Style): + """ + A modern style based on the VIM pyte theme. + """ + + background_color = "#f0f0f0" + line_number_color = "#666666" + + styles = { + Whitespace: "#bbbbbb", + Comment: "italic #60a0b0", + Comment.Preproc: "noitalic #007020", + Comment.Special: "noitalic bg:#fff0f0", + + Keyword: "bold #007020", + Keyword.Pseudo: "nobold", + Keyword.Type: "nobold #902000", + + Operator: "#666666", + Operator.Word: "bold #007020", + + Name.Builtin: "#007020", + Name.Function: "#06287e", + Name.Class: "bold #0e84b5", + Name.Namespace: "bold #0e84b5", + Name.Exception: "#007020", + Name.Variable: "#bb60d5", + Name.Constant: "#60add5", + Name.Label: "bold #002070", + Name.Entity: "bold #d55537", + Name.Attribute: "#4070a0", + Name.Tag: "bold #062873", + Name.Decorator: "bold #555555", + + String: "#4070a0", + String.Doc: "italic", + String.Interpol: "italic #70a0d0", + String.Escape: "bold #4070a0", + String.Regex: "#235388", + String.Symbol: "#517918", + String.Other: "#c65d09", + Number: "#40a070", + + Generic.Heading: "bold #000080", + Generic.Subheading: "bold #800080", + Generic.Deleted: "#A00000", + Generic.Inserted: "#00A000", + Generic.Error: "#FF0000", + Generic.Emph: "italic", + Generic.Strong: "bold", + Generic.Prompt: "bold #c65d09", + Generic.Output: "#888", + Generic.Traceback: "#04D", + + Error: "border:#FF0000" + } diff --git a/shared/package-files/7b/7bc7ed5e287e27f8e1a64fa2d20acf15a77189be3c3964fa7ccef3f3e4db1fd5/blob b/shared/package-files/7b/7bc7ed5e287e27f8e1a64fa2d20acf15a77189be3c3964fa7ccef3f3e4db1fd5/blob new file mode 100644 index 0000000000000000000000000000000000000000..8da660b274516a7e1c6a6f04ccdbf57d6a99dd87 --- /dev/null +++ b/shared/package-files/7b/7bc7ed5e287e27f8e1a64fa2d20acf15a77189be3c3964fa7ccef3f3e4db1fd5/blob @@ -0,0 +1,207 @@ +""" +Testing +======= + +General guidelines for writing good tests: + +- doctests always assume ``import networkx as nx`` so don't add that +- prefer pytest fixtures over classes with setup methods. +- use the ``@pytest.mark.parametrize`` decorator +- use ``pytest.importorskip`` for numpy, scipy, pandas, and matplotlib b/c of PyPy. + and add the module to the relevant entries below. + +""" +import sys +import warnings + +import pytest + +import networkx + + +def pytest_addoption(parser): + parser.addoption( + "--runslow", action="store_true", default=False, help="run slow tests" + ) + + +def pytest_configure(config): + config.addinivalue_line("markers", "slow: mark test as slow to run") + + +def pytest_collection_modifyitems(config, items): + # Allow pluggable backends to add markers to tests when + # running in auto-conversion test mode + networkx.classes.backends._mark_tests(items) + + if config.getoption("--runslow"): + # --runslow given in cli: do not skip slow tests + return + skip_slow = pytest.mark.skip(reason="need --runslow option to run") + for item in items: + if "slow" in item.keywords: + item.add_marker(skip_slow) + + +# TODO: The warnings below need to be dealt with, but for now we silence them. +@pytest.fixture(autouse=True) +def set_warnings(): + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="literal_stringizer is deprecated", + ) + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="literal_destringizer is deprecated", + ) + # create_using for scale_free_graph + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message="The create_using argument" + ) + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message="nx.nx_pydot" + ) + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="\n\nThe `attrs` keyword argument of node_link", + ) + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="single_target_shortest_path_length will", + ) + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="shortest_path for all_pairs", + ) + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message="\nforest_str is deprecated" + ) + + +@pytest.fixture(autouse=True) +def add_nx(doctest_namespace): + doctest_namespace["nx"] = networkx + + +# What dependencies are installed? + +try: + import numpy + + has_numpy = True +except ImportError: + has_numpy = False + +try: + import scipy + + has_scipy = True +except ImportError: + has_scipy = False + +try: + import matplotlib + + has_matplotlib = True +except ImportError: + has_matplotlib = False + +try: + import pandas + + has_pandas = True +except ImportError: + has_pandas = False + +try: + import pygraphviz + + has_pygraphviz = True +except ImportError: + has_pygraphviz = False + +try: + import pydot + + has_pydot = True +except ImportError: + has_pydot = False + +try: + import sympy + + has_sympy = True +except ImportError: + has_sympy = False + + +# List of files that pytest should ignore + +collect_ignore = [] + +needs_numpy = [ + "algorithms/approximation/traveling_salesman.py", + "algorithms/centrality/current_flow_closeness.py", + "algorithms/node_classification.py", + "algorithms/non_randomness.py", + "algorithms/shortest_paths/dense.py", + "linalg/bethehessianmatrix.py", + "linalg/laplacianmatrix.py", + "utils/misc.py", + "algorithms/centrality/laplacian.py", +] +needs_scipy = [ + "algorithms/approximation/traveling_salesman.py", + "algorithms/assortativity/correlation.py", + "algorithms/assortativity/mixing.py", + "algorithms/assortativity/pairs.py", + "algorithms/bipartite/matrix.py", + "algorithms/bipartite/spectral.py", + "algorithms/centrality/current_flow_betweenness.py", + "algorithms/centrality/current_flow_betweenness_subset.py", + "algorithms/centrality/eigenvector.py", + "algorithms/centrality/katz.py", + "algorithms/centrality/second_order.py", + "algorithms/centrality/subgraph_alg.py", + "algorithms/communicability_alg.py", + "algorithms/link_analysis/hits_alg.py", + "algorithms/link_analysis/pagerank_alg.py", + "algorithms/node_classification.py", + "algorithms/similarity.py", + "convert_matrix.py", + "drawing/layout.py", + "generators/spectral_graph_forge.py", + "linalg/algebraicconnectivity.py", + "linalg/attrmatrix.py", + "linalg/bethehessianmatrix.py", + "linalg/graphmatrix.py", + "linalg/modularitymatrix.py", + "linalg/spectrum.py", + "utils/rcm.py", + "algorithms/centrality/laplacian.py", +] +needs_matplotlib = ["drawing/nx_pylab.py"] +needs_pandas = ["convert_matrix.py"] +needs_pygraphviz = ["drawing/nx_agraph.py"] +needs_pydot = ["drawing/nx_pydot.py"] +needs_sympy = ["algorithms/polynomials.py"] + +if not has_numpy: + collect_ignore += needs_numpy +if not has_scipy: + collect_ignore += needs_scipy +if not has_matplotlib: + collect_ignore += needs_matplotlib +if not has_pandas: + collect_ignore += needs_pandas +if not has_pygraphviz: + collect_ignore += needs_pygraphviz +if not has_pydot: + collect_ignore += needs_pydot +if not has_sympy: + collect_ignore += needs_sympy diff --git a/shared/package-files/7b/7bc9543496788edd2e3078e2a3a1ceba956932ff370ed01a141b9d006ea9103c/blob b/shared/package-files/7b/7bc9543496788edd2e3078e2a3a1ceba956932ff370ed01a141b9d006ea9103c/blob new file mode 100644 index 0000000000000000000000000000000000000000..b45a17b5922f8a0b76e0237616914ce9969efca5 --- /dev/null +++ b/shared/package-files/7b/7bc9543496788edd2e3078e2a3a1ceba956932ff370ed01a141b9d006ea9103c/blob @@ -0,0 +1,19 @@ +#pragma once + +// an external backend might generate file within its code tree +// and check all the source files within the tree with clang-format. +// so, disable it since the backend might have a different config. +// clang-format off + +// ${generated_comment} + +#include + +${namespace_prologue} + +struct ${class_name} { + +${dispatch_declarations} + +}; +${namespace_epilogue} diff --git a/shared/package-files/7b/7bc96663bcf7ccaaa8e57a1e3cfedd872e4d470c46315116ec1ac4e057cb73f3/blob b/shared/package-files/7b/7bc96663bcf7ccaaa8e57a1e3cfedd872e4d470c46315116ec1ac4e057cb73f3/blob new file mode 100644 index 0000000000000000000000000000000000000000..8e6629d7263f055d3a8cc47feffa3ef13a72e9ea --- /dev/null +++ b/shared/package-files/7b/7bc96663bcf7ccaaa8e57a1e3cfedd872e4d470c46315116ec1ac4e057cb73f3/blob @@ -0,0 +1,224 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Routines common to all posix systems.""" + +import glob +import os +import signal +import sys +import time + +from ._common import TimeoutExpired +from ._common import memoize +from ._common import sdiskusage +from ._common import usage_percent +from ._compat import PY3 +from ._compat import ChildProcessError +from ._compat import FileNotFoundError +from ._compat import InterruptedError +from ._compat import PermissionError +from ._compat import ProcessLookupError +from ._compat import unicode + + +if sys.version_info >= (3, 4): + import enum +else: + enum = None + + +__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map'] + + +def pid_exists(pid): + """Check whether pid exists in the current process table.""" + if pid == 0: + # According to "man 2 kill" PID 0 has a special meaning: + # it refers to <> so we don't want to go any further. + # If we get here it means this UNIX platform *does* have + # a process with id 0. + return True + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + # EPERM clearly means there's a process to deny access to + return True + # According to "man 2 kill" possible error values are + # (EINVAL, EPERM, ESRCH) + else: + return True + + +# Python 3.5 signals enum (contributed by me ^^): +# https://bugs.python.org/issue21076 +if enum is not None and hasattr(signal, "Signals"): + Negsignal = enum.IntEnum( + 'Negsignal', dict([(x.name, -x.value) for x in signal.Signals])) + + def negsig_to_enum(num): + """Convert a negative signal value to an enum.""" + try: + return Negsignal(num) + except ValueError: + return num +else: # pragma: no cover + def negsig_to_enum(num): + return num + + +def wait_pid(pid, timeout=None, proc_name=None, + _waitpid=os.waitpid, + _timer=getattr(time, 'monotonic', time.time), + _min=min, + _sleep=time.sleep, + _pid_exists=pid_exists): + """Wait for a process PID to terminate. + + If the process terminated normally by calling exit(3) or _exit(2), + or by returning from main(), the return value is the positive integer + passed to *exit(). + + If it was terminated by a signal it returns the negated value of the + signal which caused the termination (e.g. -SIGTERM). + + If PID is not a children of os.getpid() (current process) just + wait until the process disappears and return None. + + If PID does not exist at all return None immediately. + + If *timeout* != None and process is still alive raise TimeoutExpired. + timeout=0 is also possible (either return immediately or raise). + """ + if pid <= 0: + raise ValueError("can't wait for PID 0") # see "man waitpid" + interval = 0.0001 + flags = 0 + if timeout is not None: + flags |= os.WNOHANG + stop_at = _timer() + timeout + + def sleep(interval): + # Sleep for some time and return a new increased interval. + if timeout is not None: + if _timer() >= stop_at: + raise TimeoutExpired(timeout, pid=pid, name=proc_name) + _sleep(interval) + return _min(interval * 2, 0.04) + + # See: https://linux.die.net/man/2/waitpid + while True: + try: + retpid, status = os.waitpid(pid, flags) + except InterruptedError: + interval = sleep(interval) + except ChildProcessError: + # This has two meanings: + # - PID is not a child of os.getpid() in which case + # we keep polling until it's gone + # - PID never existed in the first place + # In both cases we'll eventually return None as we + # can't determine its exit status code. + while _pid_exists(pid): + interval = sleep(interval) + return + else: + if retpid == 0: + # WNOHANG flag was used and PID is still running. + interval = sleep(interval) + continue + elif os.WIFEXITED(status): + # Process terminated normally by calling exit(3) or _exit(2), + # or by returning from main(). The return value is the + # positive integer passed to *exit(). + return os.WEXITSTATUS(status) + elif os.WIFSIGNALED(status): + # Process exited due to a signal. Return the negative value + # of that signal. + return negsig_to_enum(-os.WTERMSIG(status)) + # elif os.WIFSTOPPED(status): + # # Process was stopped via SIGSTOP or is being traced, and + # # waitpid() was called with WUNTRACED flag. PID is still + # # alive. From now on waitpid() will keep returning (0, 0) + # # until the process state doesn't change. + # # It may make sense to catch/enable this since stopped PIDs + # # ignore SIGTERM. + # interval = sleep(interval) + # continue + # elif os.WIFCONTINUED(status): + # # Process was resumed via SIGCONT and waitpid() was called + # # with WCONTINUED flag. + # interval = sleep(interval) + # continue + else: + # Should never happen. + raise ValueError("unknown process exit status %r" % status) + + +def disk_usage(path): + """Return disk usage associated with path. + Note: UNIX usually reserves 5% disk space which is not accessible + by user. In this function "total" and "used" values reflect the + total and used disk space whereas "free" and "percent" represent + the "free" and "used percent" user disk space. + """ + if PY3: + st = os.statvfs(path) + else: # pragma: no cover + # os.statvfs() does not support unicode on Python 2: + # - https://github.com/giampaolo/psutil/issues/416 + # - http://bugs.python.org/issue18695 + try: + st = os.statvfs(path) + except UnicodeEncodeError: + if isinstance(path, unicode): + try: + path = path.encode(sys.getfilesystemencoding()) + except UnicodeEncodeError: + pass + st = os.statvfs(path) + else: + raise + + # Total space which is only available to root (unless changed + # at system level). + total = (st.f_blocks * st.f_frsize) + # Remaining free space usable by root. + avail_to_root = (st.f_bfree * st.f_frsize) + # Remaining free space usable by user. + avail_to_user = (st.f_bavail * st.f_frsize) + # Total space being used in general. + used = (total - avail_to_root) + # Total space which is available to user (same as 'total' but + # for the user). + total_user = used + avail_to_user + # User usage percent compared to the total amount of space + # the user can use. This number would be higher if compared + # to root's because the user has less space (usually -5%). + usage_percent_user = usage_percent(used, total_user, round_=1) + + # NB: the percentage is -5% than what shown by df due to + # reserved blocks that we are currently not considering: + # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462 + return sdiskusage( + total=total, used=used, free=avail_to_user, percent=usage_percent_user) + + +@memoize +def get_terminal_map(): + """Get a map of device-id -> path as a dict. + Used by Process.terminal() + """ + ret = {} + ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*') + for name in ls: + assert name not in ret, name + try: + ret[os.stat(name).st_rdev] = name + except FileNotFoundError: + pass + return ret diff --git a/shared/package-files/7b/7bcb49ebd19d66ee15829456f399e5c405eb63763823cc60ebcc5eefdcb6b834/blob b/shared/package-files/7b/7bcb49ebd19d66ee15829456f399e5c405eb63763823cc60ebcc5eefdcb6b834/blob new file mode 100644 index 0000000000000000000000000000000000000000..aef9097879fcaf02efa50f7c5e3d33f492e14495 --- /dev/null +++ b/shared/package-files/7b/7bcb49ebd19d66ee15829456f399e5c405eb63763823cc60ebcc5eefdcb6b834/blob @@ -0,0 +1,580 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral + +import numpy as np +from scipy.sparse import issparse +from scipy.special import digamma + +from ..metrics.cluster import mutual_info_score +from ..neighbors import KDTree, NearestNeighbors +from ..preprocessing import scale +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.multiclass import check_classification_targets +from ..utils.parallel import Parallel, delayed +from ..utils.validation import check_array, check_X_y + + +def _compute_mi_cc(x, y, n_neighbors): + """Compute mutual information between two continuous variables. + + Parameters + ---------- + x, y : ndarray, shape (n_samples,) + Samples of two continuous random variables, must have an identical + shape. + + n_neighbors : int + Number of nearest neighbors to search for each point, see [1]_. + + Returns + ------- + mi : float + Estimated mutual information in nat units. If it turned out to be + negative it is replaced by 0. + + Notes + ----- + True mutual information can't be negative. If its estimate by a numerical + method is negative, it means (providing the method is adequate) that the + mutual information is close to 0 and replacing it by 0 is a reasonable + strategy. + + References + ---------- + .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + """ + n_samples = x.size + + x = x.reshape((-1, 1)) + y = y.reshape((-1, 1)) + xy = np.hstack((x, y)) + + # Here we rely on NearestNeighbors to select the fastest algorithm. + nn = NearestNeighbors(metric="chebyshev", n_neighbors=n_neighbors) + + nn.fit(xy) + radius = nn.kneighbors()[0] + radius = np.nextafter(radius[:, -1], 0) + + # KDTree is explicitly fit to allow for the querying of number of + # neighbors within a specified radius + kd = KDTree(x, metric="chebyshev") + nx = kd.query_radius(x, radius, count_only=True, return_distance=False) + nx = np.array(nx) - 1.0 + + kd = KDTree(y, metric="chebyshev") + ny = kd.query_radius(y, radius, count_only=True, return_distance=False) + ny = np.array(ny) - 1.0 + + mi = ( + digamma(n_samples) + + digamma(n_neighbors) + - np.mean(digamma(nx + 1)) + - np.mean(digamma(ny + 1)) + ) + + return max(0, mi) + + +def _compute_mi_cd(c, d, n_neighbors): + """Compute mutual information between continuous and discrete variables. + + Parameters + ---------- + c : ndarray, shape (n_samples,) + Samples of a continuous random variable. + + d : ndarray, shape (n_samples,) + Samples of a discrete random variable. + + n_neighbors : int + Number of nearest neighbors to search for each point, see [1]_. + + Returns + ------- + mi : float + Estimated mutual information in nat units. If it turned out to be + negative it is replaced by 0. + + Notes + ----- + True mutual information can't be negative. If its estimate by a numerical + method is negative, it means (providing the method is adequate) that the + mutual information is close to 0 and replacing it by 0 is a reasonable + strategy. + + References + ---------- + .. [1] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + """ + n_samples = c.shape[0] + c = c.reshape((-1, 1)) + + radius = np.empty(n_samples) + label_counts = np.empty(n_samples) + k_all = np.empty(n_samples) + nn = NearestNeighbors() + for label in np.unique(d): + mask = d == label + count = np.sum(mask) + if count > 1: + k = min(n_neighbors, count - 1) + nn.set_params(n_neighbors=k) + nn.fit(c[mask]) + r = nn.kneighbors()[0] + radius[mask] = np.nextafter(r[:, -1], 0) + k_all[mask] = k + label_counts[mask] = count + + # Ignore points with unique labels. + mask = label_counts > 1 + n_samples = np.sum(mask) + label_counts = label_counts[mask] + k_all = k_all[mask] + c = c[mask] + radius = radius[mask] + + kd = KDTree(c) + m_all = kd.query_radius(c, radius, count_only=True, return_distance=False) + m_all = np.array(m_all) + + mi = ( + digamma(n_samples) + + np.mean(digamma(k_all)) + - np.mean(digamma(label_counts)) + - np.mean(digamma(m_all)) + ) + + return max(0, mi) + + +def _compute_mi(x, y, x_discrete, y_discrete, n_neighbors=3): + """Compute mutual information between two variables. + + This is a simple wrapper which selects a proper function to call based on + whether `x` and `y` are discrete or not. + """ + if x_discrete and y_discrete: + return mutual_info_score(x, y) + elif x_discrete and not y_discrete: + return _compute_mi_cd(y, x, n_neighbors) + elif not x_discrete and y_discrete: + return _compute_mi_cd(x, y, n_neighbors) + else: + return _compute_mi_cc(x, y, n_neighbors) + + +def _iterate_columns(X, columns=None): + """Iterate over columns of a matrix. + + Parameters + ---------- + X : ndarray or csc_matrix, shape (n_samples, n_features) + Matrix over which to iterate. + + columns : iterable or None, default=None + Indices of columns to iterate over. If None, iterate over all columns. + + Yields + ------ + x : ndarray, shape (n_samples,) + Columns of `X` in dense format. + """ + if columns is None: + columns = range(X.shape[1]) + + if issparse(X): + for i in columns: + x = np.zeros(X.shape[0]) + start_ptr, end_ptr = X.indptr[i], X.indptr[i + 1] + x[X.indices[start_ptr:end_ptr]] = X.data[start_ptr:end_ptr] + yield x + else: + for i in columns: + yield X[:, i] + + +def _estimate_mi( + X, + y, + *, + discrete_features="auto", + discrete_target=False, + n_neighbors=3, + copy=True, + random_state=None, + n_jobs=None, +): + """Estimate mutual information between the features and the target. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Feature matrix. + + y : array-like of shape (n_samples,) + Target vector. + + discrete_features : {'auto', bool, array-like}, default='auto' + If bool, then determines whether to consider all features discrete + or continuous. If array, then it should be either a boolean mask + with shape (n_features,) or array with indices of discrete features. + If 'auto', it is assigned to False for dense `X` and to True for + sparse `X`. + + discrete_target : bool, default=False + Whether to consider `y` as a discrete variable. + + n_neighbors : int, default=3 + Number of neighbors to use for MI estimation for continuous variables, + see [1]_ and [2]_. Higher values reduce variance of the estimation, but + could introduce a bias. + + copy : bool, default=True + Whether to make a copy of the given data. If set to False, the initial + data will be overwritten. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for adding small noise to + continuous variables in order to remove repeated values. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of jobs to use for computing the mutual information. + The parallelization is done on the columns of `X`. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 1.5 + + + Returns + ------- + mi : ndarray, shape (n_features,) + Estimated mutual information between each feature and the target in + nat units. A negative value will be replaced by 0. + + References + ---------- + .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + .. [2] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + """ + X, y = check_X_y(X, y, accept_sparse="csc", y_numeric=not discrete_target) + n_samples, n_features = X.shape + + if isinstance(discrete_features, (str, bool)): + if isinstance(discrete_features, str): + if discrete_features == "auto": + discrete_features = issparse(X) + else: + raise ValueError("Invalid string value for discrete_features.") + discrete_mask = np.empty(n_features, dtype=bool) + discrete_mask.fill(discrete_features) + else: + discrete_features = check_array(discrete_features, ensure_2d=False) + if discrete_features.dtype != "bool": + discrete_mask = np.zeros(n_features, dtype=bool) + discrete_mask[discrete_features] = True + else: + discrete_mask = discrete_features + + continuous_mask = ~discrete_mask + if np.any(continuous_mask) and issparse(X): + raise ValueError("Sparse matrix `X` can't have continuous features.") + + rng = check_random_state(random_state) + if np.any(continuous_mask): + X = X.astype(np.float64, copy=copy) + X[:, continuous_mask] = scale( + X[:, continuous_mask], with_mean=False, copy=False + ) + + # Add small noise to continuous features as advised in Kraskov et. al. + means = np.maximum(1, np.mean(np.abs(X[:, continuous_mask]), axis=0)) + X[:, continuous_mask] += ( + 1e-10 + * means + * rng.standard_normal(size=(n_samples, np.sum(continuous_mask))) + ) + + if not discrete_target: + y = scale(y, with_mean=False) + y += ( + 1e-10 + * np.maximum(1, np.mean(np.abs(y))) + * rng.standard_normal(size=n_samples) + ) + + mi = Parallel(n_jobs=n_jobs)( + delayed(_compute_mi)(x, y, discrete_feature, discrete_target, n_neighbors) + for x, discrete_feature in zip(_iterate_columns(X), discrete_mask) + ) + + return np.array(mi) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like"], + "discrete_features": [StrOptions({"auto"}), "boolean", "array-like"], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "copy": ["boolean"], + "random_state": ["random_state"], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=True, +) +def mutual_info_regression( + X, + y, + *, + discrete_features="auto", + n_neighbors=3, + copy=True, + random_state=None, + n_jobs=None, +): + """Estimate mutual information for a continuous target variable. + + Mutual information (MI) [1]_ between two random variables is a non-negative + value, which measures the dependency between the variables. It is equal + to zero if and only if two random variables are independent, and higher + values mean higher dependency. + + The function relies on nonparametric methods based on entropy estimation + from k-nearest neighbors distances as described in [2]_ and [3]_. Both + methods are based on the idea originally proposed in [4]_. + + It can be used for univariate features selection, read more in the + :ref:`User Guide `. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Feature matrix. + + y : array-like of shape (n_samples,) + Target vector. + + discrete_features : {'auto', bool, array-like}, default='auto' + If bool, then determines whether to consider all features discrete + or continuous. If array, then it should be either a boolean mask + with shape (n_features,) or array with indices of discrete features. + If 'auto', it is assigned to False for dense `X` and to True for + sparse `X`. + + n_neighbors : int, default=3 + Number of neighbors to use for MI estimation for continuous variables, + see [2]_ and [3]_. Higher values reduce variance of the estimation, but + could introduce a bias. + + copy : bool, default=True + Whether to make a copy of the given data. If set to False, the initial + data will be overwritten. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for adding small noise to + continuous variables in order to remove repeated values. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of jobs to use for computing the mutual information. + The parallelization is done on the columns of `X`. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 1.5 + + Returns + ------- + mi : ndarray, shape (n_features,) + Estimated mutual information between each feature and the target in + nat units. + + Notes + ----- + 1. The term "discrete features" is used instead of naming them + "categorical", because it describes the essence more accurately. + For example, pixel intensities of an image are discrete features + (but hardly categorical) and you will get better results if mark them + as such. Also note, that treating a continuous variable as discrete and + vice versa will usually give incorrect results, so be attentive about + that. + 2. True mutual information can't be negative. If its estimate turns out + to be negative, it is replaced by zero. + + References + ---------- + .. [1] `Mutual Information + `_ + on Wikipedia. + .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + .. [3] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy + of a Random Vector", Probl. Peredachi Inf., 23:2 (1987), 9-16 + + Examples + -------- + >>> from sklearn.datasets import make_regression + >>> from sklearn.feature_selection import mutual_info_regression + >>> X, y = make_regression( + ... n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42 + ... ) + >>> mutual_info_regression(X, y) + array([0.117, 2.645, 0.0287]) + """ + return _estimate_mi( + X, + y, + discrete_features=discrete_features, + discrete_target=False, + n_neighbors=n_neighbors, + copy=copy, + random_state=random_state, + n_jobs=n_jobs, + ) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like"], + "discrete_features": [StrOptions({"auto"}), "boolean", "array-like"], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "copy": ["boolean"], + "random_state": ["random_state"], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=True, +) +def mutual_info_classif( + X, + y, + *, + discrete_features="auto", + n_neighbors=3, + copy=True, + random_state=None, + n_jobs=None, +): + """Estimate mutual information for a discrete target variable. + + Mutual information (MI) [1]_ between two random variables is a non-negative + value, which measures the dependency between the variables. It is equal + to zero if and only if two random variables are independent, and higher + values mean higher dependency. + + The function relies on nonparametric methods based on entropy estimation + from k-nearest neighbors distances as described in [2]_ and [3]_. Both + methods are based on the idea originally proposed in [4]_. + + It can be used for univariate features selection, read more in the + :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Feature matrix. + + y : array-like of shape (n_samples,) + Target vector. + + discrete_features : 'auto', bool or array-like, default='auto' + If bool, then determines whether to consider all features discrete + or continuous. If array, then it should be either a boolean mask + with shape (n_features,) or array with indices of discrete features. + If 'auto', it is assigned to False for dense `X` and to True for + sparse `X`. + + n_neighbors : int, default=3 + Number of neighbors to use for MI estimation for continuous variables, + see [2]_ and [3]_. Higher values reduce variance of the estimation, but + could introduce a bias. + + copy : bool, default=True + Whether to make a copy of the given data. If set to False, the initial + data will be overwritten. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for adding small noise to + continuous variables in order to remove repeated values. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of jobs to use for computing the mutual information. + The parallelization is done on the columns of `X`. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 1.5 + + Returns + ------- + mi : ndarray, shape (n_features,) + Estimated mutual information between each feature and the target in + nat units. + + Notes + ----- + 1. The term "discrete features" is used instead of naming them + "categorical", because it describes the essence more accurately. + For example, pixel intensities of an image are discrete features + (but hardly categorical) and you will get better results if mark them + as such. Also note, that treating a continuous variable as discrete and + vice versa will usually give incorrect results, so be attentive about + that. + 2. True mutual information can't be negative. If its estimate turns out + to be negative, it is replaced by zero. + + References + ---------- + .. [1] `Mutual Information + `_ + on Wikipedia. + .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + .. [3] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy + of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16 + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.feature_selection import mutual_info_classif + >>> X, y = make_classification( + ... n_samples=100, n_features=10, n_informative=2, n_clusters_per_class=1, + ... shuffle=False, random_state=42 + ... ) + >>> mutual_info_classif(X, y) + array([0.589, 0.107, 0.196, 0.0968 , 0., + 0. , 0. , 0. , 0. , 0.]) + """ + check_classification_targets(y) + return _estimate_mi( + X, + y, + discrete_features=discrete_features, + discrete_target=True, + n_neighbors=n_neighbors, + copy=copy, + random_state=random_state, + n_jobs=n_jobs, + ) diff --git a/shared/package-files/7b/7bcc239fad2d3b911d9e4045df826b653e57bddc96ee44560f669bb60afaa948/blob b/shared/package-files/7b/7bcc239fad2d3b911d9e4045df826b653e57bddc96ee44560f669bb60afaa948/blob new file mode 100644 index 0000000000000000000000000000000000000000..865722d8c9448ffa601ce20838315c5df1c80852 --- /dev/null +++ b/shared/package-files/7b/7bcc239fad2d3b911d9e4045df826b653e57bddc96ee44560f669bb60afaa948/blob @@ -0,0 +1,29 @@ +import sys +from pathlib import Path +from typing import IO, Any + +import numpy as np + +if sys.version_info >= (3, 11): + from typing import assert_type +else: + from typing_extensions import assert_type + +path1: Path +path2: str + +d1 = np.DataSource(path1) +d2 = np.DataSource(path2) +d3 = np.DataSource(None) + +assert_type(d1.abspath("..."), str) +assert_type(d2.abspath("..."), str) +assert_type(d3.abspath("..."), str) + +assert_type(d1.exists("..."), bool) +assert_type(d2.exists("..."), bool) +assert_type(d3.exists("..."), bool) + +assert_type(d1.open("...", "r"), IO[Any]) +assert_type(d2.open("...", encoding="utf8"), IO[Any]) +assert_type(d3.open("...", newline="/n"), IO[Any]) diff --git a/shared/package-files/7b/7bccf225b12b5d9679f77ec191715f9d547a985eeed0c6287867b9ad1957b292/blob b/shared/package-files/7b/7bccf225b12b5d9679f77ec191715f9d547a985eeed0c6287867b9ad1957b292/blob new file mode 100644 index 0000000000000000000000000000000000000000..aa1708cb0d7e460ba62ae70a5942448e6f9b8513 --- /dev/null +++ b/shared/package-files/7b/7bccf225b12b5d9679f77ec191715f9d547a985eeed0c6287867b9ad1957b292/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bccf225b12b5d9679f77ec191715f9d547a985eeed0c6287867b9ad1957b292 +size 606600 diff --git a/shared/package-files/7b/7bcd168f5acab38d70bf84f8b5554679d1a781359f5c1f186a5ece4b789744ab/blob b/shared/package-files/7b/7bcd168f5acab38d70bf84f8b5554679d1a781359f5c1f186a5ece4b789744ab/blob new file mode 100644 index 0000000000000000000000000000000000000000..09245b5218c174d4a247e186725939231bdf17cc --- /dev/null +++ b/shared/package-files/7b/7bcd168f5acab38d70bf84f8b5554679d1a781359f5c1f186a5ece4b789744ab/blob @@ -0,0 +1,134 @@ +import sys +from typing import Any, Dict, NoReturn, Optional, Sequence, Tuple, Union, overload +from typing_extensions import Literal + +CREATE_NEW_CONSOLE: int +CREATE_NEW_PROCESS_GROUP: int +DUPLICATE_CLOSE_SOURCE: int +DUPLICATE_SAME_ACCESS: int +ERROR_ALREADY_EXISTS: int +ERROR_BROKEN_PIPE: int +ERROR_IO_PENDING: int +ERROR_MORE_DATA: int +ERROR_NETNAME_DELETED: int +ERROR_NO_DATA: int +ERROR_NO_SYSTEM_RESOURCES: int +ERROR_OPERATION_ABORTED: int +ERROR_PIPE_BUSY: int +ERROR_PIPE_CONNECTED: int +ERROR_SEM_TIMEOUT: int +FILE_FLAG_FIRST_PIPE_INSTANCE: int +FILE_FLAG_OVERLAPPED: int +FILE_GENERIC_READ: int +FILE_GENERIC_WRITE: int +GENERIC_READ: int +GENERIC_WRITE: int +INFINITE: int +NMPWAIT_WAIT_FOREVER: int +NULL: int +OPEN_EXISTING: int +PIPE_ACCESS_DUPLEX: int +PIPE_ACCESS_INBOUND: int +PIPE_READMODE_MESSAGE: int +PIPE_TYPE_MESSAGE: int +PIPE_UNLIMITED_INSTANCES: int +PIPE_WAIT: int +PROCESS_ALL_ACCESS: int +PROCESS_DUP_HANDLE: int +STARTF_USESHOWWINDOW: int +STARTF_USESTDHANDLES: int +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +STILL_ACTIVE: int +SW_HIDE: int +WAIT_ABANDONED_0: int +WAIT_OBJECT_0: int +WAIT_TIMEOUT: int + +def CloseHandle(__handle: int) -> None: ... +@overload +def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... +@overload +def ConnectNamedPipe(handle: int, overlapped: Literal[False] = ...) -> None: ... +@overload +def ConnectNamedPipe(handle: int, overlapped: bool) -> Optional[Overlapped]: ... +def CreateFile( + __file_name: str, + __desired_access: int, + __share_mode: int, + __security_attributes: int, + __creation_disposition: int, + __flags_and_attributes: int, + __template_file: int, +) -> int: ... +def CreateJunction(__src_path: str, __dst_path: str) -> None: ... +def CreateNamedPipe( + __name: str, + __open_mode: int, + __pipe_mode: int, + __max_instances: int, + __out_buffer_size: int, + __in_buffer_size: int, + __default_timeout: int, + __security_attributes: int, +) -> int: ... +def CreatePipe(__pipe_attrs: Any, __size: int) -> Tuple[int, int]: ... +def CreateProcess( + __application_name: Optional[str], + __command_line: Optional[str], + __proc_attrs: Any, + __thread_attrs: Any, + __inherit_handles: bool, + __creation_flags: int, + __env_mapping: Dict[str, str], + __current_directory: Optional[str], + __startup_info: Any, +) -> Tuple[int, int, int, int]: ... +def DuplicateHandle( + __source_process_handle: int, + __source_handle: int, + __target_process_handle: int, + __desired_access: int, + __inherit_handle: bool, + __options: int = ..., +) -> int: ... +def ExitProcess(__ExitCode: int) -> NoReturn: ... + +if sys.version_info >= (3, 7): + def GetACP() -> int: ... + def GetFileType(handle: int) -> int: ... + +def GetCurrentProcess() -> int: ... +def GetExitCodeProcess(__process: int) -> int: ... +def GetLastError() -> int: ... +def GetModuleFileName(__module_handle: int) -> str: ... +def GetStdHandle(__std_handle: int) -> int: ... +def GetVersion() -> int: ... +def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... +def PeekNamedPipe(__handle: int, __size: int = ...) -> Union[Tuple[int, int], Tuple[bytes, int, int]]: ... +@overload +def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> Tuple[Overlapped, int]: ... +@overload +def ReadFile(handle: int, size: int, overlapped: Literal[False] = ...) -> Tuple[bytes, int]: ... +@overload +def ReadFile(handle: int, size: int, overlapped: Union[int, bool]) -> Tuple[Any, int]: ... +def SetNamedPipeHandleState( + __named_pipe: int, __mode: Optional[int], __max_collection_count: Optional[int], __collect_data_timeout: Optional[int] +) -> None: ... +def TerminateProcess(__handle: int, __exit_code: int) -> None: ... +def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = ...) -> int: ... +def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... +def WaitNamedPipe(__name: str, __timeout: int) -> None: ... +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> Tuple[Overlapped, int]: ... +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Literal[False] = ...) -> Tuple[int, int]: ... +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Union[int, bool]) -> Tuple[Any, int]: ... + +class Overlapped: + event: int = ... + def GetOverlappedResult(self, __wait: bool) -> Tuple[int, int]: ... + def cancel(self) -> None: ... + def getbuffer(self) -> Optional[bytes]: ... diff --git a/shared/package-files/7b/7bcfafae9425ca1d8206721121800af7170cb565dd5ebd22d469b3d777933ac9/blob b/shared/package-files/7b/7bcfafae9425ca1d8206721121800af7170cb565dd5ebd22d469b3d777933ac9/blob new file mode 100644 index 0000000000000000000000000000000000000000..7d4a2ffbfb292bbddf5ee65dd42bbc4f03eb7fe6 --- /dev/null +++ b/shared/package-files/7b/7bcfafae9425ca1d8206721121800af7170cb565dd5ebd22d469b3d777933ac9/blob @@ -0,0 +1,136 @@ +"""Support for the `bgcl` (Apple Color Emoji background) table. + +This table stores a JSON blob. We decode it to a Python object on +decompile and emit human readable JSON in the TTX via a element. +On compile we re-encode the JSON to UTF-8 bytes which is what Apple code +reads via CTFontCopyTable then JSONDecoder. + +On iOS 16 and later the `bgcl` payload is used as the wallpaper +background when the user selects an emoji wallpaper. + +Fields: + +- ``colors``: list of palette entries. Each entry is an array of four + integers ``[R, G, B, A]``. R/G/B are 0-255. A is 0-1. + +- ``emojicolors``: list of per-emoji palettes. Each item is an array of + three sublists: primary/dominant, accent, contextual + (names inferred). Each sublist contains integer indexes referencing + entries in ``colors``; the runtime uses these to assemble layered + background tints for an emoji. + +- ``indexmap``: mapping (glyph identifier → palette index). The map + maps a glyph identity to an integer index selecting an entry in + ``emojicolors``. The font/UI uses this to pick the correct palette + for a glyph when rendering wallpaper backgrounds. + +- ``version``: integer table version used for parsing/compatibility. + +Runtime usage summary: + +- The system fetches the table bytes with ``CTFontCopyTable('bgcl')``, + decodes the bytes as UTF‑8 JSON and runs the JSON through the app's + decoder into an internal ``BgclTable`` structure. The app looks up a + glyph's entry in ``indexmap``, retrieves the corresponding + ``emojicolors`` palette, then converts the referenced ``colors`` + entries into color objects (normalizing channels/alpha as needed). + This resulting color(s) drive the wallpaper background appearance for + emoji wallpapers on supported iOS versions. + +This implementation preserves the JSON payload and exposes convenience +attributes ``colors``, ``emojicolors``, ``indexmap`` and ``version`` +when available. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from fontTools.misc.textTools import tostr, strjoin +from . import DefaultTable +import json + +if TYPE_CHECKING: + from fontTools.misc.xmlWriter import XMLWriter + from fontTools.ttLib import TTFont + + +class table__b_g_c_l(DefaultTable.DefaultTable): + """bgcl table: stores a JSON blob describing background palettes. + + The JSON structure typically contains the top-level keys: + - colors: [[R,G,B,A], ...] + - emojicolors: [[[dominant...],[accent...],[contextual...]], ...] + - indexmap: {"glyphIndex": emojicolors_index, ...} + - version: int + """ + + def decompile(self, data: bytes, ttFont: TTFont) -> None: + """Store raw bytes and attempt to parse JSON. + + The JSON commonly includes palette/lookup data used at runtime to + construct wallpaper/background colors for emoji wallpapers on + recent iOS releases. + """ + self.data = data + try: + text = tostr(data, "utf_8") + self.json = json.loads(text) + except Exception as e: # keep table decompilation robust + self.json = None + self.ERROR = f"bgcl JSON parse error: {e!r}" + return + # convenient attributes + self.colors = self.json.get("colors") + self.emojicolors = self.json.get("emojicolors") + self.indexmap = self.json.get("indexmap") + self.version = self.json.get("version") + + def compile(self, ttFont: TTFont) -> bytes: + """Encode the JSON object to UTF-8 bytes for font binary storage.""" + if getattr(self, "json", None) is None: + # fallback to raw bytes if parsing failed earlier + return getattr(self, "data", b"") + # use compact representation for binary table + return json.dumps(self.json, separators=(",", ":"), ensure_ascii=False).encode( + "utf_8" + ) + + def toXML(self, writer: XMLWriter, ttFont: TTFont) -> None: + """Emit pretty-printed JSON inside a element for human inspection.""" + if getattr(self, "json", None) is None: + # fallback to default hex output + DefaultTable.DefaultTable.toXML(self, writer, ttFont) + return + writer.begintag("json") + writer.newline() + pretty = json.dumps(self.json, indent=2, ensure_ascii=False) + writer.writecdata(pretty) + writer.newline() + writer.endtag("json") + writer.newline() + + def fromXML( + self, name: str, attrs: dict[str, str], content, ttFont: TTFont + ) -> None: + """Read JSON from the element. `content` may be a list. + + This mirrors SVG/other table `fromXML` handlers which accept a + list of content chunks. + """ + if name != "json": + # fall back to DefaultTable behavior for unknown elements + return DefaultTable.DefaultTable.fromXML(self, name, attrs, content, ttFont) + text = strjoin(content).strip() + try: + self.json = json.loads(text) + # keep raw bytes in sync + self.data = text.encode("utf_8") + self.colors = self.json.get("colors") + self.emojicolors = self.json.get("emojicolors") + self.indexmap = self.json.get("indexmap") + self.version = self.json.get("version") + except Exception as e: + # store error and fall back to raw + self.json = None + self.ERROR = f"bgcl JSON parse error in fromXML: {e!r}" diff --git a/shared/package-files/7b/7bd248e17a43ce40fca587e1011f62fecb032a578ece83b7e94a683e89aad33e/infer.py b/shared/package-files/7b/7bd248e17a43ce40fca587e1011f62fecb032a578ece83b7e94a683e89aad33e/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..cec564558ab6c52b6d702aa97d84946de44d6900 --- /dev/null +++ b/shared/package-files/7b/7bd248e17a43ce40fca587e1011f62fecb032a578ece83b7e94a683e89aad33e/infer.py @@ -0,0 +1,35 @@ +"""One fixed public-condition composition of two task-trained retrieval packages.""" +import argparse,hashlib,json,os,subprocess,tempfile +from pathlib import Path + +def read(path):return [json.loads(s) for s in path.open() if s.strip()] +def sha(path): + h=hashlib.sha256() + with path.open('rb') as f: + for b in iter(lambda:f.read(1<<20),b''):h.update(b) + return h.hexdigest() +def main(): + p=argparse.ArgumentParser();p.add_argument('input',type=Path);p.add_argument('output',type=Path);a=p.parse_args();root=Path(__file__).resolve().parent;cfg=json.loads((root/'model_config.json').read_text());queries=read(a.input/'queries.jsonl');pools={r['candidate_pool_id']:r for r in read(a.input/'candidate_pools.jsonl')};groups={'native':[],'inverse':[]} + for q in queries:groups['native' if q['adduct']=='[M+H]+' and q.get('collision_energy') is not None else 'inverse'].append(q) + result={};env=dict(os.environ,PYTHONDONTWRITEBYTECODE='1',OMP_NUM_THREADS='4',OPENBLAS_NUM_THREADS='1',DGLBACKEND='pytorch') + with tempfile.TemporaryDirectory(prefix='massspecgym-conditions-') as tmp: + tmp=Path(tmp) + for name,rows in groups.items(): + pkg=root/name;m=json.loads((pkg/'model_manifest.json').read_text());cp=pkg/m['checkpoint']['path'];assert cp.resolve().is_relative_to(root) and sha(cp)==cfg[name+'_checkpoint_sha256'] + if not rows:continue + inp=tmp/(name+'-input');inp.mkdir();used={q['candidate_pool_id'] for q in rows} + for filename,values in [('queries.jsonl',rows),('candidate_pools.jsonl',[pools[k] for k in sorted(used)])]: + with (inp/filename).open('w') as f: + for row in values:f.write(json.dumps(row,separators=(',',':'))+'\n') + (inp/'manifest.json').write_text(json.dumps({'schema':'massspecgym-retrieval-input/v1','source':'public-condition partition; no labels','counts':{'queries':len(rows),'candidate_pools':len(used)},'files':{n:sha(inp/n) for n in ['queries.jsonl','candidate_pools.jsonl']}})) + out=tmp/(name+'-output');subprocess.run(['bash',str(pkg/'infer.sh'),str(inp),str(out)],check=True,env=env) + records=read(out/'rankings.jsonl');expected={q['query_id']:q for q in rows};assert len(records)==len(expected) and {r['query_id'] for r in records}==set(expected) + for r in records: + q=expected[r['query_id']];ids={c['candidate_id'] for c in pools[q['candidate_pool_id']]['candidates']};assert len(r['ranking'])==len(ids) and set(r['ranking'])==ids;result[r['query_id']]=r + a.output.mkdir(parents=True,exist_ok=True);assert not any(a.output.iterdir()) + partial=a.output/'rankings.jsonl.tmp' + with partial.open('w') as f: + for q in queries:f.write(json.dumps(result[q['query_id']],separators=(',',':'))+'\n') + os.replace(partial,a.output/'rankings.jsonl') + print(json.dumps({'queries_ranked':len(result),'branch_queries':{k:len(v) for k,v in groups.items()},'routing_fields':['adduct','collision_energy presence']}),flush=True) +if __name__=='__main__':main() diff --git a/shared/package-files/7b/7bd63b4505a1f26125dc489edf1ce09e24a08c70bf9e52eb8c10a2631e6936cf/blob b/shared/package-files/7b/7bd63b4505a1f26125dc489edf1ce09e24a08c70bf9e52eb8c10a2631e6936cf/blob new file mode 100644 index 0000000000000000000000000000000000000000..43847496fa17e618fbdbf4e9478360e008f88ab5 --- /dev/null +++ b/shared/package-files/7b/7bd63b4505a1f26125dc489edf1ce09e24a08c70bf9e52eb8c10a2631e6936cf/blob @@ -0,0 +1,525 @@ +""" +API that are reported to numba.cuda +""" + + +import contextlib +import os + +import numpy as np + +from .cudadrv import devicearray, devices, driver +from numba.core import config +from numba.cuda.api_util import prepare_shape_strides_dtype + +# NDarray device helper + +require_context = devices.require_context +current_context = devices.get_context +gpus = devices.gpus + + +@require_context +def from_cuda_array_interface(desc, owner=None, sync=True): + """Create a DeviceNDArray from a cuda-array-interface description. + The ``owner`` is the owner of the underlying memory. + The resulting DeviceNDArray will acquire a reference from it. + + If ``sync`` is ``True``, then the imported stream (if present) will be + synchronized. + """ + version = desc.get('version') + # Mask introduced in version 1 + if 1 <= version: + mask = desc.get('mask') + # Would ideally be better to detect if the mask is all valid + if mask is not None: + raise NotImplementedError('Masked arrays are not supported') + + shape = desc['shape'] + strides = desc.get('strides') + dtype = np.dtype(desc['typestr']) + + shape, strides, dtype = prepare_shape_strides_dtype( + shape, strides, dtype, order='C') + size = driver.memory_size_from_info(shape, strides, dtype.itemsize) + + devptr = driver.get_devptr_for_active_ctx(desc['data'][0]) + data = driver.MemoryPointer( + current_context(), devptr, size=size, owner=owner) + stream_ptr = desc.get('stream', None) + if stream_ptr is not None: + stream = external_stream(stream_ptr) + if sync and config.CUDA_ARRAY_INTERFACE_SYNC: + stream.synchronize() + else: + stream = 0 # No "Numba default stream", not the CUDA default stream + da = devicearray.DeviceNDArray(shape=shape, strides=strides, + dtype=dtype, gpu_data=data, + stream=stream) + return da + + +def as_cuda_array(obj, sync=True): + """Create a DeviceNDArray from any object that implements + the :ref:`cuda array interface `. + + A view of the underlying GPU buffer is created. No copying of the data + is done. The resulting DeviceNDArray will acquire a reference from `obj`. + + If ``sync`` is ``True``, then the imported stream (if present) will be + synchronized. + """ + if not is_cuda_array(obj): + raise TypeError("*obj* doesn't implement the cuda array interface.") + else: + return from_cuda_array_interface(obj.__cuda_array_interface__, + owner=obj, sync=sync) + + +def is_cuda_array(obj): + """Test if the object has defined the `__cuda_array_interface__` attribute. + + Does not verify the validity of the interface. + """ + return hasattr(obj, '__cuda_array_interface__') + + +def is_float16_supported(): + """Whether 16-bit floats are supported. + + float16 is always supported in current versions of Numba - returns True. + """ + return True + + +@require_context +def to_device(obj, stream=0, copy=True, to=None): + """to_device(obj, stream=0, copy=True, to=None) + + Allocate and transfer a numpy ndarray or structured scalar to the device. + + To copy host->device a numpy array:: + + ary = np.arange(10) + d_ary = cuda.to_device(ary) + + To enqueue the transfer to a stream:: + + stream = cuda.stream() + d_ary = cuda.to_device(ary, stream=stream) + + The resulting ``d_ary`` is a ``DeviceNDArray``. + + To copy device->host:: + + hary = d_ary.copy_to_host() + + To copy device->host to an existing array:: + + ary = np.empty(shape=d_ary.shape, dtype=d_ary.dtype) + d_ary.copy_to_host(ary) + + To enqueue the transfer to a stream:: + + hary = d_ary.copy_to_host(stream=stream) + """ + if to is None: + to, new = devicearray.auto_device(obj, stream=stream, copy=copy, + user_explicit=True) + return to + if copy: + to.copy_to_device(obj, stream=stream) + return to + + +@require_context +def device_array(shape, dtype=np.float64, strides=None, order='C', stream=0): + """device_array(shape, dtype=np.float64, strides=None, order='C', stream=0) + + Allocate an empty device ndarray. Similar to :meth:`numpy.empty`. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + return devicearray.DeviceNDArray(shape=shape, strides=strides, dtype=dtype, + stream=stream) + + +@require_context +def managed_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + attach_global=True): + """managed_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + attach_global=True) + + Allocate a np.ndarray with a buffer that is managed. + Similar to np.empty(). + + Managed memory is supported on Linux / x86 and PowerPC, and is considered + experimental on Windows and Linux / AArch64. + + :param attach_global: A flag indicating whether to attach globally. Global + attachment implies that the memory is accessible from + any stream on any device. If ``False``, attachment is + *host*, and memory is only accessible by devices + with Compute Capability 6.0 and later. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize) + buffer = current_context().memallocmanaged(bytesize, + attach_global=attach_global) + npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, + buffer=buffer) + managedview = np.ndarray.view(npary, type=devicearray.ManagedNDArray) + managedview.device_setup(buffer, stream=stream) + return managedview + + +@require_context +def pinned_array(shape, dtype=np.float64, strides=None, order='C'): + """pinned_array(shape, dtype=np.float64, strides=None, order='C') + + Allocate an :class:`ndarray ` with a buffer that is pinned + (pagelocked). Similar to :func:`np.empty() `. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + bytesize = driver.memory_size_from_info(shape, strides, + dtype.itemsize) + buffer = current_context().memhostalloc(bytesize) + return np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, + buffer=buffer) + + +@require_context +def mapped_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + portable=False, wc=False): + """mapped_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + portable=False, wc=False) + + Allocate a mapped ndarray with a buffer that is pinned and mapped on + to the device. Similar to np.empty() + + :param portable: a boolean flag to allow the allocated device memory to be + usable in multiple devices. + :param wc: a boolean flag to enable writecombined allocation which is faster + to write by the host and to read by the device, but slower to + write by the host and slower to write by the device. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize) + buffer = current_context().memhostalloc(bytesize, mapped=True) + npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, + buffer=buffer) + mappedview = np.ndarray.view(npary, type=devicearray.MappedNDArray) + mappedview.device_setup(buffer, stream=stream) + return mappedview + + +@contextlib.contextmanager +@require_context +def open_ipc_array(handle, shape, dtype, strides=None, offset=0): + """ + A context manager that opens a IPC *handle* (*CUipcMemHandle*) that is + represented as a sequence of bytes (e.g. *bytes*, tuple of int) + and represent it as an array of the given *shape*, *strides* and *dtype*. + The *strides* can be omitted. In that case, it is assumed to be a 1D + C contiguous array. + + Yields a device array. + + The IPC handle is closed automatically when context manager exits. + """ + dtype = np.dtype(dtype) + # compute size + size = np.prod(shape) * dtype.itemsize + # manually recreate the IPC mem handle + if driver.USE_NV_BINDING: + driver_handle = driver.binding.CUipcMemHandle() + driver_handle.reserved = handle + else: + driver_handle = driver.drvapi.cu_ipc_mem_handle(*handle) + # use *IpcHandle* to open the IPC memory + ipchandle = driver.IpcHandle(None, driver_handle, size, offset=offset) + yield ipchandle.open_array(current_context(), shape=shape, + strides=strides, dtype=dtype) + ipchandle.close() + + +def synchronize(): + "Synchronize the current context." + return current_context().synchronize() + + +def _contiguous_strides_like_array(ary): + """ + Given an array, compute strides for a new contiguous array of the same + shape. + """ + # Don't recompute strides if the default strides will be sufficient to + # create a contiguous array. + if ary.flags['C_CONTIGUOUS'] or ary.flags['F_CONTIGUOUS'] or ary.ndim <= 1: + return None + + # Otherwise, we need to compute new strides using an algorithm adapted from + # NumPy v1.17.4's PyArray_NewLikeArrayWithShape in + # core/src/multiarray/ctors.c. We permute the strides in ascending order + # then compute the stride for the dimensions with the same permutation. + + # Stride permutation. E.g. a stride array (4, -2, 12) becomes + # [(1, -2), (0, 4), (2, 12)] + strideperm = [ x for x in enumerate(ary.strides) ] + strideperm.sort(key=lambda x: x[1]) + + # Compute new strides using permutation + strides = [0] * len(ary.strides) + stride = ary.dtype.itemsize + for i_perm, _ in strideperm: + strides[i_perm] = stride + stride *= ary.shape[i_perm] + return tuple(strides) + + +def _order_like_array(ary): + if ary.flags['F_CONTIGUOUS'] and not ary.flags['C_CONTIGUOUS']: + return 'F' + else: + return 'C' + + +def device_array_like(ary, stream=0): + """ + Call :func:`device_array() ` with information from + the array. + """ + strides = _contiguous_strides_like_array(ary) + order = _order_like_array(ary) + return device_array(shape=ary.shape, dtype=ary.dtype, strides=strides, + order=order, stream=stream) + + +def mapped_array_like(ary, stream=0, portable=False, wc=False): + """ + Call :func:`mapped_array() ` with the information + from the array. + """ + strides = _contiguous_strides_like_array(ary) + order = _order_like_array(ary) + return mapped_array(shape=ary.shape, dtype=ary.dtype, strides=strides, + order=order, stream=stream, portable=portable, wc=wc) + + +def pinned_array_like(ary): + """ + Call :func:`pinned_array() ` with the information + from the array. + """ + strides = _contiguous_strides_like_array(ary) + order = _order_like_array(ary) + return pinned_array(shape=ary.shape, dtype=ary.dtype, strides=strides, + order=order) + + +# Stream helper +@require_context +def stream(): + """ + Create a CUDA stream that represents a command queue for the device. + """ + return current_context().create_stream() + + +@require_context +def default_stream(): + """ + Get the default CUDA stream. CUDA semantics in general are that the default + stream is either the legacy default stream or the per-thread default stream + depending on which CUDA APIs are in use. In Numba, the APIs for the legacy + default stream are always the ones in use, but an option to use APIs for + the per-thread default stream may be provided in future. + """ + return current_context().get_default_stream() + + +@require_context +def legacy_default_stream(): + """ + Get the legacy default CUDA stream. + """ + return current_context().get_legacy_default_stream() + + +@require_context +def per_thread_default_stream(): + """ + Get the per-thread default CUDA stream. + """ + return current_context().get_per_thread_default_stream() + + +@require_context +def external_stream(ptr): + """Create a Numba stream object for a stream allocated outside Numba. + + :param ptr: Pointer to the external stream to wrap in a Numba Stream + :type ptr: int + """ + return current_context().create_external_stream(ptr) + + +# Page lock +@require_context +@contextlib.contextmanager +def pinned(*arylist): + """A context manager for temporary pinning a sequence of host ndarrays. + """ + pmlist = [] + for ary in arylist: + pm = current_context().mempin(ary, driver.host_pointer(ary), + driver.host_memory_size(ary), + mapped=False) + pmlist.append(pm) + yield + + +@require_context +@contextlib.contextmanager +def mapped(*arylist, **kws): + """A context manager for temporarily mapping a sequence of host ndarrays. + """ + assert not kws or 'stream' in kws, "Only accept 'stream' as keyword." + stream = kws.get('stream', 0) + pmlist = [] + devarylist = [] + for ary in arylist: + pm = current_context().mempin(ary, driver.host_pointer(ary), + driver.host_memory_size(ary), + mapped=True) + pmlist.append(pm) + devary = devicearray.from_array_like(ary, gpu_data=pm, stream=stream) + devarylist.append(devary) + try: + if len(devarylist) == 1: + yield devarylist[0] + else: + yield devarylist + finally: + # When exiting from `with cuda.mapped(*arrs) as mapped_arrs:`, the name + # `mapped_arrs` stays in scope, blocking automatic unmapping based on + # reference count. We therefore invoke the finalizer manually. + for pm in pmlist: + pm.free() + + +def event(timing=True): + """ + Create a CUDA event. Timing data is only recorded by the event if it is + created with ``timing=True``. + """ + evt = current_context().create_event(timing=timing) + return evt + + +event_elapsed_time = driver.event_elapsed_time + + +# Device selection + +def select_device(device_id): + """ + Make the context associated with device *device_id* the current context. + + Returns a Device instance. + + Raises exception on error. + """ + context = devices.get_context(device_id) + return context.device + + +def get_current_device(): + "Get current device associated with the current thread" + return current_context().device + + +def list_devices(): + "Return a list of all detected devices" + return devices.gpus + + +def close(): + """ + Explicitly clears all contexts in the current thread, and destroys all + contexts if the current thread is the main thread. + """ + devices.reset() + + +def _auto_device(ary, stream=0, copy=True): + return devicearray.auto_device(ary, stream=stream, copy=copy) + + +def detect(): + """ + Detect supported CUDA hardware and print a summary of the detected hardware. + + Returns a boolean indicating whether any supported devices were detected. + """ + devlist = list_devices() + print('Found %d CUDA devices' % len(devlist)) + supported_count = 0 + for dev in devlist: + attrs = [] + cc = dev.compute_capability + kernel_timeout = dev.KERNEL_EXEC_TIMEOUT + tcc = dev.TCC_DRIVER + fp32_to_fp64_ratio = dev.SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO + attrs += [('Compute Capability', '%d.%d' % cc)] + attrs += [('PCI Device ID', dev.PCI_DEVICE_ID)] + attrs += [('PCI Bus ID', dev.PCI_BUS_ID)] + attrs += [('UUID', dev.uuid)] + attrs += [('Watchdog', 'Enabled' if kernel_timeout else 'Disabled')] + if os.name == "nt": + attrs += [('Compute Mode', 'TCC' if tcc else 'WDDM')] + attrs += [('FP32/FP64 Performance Ratio', fp32_to_fp64_ratio)] + if cc < (3, 5): + support = '[NOT SUPPORTED: CC < 3.5]' + elif cc < (5, 0): + support = '[SUPPORTED (DEPRECATED)]' + supported_count += 1 + else: + support = '[SUPPORTED]' + supported_count += 1 + + print('id %d %20s %40s' % (dev.id, dev.name, support)) + for key, val in attrs: + print('%40s: %s' % (key, val)) + + print('Summary:') + print('\t%d/%d devices are supported' % (supported_count, len(devlist))) + return supported_count > 0 + + +@contextlib.contextmanager +def defer_cleanup(): + """ + Temporarily disable memory deallocation. + Use this to prevent resource deallocation breaking asynchronous execution. + + For example:: + + with defer_cleanup(): + # all cleanup is deferred in here + do_speed_critical_code() + # cleanup can occur here + + Note: this context manager can be nested. + """ + with current_context().defer_cleanup(): + yield + + +profiling = require_context(driver.profiling) +profile_start = require_context(driver.profile_start) +profile_stop = require_context(driver.profile_stop) diff --git a/shared/package-files/7b/7bdbe958bf7c390f489357fb8302e5e1de5f793022c8bc0f9bfc9aac9ab74fff/blob b/shared/package-files/7b/7bdbe958bf7c390f489357fb8302e5e1de5f793022c8bc0f9bfc9aac9ab74fff/blob new file mode 100644 index 0000000000000000000000000000000000000000..ccbeca5b7a4839bbc28e9c1cfd1ebd1d028a82cf --- /dev/null +++ b/shared/package-files/7b/7bdbe958bf7c390f489357fb8302e5e1de5f793022c8bc0f9bfc9aac9ab74fff/blob @@ -0,0 +1,1310 @@ +""" +Functions for identifying peaks in signals. +""" +import math +import numpy as np + +from scipy.signal._wavelets import _cwt, _ricker +from scipy.stats import scoreatpercentile + +from ._peak_finding_utils import ( + _local_maxima_1d, + _select_by_peak_distance, + _peak_prominences, + _peak_widths +) + + +__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences', + 'peak_widths', 'find_peaks', 'find_peaks_cwt'] + + +def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Relative extrema are calculated by finding locations where + ``comparator(data[n], data[n+1:n+order+1])`` is True. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n,n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : ndarray + Boolean array of the same shape as `data` that is True at an extrema, + False otherwise. + + See also + -------- + argrelmax, argrelmin + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _boolrelextrema + >>> testdata = np.array([1,2,3,2,1]) + >>> _boolrelextrema(testdata, np.greater, axis=0) + array([False, False, True, False, False], dtype=bool) + + """ + if (int(order) != order) or (order < 1): + raise ValueError('Order must be an int >= 1') + + datalen = data.shape[axis] + locs = np.arange(0, datalen) + + results = np.ones(data.shape, dtype=bool) + main = data.take(locs, axis=axis, mode=mode) + for shift in range(1, order + 1): + plus = data.take(locs + shift, axis=axis, mode=mode) + minus = data.take(locs - shift, axis=axis, mode=mode) + results &= comparator(main, plus) + results &= comparator(main, minus) + if ~results.any(): + return results + return results + + +def argrelmin(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative minima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative minima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the minima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmax, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.less as comparator. Therefore, it + requires a strict inequality on both sides of a value to consider it a + minimum. This means flat minima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local minima, including flat ones, by calling it with negated `data`. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmin + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmin(x) + (array([1, 5]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmin(y, axis=1) + (array([0, 2]), array([2, 1])) + + """ + return argrelextrema(data, np.less, axis, order, mode) + + +def argrelmax(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative maxima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative maxima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmin, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.greater as comparator. Therefore, + it requires a strict inequality on both sides of a value to consider it a + maximum. This means flat maxima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local maxima, including flat ones. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmax + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmax(x) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmax(y, axis=1) + (array([0]), array([1])) + """ + return argrelextrema(data, np.greater, axis, order, mode) + + +def argrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default is 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelmin, argrelmax + + Notes + ----- + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelextrema + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelextrema(x, np.greater) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelextrema(y, np.less, axis=1) + (array([0, 2]), array([2, 1])) + + """ + results = _boolrelextrema(data, comparator, + axis, order, mode) + return np.nonzero(results) + + +def _arg_x_as_expected(value): + """Ensure argument `x` is a 1-D C-contiguous array of dtype('float64'). + + Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x` + compatible with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('float64'). + """ + value = np.asarray(value, order='C', dtype=np.float64) + if value.ndim != 1: + raise ValueError('`x` must be a 1-D array') + return value + + +def _arg_peaks_as_expected(value): + """Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp'). + + Used in `peak_prominences` and `peak_widths` to make `peaks` compatible + with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('intp'). + """ + value = np.asarray(value) + if value.size == 0: + # Empty arrays default to np.float64 but are valid input + value = np.array([], dtype=np.intp) + try: + # Safely convert to C-contiguous array of type np.intp + value = value.astype(np.intp, order='C', casting='safe', + subok=False, copy=False) + except TypeError as e: + raise TypeError("cannot safely cast `peaks` to dtype('intp')") from e + if value.ndim != 1: + raise ValueError('`peaks` must be a 1-D array') + return value + + +def _arg_wlen_as_expected(value): + """Ensure argument `wlen` is of type `np.intp` and larger than 1. + + Used in `peak_prominences` and `peak_widths`. + + Returns + ------- + value : np.intp + The original `value` rounded up to an integer or -1 if `value` was + None. + """ + if value is None: + # _peak_prominences expects an intp; -1 signals that no value was + # supplied by the user + value = -1 + elif 1 < value: + # Round up to a positive integer + if isinstance(value, float): + value = math.ceil(value) + value = np.intp(value) + else: + raise ValueError(f'`wlen` must be larger than 1, was {value}') + return value + + +def peak_prominences(x, peaks, wlen=None): + """ + Calculate the prominence of each peak in a signal. + + The prominence of a peak measures how much a peak stands out from the + surrounding baseline of the signal and is defined as the vertical distance + between the peak and its lowest contour line. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + wlen : int, optional + A window length in samples that optionally limits the evaluated area for + each peak to a subset of `x`. The peak is always placed in the middle of + the window therefore the given length is rounded up to the next odd + integer. This parameter can speed up the calculation (see Notes). + + Returns + ------- + prominences : ndarray + The calculated prominences for each peak in `peaks`. + left_bases, right_bases : ndarray + The peaks' bases as indices in `x` to the left and right of each peak. + The higher base of each pair is a peak's lowest contour line. + + Raises + ------ + ValueError + If a value in `peaks` is an invalid index for `x`. + + Warns + ----- + PeakPropertyWarning + For indices in `peaks` that don't point to valid local maxima in `x`, + the returned prominence will be 0 and this warning is raised. This + also happens if `wlen` is smaller than the plateau size of a peak. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_widths + Calculate the width of peaks. + + Notes + ----- + Strategy to compute a peak's prominence: + + 1. Extend a horizontal line from the current peak to the left and right + until the line either reaches the window border (see `wlen`) or + intersects the signal again at the slope of a higher peak. An + intersection with a peak of the same height is ignored. + 2. On each side find the minimal signal value within the interval defined + above. These points are the peak's bases. + 3. The higher one of the two bases marks the peak's lowest contour line. The + prominence can then be calculated as the vertical difference between the + peaks height itself and its lowest contour line. + + Searching for the peak's bases can be slow for large `x` with periodic + behavior because large chunks or even the full signal need to be evaluated + for the first algorithmic step. This evaluation area can be limited with the + parameter `wlen` which restricts the algorithm to a window around the + current peak and can shorten the calculation time if the window length is + short in relation to `x`. + However, this may stop the algorithm from finding the true global contour + line if the peak's true bases are outside this window. Instead, a higher + contour line is found within the restricted window leading to a smaller + calculated prominence. In practice, this is only relevant for the highest set + of peaks in `x`. This behavior may even be used intentionally to calculate + "local" prominences. + + .. versionadded:: 1.1.0 + + References + ---------- + .. [1] Wikipedia Article for Topographic Prominence: + https://en.wikipedia.org/wiki/Topographic_prominence + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import find_peaks, peak_prominences + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate prominences + + >>> peaks, _ = find_peaks(x) + >>> prominences = peak_prominences(x, peaks)[0] + >>> prominences + array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 , + 0.47822491, 2.48340261, 0.47822491]) + + Calculate the height of each peak's contour line and plot the results + + >>> contour_heights = x[peaks] - prominences + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) + >>> plt.show() + + Let's evaluate a second example that demonstrates several edge cases for + one peak at index 5. + + >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) + >>> peaks = np.array([5]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases) + (array([3.]), array([2]), array([6])) + + Note how the peak at index 3 of the same height is not considered as a + border while searching for the left base. Instead, two minima at 0 and 2 + are found in which case the one closer to the evaluated peak is always + chosen. On the right side, however, the base must be placed at 6 because the + higher peak represents the right border to the evaluated area. + + >>> peak_prominences(x, peaks, wlen=3.1) + (array([2.]), array([4]), array([6])) + + Here, we restricted the algorithm to a window from 3 to 7 (the length is 5 + samples because `wlen` was rounded up to the next odd integer). Thus, the + only two candidates in the evaluated area are the two neighboring samples + and a smaller prominence is calculated. + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + wlen = _arg_wlen_as_expected(wlen) + return _peak_prominences(x, peaks, wlen) + + +def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None): + """ + Calculate the width of each peak in a signal. + + This function calculates the width of a peak in samples at a relative + distance to the peak's height and prominence. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + rel_height : float, optional + Chooses the relative height at which the peak width is measured as a + percentage of its prominence. 1.0 calculates the width of the peak at + its lowest contour line while 0.5 evaluates at half the prominence + height. Must be at least 0. See notes for further explanation. + prominence_data : tuple, optional + A tuple of three arrays matching the output of `peak_prominences` when + called with the same arguments `x` and `peaks`. This data are calculated + internally if not provided. + wlen : int, optional + A window length in samples passed to `peak_prominences` as an optional + argument for internal calculation of `prominence_data`. This argument + is ignored if `prominence_data` is given. + + Returns + ------- + widths : ndarray + The widths for each peak in samples. + width_heights : ndarray + The height of the contour lines at which the `widths` where evaluated. + left_ips, right_ips : ndarray + Interpolated positions of left and right intersection points of a + horizontal line at the respective evaluation height. + + Raises + ------ + ValueError + If `prominence_data` is supplied but doesn't satisfy the condition + ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak, + has the wrong dtype, is not C-contiguous or does not have the same + shape. + + Warns + ----- + PeakPropertyWarning + Raised if any calculated width is 0. This may stem from the supplied + `prominence_data` or if `rel_height` is set to 0. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_prominences + Calculate the prominence of peaks. + + Notes + ----- + The basic algorithm to calculate a peak's width is as follows: + + * Calculate the evaluation height :math:`h_{eval}` with the formula + :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the + height of the peak itself, :math:`P` is the peak's prominence and + :math:`R` a positive ratio specified with the argument `rel_height`. + * Draw a horizontal line at the evaluation height to both sides, starting at + the peak's current vertical position until the lines either intersect a + slope, the signal border or cross the vertical position of the peak's + base (see `peak_prominences` for an definition). For the first case, + intersection with the signal, the true intersection point is estimated + with linear interpolation. + * Calculate the width as the horizontal distance between the chosen + endpoints on both sides. As a consequence of this the maximal possible + width for each peak is the horizontal distance between its bases. + + As shown above to calculate a peak's width its prominence and bases must be + known. You can supply these yourself with the argument `prominence_data`. + Otherwise, they are internally calculated (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import chirp, find_peaks, peak_widths + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate their widths at the relative height of 0.5 + (contour line at half the prominence height) and 1 (at the lowest contour + line at full prominence height). + + >>> peaks, _ = find_peaks(x) + >>> results_half = peak_widths(x, peaks, rel_height=0.5) + >>> results_half[0] # widths + array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081, + 35.46729324, 41.30429622, 181.93835853, 45.37078546]) + >>> results_full = peak_widths(x, peaks, rel_height=1) + >>> results_full[0] # widths + array([181.9396084 , 72.99284945, 61.28657872, 373.84622694, + 61.78404617, 72.48822812, 253.09161876, 79.36860878]) + + Plot signal, peaks and contour lines at which the widths where calculated + + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.hlines(*results_half[1:], color="C2") + >>> plt.hlines(*results_full[1:], color="C3") + >>> plt.show() + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + if prominence_data is None: + # Calculate prominence if not supplied and use wlen if supplied. + wlen = _arg_wlen_as_expected(wlen) + prominence_data = _peak_prominences(x, peaks, wlen) + return _peak_widths(x, peaks, rel_height, *prominence_data) + + +def _unpack_condition_args(interval, x, peaks): + """ + Parse condition arguments for `find_peaks`. + + Parameters + ---------- + interval : number or ndarray or sequence + Either a number or ndarray or a 2-element sequence of the former. The + first value is always interpreted as `imin` and the second, if supplied, + as `imax`. + x : ndarray + The signal with `peaks`. + peaks : ndarray + An array with indices used to reduce `imin` and / or `imax` if those are + arrays. + + Returns + ------- + imin, imax : number or ndarray or None + Minimal and maximal value in `argument`. + + Raises + ------ + ValueError : + If interval border is given as array and its size does not match the size + of `x`. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + try: + imin, imax = interval + except (TypeError, ValueError): + imin, imax = (interval, None) + + # Reduce arrays if arrays + if isinstance(imin, np.ndarray): + if imin.size != x.size: + raise ValueError('array size of lower interval border must match x') + imin = imin[peaks] + if isinstance(imax, np.ndarray): + if imax.size != x.size: + raise ValueError('array size of upper interval border must match x') + imax = imax[peaks] + + return imin, imax + + +def _select_by_property(peak_properties, pmin, pmax): + """ + Evaluate where the generic property of peaks confirms to an interval. + + Parameters + ---------- + peak_properties : ndarray + An array with properties for each peak. + pmin : None or number or ndarray + Lower interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + pmax : None or number or ndarray + Upper interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peak_properties` confirms to the + interval. + + See Also + -------- + find_peaks + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + keep = np.ones(peak_properties.size, dtype=bool) + if pmin is not None: + keep &= (pmin <= peak_properties) + if pmax is not None: + keep &= (peak_properties <= pmax) + return keep + + +def _select_by_peak_threshold(x, peaks, tmin, tmax): + """ + Evaluate which peaks fulfill the threshold condition. + + Parameters + ---------- + x : ndarray + A 1-D array which is indexable by `peaks`. + peaks : ndarray + Indices of peaks in `x`. + tmin, tmax : scalar or ndarray or None + Minimal and / or maximal required thresholds. If supplied as ndarrays + their size must match `peaks`. ``None`` is interpreted as an open + border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peaks` fulfill the threshold + condition. + left_thresholds, right_thresholds : ndarray + Array matching `peak` containing the thresholds of each peak on + both sides. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + # Stack thresholds on both sides to make min / max operations easier: + # tmin is compared with the smaller, and tmax with the greater threshold to + # each peak's side + stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1], + x[peaks] - x[peaks + 1]]) + keep = np.ones(peaks.size, dtype=bool) + if tmin is not None: + min_thresholds = np.min(stacked_thresholds, axis=0) + keep &= (tmin <= min_thresholds) + if tmax is not None: + max_thresholds = np.max(stacked_thresholds, axis=0) + keep &= (max_thresholds <= tmax) + + return keep, stacked_thresholds[0], stacked_thresholds[1] + + +def find_peaks(x, height=None, threshold=None, distance=None, + prominence=None, width=None, wlen=None, rel_height=0.5, + plateau_size=None): + """ + Find peaks inside a signal based on peak properties. + + This function takes a 1-D array and finds all local maxima by + simple comparison of neighboring values. Optionally, a subset of these + peaks can be selected by specifying conditions for a peak's properties. + + Parameters + ---------- + x : sequence + A signal with peaks. + height : number or ndarray or sequence, optional + Required height of peaks. Either a number, ``None``, an array matching + `x` or a 2-element sequence of the former. The first element is + always interpreted as the minimal and the second, if supplied, as the + maximal required height. + threshold : number or ndarray or sequence, optional + Required threshold of peaks, the vertical distance to its neighboring + samples. Either a number, ``None``, an array matching `x` or a + 2-element sequence of the former. The first element is always + interpreted as the minimal and the second, if supplied, as the maximal + required threshold. + distance : number, optional + Required minimal horizontal distance (>= 1) in samples between + neighbouring peaks. Smaller peaks are removed first until the condition + is fulfilled for all remaining peaks. + prominence : number or ndarray or sequence, optional + Required prominence of peaks. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required prominence. + width : number or ndarray or sequence, optional + Required width of peaks in samples. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required width. + wlen : int, optional + Used for calculation of the peaks prominences, thus it is only used if + one of the arguments `prominence` or `width` is given. See argument + `wlen` in `peak_prominences` for a full description of its effects. + rel_height : float, optional + Used for calculation of the peaks width, thus it is only used if `width` + is given. See argument `rel_height` in `peak_widths` for a full + description of its effects. + plateau_size : number or ndarray or sequence, optional + Required size of the flat top of peaks in samples. Either a number, + ``None``, an array matching `x` or a 2-element sequence of the former. + The first element is always interpreted as the minimal and the second, + if supplied as the maximal required plateau size. + + .. versionadded:: 1.2.0 + + Returns + ------- + peaks : ndarray + Indices of peaks in `x` that satisfy all given conditions. + properties : dict + A dictionary containing properties of the returned peaks which were + calculated as intermediate results during evaluation of the specified + conditions: + + * 'peak_heights' + If `height` is given, the height of each peak in `x`. + * 'left_thresholds', 'right_thresholds' + If `threshold` is given, these keys contain a peaks vertical + distance to its neighbouring samples. + * 'prominences', 'right_bases', 'left_bases' + If `prominence` is given, these keys are accessible. See + `peak_prominences` for a description of their content. + * 'widths', 'width_heights', 'left_ips', 'right_ips' + If `width` is given, these keys are accessible. See `peak_widths` + for a description of their content. + * 'plateau_sizes', left_edges', 'right_edges' + If `plateau_size` is given, these keys are accessible and contain + the indices of a peak's edges (edges are still part of the + plateau) and the calculated plateau sizes. + + .. versionadded:: 1.2.0 + + To calculate and return properties without excluding peaks, provide the + open interval ``(None, None)`` as a value to the appropriate argument + (excluding `distance`). + + Warns + ----- + PeakPropertyWarning + Raised if a peak's properties have unexpected values (see + `peak_prominences` and `peak_widths`). + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks_cwt + Find peaks using the wavelet transformation. + peak_prominences + Directly calculate the prominence of peaks. + peak_widths + Directly calculate the width of peaks. + + Notes + ----- + In the context of this function, a peak or local maximum is defined as any + sample whose two direct neighbours have a smaller amplitude. For flat peaks + (more than one sample of equal amplitude wide) the index of the middle + sample is returned (rounded down in case the number of samples is even). + For noisy signals the peak locations can be off because the noise might + change the position of local maxima. In those cases consider smoothing the + signal before searching for peaks or use other peak finding and fitting + methods (like `find_peaks_cwt`). + + Some additional comments on specifying conditions: + + * Almost all conditions (excluding `distance`) can be given as half-open or + closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open + interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval + :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified + as well, which returns the matching properties without exclusion of peaks. + * The border is always included in the interval used to select valid peaks. + * For several conditions the interval borders can be specified with + arrays matching `x` in shape which enables dynamic constrains based on + the sample position. + * The conditions are evaluated in the following order: `plateau_size`, + `height`, `threshold`, `distance`, `prominence`, `width`. In most cases + this order is the fastest one because faster operations are applied first + to reduce the number of peaks that need to be evaluated later. + * While indices in `peaks` are guaranteed to be at least `distance` samples + apart, edges of flat peaks may be closer than the allowed `distance`. + * Use `wlen` to reduce the time it takes to evaluate the conditions for + `prominence` or `width` if `x` is large or has many local maxima + (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + To demonstrate this function's usage we use a signal `x` supplied with + SciPy (see `scipy.datasets.electrocardiogram`). Let's find all peaks (local + maxima) in `x` whose amplitude lies above 0. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.datasets import electrocardiogram + >>> from scipy.signal import find_peaks + >>> x = electrocardiogram()[2000:4000] + >>> peaks, _ = find_peaks(x, height=0) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.plot(np.zeros_like(x), "--", color="gray") + >>> plt.show() + + We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching + `x` in size to reflect a changing condition for different parts of the + signal. + + >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size)) + >>> peaks, _ = find_peaks(x, height=(-border, border)) + >>> plt.plot(x) + >>> plt.plot(-border, "--", color="gray") + >>> plt.plot(border, ":", color="gray") + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Another useful condition for periodic signals can be given with the + `distance` argument. In this case, we can easily select the positions of + QRS complexes within the electrocardiogram (ECG) by demanding a distance of + at least 150 samples. + + >>> peaks, _ = find_peaks(x, distance=150) + >>> np.diff(peaks) + array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Especially for noisy signals peaks can be easily grouped by their + prominence (see `peak_prominences`). E.g., we can select all peaks except + for the mentioned QRS complexes by limiting the allowed prominence to 0.6. + + >>> peaks, properties = find_peaks(x, prominence=(None, 0.6)) + >>> properties["prominences"].max() + 0.5049999999999999 + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + And, finally, let's examine a different section of the ECG which contains + beat forms of different shape. To select only the atypical heart beats, we + combine two conditions: a minimal prominence of 1 and width of at least 20 + samples. + + >>> x = electrocardiogram()[17000:18000] + >>> peaks, properties = find_peaks(x, prominence=1, width=20) + >>> properties["prominences"], properties["widths"] + (array([1.495, 2.3 ]), array([36.93773946, 39.32723577])) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"], + ... ymax = x[peaks], color = "C1") + >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"], + ... xmax=properties["right_ips"], color = "C1") + >>> plt.show() + """ + # _argmaxima1d expects array of dtype 'float64' + x = _arg_x_as_expected(x) + if distance is not None and distance < 1: + raise ValueError('`distance` must be greater or equal to 1') + + peaks, left_edges, right_edges = _local_maxima_1d(x) + properties = {} + + if plateau_size is not None: + # Evaluate plateau size + plateau_sizes = right_edges - left_edges + 1 + pmin, pmax = _unpack_condition_args(plateau_size, x, peaks) + keep = _select_by_property(plateau_sizes, pmin, pmax) + peaks = peaks[keep] + properties["plateau_sizes"] = plateau_sizes + properties["left_edges"] = left_edges + properties["right_edges"] = right_edges + properties = {key: array[keep] for key, array in properties.items()} + + if height is not None: + # Evaluate height condition + peak_heights = x[peaks] + hmin, hmax = _unpack_condition_args(height, x, peaks) + keep = _select_by_property(peak_heights, hmin, hmax) + peaks = peaks[keep] + properties["peak_heights"] = peak_heights + properties = {key: array[keep] for key, array in properties.items()} + + if threshold is not None: + # Evaluate threshold condition + tmin, tmax = _unpack_condition_args(threshold, x, peaks) + keep, left_thresholds, right_thresholds = _select_by_peak_threshold( + x, peaks, tmin, tmax) + peaks = peaks[keep] + properties["left_thresholds"] = left_thresholds + properties["right_thresholds"] = right_thresholds + properties = {key: array[keep] for key, array in properties.items()} + + if distance is not None: + # Evaluate distance condition + keep = _select_by_peak_distance(peaks, x[peaks], distance) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if prominence is not None or width is not None: + # Calculate prominence (required for both conditions) + wlen = _arg_wlen_as_expected(wlen) + properties.update(zip( + ['prominences', 'left_bases', 'right_bases'], + _peak_prominences(x, peaks, wlen=wlen) + )) + + if prominence is not None: + # Evaluate prominence condition + pmin, pmax = _unpack_condition_args(prominence, x, peaks) + keep = _select_by_property(properties['prominences'], pmin, pmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if width is not None: + # Calculate widths + properties.update(zip( + ['widths', 'width_heights', 'left_ips', 'right_ips'], + _peak_widths(x, peaks, rel_height, properties['prominences'], + properties['left_bases'], properties['right_bases']) + )) + # Evaluate width condition + wmin, wmax = _unpack_condition_args(width, x, peaks) + keep = _select_by_property(properties['widths'], wmin, wmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + return peaks, properties + + +def _identify_ridge_lines(matr, max_distances, gap_thresh): + """ + Identify ridges in the 2-D matrix. + + Expect that the width of the wavelet feature increases with increasing row + number. + + Parameters + ---------- + matr : 2-D ndarray + Matrix in which to identify ridge lines. + max_distances : 1-D sequence + At each row, a ridge line is only connected + if the relative max at row[n] is within + `max_distances`[n] from the relative max at row[n+1]. + gap_thresh : int + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if + there are more than `gap_thresh` points without connecting + a new relative maximum. + + Returns + ------- + ridge_lines : tuple + Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the + ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none + found. Each ridge-line will be sorted by row (increasing), but the + order of the ridge lines is not specified. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _identify_ridge_lines + >>> rng = np.random.default_rng() + >>> data = rng.random((5,5)) + >>> max_dist = 3 + >>> max_distances = np.full(20, max_dist) + >>> ridge_lines = _identify_ridge_lines(data, max_distances, 1) + + Notes + ----- + This function is intended to be used in conjunction with `cwt` + as part of `find_peaks_cwt`. + + """ + if len(max_distances) < matr.shape[0]: + raise ValueError('Max_distances must have at least as many rows ' + 'as matr') + + all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1) + # Highest row for which there are any relative maxima + has_relmax = np.nonzero(all_max_cols.any(axis=1))[0] + if len(has_relmax) == 0: + return [] + start_row = has_relmax[-1] + # Each ridge line is a 3-tuple: + # rows, cols,Gap number + ridge_lines = [[[start_row], + [col], + 0] for col in np.nonzero(all_max_cols[start_row])[0]] + final_lines = [] + rows = np.arange(start_row - 1, -1, -1) + cols = np.arange(0, matr.shape[1]) + for row in rows: + this_max_cols = cols[all_max_cols[row]] + + # Increment gap number of each line, + # set it to zero later if appropriate + for line in ridge_lines: + line[2] += 1 + + # XXX These should always be all_max_cols[row] + # But the order might be different. Might be an efficiency gain + # to make sure the order is the same and avoid this iteration + prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines]) + # Look through every relative maximum found at current row + # Attempt to connect them with existing ridge lines. + for ind, col in enumerate(this_max_cols): + # If there is a previous ridge line within + # the max_distance to connect to, do so. + # Otherwise start a new one. + line = None + if len(prev_ridge_cols) > 0: + diffs = np.abs(col - prev_ridge_cols) + closest = np.argmin(diffs) + if diffs[closest] <= max_distances[row]: + line = ridge_lines[closest] + if line is not None: + # Found a point close enough, extend current ridge line + line[1].append(col) + line[0].append(row) + line[2] = 0 + else: + new_line = [[row], + [col], + 0] + ridge_lines.append(new_line) + + # Remove the ridge lines with gap_number too high + # XXX Modifying a list while iterating over it. + # Should be safe, since we iterate backwards, but + # still tacky. + for ind in range(len(ridge_lines) - 1, -1, -1): + line = ridge_lines[ind] + if line[2] > gap_thresh: + final_lines.append(line) + del ridge_lines[ind] + + out_lines = [] + for line in (final_lines + ridge_lines): + sortargs = np.array(np.argsort(line[0])) + rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs) + rows[sortargs] = line[0] + cols[sortargs] = line[1] + out_lines.append([rows, cols]) + + return out_lines + + +def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None, + min_snr=1, noise_perc=10): + """ + Filter ridge lines according to prescribed criteria. Intended + to be used for finding relative maxima. + + Parameters + ---------- + cwt : 2-D ndarray + Continuous wavelet transform from which the `ridge_lines` were defined. + ridge_lines : 1-D sequence + Each element should contain 2 sequences, the rows and columns + of the ridge line (respectively). + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the value of + the cwt matrix at the shortest length scale (``cwt[0, loc]``), the + noise is the `noise_perc`\\ th percentile of datapoints contained within a + window of `window_size` around ``cwt[0, loc]``. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + scipy.stats.scoreatpercentile. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + """ + num_points = cwt.shape[1] + if min_length is None: + min_length = np.ceil(cwt.shape[0] / 4) + if window_size is None: + window_size = np.ceil(num_points / 20) + + window_size = int(window_size) + hf_window, odd = divmod(window_size, 2) + + # Filter based on SNR + row_one = cwt[0, :] + noises = np.empty_like(row_one) + for ind, val in enumerate(row_one): + window_start = max(ind - hf_window, 0) + window_end = min(ind + hf_window + odd, num_points) + noises[ind] = scoreatpercentile(row_one[window_start:window_end], + per=noise_perc) + + def filt_func(line): + if len(line[0]) < min_length: + return False + snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]]) + if snr < min_snr: + return False + return True + + return list(filter(filt_func, ridge_lines)) + + +def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None, + gap_thresh=None, min_length=None, + min_snr=1, noise_perc=10, window_size=None): + """ + Find peaks in a 1-D array with wavelet transformation. + + The general approach is to smooth `vector` by convolving it with + `wavelet(width)` for each width in `widths`. Relative maxima which + appear at enough length scales, and with sufficiently high SNR, are + accepted. + + Parameters + ---------- + vector : ndarray + 1-D array in which to find the peaks. + widths : float or sequence + Single width or 1-D array-like of widths to use for calculating + the CWT matrix. In general, + this range should cover the expected width of peaks of interest. + wavelet : callable, optional + Should take two parameters and return a 1-D array to convolve + with `vector`. The first parameter determines the number of points + of the returned wavelet array, the second parameter is the scale + (`width`) of the wavelet. Should be normalized and symmetric. + Default is the ricker wavelet. + max_distances : ndarray, optional + At each row, a ridge line is only connected if the relative max at + row[n] is within ``max_distances[n]`` from the relative max at + ``row[n+1]``. Default value is ``widths/4``. + gap_thresh : float, optional + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if there are more + than `gap_thresh` points without connecting a new relative maximum. + Default is the first value of the widths array i.e. widths[0]. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient + on the largest ridge line. The noise is `noise_perc` th percentile of + datapoints contained within the same ridge line. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + `stats.scoreatpercentile`. Default is 10. + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + + Returns + ------- + peaks_indices : ndarray + Indices of the locations in the `vector` where peaks were found. + The list is sorted. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + + Notes + ----- + This approach was designed for finding sharp peaks among noisy data, + however with proper parameter selection it should function well for + different peak shapes. + + The algorithm is as follows: + 1. Perform a continuous wavelet transform on `vector`, for the supplied + `widths`. This is a convolution of `vector` with `wavelet(width)` for + each width in `widths`. See `cwt`. + 2. Identify "ridge lines" in the cwt matrix. These are relative maxima + at each row, connected across adjacent rows. See identify_ridge_lines + 3. Filter the ridge_lines using filter_ridge_lines. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> xs = np.arange(0, np.pi, 0.05) + >>> data = np.sin(xs) + >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10)) + >>> peakind, xs[peakind], data[peakind] + ([32], array([ 1.6]), array([ 0.9995736])) + + """ + widths = np.atleast_1d(np.asarray(widths)) + + if gap_thresh is None: + gap_thresh = np.ceil(widths[0]) + if max_distances is None: + max_distances = widths / 4.0 + if wavelet is None: + wavelet = _ricker + + cwt_dat = _cwt(vector, wavelet, widths) + ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh) + filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length, + window_size=window_size, min_snr=min_snr, + noise_perc=noise_perc) + max_locs = np.asarray([x[1][0] for x in filtered]) + max_locs.sort() + + return max_locs diff --git a/shared/package-files/7b/7bded7a0facf1890c887c9ceea68a2fff562639c95966b783a73d0a03375763b/blob b/shared/package-files/7b/7bded7a0facf1890c887c9ceea68a2fff562639c95966b783a73d0a03375763b/blob new file mode 100644 index 0000000000000000000000000000000000000000..2d4eea22db22512462368a32047b1bba5f081d94 Binary files /dev/null and b/shared/package-files/7b/7bded7a0facf1890c887c9ceea68a2fff562639c95966b783a73d0a03375763b/blob differ diff --git a/shared/package-files/7b/7be323d43dae73170e166fd5bd85ac36e4716ac8a6ed6cab7e45ef95f4932216/blob b/shared/package-files/7b/7be323d43dae73170e166fd5bd85ac36e4716ac8a6ed6cab7e45ef95f4932216/blob new file mode 100644 index 0000000000000000000000000000000000000000..e6ef2128fd495f873465c98b10ebfad6f1e323df --- /dev/null +++ b/shared/package-files/7b/7be323d43dae73170e166fd5bd85ac36e4716ac8a6ed6cab7e45ef95f4932216/blob @@ -0,0 +1,36 @@ +#pragma once + +#include + +namespace c10 { + +class RegistrationHandleRAII final { +public: + explicit RegistrationHandleRAII(std::function onDestruction) + : onDestruction_(std::move(onDestruction)) {} + + ~RegistrationHandleRAII() { + if (onDestruction_) { + onDestruction_(); + } + } + + RegistrationHandleRAII(const RegistrationHandleRAII&) = delete; + RegistrationHandleRAII& operator=(const RegistrationHandleRAII&) = delete; + + RegistrationHandleRAII(RegistrationHandleRAII&& rhs) noexcept + : onDestruction_(std::move(rhs.onDestruction_)) { + rhs.onDestruction_ = nullptr; + } + + RegistrationHandleRAII& operator=(RegistrationHandleRAII&& rhs) noexcept { + onDestruction_ = std::move(rhs.onDestruction_); + rhs.onDestruction_ = nullptr; + return *this; + } + +private: + std::function onDestruction_; +}; + +} diff --git a/shared/package-files/7b/7be395619fd4d8c9a7ec47eacfb0e4d1f11a19d3bde9ccc5daa3ce0fea840734/blob b/shared/package-files/7b/7be395619fd4d8c9a7ec47eacfb0e4d1f11a19d3bde9ccc5daa3ce0fea840734/blob new file mode 100644 index 0000000000000000000000000000000000000000..0b3d4f186d7a44ff83efab733cef1ac8827194d2 Binary files /dev/null and b/shared/package-files/7b/7be395619fd4d8c9a7ec47eacfb0e4d1f11a19d3bde9ccc5daa3ce0fea840734/blob differ diff --git a/shared/package-files/7b/7be4261aee6701ef5c953f27f5b75ae5a1301c11f865a5ea073b39fa62963184/blob b/shared/package-files/7b/7be4261aee6701ef5c953f27f5b75ae5a1301c11f865a5ea073b39fa62963184/blob new file mode 100644 index 0000000000000000000000000000000000000000..b673bd9c2ec7168971ae0ed802336e4f03ff63a7 --- /dev/null +++ b/shared/package-files/7b/7be4261aee6701ef5c953f27f5b75ae5a1301c11f865a5ea073b39fa62963184/blob @@ -0,0 +1,72 @@ +from datetime import time +import locale + +import numpy as np +import pytest + +from pandas.compat import PY311 + +from pandas import Series +import pandas._testing as tm +from pandas.core.tools.times import to_time + +# The tests marked with this are locale-dependent. +# They pass, except when the machine locale is zh_CN or it_IT. +fails_on_non_english = pytest.mark.xfail( + locale.getlocale()[0] in ("zh_CN", "it_IT"), + reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", + strict=False, +) + + +class TestToTime: + @pytest.mark.parametrize( + "time_string", + [ + "14:15", + "1415", + pytest.param("2:15pm", marks=fails_on_non_english), + pytest.param("0215pm", marks=fails_on_non_english), + "14:15:00", + "141500", + pytest.param("2:15:00pm", marks=fails_on_non_english), + pytest.param("021500pm", marks=fails_on_non_english), + time(14, 15), + ], + ) + def test_parsers_time(self, time_string): + # GH#11818 + assert to_time(time_string) == time(14, 15) + + def test_odd_format(self): + new_string = "14.15" + msg = r"Cannot convert arg \['14\.15'\] to a time" + if not PY311: + with pytest.raises(ValueError, match=msg): + to_time(new_string) + assert to_time(new_string, format="%H.%M") == time(14, 15) + + def test_arraylike(self): + arg = ["14:15", "20:20"] + expected_arr = [time(14, 15), time(20, 20)] + assert to_time(arg) == expected_arr + assert to_time(arg, format="%H:%M") == expected_arr + assert to_time(arg, infer_time_format=True) == expected_arr + assert to_time(arg, format="%I:%M%p", errors="coerce") == [None, None] + + msg = "errors='ignore' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = to_time(arg, format="%I:%M%p", errors="ignore") + tm.assert_numpy_array_equal(res, np.array(arg, dtype=np.object_)) + + msg = "Cannot convert.+to a time with given format" + with pytest.raises(ValueError, match=msg): + to_time(arg, format="%I:%M%p", errors="raise") + + tm.assert_series_equal( + to_time(Series(arg, name="test")), Series(expected_arr, name="test") + ) + + res = to_time(np.array(arg)) + assert isinstance(res, list) + assert res == expected_arr diff --git a/shared/package-files/7b/7be47f93c4f71d8202d8349c0389f38dcc2282c5c5f2b9f6942b29dca52b600a/blob b/shared/package-files/7b/7be47f93c4f71d8202d8349c0389f38dcc2282c5c5f2b9f6942b29dca52b600a/blob new file mode 100644 index 0000000000000000000000000000000000000000..b3e252ca57daf2690e6f67bed78653fcc4226173 --- /dev/null +++ b/shared/package-files/7b/7be47f93c4f71d8202d8349c0389f38dcc2282c5c5f2b9f6942b29dca52b600a/blob @@ -0,0 +1,105 @@ +"""Provide basic warnings used by setuptools modules. + +Using custom classes (other than ``UserWarning``) allow users to set +``PYTHONWARNINGS`` filters to run tests and prepare for upcoming changes in +setuptools. +""" + +import os +import warnings +from datetime import date +from inspect import cleandoc +from textwrap import indent +from typing import Optional, Tuple + +_DueDate = Tuple[int, int, int] # time tuple +_INDENT = 8 * " " +_TEMPLATE = f"""{80 * '*'}\n{{details}}\n{80 * '*'}""" + + +class SetuptoolsWarning(UserWarning): + """Base class in ``setuptools`` warning hierarchy.""" + + @classmethod + def emit( + cls, + summary: Optional[str] = None, + details: Optional[str] = None, + due_date: Optional[_DueDate] = None, + see_docs: Optional[str] = None, + see_url: Optional[str] = None, + stacklevel: int = 2, + **kwargs, + ): + """Private: reserved for ``setuptools`` internal use only""" + # Default values: + summary_ = summary or getattr(cls, "_SUMMARY", None) or "" + details_ = details or getattr(cls, "_DETAILS", None) or "" + due_date = due_date or getattr(cls, "_DUE_DATE", None) + docs_ref = see_docs or getattr(cls, "_SEE_DOCS", None) + docs_url = docs_ref and f"https://setuptools.pypa.io/en/latest/{docs_ref}" + see_url = see_url or getattr(cls, "_SEE_URL", None) + due = date(*due_date) if due_date else None + + text = cls._format(summary_, details_, due, see_url or docs_url, kwargs) + if due and due < date.today() and _should_enforce(): + raise cls(text) + warnings.warn(text, cls, stacklevel=stacklevel + 1) + + @classmethod + def _format( + cls, + summary: str, + details: str, + due_date: Optional[date] = None, + see_url: Optional[str] = None, + format_args: Optional[dict] = None, + ): + """Private: reserved for ``setuptools`` internal use only""" + today = date.today() + summary = cleandoc(summary).format_map(format_args or {}) + possible_parts = [ + cleandoc(details).format_map(format_args or {}), + ( + f"\nBy {due_date:%Y-%b-%d}, you need to update your project and remove " + "deprecated calls\nor your builds will no longer be supported." + if due_date and due_date > today + else None + ), + ( + "\nThis deprecation is overdue, please update your project and remove " + "deprecated\ncalls to avoid build errors in the future." + if due_date and due_date < today + else None + ), + (f"\nSee {see_url} for details." if see_url else None), + ] + parts = [x for x in possible_parts if x] + if parts: + body = indent(_TEMPLATE.format(details="\n".join(parts)), _INDENT) + return "\n".join([summary, "!!\n", body, "\n!!"]) + return summary + + +class InformationOnly(SetuptoolsWarning): + """Currently there is no clear way of displaying messages to the users + that use the setuptools backend directly via ``pip``. + The only thing that might work is a warning, although it is not the + most appropriate tool for the job... + + See pypa/packaging-problems#558. + """ + + +class SetuptoolsDeprecationWarning(SetuptoolsWarning): + """ + Base class for warning deprecations in ``setuptools`` + + This class is not derived from ``DeprecationWarning``, and as such is + visible by default. + """ + + +def _should_enforce(): + enforce = os.getenv("SETUPTOOLS_ENFORCE_DEPRECATION", "false").lower() + return enforce in ("true", "on", "ok", "1") diff --git a/shared/package-files/7b/7be486b66e3a9b1a7dbf090262719fc329bf7f5693bf830cb18165c470520662/blob b/shared/package-files/7b/7be486b66e3a9b1a7dbf090262719fc329bf7f5693bf830cb18165c470520662/blob new file mode 100644 index 0000000000000000000000000000000000000000..507cf879d63666cbe9e7650cbc2071bfe0269145 --- /dev/null +++ b/shared/package-files/7b/7be486b66e3a9b1a7dbf090262719fc329bf7f5693bf830cb18165c470520662/blob @@ -0,0 +1,517 @@ +# This file is part of Hypothesis, which may be found at +# https://github.com/HypothesisWorks/hypothesis/ +# +# Copyright the Hypothesis Authors. +# Individual contributors are listed in AUTHORS.rst and the git log. +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at https://mozilla.org/MPL/2.0/. + +import math +from decimal import Decimal +from fractions import Fraction +from typing import Literal, Optional, Union + +from hypothesis.control import reject +from hypothesis.errors import InvalidArgument +from hypothesis.internal.filtering import ( + get_float_predicate_bounds, + get_integer_predicate_bounds, +) +from hypothesis.internal.floats import ( + SMALLEST_SUBNORMAL, + float_of, + float_to_int, + int_to_float, + is_negative, + next_down, + next_down_normal, + next_up, + next_up_normal, + width_smallest_normals, +) +from hypothesis.internal.validation import ( + check_type, + check_valid_bound, + check_valid_interval, +) +from hypothesis.strategies._internal.misc import nothing +from hypothesis.strategies._internal.strategies import ( + SampledFromStrategy, + SearchStrategy, +) +from hypothesis.strategies._internal.utils import cacheable, defines_strategy + +# See https://github.com/python/mypy/issues/3186 - numbers.Real is wrong! +Real = Union[int, float, Fraction, Decimal] + + +class IntegersStrategy(SearchStrategy): + def __init__(self, start, end): + assert isinstance(start, int) or start is None + assert isinstance(end, int) or end is None + assert start is None or end is None or start <= end + self.start = start + self.end = end + + def __repr__(self): + if self.start is None and self.end is None: + return "integers()" + if self.end is None: + return f"integers(min_value={self.start})" + if self.start is None: + return f"integers(max_value={self.end})" + return f"integers({self.start}, {self.end})" + + def do_draw(self, data): + # For bounded integers, make the bounds and near-bounds more likely. + forced = None + if ( + self.end is not None + and self.start is not None + and self.end - self.start > 127 + ): + bits = data.draw_integer(0, 127) + forced = { + 122: self.start, + 123: self.start, + 124: self.end, + 125: self.end, + 126: self.start + 1, + 127: self.end - 1, + }.get(bits) + + return data.draw_integer( + min_value=self.start, max_value=self.end, forced=forced + ) + + def filter(self, condition): + if condition is math.isfinite: + return self + if condition in [math.isinf, math.isnan]: + return nothing() + kwargs, pred = get_integer_predicate_bounds(condition) + + start, end = self.start, self.end + if "min_value" in kwargs: + start = max(kwargs["min_value"], -math.inf if start is None else start) + if "max_value" in kwargs: + end = min(kwargs["max_value"], math.inf if end is None else end) + + if start != self.start or end != self.end: + if start is not None and end is not None and start > end: + return nothing() + self = type(self)(start, end) + if pred is None: + return self + return super().filter(pred) + + +@cacheable +@defines_strategy(force_reusable_values=True) +def integers( + min_value: Optional[int] = None, + max_value: Optional[int] = None, +) -> SearchStrategy[int]: + """Returns a strategy which generates integers. + + If min_value is not None then all values will be >= min_value. If + max_value is not None then all values will be <= max_value + + Examples from this strategy will shrink towards zero, and negative values + will also shrink towards positive (i.e. -n may be replaced by +n). + """ + check_valid_bound(min_value, "min_value") + check_valid_bound(max_value, "max_value") + check_valid_interval(min_value, max_value, "min_value", "max_value") + + if min_value is not None: + if min_value != int(min_value): + raise InvalidArgument( + "min_value=%r of type %r cannot be exactly represented as an integer." + % (min_value, type(min_value)) + ) + min_value = int(min_value) + if max_value is not None: + if max_value != int(max_value): + raise InvalidArgument( + "max_value=%r of type %r cannot be exactly represented as an integer." + % (max_value, type(max_value)) + ) + max_value = int(max_value) + + return IntegersStrategy(min_value, max_value) + + +class FloatStrategy(SearchStrategy): + """A strategy for floating point numbers.""" + + def __init__( + self, + *, + min_value: float, + max_value: float, + allow_nan: bool, + # The smallest nonzero number we can represent is usually a subnormal, but may + # be the smallest normal if we're running in unsafe denormals-are-zero mode. + # While that's usually an explicit error, we do need to handle the case where + # the user passes allow_subnormal=False. + smallest_nonzero_magnitude: float = SMALLEST_SUBNORMAL, + ): + super().__init__() + assert isinstance(allow_nan, bool) + assert smallest_nonzero_magnitude >= 0.0, "programmer error if this is negative" + if smallest_nonzero_magnitude == 0.0: # pragma: no cover + raise FloatingPointError( + "Got allow_subnormal=True, but we can't represent subnormal floats " + "right now, in violation of the IEEE-754 floating-point " + "specification. This is usually because something was compiled with " + "-ffast-math or a similar option, which sets global processor state. " + "See https://simonbyrne.github.io/notes/fastmath/ for a more detailed " + "writeup - and good luck!" + ) + self.min_value = min_value + self.max_value = max_value + self.allow_nan = allow_nan + self.smallest_nonzero_magnitude = smallest_nonzero_magnitude + + def __repr__(self): + return ( + f"{self.__class__.__name__}({self.min_value=}, {self.max_value=}, " + f"{self.allow_nan=}, {self.smallest_nonzero_magnitude=})" + ).replace("self.", "") + + def do_draw(self, data): + return data.draw_float( + min_value=self.min_value, + max_value=self.max_value, + allow_nan=self.allow_nan, + smallest_nonzero_magnitude=self.smallest_nonzero_magnitude, + ) + + def filter(self, condition): + # Handle a few specific weird cases. + if condition is math.isfinite: + return FloatStrategy( + min_value=max(self.min_value, next_up(float("-inf"))), + max_value=min(self.max_value, next_down(float("inf"))), + allow_nan=False, + smallest_nonzero_magnitude=self.smallest_nonzero_magnitude, + ) + if condition is math.isinf: + if permitted_infs := [ + x + for x in (-math.inf, math.inf) + if self.min_value <= x <= self.max_value + ]: + return SampledFromStrategy(permitted_infs) + return nothing() + if condition is math.isnan: + if not self.allow_nan: + return nothing() + return NanStrategy() + + kwargs, pred = get_float_predicate_bounds(condition) + if not kwargs: + return super().filter(pred) + min_bound = max(kwargs.get("min_value", -math.inf), self.min_value) + max_bound = min(kwargs.get("max_value", math.inf), self.max_value) + + # Adjustments for allow_subnormal=False, if any need to be made + if -self.smallest_nonzero_magnitude < min_bound < 0: + min_bound = -0.0 + elif 0 < min_bound < self.smallest_nonzero_magnitude: + min_bound = self.smallest_nonzero_magnitude + if -self.smallest_nonzero_magnitude < max_bound < 0: + max_bound = -self.smallest_nonzero_magnitude + elif 0 < max_bound < self.smallest_nonzero_magnitude: + max_bound = 0.0 + + if min_bound > max_bound: + return nothing() + if ( + min_bound > self.min_value + or self.max_value > max_bound + or (self.allow_nan and (-math.inf < min_bound or max_bound < math.inf)) + ): + self = type(self)( + min_value=min_bound, + max_value=max_bound, + allow_nan=False, + smallest_nonzero_magnitude=self.smallest_nonzero_magnitude, + ) + if pred is None: + return self + return super().filter(pred) + + +@cacheable +@defines_strategy(force_reusable_values=True) +def floats( + min_value: Optional[Real] = None, + max_value: Optional[Real] = None, + *, + allow_nan: Optional[bool] = None, + allow_infinity: Optional[bool] = None, + allow_subnormal: Optional[bool] = None, + width: Literal[16, 32, 64] = 64, + exclude_min: bool = False, + exclude_max: bool = False, +) -> SearchStrategy[float]: + """Returns a strategy which generates floats. + + - If min_value is not None, all values will be ``>= min_value`` + (or ``> min_value`` if ``exclude_min``). + - If max_value is not None, all values will be ``<= max_value`` + (or ``< max_value`` if ``exclude_max``). + - If min_value or max_value is not None, it is an error to enable + allow_nan. + - If both min_value and max_value are not None, it is an error to enable + allow_infinity. + - If inferred values range does not include subnormal values, it is an error + to enable allow_subnormal. + + Where not explicitly ruled out by the bounds, + :wikipedia:`subnormals `, infinities, and NaNs are possible + values generated by this strategy. + + The width argument specifies the maximum number of bits of precision + required to represent the generated float. Valid values are 16, 32, or 64. + Passing ``width=32`` will still use the builtin 64-bit :class:`~python:float` class, + but always for values which can be exactly represented as a 32-bit float. + + The exclude_min and exclude_max argument can be used to generate numbers + from open or half-open intervals, by excluding the respective endpoints. + Excluding either signed zero will also exclude the other. + Attempting to exclude an endpoint which is None will raise an error; + use ``allow_infinity=False`` to generate finite floats. You can however + use e.g. ``min_value=-math.inf, exclude_min=True`` to exclude only + one infinite endpoint. + + Examples from this strategy have a complicated and hard to explain + shrinking behaviour, but it tries to improve "human readability". Finite + numbers will be preferred to infinity and infinity will be preferred to + NaN. + """ + check_type(bool, exclude_min, "exclude_min") + check_type(bool, exclude_max, "exclude_max") + + if allow_nan is None: + allow_nan = bool(min_value is None and max_value is None) + elif allow_nan and (min_value is not None or max_value is not None): + raise InvalidArgument(f"Cannot have {allow_nan=}, with min_value or max_value") + + if width not in (16, 32, 64): + raise InvalidArgument( + f"Got {width=}, but the only valid values " + "are the integers 16, 32, and 64." + ) + + check_valid_bound(min_value, "min_value") + check_valid_bound(max_value, "max_value") + + if math.copysign(1.0, -0.0) == 1.0: # pragma: no cover + raise FloatingPointError( + "Your Python install can't represent -0.0, which is required by the " + "IEEE-754 floating-point specification. This is probably because it was " + "compiled with an unsafe option like -ffast-math; for a more detailed " + "explanation see https://simonbyrne.github.io/notes/fastmath/" + ) + if allow_subnormal and next_up(0.0, width=width) == 0: # pragma: no cover + # Not worth having separate CI envs and dependencies just to cover this branch; + # discussion in https://github.com/HypothesisWorks/hypothesis/issues/3092 + # + # Erroring out here ensures that the database contents are interpreted + # consistently - which matters for such a foundational strategy, even if it's + # not always true for all user-composed strategies further up the stack. + from _hypothesis_ftz_detector import identify_ftz_culprits + + try: + ftz_pkg = identify_ftz_culprits() + except Exception: + ftz_pkg = None + if ftz_pkg: + ftz_msg = ( + f"This seems to be because the `{ftz_pkg}` package was compiled with " + f"-ffast-math or a similar option, which sets global processor state " + f"- see https://simonbyrne.github.io/notes/fastmath/ for details. " + f"If you don't know why {ftz_pkg} is installed, `pipdeptree -rp " + f"{ftz_pkg}` will show which packages depend on it." + ) + else: + ftz_msg = ( + "This is usually because something was compiled with -ffast-math " + "or a similar option, which sets global processor state. See " + "https://simonbyrne.github.io/notes/fastmath/ for a more detailed " + "writeup - and good luck!" + ) + raise FloatingPointError( + f"Got {allow_subnormal=}, but we can't represent " + f"subnormal floats right now, in violation of the IEEE-754 floating-point " + f"specification. {ftz_msg}" + ) + + min_arg, max_arg = min_value, max_value + if min_value is not None: + min_value = float_of(min_value, width) + assert isinstance(min_value, float) + if max_value is not None: + max_value = float_of(max_value, width) + assert isinstance(max_value, float) + + if min_value != min_arg: + raise InvalidArgument( + f"min_value={min_arg!r} cannot be exactly represented as a float " + f"of width {width} - use {min_value=} instead." + ) + if max_value != max_arg: + raise InvalidArgument( + f"max_value={max_arg!r} cannot be exactly represented as a float " + f"of width {width} - use {max_value=} instead." + ) + + if exclude_min and (min_value is None or min_value == math.inf): + raise InvalidArgument(f"Cannot exclude {min_value=}") + if exclude_max and (max_value is None or max_value == -math.inf): + raise InvalidArgument(f"Cannot exclude {max_value=}") + + assumed_allow_subnormal = allow_subnormal is None or allow_subnormal + if min_value is not None and ( + exclude_min or (min_arg is not None and min_value < min_arg) + ): + min_value = next_up_normal(min_value, width, assumed_allow_subnormal) + if min_value == min_arg: + assert min_value == min_arg == 0 + assert is_negative(min_arg) + assert not is_negative(min_value) + min_value = next_up_normal(min_value, width, assumed_allow_subnormal) + assert min_value > min_arg # type: ignore + if max_value is not None and ( + exclude_max or (max_arg is not None and max_value > max_arg) + ): + max_value = next_down_normal(max_value, width, assumed_allow_subnormal) + if max_value == max_arg: + assert max_value == max_arg == 0 + assert is_negative(max_value) + assert not is_negative(max_arg) + max_value = next_down_normal(max_value, width, assumed_allow_subnormal) + assert max_value < max_arg # type: ignore + + if min_value == -math.inf: + min_value = None + if max_value == math.inf: + max_value = None + + bad_zero_bounds = ( + min_value == max_value == 0 + and is_negative(max_value) + and not is_negative(min_value) + ) + if ( + min_value is not None + and max_value is not None + and (min_value > max_value or bad_zero_bounds) + ): + # This is a custom alternative to check_valid_interval, because we want + # to include the bit-width and exclusion information in the message. + msg = ( + "There are no %s-bit floating-point values between min_value=%r " + "and max_value=%r" % (width, min_arg, max_arg) + ) + if exclude_min or exclude_max: + msg += f", {exclude_min=} and {exclude_max=}" + raise InvalidArgument(msg) + + if allow_infinity is None: + allow_infinity = bool(min_value is None or max_value is None) + elif allow_infinity: + if min_value is not None and max_value is not None: + raise InvalidArgument( + f"Cannot have {allow_infinity=}, with both min_value and max_value" + ) + elif min_value == math.inf: + if min_arg == math.inf: + raise InvalidArgument("allow_infinity=False excludes min_value=inf") + raise InvalidArgument( + f"exclude_min=True turns min_value={min_arg!r} into inf, " + "but allow_infinity=False" + ) + elif max_value == -math.inf: + if max_arg == -math.inf: + raise InvalidArgument("allow_infinity=False excludes max_value=-inf") + raise InvalidArgument( + f"exclude_max=True turns max_value={max_arg!r} into -inf, " + "but allow_infinity=False" + ) + + smallest_normal = width_smallest_normals[width] + if allow_subnormal is None: + if min_value is not None and max_value is not None: + if min_value == max_value: + allow_subnormal = -smallest_normal < min_value < smallest_normal + else: + allow_subnormal = ( + min_value < smallest_normal and max_value > -smallest_normal + ) + elif min_value is not None: + allow_subnormal = min_value < smallest_normal + elif max_value is not None: + allow_subnormal = max_value > -smallest_normal + else: + allow_subnormal = True + if allow_subnormal: + if min_value is not None and min_value >= smallest_normal: + raise InvalidArgument( + f"allow_subnormal=True, but minimum value {min_value} " + f"excludes values below float{width}'s " + f"smallest positive normal {smallest_normal}" + ) + if max_value is not None and max_value <= -smallest_normal: + raise InvalidArgument( + f"allow_subnormal=True, but maximum value {max_value} " + f"excludes values above float{width}'s " + f"smallest negative normal {-smallest_normal}" + ) + + if min_value is None: + min_value = float("-inf") + if max_value is None: + max_value = float("inf") + if not allow_infinity: + min_value = max(min_value, next_up(float("-inf"))) + max_value = min(max_value, next_down(float("inf"))) + assert isinstance(min_value, float) + assert isinstance(max_value, float) + smallest_nonzero_magnitude = ( + SMALLEST_SUBNORMAL if allow_subnormal else smallest_normal + ) + result: SearchStrategy = FloatStrategy( + min_value=min_value, + max_value=max_value, + allow_nan=allow_nan, + smallest_nonzero_magnitude=smallest_nonzero_magnitude, + ) + + if width < 64: + + def downcast(x): + try: + return float_of(x, width) + except OverflowError: # pragma: no cover + reject() + + result = result.map(downcast) + return result + + +class NanStrategy(SearchStrategy): + """Strategy for sampling the space of nan float values.""" + + def do_draw(self, data): + # Nans must have all exponent bits and the first mantissa bit set, so + # we generate by taking 64 random bits and setting the required ones. + sign_bit = int(data.draw_boolean()) << 63 + nan_bits = float_to_int(math.nan) + mantissa_bits = data.draw_integer(0, 2**52 - 1) + return int_to_float(sign_bit | nan_bits | mantissa_bits) diff --git a/shared/package-files/7b/7be64e9d5397613e5c98f5a158fe2cf71890a5be14e5b64f8af0fd4c6d3b474b/blob b/shared/package-files/7b/7be64e9d5397613e5c98f5a158fe2cf71890a5be14e5b64f8af0fd4c6d3b474b/blob new file mode 100644 index 0000000000000000000000000000000000000000..33b48bffa37d56123419923d1f62d578130933ea --- /dev/null +++ b/shared/package-files/7b/7be64e9d5397613e5c98f5a158fe2cf71890a5be14e5b64f8af0fd4c6d3b474b/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _convolution(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32); +TORCH_API at::Tensor & _convolution_out_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32, at::Tensor & out); +TORCH_API at::Tensor _convolution(const at::Tensor & input, const at::Tensor & weight, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, bool benchmark, bool deterministic, bool cudnn_enabled); +} // namespace native +} // namespace at diff --git a/shared/package-files/7b/7be7a25157920b67594360aef4babe72f67ad1aca163cb8d72bbd4c897f57c88/blob b/shared/package-files/7b/7be7a25157920b67594360aef4babe72f67ad1aca163cb8d72bbd4c897f57c88/blob new file mode 100644 index 0000000000000000000000000000000000000000..9fb1d75331c65e28ca53f2fd1d0fdbd6bcf91d61 --- /dev/null +++ b/shared/package-files/7b/7be7a25157920b67594360aef4babe72f67ad1aca163cb8d72bbd4c897f57c88/blob @@ -0,0 +1,12 @@ +1.604208033,1.609084497,1.612340676,1.614840017,1.617567448,1.618725109,1.618402429,1.62166538,1.622307268 +-0.3596381425,-0.3596341458,-0.3658093658,-0.3757907033,-0.3861340583,-0.3973207144,-0.4083417796,-0.3981791623,-0.3930894872 +0.6425404838,0.6461571842,0.6353921186,0.6260452325,0.6168473238,0.6157534195,0.6111525322,0.6331348482,0.6383091894 +1.122539509,1.121126321,1.122658369,1.125222816,1.130173112,1.134719924,1.13734661,1.138372321,1.138418196 +0.3347824726,0.333865797,0.3441812488,0.3596886069,0.3714092143,0.3829130645,0.3946316998,0.3968918779,0.3972556299 +0.1679934067,0.1632158202,0.1845803545,0.2040103572,0.2249986825,0.248070015,0.2665924989,0.2732456539,0.2736154569 +2.213868285,2.214665975,2.215219186,2.215695195,2.220439659,2.223854145,2.224282476,2.227783718,2.228197177 +-0.5000559401,-0.5010409734,-0.5041917046,-0.5082442607,-0.5280333353,-0.5494820186,-0.5701548101,-0.5486579487,-0.5410428144 +0.5962279226,0.5952352075,0.5836053054,0.5726845261,0.5754300007,0.6118322779,0.6135570033,0.7269567421,0.7432945092 +1.192029475,1.191952304,1.192725741,1.193764174,1.194968839,1.196084576,1.196878037,1.197089274,1.197140609 +0.3537685454,0.3534522854,0.3602232382,0.3699057196,0.3790117786,0.388013464,0.3970939092,0.3986593482,0.3995486401 +0.2093805037,0.2084484256,0.2139023053,0.2189361922,0.224061913,0.2295759446,0.2344442125,0.2356615212,0.2360115318 diff --git a/shared/package-files/7b/7beb8263843b4aef9d4de79497eb06505f45efeef455dda17ff090d98d084fd9/blob b/shared/package-files/7b/7beb8263843b4aef9d4de79497eb06505f45efeef455dda17ff090d98d084fd9/blob new file mode 100644 index 0000000000000000000000000000000000000000..995118597c049d2c7a56f66252a4def0399c1875 --- /dev/null +++ b/shared/package-files/7b/7beb8263843b4aef9d4de79497eb06505f45efeef455dda17ff090d98d084fd9/blob @@ -0,0 +1,87 @@ +import abc +import os +import pathlib +import sys +from email.message import Message +from importlib.abc import MetaPathFinder +from pathlib import Path +from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union, overload + +if sys.version_info >= (3, 8): + class PackageNotFoundError(ModuleNotFoundError): ... + class EntryPointBase(NamedTuple): + name: str + value: str + group: str + class EntryPoint(EntryPointBase): + def load(self) -> Any: ... # Callable[[], Any] or an importable module + @property + def extras(self) -> List[str]: ... + class PackagePath(pathlib.PurePosixPath): + def read_text(self, encoding: str = ...) -> str: ... + def read_binary(self) -> bytes: ... + def locate(self) -> os.PathLike[str]: ... + # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: + hash: Optional[FileHash] + size: Optional[int] + dist: Distribution + class FileHash: + mode: str + value: str + def __init__(self, spec: str) -> None: ... + class Distribution: + @abc.abstractmethod + def read_text(self, filename: str) -> Optional[str]: ... + @abc.abstractmethod + def locate_file(self, path: Union[os.PathLike[str], str]) -> os.PathLike[str]: ... + @classmethod + def from_name(cls, name: str) -> Distribution: ... + @overload + @classmethod + def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + @overload + @classmethod + def discover( + cls, *, context: None = ..., name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + @staticmethod + def at(path: Union[str, os.PathLike[str]]) -> PathDistribution: ... + @property + def metadata(self) -> Message: ... + @property + def version(self) -> str: ... + @property + def entry_points(self) -> List[EntryPoint]: ... + @property + def files(self) -> Optional[List[PackagePath]]: ... + @property + def requires(self) -> Optional[List[str]]: ... + class DistributionFinder(MetaPathFinder): + class Context: + name: Optional[str] + def __init__(self, *, name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any) -> None: ... + @property + def path(self) -> List[str]: ... + @property + def pattern(self) -> str: ... + @abc.abstractmethod + def find_distributions(self, context: Context = ...) -> Iterable[Distribution]: ... + class MetadataPathFinder(DistributionFinder): + @classmethod + def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + class PathDistribution(Distribution): + def __init__(self, path: Path) -> None: ... + def read_text(self, filename: Union[str, os.PathLike[str]]) -> str: ... + def locate_file(self, path: Union[str, os.PathLike[str]]) -> os.PathLike[str]: ... + def distribution(distribution_name: str) -> Distribution: ... + @overload + def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + @overload + def distributions( + *, context: None = ..., name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + def metadata(distribution_name: str) -> Message: ... + def version(distribution_name: str) -> str: ... + def entry_points() -> Dict[str, Tuple[EntryPoint, ...]]: ... + def files(distribution_name: str) -> Optional[List[PackagePath]]: ... + def requires(distribution_name: str) -> Optional[List[str]]: ... diff --git a/shared/package-files/7b/7bee3b770c82ece2179c06eed661160a351910a1f132dc5fa4dc7fd939a0d441/blob b/shared/package-files/7b/7bee3b770c82ece2179c06eed661160a351910a1f132dc5fa4dc7fd939a0d441/blob new file mode 100644 index 0000000000000000000000000000000000000000..bf4909aaefec7baa64e1f2d4b8b3a06743dff253 --- /dev/null +++ b/shared/package-files/7b/7bee3b770c82ece2179c06eed661160a351910a1f132dc5fa4dc7fd939a0d441/blob @@ -0,0 +1,719 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +#define C10_FORALL_TYPES(_) \ + _(AnyType) \ + _(EnumType) \ + _(AnyEnumType) \ + _(TensorType) \ + _(StorageType) \ + _(TupleType) \ + _(ListType) \ + _(DictType) \ + _(NumberType) \ + _(FloatType) \ + _(ComplexType) \ + _(FutureType) \ + _(AwaitType) \ + _(RRefType) \ + _(IntType) \ + _(NoneType) \ + _(StringType) \ + _(GeneratorType) \ + _(QuantizerType) \ + _(BoolType) \ + _(OptionalType) \ + _(VarType) \ + _(DeviceObjType) \ + _(StreamObjType) \ + _(FunctionType) \ + _(ClassType) \ + _(PyObjectType) \ + _(CapsuleType) \ + _(InterfaceType) \ + _(QSchemeType) \ + _(ScalarTypeType) \ + _(LayoutType) \ + _(MemoryFormatType) \ + _(AnyListType) \ + _(AnyTupleType) \ + _(AnyClassType) \ + _(SymIntType) \ + _(SymFloatType) \ + _(SymBoolType) \ + _(UnionType) \ + _(DynamicType) + +enum class TypeKind { +#define DEFINE_TYPE(T) T, + C10_FORALL_TYPES(DEFINE_TYPE) +#undef DEFINE_TYPE +}; + +TORCH_API const char* typeKindToString(TypeKind kind); + +struct Type; +struct SharedType; + +// Use this to customize how a Type is printed using `annotation_str()`. If +// c10::nullopt is returned, `annotation_str()` falls through to its default +// implementation. +using TypePrinter = std::function(const Type&)>; + +namespace detail { +template +struct IsSingletonType : public std::integral_constant {}; +} // namespace detail +#define TORCH_DECLARE_SINGLETON(Type) \ + struct Type; \ + namespace detail { \ + template <> struct IsSingletonType : public std::integral_constant {}; \ + } + +TORCH_DECLARE_SINGLETON(AnyType); +TORCH_DECLARE_SINGLETON(AnyEnumType); +TORCH_DECLARE_SINGLETON(NumberType); +TORCH_DECLARE_SINGLETON(FloatType); +TORCH_DECLARE_SINGLETON(ComplexType); +TORCH_DECLARE_SINGLETON(IntType); +TORCH_DECLARE_SINGLETON(BoolType); +TORCH_DECLARE_SINGLETON(StringType); +TORCH_DECLARE_SINGLETON(StorageType); +TORCH_DECLARE_SINGLETON(NoneType); +TORCH_DECLARE_SINGLETON(GeneratorType); +TORCH_DECLARE_SINGLETON(QuantizerType); +TORCH_DECLARE_SINGLETON(QSchemeType); +TORCH_DECLARE_SINGLETON(DeviceObjType); +TORCH_DECLARE_SINGLETON(StreamObjType); +TORCH_DECLARE_SINGLETON(CapsuleType); +TORCH_DECLARE_SINGLETON(PyObjectType); +TORCH_DECLARE_SINGLETON(ScalarTypeType); +TORCH_DECLARE_SINGLETON(LayoutType); +TORCH_DECLARE_SINGLETON(MemoryFormatType); +TORCH_DECLARE_SINGLETON(AnyListType); +TORCH_DECLARE_SINGLETON(AnyTupleType); +TORCH_DECLARE_SINGLETON(AnyClassType); + +namespace detail { +template +struct CastReturnType { + using type = std::shared_ptr; +}; + +template +struct CastReturnType::value>::type> { + using type = SingletonTypePtr; +}; + +template +struct CastConstReturnType { + using type = std::shared_ptr; +}; + +template +struct CastConstReturnType::value>::type> { + using type = SingletonTypePtr; +}; + +template +struct as_shared_type { + using type = SharedType*; +}; + +template +struct as_shared_type { + using type = const SharedType *; +}; +} // namespace detail + +struct TORCH_API Type { + friend TORCH_API bool operator==(const Type& lhs, const Type& rhs); + private: + TypeKind kind_; + + protected: + Type(TypeKind kind) : kind_(kind) {} + + Type(const Type&) = default; + Type& operator=(const Type&) = default; + Type(Type&&) noexcept = default; + Type& operator=(Type&&) noexcept = default; + + virtual std::string annotation_str_impl(TypePrinter /*printer*/) const { + return str(); + } + // a == b + virtual bool equals(const Type& rhs) const = 0; + // a == b <=> b == a + virtual bool symmetric() const { + return true; + } + + public: + template + class SingletonOrSharedTypePtr { + public: + using element_type = typename std::shared_ptr::element_type; + + SingletonOrSharedTypePtr() = default; + + /* implicit */ SingletonOrSharedTypePtr(std::shared_ptr x) + : repr_(std::move(x)) {} + + template ::value, bool> = true> + /* implicit */ SingletonOrSharedTypePtr(std::shared_ptr x) + : repr_(std::move(x)) {} + + /* implicit */ SingletonOrSharedTypePtr(std::nullptr_t) + : repr_(nullptr) {} + + /* implicit */ SingletonOrSharedTypePtr(SingletonTypePtr p) + : repr_(p) {} + + template ::value, bool> = true> + /* implicit */ SingletonOrSharedTypePtr(SingletonTypePtr p) + : repr_(SingletonTypePtr(p.get())) {} + + + // We need to support construction from T* for pybind. The problem + // is that it's not clear if we are supposed to be taking shared + // ownership or not. + // + // Case 1: if T is known statically to derive from SharedType, we should use + // shared_from_this() and take shared_ownership. + // + // Case 2: if T is exactly Type, we need to do a dynamic_cast to + // check if it's a SharedType and do the right thing. + // + // Case 3: Otherwise, T is not a SharedType. (debug-check this + // assumption!) Use a singleton pointer. + + template ::value, bool> = true> + /* implicit */ SingletonOrSharedTypePtr(T* p) : SingletonOrSharedTypePtr(static_cast::type>(p)->shared_from_this()) {} + + template ::value, bool> = true> + /* implicit */ SingletonOrSharedTypePtr(T* p) { + if (auto* shared_p = dynamic_cast::type>(p)) { + repr_ = Repr(shared_p->shared_from_this()); + } else { + repr_ = Repr(p); + } + } + + template ::value && !std::is_base_of::value, bool> = true> + /* implicit */ SingletonOrSharedTypePtr(T* p) + : repr_(p) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dynamic_cast::type>(p) == nullptr); + } + + SingletonOrSharedTypePtr(const SingletonOrSharedTypePtr&) = default; + SingletonOrSharedTypePtr(SingletonOrSharedTypePtr&&) noexcept = default; + SingletonOrSharedTypePtr& operator=(const SingletonOrSharedTypePtr&) = default; + SingletonOrSharedTypePtr& operator=(SingletonOrSharedTypePtr&&) noexcept = default; + + T* get() const { + return repr_.isSharedAndNonNull() ? repr_.shared_.repr_.get() : static_cast(repr_.rawRepr().first); + } + + operator bool() const { + return repr_.isNonNull(); + } + + bool operator==(std::nullptr_t) const { + return !repr_.isNonNull(); + } + + bool operator!=(std::nullptr_t) const { + return repr_.isNonNull(); + } + + template , void>::value, bool> = true> + U& operator*() const { + return *get(); + } + + T* operator->() const { + return get(); + } + + private: + // NOTE: SharedPtrWrapper exists to work around a baffling bug in + // nvcc; see comment in destroy() below. + struct SharedPtrWrapper { + SharedPtrWrapper(std::shared_ptr &&x) + : repr_(std::move(x)) {} + std::shared_ptr repr_; + }; + union Repr { + Repr() : Repr(nullptr) {} + + explicit Repr(std::shared_ptr x) + : shared_(std::move(x)) {} + + explicit Repr(std::nullptr_t) + : singletonRepr_(nullptr) {} + + explicit Repr(SingletonTypePtr p) + : singletonRepr_(p.get()) {} + + ~Repr() { + destroy(); + } + + // NOTE: the only non-UB way to access our null state is through + // rawRepr(), because our copy operation doesn't preserve which + // union member is active for null pointers. + Repr(const Repr& rhs) { + if (rhs.isSharedAndNonNull()) { + new (&shared_) SharedPtrWrapper(rhs.shared_); + } else { + singletonRepr_.singleton_ = static_cast(rhs.rawRepr().first); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.singletonRepr_.unused_ == nullptr); + singletonRepr_.unused_ = nullptr; + } + } + + Repr(Repr&& rhs) noexcept { + if (rhs.isSharedAndNonNull()) { + new (&shared_) SharedPtrWrapper(std::move(rhs.shared_)); + } else { + singletonRepr_.singleton_ = static_cast(rhs.rawRepr().first); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.singletonRepr_.unused_ == nullptr); + singletonRepr_.unused_ = nullptr; + } + } + + Repr& operator=(const Repr& rhs) { + if (&rhs == this) { + return *this; + } + if (rhs.isSharedAndNonNull()) { + if (isSharedAndNonNull()) { + shared_ = rhs.shared_; + } else { + new (&shared_) SharedPtrWrapper(rhs.shared_); + } + } else { + if (isSharedAndNonNull()) { + destroy(); + } + singletonRepr_.singleton_ = static_cast(rhs.rawRepr().first); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.rawRepr().nullIfSingleton_ == nullptr); + singletonRepr_.unused_ = nullptr; + } + return *this; + } + + Repr& operator=(Repr&& rhs) noexcept { + if (&rhs == this) { + return *this; + } + if (rhs.isSharedAndNonNull()) { + if (isSharedAndNonNull()) { + shared_ = std::move(rhs.shared_); + } else { + new (&shared_) SharedPtrWrapper(std::move(rhs.shared_)); + } + } else { + if (isSharedAndNonNull()) { + destroy(); + } + singletonRepr_.singleton_ = static_cast(rhs.rawRepr().first); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(rhs.rawRepr().nullIfSingleton_ == nullptr); + singletonRepr_.unused_ = nullptr; + } + return *this; + } + + SharedPtrWrapper shared_; + + struct SingletonRepr { + explicit SingletonRepr(T* s) : singleton_(s) {} + T* singleton_; + void* unused_ = nullptr; + } singletonRepr_; + struct RawRepr { + void* first; + void* nullIfSingleton_; + }; + + // It is UB to read the singleton part of Repr if it was + // constructed as a shared_ptr and vice versa, but memcpying out + // the representation is always OK, so here's an accessor to obey + // the letter of the law. + RawRepr rawRepr() const { + RawRepr repr{}; + memcpy(&repr, reinterpret_cast(this), sizeof(RawRepr)); + return repr; + } + + bool isNonNull() const { + auto repr = rawRepr(); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(repr.nullIfSingleton_ == nullptr || repr.first != nullptr); + return repr.first != nullptr; + } + + bool isSharedAndNonNull() const { + return rawRepr().nullIfSingleton_ != nullptr; + } + + private: + void destroy() { + if (isSharedAndNonNull()) { + // Without SharedPtrWrapper, this line would read + // `shared_.~shared_ptr()` and nvcc would complain with + // "error: expected primary-expression before '>' token" + // referring to the "t" in "shared_ptr". SharedPtrWrapper + // exists to work around this compiler bug. + shared_.~SharedPtrWrapper(); + } + } + } repr_; + }; + + using TypePtr = SingletonOrSharedTypePtr; + using Ptr = TypePtr; + using ElementType = Type; + + // subtyping relation. By default, we return true for the case + // when the type is exactly equal or if this <: T where rhs = Optional[T] + + // if this returns false and the why_not stream is non-null, it contains + // additional details that describe why this is not a subtype of 'rhs'. + // This additional information should only contain details that are not + // obvious from the annotation_str() that describes the type. For instance it + // is clear that `int <: str` is false but not clear why `Foo <: InterfaceBar` + // might be false. + virtual bool isSubtypeOfExt(const Type& rhs, std::ostream* why_not) const; + virtual bool is_module() const; + bool isSubtypeOf(const Type& rhs) const { + return isSubtypeOfExt(rhs, nullptr); + } + // Compatibility shims to accommodate existing code that passes shared_ptrs + // around. Ideally, we would just delete this, but it should be harmless. + template + typename std::enable_if::value, bool>::type + isSubtypeOf(const std::shared_ptr& rhs) const { + return isSubtypeOf(*rhs); + } + + template + typename std::enable_if::value, bool>::type + isSubtypeOf(const SingletonOrSharedTypePtr& rhs) const { + return isSubtypeOf(*rhs); + } + + template + typename std::enable_if::value, bool>::type + isSubtypeOf(SingletonTypePtr rhs) const { + return isSubtypeOf(*rhs); + } + + template + typename std::enable_if::value, bool>::type + isSubtypeOfExt(const SingletonOrSharedTypePtr& rhs, std::ostream* why_not) const { + return isSubtypeOfExt(*rhs, why_not); + } + + template + typename std::enable_if::value, bool>::type + isSubtypeOfExt(const std::shared_ptr& rhs, std::ostream* why_not) const { + return isSubtypeOfExt(*rhs, why_not); + } + + template + typename std::enable_if::value, bool>::type + isSubtypeOfExt(SingletonTypePtr rhs, std::ostream* why_not) const { + return isSubtypeOfExt(*rhs, why_not); + } + + // How this type will appear in FunctionSchema declarations + virtual std::string str() const = 0; + + // How this type will appear as if it were a type annotation in Python + // which is sometimes different than how it appears in declarations (e.g. + // int[] vs List[int]) + // + // Takes a custom printer that users can pass in to customize the output of + // this method. + std::string annotation_str(TypePrinter printer) const { + if (printer) { + // the printer can return nullopt to fall through to the default impl + if (auto renamed = printer(*this)) { + return *renamed; + } + } + return annotation_str_impl(std::move(printer)); + } + std::string annotation_str() const { + // Overload instead of define a default value for `printer` to help + // debuggers out. + return annotation_str(nullptr); + } + + // Returns a human readable string that includes additional information like + // "type is inferred rather than explicitly defined" to help construct more + // user-friendly messages. + virtual std::string repr_str() const { + return annotation_str(); + } + + TypeKind kind() const { + return kind_; + } + + virtual bool isUnionType() const { + return false; + } + + virtual bool requires_grad() const { + for (const auto& ct : containedTypes()) { + if (ct->requires_grad()) { + return true; + } + } + return false; + } + + // Dynamically cast this object to the subclass indicated by the + // template variable, returning nullptr if the cast is invalid. + template ::value, bool> = true> + typename detail::CastReturnType::type cast() { + if (T::Kind == kind()) { + return std::static_pointer_cast(static_cast(this)->shared_from_this()); + } + return nullptr; + } + template ::value, bool> = true> + typename detail::CastReturnType::type cast() { + if (T::Kind == kind()) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(this == T::get().get()); + return typename detail::CastReturnType::type(static_cast(this)); + } + return nullptr; + } + template ::value, bool> = true> + typename detail::CastConstReturnType::type cast() const { + if (T::Kind == kind()) { + return std::static_pointer_cast(static_cast(this)->shared_from_this()); + } + return nullptr; + } + template ::value, bool> = true> + typename detail::CastConstReturnType::type cast() const { + if (T::Kind == kind()) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(this == T::get().get()); + return typename detail::CastConstReturnType::type(static_cast(this)); + } + return nullptr; + } + template + T* castRaw() { + if (T::Kind == kind()) { + return static_cast(this); + } + return nullptr; + } + template + const T* castRaw() const { + if (T::Kind == kind()) { + return static_cast(this); + } + return nullptr; + } + template + auto expect() { + auto r = cast(); + AT_ASSERT(r); + return r; + } + template + auto expect() const { + auto r = cast(); + AT_ASSERT(r); + return r; + } + template + T& expectRef() { + auto* r = castRaw(); + AT_ASSERT(r); + return *r; + } + template + const T& expectRef() const { + auto* r = castRaw(); + AT_ASSERT(r); + return *r; + } + virtual ~Type() = default; + virtual bool hasFreeVariables() const { + return false; + } + // list of types this type contains, e.g. for a List then element type of a + // list for a tuple, the types of the tuple elements + virtual at::ArrayRef containedTypes() const { + return {}; + } + virtual TypePtr containedType(size_t i) const { + return containedTypes().at(i); + } + virtual size_t containedTypeSize() const { + return containedTypes().size(); + } + // create a new version of this type, replacing its contained types with + // contained_types + TypePtr withContained(std::vector contained_types); + // per-type constructor, you only need to override this if the + // containedTypes() is not empty + virtual TypePtr createWithContained( + std::vector /*contained_types*/) const { + AT_ERROR( + "type with contained types did not overload createWithContained: ", + str()); + } + +}; + +template +using SingletonOrSharedTypePtr = Type::SingletonOrSharedTypePtr; + + +template +bool operator==(const SingletonOrSharedTypePtr& x, const SingletonOrSharedTypePtr& y) { + return (void*)x.get() == (void*)y.get(); +} + +template +bool operator==(const SingletonOrSharedTypePtr& x, const std::shared_ptr& y) { + return (void*)x.get() == (void*)y.get(); +} + +template +bool operator==(const std::shared_ptr& x, const SingletonOrSharedTypePtr& y) { + return (void*)x.get() == (void*)y.get(); +} + +template +bool operator==(const SingletonOrSharedTypePtr& x, const SingletonTypePtr& y) { + return (void*)x.get() == (void*)y.get(); +} + +template +bool operator==(const SingletonTypePtr& x, const SingletonOrSharedTypePtr& y) { + return (void*)x.get() == (void*)y.get(); +} + +template +bool operator!=(const SingletonOrSharedTypePtr& x, const SingletonOrSharedTypePtr& y) { + return !(x == y); +} + +template +bool operator!=(const SingletonOrSharedTypePtr& x, const std::shared_ptr& y) { + return !(x == y); +} + +template +bool operator!=(const std::shared_ptr& x, const SingletonOrSharedTypePtr& y) { + return !(x == y); +} + +template +bool operator!=(const SingletonOrSharedTypePtr& x, const SingletonTypePtr& y) { + return !(x == y); +} + +template +bool operator!=(const SingletonTypePtr& x, const SingletonOrSharedTypePtr& y) { + return !(x == y); +} + +using TypePtr = SingletonOrSharedTypePtr; +using ConstTypePtr = SingletonOrSharedTypePtr; + +// Explicitly enable MaybeOwned>, rather than allowing +// MaybeOwned to be used for any type right away. +template +struct MaybeOwnedTraits> + : public MaybeOwnedTraitsGenericImpl> {}; + +// Base class for Types that are guaranteed to be owned by std::shared_ptr. +struct TORCH_API SharedType : public Type, public std::enable_shared_from_this { + using Type::Type; +}; + +inline TypePtr Type::withContained(std::vector contained_types) { + auto current_contained = containedTypes(); + // Types with no contained_types don't need this call. Check before calling! + // + // (We can't support this efficiently because types without + // contained types may be singletons, in which case + // shared_from_this will crash; we would have to provide a virtual + // typeptr_from_this or isSingleton.) + TORCH_INTERNAL_ASSERT(!current_contained.empty() && current_contained.size() == contained_types.size()); + if (current_contained.equals(contained_types)) { + return std::static_pointer_cast(static_cast(this)->shared_from_this()); + } + return createWithContained(std::move(contained_types)); +} + + +TORCH_API inline bool operator==(const Type& lhs, const Type& rhs) { + if (C10_UNLIKELY(!rhs.symmetric())) { + return rhs.equals(lhs); + } + return lhs.equals(rhs); +} + +struct NamedType; +using NamedTypePtr = std::shared_ptr; +using ConstNamedTypePtr = std::shared_ptr; + +struct TORCH_API NamedType : public SharedType { + NamedType(TypeKind tk, c10::optional name) + : SharedType(tk), name_(std::move(name)) { + TORCH_INTERNAL_ASSERT( + tk == TypeKind::TupleType || tk == TypeKind::FunctionType || + tk == TypeKind::ClassType || tk == TypeKind::InterfaceType || + tk == TypeKind::EnumType, + "If you add a new kind of NamedType, ", + "please update the cast specialization and this assert"); + } + + // Fully qualified name of type + // Looks like: "foo.bar.Baz". + const c10::optional& name() const { + return name_; + } + + private: + c10::optional name_; +}; + +} // namespace c10 + +namespace std { +template +struct hash> { + size_t operator()(const c10::SingletonOrSharedTypePtr& x) const { + return std::hash()(x.get()); + } +}; +} // namespace std diff --git a/shared/package-files/7b/7befc3e5955470328beb25c36dc8f50695eca2f99f88ea206fd8a84f58f4be5d/blob b/shared/package-files/7b/7befc3e5955470328beb25c36dc8f50695eca2f99f88ea206fd8a84f58f4be5d/blob new file mode 100644 index 0000000000000000000000000000000000000000..11fd059b2055960801f65c03f245e2382bd49e1f --- /dev/null +++ b/shared/package-files/7b/7befc3e5955470328beb25c36dc8f50695eca2f99f88ea206fd8a84f58f4be5d/blob @@ -0,0 +1,59 @@ +import datetime +from decimal import Decimal +from typing import Any, TypeVar, overload, Union + +from django.utils.functional import Promise +from typing_extensions import Literal + +class DjangoUnicodeDecodeError(UnicodeDecodeError): + obj: bytes = ... + def __init__(self, obj: bytes, *args: Any) -> None: ... + +_P = TypeVar("_P", bound=Promise) +_S = TypeVar("_S", bound=str) +_PT = TypeVar("_PT", None, int, float, Decimal, datetime.datetime, datetime.date, datetime.time) +@overload +def smart_text(s: _P, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> _P: ... +@overload +def smart_text(s: _PT, encoding: str = ..., strings_only: Literal[True] = ..., errors: str = ...) -> _PT: ... +@overload +def smart_text(s: _S, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> _S: ... +@overload +def smart_text(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> str: ... +def is_protected_type(obj: Any) -> bool: ... +@overload +def force_text(s: _PT, encoding: str = ..., strings_only: Literal[True] = ..., errors: str = ...) -> _PT: ... +@overload +def force_text(s: _S, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> _S: ... +@overload +def force_text(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> str: ... +@overload +def smart_bytes(s: _P, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> _P: ... +@overload +def smart_bytes(s: _PT, encoding: str = ..., strings_only: Literal[True] = ..., errors: str = ...) -> _PT: ... +@overload +def smart_bytes(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> bytes: ... +@overload +def force_bytes(s: _PT, encoding: str = ..., strings_only: Literal[True] = ..., errors: str = ...) -> _PT: ... +@overload +def force_bytes(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> bytes: ... + +smart_str = smart_text +force_str = force_text +@overload +def iri_to_uri(iri: None) -> None: ... +@overload +def iri_to_uri(iri: Union[str, Promise]) -> str: ... +@overload +def uri_to_iri(iri: None) -> None: ... +@overload +def uri_to_iri(iri: str) -> str: ... +def escape_uri_path(path: str) -> str: ... +def repercent_broken_unicode(path: bytes) -> bytes: ... +@overload +def filepath_to_uri(path: None) -> None: ... +@overload +def filepath_to_uri(path: str) -> str: ... +def get_system_encoding() -> str: ... + +DEFAULT_LOCALE_ENCODING: Any diff --git a/shared/package-files/7b/7bf552dd719a9b35d6c313c407f16905fc99ee2ad40d3952d74a4fac0355edc4/blob b/shared/package-files/7b/7bf552dd719a9b35d6c313c407f16905fc99ee2ad40d3952d74a4fac0355edc4/blob new file mode 100644 index 0000000000000000000000000000000000000000..ea61a4b6f4a75676c002be8118e439e3fa0a1325 --- /dev/null +++ b/shared/package-files/7b/7bf552dd719a9b35d6c313c407f16905fc99ee2ad40d3952d74a4fac0355edc4/blob @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_linalg_lu_factor_ex_out : public at::meta::structured_linalg_lu_factor_ex { +void impl(const at::Tensor & A, bool pivot, bool check_errors, const at::Tensor & LU, const at::Tensor & pivots, const at::Tensor & info); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/7b/7bf6238c766ef0fcd007290bce1a58d912478c29cbc67966a068fee518a73fa7/blob b/shared/package-files/7b/7bf6238c766ef0fcd007290bce1a58d912478c29cbc67966a068fee518a73fa7/blob new file mode 100644 index 0000000000000000000000000000000000000000..eab6cbfffa07928c14e1992ecc2bdf36fed0d9ad --- /dev/null +++ b/shared/package-files/7b/7bf6238c766ef0fcd007290bce1a58d912478c29cbc67966a068fee518a73fa7/blob @@ -0,0 +1,894 @@ +""" + pygments.lexers.freefem + ~~~~~~~~~~~~~~~~~~~~~~~ + + Lexer for FreeFem++ language. + + :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.token import Comment, Operator, Keyword, Name + +from pygments.lexers.c_cpp import CppLexer + +__all__ = ['FreeFemLexer'] + + +class FreeFemLexer(CppLexer): + """ + For FreeFem++ source. + + This is an extension of the CppLexer, as the FreeFem Language is a superset + of C++. + + .. versionadded:: 2.4 + """ + + name = 'Freefem' + url = 'https://freefem.org/' + aliases = ['freefem'] + filenames = ['*.edp'] + mimetypes = ['text/x-freefem'] + + # Language operators + operators = {'+', '-', '*', '.*', '/', './', '%', '^', '^-1', ':', '\''} + + # types + types = {'bool', 'border', 'complex', 'dmatrix', 'fespace', 'func', 'gslspline', + 'ifstream', 'int', 'macro', 'matrix', 'mesh', 'mesh3', 'mpiComm', + 'mpiGroup', 'mpiRequest', 'NewMacro', 'EndMacro', 'ofstream', 'Pmmap', + 'problem', 'Psemaphore', 'real', 'solve', 'string', 'varf'} + + # finite element spaces + fespaces = {'BDM1', 'BDM1Ortho', 'Edge03d', 'Edge13d', 'Edge23d', 'FEQF', 'HCT', + 'P0', 'P03d', 'P0Edge', 'P1', 'P13d', 'P1b', 'P1b3d', 'P1bl', 'P1bl3d', + 'P1dc', 'P1Edge', 'P1nc', 'P2', 'P23d', 'P2b', 'P2BR', 'P2dc', 'P2Edge', + 'P2h', 'P2Morley', 'P2pnc', 'P3', 'P3dc', 'P3Edge', 'P4', 'P4dc', + 'P4Edge', 'P5Edge', 'RT0', 'RT03d', 'RT0Ortho', 'RT1', 'RT1Ortho', + 'RT2', 'RT2Ortho'} + + # preprocessor + preprocessor = {'ENDIFMACRO', 'include', 'IFMACRO', 'load'} + + # Language keywords + keywords = { + 'adj', + 'append', + 'area', + 'ARGV', + 'be', + 'binary', + 'BoundaryEdge', + 'bordermeasure', + 'CG', + 'Cholesky', + 'cin', + 'cout', + 'Crout', + 'default', + 'diag', + 'edgeOrientation', + 'endl', + 'false', + 'ffind', + 'FILE', + 'find', + 'fixed', + 'flush', + 'GMRES', + 'good', + 'hTriangle', + 'im', + 'imax', + 'imin', + 'InternalEdge', + 'l1', + 'l2', + 'label', + 'lenEdge', + 'length', + 'LINE', + 'linfty', + 'LU', + 'm', + 'max', + 'measure', + 'min', + 'mpiAnySource', + 'mpiBAND', + 'mpiBXOR', + 'mpiCommWorld', + 'mpiLAND', + 'mpiLOR', + 'mpiLXOR', + 'mpiMAX', + 'mpiMIN', + 'mpiPROD', + 'mpirank', + 'mpisize', + 'mpiSUM', + 'mpiUndefined', + 'n', + 'N', + 'nbe', + 'ndof', + 'ndofK', + 'noshowbase', + 'noshowpos', + 'notaregion', + 'nt', + 'nTonEdge', + 'nuEdge', + 'nuTriangle', + 'nv', + 'P', + 'pi', + 'precision', + 'qf1pE', + 'qf1pElump', + 'qf1pT', + 'qf1pTlump', + 'qfV1', + 'qfV1lump', + 'qf2pE', + 'qf2pT', + 'qf2pT4P1', + 'qfV2', + 'qf3pE', + 'qf4pE', + 'qf5pE', + 'qf5pT', + 'qfV5', + 'qf7pT', + 'qf9pT', + 'qfnbpE', + 'quantile', + 're', + 'region', + 'rfind', + 'scientific', + 'searchMethod', + 'setw', + 'showbase', + 'showpos', + 'sparsesolver', + 'sum', + 'tellp', + 'true', + 'UMFPACK', + 'unused', + 'whoinElement', + 'verbosity', + 'version', + 'volume', + 'x', + 'y', + 'z' + } + + # Language shipped functions and class ( ) + functions = { + 'abs', + 'acos', + 'acosh', + 'adaptmesh', + 'adj', + 'AffineCG', + 'AffineGMRES', + 'arg', + 'asin', + 'asinh', + 'assert', + 'atan', + 'atan2', + 'atanh', + 'atof', + 'atoi', + 'BFGS', + 'broadcast', + 'buildlayers', + 'buildmesh', + 'ceil', + 'chi', + 'complexEigenValue', + 'copysign', + 'change', + 'checkmovemesh', + 'clock', + 'cmaes', + 'conj', + 'convect', + 'cos', + 'cosh', + 'cube', + 'd', + 'dd', + 'dfft', + 'diffnp', + 'diffpos', + 'dimKrylov', + 'dist', + 'dumptable', + 'dx', + 'dxx', + 'dxy', + 'dxz', + 'dy', + 'dyx', + 'dyy', + 'dyz', + 'dz', + 'dzx', + 'dzy', + 'dzz', + 'EigenValue', + 'emptymesh', + 'erf', + 'erfc', + 'exec', + 'exit', + 'exp', + 'fdim', + 'floor', + 'fmax', + 'fmin', + 'fmod', + 'freeyams', + 'getARGV', + 'getline', + 'gmshload', + 'gmshload3', + 'gslcdfugaussianP', + 'gslcdfugaussianQ', + 'gslcdfugaussianPinv', + 'gslcdfugaussianQinv', + 'gslcdfgaussianP', + 'gslcdfgaussianQ', + 'gslcdfgaussianPinv', + 'gslcdfgaussianQinv', + 'gslcdfgammaP', + 'gslcdfgammaQ', + 'gslcdfgammaPinv', + 'gslcdfgammaQinv', + 'gslcdfcauchyP', + 'gslcdfcauchyQ', + 'gslcdfcauchyPinv', + 'gslcdfcauchyQinv', + 'gslcdflaplaceP', + 'gslcdflaplaceQ', + 'gslcdflaplacePinv', + 'gslcdflaplaceQinv', + 'gslcdfrayleighP', + 'gslcdfrayleighQ', + 'gslcdfrayleighPinv', + 'gslcdfrayleighQinv', + 'gslcdfchisqP', + 'gslcdfchisqQ', + 'gslcdfchisqPinv', + 'gslcdfchisqQinv', + 'gslcdfexponentialP', + 'gslcdfexponentialQ', + 'gslcdfexponentialPinv', + 'gslcdfexponentialQinv', + 'gslcdfexppowP', + 'gslcdfexppowQ', + 'gslcdftdistP', + 'gslcdftdistQ', + 'gslcdftdistPinv', + 'gslcdftdistQinv', + 'gslcdffdistP', + 'gslcdffdistQ', + 'gslcdffdistPinv', + 'gslcdffdistQinv', + 'gslcdfbetaP', + 'gslcdfbetaQ', + 'gslcdfbetaPinv', + 'gslcdfbetaQinv', + 'gslcdfflatP', + 'gslcdfflatQ', + 'gslcdfflatPinv', + 'gslcdfflatQinv', + 'gslcdflognormalP', + 'gslcdflognormalQ', + 'gslcdflognormalPinv', + 'gslcdflognormalQinv', + 'gslcdfgumbel1P', + 'gslcdfgumbel1Q', + 'gslcdfgumbel1Pinv', + 'gslcdfgumbel1Qinv', + 'gslcdfgumbel2P', + 'gslcdfgumbel2Q', + 'gslcdfgumbel2Pinv', + 'gslcdfgumbel2Qinv', + 'gslcdfweibullP', + 'gslcdfweibullQ', + 'gslcdfweibullPinv', + 'gslcdfweibullQinv', + 'gslcdfparetoP', + 'gslcdfparetoQ', + 'gslcdfparetoPinv', + 'gslcdfparetoQinv', + 'gslcdflogisticP', + 'gslcdflogisticQ', + 'gslcdflogisticPinv', + 'gslcdflogisticQinv', + 'gslcdfbinomialP', + 'gslcdfbinomialQ', + 'gslcdfpoissonP', + 'gslcdfpoissonQ', + 'gslcdfgeometricP', + 'gslcdfgeometricQ', + 'gslcdfnegativebinomialP', + 'gslcdfnegativebinomialQ', + 'gslcdfpascalP', + 'gslcdfpascalQ', + 'gslinterpakima', + 'gslinterpakimaperiodic', + 'gslinterpcsplineperiodic', + 'gslinterpcspline', + 'gslinterpsteffen', + 'gslinterplinear', + 'gslinterppolynomial', + 'gslranbernoullipdf', + 'gslranbeta', + 'gslranbetapdf', + 'gslranbinomialpdf', + 'gslranexponential', + 'gslranexponentialpdf', + 'gslranexppow', + 'gslranexppowpdf', + 'gslrancauchy', + 'gslrancauchypdf', + 'gslranchisq', + 'gslranchisqpdf', + 'gslranerlang', + 'gslranerlangpdf', + 'gslranfdist', + 'gslranfdistpdf', + 'gslranflat', + 'gslranflatpdf', + 'gslrangamma', + 'gslrangammaint', + 'gslrangammapdf', + 'gslrangammamt', + 'gslrangammaknuth', + 'gslrangaussian', + 'gslrangaussianratiomethod', + 'gslrangaussianziggurat', + 'gslrangaussianpdf', + 'gslranugaussian', + 'gslranugaussianratiomethod', + 'gslranugaussianpdf', + 'gslrangaussiantail', + 'gslrangaussiantailpdf', + 'gslranugaussiantail', + 'gslranugaussiantailpdf', + 'gslranlandau', + 'gslranlandaupdf', + 'gslrangeometricpdf', + 'gslrangumbel1', + 'gslrangumbel1pdf', + 'gslrangumbel2', + 'gslrangumbel2pdf', + 'gslranlogistic', + 'gslranlogisticpdf', + 'gslranlognormal', + 'gslranlognormalpdf', + 'gslranlogarithmicpdf', + 'gslrannegativebinomialpdf', + 'gslranpascalpdf', + 'gslranpareto', + 'gslranparetopdf', + 'gslranpoissonpdf', + 'gslranrayleigh', + 'gslranrayleighpdf', + 'gslranrayleightail', + 'gslranrayleightailpdf', + 'gslrantdist', + 'gslrantdistpdf', + 'gslranlaplace', + 'gslranlaplacepdf', + 'gslranlevy', + 'gslranweibull', + 'gslranweibullpdf', + 'gslsfairyAi', + 'gslsfairyBi', + 'gslsfairyAiscaled', + 'gslsfairyBiscaled', + 'gslsfairyAideriv', + 'gslsfairyBideriv', + 'gslsfairyAiderivscaled', + 'gslsfairyBiderivscaled', + 'gslsfairyzeroAi', + 'gslsfairyzeroBi', + 'gslsfairyzeroAideriv', + 'gslsfairyzeroBideriv', + 'gslsfbesselJ0', + 'gslsfbesselJ1', + 'gslsfbesselJn', + 'gslsfbesselY0', + 'gslsfbesselY1', + 'gslsfbesselYn', + 'gslsfbesselI0', + 'gslsfbesselI1', + 'gslsfbesselIn', + 'gslsfbesselI0scaled', + 'gslsfbesselI1scaled', + 'gslsfbesselInscaled', + 'gslsfbesselK0', + 'gslsfbesselK1', + 'gslsfbesselKn', + 'gslsfbesselK0scaled', + 'gslsfbesselK1scaled', + 'gslsfbesselKnscaled', + 'gslsfbesselj0', + 'gslsfbesselj1', + 'gslsfbesselj2', + 'gslsfbesseljl', + 'gslsfbessely0', + 'gslsfbessely1', + 'gslsfbessely2', + 'gslsfbesselyl', + 'gslsfbesseli0scaled', + 'gslsfbesseli1scaled', + 'gslsfbesseli2scaled', + 'gslsfbesselilscaled', + 'gslsfbesselk0scaled', + 'gslsfbesselk1scaled', + 'gslsfbesselk2scaled', + 'gslsfbesselklscaled', + 'gslsfbesselJnu', + 'gslsfbesselYnu', + 'gslsfbesselInuscaled', + 'gslsfbesselInu', + 'gslsfbesselKnuscaled', + 'gslsfbesselKnu', + 'gslsfbessellnKnu', + 'gslsfbesselzeroJ0', + 'gslsfbesselzeroJ1', + 'gslsfbesselzeroJnu', + 'gslsfclausen', + 'gslsfhydrogenicR1', + 'gslsfdawson', + 'gslsfdebye1', + 'gslsfdebye2', + 'gslsfdebye3', + 'gslsfdebye4', + 'gslsfdebye5', + 'gslsfdebye6', + 'gslsfdilog', + 'gslsfmultiply', + 'gslsfellintKcomp', + 'gslsfellintEcomp', + 'gslsfellintPcomp', + 'gslsfellintDcomp', + 'gslsfellintF', + 'gslsfellintE', + 'gslsfellintRC', + 'gslsferfc', + 'gslsflogerfc', + 'gslsferf', + 'gslsferfZ', + 'gslsferfQ', + 'gslsfhazard', + 'gslsfexp', + 'gslsfexpmult', + 'gslsfexpm1', + 'gslsfexprel', + 'gslsfexprel2', + 'gslsfexpreln', + 'gslsfexpintE1', + 'gslsfexpintE2', + 'gslsfexpintEn', + 'gslsfexpintE1scaled', + 'gslsfexpintE2scaled', + 'gslsfexpintEnscaled', + 'gslsfexpintEi', + 'gslsfexpintEiscaled', + 'gslsfShi', + 'gslsfChi', + 'gslsfexpint3', + 'gslsfSi', + 'gslsfCi', + 'gslsfatanint', + 'gslsffermidiracm1', + 'gslsffermidirac0', + 'gslsffermidirac1', + 'gslsffermidirac2', + 'gslsffermidiracint', + 'gslsffermidiracmhalf', + 'gslsffermidirachalf', + 'gslsffermidirac3half', + 'gslsffermidiracinc0', + 'gslsflngamma', + 'gslsfgamma', + 'gslsfgammastar', + 'gslsfgammainv', + 'gslsftaylorcoeff', + 'gslsffact', + 'gslsfdoublefact', + 'gslsflnfact', + 'gslsflndoublefact', + 'gslsflnchoose', + 'gslsfchoose', + 'gslsflnpoch', + 'gslsfpoch', + 'gslsfpochrel', + 'gslsfgammaincQ', + 'gslsfgammaincP', + 'gslsfgammainc', + 'gslsflnbeta', + 'gslsfbeta', + 'gslsfbetainc', + 'gslsfgegenpoly1', + 'gslsfgegenpoly2', + 'gslsfgegenpoly3', + 'gslsfgegenpolyn', + 'gslsfhyperg0F1', + 'gslsfhyperg1F1int', + 'gslsfhyperg1F1', + 'gslsfhypergUint', + 'gslsfhypergU', + 'gslsfhyperg2F0', + 'gslsflaguerre1', + 'gslsflaguerre2', + 'gslsflaguerre3', + 'gslsflaguerren', + 'gslsflambertW0', + 'gslsflambertWm1', + 'gslsflegendrePl', + 'gslsflegendreP1', + 'gslsflegendreP2', + 'gslsflegendreP3', + 'gslsflegendreQ0', + 'gslsflegendreQ1', + 'gslsflegendreQl', + 'gslsflegendrePlm', + 'gslsflegendresphPlm', + 'gslsflegendrearraysize', + 'gslsfconicalPhalf', + 'gslsfconicalPmhalf', + 'gslsfconicalP0', + 'gslsfconicalP1', + 'gslsfconicalPsphreg', + 'gslsfconicalPcylreg', + 'gslsflegendreH3d0', + 'gslsflegendreH3d1', + 'gslsflegendreH3d', + 'gslsflog', + 'gslsflogabs', + 'gslsflog1plusx', + 'gslsflog1plusxmx', + 'gslsfpowint', + 'gslsfpsiint', + 'gslsfpsi', + 'gslsfpsi1piy', + 'gslsfpsi1int', + 'gslsfpsi1', + 'gslsfpsin', + 'gslsfsynchrotron1', + 'gslsfsynchrotron2', + 'gslsftransport2', + 'gslsftransport3', + 'gslsftransport4', + 'gslsftransport5', + 'gslsfsin', + 'gslsfcos', + 'gslsfhypot', + 'gslsfsinc', + 'gslsflnsinh', + 'gslsflncosh', + 'gslsfanglerestrictsymm', + 'gslsfanglerestrictpos', + 'gslsfzetaint', + 'gslsfzeta', + 'gslsfzetam1', + 'gslsfzetam1int', + 'gslsfhzeta', + 'gslsfetaint', + 'gslsfeta', + 'imag', + 'int1d', + 'int2d', + 'int3d', + 'intalledges', + 'intallfaces', + 'interpolate', + 'invdiff', + 'invdiffnp', + 'invdiffpos', + 'Isend', + 'isInf', + 'isNaN', + 'isoline', + 'Irecv', + 'j0', + 'j1', + 'jn', + 'jump', + 'lgamma', + 'LinearCG', + 'LinearGMRES', + 'log', + 'log10', + 'lrint', + 'lround', + 'max', + 'mean', + 'medit', + 'min', + 'mmg3d', + 'movemesh', + 'movemesh23', + 'mpiAlltoall', + 'mpiAlltoallv', + 'mpiAllgather', + 'mpiAllgatherv', + 'mpiAllReduce', + 'mpiBarrier', + 'mpiGather', + 'mpiGatherv', + 'mpiRank', + 'mpiReduce', + 'mpiScatter', + 'mpiScatterv', + 'mpiSize', + 'mpiWait', + 'mpiWaitAny', + 'mpiWtick', + 'mpiWtime', + 'mshmet', + 'NaN', + 'NLCG', + 'on', + 'plot', + 'polar', + 'Post', + 'pow', + 'processor', + 'processorblock', + 'projection', + 'randinit', + 'randint31', + 'randint32', + 'random', + 'randreal1', + 'randreal2', + 'randreal3', + 'randres53', + 'Read', + 'readmesh', + 'readmesh3', + 'Recv', + 'rint', + 'round', + 'savemesh', + 'savesol', + 'savevtk', + 'seekg', + 'Sent', + 'set', + 'sign', + 'signbit', + 'sin', + 'sinh', + 'sort', + 'splitComm', + 'splitmesh', + 'sqrt', + 'square', + 'srandom', + 'srandomdev', + 'Stringification', + 'swap', + 'system', + 'tan', + 'tanh', + 'tellg', + 'tetg', + 'tetgconvexhull', + 'tetgreconstruction', + 'tetgtransfo', + 'tgamma', + 'triangulate', + 'trunc', + 'Wait', + 'Write', + 'y0', + 'y1', + 'yn' + } + + # function parameters + parameters = { + 'A', + 'A1', + 'abserror', + 'absolute', + 'aniso', + 'aspectratio', + 'B', + 'B1', + 'bb', + 'beginend', + 'bin', + 'boundary', + 'bw', + 'close', + 'cmm', + 'coef', + 'composante', + 'cutoff', + 'datafilename', + 'dataname', + 'dim', + 'distmax', + 'displacement', + 'doptions', + 'dparams', + 'eps', + 'err', + 'errg', + 'facemerge', + 'facetcl', + 'factorize', + 'file', + 'fill', + 'fixedborder', + 'flabel', + 'flags', + 'floatmesh', + 'floatsol', + 'fregion', + 'gradation', + 'grey', + 'hmax', + 'hmin', + 'holelist', + 'hsv', + 'init', + 'inquire', + 'inside', + 'IsMetric', + 'iso', + 'ivalue', + 'keepbackvertices', + 'label', + 'labeldown', + 'labelmid', + 'labelup', + 'levelset', + 'loptions', + 'lparams', + 'maxit', + 'maxsubdiv', + 'meditff', + 'mem', + 'memory', + 'metric', + 'mode', + 'nbarrow', + 'nbiso', + 'nbiter', + 'nbjacoby', + 'nboffacetcl', + 'nbofholes', + 'nbofregions', + 'nbregul', + 'nbsmooth', + 'nbvx', + 'ncv', + 'nev', + 'nomeshgeneration', + 'normalization', + 'omega', + 'op', + 'optimize', + 'option', + 'options', + 'order', + 'orientation', + 'periodic', + 'power', + 'precon', + 'prev', + 'ps', + 'ptmerge', + 'qfe', + 'qforder', + 'qft', + 'qfV', + 'ratio', + 'rawvector', + 'reffacelow', + 'reffacemid', + 'reffaceup', + 'refnum', + 'reftet', + 'reftri', + 'region', + 'regionlist', + 'renumv', + 'rescaling', + 'ridgeangle', + 'save', + 'sigma', + 'sizeofvolume', + 'smoothing', + 'solver', + 'sparams', + 'split', + 'splitin2', + 'splitpbedge', + 'stop', + 'strategy', + 'swap', + 'switch', + 'sym', + 't', + 'tgv', + 'thetamax', + 'tol', + 'tolpivot', + 'tolpivotsym', + 'transfo', + 'U2Vc', + 'value', + 'varrow', + 'vector', + 'veps', + 'viso', + 'wait', + 'width', + 'withsurfacemesh', + 'WindowIndex', + 'which', + 'zbound' + } + + # deprecated + deprecated = {'fixeborder'} + + # do not highlight + suppress_highlight = { + 'alignof', + 'asm', + 'constexpr', + 'decltype', + 'div', + 'double', + 'grad', + 'mutable', + 'namespace', + 'noexcept', + 'restrict', + 'static_assert', + 'template', + 'this', + 'thread_local', + 'typeid', + 'typename', + 'using' + } + + def get_tokens_unprocessed(self, text, stack=('root',)): + for index, token, value in CppLexer.get_tokens_unprocessed(self, text, stack): + if value in self.operators: + yield index, Operator, value + elif value in self.types: + yield index, Keyword.Type, value + elif value in self.fespaces: + yield index, Name.Class, value + elif value in self.preprocessor: + yield index, Comment.Preproc, value + elif value in self.keywords: + yield index, Keyword.Reserved, value + elif value in self.functions: + yield index, Name.Function, value + elif value in self.parameters: + yield index, Keyword.Pseudo, value + elif value in self.suppress_highlight: + yield index, Name, value + else: + yield index, token, value diff --git a/shared/package-files/7b/7bf9ee1a8e102e0b1da6766b0b8f710d57dccffa6b4c600e5c6ca31046e428ce/blob b/shared/package-files/7b/7bf9ee1a8e102e0b1da6766b0b8f710d57dccffa6b4c600e5c6ca31046e428ce/blob new file mode 100644 index 0000000000000000000000000000000000000000..7f24c778feb1b4556587773f711e21521efc537c --- /dev/null +++ b/shared/package-files/7b/7bf9ee1a8e102e0b1da6766b0b8f710d57dccffa6b4c600e5c6ca31046e428ce/blob @@ -0,0 +1,41 @@ +from datetime import datetime + +import numpy as np + +from pandas import Series +import pandas._testing as tm + + +def test_reindex_like(datetime_series): + other = datetime_series[::2] + tm.assert_series_equal( + datetime_series.reindex(other.index), datetime_series.reindex_like(other) + ) + + # GH#7179 + day1 = datetime(2013, 3, 5) + day2 = datetime(2013, 5, 5) + day3 = datetime(2014, 3, 5) + + series1 = Series([5, None, None], [day1, day2, day3]) + series2 = Series([None, None], [day1, day3]) + + result = series1.reindex_like(series2, method="pad") + expected = Series([5, np.nan], index=[day1, day3]) + tm.assert_series_equal(result, expected) + + +def test_reindex_like_nearest(): + ser = Series(np.arange(10, dtype="int64")) + + target = [0.1, 0.9, 1.5, 2.0] + other = ser.reindex(target, method="nearest") + expected = Series(np.around(target).astype("int64"), target) + + result = ser.reindex_like(other, method="nearest") + tm.assert_series_equal(expected, result) + + result = ser.reindex_like(other, method="nearest", tolerance=1) + tm.assert_series_equal(expected, result) + result = ser.reindex_like(other, method="nearest", tolerance=[1, 2, 3, 4]) + tm.assert_series_equal(expected, result) diff --git a/shared/package-files/7c/7c01b40185a8289ffeab36e4253218999fcbaebd12e6db3aa417f65ebc251603/blob b/shared/package-files/7c/7c01b40185a8289ffeab36e4253218999fcbaebd12e6db3aa417f65ebc251603/blob new file mode 100644 index 0000000000000000000000000000000000000000..c21cb1cec88adae7bb11006447c15f5a29c3de77 --- /dev/null +++ b/shared/package-files/7c/7c01b40185a8289ffeab36e4253218999fcbaebd12e6db3aa417f65ebc251603/blob @@ -0,0 +1,1097 @@ +#pragma once + +#if defined(__linux__) +#include +#include +#include +#include +#endif + +#ifdef USE_C10D_NCCL + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace c10d { + +// Control whether or not wait() is blocking or non-blocking. +static std::vector TORCH_NCCL_BLOCKING_WAIT = { + "TORCH_NCCL_BLOCKING_WAIT", + "NCCL_BLOCKING_WAIT"}; + +// Control whether or not we perform Async Error Handling with NCCL. +static std::vector TORCH_NCCL_ASYNC_ERROR_HANDLING = { + "TORCH_NCCL_ASYNC_ERROR_HANDLING", + "NCCL_ASYNC_ERROR_HANDLING"}; + +// Control whether dumping debug info on watchdog +// timeout is enabled. This variable must be set together with +// TORCH_NCCL_ENABLE_MONITORING=1 and TORCH_NCCL_TRACE_BUFFER_SIZE > 0. +static std::vector TORCH_NCCL_DUMP_ON_TIMEOUT = { + "TORCH_NCCL_DUMP_ON_TIMEOUT"}; + +// Control whether Desync Debug is enabled. This variable must be set +// together with TORCH_NCCL_ASYNC_ERROR_HANDLING. +static std::vector TORCH_NCCL_DESYNC_DEBUG = { + "TORCH_NCCL_DESYNC_DEBUG", + "NCCL_DESYNC_DEBUG"}; + +// Enable recording start-events for all ProcessGroupNCCL collectives, and +// compute accurate collective timing per-collective. (Note: end-events are +// recorded by default. Turn on this flag can increase chances of a watchdog +// hang due to performing a CUDA event query which eventually calls +// cudaEventElapsedTime() API. +static std::vector TORCH_NCCL_ENABLE_TIMING = { + "TORCH_NCCL_ENABLE_TIMING", + "NCCL_ENABLE_TIMING"}; + +// Enable monitoring thread which aborts the process when the ProcessGroupNCCL +// Watchdog thread gets stuck and no heartbeat is detected after +// TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC. This can happen due to calling CUDA/NCCL +// APIs that may hang. It is Useful to prevent jobs being stuck for a prolonged +// time than necessary tying up cluster resources. +static std::vector TORCH_NCCL_ENABLE_MONITORING = { + "TORCH_NCCL_ENABLE_MONITORING"}; + +// Control the watchdog heartbeat timeout period after which the monitoring +// thread will abort the process. +static std::vector TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC = { + "TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC"}; + +// The maximum number of events we store in the flight recorder's ring buffer. +// (One event could be the start or end of a collective, for example). +static std::vector TORCH_NCCL_TRACE_BUFFER_SIZE = { + "TORCH_NCCL_TRACE_BUFFER_SIZE"}; + +// Control how much extra time we will wait for dumping the debugging info +// before we exit and throws timeout exception. +static std::vector TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC = { + "TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC"}; + +// Control the interval inside the watchdog thread to check the coordinated +// signal from other ranks, e.g. to dump the debugging information. +static std::vector TORCH_NCCL_COORD_CHECK_MILSEC = { + "TORCH_NCCL_COORD_CHECK_MILSEC"}; + +// Whether to abort the communicators when users call destroy_process_group(). +// If yes, communicators will be aborted when destroy_process_group is called, +// but not in destructor. +static std::vector TORCH_NCCL_ABORT_IN_DESTROY_PG = { + "TORCH_NCCL_ABORT_IN_DESTROY_PG"}; + +constexpr const char* NCCL_BACKEND_NAME = "nccl"; + +constexpr const char* TIMEOUT_DUMP = "timeout_dump"; + +constexpr const int kWorkStatusUpdatePeriodMs = 10 * 1000; // 10 seconds + +constexpr auto kProcessGroupNCCLDefaultTimeout = + std::chrono::milliseconds(10 * 60 * 1000); + +// NoHandling: do not handle asynchronous NCCL errors +// TearDown: tear down process upon error, see `WorkNCCL::handleException` +// CleanUpOnly: just clean up collectives and abort communicators without +// tearing down process SkipCleanUp: (this is a temporary option and can be +// removed in future) tear down process without cleaning up NCCL communicators. +// This should be used as a last resort in case `ncclCommAbort` itself is +// hanging +enum ErrorHandlingMode { + NoHandling = 0, + TearDown = 1, + CleanUpOnly = 2, + SkipCleanUp = 3 +}; + +#define SHOULD_CLEAN_UP(a) (a != NoHandling && a != SkipCleanUp) + +#define SHOULD_TEAR_DOWN(a) (a != NoHandling && a != CleanUpOnly) + +#define PRINT_COLLECTIVE_HASH_SIGNATURE(phase, opType, numel, hashValue) \ + LOG(WARNING) << logPrefix() << "Hash of " << phase << " to NCCL " << opType \ + << " with size " << numel << " is " << hashValue; + +// If set, ProcessGroupNCCL doesn't use recordStream calls to ensure +// caching allocator safety for tensors used on both user-facing and +// internal comm streams. +// Instead, it stashes live references to those tensors until after +// user-facing streams are synced with comm streams. +// See stashed_for_allocator_safety_ below. +static std::vector TORCH_NCCL_AVOID_RECORD_STREAMS = { + "TORCH_NCCL_AVOID_RECORD_STREAMS"}; + +// If set, ProcessGroupNCCL registers postAlloc and preFree hooks to cuda cache +// allocator so that whenever a tensor is allocated or freed, ProcessGroupNCCL +// can register/deregister the tensor on all available NCCL communicators. +static std::vector TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK = + {"TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK", + "NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK"}; + +#if defined(__linux__) +struct DumpPipe { + DumpPipe(int rank) { + std::string fileStem = + getCvarString({"TORCH_NCCL_DEBUG_INFO_PIPE_FILE"}, ""); + if (fileStem.empty() || + getCvarInt({"TORCH_NCCL_TRACE_BUFFER_SIZE"}, 0) <= 0) { + return; + } + TORCH_CHECK(!fileStem.empty(), "TORCH_NCCL_DEBUG_INFO_TEMP_FILE is empty"); + std::string filename = c10::str(fileStem, rank, ".pipe"); + TORCH_CHECK( + unlink(filename.c_str()) != -1 || errno == ENOENT, + "Error removing existing named pipe ", + filename); + TORCH_CHECK( + mkfifo(filename.c_str(), 0666) != -1, + "Error creating named pipe ", + filename); + fd_ = open(filename.c_str(), O_RDONLY | O_NONBLOCK); + LOG(INFO) << "Pipe file " << filename + << " has been opened, write to it to trigger NCCL Debug Dump."; + TORCH_CHECK(fd_ != -1, "Error opening named pipe ", filename); + } + bool shouldDump() { + if (fd_ == -1) { + return false; + } + char buf[128]; + // non-blocking from O_NONBLOCK above. + // Ignore EINTR because we already will poll this + // again later. + ssize_t bytesRead = read(fd_, &buf, 128); + return bytesRead > 0; + } + ~DumpPipe() { + if (fd_ != -1) { + close(fd_); + } + } + + private: + int fd_ = -1; +}; +#else +struct DumpPipe { + DumpPipe(int rank) {} + bool shouldDump() { + return false; + } +}; +#endif + +// ProcessGroupNCCL implements NCCL bindings for c10d. +// +// All functions of the class are expected to be called in the same order +// across all processes in the process group. This is the only way that we +// can guarantee to match up the same calls among all processes. +// +// All NCCL functions provided by this class are asynchronous functions. More +// specifically, each NCCL call is scheduled on a separate CUDA stream that is +// different from the current CUDA stream. This is for the purpose of +// achieving potentially concurrency and better performance. As a result, +// it is the callers' responsibility to make sure that the CUDA stream their +// code works on needs to wait for the NCCL operation from +// this class. +// +// This can be done by calling: +// +// either WorkNCCL::wait() or WorkNCCL::synchronize(), both achieves the same +// functionality and are synonyms. +// +// Also note that WorkNCCL::finishedGPUExecution() is a helper function only +// provided by ProcessGroupNCCL to check if the NCCL operation of WorkNCCL has +// finished execution on the GPU (not just scheduled). +// +// Example on using the NCCL process group +// +// ProcessGroupNCCL pg(store, rank, size); +// std::shared_ptr work = pg.allreduce(tensors); +// +// // At this point, NCCL kernel has already by queued successfully +// // Now, let current stream wait for the NCCL to finish, this function is +// // async operation as well +// +// work->wait() +// +// // Now continue on other work in the current stream. +class TORCH_API ProcessGroupNCCL : public Backend { + public: + class WorkNCCL : public Work, public std::enable_shared_from_this { + public: + friend struct WorkInfo; + + // Constructor takes a list of CUDA devices + WorkNCCL( + at::Device& device, + int rank, + OpType opType, + uint64_t seq, + const char* profilingTitle = nullptr, + const c10::optional>& inputs = c10::nullopt, + bool desyncDebug = false, + bool enableTiming = false, + DebugLevel distDebugLevel = DebugLevel::Off); + // Copy constructor doing partial copy without outputs_. Cleanup thread + // monitors and removes finished works. However it will deadlock when + // destructs outputs_ tensors who are view tensors in autograd graph. + WorkNCCL(const WorkNCCL& w); + + ~WorkNCCL() override; + + // Checks if the NCCL kernel has started to execute. + bool isStarted(); + + // Checks if request has completed. In this specific case of NCCL, it checks + // if the NCCL operation has completed on the GPU in its own NCCL stream. + // Non-blocking operation. + bool isCompleted() override; + + bool isSuccess() const override; + + // Same as calling synchronize() for NCCL work. + bool wait(std::chrono::milliseconds timeout = kNoTimeout) override; + + void abort() override; + + // Let current stream wait on the completing of the NCCL work + // Throws on exceptions. Blocking operation, which will wait for work + // completion. + void synchronize() override; + + // Synchronize streams by blocking each on the NCCL stream + void synchronizeStream(); + + // Helper function to handle exception (throw if needed). + void handleException(ErrorHandlingMode asyncErrorHandling); + + // Helper function that checks if the NCCL kernels have finished + // execution on the GPUs + bool finishedGPUExecution(); + + // Get a Future object that will be marked as completed internally. + c10::intrusive_ptr getFuture() override; + + float getDuration() const override; + + uint64_t getSequencenumber() const override; + + const std::string& logPrefix() const; + + // Helper function that sets an exception_ptr on the WorkNCCL object. + void setException(std::exception_ptr exception_ptr); + + // Helper function that returns True if the WorkNCCL object has timed out + // and False otherwise. + // In case of timeout, set exception on the WorkNCCL object. + bool checkTimeout( + c10::optional timeout = c10::nullopt); + + std::vector result() override; + + protected: + // The cached list of CUDA devices to operate on + at::Device device_; + + // The start CUDA event of NCCL operator tracking this work item. These + // start CUDA events are needed by desync debugging if enabled. + std::shared_ptr ncclStartEvent_; + + // The end CUDA event of NCCL operator tracking this work item. + std::shared_ptr ncclEndEvent_; + + // The NCCL communicator used for this work item. + std::shared_ptr ncclComm_; + + // Tensors used for barrier op + at::Tensor barrierTensor_; + + // Clone of blockingWait_ from ProcessGroupNCCL. + bool blockingWait_ = false; + + // Clone of avoidRecordStreams_ from ProcessGroupNCCL. + bool avoidRecordStreams_ = false; + + // Clone of opTimeout_ from ProcessGroupNCCL. + std::chrono::milliseconds opTimeout_; + + // Time point representing when the work started. + std::chrono::time_point workStartTime_; + + // Record the collective sequential number. + uint64_t seq_; + + // Indicates if the nccl start event has been updated to the store trace. + // This will be used by desync debug. + bool startTraceUpdated_{false}; + + // Record collective sizes for debug. We only record the size on the first + // device as multi-device per process is deprecated + size_t numelIn_ = -1; + size_t numelOut_ = -1; + + // Wrapper method for the static checkForNCCLErrors which can be overridden + // for tests. + virtual std::exception_ptr checkForNCCLErrors(); + + friend std::ostream& operator<<( + std::ostream& output, + const WorkNCCL& workNCCL); + + private: + // Helper function for synchronize + void synchronizeInternal(std::chrono::milliseconds timeout); + + // Checks for NCCL errors and sets an appropriate exception_ptr. + void checkAndSetException(); + + // Just checks whether GPU execution has started, without modifying + // exception_ptr. + bool startedGPUExecutionInternal() const; + + // Just checks whether GPU execution has completed, without modifying + // exception_ptr. + bool finishedGPUExecutionInternal() const; + + // Reference to the store so that we can write aborted communicators + // to the store. + c10::intrusive_ptr store_; + + // Store a reference to NCCL collective's outputs, used by result and to + // give a more descriptive message when representing the Work as a string. + std::shared_ptr> outputs_; + + // TORCH_NCCL_AVOID_RECORD_STREAMS implementation helper. + // Stores references to participating non-output tensors (ie inputs, + // flattened intermediates). + // We'll clear this list in synchronizeStream, just after user-facing + // stream(s) are synced with the nccl work stream(s). + // By keeping these refs (as well as outputs_) alive until after the + // collective's work rejoins the user-facing streams, we achieve + // caching allocator safety without any recordStream calls. + // For in-place collectives, some refs stashed here may alias outputs_, + // but that doesn't do any harm. + std::shared_ptr> stashed_for_allocator_safety_; + + // The future returned by getFuture. + c10::intrusive_ptr future_; + + bool timingEnabled_; + // unique id used to tell the trace buffer that this + // work has completed + c10::optional trace_id_; + DebugLevel distDebugLevel_; + friend class ProcessGroupNCCL; + }; + + struct Options : Backend::Options { + // NOTE: timeout in ProcessGroupNCCL::Options denote the timeout for + // operations. This is only used when blockingWait_ is enabled. + explicit Options(bool is_high_priority_stream = false); + + // return intrusive_ptr of the object + static c10::intrusive_ptr create( + bool is_high_priority_stream = false) { + return c10::make_intrusive(is_high_priority_stream); + } + + // Schedule NCCL operations on high priority CUDA streams + bool is_high_priority_stream; + +#ifdef NCCL_HAS_COMM_NONBLOCKING + // Configure ranks + ncclConfig_t config = NCCL_CONFIG_INITIALIZER; +#endif + + // Optional "parent" backend and color to create communicators from + // via `ncclCommSplit` + std::shared_ptr split_from; + int64_t split_color{0}; + std::vector global_ranks_in_group; + }; + + // If you wish to create multiple process groups, each with a potentially + // different rank and size, you can do so by passing a new store instance + // to each one. If you have only a single store object, you can + // use the `c10d::PrefixStore` to derive scoped instances. + // This is also what the Python API in torch.distributed does. + // + // The process group instance keeps a reference to the store because + // it may be used long after the constructor runs. In fact, the constructor + // doesn't create any NCCL communicators. A single NCCL communicator can + // only be used on a specific set of devices, and are therefore created + // on-demand when a collective runs. If another collective is executed later, + // against a different set of devices, the process group creates another NCCL + // communicator. These NCCL communicators are cached and reused if possible. + // + ProcessGroupNCCL( + const c10::intrusive_ptr& store, + int rank, + int size, + c10::intrusive_ptr options = Options::create()); + + // This constructor includes the deprecated `groupName` argument. + // If you have existing code that uses the `groupName`, you can replace + // it by specifying a `c10d::PrefixStore(groupName, store)` for store. + C10_DEPRECATED ProcessGroupNCCL( + const c10::intrusive_ptr& store, + int rank, + int size, + const std::string& groupName, + c10::intrusive_ptr options = Options::create()) + : ProcessGroupNCCL(store, rank, size, options) {} + + ~ProcessGroupNCCL() override; + + uint64_t getUid() { + return static_cast(uid_); + } + + c10::intrusive_ptr getOptions() { + return options_; + } + + const std::string getBackendName() const override { + return std::string(NCCL_BACKEND_NAME); + } + + bool supportsSplitting() const override { + return true; + } + + void startCoalescing() override; + + c10::intrusive_ptr endCoalescing() override; + + // For specifying a composite optype, such as ALLGATHER and REDUCE_SCATTER + c10::intrusive_ptr endCoalescing(OpType optype); + + c10::intrusive_ptr broadcast( + std::vector& tensors, + const BroadcastOptions& opts = BroadcastOptions()) override; + + c10::intrusive_ptr _broadcast_oop( + at::Tensor& outputTensors, + at::Tensor& inputTensors, + const BroadcastOptions& opts = BroadcastOptions()); + + c10::intrusive_ptr allreduce_sparse( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector& tensors, + const AllreduceOptions& opts = AllreduceOptions()) override; + + c10::intrusive_ptr allreduce_coalesced( + std::vector& tensors, + const AllreduceCoalescedOptions& opts = + AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr reduce( + std::vector& tensors, + const ReduceOptions& opts = ReduceOptions()) override; + + c10::intrusive_ptr _reduce_oop( + at::Tensor& outputTensors, + at::Tensor& inputTensors, + const ReduceOptions& opts = ReduceOptions()); + + c10::intrusive_ptr allgather( + std::vector>& outputTensors, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor& outputbuffer, + at::Tensor& inputbuffer, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_coalesced( + std::vector>& outputTensorLists, + std::vector& inputTensors, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr allgather_into_tensor_coalesced( + std::vector& outputs, + std::vector& inputs, + const AllgatherOptions& opts = AllgatherOptions()) override; + + c10::intrusive_ptr reduce_scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr _reduce_scatter_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr reduce_scatter_tensor_coalesced( + std::vector& outputs, + std::vector& inputs, + const ReduceScatterOptions& opts = ReduceScatterOptions()) override; + + c10::intrusive_ptr barrier( + const BarrierOptions& opts = BarrierOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor& outputTensor, + at::Tensor& inputTensor, + std::vector& outputSplitSizes, + std::vector& inputSplitSizes, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector& outputTensors, + std::vector& inputTensors, + const AllToAllOptions& opts = AllToAllOptions()) override; + + c10::intrusive_ptr send( + std::vector& tensors, + int dstRank, + int tag) override; + + c10::intrusive_ptr recv( + std::vector& tensors, + int srcRank, + int tag) override; + + void groupStart(); + + void groupEnd(); + + void groupEndNonblocking(std::shared_ptr comm); + + c10::intrusive_ptr gather( + std::vector>& outputTensors, + std::vector& inputTensors, + const GatherOptions& opts = GatherOptions()) override; + + c10::intrusive_ptr scatter( + std::vector& outputTensors, + std::vector>& inputTensors, + const ScatterOptions& opts = ScatterOptions()) override; + + // Unsupported Ops + c10::intrusive_ptr recvAnysource( + std::vector& tensors, + int tag) override; + + // Agrees on an initial sequence number for the whole group by having rank 0 + // create it and broadcast it to other ranks using the store. + void setSequenceNumberForGroup() override; + + // Retrieves the current sequence number for the whole group, which should be + // in sync. If the returned number is not consistent across the group, it + // may indicate that there is some sort of collective desynchronization. + uint64_t getSequenceNumberForGroup() override; + + // Return the total number of splits the communicators held by this process + // group have performed. + uint64_t getCommSplitCounter() const; + + void registerOnCompletionHook( + std::function)>&& hook) override; + void waitForPendingWorks() override; + + void enableCollectivesTiming() override; + + // Helper function for iteratively aborting communicators in the provided map + void abortCommsFromMap( + std::unordered_map>& ncclCommsMap, + c10::optional abortReason); + + c10::intrusive_ptr initIntraNodeComm(); + + // Provides an API to abort the ProcessGroup (similar to ncclCommAbort) + // instead of relying on ProcessGroupNCCL destructor. + // return true if abort is successful, otherwise false + bool abort(c10::optional abortReason = c10::nullopt); + + void shutdown(c10::optional reason = c10::nullopt); + + void eagerConnectSingleDevice(at::Device device) override; + + void performNocolorSplit(at::Device device); + + protected: + // Helper that broadcasts nccl unique ID to all ranks through the store + void broadcastUniqueNCCLID( + ncclUniqueId* ncclID, + bool isSingleP2POp, + const std::string& devicesKey, + int p2pRank); + + // Helper that either looks up the cached NCCL communicators or creates + // a new set of NCCL communicators as a cache entry + std::shared_ptr getNCCLComm( + const std::string& deviceKey, + at::Device& device, + OpType opType, + int p2pRank = 0, + bool isSendRecvSelf = false); + + // Wrapper method which can be overridden for tests. + virtual std::exception_ptr checkForNCCLErrors( + std::shared_ptr& ncclComm); + + // Ensure thaht if record is True, the work obj will be enqueued via + // workEnqueue + virtual c10::intrusive_ptr initWork( + at::Device& device, + int rank, + OpType opType, + const char* profilingTitle = nullptr, + const std::vector& inputs = {}, + const std::vector& outputs = {}, + bool record = false); + + // In the timeout case and we will dump debug info such as the NCCL flight + // recorder to storage. Down the road, if we have more complicated or blocking + // operations, we might need to use a side thread to do it. + bool dumpDebuggingInfo(); + + private: + int globalRankStart; + int globalRankStride; + + // Helper that encapsulates work shared across all collective communication + // primitives. The callbacks have the following signatures: + // + // ncclResult_t fn(at::Tensor& input, at::Tensor& output, + // ncclComm_t, at::cuda::CUDAStream&); + // void {pre,post}(std::vector); + template + c10::intrusive_ptr collective( + at::Tensor& input, + at::Tensor& output, + Fn fn, + OpType opType, + const char* profilingTitle = nullptr, + bool avoidRecordStreams = false); + + template + c10::intrusive_ptr collective( + at::Tensor& input, + at::Tensor& output, + Fn fn, + PreProcess pre, + PostProcess post, + OpType opType, + const char* profilingTitle = nullptr, + bool avoidRecordStreams = false); + + template + c10::intrusive_ptr collectiveCoalesced( + std::vector& input, + std::vector& output, + Fn fn, + OpType opType, + const char* profilingTitle = nullptr, + bool avoidRecordStreams = false); + + // Helper that encapsulates work shared across point-to-point communication + // primitives. It is the same structure as the helper used for collective + // communication primitives. + template + c10::intrusive_ptr pointToPoint( + at::Tensor& tensor, + Fn fn, + int peer, + OpType opType, + const char* profilingTitle = nullptr); + + template + c10::intrusive_ptr pointToPoint( + at::Tensor& tensor, + Fn fn, + int peer, + OpType opType, + PreProcess pre, + PostProcess post, + const char* profilingTitle); + + c10::intrusive_ptr allreduce_impl( + at::Tensor& tensor, + const AllreduceOptions& opts = AllreduceOptions()); + + // Checks for NCCL errors on each of the communicators and returns an + // appropriate exception_ptr (nullptr if no errors). + static std::exception_ptr checkForNCCLErrorsInternal( + std::shared_ptr& ncclComm); + + // Function that runs as part of a separate thread and checks for errors on + // NCCL communicators. We need a separate thread to check for NCCL errors + // since we can't rely on the user calling certain methods like wait(), + // isCompleted() etc. to detect and remediate errors. In addition to this, we + // need a mechanism to safely abort and remove NCCL communicators from our + // cache. This can be done cleanly by having a thread for the ProcessGroupNCCL + // class. Attempting to modify the communicator cache from the WorkNCCL class + // might run into issues with object lifetime since the ProcessGroupNCCL + // object might get destroyed before the WorkNCCL object. + void ncclCommWatchdog(); + + // Return the CUDA device most likely associated with this backend. + // If we aren't bound to a specific device, there is no strict + // guarantee that this heuristic is the correct assignment of ranks + // to GPUs that Python layers use, but in practice it tends to be. + // Fortunately we don't rely on this for correctness of any tensor + // operations, just for ancillary uses like barriers. + at::Device guessDeviceForRank() const; + + // Destroys initialized NCCL communicators in devNCCLComMap_ given by input + // key. Throws if there are no communicators to destroy. Also removes + // communicators from the cache and clears used device indices. + void destroyNCCLComms(const std::string& devNCCLCommMapKey); + + // Watchdog's inside loop. + // Takes care of cleaning up completed work, and aborting upon failure or + // timeout. + void watchdogHandler(); + + void runHookLoop(); + + // Desync debug helper + void logWorkStart(WorkNCCL& work); + + // Desync debug helper + void logWorkEnd(WorkNCCL& work); + + // Generates a prefix that is unique to this process group and rank, for + // disambiguating logs + std::string createLogPrefix() const; + + // Returns the unique prefix created in createLogPrefix + const std::string& logPrefix() const; + + // Returns the global rank of the device. This function assumes that users + // always create a default global process group(PG) which includes all + // devices. It is called in the constructor of ProcessGroupNCCL, so it always + // return the rank_ of the the very first PG created, aka, default global PG. + const int& globalRank() const; + + // Returns the global ranks of a PG. + const std::vector& groupRanks() const; + + protected: + // Function that runs as part of a separate thread aside from watchdog + // thread because we need to check the heartbeat from watchdog thread + // so that when we get stuck in some NCCL/CUDA calls, + // we can dump the debugging information and abort the process. + virtual void heartbeatMonitor(); + + // Function that directly trigger std::abort so that the whole process + // gets terminated. + virtual void terminateProcess(std::string errMsg); + + // A helper function to wait for a future to complete or timeout. + void waitForFutureOrTimeout( + std::future& fut, + const std::chrono::milliseconds& timeOutMilSec, + const std::string& futDescription, + bool throwException = false); + + // When watchdog timeout, this function will be called and return debug info + // for users. For now we only get information from retrieveDesyncReport. + // We are working on enabling more useful debug information for watchdog + // timeout. + virtual std::string getNCCLWatchdogDebugInfo(); + + static const int64_t kWatchdogThreadSleepMillis; + + // The store is used to broadcast the NCCL unique ID of rank 0. This store + // comes with prefix and it is different across ProcessGroup NCCL instances + // (aka, different ProcessGroups). + c10::intrusive_ptr store_; + + // Reference to the store without prefix so that keys are same across all + // ProcessGroup NCCL instances and (key, value) pairs written to the store are + // global. + c10::intrusive_ptr globalStore_; + + bool storeError_{false}; + + const c10::intrusive_ptr options_; + + // The number of NCCL communicators that have been created during + // the lifetime of this process group. This sequence number is + // used to scope keys used in the store. + uint64_t ncclCommCounter_{0}; + + // The store keys to trace the last NCCL collective kernel CUDA events - start + // event and end event respectively. These are used to do desync root cause + // analysis. + const std::string traceKeyStart_; + const std::string traceKeyEnd_; + + // The NCCL communicator that the process group has cached. + // + // For collective operations: + // The key is a list of GPU devices that an operation is operating on + // The GPU devices are stored in a device sequence and the cache NCCL + // communicator is associated with this GPU device sequence + // + // e.g. If the process group op only uses device 0, then the value of + // the used device string stored (value of the hashmap) would be "0". + // + // If the process group op uses device 0 - 7 and the each tensor of the + // input tensor list is on device, 0, 1, 2, 3, 4, 5, 6, 7 separately, + // then the value of the used device string (key) stored would be + // "0,1,2,3,4,5,6,7" + // + // If the process group op uses device 0 - 7 and the each tensor of the + // input tensor list is on device, 0, 4, 5, 6, 7, 1, 2, 3 separately, + // then the value of the used device string stored would be + // "0,4,5,6,7,1,2,3" + // + // Note that the order of the device for the tensor list matters. + // + // For point-to-point operations: + // The key is a string of my current rank and the peer process rank. + // e.g. If process 1 and process 2 are involved in a point-to-point + // communication, the key will be "1:2" on both processes. Note: this is for + // the scenario where there is only 1 GPU per process. When it comes to + // multiple GPUs per process, this part may need to redesigned. + std::unordered_map> devNCCLCommMap_; + + // The NCCL communicators currently in process of being initialized. + std::unordered_map> + inInitializationCommMap_; + + // Map from ncclUniqueId to appropriate communicator. + std::unordered_map> ncclIdToCommMap_; + + // Mutex to guard maps like devNCCLCommMap_ and ncclIdToCommMap_. + std::mutex mutex_; + + // Heartbeat of watchdog thread. + std::atomic_uint64_t heartbeat_; + + // The time interval used for deciding whether there is no watchdog heartbeat. + int heartbeatTimeoutInSec_; + + // timeout for the dump to finish. + int waitTimeoutDumpInMilSec_; + + // Interval of check coordinated signals in ProcessGroupNCCL from other ranks + // e.g., trigger the dump of the debugging info for timeout when notified. + int coordCheckIntervalMilSec_; + + // Size of ring buffer where we store NCCL Traces for debugging. + int ncclTraceBufferSize_; + + // We gate the heartbeat monitor thread so that we can roll it out gradually. + std::atomic monitorThreadEnabled_; + + // Monitor thread which checks the heartbeat of Watchdog thread. + // If the monitor thread finds there is no heartbeat, it will dump debug info + // and then kill the watchdog thread to avoid hang. + std::thread ncclHeartbeatMonitorThread_; + + // Watchdog thread which looks for errors on the cached NCCL communicators. + std::thread ncclCommWatchdogThread_; + + std::thread onCompletionHookThread_; + + // Whether or not we should terminate the watchdog and workCleanup threads. + std::atomic terminateProcessGroup_; + + // Whether or not we should terminate the heartbeat monitoring threads. + std::atomic terminateHeartbeatMonitorThread_; + + // Whether we are in the shutdown mode when we are trying to get debug info, + // such as desync report. + std::atomic collectiveDebugInfoMode_; + + // Whether there are hooks pending to be fired + std::atomic hasPendingHooks_; + + // This is the signal from watchdog threads to indicate whether the monitor + // thread should dump. Making it static so that it is accessiable from all the + // PGs. With this flag, monitor thread would dump debug info under any one of + // the 3 conditions: 1: this flag is set to true by the watchdog thread when + // it detects a timeout. 2: timeout signal is received from + // other ranks through tcpstore 3: no heartbeat of watchdog Note that only the + // monitor thread from PG0 should dump the debug info and only once + static std::atomic shouldDump_; + + // Mutex to Guard workMetaList_ + std::mutex workMetaListMutex_; + + // Mutex to Guard monitorWakeUpCV_ + std::mutex monitorMutex_; + + bool writeDebugInfo_ = false; + + // Condition Variable for watchdog thread sleep + std::condition_variable workMetaListCV_; + + // Condition Variable for monitor thread to wake up early + std::condition_variable monitorWakeUpCV_; + + // Vector to Store WorkNCCL pointers + std::list workMetaList_; + + std::chrono::time_point lastWorkListUpdateTime_; + + // Mutex to Guard workMetaList_ + std::mutex completedWorkListMutex_; + + // Condition Variable for watchdog thread sleep + std::condition_variable completedWorkListCV_; + + std::list completedWorkList_; + + // Add Work Pointer to workVector + void workEnqueue(c10::intrusive_ptr); + + // The CUDA streams used by NCCL kernels + std::unordered_map ncclStreams_; + + // The CUDA events used to sync NCCL streams + std::unordered_map ncclEvents_; + + // Device Indexes used for all collectives in this group + std::set usedDeviceIdxs_; + + // Flag to denote if a coalescing groupStart/groupEnd block is active + int coalescing_state_ = 0; + + // Stores device indexes for all collectives run inside a coalescing block + std::vector coalescedDevices_; + + // Stores communicators for all collectives run inside a coalescing block + std::vector> coalescedComms_; + + // map from the key: "group name + pg counter (ID)" to the + // unique NCCL ID count. This needs to be group and pg specific + // + // For each process group, we need a uniform unique NCCL ID counter to ensure + // that NCCL operation in this process group can be completed successfully. + // Since each process group ID belongs to a group name, the key to this map + // is a combination of group name and ProcessGroupNCCL ID. + static std::unordered_map pgUniqueNCCLIDCnt_; + + // map from group name to the pg counter (ID) within that group + // + // For each group with the "group name" (which is the key), we need to + // keep track of a unique process group ID when creating a new + // ProcessGroupNCCL for this "group name". Therefore, the value of this + // map keeps the unique ProcessGroupNCCL's ID for a specific group with + // the "group name". The reason we need a per-group process group ID counter + // is that different group can have different ranks and we need ensure that + // each group has its own uniform process group ID for all its ranks. + static std::unordered_map processGroupCounterMap_; + + // Whether or not wait() and synchronize() are blocking operations that wait + // for the operation to complete. + bool blockingWait_ = false; + + // Whether to abort the communicators when users call destroy_process_group(). + // If yes, communicators will be aborted when destroy_process_group is called, + // but not in destructor. + bool abortInDestroyProcessGroup_ = false; + + // Whether or not to hook the cache allocator to register all allocated + // tensors + bool useTensorRegisterAllocatorHook_ = false; + + // Whether or not the workCleanupThread is used to perform async error + // handling. + ErrorHandlingMode asyncErrorHandling_ = NoHandling; + + // Whether or not to enable timeout root cause analysis. + bool desyncDebug_; + + // Whether or not to dump debug info on timeout + bool dumpOnTimeout_; + + // Whether or not to create start CUDAEvent and enable timing for start + // and end events. Note that enableTiming_ is always true if desyncDebug_ + // is set to true. + std::atomic enableTiming_; + + // Flag to enable the print of hash value of input/output of collectives for + // verification. + std::atomic enableCollecticeHashDebug_; + + // Whether or not TORCH_NCCL_AVOID_RECORD_STREAMS was set + bool avoidRecordStreams_ = false; + + // Set of communicators that this process group has aborted and their + // ncclUniqueId has been written to the store. We don't need a lock + // for this map since only the watchdog thread accesses this set. The + // set contains the string representation of ncclUniqueId. + std::unordered_set abortedComms_; + + // The number of active ncclGroupStart() calls. This counter will be increased + // by 1 when ncclGroupStart() is called and decreased by 1 when ncclGroupEnd() + // is called. + static thread_local uint64_t ncclActiveGroupCounter_; + + // Counting for the sequential number of NCCL collective call. + // (specifically, how many actual kernels we launched, which differs from + // op_id_ when coalescing is enabled) + uint64_t seq_{0}; + + // Incrementing counter for logical operations (collective or p2p) issued on + // the ProcessGroup + uint64_t op_id_{0}; + + // the sequential number of the last colletive enqueued into workMetaList_ + // This is useful for indentifying a rank that has not join a collective + uint64_t lastEnqueuedSeq_; + + // the sequential number of the last colletive completed marked by + // the watchdog thread + uint64_t lastCompletedSeq_; + + std::exception_ptr watchDogException_ = nullptr; + + size_t uid_; + + std::string logPrefix_; + + c10::intrusive_ptr intraNodeComm_; +}; + +TORCH_API std::string dump_nccl_trace(); + +// Gets a mutable reference to a global optional function. Heartbeat Monitor +// will query this function and if available, call it to dump traces. Inside +// fbcode, we store a function here that uses an internal tool for process +// tracing +TORCH_API c10::optional>& get_cpp_trace_dumper(); + +// Similar to get_cpp_trace_dumper, this stores a function defined in +// torch-python layer that lets us check whether the GIL can be acquired, +// helpful for instrumenting in cases where a hang was observed. +typedef bool (*gil_checker_t)(); + +TORCH_API gil_checker_t& get_gil_checker(); +} // namespace c10d + +#endif // USE_C10D_NCCL diff --git a/shared/package-files/7c/7c032686ee5e27ecc027eb267ea430442950dfe9e8cce0a6bc9ebe13c960189a/blob b/shared/package-files/7c/7c032686ee5e27ecc027eb267ea430442950dfe9e8cce0a6bc9ebe13c960189a/blob new file mode 100644 index 0000000000000000000000000000000000000000..a884269e7fc0d5f0cd96ba63c8d473c6560264b6 --- /dev/null +++ b/shared/package-files/7c/7c032686ee5e27ecc027eb267ea430442950dfe9e8cce0a6bc9ebe13c960189a/blob @@ -0,0 +1,3 @@ +[console_scripts] +chardetect = chardet.cli.chardetect:main + diff --git a/shared/package-files/7c/7c03274b750f4a417059397a0c88ddeacf41ac5d3bc488cb49d5019e0afa5caa/blob b/shared/package-files/7c/7c03274b750f4a417059397a0c88ddeacf41ac5d3bc488cb49d5019e0afa5caa/blob new file mode 100644 index 0000000000000000000000000000000000000000..b8f0d0f5294ad1e182499c0729e6b7371fff6a5e Binary files /dev/null and b/shared/package-files/7c/7c03274b750f4a417059397a0c88ddeacf41ac5d3bc488cb49d5019e0afa5caa/blob differ diff --git a/shared/package-files/7c/7c03ddb098804456e43c08a1e8d918af2d1da63e233ea7a5195325138c16156f/blob b/shared/package-files/7c/7c03ddb098804456e43c08a1e8d918af2d1da63e233ea7a5195325138c16156f/blob new file mode 100644 index 0000000000000000000000000000000000000000..ec0b3a4fe6055b276d5515a4e81d60d921c6f381 --- /dev/null +++ b/shared/package-files/7c/7c03ddb098804456e43c08a1e8d918af2d1da63e233ea7a5195325138c16156f/blob @@ -0,0 +1,361 @@ +# unicode.py + +import sys +from itertools import filterfalse +from typing import List, Tuple, Union + + +class _lazyclassproperty: + def __init__(self, fn): + self.fn = fn + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + + def __get__(self, obj, cls): + if cls is None: + cls = type(obj) + if not hasattr(cls, "_intern") or any( + cls._intern is getattr(superclass, "_intern", []) + for superclass in cls.__mro__[1:] + ): + cls._intern = {} + attrname = self.fn.__name__ + if attrname not in cls._intern: + cls._intern[attrname] = self.fn(cls) + return cls._intern[attrname] + + +UnicodeRangeList = List[Union[Tuple[int, int], Tuple[int]]] + + +class unicode_set: + """ + A set of Unicode characters, for language-specific strings for + ``alphas``, ``nums``, ``alphanums``, and ``printables``. + A unicode_set is defined by a list of ranges in the Unicode character + set, in a class attribute ``_ranges``. Ranges can be specified using + 2-tuples or a 1-tuple, such as:: + + _ranges = [ + (0x0020, 0x007e), + (0x00a0, 0x00ff), + (0x0100,), + ] + + Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x). + + A unicode set can also be defined using multiple inheritance of other unicode sets:: + + class CJK(Chinese, Japanese, Korean): + pass + """ + + _ranges: UnicodeRangeList = [] + + @_lazyclassproperty + def _chars_for_ranges(cls): + ret = [] + for cc in cls.__mro__: + if cc is unicode_set: + break + for rr in getattr(cc, "_ranges", ()): + ret.extend(range(rr[0], rr[-1] + 1)) + return [chr(c) for c in sorted(set(ret))] + + @_lazyclassproperty + def printables(cls): + """all non-whitespace characters in this range""" + return "".join(filterfalse(str.isspace, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphas(cls): + """all alphabetic characters in this range""" + return "".join(filter(str.isalpha, cls._chars_for_ranges)) + + @_lazyclassproperty + def nums(cls): + """all numeric digit characters in this range""" + return "".join(filter(str.isdigit, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphanums(cls): + """all alphanumeric characters in this range""" + return cls.alphas + cls.nums + + @_lazyclassproperty + def identchars(cls): + """all characters in this range that are valid identifier characters, plus underscore '_'""" + return "".join( + sorted( + set( + "".join(filter(str.isidentifier, cls._chars_for_ranges)) + + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº" + + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ" + + "_" + ) + ) + ) + + @_lazyclassproperty + def identbodychars(cls): + """ + all characters in this range that are valid identifier body characters, + plus the digits 0-9, and · (Unicode MIDDLE DOT) + """ + return "".join( + sorted( + set( + cls.identchars + + "0123456789·" + + "".join( + [c for c in cls._chars_for_ranges if ("_" + c).isidentifier()] + ) + ) + ) + ) + + @_lazyclassproperty + def identifier(cls): + """ + a pyparsing Word expression for an identifier using this range's definitions for + identchars and identbodychars + """ + from pip._vendor.pyparsing import Word + + return Word(cls.identchars, cls.identbodychars) + + +class pyparsing_unicode(unicode_set): + """ + A namespace class for defining common language unicode_sets. + """ + + # fmt: off + + # define ranges in language character sets + _ranges: UnicodeRangeList = [ + (0x0020, sys.maxunicode), + ] + + class BasicMultilingualPlane(unicode_set): + """Unicode set for the Basic Multilingual Plane""" + _ranges: UnicodeRangeList = [ + (0x0020, 0xFFFF), + ] + + class Latin1(unicode_set): + """Unicode set for Latin-1 Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0020, 0x007E), + (0x00A0, 0x00FF), + ] + + class LatinA(unicode_set): + """Unicode set for Latin-A Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0100, 0x017F), + ] + + class LatinB(unicode_set): + """Unicode set for Latin-B Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0180, 0x024F), + ] + + class Greek(unicode_set): + """Unicode set for Greek Unicode Character Ranges""" + _ranges: UnicodeRangeList = [ + (0x0342, 0x0345), + (0x0370, 0x0377), + (0x037A, 0x037F), + (0x0384, 0x038A), + (0x038C,), + (0x038E, 0x03A1), + (0x03A3, 0x03E1), + (0x03F0, 0x03FF), + (0x1D26, 0x1D2A), + (0x1D5E,), + (0x1D60,), + (0x1D66, 0x1D6A), + (0x1F00, 0x1F15), + (0x1F18, 0x1F1D), + (0x1F20, 0x1F45), + (0x1F48, 0x1F4D), + (0x1F50, 0x1F57), + (0x1F59,), + (0x1F5B,), + (0x1F5D,), + (0x1F5F, 0x1F7D), + (0x1F80, 0x1FB4), + (0x1FB6, 0x1FC4), + (0x1FC6, 0x1FD3), + (0x1FD6, 0x1FDB), + (0x1FDD, 0x1FEF), + (0x1FF2, 0x1FF4), + (0x1FF6, 0x1FFE), + (0x2129,), + (0x2719, 0x271A), + (0xAB65,), + (0x10140, 0x1018D), + (0x101A0,), + (0x1D200, 0x1D245), + (0x1F7A1, 0x1F7A7), + ] + + class Cyrillic(unicode_set): + """Unicode set for Cyrillic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0400, 0x052F), + (0x1C80, 0x1C88), + (0x1D2B,), + (0x1D78,), + (0x2DE0, 0x2DFF), + (0xA640, 0xA672), + (0xA674, 0xA69F), + (0xFE2E, 0xFE2F), + ] + + class Chinese(unicode_set): + """Unicode set for Chinese Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x2E80, 0x2E99), + (0x2E9B, 0x2EF3), + (0x31C0, 0x31E3), + (0x3400, 0x4DB5), + (0x4E00, 0x9FEF), + (0xA700, 0xA707), + (0xF900, 0xFA6D), + (0xFA70, 0xFAD9), + (0x16FE2, 0x16FE3), + (0x1F210, 0x1F212), + (0x1F214, 0x1F23B), + (0x1F240, 0x1F248), + (0x20000, 0x2A6D6), + (0x2A700, 0x2B734), + (0x2B740, 0x2B81D), + (0x2B820, 0x2CEA1), + (0x2CEB0, 0x2EBE0), + (0x2F800, 0x2FA1D), + ] + + class Japanese(unicode_set): + """Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges""" + + class Kanji(unicode_set): + "Unicode set for Kanji Unicode Character Range" + _ranges: UnicodeRangeList = [ + (0x4E00, 0x9FBF), + (0x3000, 0x303F), + ] + + class Hiragana(unicode_set): + """Unicode set for Hiragana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3041, 0x3096), + (0x3099, 0x30A0), + (0x30FC,), + (0xFF70,), + (0x1B001,), + (0x1B150, 0x1B152), + (0x1F200,), + ] + + class Katakana(unicode_set): + """Unicode set for Katakana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3099, 0x309C), + (0x30A0, 0x30FF), + (0x31F0, 0x31FF), + (0x32D0, 0x32FE), + (0xFF65, 0xFF9F), + (0x1B000,), + (0x1B164, 0x1B167), + (0x1F201, 0x1F202), + (0x1F213,), + ] + + 漢字 = Kanji + カタカナ = Katakana + ひらがな = Hiragana + + _ranges = ( + Kanji._ranges + + Hiragana._ranges + + Katakana._ranges + ) + + class Hangul(unicode_set): + """Unicode set for Hangul (Korean) Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x1100, 0x11FF), + (0x302E, 0x302F), + (0x3131, 0x318E), + (0x3200, 0x321C), + (0x3260, 0x327B), + (0x327E,), + (0xA960, 0xA97C), + (0xAC00, 0xD7A3), + (0xD7B0, 0xD7C6), + (0xD7CB, 0xD7FB), + (0xFFA0, 0xFFBE), + (0xFFC2, 0xFFC7), + (0xFFCA, 0xFFCF), + (0xFFD2, 0xFFD7), + (0xFFDA, 0xFFDC), + ] + + Korean = Hangul + + class CJK(Chinese, Japanese, Hangul): + """Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range""" + + class Thai(unicode_set): + """Unicode set for Thai Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0E01, 0x0E3A), + (0x0E3F, 0x0E5B) + ] + + class Arabic(unicode_set): + """Unicode set for Arabic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0600, 0x061B), + (0x061E, 0x06FF), + (0x0700, 0x077F), + ] + + class Hebrew(unicode_set): + """Unicode set for Hebrew Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0591, 0x05C7), + (0x05D0, 0x05EA), + (0x05EF, 0x05F4), + (0xFB1D, 0xFB36), + (0xFB38, 0xFB3C), + (0xFB3E,), + (0xFB40, 0xFB41), + (0xFB43, 0xFB44), + (0xFB46, 0xFB4F), + ] + + class Devanagari(unicode_set): + """Unicode set for Devanagari Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0900, 0x097F), + (0xA8E0, 0xA8FF) + ] + + BMP = BasicMultilingualPlane + + # add language identifiers using language Unicode + العربية = Arabic + 中文 = Chinese + кириллица = Cyrillic + Ελληνικά = Greek + עִברִית = Hebrew + 日本語 = Japanese + 한국어 = Korean + ไทย = Thai + देवनागरी = Devanagari + + # fmt: on diff --git a/shared/package-files/7c/7c0436a823b2263fa13522d016b6340832c2571ba946805f4426ee2943de0dde/blob b/shared/package-files/7c/7c0436a823b2263fa13522d016b6340832c2571ba946805f4426ee2943de0dde/blob new file mode 100644 index 0000000000000000000000000000000000000000..6985552fa21a5903ee26a765baeeb81f02c19aff --- /dev/null +++ b/shared/package-files/7c/7c0436a823b2263fa13522d016b6340832c2571ba946805f4426ee2943de0dde/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API is_nonzero { + using schema = bool (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::is_nonzero") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "is_nonzero(Tensor self) -> bool") + static bool call(const at::Tensor & self); + static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7c049b8348bb88b8892048f9bc89220ee4eadf0534cf798a258d35f64ccaac59/blob b/shared/package-files/7c/7c049b8348bb88b8892048f9bc89220ee4eadf0534cf798a258d35f64ccaac59/blob new file mode 100644 index 0000000000000000000000000000000000000000..0e2553bf7ad56e97b567e5b334ccf17921f7f7f3 --- /dev/null +++ b/shared/package-files/7c/7c049b8348bb88b8892048f9bc89220ee4eadf0534cf798a258d35f64ccaac59/blob @@ -0,0 +1,91 @@ +import pytest +import numpy as np +from numpy.testing import assert_, assert_array_equal, assert_allclose + +try: + import matplotlib + matplotlib.rcParams['backend'] = 'Agg' + import matplotlib.pyplot as plt + has_matplotlib = True +except Exception: + has_matplotlib = False + +from scipy.spatial import \ + delaunay_plot_2d, voronoi_plot_2d, convex_hull_plot_2d, \ + Delaunay, Voronoi, ConvexHull + + +@pytest.mark.skipif(not has_matplotlib, reason="Matplotlib not available") +class TestPlotting: + points = [(0,0), (0,1), (1,0), (1,1)] + + def test_delaunay(self): + # Smoke test + fig = plt.figure() + obj = Delaunay(self.points) + s_before = obj.simplices.copy() + r = delaunay_plot_2d(obj, ax=fig.gca()) + assert_array_equal(obj.simplices, s_before) # shouldn't modify + assert_(r is fig) + delaunay_plot_2d(obj, ax=fig.gca()) + + def test_voronoi(self): + # Smoke test + fig = plt.figure() + obj = Voronoi(self.points) + r = voronoi_plot_2d(obj, ax=fig.gca()) + assert_(r is fig) + voronoi_plot_2d(obj) + voronoi_plot_2d(obj, show_vertices=False) + + def test_convex_hull(self): + # Smoke test + fig = plt.figure() + tri = ConvexHull(self.points) + r = convex_hull_plot_2d(tri, ax=fig.gca()) + assert_(r is fig) + convex_hull_plot_2d(tri) + + def test_gh_19653(self): + # aspect ratio sensitivity of voronoi_plot_2d + # infinite Voronoi edges + points = np.array([[245.059986986012, 10.971011721360075], + [320.49044143557785, 10.970258360366753], + [239.79023081978914, 13.108487516946218], + [263.38325791238833, 12.93241352743668], + [219.53334398353175, 13.346107628161008]]) + vor = Voronoi(points) + fig = voronoi_plot_2d(vor) + ax = fig.gca() + infinite_segments = ax.collections[1].get_segments() + expected_segments = np.array([[[282.77256, -254.76904], + [282.729714, -4544.744698]], + [[282.77256014, -254.76904029], + [430.08561382, 4032.67658742]], + [[229.26733285, -20.39957514], + [-168.17167404, -4291.92545966]], + [[289.93433364, 5151.40412217], + [330.40553385, 9441.18887532]]]) + assert_allclose(infinite_segments, expected_segments) + + def test_gh_19653_smaller_aspect(self): + # reasonable behavior for less extreme aspect + # ratio + points = np.array([[24.059986986012, 10.971011721360075], + [32.49044143557785, 10.970258360366753], + [23.79023081978914, 13.108487516946218], + [26.38325791238833, 12.93241352743668], + [21.53334398353175, 13.346107628161008]]) + vor = Voronoi(points) + fig = voronoi_plot_2d(vor) + ax = fig.gca() + infinite_segments = ax.collections[1].get_segments() + expected_segments = np.array([[[28.274979, 8.335027], + [28.270463, -42.19763338]], + [[28.27497869, 8.33502697], + [43.73223829, 56.44555501]], + [[22.51805823, 11.8621754], + [-12.09266506, -24.95694485]], + [[29.53092448, 78.46952378], + [33.82572726, 128.81934455]]]) + assert_allclose(infinite_segments, expected_segments) diff --git a/shared/package-files/7c/7c052b3585b286a4204bb460c5ff89af0afa9a201f28e08cdbc1ccdc10a353d9/blob b/shared/package-files/7c/7c052b3585b286a4204bb460c5ff89af0afa9a201f28e08cdbc1ccdc10a353d9/blob new file mode 100644 index 0000000000000000000000000000000000000000..8c53e460f7bd6405575282ba3ece851c760cfb40 --- /dev/null +++ b/shared/package-files/7c/7c052b3585b286a4204bb460c5ff89af0afa9a201f28e08cdbc1ccdc10a353d9/blob @@ -0,0 +1,59 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::std_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor) +inline ::std::tuple std_mean(const at::Tensor & self, bool unbiased) { + return at::_ops::std_mean::call(self, unbiased); +} + +// aten::std_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple std_mean(const at::Tensor & self, at::OptionalIntArrayRef dim, bool unbiased, bool keepdim=false) { + return at::_ops::std_mean_dim::call(self, dim, unbiased, keepdim); +} + +// aten::std_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple std_mean(const at::Tensor & self, at::OptionalIntArrayRef dim=c10::nullopt, const c10::optional & correction=c10::nullopt, bool keepdim=false) { + return at::_ops::std_mean_correction::call(self, dim, correction, keepdim); +} + +// aten::std_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple std_mean(const at::Tensor & self, at::DimnameList dim, bool unbiased, bool keepdim=false) { + return at::_ops::std_mean_names_dim::call(self, dim, unbiased, keepdim); +} + +// aten::std_mean.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) +inline ::std::tuple std_mean(const at::Tensor & self, at::DimnameList dim, const c10::optional & correction=c10::nullopt, bool keepdim=false) { + return at::_ops::std_mean_correction_names::call(self, dim, correction, keepdim); +} + +// aten::std_mean.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple std_mean_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & self, at::OptionalIntArrayRef dim=c10::nullopt, const c10::optional & correction=c10::nullopt, bool keepdim=false) { + return at::_ops::std_mean_correction_out::call(self, dim, correction, keepdim, out0, out1); +} +// aten::std_mean.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple std_mean_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, const c10::optional & correction, bool keepdim, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::std_mean_correction_out::call(self, dim, correction, keepdim, out0, out1); +} + +} diff --git a/shared/package-files/7c/7c061a460bafc10d15c51d693fee3fe7e6ffc21dcfcfd8f3b4f55177cc38b0cf/blob b/shared/package-files/7c/7c061a460bafc10d15c51d693fee3fe7e6ffc21dcfcfd8f3b4f55177cc38b0cf/blob new file mode 100644 index 0000000000000000000000000000000000000000..20379c92b81b413a3aaba5d6a31d91c61313afaf --- /dev/null +++ b/shared/package-files/7c/7c061a460bafc10d15c51d693fee3fe7e6ffc21dcfcfd8f3b4f55177cc38b0cf/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::batch_norm_backward_reduce(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g) -> (Tensor, Tensor, Tensor, Tensor) +inline ::std::tuple batch_norm_backward_reduce(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const c10::optional & weight, bool input_g, bool weight_g, bool bias_g) { + return at::_ops::batch_norm_backward_reduce::call(grad_out, input, mean, invstd, weight, input_g, weight_g, bias_g); +} + +// aten::batch_norm_backward_reduce.out(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!)) +inline ::std::tuple batch_norm_backward_reduce_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const c10::optional & weight, bool input_g, bool weight_g, bool bias_g) { + return at::_ops::batch_norm_backward_reduce_out::call(grad_out, input, mean, invstd, weight, input_g, weight_g, bias_g, out0, out1, out2, out3); +} +// aten::batch_norm_backward_reduce.out(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!)) +inline ::std::tuple batch_norm_backward_reduce_outf(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const c10::optional & weight, bool input_g, bool weight_g, bool bias_g, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3) { + return at::_ops::batch_norm_backward_reduce_out::call(grad_out, input, mean, invstd, weight, input_g, weight_g, bias_g, out0, out1, out2, out3); +} + +} diff --git a/shared/package-files/7c/7c061fcc9d5ce53a6e293335e292b4f2aeb6b320c523b1ec79d491c4d7d2c1c3/blob b/shared/package-files/7c/7c061fcc9d5ce53a6e293335e292b4f2aeb6b320c523b1ec79d491c4d7d2c1c3/blob new file mode 100644 index 0000000000000000000000000000000000000000..5d0958b6ddb1b27e574b2d6337c8673881218945 --- /dev/null +++ b/shared/package-files/7c/7c061fcc9d5ce53a6e293335e292b4f2aeb6b320c523b1ec79d491c4d7d2c1c3/blob @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _batch_norm_legit_no_training(const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, double momentum, double eps); +TORCH_API ::std::tuple _native_batch_norm_legit_no_training_out(const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const at::Tensor & running_mean, const at::Tensor & running_var, double momentum, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c08b91b35ae33d98a51eb0964ee7a2dc3c254c0ed9bae1cdad0bf614a48d6ab/blob b/shared/package-files/7c/7c08b91b35ae33d98a51eb0964ee7a2dc3c254c0ed9bae1cdad0bf614a48d6ab/blob new file mode 100644 index 0000000000000000000000000000000000000000..8fb16dc4a6a2d45a8e762aa182100ecd4506b3b5 --- /dev/null +++ b/shared/package-files/7c/7c08b91b35ae33d98a51eb0964ee7a2dc3c254c0ed9bae1cdad0bf614a48d6ab/blob @@ -0,0 +1,1077 @@ +""" +shared options and groups + +The principle here is to define options once, but *not* instantiate them +globally. One reason being that options with action='append' can carry state +between parses. pip parses general options twice internally, and shouldn't +pass on state. To be consistent, all options will follow this design. +""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +import importlib.util +import logging +import os +import textwrap +from functools import partial +from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values +from textwrap import dedent +from typing import Any, Callable, Dict, Optional, Tuple + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli.parser import ConfigOptionParser +from pip._internal.exceptions import CommandError +from pip._internal.locations import USER_CACHE_DIR, get_src_prefix +from pip._internal.models.format_control import FormatControl +from pip._internal.models.index import PyPI +from pip._internal.models.target_python import TargetPython +from pip._internal.utils.hashes import STRONG_HASHES +from pip._internal.utils.misc import strtobool + +logger = logging.getLogger(__name__) + + +def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None: + """ + Raise an option parsing error using parser.error(). + + Args: + parser: an OptionParser instance. + option: an Option instance. + msg: the error text. + """ + msg = f"{option} error: {msg}" + msg = textwrap.fill(" ".join(msg.split())) + parser.error(msg) + + +def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup: + """ + Return an OptionGroup object + group -- assumed to be dict with 'name' and 'options' keys + parser -- an optparse Parser + """ + option_group = OptionGroup(parser, group["name"]) + for option in group["options"]: + option_group.add_option(option()) + return option_group + + +def check_dist_restriction(options: Values, check_target: bool = False) -> None: + """Function for determining if custom platform options are allowed. + + :param options: The OptionParser options. + :param check_target: Whether or not to check if --target is being used. + """ + dist_restriction_set = any( + [ + options.python_version, + options.platforms, + options.abis, + options.implementation, + ] + ) + + binary_only = FormatControl(set(), {":all:"}) + sdist_dependencies_allowed = ( + options.format_control != binary_only and not options.ignore_dependencies + ) + + # Installations or downloads using dist restrictions must not combine + # source distributions and dist-specific wheels, as they are not + # guaranteed to be locally compatible. + if dist_restriction_set and sdist_dependencies_allowed: + raise CommandError( + "When restricting platform and interpreter constraints using " + "--python-version, --platform, --abi, or --implementation, " + "either --no-deps must be set, or --only-binary=:all: must be " + "set and --no-binary must not be set (or must be set to " + ":none:)." + ) + + if check_target: + if not options.dry_run and dist_restriction_set and not options.target_dir: + raise CommandError( + "Can not use any platform or abi specific options unless " + "installing via '--target' or using '--dry-run'" + ) + + +def _path_option_check(option: Option, opt: str, value: str) -> str: + return os.path.expanduser(value) + + +def _package_name_option_check(option: Option, opt: str, value: str) -> str: + return canonicalize_name(value) + + +class PipOption(Option): + TYPES = Option.TYPES + ("path", "package_name") + TYPE_CHECKER = Option.TYPE_CHECKER.copy() + TYPE_CHECKER["package_name"] = _package_name_option_check + TYPE_CHECKER["path"] = _path_option_check + + +########### +# options # +########### + +help_: Callable[..., Option] = partial( + Option, + "-h", + "--help", + dest="help", + action="help", + help="Show help.", +) + +debug_mode: Callable[..., Option] = partial( + Option, + "--debug", + dest="debug_mode", + action="store_true", + default=False, + help=( + "Let unhandled exceptions propagate outside the main subroutine, " + "instead of logging them to stderr." + ), +) + +isolated_mode: Callable[..., Option] = partial( + Option, + "--isolated", + dest="isolated_mode", + action="store_true", + default=False, + help=( + "Run pip in an isolated mode, ignoring environment variables and user " + "configuration." + ), +) + +require_virtualenv: Callable[..., Option] = partial( + Option, + "--require-virtualenv", + "--require-venv", + dest="require_venv", + action="store_true", + default=False, + help=( + "Allow pip to only run in a virtual environment; " + "exit with an error otherwise." + ), +) + +override_externally_managed: Callable[..., Option] = partial( + Option, + "--break-system-packages", + dest="override_externally_managed", + action="store_true", + help="Allow pip to modify an EXTERNALLY-MANAGED Python installation", +) + +python: Callable[..., Option] = partial( + Option, + "--python", + dest="python", + help="Run pip with the specified Python interpreter.", +) + +verbose: Callable[..., Option] = partial( + Option, + "-v", + "--verbose", + dest="verbose", + action="count", + default=0, + help="Give more output. Option is additive, and can be used up to 3 times.", +) + +no_color: Callable[..., Option] = partial( + Option, + "--no-color", + dest="no_color", + action="store_true", + default=False, + help="Suppress colored output.", +) + +version: Callable[..., Option] = partial( + Option, + "-V", + "--version", + dest="version", + action="store_true", + help="Show version and exit.", +) + +quiet: Callable[..., Option] = partial( + Option, + "-q", + "--quiet", + dest="quiet", + action="count", + default=0, + help=( + "Give less output. Option is additive, and can be used up to 3" + " times (corresponding to WARNING, ERROR, and CRITICAL logging" + " levels)." + ), +) + +progress_bar: Callable[..., Option] = partial( + Option, + "--progress-bar", + dest="progress_bar", + type="choice", + choices=["on", "off"], + default="on", + help="Specify whether the progress bar should be used [on, off] (default: on)", +) + +log: Callable[..., Option] = partial( + PipOption, + "--log", + "--log-file", + "--local-log", + dest="log", + metavar="path", + type="path", + help="Path to a verbose appending log.", +) + +no_input: Callable[..., Option] = partial( + Option, + # Don't ask for input + "--no-input", + dest="no_input", + action="store_true", + default=False, + help="Disable prompting for input.", +) + +keyring_provider: Callable[..., Option] = partial( + Option, + "--keyring-provider", + dest="keyring_provider", + choices=["auto", "disabled", "import", "subprocess"], + default="auto", + help=( + "Enable the credential lookup via the keyring library if user input is allowed." + " Specify which mechanism to use [disabled, import, subprocess]." + " (default: disabled)" + ), +) + +proxy: Callable[..., Option] = partial( + Option, + "--proxy", + dest="proxy", + type="str", + default="", + help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.", +) + +retries: Callable[..., Option] = partial( + Option, + "--retries", + dest="retries", + type="int", + default=5, + help="Maximum number of retries each connection should attempt " + "(default %default times).", +) + +timeout: Callable[..., Option] = partial( + Option, + "--timeout", + "--default-timeout", + metavar="sec", + dest="timeout", + type="float", + default=15, + help="Set the socket timeout (default %default seconds).", +) + + +def exists_action() -> Option: + return Option( + # Option when path already exist + "--exists-action", + dest="exists_action", + type="choice", + choices=["s", "i", "w", "b", "a"], + default=[], + action="append", + metavar="action", + help="Default action when a path already exists: " + "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", + ) + + +cert: Callable[..., Option] = partial( + PipOption, + "--cert", + dest="cert", + type="path", + metavar="path", + help=( + "Path to PEM-encoded CA certificate bundle. " + "If provided, overrides the default. " + "See 'SSL Certificate Verification' in pip documentation " + "for more information." + ), +) + +client_cert: Callable[..., Option] = partial( + PipOption, + "--client-cert", + dest="client_cert", + type="path", + default=None, + metavar="path", + help="Path to SSL client certificate, a single file containing the " + "private key and the certificate in PEM format.", +) + +index_url: Callable[..., Option] = partial( + Option, + "-i", + "--index-url", + "--pypi-url", + dest="index_url", + metavar="URL", + default=PyPI.simple_url, + help="Base URL of the Python Package Index (default %default). " + "This should point to a repository compliant with PEP 503 " + "(the simple repository API) or a local directory laid out " + "in the same format.", +) + + +def extra_index_url() -> Option: + return Option( + "--extra-index-url", + dest="extra_index_urls", + metavar="URL", + action="append", + default=[], + help="Extra URLs of package indexes to use in addition to " + "--index-url. Should follow the same rules as " + "--index-url.", + ) + + +no_index: Callable[..., Option] = partial( + Option, + "--no-index", + dest="no_index", + action="store_true", + default=False, + help="Ignore package index (only looking at --find-links URLs instead).", +) + + +def find_links() -> Option: + return Option( + "-f", + "--find-links", + dest="find_links", + action="append", + default=[], + metavar="url", + help="If a URL or path to an html file, then parse for links to " + "archives such as sdist (.tar.gz) or wheel (.whl) files. " + "If a local path or file:// URL that's a directory, " + "then look for archives in the directory listing. " + "Links to VCS project URLs are not supported.", + ) + + +def trusted_host() -> Option: + return Option( + "--trusted-host", + dest="trusted_hosts", + action="append", + metavar="HOSTNAME", + default=[], + help="Mark this host or host:port pair as trusted, even though it " + "does not have valid or any HTTPS.", + ) + + +def constraints() -> Option: + return Option( + "-c", + "--constraint", + dest="constraints", + action="append", + default=[], + metavar="file", + help="Constrain versions using the given constraints file. " + "This option can be used multiple times.", + ) + + +def requirements() -> Option: + return Option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help="Install from the given requirements file. " + "This option can be used multiple times.", + ) + + +def editable() -> Option: + return Option( + "-e", + "--editable", + dest="editables", + action="append", + default=[], + metavar="path/url", + help=( + "Install a project in editable mode (i.e. setuptools " + '"develop mode") from a local project path or a VCS url.' + ), + ) + + +def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None: + value = os.path.abspath(value) + setattr(parser.values, option.dest, value) + + +src: Callable[..., Option] = partial( + PipOption, + "--src", + "--source", + "--source-dir", + "--source-directory", + dest="src_dir", + type="path", + metavar="dir", + default=get_src_prefix(), + action="callback", + callback=_handle_src, + help="Directory to check out editable projects into. " + 'The default in a virtualenv is "/src". ' + 'The default for global installs is "/src".', +) + + +def _get_format_control(values: Values, option: Option) -> Any: + """Get a format_control object.""" + return getattr(values, option.dest) + + +def _handle_no_binary( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + existing = _get_format_control(parser.values, option) + FormatControl.handle_mutual_excludes( + value, + existing.no_binary, + existing.only_binary, + ) + + +def _handle_only_binary( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + existing = _get_format_control(parser.values, option) + FormatControl.handle_mutual_excludes( + value, + existing.only_binary, + existing.no_binary, + ) + + +def no_binary() -> Option: + format_control = FormatControl(set(), set()) + return Option( + "--no-binary", + dest="format_control", + action="callback", + callback=_handle_no_binary, + type="str", + default=format_control, + help="Do not use binary packages. Can be supplied multiple times, and " + 'each time adds to the existing value. Accepts either ":all:" to ' + 'disable all binary packages, ":none:" to empty the set (notice ' + "the colons), or one or more package names with commas between " + "them (no colons). Note that some packages are tricky to compile " + "and may fail to install when this option is used on them.", + ) + + +def only_binary() -> Option: + format_control = FormatControl(set(), set()) + return Option( + "--only-binary", + dest="format_control", + action="callback", + callback=_handle_only_binary, + type="str", + default=format_control, + help="Do not use source packages. Can be supplied multiple times, and " + 'each time adds to the existing value. Accepts either ":all:" to ' + 'disable all source packages, ":none:" to empty the set, or one ' + "or more package names with commas between them. Packages " + "without binary distributions will fail to install when this " + "option is used on them.", + ) + + +platforms: Callable[..., Option] = partial( + Option, + "--platform", + dest="platforms", + metavar="platform", + action="append", + default=None, + help=( + "Only use wheels compatible with . Defaults to the " + "platform of the running system. Use this option multiple times to " + "specify multiple platforms supported by the target interpreter." + ), +) + + +# This was made a separate function for unit-testing purposes. +def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]: + """ + Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. + + :return: A 2-tuple (version_info, error_msg), where `error_msg` is + non-None if and only if there was a parsing error. + """ + if not value: + # The empty string is the same as not providing a value. + return (None, None) + + parts = value.split(".") + if len(parts) > 3: + return ((), "at most three version parts are allowed") + + if len(parts) == 1: + # Then we are in the case of "3" or "37". + value = parts[0] + if len(value) > 1: + parts = [value[0], value[1:]] + + try: + version_info = tuple(int(part) for part in parts) + except ValueError: + return ((), "each version part must be an integer") + + return (version_info, None) + + +def _handle_python_version( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + """ + Handle a provided --python-version value. + """ + version_info, error_msg = _convert_python_version(value) + if error_msg is not None: + msg = "invalid --python-version value: {!r}: {}".format( + value, + error_msg, + ) + raise_option_error(parser, option=option, msg=msg) + + parser.values.python_version = version_info + + +python_version: Callable[..., Option] = partial( + Option, + "--python-version", + dest="python_version", + metavar="python_version", + action="callback", + callback=_handle_python_version, + type="str", + default=None, + help=dedent( + """\ + The Python interpreter version to use for wheel and "Requires-Python" + compatibility checks. Defaults to a version derived from the running + interpreter. The version can be specified using up to three dot-separated + integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor + version can also be given as a string without dots (e.g. "37" for 3.7.0). + """ + ), +) + + +implementation: Callable[..., Option] = partial( + Option, + "--implementation", + dest="implementation", + metavar="implementation", + default=None, + help=( + "Only use wheels compatible with Python " + "implementation , e.g. 'pp', 'jy', 'cp', " + " or 'ip'. If not specified, then the current " + "interpreter implementation is used. Use 'py' to force " + "implementation-agnostic wheels." + ), +) + + +abis: Callable[..., Option] = partial( + Option, + "--abi", + dest="abis", + metavar="abi", + action="append", + default=None, + help=( + "Only use wheels compatible with Python abi , e.g. 'pypy_41'. " + "If not specified, then the current interpreter abi tag is used. " + "Use this option multiple times to specify multiple abis supported " + "by the target interpreter. Generally you will need to specify " + "--implementation, --platform, and --python-version when using this " + "option." + ), +) + + +def add_target_python_options(cmd_opts: OptionGroup) -> None: + cmd_opts.add_option(platforms()) + cmd_opts.add_option(python_version()) + cmd_opts.add_option(implementation()) + cmd_opts.add_option(abis()) + + +def make_target_python(options: Values) -> TargetPython: + target_python = TargetPython( + platforms=options.platforms, + py_version_info=options.python_version, + abis=options.abis, + implementation=options.implementation, + ) + + return target_python + + +def prefer_binary() -> Option: + return Option( + "--prefer-binary", + dest="prefer_binary", + action="store_true", + default=False, + help=( + "Prefer binary packages over source packages, even if the " + "source packages are newer." + ), + ) + + +cache_dir: Callable[..., Option] = partial( + PipOption, + "--cache-dir", + dest="cache_dir", + default=USER_CACHE_DIR, + metavar="dir", + type="path", + help="Store the cache data in .", +) + + +def _handle_no_cache_dir( + option: Option, opt: str, value: str, parser: OptionParser +) -> None: + """ + Process a value provided for the --no-cache-dir option. + + This is an optparse.Option callback for the --no-cache-dir option. + """ + # The value argument will be None if --no-cache-dir is passed via the + # command-line, since the option doesn't accept arguments. However, + # the value can be non-None if the option is triggered e.g. by an + # environment variable, like PIP_NO_CACHE_DIR=true. + if value is not None: + # Then parse the string value to get argument error-checking. + try: + strtobool(value) + except ValueError as exc: + raise_option_error(parser, option=option, msg=str(exc)) + + # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() + # converted to 0 (like "false" or "no") caused cache_dir to be disabled + # rather than enabled (logic would say the latter). Thus, we disable + # the cache directory not just on values that parse to True, but (for + # backwards compatibility reasons) also on values that parse to False. + # In other words, always set it to False if the option is provided in + # some (valid) form. + parser.values.cache_dir = False + + +no_cache: Callable[..., Option] = partial( + Option, + "--no-cache-dir", + dest="cache_dir", + action="callback", + callback=_handle_no_cache_dir, + help="Disable the cache.", +) + +no_deps: Callable[..., Option] = partial( + Option, + "--no-deps", + "--no-dependencies", + dest="ignore_dependencies", + action="store_true", + default=False, + help="Don't install package dependencies.", +) + +ignore_requires_python: Callable[..., Option] = partial( + Option, + "--ignore-requires-python", + dest="ignore_requires_python", + action="store_true", + help="Ignore the Requires-Python information.", +) + +no_build_isolation: Callable[..., Option] = partial( + Option, + "--no-build-isolation", + dest="build_isolation", + action="store_false", + default=True, + help="Disable isolation when building a modern source distribution. " + "Build dependencies specified by PEP 518 must be already installed " + "if this option is used.", +) + +check_build_deps: Callable[..., Option] = partial( + Option, + "--check-build-dependencies", + dest="check_build_deps", + action="store_true", + default=False, + help="Check the build dependencies when PEP517 is used.", +) + + +def _handle_no_use_pep517( + option: Option, opt: str, value: str, parser: OptionParser +) -> None: + """ + Process a value provided for the --no-use-pep517 option. + + This is an optparse.Option callback for the no_use_pep517 option. + """ + # Since --no-use-pep517 doesn't accept arguments, the value argument + # will be None if --no-use-pep517 is passed via the command-line. + # However, the value can be non-None if the option is triggered e.g. + # by an environment variable, for example "PIP_NO_USE_PEP517=true". + if value is not None: + msg = """A value was passed for --no-use-pep517, + probably using either the PIP_NO_USE_PEP517 environment variable + or the "no-use-pep517" config file option. Use an appropriate value + of the PIP_USE_PEP517 environment variable or the "use-pep517" + config file option instead. + """ + raise_option_error(parser, option=option, msg=msg) + + # If user doesn't wish to use pep517, we check if setuptools and wheel are installed + # and raise error if it is not. + packages = ("setuptools", "wheel") + if not all(importlib.util.find_spec(package) for package in packages): + msg = ( + f"It is not possible to use --no-use-pep517 " + f"without {' and '.join(packages)} installed." + ) + raise_option_error(parser, option=option, msg=msg) + + # Otherwise, --no-use-pep517 was passed via the command-line. + parser.values.use_pep517 = False + + +use_pep517: Any = partial( + Option, + "--use-pep517", + dest="use_pep517", + action="store_true", + default=None, + help="Use PEP 517 for building source distributions " + "(use --no-use-pep517 to force legacy behaviour).", +) + +no_use_pep517: Any = partial( + Option, + "--no-use-pep517", + dest="use_pep517", + action="callback", + callback=_handle_no_use_pep517, + default=None, + help=SUPPRESS_HELP, +) + + +def _handle_config_settings( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + key, sep, val = value.partition("=") + if sep != "=": + parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL") + dest = getattr(parser.values, option.dest) + if dest is None: + dest = {} + setattr(parser.values, option.dest, dest) + if key in dest: + if isinstance(dest[key], list): + dest[key].append(val) + else: + dest[key] = [dest[key], val] + else: + dest[key] = val + + +config_settings: Callable[..., Option] = partial( + Option, + "-C", + "--config-settings", + dest="config_settings", + type=str, + action="callback", + callback=_handle_config_settings, + metavar="settings", + help="Configuration settings to be passed to the PEP 517 build backend. " + "Settings take the form KEY=VALUE. Use multiple --config-settings options " + "to pass multiple keys to the backend.", +) + +build_options: Callable[..., Option] = partial( + Option, + "--build-option", + dest="build_options", + metavar="options", + action="append", + help="Extra arguments to be supplied to 'setup.py bdist_wheel'.", +) + +global_options: Callable[..., Option] = partial( + Option, + "--global-option", + dest="global_options", + action="append", + metavar="options", + help="Extra global options to be supplied to the setup.py " + "call before the install or bdist_wheel command.", +) + +no_clean: Callable[..., Option] = partial( + Option, + "--no-clean", + action="store_true", + default=False, + help="Don't clean up build directories.", +) + +pre: Callable[..., Option] = partial( + Option, + "--pre", + action="store_true", + default=False, + help="Include pre-release and development versions. By default, " + "pip only finds stable versions.", +) + +disable_pip_version_check: Callable[..., Option] = partial( + Option, + "--disable-pip-version-check", + dest="disable_pip_version_check", + action="store_true", + default=False, + help="Don't periodically check PyPI to determine whether a new version " + "of pip is available for download. Implied with --no-index.", +) + +root_user_action: Callable[..., Option] = partial( + Option, + "--root-user-action", + dest="root_user_action", + default="warn", + choices=["warn", "ignore"], + help="Action if pip is run as a root user. By default, a warning message is shown.", +) + + +def _handle_merge_hash( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + """Given a value spelled "algo:digest", append the digest to a list + pointed to in a dict by the algo name.""" + if not parser.values.hashes: + parser.values.hashes = {} + try: + algo, digest = value.split(":", 1) + except ValueError: + parser.error( + "Arguments to {} must be a hash name " + "followed by a value, like --hash=sha256:" + "abcde...".format(opt_str) + ) + if algo not in STRONG_HASHES: + parser.error( + "Allowed hash algorithms for {} are {}.".format( + opt_str, ", ".join(STRONG_HASHES) + ) + ) + parser.values.hashes.setdefault(algo, []).append(digest) + + +hash: Callable[..., Option] = partial( + Option, + "--hash", + # Hash values eventually end up in InstallRequirement.hashes due to + # __dict__ copying in process_line(). + dest="hashes", + action="callback", + callback=_handle_merge_hash, + type="string", + help="Verify that the package's archive matches this " + "hash before installing. Example: --hash=sha256:abcdef...", +) + + +require_hashes: Callable[..., Option] = partial( + Option, + "--require-hashes", + dest="require_hashes", + action="store_true", + default=False, + help="Require a hash to check each requirement against, for " + "repeatable installs. This option is implied when any package in a " + "requirements file has a --hash option.", +) + + +list_path: Callable[..., Option] = partial( + PipOption, + "--path", + dest="path", + type="path", + action="append", + help="Restrict to the specified installation path for listing " + "packages (can be used multiple times).", +) + + +def check_list_path_option(options: Values) -> None: + if options.path and (options.user or options.local): + raise CommandError("Cannot combine '--path' with '--user' or '--local'") + + +list_exclude: Callable[..., Option] = partial( + PipOption, + "--exclude", + dest="excludes", + action="append", + metavar="package", + type="package_name", + help="Exclude specified package from the output", +) + + +no_python_version_warning: Callable[..., Option] = partial( + Option, + "--no-python-version-warning", + dest="no_python_version_warning", + action="store_true", + default=False, + help="Silence deprecation warnings for upcoming unsupported Pythons.", +) + + +# Features that are now always on. A warning is printed if they are used. +ALWAYS_ENABLED_FEATURES = [ + "no-binary-enable-wheel-cache", # always on since 23.1 +] + +use_new_feature: Callable[..., Option] = partial( + Option, + "--use-feature", + dest="features_enabled", + metavar="feature", + action="append", + default=[], + choices=[ + "fast-deps", + "truststore", + ] + + ALWAYS_ENABLED_FEATURES, + help="Enable new functionality, that may be backward incompatible.", +) + +use_deprecated_feature: Callable[..., Option] = partial( + Option, + "--use-deprecated", + dest="deprecated_features_enabled", + metavar="feature", + action="append", + default=[], + choices=[ + "legacy-resolver", + ], + help=("Enable deprecated functionality, that will be removed in the future."), +) + + +########## +# groups # +########## + +general_group: Dict[str, Any] = { + "name": "General Options", + "options": [ + help_, + debug_mode, + isolated_mode, + require_virtualenv, + python, + verbose, + version, + quiet, + log, + no_input, + keyring_provider, + proxy, + retries, + timeout, + exists_action, + trusted_host, + cert, + client_cert, + cache_dir, + no_cache, + disable_pip_version_check, + no_color, + no_python_version_warning, + use_new_feature, + use_deprecated_feature, + ], +} + +index_group: Dict[str, Any] = { + "name": "Package Index Options", + "options": [ + index_url, + extra_index_url, + no_index, + find_links, + ], +} diff --git a/shared/package-files/7c/7c0a660d0d355739c5fee680e1b29c87422a1c77c130bc406b554c6bf73bb2ee/blob b/shared/package-files/7c/7c0a660d0d355739c5fee680e1b29c87422a1c77c130bc406b554c6bf73bb2ee/blob new file mode 100644 index 0000000000000000000000000000000000000000..a47eaace5b9a2362e7abf6326f2e0c7ad10c112f --- /dev/null +++ b/shared/package-files/7c/7c0a660d0d355739c5fee680e1b29c87422a1c77c130bc406b554c6bf73bb2ee/blob @@ -0,0 +1,786 @@ +from numbers import Integral, Real + +import numpy as np +import pytest +from scipy.sparse import csr_matrix + +from sklearn._config import config_context, get_config +from sklearn.base import BaseEstimator, _fit_context +from sklearn.model_selection import LeaveOneOut +from sklearn.utils import deprecated +from sklearn.utils._param_validation import ( + HasMethods, + Hidden, + Interval, + InvalidParameterError, + MissingValues, + Options, + RealNotInt, + StrOptions, + _ArrayLikes, + _Booleans, + _Callables, + _CVObjects, + _InstancesOf, + _IterablesNotString, + _NanConstraint, + _NoneConstraint, + _PandasNAConstraint, + _RandomStates, + _SparseMatrices, + _VerboseHelper, + generate_invalid_param_val, + generate_valid_param, + make_constraint, + validate_params, +) +from sklearn.utils.fixes import CSR_CONTAINERS + + +# Some helpers for the tests +@validate_params( + {"a": [Real], "b": [Real], "c": [Real], "d": [Real]}, + prefer_skip_nested_validation=True, +) +def _func(a, b=0, *args, c, d=0, **kwargs): + """A function to test the validation of functions.""" + + +class _Class: + """A class to test the _InstancesOf constraint and the validation of methods.""" + + @validate_params({"a": [Real]}, prefer_skip_nested_validation=True) + def _method(self, a): + """A validated method""" + + @deprecated() + @validate_params({"a": [Real]}, prefer_skip_nested_validation=True) + def _deprecated_method(self, a): + """A deprecated validated method""" + + +class _Estimator(BaseEstimator): + """An estimator to test the validation of estimator parameters.""" + + _parameter_constraints: dict = {"a": [Real]} + + def __init__(self, a): + self.a = a + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X=None, y=None): + pass + + +@pytest.mark.parametrize("interval_type", [Integral, Real]) +def test_interval_range(interval_type): + """Check the range of values depending on closed.""" + interval = Interval(interval_type, -2, 2, closed="left") + assert -2 in interval + assert 2 not in interval + + interval = Interval(interval_type, -2, 2, closed="right") + assert -2 not in interval + assert 2 in interval + + interval = Interval(interval_type, -2, 2, closed="both") + assert -2 in interval + assert 2 in interval + + interval = Interval(interval_type, -2, 2, closed="neither") + assert -2 not in interval + assert 2 not in interval + + +@pytest.mark.parametrize("interval_type", [Integral, Real]) +def test_interval_large_integers(interval_type): + """Check that Interval constraint work with large integers. + + non-regression test for #26648. + """ + interval = Interval(interval_type, 0, 2, closed="neither") + assert 2**65 not in interval + assert 2**128 not in interval + assert float(2**65) not in interval + assert float(2**128) not in interval + + interval = Interval(interval_type, 0, 2**128, closed="neither") + assert 2**65 in interval + assert 2**128 not in interval + assert float(2**65) in interval + assert float(2**128) not in interval + + assert 2**1024 not in interval + + +def test_interval_inf_in_bounds(): + """Check that inf is included iff a bound is closed and set to None. + + Only valid for real intervals. + """ + interval = Interval(Real, 0, None, closed="right") + assert np.inf in interval + + interval = Interval(Real, None, 0, closed="left") + assert -np.inf in interval + + interval = Interval(Real, None, None, closed="neither") + assert np.inf not in interval + assert -np.inf not in interval + + +@pytest.mark.parametrize( + "interval", + [Interval(Real, 0, 1, closed="left"), Interval(Real, None, None, closed="both")], +) +def test_nan_not_in_interval(interval): + """Check that np.nan is not in any interval.""" + assert np.nan not in interval + + +@pytest.mark.parametrize( + "params, error, match", + [ + ( + {"type": Integral, "left": 1.0, "right": 2, "closed": "both"}, + TypeError, + r"Expecting left to be an int for an interval over the integers", + ), + ( + {"type": Integral, "left": 1, "right": 2.0, "closed": "neither"}, + TypeError, + "Expecting right to be an int for an interval over the integers", + ), + ( + {"type": Integral, "left": None, "right": 0, "closed": "left"}, + ValueError, + r"left can't be None when closed == left", + ), + ( + {"type": Integral, "left": 0, "right": None, "closed": "right"}, + ValueError, + r"right can't be None when closed == right", + ), + ( + {"type": Integral, "left": 1, "right": -1, "closed": "both"}, + ValueError, + r"right can't be less than left", + ), + ], +) +def test_interval_errors(params, error, match): + """Check that informative errors are raised for invalid combination of parameters""" + with pytest.raises(error, match=match): + Interval(**params) + + +def test_stroptions(): + """Sanity check for the StrOptions constraint""" + options = StrOptions({"a", "b", "c"}, deprecated={"c"}) + assert options.is_satisfied_by("a") + assert options.is_satisfied_by("c") + assert not options.is_satisfied_by("d") + + assert "'c' (deprecated)" in str(options) + + +def test_options(): + """Sanity check for the Options constraint""" + options = Options(Real, {-0.5, 0.5, np.inf}, deprecated={-0.5}) + assert options.is_satisfied_by(-0.5) + assert options.is_satisfied_by(np.inf) + assert not options.is_satisfied_by(1.23) + + assert "-0.5 (deprecated)" in str(options) + + +@pytest.mark.parametrize( + "type, expected_type_name", + [ + (int, "int"), + (Integral, "int"), + (Real, "float"), + (np.ndarray, "numpy.ndarray"), + ], +) +def test_instances_of_type_human_readable(type, expected_type_name): + """Check the string representation of the _InstancesOf constraint.""" + constraint = _InstancesOf(type) + assert str(constraint) == f"an instance of '{expected_type_name}'" + + +def test_hasmethods(): + """Check the HasMethods constraint.""" + constraint = HasMethods(["a", "b"]) + + class _Good: + def a(self): + pass # pragma: no cover + + def b(self): + pass # pragma: no cover + + class _Bad: + def a(self): + pass # pragma: no cover + + assert constraint.is_satisfied_by(_Good()) + assert not constraint.is_satisfied_by(_Bad()) + assert str(constraint) == "an object implementing 'a' and 'b'" + + +@pytest.mark.parametrize( + "constraint", + [ + Interval(Real, None, 0, closed="left"), + Interval(Real, 0, None, closed="left"), + Interval(Real, None, None, closed="neither"), + StrOptions({"a", "b", "c"}), + MissingValues(), + MissingValues(numeric_only=True), + _VerboseHelper(), + HasMethods("fit"), + _IterablesNotString(), + _CVObjects(), + ], +) +def test_generate_invalid_param_val(constraint): + """Check that the value generated does not satisfy the constraint""" + bad_value = generate_invalid_param_val(constraint) + assert not constraint.is_satisfied_by(bad_value) + + +@pytest.mark.parametrize( + "integer_interval, real_interval", + [ + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, -5, 5, closed="both"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, -5, 5, closed="neither"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, 4, 5, closed="both"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, 5, None, closed="left"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, 4, None, closed="neither"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, -5, 5, closed="both"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, -5, 5, closed="neither"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, 1, 2, closed="both"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, None, -5, closed="left"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, None, -4, closed="neither"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, None, 1, closed="right"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, 1, None, closed="left"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, -10, -4, closed="neither"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, -10, -4, closed="right"), + ), + ( + Interval(Integral, -5, 5, closed="neither"), + Interval(RealNotInt, 6, 10, closed="neither"), + ), + ( + Interval(Integral, -5, 5, closed="neither"), + Interval(RealNotInt, 6, 10, closed="left"), + ), + ( + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ), + ( + Interval(Integral, 1, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ), + ], +) +def test_generate_invalid_param_val_2_intervals(integer_interval, real_interval): + """Check that the value generated for an interval constraint does not satisfy any of + the interval constraints. + """ + bad_value = generate_invalid_param_val(constraint=real_interval) + assert not real_interval.is_satisfied_by(bad_value) + assert not integer_interval.is_satisfied_by(bad_value) + + bad_value = generate_invalid_param_val(constraint=integer_interval) + assert not real_interval.is_satisfied_by(bad_value) + assert not integer_interval.is_satisfied_by(bad_value) + + +@pytest.mark.parametrize( + "constraint", + [ + _ArrayLikes(), + _InstancesOf(list), + _Callables(), + _NoneConstraint(), + _RandomStates(), + _SparseMatrices(), + _Booleans(), + Interval(Integral, None, None, closed="neither"), + ], +) +def test_generate_invalid_param_val_all_valid(constraint): + """Check that the function raises NotImplementedError when there's no invalid value + for the constraint. + """ + with pytest.raises(NotImplementedError): + generate_invalid_param_val(constraint) + + +@pytest.mark.parametrize( + "constraint", + [ + _ArrayLikes(), + _Callables(), + _InstancesOf(list), + _NoneConstraint(), + _RandomStates(), + _SparseMatrices(), + _Booleans(), + _VerboseHelper(), + MissingValues(), + MissingValues(numeric_only=True), + StrOptions({"a", "b", "c"}), + Options(Integral, {1, 2, 3}), + Interval(Integral, None, None, closed="neither"), + Interval(Integral, 0, 10, closed="neither"), + Interval(Integral, 0, None, closed="neither"), + Interval(Integral, None, 0, closed="neither"), + Interval(Real, 0, 1, closed="neither"), + Interval(Real, 0, None, closed="both"), + Interval(Real, None, 0, closed="right"), + HasMethods("fit"), + _IterablesNotString(), + _CVObjects(), + ], +) +def test_generate_valid_param(constraint): + """Check that the value generated does satisfy the constraint.""" + value = generate_valid_param(constraint) + assert constraint.is_satisfied_by(value) + + +@pytest.mark.parametrize( + "constraint_declaration, value", + [ + (Interval(Real, 0, 1, closed="both"), 0.42), + (Interval(Integral, 0, None, closed="neither"), 42), + (StrOptions({"a", "b", "c"}), "b"), + (Options(type, {np.float32, np.float64}), np.float64), + (callable, lambda x: x + 1), + (None, None), + ("array-like", [[1, 2], [3, 4]]), + ("array-like", np.array([[1, 2], [3, 4]])), + ("sparse matrix", csr_matrix([[1, 2], [3, 4]])), + *[ + ("sparse matrix", container([[1, 2], [3, 4]])) + for container in CSR_CONTAINERS + ], + ("random_state", 0), + ("random_state", np.random.RandomState(0)), + ("random_state", None), + (_Class, _Class()), + (int, 1), + (Real, 0.5), + ("boolean", False), + ("verbose", 1), + ("nan", np.nan), + (MissingValues(), -1), + (MissingValues(), -1.0), + (MissingValues(), 2**1028), + (MissingValues(), None), + (MissingValues(), float("nan")), + (MissingValues(), np.nan), + (MissingValues(), "missing"), + (HasMethods("fit"), _Estimator(a=0)), + ("cv_object", 5), + ], +) +def test_is_satisfied_by(constraint_declaration, value): + """Sanity check for the is_satisfied_by method""" + constraint = make_constraint(constraint_declaration) + assert constraint.is_satisfied_by(value) + + +@pytest.mark.parametrize( + "constraint_declaration, expected_constraint_class", + [ + (Interval(Real, 0, 1, closed="both"), Interval), + (StrOptions({"option1", "option2"}), StrOptions), + (Options(Real, {0.42, 1.23}), Options), + ("array-like", _ArrayLikes), + ("sparse matrix", _SparseMatrices), + ("random_state", _RandomStates), + (None, _NoneConstraint), + (callable, _Callables), + (int, _InstancesOf), + ("boolean", _Booleans), + ("verbose", _VerboseHelper), + (MissingValues(numeric_only=True), MissingValues), + (HasMethods("fit"), HasMethods), + ("cv_object", _CVObjects), + ("nan", _NanConstraint), + (np.nan, _NanConstraint), + ], +) +def test_make_constraint(constraint_declaration, expected_constraint_class): + """Check that make_constraint dispatches to the appropriate constraint class""" + constraint = make_constraint(constraint_declaration) + assert constraint.__class__ is expected_constraint_class + + +def test_make_constraint_unknown(): + """Check that an informative error is raised when an unknown constraint is passed""" + with pytest.raises(ValueError, match="Unknown constraint"): + make_constraint("not a valid constraint") + + +def test_validate_params(): + """Check that validate_params works no matter how the arguments are passed""" + with pytest.raises( + InvalidParameterError, match="The 'a' parameter of _func must be" + ): + _func("wrong", c=1) + + with pytest.raises( + InvalidParameterError, match="The 'b' parameter of _func must be" + ): + _func(*[1, "wrong"], c=1) + + with pytest.raises( + InvalidParameterError, match="The 'c' parameter of _func must be" + ): + _func(1, **{"c": "wrong"}) + + with pytest.raises( + InvalidParameterError, match="The 'd' parameter of _func must be" + ): + _func(1, c=1, d="wrong") + + # check in the presence of extra positional and keyword args + with pytest.raises( + InvalidParameterError, match="The 'b' parameter of _func must be" + ): + _func(0, *["wrong", 2, 3], c=4, **{"e": 5}) + + with pytest.raises( + InvalidParameterError, match="The 'c' parameter of _func must be" + ): + _func(0, *[1, 2, 3], c="four", **{"e": 5}) + + +def test_validate_params_missing_params(): + """Check that no error is raised when there are parameters without + constraints + """ + + @validate_params({"a": [int]}, prefer_skip_nested_validation=True) + def func(a, b): + pass + + func(1, 2) + + +def test_decorate_validated_function(): + """Check that validate_params functions can be decorated""" + decorated_function = deprecated()(_func) + + with pytest.warns(FutureWarning, match="Function _func is deprecated"): + decorated_function(1, 2, c=3) + + # outer decorator does not interfere with validation + with pytest.warns(FutureWarning, match="Function _func is deprecated"): + with pytest.raises( + InvalidParameterError, match=r"The 'c' parameter of _func must be" + ): + decorated_function(1, 2, c="wrong") + + +def test_validate_params_method(): + """Check that validate_params works with methods""" + with pytest.raises( + InvalidParameterError, match="The 'a' parameter of _Class._method must be" + ): + _Class()._method("wrong") + + # validated method can be decorated + with pytest.warns(FutureWarning, match="Function _deprecated_method is deprecated"): + with pytest.raises( + InvalidParameterError, + match="The 'a' parameter of _Class._deprecated_method must be", + ): + _Class()._deprecated_method("wrong") + + +def test_validate_params_estimator(): + """Check that validate_params works with Estimator instances""" + # no validation in init + est = _Estimator("wrong") + + with pytest.raises( + InvalidParameterError, match="The 'a' parameter of _Estimator must be" + ): + est.fit() + + +def test_stroptions_deprecated_subset(): + """Check that the deprecated parameter must be a subset of options.""" + with pytest.raises(ValueError, match="deprecated options must be a subset"): + StrOptions({"a", "b", "c"}, deprecated={"a", "d"}) + + +def test_hidden_constraint(): + """Check that internal constraints are not exposed in the error message.""" + + @validate_params( + {"param": [Hidden(list), dict]}, prefer_skip_nested_validation=True + ) + def f(param): + pass + + # list and dict are valid params + f({"a": 1, "b": 2, "c": 3}) + f([1, 2, 3]) + + with pytest.raises( + InvalidParameterError, match="The 'param' parameter" + ) as exc_info: + f(param="bad") + + # the list option is not exposed in the error message + err_msg = str(exc_info.value) + assert "an instance of 'dict'" in err_msg + assert "an instance of 'list'" not in err_msg + + +def test_hidden_stroptions(): + """Check that we can have 2 StrOptions constraints, one being hidden.""" + + @validate_params( + {"param": [StrOptions({"auto"}), Hidden(StrOptions({"warn"}))]}, + prefer_skip_nested_validation=True, + ) + def f(param): + pass + + # "auto" and "warn" are valid params + f("auto") + f("warn") + + with pytest.raises( + InvalidParameterError, match="The 'param' parameter" + ) as exc_info: + f(param="bad") + + # the "warn" option is not exposed in the error message + err_msg = str(exc_info.value) + assert "auto" in err_msg + assert "warn" not in err_msg + + +def test_validate_params_set_param_constraints_attribute(): + """Check that the validate_params decorator properly sets the parameter constraints + as attribute of the decorated function/method. + """ + assert hasattr(_func, "_skl_parameter_constraints") + assert hasattr(_Class()._method, "_skl_parameter_constraints") + + +def test_boolean_constraint_deprecated_int(): + """Check that validate_params raise a deprecation message but still passes + validation when using an int for a parameter accepting a boolean. + """ + + @validate_params({"param": ["boolean"]}, prefer_skip_nested_validation=True) + def f(param): + pass + + # True/False and np.bool_(True/False) are valid params + f(True) + f(np.bool_(False)) + + +def test_no_validation(): + """Check that validation can be skipped for a parameter.""" + + @validate_params( + {"param1": [int, None], "param2": "no_validation"}, + prefer_skip_nested_validation=True, + ) + def f(param1=None, param2=None): + pass + + # param1 is validated + with pytest.raises(InvalidParameterError, match="The 'param1' parameter"): + f(param1="wrong") + + # param2 is not validated: any type is valid. + class SomeType: + pass + + f(param2=SomeType) + f(param2=SomeType()) + + +def test_pandas_na_constraint_with_pd_na(): + """Add a specific test for checking support for `pandas.NA`.""" + pd = pytest.importorskip("pandas") + + na_constraint = _PandasNAConstraint() + assert na_constraint.is_satisfied_by(pd.NA) + assert not na_constraint.is_satisfied_by(np.array([1, 2, 3])) + + +def test_iterable_not_string(): + """Check that a string does not satisfy the _IterableNotString constraint.""" + constraint = _IterablesNotString() + assert constraint.is_satisfied_by([1, 2, 3]) + assert constraint.is_satisfied_by(range(10)) + assert not constraint.is_satisfied_by("some string") + + +def test_cv_objects(): + """Check that the _CVObjects constraint accepts all current ways + to pass cv objects.""" + constraint = _CVObjects() + assert constraint.is_satisfied_by(5) + assert constraint.is_satisfied_by(LeaveOneOut()) + assert constraint.is_satisfied_by([([1, 2], [3, 4]), ([3, 4], [1, 2])]) + assert constraint.is_satisfied_by(None) + assert not constraint.is_satisfied_by("not a CV object") + + +def test_third_party_estimator(): + """Check that the validation from a scikit-learn estimator inherited by a third + party estimator does not impose a match between the dict of constraints and the + parameters of the estimator. + """ + + class ThirdPartyEstimator(_Estimator): + def __init__(self, b): + self.b = b + super().__init__(a=0) + + def fit(self, X=None, y=None): + super().fit(X, y) + + # does not raise, even though "b" is not in the constraints dict and "a" is not + # a parameter of the estimator. + ThirdPartyEstimator(b=0).fit() + + +def test_interval_real_not_int(): + """Check for the type RealNotInt in the Interval constraint.""" + constraint = Interval(RealNotInt, 0, 1, closed="both") + assert constraint.is_satisfied_by(1.0) + assert not constraint.is_satisfied_by(1) + + +def test_real_not_int(): + """Check for the RealNotInt type.""" + assert isinstance(1.0, RealNotInt) + assert not isinstance(1, RealNotInt) + assert isinstance(np.float64(1), RealNotInt) + assert not isinstance(np.int64(1), RealNotInt) + + +def test_skip_param_validation(): + """Check that param validation can be skipped using config_context.""" + + @validate_params({"a": [int]}, prefer_skip_nested_validation=True) + def f(a): + pass + + with pytest.raises(InvalidParameterError, match="The 'a' parameter"): + f(a="1") + + # does not raise + with config_context(skip_parameter_validation=True): + f(a="1") + + +@pytest.mark.parametrize("prefer_skip_nested_validation", [True, False]) +def test_skip_nested_validation(prefer_skip_nested_validation): + """Check that nested validation can be skipped.""" + + @validate_params({"a": [int]}, prefer_skip_nested_validation=True) + def f(a): + pass + + @validate_params( + {"b": [int]}, + prefer_skip_nested_validation=prefer_skip_nested_validation, + ) + def g(b): + # calls f with a bad parameter type + return f(a="invalid_param_value") + + # Validation for g is never skipped. + with pytest.raises(InvalidParameterError, match="The 'b' parameter"): + g(b="invalid_param_value") + + if prefer_skip_nested_validation: + g(b=1) # does not raise because inner f is not validated + else: + with pytest.raises(InvalidParameterError, match="The 'a' parameter"): + g(b=1) + + +@pytest.mark.parametrize( + "skip_parameter_validation, prefer_skip_nested_validation, expected_skipped", + [ + (True, True, True), + (True, False, True), + (False, True, True), + (False, False, False), + ], +) +def test_skip_nested_validation_and_config_context( + skip_parameter_validation, prefer_skip_nested_validation, expected_skipped +): + """Check interaction between global skip and local skip.""" + + @validate_params( + {"a": [int]}, prefer_skip_nested_validation=prefer_skip_nested_validation + ) + def g(a): + return get_config()["skip_parameter_validation"] + + with config_context(skip_parameter_validation=skip_parameter_validation): + actual_skipped = g(1) + + assert actual_skipped == expected_skipped diff --git a/shared/package-files/7c/7c0c295f48443337b9695e7b04feeb8c12f046265adc08defcd5e2ff7a35eb00/blob b/shared/package-files/7c/7c0c295f48443337b9695e7b04feeb8c12f046265adc08defcd5e2ff7a35eb00/blob new file mode 100644 index 0000000000000000000000000000000000000000..f0cb3100f7c4ad2e488c20bdfaac3833e0a136dd --- /dev/null +++ b/shared/package-files/7c/7c0c295f48443337b9695e7b04feeb8c12f046265adc08defcd5e2ff7a35eb00/blob @@ -0,0 +1,111 @@ +import os +from pathlib import Path +from typing import List, Tuple, Union + +import torchaudio +from torch import Tensor +from torch.utils.data import Dataset +from torchaudio._internal import download_url_to_file +from torchaudio.datasets.librispeech import _get_librispeech_metadata +from torchaudio.datasets.utils import _extract_tar + + +_ARCHIVE_NAME = "librispeech_finetuning" +_URL = "https://dl.fbaipublicfiles.com/librilight/data/librispeech_finetuning.tgz" +_CHECKSUM = "5d1efdc777b548194d7e09ba89126e2188026df9fd57aa57eb14408d2b2342af" +_SUBSET_MAP = {"10min": ["1h/0"], "1h": ["1h/*"], "10h": ["1h/*", "9h"]} + + +def _get_fileids_paths(path: Path, folders: List[str], _ext_audio: str) -> List[Tuple[str, str]]: + """Get the file names and the corresponding file paths without `speaker_id` + and `chapter_id` directories. + The format of path is like: + {root}/{_ARCHIVE_NAME}/1h/[0-5]/[clean, other] or + {root}/{_ARCHIVE_NAME}/9h/[clean, other] + + Args: + path (Path): Root path to the dataset. + folders (List[str]): Folders that contain the desired audio files. + _ext_audio (str): Extension of audio files. + + Returns: + List[Tuple[str, str]]: + List of tuples where the first element is the relative path to the audio file. + The format of relative path is like: + 1h/[0-5]/[clean, other] or 9h/[clean, other] + The second element is the file name without audio extension. + """ + + path = Path(path) + files_paths = [] + for folder in folders: + paths = [p.relative_to(path) for p in path.glob(f"{folder}/*/*/*/*{_ext_audio}")] + files_paths += [(str(p.parent.parent.parent), str(p.stem)) for p in paths] # get subset folder and file name + files_paths.sort(key=lambda x: x[0] + x[1]) + return files_paths + + +class LibriLightLimited(Dataset): + """Subset of Libri-light :cite:`librilight` dataset, + which was used in HuBERT :cite:`hsu2021hubert` for supervised fine-tuning. + + Args: + root (str or Path): Path to the directory where the dataset is found or downloaded. + subset (str, optional): The subset to use. Options: [``"10min"``, ``"1h"``, ``"10h"``] + (Default: ``"10min"``). + download (bool, optional): + Whether to download the dataset if it is not found at root path. (default: ``False``). + """ + + _ext_txt = ".trans.txt" + _ext_audio = ".flac" + + def __init__( + self, + root: Union[str, Path], + subset: str = "10min", + download: bool = False, + ) -> None: + if subset not in _SUBSET_MAP: + raise ValueError(f"`subset` must be one of {_SUBSET_MAP.keys()}. Found: {subset}") + folders = _SUBSET_MAP[subset] + + root = os.fspath(root) + self._path = os.path.join(root, _ARCHIVE_NAME) + archive = os.path.join(root, f"{_ARCHIVE_NAME}.tgz") + if not os.path.isdir(self._path): + if not download: + raise RuntimeError("Dataset not found. Please use `download=True` to download") + if not os.path.isfile(archive): + download_url_to_file(_URL, archive, hash_prefix=_CHECKSUM) + _extract_tar(archive) + self._fileids_paths = _get_fileids_paths(self._path, folders, self._ext_audio) + + def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int]: + """Load the n-th sample from the dataset. + + Args: + n (int): The index of the sample to be loaded + Returns: + Tuple of the following items; + + Tensor: + Waveform + int: + Sample rate + str: + Transcript + int: + Speaker ID + int: + Chapter ID + int: + Utterance ID + """ + file_path, fileid = self._fileids_paths[n] + metadata = _get_librispeech_metadata(fileid, self._path, file_path, self._ext_audio, self._ext_txt) + waveform, _ = torchaudio.load(os.path.join(self._path, metadata[0])) + return (waveform,) + metadata[1:] + + def __len__(self) -> int: + return len(self._fileids_paths) diff --git a/shared/package-files/7c/7c0dffa2f25c3eaaf04f66cf8e677871218f0f2546e8748cf683f4ec73f547fb/blob b/shared/package-files/7c/7c0dffa2f25c3eaaf04f66cf8e677871218f0f2546e8748cf683f4ec73f547fb/blob new file mode 100644 index 0000000000000000000000000000000000000000..2962f511ff1473978ca9fb624e202094474b00dd --- /dev/null +++ b/shared/package-files/7c/7c0dffa2f25c3eaaf04f66cf8e677871218f0f2546e8748cf683f4ec73f547fb/blob @@ -0,0 +1,255 @@ +from functools import reduce +from math import prod + +from sympy.core.numbers import igcdex, igcd +from sympy.ntheory.primetest import isprime +from sympy.polys.domains import ZZ +from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2 +from sympy.utilities.misc import as_int + + +def symmetric_residue(a, m): + """Return the residual mod m such that it is within half of the modulus. + + >>> from sympy.ntheory.modular import symmetric_residue + >>> symmetric_residue(1, 6) + 1 + >>> symmetric_residue(4, 6) + -2 + """ + if a <= m // 2: + return a + return a - m + + +def crt(m, v, symmetric=False, check=True): + r"""Chinese Remainder Theorem. + + The moduli in m are assumed to be pairwise coprime. The output + is then an integer f, such that f = v_i mod m_i for each pair out + of v and m. If ``symmetric`` is False a positive integer will be + returned, else \|f\| will be less than or equal to the LCM of the + moduli, and thus f may be negative. + + If the moduli are not co-prime the correct result will be returned + if/when the test of the result is found to be incorrect. This result + will be None if there is no solution. + + The keyword ``check`` can be set to False if it is known that the moduli + are coprime. + + Examples + ======== + + As an example consider a set of residues ``U = [49, 76, 65]`` + and a set of moduli ``M = [99, 97, 95]``. Then we have:: + + >>> from sympy.ntheory.modular import crt + + >>> crt([99, 97, 95], [49, 76, 65]) + (639985, 912285) + + This is the correct result because:: + + >>> [639985 % m for m in [99, 97, 95]] + [49, 76, 65] + + If the moduli are not co-prime, you may receive an incorrect result + if you use ``check=False``: + + >>> crt([12, 6, 17], [3, 4, 2], check=False) + (954, 1224) + >>> [954 % m for m in [12, 6, 17]] + [6, 0, 2] + >>> crt([12, 6, 17], [3, 4, 2]) is None + True + >>> crt([3, 6], [2, 5]) + (5, 6) + + Note: the order of gf_crt's arguments is reversed relative to crt, + and that solve_congruence takes residue, modulus pairs. + + Programmer's note: rather than checking that all pairs of moduli share + no GCD (an O(n**2) test) and rather than factoring all moduli and seeing + that there is no factor in common, a check that the result gives the + indicated residuals is performed -- an O(n) operation. + + See Also + ======== + + solve_congruence + sympy.polys.galoistools.gf_crt : low level crt routine used by this routine + """ + if check: + m = list(map(as_int, m)) + v = list(map(as_int, v)) + + result = gf_crt(v, m, ZZ) + mm = prod(m) + + if check: + if not all(v % m == result % m for v, m in zip(v, m)): + result = solve_congruence(*list(zip(v, m)), + check=False, symmetric=symmetric) + if result is None: + return result + result, mm = result + + if symmetric: + return symmetric_residue(result, mm), mm + return result, mm + + +def crt1(m): + """First part of Chinese Remainder Theorem, for multiple application. + + Examples + ======== + + >>> from sympy.ntheory.modular import crt1 + >>> crt1([18, 42, 6]) + (4536, [252, 108, 756], [0, 2, 0]) + """ + + return gf_crt1(m, ZZ) + + +def crt2(m, v, mm, e, s, symmetric=False): + """Second part of Chinese Remainder Theorem, for multiple application. + + Examples + ======== + + >>> from sympy.ntheory.modular import crt1, crt2 + >>> mm, e, s = crt1([18, 42, 6]) + >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s) + (0, 4536) + """ + + result = gf_crt2(v, m, mm, e, s, ZZ) + + if symmetric: + return symmetric_residue(result, mm), mm + return result, mm + + +def solve_congruence(*remainder_modulus_pairs, **hint): + """Compute the integer ``n`` that has the residual ``ai`` when it is + divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to + this function: ((a1, m1), (a2, m2), ...). If there is no solution, + return None. Otherwise return ``n`` and its modulus. + + The ``mi`` values need not be co-prime. If it is known that the moduli are + not co-prime then the hint ``check`` can be set to False (default=True) and + the check for a quicker solution via crt() (valid when the moduli are + co-prime) will be skipped. + + If the hint ``symmetric`` is True (default is False), the value of ``n`` + will be within 1/2 of the modulus, possibly negative. + + Examples + ======== + + >>> from sympy.ntheory.modular import solve_congruence + + What number is 2 mod 3, 3 mod 5 and 2 mod 7? + + >>> solve_congruence((2, 3), (3, 5), (2, 7)) + (23, 105) + >>> [23 % m for m in [3, 5, 7]] + [2, 3, 2] + + If you prefer to work with all remainder in one list and + all moduli in another, send the arguments like this: + + >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7))) + (23, 105) + + The moduli need not be co-prime; in this case there may or + may not be a solution: + + >>> solve_congruence((2, 3), (4, 6)) is None + True + + >>> solve_congruence((2, 3), (5, 6)) + (5, 6) + + The symmetric flag will make the result be within 1/2 of the modulus: + + >>> solve_congruence((2, 3), (5, 6), symmetric=True) + (-1, 6) + + See Also + ======== + + crt : high level routine implementing the Chinese Remainder Theorem + + """ + def combine(c1, c2): + """Return the tuple (a, m) which satisfies the requirement + that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution + """ + a1, m1 = c1 + a2, m2 = c2 + a, b, c = m1, a2 - a1, m2 + g = reduce(igcd, [a, b, c]) + a, b, c = [i//g for i in [a, b, c]] + if a != 1: + inv_a, _, g = igcdex(a, c) + if g != 1: + return None + b *= inv_a + a, m = a1 + m1*b, m1*c + return a, m + + rm = remainder_modulus_pairs + symmetric = hint.get('symmetric', False) + + if hint.get('check', True): + rm = [(as_int(r), as_int(m)) for r, m in rm] + + # ignore redundant pairs but raise an error otherwise; also + # make sure that a unique set of bases is sent to gf_crt if + # they are all prime. + # + # The routine will work out less-trivial violations and + # return None, e.g. for the pairs (1,3) and (14,42) there + # is no answer because 14 mod 42 (having a gcd of 14) implies + # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14) + # which, being 0 mod 3, is inconsistent with 1 mod 3. But to + # preprocess the input beyond checking of another pair with 42 + # or 3 as the modulus (for this example) is not necessary. + uniq = {} + for r, m in rm: + r %= m + if m in uniq: + if r != uniq[m]: + return None + continue + uniq[m] = r + rm = [(r, m) for m, r in uniq.items()] + del uniq + + # if the moduli are co-prime, the crt will be significantly faster; + # checking all pairs for being co-prime gets to be slow but a prime + # test is a good trade-off + if all(isprime(m) for r, m in rm): + r, m = list(zip(*rm)) + return crt(m, r, symmetric=symmetric, check=False) + + rv = (0, 1) + for rmi in rm: + rv = combine(rv, rmi) + if rv is None: + break + n, m = rv + n = n % m + else: + if symmetric: + return symmetric_residue(n, m), m + return n, m diff --git a/shared/package-files/7c/7c0f114b23205230865dbb7c51a67c17cca2566119ff2c9ad0a7c687e03319bb/blob b/shared/package-files/7c/7c0f114b23205230865dbb7c51a67c17cca2566119ff2c9ad0a7c687e03319bb/blob new file mode 100644 index 0000000000000000000000000000000000000000..bda09bad6fe84d07da36e3056974264c89e482b1 --- /dev/null +++ b/shared/package-files/7c/7c0f114b23205230865dbb7c51a67c17cca2566119ff2c9ad0a7c687e03319bb/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c0f114b23205230865dbb7c51a67c17cca2566119ff2c9ad0a7c687e03319bb +size 424802 diff --git a/shared/package-files/7c/7c0f5fc19a95400a78a0508aff291ccd2d2ce74aea7aa5ce967024a63d495913/blob b/shared/package-files/7c/7c0f5fc19a95400a78a0508aff291ccd2d2ce74aea7aa5ce967024a63d495913/blob new file mode 100644 index 0000000000000000000000000000000000000000..de8153e19c01f1a5fad4d3af807e1fe9eb346f17 --- /dev/null +++ b/shared/package-files/7c/7c0f5fc19a95400a78a0508aff291ccd2d2ce74aea7aa5ce967024a63d495913/blob @@ -0,0 +1,249 @@ +from datetime import timedelta +import logging +import os +import threading +import warnings +from typing import Generator, Tuple +from urllib.parse import urlparse + +import torch +import torch.distributed as dist + +logger = logging.getLogger(__name__) + + +_init_counter = 0 +_init_counter_lock = threading.Lock() + +__all__ = ["is_available"] + +def is_available() -> bool: + return hasattr(torch._C, "_rpc_init") + + +if is_available() and not torch._C._rpc_init(): + raise RuntimeError("Failed to initialize torch.distributed.rpc") + + +if is_available(): + from torch._C._distributed_c10d import Store + from torch._C._distributed_rpc import ( + _disable_jit_rref_pickle, + _enable_jit_rref_pickle, + _disable_server_process_global_profiler, + _enable_server_process_global_profiler, + _set_and_start_rpc_agent, + _reset_current_rpc_agent, + _delete_all_user_and_unforked_owner_rrefs, + _destroy_rref_context, + _set_profiler_node_id, + _is_current_rpc_agent_set, + _rref_context_get_debug_info, + _cleanup_python_rpc_handler, + _invoke_rpc_builtin, + _invoke_rpc_python_udf, + _invoke_rpc_torchscript, + _invoke_remote_builtin, + _invoke_remote_python_udf, + _invoke_remote_torchscript, + _set_rpc_timeout, + _get_current_rpc_agent, + get_rpc_timeout, + enable_gil_profiling, + RpcBackendOptions, + _TensorPipeRpcBackendOptionsBase, + RpcAgent, + PyRRef, + TensorPipeAgent, + RemoteProfilerManager, + WorkerInfo, + _DEFAULT_INIT_METHOD, + _DEFAULT_NUM_WORKER_THREADS, + _UNSET_RPC_TIMEOUT, + _DEFAULT_RPC_TIMEOUT_SEC, + ) # noqa: F401 + + from . import api, backend_registry, functions + from .api import * # noqa: F401,F403 + import numbers + + import torch.distributed.autograd as dist_autograd + + from .backend_registry import BackendType + from .options import TensorPipeRpcBackendOptions # noqa: F401 + from .server_process_global_profiler import ( + _server_process_global_profile, + ) + + rendezvous_iterator: Generator[Tuple[Store, int, int], None, None] + + __all__ += ["init_rpc", "BackendType", "TensorPipeRpcBackendOptions"] + __all__ = __all__ + api.__all__ + backend_registry.__all__ # noqa: PLE0605 + + def init_rpc( + name, + backend=None, + rank=-1, + world_size=None, + rpc_backend_options=None, + ): + r""" + Initializes RPC primitives such as the local RPC agent + and distributed autograd, which immediately makes the current + process ready to send and receive RPCs. + + Args: + name (str): a globally unique name of this node. (e.g., + ``Trainer3``, ``ParameterServer2``, ``Master``, ``Worker1``) + Name can only contain number, alphabet, underscore, colon, + and/or dash, and must be shorter than 128 characters. + backend (BackendType, optional): The type of RPC backend + implementation. Supported values is + ``BackendType.TENSORPIPE`` (the default). + See :ref:`rpc-backends` for more information. + rank (int): a globally unique id/rank of this node. + world_size (int): The number of workers in the group. + rpc_backend_options (RpcBackendOptions, optional): The options + passed to the RpcAgent constructor. It must be an agent-specific + subclass of :class:`~torch.distributed.rpc.RpcBackendOptions` + and contains agent-specific initialization configurations. By + default, for all agents, it sets the default timeout to 60 + seconds and performs the rendezvous with an underlying process + group initialized using ``init_method = "env://"``, + meaning that environment variables ``MASTER_ADDR`` and + ``MASTER_PORT`` need to be set properly. See + :ref:`rpc-backends` for more information and find which options + are available. + """ + torch._C._log_api_usage_once("torch.distributed.init_rpc") + if backend is not None and not isinstance( + backend, backend_registry.BackendType + ): + raise TypeError("Argument backend must be a member of BackendType") + + if rpc_backend_options is not None and not isinstance( + rpc_backend_options, RpcBackendOptions + ): + raise TypeError( + "Argument rpc_backend_options must be an instance of RpcBackendOptions" + ) + + # Try to detect the backend from the options + if backend is None and rpc_backend_options is not None: + for candidate_backend in BackendType: + if isinstance( + rpc_backend_options, + type( + backend_registry.construct_rpc_backend_options( + candidate_backend + ) + ), + ): + backend = candidate_backend + break + else: + raise TypeError( + f"Could not infer backend for options {rpc_backend_options}" + ) + # Ignore type error because mypy doesn't handle dynamically generated type objects (#4865) + if backend != BackendType.TENSORPIPE: # type: ignore[attr-defined] + logger.warning( + "RPC was initialized with no explicit backend but with options " # type: ignore[attr-defined] + "corresponding to %(backend)s, hence that backend will be used " + "instead of the default BackendType.TENSORPIPE. To silence this " + "warning pass `backend=%(backend)s` explicitly.", + {'backend': backend} + ) + + if backend is None: + backend = BackendType.TENSORPIPE # type: ignore[attr-defined] + + if rpc_backend_options is None: + # default construct a set of RPC backend options. + rpc_backend_options = backend_registry.construct_rpc_backend_options( + backend + ) + + # Create store, performs rendezvous for static RPC group. + if not world_size: + # If world_size is not set in construction and also not set in environment variables + # The store will be created for the dynamic group setting + store = dist._create_store_from_options(rpc_backend_options, rank) + else: + # This rendezvous state sometimes is destroyed before all processes + # finishing handshaking. To avoid that issue, we make it global to + # keep it alive. + global rendezvous_iterator + rendezvous_iterator = dist.rendezvous( + rpc_backend_options.init_method, rank=rank, world_size=world_size + ) + store, _, _ = next(rendezvous_iterator) + # Use same timeout as RPC. + store.set_timeout(timedelta(seconds=rpc_backend_options.rpc_timeout)) + + # Use a PrefixStore to distinguish multiple invocations. + with _init_counter_lock: + global _init_counter + store = dist.PrefixStore(str(f"rpc_prefix_{_init_counter}"), store) + _init_counter += 1 + + # Initialize autograd before RPC since _init_rpc_backend guarantees all + # processes sync via the store. If we initialize autograd after RPC, + # there could be a race where some nodes might have initialized autograd + # and others might not have. As a result, a node calling + # torch.distributed.autograd.backward() would run into errors since + # other nodes might not have been initialized. + dist_autograd._init(rank) + + _set_profiler_node_id(rank) + # Initialize RPC. + _init_rpc_backend(backend, store, name, rank, world_size, rpc_backend_options) + + def _validate_rpc_args(backend, store, name, rank, world_size, rpc_backend_options): + type_mapping = { + backend: backend_registry.BackendType, + store: dist.Store, + name: str, + rank: numbers.Integral, + # world_size can be None for a dynamic group + world_size: (numbers.Integral, type(None)), + rpc_backend_options: RpcBackendOptions, + } + for arg, arg_type in type_mapping.items(): + if not isinstance(arg, arg_type): # type: ignore[arg-type] + raise RuntimeError( + f"Argument {arg} must be of type {arg_type} but got type {type(arg)}" + ) + + def _init_rpc_backend( + backend=BackendType.TENSORPIPE, # type: ignore[attr-defined] + store=None, + name=None, + rank=-1, + world_size=None, + rpc_backend_options=None, + ): + + _validate_rpc_args(backend, store, name, rank, world_size, rpc_backend_options) + + if _is_current_rpc_agent_set(): + raise RuntimeError("RPC is already initialized") + + # Initialize RPC. + rpc_agent = backend_registry.init_backend( + backend, + store=store, + name=name, + rank=rank, + world_size=world_size, + rpc_backend_options=rpc_backend_options, + ) + + api._init_rpc_states(rpc_agent) + + @api._require_initialized + def _get_debug_info(): + info = _rref_context_get_debug_info() + info.update(api._get_current_rpc_agent().get_debug_info()) + info.update(dist_autograd._get_debug_info()) + return info diff --git a/shared/package-files/7c/7c113202ef734cc1eef68be0c0ec2fee412c958858dfcb1dd06351efc77e1028/blob b/shared/package-files/7c/7c113202ef734cc1eef68be0c0ec2fee412c958858dfcb1dd06351efc77e1028/blob new file mode 100644 index 0000000000000000000000000000000000000000..a6d3546e57c68b75fb4e3abfae76440ab2474491 --- /dev/null +++ b/shared/package-files/7c/7c113202ef734cc1eef68be0c0ec2fee412c958858dfcb1dd06351efc77e1028/blob @@ -0,0 +1,2212 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import bz2 +from contextlib import contextmanager +from io import (BytesIO, StringIO, TextIOWrapper, BufferedIOBase, IOBase) +import itertools +import gc +import gzip +import math +import os +import pathlib +import pytest +import random +import sys +import tempfile +import weakref + +try: + import numpy as np +except ImportError: + np = None + +from pyarrow.util import guid +from pyarrow import Codec +import pyarrow as pa + + +def check_large_seeks(file_factory, expected_error=None): + if sys.platform in ('win32', 'darwin', 'emscripten'): + pytest.skip("need sparse file support") + try: + filename = tempfile.mktemp(prefix='test_io') + with open(filename, 'wb') as f: + f.truncate(2 ** 32 + 10) + f.seek(2 ** 32 + 5) + f.write(b'mark\n') + if expected_error: + with expected_error: + file_factory(filename) + else: + with file_factory(filename) as f: + assert f.size() == 2 ** 32 + 10 + assert f.seek(2 ** 32 + 5) == 2 ** 32 + 5 + assert f.tell() == 2 ** 32 + 5 + assert f.read(5) == b'mark\n' + assert f.tell() == 2 ** 32 + 10 + finally: + os.unlink(filename) + + +@contextmanager +def assert_file_not_found(): + with pytest.raises(FileNotFoundError): + yield + + +# ---------------------------------------------------------------------- +# Python file-like objects + + +def test_python_file_write(): + buf = BytesIO() + + f = pa.PythonFile(buf) + + assert f.tell() == 0 + + s1 = b'enga\xc3\xb1ado' + s2 = b'foobar' + + f.write(s1) + assert f.tell() == len(s1) + + f.write(s2) + + expected = s1 + s2 + + result = buf.getvalue() + assert result == expected + + assert not f.closed + f.close() + assert f.closed + + with pytest.raises(TypeError, match="binary file expected"): + pa.PythonFile(StringIO()) + + +def test_python_file_read(): + data = b'some sample data' + + buf = BytesIO(data) + f = pa.PythonFile(buf, mode='r') + + assert f.size() == len(data) + + assert f.tell() == 0 + + assert f.read(4) == b'some' + assert f.tell() == 4 + + f.seek(0) + assert f.tell() == 0 + + f.seek(5) + assert f.tell() == 5 + + v = f.read(50) + assert v == b'sample data' + assert len(v) == 11 + + assert f.size() == len(data) + + assert not f.closed + f.close() + assert f.closed + + with pytest.raises(TypeError, match="binary file expected"): + pa.PythonFile(StringIO(), mode='r') + + +@pytest.mark.parametrize("nbytes", (-1, 0, 1, 5, 100)) +@pytest.mark.parametrize("file_offset", (-1, 0, 5, 100)) +def test_python_file_get_stream(nbytes, file_offset): + + data = b'data1data2data3data4data5' + + f = pa.PythonFile(BytesIO(data), mode='r') + + # negative nbytes or offsets don't make sense here, raise ValueError + if nbytes < 0 or file_offset < 0: + with pytest.raises(pa.ArrowInvalid, + match="should be a positive value"): + f.get_stream(file_offset=file_offset, nbytes=nbytes) + f.close() + return + else: + stream = f.get_stream(file_offset=file_offset, nbytes=nbytes) + + # Subsequent calls to 'read' should match behavior if same + # data passed to BytesIO where get_stream should handle if + # nbytes/file_offset results in no bytes b/c out of bounds. + start = min(file_offset, len(data)) + end = min(file_offset + nbytes, len(data)) + buf = BytesIO(data[start:end]) + + # read some chunks + assert stream.read(nbytes=4) == buf.read(4) + assert stream.read(nbytes=6) == buf.read(6) + + # Read to end of each stream + assert stream.read() == buf.read() + + # Try reading past the stream + n = len(data) * 2 + assert stream.read(n) == buf.read(n) + + # NativeFile[CInputStream] is not seekable + with pytest.raises(OSError, match="seekable"): + stream.seek(0) + + stream.close() + assert stream.closed + + +def test_python_file_read_at(): + data = b'some sample data' + + buf = BytesIO(data) + f = pa.PythonFile(buf, mode='r') + + # test simple read at + v = f.read_at(nbytes=5, offset=3) + assert v == b'e sam' + assert len(v) == 5 + + # test reading entire file when nbytes > len(file) + w = f.read_at(nbytes=50, offset=0) + assert w == data + assert len(w) == 16 + + +def test_python_file_readall(): + data = b'some sample data' + + buf = BytesIO(data) + with pa.PythonFile(buf, mode='r') as f: + assert f.readall() == data + + +def test_python_file_readinto(): + length = 10 + data = b'some sample data longer than 10' + dst_buf = bytearray(length) + src_buf = BytesIO(data) + + with pa.PythonFile(src_buf, mode='r') as f: + assert f.readinto(dst_buf) == 10 + + assert dst_buf[:length] == data[:length] + assert len(dst_buf) == length + + +def test_python_file_read_buffer(): + length = 10 + data = b'0123456798' + dst_buf = bytearray(data) + + class DuckReader: + def close(self): + pass + + @property + def closed(self): + return False + + def read_buffer(self, nbytes): + assert nbytes == length + return memoryview(dst_buf)[:nbytes] + + duck_reader = DuckReader() + with pa.PythonFile(duck_reader, mode='r') as f: + buf = f.read_buffer(length) + assert len(buf) == length + assert memoryview(buf).tobytes() == dst_buf[:length] + # buf should point to the same memory, so modifying it + memoryview(buf)[0] = ord(b'x') + # should modify the original + assert dst_buf[0] == ord(b'x') + + +def test_python_file_correct_abc(): + with pa.PythonFile(BytesIO(b''), mode='r') as f: + assert isinstance(f, BufferedIOBase) + assert isinstance(f, IOBase) + + +def test_python_file_iterable(): + data = b'''line1 + line2 + line3 + ''' + + buf = BytesIO(data) + buf2 = BytesIO(data) + + with pa.PythonFile(buf, mode='r') as f: + for read, expected in zip(f, buf2): + assert read == expected + + +def test_python_file_large_seeks(): + def factory(filename): + return pa.PythonFile(open(filename, 'rb')) + + check_large_seeks(factory) + + +def test_bytes_reader(): + # Like a BytesIO, but zero-copy underneath for C++ consumers + data = b'some sample data' + f = pa.BufferReader(data) + assert f.tell() == 0 + + assert f.size() == len(data) + + assert f.read(4) == b'some' + assert f.tell() == 4 + + f.seek(0) + assert f.tell() == 0 + + f.seek(0, 2) + assert f.tell() == len(data) + + f.seek(5) + assert f.tell() == 5 + + assert f.read(50) == b'sample data' + + assert not f.closed + f.close() + assert f.closed + + +def test_bytes_reader_non_bytes(): + with pytest.raises(TypeError): + pa.BufferReader('some sample data') + + +def test_bytes_reader_retains_parent_reference(): + import gc + + # ARROW-421 + def get_buffer(): + data = b'some sample data' * 1000 + reader = pa.BufferReader(data) + reader.seek(5) + return reader.read_buffer(6) + + buf = get_buffer() + gc.collect() + assert buf.to_pybytes() == b'sample' + assert buf.parent is not None + + +def test_python_file_implicit_mode(tmpdir): + path = os.path.join(str(tmpdir), 'foo.txt') + with open(path, 'wb') as f: + pf = pa.PythonFile(f) + assert pf.writable() + assert not pf.readable() + assert not pf.seekable() # PyOutputStream isn't seekable + f.write(b'foobar\n') + + with open(path, 'rb') as f: + pf = pa.PythonFile(f) + assert pf.readable() + assert not pf.writable() + assert pf.seekable() + assert pf.read() == b'foobar\n' + + bio = BytesIO() + pf = pa.PythonFile(bio) + assert pf.writable() + assert not pf.readable() + assert not pf.seekable() + pf.write(b'foobar\n') + assert bio.getvalue() == b'foobar\n' + + +def test_python_file_writelines(tmpdir): + lines = [b'line1\n', b'line2\n' b'line3'] + path = os.path.join(str(tmpdir), 'foo.txt') + with open(path, 'wb') as f: + try: + f = pa.PythonFile(f, mode='w') + assert f.writable() + f.writelines(lines) + finally: + f.close() + + with open(path, 'rb') as f: + try: + f = pa.PythonFile(f, mode='r') + assert f.readable() + assert f.read() == b''.join(lines) + finally: + f.close() + + +def test_python_file_closing(): + bio = BytesIO() + pf = pa.PythonFile(bio) + wr = weakref.ref(pf) + del pf + assert wr() is None # object was destroyed + assert not bio.closed + pf = pa.PythonFile(bio) + pf.close() + assert bio.closed + + +# ---------------------------------------------------------------------- +# Buffers + + +def check_buffer_pickling(buf, pickler): + # Check that buffer survives a pickle roundtrip + for protocol in range(0, pickler.HIGHEST_PROTOCOL + 1): + result = pickler.loads(pickler.dumps(buf, protocol=protocol)) + assert len(result) == len(buf) + assert memoryview(result) == memoryview(buf) + assert result.to_pybytes() == buf.to_pybytes() + assert result.is_mutable == buf.is_mutable + + +def test_buffer_bytes(pickle_module): + val = b'some data' + + buf = pa.py_buffer(val) + assert isinstance(buf, pa.Buffer) + assert not buf.is_mutable + assert buf.is_cpu + + result = buf.to_pybytes() + assert result == val + + check_buffer_pickling(buf, pickle_module) + + +def test_buffer_null_data(pickle_module): + null_buff = pa.foreign_buffer(address=0, size=0) + assert null_buff.to_pybytes() == b"" + assert null_buff.address == 0 + # ARROW-16048: we shouldn't expose a NULL address through the Python + # buffer protocol. + m = memoryview(null_buff) + assert m.tobytes() == b"" + assert pa.py_buffer(m).address != 0 + + check_buffer_pickling(null_buff, pickle_module) + + +def test_buffer_memoryview(pickle_module): + val = b'some data' + + buf = pa.py_buffer(val) + assert isinstance(buf, pa.Buffer) + assert not buf.is_mutable + assert buf.is_cpu + + result = memoryview(buf) + assert result == val + + check_buffer_pickling(buf, pickle_module) + + +def test_buffer_bytearray(pickle_module): + val = bytearray(b'some data') + + buf = pa.py_buffer(val) + assert isinstance(buf, pa.Buffer) + assert buf.is_mutable + assert buf.is_cpu + + result = bytearray(buf) + assert result == val + + check_buffer_pickling(buf, pickle_module) + + +def test_buffer_invalid(): + with pytest.raises(TypeError, + match="(bytes-like object|buffer interface)"): + pa.py_buffer(None) + + +def test_buffer_weakref(): + buf = pa.py_buffer(b'some data') + wr = weakref.ref(buf) + assert wr() is not None + del buf + assert wr() is None + + +@pytest.mark.parametrize('val, expected_hex_buffer', + [(b'check', b'636865636B'), + (b'\a0', b'0730'), + (b'', b'')]) +def test_buffer_hex(val, expected_hex_buffer): + buf = pa.py_buffer(val) + assert buf.hex() == expected_hex_buffer + + +@pytest.mark.numpy +def test_buffer_to_numpy(): + # Make sure creating a numpy array from an arrow buffer works + byte_array = bytearray(20) + byte_array[0] = 42 + buf = pa.py_buffer(byte_array) + array = np.frombuffer(buf, dtype="uint8") + assert array[0] == byte_array[0] + byte_array[0] += 1 + assert array[0] == byte_array[0] + assert array.base == buf + + +@pytest.mark.numpy +def test_buffer_from_numpy(): + # C-contiguous + arr = np.arange(12, dtype=np.int8).reshape((3, 4)) + buf = pa.py_buffer(arr) + assert buf.is_cpu + assert buf.is_mutable + assert buf.to_pybytes() == arr.tobytes() + # F-contiguous; note strides information is lost + buf = pa.py_buffer(arr.T) + assert buf.is_cpu + assert buf.is_mutable + assert buf.to_pybytes() == arr.tobytes() + # Non-contiguous + with pytest.raises(ValueError, match="not contiguous"): + buf = pa.py_buffer(arr.T[::2]) + + +@pytest.mark.numpy +def test_buffer_address(): + b1 = b'some data!' + b2 = bytearray(b1) + b3 = bytearray(b1) + + buf1 = pa.py_buffer(b1) + buf2 = pa.py_buffer(b1) + buf3 = pa.py_buffer(b2) + buf4 = pa.py_buffer(b3) + + assert buf1.address > 0 + assert buf1.address == buf2.address + assert buf3.address != buf2.address + assert buf4.address != buf3.address + + arr = np.arange(5) + buf = pa.py_buffer(arr) + assert buf.address == arr.ctypes.data + + +@pytest.mark.numpy +def test_buffer_equals(): + # Buffer.equals() returns true iff the buffers have the same contents + def eq(a, b): + assert a.equals(b) + assert a == b + assert not (a != b) + + def ne(a, b): + assert not a.equals(b) + assert not (a == b) + assert a != b + + b1 = b'some data!' + b2 = bytearray(b1) + b3 = bytearray(b1) + b3[0] = 42 + buf1 = pa.py_buffer(b1) + buf2 = pa.py_buffer(b2) + buf3 = pa.py_buffer(b2) + buf4 = pa.py_buffer(b3) + buf5 = pa.py_buffer(np.frombuffer(b2, dtype=np.int16)) + eq(buf1, buf1) + eq(buf1, buf2) + eq(buf2, buf3) + ne(buf2, buf4) + # Data type is indifferent + eq(buf2, buf5) + + +def test_buffer_eq_bytes(): + buf = pa.py_buffer(b'some data') + assert buf == b'some data' + assert buf == bytearray(b'some data') + assert buf != b'some dat1' + + with pytest.raises(TypeError): + buf == 'some data' + + +def test_buffer_getitem(): + data = bytearray(b'some data!') + buf = pa.py_buffer(data) + + n = len(data) + for ix in range(-n, n - 1): + assert buf[ix] == data[ix] + + with pytest.raises(IndexError): + buf[n] + + with pytest.raises(IndexError): + buf[-n - 1] + + +def test_buffer_slicing(): + data = b'some data!' + buf = pa.py_buffer(data) + + sliced = buf.slice(2) + expected = pa.py_buffer(b'me data!') + assert sliced.equals(expected) + + sliced2 = buf.slice(2, 4) + expected2 = pa.py_buffer(b'me d') + assert sliced2.equals(expected2) + + # 0 offset + assert buf.slice(0).equals(buf) + + # Slice past end of buffer + assert len(buf.slice(len(buf))) == 0 + + with pytest.raises(IndexError): + buf.slice(-1) + + with pytest.raises(IndexError): + buf.slice(len(buf) + 1) + assert buf[11:].to_pybytes() == b"" + + # Slice stop exceeds buffer length + with pytest.raises(IndexError): + buf.slice(1, len(buf)) + assert buf[1:11].to_pybytes() == buf.to_pybytes()[1:] + + # Negative length + with pytest.raises(IndexError): + buf.slice(1, -1) + + # Test slice notation + assert buf[2:].equals(buf.slice(2)) + assert buf[2:5].equals(buf.slice(2, 3)) + assert buf[-5:].equals(buf.slice(len(buf) - 5)) + assert buf[-5:-2].equals(buf.slice(len(buf) - 5, 3)) + + with pytest.raises(IndexError): + buf[::-1] + with pytest.raises(IndexError): + buf[::2] + + n = len(buf) + for start in range(-n * 2, n * 2): + for stop in range(-n * 2, n * 2): + assert buf[start:stop].to_pybytes() == buf.to_pybytes()[start:stop] + + +def test_buffer_hashing(): + # Buffers are unhashable + with pytest.raises(TypeError, match="unhashable"): + hash(pa.py_buffer(b'123')) + + +@pytest.mark.numpy +def test_buffer_protocol_respects_immutability(): + # ARROW-3228; NumPy's frombuffer ctor determines whether a buffer-like + # object is mutable by first attempting to get a mutable buffer using + # PyObject_FromBuffer. If that fails, it assumes that the object is + # immutable + a = b'12345' + arrow_ref = pa.py_buffer(a) + numpy_ref = np.frombuffer(arrow_ref, dtype=np.uint8) + assert not numpy_ref.flags.writeable + + +@pytest.mark.numpy +def test_foreign_buffer(): + obj = np.array([1, 2], dtype=np.int32) + addr = obj.__array_interface__["data"][0] + size = obj.nbytes + buf = pa.foreign_buffer(addr, size, obj) + wr = weakref.ref(obj) + del obj + assert np.frombuffer(buf, dtype=np.int32).tolist() == [1, 2] + assert wr() is not None + del buf + assert wr() is None + + +def test_allocate_buffer(): + buf = pa.allocate_buffer(100) + assert buf.size == 100 + assert buf.is_mutable + assert buf.parent is None + + bit = b'abcde' + writer = pa.FixedSizeBufferWriter(buf) + writer.write(bit) + + assert buf.to_pybytes()[:5] == bit + + +def test_allocate_buffer_resizable(): + buf = pa.allocate_buffer(100, resizable=True) + assert isinstance(buf, pa.ResizableBuffer) + + buf.resize(200) + assert buf.size == 200 + + +@pytest.mark.numpy +def test_non_cpu_buffer(pickle_module): + cuda = pytest.importorskip("pyarrow.cuda") + ctx = cuda.Context(0) + + data = np.array([b'testing']) + cuda_buf = ctx.buffer_from_data(data) + arr = pa.FixedSizeBinaryArray.from_buffers(pa.binary(7), 1, [None, cuda_buf]) + buf_on_gpu = arr.buffers()[1] + + assert buf_on_gpu.size == cuda_buf.size + assert buf_on_gpu.address == cuda_buf.address + assert buf_on_gpu.is_cpu == cuda_buf.is_cpu + assert buf_on_gpu.is_mutable + + repr1 = "" + assert repr1 in repr(buf_on_gpu) + assert repr2 in repr(buf_on_gpu) + + buf_on_gpu_sliced = buf_on_gpu.slice(2) + cuda_sliced = cuda.CudaBuffer.from_buffer(buf_on_gpu_sliced) + assert cuda_sliced.to_pybytes() == b'sting' + + buf_on_gpu_sliced = buf_on_gpu[2:4] + cuda_sliced = cuda.CudaBuffer.from_buffer(buf_on_gpu_sliced) + assert cuda_sliced.to_pybytes() == b'st' + + # Sliced buffers with same address + assert buf_on_gpu_sliced.equals(cuda_buf[2:4]) + + # Buffers on different devices + msg_device = "Device on which the data resides differs between buffers" + with pytest.raises(ValueError, match=msg_device): + buf_on_gpu.equals(pa.py_buffer(data)) + + msg = "Implemented only for data on CPU device" + # Buffers with different addresses + arr_short = np.array([b'sting']) + cuda_buf_short = ctx.buffer_from_data(arr_short) + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu_sliced.equals(cuda_buf_short) + arr_short = pa.FixedSizeBinaryArray.from_buffers( + pa.binary(5), 1, [None, cuda_buf_short] + ) + buf_on_gpu_short = arr_short.buffers()[1] + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu_sliced.equals(buf_on_gpu_short) + + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu.hex() + + with pytest.raises(NotImplementedError, match=msg): + cuda_buf.hex() + + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu[1] + + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu.to_pybytes() + + with pytest.raises(NotImplementedError, match=msg): + pickle_module.dumps(buf_on_gpu, protocol=4) + + with pytest.raises(NotImplementedError, match=msg): + pickle_module.dumps(cuda_buf, protocol=4) + + with pytest.raises(NotImplementedError, match=msg): + memoryview(buf_on_gpu) + + +def test_cache_options(): + opts1 = pa.CacheOptions() + opts2 = pa.CacheOptions(hole_size_limit=1024) + opts3 = pa.CacheOptions(hole_size_limit=4096, range_size_limit=8192) + opts4 = pa.CacheOptions(hole_size_limit=4096, + range_size_limit=8192, prefetch_limit=5) + opts5 = pa.CacheOptions(hole_size_limit=4096, + range_size_limit=8192, lazy=False) + opts6 = pa.CacheOptions.from_network_metrics(time_to_first_byte_millis=100, + transfer_bandwidth_mib_per_sec=200, + ideal_bandwidth_utilization_frac=0.9, + max_ideal_request_size_mib=64) + + assert opts1.hole_size_limit == 8192 + assert opts1.range_size_limit == 32 * 1024 * 1024 + assert opts1.lazy is True + assert opts1.prefetch_limit == 0 + + assert opts2.hole_size_limit == 1024 + assert opts2.range_size_limit == 32 * 1024 * 1024 + assert opts2.lazy is True + assert opts2.prefetch_limit == 0 + + assert opts3.hole_size_limit == 4096 + assert opts3.range_size_limit == 8192 + assert opts3.lazy is True + assert opts3.prefetch_limit == 0 + + assert opts4.hole_size_limit == 4096 + assert opts4.range_size_limit == 8192 + assert opts4.lazy is True + assert opts4.prefetch_limit == 5 + + assert opts5.hole_size_limit == 4096 + assert opts5.range_size_limit == 8192 + assert opts5.lazy is False + assert opts5.prefetch_limit == 0 + + assert opts6.lazy is False + + assert opts1 == opts1 + assert opts1 != opts2 + assert opts2 != opts3 + assert opts3 != opts4 + assert opts4 != opts5 + assert opts6 != opts1 + + +def test_cache_options_pickling(pickle_module): + options = [ + pa.CacheOptions(), + pa.CacheOptions(hole_size_limit=4096, range_size_limit=8192, + lazy=True, prefetch_limit=5), + ] + + for option in options: + assert pickle_module.loads(pickle_module.dumps(option)) == option + + +@pytest.mark.numpy +@pytest.mark.parametrize("compression", [ + pytest.param( + "bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) + ), + "brotli", + "gzip", + "lz4", + "zstd", + "snappy" +]) +def test_compress_decompress(compression): + if not Codec.is_available(compression): + pytest.skip(f"{compression} support is not built") + + INPUT_SIZE = 10000 + test_data = (np.random.randint(0, 255, size=INPUT_SIZE) + .astype(np.uint8) + .tobytes()) + test_buf = pa.py_buffer(test_data) + + compressed_buf = pa.compress(test_buf, codec=compression) + compressed_bytes = pa.compress(test_data, codec=compression, + asbytes=True) + + assert isinstance(compressed_bytes, bytes) + + decompressed_buf = pa.decompress(compressed_buf, INPUT_SIZE, + codec=compression) + decompressed_bytes = pa.decompress(compressed_bytes, INPUT_SIZE, + codec=compression, asbytes=True) + + assert isinstance(decompressed_bytes, bytes) + + assert decompressed_buf.equals(test_buf) + assert decompressed_bytes == test_data + + with pytest.raises(ValueError): + pa.decompress(compressed_bytes, codec=compression) + + +@pytest.mark.numpy +@pytest.mark.parametrize("compression", [ + pytest.param( + "bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) + ), + "brotli", + "gzip", + "lz4", + "zstd", + "snappy" +]) +def test_compression_level(compression): + if not Codec.is_available(compression): + pytest.skip(f"{compression} support is not built") + + codec = Codec(compression) + if codec.name == "snappy": + assert codec.compression_level is None + else: + assert isinstance(codec.compression_level, int) + + # These codecs do not support a compression level + no_level = ['snappy'] + if compression in no_level: + assert not Codec.supports_compression_level(compression) + with pytest.raises(ValueError): + Codec(compression, 0) + with pytest.raises(ValueError): + Codec.minimum_compression_level(compression) + with pytest.raises(ValueError): + Codec.maximum_compression_level(compression) + with pytest.raises(ValueError): + Codec.default_compression_level(compression) + return + + INPUT_SIZE = 10000 + test_data = (np.random.randint(0, 255, size=INPUT_SIZE) + .astype(np.uint8) + .tobytes()) + test_buf = pa.py_buffer(test_data) + + min_level = Codec.minimum_compression_level(compression) + max_level = Codec.maximum_compression_level(compression) + default_level = Codec.default_compression_level(compression) + + assert min_level < max_level + assert default_level >= min_level + assert default_level <= max_level + + for compression_level in range(min_level, max_level+1): + codec = Codec(compression, compression_level) + compressed_buf = codec.compress(test_buf) + compressed_bytes = codec.compress(test_data, asbytes=True) + assert isinstance(compressed_bytes, bytes) + decompressed_buf = codec.decompress(compressed_buf, INPUT_SIZE) + decompressed_bytes = codec.decompress(compressed_bytes, INPUT_SIZE, + asbytes=True) + + assert isinstance(decompressed_bytes, bytes) + + assert decompressed_buf.equals(test_buf) + assert decompressed_bytes == test_data + + with pytest.raises(ValueError): + codec.decompress(compressed_bytes) + + # The ability to set a seed this way is not present on older versions of + # numpy (currently in our python 3.6 CI build). Some inputs might just + # happen to compress the same between the two levels so using seeded + # random numbers is necessary to help get more reliable results + # + # The goal of this part is to ensure the compression_level is being + # passed down to the C++ layer, not to verify the compression algs + # themselves + if not hasattr(np.random, 'default_rng'): + pytest.skip('Requires newer version of numpy') + rng = np.random.default_rng(seed=42) + values = rng.integers(0, 100, 1000) + arr = pa.array(values) + hard_to_compress_buffer = arr.buffers()[1] + + weak_codec = Codec(compression, min_level) + weakly_compressed_buf = weak_codec.compress(hard_to_compress_buffer) + + strong_codec = Codec(compression, max_level) + strongly_compressed_buf = strong_codec.compress(hard_to_compress_buffer) + + assert len(weakly_compressed_buf) > len(strongly_compressed_buf) + + +def test_buffer_memoryview_is_immutable(): + val = b'some data' + + buf = pa.py_buffer(val) + assert not buf.is_mutable + assert isinstance(buf, pa.Buffer) + + result = memoryview(buf) + assert result.readonly + + with pytest.raises(TypeError) as exc: + result[0] = b'h' + assert 'cannot modify read-only' in str(exc.value) + + b = bytes(buf) + with pytest.raises(TypeError) as exc: + b[0] = b'h' + assert 'cannot modify read-only' in str(exc.value) + + +def test_uninitialized_buffer(): + # ARROW-2039: calling Buffer() directly creates an uninitialized object + # ARROW-2638: prevent calling extension class constructors directly + with pytest.raises(TypeError): + pa.Buffer() + + +def test_memory_output_stream(): + # 10 bytes + val = b'dataabcdef' + f = pa.BufferOutputStream() + + K = 1000 + for i in range(K): + f.write(val) + + buf = f.getvalue() + assert len(buf) == len(val) * K + assert buf.to_pybytes() == val * K + + +def test_inmemory_write_after_closed(): + f = pa.BufferOutputStream() + f.write(b'ok') + assert not f.closed + f.getvalue() + assert f.closed + + with pytest.raises(ValueError): + f.write(b'not ok') + + +def test_buffer_protocol_ref_counting(): + def make_buffer(bytes_obj): + return bytearray(pa.py_buffer(bytes_obj)) + + buf = make_buffer(b'foo') + gc.collect() + assert buf == b'foo' + + # ARROW-1053 + val = b'foo' + refcount_before = sys.getrefcount(val) + for i in range(10): + make_buffer(val) + gc.collect() + assert refcount_before == sys.getrefcount(val) + + +@pytest.mark.numpy +def test_nativefile_write_memoryview(): + f = pa.BufferOutputStream() + data = b'ok' + + arr = np.frombuffer(data, dtype='S1') + + f.write(arr) + f.write(bytearray(data)) + f.write(pa.py_buffer(data)) + with pytest.raises(TypeError): + f.write(data.decode('utf8')) + + buf = f.getvalue() + + assert buf.to_pybytes() == data * 3 + + +# ---------------------------------------------------------------------- +# Mock output stream + + +def test_mock_output_stream(): + # Make sure that the MockOutputStream and the BufferOutputStream record the + # same size + + # 10 bytes + val = b'dataabcdef' + + f1 = pa.MockOutputStream() + f2 = pa.BufferOutputStream() + + K = 1000 + for i in range(K): + f1.write(val) + f2.write(val) + + assert f1.size() == len(f2.getvalue()) + + # Do the same test with a table + record_batch = pa.RecordBatch.from_arrays([pa.array([1, 2, 3])], ['a']) + + f1 = pa.MockOutputStream() + f2 = pa.BufferOutputStream() + + stream_writer1 = pa.RecordBatchStreamWriter(f1, record_batch.schema) + stream_writer2 = pa.RecordBatchStreamWriter(f2, record_batch.schema) + + stream_writer1.write_batch(record_batch) + stream_writer2.write_batch(record_batch) + stream_writer1.close() + stream_writer2.close() + + assert f1.size() == len(f2.getvalue()) + + +# ---------------------------------------------------------------------- +# OS files and memory maps + + +@pytest.fixture +def sample_disk_data(request, tmpdir): + SIZE = 4096 + arr = [random.randint(0, 255) for _ in range(SIZE)] + data = bytes(arr[:SIZE]) + + path = os.path.join(str(tmpdir), guid()) + + with open(path, 'wb') as f: + f.write(data) + + def teardown(): + _try_delete(path) + + request.addfinalizer(teardown) + return path, data + + +def _check_native_file_reader(FACTORY, sample_data, + allow_read_out_of_bounds=True): + path, data = sample_data + + f = FACTORY(path, mode='r') + + assert f.read(10) == data[:10] + assert f.read(0) == b'' + assert f.tell() == 10 + + assert f.read() == data[10:] + + assert f.size() == len(data) + + f.seek(0) + assert f.tell() == 0 + + # Seeking past end of file not supported in memory maps + if allow_read_out_of_bounds: + f.seek(len(data) + 1) + assert f.tell() == len(data) + 1 + assert f.read(5) == b'' + + # Test whence argument of seek, ARROW-1287 + assert f.seek(3) == 3 + assert f.seek(3, os.SEEK_CUR) == 6 + assert f.tell() == 6 + + ex_length = len(data) - 2 + assert f.seek(-2, os.SEEK_END) == ex_length + assert f.tell() == ex_length + + +def test_memory_map_reader(sample_disk_data): + _check_native_file_reader(pa.memory_map, sample_disk_data, + allow_read_out_of_bounds=False) + + +def test_memory_map_retain_buffer_reference(sample_disk_data): + path, data = sample_disk_data + + cases = [] + with pa.memory_map(path, 'rb') as f: + cases.append((f.read_buffer(100), data[:100])) + cases.append((f.read_buffer(100), data[100:200])) + cases.append((f.read_buffer(100), data[200:300])) + + # Call gc.collect() for good measure + gc.collect() + + for buf, expected in cases: + assert buf.to_pybytes() == expected + + +def test_os_file_reader(sample_disk_data): + _check_native_file_reader(pa.OSFile, sample_disk_data) + + +def test_os_file_large_seeks(): + check_large_seeks(pa.OSFile) + + +def _try_delete(path): + try: + os.remove(path) + except os.error: + pass + + +def test_memory_map_writer(tmpdir): + if sys.platform == "emscripten": + pytest.xfail("Multiple memory maps to same file don't work on emscripten") + SIZE = 4096 + arr = [random.randint(0, 255) for _ in range(SIZE)] + data = bytes(arr[:SIZE]) + + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(data) + + f = pa.memory_map(path, mode='r+b') + + f.seek(10) + f.write(b'peekaboo') + assert f.tell() == 18 + + f.seek(10) + assert f.read(8) == b'peekaboo' + + f2 = pa.memory_map(path, mode='r+b') + + f2.seek(10) + f2.write(b'booapeak') + f2.seek(10) + + f.seek(10) + assert f.read(8) == b'booapeak' + + # Does not truncate file + f3 = pa.memory_map(path, mode='w') + f3.write(b'foo') + + with pa.memory_map(path) as f4: + assert f4.size() == SIZE + + with pytest.raises(IOError): + f3.read(5) + + f.seek(0) + assert f.read(3) == b'foo' + + +def test_memory_map_resize(tmpdir): + SIZE = 4096 + arr = [random.randint(0, 255) for _ in range(SIZE)] + data1 = bytes(arr[:(SIZE // 2)]) + data2 = bytes(arr[(SIZE // 2):]) + + path = os.path.join(str(tmpdir), guid()) + + mmap = pa.create_memory_map(path, SIZE / 2) + mmap.write(data1) + + mmap.resize(SIZE) + mmap.write(data2) + + mmap.close() + + with open(path, 'rb') as f: + assert f.read() == bytes(arr[:SIZE]) + + +def test_memory_zero_length(tmpdir): + path = os.path.join(str(tmpdir), guid()) + f = open(path, 'wb') + f.close() + with pa.memory_map(path, mode='r+b') as memory_map: + assert memory_map.size() == 0 + + +def test_memory_map_large_seeks(): + if sys.maxsize >= 2**32: + expected_error = None + else: + expected_error = pytest.raises( + pa.ArrowCapacityError, + match="Requested memory map length 4294967306 " + "does not fit in a C size_t") + check_large_seeks(pa.memory_map, expected_error=expected_error) + + +def test_memory_map_close_remove(tmpdir): + # ARROW-6740: should be able to delete closed memory-mapped file (Windows) + path = os.path.join(str(tmpdir), guid()) + mmap = pa.create_memory_map(path, 4096) + mmap.close() + assert mmap.closed + os.remove(path) # Shouldn't fail + + +def test_memory_map_deref_remove(tmpdir): + path = os.path.join(str(tmpdir), guid()) + pa.create_memory_map(path, 4096) + os.remove(path) # Shouldn't fail + + +def test_os_file_writer(tmpdir): + SIZE = 4096 + arr = [random.randint(0, 255) for _ in range(SIZE)] + data = bytes(arr[:SIZE]) + + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(data) + + # Truncates file + f2 = pa.OSFile(path, mode='w') + f2.write(b'foo') + + with pa.OSFile(path) as f3: + assert f3.size() == 3 + + with pytest.raises(IOError): + f2.read(5) + f2.close() + + # Append + with pa.OSFile(path, mode='ab') as f4: + f4.write(b'bar') + with pa.OSFile(path) as f5: + assert f5.size() == 6 # foo + bar + + +def test_native_file_write_reject_unicode(): + # ARROW-3227 + nf = pa.BufferOutputStream() + with pytest.raises(TypeError): + nf.write('foo') + + +def test_native_file_modes(tmpdir): + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(b'foooo') + + with pa.OSFile(path, mode='r') as f: + assert f.mode == 'rb' + assert f.readable() + assert not f.writable() + assert f.seekable() + + with pa.OSFile(path, mode='rb') as f: + assert f.mode == 'rb' + assert f.readable() + assert not f.writable() + assert f.seekable() + + with pa.OSFile(path, mode='w') as f: + assert f.mode == 'wb' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with pa.OSFile(path, mode='wb') as f: + assert f.mode == 'wb' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with pa.OSFile(path, mode='ab') as f: + assert f.mode == 'ab' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with pa.OSFile(path, mode='a') as f: + assert f.mode == 'ab' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with open(path, 'wb') as f: + f.write(b'foooo') + + with pa.memory_map(path, 'r') as f: + assert f.mode == 'rb' + assert f.readable() + assert not f.writable() + assert f.seekable() + + with pa.memory_map(path, 'r+') as f: + assert f.mode == 'rb+' + assert f.readable() + assert f.writable() + assert f.seekable() + + with pa.memory_map(path, 'r+b') as f: + assert f.mode == 'rb+' + assert f.readable() + assert f.writable() + assert f.seekable() + + +@pytest.mark.xfail( + sys.platform == "emscripten", reason="umask doesn't work on Emscripten" +) +def test_native_file_permissions(tmpdir): + # ARROW-10124: permissions of created files should follow umask + cur_umask = os.umask(0o002) + os.umask(cur_umask) + + path = os.path.join(str(tmpdir), guid()) + with pa.OSFile(path, mode='w'): + pass + assert os.stat(path).st_mode & 0o777 == 0o666 & ~cur_umask + + path = os.path.join(str(tmpdir), guid()) + with pa.memory_map(path, 'w'): + pass + assert os.stat(path).st_mode & 0o777 == 0o666 & ~cur_umask + + +def test_native_file_raises_ValueError_after_close(tmpdir): + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(b'foooo') + + with pa.OSFile(path, mode='rb') as os_file: + assert not os_file.closed + assert os_file.closed + + with pa.memory_map(path, mode='rb') as mmap_file: + assert not mmap_file.closed + assert mmap_file.closed + + files = [os_file, + mmap_file] + + methods = [('tell', ()), + ('seek', (0,)), + ('size', ()), + ('flush', ()), + ('readable', ()), + ('writable', ()), + ('seekable', ())] + + for f in files: + for method, args in methods: + with pytest.raises(ValueError): + getattr(f, method)(*args) + + +def test_native_file_TextIOWrapper(tmpdir): + data = ('foooo\n' + 'barrr\n' + 'bazzz\n') + + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(data.encode('utf-8')) + + with TextIOWrapper(pa.OSFile(path, mode='rb')) as fil: + assert fil.readable() + res = fil.read() + assert res == data + assert fil.closed + + with TextIOWrapper(pa.OSFile(path, mode='rb')) as fil: + # Iteration works + lines = list(fil) + assert ''.join(lines) == data + + # Writing + path2 = os.path.join(str(tmpdir), guid()) + with TextIOWrapper(pa.OSFile(path2, mode='wb')) as fil: + assert fil.writable() + fil.write(data) + + with TextIOWrapper(pa.OSFile(path2, mode='rb')) as fil: + res = fil.read() + assert res == data + + +def test_native_file_TextIOWrapper_perf(tmpdir): + # ARROW-16272: TextIOWrapper.readline() shouldn't exhaust a large + # Arrow input stream. + data = b'foo\nquux\n' + path = str(tmpdir / 'largefile.txt') + with open(path, 'wb') as f: + f.write(data * 100_000) + + binary_file = pa.OSFile(path, mode='rb') + with TextIOWrapper(binary_file) as f: + assert binary_file.tell() == 0 + nbytes = 20_000 + lines = f.readlines(nbytes) + assert len(lines) == math.ceil(2 * nbytes / len(data)) + assert nbytes <= binary_file.tell() <= nbytes * 2 + + +def test_native_file_read1(tmpdir): + # ARROW-16272: read1() should not exhaust the input stream if there + # is a large amount of data remaining. + data = b'123\n' * 1_000_000 + path = str(tmpdir / 'largefile.txt') + with open(path, 'wb') as f: + f.write(data) + + chunks = [] + with pa.OSFile(path, mode='rb') as f: + while True: + b = f.read1() + assert len(b) < len(data) + chunks.append(b) + b = f.read1(30_000) + assert len(b) <= 30_000 + chunks.append(b) + if not b: + break + + assert b"".join(chunks) == data + + +@pytest.mark.pandas +def test_native_file_pandas_text_reader(tmpdir): + # ARROW-16272: Pandas' read_csv() should not exhaust an Arrow + # input stream when a small nrows is passed. + import pandas as pd + import pandas.testing as tm + data = b'a,b\n' * 10_000_000 + path = str(tmpdir / 'largefile.txt') + with open(path, 'wb') as f: + f.write(data) + + with pa.OSFile(path, mode='rb') as f: + df = pd.read_csv(f, nrows=10) + expected = pd.DataFrame({'a': ['a'] * 10, 'b': ['b'] * 10}) + tm.assert_frame_equal(df, expected) + # Some readahead occurred, but not up to the end of file + assert f.tell() <= 256 * 1024 + + +def test_native_file_open_error(): + with assert_file_not_found(): + pa.OSFile('non_existent_file', 'rb') + with assert_file_not_found(): + pa.memory_map('non_existent_file', 'rb') + + +# ---------------------------------------------------------------------- +# Buffered streams + +def test_buffered_input_stream(): + raw = pa.BufferReader(b"123456789") + f = pa.BufferedInputStream(raw, buffer_size=4) + assert f.read(2) == b"12" + assert raw.tell() == 4 + f.close() + assert f.closed + assert raw.closed + + +def test_buffered_input_stream_detach_seekable(): + # detach() to a seekable file (io::RandomAccessFile in C++) + f = pa.BufferedInputStream(pa.BufferReader(b"123456789"), buffer_size=4) + assert f.read(2) == b"12" + raw = f.detach() + assert f.closed + assert not raw.closed + assert raw.seekable() + assert raw.read(4) == b"5678" + raw.seek(2) + assert raw.read(4) == b"3456" + + +def test_buffered_input_stream_detach_non_seekable(): + # detach() to a non-seekable file (io::InputStream in C++) + f = pa.BufferedInputStream( + pa.BufferedInputStream(pa.BufferReader(b"123456789"), buffer_size=4), + buffer_size=4) + assert f.read(2) == b"12" + raw = f.detach() + assert f.closed + assert not raw.closed + assert not raw.seekable() + assert raw.read(4) == b"5678" + with pytest.raises(EnvironmentError): + raw.seek(2) + + +@pytest.mark.numpy +def test_buffered_output_stream(): + np_buf = np.zeros(100, dtype=np.int8) # zero-initialized buffer + buf = pa.py_buffer(np_buf) + + raw = pa.FixedSizeBufferWriter(buf) + f = pa.BufferedOutputStream(raw, buffer_size=4) + f.write(b"12") + assert np_buf[:4].tobytes() == b'\0\0\0\0' + f.flush() + assert np_buf[:4].tobytes() == b'12\0\0' + f.write(b"3456789") + f.close() + assert f.closed + assert raw.closed + assert np_buf[:10].tobytes() == b'123456789\0' + + +@pytest.mark.numpy +def test_buffered_output_stream_detach(): + np_buf = np.zeros(100, dtype=np.int8) # zero-initialized buffer + buf = pa.py_buffer(np_buf) + + f = pa.BufferedOutputStream(pa.FixedSizeBufferWriter(buf), buffer_size=4) + f.write(b"12") + assert np_buf[:4].tobytes() == b'\0\0\0\0' + raw = f.detach() + assert f.closed + assert not raw.closed + assert np_buf[:4].tobytes() == b'12\0\0' + + +# ---------------------------------------------------------------------- +# Compressed input and output streams + +def check_compressed_input(data, fn, compression): + raw = pa.OSFile(fn, mode="rb") + with pa.CompressedInputStream(raw, compression) as compressed: + assert not compressed.closed + assert compressed.readable() + assert not compressed.writable() + assert not compressed.seekable() + got = compressed.read() + assert got == data + assert compressed.closed + assert raw.closed + + # Same with read_buffer() + raw = pa.OSFile(fn, mode="rb") + with pa.CompressedInputStream(raw, compression) as compressed: + buf = compressed.read_buffer() + assert isinstance(buf, pa.Buffer) + assert buf.to_pybytes() == data + + +@pytest.mark.gzip +def test_compressed_input_gzip(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_input_test.gz") + with gzip.open(fn, "wb") as f: + f.write(data) + check_compressed_input(data, fn, "gzip") + + +def test_compressed_input_bz2(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_input_test.bz2") + with bz2.BZ2File(fn, "w") as f: + f.write(data) + try: + check_compressed_input(data, fn, "bz2") + except NotImplementedError as e: + pytest.skip(str(e)) + + +@pytest.mark.gzip +def test_compressed_input_openfile(tmpdir): + if not Codec.is_available("gzip"): + pytest.skip("gzip support is not built") + + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "test_compressed_input_openfile.gz") + with gzip.open(fn, "wb") as f: + f.write(data) + + with pa.CompressedInputStream(fn, "gzip") as compressed: + buf = compressed.read_buffer() + assert buf.to_pybytes() == data + assert compressed.closed + + with pa.CompressedInputStream(pathlib.Path(fn), "gzip") as compressed: + buf = compressed.read_buffer() + assert buf.to_pybytes() == data + assert compressed.closed + + f = open(fn, "rb") + with pa.CompressedInputStream(f, "gzip") as compressed: + buf = compressed.read_buffer() + assert buf.to_pybytes() == data + assert f.closed + + +def check_compressed_concatenated(data, fn, compression): + raw = pa.OSFile(fn, mode="rb") + with pa.CompressedInputStream(raw, compression) as compressed: + got = compressed.read() + assert got == data + + +@pytest.mark.gzip +def test_compressed_concatenated_gzip(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_input_test2.gz") + with gzip.open(fn, "wb") as f: + f.write(data[:50]) + with gzip.open(fn, "ab") as f: + f.write(data[50:]) + check_compressed_concatenated(data, fn, "gzip") + + +@pytest.mark.gzip +def test_compressed_input_invalid(): + data = b"foo" * 10 + raw = pa.BufferReader(data) + with pytest.raises(ValueError): + pa.CompressedInputStream(raw, "unknown_compression") + with pytest.raises(TypeError): + pa.CompressedInputStream(raw, None) + + with pa.CompressedInputStream(raw, "gzip") as compressed: + with pytest.raises(IOError, match="zlib inflate failed"): + compressed.read() + + +def make_compressed_output(data, fn, compression): + raw = pa.BufferOutputStream() + with pa.CompressedOutputStream(raw, compression) as compressed: + assert not compressed.closed + assert not compressed.readable() + assert compressed.writable() + assert not compressed.seekable() + compressed.write(data) + assert compressed.closed + assert raw.closed + with open(fn, "wb") as f: + f.write(raw.getvalue()) + + +@pytest.mark.gzip +def test_compressed_output_gzip(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_output_test.gz") + make_compressed_output(data, fn, "gzip") + with gzip.open(fn, "rb") as f: + got = f.read() + assert got == data + + +def test_compressed_output_bz2(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_output_test.bz2") + try: + make_compressed_output(data, fn, "bz2") + except NotImplementedError as e: + pytest.skip(str(e)) + with bz2.BZ2File(fn, "r") as f: + got = f.read() + assert got == data + + +def test_output_stream_constructor(tmpdir): + if not Codec.is_available("gzip"): + pytest.skip("gzip support is not built") + with pa.CompressedOutputStream(tmpdir / "ctor.gz", "gzip") as stream: + stream.write(b"test") + with (tmpdir / "ctor2.gz").open("wb") as f: + with pa.CompressedOutputStream(f, "gzip") as stream: + stream.write(b"test") + + +@pytest.mark.parametrize(("path", "expected_compression"), [ + ("file.bz2", "bz2"), + ("file.lz4", "lz4"), + (pathlib.Path("file.gz"), "gzip"), + (pathlib.Path("path/to/file.zst"), "zstd"), +]) +def test_compression_detection(path, expected_compression): + if not Codec.is_available(expected_compression): + with pytest.raises(pa.lib.ArrowNotImplementedError): + Codec.detect(path) + else: + codec = Codec.detect(path) + assert isinstance(codec, Codec) + assert codec.name == expected_compression + + +def test_unknown_compression_raises(): + with pytest.raises(ValueError): + Codec.is_available('unknown') + with pytest.raises(TypeError): + Codec(None) + with pytest.raises(ValueError): + Codec('unknown') + + +@pytest.mark.parametrize("compression", [ + "bz2", + "brotli", + "gzip", + "lz4", + "zstd", + pytest.param( + "snappy", + marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) + ) +]) +def test_compressed_roundtrip(compression): + if not Codec.is_available(compression): + pytest.skip(f"{compression} support is not built") + + data = b"some test data\n" * 10 + b"eof\n" + raw = pa.BufferOutputStream() + with pa.CompressedOutputStream(raw, compression) as compressed: + compressed.write(data) + + cdata = raw.getvalue() + assert len(cdata) < len(data) + raw = pa.BufferReader(cdata) + with pa.CompressedInputStream(raw, compression) as compressed: + got = compressed.read() + assert got == data + + +@pytest.mark.parametrize( + "compression", + ["bz2", "brotli", "gzip", "lz4", "zstd"] +) +def test_compressed_recordbatch_stream(compression): + if not Codec.is_available(compression): + pytest.skip(f"{compression} support is not built") + + # ARROW-4836: roundtrip a RecordBatch through a compressed stream + table = pa.Table.from_arrays([pa.array([1, 2, 3, 4, 5])], ['a']) + raw = pa.BufferOutputStream() + stream = pa.CompressedOutputStream(raw, compression) + writer = pa.RecordBatchStreamWriter(stream, table.schema) + writer.write_table(table, max_chunksize=3) + writer.close() + stream.close() # Flush data + buf = raw.getvalue() + stream = pa.CompressedInputStream(pa.BufferReader(buf), compression) + got_table = pa.RecordBatchStreamReader(stream).read_all() + assert got_table == table + + +# ---------------------------------------------------------------------- +# Transform input streams + +unicode_transcoding_example = ( + "Dès Noël où un zéphyr haï me vêt de glaçons würmiens " + "je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera !" +) + + +def check_transcoding(data, src_encoding, dest_encoding, chunk_sizes): + chunk_sizes = iter(chunk_sizes) + stream = pa.transcoding_input_stream( + pa.BufferReader(data.encode(src_encoding)), + src_encoding, dest_encoding) + out = [] + while True: + buf = stream.read(next(chunk_sizes)) + out.append(buf) + if not buf: + break + out = b''.join(out) + assert out.decode(dest_encoding) == data + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'utf-16'), + ('utf-16', 'utf-8'), + ('utf-8', 'utf-32-le'), + ('utf-8', 'utf-32-be'), + ]) +def test_transcoding_input_stream(src_encoding, dest_encoding): + # All at once + check_transcoding(unicode_transcoding_example, + src_encoding, dest_encoding, [1000, 0]) + # Incremental + check_transcoding(unicode_transcoding_example, + src_encoding, dest_encoding, + itertools.cycle([1, 2, 3, 5])) + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'utf-8'), + ('utf-8', 'UTF8')]) +def test_transcoding_no_ops(src_encoding, dest_encoding): + # No indirection is wasted when a trivial transcoding is requested + stream = pa.BufferReader(b"abc123") + assert pa.transcoding_input_stream( + stream, src_encoding, dest_encoding) is stream + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'ascii'), + ('utf-8', 'latin-1'), + ]) +def test_transcoding_encoding_error(src_encoding, dest_encoding): + # Character \u0100 cannot be represented in the destination encoding + stream = pa.transcoding_input_stream( + pa.BufferReader("\u0100".encode(src_encoding)), + src_encoding, + dest_encoding) + with pytest.raises(UnicodeEncodeError): + stream.read(1) + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'utf-16'), + ('utf-16', 'utf-8'), + ]) +def test_transcoding_decoding_error(src_encoding, dest_encoding): + # The given bytestring is not valid in the source encoding + stream = pa.transcoding_input_stream( + pa.BufferReader(b"\xff\xff\xff\xff"), + src_encoding, + dest_encoding) + with pytest.raises(UnicodeError): + stream.read(1) + + +# ---------------------------------------------------------------------- +# High-level API + +@pytest.mark.gzip +def test_input_stream_buffer(): + data = b"some test data\n" * 10 + b"eof\n" + for arg in [pa.py_buffer(data), memoryview(data)]: + stream = pa.input_stream(arg) + assert stream.read() == data + + gz_data = gzip.compress(data) + stream = pa.input_stream(memoryview(gz_data)) + assert stream.read() == gz_data + stream = pa.input_stream(memoryview(gz_data), compression='gzip') + assert stream.read() == data + + +def test_input_stream_duck_typing(): + # Accept objects having the right file-like methods... + class DuckReader: + + def close(self): + pass + + @property + def closed(self): + return False + + def read(self, nbytes=None): + return b'hello' + + stream = pa.input_stream(DuckReader()) + assert stream.read(5) == b'hello' + + +def test_input_stream_file_path(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'input_stream' + with open(str(file_path), 'wb') as f: + f.write(data) + + stream = pa.input_stream(file_path) + assert stream.read() == data + stream = pa.input_stream(str(file_path)) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path))) + assert stream.read() == data + + +@pytest.mark.gzip +def test_input_stream_file_path_compressed(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + gz_data = gzip.compress(data) + file_path = tmpdir / 'input_stream.gz' + with open(str(file_path), 'wb') as f: + f.write(gz_data) + + stream = pa.input_stream(file_path) + assert stream.read() == data + stream = pa.input_stream(str(file_path)) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path))) + assert stream.read() == data + + stream = pa.input_stream(file_path, compression='gzip') + assert stream.read() == data + stream = pa.input_stream(file_path, compression=None) + assert stream.read() == gz_data + + +def test_input_stream_file_path_buffered(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'input_stream.buffered' + with open(str(file_path), 'wb') as f: + f.write(data) + + stream = pa.input_stream(file_path, buffer_size=32) + assert isinstance(stream, pa.BufferedInputStream) + assert stream.read() == data + stream = pa.input_stream(str(file_path), buffer_size=64) + assert isinstance(stream, pa.BufferedInputStream) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path)), buffer_size=1024) + assert isinstance(stream, pa.BufferedInputStream) + assert stream.read() == data + + unbuffered_stream = pa.input_stream(file_path, buffer_size=0) + assert isinstance(unbuffered_stream, pa.OSFile) + + msg = 'Buffer size must be larger than zero' + with pytest.raises(ValueError, match=msg): + pa.input_stream(file_path, buffer_size=-1) + with pytest.raises(TypeError): + pa.input_stream(file_path, buffer_size='million') + + +@pytest.mark.gzip +def test_input_stream_file_path_compressed_and_buffered(tmpdir): + data = b"some test data\n" * 100 + b"eof\n" + gz_data = gzip.compress(data) + file_path = tmpdir / 'input_stream_compressed_and_buffered.gz' + with open(str(file_path), 'wb') as f: + f.write(gz_data) + + stream = pa.input_stream(file_path, buffer_size=32, compression='gzip') + assert stream.read() == data + stream = pa.input_stream(str(file_path), buffer_size=64) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path)), buffer_size=1024) + assert stream.read() == data + + +@pytest.mark.gzip +def test_input_stream_python_file(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + bio = BytesIO(data) + + stream = pa.input_stream(bio) + assert stream.read() == data + + gz_data = gzip.compress(data) + bio = BytesIO(gz_data) + stream = pa.input_stream(bio) + assert stream.read() == gz_data + bio.seek(0) + stream = pa.input_stream(bio, compression='gzip') + assert stream.read() == data + + file_path = tmpdir / 'input_stream' + with open(str(file_path), 'wb') as f: + f.write(data) + with open(str(file_path), 'rb') as f: + stream = pa.input_stream(f) + assert stream.read() == data + + +@pytest.mark.gzip +def test_input_stream_native_file(): + data = b"some test data\n" * 10 + b"eof\n" + gz_data = gzip.compress(data) + reader = pa.BufferReader(gz_data) + stream = pa.input_stream(reader) + assert stream is reader + reader = pa.BufferReader(gz_data) + stream = pa.input_stream(reader, compression='gzip') + assert stream.read() == data + + +def test_input_stream_errors(tmpdir): + buf = memoryview(b"") + with pytest.raises(ValueError): + pa.input_stream(buf, compression="foo") + + for arg in [bytearray(), StringIO()]: + with pytest.raises(TypeError): + pa.input_stream(arg) + + with assert_file_not_found(): + pa.input_stream("non_existent_file") + + with open(str(tmpdir / 'new_file'), 'wb') as f: + with pytest.raises(TypeError, match="readable file expected"): + pa.input_stream(f) + + +def test_output_stream_buffer(): + data = b"some test data\n" * 10 + b"eof\n" + buf = bytearray(len(data)) + stream = pa.output_stream(pa.py_buffer(buf)) + stream.write(data) + assert buf == data + + buf = bytearray(len(data)) + stream = pa.output_stream(memoryview(buf)) + stream.write(data) + assert buf == data + + +def test_output_stream_duck_typing(): + # Accept objects having the right file-like methods... + class DuckWriter: + def __init__(self): + self.buf = pa.BufferOutputStream() + + def close(self): + pass + + @property + def closed(self): + return False + + def write(self, data): + self.buf.write(data) + + duck_writer = DuckWriter() + stream = pa.output_stream(duck_writer) + assert stream.write(b'hello') + assert duck_writer.buf.getvalue().to_pybytes() == b'hello' + + +def test_output_stream_file_path(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'output_stream' + + def check_data(file_path, data): + with pa.output_stream(file_path) as stream: + stream.write(data) + with open(str(file_path), 'rb') as f: + assert f.read() == data + + check_data(file_path, data) + check_data(str(file_path), data) + check_data(pathlib.Path(str(file_path)), data) + + +@pytest.mark.gzip +def test_output_stream_file_path_compressed(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'output_stream.gz' + + def check_data(file_path, data, **kwargs): + with pa.output_stream(file_path, **kwargs) as stream: + stream.write(data) + with open(str(file_path), 'rb') as f: + return f.read() + + assert gzip.decompress(check_data(file_path, data)) == data + assert gzip.decompress(check_data(str(file_path), data)) == data + assert gzip.decompress( + check_data(pathlib.Path(str(file_path)), data)) == data + + assert gzip.decompress( + check_data(file_path, data, compression='gzip')) == data + assert check_data(file_path, data, compression=None) == data + + with pytest.raises(ValueError, match='Invalid value for compression'): + assert check_data(file_path, data, compression='rabbit') == data + + +def test_output_stream_file_path_buffered(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'output_stream.buffered' + + def check_data(file_path, data, **kwargs): + with pa.output_stream(file_path, **kwargs) as stream: + if kwargs.get('buffer_size', 0) > 0: + assert isinstance(stream, pa.BufferedOutputStream) + stream.write(data) + with open(str(file_path), 'rb') as f: + return f.read() + + unbuffered_stream = pa.output_stream(file_path, buffer_size=0) + assert isinstance(unbuffered_stream, pa.OSFile) + + msg = 'Buffer size must be larger than zero' + with pytest.raises(ValueError, match=msg): + assert check_data(file_path, data, buffer_size=-128) == data + + assert check_data(file_path, data, buffer_size=32) == data + assert check_data(file_path, data, buffer_size=1024) == data + assert check_data(str(file_path), data, buffer_size=32) == data + + result = check_data(pathlib.Path(str(file_path)), data, buffer_size=32) + assert result == data + + +@pytest.mark.gzip +def test_output_stream_file_path_compressed_and_buffered(tmpdir): + data = b"some test data\n" * 100 + b"eof\n" + file_path = tmpdir / 'output_stream_compressed_and_buffered.gz' + + def check_data(file_path, data, **kwargs): + with pa.output_stream(file_path, **kwargs) as stream: + stream.write(data) + with open(str(file_path), 'rb') as f: + return f.read() + + result = check_data(file_path, data, buffer_size=32) + assert gzip.decompress(result) == data + + result = check_data(file_path, data, buffer_size=1024) + assert gzip.decompress(result) == data + + result = check_data(file_path, data, buffer_size=1024, compression='gzip') + assert gzip.decompress(result) == data + + +def test_output_stream_destructor(tmpdir): + # The wrapper returned by pa.output_stream() should respect Python + # file semantics, i.e. destroying it should close the underlying + # file cleanly. + data = b"some test data\n" + file_path = tmpdir / 'output_stream.buffered' + + def check_data(file_path, data, **kwargs): + stream = pa.output_stream(file_path, **kwargs) + stream.write(data) + del stream + gc.collect() + with open(str(file_path), 'rb') as f: + return f.read() + + assert check_data(file_path, data, buffer_size=0) == data + assert check_data(file_path, data, buffer_size=1024) == data + + +@pytest.mark.gzip +def test_output_stream_python_file(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + + def check_data(data, **kwargs): + # XXX cannot use BytesIO because stream.close() is necessary + # to finish writing compressed data, but it will also close the + # underlying BytesIO + fn = str(tmpdir / 'output_stream_file') + with open(fn, 'wb') as f: + with pa.output_stream(f, **kwargs) as stream: + stream.write(data) + with open(fn, 'rb') as f: + return f.read() + + assert check_data(data) == data + assert gzip.decompress(check_data(data, compression='gzip')) == data + + +def test_output_stream_errors(tmpdir): + buf = memoryview(bytearray()) + with pytest.raises(ValueError): + pa.output_stream(buf, compression="foo") + + for arg in [bytearray(), StringIO()]: + with pytest.raises(TypeError): + pa.output_stream(arg) + + fn = str(tmpdir / 'new_file') + with open(fn, 'wb') as f: + pass + with open(fn, 'rb') as f: + with pytest.raises(TypeError, match="writable file expected"): + pa.output_stream(f) diff --git a/shared/package-files/7c/7c125311645eed9ecc907015e85fe3dc44b980812d075b12b450bafa7cdccf15/blob b/shared/package-files/7c/7c125311645eed9ecc907015e85fe3dc44b980812d075b12b450bafa7cdccf15/blob new file mode 100644 index 0000000000000000000000000000000000000000..d1d76a42c68c89fc6fc473952b1e857368f19b1e Binary files /dev/null and b/shared/package-files/7c/7c125311645eed9ecc907015e85fe3dc44b980812d075b12b450bafa7cdccf15/blob differ diff --git a/shared/package-files/7c/7c12e283ccf9e3c82c041950c3a54974665be0872a263effd268b615dda77043/blob b/shared/package-files/7c/7c12e283ccf9e3c82c041950c3a54974665be0872a263effd268b615dda77043/blob new file mode 100644 index 0000000000000000000000000000000000000000..2da59117cad0d72d5830b53c8d19c6e0ca988d54 --- /dev/null +++ b/shared/package-files/7c/7c12e283ccf9e3c82c041950c3a54974665be0872a263effd268b615dda77043/blob @@ -0,0 +1,177 @@ +import pytest + +import networkx as nx + + +class TestFilterFactory: + def test_no_filter(self): + nf = nx.filters.no_filter + assert nf() + assert nf(1) + assert nf(2, 1) + + def test_hide_nodes(self): + f = nx.classes.filters.hide_nodes([1, 2, 3]) + assert not f(1) + assert not f(2) + assert not f(3) + assert f(4) + assert f(0) + assert f("a") + pytest.raises(TypeError, f, 1, 2) + pytest.raises(TypeError, f) + + def test_show_nodes(self): + f = nx.classes.filters.show_nodes([1, 2, 3]) + assert f(1) + assert f(2) + assert f(3) + assert not f(4) + assert not f(0) + assert not f("a") + pytest.raises(TypeError, f, 1, 2) + pytest.raises(TypeError, f) + + def test_hide_edges(self): + factory = nx.classes.filters.hide_edges + f = factory([(1, 2), (3, 4)]) + assert not f(1, 2) + assert not f(3, 4) + assert not f(4, 3) + assert f(2, 3) + assert f(0, -1) + assert f("a", "b") + pytest.raises(TypeError, f, 1, 2, 3) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2, 3)]) + + def test_show_edges(self): + factory = nx.classes.filters.show_edges + f = factory([(1, 2), (3, 4)]) + assert f(1, 2) + assert f(3, 4) + assert f(4, 3) + assert not f(2, 3) + assert not f(0, -1) + assert not f("a", "b") + pytest.raises(TypeError, f, 1, 2, 3) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2, 3)]) + + def test_hide_diedges(self): + factory = nx.classes.filters.hide_diedges + f = factory([(1, 2), (3, 4)]) + assert not f(1, 2) + assert not f(3, 4) + assert f(4, 3) + assert f(2, 3) + assert f(0, -1) + assert f("a", "b") + pytest.raises(TypeError, f, 1, 2, 3) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2, 3)]) + + def test_show_diedges(self): + factory = nx.classes.filters.show_diedges + f = factory([(1, 2), (3, 4)]) + assert f(1, 2) + assert f(3, 4) + assert not f(4, 3) + assert not f(2, 3) + assert not f(0, -1) + assert not f("a", "b") + pytest.raises(TypeError, f, 1, 2, 3) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2, 3)]) + + def test_hide_multiedges(self): + factory = nx.classes.filters.hide_multiedges + f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)]) + assert not f(1, 2, 0) + assert not f(1, 2, 1) + assert f(1, 2, 2) + assert f(3, 4, 0) + assert not f(3, 4, 1) + assert not f(4, 3, 1) + assert f(4, 3, 0) + assert f(2, 3, 0) + assert f(0, -1, 0) + assert f("a", "b", 0) + pytest.raises(TypeError, f, 1, 2, 3, 4) + pytest.raises(TypeError, f, 1, 2) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2)]) + pytest.raises(ValueError, factory, [(1, 2, 3, 4)]) + + def test_show_multiedges(self): + factory = nx.classes.filters.show_multiedges + f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)]) + assert f(1, 2, 0) + assert f(1, 2, 1) + assert not f(1, 2, 2) + assert not f(3, 4, 0) + assert f(3, 4, 1) + assert f(4, 3, 1) + assert not f(4, 3, 0) + assert not f(2, 3, 0) + assert not f(0, -1, 0) + assert not f("a", "b", 0) + pytest.raises(TypeError, f, 1, 2, 3, 4) + pytest.raises(TypeError, f, 1, 2) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2)]) + pytest.raises(ValueError, factory, [(1, 2, 3, 4)]) + + def test_hide_multidiedges(self): + factory = nx.classes.filters.hide_multidiedges + f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)]) + assert not f(1, 2, 0) + assert not f(1, 2, 1) + assert f(1, 2, 2) + assert f(3, 4, 0) + assert not f(3, 4, 1) + assert f(4, 3, 1) + assert f(4, 3, 0) + assert f(2, 3, 0) + assert f(0, -1, 0) + assert f("a", "b", 0) + pytest.raises(TypeError, f, 1, 2, 3, 4) + pytest.raises(TypeError, f, 1, 2) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2)]) + pytest.raises(ValueError, factory, [(1, 2, 3, 4)]) + + def test_show_multidiedges(self): + factory = nx.classes.filters.show_multidiedges + f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)]) + assert f(1, 2, 0) + assert f(1, 2, 1) + assert not f(1, 2, 2) + assert not f(3, 4, 0) + assert f(3, 4, 1) + assert not f(4, 3, 1) + assert not f(4, 3, 0) + assert not f(2, 3, 0) + assert not f(0, -1, 0) + assert not f("a", "b", 0) + pytest.raises(TypeError, f, 1, 2, 3, 4) + pytest.raises(TypeError, f, 1, 2) + pytest.raises(TypeError, f, 1) + pytest.raises(TypeError, f) + pytest.raises(TypeError, factory, [1, 2, 3]) + pytest.raises(ValueError, factory, [(1, 2)]) + pytest.raises(ValueError, factory, [(1, 2, 3, 4)]) diff --git a/shared/package-files/7c/7c132097d9d7a3dc0e022f99afdbf1b99e03d4888399db98744206f3918308a5/blob b/shared/package-files/7c/7c132097d9d7a3dc0e022f99afdbf1b99e03d4888399db98744206f3918308a5/blob new file mode 100644 index 0000000000000000000000000000000000000000..07495a5f2b2497d574269740413d740963190790 --- /dev/null +++ b/shared/package-files/7c/7c132097d9d7a3dc0e022f99afdbf1b99e03d4888399db98744206f3918308a5/blob @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API diagonal_scatter { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::diagonal_scatter") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2); +}; + +struct TORCH_API diagonal_scatter_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, int64_t, int64_t, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::diagonal_scatter") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "diagonal_scatter.out(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7c13d5d65ea4ae0b467c76ac45f68bef4f0cd3978db338c0406df7cfe36dbd48/blob b/shared/package-files/7c/7c13d5d65ea4ae0b467c76ac45f68bef4f0cd3978db338c0406df7cfe36dbd48/blob new file mode 100644 index 0000000000000000000000000000000000000000..dde0cc214aac1c6561534a483b60b7baa78629d2 --- /dev/null +++ b/shared/package-files/7c/7c13d5d65ea4ae0b467c76ac45f68bef4f0cd3978db338c0406df7cfe36dbd48/blob @@ -0,0 +1,51 @@ +// +// Generated by NVIDIA NVVM Compiler +// +// Compiler Build ID: CL-27506705 +// Cuda compilation tools, release 10.2, V10.2.89 +// Based on LLVM 3.4svn +// + +.version 6.5 +.target sm_50 +.address_size 64 + + // .globl bar + +.visible .func (.param .b32 func_retval0) bar( + .param .b64 bar_param_0, + .param .b32 bar_param_1 +) +{ + .reg .b32 %r<4>; + .reg .b64 %rd<2>; + + + ld.param.u64 %rd1, [bar_param_0]; + ld.param.u32 %r1, [bar_param_1]; + shl.b32 %r2, %r1, 1; + st.u32 [%rd1], %r2; + mov.u32 %r3, 0; + st.param.b32 [func_retval0+0], %r3; + ret; +} + + // .globl array_mutator +.visible .func (.param .b32 func_retval0) array_mutator( + .param .b64 array_mutator_param_0, + .param .b64 array_mutator_param_1 +) +{ + .reg .b32 %r<3>; + .reg .b64 %rd<2>; + + + ld.param.u64 %rd1, [array_mutator_param_1]; + ld.u32 %r1, [%rd1+4]; + st.u32 [%rd1], %r1; + mov.u32 %r2, 0; + st.param.b32 [func_retval0+0], %r2; + ret; +} + + diff --git a/shared/package-files/7c/7c1459904e57697fddd21e7fa2f52cb9a157eca6609afc58efde3a4614b47517/blob b/shared/package-files/7c/7c1459904e57697fddd21e7fa2f52cb9a157eca6609afc58efde3a4614b47517/blob new file mode 100644 index 0000000000000000000000000000000000000000..986f825d9280396ae8b317d19d3a1594ef36149d --- /dev/null +++ b/shared/package-files/7c/7c1459904e57697fddd21e7fa2f52cb9a157eca6609afc58efde3a4614b47517/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c1459904e57697fddd21e7fa2f52cb9a157eca6609afc58efde3a4614b47517 +size 1067032 diff --git a/shared/package-files/7c/7c14a11a75df13294d19cd5d72baa874358da91e0a345876b3b5aad2c17e7cb0/blob b/shared/package-files/7c/7c14a11a75df13294d19cd5d72baa874358da91e0a345876b3b5aad2c17e7cb0/blob new file mode 100644 index 0000000000000000000000000000000000000000..8b49397f5434c7a21827a55bc9009626c9415096 --- /dev/null +++ b/shared/package-files/7c/7c14a11a75df13294d19cd5d72baa874358da91e0a345876b3b5aad2c17e7cb0/blob @@ -0,0 +1,27 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from logging import getLogger + +from ..auxlib.entity import Entity, EnumField, StringField +from .enums import LeasedPathType + +log = getLogger(__name__) + + +class LeasedPathEntry(Entity): + """ + _path: short path for the leased path, using forward slashes + target_path: the full path to the executable in the private env + target_prefix: the full path to the private environment + leased_path: the full path for the lease in the root prefix + package_name: the package holding the lease + leased_path_type: application_entry_point + + """ + + _path = StringField() + target_path = StringField() + target_prefix = StringField() + leased_path = StringField() + package_name = StringField() + leased_path_type = EnumField(LeasedPathType) diff --git a/shared/package-files/7c/7c1a40bff4f0db44962a720da96f94ca2aa5e45584f5637a4adbd2a5fa07abbc/blob b/shared/package-files/7c/7c1a40bff4f0db44962a720da96f94ca2aa5e45584f5637a4adbd2a5fa07abbc/blob new file mode 100644 index 0000000000000000000000000000000000000000..2540f4df92e1ba255b4ac36cce81a2e58500d4cc --- /dev/null +++ b/shared/package-files/7c/7c1a40bff4f0db44962a720da96f94ca2aa5e45584f5637a4adbd2a5fa07abbc/blob @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple<::std::vector,at::Tensor> _amp_foreach_non_finite_check_and_unscale(at::TensorList self, const at::Tensor & found_inf, const at::Tensor & inv_scale); +TORCH_API void _amp_foreach_non_finite_check_and_unscale_out(at::TensorList out, at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale); +TORCH_API void _amp_foreach_non_finite_check_and_unscale_outf(at::TensorList self, at::Tensor & found_inf, const at::Tensor & inv_scale, at::TensorList out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/7c/7c1c707cd6ad3872515cf3fc9d8dd1a3f7cc08e3eb71813ed427499b256a8751/blob b/shared/package-files/7c/7c1c707cd6ad3872515cf3fc9d8dd1a3f7cc08e3eb71813ed427499b256a8751/blob new file mode 100644 index 0000000000000000000000000000000000000000..6106819db843b5d93e85c4ee6929825d45c2f08a --- /dev/null +++ b/shared/package-files/7c/7c1c707cd6ad3872515cf3fc9d8dd1a3f7cc08e3eb71813ed427499b256a8751/blob @@ -0,0 +1,33 @@ +"""distutils.command.x + +Implements the Distutils 'x' command. +""" + +# created 2000/mm/dd, John Doe + +__revision__ = "$Id$" + +from distutils.core import Command + + +class x(Command): + + # Brief (40-50 characters) description of the command + description = "" + + # List of option tuples: long name, short name (None if no short + # name), and help string. + user_options = [('', '', + ""), + ] + + def initialize_options(self): + self. = None + self. = None + self. = None + + def finalize_options(self): + if self.x is None: + self.x = + + def run(self): diff --git a/shared/package-files/7c/7c1e5f21e8833b85947ab52ab1ebeb7ecfb8cfcd1122fcee57c3ad96fed8d8cd/blob b/shared/package-files/7c/7c1e5f21e8833b85947ab52ab1ebeb7ecfb8cfcd1122fcee57c3ad96fed8d8cd/blob new file mode 100644 index 0000000000000000000000000000000000000000..11b3b5cffd2020f178c885510d445cb3b197ba08 --- /dev/null +++ b/shared/package-files/7c/7c1e5f21e8833b85947ab52ab1ebeb7ecfb8cfcd1122fcee57c3ad96fed8d8cd/blob @@ -0,0 +1,268 @@ +# Copyright (C) 2008 Pat Thoyts +# +# Calculate a Knight's tour of a chessboard. +# +# This uses Warnsdorff's rule to calculate the next square each +# time. This specifies that the next square should be the one that +# has the least number of available moves. +# +# Using this rule it is possible to get to a position where +# there are no squares available to move into. In this implementation +# this occurs when the starting square is d6. +# +# To solve this fault an enhancement to the rule is that if we +# have a choice of squares with an equal score, we should choose +# the one nearest the edge of the board. +# +# If the call to the Edgemost function is commented out you can see +# this occur. +# +# You can drag the knight to a specific square to start if you wish. +# If you let it repeat then it will choose random start positions +# for each new tour. + +package require Tk + +# Return a list of accessible squares from a given square +proc ValidMoves {square} { + set moves {} + foreach pair {{-1 -2} {-2 -1} {-2 1} {-1 2} {1 2} {2 1} {2 -1} {1 -2}} { + set col [expr {($square % 8) + [lindex $pair 0]}] + set row [expr {($square / 8) + [lindex $pair 1]}] + if {$row >= 0 && $row < 8 && $col >= 0 && $col < 8} { + lappend moves [expr {$row * 8 + $col}] + } + } + return $moves +} + +# Return the number of available moves for this square +proc CheckSquare {square} { + variable visited + set moves 0 + foreach test [ValidMoves $square] { + if {[lsearch -exact -integer $visited $test] < 0} { + incr moves + } + } + return $moves +} + +# Select the next square to move to. Returns -1 if there are no available +# squares remaining that we can move to. +proc Next {square} { + variable visited + set minimum 9 + set nextSquare -1 + foreach testSquare [ValidMoves $square] { + if {[lsearch -exact -integer $visited $testSquare] < 0} { + set count [CheckSquare $testSquare] + if {$count < $minimum} { + set minimum $count + set nextSquare $testSquare + } elseif {$count == $minimum} { + # to remove the enhancement to Warnsdorff's rule + # remove the next line: + set nextSquare [Edgemost $nextSquare $testSquare] + } + } + } + return $nextSquare +} + +# Select the square nearest the edge of the board +proc Edgemost {a b} { + set colA [expr {3-int(abs(3.5-($a%8)))}] + set colB [expr {3-int(abs(3.5-($b%8)))}] + set rowA [expr {3-int(abs(3.5-($a/8)))}] + set rowB [expr {3-int(abs(3.5-($b/8)))}] + return [expr {($colA * $rowA) < ($colB * $rowB) ? $a : $b}] +} + +# Display a square number as a standard chess square notation. +proc N {square} { + return [format %c%d [expr {97 + $square % 8}] \ + [expr {$square / 8 + 1}]] +} + +# Perform a Knight's move and schedule the next move. +proc MovePiece {dlg last square} { + variable visited + variable delay + variable continuous + $dlg.f.txt insert end "[llength $visited]. [N $last] .. [N $square]\n" {} + $dlg.f.txt see end + $dlg.f.c itemconfigure [expr {1+$last}] -state normal -outline black + $dlg.f.c itemconfigure [expr {1+$square}] -state normal -outline red + $dlg.f.c moveto knight {*}[lrange [$dlg.f.c coords [expr {1+$square}]] 0 1] + lappend visited $square + set next [Next $square] + if {$next ne -1} { + variable aid [after $delay [list MovePiece $dlg $square $next]] + } else { + $dlg.tf.b1 configure -state normal + if {[llength $visited] == 64} { + variable initial + if {$initial == $square} { + $dlg.f.txt insert end "Closed tour!" + } else { + $dlg.f.txt insert end "Success\n" {} + if {$continuous} { + after [expr {$delay * 2}] [namespace code \ + [list Tour $dlg [expr {int(rand() * 64)}]]] + } + } + } else { + $dlg.f.txt insert end "FAILED!\n" {} + } + } +} + +# Begin a new tour of the board given a random start position +proc Tour {dlg {square {}}} { + variable visited {} + $dlg.f.txt delete 1.0 end + $dlg.tf.b1 configure -state disabled + for {set n 0} {$n < 64} {incr n} { + $dlg.f.c itemconfigure $n -state disabled -outline black + } + if {$square eq {}} { + set coords [lrange [$dlg.f.c coords knight] 0 1] + set square [expr {[$dlg.f.c find closest {*}$coords 0 65]-1}] + } + variable initial $square + after idle [list MovePiece $dlg $initial $initial] +} + +proc Stop {} { + variable aid + catch {after cancel $aid} +} + +proc Exit {dlg} { + Stop + destroy $dlg +} + +proc SetDelay {new} { + variable delay [expr {int($new)}] +} + +proc DragStart {w x y} { + $w dtag selected + $w addtag selected withtag current + variable dragging [list $x $y] +} +proc DragMotion {w x y} { + variable dragging + if {[info exists dragging]} { + $w move selected [expr {$x - [lindex $dragging 0]}] \ + [expr {$y - [lindex $dragging 1]}] + variable dragging [list $x $y] + } +} +proc DragEnd {w x y} { + set square [$w find closest $x $y 0 65] + $w moveto selected {*}[lrange [$w coords $square] 0 1] + $w dtag selected + variable dragging ; unset dragging +} + +proc CreateGUI {} { + catch {destroy .knightstour} + set dlg [toplevel .knightstour] + wm title $dlg "Knights tour" + wm withdraw $dlg + set f [ttk::frame $dlg.f] + set c [canvas $f.c -width 240 -height 240] + text $f.txt -width 10 -height 1 \ + -yscrollcommand [list $f.vs set] -font {Arial 8} + ttk::scrollbar $f.vs -command [list $f.txt yview] + + variable delay 600 + variable continuous 0 + ttk::frame $dlg.tf + ttk::label $dlg.tf.ls -text Speed + ttk::scale $dlg.tf.sc -from 8 -to 2000 -command [list SetDelay] \ + -variable [namespace which -variable delay] + ttk::checkbutton $dlg.tf.cc -text Repeat \ + -variable [namespace which -variable continuous] + ttk::button $dlg.tf.b1 -text Start -command [list Tour $dlg] + ttk::button $dlg.tf.b2 -text Exit -command [list Exit $dlg] + set square 0 + for {set row 7} {$row >= 0} {incr row -1} { + for {set col 0} {$col < 8} {incr col} { + if {(($col & 1) ^ ($row & 1))} { + set fill tan3 ; set dfill tan4 + } else { + set fill bisque ; set dfill bisque3 + } + set coords [list [expr {$col * 30 + 4}] [expr {$row * 30 + 4}] \ + [expr {$col * 30 + 30}] [expr {$row * 30 + 30}]] + $c create rectangle $coords -fill $fill -disabledfill $dfill \ + -width 2 -state disabled -outline black + } + } + if {[tk windowingsystem] ne "x11"} { + catch {eval font create KnightFont -size -24} + $c create text 0 0 -font KnightFont -text "\u265e" \ + -anchor nw -tags knight -fill black -activefill "#600000" + } else { + # On X11 we cannot reliably tell if the \u265e glyph is available + # so just use a polygon + set pts { + 2 25 24 25 21 19 20 8 14 0 10 0 0 13 0 16 + 2 17 4 14 5 15 3 17 5 17 9 14 10 15 5 21 + } + $c create polygon $pts -tag knight -offset 8 \ + -fill black -activefill "#600000" + } + $c moveto knight {*}[lrange [$c coords [expr {1 + int(rand() * 64)}]] 0 1] + $c bind knight [namespace code [list DragStart %W %x %y]] + $c bind knight [namespace code [list DragMotion %W %x %y]] + $c bind knight [namespace code [list DragEnd %W %x %y]] + + grid $c $f.txt $f.vs -sticky news + grid rowconfigure $f 0 -weight 1 + grid columnconfigure $f 1 -weight 1 + + grid $f - - - - - -sticky news + set things [list $dlg.tf.ls $dlg.tf.sc $dlg.tf.cc $dlg.tf.b1] + if {![info exists ::widgetDemo]} { + lappend things $dlg.tf.b2 + if {[tk windowingsystem] ne "aqua"} { + set things [linsert $things 0 [ttk::sizegrip $dlg.tf.sg]] + } + } + pack {*}$things -side right + if {[tk windowingsystem] eq "aqua"} { + pack configure {*}$things -padx {4 4} -pady {12 12} + pack configure [lindex $things 0] -padx {4 24} + pack configure [lindex $things end] -padx {16 4} + } + grid $dlg.tf - - - - - -sticky ew + if {[info exists ::widgetDemo]} { + grid [addSeeDismiss $dlg.buttons $dlg] - - - - - -sticky ew + } + + grid rowconfigure $dlg 0 -weight 1 + grid columnconfigure $dlg 0 -weight 1 + + bind $dlg {console show} + bind $dlg [list $dlg.tf.b1 invoke] + bind $dlg [list $dlg.tf.b2 invoke] + bind $dlg [namespace code [list Stop]] + wm protocol $dlg WM_DELETE_WINDOW [namespace code [list Exit $dlg]] + + wm deiconify $dlg + tkwait window $dlg +} + +if {![winfo exists .knightstour]} { + if {![info exists widgetDemo]} { wm withdraw . } + set r [catch [linsert $argv 0 CreateGUI] err] + if {$r} { + tk_messageBox -icon error -title "Error" -message $err + } + if {![info exists widgetDemo]} { exit $r } +} diff --git a/shared/package-files/7c/7c1f24f749470aa6465ea1caca5fef9aa93f31bd940e75dabc2d3e3e87f6f0ce/blob b/shared/package-files/7c/7c1f24f749470aa6465ea1caca5fef9aa93f31bd940e75dabc2d3e3e87f6f0ce/blob new file mode 100644 index 0000000000000000000000000000000000000000..5f42212b202cc466ef89091ad1bdac4576e59a4a --- /dev/null +++ b/shared/package-files/7c/7c1f24f749470aa6465ea1caca5fef9aa93f31bd940e75dabc2d3e3e87f6f0ce/blob @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_eq_Scalar_out : public at::meta::structured_eq_Scalar { +void impl(const at::Tensor & self, const at::Scalar & other, const at::Tensor & out); +}; +TORCH_API at::Tensor eq_scalar_nested(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor eq_quantized_cpu(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & eq_out_quantized_cpu(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +struct TORCH_API structured_eq_Tensor_out : public at::meta::structured_eq_Tensor { +void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out); +}; +TORCH_API at::Tensor eq_quantized_cpu(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & eq_out_quantized_cpu(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c1f715a4bcc49a5b9fd43e8793be8e4d45c396d21b7ed5add6da38ae095d495/blob b/shared/package-files/7c/7c1f715a4bcc49a5b9fd43e8793be8e4d45c396d21b7ed5add6da38ae095d495/blob new file mode 100644 index 0000000000000000000000000000000000000000..eee2c45fd17cc2817e842d3edcd413b0cf142ffa --- /dev/null +++ b/shared/package-files/7c/7c1f715a4bcc49a5b9fd43e8793be8e4d45c396d21b7ed5add6da38ae095d495/blob @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API batch_norm { + using schema = at::Tensor (const at::Tensor &, const c10::optional &, const c10::optional &, const c10::optional &, const c10::optional &, bool, double, double, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::batch_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor") + static at::Tensor call(const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const c10::optional & running_mean, const c10::optional & running_var, bool training, double momentum, double eps, bool cudnn_enabled); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const c10::optional & weight, const c10::optional & bias, const c10::optional & running_mean, const c10::optional & running_var, bool training, double momentum, double eps, bool cudnn_enabled); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7c2044765616726237b029e9524da9cf6d8662d5f3a93929e8d78ea5d23ae0f6/blob b/shared/package-files/7c/7c2044765616726237b029e9524da9cf6d8662d5f3a93929e8d78ea5d23ae0f6/blob new file mode 100644 index 0000000000000000000000000000000000000000..edfa8d3c16ac8642773651778012a3cd57005d9b --- /dev/null +++ b/shared/package-files/7c/7c2044765616726237b029e9524da9cf6d8662d5f3a93929e8d78ea5d23ae0f6/blob @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.converters import * # noqa diff --git a/shared/package-files/7c/7c217812c06ed17b2236f08f3726d13ab38da9fe2457794f17d3483f94da4aef/blob b/shared/package-files/7c/7c217812c06ed17b2236f08f3726d13ab38da9fe2457794f17d3483f94da4aef/blob new file mode 100644 index 0000000000000000000000000000000000000000..18939577da082d06e9d2d8e191cbf7343c683c07 --- /dev/null +++ b/shared/package-files/7c/7c217812c06ed17b2236f08f3726d13ab38da9fe2457794f17d3483f94da4aef/blob @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor fractional_max_pool3d_backward_cpu(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool3d_backward_out_cpu(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices, at::Tensor & grad_input); +TORCH_API at::Tensor fractional_max_pool3d_backward_cuda(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool3d_backward_out_cuda(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices, at::Tensor & grad_input); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c21c7524d68b6725e4008fc9e7721e3bd323780f305b80660b00b68da364765/blob b/shared/package-files/7c/7c21c7524d68b6725e4008fc9e7721e3bd323780f305b80660b00b68da364765/blob new file mode 100644 index 0000000000000000000000000000000000000000..2a95520d1743d51c4bdcf9245f0b3f13d57c7fca --- /dev/null +++ b/shared/package-files/7c/7c21c7524d68b6725e4008fc9e7721e3bd323780f305b80660b00b68da364765/blob @@ -0,0 +1,791 @@ +""" +Helper and filter functions for VAR and VARMA, and basic VAR class + +Created on Mon Jan 11 11:04:23 2010 +Author: josef-pktd +License: BSD + +This is a new version, I did not look at the old version again, but similar +ideas. + +not copied/cleaned yet: + * fftn based filtering, creating samples with fft + * Tests: I ran examples but did not convert them to tests + examples look good for parameter estimate and forecast, and filter functions + +main TODOs: +* result statistics +* see whether Bayesian dummy observation can be included without changing + the single call to linalg.lstsq +* impulse response function does not treat correlation, see Hamilton and jplv + +Extensions +* constraints, Bayesian priors/penalization +* Error Correction Form and Cointegration +* Factor Models Stock-Watson, ??? + + +see also VAR section in Notes.txt + +""" + +import warnings + +import numpy as np +from scipy import signal + +from statsmodels.tools.validation import string_like +from statsmodels.tsa.tsatools import lagmat + + +def varfilter(x, a): + """ + Apply an autoregressive filter to a series x + + x can be 2d, a can be 1d, 2d, or 3d + + Parameters + ---------- + x : array_like + data array, 1d or 2d, if 2d then observations in rows + a : array_like + autoregressive filter coefficients, ar lag polynomial + see Notes + + Returns + ------- + y : ndarray + filtered array, 2d, number of columns determined by x and a + + Warnings + -------- + convolve does not work as expected; this likely does not work + correctly for nvars>3. + + Notes + ----- + + In general form this uses the linear filter :: + + y = a(L)x + + where + x : nobs, nvars + a : nlags, nvars, npoly + + Depending on the shape and dimension of a this uses different + Lag polynomial arrays + + case 1 : a is 1d or (nlags,1) + one lag polynomial is applied to all variables (columns of x) + case 2 : a is 2d, (nlags, nvars) + each series is independently filtered with its own + lag polynomial, uses loop over nvar + case 3 : a is 3d, (nlags, nvars, npoly) + the ith column of the output array is given by the linear filter + defined by the 2d array a[:,:,i], i.e., :: + + y[:,i] = a(.,.,i)(L) * x + y[t,i] = sum_p sum_j a(p,j,i)*x(t-p,j) + for p = 0,...nlags-1, j = 0,...nvars-1, + for all t >= nlags + + + Note: maybe convert to axis=1, Not + + TODO: initial conditions + + """ + x = np.asarray(x) + a = np.asarray(a) + if x.ndim == 1: + x = x[:, None] + if x.ndim > 2: + raise ValueError("x array has to be 1d or 2d") + nvar = x.shape[1] + nlags = a.shape[0] + ntrim = nlags // 2 + # for x is 2d with ncols >1 + + if a.ndim == 1: + # case: identical ar filter (lag polynomial) + return signal.convolve(x, a[:, None], mode="valid") + # alternative: + # return signal.lfilter(a,[1],x.astype(float),axis=0) + elif a.ndim == 2: + if min(a.shape) == 1: + # case: identical ar filter (lag polynomial) + return signal.convolve(x, a, mode="valid") + + # case: independent ar + # (a bit like recserar in gauss, but no x yet) + # (no, reserar is inverse filter) + result = np.zeros((x.shape[0] - nlags + 1, nvar)) + for i in range(nvar): + # could also use np.convolve, but easier for swiching to fft + result[:, i] = signal.convolve(x[:, i], a[:, i], mode="valid") + return result + + elif a.ndim == 3: + # case: vector autoregressive with lag matrices + # Note: we must have shape[1] == shape[2] == nvar + yf = signal.convolve(x[:, :, None], a) + yvalid = yf[ntrim:-ntrim, yf.shape[1] // 2, :] + return yvalid + + +def varinversefilter(ar, nobs, version=1): + """ + Creates inverse ar filter (MA representation) recursively + + The VAR lag polynomial is defined by :: + + ar(L) y_t = u_t or + y_t = -ar_{-1}(L) y_{t-1} + u_t + + the returned lagpolynomial is arinv(L)=ar^{-1}(L) in :: + + y_t = arinv(L) u_t + + Parameters + ---------- + ar : ndarray, (nlags,nvars,nvars) + matrix lagpolynomial, currently no exog + first row should be identity + nobs : int + Number of observations (time points) for which to compute the + inverse filter. + version : int, optional + Selects the implementation to use. If 1 (the default), the + inverse filter is computed recursively. If 0, the alternative + implementation is not yet finished and raises NotImplementedError. + + Returns + ------- + arinv : ndarray + The inverse (MA representation) lag polynomial array, of shape + (nobs + 1, nvars, nvars). + """ + nlags, nvars, nvarsex = ar.shape + if nvars != nvarsex: + print("exogenous variables not implemented not tested") + arinv = np.zeros((nobs + 1, nvarsex, nvars)) + arinv[0, :, :] = ar[0] + arinv[1:nlags, :, :] = -ar[1:] + if version == 1: + for i in range(2, nobs + 1): + tmp = np.zeros((nvars, nvars)) + for p in range(1, nlags): + tmp += np.dot(-ar[p], arinv[i - p, :, :]) + arinv[i, :, :] = tmp + if version == 0: + for i in range(nlags + 1, nobs + 1): + print(ar[1:].shape, arinv[i - 1 : i - nlags : -1, :, :].shape) + # arinv[i,:,:] = np.dot(-ar[1:],arinv[i-1:i-nlags:-1,:,:]) + # print(np.tensordot(-ar[1:],arinv[i-1:i-nlags:-1,:,:],axes=([2],[1])).shape + # arinv[i,:,:] = np.tensordot(-ar[1:],arinv[i-1:i-nlags:-1,:,:],axes=([2],[1])) + raise NotImplementedError("waiting for generalized ufuncs or something") + + return arinv + + +def vargenerate(ar, u, initvalues=None): + """ + Generate a VAR process with errors u + + similar to gauss + uses loop + + Parameters + ---------- + ar : ndarray + Matrix lagpolynomial, of shape (nlags, nvars, nvars). + u : ndarray + Error terms (innovations) for the VAR process, of shape + (nobs, nvars). + initvalues : ndarray, optional + Initial (presample) values for the process. If None, the initial + values are set to zero. + + Returns + ------- + sar : ndarray + Sample of the VAR process, the inverse filtered `u`. Has shape + (nobs + max(nlags - 1, len(initvalues)), nvars); the presample + values, including the initial condition y_0 = 0, are not + trimmed. + + Examples + -------- + # generate random sample of VAR + nobs, nvars = 10, 2 + u = numpy.random.randn(nobs,nvars) + a21 = np.array([[[ 1. , 0. ], + [ 0. , 1. ]], + + [[-0.8, 0. ], + [ 0., -0.6]]]) + vargenerate(a21,u) + + # Impulse Response to an initial shock to the first variable + imp = np.zeros((nobs, nvars)) + imp[0,0] = 1 + vargenerate(a21,imp) + + """ + nlags, nvars, nvarsex = ar.shape + nlagsm1 = nlags - 1 + nobs = u.shape[0] + if nvars != nvarsex: + print("exogenous variables not implemented not tested") + if u.shape[1] != nvars: + raise ValueError("u needs to have nvars columns") + if initvalues is None: + sar = np.zeros((nobs + nlagsm1, nvars)) + start = nlagsm1 + else: + start = max(nlagsm1, initvalues.shape[0]) + sar = np.zeros((nobs + start, nvars)) + sar[start - initvalues.shape[0] : start] = initvalues + # sar[nlagsm1:] = u + sar[start:] = u + # if version == 1: + for i in range(start, start + nobs): + for p in range(1, nlags): + sar[i] += np.dot(sar[i - p, :], -ar[p]) + + return sar + + +def padone(x, front=0, back=0, axis=0, fillvalue=0): + """ + Pad with zeros along one axis + + Can be used sequentially to pad several axes. + + Parameters + ---------- + x : ndarray + Array to pad. + front : int, optional + Number of `fillvalue` elements to add before the array along + `axis`. + back : int, optional + Number of `fillvalue` elements to add after the array along + `axis`. + axis : int, optional + Axis along which to pad. + fillvalue : scalar, optional + Value used to fill the padded elements. + + Returns + ------- + ndarray + The padded array. + + Examples + -------- + >>> padone(np.ones((2,3)),1,3,axis=1) + array([[ 0., 1., 1., 1., 0., 0., 0.], + [ 0., 1., 1., 1., 0., 0., 0.]]) + + >>> padone(np.ones((2,3)),1,1, fillvalue=np.nan) + array([[ NaN, NaN, NaN], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ NaN, NaN, NaN]]) + """ + # primitive version + shape = np.array(x.shape) + shape[axis] += front + back + shapearr = np.array(x.shape) + out = np.empty(shape) + out.fill(fillvalue) + startind = np.zeros(x.ndim) + startind[axis] = front + endind = startind + shapearr + myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] + # print(myslice + # print(out.shape + # print(out[tuple(myslice)].shape + out[tuple(myslice)] = x + return out + + +def trimone(x, front=0, back=0, axis=0): + """ + Trim a number of array elements along one axis + + Parameters + ---------- + x : ndarray + Array to trim. + front : int, optional + Number of elements to remove from the front along `axis`. + back : int, optional + Number of elements to remove from the back along `axis`. + axis : int, optional + Axis along which to trim. + + Returns + ------- + ndarray + The trimmed array. + + Examples + -------- + >>> xp = padone(np.ones((2,3)),1,3,axis=1) + >>> xp + array([[ 0., 1., 1., 1., 0., 0., 0.], + [ 0., 1., 1., 1., 0., 0., 0.]]) + >>> trimone(xp,1,3,1) + array([[ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + shape = np.array(x.shape) + shape[axis] -= front + back + # print(shape, front, back + startind = np.zeros(x.ndim) + startind[axis] = front + endind = startind + shape + myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] + # print(myslice + # print(shape, endind + # print(x[tuple(myslice)].shape + return x[tuple(myslice)] + + +def ar2full(ar): + """ + Make reduced lagpolynomial into a right side lagpoly array + + Parameters + ---------- + ar : ndarray + Reduced-form lag polynomial array, of shape (nlags, nvar, nvarex). + + Returns + ------- + ndarray + Full (right-hand side) lag polynomial array, of shape + (nlags + 1, nvar, nvarex), with an identity matrix prepended. + """ + nlags, nvar, nvarex = ar.shape + return np.r_[np.eye(nvar, nvarex)[None, :, :], -ar] + + +def ar2lhs(ar): + """ + Convert full (rhs) lagpolynomial into a reduced, left side lagpoly array + + This is mainly a reminder about the definition. + + Parameters + ---------- + ar : ndarray + Full (right-hand side) lag polynomial array. + + Returns + ------- + ndarray + Reduced, left-hand side lag polynomial array. + """ + return -ar[1:] + + +class _Var: + """ + Obsolete VAR class, use tsa.VAR instead, for internal use only + + Examples + -------- + + >>> v = Var(ar2s) + >>> v.fit(1) + >>> v.arhat + array([[[ 1. , 0. ], + [ 0. , 1. ]], + + [[-0.77784898, 0.01726193], + [ 0.10733009, -0.78665335]]]) + + """ + + def __init__(self, y): + warnings.warn( + "_Var is deprecated (its own docstring already called it " + "\"Obsolete\" -- use tsa.VAR instead). It has had no test " + "coverage and its behavior is not guaranteed. It will be " + "removed after statsmodels 0.16 is released. If you rely on " + "this class, please open an issue at " + "https://github.com/statsmodels/statsmodels/issues.", + FutureWarning, + stacklevel=2, + ) + self.y = y + self.nobs, self.nvars = y.shape + + def fit(self, nlags): + """ + Estimate parameters using OLS + + Parameters + ---------- + nlags : int + number of lags to include in regression, same for all variables + + Returns + ------- + None + Nothing is returned; the estimation results are attached to + the instance, see Notes. + + Notes + ----- + This currently assumes all parameters are estimated without restrictions. + In this case SUR is identical to OLS. + + The following are attached to the instance: + + arhat : ndarray of shape (nlags, nvar, nvar) + Full lag polynomial array. + arlhs : ndarray of shape (nlags - 1, nvar, nvar) + Reduced lag polynomial for the left-hand side. + estresults + The full result tuple as returned by ``linalg.lstsq``; other + statistics still need to be completed. + """ + self.nlags = nlags # without current period + nvars = self.nvars + # TODO: ar2s looks like a module variable, bug? + # lmat = lagmat(ar2s, nlags, trim='both', original='in') + lmat = lagmat(self.y, nlags, trim="both", original="in") + self.yred = lmat[:, :nvars] + self.xred = lmat[:, nvars:] + res = np.linalg.lstsq(self.xred, self.yred, rcond=-1) + self.estresults = res + self.arlhs = res[0].reshape(nlags, nvars, nvars) + self.arhat = ar2full(self.arlhs) + self.rss = res[1] + self.xredrank = res[2] + + def predict(self): + """Calculate estimated timeseries (yhat) for sample""" + + if not hasattr(self, "yhat"): + self.yhat = varfilter(self.y, self.arhat) + return self.yhat + + def covmat(self): + """ + Covariance matrix of estimate + + Notes + ----- + Not sure it's correct, need to check orientation everywhere. + Looks ok, display needs getting used to. + + Examples + -------- + >>> v.rss[None,None,:]*np.linalg.inv(np.dot(v.xred.T,v.xred))[:,:,None] + array([[[ 0.37247445, 0.32210609], + [ 0.1002642 , 0.08670584]], + + [[ 0.1002642 , 0.08670584], + [ 0.45903637, 0.39696255]]]) + >>> + >>> v.rss[0]*np.linalg.inv(np.dot(v.xred.T,v.xred)) + array([[ 0.37247445, 0.1002642 ], + [ 0.1002642 , 0.45903637]]) + >>> v.rss[1]*np.linalg.inv(np.dot(v.xred.T,v.xred)) + array([[ 0.32210609, 0.08670584], + [ 0.08670584, 0.39696255]]) + """ + + # check if orientation is same as self.arhat + self.paramcov = ( + self.rss[None, None, :] + * np.linalg.inv(np.dot(self.xred.T, self.xred))[:, :, None] + ) + + def forecast(self, horiz=1, u=None): + """ + Calculates forecast for horiz number of periods at end of sample + + Parameters + ---------- + horiz : int, optional + Forecast horizon. + u : ndarray, optional + Error term for forecast periods, of shape (horiz, nvars). If + None, then u is zero. + + Returns + ------- + yforecast : ndarray + Forecast array, of shape (nobs + horiz, nvars); this includes + the sample and the forecasts. + """ + if u is None: + u = np.zeros((horiz, self.nvars)) + return vargenerate(self.arhat, u, initvalues=self.y) + + +class VarmaPoly: + """ + Class to keep track of Varma polynomial format + + Parameters + ---------- + ar : ndarray + The autoregressive lag polynomial array, of shape + (nlags, nvarall, nvars). + ma : ndarray, optional + The moving-average lag polynomial array, of shape + (malags, nvars, nvars). If None, no moving-average terms are + used and an identity matrix is used in their place. + + Examples + -------- + + ar23 = np.array([[[ 1. , 0. ], + [ 0. , 1. ]], + + [[-0.6, 0. ], + [ 0.2, -0.6]], + + [[-0.1, 0. ], + [ 0.1, -0.1]]]) + + ma22 = np.array([[[ 1. , 0. ], + [ 0. , 1. ]], + + [[ 0.4, 0. ], + [ 0.2, 0.3]]]) + + + """ + + def __init__(self, ar, ma=None): + self.ar = ar + self.ma = ma + nlags, nvarall, nvars = ar.shape + self.nlags, self.nvarall, self.nvars = nlags, nvarall, nvars + self.isstructured = not (ar[0, :nvars] == np.eye(nvars)).all() + if self.ma is None: + self.ma = np.eye(nvars)[None, ...] + self.isindependent = True + else: + self.isindependent = not (ma[0] == np.eye(nvars)).all() + self.malags = ar.shape[0] + self.hasexog = nvarall > nvars + self.arm1 = -ar[1:] + + # @property + def vstack(self, a=None, name="ar"): + """ + Stack lagpolynomial vertically in 2d array + + Parameters + ---------- + a : ndarray, optional + Lag polynomial array to stack. If None, uses ``self.ar`` or + ``self.ma``, selected by `name`. + name : {"ar", "ma"}, optional + Which instance lag polynomial to use when `a` is None. + + Returns + ------- + ndarray + The lag polynomial stacked vertically into a 2d array. + """ + if a is not None: + _a = a + else: + name = string_like(name, "name", options=("ar", "ma")) + _a = self.ar if name == "ar" else self.ma + return _a.reshape(-1, self.nvarall) + + # @property + def hstack(self, a=None, name="ar"): + """ + Stack lagpolynomial horizontally in 2d array + + Parameters + ---------- + a : ndarray, optional + Lag polynomial array to stack. If None, uses ``self.ar`` or + ``self.ma``, selected by `name`. + name : {"ar", "ma"}, optional + Which instance lag polynomial to use when `a` is None. + + Returns + ------- + ndarray + The lag polynomial stacked horizontally into a 2d array. + """ + if a is not None: + _a = a + else: + name = string_like(name, "name", options=("ar", "ma")) + _a = self.ar if name == "ar" else self.ma + return _a.swapaxes(1, 2).reshape(-1, self.nvarall).T + + # @property + def stacksquare(self, a=None, name="ar", orientation="vertical"): + """ + Stack lagpolynomial vertically in 2d square array with eye + + Parameters + ---------- + a : ndarray, optional + Lag polynomial array to stack. If None, uses ``self.ar`` or + ``self.ma``, selected by `name`. + name : {"ar", "ma"}, optional + Which instance lag polynomial to use when `a` is None. + orientation : str, optional + Currently not used. + + Returns + ------- + ndarray + The lag polynomial stacked vertically into a 2d square array, + with an identity block appended. + """ + if a is not None: + _a = a + else: + name = string_like(name, "name", options=("ar", "ma")) + _a = self.ar if name == "ar" else self.ma + astacked = _a.reshape(-1, self.nvarall) + lenpk, nvars = astacked.shape # [0] + amat = np.eye(lenpk, k=nvars) + amat[:, :nvars] = astacked + return amat + + # @property + def vstackarma_minus1(self): + """Stack ar and lagpolynomial vertically in 2d array""" + a = np.concatenate((self.ar[1:], self.ma[1:]), 0) + return a.reshape(-1, self.nvarall) + + # @property + def hstackarma_minus1(self): + """ + Stack ar and lagpolynomial vertically in 2d array + + This is the Kalman Filter representation, I think. + """ + a = np.concatenate((self.ar[1:], self.ma[1:]), 0) + return a.swapaxes(1, 2).reshape(-1, self.nvarall) + + def getisstationary(self, a=None): + """ + Check whether the auto-regressive lag-polynomial is stationary + + Parameters + ---------- + a : ndarray, optional + The lag polynomial array to check. If None, uses the reduced + form of ``self.ar``. + + Returns + ------- + isstationary : bool + True if all eigenvalues of the lag-polynomial are less than one + in absolute value. + + Notes + ----- + Attaches ``areigenvalues``, the eigenvalues sorted by absolute + value, as a complex array. + + References + ---------- + Formula taken from NAG manual. + """ + if a is not None: + _a = a + elif self.isstructured: + _a = -self.reduceform(self.ar)[1:] + else: + _a = -self.ar[1:] + amat = self.stacksquare(_a) + ev = np.sort(np.linalg.eigvals(amat))[::-1] + self.areigenvalues = ev + return (np.abs(ev) < 1).all() + + def getisinvertible(self, a=None): + """ + Check whether the moving-average lag-polynomial is invertible + + Parameters + ---------- + a : ndarray, optional + The lag polynomial array to check. If None, uses the reduced + form of ``self.ma``. + + Returns + ------- + isinvertible : bool + True if all eigenvalues of the lag-polynomial are less than one + in absolute value. + + Notes + ----- + Attaches ``maeigenvalues``, the eigenvalues sorted by absolute + value, as a complex array. + + References + ---------- + Formula taken from NAG manual. + """ + if a is not None: + _a = a + elif self.isindependent: + _a = self.reduceform(self.ma)[1:] + else: + _a = self.ma[1:] + if _a.shape[0] == 0: + # no ma lags + self.maeigenvalues = np.array([], dtype=complex) + return True + + amat = self.stacksquare(_a) + ev = np.sort(np.linalg.eigvals(amat))[::-1] + self.maeigenvalues = ev + return (np.abs(ev) < 1).all() + + def reduceform(self, apoly): + """ + Convert a structural lag polynomial to reduced form + + This assumes no exog, todo + + Parameters + ---------- + apoly : ndarray + 3d lag polynomial array, of shape (nlags, nvars, nvars). + + Returns + ------- + ndarray + The reduced-form lag polynomial array, with the same shape as + `apoly`. + """ + if apoly.ndim != 3: + raise ValueError("apoly needs to be 3d") + nlags, nvarsex, nvars = apoly.shape + + try: + a0inv = np.linalg.inv(apoly[0, :nvars, :]) + except np.linalg.LinAlgError as la_err: + raise ValueError( + "matrix not invertible, ask for implementation of pinv" + ) from la_err + + a = np.empty_like(apoly) + for lag in range(nlags): + a[lag] = np.dot(a0inv, apoly[lag]) + + return a diff --git a/shared/package-files/7c/7c2372877793688738dda5eb84c6302f8554151560707beda5cf6f63ce20439b/blob b/shared/package-files/7c/7c2372877793688738dda5eb84c6302f8554151560707beda5cf6f63ce20439b/blob new file mode 100644 index 0000000000000000000000000000000000000000..cd51138e08a6a8928ee316d8e064fe8d506309ff --- /dev/null +++ b/shared/package-files/7c/7c2372877793688738dda5eb84c6302f8554151560707beda5cf6f63ce20439b/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::vector _foreach_round(at::TensorList self); +TORCH_API void _foreach_round_(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7c/7c24481ec3f85de7aabd9cd01851770c56f9c9a901f570ad4ab71827afede63b/blob b/shared/package-files/7c/7c24481ec3f85de7aabd9cd01851770c56f9c9a901f570ad4ab71827afede63b/blob new file mode 100644 index 0000000000000000000000000000000000000000..09ca2c0f8064899914d666bd626de0c93ebe5df2 --- /dev/null +++ b/shared/package-files/7c/7c24481ec3f85de7aabd9cd01851770c56f9c9a901f570ad4ab71827afede63b/blob @@ -0,0 +1,201 @@ +"","x","y","y_est" +"1",-10,0,0.872773934309234 +"2",-9.89949748743719,0,0.914587328782016 +"3",-9.79899497487437,1,0.956147534160093 +"4",-9.69849246231156,1,0.997201361348758 +"5",-9.59798994974874,1,1.03749562125331 +"6",-9.49748743718593,1,1.07677712477903 +"7",-9.39698492462312,1,1.11479268283124 +"8",-9.2964824120603,1,1.1512891063152 +"9",-9.19597989949749,1,1.18601320613623 +"10",-9.09547738693467,1,1.21871179319962 +"11",-8.99497487437186,1,1.24913167841065 +"12",-8.89447236180905,1,1.27701967267464 +"13",-8.79396984924623,0,1.30212258689686 +"14",-8.69346733668342,1,1.32418723198261 +"15",-8.5929648241206,1,1.3429604188372 +"16",-8.49246231155779,1,1.35818895836591 +"17",-8.39195979899498,0,1.36961966147404 +"18",-8.29145728643216,1,1.37699933906688 +"19",-8.19095477386935,1,1.38007480204973 +"20",-8.09045226130653,0,1.37859286132787 +"21",-7.98994974874372,1,1.37230032780662 +"22",-7.8894472361809,1,1.36094401239126 +"23",-7.78894472361809,1,1.34427072598708 +"24",-7.68844221105528,1,1.32213697950808 +"25",-7.58793969849246,1,1.29501313254974 +"26",-7.48743718592965,0,1.26358294550573 +"27",-7.38693467336683,1,1.22853039302752 +"28",-7.28643216080402,0,1.1905394497666 +"29",-7.18592964824121,1,1.15029409037445 +"30",-7.08542713567839,1,1.10847828950257 +"31",-6.98492462311558,0,1.06577602180244 +"32",-6.88442211055276,1,1.02287126192554 +"33",-6.78391959798995,1,0.980447984523354 +"34",-6.68341708542714,1,0.939190164247379 +"35",-6.58291457286432,0,0.899781775749094 +"36",-6.48241206030151,1,0.862906793679986 +"37",-6.38190954773869,1,0.829249192691541 +"38",-6.28140703517588,1,0.799492947435244 +"39",-6.18090452261307,1,0.774322032562581 +"40",-6.08040201005025,1,0.754420422725038 +"41",-5.97989949748744,1,0.740472092574101 +"42",-5.87939698492462,0,0.733161016761255 +"43",-5.77889447236181,1,0.733171169937986 +"44",-5.67839195979899,1,0.741186526755779 +"45",-5.57788944723618,0,0.757891061866122 +"46",-5.47738693467337,0,0.783825768321446 +"47",-5.37688442211055,1,0.81839612350124 +"48",-5.27638190954774,0,0.860466108874879 +"49",-5.17587939698492,1,0.908896371063943 +"50",-5.07537688442211,1,0.962547556690015 +"51",-4.9748743718593,0,1.02028031237468 +"52",-4.87437185929648,1,1.08095528473951 +"53",-4.77386934673367,1,1.1434331204061 +"54",-4.67336683417085,1,1.20657446599603 +"55",-4.57286432160804,1,1.26923996813087 +"56",-4.47236180904523,1,1.33029027343222 +"57",-4.37185929648241,1,1.38858602852165 +"58",-4.2713567839196,1,1.44298788002074 +"59",-4.17085427135678,0,1.49235647455108 +"60",-4.07035175879397,1,1.53555245873425 +"61",-3.96984924623116,1,1.57143647919183 +"62",-3.86934673366834,1,1.59886918254541 +"63",-3.76884422110553,0,1.61671121541656 +"64",-3.66834170854271,1,1.62382322442687 +"65",-3.5678391959799,1,1.61906585619792 +"66",-3.46733668341709,1,1.60129975735129 +"67",-3.36683417085427,0,1.56938557450856 +"68",-3.26633165829146,1,1.52228903292485 +"69",-3.16582914572864,0,1.46019739696999 +"70",-3.06532663316583,1,1.38408602076526 +"71",-2.96482412060301,1,1.29494339326115 +"72",-2.8643216080402,1,1.19375800340811 +"73",-2.76381909547739,1,1.08151834015664 +"74",-2.66331658291457,0,0.959212892457185 +"75",-2.56281407035176,1,0.827830149260236 +"76",-2.46231155778894,1,0.688358599516262 +"77",-2.36180904522613,1,0.541786732175736 +"78",-2.26130653266332,1,0.389103036189131 +"79",-2.1608040201005,1,0.23129600050692 +"80",-2.06030150753769,0,0.0693541140795766 +"81",-1.95979899497487,1,-0.0957341341424275 +"82",-1.85929648241206,0,-0.262980255208617 +"83",-1.75879396984925,1,-0.431395760168519 +"84",-1.65829145728643,1,-0.599992160071661 +"85",-1.55778894472362,0,-0.76778096596757 +"86",-1.4572864321608,1,-0.933773688905772 +"87",-1.35678391959799,0,-1.09698183993579 +"88",-1.25628140703517,0,-1.25641693010716 +"89",-1.15577889447236,0,-1.41109047046941 +"90",-1.05527638190955,0,-1.5600238850824 +"91",-0.954773869346733,0,-1.70241655636777 +"92",-0.854271356783919,0,-1.83762179597183 +"93",-0.753768844221105,0,-1.96499799100219 +"94",-0.653266331658291,0,-2.08390352856645 +"95",-0.552763819095476,0,-2.19369679577221 +"96",-0.452261306532662,0,-2.29373617972709 +"97",-0.351758793969848,0,-2.38338006753869 +"98",-0.251256281407034,0,-2.46198684631461 +"99",-0.15075376884422,0,-2.52891490316247 +"100",-0.0502512562814061,0,-2.58352262518986 +"101",0.0502512562814079,0,-2.6251683995044 +"102",0.150753768844222,0,-2.65321061321369 +"103",0.251256281407036,0,-2.66700765342533 +"104",0.35175879396985,0,-2.66591790724694 +"105",0.452261306532664,0,-2.64929976178612 +"106",0.552763819095478,0,-2.61651160415047 +"107",0.653266331658292,0,-2.5669118214476 +"108",0.753768844221106,0,-2.49985880078512 +"109",0.85427135678392,0,-2.41471092927063 +"110",0.954773869346734,0,-2.31082659401174 +"111",1.05527638190955,0,-2.18756418211606 +"112",1.15577889447236,0,-2.04432087552674 +"113",1.25628140703518,0,-1.88167043080889 +"114",1.35678391959799,0,-1.70154684844915 +"115",1.4572864321608,0,-1.50595990009734 +"116",1.55778894472362,1,-1.29691935740326 +"117",1.65829145728643,0,-1.07643499201674 +"118",1.75879396984925,1,-0.846516575587594 +"119",1.85929648241206,0,-0.60917387976564 +"120",1.95979899497488,0,-0.366416676200693 +"121",2.06030150753769,1,-0.120254736542572 +"122",2.1608040201005,1,0.127302167558909 +"123",2.26130653266332,0,0.37424426445393 +"124",2.36180904522613,1,0.618561782492676 +"125",2.46231155778895,1,0.858244950025329 +"126",2.56281407035176,1,1.09128399540207 +"127",2.66331658291457,1,1.31566914697309 +"128",2.76381909547739,1,1.52939063308856 +"129",2.8643216080402,0,1.73043868209868 +"130",2.96482412060302,1,1.91680352235361 +"131",3.06532663316583,1,2.08647538220355 +"132",3.16582914572864,1,2.23744448999868 +"133",3.26633165829146,1,2.36770107408919 +"134",3.36683417085427,1,2.47525668488848 +"135",3.46733668341709,1,2.55940219660391 +"136",3.5678391959799,1,2.62141143532344 +"137",3.66834170854271,1,2.66272880364089 +"138",3.76884422110553,1,2.68479870415008 +"139",3.86934673366834,1,2.68906553944483 +"140",3.96984924623116,0,2.67697371211895 +"141",4.07035175879397,1,2.64996762476627 +"142",4.17085427135678,1,2.6094916799806 +"143",4.2713567839196,1,2.55699028035576 +"144",4.37185929648241,1,2.49390782848557 +"145",4.47236180904523,1,2.42168872696384 +"146",4.57286432160804,1,2.3417773783844 +"147",4.67336683417085,1,2.25561818534107 +"148",4.77386934673367,1,2.16465555042766 +"149",4.87437185929648,1,2.07033387623799 +"150",4.9748743718593,0,1.97409756536587 +"151",5.07537688442211,1,1.87739102040514 +"152",5.17587939698493,1,1.7816586439496 +"153",5.27638190954774,1,1.68834483859308 +"154",5.37688442211055,0,1.59889400692939 +"155",5.47738693467337,1,1.51475055155235 +"156",5.57788944723618,1,1.4373555314731 +"157",5.678391959799,1,1.36760709146401 +"158",5.77889447236181,1,1.30526488639263 +"159",5.87939698492462,1,1.24994521501885 +"160",5.97989949748744,0,1.20126437610251 +"161",6.08040201005025,1,1.15883866840349 +"162",6.18090452261307,1,1.12228439068165 +"163",6.28140703517588,1,1.09121784169686 +"164",6.38190954773869,1,1.06525532020898 +"165",6.48241206030151,1,1.04401312497788 +"166",6.58291457286432,0,1.02710755476343 +"167",6.68341708542714,1,1.01415490832548 +"168",6.78391959798995,0,1.0047714844239 +"169",6.88442211055277,1,0.998573581818567 +"170",6.98492462311558,1,0.995177499269337 +"171",7.08542713567839,0,0.994199535536078 +"172",7.18592964824121,1,0.995255989378654 +"173",7.28643216080402,1,0.997963159556932 +"174",7.38693467336683,1,1.00193734483078 +"175",7.48743718592965,1,1.00679484396005 +"176",7.58793969849246,1,1.01215195570463 +"177",7.68844221105528,1,1.01762497882437 +"178",7.78894472361809,0,1.02283030609777 +"179",7.88944723618091,0,1.02747797286506 +"180",7.98994974874372,1,1.03154737785938 +"181",8.09045226130653,1,1.03506605735562 +"182",8.19095477386935,0,1.03806154762869 +"183",8.29145728643216,1,1.0405613849535 +"184",8.39195979899498,0,1.04259310560495 +"185",8.49246231155779,1,1.04418424585794 +"186",8.5929648241206,1,1.04536234198738 +"187",8.69346733668342,1,1.04615493026816 +"188",8.79396984924623,1,1.0465895469752 +"189",8.89447236180905,1,1.0466937283834 +"190",8.99497487437186,1,1.04649501076765 +"191",9.09547738693468,1,1.04602093040287 +"192",9.19597989949749,1,1.04529902356396 +"193",9.2964824120603,1,1.04435682652581 +"194",9.39698492462312,0,1.04322187556335 +"195",9.49748743718593,1,1.04192170695146 +"196",9.59798994974874,0,1.04048385696505 +"197",9.69849246231156,0,1.03893586187903 +"198",9.79899497487437,1,1.03730525796829 +"199",9.89949748743719,1,1.03561958150775 +"200",10,1,1.03390636877231 diff --git a/shared/package-files/7c/7c262b62985863aad47f13b0ef5db2e5cc917b5d38002de9a2ea83ddb0883458/blob b/shared/package-files/7c/7c262b62985863aad47f13b0ef5db2e5cc917b5d38002de9a2ea83ddb0883458/blob new file mode 100644 index 0000000000000000000000000000000000000000..cb56709a77dedb471150f4907771bf38f1879ba4 Binary files /dev/null and b/shared/package-files/7c/7c262b62985863aad47f13b0ef5db2e5cc917b5d38002de9a2ea83ddb0883458/blob differ diff --git a/shared/package-files/7c/7c284fc3bc6770d0933cc5066f40bc042fa50ca1d6a045d2cfc45be16bfcbcda/blob b/shared/package-files/7c/7c284fc3bc6770d0933cc5066f40bc042fa50ca1d6a045d2cfc45be16bfcbcda/blob new file mode 100644 index 0000000000000000000000000000000000000000..fbb26ac281dff81ea71b30318731065fe5a78f94 --- /dev/null +++ b/shared/package-files/7c/7c284fc3bc6770d0933cc5066f40bc042fa50ca1d6a045d2cfc45be16bfcbcda/blob @@ -0,0 +1,32 @@ +import numpy as np +from numpy import sqrt, log, pi +from scipy.special._testutils import FuncData +from scipy.special import spence + + +def test_consistency(): + # Make sure the implementation of spence for real arguments + # agrees with the implementation of spence for imaginary arguments. + + x = np.logspace(-30, 300, 200) + dataset = np.vstack((x + 0j, spence(x))).T + FuncData(spence, dataset, 0, 1, rtol=1e-14).check() + + +def test_special_points(): + # Check against known values of Spence's function. + + phi = (1 + sqrt(5))/2 + dataset = [(1, 0), + (2, -pi**2/12), + (0.5, pi**2/12 - log(2)**2/2), + (0, pi**2/6), + (-1, pi**2/4 - 1j*pi*log(2)), + ((-1 + sqrt(5))/2, pi**2/15 - log(phi)**2), + ((3 - sqrt(5))/2, pi**2/10 - log(phi)**2), + (phi, -pi**2/15 + log(phi)**2/2), + # Corrected from Zagier, "The Dilogarithm Function" + ((3 + sqrt(5))/2, -pi**2/10 - log(phi)**2)] + + dataset = np.asarray(dataset) + FuncData(spence, dataset, 0, 1, rtol=1e-14).check() diff --git a/shared/package-files/7c/7c301fc7ccc7fb1d0f63ad366e487e18fe758ddd0b06d11db1ab7ea4e79eabfc/blob b/shared/package-files/7c/7c301fc7ccc7fb1d0f63ad366e487e18fe758ddd0b06d11db1ab7ea4e79eabfc/blob new file mode 100644 index 0000000000000000000000000000000000000000..de2ccd7689a6b6d204318bf574a65f4500d3199f Binary files /dev/null and b/shared/package-files/7c/7c301fc7ccc7fb1d0f63ad366e487e18fe758ddd0b06d11db1ab7ea4e79eabfc/blob differ diff --git a/shared/package-files/7c/7c329e09fba37782964c757184adee10727071cd73d296b82a986ae85416fcf4/blob b/shared/package-files/7c/7c329e09fba37782964c757184adee10727071cd73d296b82a986ae85416fcf4/blob new file mode 100644 index 0000000000000000000000000000000000000000..0b5b5b1b3f955abf2ec36a806fb1344611c4f060 --- /dev/null +++ b/shared/package-files/7c/7c329e09fba37782964c757184adee10727071cd73d296b82a986ae85416fcf4/blob @@ -0,0 +1,415 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch { +namespace nn { + +namespace detail { + +typedef std::variant< + enumtype::kZeros, + enumtype::kReflect, + enumtype::kReplicate, + enumtype::kCircular> + conv_padding_mode_t; + +template +using conv_padding_t = + std::variant, enumtype::kValid, enumtype::kSame>; + +/// Options for a `D`-dimensional convolution or convolution transpose module. +template +struct ConvNdOptions { + using padding_t = conv_padding_t; + ConvNdOptions( + int64_t in_channels, + int64_t out_channels, + ExpandingArray kernel_size) + : in_channels_(in_channels), + out_channels_(out_channels), + kernel_size_(std::move(kernel_size)) {} + + /// The number of channels the input volumes will have. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(int64_t, in_channels); + + /// The number of output channels the convolution should produce. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(int64_t, out_channels); + + /// The kernel size to use. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, kernel_size); + + /// The stride of the convolution. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, stride) = 1; + + /// The padding to add to the input volumes. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(padding_t, padding) = 0; + + public: + decltype(auto) padding(std::initializer_list il) { + return padding(IntArrayRef{il}); + } + + /// The kernel dilation. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, dilation) = 1; + + /// If true, convolutions will be transpose convolutions (a.k.a. + /// deconvolutions). + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(bool, transposed) = false; + + /// For transpose convolutions, the padding to add to output volumes. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, output_padding) = 0; + + /// The number of convolution groups. + /// This parameter __can__ be changed after construction. + TORCH_ARG(int64_t, groups) = 1; + + /// Whether to add a bias after individual applications of the kernel. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(bool, bias) = true; + + /// Accepted values `torch::kZeros`, `torch::kReflect`, `torch::kReplicate` or + /// `torch::kCircular`. Default: `torch::kZeros` + TORCH_ARG(conv_padding_mode_t, padding_mode) = torch::kZeros; +}; + +} // namespace detail + +// ============================================================================ + +/// Options for a `D`-dimensional convolution module. +template +struct ConvOptions { + using padding_mode_t = detail::conv_padding_mode_t; + using padding_t = detail::conv_padding_t; + + ConvOptions( + int64_t in_channels, + int64_t out_channels, + ExpandingArray kernel_size) + : in_channels_(in_channels), + out_channels_(out_channels), + kernel_size_(std::move(kernel_size)) {} + + /// The number of channels the input volumes will have. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(int64_t, in_channels); + + /// The number of output channels the convolution should produce. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(int64_t, out_channels); + + /// The kernel size to use. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, kernel_size); + + /// The stride of the convolution. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, stride) = 1; + + /// The padding to add to the input volumes. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(padding_t, padding) = 0; + + public: + decltype(auto) padding(std::initializer_list il) { + return padding(IntArrayRef{il}); + } + + /// The kernel dilation. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, dilation) = 1; + + /// The number of convolution groups. + /// This parameter __can__ be changed after construction. + TORCH_ARG(int64_t, groups) = 1; + + /// Whether to add a bias after individual applications of the kernel. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(bool, bias) = true; + + /// Accepted values `torch::kZeros`, `torch::kReflect`, `torch::kReplicate` or + /// `torch::kCircular`. Default: `torch::kZeros` + TORCH_ARG(padding_mode_t, padding_mode) = torch::kZeros; +}; + +/// `ConvOptions` specialized for the `Conv1d` module. +/// +/// Example: +/// ``` +/// Conv1d model(Conv1dOptions(3, 2, 3).stride(1).bias(false)); +/// ``` +using Conv1dOptions = ConvOptions<1>; + +/// `ConvOptions` specialized for the `Conv2d` module. +/// +/// Example: +/// ``` +/// Conv2d model(Conv2dOptions(3, 2, 3).stride(1).bias(false)); +/// ``` +using Conv2dOptions = ConvOptions<2>; + +/// `ConvOptions` specialized for the `Conv3d` module. +/// +/// Example: +/// ``` +/// Conv3d model(Conv3dOptions(3, 2, 3).stride(1).bias(false)); +/// ``` +using Conv3dOptions = ConvOptions<3>; + +// ============================================================================ + +namespace functional { + +/// Options for a `D`-dimensional convolution functional. +template +struct ConvFuncOptions { + using padding_t = torch::nn::detail::conv_padding_t; + + /// optional bias of shape `(out_channels)`. Default: ``None`` + TORCH_ARG(torch::Tensor, bias) = Tensor(); + + /// The stride of the convolving kernel. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + TORCH_ARG(ExpandingArray, stride) = 1; + + /// Implicit paddings on both sides of the input. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + TORCH_ARG(padding_t, padding) = 0; + + public: + decltype(auto) padding(std::initializer_list il) { + return padding(IntArrayRef{il}); + } + + /// The spacing between kernel elements. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + TORCH_ARG(ExpandingArray, dilation) = 1; + + /// Split input into groups, `in_channels` should be divisible by + /// the number of groups. + TORCH_ARG(int64_t, groups) = 1; +}; + +/// `ConvFuncOptions` specialized for `torch::nn::functional::conv1d`. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::conv1d(x, weight, F::Conv1dFuncOptions().stride(1)); +/// ``` +using Conv1dFuncOptions = ConvFuncOptions<1>; + +/// `ConvFuncOptions` specialized for `torch::nn::functional::conv2d`. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::conv2d(x, weight, F::Conv2dFuncOptions().stride(1)); +/// ``` +using Conv2dFuncOptions = ConvFuncOptions<2>; + +/// `ConvFuncOptions` specialized for `torch::nn::functional::conv3d`. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::conv3d(x, weight, F::Conv3dFuncOptions().stride(1)); +/// ``` +using Conv3dFuncOptions = ConvFuncOptions<3>; + +} // namespace functional + +// ============================================================================ + +template +struct ConvTransposeOptions { + using padding_mode_t = detail::conv_padding_mode_t; + + ConvTransposeOptions( + int64_t in_channels, + int64_t out_channels, + ExpandingArray kernel_size) + : in_channels_(in_channels), + out_channels_(out_channels), + kernel_size_(std::move(kernel_size)) {} + + /// The number of channels the input volumes will have. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(int64_t, in_channels); + + /// The number of output channels the convolution should produce. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(int64_t, out_channels); + + /// The kernel size to use. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, kernel_size); + + /// The stride of the convolution. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, stride) = 1; + + /// The padding to add to the input volumes. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, padding) = 0; + + /// For transpose convolutions, the padding to add to output volumes. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, output_padding) = 0; + + /// The number of convolution groups. + /// This parameter __can__ be changed after construction. + TORCH_ARG(int64_t, groups) = 1; + + /// Whether to add a bias after individual applications of the kernel. + /// Changing this parameter after construction __has no effect__. + TORCH_ARG(bool, bias) = true; + + /// The kernel dilation. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + /// This parameter __can__ be changed after construction. + TORCH_ARG(ExpandingArray, dilation) = 1; + + /// Accepted values `torch::kZeros`, `torch::kReflect`, `torch::kReplicate` or + /// `torch::kCircular`. Default: `torch::kZeros` + TORCH_ARG(padding_mode_t, padding_mode) = torch::kZeros; +}; + +/// `ConvTransposeOptions` specialized for the `ConvTranspose1d` module. +/// +/// Example: +/// ``` +/// ConvTranspose1d model(ConvTranspose1dOptions(3, 2, +/// 3).stride(1).bias(false)); +/// ``` +using ConvTranspose1dOptions = ConvTransposeOptions<1>; + +/// `ConvTransposeOptions` specialized for the `ConvTranspose2d` module. +/// +/// Example: +/// ``` +/// ConvTranspose2d model(ConvTranspose2dOptions(3, 2, +/// 3).stride(1).bias(false)); +/// ``` +using ConvTranspose2dOptions = ConvTransposeOptions<2>; + +/// `ConvTransposeOptions` specialized for the `ConvTranspose3d` module. +/// +/// Example: +/// ``` +/// ConvTranspose3d model(ConvTranspose3dOptions(2, 2, +/// 2).stride(1).bias(false)); +/// ``` +using ConvTranspose3dOptions = ConvTransposeOptions<3>; + +// ============================================================================ + +namespace functional { + +/// Options for a `D`-dimensional convolution functional. +template +struct ConvTransposeFuncOptions { + /// optional bias of shape `(out_channels)`. Default: ``None`` + TORCH_ARG(torch::Tensor, bias) = Tensor(); + + /// The stride of the convolving kernel. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + TORCH_ARG(ExpandingArray, stride) = 1; + + /// Implicit paddings on both sides of the input. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + TORCH_ARG(ExpandingArray, padding) = 0; + + /// Additional size added to one side of each dimension in the output shape. + /// Default: 0 + TORCH_ARG(ExpandingArray, output_padding) = 0; + + /// Split input into groups, `in_channels` should be divisible by + /// the number of groups. + TORCH_ARG(int64_t, groups) = 1; + + /// The spacing between kernel elements. + /// For a `D`-dim convolution, must be a single number or a list of `D` + /// numbers. + TORCH_ARG(ExpandingArray, dilation) = 1; +}; + +/// `ConvTransposeFuncOptions` specialized for +/// `torch::nn::functional::conv_transpose1d`. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::conv_transpose1d(x, weight, F::ConvTranspose1dFuncOptions().stride(1)); +/// ``` +using ConvTranspose1dFuncOptions = ConvTransposeFuncOptions<1>; + +/// `ConvTransposeFuncOptions` specialized for +/// `torch::nn::functional::conv_transpose2d`. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::conv_transpose2d(x, weight, F::ConvTranspose2dFuncOptions().stride(1)); +/// ``` +using ConvTranspose2dFuncOptions = ConvTransposeFuncOptions<2>; + +/// `ConvTransposeFuncOptions` specialized for +/// `torch::nn::functional::conv_transpose3d`. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::conv_transpose3d(x, weight, F::ConvTranspose3dFuncOptions().stride(1)); +/// ``` +using ConvTranspose3dFuncOptions = ConvTransposeFuncOptions<3>; + +} // namespace functional + +} // namespace nn +} // namespace torch diff --git a/shared/package-files/7c/7c33f036b16003edcf2c5f5114dc6156fbb9b1e13973c6d30e9a19c6a1d2bd43/blob b/shared/package-files/7c/7c33f036b16003edcf2c5f5114dc6156fbb9b1e13973c6d30e9a19c6a1d2bd43/blob new file mode 100644 index 0000000000000000000000000000000000000000..71b11c9fe151c310f4fd5a60f99323360e493506 --- /dev/null +++ b/shared/package-files/7c/7c33f036b16003edcf2c5f5114dc6156fbb9b1e13973c6d30e9a19c6a1d2bd43/blob @@ -0,0 +1,335 @@ +"""Testing for Spectral Clustering methods""" + +import pickle +import re + +import numpy as np +import pytest +from scipy.linalg import LinAlgError + +from sklearn.cluster import SpectralClustering, spectral_clustering +from sklearn.cluster._spectral import cluster_qr, discretize +from sklearn.datasets import make_blobs +from sklearn.feature_extraction import img_to_graph +from sklearn.metrics import adjusted_rand_score +from sklearn.metrics.pairwise import kernel_metrics, rbf_kernel +from sklearn.neighbors import NearestNeighbors +from sklearn.utils import check_random_state +from sklearn.utils._testing import assert_array_equal +from sklearn.utils.fixes import COO_CONTAINERS, CSR_CONTAINERS + +try: + from pyamg import smoothed_aggregation_solver # noqa: F401 + + amg_loaded = True +except ImportError: + amg_loaded = False + +centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 +X, _ = make_blobs( + n_samples=60, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=0, +) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +@pytest.mark.parametrize("eigen_solver", ("arpack", "lobpcg")) +@pytest.mark.parametrize("assign_labels", ("kmeans", "discretize", "cluster_qr")) +def test_spectral_clustering( + eigen_solver, assign_labels, csr_container, global_random_seed +): + S = np.array( + [ + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [0.2, 0.2, 0.2, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + ] + ) + + for mat in (S, csr_container(S)): + model = SpectralClustering( + random_state=global_random_seed, + n_clusters=2, + affinity="precomputed", + eigen_solver=eigen_solver, + assign_labels=assign_labels, + ).fit(mat) + labels = model.labels_ + if labels[0] == 0: + labels = 1 - labels + + assert adjusted_rand_score(labels, [1, 1, 1, 0, 0, 0, 0]) == 1 + + model_copy = pickle.loads(pickle.dumps(model)) + assert model_copy.n_clusters == model.n_clusters + assert model_copy.eigen_solver == model.eigen_solver + assert_array_equal(model_copy.labels_, model.labels_) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +@pytest.mark.parametrize("assign_labels", ("kmeans", "discretize", "cluster_qr")) +def test_spectral_clustering_sparse(assign_labels, coo_container, global_random_seed): + X, y = make_blobs( + n_samples=20, + random_state=global_random_seed, + centers=[[1, 1], [-1, -1]], + cluster_std=0.01, + ) + + S = rbf_kernel(X, gamma=1) + S = np.maximum(S - 1e-4, 0) + S = coo_container(S) + + labels = ( + SpectralClustering( + random_state=global_random_seed, + n_clusters=2, + affinity="precomputed", + assign_labels=assign_labels, + ) + .fit(S) + .labels_ + ) + assert adjusted_rand_score(y, labels) == 1 + + +def test_precomputed_nearest_neighbors_filtering(global_random_seed): + # Test precomputed graph filtering when containing too many neighbors + X, y = make_blobs( + n_samples=250, + random_state=global_random_seed, + centers=[[1, 1, 1], [-1, -1, -1]], + cluster_std=0.01, + ) + + n_neighbors = 2 + results = [] + for additional_neighbors in [0, 10]: + nn = NearestNeighbors(n_neighbors=n_neighbors + additional_neighbors).fit(X) + graph = nn.kneighbors_graph(X, mode="distance") + labels = ( + SpectralClustering( + random_state=global_random_seed, + n_clusters=2, + affinity="precomputed_nearest_neighbors", + n_neighbors=n_neighbors, + ) + .fit(graph) + .labels_ + ) + results.append(labels) + + assert_array_equal(results[0], results[1]) + + +def test_affinities(global_random_seed): + # Note: in the following, random_state has been selected to have + # a dataset that yields a stable eigen decomposition both when built + # on OSX and Linux + X, y = make_blobs( + n_samples=20, random_state=0, centers=[[1, 1], [-1, -1]], cluster_std=0.01 + ) + # nearest neighbors affinity + sp = SpectralClustering(n_clusters=2, affinity="nearest_neighbors", random_state=0) + with pytest.warns(UserWarning, match="not fully connected"): + sp.fit(X) + assert adjusted_rand_score(y, sp.labels_) == 1 + + sp = SpectralClustering(n_clusters=2, gamma=2, random_state=global_random_seed) + labels = sp.fit(X).labels_ + assert adjusted_rand_score(y, labels) == 1 + + X = check_random_state(10).rand(10, 5) * 10 + + kernels_available = kernel_metrics() + for kern in kernels_available: + # Additive chi^2 gives a negative similarity matrix which + # doesn't make sense for spectral clustering + if kern != "additive_chi2": + sp = SpectralClustering(n_clusters=2, affinity=kern, random_state=0) + labels = sp.fit(X).labels_ + assert (X.shape[0],) == labels.shape + + sp = SpectralClustering(n_clusters=2, affinity=lambda x, y: 1, random_state=0) + labels = sp.fit(X).labels_ + assert (X.shape[0],) == labels.shape + + def histogram(x, y, **kwargs): + # Histogram kernel implemented as a callable. + assert kwargs == {} # no kernel_params that we didn't ask for + return np.minimum(x, y).sum() + + sp = SpectralClustering(n_clusters=2, affinity=histogram, random_state=0) + labels = sp.fit(X).labels_ + assert (X.shape[0],) == labels.shape + + +def test_cluster_qr(global_random_seed): + # cluster_qr by itself should not be used for clustering generic data + # other than the rows of the eigenvectors within spectral clustering, + # but cluster_qr must still preserve the labels for different dtypes + # of the generic fixed input even if the labels may be meaningless. + random_state = np.random.RandomState(seed=global_random_seed) + n_samples, n_components = 10, 5 + data = random_state.randn(n_samples, n_components) + labels_float64 = cluster_qr(data.astype(np.float64)) + # Each sample is assigned a cluster identifier + assert labels_float64.shape == (n_samples,) + # All components should be covered by the assignment + assert np.array_equal(np.unique(labels_float64), np.arange(n_components)) + # Single precision data should yield the same cluster assignments + labels_float32 = cluster_qr(data.astype(np.float32)) + assert np.array_equal(labels_float64, labels_float32) + + +def test_cluster_qr_permutation_invariance(global_random_seed): + # cluster_qr must be invariant to sample permutation. + random_state = np.random.RandomState(seed=global_random_seed) + n_samples, n_components = 100, 5 + data = random_state.randn(n_samples, n_components) + perm = random_state.permutation(n_samples) + assert np.array_equal( + cluster_qr(data)[perm], + cluster_qr(data[perm]), + ) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +@pytest.mark.parametrize("n_samples", [50, 100, 150, 500]) +def test_discretize(n_samples, coo_container, global_random_seed): + # Test the discretize using a noise assignment matrix + random_state = np.random.RandomState(seed=global_random_seed) + for n_class in range(2, 10): + # random class labels + y_true = random_state.randint(0, n_class + 1, n_samples) + y_true = np.array(y_true, float) + # noise class assignment matrix + y_indicator = coo_container( + (np.ones(n_samples), (np.arange(n_samples), y_true)), + shape=(n_samples, n_class + 1), + ) + y_true_noisy = y_indicator.toarray() + 0.1 * random_state.randn( + n_samples, n_class + 1 + ) + y_pred = discretize(y_true_noisy, random_state=random_state) + assert adjusted_rand_score(y_true, y_pred) > 0.8 + + +def test_spectral_clustering_with_arpack_amg_solvers(global_random_seed): + # Test that spectral_clustering is the same for arpack and amg solver + # Based on toy example from plot_segmentation_toy.py + + # a small two coin image + x, y = np.indices((40, 40)) + + center1, center2 = (14, 12), (20, 25) + radius1, radius2 = 8, 7 + + circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2 + circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2 + + circles = circle1 | circle2 + mask = circles.copy() + img = circles.astype(float) + + graph = img_to_graph(img, mask=mask) + graph.data = np.exp(-graph.data / graph.data.std()) + + labels_arpack = spectral_clustering( + graph, n_clusters=2, eigen_solver="arpack", random_state=global_random_seed + ) + + assert len(np.unique(labels_arpack)) == 2 + + if amg_loaded: + labels_amg = spectral_clustering( + graph, n_clusters=2, eigen_solver="amg", random_state=global_random_seed + ) + assert adjusted_rand_score(labels_arpack, labels_amg) == 1 + else: + with pytest.raises(ValueError): + spectral_clustering(graph, n_clusters=2, eigen_solver="amg", random_state=0) + + +def test_n_components(global_random_seed): + # Test that after adding n_components, result is different and + # n_components = n_clusters by default + X, y = make_blobs( + n_samples=20, + random_state=global_random_seed, + centers=[[1, 1], [-1, -1]], + cluster_std=0.01, + ) + sp = SpectralClustering(n_clusters=2, random_state=global_random_seed) + labels = sp.fit(X).labels_ + # set n_components = n_cluster and test if result is the same + labels_same_ncomp = ( + SpectralClustering( + n_clusters=2, n_components=2, random_state=global_random_seed + ) + .fit(X) + .labels_ + ) + # test that n_components=n_clusters by default + assert_array_equal(labels, labels_same_ncomp) + + # test that n_components affect result + # n_clusters=8 by default, and set n_components=2 + labels_diff_ncomp = ( + SpectralClustering(n_components=2, random_state=global_random_seed) + .fit(X) + .labels_ + ) + assert not np.array_equal(labels, labels_diff_ncomp) + + +@pytest.mark.parametrize("assign_labels", ("kmeans", "discretize", "cluster_qr")) +def test_verbose(assign_labels, capsys): + # Check verbose mode of KMeans for better coverage. + X, y = make_blobs( + n_samples=20, random_state=0, centers=[[1, 1], [-1, -1]], cluster_std=0.01 + ) + + SpectralClustering(n_clusters=2, random_state=42, verbose=1).fit(X) + + captured = capsys.readouterr() + + assert re.search(r"Computing label assignment using", captured.out) + + if assign_labels == "kmeans": + assert re.search(r"Initialization complete", captured.out) + assert re.search(r"Iteration [0-9]+, inertia", captured.out) + + +def test_spectral_clustering_np_matrix_raises(): + """Check that spectral_clustering raises an informative error when passed + a np.matrix. See #10993""" + X = np.matrix([[0.0, 2.0], [2.0, 0.0]]) + + msg = r"np\.matrix is not supported. Please convert to a numpy array" + with pytest.raises(TypeError, match=msg): + spectral_clustering(X) + + +def test_spectral_clustering_not_infinite_loop(capsys, monkeypatch): + """Check that discretize raises LinAlgError when svd never converges. + + Non-regression test for #21380 + """ + + def new_svd(*args, **kwargs): + raise LinAlgError() + + monkeypatch.setattr(np.linalg, "svd", new_svd) + vectors = np.ones((10, 4)) + + with pytest.raises(LinAlgError, match="SVD did not converge"): + discretize(vectors) diff --git a/shared/package-files/7c/7c34b19db1afe714e31a4f1d8f4338862268c92c5b50d74a12121508e5222b97/blob b/shared/package-files/7c/7c34b19db1afe714e31a4f1d8f4338862268c92c5b50d74a12121508e5222b97/blob new file mode 100644 index 0000000000000000000000000000000000000000..56132d50f04c4c8c0fd290b2dd69c0a69ba00329 --- /dev/null +++ b/shared/package-files/7c/7c34b19db1afe714e31a4f1d8f4338862268c92c5b50d74a12121508e5222b97/blob @@ -0,0 +1,62 @@ +""" +Exception handling intrinsics. +""" + +from numba.core import types, errors, cgutils +from numba.core.extending import intrinsic + + +@intrinsic +def exception_check(typingctx): + """An intrinsic to check if an exception is raised + """ + def codegen(context, builder, signature, args): + nrt = context.nrt + return nrt.eh_check(builder) + + restype = types.boolean + return restype(), codegen + + +@intrinsic +def mark_try_block(typingctx): + """An intrinsic to mark the start of a *try* block. + """ + def codegen(context, builder, signature, args): + nrt = context.nrt + nrt.eh_try(builder) + return context.get_dummy_value() + + restype = types.none + return restype(), codegen + + +@intrinsic +def end_try_block(typingctx): + """An intrinsic to mark the end of a *try* block. + """ + def codegen(context, builder, signature, args): + nrt = context.nrt + nrt.eh_end_try(builder) + return context.get_dummy_value() + + restype = types.none + return restype(), codegen + + +@intrinsic +def exception_match(typingctx, exc_value, exc_class): + """Basically do ``isinstance(exc_value, exc_class)`` for exception objects. + Used in ``except Exception:`` syntax. + """ + # Check for our limitation + if exc_class.exc_class is not Exception: + msg = "Exception matching is limited to {}" + raise errors.UnsupportedError(msg.format(Exception)) + + def codegen(context, builder, signature, args): + # Intentionally always True. + return cgutils.true_bit + + restype = types.boolean + return restype(exc_value, exc_class), codegen diff --git a/shared/package-files/7c/7c3602b8e21e7e08cd049ef38405189e23559794a5b52b36ef95da3682f44beb/blob b/shared/package-files/7c/7c3602b8e21e7e08cd049ef38405189e23559794a5b52b36ef95da3682f44beb/blob new file mode 100644 index 0000000000000000000000000000000000000000..f8164102815f61ec61962524db2a2b3dd0ff6d55 --- /dev/null +++ b/shared/package-files/7c/7c3602b8e21e7e08cd049ef38405189e23559794a5b52b36ef95da3682f44beb/blob @@ -0,0 +1,145 @@ +from datetime import timedelta + +import numpy as np +import pytest + +from pandas._libs import lib + +import pandas as pd +from pandas import ( + Index, + Timedelta, + TimedeltaIndex, + timedelta_range, +) +import pandas._testing as tm + + +class TestTimedeltaIndexInsert: + def test_insert(self): + idx = TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + result = idx.insert(2, timedelta(days=5)) + exp = TimedeltaIndex(["4day", "1day", "5day", "2day"], name="idx") + tm.assert_index_equal(result, exp) + + # insertion of non-datetime should coerce to object index + result = idx.insert(1, "inserted") + expected = Index( + [Timedelta("4day"), "inserted", Timedelta("1day"), Timedelta("2day")], + name="idx", + ) + assert not isinstance(result, TimedeltaIndex) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + + idx = timedelta_range("1day 00:00:01", periods=3, freq="s", name="idx") + + # preserve freq + expected_0 = TimedeltaIndex( + ["1day", "1day 00:00:01", "1day 00:00:02", "1day 00:00:03"], + name="idx", + freq="s", + ) + expected_3 = TimedeltaIndex( + ["1day 00:00:01", "1day 00:00:02", "1day 00:00:03", "1day 00:00:04"], + name="idx", + freq="s", + ) + + # reset freq to None + expected_1_nofreq = TimedeltaIndex( + ["1day 00:00:01", "1day 00:00:01", "1day 00:00:02", "1day 00:00:03"], + name="idx", + freq=None, + ) + expected_3_nofreq = TimedeltaIndex( + ["1day 00:00:01", "1day 00:00:02", "1day 00:00:03", "1day 00:00:05"], + name="idx", + freq=None, + ) + + cases = [ + (0, Timedelta("1day"), expected_0), + (-3, Timedelta("1day"), expected_0), + (3, Timedelta("1day 00:00:04"), expected_3), + (1, Timedelta("1day 00:00:01"), expected_1_nofreq), + (3, Timedelta("1day 00:00:05"), expected_3_nofreq), + ] + + for n, d, expected in cases: + result = idx.insert(n, d) + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert result.freq == expected.freq + + @pytest.mark.parametrize( + "null", [None, np.nan, np.timedelta64("NaT"), pd.NaT, pd.NA] + ) + def test_insert_nat(self, null): + # GH 18295 (test missing) + idx = timedelta_range("1day", "3day") + result = idx.insert(1, null) + expected = TimedeltaIndex(["1day", pd.NaT, "2day", "3day"]) + tm.assert_index_equal(result, expected) + + def test_insert_invalid_na(self): + idx = TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + item = np.datetime64("NaT") + result = idx.insert(0, item) + + expected = Index([item] + list(idx), dtype=object, name="idx") + tm.assert_index_equal(result, expected) + + # Also works if we pass a different dt64nat object + item2 = np.datetime64("NaT") + result = idx.insert(0, item2) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")] + ) + def test_insert_mismatched_types_raises(self, item): + # GH#33703 dont cast these to td64 + tdi = TimedeltaIndex(["4day", "1day", "2day"], name="idx") + + result = tdi.insert(1, item) + + expected = Index( + [tdi[0], lib.item_from_zerodim(item)] + list(tdi[1:]), + dtype=object, + name="idx", + ) + tm.assert_index_equal(result, expected) + + def test_insert_castable_str(self): + idx = timedelta_range("1day", "3day") + + result = idx.insert(0, "1 Day") + + expected = TimedeltaIndex([idx[0]] + list(idx)) + tm.assert_index_equal(result, expected) + + def test_insert_non_castable_str(self): + idx = timedelta_range("1day", "3day") + + result = idx.insert(0, "foo") + + expected = Index(["foo"] + list(idx), dtype=object) + tm.assert_index_equal(result, expected) + + def test_insert_empty(self): + # Corner case inserting with length zero doesn't raise IndexError + # GH#33573 for freq preservation + idx = timedelta_range("1 Day", periods=3) + td = idx[0] + + result = idx[:0].insert(0, td) + assert result.freq == "D" + + with pytest.raises(IndexError, match="loc must be an integer between"): + result = idx[:0].insert(1, td) + + with pytest.raises(IndexError, match="loc must be an integer between"): + result = idx[:0].insert(-1, td) diff --git a/shared/package-files/7c/7c3c57eb145a85eb2faa5358547f4fae4dbbe9ec3596b17d18648ee0fad8f0df/blob b/shared/package-files/7c/7c3c57eb145a85eb2faa5358547f4fae4dbbe9ec3596b17d18648ee0fad8f0df/blob new file mode 100644 index 0000000000000000000000000000000000000000..6c88515da87b658ac80f584205f8cc3bb158bba1 Binary files /dev/null and b/shared/package-files/7c/7c3c57eb145a85eb2faa5358547f4fae4dbbe9ec3596b17d18648ee0fad8f0df/blob differ diff --git a/shared/package-files/7c/7c3d5a1bd3cf76695ccc50d4a89c7b9ef7e881fb0cf87fa9c91a6750cea7f973/blob b/shared/package-files/7c/7c3d5a1bd3cf76695ccc50d4a89c7b9ef7e881fb0cf87fa9c91a6750cea7f973/blob new file mode 100644 index 0000000000000000000000000000000000000000..5da653697a17892d4f570898d08d44ddb9c59b9d --- /dev/null +++ b/shared/package-files/7c/7c3d5a1bd3cf76695ccc50d4a89c7b9ef7e881fb0cf87fa9c91a6750cea7f973/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c3d5a1bd3cf76695ccc50d4a89c7b9ef7e881fb0cf87fa9c91a6750cea7f973 +size 67317209 diff --git a/shared/package-files/7c/7c3e49ba06edff7f676757958cf35d020a0346e3574dc9d907d940e30ebceef3/blob b/shared/package-files/7c/7c3e49ba06edff7f676757958cf35d020a0346e3574dc9d907d940e30ebceef3/blob new file mode 100644 index 0000000000000000000000000000000000000000..72c4ebfb5d84ae82f74a4c814e72372a651ae6b8 --- /dev/null +++ b/shared/package-files/7c/7c3e49ba06edff7f676757958cf35d020a0346e3574dc9d907d940e30ebceef3/blob @@ -0,0 +1,19 @@ +""" +Tests for Indexes backed by arbitrary ExtensionArrays. +""" +import pandas as pd + + +class BaseIndexTests: + """Tests for Index object backed by an ExtensionArray""" + + def test_index_from_array(self, data): + idx = pd.Index(data) + assert data.dtype == idx.dtype + + def test_index_from_listlike_with_dtype(self, data): + idx = pd.Index(data, dtype=data.dtype) + assert idx.dtype == data.dtype + + idx = pd.Index(list(data), dtype=data.dtype) + assert idx.dtype == data.dtype diff --git a/shared/package-files/7c/7c411676c7c6aa80510f711598786df0ef9ad986bbe9496b71d41da73734dab4/blob b/shared/package-files/7c/7c411676c7c6aa80510f711598786df0ef9ad986bbe9496b71d41da73734dab4/blob new file mode 100644 index 0000000000000000000000000000000000000000..72e96acfd29251832e595d96545d4f6f82edfbf4 Binary files /dev/null and b/shared/package-files/7c/7c411676c7c6aa80510f711598786df0ef9ad986bbe9496b71d41da73734dab4/blob differ diff --git a/shared/package-files/7c/7c424697b918fdd0c07abc5165c2c0238d0dc524d09e54c930b5e6a2f2aaa072/blob b/shared/package-files/7c/7c424697b918fdd0c07abc5165c2c0238d0dc524d09e54c930b5e6a2f2aaa072/blob new file mode 100644 index 0000000000000000000000000000000000000000..77d72373651e551df5654b3440119ad2ba181f5a --- /dev/null +++ b/shared/package-files/7c/7c424697b918fdd0c07abc5165c2c0238d0dc524d09e54c930b5e6a2f2aaa072/blob @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor slow_conv_dilated3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor slow_conv_dilated3d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/7c/7c4301e0474ef1a5f8eda5b5decfa7552cbec8ce6a2337d7ace61a4249afdfe0/blob b/shared/package-files/7c/7c4301e0474ef1a5f8eda5b5decfa7552cbec8ce6a2337d7ace61a4249afdfe0/blob new file mode 100644 index 0000000000000000000000000000000000000000..407165147e353ce2776e98a6f2a3f6dfc6b2be7e --- /dev/null +++ b/shared/package-files/7c/7c4301e0474ef1a5f8eda5b5decfa7552cbec8ce6a2337d7ace61a4249afdfe0/blob @@ -0,0 +1,388 @@ +from typing import Dict, Union + +from torchgen.model import NativeFunctionsGroup, NativeFunctionsViewGroup + + +def func_name_base_str(g: Union[NativeFunctionsGroup, NativeFunctionsViewGroup]) -> str: + if isinstance(g, NativeFunctionsGroup): + return str(g.functional.func.name.name.base) + else: + return str(g.view.root_name) + + +is_hand_written_ops_ = frozenset( + ( + "abs", + "add", + "addmm", + "all", + "any", + "argmin", + "bmm", + "clamp", + "clamp_min", + "cumsum", + "div", + "fmod", + "index_select", + "leaky_relu", + "linear", + "log", + "matmul", + "mul", + "narrow_copy", + "nonzero", + "pow", + "remainder", + "sigmoid", + "sign", + "sub", + "tanh", + "detach", + "expand_as", + "flatten", + "narrow", + "reshape_as", + "select", + "slice", + "softmax", + "split", + "squeeze", + "transpose", + "view", + "where", + ) +) + + +def is_hand_written(g: Union[NativeFunctionsGroup, NativeFunctionsViewGroup]) -> bool: + name_base = func_name_base_str(g) + return name_base in is_hand_written_ops_ + + +def override_test_values(arg_map: Dict[str, str], op_name: str, index: int) -> None: + assert index == 0 or index == 1 + if op_name == "addr": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["vec1"] = "at::rand({6})" + arg_map["vec2"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["vec1"] = "at::rand({22})" + arg_map["vec2"] = "at::rand({22})" + return + if op_name == "mv": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["vec"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["vec"] = "at::rand({22})" + return + if op_name == "addbmm": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + else: + arg_map["self"] = "at::rand({22, 22})" + return + if op_name == "cross": + if index == 0: + arg_map["self"] = "at::rand({3, 3, 3})" + arg_map["other"] = "at::rand({3, 3, 3})" + else: + arg_map["self"] = "at::rand({22, 3, 22})" + arg_map["other"] = "at::rand({22, 3, 22})" + return + if op_name == "take": + if index == 0: + arg_map["index"] = "at::randint(0, 216, {20}, torch::kInt64)" + else: + arg_map["index"] = "at::randint(0, 1000, {100}, torch::kInt64)" + return + if op_name == "take_along_dim": + if index == 0: + arg_map["indices"] = "at::argsort(self0, 1, true)" + else: + arg_map["indices"] = "at::argsort(self1, 1, true)" + return + if op_name == "masked_select": + if index == 0: + arg_map["mask"] = "at::randn({6, 6, 6}) > 0.5" + else: + arg_map["mask"] = "at::rand({22, 22, 22}) > 0.5" + return + if op_name == "orgqr": + if index == 0: + arg_map["input2"] = "at::rand({6, 6})" + else: + arg_map["input2"] = "at::rand({22, 22})" + return + if op_name == "ormqr": + if index == 0: + arg_map["input2"] = "at::rand({6, 6})" + else: + arg_map["input2"] = "at::rand({22, 22})" + return + if op_name == "quantile": + if index == 0: + arg_map["q"] = "at::rand({6})" + arg_map["interpolation"] = '"linear"' + else: + arg_map["q"] = "at::rand({22})" + arg_map["interpolation"] = '"linear"' + return + if op_name == "nanquantile": + if index == 0: + arg_map["q"] = "at::rand({6})" + arg_map["interpolation"] = '"linear"' + else: + arg_map["q"] = "at::rand({22})" + arg_map["interpolation"] = '"linear"' + return + if op_name == "multi_margin_loss": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["target"] = "at::randint(6, {6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["target"] = "at::randint(22, {22}, torch::kInt64)" + arg_map["weight"] = "at::rand({22})" + return + if op_name == "multilabel_margin_loss": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["target"] = "at::randint(6, {6, 6}, torch::kInt64)" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["target"] = "at::randint(22, {22, 22}, torch::kInt64)" + return + if op_name == "nll_loss": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["target"] = "at::randint(6, {6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["target"] = "at::randint(22, {22}, torch::kInt64)" + arg_map["weight"] = "at::rand({22})" + return + if op_name == "nll_loss2d": + if index == 0: + arg_map["self"] = "at::rand({6, 6, 6, 6})" + arg_map["target"] = "at::randint(6, {6, 6, 6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22, 22, 22})" + arg_map["target"] = "at::randint(22, {22, 22, 22}, torch::kInt64)" + arg_map["weight"] = "at::rand({22})" + return + if op_name in ( + "fft_fft", + "fft_ifft", + "fft_rfft", + "fft_irfft", + "fft_hfft", + "fft_ihfft", + ): + arg_map["norm"] = '"forward"' + return + if op_name == "linalg_tensorinv": + if index == 0: + arg_map["self"] = "at::rand({6, 6, 6, 6})" + arg_map["ind"] = "2" + else: + arg_map["self"] = "at::rand({22, 22, 22, 22})" + arg_map["ind"] = "2" + return + if op_name == "addmv": + if index == 0: + arg_map["self"] = "at::rand({2})" + arg_map["mat"] = "at::rand({2, 2})" + arg_map["vec"] = "at::rand({2})" + else: + arg_map["self"] = "at::rand({35})" + arg_map["mat"] = "at::rand({35, 35})" + arg_map["vec"] = "at::rand({35})" + return + if op_name == "acosh": + if index == 0: + arg_map["self"] = "at::rand({2, 2, 2}) + at::ones({2, 2, 2})" + else: + arg_map["self"] = "at::rand({5, 5, 5}) + at::ones({5, 5, 5})" + return + if op_name == "adaptive_max_pool2d_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({2, 2, 2}, at::kFloat)" + arg_map["self"] = "at::rand({2, 2, 2}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {2, 2, 2}, at::kLong)" + else: + arg_map["grad_output"] = "at::rand({3, 3, 3}, at::kFloat)" + arg_map["self"] = "at::rand({3, 3, 3}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {3, 3, 3}, at::kLong)" + return + if op_name == "adaptive_max_pool3d_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({2, 2, 2, 2}, at::kFloat)" + arg_map["self"] = "at::rand({2, 2, 2, 2}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {2, 2, 2, 2}, at::kLong)" + else: + arg_map["grad_output"] = "at::rand({3, 3, 3, 3}, at::kFloat)" + arg_map["self"] = "at::rand({3, 3, 3, 3}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {3, 3, 3, 3}, at::kLong)" + return + if op_name == "bitwise_left_shift": + if index == 0: + arg_map["self"] = "at::randint(1, 1 << 4, {6, 6, 6}, at::kInt)" + arg_map["other"] = "at::randint(1, 26, {6, 6, 6}, at::kInt)" + else: + arg_map["self"] = "at::randint(1, 1 << 4, {22, 22, 22}, at::kInt)" + arg_map["other"] = "at::randint(1, 26, {22, 22, 22}, at::kInt)" + return + if op_name == "bitwise_right_shift": + if index == 0: + arg_map["self"] = "at::randint(1 << 21, 1 << 30, {6, 6, 6}, at::kInt)" + arg_map["other"] = "at::randint(1, 22, {6, 6, 6}, at::kInt)" + else: + arg_map["self"] = "at::randint(1 << 21, 1 << 30, {22, 22, 22}, at::kInt)" + arg_map["other"] = "at::randint(1, 22, {22, 22, 22}, at::kInt)" + return + if op_name == "gather": + if index == 0: + arg_map["self"] = "at::randint(1, 100, {2,2,2}, at::kInt)" + arg_map["dim"] = "1" + arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)" + arg_map["sparse_grad"] = "false" + else: + arg_map["self"] = "at::randint(1, 100, {5,5,5}, at::kInt)" + arg_map["dim"] = "1" + arg_map["index"] = "at::randint(0, 4, {5,5,5}, torch::kInt64)" + arg_map["sparse_grad"] = "false" + return + if op_name == "gelu": + if index == 0: + arg_map["self"] = "at::rand({6, 6, 6})" + arg_map["approximate"] = '"tanh"' + else: + arg_map["self"] = "at::rand({22, 22, 22})" + arg_map["approximate"] = '"tanh"' + return + if op_name == "gelu_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({6, 6, 6})" + arg_map["self"] = "at::rand({6, 6, 6})" + arg_map["approximate"] = '"tanh"' + else: + arg_map["grad_output"] = "at::rand({22, 22, 22})" + arg_map["self"] = "at::rand({22, 22, 22})" + arg_map["approximate"] = '"tanh"' + return + if op_name == "index_add": + if index == 0: + arg_map["self"] = "at::rand({2})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 1, {2}, at::kInt)" + arg_map["source"] = "at::rand({2})" + arg_map["alpha"] = "2" + else: + arg_map["self"] = "at::rand({16})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 10, {16}, at::kInt)" + arg_map["source"] = "at::rand({16})" + arg_map["alpha"] = "2" + return + if op_name == "index_copy": + if index == 0: + arg_map["self"] = "at::rand({2})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 1, {2}, at::kLong)" + arg_map["source"] = "at::rand({2})" + else: + arg_map["self"] = "at::rand({32})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 10, {32}, at::kLong)" + arg_map["source"] = "at::rand({32})" + return + if op_name == "linalg_cross": + if index == 0: + arg_map["self"] = "at::rand({6, 3, 6})" + arg_map["other"] = "at::rand({6, 3, 6})" + arg_map["dim"] = "1" + else: + arg_map["self"] = "at::rand({22, 3, 22})" + arg_map["other"] = "at::rand({22, 3, 22})" + arg_map["dim"] = "1" + return + if op_name == "nll_loss_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({})" + arg_map["self"] = "at::rand({6})" + arg_map["target"] = "at::randint(0, 5, {6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + arg_map["reduction"] = "1" + arg_map["ignore_index"] = "1" + arg_map["total_weight"] = "at::rand({})" + else: + arg_map["grad_output"] = "at::rand({})" + arg_map["self"] = "at::rand({36})" + arg_map["target"] = "at::randint(0, 11, {36}, torch::kInt64)" + arg_map["weight"] = "at::rand({36})" + arg_map["reduction"] = "1" + arg_map["ignore_index"] = "1" + arg_map["total_weight"] = "at::rand({})" + return + if op_name in ["scatter", "scatter_add", "_scatter_reduce"]: + if index == 0: + arg_map["self"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)" + arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)" + arg_map["src"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)" + else: + arg_map["self"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)" + arg_map["index"] = "at::randint(0, 1, {5,5,5}, torch::kInt64)" + arg_map["src"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)" + if "reduce" in arg_map: + arg_map["reduce"] = '"sum"' if op_name == "_scatter_reduce" else '"add"' + return + if op_name == "scatter_reduce": + arg_map["reduce"] = '"mean"' + if index == 0: + arg_map["index"] = "at::randint(6, {6, 6, 6}, torch::kInt64)" + else: + arg_map["index"] = "at::randint(22, {22, 22, 22}, torch::kInt64)" + return + if op_name == "special_zeta": + if index == 0: + arg_map["self"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})" + arg_map["other"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})" + else: + arg_map["self"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})" + arg_map["other"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})" + return + if op_name == "_convert_indices_from_csr_to_coo": + if index == 0: + arg_map["crow_indices"] = "torch::tensor({1}, torch::kInt32)" + arg_map["col_indices"] = "torch::tensor({0, 1, 0}, torch::kInt32)" + arg_map["out_int32"] = "false" + else: + arg_map["crow_indices"] = "torch::tensor({0}, torch::kInt32)" + arg_map[ + "col_indices" + ] = "torch::tensor({0, 1, 0, 2, 1, 2, 0, 1, 0, 2, 1, 2}, torch::kInt32)" + arg_map["out_int32"] = "false" + return + if op_name == "_convert_indices_from_coo_to_csr": + if index == 0: + arg_map["self"] = "at::randint(0, 3, {2}, at::kInt)" + arg_map["size"] = "10" + arg_map["out_int32"] = "false" + else: + arg_map["self"] = "at::randint(0, 3, {12}, at::kInt)" + arg_map["size"] = "24" + arg_map["out_int32"] = "false" + return + if op_name in ("diagonal", "linalg_diagonal"): + arg_map["offset"] = "0" + arg_map["dim0"] = "1" + arg_map["dim1"] = "2" + return diff --git a/shared/package-files/7c/7c43efc28eac8f067dcad767b9f148504fa012421ed740db76c5f9d6fde58f2a/blob b/shared/package-files/7c/7c43efc28eac8f067dcad767b9f148504fa012421ed740db76c5f9d6fde58f2a/blob new file mode 100644 index 0000000000000000000000000000000000000000..fb328e3f6512081f76604c4b92fe3d407819e448 --- /dev/null +++ b/shared/package-files/7c/7c43efc28eac8f067dcad767b9f148504fa012421ed740db76c5f9d6fde58f2a/blob @@ -0,0 +1,395 @@ +"""unit tests for sparse utility functions""" + +import numpy as np +from numpy.testing import assert_equal +import pytest +from pytest import raises as assert_raises +from scipy.sparse import _sputils as sputils, csr_array, bsr_array, dia_array, coo_array +from scipy.sparse._sputils import matrix + + +class TestSparseUtils: + + def test_upcast(self): + assert_equal(sputils.upcast('intc'), np.intc) + assert_equal(sputils.upcast('int32', 'float32'), np.float64) + assert_equal(sputils.upcast('bool', complex, float), np.complex128) + assert_equal(sputils.upcast('i', 'd'), np.float64) + + def test_getdtype(self): + A = np.array([1], dtype='int8') + + assert_equal(sputils.getdtype(None, default=float), float) + assert_equal(sputils.getdtype(None, a=A), np.int8) + + with assert_raises( + ValueError, + match="scipy.sparse does not support dtype object. .*", + ): + sputils.getdtype("O") + + with assert_raises( + ValueError, + match="scipy.sparse does not support dtype float16. .*", + ): + sputils.getdtype(None, default=np.float16) + + def test_isscalarlike(self): + assert_equal(sputils.isscalarlike(3.0), True) + assert_equal(sputils.isscalarlike(-4), True) + assert_equal(sputils.isscalarlike(2.5), True) + assert_equal(sputils.isscalarlike(1 + 3j), True) + assert_equal(sputils.isscalarlike(np.array(3)), True) + assert_equal(sputils.isscalarlike("16"), True) + + assert_equal(sputils.isscalarlike(np.array([3])), False) + assert_equal(sputils.isscalarlike([[3]]), False) + assert_equal(sputils.isscalarlike((1,)), False) + assert_equal(sputils.isscalarlike((1, 2)), False) + + def test_isintlike(self): + assert_equal(sputils.isintlike(-4), True) + assert_equal(sputils.isintlike(np.array(3)), True) + assert_equal(sputils.isintlike(np.array([3])), False) + with assert_raises( + ValueError, + match="Inexact indices into sparse matrices are not allowed" + ): + sputils.isintlike(3.0) + + assert_equal(sputils.isintlike(2.5), False) + assert_equal(sputils.isintlike(1 + 3j), False) + assert_equal(sputils.isintlike((1,)), False) + assert_equal(sputils.isintlike((1, 2)), False) + + def test_isshape(self): + assert_equal(sputils.isshape((1, 2)), True) + assert_equal(sputils.isshape((5, 2)), True) + + assert_equal(sputils.isshape((1.5, 2)), False) + assert_equal(sputils.isshape((2, 2, 2)), False) + assert_equal(sputils.isshape(([2], 2)), False) + assert_equal(sputils.isshape((-1, 2), nonneg=False),True) + assert_equal(sputils.isshape((2, -1), nonneg=False),True) + assert_equal(sputils.isshape((-1, 2), nonneg=True),False) + assert_equal(sputils.isshape((2, -1), nonneg=True),False) + + assert_equal(sputils.isshape((1.5, 2), allow_nd=(1, 2)), False) + assert_equal(sputils.isshape(([2], 2), allow_nd=(1, 2)), False) + assert_equal(sputils.isshape((2, 2, -2), nonneg=True, allow_nd=(1, 2)), + False) + assert_equal(sputils.isshape((2,), allow_nd=(1, 2)), True) + assert_equal(sputils.isshape((2, 2,), allow_nd=(1, 2)), True) + assert_equal(sputils.isshape((2, 2, 2), allow_nd=(1, 2)), False) + + def test_issequence(self): + assert_equal(sputils.issequence((1,)), True) + assert_equal(sputils.issequence((1, 2, 3)), True) + assert_equal(sputils.issequence([1]), True) + assert_equal(sputils.issequence([1, 2, 3]), True) + assert_equal(sputils.issequence(np.array([1, 2, 3])), True) + + assert_equal(sputils.issequence(np.array([[1], [2], [3]])), False) + assert_equal(sputils.issequence(3), False) + + def test_ismatrix(self): + assert_equal(sputils.ismatrix(((),)), True) + assert_equal(sputils.ismatrix([[1], [2]]), True) + assert_equal(sputils.ismatrix(np.arange(3)[None]), True) + + assert_equal(sputils.ismatrix([1, 2]), False) + assert_equal(sputils.ismatrix(np.arange(3)), False) + assert_equal(sputils.ismatrix([[[1]]]), False) + assert_equal(sputils.ismatrix(3), False) + + def test_isdense(self): + assert_equal(sputils.isdense(np.array([1])), True) + assert_equal(sputils.isdense(matrix([1])), True) + + def test_validateaxis(self): + assert_raises(TypeError, sputils.validateaxis, (0, 1)) + assert_raises(TypeError, sputils.validateaxis, 1.5) + assert_raises(ValueError, sputils.validateaxis, 3) + + # These function calls should not raise errors + for axis in (-2, -1, 0, 1, None): + sputils.validateaxis(axis) + + @pytest.mark.parametrize("container", [csr_array, bsr_array]) + def test_safely_cast_index_compressed(self, container): + # This is slow to test completely as nnz > imax is big + # and indptr is big for some shapes + # So we don't test large nnz, nor csc_array (same code as csr_array) + imax = np.int64(np.iinfo(np.int32).max) + + # Shape 32bit + A32 = container((1, imax)) + # indices big type, small values + B32 = A32.copy() + B32.indices = B32.indices.astype(np.int64) + B32.indptr = B32.indptr.astype(np.int64) + + # Shape 64bit + # indices big type, small values + A64 = csr_array((1, imax + 1)) + # indices small type, small values + B64 = A64.copy() + B64.indices = B64.indices.astype(np.int32) + B64.indptr = B64.indptr.astype(np.int32) + # indices big type, big values + C64 = A64.copy() + C64.indices = np.array([imax + 1], dtype=np.int64) + C64.indptr = np.array([0, 1], dtype=np.int64) + C64.data = np.array([2.2]) + + assert (A32.indices.dtype, A32.indptr.dtype) == (np.int32, np.int32) + assert (B32.indices.dtype, B32.indptr.dtype) == (np.int64, np.int64) + assert (A64.indices.dtype, A64.indptr.dtype) == (np.int64, np.int64) + assert (B64.indices.dtype, B64.indptr.dtype) == (np.int32, np.int32) + assert (C64.indices.dtype, C64.indptr.dtype) == (np.int64, np.int64) + + for A in [A32, B32, A64, B64]: + indices, indptr = sputils.safely_cast_index_arrays(A, np.int32) + assert (indices.dtype, indptr.dtype) == (np.int32, np.int32) + indices, indptr = sputils.safely_cast_index_arrays(A, np.int64) + assert (indices.dtype, indptr.dtype) == (np.int64, np.int64) + + indices, indptr = sputils.safely_cast_index_arrays(A, A.indices.dtype) + assert indices is A.indices + assert indptr is A.indptr + + with assert_raises(ValueError): + sputils.safely_cast_index_arrays(C64, np.int32) + indices, indptr = sputils.safely_cast_index_arrays(C64, np.int64) + assert indices is C64.indices + assert indptr is C64.indptr + + def test_safely_cast_index_coo(self): + # This is slow to test completely as nnz > imax is big + # So we don't test large nnz + imax = np.int64(np.iinfo(np.int32).max) + + # Shape 32bit + A32 = coo_array((1, imax)) + # coords big type, small values + B32 = A32.copy() + B32.coords = tuple(co.astype(np.int64) for co in B32.coords) + + # Shape 64bit + # coords big type, small values + A64 = coo_array((1, imax + 1)) + # coords small type, small values + B64 = A64.copy() + B64.coords = tuple(co.astype(np.int32) for co in B64.coords) + # coords big type, big values + C64 = A64.copy() + C64.coords = (np.array([imax + 1]), np.array([0])) + C64.data = np.array([2.2]) + + assert A32.coords[0].dtype == np.int32 + assert B32.coords[0].dtype == np.int64 + assert A64.coords[0].dtype == np.int64 + assert B64.coords[0].dtype == np.int32 + assert C64.coords[0].dtype == np.int64 + + for A in [A32, B32, A64, B64]: + coords = sputils.safely_cast_index_arrays(A, np.int32) + assert coords[0].dtype == np.int32 + coords = sputils.safely_cast_index_arrays(A, np.int64) + assert coords[0].dtype == np.int64 + + coords = sputils.safely_cast_index_arrays(A, A.coords[0].dtype) + assert coords[0] is A.coords[0] + + with assert_raises(ValueError): + sputils.safely_cast_index_arrays(C64, np.int32) + coords = sputils.safely_cast_index_arrays(C64, np.int64) + assert coords[0] is C64.coords[0] + + def test_safely_cast_index_dia(self): + # This is slow to test completely as nnz > imax is big + # So we don't test large nnz + imax = np.int64(np.iinfo(np.int32).max) + + # Shape 32bit + A32 = dia_array((1, imax)) + # offsets big type, small values + B32 = A32.copy() + B32.offsets = B32.offsets.astype(np.int64) + + # Shape 64bit + # offsets big type, small values + A64 = dia_array((1, imax + 2)) + # offsets small type, small values + B64 = A64.copy() + B64.offsets = B64.offsets.astype(np.int32) + # offsets big type, big values + C64 = A64.copy() + C64.offsets = np.array([imax + 1]) + C64.data = np.array([2.2]) + + assert A32.offsets.dtype == np.int32 + assert B32.offsets.dtype == np.int64 + assert A64.offsets.dtype == np.int64 + assert B64.offsets.dtype == np.int32 + assert C64.offsets.dtype == np.int64 + + for A in [A32, B32, A64, B64]: + offsets = sputils.safely_cast_index_arrays(A, np.int32) + assert offsets.dtype == np.int32 + offsets = sputils.safely_cast_index_arrays(A, np.int64) + assert offsets.dtype == np.int64 + + offsets = sputils.safely_cast_index_arrays(A, A.offsets.dtype) + assert offsets is A.offsets + + with assert_raises(ValueError): + sputils.safely_cast_index_arrays(C64, np.int32) + offsets = sputils.safely_cast_index_arrays(C64, np.int64) + assert offsets is C64.offsets + + def test_get_index_dtype(self): + imax = np.int64(np.iinfo(np.int32).max) + too_big = imax + 1 + + # Check that uint32's with no values too large doesn't return + # int64 + a1 = np.ones(90, dtype='uint32') + a2 = np.ones(90, dtype='uint32') + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), + np.dtype('int32') + ) + + # Check that if we can not convert but all values are less than or + # equal to max that we can just convert to int32 + a1[-1] = imax + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), + np.dtype('int32') + ) + + # Check that if it can not convert directly and the contents are + # too large that we return int64 + a1[-1] = too_big + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)), + np.dtype('int64') + ) + + # test that if can not convert and didn't specify to check_contents + # we return int64 + a1 = np.ones(89, dtype='uint32') + a2 = np.ones(89, dtype='uint32') + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2))), + np.dtype('int64') + ) + + # Check that even if we have arrays that can be converted directly + # that if we specify a maxval directly it takes precedence + a1 = np.ones(12, dtype='uint32') + a2 = np.ones(12, dtype='uint32') + assert_equal( + np.dtype(sputils.get_index_dtype( + (a1, a2), maxval=too_big, check_contents=True + )), + np.dtype('int64') + ) + + # Check that an array with a too max size and maxval set + # still returns int64 + a1[-1] = too_big + assert_equal( + np.dtype(sputils.get_index_dtype((a1, a2), maxval=too_big)), + np.dtype('int64') + ) + + # tests public broadcast_shapes largely from + # numpy/numpy/lib/tests/test_stride_tricks.py + # first 3 cause np.broadcast to raise index too large, but not sputils + @pytest.mark.parametrize("input_shapes,target_shape", [ + [((6, 5, 1, 4, 1, 1), (1, 2**32), (2**32, 1)), (6, 5, 1, 4, 2**32, 2**32)], + [((6, 5, 1, 4, 1, 1), (1, 2**32)), (6, 5, 1, 4, 1, 2**32)], + [((1, 2**32), (2**32, 1)), (2**32, 2**32)], + [[2, 2, 2], (2,)], + [[], ()], + [[()], ()], + [[(7,)], (7,)], + [[(1, 2), (2,)], (1, 2)], + [[(2,), (1, 2)], (1, 2)], + [[(1, 1)], (1, 1)], + [[(1, 1), (3, 4)], (3, 4)], + [[(6, 7), (5, 6, 1), (7,), (5, 1, 7)], (5, 6, 7)], + [[(5, 6, 1)], (5, 6, 1)], + [[(1, 3), (3, 1)], (3, 3)], + [[(1, 0), (0, 0)], (0, 0)], + [[(0, 1), (0, 0)], (0, 0)], + [[(1, 0), (0, 1)], (0, 0)], + [[(1, 1), (0, 0)], (0, 0)], + [[(1, 1), (1, 0)], (1, 0)], + [[(1, 1), (0, 1)], (0, 1)], + [[(), (0,)], (0,)], + [[(0,), (0, 0)], (0, 0)], + [[(0,), (0, 1)], (0, 0)], + [[(1,), (0, 0)], (0, 0)], + [[(), (0, 0)], (0, 0)], + [[(1, 1), (0,)], (1, 0)], + [[(1,), (0, 1)], (0, 1)], + [[(1,), (1, 0)], (1, 0)], + [[(), (1, 0)], (1, 0)], + [[(), (0, 1)], (0, 1)], + [[(1,), (3,)], (3,)], + [[2, (3, 2)], (3, 2)], + [[(1, 2)] * 32, (1, 2)], + [[(1, 2)] * 100, (1, 2)], + [[(2,)] * 32, (2,)], + ]) + def test_broadcast_shapes_successes(self, input_shapes, target_shape): + assert_equal(sputils.broadcast_shapes(*input_shapes), target_shape) + + # tests public broadcast_shapes failures + @pytest.mark.parametrize("input_shapes", [ + [(3,), (4,)], + [(2, 3), (2,)], + [2, (2, 3)], + [(3,), (3,), (4,)], + [(2, 5), (3, 5)], + [(2, 4), (2, 5)], + [(1, 3, 4), (2, 3, 3)], + [(1, 2), (3, 1), (3, 2), (10, 5)], + [(2,)] * 32 + [(3,)] * 32, + ]) + def test_broadcast_shapes_failures(self, input_shapes): + with assert_raises(ValueError, match="cannot be broadcast"): + sputils.broadcast_shapes(*input_shapes) + + def test_check_shape_overflow(self): + new_shape = sputils.check_shape([(10, -1)], (65535, 131070)) + assert_equal(new_shape, (10, 858967245)) + + def test_matrix(self): + a = [[1, 2, 3]] + b = np.array(a) + + assert isinstance(sputils.matrix(a), np.matrix) + assert isinstance(sputils.matrix(b), np.matrix) + + c = sputils.matrix(b) + c[:, :] = 123 + assert_equal(b, a) + + c = sputils.matrix(b, copy=False) + c[:, :] = 123 + assert_equal(b, [[123, 123, 123]]) + + def test_asmatrix(self): + a = [[1, 2, 3]] + b = np.array(a) + + assert isinstance(sputils.asmatrix(a), np.matrix) + assert isinstance(sputils.asmatrix(b), np.matrix) + + c = sputils.asmatrix(b) + c[:, :] = 123 + assert_equal(b, [[123, 123, 123]]) diff --git a/shared/package-files/7c/7c45c4f4af6cdb6a22556917f76058fa0d34fae5c22be1f18d9859c716002857/blob b/shared/package-files/7c/7c45c4f4af6cdb6a22556917f76058fa0d34fae5c22be1f18d9859c716002857/blob new file mode 100644 index 0000000000000000000000000000000000000000..55a2bcf72fad9bfae39f03badf0ae768eb305b85 --- /dev/null +++ b/shared/package-files/7c/7c45c4f4af6cdb6a22556917f76058fa0d34fae5c22be1f18d9859c716002857/blob @@ -0,0 +1,44 @@ +import pytest +import warnings +import numpy as np + + +@pytest.mark.filterwarnings("error") +def test_getattr_warning(): + # issue gh-14735: make sure we clear only getattr errors, and let warnings + # through + class Wrapper: + def __init__(self, array): + self.array = array + + def __len__(self): + return len(self.array) + + def __getitem__(self, item): + return type(self)(self.array[item]) + + def __getattr__(self, name): + if name.startswith("__array_"): + warnings.warn("object got converted", UserWarning, stacklevel=1) + + return getattr(self.array, name) + + def __repr__(self): + return "".format(self=self) + + array = Wrapper(np.arange(10)) + with pytest.raises(UserWarning, match="object got converted"): + np.asarray(array) + + +def test_array_called(): + class Wrapper: + val = '0' * 100 + def __array__(self, result=None): + return np.array([self.val], dtype=object) + + + wrapped = Wrapper() + arr = np.array(wrapped, dtype=str) + assert arr.dtype == 'U100' + assert arr[0] == Wrapper.val diff --git a/shared/package-files/7c/7c4b4f52f7f19e14a1f61585e8ee7caad717fde3a3bcc02e043c4ec8752bb6fc/blob b/shared/package-files/7c/7c4b4f52f7f19e14a1f61585e8ee7caad717fde3a3bcc02e043c4ec8752bb6fc/blob new file mode 100644 index 0000000000000000000000000000000000000000..ca01874bf8e98da0aa9555bef423f950cf15746c --- /dev/null +++ b/shared/package-files/7c/7c4b4f52f7f19e14a1f61585e8ee7caad717fde3a3bcc02e043c4ec8752bb6fc/blob @@ -0,0 +1,105 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API xlogy_Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API xlogy_Scalar_Self { + using schema = at::Tensor (const at::Scalar &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Self") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor") + static at::Tensor call(const at::Scalar & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other); +}; + +struct TORCH_API xlogy_Scalar_Other { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Other") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API xlogy__Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API xlogy__Scalar_Other { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Other") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy_.Scalar_Other(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API xlogy_OutTensor { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "OutTensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy.OutTensor(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API xlogy_OutScalar_Self { + using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "OutScalar_Self") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy.OutScalar_Self(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Scalar & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API xlogy_OutScalar_Other { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::xlogy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "OutScalar_Other") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "xlogy.OutScalar_Other(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +}} // namespace at::_ops